1 /** @file
2  *  @brief Internal APIs for Bluetooth connection handling.
3  */
4 
5 /*
6  * Copyright (c) 2015 Intel Corporation
7  * Copyright (c) 2021 Nordic Semiconductor ASA
8  *
9  * SPDX-License-Identifier: Apache-2.0
10  */
11 
12 #include <zephyr/bluetooth/iso.h>
13 
14 typedef enum __packed {
15 	BT_CONN_DISCONNECTED,         /* Disconnected, conn is completely down */
16 	BT_CONN_DISCONNECT_COMPLETE,  /* Received disconn comp event, transition to DISCONNECTED */
17 
18 	BT_CONN_INITIATING,           /* Central connection establishment */
19 	/** Central scans for a device preceding establishing a connection to it.
20 	 *
21 	 * This can happen when:
22 	 * - The application has explicitly configured the stack to connect to the device,
23 	 *   but the controller resolving list is too small. The stack therefore first
24 	 *   scans to be able to retrieve the currently used (private) address, resolving
25 	 *   the address in the host if needed.
26 	 * - The stack uses this connection context for automatic connection establishment
27 	 *   without the use of filter accept list. Instead of immediately starting
28 	 *   the initiator, it first starts scanning. This allows the application to start
29 	 *   scanning while automatic connection establishment in ongoing.
30 	 *   It also allows the stack to use host based privacy for cases where this is needed.
31 	 */
32 	BT_CONN_SCAN_BEFORE_INITIATING,
33 
34 	/** Central initiates a connection to a device in the filter accept list.
35 	 *
36 	 * For this type of connection establishment, the controller's initiator is started
37 	 * immediately. That is, it is assumed that the controller resolving list
38 	 * holds all entries that are part of the filter accept list if private addresses are used.
39 	 */
40 	BT_CONN_INITIATING_FILTER_LIST,
41 
42 	BT_CONN_ADV_CONNECTABLE,       /* Peripheral connectable advertising */
43 	BT_CONN_ADV_DIR_CONNECTABLE,   /* Peripheral directed advertising */
44 	BT_CONN_CONNECTED,            /* Peripheral or Central connected */
45 	BT_CONN_DISCONNECTING,        /* Peripheral or Central issued disconnection command */
46 } bt_conn_state_t;
47 
48 /* bt_conn flags: the flags defined here represent connection parameters */
49 enum {
50 	/** The connection context is used for automatic connection establishment
51 	 *
52 	 * That is, with @ref bt_conn_le_create_auto() or bt_le_set_auto_conn().
53 	 * This flag is set even after the connection has been established so
54 	 * that the connection can be reestablished once disconnected.
55 	 * The connection establishment may be performed with or without the filter
56 	 * accept list.
57 	 */
58 	BT_CONN_AUTO_CONNECT,
59 	BT_CONN_BR_LEGACY_SECURE,             /* 16 digits legacy PIN tracker */
60 	BT_CONN_USER,                         /* user I/O when pairing */
61 	BT_CONN_BR_PAIRING,                   /* BR connection in pairing context */
62 	BT_CONN_BR_NOBOND,                    /* SSP no bond pairing tracker */
63 	BT_CONN_BR_PAIRING_INITIATOR,         /* local host starts authentication */
64 	BT_CONN_CLEANUP,                      /* Disconnected, pending cleanup */
65 	BT_CONN_PERIPHERAL_PARAM_UPDATE,      /* If periph param update timer fired */
66 	BT_CONN_PERIPHERAL_PARAM_AUTO_UPDATE, /* If periph param auto update on timer fired */
67 	BT_CONN_PERIPHERAL_PARAM_SET,         /* If periph param were set from app */
68 	BT_CONN_PERIPHERAL_PARAM_L2CAP,       /* If should force L2CAP for CPUP */
69 	BT_CONN_FORCE_PAIR,                   /* Pairing even with existing keys. */
70 #if defined(CONFIG_BT_GATT_CLIENT)
71 	BT_CONN_ATT_MTU_EXCHANGED,            /* If ATT MTU has been exchanged. */
72 #endif /* CONFIG_BT_GATT_CLIENT */
73 
74 	BT_CONN_AUTO_FEATURE_EXCH,            /* Auto-initiated LE Feat done */
75 	BT_CONN_AUTO_VERSION_INFO,            /* Auto-initiated LE version done */
76 
77 	BT_CONN_CTE_RX_ENABLED,               /* CTE receive and sampling is enabled */
78 	BT_CONN_CTE_RX_PARAMS_SET,            /* CTE parameters are set */
79 	BT_CONN_CTE_TX_PARAMS_SET,            /* CTE transmission parameters are set */
80 	BT_CONN_CTE_REQ_ENABLED,              /* CTE request procedure is enabled */
81 	BT_CONN_CTE_RSP_ENABLED,              /* CTE response procedure is enabled */
82 
83 	/* Total number of flags - must be at the end of the enum */
84 	BT_CONN_NUM_FLAGS,
85 };
86 
87 struct bt_conn_le {
88 	bt_addr_le_t dst;
89 
90 	bt_addr_le_t init_addr;
91 	bt_addr_le_t resp_addr;
92 
93 	uint16_t interval;
94 	uint16_t interval_min;
95 	uint16_t interval_max;
96 
97 	uint16_t latency;
98 	uint16_t timeout;
99 	uint16_t pending_latency;
100 	uint16_t pending_timeout;
101 
102 #if defined(CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS)
103 	uint8_t  conn_param_retry_countdown;
104 #endif
105 
106 	uint8_t features[8];
107 
108 	struct bt_keys *keys;
109 
110 #if defined(CONFIG_BT_USER_PHY_UPDATE)
111 	struct bt_conn_le_phy_info phy;
112 #endif
113 
114 #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE)
115 	struct bt_conn_le_data_len_info data_len;
116 #endif
117 };
118 
119 #if defined(CONFIG_BT_CLASSIC)
120 /* For now reserve space for 2 pages of LMP remote features */
121 #define LMP_MAX_PAGES 2
122 
123 struct bt_conn_br {
124 	bt_addr_t		dst;
125 	uint8_t			remote_io_capa;
126 	uint8_t			remote_auth;
127 	uint8_t			pairing_method;
128 	/* remote LMP features pages per 8 bytes each */
129 	uint8_t			features[LMP_MAX_PAGES][8];
130 
131 	struct bt_keys_link_key	*link_key;
132 };
133 
134 struct bt_conn_sco {
135 	/* Reference to ACL Connection */
136 	struct bt_conn          *acl;
137 
138 	/* Reference to the struct bt_sco_chan */
139 	struct bt_sco_chan      *chan;
140 
141 	uint16_t                pkt_type;
142 	uint8_t                 dev_class[3];
143 	uint8_t                 link_type;
144 };
145 #endif
146 
147 struct bt_conn_iso {
148 	/* Reference to ACL Connection */
149 	struct bt_conn          *acl;
150 
151 	/* Reference to the struct bt_iso_chan */
152 	struct bt_iso_chan      *chan;
153 
154 	union {
155 		/* CIG ID */
156 		uint8_t			cig_id;
157 		/* BIG handle */
158 		uint8_t			big_handle;
159 	};
160 
161 	union {
162 		/* CIS ID within the CIG */
163 		uint8_t			cis_id;
164 
165 		/* BIS ID within the BIG*/
166 		uint8_t			bis_id;
167 	};
168 
169 	/** Stored information about the ISO stream */
170 	struct bt_iso_info info;
171 
172 	/** Queue from which conn will pull data */
173 	struct k_fifo                   txq;
174 };
175 
176 typedef void (*bt_conn_tx_cb_t)(struct bt_conn *conn, void *user_data, int err);
177 
178 struct bt_conn_tx {
179 	sys_snode_t node;
180 
181 	bt_conn_tx_cb_t cb;
182 	void *user_data;
183 };
184 
185 struct acl_data {
186 	/* Extend the bt_buf user data */
187 	struct bt_buf_data buf_data;
188 
189 	/* Index into the bt_conn storage array */
190 	uint8_t index;
191 
192 	/** Host has already sent a Host Number of Completed Packets
193 	 *  for this buffer.
194 	 */
195 	bool host_ncp_sent;
196 
197 	/** ACL connection handle */
198 	uint16_t handle;
199 };
200 
201 struct bt_conn {
202 	uint16_t			handle;
203 	enum bt_conn_type	type;
204 	uint8_t			role;
205 
206 	ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS);
207 
208 	/* Which local identity address this connection uses */
209 	uint8_t                    id;
210 
211 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CLASSIC)
212 	bt_security_t		sec_level;
213 	bt_security_t		required_sec_level;
214 	uint8_t			encrypt;
215 #endif /* CONFIG_BT_SMP || CONFIG_BT_CLASSIC */
216 
217 #if defined(CONFIG_BT_DF_CONNECTION_CTE_RX)
218 	/**
219 	 * @brief Bitfield with allowed CTE types.
220 	 *
221 	 *  Allowed values are defined by @ref bt_df_cte_type, except BT_DF_CTE_TYPE_NONE.
222 	 */
223 	uint8_t cte_types;
224 #endif /* CONFIG_BT_DF_CONNECTION_CTE_RX */
225 
226 	/* Connection error or reason for disconnect */
227 	uint8_t			err;
228 
229 	bt_conn_state_t		state;
230 	uint16_t rx_len;
231 	struct net_buf		*rx;
232 
233 	/* Pending TX that are awaiting the NCP event. len(tx_pending) == in_ll */
234 	sys_slist_t		tx_pending;
235 
236 	/* Completed TX for which we need to call the callback */
237 	sys_slist_t		tx_complete;
238 #if defined(CONFIG_BT_CONN_TX)
239 	struct k_work           tx_complete_work;
240 #endif /* CONFIG_BT_CONN_TX */
241 
242 	/* Active L2CAP channels */
243 	sys_slist_t		channels;
244 
245 	/* Delayed work deferred tasks:
246 	 * - Peripheral delayed connection update.
247 	 * - Initiator connect create cancel.
248 	 * - Connection cleanup.
249 	 */
250 	struct k_work_delayable	deferred_work;
251 
252 	union {
253 		struct bt_conn_le	le;
254 #if defined(CONFIG_BT_CLASSIC)
255 		struct bt_conn_br	br;
256 		struct bt_conn_sco	sco;
257 #endif
258 #if defined(CONFIG_BT_ISO)
259 		struct bt_conn_iso	iso;
260 #endif
261 	};
262 
263 #if defined(CONFIG_BT_REMOTE_VERSION)
264 	struct bt_conn_rv {
265 		uint8_t  version;
266 		uint16_t manufacturer;
267 		uint16_t subversion;
268 	} rv;
269 #endif
270 
271 	/* Callback into the higher-layers (L2CAP / ISO) to return a buffer for
272 	 * sending `amount` of bytes to HCI.
273 	 *
274 	 * Scheduling from which channel to pull (e.g. for L2CAP) is done at the
275 	 * upper layer's discretion.
276 	 */
277 	struct net_buf * (*tx_data_pull)(struct bt_conn *conn,
278 					 size_t amount,
279 					 size_t *length);
280 
281 	/* Get (and clears for ACL conns) callback and user-data for `buf`. */
282 	void (*get_and_clear_cb)(struct bt_conn *conn, struct net_buf *buf,
283 				 bt_conn_tx_cb_t *cb, void **ud);
284 
285 	/* Return true if upper layer has data to send over HCI */
286 	bool (*has_data)(struct bt_conn *conn);
287 
288 	/* For ACL: List of data-ready L2 channels. Used by TX processor for
289 	 * pulling HCI fragments. Channels are only ever removed from this list
290 	 * when a whole PDU (ie all its frags) have been sent.
291 	 */
292 	sys_slist_t		l2cap_data_ready;
293 
294 	/* Node for putting this connection in a data-ready mode for the bt_dev.
295 	 * This will be used by the TX processor to then fetch HCI frags from it.
296 	 */
297 	sys_snode_t		_conn_ready;
298 	atomic_t		_conn_ready_lock;
299 
300 	/* Holds the number of packets that have been sent to the controller but
301 	 * not yet ACKd (by receiving an Number of Completed Packets). This
302 	 * variable can be used for deriving a QoS or waterlevel scheme in order
303 	 * to maximize throughput/latency.
304 	 * It's an optimization so we don't chase `tx_pending` all the time.
305 	 */
306 	atomic_t		in_ll;
307 
308 	/* Next buffer should be an ACL/ISO HCI fragment */
309 	bool			next_is_frag;
310 
311 	/* Must be at the end so that everything else in the structure can be
312 	 * memset to zero without affecting the ref.
313 	 */
314 	atomic_t		ref;
315 };
316 
317 /* Holds the callback and a user-data field for the upper layer. This callback
318  * shall be called when the buffer is ACK'd by the controller (by a Num Complete
319  * Packets event) or if the connection dies.
320  *
321  * Flow control in the spec be crazy, look it up. LL is allowed to choose
322  * between sending NCP events always or not at all on disconnect.
323  *
324  * We pack the struct to make sure it fits in the net_buf user_data field.
325  */
326 struct closure {
327 	void *cb;
328 	void *data;
329 } __packed;
330 
331 #if defined(CONFIG_BT_CONN_TX_USER_DATA_SIZE)
332 BUILD_ASSERT(sizeof(struct closure) < CONFIG_BT_CONN_TX_USER_DATA_SIZE);
333 #endif
334 
make_closure(void * storage,void * cb,void * data)335 static inline void make_closure(void *storage, void *cb, void *data)
336 {
337 	((struct closure *)storage)->cb = cb;
338 	((struct closure *)storage)->data = data;
339 }
340 
closure_cb(void * storage)341 static inline void *closure_cb(void *storage)
342 {
343 	return ((struct closure *)storage)->cb;
344 }
345 
closure_data(void * storage)346 static inline void *closure_data(void *storage)
347 {
348 	return ((struct closure *)storage)->data;
349 }
350 
351 void bt_conn_reset_rx_state(struct bt_conn *conn);
352 
353 /* Process incoming data for a connection */
354 void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, uint8_t flags);
355 
356 /* Send data over a connection
357  *
358  * Buffer ownership is transferred to stack in case of success.
359  *
360  * Calling this from RX thread is assumed to never fail so the return can be
361  * ignored.
362  */
363 int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
364 		    bt_conn_tx_cb_t cb, void *user_data);
365 
366 /* Thin wrapper over `bt_conn_send_cb`
367  *
368  * Used to set the TS_Flag bit in `buf`'s metadata.
369  *
370  * Return values & buf ownership same as parent.
371  */
372 int bt_conn_send_iso_cb(struct bt_conn *conn, struct net_buf *buf,
373 			bt_conn_tx_cb_t cb, bool has_ts);
374 
375 /* Check if a connection object with the peer already exists */
376 bool bt_conn_exists_le(uint8_t id, const bt_addr_le_t *peer);
377 
378 /* Add a new LE connection */
379 struct bt_conn *bt_conn_add_le(uint8_t id, const bt_addr_le_t *peer);
380 
381 /** Connection parameters for ISO connections */
382 struct bt_iso_create_param {
383 	uint8_t			id;
384 	uint8_t			num_conns;
385 	struct bt_conn		**conns;
386 	struct bt_iso_chan	**chans;
387 };
388 
389 int bt_conn_iso_init(void);
390 
391 /* Cleanup ISO references */
392 void bt_iso_cleanup_acl(struct bt_conn *iso_conn);
393 
394 void bt_iso_reset(void);
395 
396 /* Add a new BR/EDR connection */
397 struct bt_conn *bt_conn_add_br(const bt_addr_t *peer);
398 
399 /* Add a new SCO connection */
400 struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type);
401 
402 /* Cleanup SCO ACL reference */
403 void bt_sco_cleanup_acl(struct bt_conn *sco_conn);
404 
405 /* Cleanup SCO references */
406 void bt_sco_cleanup(struct bt_conn *sco_conn);
407 
408 /* Look up an existing sco connection by BT address */
409 struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer);
410 
411 /* Look up an existing connection by BT address */
412 struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer);
413 
414 void bt_conn_disconnect_all(uint8_t id);
415 
416 /* Allocate new connection object */
417 struct bt_conn *bt_conn_new(struct bt_conn *conns, size_t size);
418 
419 /* Look up an existing connection */
420 struct bt_conn *bt_conn_lookup_handle(uint16_t handle, enum bt_conn_type type);
421 
bt_conn_is_handle_valid(struct bt_conn * conn)422 static inline bool bt_conn_is_handle_valid(struct bt_conn *conn)
423 {
424 	switch (conn->state) {
425 	case BT_CONN_CONNECTED:
426 	case BT_CONN_DISCONNECTING:
427 	case BT_CONN_DISCONNECT_COMPLETE:
428 		return true;
429 	case BT_CONN_INITIATING:
430 		/* ISO connection handle assigned at connect state */
431 		if (IS_ENABLED(CONFIG_BT_ISO) &&
432 		    conn->type == BT_CONN_TYPE_ISO) {
433 			return true;
434 		}
435 	__fallthrough;
436 	default:
437 		return false;
438 	}
439 }
440 
441 /* Check if the connection is with the given peer. */
442 bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, uint8_t id,
443 			     const bt_addr_le_t *peer);
444 
445 /* Helpers for identifying & looking up connections based on the index to
446  * the connection list. This is useful for O(1) lookups, but can't be used
447  * e.g. as the handle since that's assigned to us by the controller.
448  */
449 #define BT_CONN_INDEX_INVALID 0xff
450 struct bt_conn *bt_conn_lookup_index(uint8_t index);
451 
452 /* Look up a connection state. For BT_ADDR_LE_ANY, returns the first connection
453  * with the specific state
454  */
455 struct bt_conn *bt_conn_lookup_state_le(uint8_t id, const bt_addr_le_t *peer,
456 					const bt_conn_state_t state);
457 
458 /* Set connection object in certain state and perform action related to state */
459 void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state);
460 
461 void bt_conn_connected(struct bt_conn *conn);
462 
463 int bt_conn_le_conn_update(struct bt_conn *conn,
464 			   const struct bt_le_conn_param *param);
465 
466 void notify_remote_info(struct bt_conn *conn);
467 
468 void notify_le_param_updated(struct bt_conn *conn);
469 
470 void notify_le_data_len_updated(struct bt_conn *conn);
471 
472 void notify_le_phy_updated(struct bt_conn *conn);
473 
474 bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param);
475 
476 void notify_tx_power_report(struct bt_conn *conn,
477 			    struct bt_conn_le_tx_power_report report);
478 
479 void notify_path_loss_threshold_report(struct bt_conn *conn,
480 				       struct bt_conn_le_path_loss_threshold_report report);
481 
482 #if defined(CONFIG_BT_SMP)
483 /* If role specific LTK is present */
484 bool bt_conn_ltk_present(const struct bt_conn *conn);
485 
486 /* rand and ediv should be in BT order */
487 int bt_conn_le_start_encryption(struct bt_conn *conn, uint8_t rand[8],
488 				uint8_t ediv[2], const uint8_t *ltk, size_t len);
489 
490 /* Notify higher layers that RPA was resolved */
491 void bt_conn_identity_resolved(struct bt_conn *conn);
492 #endif /* CONFIG_BT_SMP */
493 
494 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CLASSIC)
495 /* Notify higher layers that connection security changed */
496 void bt_conn_security_changed(struct bt_conn *conn, uint8_t hci_err,
497 			      enum bt_security_err err);
498 #endif /* CONFIG_BT_SMP || CONFIG_BT_CLASSIC */
499 
500 /* Prepare a PDU to be sent over a connection */
501 #if defined(CONFIG_NET_BUF_LOG)
502 struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool,
503 						 size_t reserve,
504 						 k_timeout_t timeout,
505 						 const char *func, int line);
506 #define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) \
507 	bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \
508 					 __func__, __LINE__)
509 
510 #define bt_conn_create_pdu(_pool, _reserve) \
511 	bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \
512 					 __func__, __LINE__)
513 #else
514 struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
515 					   size_t reserve, k_timeout_t timeout);
516 
517 #define bt_conn_create_pdu(_pool, _reserve) \
518 	bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER)
519 #endif
520 
521 /* Prepare a PDU to be sent over a connection */
522 #if defined(CONFIG_NET_BUF_LOG)
523 struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve,
524 						  k_timeout_t timeout,
525 						  const char *func, int line);
526 
527 #define bt_conn_create_frag_timeout(_reserve, _timeout) \
528 	bt_conn_create_frag_timeout_debug(_reserve, _timeout, \
529 					  __func__, __LINE__)
530 
531 #define bt_conn_create_frag(_reserve) \
532 	bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \
533 					  __func__, __LINE__)
534 #else
535 struct net_buf *bt_conn_create_frag_timeout(size_t reserve,
536 					    k_timeout_t timeout);
537 
538 #define bt_conn_create_frag(_reserve) \
539 	bt_conn_create_frag_timeout(_reserve, K_FOREVER)
540 #endif
541 
542 /* Initialize connection management */
543 int bt_conn_init(void);
544 
545 /* Reset states of connections and set state to BT_CONN_DISCONNECTED. */
546 void bt_conn_cleanup_all(void);
547 
548 /* Selects based on connection type right semaphore for ACL packets */
549 struct k_sem *bt_conn_get_pkts(struct bt_conn *conn);
550 
551 void bt_conn_tx_processor(void);
552 
553 /* To be called by upper layers when they want to send something.
554  * Functions just like an IRQ.
555  *
556  * Note: This fn will take and hold a reference to `conn` until the IRQ for that
557  * conn is serviced.
558  * For the current implementation, that means:
559  * - ref the conn when putting on an "conn-ready" slist
560  * - unref the conn when popping the conn from the slist
561  */
562 void bt_conn_data_ready(struct bt_conn *conn);
563