1 /* @file
2  * @brief Bluetooth ASCS
3  */
4 /*
5  * Copyright (c) 2020 Intel Corporation
6  * Copyright (c) 2022-2023 Nordic Semiconductor ASA
7  *
8  * SPDX-License-Identifier: Apache-2.0
9  */
10 #include <errno.h>
11 #include <stdbool.h>
12 #include <stddef.h>
13 #include <stdint.h>
14 #include <string.h>
15 #include <sys/types.h>
16 
17 #include <zephyr/autoconf.h>
18 #include <zephyr/bluetooth/att.h>
19 #include <zephyr/bluetooth/audio/audio.h>
20 #include <zephyr/bluetooth/audio/bap.h>
21 #include <zephyr/bluetooth/audio/pacs.h>
22 #include <zephyr/bluetooth/bluetooth.h>
23 #include <zephyr/bluetooth/conn.h>
24 #include <zephyr/bluetooth/gatt.h>
25 #include <zephyr/bluetooth/hci_types.h>
26 #include <zephyr/bluetooth/iso.h>
27 #include <zephyr/bluetooth/uuid.h>
28 #include <zephyr/kernel.h>
29 #include <zephyr/logging/log.h>
30 #include <zephyr/net/buf.h>
31 #include <zephyr/sys/__assert.h>
32 #include <zephyr/sys/byteorder.h>
33 #include <zephyr/sys/check.h>
34 #include <zephyr/sys/util.h>
35 #include <zephyr/sys/util_macro.h>
36 #include <zephyr/toolchain.h>
37 
38 LOG_MODULE_REGISTER(bt_ascs, CONFIG_BT_ASCS_LOG_LEVEL);
39 
40 #include "common/bt_str.h"
41 #include "common/assert.h"
42 
43 #include "../host/att_internal.h"
44 
45 #include "ascs_internal.h"
46 #include "audio_internal.h"
47 #include "bap_endpoint.h"
48 #include "bap_iso.h"
49 #include "bap_stream.h"
50 #include "bap_unicast_server.h"
51 #include "pacs_internal.h"
52 #include "cap_internal.h"
53 
54 #define ASE_BUF_SEM_TIMEOUT K_MSEC(CONFIG_BT_ASCS_ASE_BUF_TIMEOUT)
55 
56 #define MAX_ASES_SESSIONS CONFIG_BT_MAX_CONN * \
57 				(CONFIG_BT_ASCS_ASE_SNK_COUNT + \
58 				 CONFIG_BT_ASCS_ASE_SRC_COUNT)
59 
60 #define NTF_HEADER_SIZE (3) /* opcode (1) + handle (2) */
61 
62 BUILD_ASSERT(CONFIG_BT_ASCS_MAX_ACTIVE_ASES <= MAX(MAX_ASES_SESSIONS,
63 						   CONFIG_BT_ISO_MAX_CHAN),
64 	     "Max active ASEs are set to more than actual number of ASEs or ISOs");
65 
66 #if defined(CONFIG_BT_BAP_UNICAST_SERVER)
67 
68 #define ASE_ID(_ase) ase->ep.status.id
69 #define ASE_DIR(_id) \
70 	(_id > CONFIG_BT_ASCS_ASE_SNK_COUNT ? BT_AUDIO_DIR_SOURCE : BT_AUDIO_DIR_SINK)
71 #define ASE_UUID(_id) \
72 	(_id > CONFIG_BT_ASCS_ASE_SNK_COUNT ? BT_UUID_ASCS_ASE_SRC : BT_UUID_ASCS_ASE_SNK)
73 #define ASE_COUNT (CONFIG_BT_ASCS_ASE_SNK_COUNT + CONFIG_BT_ASCS_ASE_SRC_COUNT)
74 #define BT_BAP_ASCS_RSP_NULL ((struct bt_bap_ascs_rsp[]) { BT_BAP_ASCS_RSP(0, 0) })
75 
76 static struct bt_ascs_ase {
77 	struct bt_conn *conn;
78 	struct bt_bap_ep ep;
79 	const struct bt_gatt_attr *attr;
80 	struct k_work_delayable disconnect_work;
81 	struct k_work_delayable state_transition_work;
82 	enum bt_bap_ep_state state_pending;
83 	bool unexpected_iso_link_loss;
84 } ase_pool[CONFIG_BT_ASCS_MAX_ACTIVE_ASES];
85 
86 /* Minimum state size when in the codec configured state */
87 #define MIN_CONFIG_STATE_SIZE (1 + 1 + 1 + 1 + 1 + 2 + 3 + 3 + 3 + 3 + 5 + 1)
88 /* Minimum state size when in the QoS configured state */
89 #define MIN_QOS_STATE_SIZE    (1 + 1 + 1 + 1 + 3 + 1 + 1 + 2 + 1 + 2 + 3 + 1 + 1 + 1)
90 
91 /* Calculate the size requirement of the ASE BUF, based on the maximum possible
92  * size of the Codec Configured state or the QoS Configured state, as either
93  * of them can be the largest state
94  */
95 #define ASE_BUF_SIZE                                                                               \
96 	MIN(BT_ATT_MAX_ATTRIBUTE_LEN,                                                              \
97 	    MAX(MIN_CONFIG_STATE_SIZE + CONFIG_BT_AUDIO_CODEC_CFG_MAX_DATA_SIZE,                   \
98 		MIN_QOS_STATE_SIZE + CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE))
99 
100 /* Verify that the prepare count is large enough to cover the maximum value we support a client
101  * writing
102  */
103 BUILD_ASSERT(
104 	(BT_ATT_BUF_SIZE - NTF_HEADER_SIZE) >= ASE_BUF_SIZE ||
105 		DIV_ROUND_UP(ASE_BUF_SIZE, (BT_ATT_BUF_SIZE - NTF_HEADER_SIZE)) <=
106 			CONFIG_BT_ATT_PREPARE_COUNT,
107 	"CONFIG_BT_ATT_PREPARE_COUNT not large enough to cover the maximum supported ASCS value");
108 
109 /* It is mandatory to support long writes in ASCS unconditionally, and thus
110  * CONFIG_BT_ATT_PREPARE_COUNT must be at least 1 to support the feature
111  */
112 BUILD_ASSERT(CONFIG_BT_ATT_PREPARE_COUNT > 0, "CONFIG_BT_ATT_PREPARE_COUNT shall be at least 1");
113 
114 static const struct bt_bap_unicast_server_cb *unicast_server_cb;
115 
116 static K_SEM_DEFINE(ase_buf_sem, 1, 1);
117 NET_BUF_SIMPLE_DEFINE_STATIC(ase_buf, ASE_BUF_SIZE);
118 
119 static int control_point_notify(struct bt_conn *conn, const void *data, uint16_t len);
120 static int ascs_ep_get_status(struct bt_bap_ep *ep, struct net_buf_simple *buf);
121 
ascs_app_rsp_warn_valid(const struct bt_bap_ascs_rsp * rsp)122 static void ascs_app_rsp_warn_valid(const struct bt_bap_ascs_rsp *rsp)
123 {
124 	/* Validate application error code */
125 	switch (rsp->code) {
126 	case BT_BAP_ASCS_RSP_CODE_SUCCESS:
127 	case BT_BAP_ASCS_RSP_CODE_CAP_UNSUPPORTED:
128 	case BT_BAP_ASCS_RSP_CODE_NO_MEM:
129 	case BT_BAP_ASCS_RSP_CODE_UNSPECIFIED:
130 	case BT_BAP_ASCS_RSP_CODE_CONF_UNSUPPORTED:
131 	case BT_BAP_ASCS_RSP_CODE_CONF_REJECTED:
132 	case BT_BAP_ASCS_RSP_CODE_METADATA_UNSUPPORTED:
133 	case BT_BAP_ASCS_RSP_CODE_METADATA_REJECTED:
134 		break;
135 	default:
136 		LOG_WRN("Invalid application error code: %u", rsp->code);
137 		return;
138 	}
139 
140 	/* Validate application error code and reason combinations */
141 	switch (rsp->code) {
142 	case BT_BAP_ASCS_RSP_CODE_SUCCESS:
143 	case BT_BAP_ASCS_RSP_CODE_CAP_UNSUPPORTED:
144 	case BT_BAP_ASCS_RSP_CODE_NO_MEM:
145 	case BT_BAP_ASCS_RSP_CODE_UNSPECIFIED:
146 		if (rsp->reason != BT_BAP_ASCS_REASON_NONE) {
147 			LOG_WRN("Invalid reason %u for code %u", rsp->reason, rsp->code);
148 		}
149 		break;
150 	case BT_BAP_ASCS_RSP_CODE_CONF_UNSUPPORTED:
151 	case BT_BAP_ASCS_RSP_CODE_CONF_REJECTED:
152 		if (!IN_RANGE(rsp->reason, BT_BAP_ASCS_REASON_NONE, BT_BAP_ASCS_REASON_CIS)) {
153 			LOG_WRN("Invalid reason %u for code %u", rsp->reason, rsp->code);
154 		}
155 		break;
156 	case BT_BAP_ASCS_RSP_CODE_METADATA_UNSUPPORTED:
157 	case BT_BAP_ASCS_RSP_CODE_METADATA_REJECTED:
158 		if (!BT_AUDIO_METADATA_TYPE_IS_KNOWN(rsp->metadata_type)) {
159 			LOG_WRN("Invalid metadata type %u for code %u", rsp->metadata_type,
160 				rsp->code);
161 		}
162 		break;
163 	default:
164 		break;
165 	}
166 }
167 
is_valid_ase_id(uint8_t ase_id)168 static bool is_valid_ase_id(uint8_t ase_id)
169 {
170 	return IN_RANGE(ase_id, 1, ASE_COUNT);
171 }
172 
ascs_ep_get_state(struct bt_bap_ep * ep)173 static enum bt_bap_ep_state ascs_ep_get_state(struct bt_bap_ep *ep)
174 {
175 	return ep->status.state;
176 }
177 
ase_free(struct bt_ascs_ase * ase)178 static void ase_free(struct bt_ascs_ase *ase)
179 {
180 	__ASSERT(ase && ase->conn, "Non-existing ASE");
181 
182 	LOG_DBG("conn %p ase %p id 0x%02x", (void *)ase->conn, ase, ase->ep.status.id);
183 
184 	if (ase->ep.iso != NULL) {
185 		bt_bap_iso_unbind_ep(ase->ep.iso, &ase->ep);
186 	}
187 
188 	bt_conn_unref(ase->conn);
189 	ase->conn = NULL;
190 
191 	(void)k_work_cancel_delayable(&ase->disconnect_work);
192 	(void)k_work_cancel_delayable(&ase->state_transition_work);
193 }
194 
get_max_ntf_size(struct bt_conn * conn)195 static uint16_t get_max_ntf_size(struct bt_conn *conn)
196 {
197 	const uint16_t mtu = conn == NULL ? 0 : bt_gatt_get_mtu(conn);
198 
199 	if (mtu > NTF_HEADER_SIZE) {
200 		return mtu - NTF_HEADER_SIZE;
201 	}
202 
203 	return 0U;
204 }
205 
ase_state_notify(struct bt_ascs_ase * ase)206 static int ase_state_notify(struct bt_ascs_ase *ase)
207 {
208 	struct bt_conn *conn = ase->conn;
209 	struct bt_conn_info conn_info;
210 	uint16_t max_ntf_size;
211 	uint16_t ntf_size;
212 	int err;
213 
214 	__ASSERT_NO_MSG(conn != NULL);
215 
216 	err = bt_conn_get_info(conn, &conn_info);
217 	__ASSERT_NO_MSG(err == 0);
218 
219 	if (conn_info.state != BT_CONN_STATE_CONNECTED ||
220 	    !bt_gatt_is_subscribed(conn, ase->attr, BT_GATT_CCC_NOTIFY)) {
221 		return 0;
222 	}
223 
224 	err = k_sem_take(&ase_buf_sem, ASE_BUF_SEM_TIMEOUT);
225 	if (err != 0) {
226 		LOG_WRN("Failed to take ase_buf_sem: %d", err);
227 
228 		return err;
229 	}
230 
231 	ascs_ep_get_status(&ase->ep, &ase_buf);
232 
233 	max_ntf_size = get_max_ntf_size(conn);
234 
235 	ntf_size = MIN(max_ntf_size, ase_buf.len);
236 	if (ntf_size < ase_buf.len) {
237 		LOG_DBG("Sending truncated notification (%u / %u)",
238 			ntf_size, ase_buf.len);
239 	}
240 
241 	err = bt_gatt_notify(conn, ase->attr, ase_buf.data, ntf_size);
242 
243 	k_sem_give(&ase_buf_sem);
244 
245 	return err;
246 }
247 
ascs_disconnect_stream_work_handler(struct k_work * work)248 static void ascs_disconnect_stream_work_handler(struct k_work *work)
249 {
250 	struct k_work_delayable *d_work = k_work_delayable_from_work(work);
251 	struct bt_ascs_ase *ase = CONTAINER_OF(d_work, struct bt_ascs_ase,
252 					       disconnect_work);
253 	struct bt_bap_ep *ep = &ase->ep;
254 	struct bt_bap_stream *stream = ep->stream;
255 	struct bt_bap_stream *pair_stream;
256 
257 	__ASSERT(ep != NULL && ep->iso && stream != NULL,
258 		 "Invalid endpoint %p, iso %p or stream %p",
259 		 ep, ep == NULL ? NULL : ep->iso, stream);
260 
261 	if (ep->dir == BT_AUDIO_DIR_SINK) {
262 		pair_stream = ep->iso->tx.stream;
263 	} else {
264 		pair_stream = ep->iso->rx.stream;
265 	}
266 
267 	LOG_DBG("ase %p ep %p stream %p pair_stream %p",
268 		ase, ep, stream, pair_stream);
269 
270 	if (pair_stream != NULL) {
271 		struct bt_ascs_ase *pair_ase;
272 
273 		__ASSERT(pair_stream->ep != NULL, "Invalid pair_stream %p",
274 			 pair_stream);
275 
276 		if (pair_stream->ep->status.state == BT_BAP_EP_STATE_STREAMING) {
277 			/* Should not disconnect ISO if the stream is paired
278 			 * with another one in the streaming state
279 			 */
280 
281 			return;
282 		}
283 
284 		pair_ase = CONTAINER_OF(pair_stream->ep, struct bt_ascs_ase,
285 					ep);
286 
287 		/* Cancel pair ASE disconnect work if pending */
288 		(void)k_work_cancel_delayable(&pair_ase->disconnect_work);
289 	}
290 
291 	if (stream != NULL &&
292 	    ep->iso != NULL &&
293 	    (ep->iso->chan.state == BT_ISO_STATE_CONNECTED ||
294 	     ep->iso->chan.state == BT_ISO_STATE_CONNECTING)) {
295 		const int err = bt_bap_stream_disconnect(stream);
296 
297 		if (err != 0) {
298 			LOG_ERR("Failed to disconnect CIS %p: %d",
299 				stream, err);
300 		}
301 	}
302 }
303 
ascs_disconnect_stream(struct bt_bap_stream * stream)304 static int ascs_disconnect_stream(struct bt_bap_stream *stream)
305 {
306 	struct bt_ascs_ase *ase = CONTAINER_OF(stream->ep, struct bt_ascs_ase,
307 					       ep);
308 
309 	LOG_DBG("%p", stream);
310 
311 	return k_work_reschedule(&ase->disconnect_work,
312 				 K_MSEC(CONFIG_BT_ASCS_ISO_DISCONNECT_DELAY));
313 }
314 
ase_enter_state_idle(struct bt_ascs_ase * ase)315 static void ase_enter_state_idle(struct bt_ascs_ase *ase)
316 {
317 	struct bt_bap_stream *stream = ase->ep.stream;
318 	struct bt_bap_stream_ops *ops;
319 
320 	__ASSERT_NO_MSG(stream != NULL);
321 
322 	ase->ep.receiver_ready = false;
323 
324 	if (stream->conn != NULL) {
325 		bt_conn_unref(stream->conn);
326 		stream->conn = NULL;
327 	}
328 
329 	ops = stream->ops;
330 	if (ops != NULL && ops->released != NULL) {
331 		ops->released(stream);
332 	}
333 
334 	ase_free(ase);
335 }
336 
ase_enter_state_codec_configured(struct bt_ascs_ase * ase)337 static void ase_enter_state_codec_configured(struct bt_ascs_ase *ase)
338 {
339 	struct bt_bap_stream *stream = ase->ep.stream;
340 	struct bt_bap_stream_ops *ops;
341 
342 	__ASSERT_NO_MSG(stream != NULL);
343 
344 	ase->ep.receiver_ready = false;
345 
346 	ops = stream->ops;
347 	if (ops != NULL && ops->configured != NULL) {
348 		ops->configured(stream, &ase->ep.qos_pref);
349 	}
350 }
351 
ase_enter_state_qos_configured(struct bt_ascs_ase * ase)352 static void ase_enter_state_qos_configured(struct bt_ascs_ase *ase)
353 {
354 	struct bt_bap_stream *stream = ase->ep.stream;
355 	struct bt_bap_stream_ops *ops;
356 
357 	__ASSERT_NO_MSG(stream != NULL);
358 
359 	ase->ep.receiver_ready = false;
360 
361 	ops = stream->ops;
362 	if (ops != NULL && ops->qos_set != NULL) {
363 		ops->qos_set(stream);
364 	}
365 }
366 
ase_enter_state_enabling(struct bt_ascs_ase * ase)367 static void ase_enter_state_enabling(struct bt_ascs_ase *ase)
368 {
369 	struct bt_bap_stream *stream = ase->ep.stream;
370 	struct bt_bap_stream_ops *ops;
371 
372 	__ASSERT_NO_MSG(stream != NULL);
373 
374 	ops = stream->ops;
375 	if (ops != NULL && ops->enabled != NULL) {
376 		ops->enabled(stream);
377 	}
378 
379 	/* SINK ASEs can autonomously go into the streaming state if the CIS is connected */
380 	if (ase->ep.dir == BT_AUDIO_DIR_SINK && ase->ep.receiver_ready && ase->ep.iso != NULL &&
381 	    ase->ep.iso->chan.state == BT_ISO_STATE_CONNECTED) {
382 		ascs_ep_set_state(&ase->ep, BT_BAP_EP_STATE_STREAMING);
383 	}
384 }
385 
ase_enter_state_streaming(struct bt_ascs_ase * ase)386 static void ase_enter_state_streaming(struct bt_ascs_ase *ase)
387 {
388 	struct bt_bap_stream *stream = ase->ep.stream;
389 	struct bt_bap_stream_ops *ops;
390 
391 	__ASSERT_NO_MSG(stream != NULL);
392 
393 	ops = stream->ops;
394 	if (ops != NULL && ops->started != NULL) {
395 		ops->started(stream);
396 	}
397 }
398 
ase_metadata_updated(struct bt_ascs_ase * ase)399 static void ase_metadata_updated(struct bt_ascs_ase *ase)
400 {
401 	struct bt_bap_stream *stream = ase->ep.stream;
402 	struct bt_bap_stream_ops *ops;
403 
404 	__ASSERT_NO_MSG(stream != NULL);
405 
406 	ops = stream->ops;
407 	if (ops != NULL && ops->metadata_updated != NULL) {
408 		ops->metadata_updated(stream);
409 	}
410 }
411 
ase_exit_state_streaming(struct bt_ascs_ase * ase)412 static void ase_exit_state_streaming(struct bt_ascs_ase *ase)
413 {
414 	struct bt_bap_stream *stream = ase->ep.stream;
415 	struct bt_bap_stream_ops *ops;
416 	const enum bt_bap_ep_state next_state = ascs_ep_get_state(&ase->ep);
417 	uint8_t reason = ase->ep.reason;
418 
419 	__ASSERT_NO_MSG(stream != NULL);
420 
421 	if (reason == BT_HCI_ERR_SUCCESS) {
422 		/* Default to BT_HCI_ERR_UNSPECIFIED if no other reason is set */
423 		reason = BT_HCI_ERR_UNSPECIFIED;
424 	}
425 
426 	ops = stream->ops;
427 
428 	/*
429 	 * On link-loss we go from streaming state to QOS configured state,
430 	 * and it makes sense to do the disabled callback before entering the
431 	 * QOS configured state
432 	 */
433 	if (next_state == BT_BAP_EP_STATE_QOS_CONFIGURED) {
434 		if (ops != NULL && ops->disabled != NULL) {
435 			ops->disabled(stream);
436 		} else {
437 			LOG_WRN("No callback for disabled set");
438 		}
439 	}
440 
441 	if (ops != NULL && ops->stopped != NULL) {
442 		ops->stopped(stream, reason);
443 	} else {
444 		LOG_WRN("No callback for stopped set");
445 	}
446 }
447 
ase_exit_state_enabling(struct bt_ascs_ase * ase)448 static void ase_exit_state_enabling(struct bt_ascs_ase *ase)
449 {
450 	struct bt_bap_stream *stream = ase->ep.stream;
451 	struct bt_bap_stream_ops *ops;
452 	const enum bt_bap_ep_state next_state = ascs_ep_get_state(&ase->ep);
453 
454 	ops = stream->ops;
455 
456 	/*
457 	 * When the EP direction is BT_AUDIO_DIR_SOURCE the state machine goes from
458 	 * enabled to disabled where the disabled callback will be called,
459 	 * for BT_AUDIO_DIR_SINK we go from enabled to qos_configured,
460 	 * and logically we have to do the disabled callback first
461 	 */
462 	if (next_state == BT_BAP_EP_STATE_QOS_CONFIGURED && ase->ep.dir == BT_AUDIO_DIR_SINK) {
463 		if (ops != NULL && ops->disabled != NULL) {
464 			ops->disabled(stream);
465 		} else {
466 			LOG_WRN("No callback for disabled set");
467 		}
468 	}
469 }
470 
ase_enter_state_disabling(struct bt_ascs_ase * ase)471 static void ase_enter_state_disabling(struct bt_ascs_ase *ase)
472 {
473 	struct bt_bap_stream *stream = ase->ep.stream;
474 	struct bt_bap_stream_ops *ops;
475 
476 	__ASSERT_NO_MSG(stream != NULL);
477 
478 	ase->ep.receiver_ready = false;
479 
480 	ops = stream->ops;
481 	if (ops != NULL && ops->disabled != NULL) {
482 		ops->disabled(stream);
483 	}
484 }
485 
ase_enter_state_releasing(struct bt_ascs_ase * ase)486 static void ase_enter_state_releasing(struct bt_ascs_ase *ase)
487 {
488 	struct bt_bap_stream *stream = ase->ep.stream;
489 
490 	__ASSERT_NO_MSG(stream != NULL);
491 
492 	ase->ep.receiver_ready = false;
493 
494 	/* Either the client or the server may disconnect the CISes when entering the releasing
495 	 * state.
496 	 */
497 	if (bt_bap_stream_can_disconnect(stream)) {
498 		int err;
499 
500 		err = ascs_disconnect_stream(stream);
501 		if (err < 0) {
502 			LOG_ERR("Failed to disconnect stream %p: %d", stream, err);
503 		}
504 	} else {
505 		ascs_ep_set_state(&ase->ep, BT_BAP_EP_STATE_IDLE);
506 	}
507 }
508 
state_transition_work_handler(struct k_work * work)509 static void state_transition_work_handler(struct k_work *work)
510 {
511 	struct k_work_delayable *d_work = k_work_delayable_from_work(work);
512 	struct bt_ascs_ase *ase = CONTAINER_OF(d_work, struct bt_ascs_ase, state_transition_work);
513 	const enum bt_bap_ep_state old_state = ascs_ep_get_state(&ase->ep);
514 	const enum bt_bap_ep_state new_state = ase->state_pending;
515 	int err;
516 
517 	ase->ep.status.state = new_state;
518 
519 	/* Notify ASE state */
520 	if (ase->conn != NULL) {
521 		err = ase_state_notify(ase);
522 		if (err == -ENOMEM) {
523 			struct bt_conn_info info;
524 			uint32_t retry_delay_ms;
525 
526 			/* Revert back to old state */
527 			ase->ep.status.state = old_state;
528 
529 			err = bt_conn_get_info(ase->conn, &info);
530 			__ASSERT_NO_MSG(err == 0);
531 
532 			retry_delay_ms = BT_CONN_INTERVAL_TO_MS(info.le.interval);
533 
534 			/* Reschedule the state transition */
535 			err = k_work_reschedule(d_work, K_MSEC(retry_delay_ms));
536 			if (err >= 0) {
537 				LOG_WRN("Out of buffers for ase state notification. "
538 					"Will retry in %dms", retry_delay_ms);
539 				return;
540 			}
541 		}
542 
543 		if (err < 0) {
544 			LOG_ERR("Failed to notify ASE state (err %d)", err);
545 		}
546 	}
547 
548 	LOG_DBG("ase %p ep %p id 0x%02x %s -> %s", ase, &ase->ep, ase->ep.status.id,
549 		bt_bap_ep_state_str(old_state), bt_bap_ep_state_str(new_state));
550 
551 	if (old_state == new_state) {
552 		switch (new_state) {
553 		case BT_BAP_EP_STATE_ENABLING:
554 		case BT_BAP_EP_STATE_STREAMING:
555 			ase_metadata_updated(ase);
556 			return;
557 		default:
558 			break;
559 		}
560 	}
561 
562 	/* Actions needed for exiting the old state */
563 	switch (old_state) {
564 	case BT_BAP_EP_STATE_STREAMING:
565 		ase_exit_state_streaming(ase);
566 		break;
567 	case BT_BAP_EP_STATE_ENABLING:
568 		ase_exit_state_enabling(ase);
569 		break;
570 	default:
571 		break;
572 	}
573 
574 	/* Actions needed for entering the new state */
575 	switch (new_state) {
576 	case BT_BAP_EP_STATE_IDLE:
577 		ase_enter_state_idle(ase);
578 		break;
579 	case BT_BAP_EP_STATE_CODEC_CONFIGURED:
580 		ase_enter_state_codec_configured(ase);
581 		break;
582 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
583 		ase_enter_state_qos_configured(ase);
584 		break;
585 	case BT_BAP_EP_STATE_ENABLING:
586 		ase_enter_state_enabling(ase);
587 		break;
588 	case BT_BAP_EP_STATE_STREAMING:
589 		ase_enter_state_streaming(ase);
590 		break;
591 	case BT_BAP_EP_STATE_DISABLING:
592 		ase_enter_state_disabling(ase);
593 		break;
594 	case BT_BAP_EP_STATE_RELEASING:
595 		ase_enter_state_releasing(ase);
596 		break;
597 	default:
598 		__ASSERT_PRINT("Invalid state %d", new_state);
599 	}
600 }
601 
ascs_ep_set_state(struct bt_bap_ep * ep,uint8_t state)602 int ascs_ep_set_state(struct bt_bap_ep *ep, uint8_t state)
603 {
604 	struct bt_ascs_ase *ase = CONTAINER_OF(ep, struct bt_ascs_ase, ep);
605 	const enum bt_bap_ep_state old_state = ascs_ep_get_state(&ase->ep);
606 	bool valid_state_transition = false;
607 	int err;
608 
609 	switch (state) {
610 	case BT_BAP_EP_STATE_IDLE:
611 		valid_state_transition = true;
612 		break;
613 	case BT_BAP_EP_STATE_CODEC_CONFIGURED:
614 		switch (old_state) {
615 		case BT_BAP_EP_STATE_IDLE:
616 		case BT_BAP_EP_STATE_CODEC_CONFIGURED:
617 		case BT_BAP_EP_STATE_QOS_CONFIGURED:
618 		case BT_BAP_EP_STATE_RELEASING:
619 			valid_state_transition = true;
620 			break;
621 		default:
622 			break;
623 		} break;
624 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
625 		switch (old_state) {
626 		case BT_BAP_EP_STATE_CODEC_CONFIGURED:
627 		case BT_BAP_EP_STATE_QOS_CONFIGURED:
628 			valid_state_transition = true;
629 			break;
630 		case BT_BAP_EP_STATE_DISABLING:
631 			valid_state_transition = ase->ep.dir == BT_AUDIO_DIR_SOURCE;
632 			break;
633 		case BT_BAP_EP_STATE_ENABLING:
634 		case BT_BAP_EP_STATE_STREAMING:
635 			/* Source ASE transition Streaming->QoS configured is valid on case of CIS
636 			 * link-loss.
637 			 */
638 			valid_state_transition = ase->ep.dir == BT_AUDIO_DIR_SINK ||
639 						 ase->unexpected_iso_link_loss;
640 			break;
641 		default:
642 			break;
643 		} break;
644 	case BT_BAP_EP_STATE_ENABLING:
645 		switch (old_state) {
646 		case BT_BAP_EP_STATE_QOS_CONFIGURED:
647 		case BT_BAP_EP_STATE_ENABLING:
648 			valid_state_transition = true;
649 			break;
650 		default:
651 			break;
652 		} break;
653 	case BT_BAP_EP_STATE_STREAMING:
654 		switch (old_state) {
655 		case BT_BAP_EP_STATE_ENABLING:
656 		case BT_BAP_EP_STATE_STREAMING:
657 			valid_state_transition = true;
658 			break;
659 		default:
660 			break;
661 		} break;
662 	case BT_BAP_EP_STATE_DISABLING:
663 		switch (old_state) {
664 		case BT_BAP_EP_STATE_ENABLING:
665 		case BT_BAP_EP_STATE_STREAMING:
666 			valid_state_transition = ase->ep.dir == BT_AUDIO_DIR_SOURCE;
667 			break;
668 		default:
669 			break;
670 		} break;
671 	case BT_BAP_EP_STATE_RELEASING:
672 		switch (old_state) {
673 		case BT_BAP_EP_STATE_CODEC_CONFIGURED:
674 		case BT_BAP_EP_STATE_QOS_CONFIGURED:
675 		case BT_BAP_EP_STATE_ENABLING:
676 		case BT_BAP_EP_STATE_STREAMING:
677 			valid_state_transition = true;
678 			break;
679 		case BT_BAP_EP_STATE_DISABLING:
680 			valid_state_transition = ase->ep.dir == BT_AUDIO_DIR_SOURCE;
681 			break;
682 		default:
683 			break;
684 		} break;
685 	}
686 
687 	if (!valid_state_transition) {
688 		BT_ASSERT_MSG(false, "Invalid state transition: %s -> %s",
689 			      bt_bap_ep_state_str(old_state), bt_bap_ep_state_str(state));
690 
691 		return -EBADMSG;
692 	}
693 
694 	ase->state_pending = state;
695 
696 	err = k_work_schedule(&ase->state_transition_work, K_NO_WAIT);
697 	if (err < 0) {
698 		LOG_ERR("Failed to schedule state transition work err %d", err);
699 		return err;
700 	}
701 
702 	return 0;
703 }
704 
ascs_ep_get_status_config(struct bt_bap_ep * ep,struct net_buf_simple * buf)705 static void ascs_ep_get_status_config(struct bt_bap_ep *ep, struct net_buf_simple *buf)
706 {
707 	struct bt_ascs_ase_status_config *cfg;
708 	struct bt_audio_codec_qos_pref *pref = &ep->qos_pref;
709 
710 	cfg = net_buf_simple_add(buf, sizeof(*cfg));
711 	cfg->framing = pref->unframed_supported ? BT_ASCS_QOS_FRAMING_UNFRAMED
712 						: BT_ASCS_QOS_FRAMING_FRAMED;
713 	cfg->phy = pref->phy;
714 	cfg->rtn = pref->rtn;
715 	cfg->latency = sys_cpu_to_le16(pref->latency);
716 	sys_put_le24(pref->pd_min, cfg->pd_min);
717 	sys_put_le24(pref->pd_max, cfg->pd_max);
718 	sys_put_le24(pref->pref_pd_min, cfg->prefer_pd_min);
719 	sys_put_le24(pref->pref_pd_max, cfg->prefer_pd_max);
720 	cfg->codec.id = ep->codec_cfg.id;
721 	cfg->codec.cid = sys_cpu_to_le16(ep->codec_cfg.cid);
722 	cfg->codec.vid = sys_cpu_to_le16(ep->codec_cfg.vid);
723 
724 	LOG_DBG("dir %s unframed_supported 0x%02x phy 0x%02x rtn %u "
725 		"latency %u pd_min %u pd_max %u pref_pd_min %u pref_pd_max %u codec id 0x%02x",
726 		bt_audio_dir_str(ep->dir), pref->unframed_supported, pref->phy, pref->rtn,
727 		pref->latency, pref->pd_min, pref->pd_max, pref->pref_pd_min, pref->pref_pd_max,
728 		ep->stream->codec_cfg->id);
729 
730 	cfg->cc_len = ep->codec_cfg.data_len;
731 	net_buf_simple_add_mem(buf, ep->codec_cfg.data, ep->codec_cfg.data_len);
732 }
733 
ascs_ep_get_status_qos(struct bt_bap_ep * ep,struct net_buf_simple * buf)734 static void ascs_ep_get_status_qos(struct bt_bap_ep *ep, struct net_buf_simple *buf)
735 {
736 	struct bt_ascs_ase_status_qos *qos;
737 
738 	qos = net_buf_simple_add(buf, sizeof(*qos));
739 	qos->cig_id = ep->cig_id;
740 	qos->cis_id = ep->cis_id;
741 	sys_put_le24(ep->stream->qos->interval, qos->interval);
742 	qos->framing = ep->stream->qos->framing;
743 	qos->phy = ep->stream->qos->phy;
744 	qos->sdu = sys_cpu_to_le16(ep->stream->qos->sdu);
745 	qos->rtn = ep->stream->qos->rtn;
746 	qos->latency = sys_cpu_to_le16(ep->stream->qos->latency);
747 	sys_put_le24(ep->stream->qos->pd, qos->pd);
748 
749 	LOG_DBG("dir %s codec id 0x%02x interval %u framing 0x%02x phy 0x%02x "
750 		"rtn %u latency %u pd %u",
751 		bt_audio_dir_str(ep->dir), ep->stream->codec_cfg->id, ep->stream->qos->interval,
752 		ep->stream->qos->framing, ep->stream->qos->phy, ep->stream->qos->rtn,
753 		ep->stream->qos->latency, ep->stream->qos->pd);
754 }
755 
ascs_ep_get_status_enable(struct bt_bap_ep * ep,struct net_buf_simple * buf)756 static void ascs_ep_get_status_enable(struct bt_bap_ep *ep, struct net_buf_simple *buf)
757 {
758 	struct bt_ascs_ase_status_enable *enable;
759 
760 	enable = net_buf_simple_add(buf, sizeof(*enable));
761 	enable->cig_id = ep->cig_id;
762 	enable->cis_id = ep->cis_id;
763 
764 	enable->metadata_len = ep->codec_cfg.meta_len;
765 	net_buf_simple_add_mem(buf, ep->codec_cfg.meta, ep->codec_cfg.meta_len);
766 
767 	LOG_DBG("dir %s cig 0x%02x cis 0x%02x",
768 		bt_audio_dir_str(ep->dir), ep->cig_id, ep->cis_id);
769 }
770 
ascs_ase_read_status_idle(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)771 static ssize_t ascs_ase_read_status_idle(struct bt_conn *conn, const struct bt_gatt_attr *attr,
772 					 void *buf, uint16_t len, uint16_t offset)
773 {
774 	struct bt_ascs_ase_status status = {
775 		.id = POINTER_TO_UINT(BT_AUDIO_CHRC_USER_DATA(attr)),
776 		.state = BT_BAP_EP_STATE_IDLE,
777 	};
778 
779 	LOG_DBG("conn %p id 0x%02x", (void *)conn, status.id);
780 
781 	return bt_gatt_attr_read(conn, attr, buf, len, offset, &status, sizeof(status));
782 }
783 
ascs_ep_get_status(struct bt_bap_ep * ep,struct net_buf_simple * buf)784 static int ascs_ep_get_status(struct bt_bap_ep *ep, struct net_buf_simple *buf)
785 {
786 	if (!ep || !buf) {
787 		return -EINVAL;
788 	}
789 
790 	LOG_DBG("ep %p id 0x%02x state %s", ep, ep->status.id,
791 		bt_bap_ep_state_str(ep->status.state));
792 
793 	/* Reset if buffer before using */
794 	net_buf_simple_reset(buf);
795 
796 	(void)net_buf_simple_add_mem(buf, &ep->status, sizeof(ep->status));
797 
798 	switch (ep->status.state) {
799 	case BT_BAP_EP_STATE_IDLE:
800 	/* Fallthrough */
801 	case BT_BAP_EP_STATE_RELEASING:
802 		break;
803 	case BT_BAP_EP_STATE_CODEC_CONFIGURED:
804 		ascs_ep_get_status_config(ep, buf);
805 		break;
806 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
807 		ascs_ep_get_status_qos(ep, buf);
808 		break;
809 	case BT_BAP_EP_STATE_ENABLING:
810 	/* Fallthrough */
811 	case BT_BAP_EP_STATE_STREAMING:
812 	/* Fallthrough */
813 	case BT_BAP_EP_STATE_DISABLING:
814 		ascs_ep_get_status_enable(ep, buf);
815 		break;
816 	default:
817 		LOG_ERR("Invalid Endpoint state");
818 		break;
819 	}
820 
821 	return 0;
822 }
823 
ascs_iso_accept(const struct bt_iso_accept_info * info,struct bt_iso_chan ** iso_chan)824 static int ascs_iso_accept(const struct bt_iso_accept_info *info, struct bt_iso_chan **iso_chan)
825 {
826 	LOG_DBG("conn %p", (void *)info->acl);
827 
828 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
829 		struct bt_ascs_ase *ase = &ase_pool[i];
830 		enum bt_bap_ep_state state;
831 		struct bt_iso_chan *chan;
832 
833 		if (ase->conn != info->acl ||
834 		    ase->ep.cig_id != info->cig_id ||
835 		    ase->ep.cis_id != info->cis_id) {
836 			continue;
837 		}
838 
839 		state = ascs_ep_get_state(&ase->ep);
840 		if (state != BT_BAP_EP_STATE_ENABLING && state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
841 			LOG_WRN("ase %p cannot accept ISO connection", ase);
842 			break;
843 		}
844 
845 		__ASSERT(ase->ep.iso != NULL, "ep %p not bound with ISO", &ase->ep);
846 
847 		chan = &ase->ep.iso->chan;
848 		if (chan->iso != NULL) {
849 			LOG_WRN("ase %p chan %p already connected", ase, chan);
850 			return -EALREADY;
851 		}
852 
853 		*iso_chan = chan;
854 
855 		LOG_DBG("iso_chan %p", *iso_chan);
856 
857 		return 0;
858 	}
859 
860 	return -EACCES;
861 }
862 
863 #if defined(CONFIG_BT_AUDIO_RX)
ascs_iso_recv(struct bt_iso_chan * chan,const struct bt_iso_recv_info * info,struct net_buf * buf)864 static void ascs_iso_recv(struct bt_iso_chan *chan,
865 			  const struct bt_iso_recv_info *info,
866 			  struct net_buf *buf)
867 {
868 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
869 	const struct bt_bap_stream_ops *ops;
870 	struct bt_bap_stream *stream;
871 	struct bt_bap_ep *ep;
872 
873 	ep = iso->rx.ep;
874 	if (ep == NULL) {
875 		/* In the case that the CIS has been setup as bidirectional, and
876 		 * only one of the directions have an ASE configured yet,
877 		 * we should only care about valid ISO packets when doing this
878 		 * check. The reason is that some controllers send HCI ISO data
879 		 * packets to the host, even if no SDU was sent on the remote
880 		 * side. This basically means that empty PDUs are sent to the
881 		 * host as HCI ISO data packets, which we should just ignore
882 		 */
883 		if ((info->flags & BT_ISO_FLAGS_VALID) != 0) {
884 			LOG_DBG("Valid ISO packet of len %zu received for iso %p not bound with ep",
885 				net_buf_frags_len(buf), chan);
886 		}
887 
888 		return;
889 	}
890 
891 	if (ep->status.state != BT_BAP_EP_STATE_STREAMING) {
892 		if (IS_ENABLED(CONFIG_BT_BAP_DEBUG_STREAM_DATA)) {
893 			LOG_DBG("ep %p is not in the streaming state: %s", ep,
894 				bt_bap_ep_state_str(ep->status.state));
895 		}
896 
897 		return;
898 	}
899 
900 	stream = ep->stream;
901 	if (stream == NULL) {
902 		LOG_ERR("No stream for ep %p", ep);
903 		return;
904 	}
905 
906 	ops = stream->ops;
907 
908 	if (IS_ENABLED(CONFIG_BT_BAP_DEBUG_STREAM_DATA)) {
909 		LOG_DBG("stream %p ep %p len %zu", stream, stream->ep, net_buf_frags_len(buf));
910 	}
911 
912 	if (ops != NULL && ops->recv != NULL) {
913 		ops->recv(stream, info, buf);
914 	} else {
915 		LOG_WRN("No callback for recv set");
916 	}
917 }
918 #endif /* CONFIG_BT_AUDIO_RX */
919 
920 #if defined(CONFIG_BT_AUDIO_TX)
ascs_iso_sent(struct bt_iso_chan * chan)921 static void ascs_iso_sent(struct bt_iso_chan *chan)
922 {
923 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
924 	const struct bt_bap_stream_ops *ops;
925 	struct bt_bap_stream *stream;
926 	struct bt_bap_ep *ep;
927 
928 	ep = iso->tx.ep;
929 	if (ep == NULL) {
930 		LOG_ERR("iso %p not bound with ep", chan);
931 		return;
932 	}
933 
934 	stream = ep->stream;
935 	if (stream == NULL) {
936 		LOG_ERR("No stream for ep %p", ep);
937 		return;
938 	}
939 
940 	ops = stream->ops;
941 
942 	if (IS_ENABLED(CONFIG_BT_BAP_DEBUG_STREAM_DATA)) {
943 		LOG_DBG("stream %p ep %p", stream, stream->ep);
944 	}
945 
946 	if (ops != NULL && ops->sent != NULL) {
947 		ops->sent(stream);
948 	}
949 }
950 #endif /* CONFIG_BT_AUDIO_TX */
951 
ascs_update_sdu_size(struct bt_bap_ep * ep)952 static void ascs_update_sdu_size(struct bt_bap_ep *ep)
953 {
954 	struct bt_iso_chan_io_qos *io_qos;
955 	struct bt_audio_codec_qos *codec_qos = &ep->qos;
956 
957 	if (ep->dir == BT_AUDIO_DIR_SINK) {
958 		io_qos = ep->iso->chan.qos->rx;
959 	} else if (ep->dir == BT_AUDIO_DIR_SOURCE) {
960 		io_qos = ep->iso->chan.qos->tx;
961 	} else {
962 		return;
963 	}
964 
965 	io_qos->sdu = codec_qos->sdu;
966 	io_qos->rtn = codec_qos->rtn;
967 }
968 
ascs_ep_iso_connected(struct bt_bap_ep * ep)969 static void ascs_ep_iso_connected(struct bt_bap_ep *ep)
970 {
971 	struct bt_ascs_ase *ase = CONTAINER_OF(ep, struct bt_ascs_ase, ep);
972 	const struct bt_bap_stream_ops *stream_ops;
973 	struct bt_bap_stream *stream;
974 
975 	if (ep->status.state != BT_BAP_EP_STATE_ENABLING) {
976 		LOG_DBG("ep %p not in enabling state: %s", ep,
977 			bt_bap_ep_state_str(ep->status.state));
978 		return;
979 	}
980 
981 	stream = ep->stream;
982 	if (stream == NULL) {
983 		LOG_ERR("No stream for ep %p", ep);
984 		return;
985 	}
986 
987 	/* Reset reason */
988 	ep->reason = BT_HCI_ERR_SUCCESS;
989 	ase->unexpected_iso_link_loss = false;
990 
991 	/* Some values are not provided by the HCI events when the CIS is established for the
992 	 * peripheral, so we update them here based on the parameters provided by the BAP Unicast
993 	 * Client
994 	 */
995 	ascs_update_sdu_size(ep);
996 
997 	LOG_DBG("stream %p ep %p dir %s", stream, ep, bt_audio_dir_str(ep->dir));
998 
999 #if defined(CONFIG_BT_BAP_DEBUG_STREAM_SEQ_NUM)
1000 	/* reset sequence number */
1001 	stream->_prev_seq_num = 0U;
1002 #endif /* CONFIG_BT_BAP_DEBUG_STREAM_SEQ_NUM */
1003 
1004 	stream_ops = stream->ops;
1005 	if (stream_ops != NULL && stream_ops->connected != NULL) {
1006 		stream_ops->connected(stream);
1007 	}
1008 
1009 	if (ep->dir == BT_AUDIO_DIR_SINK && ep->receiver_ready) {
1010 		/* Source ASEs shall be ISO connected first, and then receive
1011 		 * the receiver start ready command to enter the streaming
1012 		 * state
1013 		 */
1014 		ascs_ep_set_state(ep, BT_BAP_EP_STATE_STREAMING);
1015 	}
1016 }
1017 
ascs_iso_connected(struct bt_iso_chan * chan)1018 static void ascs_iso_connected(struct bt_iso_chan *chan)
1019 {
1020 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
1021 
1022 	if (iso->rx.ep == NULL && iso->tx.ep == NULL) {
1023 		LOG_ERR("iso %p not bound with ep", chan);
1024 		return;
1025 	}
1026 
1027 	if (iso->rx.ep != NULL) {
1028 		ascs_ep_iso_connected(iso->rx.ep);
1029 	}
1030 
1031 	if (iso->tx.ep != NULL) {
1032 		ascs_ep_iso_connected(iso->tx.ep);
1033 	}
1034 }
1035 
ascs_ep_iso_disconnected(struct bt_bap_ep * ep,uint8_t reason)1036 static void ascs_ep_iso_disconnected(struct bt_bap_ep *ep, uint8_t reason)
1037 {
1038 	struct bt_ascs_ase *ase = CONTAINER_OF(ep, struct bt_ascs_ase, ep);
1039 	const struct bt_bap_stream_ops *stream_ops;
1040 	struct bt_bap_stream *stream;
1041 
1042 	stream = ep->stream;
1043 	if (stream == NULL) {
1044 		LOG_ERR("No stream for ep %p", ep);
1045 		return;
1046 	}
1047 
1048 	LOG_DBG("stream %p ep %p state %s reason 0x%02x", stream, stream->ep,
1049 		bt_bap_ep_state_str(ep->status.state), reason);
1050 
1051 	stream_ops = stream->ops;
1052 	if (stream_ops != NULL && stream_ops->disconnected != NULL) {
1053 		stream_ops->disconnected(stream, reason);
1054 	}
1055 
1056 	/* Cancel ASE disconnect work if pending */
1057 	(void)k_work_cancel_delayable(&ase->disconnect_work);
1058 	ep->reason = reason;
1059 
1060 	if (ep->status.state == BT_BAP_EP_STATE_RELEASING) {
1061 		ascs_ep_set_state(ep, BT_BAP_EP_STATE_IDLE);
1062 	} else if (ep->status.state == BT_BAP_EP_STATE_STREAMING ||
1063 		   ep->status.state == BT_BAP_EP_STATE_DISABLING) {
1064 		/* ASCS_v1.0 3.2 ASE state machine transitions
1065 		 *
1066 		 * If the server detects link loss of a CIS for an ASE in the Streaming
1067 		 * state or the Disabling state, the server shall immediately transition
1068 		 * that ASE to the QoS Configured state.
1069 		 */
1070 		ase->unexpected_iso_link_loss = true;
1071 
1072 		ascs_ep_set_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
1073 	}
1074 }
1075 
ascs_iso_disconnected(struct bt_iso_chan * chan,uint8_t reason)1076 static void ascs_iso_disconnected(struct bt_iso_chan *chan, uint8_t reason)
1077 {
1078 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
1079 
1080 	if (iso->rx.ep == NULL && iso->tx.ep == NULL) {
1081 		return;
1082 	}
1083 
1084 	if (iso->rx.ep != NULL) {
1085 		ascs_ep_iso_disconnected(iso->rx.ep, reason);
1086 	}
1087 
1088 	if (iso->tx.ep != NULL) {
1089 		ascs_ep_iso_disconnected(iso->tx.ep, reason);
1090 	}
1091 }
1092 
1093 static struct bt_iso_chan_ops ascs_iso_ops = {
1094 #if defined(CONFIG_BT_AUDIO_RX)
1095 	.recv = ascs_iso_recv,
1096 #endif /* CONFIG_BT_AUDIO_RX */
1097 #if defined(CONFIG_BT_AUDIO_TX)
1098 	.sent = ascs_iso_sent,
1099 #endif /* CONFIG_BT_AUDIO_TX */
1100 	.connected = ascs_iso_connected,
1101 	.disconnected = ascs_iso_disconnected,
1102 };
1103 
ascs_ase_cfg_changed(const struct bt_gatt_attr * attr,uint16_t value)1104 static void ascs_ase_cfg_changed(const struct bt_gatt_attr *attr,
1105 				 uint16_t value)
1106 {
1107 	LOG_DBG("attr %p value 0x%04x", attr, value);
1108 }
1109 
1110 #define CP_RSP_BUF_SIZE                                                                            \
1111 	(sizeof(struct bt_ascs_cp_rsp) + (ASE_COUNT * sizeof(struct bt_ascs_cp_ase_rsp)))
1112 
1113 /* Ensure that the cp_rsp_buf can fit in any notification
1114  * (sizeof buffer - header for notification)
1115  */
1116 BUILD_ASSERT(BT_ATT_BUF_SIZE - NTF_HEADER_SIZE >= CP_RSP_BUF_SIZE,
1117 	     "BT_ATT_BUF_SIZE not large enough to hold responses for all ASEs");
1118 NET_BUF_SIMPLE_DEFINE_STATIC(cp_rsp_buf, CP_RSP_BUF_SIZE);
1119 
ascs_cp_rsp_init(uint8_t op)1120 static void ascs_cp_rsp_init(uint8_t op)
1121 {
1122 	struct bt_ascs_cp_rsp *rsp;
1123 
1124 	net_buf_simple_reset(&cp_rsp_buf);
1125 
1126 	rsp = net_buf_simple_add(&cp_rsp_buf, sizeof(*rsp));
1127 	rsp->op = op;
1128 	rsp->num_ase = 0;
1129 }
1130 
1131 /* Add response to an opcode/ASE ID */
ascs_cp_rsp_add(uint8_t id,uint8_t code,uint8_t reason)1132 static void ascs_cp_rsp_add(uint8_t id, uint8_t code, uint8_t reason)
1133 {
1134 	struct bt_ascs_cp_rsp *rsp = (void *)cp_rsp_buf.__buf;
1135 	struct bt_ascs_cp_ase_rsp *ase_rsp;
1136 
1137 	LOG_DBG("id 0x%02x code %s (0x%02x) reason %s (0x%02x)", id,
1138 		bt_ascs_rsp_str(code), code, bt_ascs_reason_str(reason), reason);
1139 
1140 	if (rsp->num_ase == BT_ASCS_UNSUPP_OR_LENGTH_ERR_NUM_ASE) {
1141 		return;
1142 	}
1143 
1144 	switch (code) {
1145 	/* If the Response_Code value is 0x01 or 0x02, Number_of_ASEs shall be
1146 	 * set to 0xFF.
1147 	 */
1148 	case BT_BAP_ASCS_RSP_CODE_NOT_SUPPORTED:
1149 	case BT_BAP_ASCS_RSP_CODE_INVALID_LENGTH:
1150 		rsp->num_ase = BT_ASCS_UNSUPP_OR_LENGTH_ERR_NUM_ASE;
1151 		break;
1152 	default:
1153 		rsp->num_ase++;
1154 		break;
1155 	}
1156 
1157 	ase_rsp = net_buf_simple_add(&cp_rsp_buf, sizeof(*ase_rsp));
1158 	ase_rsp->id = id;
1159 	ase_rsp->code = code;
1160 	ase_rsp->reason = reason;
1161 }
1162 
ascs_cp_rsp_success(uint8_t id)1163 static void ascs_cp_rsp_success(uint8_t id)
1164 {
1165 	ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_SUCCESS, BT_BAP_ASCS_REASON_NONE);
1166 }
1167 
ase_release(struct bt_ascs_ase * ase,uint8_t reason,struct bt_bap_ascs_rsp * rsp)1168 static int ase_release(struct bt_ascs_ase *ase, uint8_t reason, struct bt_bap_ascs_rsp *rsp)
1169 {
1170 	enum bt_bap_ep_state state = ascs_ep_get_state(&ase->ep);
1171 	int err;
1172 
1173 	if (state == BT_BAP_EP_STATE_IDLE || state == BT_BAP_EP_STATE_RELEASING) {
1174 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(state));
1175 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
1176 				       BT_BAP_ASCS_REASON_NONE);
1177 		return -EBADMSG;
1178 	}
1179 
1180 	if (unicast_server_cb == NULL || unicast_server_cb->release == NULL) {
1181 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1182 				       BT_BAP_ASCS_REASON_NONE);
1183 		return -ENOTSUP;
1184 	}
1185 
1186 	err = unicast_server_cb->release(ase->ep.stream, rsp);
1187 	if (err) {
1188 		if (rsp->code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
1189 			*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1190 					       BT_BAP_ASCS_REASON_NONE);
1191 		}
1192 
1193 		LOG_ERR("Release failed: err %d, code %u, reason %u", err, rsp->code, rsp->reason);
1194 		return err;
1195 	}
1196 
1197 	/* Set reason in case this exits the streaming state */
1198 	ase->ep.reason = reason;
1199 
1200 	ascs_ep_set_state(&ase->ep, BT_BAP_EP_STATE_RELEASING);
1201 
1202 	*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS, BT_BAP_ASCS_REASON_NONE);
1203 	return 0;
1204 }
1205 
bt_ascs_release_ase(struct bt_bap_ep * ep)1206 int bt_ascs_release_ase(struct bt_bap_ep *ep)
1207 {
1208 	struct bt_ascs_ase *ase = CONTAINER_OF(ep, struct bt_ascs_ase, ep);
1209 	const enum bt_bap_ep_state state = ascs_ep_get_state(&ase->ep);
1210 
1211 	if (state == BT_BAP_EP_STATE_IDLE) {
1212 		ase_free(ase);
1213 		return 0;
1214 	}
1215 
1216 	return ase_release(ase, BT_HCI_ERR_LOCALHOST_TERM_CONN, BT_BAP_ASCS_RSP_NULL);
1217 }
1218 
ase_disable(struct bt_ascs_ase * ase,uint8_t reason,struct bt_bap_ascs_rsp * rsp)1219 static int ase_disable(struct bt_ascs_ase *ase, uint8_t reason, struct bt_bap_ascs_rsp *rsp)
1220 {
1221 	struct bt_bap_stream *stream;
1222 	struct bt_bap_ep *ep;
1223 	int err;
1224 
1225 	LOG_DBG("ase %p", ase);
1226 
1227 	ep = &ase->ep;
1228 
1229 	switch (ep->status.state) {
1230 	/* Valid only if ASE_State field = 0x03 (Enabling) */
1231 	case BT_BAP_EP_STATE_ENABLING:
1232 		/* or 0x04 (Streaming) */
1233 	case BT_BAP_EP_STATE_STREAMING:
1234 		break;
1235 	default:
1236 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(ep->status.state));
1237 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
1238 				       BT_BAP_ASCS_REASON_NONE);
1239 		return -EBADMSG;
1240 	}
1241 
1242 	stream = ep->stream;
1243 
1244 	if (unicast_server_cb == NULL || unicast_server_cb->disable == NULL) {
1245 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED, BT_BAP_ASCS_REASON_NONE);
1246 		return -ENOTSUP;
1247 	}
1248 
1249 	err = unicast_server_cb->disable(stream, rsp);
1250 	if (err) {
1251 		if (rsp->code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
1252 			*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1253 					       BT_BAP_ASCS_REASON_NONE);
1254 		}
1255 
1256 		LOG_ERR("Disable failed: err %d, code %u, reason %u", err, rsp->code, rsp->reason);
1257 		return err;
1258 	}
1259 
1260 	/* Set reason in case this exits the streaming state */
1261 	ep->reason = reason;
1262 
1263 	/* The ASE state machine goes into different states from this operation
1264 	 * based on whether it is a source or a sink ASE.
1265 	 */
1266 	if (ep->dir == BT_AUDIO_DIR_SOURCE) {
1267 		ascs_ep_set_state(ep, BT_BAP_EP_STATE_DISABLING);
1268 	} else {
1269 		ascs_ep_set_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
1270 	}
1271 
1272 	*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS, BT_BAP_ASCS_REASON_NONE);
1273 	return 0;
1274 }
1275 
bt_ascs_disable_ase(struct bt_bap_ep * ep)1276 int bt_ascs_disable_ase(struct bt_bap_ep *ep)
1277 {
1278 	struct bt_ascs_ase *ase = CONTAINER_OF(ep, struct bt_ascs_ase, ep);
1279 
1280 	return ase_disable(ase, BT_HCI_ERR_LOCALHOST_TERM_CONN, BT_BAP_ASCS_RSP_NULL);
1281 }
1282 
disconnected(struct bt_conn * conn,uint8_t reason)1283 static void disconnected(struct bt_conn *conn, uint8_t reason)
1284 {
1285 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
1286 		struct bt_ascs_ase *ase = &ase_pool[i];
1287 
1288 		if (ase->conn != conn) {
1289 			continue;
1290 		}
1291 
1292 		if (ase->ep.status.state != BT_BAP_EP_STATE_IDLE) {
1293 			/* We must set the state to idle when the ACL is disconnected immediately,
1294 			 * as when the ACL disconnect callbacks have been called, the application
1295 			 * should expect there to be only a single reference to the bt_conn pointer
1296 			 * from the stack.
1297 			 * We trigger the work handler directly rather than e.g. calling
1298 			 * ase_enter_state_idle to trigger "regular" state change behavior (such) as
1299 			 * calling stream->stopped when leaving the streaming state.
1300 			 */
1301 			ase->ep.reason = reason;
1302 			ase->state_pending = BT_BAP_EP_STATE_IDLE;
1303 			state_transition_work_handler(&ase->state_transition_work.work);
1304 			/* At this point, `ase` object have been free'd */
1305 		}
1306 	}
1307 }
1308 
1309 BT_CONN_CB_DEFINE(conn_cb) = {
1310 	.disconnected = disconnected,
1311 };
1312 
1313 struct bap_iso_find_params {
1314 	struct bt_conn *acl;
1315 	uint8_t cig_id;
1316 	uint8_t cis_id;
1317 };
1318 
bap_iso_find_func(struct bt_bap_iso * iso,void * user_data)1319 static bool bap_iso_find_func(struct bt_bap_iso *iso, void *user_data)
1320 {
1321 	struct bap_iso_find_params *params = user_data;
1322 	const struct bt_bap_ep *ep;
1323 
1324 	if (iso->rx.ep != NULL) {
1325 		ep = iso->rx.ep;
1326 	} else if (iso->tx.ep != NULL) {
1327 		ep = iso->tx.ep;
1328 	} else {
1329 		return false;
1330 	}
1331 
1332 	return ep->stream->conn == params->acl &&
1333 	       ep->cig_id == params->cig_id &&
1334 	       ep->cis_id == params->cis_id;
1335 }
1336 
bap_iso_get_or_new(struct bt_conn * conn,uint8_t cig_id,uint8_t cis_id)1337 static struct bt_bap_iso *bap_iso_get_or_new(struct bt_conn *conn, uint8_t cig_id, uint8_t cis_id)
1338 {
1339 	struct bt_bap_iso *iso;
1340 	struct bap_iso_find_params params = {
1341 		.acl = bt_conn_ref(conn),
1342 		.cig_id = cig_id,
1343 		.cis_id = cis_id,
1344 	};
1345 
1346 	iso = bt_bap_iso_find(bap_iso_find_func, &params);
1347 	bt_conn_unref(conn);
1348 
1349 	if (iso) {
1350 		return iso;
1351 	}
1352 
1353 	iso = bt_bap_iso_new();
1354 	if (!iso) {
1355 		return NULL;
1356 	}
1357 
1358 	bt_bap_iso_init(iso, &ascs_iso_ops);
1359 
1360 	return iso;
1361 }
1362 
ase_attr_cb(const struct bt_gatt_attr * attr,uint16_t handle,void * user_data)1363 static uint8_t ase_attr_cb(const struct bt_gatt_attr *attr, uint16_t handle,
1364 			   void *user_data)
1365 {
1366 	struct bt_ascs_ase *ase = user_data;
1367 
1368 	if (ase->ep.status.id == POINTER_TO_UINT(BT_AUDIO_CHRC_USER_DATA(attr))) {
1369 		ase->attr = attr;
1370 
1371 		return BT_GATT_ITER_STOP;
1372 	}
1373 
1374 	return BT_GATT_ITER_CONTINUE;
1375 }
1376 
ascs_ep_init(struct bt_bap_ep * ep,uint8_t id)1377 void ascs_ep_init(struct bt_bap_ep *ep, uint8_t id)
1378 {
1379 	LOG_DBG("ep %p id 0x%02x", ep, id);
1380 
1381 	(void)memset(ep, 0, sizeof(*ep));
1382 	ep->status.id = id;
1383 	ep->dir = ASE_DIR(id);
1384 	ep->reason = BT_HCI_ERR_SUCCESS;
1385 }
1386 
ase_init(struct bt_ascs_ase * ase,struct bt_conn * conn,uint8_t id)1387 static void ase_init(struct bt_ascs_ase *ase, struct bt_conn *conn, uint8_t id)
1388 {
1389 	memset(ase, 0, sizeof(*ase));
1390 
1391 	ascs_ep_init(&ase->ep, id);
1392 
1393 	ase->conn = bt_conn_ref(conn);
1394 
1395 	/* Lookup ASE characteristic */
1396 	bt_gatt_foreach_attr_type(0x0001, 0xffff, ASE_UUID(id), NULL, 0, ase_attr_cb, ase);
1397 
1398 	__ASSERT(ase->attr, "ASE characteristic not found\n");
1399 
1400 	k_work_init_delayable(&ase->disconnect_work, ascs_disconnect_stream_work_handler);
1401 	k_work_init_delayable(&ase->state_transition_work, state_transition_work_handler);
1402 }
1403 
ase_new(struct bt_conn * conn,uint8_t id)1404 static struct bt_ascs_ase *ase_new(struct bt_conn *conn, uint8_t id)
1405 {
1406 	struct bt_ascs_ase *ase = NULL;
1407 
1408 	__ASSERT(id > 0 && id <= ASE_COUNT, "invalid ASE_ID 0x%02x", id);
1409 
1410 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
1411 		if (ase_pool[i].conn == NULL) {
1412 			ase = &ase_pool[i];
1413 			break;
1414 		}
1415 	}
1416 
1417 	if (ase == NULL) {
1418 		return NULL;
1419 	}
1420 
1421 	ase_init(ase, conn, id);
1422 
1423 	LOG_DBG("conn %p new ase %p id 0x%02x", (void *)conn, ase, id);
1424 
1425 	return ase;
1426 }
1427 
ase_find(struct bt_conn * conn,uint8_t id)1428 static struct bt_ascs_ase *ase_find(struct bt_conn *conn, uint8_t id)
1429 {
1430 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
1431 		struct bt_ascs_ase *ase = &ase_pool[i];
1432 
1433 		if (ase->conn == conn && ase->ep.status.id == id) {
1434 			return ase;
1435 		}
1436 	}
1437 
1438 	return NULL;
1439 }
1440 
ascs_ase_read(struct bt_conn * conn,const struct bt_gatt_attr * attr,void * buf,uint16_t len,uint16_t offset)1441 static ssize_t ascs_ase_read(struct bt_conn *conn,
1442 			     const struct bt_gatt_attr *attr, void *buf,
1443 			     uint16_t len, uint16_t offset)
1444 {
1445 	uint8_t ase_id = POINTER_TO_UINT(BT_AUDIO_CHRC_USER_DATA(attr));
1446 	struct bt_ascs_ase *ase = NULL;
1447 	ssize_t ret_val;
1448 	int err;
1449 
1450 	LOG_DBG("conn %p attr %p buf %p len %u offset %u", (void *)conn, attr, buf, len, offset);
1451 
1452 	/* The callback can be used locally to read the ASE_ID in which case conn won't be set. */
1453 	if (conn != NULL) {
1454 		ase = ase_find(conn, ase_id);
1455 	}
1456 
1457 	/* If NULL, we haven't assigned an ASE, this also means that we are currently in IDLE */
1458 	if (ase == NULL) {
1459 		return ascs_ase_read_status_idle(conn, attr, buf, len, offset);
1460 	}
1461 
1462 	err = k_sem_take(&ase_buf_sem, ASE_BUF_SEM_TIMEOUT);
1463 	if (err != 0) {
1464 		LOG_DBG("Failed to take ase_buf_sem: %d", err);
1465 
1466 		return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
1467 	}
1468 
1469 	ascs_ep_get_status(&ase->ep, &ase_buf);
1470 
1471 	ret_val = bt_gatt_attr_read(conn, attr, buf, len, offset, ase_buf.data, ase_buf.len);
1472 
1473 	k_sem_give(&ase_buf_sem);
1474 
1475 	return ret_val;
1476 }
1477 
ascs_cp_cfg_changed(const struct bt_gatt_attr * attr,uint16_t value)1478 static void ascs_cp_cfg_changed(const struct bt_gatt_attr *attr, uint16_t value)
1479 {
1480 	LOG_DBG("attr %p value 0x%04x", attr, value);
1481 }
1482 
1483 struct codec_cap_lookup_id_data {
1484 	uint8_t id;
1485 	uint16_t cid;
1486 	uint16_t vid;
1487 	const struct bt_audio_codec_cap *codec_cap;
1488 };
1489 
codec_lookup_id(const struct bt_pacs_cap * cap,void * user_data)1490 static bool codec_lookup_id(const struct bt_pacs_cap *cap, void *user_data)
1491 {
1492 	struct codec_cap_lookup_id_data *data = user_data;
1493 
1494 	if (cap->codec_cap->id == data->id && cap->codec_cap->cid == data->cid &&
1495 	    cap->codec_cap->vid == data->vid) {
1496 		data->codec_cap = cap->codec_cap;
1497 
1498 		return false;
1499 	}
1500 
1501 	return true;
1502 }
1503 
ascs_ep_set_codec(struct bt_bap_ep * ep,uint8_t id,uint16_t cid,uint16_t vid,uint8_t * cc,uint8_t len,struct bt_bap_ascs_rsp * rsp)1504 static int ascs_ep_set_codec(struct bt_bap_ep *ep, uint8_t id, uint16_t cid, uint16_t vid,
1505 			     uint8_t *cc, uint8_t len, struct bt_bap_ascs_rsp *rsp)
1506 {
1507 	struct bt_audio_codec_cfg *codec_cfg;
1508 	struct codec_cap_lookup_id_data lookup_data = {
1509 		.id = id,
1510 		.cid = cid,
1511 		.vid = vid,
1512 	};
1513 
1514 	if (ep == NULL) {
1515 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_CONF_INVALID,
1516 				       BT_BAP_ASCS_REASON_CODEC_DATA);
1517 		return -EINVAL;
1518 	}
1519 
1520 	codec_cfg = &ep->codec_cfg;
1521 
1522 	LOG_DBG("ep %p dir %s codec id 0x%02x cid 0x%04x vid 0x%04x len %u",
1523 		ep, bt_audio_dir_str(ep->dir), id, cid, vid, len);
1524 
1525 	bt_pacs_cap_foreach(ep->dir, codec_lookup_id, &lookup_data);
1526 
1527 	if (lookup_data.codec_cap == NULL) {
1528 		LOG_DBG("Codec with id %u for dir %s is not supported by our capabilities",
1529 			id, bt_audio_dir_str(ep->dir));
1530 
1531 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_CONF_INVALID,
1532 				       BT_BAP_ASCS_REASON_CODEC);
1533 		return -ENOENT;
1534 	}
1535 
1536 	codec_cfg->id = id;
1537 	codec_cfg->cid = cid;
1538 	codec_cfg->vid = vid;
1539 	codec_cfg->data_len = len;
1540 	memcpy(codec_cfg->data, cc, len);
1541 	codec_cfg->path_id = lookup_data.codec_cap->path_id;
1542 
1543 	*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS, BT_BAP_ASCS_REASON_NONE);
1544 
1545 	return 0;
1546 }
1547 
ase_config(struct bt_ascs_ase * ase,const struct bt_ascs_config * cfg)1548 static int ase_config(struct bt_ascs_ase *ase, const struct bt_ascs_config *cfg)
1549 {
1550 	struct bt_bap_stream *stream;
1551 	struct bt_audio_codec_cfg codec_cfg;
1552 	struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS,
1553 						     BT_BAP_ASCS_REASON_NONE);
1554 	int err;
1555 
1556 	LOG_DBG("ase %p latency 0x%02x phy 0x%02x codec 0x%02x "
1557 		"cid 0x%04x vid 0x%04x codec config len 0x%02x",
1558 		ase, cfg->latency, cfg->phy, cfg->codec.id, cfg->codec.cid, cfg->codec.vid,
1559 		cfg->cc_len);
1560 
1561 	if (cfg->latency < BT_ASCS_CONFIG_LATENCY_LOW ||
1562 	    cfg->latency > BT_ASCS_CONFIG_LATENCY_HIGH) {
1563 		LOG_WRN("Invalid latency: 0x%02x", cfg->latency);
1564 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_CONF_INVALID,
1565 				BT_BAP_ASCS_REASON_LATENCY);
1566 		return -EINVAL;
1567 	}
1568 
1569 	if (cfg->phy < BT_ASCS_CONFIG_PHY_LE_1M ||
1570 	    cfg->phy > BT_ASCS_CONFIG_PHY_LE_CODED) {
1571 		LOG_WRN("Invalid PHY: 0x%02x", cfg->phy);
1572 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_CONF_INVALID,
1573 				BT_BAP_ASCS_REASON_PHY);
1574 		return -EINVAL;
1575 	}
1576 
1577 	if (cfg->cc_len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_DATA_SIZE) {
1578 		LOG_DBG("Can not store %u codec configuration data", cfg->cc_len);
1579 
1580 		return -ENOMEM;
1581 	}
1582 
1583 	switch (ase->ep.status.state) {
1584 	/* Valid only if ASE_State field = 0x00 (Idle) */
1585 	case BT_BAP_EP_STATE_IDLE:
1586 		/* or 0x01 (Codec Configured) */
1587 	case BT_BAP_EP_STATE_CODEC_CONFIGURED:
1588 		/* or 0x02 (QoS Configured) */
1589 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
1590 		break;
1591 	default:
1592 		LOG_WRN("Invalid operation in state: %s",
1593 			bt_bap_ep_state_str(ase->ep.status.state));
1594 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
1595 				BT_BAP_ASCS_REASON_NONE);
1596 		return -EINVAL;
1597 	}
1598 
1599 	/* Store current codec configuration to be able to restore it
1600 	 * in case of error.
1601 	 */
1602 	(void)memcpy(&codec_cfg, &ase->ep.codec_cfg, sizeof(codec_cfg));
1603 
1604 	err = ascs_ep_set_codec(&ase->ep, cfg->codec.id, sys_le16_to_cpu(cfg->codec.cid),
1605 				sys_le16_to_cpu(cfg->codec.vid), (uint8_t *)cfg->cc, cfg->cc_len,
1606 				&rsp);
1607 	if (err) {
1608 		ascs_app_rsp_warn_valid(&rsp);
1609 		(void)memcpy(&ase->ep.codec_cfg, &codec_cfg, sizeof(codec_cfg));
1610 		ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
1611 		return err;
1612 	}
1613 
1614 	if (ase->ep.stream != NULL) {
1615 		if (unicast_server_cb != NULL &&
1616 		    unicast_server_cb->reconfig != NULL) {
1617 			err = unicast_server_cb->reconfig(ase->ep.stream, ase->ep.dir,
1618 							  &ase->ep.codec_cfg, &ase->ep.qos_pref,
1619 							  &rsp);
1620 		} else {
1621 			err = -ENOTSUP;
1622 			rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1623 					      BT_BAP_ASCS_REASON_NONE);
1624 		}
1625 
1626 		if (err) {
1627 			ascs_app_rsp_warn_valid(&rsp);
1628 
1629 			if (rsp.code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
1630 				rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1631 						      BT_BAP_ASCS_REASON_NONE);
1632 			}
1633 
1634 			LOG_ERR("Reconfig failed: err %d, code %u, reason %u",
1635 				err, rsp.code, rsp.reason);
1636 
1637 			(void)memcpy(&ase->ep.codec_cfg, &codec_cfg, sizeof(codec_cfg));
1638 			ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
1639 
1640 			return err;
1641 		}
1642 
1643 		stream = ase->ep.stream;
1644 	} else {
1645 		stream = NULL;
1646 		if (unicast_server_cb != NULL &&
1647 		    unicast_server_cb->config != NULL) {
1648 			err = unicast_server_cb->config(ase->conn, &ase->ep, ase->ep.dir,
1649 							&ase->ep.codec_cfg, &stream,
1650 							&ase->ep.qos_pref, &rsp);
1651 		} else {
1652 			err = -ENOTSUP;
1653 			rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1654 					      BT_BAP_ASCS_REASON_NONE);
1655 		}
1656 
1657 		if (err || stream == NULL) {
1658 			ascs_app_rsp_warn_valid(&rsp);
1659 
1660 			if (rsp.code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
1661 				rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1662 						      BT_BAP_ASCS_REASON_NONE);
1663 			}
1664 
1665 			LOG_ERR("Config failed: err %d, stream %p, code %u, reason %u",
1666 				err, stream, rsp.code, rsp.reason);
1667 
1668 			(void)memcpy(&ase->ep.codec_cfg, &codec_cfg, sizeof(codec_cfg));
1669 			ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
1670 
1671 			return err ? err : -ENOMEM;
1672 		}
1673 
1674 		bt_bap_stream_init(stream);
1675 	}
1676 
1677 	ascs_cp_rsp_success(ASE_ID(ase));
1678 
1679 	bt_bap_stream_attach(ase->conn, stream, &ase->ep, &ase->ep.codec_cfg);
1680 
1681 	ascs_ep_set_state(&ase->ep, BT_BAP_EP_STATE_CODEC_CONFIGURED);
1682 
1683 	return 0;
1684 }
1685 
ep_lookup_stream(struct bt_conn * conn,struct bt_bap_stream * stream)1686 static struct bt_bap_ep *ep_lookup_stream(struct bt_conn *conn, struct bt_bap_stream *stream)
1687 {
1688 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
1689 		struct bt_ascs_ase *ase = &ase_pool[i];
1690 
1691 		if (ase->conn == conn && ase->ep.stream == stream) {
1692 			return &ase->ep;
1693 		}
1694 	}
1695 
1696 	return NULL;
1697 }
1698 
bt_ascs_config_ase(struct bt_conn * conn,struct bt_bap_stream * stream,struct bt_audio_codec_cfg * codec_cfg,const struct bt_audio_codec_qos_pref * qos_pref)1699 int bt_ascs_config_ase(struct bt_conn *conn, struct bt_bap_stream *stream,
1700 		       struct bt_audio_codec_cfg *codec_cfg,
1701 		       const struct bt_audio_codec_qos_pref *qos_pref)
1702 {
1703 	int err;
1704 	struct bt_ascs_ase *ase = NULL;
1705 	struct bt_bap_ep *ep;
1706 	struct codec_cap_lookup_id_data lookup_data;
1707 
1708 	CHECKIF(conn == NULL || stream == NULL || codec_cfg == NULL || qos_pref == NULL) {
1709 		LOG_DBG("NULL value(s) supplied)");
1710 		return -EINVAL;
1711 	}
1712 
1713 	ep = ep_lookup_stream(conn, stream);
1714 	if (ep != NULL) {
1715 		LOG_DBG("Stream already configured for conn %p", (void *)stream->conn);
1716 		return -EALREADY;
1717 	}
1718 
1719 	/* Get a free ASE or NULL if all ASE instances are already in use */
1720 	for (int i = 1; i <= ASE_COUNT; i++) {
1721 		if (ase_find(conn, i) == NULL) {
1722 			ase = ase_new(conn, i);
1723 			break;
1724 		}
1725 	}
1726 
1727 	if (ase == NULL) {
1728 		LOG_WRN("No free ASE found.");
1729 		return -ENOTSUP;
1730 	}
1731 
1732 	ep = &ase->ep;
1733 
1734 	if (ep == NULL) {
1735 		return -EINVAL;
1736 	}
1737 
1738 	lookup_data.id = codec_cfg->id;
1739 	lookup_data.cid = codec_cfg->cid;
1740 	lookup_data.vid = codec_cfg->vid;
1741 
1742 	bt_pacs_cap_foreach(ep->dir, codec_lookup_id, &lookup_data);
1743 
1744 	if (lookup_data.codec_cap == NULL) {
1745 		LOG_DBG("Codec with id %u for dir %s is not supported by our capabilities",
1746 			codec_cfg->id, bt_audio_dir_str(ep->dir));
1747 		return -ENOENT;
1748 	}
1749 
1750 	(void)memcpy(&ep->codec_cfg, codec_cfg, sizeof(ep->codec_cfg));
1751 
1752 	ep->qos_pref = *qos_pref;
1753 
1754 	bt_bap_stream_attach(conn, stream, ep, &ep->codec_cfg);
1755 
1756 	err = ascs_ep_set_state(ep, BT_BAP_EP_STATE_CODEC_CONFIGURED);
1757 	if (err != 0) {
1758 		bt_bap_stream_detach(stream);
1759 		ase_free(ase);
1760 		return err;
1761 	}
1762 
1763 	return 0;
1764 }
1765 
get_max_ase_rsp_for_conn(struct bt_conn * conn)1766 static uint16_t get_max_ase_rsp_for_conn(struct bt_conn *conn)
1767 {
1768 	const uint16_t max_ntf_size = get_max_ntf_size(conn);
1769 	const size_t rsp_hdr_size = sizeof(struct bt_ascs_cp_rsp);
1770 
1771 	if (max_ntf_size > rsp_hdr_size) {
1772 		return (max_ntf_size - rsp_hdr_size) / sizeof(struct bt_ascs_cp_ase_rsp);
1773 	}
1774 
1775 	return 0U;
1776 }
1777 
is_valid_num_ases(struct bt_conn * conn,uint8_t num_ases)1778 static bool is_valid_num_ases(struct bt_conn *conn, uint8_t num_ases)
1779 {
1780 	const uint16_t max_ase_rsp = get_max_ase_rsp_for_conn(conn);
1781 
1782 	if (num_ases < 1U) {
1783 		LOG_WRN("Number_of_ASEs parameter value is less than 1");
1784 		return false;
1785 	} else if (num_ases > ASE_COUNT) {
1786 		/* If the request is for more ASEs than we have, we just reject the request */
1787 		LOG_DBG("Number_of_ASEs parameter value (%u) is greater than %d", num_ases,
1788 			ASE_COUNT);
1789 		return false;
1790 	} else if (num_ases > max_ase_rsp) {
1791 		/* If the request is for more ASEs than we can respond to, we reject the request */
1792 		LOG_DBG("Number_of_ASEs parameter value (%u) is greater than what we can respond "
1793 			"to (%u) based on the MTU",
1794 			num_ases, max_ase_rsp);
1795 		return false;
1796 	}
1797 
1798 	return true;
1799 }
1800 
is_valid_config_len(struct bt_conn * conn,struct net_buf_simple * buf)1801 static bool is_valid_config_len(struct bt_conn *conn, struct net_buf_simple *buf)
1802 {
1803 	const struct bt_ascs_config_op *op;
1804 	struct net_buf_simple_state state;
1805 
1806 	net_buf_simple_save(buf, &state);
1807 
1808 	if (buf->len < sizeof(*op)) {
1809 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
1810 		return false;
1811 	}
1812 
1813 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
1814 	if (!is_valid_num_ases(conn, op->num_ases)) {
1815 		return false;
1816 	}
1817 
1818 	for (uint8_t i = 0U; i < op->num_ases; i++) {
1819 		const struct bt_ascs_config *config;
1820 
1821 		if (buf->len < sizeof(*config)) {
1822 			LOG_WRN("Malformed params array");
1823 			return false;
1824 		}
1825 
1826 		config = net_buf_simple_pull_mem(buf, sizeof(*config));
1827 		if (buf->len < config->cc_len) {
1828 			LOG_WRN("Malformed codec specific config");
1829 			return false;
1830 		}
1831 
1832 		(void)net_buf_simple_pull_mem(buf, config->cc_len);
1833 	}
1834 
1835 	if (buf->len > 0) {
1836 		LOG_WRN("Unexpected data");
1837 		return false;
1838 	}
1839 
1840 	net_buf_simple_restore(buf, &state);
1841 
1842 	return true;
1843 }
1844 
ascs_config(struct bt_conn * conn,struct net_buf_simple * buf)1845 static ssize_t ascs_config(struct bt_conn *conn, struct net_buf_simple *buf)
1846 {
1847 	const struct bt_ascs_config_op *req;
1848 	const struct bt_ascs_config *cfg;
1849 
1850 	if (!is_valid_config_len(conn, buf)) {
1851 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
1852 	}
1853 
1854 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
1855 
1856 	LOG_DBG("num_ases %u", req->num_ases);
1857 
1858 	for (uint8_t i = 0; i < req->num_ases; i++) {
1859 		struct bt_ascs_ase *ase;
1860 		int err;
1861 
1862 		cfg = net_buf_simple_pull_mem(buf, sizeof(*cfg));
1863 		(void)net_buf_simple_pull(buf, cfg->cc_len);
1864 
1865 		LOG_DBG("ase 0x%02x cc_len %u", cfg->ase, cfg->cc_len);
1866 
1867 		if (!cfg->ase || cfg->ase > ASE_COUNT) {
1868 			LOG_WRN("Invalid ASE ID: %u", cfg->ase);
1869 			ascs_cp_rsp_add(cfg->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
1870 					BT_BAP_ASCS_REASON_NONE);
1871 			continue;
1872 		}
1873 
1874 		ase = ase_find(conn, cfg->ase);
1875 		if (ase != NULL) {
1876 			ase_config(ase, cfg);
1877 			continue;
1878 		}
1879 
1880 		ase = ase_new(conn, cfg->ase);
1881 		if (!ase) {
1882 			ascs_cp_rsp_add(cfg->ase, BT_BAP_ASCS_RSP_CODE_NO_MEM,
1883 					BT_BAP_ASCS_REASON_NONE);
1884 			LOG_WRN("No free ASE found for config ASE ID 0x%02x", cfg->ase);
1885 			continue;
1886 		}
1887 
1888 		err = ase_config(ase, cfg);
1889 		if (err != 0) {
1890 			ase_free(ase);
1891 		}
1892 	}
1893 
1894 	return buf->size;
1895 }
1896 
bt_ascs_foreach_ep(struct bt_conn * conn,bt_bap_ep_func_t func,void * user_data)1897 void bt_ascs_foreach_ep(struct bt_conn *conn, bt_bap_ep_func_t func, void *user_data)
1898 {
1899 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
1900 		struct bt_ascs_ase *ase = &ase_pool[i];
1901 
1902 		if (ase->conn == conn) {
1903 			func(&ase->ep, user_data);
1904 		}
1905 	}
1906 }
1907 
ase_qos(struct bt_ascs_ase * ase,uint8_t cig_id,uint8_t cis_id,struct bt_audio_codec_qos * qos,struct bt_bap_ascs_rsp * rsp)1908 static void ase_qos(struct bt_ascs_ase *ase, uint8_t cig_id, uint8_t cis_id,
1909 		    struct bt_audio_codec_qos *qos, struct bt_bap_ascs_rsp *rsp)
1910 {
1911 	struct bt_bap_ep *ep = &ase->ep;
1912 	struct bt_bap_stream *stream;
1913 
1914 	LOG_DBG("ase %p cig 0x%02x cis 0x%02x interval %u framing 0x%02x phy 0x%02x sdu %u rtn %u "
1915 		"latency %u pd %u", ase, cig_id, cis_id, qos->interval, qos->framing, qos->phy,
1916 		qos->sdu, qos->rtn, qos->latency, qos->pd);
1917 
1918 	switch (ep->status.state) {
1919 	/* Valid only if ASE_State field = 0x01 (Codec Configured) */
1920 	case BT_BAP_EP_STATE_CODEC_CONFIGURED:
1921 	/* or 0x02 (QoS Configured) */
1922 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
1923 		break;
1924 	default:
1925 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(ep->status.state));
1926 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
1927 				       BT_BAP_ASCS_REASON_NONE);
1928 		return;
1929 	}
1930 
1931 	stream = ep->stream;
1932 	if (stream == NULL) {
1933 		LOG_ERR("NULL stream");
1934 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED, BT_BAP_ASCS_REASON_NONE);
1935 		return;
1936 	}
1937 
1938 	if (stream->ep == NULL) {
1939 		LOG_ERR("NULL stream->ep");
1940 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED, BT_BAP_ASCS_REASON_NONE);
1941 		return;
1942 	}
1943 
1944 	rsp->reason = bt_audio_verify_qos(qos);
1945 	if (rsp->reason != BT_BAP_ASCS_REASON_NONE) {
1946 		rsp->code = BT_BAP_ASCS_RSP_CODE_CONF_INVALID;
1947 		return;
1948 	}
1949 
1950 	rsp->reason = bt_bap_stream_verify_qos(stream, qos);
1951 	if (rsp->reason != BT_BAP_ASCS_REASON_NONE) {
1952 		rsp->code = BT_BAP_ASCS_RSP_CODE_CONF_INVALID;
1953 		return;
1954 	}
1955 
1956 	if (unicast_server_cb != NULL && unicast_server_cb->qos != NULL) {
1957 		int err = unicast_server_cb->qos(stream, qos, rsp);
1958 
1959 		if (err) {
1960 			if (rsp->code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
1961 				*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
1962 						       BT_BAP_ASCS_REASON_NONE);
1963 			}
1964 
1965 			LOG_DBG("Application returned error: err %d status %u reason %u",
1966 				err, rsp->code, rsp->reason);
1967 			return;
1968 		}
1969 	}
1970 
1971 	/* QoS->QoS transition. Unbind ISO if CIG/CIS changed. */
1972 	if (ep->iso != NULL && (ep->cig_id != cig_id || ep->cis_id != cis_id)) {
1973 		bt_bap_iso_unbind_ep(ep->iso, ep);
1974 	}
1975 
1976 	if (ep->iso == NULL) {
1977 		struct bt_bap_iso *iso;
1978 
1979 		iso = bap_iso_get_or_new(ase->conn, cig_id, cis_id);
1980 		if (iso == NULL) {
1981 			LOG_ERR("Could not allocate bap_iso");
1982 			*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_NO_MEM,
1983 					       BT_BAP_ASCS_REASON_NONE);
1984 			return;
1985 		}
1986 
1987 		if (bt_bap_iso_get_ep(false, iso, ep->dir) != NULL) {
1988 			LOG_ERR("iso %p already in use in dir %s",
1989 			       &iso->chan, bt_audio_dir_str(ep->dir));
1990 			bt_bap_iso_unref(iso);
1991 			*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_CONF_INVALID,
1992 					       BT_BAP_ASCS_REASON_CIS);
1993 			return;
1994 		}
1995 
1996 		bt_bap_iso_bind_ep(iso, ep);
1997 		bt_bap_iso_unref(iso);
1998 	}
1999 
2000 	/* Store the QoS once accepted */
2001 	ep->qos = *qos;
2002 	stream->qos = &ep->qos;
2003 
2004 	/* We setup the data path here, as this is the earliest where
2005 	 * we have the ISO <-> EP coupling completed (due to setting
2006 	 * the CIS ID in the QoS procedure).
2007 	 */
2008 	bt_bap_iso_configure_data_path(ep, stream->codec_cfg);
2009 
2010 	ep->cig_id = cig_id;
2011 	ep->cis_id = cis_id;
2012 
2013 	ascs_ep_set_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
2014 
2015 	*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS, BT_BAP_ASCS_REASON_NONE);
2016 }
2017 
is_valid_qos_len(struct bt_conn * conn,struct net_buf_simple * buf)2018 static bool is_valid_qos_len(struct bt_conn *conn, struct net_buf_simple *buf)
2019 {
2020 	const struct bt_ascs_qos_op *op;
2021 	struct net_buf_simple_state state;
2022 	size_t params_size;
2023 
2024 	net_buf_simple_save(buf, &state);
2025 
2026 	if (buf->len < sizeof(*op)) {
2027 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2028 		return false;
2029 	}
2030 
2031 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2032 	if (!is_valid_num_ases(conn, op->num_ases)) {
2033 		return false;
2034 	}
2035 
2036 	params_size = sizeof(struct bt_ascs_qos) * op->num_ases;
2037 	if (buf->len < params_size) {
2038 		LOG_WRN("Malformed params array");
2039 		return false;
2040 	}
2041 
2042 	(void)net_buf_simple_pull_mem(buf, params_size);
2043 
2044 	if (buf->len > 0) {
2045 		LOG_WRN("Unexpected data");
2046 		return false;
2047 	}
2048 
2049 	net_buf_simple_restore(buf, &state);
2050 
2051 	return true;
2052 }
2053 
ascs_qos(struct bt_conn * conn,struct net_buf_simple * buf)2054 static ssize_t ascs_qos(struct bt_conn *conn, struct net_buf_simple *buf)
2055 {
2056 	const struct bt_ascs_qos_op *req;
2057 
2058 	if (!is_valid_qos_len(conn, buf)) {
2059 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2060 	}
2061 
2062 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2063 
2064 	LOG_DBG("num_ases %u", req->num_ases);
2065 
2066 	for (uint8_t i = 0; i < req->num_ases; i++) {
2067 		struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2068 							     BT_BAP_ASCS_REASON_NONE);
2069 		struct bt_audio_codec_qos cqos;
2070 		const struct bt_ascs_qos *qos;
2071 		struct bt_ascs_ase *ase;
2072 
2073 		qos = net_buf_simple_pull_mem(buf, sizeof(*qos));
2074 
2075 		LOG_DBG("ase 0x%02x", qos->ase);
2076 
2077 		if (!is_valid_ase_id(qos->ase)) {
2078 			ascs_cp_rsp_add(qos->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2079 					BT_BAP_ASCS_REASON_NONE);
2080 			LOG_WRN("Unknown ase 0x%02x", qos->ase);
2081 			continue;
2082 		}
2083 
2084 		ase = ase_find(conn, qos->ase);
2085 		if (!ase) {
2086 			LOG_DBG("Invalid operation for idle ASE");
2087 			ascs_cp_rsp_add(qos->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2088 					BT_BAP_ASCS_REASON_NONE);
2089 			continue;
2090 		}
2091 
2092 		cqos.interval = sys_get_le24(qos->interval);
2093 		cqos.framing = qos->framing;
2094 		cqos.phy = qos->phy;
2095 		cqos.sdu = sys_le16_to_cpu(qos->sdu);
2096 		cqos.rtn = qos->rtn;
2097 		cqos.latency = sys_le16_to_cpu(qos->latency);
2098 		cqos.pd = sys_get_le24(qos->pd);
2099 
2100 		ase_qos(ase, qos->cig, qos->cis, &cqos, &rsp);
2101 		ascs_cp_rsp_add(qos->ase, rsp.code, rsp.reason);
2102 	}
2103 
2104 	return buf->size;
2105 }
2106 
2107 struct ascs_parse_result {
2108 	int err;
2109 	struct bt_conn *conn;
2110 	struct bt_bap_ascs_rsp *rsp;
2111 	const struct bt_bap_ep *ep;
2112 };
2113 
is_context_available(struct bt_conn * conn,enum bt_audio_dir dir,uint16_t context)2114 static bool is_context_available(struct bt_conn *conn, enum bt_audio_dir dir, uint16_t context)
2115 {
2116 	return (context & bt_pacs_get_available_contexts_for_conn(conn, dir)) == context;
2117 }
2118 
ascs_parse_metadata(struct bt_data * data,void * user_data)2119 static bool ascs_parse_metadata(struct bt_data *data, void *user_data)
2120 {
2121 	struct ascs_parse_result *result = user_data;
2122 	const struct bt_bap_ep *ep = result->ep;
2123 	const uint8_t data_len = data->data_len;
2124 	const uint8_t data_type = data->type;
2125 	const uint8_t *data_value = data->data;
2126 
2127 	LOG_DBG("type 0x%02x len %u", data_type, data_len);
2128 
2129 	if (!BT_AUDIO_METADATA_TYPE_IS_KNOWN(data_type)) {
2130 		LOG_WRN("Unknown metadata type 0x%02x", data_type);
2131 		return true;
2132 	}
2133 
2134 	switch (data_type) {
2135 	/* TODO: Consider rejecting BT_AUDIO_METADATA_TYPE_PREF_CONTEXT type */
2136 	case BT_AUDIO_METADATA_TYPE_PREF_CONTEXT:
2137 	case BT_AUDIO_METADATA_TYPE_STREAM_CONTEXT: {
2138 		uint16_t context;
2139 
2140 		if (data_len != sizeof(context)) {
2141 			*result->rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2142 						       data_type);
2143 			result->err = -EBADMSG;
2144 			return false;
2145 		}
2146 
2147 		context = sys_get_le16(data_value);
2148 		if (context == BT_AUDIO_CONTEXT_TYPE_PROHIBITED) {
2149 			*result->rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2150 						       data_type);
2151 			result->err = -EINVAL;
2152 			return false;
2153 		}
2154 
2155 		/* The CAP acceptor shall not accept metadata with unsupported stream context. */
2156 		if (IS_ENABLED(CONFIG_BT_CAP_ACCEPTOR) &&
2157 		    data_type == BT_AUDIO_METADATA_TYPE_STREAM_CONTEXT) {
2158 			if (!is_context_available(result->conn, ep->dir, context)) {
2159 				LOG_WRN("Context 0x%04x is unavailable", context);
2160 				*result->rsp = BT_BAP_ASCS_RSP(
2161 					BT_BAP_ASCS_RSP_CODE_METADATA_REJECTED, data_type);
2162 				result->err = -EACCES;
2163 				return false;
2164 			}
2165 		}
2166 
2167 		break;
2168 	}
2169 	case BT_AUDIO_METADATA_TYPE_LANG:
2170 		if (data_len != BT_AUDIO_LANG_SIZE) {
2171 			*result->rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2172 						       data_type);
2173 			result->err = -EBADMSG;
2174 			return false;
2175 		}
2176 
2177 		break;
2178 	case BT_AUDIO_METADATA_TYPE_CCID_LIST: {
2179 		/* Verify that the CCID is a known CCID on the writing device */
2180 		if (IS_ENABLED(CONFIG_BT_CAP_ACCEPTOR)) {
2181 			for (uint8_t i = 0; i < data_len; i++) {
2182 				const uint8_t ccid = data_value[i];
2183 
2184 				if (!bt_cap_acceptor_ccid_exist(ep->stream->conn, ccid)) {
2185 					LOG_WRN("CCID %u is unknown", ccid);
2186 
2187 					/* TBD:
2188 					 * Should we reject the Metadata?
2189 					 *
2190 					 * Should unknown CCIDs trigger a
2191 					 * discovery procedure for TBS or MCS?
2192 					 *
2193 					 * Or should we just accept as is, and
2194 					 * then let the application decide?
2195 					 */
2196 				}
2197 			}
2198 		}
2199 
2200 		break;
2201 	}
2202 	case BT_AUDIO_METADATA_TYPE_PARENTAL_RATING:
2203 		if (data_len != 1) {
2204 			*result->rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2205 						       data_type);
2206 			result->err = -EBADMSG;
2207 			return false;
2208 		}
2209 
2210 		break;
2211 	case BT_AUDIO_METADATA_TYPE_AUDIO_STATE: {
2212 		uint8_t state;
2213 
2214 		if (data_len != sizeof(state)) {
2215 			*result->rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2216 						       data_type);
2217 			result->err = -EBADMSG;
2218 			return false;
2219 		}
2220 
2221 		break;
2222 	}
2223 	/* TODO: Consider rejecting BT_AUDIO_METADATA_TYPE_BROADCAST_IMMEDIATE type */
2224 	case BT_AUDIO_METADATA_TYPE_BROADCAST_IMMEDIATE:
2225 		if (data_len != 0) {
2226 			*result->rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2227 						       data_type);
2228 			result->err = -EBADMSG;
2229 			return false;
2230 		}
2231 
2232 		break;
2233 	default:
2234 		break;
2235 	}
2236 
2237 	return true;
2238 }
2239 
ascs_verify_metadata(struct bt_bap_ep * ep,const struct bt_ascs_metadata * meta,struct bt_bap_ascs_rsp * rsp)2240 static int ascs_verify_metadata(struct bt_bap_ep *ep, const struct bt_ascs_metadata *meta,
2241 				struct bt_bap_ascs_rsp *rsp)
2242 {
2243 	struct bt_ascs_ase *ase = CONTAINER_OF(ep, struct bt_ascs_ase, ep);
2244 	struct ascs_parse_result result = {
2245 		.conn = ase->conn,
2246 		.rsp = rsp,
2247 		.err = 0,
2248 		.ep = ep,
2249 	};
2250 	int err;
2251 
2252 	if (meta->len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE) {
2253 		LOG_WRN("Not enough space for Codec Config Metadata: %u > %d", meta->len,
2254 			CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE);
2255 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_NO_MEM, BT_BAP_ASCS_REASON_NONE);
2256 
2257 		return -ENOMEM;
2258 	}
2259 
2260 	/* Parse LTV entries */
2261 	err = bt_audio_data_parse(meta->data, meta->len, ascs_parse_metadata, &result);
2262 	if (err != 0 && err != -ECANCELED) {
2263 		/* ECANCELED is called if the callback stops the parsing prematurely, in which case
2264 		 * result.err will be set
2265 		 */
2266 		LOG_DBG("Failed to parse metadata: %d", err);
2267 		*rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_METADATA_INVALID,
2268 				       BT_BAP_ASCS_REASON_NONE);
2269 
2270 		return err;
2271 	}
2272 
2273 	return result.err;
2274 }
2275 
ase_metadata(struct bt_ascs_ase * ase,struct bt_ascs_metadata * meta)2276 static void ase_metadata(struct bt_ascs_ase *ase, struct bt_ascs_metadata *meta)
2277 {
2278 	struct bt_bap_stream *stream;
2279 	struct bt_bap_ep *ep;
2280 	struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS,
2281 						     BT_BAP_ASCS_REASON_NONE);
2282 	uint8_t state;
2283 	int err;
2284 
2285 	LOG_DBG("ase %p meta->len %u", ase, meta->len);
2286 
2287 	ep = &ase->ep;
2288 	state = ep->status.state;
2289 
2290 	switch (state) {
2291 	/* Valid for an ASE only if ASE_State field = 0x03 (Enabling) */
2292 	case BT_BAP_EP_STATE_ENABLING:
2293 	/* or 0x04 (Streaming) */
2294 	case BT_BAP_EP_STATE_STREAMING:
2295 		break;
2296 	default:
2297 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(state));
2298 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2299 				BT_BAP_ASCS_REASON_NONE);
2300 		return;
2301 	}
2302 
2303 	stream = ep->stream;
2304 
2305 	err = ascs_verify_metadata(ep, meta, &rsp);
2306 	if (err != 0) {
2307 		LOG_DBG("Invalid metadata from client: %d", err);
2308 
2309 		/* rsp will be set by ascs_verify_metadata*/
2310 	} else if (unicast_server_cb != NULL && unicast_server_cb->metadata != NULL) {
2311 		err = unicast_server_cb->metadata(stream, meta->data, meta->len, &rsp);
2312 	} else {
2313 		err = -ENOTSUP;
2314 		rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2315 				      BT_BAP_ASCS_REASON_NONE);
2316 	}
2317 
2318 	if (err) {
2319 		ascs_app_rsp_warn_valid(&rsp);
2320 
2321 		if (rsp.code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
2322 			rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2323 					      BT_BAP_ASCS_REASON_NONE);
2324 		}
2325 
2326 		LOG_ERR("Metadata failed: err %d, code %u, reason %u", err, rsp.code, rsp.reason);
2327 		ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
2328 		return;
2329 	}
2330 
2331 	ep->codec_cfg.meta_len = meta->len;
2332 	(void)memcpy(ep->codec_cfg.meta, meta->data, meta->len);
2333 
2334 	/* Set the state to the same state to trigger the notifications */
2335 	ascs_ep_set_state(ep, ep->status.state);
2336 	ascs_cp_rsp_success(ASE_ID(ase));
2337 }
2338 
ase_enable(struct bt_ascs_ase * ase,struct bt_ascs_metadata * meta)2339 static int ase_enable(struct bt_ascs_ase *ase, struct bt_ascs_metadata *meta)
2340 {
2341 	struct bt_bap_stream *stream;
2342 	struct bt_bap_ep *ep;
2343 	struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS,
2344 						     BT_BAP_ASCS_REASON_NONE);
2345 	int err;
2346 
2347 	LOG_DBG("ase %p meta->len %u", ase, meta->len);
2348 
2349 	ep = &ase->ep;
2350 
2351 	/* Valid for an ASE only if ASE_State field = 0x02 (QoS Configured) */
2352 	if (ep->status.state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
2353 		err = -EBADMSG;
2354 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(ep->status.state));
2355 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2356 				BT_BAP_ASCS_REASON_NONE);
2357 		return err;
2358 	}
2359 
2360 	stream = ep->stream;
2361 
2362 	err = ascs_verify_metadata(ep, meta, &rsp);
2363 	if (err != 0) {
2364 		LOG_DBG("Invalid metadata from client: %d", err);
2365 
2366 		/* rsp will be set by ascs_verify_metadata*/
2367 	} else if (unicast_server_cb != NULL && unicast_server_cb->enable != NULL) {
2368 		err = unicast_server_cb->enable(stream, meta->data, meta->len, &rsp);
2369 	} else {
2370 		err = -ENOTSUP;
2371 		rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2372 				      BT_BAP_ASCS_REASON_NONE);
2373 	}
2374 
2375 	if (err) {
2376 		ascs_app_rsp_warn_valid(&rsp);
2377 
2378 		if (rsp.code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
2379 			rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2380 					      BT_BAP_ASCS_REASON_NONE);
2381 		}
2382 
2383 		LOG_ERR("Enable rejected: err %d, code %u, reason %u", err, rsp.code, rsp.reason);
2384 		ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
2385 
2386 		return -EFAULT;
2387 	}
2388 
2389 	ep->codec_cfg.meta_len = meta->len;
2390 	(void)memcpy(ep->codec_cfg.meta, meta->data, meta->len);
2391 
2392 	ascs_ep_set_state(ep, BT_BAP_EP_STATE_ENABLING);
2393 
2394 	ascs_cp_rsp_success(ASE_ID(ase));
2395 
2396 	return 0;
2397 }
2398 
is_valid_enable_len(struct bt_conn * conn,struct net_buf_simple * buf)2399 static bool is_valid_enable_len(struct bt_conn *conn, struct net_buf_simple *buf)
2400 {
2401 	const struct bt_ascs_enable_op *op;
2402 	struct net_buf_simple_state state;
2403 
2404 	net_buf_simple_save(buf, &state);
2405 
2406 	if (buf->len < sizeof(*op)) {
2407 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2408 		return false;
2409 	}
2410 
2411 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2412 	if (!is_valid_num_ases(conn, op->num_ases)) {
2413 		return false;
2414 	}
2415 
2416 	for (uint8_t i = 0U; i < op->num_ases; i++) {
2417 		const struct bt_ascs_metadata *metadata;
2418 
2419 		if (buf->len < sizeof(*metadata)) {
2420 			LOG_WRN("Malformed params array");
2421 			return false;
2422 		}
2423 
2424 		metadata = net_buf_simple_pull_mem(buf, sizeof(*metadata));
2425 		if (buf->len < metadata->len) {
2426 			LOG_WRN("Malformed metadata");
2427 			return false;
2428 		}
2429 
2430 		(void)net_buf_simple_pull_mem(buf, metadata->len);
2431 	}
2432 
2433 	if (buf->len > 0) {
2434 		LOG_WRN("Unexpected data");
2435 		return false;
2436 	}
2437 
2438 	net_buf_simple_restore(buf, &state);
2439 
2440 	return true;
2441 }
2442 
ascs_enable(struct bt_conn * conn,struct net_buf_simple * buf)2443 static ssize_t ascs_enable(struct bt_conn *conn, struct net_buf_simple *buf)
2444 {
2445 	const struct bt_ascs_enable_op *req;
2446 	struct bt_ascs_metadata *meta;
2447 	int i;
2448 
2449 	if (!is_valid_enable_len(conn, buf)) {
2450 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2451 	}
2452 
2453 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2454 
2455 	LOG_DBG("num_ases %u", req->num_ases);
2456 
2457 	for (i = 0; i < req->num_ases; i++) {
2458 		struct bt_ascs_ase *ase;
2459 
2460 		meta = net_buf_simple_pull_mem(buf, sizeof(*meta));
2461 		(void)net_buf_simple_pull(buf, meta->len);
2462 
2463 		if (!is_valid_ase_id(meta->ase)) {
2464 			ascs_cp_rsp_add(meta->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2465 					BT_BAP_ASCS_REASON_NONE);
2466 			LOG_WRN("Unknown ase 0x%02x", meta->ase);
2467 			continue;
2468 		}
2469 
2470 		ase = ase_find(conn, meta->ase);
2471 		if (!ase) {
2472 			LOG_DBG("Invalid operation for idle ase 0x%02x", meta->ase);
2473 			ascs_cp_rsp_add(meta->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2474 					BT_BAP_ASCS_REASON_NONE);
2475 			continue;
2476 		}
2477 
2478 		ase_enable(ase, meta);
2479 	}
2480 
2481 	return buf->size;
2482 }
2483 
ase_start(struct bt_ascs_ase * ase)2484 static void ase_start(struct bt_ascs_ase *ase)
2485 {
2486 	struct bt_bap_ep *ep;
2487 	struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS,
2488 						     BT_BAP_ASCS_REASON_NONE);
2489 	int err;
2490 
2491 	LOG_DBG("ase %p", ase);
2492 
2493 	ep = &ase->ep;
2494 
2495 	/* Valid for an ASE only if ASE_State field = 0x02 (QoS Configured) */
2496 	if (ep->status.state != BT_BAP_EP_STATE_ENABLING) {
2497 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(ep->status.state));
2498 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2499 				BT_BAP_ASCS_REASON_NONE);
2500 		return;
2501 	}
2502 
2503 	if (ep->iso->chan.state != BT_ISO_STATE_CONNECTED) {
2504 		/* An ASE may not go into the streaming state unless the CIS
2505 		 * is connected
2506 		 */
2507 		LOG_WRN("Start failed: CIS not connected: %u",
2508 			ep->iso->chan.state);
2509 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2510 				BT_BAP_ASCS_REASON_NONE);
2511 		return;
2512 	}
2513 
2514 	if (unicast_server_cb != NULL && unicast_server_cb->start != NULL) {
2515 		err = unicast_server_cb->start(ep->stream, &rsp);
2516 	} else {
2517 		err = -ENOTSUP;
2518 		rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2519 				      BT_BAP_ASCS_REASON_NONE);
2520 	}
2521 
2522 	if (err) {
2523 		ascs_app_rsp_warn_valid(&rsp);
2524 
2525 		if (rsp.code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
2526 			rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2527 					      BT_BAP_ASCS_REASON_NONE);
2528 		}
2529 
2530 		LOG_ERR("Start failed: err %d, code %u, reason %u", err, rsp.code, rsp.reason);
2531 		ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
2532 
2533 		return;
2534 	}
2535 
2536 	ep->receiver_ready = true;
2537 
2538 	ascs_ep_set_state(ep, BT_BAP_EP_STATE_STREAMING);
2539 
2540 	ascs_cp_rsp_success(ASE_ID(ase));
2541 }
2542 
is_valid_start_len(struct bt_conn * conn,struct net_buf_simple * buf)2543 static bool is_valid_start_len(struct bt_conn *conn, struct net_buf_simple *buf)
2544 {
2545 	const struct bt_ascs_start_op *op;
2546 	struct net_buf_simple_state state;
2547 
2548 	net_buf_simple_save(buf, &state);
2549 
2550 	if (buf->len < sizeof(*op)) {
2551 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2552 		return false;
2553 	}
2554 
2555 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2556 	if (!is_valid_num_ases(conn, op->num_ases)) {
2557 		return false;
2558 	}
2559 
2560 	if (buf->len != op->num_ases) {
2561 		LOG_WRN("Number_of_ASEs mismatch");
2562 		return false;
2563 	}
2564 
2565 	net_buf_simple_restore(buf, &state);
2566 
2567 	return true;
2568 }
2569 
ascs_start(struct bt_conn * conn,struct net_buf_simple * buf)2570 static ssize_t ascs_start(struct bt_conn *conn, struct net_buf_simple *buf)
2571 {
2572 	const struct bt_ascs_start_op *req;
2573 	int i;
2574 
2575 	if (!is_valid_start_len(conn, buf)) {
2576 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2577 	}
2578 
2579 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2580 
2581 	LOG_DBG("num_ases %u", req->num_ases);
2582 
2583 	for (i = 0; i < req->num_ases; i++) {
2584 		struct bt_ascs_ase *ase;
2585 		uint8_t id;
2586 
2587 		id = net_buf_simple_pull_u8(buf);
2588 
2589 		LOG_DBG("ase 0x%02x", id);
2590 
2591 		if (!is_valid_ase_id(id)) {
2592 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2593 					BT_BAP_ASCS_REASON_NONE);
2594 			LOG_WRN("Unknown ase 0x%02x", id);
2595 			continue;
2596 		}
2597 
2598 		/* If the ASE_ID  written by the client represents a Sink ASE, the
2599 		 * server shall not accept the Receiver Start Ready operation for that
2600 		 * ASE. The server shall send a notification of the ASE Control Point
2601 		 * characteristic to the client, and the server shall set the
2602 		 * Response_Code value for that ASE to 0x05 (Invalid ASE direction).
2603 		 */
2604 		if (ASE_DIR(id) == BT_AUDIO_DIR_SINK) {
2605 			LOG_WRN("Start failed: invalid operation for Sink");
2606 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_DIR,
2607 					BT_BAP_ASCS_REASON_NONE);
2608 			continue;
2609 		}
2610 
2611 		ase = ase_find(conn, id);
2612 		if (!ase) {
2613 			LOG_DBG("Invalid operation for idle ASE");
2614 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2615 					BT_BAP_ASCS_REASON_NONE);
2616 			continue;
2617 		}
2618 
2619 		ase_start(ase);
2620 	}
2621 
2622 	return buf->size;
2623 }
2624 
is_valid_disable_len(struct bt_conn * conn,struct net_buf_simple * buf)2625 static bool is_valid_disable_len(struct bt_conn *conn, struct net_buf_simple *buf)
2626 {
2627 	const struct bt_ascs_disable_op *op;
2628 	struct net_buf_simple_state state;
2629 
2630 	net_buf_simple_save(buf, &state);
2631 
2632 	if (buf->len < sizeof(*op)) {
2633 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2634 		return false;
2635 	}
2636 
2637 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2638 	if (!is_valid_num_ases(conn, op->num_ases)) {
2639 		return false;
2640 	}
2641 
2642 	if (buf->len != op->num_ases) {
2643 		LOG_WRN("Number_of_ASEs mismatch");
2644 		return false;
2645 	}
2646 
2647 	net_buf_simple_restore(buf, &state);
2648 
2649 	return true;
2650 }
2651 
ascs_disable(struct bt_conn * conn,struct net_buf_simple * buf)2652 static ssize_t ascs_disable(struct bt_conn *conn, struct net_buf_simple *buf)
2653 {
2654 	const struct bt_ascs_disable_op *req;
2655 
2656 	if (!is_valid_disable_len(conn, buf)) {
2657 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2658 	}
2659 
2660 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2661 
2662 	LOG_DBG("num_ases %u", req->num_ases);
2663 
2664 	for (uint8_t i = 0; i < req->num_ases; i++) {
2665 		struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2666 							     BT_BAP_ASCS_REASON_NONE);
2667 		struct bt_ascs_ase *ase;
2668 		uint8_t id;
2669 
2670 		id = net_buf_simple_pull_u8(buf);
2671 
2672 		LOG_DBG("ase 0x%02x", id);
2673 
2674 		if (!is_valid_ase_id(id)) {
2675 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2676 					BT_BAP_ASCS_REASON_NONE);
2677 			LOG_WRN("Unknown ase 0x%02x", id);
2678 			continue;
2679 		}
2680 
2681 		ase = ase_find(conn, id);
2682 		if (!ase) {
2683 			LOG_DBG("Invalid operation for idle ASE");
2684 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2685 					BT_BAP_ASCS_REASON_NONE);
2686 			continue;
2687 		}
2688 
2689 		ase_disable(ase, BT_HCI_ERR_REMOTE_USER_TERM_CONN, &rsp);
2690 		ascs_cp_rsp_add(id, rsp.code, rsp.reason);
2691 	}
2692 
2693 	return buf->size;
2694 }
2695 
ase_stop(struct bt_ascs_ase * ase)2696 static void ase_stop(struct bt_ascs_ase *ase)
2697 {
2698 	struct bt_bap_stream *stream;
2699 	struct bt_bap_ep *ep;
2700 	struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_SUCCESS,
2701 						     BT_BAP_ASCS_REASON_NONE);
2702 	int err;
2703 
2704 	LOG_DBG("ase %p", ase);
2705 
2706 	ep = &ase->ep;
2707 
2708 	if (ep->status.state != BT_BAP_EP_STATE_DISABLING) {
2709 		LOG_WRN("Invalid operation in state: %s", bt_bap_ep_state_str(ep->status.state));
2710 		ascs_cp_rsp_add(ASE_ID(ase), BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2711 				BT_BAP_ASCS_REASON_NONE);
2712 		return;
2713 	}
2714 
2715 	stream = ep->stream;
2716 	if (unicast_server_cb != NULL && unicast_server_cb->stop != NULL) {
2717 		err = unicast_server_cb->stop(stream, &rsp);
2718 	} else {
2719 		err = -ENOTSUP;
2720 		rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2721 				      BT_BAP_ASCS_REASON_NONE);
2722 	}
2723 
2724 	if (err) {
2725 		ascs_app_rsp_warn_valid(&rsp);
2726 
2727 		if (rsp.code == BT_BAP_ASCS_RSP_CODE_SUCCESS) {
2728 			rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2729 					      BT_BAP_ASCS_REASON_NONE);
2730 		}
2731 
2732 		LOG_ERR("Stop failed: err %d, code %u, reason %u", err, rsp.code, rsp.reason);
2733 		ascs_cp_rsp_add(ASE_ID(ase), rsp.code, rsp.reason);
2734 		return;
2735 	}
2736 
2737 	/* If the Receiver Stop Ready operation has completed successfully the
2738 	 * Unicast Client or the Unicast Server may terminate a CIS established
2739 	 * for that ASE by following the Connected Isochronous Stream Terminate
2740 	 * procedure defined in Volume 3, Part C, Section 9.3.15.
2741 	 */
2742 	if (bt_bap_stream_can_disconnect(stream)) {
2743 		err = ascs_disconnect_stream(stream);
2744 		if (err < 0) {
2745 			LOG_ERR("Failed to disconnect stream %p: %d", stream, err);
2746 		}
2747 	}
2748 
2749 	ascs_ep_set_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
2750 
2751 	ascs_cp_rsp_success(ASE_ID(ase));
2752 }
2753 
is_valid_stop_len(struct bt_conn * conn,struct net_buf_simple * buf)2754 static bool is_valid_stop_len(struct bt_conn *conn, struct net_buf_simple *buf)
2755 {
2756 	const struct bt_ascs_stop_op *op;
2757 	struct net_buf_simple_state state;
2758 
2759 	net_buf_simple_save(buf, &state);
2760 
2761 	if (buf->len < sizeof(*op)) {
2762 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2763 		return false;
2764 	}
2765 
2766 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2767 	if (op->num_ases < 1U) {
2768 		LOG_WRN("Number_of_ASEs parameter value is less than 1");
2769 		return false;
2770 	}
2771 
2772 	if (buf->len != op->num_ases) {
2773 		LOG_WRN("Number_of_ASEs mismatch");
2774 		return false;
2775 	}
2776 
2777 	net_buf_simple_restore(buf, &state);
2778 
2779 	return true;
2780 }
2781 
ascs_stop(struct bt_conn * conn,struct net_buf_simple * buf)2782 static ssize_t ascs_stop(struct bt_conn *conn, struct net_buf_simple *buf)
2783 {
2784 	const struct bt_ascs_start_op *req;
2785 	int i;
2786 
2787 	if (!is_valid_stop_len(conn, buf)) {
2788 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2789 	}
2790 
2791 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2792 
2793 	LOG_DBG("num_ases %u", req->num_ases);
2794 
2795 	for (i = 0; i < req->num_ases; i++) {
2796 		struct bt_ascs_ase *ase;
2797 		uint8_t id;
2798 
2799 		id = net_buf_simple_pull_u8(buf);
2800 
2801 		LOG_DBG("ase 0x%02x", id);
2802 
2803 		if (!is_valid_ase_id(id)) {
2804 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2805 					BT_BAP_ASCS_REASON_NONE);
2806 			LOG_WRN("Unknown ase 0x%02x", id);
2807 			continue;
2808 		}
2809 
2810 		/* If the ASE_ID  written by the client represents a Sink ASE, the
2811 		 * server shall not accept the Receiver Stop Ready operation for that
2812 		 * ASE. The server shall send a notification of the ASE Control Point
2813 		 * characteristic to the client, and the server shall set the
2814 		 * Response_Code value for that ASE to 0x05 (Invalid ASE direction).
2815 		 */
2816 		if (ASE_DIR(id) == BT_AUDIO_DIR_SINK) {
2817 			LOG_WRN("Stop failed: invalid operation for Sink");
2818 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_DIR,
2819 					BT_BAP_ASCS_REASON_NONE);
2820 			continue;
2821 		}
2822 
2823 		ase = ase_find(conn, id);
2824 		if (!ase) {
2825 			LOG_DBG("Invalid operation for idle ASE");
2826 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2827 					BT_BAP_ASCS_REASON_NONE);
2828 			continue;
2829 		}
2830 
2831 		ase_stop(ase);
2832 	}
2833 
2834 	return buf->size;
2835 }
2836 
is_valid_metadata_len(struct bt_conn * conn,struct net_buf_simple * buf)2837 static bool is_valid_metadata_len(struct bt_conn *conn, struct net_buf_simple *buf)
2838 {
2839 	const struct bt_ascs_metadata_op *op;
2840 	struct net_buf_simple_state state;
2841 
2842 	net_buf_simple_save(buf, &state);
2843 
2844 	if (buf->len < sizeof(*op)) {
2845 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2846 		return false;
2847 	}
2848 
2849 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2850 	if (!is_valid_num_ases(conn, op->num_ases)) {
2851 		return false;
2852 	}
2853 
2854 	for (uint8_t i = 0U; i < op->num_ases; i++) {
2855 		const struct bt_ascs_metadata *metadata;
2856 
2857 		if (buf->len < sizeof(*metadata)) {
2858 			LOG_WRN("Malformed params array");
2859 			return false;
2860 		}
2861 
2862 		metadata = net_buf_simple_pull_mem(buf, sizeof(*metadata));
2863 		if (buf->len < metadata->len) {
2864 			LOG_WRN("Malformed metadata");
2865 			return false;
2866 		}
2867 
2868 		(void)net_buf_simple_pull_mem(buf, metadata->len);
2869 	}
2870 
2871 	if (buf->len > 0) {
2872 		LOG_WRN("Unexpected data");
2873 		return false;
2874 	}
2875 
2876 	net_buf_simple_restore(buf, &state);
2877 
2878 	return true;
2879 }
2880 
ascs_metadata(struct bt_conn * conn,struct net_buf_simple * buf)2881 static ssize_t ascs_metadata(struct bt_conn *conn, struct net_buf_simple *buf)
2882 {
2883 	const struct bt_ascs_metadata_op *req;
2884 	struct bt_ascs_metadata *meta;
2885 	int i;
2886 
2887 	if (!is_valid_metadata_len(conn, buf)) {
2888 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2889 	}
2890 
2891 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2892 
2893 	LOG_DBG("num_ases %u", req->num_ases);
2894 
2895 	for (i = 0; i < req->num_ases; i++) {
2896 		struct bt_ascs_ase *ase;
2897 
2898 		meta = net_buf_simple_pull_mem(buf, sizeof(*meta));
2899 		(void)net_buf_simple_pull(buf, meta->len);
2900 
2901 		if (meta->len > CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE) {
2902 			LOG_DBG("Cannot store %u octets of metadata", meta->len);
2903 
2904 			ascs_cp_rsp_add(meta->ase, BT_BAP_ASCS_RSP_CODE_NO_MEM,
2905 					BT_BAP_ASCS_REASON_NONE);
2906 			continue;
2907 		}
2908 
2909 		if (!is_valid_ase_id(meta->ase)) {
2910 			ascs_cp_rsp_add(meta->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2911 					BT_BAP_ASCS_REASON_NONE);
2912 			LOG_WRN("Unknown ase 0x%02x", meta->ase);
2913 			continue;
2914 		}
2915 
2916 		ase = ase_find(conn, meta->ase);
2917 		if (!ase) {
2918 			LOG_DBG("Invalid operation for idle ase 0x%02x", meta->ase);
2919 			ascs_cp_rsp_add(meta->ase, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2920 					BT_BAP_ASCS_REASON_NONE);
2921 			continue;
2922 		}
2923 
2924 		ase_metadata(ase, meta);
2925 	}
2926 
2927 	return buf->size;
2928 }
2929 
is_valid_release_len(struct bt_conn * conn,struct net_buf_simple * buf)2930 static bool is_valid_release_len(struct bt_conn *conn, struct net_buf_simple *buf)
2931 {
2932 	const struct bt_ascs_release_op *op;
2933 	struct net_buf_simple_state state;
2934 
2935 	net_buf_simple_save(buf, &state);
2936 
2937 	if (buf->len < sizeof(*op)) {
2938 		LOG_WRN("Invalid length %u < %zu", buf->len, sizeof(*op));
2939 		return false;
2940 	}
2941 
2942 	op = net_buf_simple_pull_mem(buf, sizeof(*op));
2943 	if (!is_valid_num_ases(conn, op->num_ases)) {
2944 		return false;
2945 	}
2946 
2947 	if (buf->len != op->num_ases) {
2948 		LOG_WRN("Number_of_ASEs mismatch");
2949 		return false;
2950 	}
2951 
2952 	net_buf_simple_restore(buf, &state);
2953 
2954 	return true;
2955 }
2956 
ascs_release(struct bt_conn * conn,struct net_buf_simple * buf)2957 static ssize_t ascs_release(struct bt_conn *conn, struct net_buf_simple *buf)
2958 {
2959 	const struct bt_ascs_release_op *req;
2960 	int i;
2961 
2962 	if (!is_valid_release_len(conn, buf)) {
2963 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
2964 	}
2965 
2966 	req = net_buf_simple_pull_mem(buf, sizeof(*req));
2967 
2968 	LOG_DBG("num_ases %u", req->num_ases);
2969 
2970 	for (i = 0; i < req->num_ases; i++) {
2971 		struct bt_bap_ascs_rsp rsp = BT_BAP_ASCS_RSP(BT_BAP_ASCS_RSP_CODE_UNSPECIFIED,
2972 							     BT_BAP_ASCS_REASON_NONE);
2973 		struct bt_ascs_ase *ase;
2974 		uint8_t id;
2975 
2976 		id = net_buf_simple_pull_u8(buf);
2977 
2978 		LOG_DBG("ase 0x%02x", id);
2979 
2980 		if (!is_valid_ase_id(id)) {
2981 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE,
2982 					BT_BAP_ASCS_REASON_NONE);
2983 			LOG_WRN("Unknown ase 0x%02x", id);
2984 			continue;
2985 		}
2986 
2987 		ase = ase_find(conn, id);
2988 		if (!ase) {
2989 			LOG_DBG("Invalid operation for idle ASE");
2990 			ascs_cp_rsp_add(id, BT_BAP_ASCS_RSP_CODE_INVALID_ASE_STATE,
2991 					BT_BAP_ASCS_REASON_NONE);
2992 			continue;
2993 		}
2994 
2995 		ase_release(ase, BT_HCI_ERR_REMOTE_USER_TERM_CONN, &rsp);
2996 		ascs_cp_rsp_add(id, rsp.code, rsp.reason);
2997 	}
2998 
2999 	return buf->size;
3000 }
3001 
ascs_cp_write(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * data,uint16_t len,uint16_t offset,uint8_t flags)3002 static ssize_t ascs_cp_write(struct bt_conn *conn,
3003 			     const struct bt_gatt_attr *attr, const void *data,
3004 			     uint16_t len, uint16_t offset, uint8_t flags)
3005 {
3006 	const struct bt_ascs_ase_cp *req;
3007 	struct net_buf_simple buf;
3008 	ssize_t ret;
3009 
3010 	if (flags & BT_GATT_WRITE_FLAG_PREPARE) {
3011 		/* Return 0 to allow long writes */
3012 		return 0;
3013 	}
3014 
3015 	if (offset != 0 && (flags & BT_GATT_WRITE_FLAG_EXECUTE) == 0) {
3016 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
3017 	}
3018 
3019 	if (len < sizeof(*req)) {
3020 		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
3021 	}
3022 
3023 	net_buf_simple_init_with_data(&buf, (void *) data, len);
3024 
3025 	req = net_buf_simple_pull_mem(&buf, sizeof(*req));
3026 
3027 	LOG_DBG("conn %p attr %p buf %p len %u op %s (0x%02x)",
3028 		(void *)conn, attr, data, len, bt_ascs_op_str(req->op), req->op);
3029 
3030 	ascs_cp_rsp_init(req->op);
3031 
3032 	switch (req->op) {
3033 	case BT_ASCS_CONFIG_OP:
3034 		ret = ascs_config(conn, &buf);
3035 		break;
3036 	case BT_ASCS_QOS_OP:
3037 		ret = ascs_qos(conn, &buf);
3038 		break;
3039 	case BT_ASCS_ENABLE_OP:
3040 		ret = ascs_enable(conn, &buf);
3041 		break;
3042 	case BT_ASCS_START_OP:
3043 		ret = ascs_start(conn, &buf);
3044 		break;
3045 	case BT_ASCS_DISABLE_OP:
3046 		ret = ascs_disable(conn, &buf);
3047 		break;
3048 	case BT_ASCS_STOP_OP:
3049 		ret = ascs_stop(conn, &buf);
3050 		break;
3051 	case BT_ASCS_METADATA_OP:
3052 		ret = ascs_metadata(conn, &buf);
3053 		break;
3054 	case BT_ASCS_RELEASE_OP:
3055 		ret = ascs_release(conn, &buf);
3056 		break;
3057 	default:
3058 		ascs_cp_rsp_add(BT_ASCS_ASE_ID_NONE, BT_BAP_ASCS_RSP_CODE_NOT_SUPPORTED,
3059 				BT_BAP_ASCS_REASON_NONE);
3060 		LOG_DBG("Unknown opcode");
3061 		goto respond;
3062 	}
3063 
3064 	if (ret == BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN)) {
3065 		ascs_cp_rsp_add(BT_ASCS_ASE_ID_NONE, BT_BAP_ASCS_RSP_CODE_INVALID_LENGTH,
3066 				BT_BAP_ASCS_REASON_NONE);
3067 	}
3068 
3069 respond:
3070 	control_point_notify(conn, cp_rsp_buf.data, cp_rsp_buf.len);
3071 
3072 	return len;
3073 }
3074 
3075 #define BT_ASCS_ASE_DEFINE(_uuid, _id) \
3076 	BT_AUDIO_CHRC(_uuid, \
3077 		      BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, \
3078 		      BT_GATT_PERM_READ_ENCRYPT, \
3079 		      ascs_ase_read, NULL, UINT_TO_POINTER(_id)), \
3080 	BT_AUDIO_CCC(ascs_ase_cfg_changed)
3081 #define BT_ASCS_ASE_SNK_DEFINE(_n, ...) BT_ASCS_ASE_DEFINE(BT_UUID_ASCS_ASE_SNK, (_n) + 1)
3082 #define BT_ASCS_ASE_SRC_DEFINE(_n, ...) BT_ASCS_ASE_DEFINE(BT_UUID_ASCS_ASE_SRC, (_n) + 1 + \
3083 							   CONFIG_BT_ASCS_ASE_SNK_COUNT)
3084 
3085 BT_GATT_SERVICE_DEFINE(ascs_svc,
3086 	BT_GATT_PRIMARY_SERVICE(BT_UUID_ASCS),
3087 	BT_AUDIO_CHRC(BT_UUID_ASCS_ASE_CP,
3088 		      BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP | BT_GATT_CHRC_NOTIFY,
3089 		      BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_PREPARE_WRITE,
3090 		      NULL, ascs_cp_write, NULL),
3091 	BT_AUDIO_CCC(ascs_cp_cfg_changed),
3092 #if CONFIG_BT_ASCS_ASE_SNK_COUNT > 0
3093 	LISTIFY(CONFIG_BT_ASCS_ASE_SNK_COUNT, BT_ASCS_ASE_SNK_DEFINE, (,)),
3094 #endif /* CONFIG_BT_ASCS_ASE_SNK_COUNT > 0 */
3095 #if CONFIG_BT_ASCS_ASE_SRC_COUNT > 0
3096 	LISTIFY(CONFIG_BT_ASCS_ASE_SRC_COUNT, BT_ASCS_ASE_SRC_DEFINE, (,)),
3097 #endif /* CONFIG_BT_ASCS_ASE_SRC_COUNT > 0 */
3098 );
3099 
control_point_notify(struct bt_conn * conn,const void * data,uint16_t len)3100 static int control_point_notify(struct bt_conn *conn, const void *data, uint16_t len)
3101 {
3102 	return bt_gatt_notify_uuid(conn, BT_UUID_ASCS_ASE_CP, ascs_svc.attrs, data, len);
3103 }
3104 
3105 static struct bt_iso_server iso_server = {
3106 	.sec_level = BT_SECURITY_L2,
3107 	.accept = ascs_iso_accept,
3108 };
3109 
bt_ascs_init(const struct bt_bap_unicast_server_cb * cb)3110 int bt_ascs_init(const struct bt_bap_unicast_server_cb *cb)
3111 {
3112 	int err;
3113 
3114 	if (unicast_server_cb != NULL) {
3115 		return -EALREADY;
3116 	}
3117 
3118 	err = bt_iso_server_register(&iso_server);
3119 	if (err) {
3120 		LOG_ERR("Failed to register ISO server %d", err);
3121 		return err;
3122 	}
3123 
3124 	unicast_server_cb = cb;
3125 
3126 	return 0;
3127 }
3128 
bt_ascs_cleanup(void)3129 void bt_ascs_cleanup(void)
3130 {
3131 	for (size_t i = 0; i < ARRAY_SIZE(ase_pool); i++) {
3132 		struct bt_ascs_ase *ase = &ase_pool[i];
3133 
3134 		if (ase->conn != NULL) {
3135 			bt_ascs_release_ase(&ase->ep);
3136 		}
3137 	}
3138 
3139 	if (unicast_server_cb != NULL) {
3140 		bt_iso_server_unregister(&iso_server);
3141 		unicast_server_cb = NULL;
3142 	}
3143 }
3144 #endif /* BT_BAP_UNICAST_SERVER */
3145