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