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 bt_conn {
150 	uint16_t			handle;
151 	enum bt_conn_type	type;
152 	uint8_t			role;
153 
154 	ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS);
155 
156 	/* Which local identity address this connection uses */
157 	uint8_t                    id;
158 
159 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
160 	bt_security_t		sec_level;
161 	bt_security_t		required_sec_level;
162 	uint8_t			encrypt;
163 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
164 
165 #if defined(CONFIG_BT_DF_CONNECTION_CTE_RX)
166 	/**
167 	 * @brief Bitfield with allowed CTE types.
168 	 *
169 	 *  Allowed values are defined by @ref bt_df_cte_type, except BT_DF_CTE_TYPE_NONE.
170 	 */
171 	uint8_t cte_types;
172 #endif /* CONFIG_BT_DF_CONNECTION_CTE_RX */
173 
174 	/* Connection error or reason for disconnect */
175 	uint8_t			err;
176 
177 	bt_conn_state_t		state;
178 	uint16_t rx_len;
179 	struct net_buf		*rx;
180 
181 	/* Sent but not acknowledged TX packets with a callback */
182 	sys_slist_t		tx_pending;
183 	/* Sent but not acknowledged TX packets without a callback before
184 	 * the next packet (if any) in tx_pending.
185 	 */
186 	uint32_t                   pending_no_cb;
187 
188 	/* Completed TX for which we need to call the callback */
189 	sys_slist_t		tx_complete;
190 #if defined(CONFIG_BT_CONN_TX)
191 	struct k_work           tx_complete_work;
192 #endif /* CONFIG_BT_CONN_TX */
193 
194 	/* Queue for outgoing ACL data */
195 	struct k_fifo		tx_queue;
196 
197 	/* Active L2CAP channels */
198 	sys_slist_t		channels;
199 
200 	/* Delayed work deferred tasks:
201 	 * - Peripheral delayed connection update.
202 	 * - Initiator connect create cancel.
203 	 * - Connection cleanup.
204 	 */
205 	struct k_work_delayable	deferred_work;
206 
207 	union {
208 		struct bt_conn_le	le;
209 #if defined(CONFIG_BT_BREDR)
210 		struct bt_conn_br	br;
211 		struct bt_conn_sco	sco;
212 #endif
213 #if defined(CONFIG_BT_ISO)
214 		struct bt_conn_iso	iso;
215 #endif
216 	};
217 
218 #if defined(CONFIG_BT_REMOTE_VERSION)
219 	struct bt_conn_rv {
220 		uint8_t  version;
221 		uint16_t manufacturer;
222 		uint16_t subversion;
223 	} rv;
224 #endif
225 	/* Must be at the end so that everything else in the structure can be
226 	 * memset to zero without affecting the ref.
227 	 */
228 	atomic_t		ref;
229 };
230 
231 void bt_conn_reset_rx_state(struct bt_conn *conn);
232 
233 /* Process incoming data for a connection */
234 void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, uint8_t flags);
235 
236 /* Send data over a connection
237  *
238  * Buffer ownership is transferred to stack in case of success.
239  *
240  * Calling this from RX thread is assumed to never fail so the return can be
241  * ignored.
242  */
243 int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
244 		    bt_conn_tx_cb_t cb, void *user_data);
245 
246 /* Thin wrapper over `bt_conn_send_cb`
247  *
248  * Used to set the TS_Flag bit in `buf`'s metadata.
249  *
250  * Return values & buf ownership same as parent.
251  */
252 int bt_conn_send_iso_cb(struct bt_conn *conn, struct net_buf *buf,
253 			bt_conn_tx_cb_t cb, bool has_ts);
254 
bt_conn_send(struct bt_conn * conn,struct net_buf * buf)255 static inline int bt_conn_send(struct bt_conn *conn, struct net_buf *buf)
256 {
257 	return bt_conn_send_cb(conn, buf, NULL, NULL);
258 }
259 
260 /* Check if a connection object with the peer already exists */
261 bool bt_conn_exists_le(uint8_t id, const bt_addr_le_t *peer);
262 
263 /* Add a new LE connection */
264 struct bt_conn *bt_conn_add_le(uint8_t id, const bt_addr_le_t *peer);
265 
266 /** Connection parameters for ISO connections */
267 struct bt_iso_create_param {
268 	uint8_t			id;
269 	uint8_t			num_conns;
270 	struct bt_conn		**conns;
271 	struct bt_iso_chan	**chans;
272 };
273 
274 int bt_conn_iso_init(void);
275 
276 /* Cleanup ISO references */
277 void bt_iso_cleanup_acl(struct bt_conn *iso_conn);
278 
279 /* Add a new BR/EDR connection */
280 struct bt_conn *bt_conn_add_br(const bt_addr_t *peer);
281 
282 /* Add a new SCO connection */
283 struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type);
284 
285 /* Cleanup SCO references */
286 void bt_sco_cleanup(struct bt_conn *sco_conn);
287 
288 /* Look up an existing sco connection by BT address */
289 struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer);
290 
291 /* Look up an existing connection by BT address */
292 struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer);
293 
294 void bt_conn_disconnect_all(uint8_t id);
295 
296 /* Allocate new connection object */
297 struct bt_conn *bt_conn_new(struct bt_conn *conns, size_t size);
298 
299 /* Look up an existing connection */
300 struct bt_conn *bt_conn_lookup_handle(uint16_t handle, enum bt_conn_type type);
301 
bt_conn_is_handle_valid(struct bt_conn * conn)302 static inline bool bt_conn_is_handle_valid(struct bt_conn *conn)
303 {
304 	switch (conn->state) {
305 	case BT_CONN_CONNECTED:
306 	case BT_CONN_DISCONNECTING:
307 	case BT_CONN_DISCONNECT_COMPLETE:
308 		return true;
309 	case BT_CONN_CONNECTING:
310 		/* ISO connection handle assigned at connect state */
311 		if (IS_ENABLED(CONFIG_BT_ISO) &&
312 		    conn->type == BT_CONN_TYPE_ISO) {
313 			return true;
314 		}
315 	__fallthrough;
316 	default:
317 		return false;
318 	}
319 }
320 
321 /* Check if the connection is with the given peer. */
322 bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, uint8_t id,
323 			     const bt_addr_le_t *peer);
324 
325 /* Helpers for identifying & looking up connections based on the the index to
326  * the connection list. This is useful for O(1) lookups, but can't be used
327  * e.g. as the handle since that's assigned to us by the controller.
328  */
329 #define BT_CONN_INDEX_INVALID 0xff
330 struct bt_conn *bt_conn_lookup_index(uint8_t index);
331 
332 /* Look up a connection state. For BT_ADDR_LE_ANY, returns the first connection
333  * with the specific state
334  */
335 struct bt_conn *bt_conn_lookup_state_le(uint8_t id, const bt_addr_le_t *peer,
336 					const bt_conn_state_t state);
337 
338 /* Set connection object in certain state and perform action related to state */
339 void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state);
340 
341 void bt_conn_connected(struct bt_conn *conn);
342 
343 int bt_conn_le_conn_update(struct bt_conn *conn,
344 			   const struct bt_le_conn_param *param);
345 
346 void notify_remote_info(struct bt_conn *conn);
347 
348 void notify_le_param_updated(struct bt_conn *conn);
349 
350 void notify_le_data_len_updated(struct bt_conn *conn);
351 
352 void notify_le_phy_updated(struct bt_conn *conn);
353 
354 bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param);
355 
356 #if defined(CONFIG_BT_SMP)
357 /* If role specific LTK is present */
358 bool bt_conn_ltk_present(const struct bt_conn *conn);
359 
360 /* rand and ediv should be in BT order */
361 int bt_conn_le_start_encryption(struct bt_conn *conn, uint8_t rand[8],
362 				uint8_t ediv[2], const uint8_t *ltk, size_t len);
363 
364 /* Notify higher layers that RPA was resolved */
365 void bt_conn_identity_resolved(struct bt_conn *conn);
366 #endif /* CONFIG_BT_SMP */
367 
368 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
369 /* Notify higher layers that connection security changed */
370 void bt_conn_security_changed(struct bt_conn *conn, uint8_t hci_err,
371 			      enum bt_security_err err);
372 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
373 
374 /* Prepare a PDU to be sent over a connection */
375 #if defined(CONFIG_NET_BUF_LOG)
376 struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool,
377 						 size_t reserve,
378 						 k_timeout_t timeout,
379 						 const char *func, int line);
380 #define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) \
381 	bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \
382 					 __func__, __LINE__)
383 
384 #define bt_conn_create_pdu(_pool, _reserve) \
385 	bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \
386 					 __func__, __line__)
387 #else
388 struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
389 					   size_t reserve, k_timeout_t timeout);
390 
391 #define bt_conn_create_pdu(_pool, _reserve) \
392 	bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER)
393 #endif
394 
395 /* Prepare a PDU to be sent over a connection */
396 #if defined(CONFIG_NET_BUF_LOG)
397 struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve,
398 						  k_timeout_t timeout,
399 						  const char *func, int line);
400 
401 #define bt_conn_create_frag_timeout(_reserve, _timeout) \
402 	bt_conn_create_frag_timeout_debug(_reserve, _timeout, \
403 					  __func__, __LINE__)
404 
405 #define bt_conn_create_frag(_reserve) \
406 	bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \
407 					  __func__, __LINE__)
408 #else
409 struct net_buf *bt_conn_create_frag_timeout(size_t reserve,
410 					    k_timeout_t timeout);
411 
412 #define bt_conn_create_frag(_reserve) \
413 	bt_conn_create_frag_timeout(_reserve, K_FOREVER)
414 #endif
415 
416 /* Initialize connection management */
417 int bt_conn_init(void);
418 
419 /* Reset states of connections and set state to BT_CONN_DISCONNECTED. */
420 void bt_conn_cleanup_all(void);
421 
422 /* Selects based on connection type right semaphore for ACL packets */
423 struct k_sem *bt_conn_get_pkts(struct bt_conn *conn);
424 
425 /* k_poll related helpers for the TX thread */
426 int bt_conn_prepare_events(struct k_poll_event events[]);
427 void bt_conn_process_tx(struct bt_conn *conn);
428