1 /*  Bluetooth ISO */
2 
3 /*
4  * Copyright (c) 2020 Intel Corporation
5  * Copyright (c) 2021 Nordic Semiconductor ASA
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 
10 #include <zephyr/kernel.h>
11 #include <zephyr/sys/byteorder.h>
12 #include <zephyr/sys/check.h>
13 
14 #include <zephyr/bluetooth/hci.h>
15 #include <zephyr/bluetooth/bluetooth.h>
16 #include <zephyr/bluetooth/conn.h>
17 #include <zephyr/bluetooth/iso.h>
18 
19 #include "host/hci_core.h"
20 #include "host/conn_internal.h"
21 #include "iso_internal.h"
22 
23 #include "common/assert.h"
24 
25 #define LOG_LEVEL CONFIG_BT_ISO_LOG_LEVEL
26 #include <zephyr/logging/log.h>
27 LOG_MODULE_REGISTER(bt_iso);
28 
29 #if defined(CONFIG_BT_DEBUG_ISO_DATA)
30 #define BT_ISO_DATA_DBG(fmt, ...) LOG_DBG(fmt, ##__VA_ARGS__)
31 #else
32 #define BT_ISO_DATA_DBG(fmt, ...)
33 #endif /* CONFIG_BT_DEBUG_ISO_DATA */
34 
35 #define iso_chan(_iso) ((_iso)->iso.chan);
36 
37 #if defined(CONFIG_BT_ISO_UNICAST) || defined(CONFIG_BT_ISO_SYNC_RECEIVER)
38 NET_BUF_POOL_FIXED_DEFINE(iso_rx_pool, CONFIG_BT_ISO_RX_BUF_COUNT,
39 			  BT_ISO_SDU_BUF_SIZE(CONFIG_BT_ISO_RX_MTU), 8, NULL);
40 
41 static struct bt_iso_recv_info iso_info_data[CONFIG_BT_ISO_RX_BUF_COUNT];
42 #define iso_info(buf) (&iso_info_data[net_buf_id(buf)])
43 #endif /* CONFIG_BT_ISO_UNICAST || CONFIG_BT_ISO_SYNC_RECEIVER */
44 
45 #if defined(CONFIG_BT_ISO_UNICAST) || defined(CONFIG_BT_ISO_BROADCAST)
46 NET_BUF_POOL_FIXED_DEFINE(iso_tx_pool, CONFIG_BT_ISO_TX_BUF_COUNT,
47 			  BT_ISO_SDU_BUF_SIZE(CONFIG_BT_ISO_TX_MTU),
48 			  CONFIG_BT_CONN_TX_USER_DATA_SIZE, NULL);
49 
50 #if CONFIG_BT_ISO_TX_FRAG_COUNT > 0
51 NET_BUF_POOL_FIXED_DEFINE(iso_frag_pool, CONFIG_BT_ISO_TX_FRAG_COUNT,
52 			  BT_ISO_SDU_BUF_SIZE(CONFIG_BT_ISO_TX_MTU),
53 			  CONFIG_BT_CONN_TX_USER_DATA_SIZE, NULL);
54 #endif /* CONFIG_BT_ISO_TX_FRAG_COUNT > 0 */
55 #endif /* CONFIG_BT_ISO_UNICAST || CONFIG_BT_ISO_BROADCAST */
56 
57 struct bt_conn iso_conns[CONFIG_BT_ISO_MAX_CHAN];
58 
59 /* TODO: Allow more than one server? */
60 #if defined(CONFIG_BT_ISO_CENTRAL)
61 struct bt_iso_cig cigs[CONFIG_BT_ISO_MAX_CIG];
62 
63 static struct bt_iso_cig *get_cig(const struct bt_iso_chan *iso_chan);
64 static void bt_iso_remove_data_path(struct bt_conn *iso);
65 static int hci_le_create_cis(const struct bt_iso_connect_param *param,
66 			     size_t count);
67 
68 #endif /* CONFIG_BT_ISO_CENTRAL */
69 
70 #if defined(CONFIG_BT_ISO_PERIPHERAL)
71 static struct bt_iso_server *iso_server;
72 
73 static struct bt_conn *bt_conn_add_iso(struct bt_conn *acl);
74 #endif /* CONFIG_BT_ISO_PERIPHERAL */
75 
76 #if defined(CONFIG_BT_ISO_BROADCAST)
77 struct bt_iso_big bigs[CONFIG_BT_ISO_MAX_BIG];
78 
79 static struct bt_iso_big *lookup_big_by_handle(uint8_t big_handle);
80 #endif /* CONFIG_BT_ISO_BROADCAST */
81 
82 #if defined(CONFIG_BT_ISO_UNICAST) || defined(CONFIG_BT_ISO_BROADCASTER)
bt_iso_send_cb(struct bt_conn * iso,void * user_data,int err)83 static void bt_iso_send_cb(struct bt_conn *iso, void *user_data, int err)
84 {
85 	struct bt_iso_chan *chan = iso->iso.chan;
86 	struct bt_iso_chan_ops *ops;
87 
88 	__ASSERT(chan != NULL, "NULL chan for iso %p", iso);
89 
90 	ops = chan->ops;
91 
92 	if (!err && ops != NULL && ops->sent != NULL) {
93 		ops->sent(chan);
94 	}
95 }
96 #endif /* CONFIG_BT_ISO_UNICAST || CONFIG_BT_ISO_BROADCASTER */
97 
98 
hci_iso(struct net_buf * buf)99 void hci_iso(struct net_buf *buf)
100 {
101 	struct bt_hci_iso_hdr *hdr;
102 	uint16_t handle, len;
103 	struct bt_conn *iso;
104 	uint8_t flags;
105 
106 	BT_ISO_DATA_DBG("buf %p", buf);
107 
108 	BT_ASSERT(buf->len >= sizeof(*hdr));
109 
110 	hdr = net_buf_pull_mem(buf, sizeof(*hdr));
111 	len = bt_iso_hdr_len(sys_le16_to_cpu(hdr->len));
112 	handle = sys_le16_to_cpu(hdr->handle);
113 	flags = bt_iso_flags(handle);
114 
115 	iso(buf)->handle = bt_iso_handle(handle);
116 	iso(buf)->index = BT_CONN_INDEX_INVALID;
117 
118 	BT_ISO_DATA_DBG("handle %u len %u flags %u",
119 			iso(buf)->handle, len, flags);
120 
121 	if (buf->len != len) {
122 		LOG_ERR("ISO data length mismatch (%u != %u)", buf->len, len);
123 		net_buf_unref(buf);
124 		return;
125 	}
126 
127 	iso = bt_conn_lookup_handle(iso(buf)->handle);
128 	if (iso == NULL) {
129 		LOG_ERR("Unable to find conn for handle %u", iso(buf)->handle);
130 		net_buf_unref(buf);
131 		return;
132 	}
133 
134 	iso(buf)->index = bt_conn_index(iso);
135 
136 	bt_conn_recv(iso, buf, flags);
137 	bt_conn_unref(iso);
138 }
139 
iso_new(void)140 static struct bt_conn *iso_new(void)
141 {
142 	struct bt_conn *iso = bt_conn_new(iso_conns, ARRAY_SIZE(iso_conns));
143 
144 	if (iso) {
145 		iso->type = BT_CONN_TYPE_ISO;
146 	} else {
147 		LOG_DBG("Could not create new ISO");
148 	}
149 
150 	return iso;
151 }
152 
153 #if defined(CONFIG_NET_BUF_LOG)
bt_iso_create_pdu_timeout_debug(struct net_buf_pool * pool,size_t reserve,k_timeout_t timeout,const char * func,int line)154 struct net_buf *bt_iso_create_pdu_timeout_debug(struct net_buf_pool *pool,
155 						size_t reserve,
156 						k_timeout_t timeout,
157 						const char *func, int line)
158 #else
159 struct net_buf *bt_iso_create_pdu_timeout(struct net_buf_pool *pool,
160 					  size_t reserve, k_timeout_t timeout)
161 #endif
162 {
163 	if (!pool) {
164 		pool = &iso_tx_pool;
165 	}
166 
167 	reserve += sizeof(struct bt_hci_iso_data_hdr);
168 
169 #if defined(CONFIG_NET_BUF_LOG)
170 	return bt_conn_create_pdu_timeout_debug(pool, reserve, timeout, func,
171 						line);
172 #else
173 	return bt_conn_create_pdu_timeout(pool, reserve, timeout);
174 #endif
175 }
176 
177 #if defined(CONFIG_NET_BUF_LOG)
bt_iso_create_frag_timeout_debug(size_t reserve,k_timeout_t timeout,const char * func,int line)178 struct net_buf *bt_iso_create_frag_timeout_debug(size_t reserve,
179 						 k_timeout_t timeout,
180 						 const char *func, int line)
181 #else
182 struct net_buf *bt_iso_create_frag_timeout(size_t reserve, k_timeout_t timeout)
183 #endif
184 {
185 	struct net_buf_pool *pool = NULL;
186 
187 #if CONFIG_BT_ISO_TX_FRAG_COUNT > 0
188 	pool = &iso_frag_pool;
189 #endif /* CONFIG_BT_ISO_TX_FRAG_COUNT > 0 */
190 
191 #if defined(CONFIG_NET_BUF_LOG)
192 	return bt_conn_create_pdu_timeout_debug(pool, reserve, timeout, func,
193 						line);
194 #else
195 	return bt_conn_create_pdu_timeout(pool, reserve, timeout);
196 #endif
197 }
198 
hci_le_setup_iso_data_path(const struct bt_conn * iso,uint8_t dir,const struct bt_iso_chan_path * path)199 static int hci_le_setup_iso_data_path(const struct bt_conn *iso, uint8_t dir,
200 				      const struct bt_iso_chan_path *path)
201 {
202 	struct bt_hci_cp_le_setup_iso_path *cp;
203 	struct bt_hci_rp_le_setup_iso_path *rp;
204 	struct net_buf *buf, *rsp;
205 	uint8_t *cc;
206 	int err;
207 
208 	__ASSERT(dir == BT_HCI_DATAPATH_DIR_HOST_TO_CTLR ||
209 		 dir == BT_HCI_DATAPATH_DIR_CTLR_TO_HOST,
210 		 "invalid ISO data path dir: %u", dir);
211 
212 	if ((path->cc == NULL && path->cc_len != 0)) {
213 		LOG_DBG("Invalid ISO data path CC: %p %u", path->cc, path->cc_len);
214 
215 		return -EINVAL;
216 	}
217 
218 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SETUP_ISO_PATH, sizeof(*cp) + path->cc_len);
219 	if (!buf) {
220 		return -ENOBUFS;
221 	}
222 
223 	cp = net_buf_add(buf, sizeof(*cp));
224 	cp->handle = sys_cpu_to_le16(iso->handle);
225 	cp->path_dir = dir;
226 	cp->path_id = path->pid;
227 	cp->codec_id.coding_format = path->format;
228 	cp->codec_id.company_id = sys_cpu_to_le16(path->cid);
229 	cp->codec_id.vs_codec_id = sys_cpu_to_le16(path->vid);
230 	sys_put_le24(path->delay, cp->controller_delay);
231 	cp->codec_config_len = path->cc_len;
232 	cc = net_buf_add(buf, cp->codec_config_len);
233 	memcpy(cc, path->cc, cp->codec_config_len);
234 
235 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SETUP_ISO_PATH, buf, &rsp);
236 	if (err) {
237 		return err;
238 	}
239 
240 	rp = (void *)rsp->data;
241 	if (rp->status || (sys_le16_to_cpu(rp->handle) != iso->handle)) {
242 		err = -EIO;
243 	}
244 
245 	net_buf_unref(rsp);
246 
247 	return err;
248 }
249 
bt_iso_chan_add(struct bt_conn * iso,struct bt_iso_chan * chan)250 static void bt_iso_chan_add(struct bt_conn *iso, struct bt_iso_chan *chan)
251 {
252 	/* Attach ISO channel to the connection */
253 	chan->iso = iso;
254 	iso->iso.chan = chan;
255 
256 	LOG_DBG("iso %p chan %p", iso, chan);
257 }
258 
bt_iso_setup_data_path(struct bt_iso_chan * chan)259 static int bt_iso_setup_data_path(struct bt_iso_chan *chan)
260 {
261 	int err;
262 	struct bt_iso_chan_path default_hci_path = { .pid = BT_ISO_DATA_PATH_HCI,
263 						     .format = BT_HCI_CODING_FORMAT_TRANSPARENT,
264 						     .cc_len = 0x00 };
265 	struct bt_iso_chan_path *out_path = NULL;
266 	struct bt_iso_chan_path *in_path = NULL;
267 	struct bt_iso_chan_io_qos *tx_qos;
268 	struct bt_iso_chan_io_qos *rx_qos;
269 	struct bt_conn *iso;
270 	uint8_t dir;
271 
272 	iso = chan->iso;
273 
274 	tx_qos = chan->qos->tx;
275 	rx_qos = chan->qos->rx;
276 
277 	/* The following code sets the in and out paths for ISO data.
278 	 * If the application provides a path for a direction (tx/rx) we use
279 	 * that, otherwise we simply fall back to HCI.
280 	 *
281 	 * If the direction is not set (by whether tx_qos or rx_qos is NULL),
282 	 * then we fallback to the HCI path object, but we disable the direction
283 	 * in the controller.
284 	 */
285 
286 	if (tx_qos != NULL && iso->iso.info.can_send) {
287 		if (tx_qos->path != NULL) { /* Use application path */
288 			in_path = tx_qos->path;
289 		} else { /* else fallback to HCI path */
290 			in_path = &default_hci_path;
291 		}
292 	}
293 
294 	if (rx_qos != NULL && iso->iso.info.can_recv) {
295 		if (rx_qos->path != NULL) { /* Use application path */
296 			out_path = rx_qos->path;
297 		} else { /* else fallback to HCI path */
298 			out_path = &default_hci_path;
299 		}
300 	}
301 
302 	__ASSERT(in_path || out_path,
303 		 "At least one path shall be shell: in %p out %p",
304 		 in_path, out_path);
305 
306 	if (IS_ENABLED(CONFIG_BT_ISO_BROADCASTER) &&
307 	    iso->iso.info.type == BT_ISO_CHAN_TYPE_BROADCASTER && in_path) {
308 		dir = BT_HCI_DATAPATH_DIR_HOST_TO_CTLR;
309 		err = hci_le_setup_iso_data_path(iso, dir, in_path);
310 		if (err != 0) {
311 			LOG_DBG("Failed to set broadcaster data path: %d", err);
312 		}
313 
314 		return err;
315 	} else if (IS_ENABLED(CONFIG_BT_ISO_SYNC_RECEIVER) &&
316 		   iso->iso.info.type == BT_ISO_CHAN_TYPE_SYNC_RECEIVER &&
317 		   out_path) {
318 		dir = BT_HCI_DATAPATH_DIR_CTLR_TO_HOST;
319 		err = hci_le_setup_iso_data_path(iso, dir, out_path);
320 		if (err != 0) {
321 			LOG_DBG("Failed to set sync receiver data path: %d", err);
322 		}
323 
324 		return err;
325 	} else if (IS_ENABLED(CONFIG_BT_ISO_UNICAST) &&
326 		   iso->iso.info.type == BT_ISO_CHAN_TYPE_CONNECTED) {
327 		if (in_path != NULL) {
328 			/* Enable TX */
329 			dir = BT_HCI_DATAPATH_DIR_HOST_TO_CTLR;
330 			err = hci_le_setup_iso_data_path(iso, dir, in_path);
331 			if (err) {
332 				return err;
333 			}
334 		}
335 
336 		if (out_path != NULL) {
337 			/* Enable RX */
338 			dir = BT_HCI_DATAPATH_DIR_CTLR_TO_HOST;
339 			err = hci_le_setup_iso_data_path(iso, dir, out_path);
340 			if (err) {
341 				return err;
342 			}
343 		}
344 
345 		return 0;
346 	} else {
347 		__ASSERT(false, "Invalid iso.info.type: %u",
348 			 iso->iso.info.type);
349 		return -EINVAL;
350 	}
351 }
352 
bt_iso_connected(struct bt_conn * iso)353 void bt_iso_connected(struct bt_conn *iso)
354 {
355 	struct bt_iso_chan *chan;
356 	int err;
357 
358 	if (iso == NULL || iso->type != BT_CONN_TYPE_ISO) {
359 		LOG_DBG("Invalid parameters: iso %p iso->type %u", iso, iso ? iso->type : 0);
360 		return;
361 	}
362 
363 	LOG_DBG("%p", iso);
364 
365 	chan = iso_chan(iso);
366 	if (chan == NULL) {
367 		LOG_ERR("Could not lookup chan from connected ISO");
368 		return;
369 	}
370 
371 	err = bt_iso_setup_data_path(chan);
372 	if (err != 0) {
373 		if (false) {
374 
375 #if defined(CONFIG_BT_ISO_BROADCAST)
376 		} else if (iso->iso.info.type == BT_ISO_CHAN_TYPE_BROADCASTER ||
377 			   iso->iso.info.type == BT_ISO_CHAN_TYPE_SYNC_RECEIVER) {
378 			struct bt_iso_big *big;
379 			int err;
380 
381 			big = lookup_big_by_handle(iso->iso.big_handle);
382 
383 			err = bt_iso_big_terminate(big);
384 			if (err != 0) {
385 				LOG_ERR("Could not terminate BIG: %d", err);
386 			}
387 #endif /* CONFIG_BT_ISO_BROADCAST */
388 
389 		} else if (IS_ENABLED(CONFIG_BT_ISO_UNICAST) &&
390 		    iso->iso.info.type == BT_ISO_CHAN_TYPE_CONNECTED) {
391 			bt_conn_disconnect(iso,
392 					   BT_HCI_ERR_REMOTE_USER_TERM_CONN);
393 		} else {
394 			__ASSERT(false, "Invalid iso.info.type: %u",
395 				 iso->iso.info.type);
396 		}
397 		return;
398 	}
399 
400 	bt_iso_chan_set_state(chan, BT_ISO_STATE_CONNECTED);
401 
402 	if (chan->ops->connected) {
403 		chan->ops->connected(chan);
404 	}
405 }
406 
bt_iso_chan_disconnected(struct bt_iso_chan * chan,uint8_t reason)407 static void bt_iso_chan_disconnected(struct bt_iso_chan *chan, uint8_t reason)
408 {
409 	LOG_DBG("%p, reason 0x%02x", chan, reason);
410 
411 	__ASSERT(chan->iso != NULL, "NULL conn for iso chan %p", chan);
412 
413 	bt_iso_chan_set_state(chan, BT_ISO_STATE_DISCONNECTED);
414 
415 	/* The peripheral does not have the concept of a CIG, so once a CIS
416 	 * disconnects it is completely freed by unref'ing it
417 	 */
418 	if (IS_ENABLED(CONFIG_BT_ISO_UNICAST) &&
419 	    chan->iso->iso.info.type == BT_ISO_CHAN_TYPE_CONNECTED) {
420 		bt_iso_cleanup_acl(chan->iso);
421 
422 		if (chan->iso->role == BT_HCI_ROLE_PERIPHERAL) {
423 			bt_conn_unref(chan->iso);
424 			chan->iso = NULL;
425 #if defined(CONFIG_BT_ISO_CENTRAL)
426 		} else {
427 			/* ISO data paths are automatically removed when the
428 			 * peripheral disconnects, so we only need to
429 			 * move it for the central
430 			 */
431 			bt_iso_remove_data_path(chan->iso);
432 			bool is_chan_connected;
433 			struct bt_iso_cig *cig;
434 			struct bt_iso_chan *cis_chan;
435 
436 			/* Update CIG state */
437 			cig = get_cig(chan);
438 			__ASSERT(cig != NULL, "CIG was NULL");
439 
440 			is_chan_connected = false;
441 			SYS_SLIST_FOR_EACH_CONTAINER(&cig->cis_channels, cis_chan, node) {
442 				if (cis_chan->state == BT_ISO_STATE_CONNECTED ||
443 				    cis_chan->state == BT_ISO_STATE_CONNECTING) {
444 					is_chan_connected = true;
445 					break;
446 				}
447 			}
448 
449 			if (!is_chan_connected) {
450 				cig->state = BT_ISO_CIG_STATE_INACTIVE;
451 			}
452 #endif /* CONFIG_BT_ISO_CENTRAL */
453 		}
454 	}
455 
456 	if (chan->ops->disconnected) {
457 		chan->ops->disconnected(chan, reason);
458 	}
459 }
460 
bt_iso_disconnected(struct bt_conn * iso)461 void bt_iso_disconnected(struct bt_conn *iso)
462 {
463 	struct bt_iso_chan *chan;
464 
465 	if (iso == NULL || iso->type != BT_CONN_TYPE_ISO) {
466 		LOG_DBG("Invalid parameters: iso %p iso->type %u", iso, iso ? iso->type : 0);
467 		return;
468 	}
469 
470 	LOG_DBG("%p", iso);
471 
472 	chan = iso_chan(iso);
473 	if (chan == NULL) {
474 		LOG_ERR("Could not lookup chan from disconnected ISO");
475 		return;
476 	}
477 
478 	bt_iso_chan_disconnected(chan, iso->err);
479 }
480 
481 #if defined(CONFIG_BT_ISO_LOG_LEVEL_DBG)
bt_iso_chan_state_str(uint8_t state)482 const char *bt_iso_chan_state_str(uint8_t state)
483 {
484 	switch (state) {
485 	case BT_ISO_STATE_DISCONNECTED:
486 		return "disconnected";
487 	case BT_ISO_STATE_CONNECTING:
488 		return "connecting";
489 	case BT_ISO_STATE_ENCRYPT_PENDING:
490 		return "encryption pending";
491 	case BT_ISO_STATE_CONNECTED:
492 		return "connected";
493 	case BT_ISO_STATE_DISCONNECTING:
494 		return "disconnecting";
495 	default:
496 		return "unknown";
497 	}
498 }
499 
bt_iso_chan_set_state_debug(struct bt_iso_chan * chan,enum bt_iso_state state,const char * func,int line)500 void bt_iso_chan_set_state_debug(struct bt_iso_chan *chan,
501 				 enum bt_iso_state state,
502 				 const char *func, int line)
503 {
504 	LOG_DBG("chan %p iso %p %s -> %s", chan, chan->iso, bt_iso_chan_state_str(chan->state),
505 		bt_iso_chan_state_str(state));
506 
507 	/* check transitions validness */
508 	switch (state) {
509 	case BT_ISO_STATE_DISCONNECTED:
510 		/* regardless of old state always allows this states */
511 		break;
512 	case BT_ISO_STATE_ENCRYPT_PENDING:
513 		__fallthrough;
514 	case BT_ISO_STATE_CONNECTING:
515 		if (chan->state != BT_ISO_STATE_DISCONNECTED) {
516 			LOG_WRN("%s()%d: invalid transition", func, line);
517 		}
518 		break;
519 	case BT_ISO_STATE_CONNECTED:
520 		if (chan->state != BT_ISO_STATE_CONNECTING) {
521 			LOG_WRN("%s()%d: invalid transition", func, line);
522 		}
523 		break;
524 	case BT_ISO_STATE_DISCONNECTING:
525 		if (chan->state != BT_ISO_STATE_CONNECTING &&
526 		    chan->state != BT_ISO_STATE_CONNECTED) {
527 			LOG_WRN("%s()%d: invalid transition", func, line);
528 		}
529 		break;
530 	default:
531 		LOG_ERR("%s()%d: unknown (%u) state was set", func, line, state);
532 		return;
533 	}
534 
535 	chan->state = state;
536 }
537 #else
bt_iso_chan_set_state(struct bt_iso_chan * chan,enum bt_iso_state state)538 void bt_iso_chan_set_state(struct bt_iso_chan *chan, enum bt_iso_state state)
539 {
540 	chan->state = state;
541 }
542 #endif /* CONFIG_BT_ISO_LOG_LEVEL_DBG */
543 
bt_iso_chan_get_info(const struct bt_iso_chan * chan,struct bt_iso_info * info)544 int bt_iso_chan_get_info(const struct bt_iso_chan *chan,
545 			 struct bt_iso_info *info)
546 {
547 	CHECKIF(chan == NULL) {
548 		LOG_DBG("chan is NULL");
549 		return -EINVAL;
550 	}
551 
552 	CHECKIF(chan->iso == NULL) {
553 		LOG_DBG("chan->iso is NULL");
554 		return -EINVAL;
555 	}
556 
557 	CHECKIF(info == NULL) {
558 		LOG_DBG("info is NULL");
559 		return -EINVAL;
560 	}
561 
562 	(void)memcpy(info, &chan->iso->iso.info, sizeof(*info));
563 
564 	return 0;
565 }
566 
567 #if defined(CONFIG_BT_ISO_UNICAST) || defined(CONFIG_BT_ISO_SYNC_RECEIVER)
bt_iso_get_rx(k_timeout_t timeout)568 struct net_buf *bt_iso_get_rx(k_timeout_t timeout)
569 {
570 	struct net_buf *buf = net_buf_alloc(&iso_rx_pool, timeout);
571 
572 	if (buf) {
573 		net_buf_reserve(buf, BT_BUF_RESERVE);
574 		bt_buf_set_type(buf, BT_BUF_ISO_IN);
575 	}
576 
577 	return buf;
578 }
579 
bt_iso_recv(struct bt_conn * iso,struct net_buf * buf,uint8_t flags)580 void bt_iso_recv(struct bt_conn *iso, struct net_buf *buf, uint8_t flags)
581 {
582 	struct bt_hci_iso_data_hdr *hdr;
583 	struct bt_iso_chan *chan;
584 	uint8_t pb, ts;
585 	uint16_t len, pkt_seq_no;
586 
587 	pb = bt_iso_flags_pb(flags);
588 	ts = bt_iso_flags_ts(flags);
589 
590 	BT_ISO_DATA_DBG("handle %u len %u flags 0x%02x pb 0x%02x ts 0x%02x",
591 			iso->handle, buf->len, flags, pb, ts);
592 
593 	/* When the PB_Flag does not equal 0b00, the fields Time_Stamp,
594 	 * Packet_Sequence_Number, Packet_Status_Flag and ISO_SDU_Length
595 	 * are omitted from the HCI ISO Data packet.
596 	 */
597 	switch (pb) {
598 	case BT_ISO_START:
599 	case BT_ISO_SINGLE:
600 		iso_info(buf)->flags = 0;
601 
602 		/* The ISO_Data_Load field contains either the first fragment
603 		 * of an SDU or a complete SDU.
604 		 */
605 		if (ts) {
606 			struct bt_hci_iso_ts_data_hdr *ts_hdr;
607 
608 			ts_hdr = net_buf_pull_mem(buf, sizeof(*ts_hdr));
609 			iso_info(buf)->ts = sys_le32_to_cpu(ts_hdr->ts);
610 
611 			hdr = &ts_hdr->data;
612 			iso_info(buf)->flags |= BT_ISO_FLAGS_TS;
613 		} else {
614 			hdr = net_buf_pull_mem(buf, sizeof(*hdr));
615 			/* TODO: Generate a timestamp? */
616 			iso_info(buf)->ts = 0x00000000;
617 		}
618 
619 		len = sys_le16_to_cpu(hdr->slen);
620 		flags = bt_iso_pkt_flags(len);
621 		len = bt_iso_pkt_len(len);
622 		pkt_seq_no = sys_le16_to_cpu(hdr->sn);
623 		iso_info(buf)->seq_num = pkt_seq_no;
624 		if (flags == BT_ISO_DATA_VALID) {
625 			iso_info(buf)->flags |= BT_ISO_FLAGS_VALID;
626 		} else if (flags == BT_ISO_DATA_INVALID) {
627 			iso_info(buf)->flags |= BT_ISO_FLAGS_ERROR;
628 		} else if (flags == BT_ISO_DATA_NOP) {
629 			iso_info(buf)->flags |= BT_ISO_FLAGS_LOST;
630 		} else {
631 			LOG_WRN("Invalid ISO packet status flag: %u", flags);
632 			iso_info(buf)->flags = 0;
633 		}
634 
635 		BT_ISO_DATA_DBG("%s, len %u total %u flags 0x%02x timestamp %u",
636 				pb == BT_ISO_START ? "Start" : "Single",
637 				buf->len, len, flags, iso_info(buf)->ts);
638 
639 		if (iso->rx) {
640 			LOG_ERR("Unexpected ISO %s fragment",
641 				pb == BT_ISO_START ? "Start" : "Single");
642 			bt_conn_reset_rx_state(iso);
643 		}
644 
645 		iso->rx = buf;
646 		iso->rx_len = len - buf->len;
647 		if (iso->rx_len) {
648 			/* if iso->rx_len then package is longer than the
649 			 * buf->len and cannot fit in a SINGLE package
650 			 */
651 			if (pb == BT_ISO_SINGLE) {
652 				LOG_ERR("Unexpected ISO single fragment");
653 				bt_conn_reset_rx_state(iso);
654 			}
655 			return;
656 		}
657 		break;
658 
659 	case BT_ISO_CONT:
660 		/* The ISO_Data_Load field contains a continuation fragment of
661 		 * an SDU.
662 		 */
663 		if (!iso->rx) {
664 			LOG_ERR("Unexpected ISO continuation fragment");
665 			net_buf_unref(buf);
666 			return;
667 		}
668 
669 		BT_ISO_DATA_DBG("Cont, len %u rx_len %u",
670 				buf->len, iso->rx_len);
671 
672 		if (buf->len > net_buf_tailroom(iso->rx)) {
673 			LOG_ERR("Not enough buffer space for ISO data");
674 			bt_conn_reset_rx_state(iso);
675 			net_buf_unref(buf);
676 			return;
677 		}
678 
679 		net_buf_add_mem(iso->rx, buf->data, buf->len);
680 		iso->rx_len -= buf->len;
681 		net_buf_unref(buf);
682 		return;
683 
684 	case BT_ISO_END:
685 		/* The ISO_Data_Load field contains the last fragment of an
686 		 * SDU.
687 		 */
688 		BT_ISO_DATA_DBG("End, len %u rx_len %u", buf->len, iso->rx_len);
689 
690 		if (iso->rx == NULL) {
691 			LOG_ERR("Unexpected ISO end fragment");
692 			net_buf_unref(buf);
693 			return;
694 		}
695 
696 		if (buf->len > net_buf_tailroom(iso->rx)) {
697 			LOG_ERR("Not enough buffer space for ISO data");
698 			bt_conn_reset_rx_state(iso);
699 			net_buf_unref(buf);
700 			return;
701 		}
702 
703 		(void)net_buf_add_mem(iso->rx, buf->data, buf->len);
704 		iso->rx_len -= buf->len;
705 		net_buf_unref(buf);
706 
707 		break;
708 	default:
709 		LOG_ERR("Unexpected ISO pb flags (0x%02x)", pb);
710 		bt_conn_reset_rx_state(iso);
711 		net_buf_unref(buf);
712 		return;
713 	}
714 
715 	chan = iso_chan(iso);
716 	if (chan == NULL) {
717 		LOG_ERR("Could not lookup chan from receiving ISO");
718 	} else if (chan->ops->recv != NULL) {
719 		chan->ops->recv(chan, iso_info(iso->rx), iso->rx);
720 	}
721 
722 	bt_conn_reset_rx_state(iso);
723 }
724 #endif /* CONFIG_BT_ISO_UNICAST) || defined(CONFIG_BT_ISO_SYNC_RECEIVER */
725 
726 #if defined(CONFIG_BT_ISO_UNICAST) || defined(CONFIG_BT_ISO_BROADCASTER)
iso_chan_max_data_len(const struct bt_iso_chan * chan,uint32_t ts)727 static uint16_t iso_chan_max_data_len(const struct bt_iso_chan *chan,
728 				      uint32_t ts)
729 {
730 	size_t max_controller_data_len;
731 	uint16_t max_data_len;
732 
733 	if (chan->qos->tx == NULL) {
734 		return 0;
735 	}
736 
737 	max_data_len = chan->qos->tx->sdu;
738 
739 	/* Ensure that the SDU fits when using all the buffers */
740 	max_controller_data_len = bt_dev.le.iso_mtu * bt_dev.le.iso_limit;
741 
742 	/* Update the max_data_len to take the max_controller_data_len into account */
743 	max_data_len = MIN(max_data_len, max_controller_data_len);
744 
745 	return max_data_len;
746 }
747 
bt_iso_chan_send(struct bt_iso_chan * chan,struct net_buf * buf,uint16_t seq_num,uint32_t ts)748 int bt_iso_chan_send(struct bt_iso_chan *chan, struct net_buf *buf,
749 		     uint16_t seq_num, uint32_t ts)
750 {
751 	uint16_t max_data_len;
752 	struct bt_conn *iso_conn;
753 
754 	CHECKIF(!chan || !buf) {
755 		LOG_DBG("Invalid parameters: chan %p buf %p", chan, buf);
756 		return -EINVAL;
757 	}
758 
759 	BT_ISO_DATA_DBG("chan %p len %zu", chan, net_buf_frags_len(buf));
760 
761 	if (chan->state != BT_ISO_STATE_CONNECTED) {
762 		LOG_DBG("Not connected");
763 		return -ENOTCONN;
764 	}
765 
766 	iso_conn = chan->iso;
767 	if (!iso_conn->iso.info.can_send) {
768 		LOG_DBG("Channel not able to send");
769 		return -EINVAL;
770 	}
771 
772 	if (ts == BT_ISO_TIMESTAMP_NONE &&
773 	    buf->size < BT_HCI_ISO_DATA_HDR_SIZE) {
774 		LOG_DBG("Cannot send ISO packet with buffer size %u", buf->size);
775 
776 		return -EMSGSIZE;
777 	} else if (buf->size < BT_HCI_ISO_TS_DATA_HDR_SIZE) {
778 		LOG_DBG("Cannot send ISO packet with timestamp with buffer size %u", buf->size);
779 
780 		return -EMSGSIZE;
781 	}
782 
783 	max_data_len = iso_chan_max_data_len(chan, ts);
784 	if (buf->len > max_data_len) {
785 		LOG_DBG("Cannot send %u octets, maximum %u", buf->len, max_data_len);
786 		return -EMSGSIZE;
787 	}
788 
789 	if (ts == BT_ISO_TIMESTAMP_NONE) {
790 		struct bt_hci_iso_data_hdr *hdr;
791 
792 		hdr = net_buf_push(buf, sizeof(*hdr));
793 		hdr->sn = sys_cpu_to_le16(seq_num);
794 		hdr->slen = sys_cpu_to_le16(bt_iso_pkt_len_pack(net_buf_frags_len(buf)
795 								- sizeof(*hdr),
796 								BT_ISO_DATA_VALID));
797 	} else {
798 		struct bt_hci_iso_ts_data_hdr *hdr;
799 
800 		hdr = net_buf_push(buf, sizeof(*hdr));
801 		hdr->ts = ts;
802 		hdr->data.sn = sys_cpu_to_le16(seq_num);
803 		hdr->data.slen = sys_cpu_to_le16(bt_iso_pkt_len_pack(net_buf_frags_len(buf)
804 								     - sizeof(*hdr),
805 								     BT_ISO_DATA_VALID));
806 	}
807 
808 	return bt_conn_send_iso_cb(iso_conn,
809 				   buf,
810 				   bt_iso_send_cb,
811 				   ts != BT_ISO_TIMESTAMP_NONE);
812 }
813 
814 #if defined(CONFIG_BT_ISO_CENTRAL) || defined(CONFIG_BT_ISO_BROADCASTER)
valid_chan_io_qos(const struct bt_iso_chan_io_qos * io_qos,bool is_tx)815 static bool valid_chan_io_qos(const struct bt_iso_chan_io_qos *io_qos,
816 			      bool is_tx)
817 {
818 	const size_t max_mtu = (is_tx ? CONFIG_BT_ISO_TX_MTU : CONFIG_BT_ISO_RX_MTU);
819 	const size_t max_sdu = MIN(max_mtu, BT_ISO_MAX_SDU);
820 
821 	if (io_qos->sdu > max_sdu) {
822 		LOG_DBG("sdu (%u) shall be smaller than %zu", io_qos->sdu, max_sdu);
823 		return false;
824 	}
825 
826 	if (io_qos->phy > BT_GAP_LE_PHY_CODED) {
827 		LOG_DBG("Invalid phy %u", io_qos->phy);
828 		return false;
829 	}
830 
831 	return true;
832 }
833 #endif /* CONFIG_BT_ISO_CENTRAL || CONFIG_BT_ISO_BROADCASTER */
834 
bt_iso_chan_get_tx_sync(const struct bt_iso_chan * chan,struct bt_iso_tx_info * info)835 int bt_iso_chan_get_tx_sync(const struct bt_iso_chan *chan, struct bt_iso_tx_info *info)
836 {
837 	struct bt_hci_cp_le_read_iso_tx_sync *cp;
838 	struct bt_hci_rp_le_read_iso_tx_sync *rp;
839 	struct net_buf *buf;
840 	struct net_buf *rsp = NULL;
841 	int err;
842 
843 	CHECKIF(chan == NULL) {
844 		LOG_DBG("chan is NULL");
845 		return -EINVAL;
846 	}
847 
848 	CHECKIF(chan->iso == NULL) {
849 		LOG_DBG("chan->iso is NULL");
850 		return -EINVAL;
851 	}
852 
853 	CHECKIF(info == NULL) {
854 		LOG_DBG("info is NULL");
855 		return -EINVAL;
856 	}
857 
858 	CHECKIF(chan->state != BT_ISO_STATE_CONNECTED) {
859 		return -ENOTCONN;
860 	}
861 
862 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_ISO_TX_SYNC, sizeof(*cp));
863 	if (!buf) {
864 		return -ENOMEM;
865 	}
866 
867 	cp = net_buf_add(buf, sizeof(*cp));
868 	cp->handle = sys_cpu_to_le16(chan->iso->handle);
869 
870 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_ISO_TX_SYNC, buf, &rsp);
871 	if (err) {
872 		return err;
873 	}
874 
875 	if (rsp) {
876 		rp = (struct bt_hci_rp_le_read_iso_tx_sync *)rsp->data;
877 
878 		info->ts = sys_le32_to_cpu(rp->timestamp);
879 		info->seq_num = sys_le16_to_cpu(rp->seq);
880 		info->offset = sys_get_le24(rp->offset);
881 
882 		net_buf_unref(rsp);
883 	} else {
884 		return -ENOTSUP;
885 	}
886 
887 	return 0;
888 }
889 #endif /* CONFIG_BT_ISO_UNICAST) || CONFIG_BT_ISO_BROADCASTER */
890 
891 #if defined(CONFIG_BT_ISO_UNICAST)
bt_iso_chan_disconnect(struct bt_iso_chan * chan)892 int bt_iso_chan_disconnect(struct bt_iso_chan *chan)
893 {
894 	int err;
895 
896 	CHECKIF(!chan) {
897 		LOG_DBG("Invalid parameter: chan %p", chan);
898 		return -EINVAL;
899 	}
900 
901 	CHECKIF(chan->iso == NULL) {
902 		LOG_DBG("Channel has not been initialized in a CIG");
903 		return -EINVAL;
904 	}
905 
906 	if (chan->iso->iso.acl == NULL ||
907 	    chan->state == BT_ISO_STATE_DISCONNECTED) {
908 		LOG_DBG("Channel is not connected");
909 		return -ENOTCONN;
910 	}
911 
912 	if (chan->state == BT_ISO_STATE_ENCRYPT_PENDING) {
913 		LOG_DBG("Channel already disconnected");
914 		bt_iso_chan_set_state(chan, BT_ISO_STATE_DISCONNECTED);
915 
916 		if (chan->ops->disconnected) {
917 			chan->ops->disconnected(chan,
918 						BT_HCI_ERR_LOCALHOST_TERM_CONN);
919 		}
920 
921 		return 0;
922 	}
923 
924 	if (chan->state == BT_ISO_STATE_DISCONNECTING) {
925 		LOG_DBG("Already disconnecting");
926 
927 		return -EALREADY;
928 	}
929 
930 	err = bt_conn_disconnect(chan->iso, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
931 	if (err == 0) {
932 		bt_iso_chan_set_state(chan, BT_ISO_STATE_DISCONNECTING);
933 	}
934 
935 	return err;
936 }
937 
bt_iso_cleanup_acl(struct bt_conn * iso)938 void bt_iso_cleanup_acl(struct bt_conn *iso)
939 {
940 	LOG_DBG("%p", iso);
941 
942 	if (iso->iso.acl) {
943 		bt_conn_unref(iso->iso.acl);
944 		iso->iso.acl = NULL;
945 	}
946 }
947 
store_cis_info(const struct bt_hci_evt_le_cis_established * evt,struct bt_iso_info * info)948 static void store_cis_info(const struct bt_hci_evt_le_cis_established *evt,
949 			   struct bt_iso_info *info)
950 {
951 	struct bt_iso_unicast_info *unicast_info = &info->unicast;
952 	struct bt_iso_unicast_tx_info *central = &unicast_info->central;
953 	struct bt_iso_unicast_tx_info *peripheral = &unicast_info->peripheral;
954 
955 	info->iso_interval = sys_le16_to_cpu(evt->interval);
956 	info->max_subevent = evt->nse;
957 
958 	unicast_info->cig_sync_delay = sys_get_le24(evt->cig_sync_delay);
959 	unicast_info->cis_sync_delay = sys_get_le24(evt->cis_sync_delay);
960 
961 	central->bn = evt->c_bn;
962 	central->phy = bt_get_phy(evt->c_phy);
963 	central->latency = sys_get_le16(evt->c_latency);
964 	central->max_pdu = sys_le16_to_cpu(evt->c_max_pdu);
965 	/* Transform to n * 1.25ms */
966 	central->flush_timeout = info->iso_interval * evt->c_ft;
967 
968 	peripheral->bn = evt->p_bn;
969 	peripheral->phy = bt_get_phy(evt->p_phy);
970 	peripheral->latency = sys_get_le16(evt->p_latency);
971 	peripheral->max_pdu = sys_le16_to_cpu(evt->p_max_pdu);
972 	/* Transform to n * 1.25ms */
973 	peripheral->flush_timeout = info->iso_interval * evt->p_ft;
974 }
975 
hci_le_cis_established(struct net_buf * buf)976 void hci_le_cis_established(struct net_buf *buf)
977 {
978 	struct bt_hci_evt_le_cis_established *evt = (void *)buf->data;
979 	uint16_t handle = sys_le16_to_cpu(evt->conn_handle);
980 	struct bt_conn *iso;
981 
982 	LOG_DBG("status 0x%02x handle %u", evt->status, handle);
983 
984 	/* ISO connection handles are already assigned at this point */
985 	iso = bt_conn_lookup_handle(handle);
986 	if (!iso) {
987 		LOG_ERR("No connection found for handle %u", handle);
988 		return;
989 	}
990 
991 	CHECKIF(iso->type != BT_CONN_TYPE_ISO) {
992 		LOG_DBG("Invalid connection type %u", iso->type);
993 		bt_conn_unref(iso);
994 		return;
995 	}
996 
997 	if (!evt->status) {
998 		struct bt_iso_chan_io_qos *tx;
999 		struct bt_iso_chan_io_qos *rx;
1000 		struct bt_conn_iso *iso_conn;
1001 		struct bt_iso_chan *chan;
1002 
1003 		iso_conn = &iso->iso;
1004 		chan = iso_conn->chan;
1005 
1006 		__ASSERT(chan != NULL && chan->qos != NULL, "Invalid ISO chan");
1007 
1008 		tx = chan->qos->tx;
1009 		rx = chan->qos->rx;
1010 
1011 		LOG_DBG("iso_chan %p tx %p rx %p", chan, tx, rx);
1012 
1013 		if (iso->role == BT_HCI_ROLE_PERIPHERAL) {
1014 			rx = chan->qos->rx;
1015 			tx = chan->qos->tx;
1016 
1017 			if (rx != NULL) {
1018 				rx->phy = bt_get_phy(evt->c_phy);
1019 				rx->sdu = sys_le16_to_cpu(evt->c_max_pdu);
1020 			}
1021 
1022 			if (tx != NULL) {
1023 				tx->phy = bt_get_phy(evt->p_phy);
1024 				tx->sdu = sys_le16_to_cpu(evt->p_max_pdu);
1025 			}
1026 
1027 			iso_conn->info.type = BT_ISO_CHAN_TYPE_CONNECTED;
1028 		} /* values are already set for central */
1029 
1030 		/* Verify if device can send */
1031 		iso_conn->info.can_send = false;
1032 		if (tx != NULL) {
1033 			if (iso->role == BT_HCI_ROLE_PERIPHERAL &&
1034 			    evt->p_bn > 0) {
1035 				iso_conn->info.can_send = true;
1036 			} else if (iso->role == BT_HCI_ROLE_CENTRAL &&
1037 				   evt->c_bn > 0) {
1038 				iso_conn->info.can_send = true;
1039 			}
1040 		}
1041 
1042 		/* Verify if device can recv */
1043 		iso_conn->info.can_recv = false;
1044 		if (rx != NULL) {
1045 			if (iso->role == BT_HCI_ROLE_PERIPHERAL &&
1046 			    evt->c_bn > 0) {
1047 				iso_conn->info.can_recv = true;
1048 			} else if (iso->role == BT_HCI_ROLE_CENTRAL &&
1049 				   evt->p_bn > 0) {
1050 				iso_conn->info.can_recv = true;
1051 			}
1052 		}
1053 
1054 		store_cis_info(evt, &iso_conn->info);
1055 		bt_conn_set_state(iso, BT_CONN_CONNECTED);
1056 		bt_conn_unref(iso);
1057 		return;
1058 	}
1059 
1060 	iso->err = evt->status;
1061 	bt_iso_disconnected(iso);
1062 	bt_conn_unref(iso);
1063 }
1064 
1065 #if defined(CONFIG_BT_ISO_PERIPHERAL)
bt_iso_server_register(struct bt_iso_server * server)1066 int bt_iso_server_register(struct bt_iso_server *server)
1067 {
1068 	CHECKIF(!server) {
1069 		LOG_DBG("Invalid parameter: server %p", server);
1070 		return -EINVAL;
1071 	}
1072 
1073 	/* Check if controller is ISO capable */
1074 	if (!BT_FEAT_LE_CIS_PERIPHERAL(bt_dev.le.features)) {
1075 		return -ENOTSUP;
1076 	}
1077 
1078 	if (iso_server) {
1079 		return -EADDRINUSE;
1080 	}
1081 
1082 	if (!server->accept) {
1083 		return -EINVAL;
1084 	}
1085 
1086 #if defined(CONFIG_BT_SMP)
1087 	if (server->sec_level > BT_SECURITY_L3) {
1088 		return -EINVAL;
1089 	} else if (server->sec_level < BT_SECURITY_L1) {
1090 		/* Level 0 is only applicable for BR/EDR */
1091 		server->sec_level = BT_SECURITY_L1;
1092 	}
1093 #endif /* CONFIG_BT_SMP */
1094 
1095 	LOG_DBG("%p", server);
1096 
1097 	iso_server = server;
1098 
1099 	return 0;
1100 }
1101 
bt_iso_server_unregister(struct bt_iso_server * server)1102 int bt_iso_server_unregister(struct bt_iso_server *server)
1103 {
1104 	CHECKIF(!server) {
1105 		LOG_DBG("Invalid parameter: server %p", server);
1106 		return -EINVAL;
1107 	}
1108 
1109 	if (iso_server != server) {
1110 		return -EINVAL;
1111 	}
1112 
1113 	iso_server = NULL;
1114 
1115 	return 0;
1116 }
1117 
iso_accept(struct bt_conn * acl,struct bt_conn * iso)1118 static int iso_accept(struct bt_conn *acl, struct bt_conn *iso)
1119 {
1120 	struct bt_iso_accept_info accept_info;
1121 	struct bt_iso_chan *chan;
1122 	int err;
1123 
1124 	CHECKIF(!iso || iso->type != BT_CONN_TYPE_ISO) {
1125 		LOG_DBG("Invalid parameters: iso %p iso->type %u", iso, iso ? iso->type : 0);
1126 		return -EINVAL;
1127 	}
1128 
1129 	LOG_DBG("%p", iso);
1130 
1131 	accept_info.acl = acl;
1132 	accept_info.cig_id = iso->iso.cig_id;
1133 	accept_info.cis_id = iso->iso.cis_id;
1134 
1135 	err = iso_server->accept(&accept_info, &chan);
1136 	if (err < 0) {
1137 		LOG_ERR("Server failed to accept: %d", err);
1138 		return err;
1139 	}
1140 
1141 #if defined(CONFIG_BT_SMP)
1142 	chan->required_sec_level = iso_server->sec_level;
1143 #endif /* CONFIG_BT_SMP */
1144 
1145 	bt_iso_chan_add(iso, chan);
1146 	bt_iso_chan_set_state(chan, BT_ISO_STATE_CONNECTING);
1147 
1148 	return 0;
1149 }
1150 
hci_le_reject_cis(uint16_t handle,uint8_t reason)1151 static int hci_le_reject_cis(uint16_t handle, uint8_t reason)
1152 {
1153 	struct bt_hci_cp_le_reject_cis *cp;
1154 	struct net_buf *buf;
1155 	int err;
1156 
1157 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_REJECT_CIS, sizeof(*cp));
1158 	if (!buf) {
1159 		return -ENOBUFS;
1160 	}
1161 
1162 	cp = net_buf_add(buf, sizeof(*cp));
1163 	cp->handle = sys_cpu_to_le16(handle);
1164 	cp->reason = reason;
1165 
1166 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REJECT_CIS, buf, NULL);
1167 	if (err) {
1168 		return err;
1169 	}
1170 
1171 	return 0;
1172 }
1173 
hci_le_accept_cis(uint16_t handle)1174 static int hci_le_accept_cis(uint16_t handle)
1175 {
1176 	struct bt_hci_cp_le_accept_cis *cp;
1177 	struct net_buf *buf;
1178 	int err;
1179 
1180 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_ACCEPT_CIS, sizeof(*cp));
1181 	if (!buf) {
1182 		return -ENOBUFS;
1183 	}
1184 
1185 	cp = net_buf_add(buf, sizeof(*cp));
1186 	cp->handle = sys_cpu_to_le16(handle);
1187 
1188 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ACCEPT_CIS, buf, NULL);
1189 	if (err) {
1190 		return err;
1191 	}
1192 
1193 	return 0;
1194 }
1195 
iso_server_check_security(struct bt_conn * conn)1196 static uint8_t iso_server_check_security(struct bt_conn *conn)
1197 {
1198 	if (IS_ENABLED(CONFIG_BT_CONN_DISABLE_SECURITY)) {
1199 		return BT_HCI_ERR_SUCCESS;
1200 	}
1201 
1202 #if defined(CONFIG_BT_SMP)
1203 	if (conn->sec_level >= iso_server->sec_level) {
1204 		return BT_HCI_ERR_SUCCESS;
1205 	}
1206 
1207 	return BT_HCI_ERR_INSUFFICIENT_SECURITY;
1208 #else
1209 	return BT_HCI_ERR_SUCCESS;
1210 #endif /* CONFIG_BT_SMP */
1211 }
1212 
hci_le_cis_req(struct net_buf * buf)1213 void hci_le_cis_req(struct net_buf *buf)
1214 {
1215 	struct bt_hci_evt_le_cis_req *evt = (void *)buf->data;
1216 	uint16_t acl_handle = sys_le16_to_cpu(evt->acl_handle);
1217 	uint16_t cis_handle = sys_le16_to_cpu(evt->cis_handle);
1218 	struct bt_conn *acl, *iso;
1219 	uint8_t sec_err;
1220 	int err;
1221 
1222 	LOG_DBG("acl_handle %u cis_handle %u cig_id %u cis %u", acl_handle, cis_handle, evt->cig_id,
1223 		evt->cis_id);
1224 
1225 	if (iso_server == NULL) {
1226 		LOG_DBG("No ISO server registered");
1227 		hci_le_reject_cis(cis_handle, BT_HCI_ERR_UNSPECIFIED);
1228 		return;
1229 	}
1230 
1231 	/* Lookup existing connection with same handle */
1232 	iso = bt_conn_lookup_handle(cis_handle);
1233 	if (iso) {
1234 		LOG_ERR("Invalid ISO handle %u", cis_handle);
1235 		hci_le_reject_cis(cis_handle, BT_HCI_ERR_CONN_LIMIT_EXCEEDED);
1236 		bt_conn_unref(iso);
1237 		return;
1238 	}
1239 
1240 	/* Lookup ACL connection to attach */
1241 	acl = bt_conn_lookup_handle(acl_handle);
1242 	if (!acl) {
1243 		LOG_ERR("Invalid ACL handle %u", acl_handle);
1244 		hci_le_reject_cis(cis_handle, BT_HCI_ERR_UNKNOWN_CONN_ID);
1245 		return;
1246 	}
1247 
1248 	sec_err = iso_server_check_security(acl);
1249 	if (sec_err != BT_HCI_ERR_SUCCESS) {
1250 		LOG_DBG("Insufficient security %u", sec_err);
1251 		err = hci_le_reject_cis(cis_handle, sec_err);
1252 		if (err != 0) {
1253 			LOG_ERR("Failed to reject CIS");
1254 		}
1255 
1256 		bt_conn_unref(acl);
1257 		return;
1258 	}
1259 
1260 	/* Add ISO connection */
1261 	iso = bt_conn_add_iso(acl);
1262 
1263 	bt_conn_unref(acl);
1264 
1265 	if (!iso) {
1266 		LOG_ERR("Could not create and add ISO to ACL %u", acl_handle);
1267 		hci_le_reject_cis(cis_handle,
1268 				  BT_HCI_ERR_INSUFFICIENT_RESOURCES);
1269 		return;
1270 	}
1271 
1272 	iso->iso.info.type = BT_ISO_CHAN_TYPE_CONNECTED;
1273 	iso->iso.cig_id = evt->cig_id;
1274 	iso->iso.cis_id = evt->cis_id;
1275 
1276 	/* Request application to accept */
1277 	err = iso_accept(acl, iso);
1278 	if (err) {
1279 		LOG_DBG("App rejected ISO %d", err);
1280 		bt_iso_cleanup_acl(iso);
1281 		bt_conn_unref(iso);
1282 		hci_le_reject_cis(cis_handle,
1283 				  BT_HCI_ERR_INSUFFICIENT_RESOURCES);
1284 		return;
1285 	}
1286 
1287 	iso->handle = cis_handle;
1288 	iso->role = BT_HCI_ROLE_PERIPHERAL;
1289 	bt_conn_set_state(iso, BT_CONN_CONNECTING);
1290 
1291 	err = hci_le_accept_cis(cis_handle);
1292 	if (err) {
1293 		bt_iso_cleanup_acl(iso);
1294 		bt_conn_unref(iso);
1295 		hci_le_reject_cis(cis_handle,
1296 				  BT_HCI_ERR_INSUFFICIENT_RESOURCES);
1297 		return;
1298 	}
1299 }
1300 
bt_conn_add_iso(struct bt_conn * acl)1301 static struct bt_conn *bt_conn_add_iso(struct bt_conn *acl)
1302 {
1303 	struct bt_conn *iso = iso_new();
1304 
1305 	if (iso == NULL) {
1306 		LOG_ERR("Unable to allocate ISO connection");
1307 		return NULL;
1308 	}
1309 
1310 	iso->iso.acl = bt_conn_ref(acl);
1311 
1312 	return iso;
1313 }
1314 #endif /* CONFIG_BT_ISO_PERIPHERAL */
1315 
1316 #if defined(CONFIG_BT_ISO_CENTRAL)
hci_le_remove_iso_data_path(struct bt_conn * iso,uint8_t dir)1317 static int hci_le_remove_iso_data_path(struct bt_conn *iso, uint8_t dir)
1318 {
1319 	struct bt_hci_cp_le_remove_iso_path *cp;
1320 	struct bt_hci_rp_le_remove_iso_path *rp;
1321 	struct net_buf *buf, *rsp;
1322 	int err;
1323 
1324 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_REMOVE_ISO_PATH, sizeof(*cp));
1325 	if (!buf) {
1326 		return -ENOBUFS;
1327 	}
1328 
1329 	cp = net_buf_add(buf, sizeof(*cp));
1330 	cp->handle = iso->handle;
1331 	cp->path_dir = dir;
1332 
1333 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REMOVE_ISO_PATH, buf, &rsp);
1334 	if (err) {
1335 		return err;
1336 	}
1337 
1338 	rp = (void *)rsp->data;
1339 	if (rp->status || (sys_le16_to_cpu(rp->handle) != iso->handle)) {
1340 		err = -EIO;
1341 	}
1342 
1343 	net_buf_unref(rsp);
1344 
1345 	return err;
1346 }
1347 
bt_iso_remove_data_path(struct bt_conn * iso)1348 static void bt_iso_remove_data_path(struct bt_conn *iso)
1349 {
1350 	enum bt_iso_chan_type type = iso->iso.info.type;
1351 
1352 	LOG_DBG("%p", iso);
1353 
1354 	/* TODO: Removing the ISO data path is never used for broadcast:
1355 	 * Remove the following broadcast implementation?
1356 	 */
1357 	if ((IS_ENABLED(CONFIG_BT_ISO_BROADCASTER) &&
1358 		type == BT_ISO_CHAN_TYPE_BROADCASTER) ||
1359 	    (IS_ENABLED(CONFIG_BT_ISO_SYNC_RECEIVER) &&
1360 		type == BT_ISO_CHAN_TYPE_SYNC_RECEIVER)) {
1361 		struct bt_iso_chan *chan;
1362 		struct bt_iso_chan_io_qos *tx_qos;
1363 		uint8_t dir;
1364 
1365 		chan = iso_chan(iso);
1366 		if (chan == NULL) {
1367 			return;
1368 		}
1369 
1370 		tx_qos = chan->qos->tx;
1371 
1372 		/* Only remove one data path for BIS as per the spec */
1373 		if (tx_qos) {
1374 			dir = BIT(BT_HCI_DATAPATH_DIR_HOST_TO_CTLR);
1375 		} else {
1376 			dir = BIT(BT_HCI_DATAPATH_DIR_CTLR_TO_HOST);
1377 		}
1378 
1379 		(void)hci_le_remove_iso_data_path(iso, dir);
1380 	} else if (IS_ENABLED(CONFIG_BT_ISO_UNICAST) &&
1381 		   type == BT_ISO_CHAN_TYPE_CONNECTED) {
1382 		/* Remove both directions for CIS*/
1383 
1384 		/* TODO: Check which has been setup first to avoid removing
1385 		 * data paths that are not setup
1386 		 */
1387 		(void)hci_le_remove_iso_data_path(iso, BIT(BT_HCI_DATAPATH_DIR_HOST_TO_CTLR));
1388 		(void)hci_le_remove_iso_data_path(iso, BIT(BT_HCI_DATAPATH_DIR_CTLR_TO_HOST));
1389 	} else {
1390 		__ASSERT(false, "Invalid iso.type: %u", type);
1391 	}
1392 }
1393 
valid_chan_qos(const struct bt_iso_chan_qos * qos)1394 static bool valid_chan_qos(const struct bt_iso_chan_qos *qos)
1395 {
1396 	if (qos->rx != NULL) {
1397 		if (!valid_chan_io_qos(qos->rx, false)) {
1398 			LOG_DBG("Invalid rx qos");
1399 			return false;
1400 		}
1401 	} else if (qos->tx == NULL) {
1402 		LOG_DBG("Both rx and tx qos are NULL");
1403 		return false;
1404 	}
1405 
1406 	if (qos->tx != NULL) {
1407 		if (!valid_chan_io_qos(qos->tx, true)) {
1408 			LOG_DBG("Invalid tx qos");
1409 			return false;
1410 		}
1411 	}
1412 
1413 	return true;
1414 }
1415 
hci_le_remove_cig(uint8_t cig_id)1416 static int hci_le_remove_cig(uint8_t cig_id)
1417 {
1418 	struct bt_hci_cp_le_remove_cig *req;
1419 	struct net_buf *buf;
1420 
1421 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_REMOVE_CIG, sizeof(*req));
1422 	if (!buf) {
1423 		return -ENOBUFS;
1424 	}
1425 
1426 	req = net_buf_add(buf, sizeof(*req));
1427 
1428 	memset(req, 0, sizeof(*req));
1429 
1430 	req->cig_id = cig_id;
1431 
1432 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REMOVE_CIG, buf, NULL);
1433 }
1434 
hci_le_set_cig_params(const struct bt_iso_cig * cig,const struct bt_iso_cig_param * param)1435 static struct net_buf *hci_le_set_cig_params(const struct bt_iso_cig *cig,
1436 					     const struct bt_iso_cig_param *param)
1437 {
1438 	struct bt_hci_cp_le_set_cig_params *req;
1439 	struct bt_hci_cis_params *cis_param;
1440 	struct net_buf *buf;
1441 	struct net_buf *rsp;
1442 	int i, err;
1443 
1444 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_CIG_PARAMS,
1445 				sizeof(*req) + sizeof(*cis_param) * param->num_cis);
1446 	if (!buf) {
1447 		return NULL;
1448 	}
1449 
1450 	req = net_buf_add(buf, sizeof(*req));
1451 
1452 	memset(req, 0, sizeof(*req));
1453 
1454 	req->cig_id = cig->id;
1455 	req->c_latency = sys_cpu_to_le16(param->latency);
1456 	req->p_latency = sys_cpu_to_le16(param->latency);
1457 	sys_put_le24(param->interval, req->c_interval);
1458 	sys_put_le24(param->interval, req->p_interval);
1459 
1460 	req->sca = param->sca;
1461 	req->packing = param->packing;
1462 	req->framing = param->framing;
1463 	req->num_cis = param->num_cis;
1464 
1465 	LOG_DBG("id %u, latency %u, interval %u, sca %u, packing %u, framing %u, num_cis %u",
1466 		cig->id, param->latency, param->interval, param->sca, param->packing,
1467 		param->framing, param->num_cis);
1468 
1469 	/* Program the cis parameters */
1470 	for (i = 0; i < param->num_cis; i++) {
1471 		struct bt_iso_chan *cis = param->cis_channels[i];
1472 		struct bt_iso_chan_qos *qos = cis->qos;
1473 
1474 		cis_param = net_buf_add(buf, sizeof(*cis_param));
1475 
1476 		memset(cis_param, 0, sizeof(*cis_param));
1477 
1478 		cis_param->cis_id = cis->iso->iso.cis_id;
1479 
1480 		if (!qos->tx && !qos->rx) {
1481 			LOG_ERR("Both TX and RX QoS are disabled");
1482 			net_buf_unref(buf);
1483 			return NULL;
1484 		}
1485 
1486 		if (!qos->tx) {
1487 			/* Use RX PHY if TX is not set (disabled)
1488 			 * to avoid setting invalid values
1489 			 */
1490 			cis_param->c_phy = qos->rx->phy;
1491 		} else {
1492 			cis_param->c_sdu = sys_cpu_to_le16(qos->tx->sdu);
1493 			cis_param->c_phy = qos->tx->phy;
1494 			cis_param->c_rtn = qos->tx->rtn;
1495 		}
1496 
1497 		if (!qos->rx) {
1498 			/* Use TX PHY if RX is not set (disabled)
1499 			 * to avoid setting invalid values
1500 			 */
1501 			cis_param->p_phy = qos->tx->phy;
1502 		} else {
1503 			cis_param->p_sdu = sys_cpu_to_le16(qos->rx->sdu);
1504 			cis_param->p_phy = qos->rx->phy;
1505 			cis_param->p_rtn = qos->rx->rtn;
1506 		}
1507 
1508 		LOG_DBG("[%d]: id %u, c_phy %u, c_sdu %u, c_rtn %u, p_phy %u, p_sdu %u, p_rtn %u",
1509 			i, cis_param->cis_id, cis_param->c_phy, cis_param->c_sdu, cis_param->c_rtn,
1510 			cis_param->p_phy, cis_param->p_sdu, cis_param->p_rtn);
1511 	}
1512 
1513 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_CIG_PARAMS, buf, &rsp);
1514 	if (err) {
1515 		return NULL;
1516 	}
1517 
1518 	return rsp;
1519 }
1520 
get_cig(const struct bt_iso_chan * iso_chan)1521 static struct bt_iso_cig *get_cig(const struct bt_iso_chan *iso_chan)
1522 {
1523 	if (iso_chan->iso == NULL) {
1524 		return NULL;
1525 	}
1526 
1527 	__ASSERT(iso_chan->iso->iso.cig_id < ARRAY_SIZE(cigs),
1528 		 "Invalid cig_id %u", iso_chan->iso->iso.cig_id);
1529 
1530 	return &cigs[iso_chan->iso->iso.cig_id];
1531 }
1532 
get_free_cig(void)1533 static struct bt_iso_cig *get_free_cig(void)
1534 {
1535 	/* We can use the index in the `cigs` array as CIG ID */
1536 
1537 	for (size_t i = 0; i < ARRAY_SIZE(cigs); i++) {
1538 		if (cigs[i].state == BT_ISO_CIG_STATE_IDLE) {
1539 			cigs[i].state = BT_ISO_CIG_STATE_CONFIGURED;
1540 			cigs[i].id = i;
1541 			sys_slist_init(&cigs[i].cis_channels);
1542 			return &cigs[i];
1543 		}
1544 	}
1545 
1546 	LOG_DBG("Could not allocate any more CIGs");
1547 
1548 	return NULL;
1549 }
1550 
cis_is_in_cig(const struct bt_iso_cig * cig,const struct bt_iso_chan * cis)1551 static bool cis_is_in_cig(const struct bt_iso_cig *cig,
1552 			  const struct bt_iso_chan *cis)
1553 {
1554 	return cig->id == cis->iso->iso.cig_id;
1555 }
1556 
cig_init_cis(struct bt_iso_cig * cig,const struct bt_iso_cig_param * param)1557 static int cig_init_cis(struct bt_iso_cig *cig,
1558 			const struct bt_iso_cig_param *param)
1559 {
1560 	for (uint8_t i = 0; i < param->num_cis; i++) {
1561 		struct bt_iso_chan *cis = param->cis_channels[i];
1562 
1563 		if (cis->iso == NULL) {
1564 			struct bt_conn_iso *iso_conn;
1565 
1566 			cis->iso = iso_new();
1567 			if (cis->iso == NULL) {
1568 				LOG_ERR("Unable to allocate CIS connection");
1569 				return -ENOMEM;
1570 			}
1571 			iso_conn = &cis->iso->iso;
1572 
1573 			iso_conn->cig_id = cig->id;
1574 			iso_conn->info.type = BT_ISO_CHAN_TYPE_CONNECTED;
1575 			iso_conn->cis_id = cig->num_cis++;
1576 
1577 			bt_iso_chan_add(cis->iso, cis);
1578 
1579 			sys_slist_append(&cig->cis_channels, &cis->node);
1580 		} /* else already initialized */
1581 	}
1582 
1583 	return 0;
1584 }
1585 
cleanup_cig(struct bt_iso_cig * cig)1586 static void cleanup_cig(struct bt_iso_cig *cig)
1587 {
1588 	struct bt_iso_chan *cis, *tmp;
1589 
1590 	SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&cig->cis_channels, cis, tmp, node) {
1591 		if (cis->iso != NULL) {
1592 			bt_conn_unref(cis->iso);
1593 			cis->iso = NULL;
1594 		}
1595 
1596 		sys_slist_remove(&cig->cis_channels, NULL, &cis->node);
1597 	}
1598 
1599 	memset(cig, 0, sizeof(*cig));
1600 }
1601 
valid_cig_param(const struct bt_iso_cig_param * param)1602 static bool valid_cig_param(const struct bt_iso_cig_param *param)
1603 {
1604 	if (param == NULL) {
1605 		return false;
1606 	}
1607 
1608 	for (uint8_t i = 0; i < param->num_cis; i++) {
1609 		struct bt_iso_chan *cis = param->cis_channels[i];
1610 
1611 		if (cis == NULL) {
1612 			LOG_DBG("cis_channels[%d]: NULL channel", i);
1613 			return false;
1614 		}
1615 
1616 		if (cis->iso != NULL) {
1617 			LOG_DBG("cis_channels[%d]: already allocated", i);
1618 			return false;
1619 		}
1620 
1621 		if (!valid_chan_qos(cis->qos)) {
1622 			LOG_DBG("cis_channels[%d]: Invalid QOS", i);
1623 			return false;
1624 		}
1625 
1626 		for (uint8_t j = 0; j < i; j++) {
1627 			if (cis == param->cis_channels[j]) {
1628 				LOG_DBG("ISO %p duplicated at index %u and %u", cis, i, j);
1629 				return false;
1630 			}
1631 		}
1632 	}
1633 
1634 	if (param->framing != BT_ISO_FRAMING_UNFRAMED &&
1635 	    param->framing != BT_ISO_FRAMING_FRAMED) {
1636 		LOG_DBG("Invalid framing parameter: %u", param->framing);
1637 		return false;
1638 	}
1639 
1640 	if (param->packing != BT_ISO_PACKING_SEQUENTIAL &&
1641 	    param->packing != BT_ISO_PACKING_INTERLEAVED) {
1642 		LOG_DBG("Invalid packing parameter: %u", param->packing);
1643 		return false;
1644 	}
1645 
1646 	if (param->num_cis > BT_ISO_MAX_GROUP_ISO_COUNT ||
1647 	    param->num_cis > CONFIG_BT_ISO_MAX_CHAN) {
1648 		LOG_DBG("num_cis (%u) shall be lower than: %u", param->num_cis,
1649 			MAX(CONFIG_BT_ISO_MAX_CHAN, BT_ISO_MAX_GROUP_ISO_COUNT));
1650 		return false;
1651 	}
1652 
1653 	if (param->interval < BT_ISO_SDU_INTERVAL_MIN ||
1654 	    param->interval > BT_ISO_SDU_INTERVAL_MAX) {
1655 		LOG_DBG("Invalid interval: %u", param->interval);
1656 		return false;
1657 	}
1658 
1659 	if (param->latency < BT_ISO_LATENCY_MIN ||
1660 	    param->latency > BT_ISO_LATENCY_MAX) {
1661 		LOG_DBG("Invalid latency: %u", param->latency);
1662 		return false;
1663 	}
1664 
1665 	return true;
1666 }
1667 
bt_iso_cig_create(const struct bt_iso_cig_param * param,struct bt_iso_cig ** out_cig)1668 int bt_iso_cig_create(const struct bt_iso_cig_param *param,
1669 		      struct bt_iso_cig **out_cig)
1670 {
1671 	int err;
1672 	struct net_buf *rsp;
1673 	struct bt_iso_cig *cig;
1674 	struct bt_hci_rp_le_set_cig_params *cig_rsp;
1675 	struct bt_iso_chan *cis;
1676 	int i;
1677 
1678 	CHECKIF(out_cig == NULL) {
1679 		LOG_DBG("out_cig is NULL");
1680 		return -EINVAL;
1681 	}
1682 
1683 	*out_cig = NULL;
1684 
1685 	/* Check if controller is ISO capable as a central */
1686 	if (!BT_FEAT_LE_CIS_CENTRAL(bt_dev.le.features)) {
1687 		return -ENOTSUP;
1688 	}
1689 
1690 	/* TBD: Should we allow creating empty CIGs? */
1691 	CHECKIF(param->cis_channels == NULL) {
1692 		LOG_DBG("NULL CIS channels");
1693 		return -EINVAL;
1694 	}
1695 
1696 	CHECKIF(param->num_cis == 0) {
1697 		LOG_DBG("Invalid number of CIS %u", param->num_cis);
1698 		return -EINVAL;
1699 	}
1700 
1701 	CHECKIF(!valid_cig_param(param)) {
1702 		LOG_DBG("Invalid CIG params");
1703 		return -EINVAL;
1704 	}
1705 
1706 	cig = get_free_cig();
1707 
1708 	if (!cig) {
1709 		return -ENOMEM;
1710 	}
1711 
1712 	err = cig_init_cis(cig, param);
1713 	if (err) {
1714 		LOG_DBG("Could not init CIS %d", err);
1715 		cleanup_cig(cig);
1716 		return err;
1717 	}
1718 
1719 	rsp = hci_le_set_cig_params(cig, param);
1720 	if (rsp == NULL) {
1721 		LOG_WRN("Unexpected response to hci_le_set_cig_params");
1722 		err = -EIO;
1723 		cleanup_cig(cig);
1724 		return err;
1725 	}
1726 
1727 	cig_rsp = (void *)rsp->data;
1728 
1729 	if (rsp->len < sizeof(cig_rsp) ||
1730 	    cig_rsp->num_handles != param->num_cis) {
1731 		LOG_WRN("Unexpected response to hci_le_set_cig_params");
1732 		err = -EIO;
1733 		net_buf_unref(rsp);
1734 		cleanup_cig(cig);
1735 		return err;
1736 	}
1737 
1738 	i = 0;
1739 	SYS_SLIST_FOR_EACH_CONTAINER(&cig->cis_channels, cis, node) {
1740 		const uint16_t handle = cig_rsp->handle[i++];
1741 
1742 		/* Assign the connection handle */
1743 		cis->iso->handle = sys_le16_to_cpu(handle);
1744 	}
1745 
1746 	net_buf_unref(rsp);
1747 
1748 	*out_cig = cig;
1749 
1750 	return err;
1751 }
1752 
restore_cig(struct bt_iso_cig * cig,uint8_t existing_num_cis)1753 static void restore_cig(struct bt_iso_cig *cig, uint8_t existing_num_cis)
1754 {
1755 	struct bt_iso_chan *cis, *tmp;
1756 
1757 	SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&cig->cis_channels, cis, tmp, node) {
1758 		/* Remove all newly added by comparing the cis_id to the number
1759 		 * of CIS that was previously added before
1760 		 * bt_iso_cig_reconfigure was called
1761 		 */
1762 		if (cis->iso != NULL &&
1763 		    cis->iso->iso.cis_id >= existing_num_cis) {
1764 			bt_conn_unref(cis->iso);
1765 			cis->iso = NULL;
1766 
1767 			sys_slist_remove(&cig->cis_channels, NULL, &cis->node);
1768 			cig->num_cis--;
1769 		}
1770 	}
1771 }
1772 
1773 
bt_iso_cig_reconfigure(struct bt_iso_cig * cig,const struct bt_iso_cig_param * param)1774 int bt_iso_cig_reconfigure(struct bt_iso_cig *cig,
1775 			   const struct bt_iso_cig_param *param)
1776 {
1777 	struct bt_hci_rp_le_set_cig_params *cig_rsp;
1778 	uint8_t existing_num_cis;
1779 	struct bt_iso_chan *cis;
1780 	struct net_buf *rsp;
1781 	int err;
1782 	int i;
1783 
1784 	CHECKIF(cig == NULL) {
1785 		LOG_DBG("cig is NULL");
1786 		return -EINVAL;
1787 	}
1788 
1789 	if (cig->state != BT_ISO_CIG_STATE_CONFIGURED) {
1790 		LOG_DBG("Invalid CIG state: %u", cig->state);
1791 		return -EINVAL;
1792 	}
1793 
1794 	CHECKIF(!valid_cig_param(param)) {
1795 		LOG_DBG("Invalid CIG params");
1796 		return -EINVAL;
1797 	}
1798 
1799 	for (uint8_t i = 0; i < param->num_cis; i++) {
1800 		struct bt_iso_chan *cis = param->cis_channels[i];
1801 
1802 		if (cis->iso != NULL && !cis_is_in_cig(cig, cis)) {
1803 			LOG_DBG("Cannot reconfigure other CIG's (id 0x%02X) CIS "
1804 			       "with this CIG (id 0x%02X)",
1805 			       cis->iso->iso.cig_id, cig->id);
1806 			return -EINVAL;
1807 		}
1808 	}
1809 
1810 	/* Used to restore CIG in case of error */
1811 	existing_num_cis = cig->num_cis;
1812 
1813 	err = cig_init_cis(cig, param);
1814 	if (err != 0) {
1815 		LOG_DBG("Could not init CIS %d", err);
1816 		restore_cig(cig, existing_num_cis);
1817 		return err;
1818 	}
1819 
1820 	rsp = hci_le_set_cig_params(cig, param);
1821 	if (rsp == NULL) {
1822 		LOG_WRN("Unexpected response to hci_le_set_cig_params");
1823 		err = -EIO;
1824 		restore_cig(cig, existing_num_cis);
1825 		return err;
1826 	}
1827 
1828 	cig_rsp = (void *)rsp->data;
1829 
1830 	if (rsp->len < sizeof(cig_rsp) ||
1831 	    cig_rsp->num_handles != param->num_cis) {
1832 		LOG_WRN("Unexpected response to hci_le_set_cig_params");
1833 		err = -EIO;
1834 		net_buf_unref(rsp);
1835 		restore_cig(cig, existing_num_cis);
1836 		return err;
1837 	}
1838 
1839 	i = 0;
1840 	SYS_SLIST_FOR_EACH_CONTAINER(&cig->cis_channels, cis, node) {
1841 		const uint16_t handle = cig_rsp->handle[i++];
1842 
1843 		/* Assign the connection handle */
1844 		cis->iso->handle = sys_le16_to_cpu(handle);
1845 	}
1846 
1847 	net_buf_unref(rsp);
1848 
1849 	return err;
1850 }
1851 
bt_iso_cig_terminate(struct bt_iso_cig * cig)1852 int bt_iso_cig_terminate(struct bt_iso_cig *cig)
1853 {
1854 	int err;
1855 
1856 	CHECKIF(cig == NULL) {
1857 		LOG_DBG("cig is NULL");
1858 		return -EINVAL;
1859 	}
1860 
1861 	if (cig->state != BT_ISO_CIG_STATE_INACTIVE &&
1862 	    cig->state != BT_ISO_CIG_STATE_CONFIGURED) {
1863 		LOG_DBG("Invalid CIG state: %u", cig->state);
1864 		return -EINVAL;
1865 	}
1866 
1867 	err = hci_le_remove_cig(cig->id);
1868 	if (err != 0) {
1869 		LOG_DBG("Failed to terminate CIG: %d", err);
1870 		return err;
1871 	}
1872 
1873 	cleanup_cig(cig);
1874 
1875 	return 0;
1876 }
1877 
bt_iso_security_changed(struct bt_conn * acl,uint8_t hci_status)1878 void bt_iso_security_changed(struct bt_conn *acl, uint8_t hci_status)
1879 {
1880 	struct bt_iso_connect_param param[CONFIG_BT_ISO_MAX_CHAN];
1881 	size_t param_count;
1882 	int err;
1883 
1884 	/* The peripheral does not accept any ISO requests if security is
1885 	 * insufficient, so we only need to handle central here.
1886 	 * BT_ISO_STATE_ENCRYPT_PENDING is only set by the central.
1887 	 */
1888 	if (!IS_ENABLED(CONFIG_BT_CENTRAL) ||
1889 	    acl->role != BT_CONN_ROLE_CENTRAL) {
1890 		return;
1891 	}
1892 
1893 	param_count = 0;
1894 	for (size_t i = 0; i < ARRAY_SIZE(iso_conns); i++) {
1895 		struct bt_conn *iso = &iso_conns[i];
1896 		struct bt_iso_chan *iso_chan;
1897 
1898 		if (iso == NULL || iso->iso.acl != acl) {
1899 			continue;
1900 		}
1901 
1902 		iso_chan = iso_chan(iso);
1903 		if (iso_chan->state != BT_ISO_STATE_ENCRYPT_PENDING) {
1904 			continue;
1905 		}
1906 
1907 		bt_iso_chan_set_state(iso_chan, BT_ISO_STATE_DISCONNECTED);
1908 
1909 		if (hci_status == BT_HCI_ERR_SUCCESS) {
1910 			param[param_count].acl = acl;
1911 			param[param_count].iso_chan = iso_chan;
1912 			param_count++;
1913 		} else {
1914 			LOG_DBG("Failed to encrypt ACL %p for ISO %p: %u", acl, iso, hci_status);
1915 
1916 			/* We utilize the disconnected callback to make the
1917 			 * upper layers aware of the error
1918 			 */
1919 			if (iso_chan->ops->disconnected) {
1920 				iso_chan->ops->disconnected(iso_chan,
1921 							    hci_status);
1922 			}
1923 		}
1924 	}
1925 
1926 	if (param_count == 0) {
1927 		/* Nothing to do for ISO. This happens if security is changed,
1928 		 * but no ISO channels were pending encryption.
1929 		 */
1930 		return;
1931 	}
1932 
1933 	err = hci_le_create_cis(param, param_count);
1934 	if (err != 0) {
1935 		LOG_ERR("Failed to connect CISes: %d", err);
1936 
1937 		for (size_t i = 0; i < param_count; i++) {
1938 			struct bt_iso_chan *iso_chan = param[i].iso_chan;
1939 
1940 			/* We utilize the disconnected callback to make the
1941 			 * upper layers aware of the error
1942 			 */
1943 			if (iso_chan->ops->disconnected) {
1944 				iso_chan->ops->disconnected(iso_chan,
1945 							    hci_status);
1946 			}
1947 		}
1948 
1949 		return;
1950 	}
1951 
1952 	/* Set connection states */
1953 	for (size_t i = 0; i < param_count; i++) {
1954 		struct bt_iso_chan *iso_chan = param[i].iso_chan;
1955 		struct bt_iso_cig *cig = get_cig(iso_chan);
1956 
1957 		__ASSERT(cig != NULL, "CIG was NULL");
1958 		cig->state = BT_ISO_CIG_STATE_ACTIVE;
1959 
1960 		bt_conn_set_state(iso_chan->iso, BT_CONN_CONNECTING);
1961 		bt_iso_chan_set_state(iso_chan, BT_ISO_STATE_CONNECTING);
1962 	}
1963 }
1964 
hci_le_create_cis(const struct bt_iso_connect_param * param,size_t count)1965 static int hci_le_create_cis(const struct bt_iso_connect_param *param,
1966 			     size_t count)
1967 {
1968 	struct bt_hci_cis *cis;
1969 	struct bt_hci_cp_le_create_cis *req;
1970 	struct net_buf *buf;
1971 
1972 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CIS,
1973 				sizeof(*req) + sizeof(*cis) * count);
1974 	if (!buf) {
1975 		return -ENOBUFS;
1976 	}
1977 
1978 	req = net_buf_add(buf, sizeof(*req));
1979 
1980 	memset(req, 0, sizeof(*req));
1981 
1982 	/* Program the cis parameters */
1983 	for (size_t i = 0; i < count; i++) {
1984 		struct bt_iso_chan *iso_chan = param[i].iso_chan;
1985 
1986 		if (iso_chan->state == BT_ISO_STATE_ENCRYPT_PENDING) {
1987 			continue;
1988 		}
1989 
1990 		cis = net_buf_add(buf, sizeof(*cis));
1991 
1992 		memset(cis, 0, sizeof(*cis));
1993 
1994 		cis->cis_handle = sys_cpu_to_le16(param[i].iso_chan->iso->handle);
1995 		cis->acl_handle = sys_cpu_to_le16(param[i].acl->handle);
1996 		req->num_cis++;
1997 	}
1998 
1999 	/* If all CIS are pending for security, do nothing,
2000 	 * but return a recognizable return value
2001 	 */
2002 	if (req->num_cis == 0) {
2003 		net_buf_unref(buf);
2004 
2005 		return -ECANCELED;
2006 	}
2007 
2008 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CIS, buf, NULL);
2009 }
2010 
2011 #if defined(CONFIG_BT_SMP)
iso_chan_connect_security(const struct bt_iso_connect_param * param,size_t count)2012 static int iso_chan_connect_security(const struct bt_iso_connect_param *param,
2013 				     size_t count)
2014 {
2015 	/* conn_idx_handled is an array of booleans for which conn indexes
2016 	 * already have been used to call bt_conn_set_security.
2017 	 * Using indexes avoids looping the array when checking if it has been
2018 	 * handled.
2019 	 */
2020 	bool conn_idx_handled[CONFIG_BT_MAX_CONN];
2021 
2022 	memset(conn_idx_handled, false, sizeof(conn_idx_handled));
2023 	for (size_t i = 0; i < count; i++) {
2024 		struct bt_iso_chan *iso_chan = param[i].iso_chan;
2025 		struct bt_conn *acl = param[i].acl;
2026 		uint8_t conn_idx = bt_conn_index(acl);
2027 
2028 		if (acl->sec_level < iso_chan->required_sec_level) {
2029 			if (!conn_idx_handled[conn_idx]) {
2030 				int err;
2031 
2032 				err = bt_conn_set_security(acl,
2033 							   iso_chan->required_sec_level);
2034 				if (err != 0) {
2035 					LOG_DBG("[%zu]: Failed to set security: %d", i, err);
2036 
2037 					/* Restore states */
2038 					for (size_t j = 0; j < i; j++) {
2039 						iso_chan = param[j].iso_chan;
2040 
2041 						bt_iso_cleanup_acl(iso_chan->iso);
2042 						bt_iso_chan_set_state(iso_chan,
2043 								      BT_ISO_STATE_DISCONNECTED);
2044 					}
2045 
2046 					return err;
2047 				}
2048 
2049 				conn_idx_handled[conn_idx] = true;
2050 			}
2051 
2052 			iso_chan->iso->iso.acl = bt_conn_ref(acl);
2053 			bt_iso_chan_set_state(iso_chan, BT_ISO_STATE_ENCRYPT_PENDING);
2054 		}
2055 	}
2056 
2057 	return 0;
2058 }
2059 #endif /* CONFIG_BT_SMP */
2060 
iso_chans_connecting(void)2061 static bool iso_chans_connecting(void)
2062 {
2063 	for (size_t i = 0U; i < ARRAY_SIZE(iso_conns); i++) {
2064 		const struct bt_conn *iso = &iso_conns[i];
2065 		const struct bt_iso_chan *iso_chan;
2066 
2067 		if (iso == NULL ||
2068 		    iso->iso.info.type != BT_ISO_CHAN_TYPE_CONNECTED) {
2069 			continue;
2070 		}
2071 
2072 		iso_chan = iso_chan(iso);
2073 		if (iso_chan->state == BT_ISO_STATE_CONNECTING ||
2074 		    iso_chan->state == BT_ISO_STATE_ENCRYPT_PENDING) {
2075 			return true;
2076 		}
2077 	}
2078 
2079 	return false;
2080 }
2081 
bt_iso_chan_connect(const struct bt_iso_connect_param * param,size_t count)2082 int bt_iso_chan_connect(const struct bt_iso_connect_param *param, size_t count)
2083 {
2084 	int err;
2085 
2086 	CHECKIF(param == NULL) {
2087 		LOG_DBG("param is NULL");
2088 		return -EINVAL;
2089 	}
2090 
2091 	CHECKIF(count == 0) {
2092 		LOG_DBG("Invalid count %zu", count);
2093 		return -EINVAL;
2094 	}
2095 
2096 	CHECKIF(count > CONFIG_BT_ISO_MAX_CHAN) {
2097 		return -EINVAL;
2098 	}
2099 
2100 	/* Validate input */
2101 	for (size_t i = 0; i < count; i++) {
2102 		CHECKIF(param[i].iso_chan == NULL) {
2103 			LOG_DBG("[%zu]: Invalid iso (%p)", i, param[i].iso_chan);
2104 			return -EINVAL;
2105 		}
2106 
2107 		CHECKIF(param[i].acl == NULL) {
2108 			LOG_DBG("[%zu]: Invalid acl (%p)", i, param[i].acl);
2109 			return -EINVAL;
2110 		}
2111 
2112 		CHECKIF((param[i].acl->type & BT_CONN_TYPE_LE) == 0) {
2113 			LOG_DBG("[%zu]: acl type (%u) shall be an LE connection", i,
2114 				param[i].acl->type);
2115 			return -EINVAL;
2116 		}
2117 
2118 		if (param[i].iso_chan->iso == NULL) {
2119 			LOG_DBG("[%zu]: ISO has not been initialized in a CIG", i);
2120 			return -EINVAL;
2121 		}
2122 
2123 		if (param[i].iso_chan->state != BT_ISO_STATE_DISCONNECTED) {
2124 			LOG_DBG("[%zu]: ISO is not in the BT_ISO_STATE_DISCONNECTED state: %u", i,
2125 				param[i].iso_chan->state);
2126 			return -EINVAL;
2127 		}
2128 	}
2129 
2130 	if (iso_chans_connecting()) {
2131 		LOG_DBG("There are pending ISO connections");
2132 		return -EBUSY;
2133 	}
2134 
2135 #if defined(CONFIG_BT_SMP)
2136 	/* Check for and initiate security for all channels that have
2137 	 * requested encryption if the ACL link is not already secured
2138 	 */
2139 	err = iso_chan_connect_security(param, count);
2140 	if (err != 0) {
2141 		LOG_DBG("Failed to initate security for all CIS: %d", err);
2142 		return err;
2143 	}
2144 #endif /* CONFIG_BT_SMP */
2145 
2146 	err = hci_le_create_cis(param, count);
2147 	if (err == -ECANCELED) {
2148 		LOG_DBG("All channels are pending on security");
2149 
2150 		return 0;
2151 	} else if (err != 0) {
2152 		LOG_DBG("Failed to connect CISes: %d", err);
2153 
2154 		return err;
2155 	}
2156 
2157 	/* Set connection states */
2158 	for (size_t i = 0; i < count; i++) {
2159 		struct bt_iso_chan *iso_chan = param[i].iso_chan;
2160 		struct bt_iso_cig *cig;
2161 
2162 		if (iso_chan->state == BT_ISO_STATE_ENCRYPT_PENDING) {
2163 			continue;
2164 		}
2165 
2166 		iso_chan->iso->iso.acl = bt_conn_ref(param[i].acl);
2167 		bt_conn_set_state(iso_chan->iso, BT_CONN_CONNECTING);
2168 		bt_iso_chan_set_state(iso_chan, BT_ISO_STATE_CONNECTING);
2169 
2170 		cig = get_cig(iso_chan);
2171 		__ASSERT(cig != NULL, "CIG was NULL");
2172 		cig->state = BT_ISO_CIG_STATE_ACTIVE;
2173 	}
2174 
2175 	return 0;
2176 }
2177 #endif /* CONFIG_BT_ISO_CENTRAL */
2178 #endif /* CONFIG_BT_ISO_UNICAST */
2179 
2180 #if defined(CONFIG_BT_ISO_BROADCAST)
lookup_big_by_handle(uint8_t big_handle)2181 static struct bt_iso_big *lookup_big_by_handle(uint8_t big_handle)
2182 {
2183 	return &bigs[big_handle];
2184 }
2185 
get_free_big(void)2186 static struct bt_iso_big *get_free_big(void)
2187 {
2188 	/* We can use the index in the `bigs` array as BIG handles, for both
2189 	 * broadcaster and receiver (even if the device is both!)
2190 	 */
2191 
2192 	for (size_t i = 0; i < ARRAY_SIZE(bigs); i++) {
2193 		if (!atomic_test_and_set_bit(bigs[i].flags, BT_BIG_INITIALIZED)) {
2194 			bigs[i].handle = i;
2195 			sys_slist_init(&bigs[i].bis_channels);
2196 			return &bigs[i];
2197 		}
2198 	}
2199 
2200 	LOG_DBG("Could not allocate any more BIGs");
2201 
2202 	return NULL;
2203 }
2204 
big_lookup_flag(int bit)2205 static struct bt_iso_big *big_lookup_flag(int bit)
2206 {
2207 	for (size_t i = 0; i < ARRAY_SIZE(bigs); i++) {
2208 		if (atomic_test_bit(bigs[i].flags, bit)) {
2209 			return &bigs[i];
2210 		}
2211 	}
2212 
2213 	LOG_DBG("No BIG with flag bit %d set", bit);
2214 
2215 	return NULL;
2216 }
2217 
cleanup_big(struct bt_iso_big * big)2218 static void cleanup_big(struct bt_iso_big *big)
2219 {
2220 	struct bt_iso_chan *bis, *tmp;
2221 
2222 	SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&big->bis_channels, bis, tmp, node) {
2223 		if (bis->iso != NULL) {
2224 			bt_conn_unref(bis->iso);
2225 			bis->iso = NULL;
2226 		}
2227 
2228 		sys_slist_remove(&big->bis_channels, NULL, &bis->node);
2229 	}
2230 
2231 	memset(big, 0, sizeof(*big));
2232 }
2233 
big_disconnect(struct bt_iso_big * big,uint8_t reason)2234 static void big_disconnect(struct bt_iso_big *big, uint8_t reason)
2235 {
2236 	struct bt_iso_chan *bis;
2237 
2238 	SYS_SLIST_FOR_EACH_CONTAINER(&big->bis_channels, bis, node) {
2239 		bis->iso->err = reason;
2240 
2241 		bt_iso_disconnected(bis->iso);
2242 	}
2243 }
2244 
big_init_bis(struct bt_iso_big * big,struct bt_iso_chan ** bis_channels,uint8_t num_bis,bool broadcaster)2245 static int big_init_bis(struct bt_iso_big *big,
2246 			struct bt_iso_chan **bis_channels,
2247 			uint8_t num_bis,
2248 			bool broadcaster)
2249 {
2250 	for (uint8_t i = 0; i < num_bis; i++) {
2251 		struct bt_iso_chan *bis = bis_channels[i];
2252 		struct bt_conn_iso *iso_conn;
2253 
2254 		bis->iso = iso_new();
2255 
2256 		if (!bis->iso) {
2257 			LOG_ERR("Unable to allocate BIS connection");
2258 			return -ENOMEM;
2259 		}
2260 		iso_conn = &bis->iso->iso;
2261 
2262 		iso_conn->big_handle = big->handle;
2263 		iso_conn->info.type = broadcaster ? BT_ISO_CHAN_TYPE_BROADCASTER
2264 						  : BT_ISO_CHAN_TYPE_SYNC_RECEIVER;
2265 		iso_conn->bis_id = bt_conn_index(bis->iso);
2266 
2267 		bt_iso_chan_add(bis->iso, bis);
2268 
2269 		sys_slist_append(&big->bis_channels, &bis->node);
2270 	}
2271 
2272 	return 0;
2273 }
2274 
2275 #if defined(CONFIG_BT_ISO_BROADCASTER)
hci_le_create_big(struct bt_le_ext_adv * padv,struct bt_iso_big * big,struct bt_iso_big_create_param * param)2276 static int hci_le_create_big(struct bt_le_ext_adv *padv, struct bt_iso_big *big,
2277 			     struct bt_iso_big_create_param *param)
2278 {
2279 	struct bt_hci_cp_le_create_big *req;
2280 	struct bt_hci_cmd_state_set state;
2281 	struct net_buf *buf;
2282 	int err;
2283 	static struct bt_iso_chan_qos *qos;
2284 	struct bt_iso_chan *bis;
2285 
2286 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_BIG, sizeof(*req));
2287 
2288 	if (!buf) {
2289 		return -ENOBUFS;
2290 	}
2291 
2292 	bis = SYS_SLIST_PEEK_HEAD_CONTAINER(&big->bis_channels, bis, node);
2293 	__ASSERT(bis != NULL, "bis was NULL");
2294 
2295 	/* All BIS will share the same QOS */
2296 	qos = bis->qos;
2297 
2298 	req = net_buf_add(buf, sizeof(*req));
2299 	req->big_handle = big->handle;
2300 	req->adv_handle = padv->handle;
2301 	req->num_bis = big->num_bis;
2302 	sys_put_le24(param->interval, req->sdu_interval);
2303 	req->max_sdu = sys_cpu_to_le16(qos->tx->sdu);
2304 	req->max_latency = sys_cpu_to_le16(param->latency);
2305 	req->rtn = qos->tx->rtn;
2306 	req->phy = qos->tx->phy;
2307 	req->packing = param->packing;
2308 	req->framing = param->framing;
2309 	req->encryption = param->encryption;
2310 	if (req->encryption) {
2311 		memcpy(req->bcode, param->bcode, sizeof(req->bcode));
2312 	} else {
2313 		memset(req->bcode, 0, sizeof(req->bcode));
2314 	}
2315 
2316 	bt_hci_cmd_state_set_init(buf, &state, big->flags, BT_BIG_PENDING, true);
2317 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_BIG, buf, NULL);
2318 
2319 	if (err) {
2320 		return err;
2321 	}
2322 
2323 	SYS_SLIST_FOR_EACH_CONTAINER(&big->bis_channels, bis, node) {
2324 		bt_iso_chan_set_state(bis, BT_ISO_STATE_CONNECTING);
2325 	}
2326 
2327 	return err;
2328 }
2329 
bt_iso_big_create(struct bt_le_ext_adv * padv,struct bt_iso_big_create_param * param,struct bt_iso_big ** out_big)2330 int bt_iso_big_create(struct bt_le_ext_adv *padv, struct bt_iso_big_create_param *param,
2331 		      struct bt_iso_big **out_big)
2332 {
2333 	int err;
2334 	struct bt_iso_big *big;
2335 
2336 	if (!atomic_test_bit(padv->flags, BT_PER_ADV_PARAMS_SET)) {
2337 		LOG_DBG("PA params not set; invalid adv object");
2338 		return -EINVAL;
2339 	}
2340 
2341 	CHECKIF(!param->bis_channels) {
2342 		LOG_DBG("NULL BIS channels");
2343 		return -EINVAL;
2344 	}
2345 
2346 	CHECKIF(!param->num_bis) {
2347 		LOG_DBG("Invalid number of BIS %u", param->num_bis);
2348 		return -EINVAL;
2349 	}
2350 
2351 	for (uint8_t i = 0; i < param->num_bis; i++) {
2352 		struct bt_iso_chan *bis = param->bis_channels[i];
2353 
2354 		CHECKIF(bis == NULL) {
2355 			LOG_DBG("bis_channels[%u]: NULL channel", i);
2356 			return -EINVAL;
2357 		}
2358 
2359 		if (bis->iso) {
2360 			LOG_DBG("bis_channels[%u]: already allocated", i);
2361 			return -EALREADY;
2362 		}
2363 
2364 		CHECKIF(bis->qos == NULL) {
2365 			LOG_DBG("bis_channels[%u]: qos is NULL", i);
2366 			return -EINVAL;
2367 		}
2368 
2369 		CHECKIF(bis->qos->tx == NULL ||
2370 			!valid_chan_io_qos(bis->qos->tx, true)) {
2371 			LOG_DBG("bis_channels[%u]: Invalid QOS", i);
2372 			return -EINVAL;
2373 		}
2374 	}
2375 
2376 	CHECKIF(param->framing != BT_ISO_FRAMING_UNFRAMED &&
2377 		param->framing != BT_ISO_FRAMING_FRAMED) {
2378 		LOG_DBG("Invalid framing parameter: %u", param->framing);
2379 		return -EINVAL;
2380 	}
2381 
2382 	CHECKIF(param->packing != BT_ISO_PACKING_SEQUENTIAL &&
2383 		param->packing != BT_ISO_PACKING_INTERLEAVED) {
2384 		LOG_DBG("Invalid packing parameter: %u", param->packing);
2385 		return -EINVAL;
2386 	}
2387 
2388 	CHECKIF(param->num_bis > BT_ISO_MAX_GROUP_ISO_COUNT ||
2389 		param->num_bis > CONFIG_BT_ISO_MAX_CHAN) {
2390 		LOG_DBG("num_bis (%u) shall be lower than: %u", param->num_bis,
2391 			MAX(CONFIG_BT_ISO_MAX_CHAN, BT_ISO_MAX_GROUP_ISO_COUNT));
2392 		return -EINVAL;
2393 	}
2394 
2395 	CHECKIF(param->interval < BT_ISO_SDU_INTERVAL_MIN ||
2396 		param->interval > BT_ISO_SDU_INTERVAL_MAX) {
2397 		LOG_DBG("Invalid interval: %u", param->interval);
2398 		return -EINVAL;
2399 	}
2400 
2401 	CHECKIF(param->latency < BT_ISO_LATENCY_MIN ||
2402 		param->latency > BT_ISO_LATENCY_MAX) {
2403 		LOG_DBG("Invalid latency: %u", param->latency);
2404 		return -EINVAL;
2405 	}
2406 
2407 	big = get_free_big();
2408 
2409 	if (!big) {
2410 		return -ENOMEM;
2411 	}
2412 
2413 	err = big_init_bis(big, param->bis_channels, param->num_bis, true);
2414 	if (err) {
2415 		LOG_DBG("Could not init BIG %d", err);
2416 		cleanup_big(big);
2417 		return err;
2418 	}
2419 	big->num_bis = param->num_bis;
2420 
2421 	err = hci_le_create_big(padv, big, param);
2422 	if (err) {
2423 		LOG_DBG("Could not create BIG %d", err);
2424 		cleanup_big(big);
2425 		return err;
2426 	}
2427 
2428 	*out_big = big;
2429 
2430 	return err;
2431 }
2432 
store_bis_broadcaster_info(const struct bt_hci_evt_le_big_complete * evt,struct bt_iso_info * info)2433 static void store_bis_broadcaster_info(const struct bt_hci_evt_le_big_complete *evt,
2434 				       struct bt_iso_info *info)
2435 {
2436 	struct bt_iso_broadcaster_info *broadcaster_info = &info->broadcaster;
2437 
2438 	info->iso_interval = sys_le16_to_cpu(evt->iso_interval);
2439 	info->max_subevent = evt->nse;
2440 
2441 	broadcaster_info->sync_delay = sys_get_le24(evt->sync_delay);
2442 	broadcaster_info->latency = sys_get_le24(evt->latency);
2443 	broadcaster_info->phy = bt_get_phy(evt->phy);
2444 	broadcaster_info->bn = evt->bn;
2445 	broadcaster_info->irc = evt->irc;
2446 	/* Transform to n * 1.25ms */
2447 	broadcaster_info->pto = info->iso_interval * evt->pto;
2448 	broadcaster_info->max_pdu = sys_le16_to_cpu(evt->max_pdu);
2449 
2450 	info->can_send = true;
2451 	info->can_recv = false;
2452 }
2453 
hci_le_big_complete(struct net_buf * buf)2454 void hci_le_big_complete(struct net_buf *buf)
2455 {
2456 	struct bt_hci_evt_le_big_complete *evt = (void *)buf->data;
2457 	struct bt_iso_chan *bis;
2458 	struct bt_iso_big *big;
2459 	int i;
2460 
2461 	if (evt->big_handle >= ARRAY_SIZE(bigs)) {
2462 		LOG_WRN("Invalid BIG handle");
2463 
2464 		big = big_lookup_flag(BT_BIG_PENDING);
2465 		if (big) {
2466 			big_disconnect(big, evt->status ? evt->status : BT_HCI_ERR_UNSPECIFIED);
2467 			cleanup_big(big);
2468 		}
2469 
2470 		return;
2471 	}
2472 
2473 	big = lookup_big_by_handle(evt->big_handle);
2474 	atomic_clear_bit(big->flags, BT_BIG_PENDING);
2475 
2476 	LOG_DBG("BIG[%u] %p completed, status 0x%02x", big->handle, big, evt->status);
2477 
2478 	if (evt->status || evt->num_bis != big->num_bis) {
2479 		if (evt->status == BT_HCI_ERR_SUCCESS && evt->num_bis != big->num_bis) {
2480 			LOG_ERR("Invalid number of BIS created, was %u expected %u", evt->num_bis,
2481 				big->num_bis);
2482 		}
2483 		big_disconnect(big, evt->status ? evt->status : BT_HCI_ERR_UNSPECIFIED);
2484 		cleanup_big(big);
2485 		return;
2486 	}
2487 
2488 	i = 0;
2489 	SYS_SLIST_FOR_EACH_CONTAINER(&big->bis_channels, bis, node) {
2490 		const uint16_t handle = evt->handle[i++];
2491 		struct bt_conn *iso_conn = bis->iso;
2492 
2493 		iso_conn->handle = sys_le16_to_cpu(handle);
2494 		store_bis_broadcaster_info(evt, &iso_conn->iso.info);
2495 		bt_conn_set_state(iso_conn, BT_CONN_CONNECTED);
2496 	}
2497 }
2498 
hci_le_big_terminate(struct net_buf * buf)2499 void hci_le_big_terminate(struct net_buf *buf)
2500 {
2501 	struct bt_hci_evt_le_big_terminate *evt = (void *)buf->data;
2502 	struct bt_iso_big *big;
2503 
2504 	if (evt->big_handle >= ARRAY_SIZE(bigs)) {
2505 		LOG_WRN("Invalid BIG handle");
2506 		return;
2507 	}
2508 
2509 	big = lookup_big_by_handle(evt->big_handle);
2510 
2511 	LOG_DBG("BIG[%u] %p terminated", big->handle, big);
2512 
2513 	big_disconnect(big, evt->reason);
2514 	cleanup_big(big);
2515 }
2516 #endif /* CONFIG_BT_ISO_BROADCASTER */
2517 
hci_le_terminate_big(struct bt_iso_big * big)2518 static int hci_le_terminate_big(struct bt_iso_big *big)
2519 {
2520 	struct bt_hci_cp_le_terminate_big *req;
2521 	struct net_buf *buf;
2522 
2523 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_TERMINATE_BIG, sizeof(*req));
2524 	if (!buf) {
2525 		return -ENOBUFS;
2526 	}
2527 
2528 	req = net_buf_add(buf, sizeof(*req));
2529 	req->big_handle = big->handle;
2530 	req->reason = BT_HCI_ERR_REMOTE_USER_TERM_CONN;
2531 
2532 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_TERMINATE_BIG, buf, NULL);
2533 }
2534 
hci_le_big_sync_term(struct bt_iso_big * big)2535 static int hci_le_big_sync_term(struct bt_iso_big *big)
2536 {
2537 	struct bt_hci_cp_le_big_terminate_sync *req;
2538 	struct bt_hci_rp_le_big_terminate_sync *evt;
2539 	struct net_buf *buf;
2540 	struct net_buf *rsp;
2541 	int err;
2542 
2543 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_BIG_TERMINATE_SYNC, sizeof(*req));
2544 	if (!buf) {
2545 		return -ENOBUFS;
2546 	}
2547 
2548 	req = net_buf_add(buf, sizeof(*req));
2549 	req->big_handle = big->handle;
2550 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_BIG_TERMINATE_SYNC, buf, &rsp);
2551 	if (err) {
2552 		return err;
2553 	}
2554 
2555 	evt = (struct bt_hci_rp_le_big_terminate_sync *)rsp->data;
2556 	if (evt->status || (evt->big_handle != big->handle)) {
2557 		err = -EIO;
2558 	}
2559 
2560 	net_buf_unref(rsp);
2561 
2562 	return err;
2563 }
2564 
bt_iso_big_terminate(struct bt_iso_big * big)2565 int bt_iso_big_terminate(struct bt_iso_big *big)
2566 {
2567 	struct bt_iso_chan *bis;
2568 	int err;
2569 
2570 	if (!atomic_test_bit(big->flags, BT_BIG_INITIALIZED) || !big->num_bis) {
2571 		LOG_DBG("BIG not initialized");
2572 		return -EINVAL;
2573 	}
2574 
2575 	bis = SYS_SLIST_PEEK_HEAD_CONTAINER(&big->bis_channels, bis, node);
2576 	__ASSERT(bis != NULL, "bis was NULL");
2577 
2578 	if (IS_ENABLED(CONFIG_BT_ISO_BROADCASTER) &&
2579 	    bis->iso->iso.info.type == BT_ISO_CHAN_TYPE_BROADCASTER) {
2580 		err = hci_le_terminate_big(big);
2581 
2582 		/* Wait for BT_HCI_EVT_LE_BIG_TERMINATE before cleaning up
2583 		 * the BIG in hci_le_big_terminate
2584 		 */
2585 		if (!err) {
2586 			SYS_SLIST_FOR_EACH_CONTAINER(&big->bis_channels, bis, node) {
2587 				bt_iso_chan_set_state(bis, BT_ISO_STATE_DISCONNECTING);
2588 			}
2589 		}
2590 	} else if (IS_ENABLED(CONFIG_BT_ISO_SYNC_RECEIVER) &&
2591 		   bis->iso->iso.info.type == BT_ISO_CHAN_TYPE_SYNC_RECEIVER) {
2592 		err = hci_le_big_sync_term(big);
2593 
2594 		if (!err) {
2595 			big_disconnect(big, BT_HCI_ERR_LOCALHOST_TERM_CONN);
2596 			cleanup_big(big);
2597 		}
2598 	} else {
2599 		err = -EINVAL;
2600 	}
2601 
2602 	if (err) {
2603 		LOG_DBG("Could not terminate BIG %d", err);
2604 	}
2605 
2606 	return err;
2607 }
2608 
2609 #if defined(CONFIG_BT_ISO_SYNC_RECEIVER)
store_bis_sync_receiver_info(const struct bt_hci_evt_le_big_sync_established * evt,struct bt_iso_info * info)2610 static void store_bis_sync_receiver_info(const struct bt_hci_evt_le_big_sync_established *evt,
2611 					 struct bt_iso_info *info)
2612 {
2613 	struct bt_iso_sync_receiver_info *receiver_info = &info->sync_receiver;
2614 
2615 	info->max_subevent = evt->nse;
2616 	info->iso_interval = sys_le16_to_cpu(evt->iso_interval);
2617 
2618 	receiver_info->latency = sys_get_le24(evt->latency);
2619 	receiver_info->bn = evt->bn;
2620 	receiver_info->irc = evt->irc;
2621 	/* Transform to n * 1.25ms */
2622 	receiver_info->pto = info->iso_interval * evt->pto;
2623 	receiver_info->max_pdu = sys_le16_to_cpu(evt->max_pdu);
2624 
2625 	info->can_send = false;
2626 	info->can_recv = true;
2627 }
2628 
hci_le_big_sync_established(struct net_buf * buf)2629 void hci_le_big_sync_established(struct net_buf *buf)
2630 {
2631 	struct bt_hci_evt_le_big_sync_established *evt = (void *)buf->data;
2632 	struct bt_iso_chan *bis;
2633 	struct bt_iso_big *big;
2634 	int i;
2635 
2636 	if (evt->big_handle >= ARRAY_SIZE(bigs)) {
2637 		LOG_WRN("Invalid BIG handle");
2638 		big = big_lookup_flag(BT_BIG_SYNCING);
2639 		if (big) {
2640 			big_disconnect(big, evt->status ? evt->status : BT_HCI_ERR_UNSPECIFIED);
2641 			cleanup_big(big);
2642 		}
2643 
2644 		return;
2645 	}
2646 
2647 	big = lookup_big_by_handle(evt->big_handle);
2648 	atomic_clear_bit(big->flags, BT_BIG_SYNCING);
2649 
2650 	LOG_DBG("BIG[%u] %p sync established, status 0x%02x", big->handle, big, evt->status);
2651 
2652 	if (evt->status || evt->num_bis != big->num_bis) {
2653 		if (evt->status == BT_HCI_ERR_SUCCESS && evt->num_bis != big->num_bis) {
2654 			LOG_ERR("Invalid number of BIS synced, was %u expected %u", evt->num_bis,
2655 				big->num_bis);
2656 		}
2657 		big_disconnect(big, evt->status ? evt->status : BT_HCI_ERR_UNSPECIFIED);
2658 		cleanup_big(big);
2659 		return;
2660 	}
2661 
2662 	i = 0;
2663 	SYS_SLIST_FOR_EACH_CONTAINER(&big->bis_channels, bis, node) {
2664 		const uint16_t handle = evt->handle[i++];
2665 		struct bt_conn *iso_conn = bis->iso;
2666 
2667 		iso_conn->handle = sys_le16_to_cpu(handle);
2668 		store_bis_sync_receiver_info(evt, &iso_conn->iso.info);
2669 		bt_conn_set_state(iso_conn, BT_CONN_CONNECTED);
2670 	}
2671 }
2672 
hci_le_big_sync_lost(struct net_buf * buf)2673 void hci_le_big_sync_lost(struct net_buf *buf)
2674 {
2675 	struct bt_hci_evt_le_big_sync_lost *evt = (void *)buf->data;
2676 	struct bt_iso_big *big;
2677 
2678 	if (evt->big_handle >= ARRAY_SIZE(bigs)) {
2679 		LOG_WRN("Invalid BIG handle");
2680 		return;
2681 	}
2682 
2683 	big = lookup_big_by_handle(evt->big_handle);
2684 
2685 	LOG_DBG("BIG[%u] %p sync lost", big->handle, big);
2686 
2687 	big_disconnect(big, evt->reason);
2688 	cleanup_big(big);
2689 }
2690 
hci_le_big_create_sync(const struct bt_le_per_adv_sync * sync,struct bt_iso_big * big,const struct bt_iso_big_sync_param * param)2691 static int hci_le_big_create_sync(const struct bt_le_per_adv_sync *sync, struct bt_iso_big *big,
2692 				  const struct bt_iso_big_sync_param *param)
2693 {
2694 	struct bt_hci_cp_le_big_create_sync *req;
2695 	struct bt_hci_cmd_state_set state;
2696 	struct net_buf *buf;
2697 	int err;
2698 	uint8_t bit_idx = 0;
2699 
2700 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_BIG_CREATE_SYNC, sizeof(*req) + big->num_bis);
2701 	if (!buf) {
2702 		return -ENOBUFS;
2703 	}
2704 
2705 	req = net_buf_add(buf, sizeof(*req) + big->num_bis);
2706 	req->big_handle = big->handle;
2707 	req->sync_handle = sys_cpu_to_le16(sync->handle);
2708 	req->encryption = param->encryption;
2709 	if (req->encryption) {
2710 		memcpy(req->bcode, param->bcode, sizeof(req->bcode));
2711 	} else {
2712 		memset(req->bcode, 0, sizeof(req->bcode));
2713 	}
2714 	req->mse = param->mse;
2715 	req->sync_timeout = sys_cpu_to_le16(param->sync_timeout);
2716 	req->num_bis = big->num_bis;
2717 	/* Transform from bitfield to array */
2718 	for (int i = 1; i <= BT_ISO_MAX_GROUP_ISO_COUNT; i++) {
2719 		if (param->bis_bitfield & BIT(i)) {
2720 			if (bit_idx == big->num_bis) {
2721 				LOG_DBG("BIG cannot contain %u BISes", bit_idx + 1);
2722 				return -EINVAL;
2723 			}
2724 			req->bis[bit_idx++] = i;
2725 		}
2726 	}
2727 
2728 	if (bit_idx != big->num_bis) {
2729 		LOG_DBG("Number of bits in bis_bitfield (%u) doesn't match num_bis (%u)", bit_idx,
2730 			big->num_bis);
2731 		return -EINVAL;
2732 	}
2733 
2734 	bt_hci_cmd_state_set_init(buf, &state, big->flags, BT_BIG_SYNCING, true);
2735 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_BIG_CREATE_SYNC, buf, NULL);
2736 
2737 	return err;
2738 }
2739 
bt_iso_big_sync(struct bt_le_per_adv_sync * sync,struct bt_iso_big_sync_param * param,struct bt_iso_big ** out_big)2740 int bt_iso_big_sync(struct bt_le_per_adv_sync *sync, struct bt_iso_big_sync_param *param,
2741 		    struct bt_iso_big **out_big)
2742 {
2743 	int err;
2744 	struct bt_iso_chan *bis;
2745 	struct bt_iso_big *big;
2746 
2747 	if (!atomic_test_bit(sync->flags, BT_PER_ADV_SYNC_SYNCED)) {
2748 		LOG_DBG("PA sync not synced");
2749 		return -EINVAL;
2750 	}
2751 
2752 	CHECKIF(param->mse > BT_ISO_SYNC_MSE_MAX) {
2753 		LOG_DBG("Invalid MSE 0x%02x", param->mse);
2754 		return -EINVAL;
2755 	}
2756 
2757 	CHECKIF(param->sync_timeout < BT_ISO_SYNC_TIMEOUT_MIN ||
2758 		param->sync_timeout > BT_ISO_SYNC_TIMEOUT_MAX) {
2759 		LOG_DBG("Invalid sync timeout 0x%04x", param->sync_timeout);
2760 		return -EINVAL;
2761 	}
2762 
2763 	CHECKIF(param->bis_bitfield <= BIT(0)) {
2764 		LOG_DBG("Invalid BIS bitfield 0x%08x", param->bis_bitfield);
2765 		return -EINVAL;
2766 	}
2767 
2768 	CHECKIF(!param->bis_channels) {
2769 		LOG_DBG("NULL BIS channels");
2770 		return -EINVAL;
2771 	}
2772 
2773 	CHECKIF(!param->num_bis) {
2774 		LOG_DBG("Invalid number of BIS %u", param->num_bis);
2775 		return -EINVAL;
2776 	}
2777 
2778 	for (uint8_t i = 0; i < param->num_bis; i++) {
2779 		struct bt_iso_chan *bis = param->bis_channels[i];
2780 
2781 		CHECKIF(bis == NULL) {
2782 			LOG_DBG("bis_channels[%u]: NULL channel", i);
2783 			return -EINVAL;
2784 		}
2785 
2786 		if (bis->iso) {
2787 			LOG_DBG("bis_channels[%u]: already allocated", i);
2788 			return -EALREADY;
2789 		}
2790 
2791 		CHECKIF(bis->qos == NULL) {
2792 			LOG_DBG("bis_channels[%u]: qos is NULL", i);
2793 			return -EINVAL;
2794 		}
2795 
2796 		CHECKIF(bis->qos->rx == NULL) {
2797 			LOG_DBG("bis_channels[%u]: qos->rx is NULL", i);
2798 			return -EINVAL;
2799 		}
2800 	}
2801 
2802 	big = get_free_big();
2803 
2804 	if (!big) {
2805 		return -ENOMEM;
2806 	}
2807 
2808 	err = big_init_bis(big, param->bis_channels, param->num_bis, false);
2809 	if (err) {
2810 		LOG_DBG("Could not init BIG %d", err);
2811 		cleanup_big(big);
2812 		return err;
2813 	}
2814 	big->num_bis = param->num_bis;
2815 
2816 	err = hci_le_big_create_sync(sync, big, param);
2817 	if (err) {
2818 		LOG_DBG("Could not create BIG sync %d", err);
2819 		cleanup_big(big);
2820 		return err;
2821 	}
2822 
2823 
2824 	SYS_SLIST_FOR_EACH_CONTAINER(&big->bis_channels, bis, node) {
2825 		bt_iso_chan_set_state(bis, BT_ISO_STATE_CONNECTING);
2826 	}
2827 
2828 	*out_big = big;
2829 
2830 	return 0;
2831 }
2832 #endif /* CONFIG_BT_ISO_SYNC_RECEIVER */
2833 #endif /* CONFIG_BT_ISO_BROADCAST */
2834