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