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 	BT_CONN_CONNECTING_SCAN,      /* Central passive scanning */
18 	BT_CONN_CONNECTING_AUTO,      /* Central connection establishment w/ filter */
19 	BT_CONN_CONNECTING_ADV,       /* Peripheral connectable advertising */
20 	BT_CONN_CONNECTING_DIR_ADV,   /* Peripheral directed advertising */
21 	BT_CONN_CONNECTING,           /* Central connection establishment */
22 	BT_CONN_CONNECTED,            /* Peripheral or Central connected */
23 	BT_CONN_DISCONNECTING,        /* Peripheral or Central issued disconnection command */
24 } bt_conn_state_t;
25 
26 /* bt_conn flags: the flags defined here represent connection parameters */
27 enum {
28 	BT_CONN_AUTO_CONNECT,
29 	BT_CONN_BR_LEGACY_SECURE,             /* 16 digits legacy PIN tracker */
30 	BT_CONN_USER,                         /* user I/O when pairing */
31 	BT_CONN_BR_PAIRING,                   /* BR connection in pairing context */
32 	BT_CONN_BR_NOBOND,                    /* SSP no bond pairing tracker */
33 	BT_CONN_BR_PAIRING_INITIATOR,         /* local host starts authentication */
34 	BT_CONN_CLEANUP,                      /* Disconnected, pending cleanup */
35 	BT_CONN_PERIPHERAL_PARAM_UPDATE,      /* If periph param update timer fired */
36 	BT_CONN_PERIPHERAL_PARAM_AUTO_UPDATE, /* If periph param auto update on timer fired */
37 	BT_CONN_PERIPHERAL_PARAM_SET,         /* If periph param were set from app */
38 	BT_CONN_PERIPHERAL_PARAM_L2CAP,       /* If should force L2CAP for CPUP */
39 	BT_CONN_FORCE_PAIR,                   /* Pairing even with existing keys. */
40 #if defined(CONFIG_BT_GATT_CLIENT)
41 	BT_CONN_ATT_MTU_EXCHANGED,            /* If ATT MTU has been exchanged. */
42 #endif /* CONFIG_BT_GATT_CLIENT */
43 
44 	BT_CONN_AUTO_FEATURE_EXCH,            /* Auto-initiated LE Feat done */
45 	BT_CONN_AUTO_VERSION_INFO,            /* Auto-initiated LE version done */
46 
47 	BT_CONN_CTE_RX_ENABLED,               /* CTE receive and sampling is enabled */
48 	BT_CONN_CTE_RX_PARAMS_SET,            /* CTE parameters are set */
49 	BT_CONN_CTE_TX_PARAMS_SET,            /* CTE transmission parameters are set */
50 	BT_CONN_CTE_REQ_ENABLED,              /* CTE request procedure is enabled */
51 	BT_CONN_CTE_RSP_ENABLED,              /* CTE response procedure is enabled */
52 
53 	/* Total number of flags - must be at the end of the enum */
54 	BT_CONN_NUM_FLAGS,
55 };
56 
57 struct bt_conn_le {
58 	bt_addr_le_t dst;
59 
60 	bt_addr_le_t init_addr;
61 	bt_addr_le_t resp_addr;
62 
63 	uint16_t interval;
64 	uint16_t interval_min;
65 	uint16_t interval_max;
66 
67 	uint16_t latency;
68 	uint16_t timeout;
69 	uint16_t pending_latency;
70 	uint16_t pending_timeout;
71 
72 #if defined(CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS)
73 	uint8_t  conn_param_retry_countdown;
74 #endif
75 
76 	uint8_t features[8];
77 
78 	struct bt_keys *keys;
79 
80 #if defined(CONFIG_BT_USER_PHY_UPDATE)
81 	struct bt_conn_le_phy_info phy;
82 #endif
83 
84 #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE)
85 	struct bt_conn_le_data_len_info data_len;
86 #endif
87 };
88 
89 #if defined(CONFIG_BT_BREDR)
90 /* For now reserve space for 2 pages of LMP remote features */
91 #define LMP_MAX_PAGES 2
92 
93 struct bt_conn_br {
94 	bt_addr_t		dst;
95 	uint8_t			remote_io_capa;
96 	uint8_t			remote_auth;
97 	uint8_t			pairing_method;
98 	/* remote LMP features pages per 8 bytes each */
99 	uint8_t			features[LMP_MAX_PAGES][8];
100 
101 	struct bt_keys_link_key	*link_key;
102 };
103 
104 struct bt_conn_sco {
105 	/* Reference to ACL Connection */
106 	struct bt_conn          *acl;
107 	uint16_t                pkt_type;
108 };
109 #endif
110 
111 struct bt_conn_iso {
112 	/* Reference to ACL Connection */
113 	struct bt_conn          *acl;
114 
115 	/* Reference to the struct bt_iso_chan */
116 	struct bt_iso_chan      *chan;
117 
118 	union {
119 		/* CIG ID */
120 		uint8_t			cig_id;
121 		/* BIG handle */
122 		uint8_t			big_handle;
123 	};
124 
125 	union {
126 		/* CIS ID within the CIG */
127 		uint8_t			cis_id;
128 
129 		/* BIS ID within the BIG*/
130 		uint8_t			bis_id;
131 	};
132 
133 	/** Stored information about the ISO stream */
134 	struct bt_iso_info info;
135 };
136 
137 typedef void (*bt_conn_tx_cb_t)(struct bt_conn *conn, void *user_data, int err);
138 
139 struct bt_conn_tx {
140 	sys_snode_t node;
141 
142 	bt_conn_tx_cb_t cb;
143 	void *user_data;
144 
145 	/* Number of pending packets without a callback after this one */
146 	uint32_t pending_no_cb;
147 };
148 
149 struct acl_data {
150 	/* Extend the bt_buf user data */
151 	struct bt_buf_data buf_data;
152 
153 	/* Index into the bt_conn storage array */
154 	uint8_t  index;
155 
156 	/** ACL connection handle */
157 	uint16_t handle;
158 };
159 
160 struct bt_conn {
161 	uint16_t			handle;
162 	enum bt_conn_type	type;
163 	uint8_t			role;
164 
165 	ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS);
166 
167 	/* Which local identity address this connection uses */
168 	uint8_t                    id;
169 
170 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
171 	bt_security_t		sec_level;
172 	bt_security_t		required_sec_level;
173 	uint8_t			encrypt;
174 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
175 
176 #if defined(CONFIG_BT_DF_CONNECTION_CTE_RX)
177 	/**
178 	 * @brief Bitfield with allowed CTE types.
179 	 *
180 	 *  Allowed values are defined by @ref bt_df_cte_type, except BT_DF_CTE_TYPE_NONE.
181 	 */
182 	uint8_t cte_types;
183 #endif /* CONFIG_BT_DF_CONNECTION_CTE_RX */
184 
185 	/* Connection error or reason for disconnect */
186 	uint8_t			err;
187 
188 	bt_conn_state_t		state;
189 	uint16_t rx_len;
190 	struct net_buf		*rx;
191 
192 	/* Sent but not acknowledged TX packets with a callback */
193 	sys_slist_t		tx_pending;
194 	/* Sent but not acknowledged TX packets without a callback before
195 	 * the next packet (if any) in tx_pending.
196 	 */
197 	uint32_t                   pending_no_cb;
198 
199 	/* Completed TX for which we need to call the callback */
200 	sys_slist_t		tx_complete;
201 #if defined(CONFIG_BT_CONN_TX)
202 	struct k_work           tx_complete_work;
203 #endif /* CONFIG_BT_CONN_TX */
204 
205 	/* Queue for outgoing ACL data */
206 	struct k_fifo		tx_queue;
207 
208 	/* Active L2CAP channels */
209 	sys_slist_t		channels;
210 
211 	/* Delayed work deferred tasks:
212 	 * - Peripheral delayed connection update.
213 	 * - Initiator connect create cancel.
214 	 * - Connection cleanup.
215 	 */
216 	struct k_work_delayable	deferred_work;
217 
218 	union {
219 		struct bt_conn_le	le;
220 #if defined(CONFIG_BT_BREDR)
221 		struct bt_conn_br	br;
222 		struct bt_conn_sco	sco;
223 #endif
224 #if defined(CONFIG_BT_ISO)
225 		struct bt_conn_iso	iso;
226 #endif
227 	};
228 
229 #if defined(CONFIG_BT_REMOTE_VERSION)
230 	struct bt_conn_rv {
231 		uint8_t  version;
232 		uint16_t manufacturer;
233 		uint16_t subversion;
234 	} rv;
235 #endif
236 	/* Must be at the end so that everything else in the structure can be
237 	 * memset to zero without affecting the ref.
238 	 */
239 	atomic_t		ref;
240 };
241 
242 void bt_conn_reset_rx_state(struct bt_conn *conn);
243 
244 /* Process incoming data for a connection */
245 void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, uint8_t flags);
246 
247 /* Send data over a connection
248  *
249  * Buffer ownership is transferred to stack in case of success.
250  *
251  * Calling this from RX thread is assumed to never fail so the return can be
252  * ignored.
253  */
254 int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
255 		    bt_conn_tx_cb_t cb, void *user_data);
256 
257 /* Thin wrapper over `bt_conn_send_cb`
258  *
259  * Used to set the TS_Flag bit in `buf`'s metadata.
260  *
261  * Return values & buf ownership same as parent.
262  */
263 int bt_conn_send_iso_cb(struct bt_conn *conn, struct net_buf *buf,
264 			bt_conn_tx_cb_t cb, bool has_ts);
265 
bt_conn_send(struct bt_conn * conn,struct net_buf * buf)266 static inline int bt_conn_send(struct bt_conn *conn, struct net_buf *buf)
267 {
268 	return bt_conn_send_cb(conn, buf, NULL, NULL);
269 }
270 
271 /* Check if a connection object with the peer already exists */
272 bool bt_conn_exists_le(uint8_t id, const bt_addr_le_t *peer);
273 
274 /* Add a new LE connection */
275 struct bt_conn *bt_conn_add_le(uint8_t id, const bt_addr_le_t *peer);
276 
277 /** Connection parameters for ISO connections */
278 struct bt_iso_create_param {
279 	uint8_t			id;
280 	uint8_t			num_conns;
281 	struct bt_conn		**conns;
282 	struct bt_iso_chan	**chans;
283 };
284 
285 int bt_conn_iso_init(void);
286 
287 /* Cleanup ISO references */
288 void bt_iso_cleanup_acl(struct bt_conn *iso_conn);
289 
290 /* Add a new BR/EDR connection */
291 struct bt_conn *bt_conn_add_br(const bt_addr_t *peer);
292 
293 /* Add a new SCO connection */
294 struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type);
295 
296 /* Cleanup SCO references */
297 void bt_sco_cleanup(struct bt_conn *sco_conn);
298 
299 /* Look up an existing sco connection by BT address */
300 struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer);
301 
302 /* Look up an existing connection by BT address */
303 struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer);
304 
305 void bt_conn_disconnect_all(uint8_t id);
306 
307 /* Allocate new connection object */
308 struct bt_conn *bt_conn_new(struct bt_conn *conns, size_t size);
309 
310 /* Look up an existing connection */
311 struct bt_conn *bt_conn_lookup_handle(uint16_t handle, enum bt_conn_type type);
312 
bt_conn_is_handle_valid(struct bt_conn * conn)313 static inline bool bt_conn_is_handle_valid(struct bt_conn *conn)
314 {
315 	switch (conn->state) {
316 	case BT_CONN_CONNECTED:
317 	case BT_CONN_DISCONNECTING:
318 	case BT_CONN_DISCONNECT_COMPLETE:
319 		return true;
320 	case BT_CONN_CONNECTING:
321 		/* ISO connection handle assigned at connect state */
322 		if (IS_ENABLED(CONFIG_BT_ISO) &&
323 		    conn->type == BT_CONN_TYPE_ISO) {
324 			return true;
325 		}
326 	__fallthrough;
327 	default:
328 		return false;
329 	}
330 }
331 
332 /* Check if the connection is with the given peer. */
333 bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, uint8_t id,
334 			     const bt_addr_le_t *peer);
335 
336 /* Helpers for identifying & looking up connections based on the the index to
337  * the connection list. This is useful for O(1) lookups, but can't be used
338  * e.g. as the handle since that's assigned to us by the controller.
339  */
340 #define BT_CONN_INDEX_INVALID 0xff
341 struct bt_conn *bt_conn_lookup_index(uint8_t index);
342 
343 /* Look up a connection state. For BT_ADDR_LE_ANY, returns the first connection
344  * with the specific state
345  */
346 struct bt_conn *bt_conn_lookup_state_le(uint8_t id, const bt_addr_le_t *peer,
347 					const bt_conn_state_t state);
348 
349 /* Set connection object in certain state and perform action related to state */
350 void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state);
351 
352 void bt_conn_connected(struct bt_conn *conn);
353 
354 int bt_conn_le_conn_update(struct bt_conn *conn,
355 			   const struct bt_le_conn_param *param);
356 
357 void notify_remote_info(struct bt_conn *conn);
358 
359 void notify_le_param_updated(struct bt_conn *conn);
360 
361 void notify_le_data_len_updated(struct bt_conn *conn);
362 
363 void notify_le_phy_updated(struct bt_conn *conn);
364 
365 bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param);
366 
367 void notify_tx_power_report(struct bt_conn *conn,
368 			    struct bt_conn_le_tx_power_report report);
369 
370 #if defined(CONFIG_BT_SMP)
371 /* If role specific LTK is present */
372 bool bt_conn_ltk_present(const struct bt_conn *conn);
373 
374 /* rand and ediv should be in BT order */
375 int bt_conn_le_start_encryption(struct bt_conn *conn, uint8_t rand[8],
376 				uint8_t ediv[2], const uint8_t *ltk, size_t len);
377 
378 /* Notify higher layers that RPA was resolved */
379 void bt_conn_identity_resolved(struct bt_conn *conn);
380 #endif /* CONFIG_BT_SMP */
381 
382 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
383 /* Notify higher layers that connection security changed */
384 void bt_conn_security_changed(struct bt_conn *conn, uint8_t hci_err,
385 			      enum bt_security_err err);
386 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
387 
388 /* Prepare a PDU to be sent over a connection */
389 #if defined(CONFIG_NET_BUF_LOG)
390 struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool,
391 						 size_t reserve,
392 						 k_timeout_t timeout,
393 						 const char *func, int line);
394 #define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) \
395 	bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \
396 					 __func__, __LINE__)
397 
398 #define bt_conn_create_pdu(_pool, _reserve) \
399 	bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \
400 					 __func__, __line__)
401 #else
402 struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
403 					   size_t reserve, k_timeout_t timeout);
404 
405 #define bt_conn_create_pdu(_pool, _reserve) \
406 	bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER)
407 #endif
408 
409 /* Prepare a PDU to be sent over a connection */
410 #if defined(CONFIG_NET_BUF_LOG)
411 struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve,
412 						  k_timeout_t timeout,
413 						  const char *func, int line);
414 
415 #define bt_conn_create_frag_timeout(_reserve, _timeout) \
416 	bt_conn_create_frag_timeout_debug(_reserve, _timeout, \
417 					  __func__, __LINE__)
418 
419 #define bt_conn_create_frag(_reserve) \
420 	bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \
421 					  __func__, __LINE__)
422 #else
423 struct net_buf *bt_conn_create_frag_timeout(size_t reserve,
424 					    k_timeout_t timeout);
425 
426 #define bt_conn_create_frag(_reserve) \
427 	bt_conn_create_frag_timeout(_reserve, K_FOREVER)
428 #endif
429 
430 /* Initialize connection management */
431 int bt_conn_init(void);
432 
433 /* Reset states of connections and set state to BT_CONN_DISCONNECTED. */
434 void bt_conn_cleanup_all(void);
435 
436 /* Selects based on connection type right semaphore for ACL packets */
437 struct k_sem *bt_conn_get_pkts(struct bt_conn *conn);
438 
439 /* k_poll related helpers for the TX thread */
440 int bt_conn_prepare_events(struct k_poll_event events[]);
441 void bt_conn_process_tx(struct bt_conn *conn);
442