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 <stddef.h>
13 #include <stdint.h>
14
15 #include <zephyr/bluetooth/addr.h>
16 #include <zephyr/bluetooth/buf.h>
17 #include <zephyr/bluetooth/conn.h>
18 #include <zephyr/bluetooth/iso.h>
19 #include <zephyr/kernel.h>
20 #include <zephyr/net_buf.h>
21 #include <zephyr/sys/atomic.h>
22 #include <zephyr/sys/slist.h>
23 #include <zephyr/sys/util_macro.h>
24 #include <zephyr/sys_clock.h>
25 #include <zephyr/toolchain.h>
26
27 typedef enum __packed {
28 BT_CONN_DISCONNECTED, /* Disconnected, conn is completely down */
29 BT_CONN_DISCONNECT_COMPLETE, /* Received disconn comp event, transition to DISCONNECTED */
30
31 BT_CONN_INITIATING, /* Central connection establishment */
32 /** Central scans for a device preceding establishing a connection to it.
33 *
34 * This can happen when:
35 * - The application has explicitly configured the stack to connect to the device,
36 * but the controller resolving list is too small. The stack therefore first
37 * scans to be able to retrieve the currently used (private) address, resolving
38 * the address in the host if needed.
39 * - The stack uses this connection context for automatic connection establishment
40 * without the use of filter accept list. Instead of immediately starting
41 * the initiator, it first starts scanning. This allows the application to start
42 * scanning while automatic connection establishment in ongoing.
43 * It also allows the stack to use host based privacy for cases where this is needed.
44 */
45 BT_CONN_SCAN_BEFORE_INITIATING,
46
47 /** Central initiates a connection to a device in the filter accept list.
48 *
49 * For this type of connection establishment, the controller's initiator is started
50 * immediately. That is, it is assumed that the controller resolving list
51 * holds all entries that are part of the filter accept list if private addresses are used.
52 */
53 BT_CONN_INITIATING_FILTER_LIST,
54
55 BT_CONN_ADV_CONNECTABLE, /* Peripheral connectable advertising */
56 BT_CONN_ADV_DIR_CONNECTABLE, /* Peripheral directed advertising */
57 BT_CONN_CONNECTED, /* Peripheral or Central connected */
58 BT_CONN_DISCONNECTING, /* Peripheral or Central issued disconnection command */
59 } bt_conn_state_t;
60
61 /* bt_conn flags: the flags defined here represent connection parameters */
62 enum {
63 /** The connection context is used for automatic connection establishment
64 *
65 * That is, with @ref bt_conn_le_create_auto().
66 * This flag is set even after the connection has been established so
67 * that the connection can be reestablished once disconnected.
68 * The connection establishment may be performed with or without the filter
69 * accept list.
70 */
71 BT_CONN_AUTO_CONNECT,
72 BT_CONN_BR_LEGACY_SECURE, /* 16 digits legacy PIN tracker */
73 BT_CONN_BR_BONDABLE, /* BR connection is bondable */
74 BT_CONN_USER, /* user I/O when pairing */
75 BT_CONN_BR_PAIRING, /* BR connection in pairing context */
76 BT_CONN_BR_PAIRED, /* BR connection pairing is done */
77 BT_CONN_BR_NOBOND, /* SSP no bond pairing tracker */
78 BT_CONN_BR_GENERAL_BONDING, /* BR general bonding */
79 BT_CONN_BR_PAIRING_INITIATOR, /* local host starts authentication */
80 BT_CONN_CLEANUP, /* Disconnected, pending cleanup */
81 BT_CONN_AUTO_INIT_PROCEDURES_DONE, /* Auto-initiated procedures have run */
82 BT_CONN_PERIPHERAL_PARAM_UPDATE, /* If periph param update timer fired */
83 BT_CONN_PERIPHERAL_PARAM_AUTO_UPDATE, /* If periph param auto update on timer fired */
84 BT_CONN_PERIPHERAL_PARAM_SET, /* If periph param were set from app */
85 BT_CONN_PERIPHERAL_PARAM_L2CAP, /* If should force L2CAP for CPUP */
86 BT_CONN_FORCE_PAIR, /* Pairing even with existing keys. */
87 #if defined(CONFIG_BT_GATT_CLIENT)
88 BT_CONN_ATT_MTU_EXCHANGED, /* If ATT MTU has been exchanged. */
89 #endif /* CONFIG_BT_GATT_CLIENT */
90
91 BT_CONN_LE_FEATURES_EXCHANGED, /* bt_conn.le.features is valid */
92 BT_CONN_AUTO_VERSION_INFO, /* Auto-initiated LE version done */
93
94 BT_CONN_CTE_RX_ENABLED, /* CTE receive and sampling is enabled */
95 BT_CONN_CTE_RX_PARAMS_SET, /* CTE parameters are set */
96 BT_CONN_CTE_TX_PARAMS_SET, /* CTE transmission parameters are set */
97 BT_CONN_CTE_REQ_ENABLED, /* CTE request procedure is enabled */
98 BT_CONN_CTE_RSP_ENABLED, /* CTE response procedure is enabled */
99
100 /* Total number of flags - must be at the end of the enum */
101 BT_CONN_NUM_FLAGS,
102 };
103
104 struct bt_conn_le {
105 bt_addr_le_t dst;
106
107 bt_addr_le_t init_addr;
108 bt_addr_le_t resp_addr;
109
110 uint16_t interval;
111 uint16_t interval_min;
112 uint16_t interval_max;
113
114 uint16_t latency;
115 uint16_t timeout;
116 uint16_t pending_latency;
117 uint16_t pending_timeout;
118
119 #if defined(CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS)
120 uint8_t conn_param_retry_countdown;
121 #endif
122
123 /** @brief Remote LE features
124 *
125 * Available after `atomic_test_bit(conn->flags, BT_CONN_LE_FEATURES_EXCHANGED)`.
126 * Signaled by bt_conn_cb.remote_info_available().
127 */
128 uint8_t features[8];
129
130 struct bt_keys *keys;
131
132 #if defined(CONFIG_BT_USER_PHY_UPDATE)
133 struct bt_conn_le_phy_info phy;
134 #endif
135
136 #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE)
137 struct bt_conn_le_data_len_info data_len;
138 #endif
139
140 #if defined(CONFIG_BT_SUBRATING)
141 struct bt_conn_le_subrating_info subrate;
142 #endif
143 };
144
145 /* For now reserve space for 2 pages of LMP remote features */
146 #define LMP_MAX_PAGES 2
147
148 struct bt_conn_br {
149 bt_addr_t dst;
150 uint8_t remote_io_capa;
151 uint8_t remote_auth;
152 uint8_t local_auth;
153 uint8_t pairing_method;
154 /* remote LMP features pages per 8 bytes each */
155 uint8_t features[LMP_MAX_PAGES][8];
156
157 struct bt_keys_link_key *link_key;
158 };
159
160 struct bt_conn_sco {
161 /* Reference to ACL Connection */
162 struct bt_conn *acl;
163
164 /* Reference to the struct bt_sco_chan */
165 struct bt_sco_chan *chan;
166
167 uint16_t pkt_type;
168 uint8_t dev_class[3];
169 uint8_t link_type;
170 };
171
172 struct bt_conn_iso {
173 /* Reference to ACL Connection */
174 struct bt_conn *acl;
175
176 /* Reference to the struct bt_iso_chan */
177 struct bt_iso_chan *chan;
178
179 /** Stored information about the ISO stream */
180 struct bt_iso_info info;
181
182 /** Queue from which conn will pull data */
183 struct k_fifo txq;
184 };
185
186 typedef void (*bt_conn_tx_cb_t)(struct bt_conn *conn, void *user_data, int err);
187
188 struct bt_conn_tx {
189 sys_snode_t node;
190
191 bt_conn_tx_cb_t cb;
192 void *user_data;
193 };
194
195 struct bt_conn_rx {
196 /* Index into the bt_conn storage array */
197 uint8_t index;
198
199 /** Connection handle */
200 uint16_t handle;
201 };
202
203 struct bt_conn {
204 uint16_t handle;
205 enum bt_conn_type type;
206 uint8_t role;
207
208 ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS);
209
210 /* Which local identity address this connection uses */
211 uint8_t id;
212
213 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CLASSIC)
214 bt_security_t sec_level;
215 bt_security_t required_sec_level;
216 uint8_t encrypt;
217 #endif /* CONFIG_BT_SMP || CONFIG_BT_CLASSIC */
218
219 #if defined(CONFIG_BT_DF_CONNECTION_CTE_RX)
220 /**
221 * @brief Bitfield with allowed CTE types.
222 *
223 * Allowed values are defined by @ref bt_df_cte_type, except BT_DF_CTE_TYPE_NONE.
224 */
225 uint8_t cte_types;
226 #endif /* CONFIG_BT_DF_CONNECTION_CTE_RX */
227
228 /* Connection error or reason for disconnect */
229 uint8_t err;
230
231 bt_conn_state_t state;
232 uint16_t rx_len;
233 struct net_buf *rx;
234
235 /* Pending TX that are awaiting the NCP event. len(tx_pending) == in_ll */
236 sys_slist_t tx_pending;
237
238 /* Completed TX for which we need to call the callback */
239 sys_slist_t tx_complete;
240 #if defined(CONFIG_BT_CONN_TX)
241 struct k_work tx_complete_work;
242 #endif /* CONFIG_BT_CONN_TX */
243
244 /* Active L2CAP channels */
245 sys_slist_t channels;
246
247 /* Delayed work deferred tasks:
248 * - Peripheral delayed connection update.
249 * - Initiator connect create cancel.
250 * - Connection cleanup.
251 */
252 struct k_work_delayable deferred_work;
253
254 union {
255 struct bt_conn_le le;
256 #if defined(CONFIG_BT_CLASSIC)
257 struct bt_conn_br br;
258 struct bt_conn_sco sco;
259 #endif
260 #if defined(CONFIG_BT_ISO)
261 struct bt_conn_iso iso;
262 #endif
263 };
264
265 #if defined(CONFIG_BT_REMOTE_VERSION)
266 struct bt_conn_rv {
267 uint8_t version;
268 uint16_t manufacturer;
269 uint16_t subversion;
270 } rv;
271 #endif
272
273 /* Callback into the higher-layers (L2CAP / ISO) to return a buffer for
274 * sending `amount` of bytes to HCI. Will only be called when
275 * the state is connected. The higher-layer is responsible for purging
276 * the remaining buffers on disconnect.
277 *
278 * Scheduling from which channel to pull (e.g. for L2CAP) is done at the
279 * upper layer's discretion.
280 *
281 * Details about the returned net_buf when it is not NULL:
282 * - If the net_buf->len <= *length, then the net_buf has been removed
283 * from the tx_queue of the connection and the caller is now the
284 * owner of the only reference to the net_buf.
285 * - Otherwise, the net_buf is still on the tx_queue of the connection,
286 * and the callback has incremented the reference count to account
287 * for it having a reference still.
288 * - The caller must consume *length bytes from the net_buf before
289 * calling this function again.
290 */
291 struct net_buf * (*tx_data_pull)(struct bt_conn *conn,
292 size_t amount,
293 size_t *length);
294
295 /* Get (and clears for ACL conns) callback and user-data for `buf`. */
296 void (*get_and_clear_cb)(struct bt_conn *conn, struct net_buf *buf,
297 bt_conn_tx_cb_t *cb, void **ud);
298
299 /* Return true if upper layer has data to send over HCI */
300 bool (*has_data)(struct bt_conn *conn);
301
302 /* For ACL: List of data-ready L2 channels. Used by TX processor for
303 * pulling HCI fragments. Channels are only ever removed from this list
304 * when a whole PDU (ie all its frags) have been sent.
305 */
306 sys_slist_t l2cap_data_ready;
307
308 /* Node for putting this connection in a data-ready mode for the bt_dev.
309 * This will be used by the TX processor to then fetch HCI frags from it.
310 */
311 sys_snode_t _conn_ready;
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 void bt_conn_disconnect_all(uint8_t id);
427
428 /* Allocate new connection object */
429 struct bt_conn *bt_conn_new(struct bt_conn *conns, size_t size);
430
431 /* Look up an existing connection */
432 struct bt_conn *bt_conn_lookup_handle(uint16_t handle, enum bt_conn_type type);
433
bt_conn_is_handle_valid(struct bt_conn * conn)434 static inline bool bt_conn_is_handle_valid(struct bt_conn *conn)
435 {
436 switch (conn->state) {
437 case BT_CONN_CONNECTED:
438 case BT_CONN_DISCONNECTING:
439 case BT_CONN_DISCONNECT_COMPLETE:
440 return true;
441 case BT_CONN_INITIATING:
442 /* ISO connection handle assigned at connect state */
443 if (IS_ENABLED(CONFIG_BT_ISO) &&
444 conn->type == BT_CONN_TYPE_ISO) {
445 return true;
446 }
447 __fallthrough;
448 default:
449 return false;
450 }
451 }
452
453 /* Check if the connection is with the given peer. */
454 bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, uint8_t id,
455 const bt_addr_le_t *peer);
456
457 /* Helpers for identifying & looking up connections based on the index to
458 * the connection list. This is useful for O(1) lookups, but can't be used
459 * e.g. as the handle since that's assigned to us by the controller.
460 */
461 #define BT_CONN_INDEX_INVALID 0xff
462 struct bt_conn *bt_conn_lookup_index(uint8_t index);
463
464 /* Look up a connection state. For BT_ADDR_LE_ANY, returns the first connection
465 * with the specific state
466 */
467 struct bt_conn *bt_conn_lookup_state_le(uint8_t id, const bt_addr_le_t *peer,
468 const bt_conn_state_t state);
469
470 /* Set connection object in certain state and perform action related to state */
471 void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state);
472
473 void bt_conn_connected(struct bt_conn *conn);
474
475 void bt_conn_role_changed(struct bt_conn *conn, uint8_t status);
476
477 int bt_conn_le_conn_update(struct bt_conn *conn,
478 const struct bt_le_conn_param *param);
479
480 void notify_remote_info(struct bt_conn *conn);
481
482 void notify_le_param_updated(struct bt_conn *conn);
483
484 void notify_le_data_len_updated(struct bt_conn *conn);
485
486 void notify_le_phy_updated(struct bt_conn *conn);
487
488 bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param);
489
490 void notify_tx_power_report(struct bt_conn *conn,
491 struct bt_conn_le_tx_power_report report);
492
493 void notify_path_loss_threshold_report(struct bt_conn *conn,
494 struct bt_conn_le_path_loss_threshold_report report);
495
496 void notify_subrate_change(struct bt_conn *conn,
497 struct bt_conn_le_subrate_changed params);
498
499 void notify_read_all_remote_feat_complete(struct bt_conn *conn,
500 struct bt_conn_le_read_all_remote_feat_complete *params);
501
502 void notify_frame_space_update_complete(struct bt_conn *conn,
503 struct bt_conn_le_frame_space_updated *params);
504
505 void notify_remote_cs_capabilities(struct bt_conn *conn,
506 uint8_t status,
507 struct bt_conn_le_cs_capabilities *params);
508
509 void notify_remote_cs_fae_table(struct bt_conn *conn,
510 uint8_t status,
511 struct bt_conn_le_cs_fae_table *params);
512
513 void notify_cs_config_created(struct bt_conn *conn,
514 uint8_t status,
515 struct bt_conn_le_cs_config *params);
516
517 void notify_cs_config_removed(struct bt_conn *conn, uint8_t config_id);
518
519 void notify_cs_subevent_result(struct bt_conn *conn, struct bt_conn_le_cs_subevent_result *result);
520
521 void notify_cs_security_enable_available(struct bt_conn *conn, uint8_t status);
522
523 void notify_cs_procedure_enable_available(struct bt_conn *conn,
524 uint8_t status,
525 struct bt_conn_le_cs_procedure_enable_complete *params);
526
527 /* If role specific LTK is present */
528 bool bt_conn_ltk_present(const struct bt_conn *conn);
529
530 /* rand and ediv should be in BT order */
531 int bt_conn_le_start_encryption(struct bt_conn *conn, uint8_t rand[8],
532 uint8_t ediv[2], const uint8_t *ltk, size_t len);
533
534 /* Notify higher layers that RPA was resolved */
535 void bt_conn_identity_resolved(struct bt_conn *conn);
536
537 /* Notify higher layers that connection security changed */
538 void bt_conn_security_changed(struct bt_conn *conn, uint8_t hci_err,
539 enum bt_security_err err);
540
541 /* Prepare a PDU to be sent over a connection */
542 #if defined(CONFIG_NET_BUF_LOG)
543 struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool,
544 size_t reserve,
545 k_timeout_t timeout,
546 const char *func, int line);
547 #define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) \
548 bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \
549 __func__, __LINE__)
550
551 #define bt_conn_create_pdu(_pool, _reserve) \
552 bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \
553 __func__, __LINE__)
554 #else
555 struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
556 size_t reserve, k_timeout_t timeout);
557
558 #define bt_conn_create_pdu(_pool, _reserve) \
559 bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER)
560 #endif
561
562 /* Prepare a PDU to be sent over a connection */
563 #if defined(CONFIG_NET_BUF_LOG)
564 struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve,
565 k_timeout_t timeout,
566 const char *func, int line);
567
568 #define bt_conn_create_frag_timeout(_reserve, _timeout) \
569 bt_conn_create_frag_timeout_debug(_reserve, _timeout, \
570 __func__, __LINE__)
571
572 #define bt_conn_create_frag(_reserve) \
573 bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \
574 __func__, __LINE__)
575 #else
576 struct net_buf *bt_conn_create_frag_timeout(size_t reserve,
577 k_timeout_t timeout);
578
579 #define bt_conn_create_frag(_reserve) \
580 bt_conn_create_frag_timeout(_reserve, K_FOREVER)
581 #endif
582
583 /* Initialize connection management */
584 int bt_conn_init(void);
585
586 /* Reset states of connections and set state to BT_CONN_DISCONNECTED. */
587 void bt_conn_cleanup_all(void);
588
589 /* Selects based on connection type right semaphore for ACL packets */
590 struct k_sem *bt_conn_get_pkts(struct bt_conn *conn);
591
592 void bt_conn_tx_processor(void);
593
594 /* To be called by upper layers when they want to send something.
595 * Functions just like an IRQ.
596 *
597 * Note: This fn will take and hold a reference to `conn` until the IRQ for that
598 * conn is serviced.
599 * For the current implementation, that means:
600 * - ref the conn when putting on an "conn-ready" slist
601 * - unref the conn when popping the conn from the slist
602 */
603 void bt_conn_data_ready(struct bt_conn *conn);
604