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