1 /* conn.c - Bluetooth connection handling */
2 
3 /*
4  * Copyright (c) 2015-2016 Intel Corporation
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <zephyr/kernel.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <stdbool.h>
13 #include <zephyr/sys/atomic.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/sys/check.h>
16 #include <zephyr/sys/iterable_sections.h>
17 #include <zephyr/sys/util.h>
18 #include <zephyr/sys/util_macro.h>
19 #include <zephyr/sys/slist.h>
20 #include <zephyr/debug/stack.h>
21 #include <zephyr/sys/__assert.h>
22 
23 #include <zephyr/bluetooth/hci.h>
24 #include <zephyr/bluetooth/bluetooth.h>
25 #include <zephyr/bluetooth/direction.h>
26 #include <zephyr/bluetooth/conn.h>
27 #include <zephyr/drivers/bluetooth/hci_driver.h>
28 #include <zephyr/bluetooth/att.h>
29 
30 #include "common/assert.h"
31 #include "common/bt_str.h"
32 
33 #include "addr_internal.h"
34 #include "hci_core.h"
35 #include "id.h"
36 #include "adv.h"
37 #include "conn_internal.h"
38 #include "l2cap_internal.h"
39 #include "keys.h"
40 #include "smp.h"
41 #include "ssp.h"
42 #include "att_internal.h"
43 #include "iso_internal.h"
44 #include "direction_internal.h"
45 
46 #define LOG_LEVEL CONFIG_BT_CONN_LOG_LEVEL
47 #include <zephyr/logging/log.h>
48 LOG_MODULE_REGISTER(bt_conn);
49 
50 struct tx_meta {
51 	struct bt_conn_tx *tx;
52 	/* This flag indicates if the current buffer has already been partially
53 	 * sent to the controller (ie, the next fragments should be sent as
54 	 * continuations).
55 	 */
56 	bool is_cont;
57 	/* Indicates whether the ISO PDU contains a timestamp */
58 	bool iso_has_ts;
59 };
60 
61 BUILD_ASSERT(sizeof(struct tx_meta) == CONFIG_BT_CONN_TX_USER_DATA_SIZE,
62 	     "User data size is wrong!");
63 
64 #define tx_data(buf) ((struct tx_meta *)net_buf_user_data(buf))
65 K_FIFO_DEFINE(free_tx);
66 
67 static void tx_free(struct bt_conn_tx *tx);
68 
conn_tx_destroy(struct bt_conn * conn,struct bt_conn_tx * tx)69 static void conn_tx_destroy(struct bt_conn *conn, struct bt_conn_tx *tx)
70 {
71 	__ASSERT_NO_MSG(tx);
72 
73 	bt_conn_tx_cb_t cb = tx->cb;
74 	void *user_data = tx->user_data;
75 
76 	/* Free up TX metadata before calling callback in case the callback
77 	 * tries to allocate metadata
78 	 */
79 	tx_free(tx);
80 
81 	cb(conn, user_data, -ESHUTDOWN);
82 }
83 
84 #if defined(CONFIG_BT_CONN_TX)
85 static void tx_complete_work(struct k_work *work);
86 #endif /* CONFIG_BT_CONN_TX */
87 
88 static void notify_recycled_conn_slot(void);
89 
90 /* Group Connected BT_CONN only in this */
91 #if defined(CONFIG_BT_CONN)
92 /* Peripheral timeout to initialize Connection Parameter Update procedure */
93 #define CONN_UPDATE_TIMEOUT  K_MSEC(CONFIG_BT_CONN_PARAM_UPDATE_TIMEOUT)
94 
95 static void deferred_work(struct k_work *work);
96 static void notify_connected(struct bt_conn *conn);
97 
98 static struct bt_conn acl_conns[CONFIG_BT_MAX_CONN];
99 NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT,
100 		    BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU),
101 		    CONFIG_BT_CONN_TX_USER_DATA_SIZE, NULL);
102 
103 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
104 /* Dedicated pool for fragment buffers in case queued up TX buffers don't
105  * fit the controllers buffer size. We can't use the acl_tx_pool for the
106  * fragmentation, since it's possible that pool is empty and all buffers
107  * are queued up in the TX queue. In such a situation, trying to allocate
108  * another buffer from the acl_tx_pool would result in a deadlock.
109  */
110 NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT,
111 			  BT_BUF_ACL_SIZE(CONFIG_BT_BUF_ACL_TX_SIZE),
112 			  CONFIG_BT_CONN_TX_USER_DATA_SIZE, NULL);
113 
114 #endif /* CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 */
115 
116 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
117 const struct bt_conn_auth_cb *bt_auth;
118 sys_slist_t bt_auth_info_cbs = SYS_SLIST_STATIC_INIT(&bt_auth_info_cbs);
119 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
120 
121 static struct bt_conn_cb *callback_list;
122 
123 static struct bt_conn_tx conn_tx[CONFIG_BT_CONN_TX_MAX];
124 
125 #if defined(CONFIG_BT_BREDR)
126 static int bt_hci_connect_br_cancel(struct bt_conn *conn);
127 
128 static struct bt_conn sco_conns[CONFIG_BT_MAX_SCO_CONN];
129 #endif /* CONFIG_BT_BREDR */
130 #endif /* CONFIG_BT_CONN */
131 
132 #if defined(CONFIG_BT_ISO)
133 extern struct bt_conn iso_conns[CONFIG_BT_ISO_MAX_CHAN];
134 
135 /* Callback TX buffers for ISO */
136 static struct bt_conn_tx iso_tx[CONFIG_BT_ISO_TX_BUF_COUNT];
137 
bt_conn_iso_init(void)138 int bt_conn_iso_init(void)
139 {
140 	for (size_t i = 0; i < ARRAY_SIZE(iso_tx); i++) {
141 		k_fifo_put(&free_tx, &iso_tx[i]);
142 	}
143 
144 	return 0;
145 }
146 #endif /* CONFIG_BT_ISO */
147 
bt_conn_get_pkts(struct bt_conn * conn)148 struct k_sem *bt_conn_get_pkts(struct bt_conn *conn)
149 {
150 #if defined(CONFIG_BT_BREDR)
151 	if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.acl_mtu) {
152 		return &bt_dev.br.pkts;
153 	}
154 #endif /* CONFIG_BT_BREDR */
155 
156 #if defined(CONFIG_BT_ISO)
157 	/* Use ISO pkts semaphore if LE Read Buffer Size command returned
158 	 * dedicated ISO buffers.
159 	 */
160 	if (conn->type == BT_CONN_TYPE_ISO) {
161 		if (bt_dev.le.iso_mtu && bt_dev.le.iso_limit != 0) {
162 			return &bt_dev.le.iso_pkts;
163 		}
164 
165 		return NULL;
166 	}
167 #endif /* CONFIG_BT_ISO */
168 
169 #if defined(CONFIG_BT_CONN)
170 	if (bt_dev.le.acl_mtu) {
171 		return &bt_dev.le.acl_pkts;
172 	}
173 #endif /* CONFIG_BT_CONN */
174 
175 	return NULL;
176 }
177 
state2str(bt_conn_state_t state)178 static inline const char *state2str(bt_conn_state_t state)
179 {
180 	switch (state) {
181 	case BT_CONN_DISCONNECTED:
182 		return "disconnected";
183 	case BT_CONN_DISCONNECT_COMPLETE:
184 		return "disconnect-complete";
185 	case BT_CONN_CONNECTING_SCAN:
186 		return "connecting-scan";
187 	case BT_CONN_CONNECTING_DIR_ADV:
188 		return "connecting-dir-adv";
189 	case BT_CONN_CONNECTING_ADV:
190 		return "connecting-adv";
191 	case BT_CONN_CONNECTING_AUTO:
192 		return "connecting-auto";
193 	case BT_CONN_CONNECTING:
194 		return "connecting";
195 	case BT_CONN_CONNECTED:
196 		return "connected";
197 	case BT_CONN_DISCONNECTING:
198 		return "disconnecting";
199 	default:
200 		return "(unknown)";
201 	}
202 }
203 
tx_free(struct bt_conn_tx * tx)204 static void tx_free(struct bt_conn_tx *tx)
205 {
206 	tx->cb = NULL;
207 	tx->user_data = NULL;
208 	tx->pending_no_cb = 0U;
209 	k_fifo_put(&free_tx, tx);
210 }
211 
tx_notify(struct bt_conn * conn)212 static void tx_notify(struct bt_conn *conn)
213 {
214 	LOG_DBG("conn %p", conn);
215 
216 	while (1) {
217 		struct bt_conn_tx *tx = NULL;
218 		unsigned int key;
219 		bt_conn_tx_cb_t cb;
220 		void *user_data;
221 
222 		key = irq_lock();
223 		if (!sys_slist_is_empty(&conn->tx_complete)) {
224 			tx = CONTAINER_OF(sys_slist_get_not_empty(&conn->tx_complete),
225 					  struct bt_conn_tx, node);
226 		}
227 		irq_unlock(key);
228 
229 		if (!tx) {
230 			return;
231 		}
232 
233 		LOG_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data);
234 
235 		/* Copy over the params */
236 		cb = tx->cb;
237 		user_data = tx->user_data;
238 
239 		/* Free up TX notify since there may be user waiting */
240 		tx_free(tx);
241 
242 		/* Run the callback, at this point it should be safe to
243 		 * allocate new buffers since the TX should have been
244 		 * unblocked by tx_free.
245 		 */
246 		cb(conn, user_data, 0);
247 	}
248 }
249 
bt_conn_new(struct bt_conn * conns,size_t size)250 struct bt_conn *bt_conn_new(struct bt_conn *conns, size_t size)
251 {
252 	struct bt_conn *conn = NULL;
253 	int i;
254 
255 	for (i = 0; i < size; i++) {
256 		if (atomic_cas(&conns[i].ref, 0, 1)) {
257 			conn = &conns[i];
258 			break;
259 		}
260 	}
261 
262 	if (!conn) {
263 		return NULL;
264 	}
265 
266 	(void)memset(conn, 0, offsetof(struct bt_conn, ref));
267 
268 #if defined(CONFIG_BT_CONN)
269 	k_work_init_delayable(&conn->deferred_work, deferred_work);
270 #endif /* CONFIG_BT_CONN */
271 #if defined(CONFIG_BT_CONN_TX)
272 	k_work_init(&conn->tx_complete_work, tx_complete_work);
273 #endif /* CONFIG_BT_CONN_TX */
274 
275 	return conn;
276 }
277 
bt_conn_reset_rx_state(struct bt_conn * conn)278 void bt_conn_reset_rx_state(struct bt_conn *conn)
279 {
280 	if (!conn->rx) {
281 		return;
282 	}
283 
284 	net_buf_unref(conn->rx);
285 	conn->rx = NULL;
286 }
287 
bt_acl_recv(struct bt_conn * conn,struct net_buf * buf,uint8_t flags)288 static void bt_acl_recv(struct bt_conn *conn, struct net_buf *buf,
289 			uint8_t flags)
290 {
291 	uint16_t acl_total_len;
292 
293 	/* Check packet boundary flags */
294 	switch (flags) {
295 	case BT_ACL_START:
296 		if (conn->rx) {
297 			LOG_ERR("Unexpected first L2CAP frame");
298 			bt_conn_reset_rx_state(conn);
299 		}
300 
301 		LOG_DBG("First, len %u final %u", buf->len,
302 			(buf->len < sizeof(uint16_t)) ? 0 : sys_get_le16(buf->data));
303 
304 		conn->rx = buf;
305 		break;
306 	case BT_ACL_CONT:
307 		if (!conn->rx) {
308 			LOG_ERR("Unexpected L2CAP continuation");
309 			bt_conn_reset_rx_state(conn);
310 			net_buf_unref(buf);
311 			return;
312 		}
313 
314 		if (!buf->len) {
315 			LOG_DBG("Empty ACL_CONT");
316 			net_buf_unref(buf);
317 			return;
318 		}
319 
320 		if (buf->len > net_buf_tailroom(conn->rx)) {
321 			LOG_ERR("Not enough buffer space for L2CAP data");
322 
323 			/* Frame is not complete but we still pass it to L2CAP
324 			 * so that it may handle error on protocol level
325 			 * eg disconnect channel.
326 			 */
327 			bt_l2cap_recv(conn, conn->rx, false);
328 			conn->rx = NULL;
329 			net_buf_unref(buf);
330 			return;
331 		}
332 
333 		net_buf_add_mem(conn->rx, buf->data, buf->len);
334 		net_buf_unref(buf);
335 		break;
336 	default:
337 		/* BT_ACL_START_NO_FLUSH and BT_ACL_COMPLETE are not allowed on
338 		 * LE-U from Controller to Host.
339 		 * Only BT_ACL_POINT_TO_POINT is supported.
340 		 */
341 		LOG_ERR("Unexpected ACL flags (0x%02x)", flags);
342 		bt_conn_reset_rx_state(conn);
343 		net_buf_unref(buf);
344 		return;
345 	}
346 
347 	if (conn->rx->len < sizeof(uint16_t)) {
348 		/* Still not enough data received to retrieve the L2CAP header
349 		 * length field.
350 		 */
351 		return;
352 	}
353 
354 	acl_total_len = sys_get_le16(conn->rx->data) + sizeof(struct bt_l2cap_hdr);
355 
356 	if (conn->rx->len < acl_total_len) {
357 		/* L2CAP frame not complete. */
358 		return;
359 	}
360 
361 	if (conn->rx->len > acl_total_len) {
362 		LOG_ERR("ACL len mismatch (%u > %u)", conn->rx->len, acl_total_len);
363 		bt_conn_reset_rx_state(conn);
364 		return;
365 	}
366 
367 	/* L2CAP frame complete. */
368 	buf = conn->rx;
369 	conn->rx = NULL;
370 
371 	LOG_DBG("Successfully parsed %u byte L2CAP packet", buf->len);
372 	bt_l2cap_recv(conn, buf, true);
373 }
374 
bt_conn_recv(struct bt_conn * conn,struct net_buf * buf,uint8_t flags)375 void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, uint8_t flags)
376 {
377 	/* Make sure we notify any pending TX callbacks before processing
378 	 * new data for this connection.
379 	 */
380 	tx_notify(conn);
381 
382 	LOG_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags);
383 
384 	if ((IS_ENABLED(CONFIG_BT_ISO_UNICAST) ||
385 	     IS_ENABLED(CONFIG_BT_ISO_SYNC_RECEIVER)) &&
386 	    conn->type == BT_CONN_TYPE_ISO) {
387 		bt_iso_recv(conn, buf, flags);
388 		return;
389 	} else if (IS_ENABLED(CONFIG_BT_CONN)) {
390 		bt_acl_recv(conn, buf, flags);
391 	} else {
392 		__ASSERT(false, "Invalid connection type %u", conn->type);
393 	}
394 }
395 
conn_tx_alloc(void)396 static struct bt_conn_tx *conn_tx_alloc(void)
397 {
398 	/* The TX context always get freed in the system workqueue,
399 	 * so if we're in the same workqueue but there are no immediate
400 	 * contexts available, there's no chance we'll get one by waiting.
401 	 */
402 	if (k_current_get() == &k_sys_work_q.thread) {
403 		return k_fifo_get(&free_tx, K_NO_WAIT);
404 	}
405 
406 	if (IS_ENABLED(CONFIG_BT_CONN_LOG_LEVEL_DBG)) {
407 		struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT);
408 
409 		if (tx) {
410 			return tx;
411 		}
412 
413 		LOG_WRN("Unable to get an immediate free conn_tx");
414 	}
415 
416 	return k_fifo_get(&free_tx, K_FOREVER);
417 }
418 
bt_conn_send_iso_cb(struct bt_conn * conn,struct net_buf * buf,bt_conn_tx_cb_t cb,bool has_ts)419 int bt_conn_send_iso_cb(struct bt_conn *conn, struct net_buf *buf,
420 			bt_conn_tx_cb_t cb, bool has_ts)
421 {
422 	if (buf->user_data_size < CONFIG_BT_CONN_TX_USER_DATA_SIZE) {
423 		LOG_ERR("not enough room in user_data %d < %d",
424 			buf->user_data_size,
425 			CONFIG_BT_CONN_TX_USER_DATA_SIZE);
426 		return -EINVAL;
427 	}
428 
429 	/* Necessary for setting the TS_Flag bit when we pop the buffer from the
430 	 * send queue. The flag needs to be set before adding the buffer to the queue.
431 	 */
432 	tx_data(buf)->iso_has_ts = has_ts;
433 
434 	int err = bt_conn_send_cb(conn, buf, cb, NULL);
435 
436 	if (err) {
437 		return err;
438 	}
439 
440 	return 0;
441 }
442 
bt_conn_send_cb(struct bt_conn * conn,struct net_buf * buf,bt_conn_tx_cb_t cb,void * user_data)443 int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
444 		    bt_conn_tx_cb_t cb, void *user_data)
445 {
446 	struct bt_conn_tx *tx;
447 
448 	LOG_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle, buf->len, cb,
449 		user_data);
450 
451 	if (buf->user_data_size < CONFIG_BT_CONN_TX_USER_DATA_SIZE) {
452 		LOG_ERR("not enough room in user_data %d < %d pool %u",
453 			buf->user_data_size,
454 			CONFIG_BT_CONN_TX_USER_DATA_SIZE,
455 			buf->pool_id);
456 		return -EINVAL;
457 	}
458 
459 	if (conn->state != BT_CONN_CONNECTED) {
460 		LOG_ERR("not connected!");
461 		return -ENOTCONN;
462 	}
463 
464 	if (cb) {
465 		tx = conn_tx_alloc();
466 		if (!tx) {
467 			LOG_DBG("Unable to allocate TX context");
468 			return -ENOBUFS;
469 		}
470 
471 		/* Verify that we're still connected after blocking */
472 		if (conn->state != BT_CONN_CONNECTED) {
473 			LOG_WRN("Disconnected while allocating context");
474 			tx_free(tx);
475 			return -ENOTCONN;
476 		}
477 
478 		tx->cb = cb;
479 		tx->user_data = user_data;
480 		tx->pending_no_cb = 0U;
481 
482 		tx_data(buf)->tx = tx;
483 	} else {
484 		tx_data(buf)->tx = NULL;
485 	}
486 
487 	tx_data(buf)->is_cont = false;
488 
489 	net_buf_put(&conn->tx_queue, buf);
490 	return 0;
491 }
492 
493 enum {
494 	FRAG_START,
495 	FRAG_CONT,
496 	FRAG_SINGLE,
497 	FRAG_END
498 };
499 
send_acl(struct bt_conn * conn,struct net_buf * buf,uint8_t flags)500 static int send_acl(struct bt_conn *conn, struct net_buf *buf, uint8_t flags)
501 {
502 	struct bt_hci_acl_hdr *hdr;
503 
504 	switch (flags) {
505 	case FRAG_START:
506 	case FRAG_SINGLE:
507 		flags = BT_ACL_START_NO_FLUSH;
508 		break;
509 	case FRAG_CONT:
510 	case FRAG_END:
511 		flags = BT_ACL_CONT;
512 		break;
513 	default:
514 		return -EINVAL;
515 	}
516 
517 	hdr = net_buf_push(buf, sizeof(*hdr));
518 	hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags));
519 	hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
520 
521 	bt_buf_set_type(buf, BT_BUF_ACL_OUT);
522 
523 	return bt_send(buf);
524 }
525 
send_iso(struct bt_conn * conn,struct net_buf * buf,uint8_t flags)526 static int send_iso(struct bt_conn *conn, struct net_buf *buf, uint8_t flags)
527 {
528 	struct bt_hci_iso_hdr *hdr;
529 	bool ts;
530 
531 	switch (flags) {
532 	case FRAG_START:
533 		flags = BT_ISO_START;
534 		break;
535 	case FRAG_CONT:
536 		flags = BT_ISO_CONT;
537 		break;
538 	case FRAG_SINGLE:
539 		flags = BT_ISO_SINGLE;
540 		break;
541 	case FRAG_END:
542 		flags = BT_ISO_END;
543 		break;
544 	default:
545 		return -EINVAL;
546 	}
547 
548 	hdr = net_buf_push(buf, sizeof(*hdr));
549 
550 	ts = tx_data(buf)->iso_has_ts &&
551 		(flags == BT_ISO_START || flags == BT_ISO_SINGLE);
552 
553 	hdr->handle = sys_cpu_to_le16(bt_iso_handle_pack(conn->handle, flags, ts));
554 
555 	hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
556 
557 	bt_buf_set_type(buf, BT_BUF_ISO_OUT);
558 
559 	return bt_send(buf);
560 }
561 
conn_mtu(struct bt_conn * conn)562 static inline uint16_t conn_mtu(struct bt_conn *conn)
563 {
564 #if defined(CONFIG_BT_BREDR)
565 	if (conn->type == BT_CONN_TYPE_BR ||
566 	    (conn->type != BT_CONN_TYPE_ISO && !bt_dev.le.acl_mtu)) {
567 		return bt_dev.br.mtu;
568 	}
569 #endif /* CONFIG_BT_BREDR */
570 #if defined(CONFIG_BT_ISO)
571 	if (conn->type == BT_CONN_TYPE_ISO) {
572 		return bt_dev.le.iso_mtu;
573 	}
574 #endif /* CONFIG_BT_ISO */
575 #if defined(CONFIG_BT_CONN)
576 	return bt_dev.le.acl_mtu;
577 #else
578 	return 0;
579 #endif /* CONFIG_BT_CONN */
580 }
581 
do_send_frag(struct bt_conn * conn,struct net_buf * buf,uint8_t flags)582 static int do_send_frag(struct bt_conn *conn, struct net_buf *buf, uint8_t flags)
583 {
584 	struct bt_conn_tx *tx = tx_data(buf)->tx;
585 	uint32_t *pending_no_cb = NULL;
586 	unsigned int key;
587 	int err = 0;
588 
589 	LOG_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len,
590 		flags);
591 
592 	/* Add to pending, it must be done before bt_buf_set_type */
593 	key = irq_lock();
594 	if (tx) {
595 		sys_slist_append(&conn->tx_pending, &tx->node);
596 	} else {
597 		struct bt_conn_tx *tail_tx;
598 
599 		tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending);
600 		if (tail_tx) {
601 			pending_no_cb = &tail_tx->pending_no_cb;
602 		} else {
603 			pending_no_cb = &conn->pending_no_cb;
604 		}
605 
606 		(*pending_no_cb)++;
607 	}
608 	irq_unlock(key);
609 
610 	if (IS_ENABLED(CONFIG_BT_ISO) && conn->type == BT_CONN_TYPE_ISO) {
611 		err = send_iso(conn, buf, flags);
612 	} else if (IS_ENABLED(CONFIG_BT_CONN)) {
613 		err = send_acl(conn, buf, flags);
614 	} else {
615 		__ASSERT(false, "Invalid connection type %u", conn->type);
616 	}
617 
618 	if (err) {
619 		LOG_ERR("Unable to send to driver (err %d)", err);
620 		key = irq_lock();
621 		/* Roll back the pending TX info */
622 		if (tx) {
623 			sys_slist_find_and_remove(&conn->tx_pending, &tx->node);
624 		} else {
625 			__ASSERT_NO_MSG(*pending_no_cb > 0);
626 			(*pending_no_cb)--;
627 		}
628 		irq_unlock(key);
629 
630 		/* We don't want to end up in a situation where send_acl/iso
631 		 * returns the same error code as when we don't get a buffer in
632 		 * time.
633 		 */
634 		err = -EIO;
635 		goto fail;
636 	}
637 
638 	return 0;
639 
640 fail:
641 	/* If we get here, something has seriously gone wrong:
642 	 * We also need to destroy the `parent` buf.
643 	 */
644 	k_sem_give(bt_conn_get_pkts(conn));
645 	if (tx) {
646 		/* `buf` might not get destroyed, and its `tx` pointer will still be reachable.
647 		 * Make sure that we don't try to use the destroyed context later.
648 		 */
649 		tx_data(buf)->tx = NULL;
650 		conn_tx_destroy(conn, tx);
651 	}
652 
653 	return err;
654 }
655 
send_frag(struct bt_conn * conn,struct net_buf * buf,struct net_buf * frag,uint8_t flags)656 static int send_frag(struct bt_conn *conn,
657 		     struct net_buf *buf, struct net_buf *frag,
658 		     uint8_t flags)
659 {
660 	/* Check if the controller can accept ACL packets */
661 	if (k_sem_take(bt_conn_get_pkts(conn), K_NO_WAIT)) {
662 		LOG_DBG("no controller bufs");
663 		return -ENOBUFS;
664 	}
665 
666 	/* Check for disconnection. It can't be done higher up (ie `send_buf`)
667 	 * as `create_frag` blocks with K_FOREVER and the connection could
668 	 * change state after waiting.
669 	 */
670 	if (conn->state != BT_CONN_CONNECTED) {
671 		return -ENOTCONN;
672 	}
673 
674 	/* Add the data to the buffer */
675 	if (frag) {
676 		uint16_t frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag));
677 
678 		net_buf_add_mem(frag, buf->data, frag_len);
679 		net_buf_pull(buf, frag_len);
680 	} else {
681 		/* De-queue the buffer now that we know we can send it.
682 		 * Only applies if the buffer to be sent is the original buffer,
683 		 * and not one of its fragments.
684 		 * This buffer was fetched from the FIFO using a peek operation.
685 		 */
686 		buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
687 		frag = buf;
688 	}
689 
690 	return do_send_frag(conn, frag, flags);
691 }
692 
create_frag(struct bt_conn * conn,struct net_buf * buf)693 static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf)
694 {
695 	struct net_buf *frag;
696 
697 	switch (conn->type) {
698 #if defined(CONFIG_BT_ISO)
699 	case BT_CONN_TYPE_ISO:
700 		frag = bt_iso_create_frag(0);
701 		break;
702 #endif
703 	default:
704 #if defined(CONFIG_BT_CONN)
705 		frag = bt_conn_create_frag(0);
706 #else
707 		return NULL;
708 #endif /* CONFIG_BT_CONN */
709 
710 	}
711 
712 	if (conn->state != BT_CONN_CONNECTED) {
713 		net_buf_unref(frag);
714 		return NULL;
715 	}
716 
717 	/* Fragments never have a TX completion callback */
718 	tx_data(frag)->tx = NULL;
719 	tx_data(frag)->is_cont = false;
720 	tx_data(frag)->iso_has_ts = tx_data(buf)->iso_has_ts;
721 
722 	return frag;
723 }
724 
725 /* Tentatively send a buffer to the HCI driver.
726  *
727  * This is designed to be async, as in most failures due to lack of resources
728  * are not fatal. The caller should call `send_buf()` again later.
729  *
730  * Return values:
731  *
732  * - 0: `buf` sent. `buf` ownership transferred to lower layers.
733  *
734  * - -EIO: buffer failed to send due to HCI error. `buf` ownership returned to
735  *    caller BUT `buf` is popped from the TX queue. The caller shall destroy
736  *    `buf` and its TX context.
737  *
738  * - Any other error: buffer failed to send. `buf` ownership returned to caller
739  *   and `buf` is still the head of the TX queue
740  *
741  */
send_buf(struct bt_conn * conn,struct net_buf * buf)742 static int send_buf(struct bt_conn *conn, struct net_buf *buf)
743 {
744 	struct net_buf *frag;
745 	uint8_t flags;
746 	int err;
747 
748 	LOG_DBG("conn %p buf %p len %u", conn, buf, buf->len);
749 
750 	/* Send directly if the packet fits the ACL MTU */
751 	if (buf->len <= conn_mtu(conn) && !tx_data(buf)->is_cont) {
752 		LOG_DBG("send single");
753 		return send_frag(conn, buf, NULL, FRAG_SINGLE);
754 	}
755 
756 	LOG_DBG("start fragmenting");
757 	/*
758 	 * Send the fragments. For the last one simply use the original
759 	 * buffer (which works since we've used net_buf_pull on it).
760 	 */
761 	flags = FRAG_START;
762 	if (tx_data(buf)->is_cont) {
763 		flags = FRAG_CONT;
764 	}
765 
766 	while (buf->len > conn_mtu(conn)) {
767 		frag = create_frag(conn, buf);
768 		if (!frag) {
769 			return -ENOMEM;
770 		}
771 
772 		err = send_frag(conn, buf, frag, flags);
773 		if (err) {
774 			LOG_DBG("%p failed, mark as existing frag", buf);
775 			tx_data(buf)->is_cont = flags != FRAG_START;
776 			net_buf_unref(frag);
777 			return err;
778 		}
779 
780 		flags = FRAG_CONT;
781 	}
782 
783 	LOG_DBG("last frag");
784 	tx_data(buf)->is_cont = true;
785 	return send_frag(conn, buf, NULL, FRAG_END);
786 }
787 
788 static struct k_poll_signal conn_change =
789 		K_POLL_SIGNAL_INITIALIZER(conn_change);
790 
conn_cleanup(struct bt_conn * conn)791 static void conn_cleanup(struct bt_conn *conn)
792 {
793 	struct net_buf *buf;
794 
795 	/* Give back any allocated buffers */
796 	while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) {
797 		struct bt_conn_tx *tx = tx_data(buf)->tx;
798 
799 		tx_data(buf)->tx = NULL;
800 
801 		/* destroy the buffer */
802 		net_buf_unref(buf);
803 
804 		/* destroy the tx context (and any associated meta-data) */
805 		if (tx) {
806 			conn_tx_destroy(conn, tx);
807 		}
808 	}
809 
810 	__ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets");
811 	__ASSERT_NO_MSG(conn->pending_no_cb == 0);
812 
813 	bt_conn_reset_rx_state(conn);
814 
815 	k_work_reschedule(&conn->deferred_work, K_NO_WAIT);
816 }
817 
conn_destroy(struct bt_conn * conn,void * data)818 static void conn_destroy(struct bt_conn *conn, void *data)
819 {
820 	if (conn->state == BT_CONN_CONNECTED ||
821 	    conn->state == BT_CONN_DISCONNECTING) {
822 		bt_conn_set_state(conn, BT_CONN_DISCONNECT_COMPLETE);
823 	}
824 
825 	bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
826 }
827 
bt_conn_cleanup_all(void)828 void bt_conn_cleanup_all(void)
829 {
830 	bt_conn_foreach(BT_CONN_TYPE_ALL, conn_destroy, NULL);
831 }
832 
conn_prepare_events(struct bt_conn * conn,struct k_poll_event * events)833 static int conn_prepare_events(struct bt_conn *conn,
834 			       struct k_poll_event *events)
835 {
836 	if (!atomic_get(&conn->ref)) {
837 		return -ENOTCONN;
838 	}
839 
840 	if (conn->state == BT_CONN_DISCONNECTED &&
841 	    atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
842 		conn_cleanup(conn);
843 		return -ENOTCONN;
844 	}
845 
846 	if (conn->state != BT_CONN_CONNECTED) {
847 		return -ENOTCONN;
848 	}
849 
850 	LOG_DBG("Adding conn %p to poll list", conn);
851 
852 	/* ISO Synchronized Receiver only builds do not transmit and hence
853 	 * may not have any tx buffers allocated in a Controller.
854 	 */
855 	struct k_sem *conn_pkts = bt_conn_get_pkts(conn);
856 
857 	if (!conn_pkts) {
858 		return -ENOTCONN;
859 	}
860 
861 	bool buffers_available = k_sem_count_get(conn_pkts) > 0;
862 	bool packets_waiting = !k_fifo_is_empty(&conn->tx_queue);
863 
864 	if (packets_waiting && !buffers_available) {
865 		/* Only resume sending when the controller has buffer space
866 		 * available for this connection.
867 		 */
868 		LOG_DBG("wait on ctlr buffers");
869 		k_poll_event_init(&events[0],
870 				  K_POLL_TYPE_SEM_AVAILABLE,
871 				  K_POLL_MODE_NOTIFY_ONLY,
872 				  conn_pkts);
873 	} else {
874 		/* Wait until there is more data to send. */
875 		LOG_DBG("wait on host fifo");
876 		k_poll_event_init(&events[0],
877 				  K_POLL_TYPE_FIFO_DATA_AVAILABLE,
878 				  K_POLL_MODE_NOTIFY_ONLY,
879 				  &conn->tx_queue);
880 	}
881 	events[0].tag = BT_EVENT_CONN_TX_QUEUE;
882 
883 	return 0;
884 }
885 
bt_conn_prepare_events(struct k_poll_event events[])886 int bt_conn_prepare_events(struct k_poll_event events[])
887 {
888 	int i, ev_count = 0;
889 	struct bt_conn *conn;
890 
891 	LOG_DBG("");
892 
893 	k_poll_signal_init(&conn_change);
894 
895 	k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL,
896 			  K_POLL_MODE_NOTIFY_ONLY, &conn_change);
897 
898 #if defined(CONFIG_BT_CONN)
899 	for (i = 0; i < ARRAY_SIZE(acl_conns); i++) {
900 		conn = &acl_conns[i];
901 
902 		if (!conn_prepare_events(conn, &events[ev_count])) {
903 			ev_count++;
904 		}
905 	}
906 #endif /* CONFIG_BT_CONN */
907 
908 #if defined(CONFIG_BT_ISO)
909 	for (i = 0; i < ARRAY_SIZE(iso_conns); i++) {
910 		conn = &iso_conns[i];
911 
912 		if (!conn_prepare_events(conn, &events[ev_count])) {
913 			ev_count++;
914 		}
915 	}
916 #endif
917 
918 	return ev_count;
919 }
920 
bt_conn_process_tx(struct bt_conn * conn)921 void bt_conn_process_tx(struct bt_conn *conn)
922 {
923 	struct net_buf *buf;
924 	int err;
925 
926 	LOG_DBG("conn %p", conn);
927 
928 	if (conn->state == BT_CONN_DISCONNECTED &&
929 	    atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
930 		LOG_DBG("handle %u disconnected - cleaning up", conn->handle);
931 		conn_cleanup(conn);
932 		return;
933 	}
934 
935 	/* Get next ACL packet for connection. The buffer will only get dequeued
936 	 * if there is a free controller buffer to put it in.
937 	 *
938 	 * Important: no operations should be done on `buf` until it is properly
939 	 * dequeued from the FIFO, using the `net_buf_get()` API.
940 	 */
941 	buf = k_fifo_peek_head(&conn->tx_queue);
942 	BT_ASSERT(buf);
943 
944 	/* Since we used `peek`, the queue still owns the reference to the
945 	 * buffer, so we need to take an explicit additional reference here.
946 	 */
947 	buf = net_buf_ref(buf);
948 	err = send_buf(conn, buf);
949 	net_buf_unref(buf);
950 
951 	/* HCI driver error. `buf` may have been popped from `tx_queue` and
952 	 * should be destroyed.
953 	 *
954 	 * TODO: In that case we might want to disable Bluetooth or at the very
955 	 * least tear down the connection.
956 	 */
957 	if (err  == -EIO) {
958 		struct bt_conn_tx *tx = tx_data(buf)->tx;
959 
960 		tx_data(buf)->tx = NULL;
961 
962 		/* destroy the buffer */
963 		net_buf_unref(buf);
964 
965 		/* destroy the tx context (and any associated meta-data) */
966 		if (tx) {
967 			conn_tx_destroy(conn, tx);
968 		}
969 	}
970 }
971 
process_unack_tx(struct bt_conn * conn)972 static void process_unack_tx(struct bt_conn *conn)
973 {
974 	/* Return any unacknowledged packets */
975 	while (1) {
976 		struct bt_conn_tx *tx;
977 		sys_snode_t *node;
978 		unsigned int key;
979 
980 		key = irq_lock();
981 
982 		if (conn->pending_no_cb) {
983 			conn->pending_no_cb--;
984 			irq_unlock(key);
985 			k_sem_give(bt_conn_get_pkts(conn));
986 			continue;
987 		}
988 
989 		node = sys_slist_get(&conn->tx_pending);
990 		irq_unlock(key);
991 
992 		if (!node) {
993 			break;
994 		}
995 
996 		tx = CONTAINER_OF(node, struct bt_conn_tx, node);
997 
998 		key = irq_lock();
999 		conn->pending_no_cb = tx->pending_no_cb;
1000 		tx->pending_no_cb = 0U;
1001 		irq_unlock(key);
1002 
1003 		conn_tx_destroy(conn, tx);
1004 
1005 		k_sem_give(bt_conn_get_pkts(conn));
1006 	}
1007 }
1008 
conn_lookup_handle(struct bt_conn * conns,size_t size,uint16_t handle)1009 struct bt_conn *conn_lookup_handle(struct bt_conn *conns, size_t size,
1010 				   uint16_t handle)
1011 {
1012 	int i;
1013 
1014 	for (i = 0; i < size; i++) {
1015 		struct bt_conn *conn = bt_conn_ref(&conns[i]);
1016 
1017 		if (!conn) {
1018 			continue;
1019 		}
1020 
1021 		/* We only care about connections with a valid handle */
1022 		if (!bt_conn_is_handle_valid(conn)) {
1023 			bt_conn_unref(conn);
1024 			continue;
1025 		}
1026 
1027 		if (conn->handle != handle) {
1028 			bt_conn_unref(conn);
1029 			continue;
1030 		}
1031 
1032 		return conn;
1033 	}
1034 
1035 	return NULL;
1036 }
1037 
bt_conn_set_state(struct bt_conn * conn,bt_conn_state_t state)1038 void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state)
1039 {
1040 	bt_conn_state_t old_state;
1041 
1042 	LOG_DBG("%s -> %s", state2str(conn->state), state2str(state));
1043 
1044 	if (conn->state == state) {
1045 		LOG_WRN("no transition %s", state2str(state));
1046 		return;
1047 	}
1048 
1049 	old_state = conn->state;
1050 	conn->state = state;
1051 
1052 	/* Actions needed for exiting the old state */
1053 	switch (old_state) {
1054 	case BT_CONN_DISCONNECTED:
1055 		/* Take a reference for the first state transition after
1056 		 * bt_conn_add_le() and keep it until reaching DISCONNECTED
1057 		 * again.
1058 		 */
1059 		if (conn->type != BT_CONN_TYPE_ISO) {
1060 			bt_conn_ref(conn);
1061 		}
1062 		break;
1063 	case BT_CONN_CONNECTING:
1064 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1065 		    conn->type == BT_CONN_TYPE_LE) {
1066 			k_work_cancel_delayable(&conn->deferred_work);
1067 		}
1068 		break;
1069 	default:
1070 		break;
1071 	}
1072 
1073 	/* Actions needed for entering the new state */
1074 	switch (conn->state) {
1075 	case BT_CONN_CONNECTED:
1076 		if (conn->type == BT_CONN_TYPE_SCO) {
1077 			/* TODO: Notify sco connected */
1078 			break;
1079 		}
1080 		k_fifo_init(&conn->tx_queue);
1081 		k_poll_signal_raise(&conn_change, 0);
1082 
1083 		if (IS_ENABLED(CONFIG_BT_ISO) &&
1084 		    conn->type == BT_CONN_TYPE_ISO) {
1085 			bt_iso_connected(conn);
1086 			break;
1087 		}
1088 
1089 #if defined(CONFIG_BT_CONN)
1090 		sys_slist_init(&conn->channels);
1091 
1092 		if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
1093 		    conn->role == BT_CONN_ROLE_PERIPHERAL) {
1094 
1095 #if defined(CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS)
1096 			if (conn->type == BT_CONN_TYPE_LE) {
1097 				conn->le.conn_param_retry_countdown =
1098 					CONFIG_BT_CONN_PARAM_RETRY_COUNT;
1099 			}
1100 #endif /* CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS */
1101 
1102 			k_work_schedule(&conn->deferred_work,
1103 					CONN_UPDATE_TIMEOUT);
1104 		}
1105 #endif /* CONFIG_BT_CONN */
1106 
1107 		break;
1108 	case BT_CONN_DISCONNECTED:
1109 #if defined(CONFIG_BT_CONN)
1110 		if (conn->type == BT_CONN_TYPE_SCO) {
1111 			/* TODO: Notify sco disconnected */
1112 			bt_conn_unref(conn);
1113 			break;
1114 		}
1115 
1116 		/* Notify disconnection and queue a dummy buffer to wake
1117 		 * up and stop the tx thread for states where it was
1118 		 * running.
1119 		 */
1120 		switch (old_state) {
1121 		case BT_CONN_DISCONNECT_COMPLETE:
1122 			tx_notify(conn);
1123 
1124 			/* Cancel Connection Update if it is pending */
1125 			if ((conn->type == BT_CONN_TYPE_LE) &&
1126 			    (k_work_delayable_busy_get(&conn->deferred_work) &
1127 			     (K_WORK_QUEUED | K_WORK_DELAYED))) {
1128 				k_work_cancel_delayable(&conn->deferred_work);
1129 			}
1130 
1131 			atomic_set_bit(conn->flags, BT_CONN_CLEANUP);
1132 			k_poll_signal_raise(&conn_change, 0);
1133 			/* The last ref will be dropped during cleanup */
1134 			break;
1135 		case BT_CONN_CONNECTING:
1136 			/* LE Create Connection command failed. This might be
1137 			 * directly from the API, don't notify application in
1138 			 * this case.
1139 			 */
1140 			if (conn->err) {
1141 				notify_connected(conn);
1142 			}
1143 
1144 			bt_conn_unref(conn);
1145 			break;
1146 		case BT_CONN_CONNECTING_SCAN:
1147 			/* this indicate LE Create Connection with peer address
1148 			 * has been stopped. This could either be triggered by
1149 			 * the application through bt_conn_disconnect or by
1150 			 * timeout set by bt_conn_le_create_param.timeout.
1151 			 */
1152 			if (conn->err) {
1153 				notify_connected(conn);
1154 			}
1155 
1156 			bt_conn_unref(conn);
1157 			break;
1158 		case BT_CONN_CONNECTING_DIR_ADV:
1159 			/* this indicate Directed advertising stopped */
1160 			if (conn->err) {
1161 				notify_connected(conn);
1162 			}
1163 
1164 			bt_conn_unref(conn);
1165 			break;
1166 		case BT_CONN_CONNECTING_AUTO:
1167 			/* this indicates LE Create Connection with filter
1168 			 * policy has been stopped. This can only be triggered
1169 			 * by the application, so don't notify.
1170 			 */
1171 			bt_conn_unref(conn);
1172 			break;
1173 		case BT_CONN_CONNECTING_ADV:
1174 			/* This can only happen when application stops the
1175 			 * advertiser, conn->err is never set in this case.
1176 			 */
1177 			bt_conn_unref(conn);
1178 			break;
1179 		case BT_CONN_CONNECTED:
1180 		case BT_CONN_DISCONNECTING:
1181 		case BT_CONN_DISCONNECTED:
1182 			/* Cannot happen. */
1183 			LOG_WRN("Invalid (%u) old state", state);
1184 			break;
1185 		}
1186 		break;
1187 	case BT_CONN_CONNECTING_AUTO:
1188 		break;
1189 	case BT_CONN_CONNECTING_ADV:
1190 		break;
1191 	case BT_CONN_CONNECTING_SCAN:
1192 		break;
1193 	case BT_CONN_CONNECTING_DIR_ADV:
1194 		break;
1195 	case BT_CONN_CONNECTING:
1196 		if (conn->type == BT_CONN_TYPE_SCO) {
1197 			break;
1198 		}
1199 		/*
1200 		 * Timer is needed only for LE. For other link types controller
1201 		 * will handle connection timeout.
1202 		 */
1203 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1204 		    conn->type == BT_CONN_TYPE_LE &&
1205 		    bt_dev.create_param.timeout != 0) {
1206 			k_work_schedule(&conn->deferred_work,
1207 					K_MSEC(10 * bt_dev.create_param.timeout));
1208 		}
1209 
1210 		break;
1211 	case BT_CONN_DISCONNECTING:
1212 		break;
1213 #endif /* CONFIG_BT_CONN */
1214 	case BT_CONN_DISCONNECT_COMPLETE:
1215 		process_unack_tx(conn);
1216 		break;
1217 	default:
1218 		LOG_WRN("no valid (%u) state was set", state);
1219 
1220 		break;
1221 	}
1222 }
1223 
bt_conn_lookup_handle(uint16_t handle,enum bt_conn_type type)1224 struct bt_conn *bt_conn_lookup_handle(uint16_t handle, enum bt_conn_type type)
1225 {
1226 	struct bt_conn *conn;
1227 
1228 #if defined(CONFIG_BT_CONN)
1229 	conn = conn_lookup_handle(acl_conns, ARRAY_SIZE(acl_conns), handle);
1230 	if (conn) {
1231 		goto found;
1232 	}
1233 #endif /* CONFIG_BT_CONN */
1234 
1235 #if defined(CONFIG_BT_ISO)
1236 	conn = conn_lookup_handle(iso_conns, ARRAY_SIZE(iso_conns), handle);
1237 	if (conn) {
1238 		goto found;
1239 	}
1240 #endif
1241 
1242 #if defined(CONFIG_BT_BREDR)
1243 	conn = conn_lookup_handle(sco_conns, ARRAY_SIZE(sco_conns), handle);
1244 	if (conn) {
1245 		goto found;
1246 	}
1247 #endif
1248 
1249 found:
1250 	if (conn) {
1251 		if (type & conn->type) {
1252 			return conn;
1253 		}
1254 		LOG_WRN("incompatible handle %u", handle);
1255 		bt_conn_unref(conn);
1256 	}
1257 	return NULL;
1258 }
1259 
bt_conn_foreach(enum bt_conn_type type,void (* func)(struct bt_conn * conn,void * data),void * data)1260 void bt_conn_foreach(enum bt_conn_type type,
1261 		     void (*func)(struct bt_conn *conn, void *data),
1262 		     void *data)
1263 {
1264 	int i;
1265 
1266 #if defined(CONFIG_BT_CONN)
1267 	for (i = 0; i < ARRAY_SIZE(acl_conns); i++) {
1268 		struct bt_conn *conn = bt_conn_ref(&acl_conns[i]);
1269 
1270 		if (!conn) {
1271 			continue;
1272 		}
1273 
1274 		if (!(conn->type & type)) {
1275 			bt_conn_unref(conn);
1276 			continue;
1277 		}
1278 
1279 		func(conn, data);
1280 		bt_conn_unref(conn);
1281 	}
1282 #if defined(CONFIG_BT_BREDR)
1283 	if (type & BT_CONN_TYPE_SCO) {
1284 		for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
1285 			struct bt_conn *conn = bt_conn_ref(&sco_conns[i]);
1286 
1287 			if (!conn) {
1288 				continue;
1289 			}
1290 
1291 			func(conn, data);
1292 			bt_conn_unref(conn);
1293 		}
1294 	}
1295 #endif /* defined(CONFIG_BT_BREDR) */
1296 #endif /* CONFIG_BT_CONN */
1297 
1298 #if defined(CONFIG_BT_ISO)
1299 	if (type & BT_CONN_TYPE_ISO) {
1300 		for (i = 0; i < ARRAY_SIZE(iso_conns); i++) {
1301 			struct bt_conn *conn = bt_conn_ref(&iso_conns[i]);
1302 
1303 			if (!conn) {
1304 				continue;
1305 			}
1306 
1307 			func(conn, data);
1308 			bt_conn_unref(conn);
1309 		}
1310 	}
1311 #endif /* defined(CONFIG_BT_ISO) */
1312 }
1313 
bt_conn_ref(struct bt_conn * conn)1314 struct bt_conn *bt_conn_ref(struct bt_conn *conn)
1315 {
1316 	atomic_val_t old;
1317 
1318 	__ASSERT_NO_MSG(conn);
1319 
1320 	/* Reference counter must be checked to avoid incrementing ref from
1321 	 * zero, then we should return NULL instead.
1322 	 * Loop on clear-and-set in case someone has modified the reference
1323 	 * count since the read, and start over again when that happens.
1324 	 */
1325 	do {
1326 		old = atomic_get(&conn->ref);
1327 
1328 		if (!old) {
1329 			return NULL;
1330 		}
1331 	} while (!atomic_cas(&conn->ref, old, old + 1));
1332 
1333 	LOG_DBG("handle %u ref %ld -> %ld", conn->handle, old, old + 1);
1334 
1335 	return conn;
1336 }
1337 
bt_conn_unref(struct bt_conn * conn)1338 void bt_conn_unref(struct bt_conn *conn)
1339 {
1340 	atomic_val_t old;
1341 	bool deallocated;
1342 	enum bt_conn_type conn_type;
1343 	uint8_t conn_role;
1344 	uint16_t conn_handle;
1345 
1346 	__ASSERT(conn, "Invalid connection reference");
1347 
1348 	/* Storing parameters of interest so we don't access the object
1349 	 * after decrementing its ref-count
1350 	 */
1351 	conn_type = conn->type;
1352 	conn_role = conn->role;
1353 	conn_handle = conn->handle;
1354 
1355 	old = atomic_dec(&conn->ref);
1356 	/* Prevent from accessing connection object */
1357 	conn = NULL;
1358 	deallocated = (atomic_get(&old) == 1);
1359 
1360 	LOG_DBG("handle %u ref %ld -> %ld", conn_handle, old, (old - 1));
1361 
1362 	__ASSERT(old > 0, "Conn reference counter is 0");
1363 
1364 	/* Slot has been freed and can be taken. No guarantees are made on requests
1365 	 * to claim connection object as only the first claim will be served.
1366 	 */
1367 	if (deallocated) {
1368 		notify_recycled_conn_slot();
1369 	}
1370 
1371 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn_type == BT_CONN_TYPE_LE &&
1372 	    conn_role == BT_CONN_ROLE_PERIPHERAL && deallocated) {
1373 		bt_le_adv_resume();
1374 	}
1375 }
1376 
bt_conn_index(const struct bt_conn * conn)1377 uint8_t bt_conn_index(const struct bt_conn *conn)
1378 {
1379 	ptrdiff_t index = 0;
1380 
1381 	switch (conn->type) {
1382 #if defined(CONFIG_BT_ISO)
1383 	case BT_CONN_TYPE_ISO:
1384 		index = conn - iso_conns;
1385 		__ASSERT(index >= 0 && index < ARRAY_SIZE(iso_conns),
1386 			"Invalid bt_conn pointer");
1387 		break;
1388 #endif
1389 #if defined(CONFIG_BT_BREDR)
1390 	case BT_CONN_TYPE_SCO:
1391 		index = conn - sco_conns;
1392 		__ASSERT(index >= 0 && index < ARRAY_SIZE(sco_conns),
1393 			"Invalid bt_conn pointer");
1394 		break;
1395 #endif
1396 	default:
1397 #if defined(CONFIG_BT_CONN)
1398 		index = conn - acl_conns;
1399 		__ASSERT(index >= 0 && index < ARRAY_SIZE(acl_conns),
1400 			 "Invalid bt_conn pointer");
1401 #else
1402 		__ASSERT(false, "Invalid connection type %u", conn->type);
1403 #endif /* CONFIG_BT_CONN */
1404 		break;
1405 	}
1406 
1407 	return (uint8_t)index;
1408 }
1409 
1410 
1411 #if defined(CONFIG_NET_BUF_LOG)
bt_conn_create_pdu_timeout_debug(struct net_buf_pool * pool,size_t reserve,k_timeout_t timeout,const char * func,int line)1412 struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool,
1413 						 size_t reserve,
1414 						 k_timeout_t timeout,
1415 						 const char *func, int line)
1416 #else
1417 struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
1418 					   size_t reserve, k_timeout_t timeout)
1419 #endif
1420 {
1421 	struct net_buf *buf;
1422 
1423 	/*
1424 	 * PDU must not be allocated from ISR as we block with 'K_FOREVER'
1425 	 * during the allocation
1426 	 */
1427 	__ASSERT_NO_MSG(!k_is_in_isr());
1428 
1429 	if (!pool) {
1430 #if defined(CONFIG_BT_CONN)
1431 		pool = &acl_tx_pool;
1432 #else
1433 		return NULL;
1434 #endif /* CONFIG_BT_CONN */
1435 	}
1436 
1437 	if (IS_ENABLED(CONFIG_BT_CONN_LOG_LEVEL_DBG)) {
1438 #if defined(CONFIG_NET_BUF_LOG)
1439 		buf = net_buf_alloc_fixed_debug(pool, K_NO_WAIT, func, line);
1440 #else
1441 		buf = net_buf_alloc(pool, K_NO_WAIT);
1442 #endif
1443 		if (!buf) {
1444 			LOG_WRN("Unable to allocate buffer with K_NO_WAIT");
1445 #if defined(CONFIG_NET_BUF_LOG)
1446 			buf = net_buf_alloc_fixed_debug(pool, timeout, func,
1447 							line);
1448 #else
1449 			buf = net_buf_alloc(pool, timeout);
1450 #endif
1451 		}
1452 	} else {
1453 #if defined(CONFIG_NET_BUF_LOG)
1454 		buf = net_buf_alloc_fixed_debug(pool, timeout, func,
1455 							line);
1456 #else
1457 		buf = net_buf_alloc(pool, timeout);
1458 #endif
1459 	}
1460 
1461 	if (!buf) {
1462 		LOG_WRN("Unable to allocate buffer within timeout");
1463 		return NULL;
1464 	}
1465 
1466 	reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE;
1467 	net_buf_reserve(buf, reserve);
1468 
1469 	return buf;
1470 }
1471 
1472 #if defined(CONFIG_BT_CONN_TX)
tx_complete_work(struct k_work * work)1473 static void tx_complete_work(struct k_work *work)
1474 {
1475 	struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn,
1476 					    tx_complete_work);
1477 
1478 	LOG_DBG("conn %p", conn);
1479 
1480 	tx_notify(conn);
1481 }
1482 #endif /* CONFIG_BT_CONN_TX */
1483 
notify_recycled_conn_slot(void)1484 static void notify_recycled_conn_slot(void)
1485 {
1486 #if defined(CONFIG_BT_CONN)
1487 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1488 		if (cb->recycled) {
1489 			cb->recycled();
1490 		}
1491 	}
1492 
1493 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1494 		if (cb->recycled) {
1495 			cb->recycled();
1496 		}
1497 	}
1498 #endif
1499 }
1500 
1501 /* Group Connected BT_CONN only in this */
1502 #if defined(CONFIG_BT_CONN)
1503 
bt_conn_connected(struct bt_conn * conn)1504 void bt_conn_connected(struct bt_conn *conn)
1505 {
1506 	bt_l2cap_connected(conn);
1507 	notify_connected(conn);
1508 }
1509 
conn_disconnect(struct bt_conn * conn,uint8_t reason)1510 static int conn_disconnect(struct bt_conn *conn, uint8_t reason)
1511 {
1512 	int err;
1513 
1514 	err = bt_hci_disconnect(conn->handle, reason);
1515 	if (err) {
1516 		return err;
1517 	}
1518 
1519 	if (conn->state == BT_CONN_CONNECTED) {
1520 		bt_conn_set_state(conn, BT_CONN_DISCONNECTING);
1521 	}
1522 
1523 	return 0;
1524 }
1525 
bt_conn_disconnect(struct bt_conn * conn,uint8_t reason)1526 int bt_conn_disconnect(struct bt_conn *conn, uint8_t reason)
1527 {
1528 	/* Disconnection is initiated by us, so auto connection shall
1529 	 * be disabled. Otherwise the passive scan would be enabled
1530 	 * and we could send LE Create Connection as soon as the remote
1531 	 * starts advertising.
1532 	 */
1533 #if !defined(CONFIG_BT_FILTER_ACCEPT_LIST)
1534 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1535 	    conn->type == BT_CONN_TYPE_LE) {
1536 		bt_le_set_auto_conn(&conn->le.dst, NULL);
1537 	}
1538 #endif /* !defined(CONFIG_BT_FILTER_ACCEPT_LIST) */
1539 
1540 	switch (conn->state) {
1541 	case BT_CONN_CONNECTING_SCAN:
1542 		conn->err = reason;
1543 		bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
1544 		if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
1545 			bt_le_scan_update(false);
1546 		}
1547 		return 0;
1548 	case BT_CONN_CONNECTING:
1549 		if (conn->type == BT_CONN_TYPE_LE) {
1550 			if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
1551 				k_work_cancel_delayable(&conn->deferred_work);
1552 				return bt_le_create_conn_cancel();
1553 			}
1554 		}
1555 #if defined(CONFIG_BT_ISO)
1556 		else if (conn->type == BT_CONN_TYPE_ISO) {
1557 			return conn_disconnect(conn, reason);
1558 		}
1559 #endif /* CONFIG_BT_ISO */
1560 #if defined(CONFIG_BT_BREDR)
1561 		else if (conn->type == BT_CONN_TYPE_BR) {
1562 			return bt_hci_connect_br_cancel(conn);
1563 		}
1564 #endif /* CONFIG_BT_BREDR */
1565 		else {
1566 			__ASSERT(false, "Invalid conn type %u", conn->type);
1567 		}
1568 
1569 		return 0;
1570 	case BT_CONN_CONNECTED:
1571 		return conn_disconnect(conn, reason);
1572 	case BT_CONN_DISCONNECTING:
1573 		return 0;
1574 	case BT_CONN_DISCONNECTED:
1575 	default:
1576 		return -ENOTCONN;
1577 	}
1578 }
1579 
notify_connected(struct bt_conn * conn)1580 static void notify_connected(struct bt_conn *conn)
1581 {
1582 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1583 		if (cb->connected) {
1584 			cb->connected(conn, conn->err);
1585 		}
1586 	}
1587 
1588 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1589 		if (cb->connected) {
1590 			cb->connected(conn, conn->err);
1591 		}
1592 	}
1593 }
1594 
notify_disconnected(struct bt_conn * conn)1595 static void notify_disconnected(struct bt_conn *conn)
1596 {
1597 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1598 		if (cb->disconnected) {
1599 			cb->disconnected(conn, conn->err);
1600 		}
1601 	}
1602 
1603 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1604 		if (cb->disconnected) {
1605 			cb->disconnected(conn, conn->err);
1606 		}
1607 	}
1608 }
1609 
1610 #if defined(CONFIG_BT_REMOTE_INFO)
notify_remote_info(struct bt_conn * conn)1611 void notify_remote_info(struct bt_conn *conn)
1612 {
1613 	struct bt_conn_remote_info remote_info;
1614 	int err;
1615 
1616 	err = bt_conn_get_remote_info(conn, &remote_info);
1617 	if (err) {
1618 		LOG_DBG("Notify remote info failed %d", err);
1619 		return;
1620 	}
1621 
1622 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1623 		if (cb->remote_info_available) {
1624 			cb->remote_info_available(conn, &remote_info);
1625 		}
1626 	}
1627 
1628 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1629 		if (cb->remote_info_available) {
1630 			cb->remote_info_available(conn, &remote_info);
1631 		}
1632 	}
1633 }
1634 #endif /* defined(CONFIG_BT_REMOTE_INFO) */
1635 
notify_le_param_updated(struct bt_conn * conn)1636 void notify_le_param_updated(struct bt_conn *conn)
1637 {
1638 	/* If new connection parameters meet requirement of pending
1639 	 * parameters don't send peripheral conn param request anymore on timeout
1640 	 */
1641 	if (atomic_test_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_SET) &&
1642 	    conn->le.interval >= conn->le.interval_min &&
1643 	    conn->le.interval <= conn->le.interval_max &&
1644 	    conn->le.latency == conn->le.pending_latency &&
1645 	    conn->le.timeout == conn->le.pending_timeout) {
1646 		atomic_clear_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_SET);
1647 	}
1648 
1649 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1650 		if (cb->le_param_updated) {
1651 			cb->le_param_updated(conn, conn->le.interval,
1652 					     conn->le.latency,
1653 					     conn->le.timeout);
1654 		}
1655 	}
1656 
1657 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1658 		if (cb->le_param_updated) {
1659 			cb->le_param_updated(conn, conn->le.interval,
1660 					     conn->le.latency,
1661 					     conn->le.timeout);
1662 		}
1663 	}
1664 }
1665 
1666 #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE)
notify_le_data_len_updated(struct bt_conn * conn)1667 void notify_le_data_len_updated(struct bt_conn *conn)
1668 {
1669 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1670 		if (cb->le_data_len_updated) {
1671 			cb->le_data_len_updated(conn, &conn->le.data_len);
1672 		}
1673 	}
1674 
1675 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1676 		if (cb->le_data_len_updated) {
1677 			cb->le_data_len_updated(conn, &conn->le.data_len);
1678 		}
1679 	}
1680 }
1681 #endif
1682 
1683 #if defined(CONFIG_BT_USER_PHY_UPDATE)
notify_le_phy_updated(struct bt_conn * conn)1684 void notify_le_phy_updated(struct bt_conn *conn)
1685 {
1686 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1687 		if (cb->le_phy_updated) {
1688 			cb->le_phy_updated(conn, &conn->le.phy);
1689 		}
1690 	}
1691 
1692 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1693 		if (cb->le_phy_updated) {
1694 			cb->le_phy_updated(conn, &conn->le.phy);
1695 		}
1696 	}
1697 }
1698 #endif
1699 
le_param_req(struct bt_conn * conn,struct bt_le_conn_param * param)1700 bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param)
1701 {
1702 	if (!bt_le_conn_params_valid(param)) {
1703 		return false;
1704 	}
1705 
1706 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
1707 		if (!cb->le_param_req) {
1708 			continue;
1709 		}
1710 
1711 		if (!cb->le_param_req(conn, param)) {
1712 			return false;
1713 		}
1714 
1715 		/* The callback may modify the parameters so we need to
1716 		 * double-check that it returned valid parameters.
1717 		 */
1718 		if (!bt_le_conn_params_valid(param)) {
1719 			return false;
1720 		}
1721 	}
1722 
1723 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
1724 		if (!cb->le_param_req) {
1725 			continue;
1726 		}
1727 
1728 		if (!cb->le_param_req(conn, param)) {
1729 			return false;
1730 		}
1731 
1732 		/* The callback may modify the parameters so we need to
1733 		 * double-check that it returned valid parameters.
1734 		 */
1735 		if (!bt_le_conn_params_valid(param)) {
1736 			return false;
1737 		}
1738 	}
1739 
1740 	/* Default to accepting if there's no app callback */
1741 	return true;
1742 }
1743 
send_conn_le_param_update(struct bt_conn * conn,const struct bt_le_conn_param * param)1744 static int send_conn_le_param_update(struct bt_conn *conn,
1745 				const struct bt_le_conn_param *param)
1746 {
1747 	LOG_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0],
1748 		param->interval_min, param->interval_max, param->latency, param->timeout);
1749 
1750 	/* Proceed only if connection parameters contains valid values*/
1751 	if (!bt_le_conn_params_valid(param)) {
1752 		return -EINVAL;
1753 	}
1754 
1755 	/* Use LE connection parameter request if both local and remote support
1756 	 * it; or if local role is central then use LE connection update.
1757 	 */
1758 	if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) &&
1759 	     BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) &&
1760 	     !atomic_test_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_L2CAP)) ||
1761 	     (conn->role == BT_HCI_ROLE_CENTRAL)) {
1762 		int rc;
1763 
1764 		rc = bt_conn_le_conn_update(conn, param);
1765 
1766 		/* store those in case of fallback to L2CAP */
1767 		if (rc == 0) {
1768 			conn->le.interval_min = param->interval_min;
1769 			conn->le.interval_max = param->interval_max;
1770 			conn->le.pending_latency = param->latency;
1771 			conn->le.pending_timeout = param->timeout;
1772 		}
1773 
1774 		return rc;
1775 	}
1776 
1777 	/* If remote central does not support LL Connection Parameters Request
1778 	 * Procedure
1779 	 */
1780 	return bt_l2cap_update_conn_param(conn, param);
1781 }
1782 
1783 #if defined(CONFIG_BT_ISO_UNICAST)
conn_lookup_iso(struct bt_conn * conn)1784 static struct bt_conn *conn_lookup_iso(struct bt_conn *conn)
1785 {
1786 	int i;
1787 
1788 	for (i = 0; i < ARRAY_SIZE(iso_conns); i++) {
1789 		struct bt_conn *iso = bt_conn_ref(&iso_conns[i]);
1790 
1791 		if (iso == NULL) {
1792 			continue;
1793 		}
1794 
1795 		if (iso->iso.acl == conn) {
1796 			return iso;
1797 		}
1798 
1799 		bt_conn_unref(iso);
1800 	}
1801 
1802 	return NULL;
1803 }
1804 #endif /* CONFIG_BT_ISO */
1805 
deferred_work(struct k_work * work)1806 static void deferred_work(struct k_work *work)
1807 {
1808 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1809 	struct bt_conn *conn = CONTAINER_OF(dwork, struct bt_conn, deferred_work);
1810 	const struct bt_le_conn_param *param;
1811 
1812 	LOG_DBG("conn %p", conn);
1813 
1814 	if (conn->state == BT_CONN_DISCONNECTED) {
1815 #if defined(CONFIG_BT_ISO_UNICAST)
1816 		struct bt_conn *iso;
1817 
1818 		if (conn->type == BT_CONN_TYPE_ISO) {
1819 			/* bt_iso_disconnected is responsible for unref'ing the
1820 			 * connection pointer, as it is conditional on whether
1821 			 * the connection is a central or peripheral.
1822 			 */
1823 			bt_iso_disconnected(conn);
1824 			return;
1825 		}
1826 
1827 		/* Mark all ISO channels associated
1828 		 * with ACL conn as not connected, and
1829 		 * remove ACL reference
1830 		 */
1831 		iso = conn_lookup_iso(conn);
1832 		while (iso != NULL) {
1833 			struct bt_iso_chan *chan = iso->iso.chan;
1834 
1835 			if (chan != NULL) {
1836 				bt_iso_chan_set_state(chan,
1837 						      BT_ISO_STATE_DISCONNECTING);
1838 			}
1839 
1840 			bt_iso_cleanup_acl(iso);
1841 
1842 			bt_conn_unref(iso);
1843 			iso = conn_lookup_iso(conn);
1844 		}
1845 #endif
1846 
1847 		bt_l2cap_disconnected(conn);
1848 		notify_disconnected(conn);
1849 
1850 		/* Release the reference we took for the very first
1851 		 * state transition.
1852 		 */
1853 		bt_conn_unref(conn);
1854 		return;
1855 	}
1856 
1857 	if (conn->type != BT_CONN_TYPE_LE) {
1858 		return;
1859 	}
1860 
1861 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1862 	    conn->role == BT_CONN_ROLE_CENTRAL) {
1863 		/* we don't call bt_conn_disconnect as it would also clear
1864 		 * auto connect flag if it was set, instead just cancel
1865 		 * connection directly
1866 		 */
1867 		bt_le_create_conn_cancel();
1868 		return;
1869 	}
1870 
1871 	/* if application set own params use those, otherwise use defaults. */
1872 	if (atomic_test_and_clear_bit(conn->flags,
1873 				      BT_CONN_PERIPHERAL_PARAM_SET)) {
1874 		int err;
1875 
1876 		param = BT_LE_CONN_PARAM(conn->le.interval_min,
1877 					 conn->le.interval_max,
1878 					 conn->le.pending_latency,
1879 					 conn->le.pending_timeout);
1880 
1881 		err = send_conn_le_param_update(conn, param);
1882 		if (!err) {
1883 			atomic_clear_bit(conn->flags,
1884 					 BT_CONN_PERIPHERAL_PARAM_AUTO_UPDATE);
1885 		} else {
1886 			LOG_WRN("Send LE param update failed (err %d)", err);
1887 		}
1888 	} else if (IS_ENABLED(CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS)) {
1889 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
1890 		int err;
1891 
1892 		param = BT_LE_CONN_PARAM(
1893 				CONFIG_BT_PERIPHERAL_PREF_MIN_INT,
1894 				CONFIG_BT_PERIPHERAL_PREF_MAX_INT,
1895 				CONFIG_BT_PERIPHERAL_PREF_LATENCY,
1896 				CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
1897 
1898 		err = send_conn_le_param_update(conn, param);
1899 		if (!err) {
1900 			atomic_set_bit(conn->flags,
1901 				       BT_CONN_PERIPHERAL_PARAM_AUTO_UPDATE);
1902 		} else {
1903 			LOG_WRN("Send auto LE param update failed (err %d)",
1904 				err);
1905 		}
1906 #endif
1907 	}
1908 
1909 	atomic_set_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_UPDATE);
1910 }
1911 
acl_conn_new(void)1912 static struct bt_conn *acl_conn_new(void)
1913 {
1914 	return bt_conn_new(acl_conns, ARRAY_SIZE(acl_conns));
1915 }
1916 
1917 #if defined(CONFIG_BT_BREDR)
bt_sco_cleanup(struct bt_conn * sco_conn)1918 void bt_sco_cleanup(struct bt_conn *sco_conn)
1919 {
1920 	bt_conn_unref(sco_conn->sco.acl);
1921 	sco_conn->sco.acl = NULL;
1922 	bt_conn_unref(sco_conn);
1923 }
1924 
sco_conn_new(void)1925 static struct bt_conn *sco_conn_new(void)
1926 {
1927 	return bt_conn_new(sco_conns, ARRAY_SIZE(sco_conns));
1928 }
1929 
bt_conn_create_br(const bt_addr_t * peer,const struct bt_br_conn_param * param)1930 struct bt_conn *bt_conn_create_br(const bt_addr_t *peer,
1931 				  const struct bt_br_conn_param *param)
1932 {
1933 	struct bt_hci_cp_connect *cp;
1934 	struct bt_conn *conn;
1935 	struct net_buf *buf;
1936 
1937 	conn = bt_conn_lookup_addr_br(peer);
1938 	if (conn) {
1939 		switch (conn->state) {
1940 		case BT_CONN_CONNECTING:
1941 		case BT_CONN_CONNECTED:
1942 			return conn;
1943 		default:
1944 			bt_conn_unref(conn);
1945 			return NULL;
1946 		}
1947 	}
1948 
1949 	conn = bt_conn_add_br(peer);
1950 	if (!conn) {
1951 		return NULL;
1952 	}
1953 
1954 	buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
1955 	if (!buf) {
1956 		bt_conn_unref(conn);
1957 		return NULL;
1958 	}
1959 
1960 	cp = net_buf_add(buf, sizeof(*cp));
1961 
1962 	(void)memset(cp, 0, sizeof(*cp));
1963 
1964 	memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr));
1965 	cp->packet_type = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */
1966 	cp->pscan_rep_mode = 0x02; /* R2 */
1967 	cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00;
1968 	cp->clock_offset = 0x0000; /* TODO used cached clock offset */
1969 
1970 	if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
1971 		bt_conn_unref(conn);
1972 		return NULL;
1973 	}
1974 
1975 	bt_conn_set_state(conn, BT_CONN_CONNECTING);
1976 	conn->role = BT_CONN_ROLE_CENTRAL;
1977 
1978 	return conn;
1979 }
1980 
bt_conn_create_sco(const bt_addr_t * peer)1981 struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer)
1982 {
1983 	struct bt_hci_cp_setup_sync_conn *cp;
1984 	struct bt_conn *sco_conn;
1985 	struct net_buf *buf;
1986 	int link_type;
1987 
1988 	sco_conn = bt_conn_lookup_addr_sco(peer);
1989 	if (sco_conn) {
1990 		switch (sco_conn->state) {
1991 		case BT_CONN_CONNECTING:
1992 		case BT_CONN_CONNECTED:
1993 			return sco_conn;
1994 		default:
1995 			bt_conn_unref(sco_conn);
1996 			return NULL;
1997 		}
1998 	}
1999 
2000 	if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
2001 		link_type = BT_HCI_ESCO;
2002 	} else {
2003 		link_type = BT_HCI_SCO;
2004 	}
2005 
2006 	sco_conn = bt_conn_add_sco(peer, link_type);
2007 	if (!sco_conn) {
2008 		return NULL;
2009 	}
2010 
2011 	buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
2012 	if (!buf) {
2013 		bt_sco_cleanup(sco_conn);
2014 		return NULL;
2015 	}
2016 
2017 	cp = net_buf_add(buf, sizeof(*cp));
2018 
2019 	(void)memset(cp, 0, sizeof(*cp));
2020 
2021 	LOG_ERR("handle : %x", sco_conn->sco.acl->handle);
2022 
2023 	cp->handle = sco_conn->sco.acl->handle;
2024 	cp->pkt_type = sco_conn->sco.pkt_type;
2025 	cp->tx_bandwidth = 0x00001f40;
2026 	cp->rx_bandwidth = 0x00001f40;
2027 	cp->max_latency = 0x0007;
2028 	cp->retrans_effort = 0x01;
2029 	cp->content_format = BT_VOICE_CVSD_16BIT;
2030 
2031 	if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf,
2032 				 NULL) < 0) {
2033 		bt_sco_cleanup(sco_conn);
2034 		return NULL;
2035 	}
2036 
2037 	bt_conn_set_state(sco_conn, BT_CONN_CONNECTING);
2038 
2039 	return sco_conn;
2040 }
2041 
bt_conn_lookup_addr_sco(const bt_addr_t * peer)2042 struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer)
2043 {
2044 	int i;
2045 
2046 	for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
2047 		struct bt_conn *conn = bt_conn_ref(&sco_conns[i]);
2048 
2049 		if (!conn) {
2050 			continue;
2051 		}
2052 
2053 		if (conn->type != BT_CONN_TYPE_SCO) {
2054 			bt_conn_unref(conn);
2055 			continue;
2056 		}
2057 
2058 		if (!bt_addr_eq(peer, &conn->sco.acl->br.dst)) {
2059 			bt_conn_unref(conn);
2060 			continue;
2061 		}
2062 
2063 		return conn;
2064 	}
2065 
2066 	return NULL;
2067 }
2068 
bt_conn_lookup_addr_br(const bt_addr_t * peer)2069 struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer)
2070 {
2071 	int i;
2072 
2073 	for (i = 0; i < ARRAY_SIZE(acl_conns); i++) {
2074 		struct bt_conn *conn = bt_conn_ref(&acl_conns[i]);
2075 
2076 		if (!conn) {
2077 			continue;
2078 		}
2079 
2080 		if (conn->type != BT_CONN_TYPE_BR) {
2081 			bt_conn_unref(conn);
2082 			continue;
2083 		}
2084 
2085 		if (!bt_addr_eq(peer, &conn->br.dst)) {
2086 			bt_conn_unref(conn);
2087 			continue;
2088 		}
2089 
2090 		return conn;
2091 	}
2092 
2093 	return NULL;
2094 }
2095 
bt_conn_add_sco(const bt_addr_t * peer,int link_type)2096 struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type)
2097 {
2098 	struct bt_conn *sco_conn = sco_conn_new();
2099 
2100 	if (!sco_conn) {
2101 		return NULL;
2102 	}
2103 
2104 	sco_conn->sco.acl = bt_conn_lookup_addr_br(peer);
2105 	if (!sco_conn->sco.acl) {
2106 		bt_conn_unref(sco_conn);
2107 		return NULL;
2108 	}
2109 
2110 	sco_conn->type = BT_CONN_TYPE_SCO;
2111 
2112 	if (link_type == BT_HCI_SCO) {
2113 		if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
2114 			sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
2115 						  ESCO_PKT_MASK);
2116 		} else {
2117 			sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
2118 						  SCO_PKT_MASK);
2119 		}
2120 	} else if (link_type == BT_HCI_ESCO) {
2121 		sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
2122 					  ~EDR_ESCO_PKT_MASK);
2123 	}
2124 
2125 	return sco_conn;
2126 }
2127 
bt_conn_add_br(const bt_addr_t * peer)2128 struct bt_conn *bt_conn_add_br(const bt_addr_t *peer)
2129 {
2130 	struct bt_conn *conn = acl_conn_new();
2131 
2132 	if (!conn) {
2133 		return NULL;
2134 	}
2135 
2136 	bt_addr_copy(&conn->br.dst, peer);
2137 	conn->type = BT_CONN_TYPE_BR;
2138 
2139 	return conn;
2140 }
2141 
bt_hci_connect_br_cancel(struct bt_conn * conn)2142 static int bt_hci_connect_br_cancel(struct bt_conn *conn)
2143 {
2144 	struct bt_hci_cp_connect_cancel *cp;
2145 	struct bt_hci_rp_connect_cancel *rp;
2146 	struct net_buf *buf, *rsp;
2147 	int err;
2148 
2149 	buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp));
2150 	if (!buf) {
2151 		return -ENOBUFS;
2152 	}
2153 
2154 	cp = net_buf_add(buf, sizeof(*cp));
2155 	memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr));
2156 
2157 	err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp);
2158 	if (err) {
2159 		return err;
2160 	}
2161 
2162 	rp = (void *)rsp->data;
2163 
2164 	err = rp->status ? -EIO : 0;
2165 
2166 	net_buf_unref(rsp);
2167 
2168 	return err;
2169 }
2170 
2171 #endif /* CONFIG_BT_BREDR */
2172 
2173 #if defined(CONFIG_BT_SMP)
bt_conn_ltk_present(const struct bt_conn * conn)2174 bool bt_conn_ltk_present(const struct bt_conn *conn)
2175 {
2176 	const struct bt_keys *keys = conn->le.keys;
2177 
2178 	if (!keys) {
2179 		keys = bt_keys_find_addr(conn->id, &conn->le.dst);
2180 	}
2181 
2182 	if (keys) {
2183 		if (conn->role == BT_HCI_ROLE_CENTRAL) {
2184 			return keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_PERIPH_LTK);
2185 		} else {
2186 			return keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK);
2187 		}
2188 	}
2189 
2190 	return false;
2191 }
2192 
bt_conn_identity_resolved(struct bt_conn * conn)2193 void bt_conn_identity_resolved(struct bt_conn *conn)
2194 {
2195 	const bt_addr_le_t *rpa;
2196 
2197 	if (conn->role == BT_HCI_ROLE_CENTRAL) {
2198 		rpa = &conn->le.resp_addr;
2199 	} else {
2200 		rpa = &conn->le.init_addr;
2201 	}
2202 
2203 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
2204 		if (cb->identity_resolved) {
2205 			cb->identity_resolved(conn, rpa, &conn->le.dst);
2206 		}
2207 	}
2208 
2209 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
2210 		if (cb->identity_resolved) {
2211 			cb->identity_resolved(conn, rpa, &conn->le.dst);
2212 		}
2213 	}
2214 }
2215 
bt_conn_le_start_encryption(struct bt_conn * conn,uint8_t rand[8],uint8_t ediv[2],const uint8_t * ltk,size_t len)2216 int bt_conn_le_start_encryption(struct bt_conn *conn, uint8_t rand[8],
2217 				uint8_t ediv[2], const uint8_t *ltk, size_t len)
2218 {
2219 	struct bt_hci_cp_le_start_encryption *cp;
2220 	struct net_buf *buf;
2221 
2222 	if (len > sizeof(cp->ltk)) {
2223 		return -EINVAL;
2224 	}
2225 
2226 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp));
2227 	if (!buf) {
2228 		return -ENOBUFS;
2229 	}
2230 
2231 	cp = net_buf_add(buf, sizeof(*cp));
2232 	cp->handle = sys_cpu_to_le16(conn->handle);
2233 	memcpy(&cp->rand, rand, sizeof(cp->rand));
2234 	memcpy(&cp->ediv, ediv, sizeof(cp->ediv));
2235 
2236 	memcpy(cp->ltk, ltk, len);
2237 	if (len < sizeof(cp->ltk)) {
2238 		(void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len);
2239 	}
2240 
2241 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL);
2242 }
2243 #endif /* CONFIG_BT_SMP */
2244 
2245 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
bt_conn_enc_key_size(const struct bt_conn * conn)2246 uint8_t bt_conn_enc_key_size(const struct bt_conn *conn)
2247 {
2248 	if (!conn->encrypt) {
2249 		return 0;
2250 	}
2251 
2252 	if (IS_ENABLED(CONFIG_BT_BREDR) &&
2253 	    conn->type == BT_CONN_TYPE_BR) {
2254 		struct bt_hci_cp_read_encryption_key_size *cp;
2255 		struct bt_hci_rp_read_encryption_key_size *rp;
2256 		struct net_buf *buf;
2257 		struct net_buf *rsp;
2258 		uint8_t key_size;
2259 
2260 		buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
2261 					sizeof(*cp));
2262 		if (!buf) {
2263 			return 0;
2264 		}
2265 
2266 		cp = net_buf_add(buf, sizeof(*cp));
2267 		cp->handle = sys_cpu_to_le16(conn->handle);
2268 
2269 		if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
2270 					buf, &rsp)) {
2271 			return 0;
2272 		}
2273 
2274 		rp = (void *)rsp->data;
2275 
2276 		key_size = rp->status ? 0 : rp->key_size;
2277 
2278 		net_buf_unref(rsp);
2279 
2280 		return key_size;
2281 	}
2282 
2283 	if (IS_ENABLED(CONFIG_BT_SMP)) {
2284 		return conn->le.keys ? conn->le.keys->enc_size : 0;
2285 	}
2286 
2287 	return 0;
2288 }
2289 
reset_pairing(struct bt_conn * conn)2290 static void reset_pairing(struct bt_conn *conn)
2291 {
2292 #if defined(CONFIG_BT_BREDR)
2293 	if (conn->type == BT_CONN_TYPE_BR) {
2294 		atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING);
2295 		atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
2296 		atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
2297 	}
2298 #endif /* CONFIG_BT_BREDR */
2299 
2300 	/* Reset required security level to current operational */
2301 	conn->required_sec_level = conn->sec_level;
2302 }
2303 
bt_conn_security_changed(struct bt_conn * conn,uint8_t hci_err,enum bt_security_err err)2304 void bt_conn_security_changed(struct bt_conn *conn, uint8_t hci_err,
2305 			      enum bt_security_err err)
2306 {
2307 	reset_pairing(conn);
2308 	bt_l2cap_security_changed(conn, hci_err);
2309 	if (IS_ENABLED(CONFIG_BT_ISO_CENTRAL)) {
2310 		bt_iso_security_changed(conn, hci_err);
2311 	}
2312 
2313 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
2314 		if (cb->security_changed) {
2315 			cb->security_changed(conn, conn->sec_level, err);
2316 		}
2317 	}
2318 
2319 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb) {
2320 		if (cb->security_changed) {
2321 			cb->security_changed(conn, conn->sec_level, err);
2322 		}
2323 	}
2324 
2325 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
2326 	if (!err && conn->sec_level >= BT_SECURITY_L2) {
2327 		if (conn->type == BT_CONN_TYPE_LE) {
2328 			bt_keys_update_usage(conn->id, bt_conn_get_dst(conn));
2329 		}
2330 
2331 #if defined(CONFIG_BT_BREDR)
2332 		if (conn->type == BT_CONN_TYPE_BR) {
2333 			bt_keys_link_key_update_usage(&conn->br.dst);
2334 		}
2335 #endif /* CONFIG_BT_BREDR */
2336 
2337 	}
2338 #endif
2339 }
2340 
start_security(struct bt_conn * conn)2341 static int start_security(struct bt_conn *conn)
2342 {
2343 	if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
2344 		return bt_ssp_start_security(conn);
2345 	}
2346 
2347 	if (IS_ENABLED(CONFIG_BT_SMP)) {
2348 		return bt_smp_start_security(conn);
2349 	}
2350 
2351 	return -EINVAL;
2352 }
2353 
bt_conn_set_security(struct bt_conn * conn,bt_security_t sec)2354 int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec)
2355 {
2356 	bool force_pair;
2357 	int err;
2358 
2359 	if (conn->state != BT_CONN_CONNECTED) {
2360 		return -ENOTCONN;
2361 	}
2362 
2363 	force_pair = sec & BT_SECURITY_FORCE_PAIR;
2364 	sec &= ~BT_SECURITY_FORCE_PAIR;
2365 
2366 	if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY)) {
2367 		sec = BT_SECURITY_L4;
2368 	}
2369 
2370 	if (IS_ENABLED(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)) {
2371 		sec = BT_SECURITY_L3;
2372 	}
2373 
2374 	/* nothing to do */
2375 	if (!force_pair && (conn->sec_level >= sec || conn->required_sec_level >= sec)) {
2376 		return 0;
2377 	}
2378 
2379 	atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR, force_pair);
2380 	conn->required_sec_level = sec;
2381 
2382 	err = start_security(conn);
2383 
2384 	/* reset required security level in case of error */
2385 	if (err) {
2386 		conn->required_sec_level = conn->sec_level;
2387 	}
2388 
2389 	return err;
2390 }
2391 
bt_conn_get_security(const struct bt_conn * conn)2392 bt_security_t bt_conn_get_security(const struct bt_conn *conn)
2393 {
2394 	return conn->sec_level;
2395 }
2396 #else
bt_conn_get_security(const struct bt_conn * conn)2397 bt_security_t bt_conn_get_security(const struct bt_conn *conn)
2398 {
2399 	return BT_SECURITY_L1;
2400 }
2401 #endif /* CONFIG_BT_SMP */
2402 
bt_conn_cb_register(struct bt_conn_cb * cb)2403 void bt_conn_cb_register(struct bt_conn_cb *cb)
2404 {
2405 	cb->_next = callback_list;
2406 	callback_list = cb;
2407 }
2408 
bt_conn_cb_unregister(struct bt_conn_cb * cb)2409 int bt_conn_cb_unregister(struct bt_conn_cb *cb)
2410 {
2411 	struct bt_conn_cb *previous_callback;
2412 
2413 	CHECKIF(cb == NULL) {
2414 		return -EINVAL;
2415 	}
2416 
2417 	if (callback_list == cb) {
2418 		callback_list = callback_list->_next;
2419 		return 0;
2420 	}
2421 
2422 	previous_callback = callback_list;
2423 
2424 	while (previous_callback->_next) {
2425 		if (previous_callback->_next == cb) {
2426 			previous_callback->_next = previous_callback->_next->_next;
2427 			return 0;
2428 		}
2429 
2430 		previous_callback = previous_callback->_next;
2431 	}
2432 
2433 	return -ENOENT;
2434 }
2435 
bt_conn_exists_le(uint8_t id,const bt_addr_le_t * peer)2436 bool bt_conn_exists_le(uint8_t id, const bt_addr_le_t *peer)
2437 {
2438 	struct bt_conn *conn = bt_conn_lookup_addr_le(id, peer);
2439 
2440 	if (conn) {
2441 		/* Connection object already exists.
2442 		 * If the connection state is not "disconnected",then the
2443 		 * connection was created but has not yet been disconnected.
2444 		 * If the connection state is "disconnected" then the connection
2445 		 * still has valid references. The last reference of the stack
2446 		 * is released after the disconnected callback.
2447 		 */
2448 		LOG_WRN("Found valid connection (%p) with address %s in %s state ", conn,
2449 			bt_addr_le_str(peer), state2str(conn->state));
2450 		bt_conn_unref(conn);
2451 		return true;
2452 	}
2453 
2454 	return false;
2455 }
2456 
bt_conn_add_le(uint8_t id,const bt_addr_le_t * peer)2457 struct bt_conn *bt_conn_add_le(uint8_t id, const bt_addr_le_t *peer)
2458 {
2459 	struct bt_conn *conn = acl_conn_new();
2460 
2461 	if (!conn) {
2462 		return NULL;
2463 	}
2464 
2465 	conn->id = id;
2466 	bt_addr_le_copy(&conn->le.dst, peer);
2467 #if defined(CONFIG_BT_SMP)
2468 	conn->sec_level = BT_SECURITY_L1;
2469 	conn->required_sec_level = BT_SECURITY_L1;
2470 #endif /* CONFIG_BT_SMP */
2471 	conn->type = BT_CONN_TYPE_LE;
2472 	conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN;
2473 	conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX;
2474 
2475 	return conn;
2476 }
2477 
bt_conn_is_peer_addr_le(const struct bt_conn * conn,uint8_t id,const bt_addr_le_t * peer)2478 bool bt_conn_is_peer_addr_le(const struct bt_conn *conn, uint8_t id,
2479 			     const bt_addr_le_t *peer)
2480 {
2481 	if (id != conn->id) {
2482 		return false;
2483 	}
2484 
2485 	/* Check against conn dst address as it may be the identity address */
2486 	if (bt_addr_le_eq(peer, &conn->le.dst)) {
2487 		return true;
2488 	}
2489 
2490 	/* Check against initial connection address */
2491 	if (conn->role == BT_HCI_ROLE_CENTRAL) {
2492 		return bt_addr_le_eq(peer, &conn->le.resp_addr);
2493 	}
2494 
2495 	return bt_addr_le_eq(peer, &conn->le.init_addr);
2496 }
2497 
bt_conn_lookup_addr_le(uint8_t id,const bt_addr_le_t * peer)2498 struct bt_conn *bt_conn_lookup_addr_le(uint8_t id, const bt_addr_le_t *peer)
2499 {
2500 	int i;
2501 
2502 	for (i = 0; i < ARRAY_SIZE(acl_conns); i++) {
2503 		struct bt_conn *conn = bt_conn_ref(&acl_conns[i]);
2504 
2505 		if (!conn) {
2506 			continue;
2507 		}
2508 
2509 		if (conn->type != BT_CONN_TYPE_LE) {
2510 			bt_conn_unref(conn);
2511 			continue;
2512 		}
2513 
2514 		if (!bt_conn_is_peer_addr_le(conn, id, peer)) {
2515 			bt_conn_unref(conn);
2516 			continue;
2517 		}
2518 
2519 		return conn;
2520 	}
2521 
2522 	return NULL;
2523 }
2524 
bt_conn_lookup_state_le(uint8_t id,const bt_addr_le_t * peer,const bt_conn_state_t state)2525 struct bt_conn *bt_conn_lookup_state_le(uint8_t id, const bt_addr_le_t *peer,
2526 					const bt_conn_state_t state)
2527 {
2528 	int i;
2529 
2530 	for (i = 0; i < ARRAY_SIZE(acl_conns); i++) {
2531 		struct bt_conn *conn = bt_conn_ref(&acl_conns[i]);
2532 
2533 		if (!conn) {
2534 			continue;
2535 		}
2536 
2537 		if (conn->type != BT_CONN_TYPE_LE) {
2538 			bt_conn_unref(conn);
2539 			continue;
2540 		}
2541 
2542 		if (peer && !bt_conn_is_peer_addr_le(conn, id, peer)) {
2543 			bt_conn_unref(conn);
2544 			continue;
2545 		}
2546 
2547 		if (!(conn->state == state && conn->id == id)) {
2548 			bt_conn_unref(conn);
2549 			continue;
2550 		}
2551 
2552 		return conn;
2553 	}
2554 
2555 	return NULL;
2556 }
2557 
bt_conn_get_dst(const struct bt_conn * conn)2558 const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn)
2559 {
2560 	return &conn->le.dst;
2561 }
2562 
conn_internal_to_public_state(bt_conn_state_t state)2563 static enum bt_conn_state conn_internal_to_public_state(bt_conn_state_t state)
2564 {
2565 	switch (state) {
2566 	case BT_CONN_DISCONNECTED:
2567 	case BT_CONN_DISCONNECT_COMPLETE:
2568 		return BT_CONN_STATE_DISCONNECTED;
2569 	case BT_CONN_CONNECTING_SCAN:
2570 	case BT_CONN_CONNECTING_AUTO:
2571 	case BT_CONN_CONNECTING_ADV:
2572 	case BT_CONN_CONNECTING_DIR_ADV:
2573 	case BT_CONN_CONNECTING:
2574 		return BT_CONN_STATE_CONNECTING;
2575 	case BT_CONN_CONNECTED:
2576 		return BT_CONN_STATE_CONNECTED;
2577 	case BT_CONN_DISCONNECTING:
2578 		return BT_CONN_STATE_DISCONNECTING;
2579 	default:
2580 		__ASSERT(false, "Invalid conn state %u", state);
2581 		return 0;
2582 	}
2583 }
2584 
bt_conn_get_info(const struct bt_conn * conn,struct bt_conn_info * info)2585 int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info)
2586 {
2587 	info->type = conn->type;
2588 	info->role = conn->role;
2589 	info->id = conn->id;
2590 	info->state = conn_internal_to_public_state(conn->state);
2591 	info->security.flags = 0;
2592 	info->security.level = bt_conn_get_security(conn);
2593 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
2594 	info->security.enc_key_size = bt_conn_enc_key_size(conn);
2595 #else
2596 	info->security.enc_key_size = 0;
2597 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
2598 
2599 	switch (conn->type) {
2600 	case BT_CONN_TYPE_LE:
2601 		info->le.dst = &conn->le.dst;
2602 		info->le.src = &bt_dev.id_addr[conn->id];
2603 		if (conn->role == BT_HCI_ROLE_CENTRAL) {
2604 			info->le.local = &conn->le.init_addr;
2605 			info->le.remote = &conn->le.resp_addr;
2606 		} else {
2607 			info->le.local = &conn->le.resp_addr;
2608 			info->le.remote = &conn->le.init_addr;
2609 		}
2610 		info->le.interval = conn->le.interval;
2611 		info->le.latency = conn->le.latency;
2612 		info->le.timeout = conn->le.timeout;
2613 #if defined(CONFIG_BT_USER_PHY_UPDATE)
2614 		info->le.phy = &conn->le.phy;
2615 #endif
2616 #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE)
2617 		info->le.data_len = &conn->le.data_len;
2618 #endif
2619 		if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_SC)) {
2620 			info->security.flags |= BT_SECURITY_FLAG_SC;
2621 		}
2622 		if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_OOB)) {
2623 			info->security.flags |= BT_SECURITY_FLAG_OOB;
2624 		}
2625 		return 0;
2626 #if defined(CONFIG_BT_BREDR)
2627 	case BT_CONN_TYPE_BR:
2628 		info->br.dst = &conn->br.dst;
2629 		return 0;
2630 #endif
2631 #if defined(CONFIG_BT_ISO)
2632 	case BT_CONN_TYPE_ISO:
2633 		if (IS_ENABLED(CONFIG_BT_ISO_UNICAST) &&
2634 		    conn->iso.info.type == BT_ISO_CHAN_TYPE_CONNECTED && conn->iso.acl != NULL) {
2635 			info->le.dst = &conn->iso.acl->le.dst;
2636 			info->le.src = &bt_dev.id_addr[conn->iso.acl->id];
2637 		} else {
2638 			info->le.src = BT_ADDR_LE_NONE;
2639 			info->le.dst = BT_ADDR_LE_NONE;
2640 		}
2641 		return 0;
2642 #endif
2643 	default:
2644 		break;
2645 	}
2646 
2647 	return -EINVAL;
2648 }
2649 
bt_conn_get_remote_info(struct bt_conn * conn,struct bt_conn_remote_info * remote_info)2650 int bt_conn_get_remote_info(struct bt_conn *conn,
2651 			    struct bt_conn_remote_info *remote_info)
2652 {
2653 	if (!atomic_test_bit(conn->flags, BT_CONN_AUTO_FEATURE_EXCH) ||
2654 	    (IS_ENABLED(CONFIG_BT_REMOTE_VERSION) &&
2655 	     !atomic_test_bit(conn->flags, BT_CONN_AUTO_VERSION_INFO))) {
2656 		return -EBUSY;
2657 	}
2658 
2659 	remote_info->type = conn->type;
2660 #if defined(CONFIG_BT_REMOTE_VERSION)
2661 	/* The conn->rv values will be just zeroes if the operation failed */
2662 	remote_info->version = conn->rv.version;
2663 	remote_info->manufacturer = conn->rv.manufacturer;
2664 	remote_info->subversion = conn->rv.subversion;
2665 #else
2666 	remote_info->version = 0;
2667 	remote_info->manufacturer = 0;
2668 	remote_info->subversion = 0;
2669 #endif
2670 
2671 	switch (conn->type) {
2672 	case BT_CONN_TYPE_LE:
2673 		remote_info->le.features = conn->le.features;
2674 		return 0;
2675 #if defined(CONFIG_BT_BREDR)
2676 	case BT_CONN_TYPE_BR:
2677 		/* TODO: Make sure the HCI commands to read br features and
2678 		*  extended features has finished. */
2679 		return -ENOTSUP;
2680 #endif
2681 	default:
2682 		return -EINVAL;
2683 	}
2684 }
2685 
2686 /* Read Transmit Power Level HCI command */
bt_conn_get_tx_power_level(struct bt_conn * conn,uint8_t type,int8_t * tx_power_level)2687 static int bt_conn_get_tx_power_level(struct bt_conn *conn, uint8_t type,
2688 				      int8_t *tx_power_level)
2689 {
2690 	int err;
2691 	struct bt_hci_rp_read_tx_power_level *rp;
2692 	struct net_buf *rsp;
2693 	struct bt_hci_cp_read_tx_power_level *cp;
2694 	struct net_buf *buf;
2695 
2696 	buf = bt_hci_cmd_create(BT_HCI_OP_READ_TX_POWER_LEVEL, sizeof(*cp));
2697 	if (!buf) {
2698 		return -ENOBUFS;
2699 	}
2700 
2701 	cp = net_buf_add(buf, sizeof(*cp));
2702 	cp->type = type;
2703 	cp->handle = sys_cpu_to_le16(conn->handle);
2704 
2705 	err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_TX_POWER_LEVEL, buf, &rsp);
2706 	if (err) {
2707 		return err;
2708 	}
2709 
2710 	rp = (void *) rsp->data;
2711 	*tx_power_level = rp->tx_power_level;
2712 	net_buf_unref(rsp);
2713 
2714 	return 0;
2715 }
2716 
2717 #if defined(CONFIG_BT_TRANSMIT_POWER_CONTROL)
notify_tx_power_report(struct bt_conn * conn,struct bt_conn_le_tx_power_report report)2718 void notify_tx_power_report(struct bt_conn *conn,
2719 			    struct bt_conn_le_tx_power_report report)
2720 {
2721 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
2722 		if (cb->tx_power_report) {
2723 			cb->tx_power_report(conn, &report);
2724 		}
2725 	}
2726 
2727 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb)
2728 	{
2729 		if (cb->tx_power_report) {
2730 			cb->tx_power_report(conn, &report);
2731 		}
2732 	}
2733 }
2734 
bt_conn_le_enhanced_get_tx_power_level(struct bt_conn * conn,struct bt_conn_le_tx_power * tx_power)2735 int bt_conn_le_enhanced_get_tx_power_level(struct bt_conn *conn,
2736 					   struct bt_conn_le_tx_power *tx_power)
2737 {
2738 	int err;
2739 	struct bt_hci_rp_le_read_tx_power_level *rp;
2740 	struct net_buf *rsp;
2741 	struct bt_hci_cp_le_read_tx_power_level *cp;
2742 	struct net_buf *buf;
2743 
2744 	if (!tx_power->phy) {
2745 		return -EINVAL;
2746 	}
2747 
2748 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_ENH_READ_TX_POWER_LEVEL, sizeof(*cp));
2749 	if (!buf) {
2750 		return -ENOBUFS;
2751 	}
2752 
2753 	cp = net_buf_add(buf, sizeof(*cp));
2754 	cp->handle = sys_cpu_to_le16(conn->handle);
2755 	cp->phy = tx_power->phy;
2756 
2757 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ENH_READ_TX_POWER_LEVEL, buf, &rsp);
2758 	if (err) {
2759 		return err;
2760 	}
2761 
2762 	rp = (void *) rsp->data;
2763 	tx_power->phy = rp->phy;
2764 	tx_power->current_level = rp->current_tx_power_level;
2765 	tx_power->max_level = rp->max_tx_power_level;
2766 	net_buf_unref(rsp);
2767 
2768 	return 0;
2769 }
2770 
bt_conn_le_get_remote_tx_power_level(struct bt_conn * conn,enum bt_conn_le_tx_power_phy phy)2771 int bt_conn_le_get_remote_tx_power_level(struct bt_conn *conn,
2772 					 enum bt_conn_le_tx_power_phy phy)
2773 {
2774 	struct bt_hci_cp_le_read_tx_power_level *cp;
2775 	struct net_buf *buf;
2776 
2777 	if (!phy) {
2778 		return -EINVAL;
2779 	}
2780 
2781 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_TX_POWER_LEVEL, sizeof(*cp));
2782 	if (!buf) {
2783 		return -ENOBUFS;
2784 	}
2785 
2786 	cp = net_buf_add(buf, sizeof(*cp));
2787 	cp->handle = sys_cpu_to_le16(conn->handle);
2788 	cp->phy = phy;
2789 
2790 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_REMOTE_TX_POWER_LEVEL, buf, NULL);
2791 }
2792 
bt_conn_le_set_tx_power_report_enable(struct bt_conn * conn,bool local_enable,bool remote_enable)2793 int bt_conn_le_set_tx_power_report_enable(struct bt_conn *conn,
2794 					  bool local_enable,
2795 					  bool remote_enable)
2796 {
2797 	struct bt_hci_cp_le_set_tx_power_report_enable *cp;
2798 	struct net_buf *buf;
2799 
2800 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_TX_POWER_REPORT_ENABLE, sizeof(*cp));
2801 	if (!buf) {
2802 		return -ENOBUFS;
2803 	}
2804 
2805 	cp = net_buf_add(buf, sizeof(*cp));
2806 	cp->handle = sys_cpu_to_le16(conn->handle);
2807 	cp->local_enable = local_enable ? BT_HCI_LE_TX_POWER_REPORT_ENABLE :
2808 		BT_HCI_LE_TX_POWER_REPORT_DISABLE;
2809 	cp->remote_enable = remote_enable ? BT_HCI_LE_TX_POWER_REPORT_ENABLE :
2810 		BT_HCI_LE_TX_POWER_REPORT_DISABLE;
2811 
2812 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_TX_POWER_REPORT_ENABLE, buf, NULL);
2813 }
2814 #endif /* CONFIG_BT_TRANSMIT_POWER_CONTROL */
2815 
bt_conn_le_get_tx_power_level(struct bt_conn * conn,struct bt_conn_le_tx_power * tx_power_level)2816 int bt_conn_le_get_tx_power_level(struct bt_conn *conn,
2817 				  struct bt_conn_le_tx_power *tx_power_level)
2818 {
2819 	int err;
2820 
2821 	if (tx_power_level->phy != 0) {
2822 		if (IS_ENABLED(CONFIG_BT_TRANSMIT_POWER_CONTROL)) {
2823 			return bt_conn_le_enhanced_get_tx_power_level(conn, tx_power_level);
2824 		} else {
2825 			return -ENOTSUP;
2826 		}
2827 	}
2828 
2829 	err = bt_conn_get_tx_power_level(conn, BT_TX_POWER_LEVEL_CURRENT,
2830 					 &tx_power_level->current_level);
2831 	if (err) {
2832 		return err;
2833 	}
2834 
2835 	err = bt_conn_get_tx_power_level(conn, BT_TX_POWER_LEVEL_MAX,
2836 					 &tx_power_level->max_level);
2837 	return err;
2838 }
2839 
bt_conn_le_param_update(struct bt_conn * conn,const struct bt_le_conn_param * param)2840 int bt_conn_le_param_update(struct bt_conn *conn,
2841 			    const struct bt_le_conn_param *param)
2842 {
2843 	LOG_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0],
2844 		param->interval_min, param->interval_max, param->latency, param->timeout);
2845 
2846 	/* Check if there's a need to update conn params */
2847 	if (conn->le.interval >= param->interval_min &&
2848 	    conn->le.interval <= param->interval_max &&
2849 	    conn->le.latency == param->latency &&
2850 	    conn->le.timeout == param->timeout) {
2851 		atomic_clear_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_SET);
2852 		return -EALREADY;
2853 	}
2854 
2855 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2856 	    conn->role == BT_CONN_ROLE_CENTRAL) {
2857 		return send_conn_le_param_update(conn, param);
2858 	}
2859 
2860 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
2861 		/* if peripheral conn param update timer expired just send request */
2862 		if (atomic_test_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_UPDATE)) {
2863 			return send_conn_le_param_update(conn, param);
2864 		}
2865 
2866 		/* store new conn params to be used by update timer */
2867 		conn->le.interval_min = param->interval_min;
2868 		conn->le.interval_max = param->interval_max;
2869 		conn->le.pending_latency = param->latency;
2870 		conn->le.pending_timeout = param->timeout;
2871 		atomic_set_bit(conn->flags, BT_CONN_PERIPHERAL_PARAM_SET);
2872 	}
2873 
2874 	return 0;
2875 }
2876 
2877 #if defined(CONFIG_BT_USER_DATA_LEN_UPDATE)
bt_conn_le_data_len_update(struct bt_conn * conn,const struct bt_conn_le_data_len_param * param)2878 int bt_conn_le_data_len_update(struct bt_conn *conn,
2879 			       const struct bt_conn_le_data_len_param *param)
2880 {
2881 	if (conn->le.data_len.tx_max_len == param->tx_max_len &&
2882 	    conn->le.data_len.tx_max_time == param->tx_max_time) {
2883 		return -EALREADY;
2884 	}
2885 
2886 	return bt_le_set_data_len(conn, param->tx_max_len, param->tx_max_time);
2887 }
2888 #endif /* CONFIG_BT_USER_DATA_LEN_UPDATE */
2889 
2890 #if defined(CONFIG_BT_USER_PHY_UPDATE)
bt_conn_le_phy_update(struct bt_conn * conn,const struct bt_conn_le_phy_param * param)2891 int bt_conn_le_phy_update(struct bt_conn *conn,
2892 			  const struct bt_conn_le_phy_param *param)
2893 {
2894 	uint8_t phy_opts, all_phys;
2895 
2896 	if ((param->options & BT_CONN_LE_PHY_OPT_CODED_S2) &&
2897 	    (param->options & BT_CONN_LE_PHY_OPT_CODED_S8)) {
2898 		phy_opts = BT_HCI_LE_PHY_CODED_ANY;
2899 	} else if (param->options & BT_CONN_LE_PHY_OPT_CODED_S2) {
2900 		phy_opts = BT_HCI_LE_PHY_CODED_S2;
2901 	} else if (param->options & BT_CONN_LE_PHY_OPT_CODED_S8) {
2902 		phy_opts = BT_HCI_LE_PHY_CODED_S8;
2903 	} else {
2904 		phy_opts = BT_HCI_LE_PHY_CODED_ANY;
2905 	}
2906 
2907 	all_phys = 0U;
2908 	if (param->pref_tx_phy == BT_GAP_LE_PHY_NONE) {
2909 		all_phys |= BT_HCI_LE_PHY_TX_ANY;
2910 	}
2911 
2912 	if (param->pref_rx_phy == BT_GAP_LE_PHY_NONE) {
2913 		all_phys |= BT_HCI_LE_PHY_RX_ANY;
2914 	}
2915 
2916 	return bt_le_set_phy(conn, all_phys, param->pref_tx_phy,
2917 			     param->pref_rx_phy, phy_opts);
2918 }
2919 #endif
2920 
2921 #if defined(CONFIG_BT_CENTRAL)
bt_conn_set_param_le(struct bt_conn * conn,const struct bt_le_conn_param * param)2922 static void bt_conn_set_param_le(struct bt_conn *conn,
2923 				 const struct bt_le_conn_param *param)
2924 {
2925 	conn->le.interval_min = param->interval_min;
2926 	conn->le.interval_max = param->interval_max;
2927 	conn->le.latency = param->latency;
2928 	conn->le.timeout = param->timeout;
2929 }
2930 
create_param_validate(const struct bt_conn_le_create_param * param)2931 static bool create_param_validate(const struct bt_conn_le_create_param *param)
2932 {
2933 #if defined(CONFIG_BT_PRIVACY)
2934 	/* Initiation timeout cannot be greater than the RPA timeout */
2935 	const uint32_t timeout_max = (MSEC_PER_SEC / 10) * bt_dev.rpa_timeout;
2936 
2937 	if (param->timeout > timeout_max) {
2938 		return false;
2939 	}
2940 #endif
2941 
2942 	return true;
2943 }
2944 
create_param_setup(const struct bt_conn_le_create_param * param)2945 static void create_param_setup(const struct bt_conn_le_create_param *param)
2946 {
2947 	bt_dev.create_param = *param;
2948 
2949 	bt_dev.create_param.timeout =
2950 		(bt_dev.create_param.timeout != 0) ?
2951 		bt_dev.create_param.timeout :
2952 		(MSEC_PER_SEC / 10) * CONFIG_BT_CREATE_CONN_TIMEOUT;
2953 
2954 	bt_dev.create_param.interval_coded =
2955 		(bt_dev.create_param.interval_coded != 0) ?
2956 		bt_dev.create_param.interval_coded :
2957 		bt_dev.create_param.interval;
2958 
2959 	bt_dev.create_param.window_coded =
2960 		(bt_dev.create_param.window_coded != 0) ?
2961 		bt_dev.create_param.window_coded :
2962 		bt_dev.create_param.window;
2963 }
2964 
2965 #if defined(CONFIG_BT_FILTER_ACCEPT_LIST)
bt_conn_le_create_auto(const struct bt_conn_le_create_param * create_param,const struct bt_le_conn_param * param)2966 int bt_conn_le_create_auto(const struct bt_conn_le_create_param *create_param,
2967 			   const struct bt_le_conn_param *param)
2968 {
2969 	struct bt_conn *conn;
2970 	int err;
2971 
2972 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2973 		return -EAGAIN;
2974 	}
2975 
2976 	if (!bt_le_conn_params_valid(param)) {
2977 		return -EINVAL;
2978 	}
2979 
2980 	conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE,
2981 				       BT_CONN_CONNECTING_AUTO);
2982 	if (conn) {
2983 		bt_conn_unref(conn);
2984 		return -EALREADY;
2985 	}
2986 
2987 	/* Scanning either to connect or explicit scan, either case scanner was
2988 	 * started by application and should not be stopped.
2989 	 */
2990 	if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
2991 		return -EINVAL;
2992 	}
2993 
2994 	if (atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
2995 		return -EINVAL;
2996 	}
2997 
2998 	if (!bt_id_scan_random_addr_check()) {
2999 		return -EINVAL;
3000 	}
3001 
3002 	conn = bt_conn_add_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE);
3003 	if (!conn) {
3004 		return -ENOMEM;
3005 	}
3006 
3007 	bt_conn_set_param_le(conn, param);
3008 	create_param_setup(create_param);
3009 
3010 	atomic_set_bit(conn->flags, BT_CONN_AUTO_CONNECT);
3011 	bt_conn_set_state(conn, BT_CONN_CONNECTING_AUTO);
3012 
3013 	err = bt_le_create_conn(conn);
3014 	if (err) {
3015 		LOG_ERR("Failed to start filtered scan");
3016 		conn->err = 0;
3017 		bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
3018 		bt_conn_unref(conn);
3019 		return err;
3020 	}
3021 
3022 	/* Since we don't give the application a reference to manage in
3023 	 * this case, we need to release this reference here.
3024 	 */
3025 	bt_conn_unref(conn);
3026 	return 0;
3027 }
3028 
bt_conn_create_auto_stop(void)3029 int bt_conn_create_auto_stop(void)
3030 {
3031 	struct bt_conn *conn;
3032 	int err;
3033 
3034 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
3035 		return -EINVAL;
3036 	}
3037 
3038 	conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, BT_ADDR_LE_NONE,
3039 				       BT_CONN_CONNECTING_AUTO);
3040 	if (!conn) {
3041 		return -EINVAL;
3042 	}
3043 
3044 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
3045 		return -EINVAL;
3046 	}
3047 
3048 	bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
3049 	bt_conn_unref(conn);
3050 
3051 	err = bt_le_create_conn_cancel();
3052 	if (err) {
3053 		LOG_ERR("Failed to stop initiator");
3054 		return err;
3055 	}
3056 
3057 	return 0;
3058 }
3059 #endif /* defined(CONFIG_BT_FILTER_ACCEPT_LIST) */
3060 
conn_le_create_common_checks(const bt_addr_le_t * peer,const struct bt_le_conn_param * conn_param)3061 static int conn_le_create_common_checks(const bt_addr_le_t *peer,
3062 					const struct bt_le_conn_param *conn_param)
3063 {
3064 
3065 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
3066 		return -EAGAIN;
3067 	}
3068 
3069 	if (!bt_le_conn_params_valid(conn_param)) {
3070 		return -EINVAL;
3071 	}
3072 
3073 	if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
3074 		return -EAGAIN;
3075 	}
3076 
3077 	if (atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
3078 		return -EALREADY;
3079 	}
3080 
3081 	if (!bt_id_scan_random_addr_check()) {
3082 		return -EINVAL;
3083 	}
3084 
3085 	if (bt_conn_exists_le(BT_ID_DEFAULT, peer)) {
3086 		return -EINVAL;
3087 	}
3088 
3089 	return 0;
3090 }
3091 
conn_le_create_helper(const bt_addr_le_t * peer,const struct bt_le_conn_param * conn_param)3092 static struct bt_conn *conn_le_create_helper(const bt_addr_le_t *peer,
3093 				     const struct bt_le_conn_param *conn_param)
3094 {
3095 	bt_addr_le_t dst;
3096 	struct bt_conn *conn;
3097 
3098 	if (bt_addr_le_is_resolved(peer)) {
3099 		bt_addr_le_copy_resolved(&dst, peer);
3100 	} else {
3101 		bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer));
3102 	}
3103 
3104 	/* Only default identity supported for now */
3105 	conn = bt_conn_add_le(BT_ID_DEFAULT, &dst);
3106 	if (!conn) {
3107 		return NULL;
3108 	}
3109 
3110 	bt_conn_set_param_le(conn, conn_param);
3111 
3112 	return conn;
3113 }
3114 
bt_conn_le_create(const bt_addr_le_t * peer,const struct bt_conn_le_create_param * create_param,const struct bt_le_conn_param * conn_param,struct bt_conn ** ret_conn)3115 int bt_conn_le_create(const bt_addr_le_t *peer, const struct bt_conn_le_create_param *create_param,
3116 		      const struct bt_le_conn_param *conn_param, struct bt_conn **ret_conn)
3117 {
3118 	struct bt_conn *conn;
3119 	int err;
3120 
3121 	err = conn_le_create_common_checks(peer, conn_param);
3122 	if (err) {
3123 		return err;
3124 	}
3125 
3126 	if (!create_param_validate(create_param)) {
3127 		return -EINVAL;
3128 	}
3129 
3130 	conn = conn_le_create_helper(peer, conn_param);
3131 	if (!conn) {
3132 		return -ENOMEM;
3133 	}
3134 
3135 	create_param_setup(create_param);
3136 
3137 #if defined(CONFIG_BT_SMP)
3138 	if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
3139 		/* Use host-based identity resolving. */
3140 		bt_conn_set_state(conn, BT_CONN_CONNECTING_SCAN);
3141 
3142 		err = bt_le_scan_update(true);
3143 		if (err) {
3144 			bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
3145 			bt_conn_unref(conn);
3146 
3147 			return err;
3148 		}
3149 
3150 		*ret_conn = conn;
3151 		return 0;
3152 	}
3153 #endif
3154 
3155 	bt_conn_set_state(conn, BT_CONN_CONNECTING);
3156 
3157 	err = bt_le_create_conn(conn);
3158 	if (err) {
3159 		conn->err = 0;
3160 		bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
3161 		bt_conn_unref(conn);
3162 
3163 		bt_le_scan_update(false);
3164 		return err;
3165 	}
3166 
3167 	*ret_conn = conn;
3168 	return 0;
3169 }
3170 
bt_conn_le_create_synced(const struct bt_le_ext_adv * adv,const struct bt_conn_le_create_synced_param * synced_param,const struct bt_le_conn_param * conn_param,struct bt_conn ** ret_conn)3171 int bt_conn_le_create_synced(const struct bt_le_ext_adv *adv,
3172 			     const struct bt_conn_le_create_synced_param *synced_param,
3173 			     const struct bt_le_conn_param *conn_param, struct bt_conn **ret_conn)
3174 {
3175 	struct bt_conn *conn;
3176 	int err;
3177 
3178 	err = conn_le_create_common_checks(synced_param->peer, conn_param);
3179 	if (err) {
3180 		return err;
3181 	}
3182 
3183 	if (!atomic_test_bit(adv->flags, BT_PER_ADV_ENABLED)) {
3184 		return -EINVAL;
3185 	}
3186 
3187 	if (!BT_FEAT_LE_PAWR_ADVERTISER(bt_dev.le.features)) {
3188 		return -ENOTSUP;
3189 	}
3190 
3191 	if (synced_param->subevent >= BT_HCI_PAWR_SUBEVENT_MAX) {
3192 		return -EINVAL;
3193 	}
3194 
3195 	conn = conn_le_create_helper(synced_param->peer, conn_param);
3196 	if (!conn) {
3197 		return -ENOMEM;
3198 	}
3199 
3200 	/* The connection creation timeout is not really useful for PAwR.
3201 	 * The controller will give a result for the connection attempt
3202 	 * within a periodic interval. We do not know the periodic interval
3203 	 * used, so disable the timeout.
3204 	 */
3205 	bt_dev.create_param.timeout = 0;
3206 	bt_conn_set_state(conn, BT_CONN_CONNECTING);
3207 
3208 	err = bt_le_create_conn_synced(conn, adv, synced_param->subevent);
3209 	if (err) {
3210 		conn->err = 0;
3211 		bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
3212 		bt_conn_unref(conn);
3213 
3214 		return err;
3215 	}
3216 
3217 	*ret_conn = conn;
3218 	return 0;
3219 }
3220 
3221 #if !defined(CONFIG_BT_FILTER_ACCEPT_LIST)
bt_le_set_auto_conn(const bt_addr_le_t * addr,const struct bt_le_conn_param * param)3222 int bt_le_set_auto_conn(const bt_addr_le_t *addr,
3223 			const struct bt_le_conn_param *param)
3224 {
3225 	struct bt_conn *conn;
3226 
3227 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
3228 		return -EAGAIN;
3229 	}
3230 
3231 	if (param && !bt_le_conn_params_valid(param)) {
3232 		return -EINVAL;
3233 	}
3234 
3235 	if (!bt_id_scan_random_addr_check()) {
3236 		return -EINVAL;
3237 	}
3238 
3239 	/* Only default identity is supported */
3240 	conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr);
3241 	if (!conn) {
3242 		conn = bt_conn_add_le(BT_ID_DEFAULT, addr);
3243 		if (!conn) {
3244 			return -ENOMEM;
3245 		}
3246 	}
3247 
3248 	if (param) {
3249 		bt_conn_set_param_le(conn, param);
3250 
3251 		if (!atomic_test_and_set_bit(conn->flags,
3252 					     BT_CONN_AUTO_CONNECT)) {
3253 			bt_conn_ref(conn);
3254 		}
3255 	} else {
3256 		if (atomic_test_and_clear_bit(conn->flags,
3257 					      BT_CONN_AUTO_CONNECT)) {
3258 			bt_conn_unref(conn);
3259 			if (conn->state == BT_CONN_CONNECTING_SCAN) {
3260 				bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
3261 			}
3262 		}
3263 	}
3264 
3265 	if (conn->state == BT_CONN_DISCONNECTED &&
3266 	    atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
3267 		if (param) {
3268 			bt_conn_set_state(conn, BT_CONN_CONNECTING_SCAN);
3269 		}
3270 		bt_le_scan_update(false);
3271 	}
3272 
3273 	bt_conn_unref(conn);
3274 
3275 	return 0;
3276 }
3277 #endif /* !defined(CONFIG_BT_FILTER_ACCEPT_LIST) */
3278 #endif /* CONFIG_BT_CENTRAL */
3279 
bt_conn_le_conn_update(struct bt_conn * conn,const struct bt_le_conn_param * param)3280 int bt_conn_le_conn_update(struct bt_conn *conn,
3281 			   const struct bt_le_conn_param *param)
3282 {
3283 	struct hci_cp_le_conn_update *conn_update;
3284 	struct net_buf *buf;
3285 
3286 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE,
3287 				sizeof(*conn_update));
3288 	if (!buf) {
3289 		return -ENOBUFS;
3290 	}
3291 
3292 	conn_update = net_buf_add(buf, sizeof(*conn_update));
3293 	(void)memset(conn_update, 0, sizeof(*conn_update));
3294 	conn_update->handle = sys_cpu_to_le16(conn->handle);
3295 	conn_update->conn_interval_min = sys_cpu_to_le16(param->interval_min);
3296 	conn_update->conn_interval_max = sys_cpu_to_le16(param->interval_max);
3297 	conn_update->conn_latency = sys_cpu_to_le16(param->latency);
3298 	conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout);
3299 
3300 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL);
3301 }
3302 
3303 #if defined(CONFIG_NET_BUF_LOG)
bt_conn_create_frag_timeout_debug(size_t reserve,k_timeout_t timeout,const char * func,int line)3304 struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve,
3305 						  k_timeout_t timeout,
3306 						  const char *func, int line)
3307 #else
3308 struct net_buf *bt_conn_create_frag_timeout(size_t reserve, k_timeout_t timeout)
3309 #endif
3310 {
3311 	struct net_buf_pool *pool = NULL;
3312 
3313 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
3314 	pool = &frag_pool;
3315 #endif
3316 
3317 #if defined(CONFIG_NET_BUF_LOG)
3318 	return bt_conn_create_pdu_timeout_debug(pool, reserve, timeout,
3319 						func, line);
3320 #else
3321 	return bt_conn_create_pdu_timeout(pool, reserve, timeout);
3322 #endif /* CONFIG_NET_BUF_LOG */
3323 }
3324 
3325 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
bt_conn_auth_cb_register(const struct bt_conn_auth_cb * cb)3326 int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb)
3327 {
3328 	if (!cb) {
3329 		bt_auth = NULL;
3330 		return 0;
3331 	}
3332 
3333 	if (bt_auth) {
3334 		return -EALREADY;
3335 	}
3336 
3337 	/* The cancel callback must always be provided if the app provides
3338 	 * interactive callbacks.
3339 	 */
3340 	if (!cb->cancel &&
3341 	    (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm ||
3342 #if defined(CONFIG_BT_BREDR)
3343 	     cb->pincode_entry ||
3344 #endif
3345 	     cb->pairing_confirm)) {
3346 		return -EINVAL;
3347 	}
3348 
3349 	bt_auth = cb;
3350 	return 0;
3351 }
3352 
3353 #if defined(CONFIG_BT_SMP)
bt_conn_auth_cb_overlay(struct bt_conn * conn,const struct bt_conn_auth_cb * cb)3354 int bt_conn_auth_cb_overlay(struct bt_conn *conn, const struct bt_conn_auth_cb *cb)
3355 {
3356 	CHECKIF(conn == NULL) {
3357 		return -EINVAL;
3358 	}
3359 
3360 	/* The cancel callback must always be provided if the app provides
3361 	 * interactive callbacks.
3362 	 */
3363 	if (cb && !cb->cancel &&
3364 	    (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm ||
3365 	     cb->pairing_confirm)) {
3366 		return -EINVAL;
3367 	}
3368 
3369 	if (conn->type == BT_CONN_TYPE_LE) {
3370 		return bt_smp_auth_cb_overlay(conn, cb);
3371 	}
3372 
3373 	return -ENOTSUP;
3374 }
3375 #endif
3376 
bt_conn_auth_info_cb_register(struct bt_conn_auth_info_cb * cb)3377 int bt_conn_auth_info_cb_register(struct bt_conn_auth_info_cb *cb)
3378 {
3379 	CHECKIF(cb == NULL) {
3380 		return -EINVAL;
3381 	}
3382 
3383 	sys_slist_append(&bt_auth_info_cbs, &cb->node);
3384 
3385 	return 0;
3386 }
3387 
bt_conn_auth_info_cb_unregister(struct bt_conn_auth_info_cb * cb)3388 int bt_conn_auth_info_cb_unregister(struct bt_conn_auth_info_cb *cb)
3389 {
3390 	CHECKIF(cb == NULL) {
3391 		return -EINVAL;
3392 	}
3393 
3394 	if (!sys_slist_find_and_remove(&bt_auth_info_cbs, &cb->node)) {
3395 		return -EALREADY;
3396 	}
3397 
3398 	return 0;
3399 }
3400 
bt_conn_auth_passkey_entry(struct bt_conn * conn,unsigned int passkey)3401 int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey)
3402 {
3403 	if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
3404 		return bt_smp_auth_passkey_entry(conn, passkey);
3405 	}
3406 
3407 	if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
3408 		if (!bt_auth) {
3409 			return -EINVAL;
3410 		}
3411 
3412 		return bt_ssp_auth_passkey_entry(conn, passkey);
3413 	}
3414 
3415 	return -EINVAL;
3416 }
3417 
3418 #if defined(CONFIG_BT_PASSKEY_KEYPRESS)
bt_conn_auth_keypress_notify(struct bt_conn * conn,enum bt_conn_auth_keypress type)3419 int bt_conn_auth_keypress_notify(struct bt_conn *conn,
3420 				 enum bt_conn_auth_keypress type)
3421 {
3422 	if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
3423 		return bt_smp_auth_keypress_notify(conn, type);
3424 	}
3425 
3426 	LOG_ERR("Not implemented for conn type %d", conn->type);
3427 	return -EINVAL;
3428 }
3429 #endif
3430 
bt_conn_auth_passkey_confirm(struct bt_conn * conn)3431 int bt_conn_auth_passkey_confirm(struct bt_conn *conn)
3432 {
3433 	if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
3434 		return bt_smp_auth_passkey_confirm(conn);
3435 	}
3436 
3437 	if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
3438 		if (!bt_auth) {
3439 			return -EINVAL;
3440 		}
3441 
3442 		return bt_ssp_auth_passkey_confirm(conn);
3443 	}
3444 
3445 	return -EINVAL;
3446 }
3447 
bt_conn_auth_cancel(struct bt_conn * conn)3448 int bt_conn_auth_cancel(struct bt_conn *conn)
3449 {
3450 	if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
3451 		return bt_smp_auth_cancel(conn);
3452 	}
3453 
3454 	if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
3455 		if (!bt_auth) {
3456 			return -EINVAL;
3457 		}
3458 
3459 		return bt_ssp_auth_cancel(conn);
3460 	}
3461 
3462 	return -EINVAL;
3463 }
3464 
bt_conn_auth_pairing_confirm(struct bt_conn * conn)3465 int bt_conn_auth_pairing_confirm(struct bt_conn *conn)
3466 {
3467 	if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
3468 		return bt_smp_auth_pairing_confirm(conn);
3469 	}
3470 
3471 	if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
3472 		if (!bt_auth) {
3473 			return -EINVAL;
3474 		}
3475 
3476 		return bt_ssp_auth_pairing_confirm(conn);
3477 	}
3478 
3479 	return -EINVAL;
3480 }
3481 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
3482 
bt_conn_lookup_index(uint8_t index)3483 struct bt_conn *bt_conn_lookup_index(uint8_t index)
3484 {
3485 	if (index >= ARRAY_SIZE(acl_conns)) {
3486 		return NULL;
3487 	}
3488 
3489 	return bt_conn_ref(&acl_conns[index]);
3490 }
3491 
bt_conn_init(void)3492 int bt_conn_init(void)
3493 {
3494 	int err, i;
3495 
3496 	k_fifo_init(&free_tx);
3497 	for (i = 0; i < ARRAY_SIZE(conn_tx); i++) {
3498 		k_fifo_put(&free_tx, &conn_tx[i]);
3499 	}
3500 
3501 	bt_att_init();
3502 
3503 	err = bt_smp_init();
3504 	if (err) {
3505 		return err;
3506 	}
3507 
3508 	bt_l2cap_init();
3509 
3510 	/* Initialize background scan */
3511 	if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
3512 		for (i = 0; i < ARRAY_SIZE(acl_conns); i++) {
3513 			struct bt_conn *conn = bt_conn_ref(&acl_conns[i]);
3514 
3515 			if (!conn) {
3516 				continue;
3517 			}
3518 
3519 #if !defined(CONFIG_BT_FILTER_ACCEPT_LIST)
3520 			if (atomic_test_bit(conn->flags,
3521 					    BT_CONN_AUTO_CONNECT)) {
3522 				/* Only the default identity is supported */
3523 				conn->id = BT_ID_DEFAULT;
3524 				bt_conn_set_state(conn,
3525 						  BT_CONN_CONNECTING_SCAN);
3526 			}
3527 #endif /* !defined(CONFIG_BT_FILTER_ACCEPT_LIST) */
3528 
3529 			bt_conn_unref(conn);
3530 		}
3531 	}
3532 
3533 	return 0;
3534 }
3535 
3536 #if defined(CONFIG_BT_DF_CONNECTION_CTE_RX)
bt_hci_le_df_connection_iq_report_common(uint8_t event,struct net_buf * buf)3537 void bt_hci_le_df_connection_iq_report_common(uint8_t event, struct net_buf *buf)
3538 {
3539 	struct bt_df_conn_iq_samples_report iq_report;
3540 	struct bt_conn *conn;
3541 	int err;
3542 
3543 	if (event == BT_HCI_EVT_LE_CONNECTION_IQ_REPORT) {
3544 		err = hci_df_prepare_connection_iq_report(buf, &iq_report, &conn);
3545 		if (err) {
3546 			LOG_ERR("Prepare CTE conn IQ report failed %d", err);
3547 			return;
3548 		}
3549 	} else if (IS_ENABLED(CONFIG_BT_DF_VS_CONN_IQ_REPORT_16_BITS_IQ_SAMPLES) &&
3550 		   event == BT_HCI_EVT_VS_LE_CONNECTION_IQ_REPORT) {
3551 		err = hci_df_vs_prepare_connection_iq_report(buf, &iq_report, &conn);
3552 		if (err) {
3553 			LOG_ERR("Prepare CTE conn IQ report failed %d", err);
3554 			return;
3555 		}
3556 	} else {
3557 		LOG_ERR("Unhandled VS connection IQ report");
3558 		return;
3559 	}
3560 
3561 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
3562 		if (cb->cte_report_cb) {
3563 			cb->cte_report_cb(conn, &iq_report);
3564 		}
3565 	}
3566 
3567 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb)
3568 	{
3569 		if (cb->cte_report_cb) {
3570 			cb->cte_report_cb(conn, &iq_report);
3571 		}
3572 	}
3573 
3574 	bt_conn_unref(conn);
3575 }
3576 
bt_hci_le_df_connection_iq_report(struct net_buf * buf)3577 void bt_hci_le_df_connection_iq_report(struct net_buf *buf)
3578 {
3579 	bt_hci_le_df_connection_iq_report_common(BT_HCI_EVT_LE_CONNECTION_IQ_REPORT, buf);
3580 }
3581 
3582 #if defined(CONFIG_BT_DF_VS_CONN_IQ_REPORT_16_BITS_IQ_SAMPLES)
bt_hci_le_vs_df_connection_iq_report(struct net_buf * buf)3583 void bt_hci_le_vs_df_connection_iq_report(struct net_buf *buf)
3584 {
3585 	bt_hci_le_df_connection_iq_report_common(BT_HCI_EVT_VS_LE_CONNECTION_IQ_REPORT, buf);
3586 }
3587 #endif /* CONFIG_BT_DF_VS_CONN_IQ_REPORT_16_BITS_IQ_SAMPLES */
3588 #endif /* CONFIG_BT_DF_CONNECTION_CTE_RX */
3589 
3590 #if defined(CONFIG_BT_DF_CONNECTION_CTE_REQ)
bt_hci_le_df_cte_req_failed(struct net_buf * buf)3591 void bt_hci_le_df_cte_req_failed(struct net_buf *buf)
3592 {
3593 	struct bt_df_conn_iq_samples_report iq_report;
3594 	struct bt_conn *conn;
3595 	int err;
3596 
3597 	err = hci_df_prepare_conn_cte_req_failed(buf, &iq_report, &conn);
3598 	if (err) {
3599 		LOG_ERR("Prepare CTE REQ failed IQ report failed %d", err);
3600 		return;
3601 	}
3602 
3603 	for (struct bt_conn_cb *cb = callback_list; cb; cb = cb->_next) {
3604 		if (cb->cte_report_cb) {
3605 			cb->cte_report_cb(conn, &iq_report);
3606 		}
3607 	}
3608 
3609 	STRUCT_SECTION_FOREACH(bt_conn_cb, cb)
3610 	{
3611 		if (cb->cte_report_cb) {
3612 			cb->cte_report_cb(conn, &iq_report);
3613 		}
3614 	}
3615 
3616 	bt_conn_unref(conn);
3617 }
3618 #endif /* CONFIG_BT_DF_CONNECTION_CTE_REQ */
3619 
3620 #endif /* CONFIG_BT_CONN */
3621