1 /*
2  * Copyright (c) 2017-2021 Nordic Semiconductor ASA
3  * Copyright (c) 2015-2016 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 #include <errno.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <string.h>
11 
12 #include <zephyr/autoconf.h>
13 #include <zephyr/bluetooth/addr.h>
14 #include <zephyr/bluetooth/bluetooth.h>
15 #include <zephyr/bluetooth/buf.h>
16 #include <zephyr/bluetooth/conn.h>
17 #include <zephyr/bluetooth/gap.h>
18 #include <zephyr/bluetooth/hci.h>
19 #include <zephyr/bluetooth/hci_types.h>
20 #include <zephyr/kernel.h>
21 #include <zephyr/logging/log.h>
22 #include <zephyr/net_buf.h>
23 #include <zephyr/sys/__assert.h>
24 #include <zephyr/sys/atomic.h>
25 #include <zephyr/sys/byteorder.h>
26 #include <zephyr/sys/check.h>
27 #include <zephyr/sys/util.h>
28 #include <zephyr/sys/util_macro.h>
29 #include <sys/types.h>
30 
31 #include "addr_internal.h"
32 #include "common/bt_str.h"
33 #include "conn_internal.h"
34 #include "hci_core.h"
35 #include "id.h"
36 #include "scan.h"
37 #include "adv.h"
38 
39 #define LOG_LEVEL CONFIG_BT_HCI_CORE_LOG_LEVEL
40 LOG_MODULE_REGISTER(bt_adv);
41 
42 struct bt_ad {
43 	/* Pointer to an LTV structure */
44 	const struct bt_data *data;
45 	/* Number of elements in @p data */
46 	size_t len;
47 };
48 
49 struct ad_stream {
50 	/* ad is a two dimensional array of struct bt_data elements. */
51 	const struct bt_ad *ad;
52 	/* The number of struct bt_ad elements. */
53 	size_t ad_len;
54 
55 	/* The current index in the array of struct bt_ad elements */
56 	size_t ad_index;
57 	/* The current index in the array of ad.data elements */
58 	size_t data_index;
59 
60 	/* Current LTV offset contains the data offset in the ad[x].data[y].data value array
61 	 * The length and type are included in this offset.
62 	 */
63 	uint16_t current_ltv_offset;
64 
65 	/* The remaining size of total ad[i].data[j].data_len + 2 for LTV header */
66 	size_t remaining_size;
67 };
68 
ad_stream_new(struct ad_stream * stream,const struct bt_ad * ad,size_t ad_len)69 static int ad_stream_new(struct ad_stream *stream,
70 			 const struct bt_ad *ad, size_t ad_len)
71 {
72 	(void)memset(stream, 0, sizeof(*stream));
73 	stream->ad = ad;
74 	stream->ad_len = ad_len;
75 
76 	for (size_t i = 0; i < ad_len; i++) {
77 		for (size_t j = 0; j < ad[i].len; j++) {
78 			/* LTV length + type + value */
79 			stream->remaining_size += ad[i].data[j].data_len + 2;
80 
81 			if (stream->remaining_size > BT_GAP_ADV_MAX_EXT_ADV_DATA_LEN) {
82 				return -EINVAL;
83 			}
84 		}
85 	}
86 
87 	return 0;
88 }
89 
90 /**
91  * @brief Returns true if the current stream is empty.
92  *
93  * @param stream AD stream, @ref ad_stream_new
94  *
95  * @returns true if the stream is now empty.
96  */
ad_stream_is_empty(const struct ad_stream * stream)97 static bool ad_stream_is_empty(const struct ad_stream *stream)
98 {
99 	return stream->remaining_size == 0;
100 }
101 
102 /**
103  * @brief Returns the bt_data structure that is currently being read
104  *
105  * If the structure has been fully read, the function iterates to the next
106  *
107  * @param stream AD stream, @ref ad_stream_new
108  *
109  * @returns The current LTV structure or NULL if there are no left.
110  */
ad_stream_current_ltv_update(struct ad_stream * stream)111 static const struct bt_data *ad_stream_current_ltv_update(struct ad_stream *stream)
112 {
113 	const struct bt_data *current_ltv = &stream->ad[stream->ad_index].data[stream->data_index];
114 	const bool done_reading_ltv = (stream->current_ltv_offset == current_ltv->data_len + 2);
115 
116 	if (done_reading_ltv) {
117 		stream->current_ltv_offset = 0;
118 
119 		if (stream->data_index + 1 == stream->ad[stream->ad_index].len) {
120 			stream->data_index = 0;
121 			stream->ad_index++;
122 		} else {
123 			stream->data_index++;
124 		}
125 	}
126 
127 	if (stream->ad_index == stream->ad_len) {
128 		return NULL;
129 	} else {
130 		return &stream->ad[stream->ad_index].data[stream->data_index];
131 	}
132 }
133 
134 /**
135  * @brief Read at max buf_len data from the flattened AD stream.
136  *
137  * The read data can contain multiple LTV AD structures.
138  *
139  * @param stream  AD stream, @ref ad_stream_new
140  * @param buf     Buffer where the data will be put
141  * @param buf_len Buffer length
142  *
143  * @returns The number of bytes read from the stream written to the provided buffer
144  */
ad_stream_read(struct ad_stream * stream,uint8_t * buf,uint8_t buf_len)145 static uint8_t ad_stream_read(struct ad_stream *stream, uint8_t *buf, uint8_t buf_len)
146 {
147 	uint8_t read_len = 0;
148 
149 	while (read_len < buf_len) {
150 		const struct bt_data *current_ltv = ad_stream_current_ltv_update(stream);
151 
152 		if (!current_ltv) {
153 			break;
154 		}
155 
156 		if (stream->current_ltv_offset == 0) {
157 			buf[read_len] = current_ltv->data_len + 1;
158 			stream->current_ltv_offset++;
159 			read_len++;
160 		} else if (stream->current_ltv_offset == 1) {
161 			buf[read_len] = current_ltv->type;
162 			stream->current_ltv_offset++;
163 			read_len++;
164 		} else {
165 			const size_t remaining_data_len =
166 					current_ltv->data_len - stream->current_ltv_offset + 2;
167 			const size_t size_to_copy = MIN(buf_len - read_len, remaining_data_len);
168 
169 			(void)memcpy(&buf[read_len],
170 				&current_ltv->data[stream->current_ltv_offset - 2],
171 				size_to_copy);
172 			stream->current_ltv_offset += size_to_copy;
173 			read_len += size_to_copy;
174 		}
175 	}
176 
177 	__ASSERT_NO_MSG(stream->remaining_size >= read_len);
178 	stream->remaining_size -= read_len;
179 
180 	return read_len;
181 }
182 
183 #if defined(CONFIG_BT_EXT_ADV)
184 static struct bt_le_ext_adv adv_pool[CONFIG_BT_EXT_ADV_MAX_ADV_SET];
185 #endif /* defined(CONFIG_BT_EXT_ADV) */
186 
187 
188 #if defined(CONFIG_BT_EXT_ADV)
bt_le_ext_adv_get_index(struct bt_le_ext_adv * adv)189 uint8_t bt_le_ext_adv_get_index(struct bt_le_ext_adv *adv)
190 {
191 	__ASSERT(IS_ARRAY_ELEMENT(adv_pool, adv), "Invalid bt_adv pointer");
192 
193 	return (uint8_t)ARRAY_INDEX(adv_pool, adv);
194 }
195 
adv_new(void)196 static struct bt_le_ext_adv *adv_new(void)
197 {
198 	struct bt_le_ext_adv *adv = NULL;
199 	int i;
200 
201 	for (i = 0; i < ARRAY_SIZE(adv_pool); i++) {
202 		if (!atomic_test_bit(adv_pool[i].flags, BT_ADV_CREATED)) {
203 			adv = &adv_pool[i];
204 			break;
205 		}
206 	}
207 
208 	if (!adv) {
209 		return NULL;
210 	}
211 
212 	(void)memset(adv, 0, sizeof(*adv));
213 	atomic_set_bit(adv_pool[i].flags, BT_ADV_CREATED);
214 	adv->handle = i;
215 
216 	return adv;
217 }
218 
adv_delete(struct bt_le_ext_adv * adv)219 static void adv_delete(struct bt_le_ext_adv *adv)
220 {
221 	atomic_clear_bit(adv->flags, BT_ADV_CREATED);
222 }
223 
224 #if defined(CONFIG_BT_BROADCASTER)
bt_hci_adv_lookup_handle(uint8_t handle)225 struct bt_le_ext_adv *bt_hci_adv_lookup_handle(uint8_t handle)
226 {
227 	if (handle < ARRAY_SIZE(adv_pool) &&
228 	    atomic_test_bit(adv_pool[handle].flags, BT_ADV_CREATED)) {
229 		return &adv_pool[handle];
230 	}
231 
232 	return NULL;
233 }
234 #endif /* CONFIG_BT_BROADCASTER */
235 #endif /* defined(CONFIG_BT_EXT_ADV) */
236 
bt_le_ext_adv_foreach(void (* func)(struct bt_le_ext_adv * adv,void * data),void * data)237 void bt_le_ext_adv_foreach(void (*func)(struct bt_le_ext_adv *adv, void *data),
238 			   void *data)
239 {
240 #if defined(CONFIG_BT_EXT_ADV)
241 	for (size_t i = 0; i < ARRAY_SIZE(adv_pool); i++) {
242 		if (atomic_test_bit(adv_pool[i].flags, BT_ADV_CREATED)) {
243 			func(&adv_pool[i], data);
244 		}
245 	}
246 #else
247 	func(&bt_dev.adv, data);
248 #endif /* defined(CONFIG_BT_EXT_ADV) */
249 }
250 
clear_ext_adv_instance(struct bt_le_ext_adv * adv,void * data)251 static void clear_ext_adv_instance(struct bt_le_ext_adv *adv, void *data)
252 {
253 	bt_le_lim_adv_cancel_timeout(adv);
254 	memset(adv, 0, sizeof(*adv));
255 }
256 
bt_adv_reset_adv_pool(void)257 void bt_adv_reset_adv_pool(void)
258 {
259 	bt_le_ext_adv_foreach(clear_ext_adv_instance, NULL);
260 	(void)memset(&bt_dev.adv, 0, sizeof(bt_dev.adv));
261 }
262 
adv_create_legacy(void)263 static int adv_create_legacy(void)
264 {
265 #if defined(CONFIG_BT_EXT_ADV)
266 	if (bt_dev.adv) {
267 		return -EALREADY;
268 	}
269 
270 	bt_dev.adv = adv_new();
271 	if (bt_dev.adv == NULL) {
272 		return -ENOMEM;
273 	}
274 #endif
275 	return 0;
276 }
277 
bt_le_adv_delete_legacy(void)278 void bt_le_adv_delete_legacy(void)
279 {
280 #if defined(CONFIG_BT_EXT_ADV)
281 	if (bt_dev.adv) {
282 		atomic_clear_bit(bt_dev.adv->flags, BT_ADV_CREATED);
283 		bt_dev.adv = NULL;
284 	}
285 #endif
286 }
287 
bt_le_adv_lookup_legacy(void)288 struct bt_le_ext_adv *bt_le_adv_lookup_legacy(void)
289 {
290 #if defined(CONFIG_BT_EXT_ADV)
291 	return bt_dev.adv;
292 #else
293 	return &bt_dev.adv;
294 #endif
295 }
296 
bt_le_adv_set_enable_legacy(struct bt_le_ext_adv * adv,bool enable)297 int bt_le_adv_set_enable_legacy(struct bt_le_ext_adv *adv, bool enable)
298 {
299 	struct net_buf *buf;
300 	struct bt_hci_cmd_state_set state;
301 	int err;
302 
303 	buf = bt_hci_cmd_alloc(K_FOREVER);
304 	if (!buf) {
305 		return -ENOBUFS;
306 	}
307 
308 	if (enable) {
309 		net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
310 	} else {
311 		net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
312 	}
313 
314 	bt_hci_cmd_state_set_init(buf, &state, adv->flags, BT_ADV_ENABLED, enable);
315 
316 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
317 	if (err) {
318 		return err;
319 	}
320 
321 	return 0;
322 }
323 
bt_le_adv_set_enable_ext(struct bt_le_ext_adv * adv,bool enable,const struct bt_le_ext_adv_start_param * param)324 int bt_le_adv_set_enable_ext(struct bt_le_ext_adv *adv,
325 			 bool enable,
326 			 const struct bt_le_ext_adv_start_param *param)
327 {
328 	struct net_buf *buf;
329 	struct bt_hci_cmd_state_set state;
330 	int err;
331 
332 	buf = bt_hci_cmd_alloc(K_FOREVER);
333 	if (!buf) {
334 		return -ENOBUFS;
335 	}
336 
337 	if (enable) {
338 		net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
339 	} else {
340 		net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
341 	}
342 
343 	net_buf_add_u8(buf, 1);
344 
345 	net_buf_add_u8(buf, adv->handle);
346 	net_buf_add_le16(buf, param ? param->timeout : 0);
347 	net_buf_add_u8(buf, param ? param->num_events : 0);
348 
349 	bt_hci_cmd_state_set_init(buf, &state, adv->flags, BT_ADV_ENABLED, enable);
350 
351 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EXT_ADV_ENABLE, buf, NULL);
352 	if (err) {
353 		return err;
354 	}
355 
356 	return 0;
357 }
358 
bt_le_adv_set_enable(struct bt_le_ext_adv * adv,bool enable)359 int bt_le_adv_set_enable(struct bt_le_ext_adv *adv, bool enable)
360 {
361 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
362 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
363 		return bt_le_adv_set_enable_ext(adv, enable, NULL);
364 	}
365 
366 	return bt_le_adv_set_enable_legacy(adv, enable);
367 }
368 
valid_adv_ext_param(const struct bt_le_adv_param * param)369 static bool valid_adv_ext_param(const struct bt_le_adv_param *param)
370 {
371 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
372 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
373 		if (param->peer && !(param->options & BT_LE_ADV_OPT_EXT_ADV) &&
374 		    !(param->options & BT_LE_ADV_OPT_CONN)) {
375 			/* Cannot do directed non-connectable advertising
376 			 * without extended advertising.
377 			 */
378 			return false;
379 		}
380 
381 		if (param->peer &&
382 		    (param->options & BT_LE_ADV_OPT_EXT_ADV) &&
383 		    !(param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY)) {
384 			/* High duty cycle directed connectable advertising
385 			 * shall not be used with Extended Advertising.
386 			 */
387 			return false;
388 		}
389 
390 		if (!(param->options & BT_LE_ADV_OPT_EXT_ADV) &&
391 		    param->options & (BT_LE_ADV_OPT_EXT_ADV |
392 				      BT_LE_ADV_OPT_NO_2M |
393 				      BT_LE_ADV_OPT_CODED |
394 				      BT_LE_ADV_OPT_ANONYMOUS |
395 				      BT_LE_ADV_OPT_USE_TX_POWER)) {
396 			/* Extended options require extended advertising. */
397 			return false;
398 		}
399 	}
400 
401 	if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
402 	    param->peer &&
403 	    (param->options & BT_LE_ADV_OPT_USE_IDENTITY) &&
404 	    (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
405 		/* own addr type used for both RPAs in directed advertising. */
406 		return false;
407 	}
408 
409 	if (param->id >= bt_dev.id_count ||
410 	    bt_addr_le_eq(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) {
411 		return false;
412 	}
413 
414 	if (!(param->options & BT_LE_ADV_OPT_CONN)) {
415 		/*
416 		 * BT Core 4.2 [Vol 2, Part E, 7.8.5]
417 		 * The Advertising_Interval_Min and Advertising_Interval_Max
418 		 * shall not be set to less than 0x00A0 (100 ms) if the
419 		 * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND.
420 		 */
421 		if (bt_dev.hci_version < BT_HCI_VERSION_5_0 &&
422 		    param->interval_min < 0x00a0) {
423 			return false;
424 		}
425 	}
426 
427 	if ((param->options & (BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY |
428 			       BT_LE_ADV_OPT_DIR_ADDR_RPA)) &&
429 	    !param->peer) {
430 		return false;
431 	}
432 
433 	if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) ||
434 	    !param->peer) {
435 		if (param->interval_min > param->interval_max ||
436 		    param->interval_min < 0x0020 ||
437 		    param->interval_max > 0x4000) {
438 			return false;
439 		}
440 	}
441 
442 	if ((param->options & BT_LE_ADV_OPT_DISABLE_CHAN_37) &&
443 	    (param->options & BT_LE_ADV_OPT_DISABLE_CHAN_38) &&
444 	    (param->options & BT_LE_ADV_OPT_DISABLE_CHAN_39)) {
445 		return false;
446 	}
447 
448 	return true;
449 }
450 
valid_adv_param(const struct bt_le_adv_param * param)451 static bool valid_adv_param(const struct bt_le_adv_param *param)
452 {
453 	if (param->options & BT_LE_ADV_OPT_EXT_ADV) {
454 		return false;
455 	}
456 
457 	if (param->peer && !(param->options & BT_LE_ADV_OPT_CONN)) {
458 		return false;
459 	}
460 
461 	return valid_adv_ext_param(param);
462 }
463 
set_data_add_complete(uint8_t * set_data,uint8_t set_data_len_max,const struct bt_ad * ad,size_t ad_len,uint8_t * data_len)464 static int set_data_add_complete(uint8_t *set_data, uint8_t set_data_len_max,
465 			const struct bt_ad *ad, size_t ad_len, uint8_t *data_len)
466 {
467 	uint8_t set_data_len = 0;
468 
469 	for (size_t i = 0; i < ad_len; i++) {
470 		const struct bt_data *data = ad[i].data;
471 
472 		for (size_t j = 0; j < ad[i].len; j++) {
473 			size_t len = data[j].data_len;
474 			uint8_t type = data[j].type;
475 
476 			/* Check if ad fit in the remaining buffer */
477 			if ((set_data_len + len + 2) > set_data_len_max) {
478 				ssize_t shortened_len = set_data_len_max -
479 							(set_data_len + 2);
480 
481 				if (!(type == BT_DATA_NAME_COMPLETE &&
482 				      shortened_len > 0)) {
483 					LOG_ERR("Too big advertising data");
484 					return -EINVAL;
485 				}
486 
487 				type = BT_DATA_NAME_SHORTENED;
488 				len = shortened_len;
489 			}
490 
491 			set_data[set_data_len++] = len + 1;
492 			set_data[set_data_len++] = type;
493 
494 			memcpy(&set_data[set_data_len], data[j].data, len);
495 			set_data_len += len;
496 		}
497 	}
498 
499 	*data_len = set_data_len;
500 	return 0;
501 }
502 
hci_set_ad(uint16_t hci_op,const struct bt_ad * ad,size_t ad_len)503 static int hci_set_ad(uint16_t hci_op, const struct bt_ad *ad, size_t ad_len)
504 {
505 	struct bt_hci_cp_le_set_adv_data *set_data;
506 	struct net_buf *buf;
507 	int err;
508 
509 	buf = bt_hci_cmd_alloc(K_FOREVER);
510 	if (!buf) {
511 		return -ENOBUFS;
512 	}
513 
514 	set_data = net_buf_add(buf, sizeof(*set_data));
515 	(void)memset(set_data, 0, sizeof(*set_data));
516 
517 	err = set_data_add_complete(set_data->data, BT_GAP_ADV_MAX_ADV_DATA_LEN,
518 				    ad, ad_len, &set_data->len);
519 	if (err) {
520 		net_buf_unref(buf);
521 		return err;
522 	}
523 
524 	return bt_hci_cmd_send_sync(hci_op, buf, NULL);
525 }
526 
hci_set_adv_ext_complete(struct bt_le_ext_adv * adv,uint16_t hci_op,size_t total_data_len,const struct bt_ad * ad,size_t ad_len)527 static int hci_set_adv_ext_complete(struct bt_le_ext_adv *adv, uint16_t hci_op,
528 				    size_t total_data_len, const struct bt_ad *ad, size_t ad_len)
529 {
530 	struct bt_hci_cp_le_set_ext_adv_data *set_data;
531 	struct net_buf *buf;
532 	size_t cmd_size;
533 	int err;
534 
535 	/* Provide the opportunity to truncate the complete name */
536 	if (!atomic_test_bit(adv->flags, BT_ADV_EXT_ADV) &&
537 	    total_data_len > BT_GAP_ADV_MAX_ADV_DATA_LEN) {
538 		total_data_len = BT_GAP_ADV_MAX_ADV_DATA_LEN;
539 	}
540 
541 	cmd_size = sizeof(*set_data) + total_data_len;
542 
543 	buf = bt_hci_cmd_alloc(K_FOREVER);
544 	if (!buf) {
545 		return -ENOBUFS;
546 	}
547 
548 	set_data = net_buf_add(buf, cmd_size);
549 	(void)memset(set_data, 0, cmd_size);
550 
551 	err = set_data_add_complete(set_data->data, total_data_len,
552 				    ad, ad_len, &set_data->len);
553 	if (err) {
554 		net_buf_unref(buf);
555 		return err;
556 	}
557 
558 	set_data->handle = adv->handle;
559 	set_data->op = BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA;
560 	set_data->frag_pref = BT_HCI_LE_EXT_ADV_FRAG_DISABLED;
561 
562 	return bt_hci_cmd_send_sync(hci_op, buf, NULL);
563 }
564 
hci_set_adv_ext_fragmented(struct bt_le_ext_adv * adv,uint16_t hci_op,const struct bt_ad * ad,size_t ad_len)565 static int hci_set_adv_ext_fragmented(struct bt_le_ext_adv *adv, uint16_t hci_op,
566 				      const struct bt_ad *ad, size_t ad_len)
567 {
568 	int err;
569 	struct ad_stream stream;
570 	bool is_first_iteration = true;
571 
572 	err = ad_stream_new(&stream, ad, ad_len);
573 	if (err) {
574 		return err;
575 	}
576 
577 	while (!ad_stream_is_empty(&stream)) {
578 		struct bt_hci_cp_le_set_ext_adv_data *set_data;
579 		struct net_buf *buf;
580 		const size_t data_len = MIN(BT_HCI_LE_EXT_ADV_FRAG_MAX_LEN, stream.remaining_size);
581 		const size_t cmd_size = sizeof(*set_data) + data_len;
582 
583 		buf = bt_hci_cmd_alloc(K_FOREVER);
584 		if (!buf) {
585 			return -ENOBUFS;
586 		}
587 
588 		set_data = net_buf_add(buf, cmd_size);
589 
590 		set_data->handle = adv->handle;
591 		set_data->frag_pref = BT_HCI_LE_EXT_ADV_FRAG_ENABLED;
592 		set_data->len = ad_stream_read(&stream, set_data->data, data_len);
593 
594 		if (is_first_iteration && ad_stream_is_empty(&stream)) {
595 			set_data->op = BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA;
596 		} else if (is_first_iteration) {
597 			set_data->op = BT_HCI_LE_EXT_ADV_OP_FIRST_FRAG;
598 		} else if (ad_stream_is_empty(&stream)) {
599 			set_data->op = BT_HCI_LE_EXT_ADV_OP_LAST_FRAG;
600 		} else {
601 			set_data->op = BT_HCI_LE_EXT_ADV_OP_INTERM_FRAG;
602 		}
603 
604 		err = bt_hci_cmd_send_sync(hci_op, buf, NULL);
605 		if (err) {
606 			return err;
607 		}
608 
609 		is_first_iteration = false;
610 	}
611 
612 	return 0;
613 }
614 
hci_set_ad_ext(struct bt_le_ext_adv * adv,uint16_t hci_op,const struct bt_ad * ad,size_t ad_len)615 static int hci_set_ad_ext(struct bt_le_ext_adv *adv, uint16_t hci_op,
616 			  const struct bt_ad *ad, size_t ad_len)
617 {
618 	size_t total_len_bytes = 0;
619 
620 	for (size_t i = 0; i < ad_len; i++) {
621 		for (size_t j = 0; j < ad[i].len; j++) {
622 			total_len_bytes += ad[i].data[j].data_len + 2;
623 		}
624 	}
625 
626 	if ((total_len_bytes > BT_HCI_LE_EXT_ADV_FRAG_MAX_LEN) &&
627 	    atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
628 		/* It is not allowed to set advertising data in multiple
629 		 * operations while the advertiser is running.
630 		 */
631 		return -EAGAIN;
632 	}
633 
634 	if (total_len_bytes > bt_dev.le.max_adv_data_len) {
635 		LOG_WRN("adv or scan rsp data too large (%zu > max %u)", total_len_bytes,
636 			bt_dev.le.max_adv_data_len);
637 		return -EDOM;
638 	}
639 
640 	if (total_len_bytes <= BT_HCI_LE_EXT_ADV_FRAG_MAX_LEN) {
641 		/* If possible, set all data at once.
642 		 * This allows us to update advertising data while advertising.
643 		 */
644 		return hci_set_adv_ext_complete(adv, hci_op, total_len_bytes, ad, ad_len);
645 	} else {
646 		return hci_set_adv_ext_fragmented(adv, hci_op, ad, ad_len);
647 	}
648 
649 	return 0;
650 }
651 
set_ad(struct bt_le_ext_adv * adv,const struct bt_ad * ad,size_t ad_len)652 static int set_ad(struct bt_le_ext_adv *adv, const struct bt_ad *ad,
653 		  size_t ad_len)
654 {
655 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
656 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
657 		return hci_set_ad_ext(adv, BT_HCI_OP_LE_SET_EXT_ADV_DATA,
658 				      ad, ad_len);
659 	}
660 
661 	return hci_set_ad(BT_HCI_OP_LE_SET_ADV_DATA, ad, ad_len);
662 }
663 
set_sd(struct bt_le_ext_adv * adv,const struct bt_ad * sd,size_t sd_len)664 static int set_sd(struct bt_le_ext_adv *adv, const struct bt_ad *sd,
665 		  size_t sd_len)
666 {
667 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
668 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
669 		return hci_set_ad_ext(adv, BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA,
670 				      sd, sd_len);
671 	}
672 
673 	return hci_set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sd, sd_len);
674 }
675 
676 #if defined(CONFIG_BT_PER_ADV)
hci_set_per_adv_data(const struct bt_le_ext_adv * adv,const struct bt_data * ad,size_t ad_len)677 static int hci_set_per_adv_data(const struct bt_le_ext_adv *adv,
678 				const struct bt_data *ad, size_t ad_len)
679 {
680 	int err;
681 	struct ad_stream stream;
682 	struct bt_ad d = { .data = ad, .len = ad_len };
683 	bool is_first_iteration = true;
684 
685 	err = ad_stream_new(&stream, &d, 1);
686 	if (err) {
687 		return err;
688 	}
689 
690 	while (!ad_stream_is_empty(&stream)) {
691 		struct bt_hci_cp_le_set_per_adv_data *set_data;
692 		struct net_buf *buf;
693 		const size_t data_len = MIN(BT_HCI_LE_PER_ADV_FRAG_MAX_LEN, stream.remaining_size);
694 		const size_t cmd_size = sizeof(*set_data) + data_len;
695 
696 		buf = bt_hci_cmd_alloc(K_FOREVER);
697 		if (!buf) {
698 			return -ENOBUFS;
699 		}
700 
701 		set_data = net_buf_add(buf, cmd_size);
702 		(void)memset(set_data, 0, cmd_size);
703 
704 		set_data->handle = adv->handle;
705 		set_data->len = ad_stream_read(&stream, set_data->data, data_len);
706 
707 		if (is_first_iteration && ad_stream_is_empty(&stream)) {
708 			set_data->op = BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA;
709 		} else if (is_first_iteration) {
710 			set_data->op = BT_HCI_LE_EXT_ADV_OP_FIRST_FRAG;
711 		} else if (ad_stream_is_empty(&stream)) {
712 			set_data->op = BT_HCI_LE_EXT_ADV_OP_LAST_FRAG;
713 		} else {
714 			set_data->op = BT_HCI_LE_EXT_ADV_OP_INTERM_FRAG;
715 		}
716 
717 		err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PER_ADV_DATA, buf, NULL);
718 		if (err) {
719 			return err;
720 		}
721 
722 		is_first_iteration = false;
723 	}
724 
725 	return 0;
726 }
727 #endif /* CONFIG_BT_PER_ADV */
728 
ad_is_limited(const struct bt_data * ad,size_t ad_len)729 static bool ad_is_limited(const struct bt_data *ad, size_t ad_len)
730 {
731 	size_t i;
732 
733 	for (i = 0; i < ad_len; i++) {
734 		if (ad[i].type == BT_DATA_FLAGS &&
735 		    ad[i].data_len == sizeof(uint8_t) &&
736 		    ad[i].data != NULL) {
737 			if (ad[i].data[0] & BT_LE_AD_LIMITED) {
738 				return true;
739 			}
740 		}
741 	}
742 
743 	return false;
744 }
745 
le_adv_update(struct bt_le_ext_adv * adv,const struct bt_data * ad,size_t ad_len,const struct bt_data * sd,size_t sd_len,bool ext_adv,bool scannable)746 static int le_adv_update(struct bt_le_ext_adv *adv,
747 			 const struct bt_data *ad, size_t ad_len,
748 			 const struct bt_data *sd, size_t sd_len,
749 			 bool ext_adv, bool scannable)
750 {
751 	int err;
752 	struct bt_ad wrapper;
753 
754 	if (!(ext_adv && scannable)) {
755 		wrapper.data = ad;
756 		wrapper.len = ad_len;
757 
758 		err = set_ad(adv, &wrapper, 1);
759 		if (err) {
760 			return err;
761 		}
762 	}
763 
764 	if (scannable) {
765 		wrapper.data = sd;
766 		wrapper.len = sd_len;
767 
768 		err = set_sd(adv, &wrapper, 1);
769 		if (err) {
770 			return err;
771 		}
772 	}
773 
774 	atomic_set_bit(adv->flags, BT_ADV_DATA_SET);
775 	return 0;
776 }
777 
bt_le_adv_update_data(const struct bt_data * ad,size_t ad_len,const struct bt_data * sd,size_t sd_len)778 int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len,
779 			  const struct bt_data *sd, size_t sd_len)
780 {
781 	struct bt_le_ext_adv *adv = bt_le_adv_lookup_legacy();
782 	bool scannable;
783 
784 	if (!adv) {
785 		return -EINVAL;
786 	}
787 
788 	if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
789 		return -EAGAIN;
790 	}
791 
792 	scannable = atomic_test_bit(adv->flags, BT_ADV_SCANNABLE);
793 
794 	return le_adv_update(adv, ad, ad_len, sd, sd_len, false, scannable);
795 }
796 
get_filter_policy(uint32_t options)797 static uint8_t get_filter_policy(uint32_t options)
798 {
799 	if (!IS_ENABLED(CONFIG_BT_FILTER_ACCEPT_LIST)) {
800 		return BT_LE_ADV_FP_NO_FILTER;
801 	} else if ((options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) &&
802 		   (options & BT_LE_ADV_OPT_FILTER_CONN)) {
803 		return BT_LE_ADV_FP_FILTER_BOTH;
804 	} else if (options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
805 		return BT_LE_ADV_FP_FILTER_SCAN_REQ;
806 	} else if (options & BT_LE_ADV_OPT_FILTER_CONN) {
807 		return BT_LE_ADV_FP_FILTER_CONN_IND;
808 	} else {
809 		return BT_LE_ADV_FP_NO_FILTER;
810 	}
811 }
812 
get_adv_channel_map(uint32_t options)813 static uint8_t get_adv_channel_map(uint32_t options)
814 {
815 	uint8_t channel_map = 0x07;
816 
817 	if (options & BT_LE_ADV_OPT_DISABLE_CHAN_37) {
818 		channel_map &= ~0x01;
819 	}
820 
821 	if (options & BT_LE_ADV_OPT_DISABLE_CHAN_38) {
822 		channel_map &= ~0x02;
823 	}
824 
825 	if (options & BT_LE_ADV_OPT_DISABLE_CHAN_39) {
826 		channel_map &= ~0x04;
827 	}
828 
829 	return channel_map;
830 }
831 
adv_is_directed(const struct bt_le_ext_adv * adv)832 static inline bool adv_is_directed(const struct bt_le_ext_adv *adv)
833 {
834 	/* The advertiser is assumed to be directed when the peer address has
835 	 * been set.
836 	 */
837 	return !bt_addr_le_eq(&adv->target_addr, BT_ADDR_LE_ANY);
838 }
839 
le_adv_start_add_conn(const struct bt_le_ext_adv * adv,struct bt_conn ** out_conn)840 static int le_adv_start_add_conn(const struct bt_le_ext_adv *adv,
841 				 struct bt_conn **out_conn)
842 {
843 	struct bt_conn *conn;
844 
845 	bt_dev.adv_conn_id = adv->id;
846 
847 	if (!adv_is_directed(adv)) {
848 		/* Undirected advertising */
849 		conn = bt_conn_add_le(adv->id, BT_ADDR_LE_NONE);
850 		if (!conn) {
851 			return -ENOMEM;
852 		}
853 
854 		bt_conn_set_state(conn, BT_CONN_ADV_CONNECTABLE);
855 		*out_conn = conn;
856 		return 0;
857 	}
858 
859 	if (bt_conn_exists_le(adv->id, &adv->target_addr)) {
860 		return -EINVAL;
861 	}
862 
863 	conn = bt_conn_add_le(adv->id, &adv->target_addr);
864 	if (!conn) {
865 		return -ENOMEM;
866 	}
867 
868 	bt_conn_set_state(conn, BT_CONN_ADV_DIR_CONNECTABLE);
869 	*out_conn = conn;
870 	return 0;
871 }
872 
le_adv_stop_free_conn(const struct bt_le_ext_adv * adv,uint8_t status)873 static void le_adv_stop_free_conn(const struct bt_le_ext_adv *adv, uint8_t status)
874 {
875 	struct bt_conn *conn;
876 
877 	if (!adv_is_directed(adv)) {
878 		conn = bt_conn_lookup_state_le(adv->id, BT_ADDR_LE_NONE,
879 					       BT_CONN_ADV_CONNECTABLE);
880 	} else {
881 		conn = bt_conn_lookup_state_le(adv->id, &adv->target_addr,
882 					       BT_CONN_ADV_DIR_CONNECTABLE);
883 	}
884 
885 	if (conn) {
886 		conn->err = status;
887 		bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
888 		bt_conn_unref(conn);
889 	}
890 }
891 
adv_start_legacy(struct bt_le_ext_adv * adv,const struct bt_le_adv_param * param,const struct bt_data * ad,size_t ad_len,const struct bt_data * sd,size_t sd_len)892 static int adv_start_legacy(struct bt_le_ext_adv *adv,
893 			   const struct bt_le_adv_param *param,
894 			   const struct bt_data *ad, size_t ad_len,
895 			   const struct bt_data *sd, size_t sd_len)
896 {
897 	struct bt_hci_cp_le_set_adv_param set_param;
898 	struct bt_conn *conn = NULL;
899 	struct net_buf *buf;
900 	bool dir_adv = (param->peer != NULL), scannable = false;
901 
902 	int err;
903 
904 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
905 		return -EAGAIN;
906 	}
907 
908 	if (!valid_adv_param(param)) {
909 		return -EINVAL;
910 	}
911 
912 	if (!bt_id_adv_random_addr_check(param)) {
913 		return -EINVAL;
914 	}
915 
916 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
917 		return -EALREADY;
918 	}
919 
920 	(void)memset(&set_param, 0, sizeof(set_param));
921 
922 	set_param.min_interval = sys_cpu_to_le16(param->interval_min);
923 	set_param.max_interval = sys_cpu_to_le16(param->interval_max);
924 	set_param.channel_map  = get_adv_channel_map(param->options);
925 	set_param.filter_policy = get_filter_policy(param->options);
926 
927 	atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
928 
929 	adv->id = param->id;
930 	bt_dev.adv_conn_id = adv->id;
931 
932 	err = bt_id_set_adv_own_addr(adv, param->options, dir_adv,
933 				     &set_param.own_addr_type);
934 	if (err) {
935 		return err;
936 	}
937 
938 	if (dir_adv) {
939 		bt_addr_le_copy(&adv->target_addr, param->peer);
940 	} else {
941 		bt_addr_le_copy(&adv->target_addr, BT_ADDR_LE_ANY);
942 	}
943 
944 	if (param->options & BT_LE_ADV_OPT_CONN) {
945 		if (dir_adv) {
946 			if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
947 				set_param.type = BT_HCI_ADV_DIRECT_IND_LOW_DUTY;
948 			} else {
949 				set_param.type = BT_HCI_ADV_DIRECT_IND;
950 			}
951 
952 			bt_addr_le_copy(&set_param.direct_addr, param->peer);
953 		} else {
954 			scannable = true;
955 			set_param.type = BT_HCI_ADV_IND;
956 		}
957 	} else if ((param->options & BT_LE_ADV_OPT_SCANNABLE) || sd) {
958 		scannable = true;
959 		set_param.type = BT_HCI_ADV_SCAN_IND;
960 	} else {
961 		set_param.type = BT_HCI_ADV_NONCONN_IND;
962 	}
963 
964 	buf = bt_hci_cmd_alloc(K_FOREVER);
965 	if (!buf) {
966 		return -ENOBUFS;
967 	}
968 
969 	net_buf_add_mem(buf, &set_param, sizeof(set_param));
970 
971 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
972 	if (err) {
973 		return err;
974 	}
975 
976 	if (!dir_adv) {
977 		err = le_adv_update(adv, ad, ad_len, sd, sd_len, false, scannable);
978 		if (err) {
979 			return err;
980 		}
981 	}
982 
983 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && (param->options & BT_LE_ADV_OPT_CONN)) {
984 		err = le_adv_start_add_conn(adv, &conn);
985 		if (err) {
986 			return err;
987 		}
988 	}
989 
990 	err = bt_le_adv_set_enable(adv, true);
991 	if (err) {
992 		LOG_ERR("Failed to start advertiser");
993 		if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) {
994 			bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
995 			bt_conn_unref(conn);
996 		}
997 
998 		return err;
999 	}
1000 
1001 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) {
1002 		/* If undirected connectable advertiser we have created a
1003 		 * connection object that we don't yet give to the application.
1004 		 * Since we don't give the application a reference to manage in
1005 		 * this case, we need to release this reference here
1006 		 */
1007 		bt_conn_unref(conn);
1008 	}
1009 
1010 	atomic_set_bit_to(adv->flags, BT_ADV_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONN);
1011 
1012 	atomic_set_bit_to(adv->flags, BT_ADV_SCANNABLE, scannable);
1013 
1014 	atomic_set_bit_to(adv->flags, BT_ADV_USE_IDENTITY,
1015 			  param->options & BT_LE_ADV_OPT_USE_IDENTITY);
1016 
1017 	return 0;
1018 }
1019 
le_ext_adv_param_set(struct bt_le_ext_adv * adv,const struct bt_le_adv_param * param,bool has_scan_data)1020 static int le_ext_adv_param_set(struct bt_le_ext_adv *adv,
1021 				const struct bt_le_adv_param *param,
1022 				bool  has_scan_data)
1023 {
1024 	struct bt_hci_cp_le_set_ext_adv_param_v2 *cp;
1025 
1026 	uint16_t opcode;
1027 	uint16_t size;
1028 	bool dir_adv = param->peer != NULL, scannable;
1029 	struct net_buf *buf, *rsp;
1030 	uint8_t own_addr_type;
1031 	int err;
1032 	uint16_t props = 0;
1033 
1034 	adv->options = param->options;
1035 
1036 	err = bt_id_set_adv_own_addr(adv, param->options, dir_adv,
1037 				     &own_addr_type);
1038 	if (err) {
1039 		return err;
1040 	}
1041 
1042 	if (dir_adv) {
1043 		bt_addr_le_copy(&adv->target_addr, param->peer);
1044 	} else {
1045 		bt_addr_le_copy(&adv->target_addr, BT_ADDR_LE_ANY);
1046 	}
1047 
1048 	if (IS_ENABLED(CONFIG_BT_EXT_ADV_CODING_SELECTION) &&
1049 	    BT_FEAT_LE_ADV_CODING_SEL(bt_dev.le.features)) {
1050 		opcode = BT_HCI_OP_LE_SET_EXT_ADV_PARAM_V2;
1051 		size = sizeof(struct bt_hci_cp_le_set_ext_adv_param_v2);
1052 	} else {
1053 		opcode = BT_HCI_OP_LE_SET_EXT_ADV_PARAM;
1054 		size = sizeof(struct bt_hci_cp_le_set_ext_adv_param);
1055 	}
1056 
1057 	buf = bt_hci_cmd_alloc(K_FOREVER);
1058 	if (!buf) {
1059 		return -ENOBUFS;
1060 	}
1061 
1062 	cp = net_buf_add(buf, size);
1063 	(void)memset(cp, 0, size);
1064 
1065 	cp->handle = adv->handle;
1066 	sys_put_le24(param->interval_min, cp->prim_min_interval);
1067 	sys_put_le24(param->interval_max, cp->prim_max_interval);
1068 	cp->prim_channel_map = get_adv_channel_map(param->options);
1069 	cp->own_addr_type = own_addr_type;
1070 	cp->filter_policy = get_filter_policy(param->options);
1071 	cp->tx_power = BT_HCI_LE_ADV_TX_POWER_NO_PREF;
1072 	cp->prim_adv_phy = BT_HCI_LE_PHY_1M;
1073 
1074 	if ((param->options & BT_LE_ADV_OPT_EXT_ADV) &&
1075 	    !(param->options & BT_LE_ADV_OPT_NO_2M)) {
1076 		cp->sec_adv_phy = BT_HCI_LE_PHY_2M;
1077 	} else {
1078 		cp->sec_adv_phy = BT_HCI_LE_PHY_1M;
1079 	}
1080 
1081 	if (param->options & BT_LE_ADV_OPT_CODED) {
1082 		cp->prim_adv_phy = BT_HCI_LE_PHY_CODED;
1083 		cp->sec_adv_phy = BT_HCI_LE_PHY_CODED;
1084 
1085 		if (IS_ENABLED(CONFIG_BT_EXT_ADV_CODING_SELECTION) &&
1086 		    opcode == BT_HCI_OP_LE_SET_EXT_ADV_PARAM_V2) {
1087 			uint8_t adv_phy_opt;
1088 
1089 			if (param->options & BT_LE_ADV_OPT_REQUIRE_S8_CODING) {
1090 				adv_phy_opt = BT_HCI_LE_ADV_PHY_OPTION_REQUIRE_S8;
1091 			} else if (param->options & BT_LE_ADV_OPT_REQUIRE_S2_CODING) {
1092 				adv_phy_opt = BT_HCI_LE_ADV_PHY_OPTION_REQUIRE_S2;
1093 			} else {
1094 				adv_phy_opt = BT_HCI_LE_ADV_PHY_OPTION_NO_REQUIRED;
1095 			}
1096 
1097 			cp->prim_adv_phy_opt = adv_phy_opt;
1098 			cp->sec_adv_phy_opt = adv_phy_opt;
1099 		}
1100 	}
1101 
1102 	if (!(param->options & BT_LE_ADV_OPT_EXT_ADV)) {
1103 		props |= BT_HCI_LE_ADV_PROP_LEGACY;
1104 	}
1105 
1106 	if (param->options & BT_LE_ADV_OPT_USE_TX_POWER) {
1107 		props |= BT_HCI_LE_ADV_PROP_TX_POWER;
1108 	}
1109 
1110 	if (param->options & BT_LE_ADV_OPT_ANONYMOUS) {
1111 		props |= BT_HCI_LE_ADV_PROP_ANON;
1112 	}
1113 
1114 	if (param->options & BT_LE_ADV_OPT_NOTIFY_SCAN_REQ) {
1115 		cp->scan_req_notify_enable = BT_HCI_LE_ADV_SCAN_REQ_ENABLE;
1116 	}
1117 
1118 	if (param->options & BT_LE_ADV_OPT_CONN) {
1119 		props |= BT_HCI_LE_ADV_PROP_CONN;
1120 		if (!dir_adv && !(param->options & BT_LE_ADV_OPT_EXT_ADV)) {
1121 			/* When using non-extended adv packets then undirected
1122 			 * advertising has to be scannable as well.
1123 			 * We didn't require this option to be set before, so
1124 			 * it is implicitly set instead in this case.
1125 			 */
1126 			props |= BT_HCI_LE_ADV_PROP_SCAN;
1127 		}
1128 	}
1129 
1130 	if ((param->options & BT_LE_ADV_OPT_SCANNABLE) || has_scan_data) {
1131 		props |= BT_HCI_LE_ADV_PROP_SCAN;
1132 	}
1133 
1134 	scannable = !!(props & BT_HCI_LE_ADV_PROP_SCAN);
1135 
1136 	if (dir_adv) {
1137 		props |= BT_HCI_LE_ADV_PROP_DIRECT;
1138 		if (!(param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY)) {
1139 			props |= BT_HCI_LE_ADV_PROP_HI_DC_CONN;
1140 		}
1141 
1142 		bt_addr_le_copy(&cp->peer_addr, param->peer);
1143 	}
1144 
1145 	cp->sid = param->sid;
1146 
1147 	cp->sec_adv_max_skip = param->secondary_max_skip;
1148 
1149 	cp->props = sys_cpu_to_le16(props);
1150 
1151 	err = bt_hci_cmd_send_sync(opcode, buf, &rsp);
1152 	if (err) {
1153 		return err;
1154 	}
1155 
1156 #if defined(CONFIG_BT_EXT_ADV)
1157 	struct bt_hci_rp_le_set_ext_adv_param *rp = (void *)rsp->data;
1158 
1159 	adv->tx_power = rp->tx_power;
1160 #endif /* defined(CONFIG_BT_EXT_ADV) */
1161 
1162 	net_buf_unref(rsp);
1163 
1164 	atomic_set_bit(adv->flags, BT_ADV_PARAMS_SET);
1165 
1166 	if (atomic_test_and_clear_bit(adv->flags, BT_ADV_RANDOM_ADDR_PENDING)) {
1167 		err = bt_id_set_adv_random_addr(adv, &adv->random_addr.a);
1168 		if (err) {
1169 			return err;
1170 		}
1171 	}
1172 
1173 	atomic_set_bit_to(adv->flags, BT_ADV_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONN);
1174 
1175 	atomic_set_bit_to(adv->flags, BT_ADV_SCANNABLE, scannable);
1176 
1177 	atomic_set_bit_to(adv->flags, BT_ADV_USE_IDENTITY,
1178 			  param->options & BT_LE_ADV_OPT_USE_IDENTITY);
1179 
1180 	atomic_set_bit_to(adv->flags, BT_ADV_EXT_ADV,
1181 			  param->options & BT_LE_ADV_OPT_EXT_ADV);
1182 
1183 	atomic_set_bit_to(adv->flags, BT_ADV_RANDOM_ADDR_UPDATED,
1184 			  own_addr_type == BT_HCI_OWN_ADDR_RANDOM);
1185 
1186 	return 0;
1187 }
1188 
bt_le_adv_start_ext(struct bt_le_ext_adv * adv,const struct bt_le_adv_param * param,const struct bt_data * ad,size_t ad_len,const struct bt_data * sd,size_t sd_len)1189 int bt_le_adv_start_ext(struct bt_le_ext_adv *adv,
1190 			const struct bt_le_adv_param *param,
1191 			const struct bt_data *ad, size_t ad_len,
1192 			const struct bt_data *sd, size_t sd_len)
1193 {
1194 	struct bt_le_ext_adv_start_param start_param = {
1195 		.timeout = 0,
1196 		.num_events = 0,
1197 	};
1198 	bool dir_adv = (param->peer != NULL);
1199 	struct bt_conn *conn = NULL;
1200 	int err;
1201 
1202 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
1203 		return -EAGAIN;
1204 	}
1205 
1206 	if (!valid_adv_param(param)) {
1207 		return -EINVAL;
1208 	}
1209 
1210 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1211 		return -EALREADY;
1212 	}
1213 
1214 	adv->id = param->id;
1215 	err = le_ext_adv_param_set(adv, param, sd != NULL);
1216 	if (err) {
1217 		return err;
1218 	}
1219 
1220 	if (!dir_adv) {
1221 		if (IS_ENABLED(CONFIG_BT_EXT_ADV)) {
1222 			err = bt_le_ext_adv_set_data(adv, ad, ad_len, sd, sd_len);
1223 			if (err) {
1224 				return err;
1225 			}
1226 		}
1227 	} else {
1228 		if (!(param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY)) {
1229 			start_param.timeout =
1230 				BT_GAP_ADV_HIGH_DUTY_CYCLE_MAX_TIMEOUT;
1231 			atomic_set_bit(adv->flags, BT_ADV_LIMITED);
1232 		}
1233 	}
1234 
1235 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && (param->options & BT_LE_ADV_OPT_CONN)) {
1236 		err = le_adv_start_add_conn(adv, &conn);
1237 		if (err) {
1238 			return err;
1239 		}
1240 	}
1241 
1242 	err = bt_le_adv_set_enable_ext(adv, true, &start_param);
1243 	if (err) {
1244 		LOG_ERR("Failed to start advertiser");
1245 		if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) {
1246 			bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
1247 			bt_conn_unref(conn);
1248 		}
1249 
1250 		return err;
1251 	}
1252 
1253 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) {
1254 		/* If undirected connectable advertiser we have created a
1255 		 * connection object that we don't yet give to the application.
1256 		 * Since we don't give the application a reference to manage in
1257 		 * this case, we need to release this reference here
1258 		 */
1259 		bt_conn_unref(conn);
1260 	}
1261 
1262 	return 0;
1263 }
1264 
1265 static void adv_timeout(struct k_work *work);
1266 
bt_le_lim_adv_cancel_timeout(struct bt_le_ext_adv * adv)1267 int bt_le_lim_adv_cancel_timeout(struct bt_le_ext_adv *adv)
1268 {
1269 	return k_work_cancel_delayable(&adv->lim_adv_timeout_work);
1270 }
1271 
bt_le_adv_start(const struct bt_le_adv_param * param,const struct bt_data * ad,size_t ad_len,const struct bt_data * sd,size_t sd_len)1272 int bt_le_adv_start(const struct bt_le_adv_param *param,
1273 		    const struct bt_data *ad, size_t ad_len,
1274 		    const struct bt_data *sd, size_t sd_len)
1275 {
1276 	struct bt_le_ext_adv *adv;
1277 	int err;
1278 
1279 	err = adv_create_legacy();
1280 	if (err) {
1281 		return err;
1282 	}
1283 
1284 	adv = bt_le_adv_lookup_legacy();
1285 
1286 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1287 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
1288 		err = bt_le_adv_start_ext(adv, param, ad, ad_len, sd, sd_len);
1289 	} else {
1290 		err = adv_start_legacy(adv, param, ad, ad_len, sd, sd_len);
1291 	}
1292 
1293 	if (err) {
1294 		bt_le_adv_delete_legacy();
1295 	}
1296 
1297 	if (ad_is_limited(ad, ad_len)) {
1298 		k_work_init_delayable(&adv->lim_adv_timeout_work, adv_timeout);
1299 		k_work_reschedule(&adv->lim_adv_timeout_work,
1300 				  K_SECONDS(CONFIG_BT_LIM_ADV_TIMEOUT));
1301 	}
1302 
1303 	return err;
1304 }
1305 
bt_le_adv_stop(void)1306 int bt_le_adv_stop(void)
1307 {
1308 	struct bt_le_ext_adv *adv = bt_le_adv_lookup_legacy();
1309 	int err;
1310 
1311 	if (!adv) {
1312 		LOG_ERR("No valid legacy adv to stop");
1313 		return 0;
1314 	}
1315 
1316 	(void)bt_le_lim_adv_cancel_timeout(adv);
1317 
1318 	if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1319 		/* Legacy advertiser exists, but is not currently advertising.
1320 		 * This happens when keep advertising behavior is active but
1321 		 * no conn object is available to do connectable advertising.
1322 		 */
1323 		bt_le_adv_delete_legacy();
1324 		return 0;
1325 	}
1326 
1327 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
1328 	    atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) {
1329 		le_adv_stop_free_conn(adv, 0);
1330 	}
1331 
1332 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1333 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
1334 		err = bt_le_adv_set_enable_ext(adv, false, NULL);
1335 		if (err) {
1336 			return err;
1337 		}
1338 	} else {
1339 		err = bt_le_adv_set_enable_legacy(adv, false);
1340 		if (err) {
1341 			return err;
1342 		}
1343 	}
1344 
1345 	bt_le_adv_delete_legacy();
1346 
1347 #if defined(CONFIG_BT_OBSERVER)
1348 	if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1349 	      BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) &&
1350 	    !IS_ENABLED(CONFIG_BT_PRIVACY) &&
1351 	    !IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY)) {
1352 		/* If scan is ongoing set back NRPA */
1353 		if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
1354 			bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
1355 			bt_id_set_private_addr(BT_ID_DEFAULT);
1356 			bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
1357 		}
1358 	}
1359 #endif /* defined(CONFIG_BT_OBSERVER) */
1360 
1361 	return 0;
1362 }
1363 
1364 #if defined(CONFIG_BT_EXT_ADV)
bt_le_ext_adv_get_info(const struct bt_le_ext_adv * adv,struct bt_le_ext_adv_info * info)1365 int bt_le_ext_adv_get_info(const struct bt_le_ext_adv *adv,
1366 			   struct bt_le_ext_adv_info *info)
1367 {
1368 	if (!IS_ARRAY_ELEMENT(adv_pool, adv)) {
1369 		LOG_DBG("adv %p is a valid pointer from bt_le_ext_adv_create", adv);
1370 		return -EINVAL;
1371 	}
1372 
1373 	if (!atomic_test_bit(adv->flags, BT_ADV_CREATED)) {
1374 		LOG_DBG("Advertising set %p is not created", adv);
1375 		return -EINVAL;
1376 	}
1377 
1378 	if (info == NULL) {
1379 		LOG_DBG("info is NULL");
1380 		return -EINVAL;
1381 	}
1382 
1383 	info->id = adv->id;
1384 	info->sid = adv->sid;
1385 	info->tx_power = adv->tx_power;
1386 	info->addr = &adv->random_addr;
1387 
1388 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1389 		info->ext_adv_state = BT_LE_EXT_ADV_STATE_ENABLED;
1390 	} else {
1391 		info->ext_adv_state = BT_LE_EXT_ADV_STATE_DISABLED;
1392 	}
1393 
1394 	if (IS_ENABLED(CONFIG_BT_PER_ADV)) {
1395 		if (atomic_test_bit(adv->flags, BT_PER_ADV_ENABLED)) {
1396 			info->per_adv_state = BT_LE_PER_ADV_STATE_ENABLED;
1397 		} else if (atomic_test_bit(adv->flags, BT_PER_ADV_PARAMS_SET)) {
1398 			info->per_adv_state = BT_LE_PER_ADV_STATE_DISABLED;
1399 		} else {
1400 			info->per_adv_state = BT_LE_PER_ADV_STATE_NONE;
1401 		}
1402 	} else {
1403 		info->per_adv_state = BT_LE_PER_ADV_STATE_NONE;
1404 	}
1405 
1406 	return 0;
1407 }
1408 
bt_le_ext_adv_create(const struct bt_le_adv_param * param,const struct bt_le_ext_adv_cb * cb,struct bt_le_ext_adv ** out_adv)1409 int bt_le_ext_adv_create(const struct bt_le_adv_param *param,
1410 			 const struct bt_le_ext_adv_cb *cb,
1411 			 struct bt_le_ext_adv **out_adv)
1412 {
1413 	struct bt_le_ext_adv *adv;
1414 	int err;
1415 
1416 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
1417 		return -EAGAIN;
1418 	}
1419 
1420 	CHECKIF(out_adv == NULL) {
1421 		LOG_DBG("out_adv is NULL");
1422 
1423 		return -EINVAL;
1424 	}
1425 
1426 	if (!valid_adv_ext_param(param)) {
1427 		return -EINVAL;
1428 	}
1429 
1430 	adv = adv_new();
1431 	if (!adv) {
1432 		return -ENOMEM;
1433 	}
1434 
1435 	adv->id = param->id;
1436 	adv->sid = param->sid;
1437 	adv->cb = cb;
1438 
1439 	err = le_ext_adv_param_set(adv, param, false);
1440 	if (err) {
1441 		adv_delete(adv);
1442 		return err;
1443 	}
1444 
1445 	*out_adv = adv;
1446 	return 0;
1447 }
1448 
bt_le_ext_adv_update_param(struct bt_le_ext_adv * adv,const struct bt_le_adv_param * param)1449 int bt_le_ext_adv_update_param(struct bt_le_ext_adv *adv,
1450 			       const struct bt_le_adv_param *param)
1451 {
1452 	CHECKIF(adv == NULL) {
1453 		LOG_DBG("adv is NULL");
1454 
1455 		return -EINVAL;
1456 	}
1457 
1458 	if (!valid_adv_ext_param(param)) {
1459 		return -EINVAL;
1460 	}
1461 
1462 	if (IS_ENABLED(CONFIG_BT_PER_ADV) &&
1463 	    atomic_test_bit(adv->flags, BT_PER_ADV_PARAMS_SET)) {
1464 		/* If params for per adv has been set, do not allow setting
1465 		 * connectable, scanable or use legacy adv
1466 		 */
1467 		if (param->options & BT_LE_ADV_OPT_CONN ||
1468 		    param->options & BT_LE_ADV_OPT_SCANNABLE ||
1469 		    !(param->options & BT_LE_ADV_OPT_EXT_ADV) ||
1470 		    param->options & BT_LE_ADV_OPT_ANONYMOUS) {
1471 			return -EINVAL;
1472 		}
1473 	}
1474 
1475 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1476 		return -EINVAL;
1477 	}
1478 
1479 	if (param->id != adv->id) {
1480 		atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID);
1481 	}
1482 
1483 	return le_ext_adv_param_set(adv, param, false);
1484 }
1485 
bt_le_ext_adv_start(struct bt_le_ext_adv * adv,const struct bt_le_ext_adv_start_param * param)1486 int bt_le_ext_adv_start(struct bt_le_ext_adv *adv,
1487 			const struct bt_le_ext_adv_start_param *param)
1488 {
1489 	struct bt_conn *conn = NULL;
1490 	int err;
1491 
1492 	CHECKIF(adv == NULL) {
1493 		LOG_DBG("adv is NULL");
1494 
1495 		return -EINVAL;
1496 	}
1497 
1498 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1499 		return -EALREADY;
1500 	}
1501 
1502 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
1503 	    atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) {
1504 		err = le_adv_start_add_conn(adv, &conn);
1505 		if (err) {
1506 			return err;
1507 		}
1508 	}
1509 
1510 	atomic_set_bit_to(adv->flags, BT_ADV_LIMITED, param &&
1511 			  (param->timeout > 0 || param->num_events > 0));
1512 
1513 	if (atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) {
1514 		if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1515 		    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
1516 		    (!atomic_test_and_clear_bit(adv->flags, BT_ADV_RANDOM_ADDR_UPDATED) ||
1517 		     atomic_test_bit(adv->flags, BT_PER_ADV_ENABLED) ||
1518 		     !atomic_test_bit(adv->flags, BT_ADV_RPA_VALID))) {
1519 			bt_id_set_adv_private_addr(adv);
1520 		}
1521 	} else {
1522 		if (!atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
1523 		    (!atomic_test_and_clear_bit(adv->flags, BT_ADV_RANDOM_ADDR_UPDATED) ||
1524 		     atomic_test_bit(adv->flags, BT_PER_ADV_ENABLED) ||
1525 		     (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1526 		      !atomic_test_bit(adv->flags, BT_ADV_RPA_VALID)))) {
1527 			bt_id_set_adv_private_addr(adv);
1528 		}
1529 	}
1530 
1531 	err = bt_le_adv_set_enable_ext(adv, true, param);
1532 	if (err) {
1533 		LOG_ERR("Failed to start advertiser");
1534 		if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) {
1535 			bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
1536 			bt_conn_unref(conn);
1537 		}
1538 
1539 		return err;
1540 	}
1541 
1542 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn) {
1543 		/* If undirected connectable advertiser we have created a
1544 		 * connection object that we don't yet give to the application.
1545 		 * Since we don't give the application a reference to manage in
1546 		 * this case, we need to release this reference here
1547 		 */
1548 		bt_conn_unref(conn);
1549 	}
1550 
1551 	return 0;
1552 }
1553 
bt_le_ext_adv_stop(struct bt_le_ext_adv * adv)1554 int bt_le_ext_adv_stop(struct bt_le_ext_adv *adv)
1555 {
1556 	CHECKIF(adv == NULL) {
1557 		LOG_DBG("adv is NULL");
1558 
1559 		return -EINVAL;
1560 	}
1561 
1562 	(void)bt_le_lim_adv_cancel_timeout(adv);
1563 
1564 	if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1565 		return 0;
1566 	}
1567 
1568 	if (atomic_test_and_clear_bit(adv->flags, BT_ADV_LIMITED)) {
1569 		bt_id_adv_limited_stopped(adv);
1570 
1571 #if defined(CONFIG_BT_SMP)
1572 		bt_id_pending_keys_update();
1573 #endif
1574 	}
1575 
1576 	if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
1577 	    atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) {
1578 		le_adv_stop_free_conn(adv, 0);
1579 	}
1580 
1581 	return bt_le_adv_set_enable_ext(adv, false, NULL);
1582 }
1583 
bt_le_ext_adv_set_data(struct bt_le_ext_adv * adv,const struct bt_data * ad,size_t ad_len,const struct bt_data * sd,size_t sd_len)1584 int bt_le_ext_adv_set_data(struct bt_le_ext_adv *adv,
1585 			   const struct bt_data *ad, size_t ad_len,
1586 			   const struct bt_data *sd, size_t sd_len)
1587 {
1588 	bool ext_adv, scannable;
1589 
1590 	CHECKIF(adv == NULL) {
1591 		LOG_DBG("adv is NULL");
1592 
1593 		return -EINVAL;
1594 	}
1595 
1596 	ext_adv = atomic_test_bit(adv->flags, BT_ADV_EXT_ADV);
1597 	scannable = atomic_test_bit(adv->flags, BT_ADV_SCANNABLE);
1598 
1599 	if (ext_adv) {
1600 		if ((scannable && ad_len) ||
1601 		    (!scannable && sd_len)) {
1602 			return -ENOTSUP;
1603 		}
1604 	}
1605 
1606 	return le_adv_update(adv, ad, ad_len, sd, sd_len, ext_adv, scannable);
1607 }
1608 
bt_le_ext_adv_delete(struct bt_le_ext_adv * adv)1609 int bt_le_ext_adv_delete(struct bt_le_ext_adv *adv)
1610 {
1611 	struct bt_hci_cp_le_remove_adv_set *cp;
1612 	struct net_buf *buf;
1613 	int err;
1614 
1615 	if (!BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
1616 		return -ENOTSUP;
1617 	}
1618 
1619 	CHECKIF(adv == NULL) {
1620 		LOG_DBG("adv is NULL");
1621 
1622 		return -EINVAL;
1623 	}
1624 
1625 	/* Advertising set should be stopped first */
1626 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
1627 		return -EINVAL;
1628 	}
1629 
1630 	buf = bt_hci_cmd_alloc(K_FOREVER);
1631 	if (!buf) {
1632 		LOG_WRN("No HCI buffers");
1633 		return -ENOBUFS;
1634 	}
1635 
1636 	cp = net_buf_add(buf, sizeof(*cp));
1637 	cp->handle = adv->handle;
1638 
1639 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REMOVE_ADV_SET, buf, NULL);
1640 	if (err) {
1641 		return err;
1642 	}
1643 
1644 	adv_delete(adv);
1645 
1646 	return 0;
1647 }
1648 #endif /* defined(CONFIG_BT_EXT_ADV) */
1649 
1650 
adv_timeout(struct k_work * work)1651 static void adv_timeout(struct k_work *work)
1652 {
1653 	int err = 0;
1654 	struct k_work_delayable *dwork;
1655 	struct bt_le_ext_adv *adv;
1656 
1657 	dwork = k_work_delayable_from_work(work);
1658 	adv = CONTAINER_OF(dwork, struct bt_le_ext_adv, lim_adv_timeout_work);
1659 
1660 #if defined(CONFIG_BT_EXT_ADV)
1661 	if (adv == bt_dev.adv) {
1662 		err = bt_le_adv_stop();
1663 	} else {
1664 		err = bt_le_ext_adv_stop(adv);
1665 	}
1666 #else
1667 	err = bt_le_adv_stop();
1668 #endif
1669 	if (err) {
1670 		LOG_WRN("Failed to stop advertising: %d", err);
1671 	}
1672 }
1673 
1674 #if defined(CONFIG_BT_PER_ADV)
bt_le_per_adv_set_param(struct bt_le_ext_adv * adv,const struct bt_le_per_adv_param * param)1675 int bt_le_per_adv_set_param(struct bt_le_ext_adv *adv,
1676 			    const struct bt_le_per_adv_param *param)
1677 {
1678 #if defined(CONFIG_BT_PER_ADV_RSP)
1679 	/* The v2 struct can be used even if we end up sending a v1 command
1680 	 * because they have the same layout for the common fields.
1681 	 * V2 simply adds fields at the end of the v1 command.
1682 	 */
1683 	struct bt_hci_cp_le_set_per_adv_param_v2 *cp;
1684 #else
1685 	struct bt_hci_cp_le_set_per_adv_param *cp;
1686 #endif /* CONFIG_BT_PER_ADV_RSP */
1687 
1688 	uint16_t opcode;
1689 	uint16_t size;
1690 	struct net_buf *buf;
1691 	int err;
1692 	uint16_t props = 0;
1693 
1694 	if (IS_ENABLED(CONFIG_BT_PER_ADV_RSP) && BT_FEAT_LE_PAWR_ADVERTISER(bt_dev.le.features)) {
1695 		opcode = BT_HCI_OP_LE_SET_PER_ADV_PARAM_V2;
1696 		size = sizeof(struct bt_hci_cp_le_set_per_adv_param_v2);
1697 	} else if (BT_FEAT_LE_EXT_PER_ADV(bt_dev.le.features)) {
1698 		opcode = BT_HCI_OP_LE_SET_PER_ADV_PARAM;
1699 		size = sizeof(struct bt_hci_cp_le_set_per_adv_param);
1700 	} else {
1701 		return -ENOTSUP;
1702 	}
1703 
1704 	CHECKIF(adv == NULL) {
1705 		LOG_DBG("adv is NULL");
1706 
1707 		return -EINVAL;
1708 	}
1709 
1710 	if (atomic_test_bit(adv->flags, BT_ADV_SCANNABLE)) {
1711 		return -EINVAL;
1712 	} else if (atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) {
1713 		return -EINVAL;
1714 	} else if (!atomic_test_bit(adv->flags, BT_ADV_EXT_ADV)) {
1715 		return -EINVAL;
1716 	}
1717 
1718 	if (param->interval_min < BT_GAP_PER_ADV_MIN_INTERVAL ||
1719 	    param->interval_max > BT_GAP_PER_ADV_MAX_INTERVAL ||
1720 	    param->interval_min > param->interval_max) {
1721 		return -EINVAL;
1722 	}
1723 
1724 	if (!BT_FEAT_LE_PER_ADV_ADI_SUPP(bt_dev.le.features) &&
1725 	    (param->options & BT_LE_PER_ADV_OPT_INCLUDE_ADI)) {
1726 		return -ENOTSUP;
1727 	}
1728 
1729 	buf = bt_hci_cmd_alloc(K_FOREVER);
1730 	if (!buf) {
1731 		return -ENOBUFS;
1732 	}
1733 
1734 	cp = net_buf_add(buf, size);
1735 	(void)memset(cp, 0, size);
1736 
1737 	cp->handle = adv->handle;
1738 	cp->min_interval = sys_cpu_to_le16(param->interval_min);
1739 	cp->max_interval = sys_cpu_to_le16(param->interval_max);
1740 
1741 	if (param->options & BT_LE_PER_ADV_OPT_USE_TX_POWER) {
1742 		props |= BT_HCI_LE_ADV_PROP_TX_POWER;
1743 	}
1744 
1745 	cp->props = sys_cpu_to_le16(props);
1746 
1747 #if defined(CONFIG_BT_PER_ADV_RSP)
1748 	if (opcode == BT_HCI_OP_LE_SET_PER_ADV_PARAM_V2) {
1749 		cp->num_subevents = param->num_subevents;
1750 		cp->subevent_interval = param->subevent_interval;
1751 		cp->response_slot_delay = param->response_slot_delay;
1752 		cp->response_slot_spacing = param->response_slot_spacing;
1753 		cp->num_response_slots = param->num_response_slots;
1754 	}
1755 #endif /* CONFIG_BT_PER_ADV_RSP */
1756 
1757 	err = bt_hci_cmd_send_sync(opcode, buf, NULL);
1758 	if (err) {
1759 		return err;
1760 	}
1761 
1762 	if (param->options & BT_LE_PER_ADV_OPT_INCLUDE_ADI) {
1763 		atomic_set_bit(adv->flags, BT_PER_ADV_INCLUDE_ADI);
1764 	} else {
1765 		atomic_clear_bit(adv->flags, BT_PER_ADV_INCLUDE_ADI);
1766 	}
1767 
1768 	atomic_set_bit(adv->flags, BT_PER_ADV_PARAMS_SET);
1769 
1770 	return 0;
1771 }
1772 
bt_le_per_adv_set_data(const struct bt_le_ext_adv * adv,const struct bt_data * ad,size_t ad_len)1773 int bt_le_per_adv_set_data(const struct bt_le_ext_adv *adv,
1774 			   const struct bt_data *ad, size_t ad_len)
1775 {
1776 	size_t total_len_bytes = 0;
1777 
1778 	if (!BT_FEAT_LE_EXT_PER_ADV(bt_dev.le.features)) {
1779 		return -ENOTSUP;
1780 	}
1781 
1782 	CHECKIF(adv == NULL) {
1783 		LOG_DBG("adv is NULL");
1784 
1785 		return -EINVAL;
1786 	}
1787 
1788 	if (!atomic_test_bit(adv->flags, BT_PER_ADV_PARAMS_SET)) {
1789 		return -EINVAL;
1790 	}
1791 
1792 	if (ad_len != 0 && ad == NULL) {
1793 		return -EINVAL;
1794 	}
1795 
1796 	for (size_t i = 0; i < ad_len; i++) {
1797 		total_len_bytes += ad[i].data_len + 2;
1798 	}
1799 
1800 	if ((total_len_bytes > BT_HCI_LE_PER_ADV_FRAG_MAX_LEN) &&
1801 	    atomic_test_bit(adv->flags, BT_PER_ADV_ENABLED)) {
1802 		/* It is not allowed to set periodic advertising data
1803 		 * in multiple operations while it is running.
1804 		 */
1805 		return -EINVAL;
1806 	}
1807 
1808 	return hci_set_per_adv_data(adv, ad, ad_len);
1809 }
1810 
bt_le_per_adv_set_subevent_data(const struct bt_le_ext_adv * adv,uint8_t num_subevents,const struct bt_le_per_adv_subevent_data_params * params)1811 int bt_le_per_adv_set_subevent_data(const struct bt_le_ext_adv *adv, uint8_t num_subevents,
1812 				    const struct bt_le_per_adv_subevent_data_params *params)
1813 {
1814 	struct bt_hci_cp_le_set_pawr_subevent_data *cp;
1815 	struct bt_hci_cp_le_set_pawr_subevent_data_element *element;
1816 	struct net_buf *buf;
1817 	size_t cmd_length = sizeof(*cp);
1818 
1819 	if (!BT_FEAT_LE_PAWR_ADVERTISER(bt_dev.le.features)) {
1820 		return -ENOTSUP;
1821 	}
1822 
1823 	CHECKIF(adv == NULL) {
1824 		LOG_DBG("adv is NULL");
1825 
1826 		return -EINVAL;
1827 	}
1828 
1829 	for (size_t i = 0; i < num_subevents; i++) {
1830 		cmd_length += sizeof(struct bt_hci_cp_le_set_pawr_subevent_data_element);
1831 		cmd_length += params[i].data->len;
1832 	}
1833 
1834 	if (cmd_length > 0xFF) {
1835 		return -EINVAL;
1836 	}
1837 
1838 	buf = bt_hci_cmd_alloc(K_FOREVER);
1839 	if (!buf) {
1840 		return -ENOBUFS;
1841 	}
1842 
1843 	cp = net_buf_add(buf, sizeof(*cp));
1844 	cp->adv_handle = adv->handle;
1845 	cp->num_subevents = num_subevents;
1846 
1847 	for (size_t i = 0; i < num_subevents; i++) {
1848 		element = net_buf_add(buf, sizeof(*element));
1849 		element->subevent = params[i].subevent;
1850 		element->response_slot_start = params[i].response_slot_start;
1851 		element->response_slot_count = params[i].response_slot_count;
1852 		element->subevent_data_length = params[i].data->len;
1853 		net_buf_add_mem(buf, params[i].data->data, params[i].data->len);
1854 	}
1855 
1856 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PER_ADV_SUBEVENT_DATA, buf, NULL);
1857 }
1858 
bt_le_per_adv_enable(struct bt_le_ext_adv * adv,bool enable)1859 static int bt_le_per_adv_enable(struct bt_le_ext_adv *adv, bool enable)
1860 {
1861 	struct bt_hci_cp_le_set_per_adv_enable *cp;
1862 	struct net_buf *buf;
1863 	struct bt_hci_cmd_state_set state;
1864 	int err;
1865 
1866 	if (!BT_FEAT_LE_EXT_PER_ADV(bt_dev.le.features)) {
1867 		return -ENOTSUP;
1868 	}
1869 
1870 	CHECKIF(adv == NULL) {
1871 		LOG_DBG("adv is NULL");
1872 
1873 		return -EINVAL;
1874 	}
1875 
1876 	/* TODO: We could setup some default ext adv params if not already set*/
1877 	if (!atomic_test_bit(adv->flags, BT_PER_ADV_PARAMS_SET)) {
1878 		return -EINVAL;
1879 	}
1880 
1881 	if (atomic_test_bit(adv->flags, BT_PER_ADV_ENABLED) == enable) {
1882 		return -EALREADY;
1883 	}
1884 
1885 	buf = bt_hci_cmd_alloc(K_FOREVER);
1886 	if (!buf) {
1887 		return -ENOBUFS;
1888 	}
1889 
1890 	cp = net_buf_add(buf, sizeof(*cp));
1891 	(void)memset(cp, 0, sizeof(*cp));
1892 
1893 	cp->handle = adv->handle;
1894 
1895 	if (enable) {
1896 		cp->enable = BT_HCI_LE_SET_PER_ADV_ENABLE_ENABLE;
1897 
1898 		if (atomic_test_bit(adv->flags, BT_PER_ADV_INCLUDE_ADI)) {
1899 			cp->enable |= BT_HCI_LE_SET_PER_ADV_ENABLE_ADI;
1900 		}
1901 	} else {
1902 		cp->enable = 0U;
1903 	}
1904 
1905 	bt_hci_cmd_state_set_init(buf, &state, adv->flags,
1906 				  BT_PER_ADV_ENABLED, enable);
1907 
1908 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PER_ADV_ENABLE, buf, NULL);
1909 	if (err) {
1910 		return err;
1911 	}
1912 
1913 	return 0;
1914 }
1915 
bt_le_per_adv_start(struct bt_le_ext_adv * adv)1916 int bt_le_per_adv_start(struct bt_le_ext_adv *adv)
1917 {
1918 	return bt_le_per_adv_enable(adv, true);
1919 }
1920 
bt_le_per_adv_stop(struct bt_le_ext_adv * adv)1921 int bt_le_per_adv_stop(struct bt_le_ext_adv *adv)
1922 {
1923 	return bt_le_per_adv_enable(adv, false);
1924 }
1925 
1926 #if defined(CONFIG_BT_PER_ADV_RSP)
bt_hci_le_per_adv_subevent_data_request(struct net_buf * buf)1927 void bt_hci_le_per_adv_subevent_data_request(struct net_buf *buf)
1928 {
1929 	struct bt_hci_evt_le_per_adv_subevent_data_request *evt;
1930 	struct bt_le_per_adv_data_request request;
1931 	struct bt_le_ext_adv *adv;
1932 
1933 	if (buf->len < sizeof(struct bt_hci_evt_le_per_adv_subevent_data_request)) {
1934 		LOG_ERR("Invalid data request");
1935 
1936 		return;
1937 	}
1938 
1939 	evt = net_buf_pull_mem(buf, sizeof(struct bt_hci_evt_le_per_adv_subevent_data_request));
1940 	adv = bt_hci_adv_lookup_handle(evt->adv_handle);
1941 	if (!adv) {
1942 		LOG_ERR("Unknown advertising handle %d", evt->adv_handle);
1943 
1944 		return;
1945 	}
1946 
1947 	request.start = evt->subevent_start;
1948 	request.count = evt->subevent_data_count;
1949 
1950 	if (adv->cb && adv->cb->pawr_data_request) {
1951 		adv->cb->pawr_data_request(adv, &request);
1952 	}
1953 }
1954 
bt_hci_le_per_adv_response_report(struct net_buf * buf)1955 void bt_hci_le_per_adv_response_report(struct net_buf *buf)
1956 {
1957 	struct bt_hci_evt_le_per_adv_response_report *evt;
1958 	struct bt_hci_evt_le_per_adv_response *response;
1959 	struct bt_le_ext_adv *adv;
1960 	struct bt_le_per_adv_response_info info;
1961 	struct net_buf_simple data;
1962 
1963 	if (buf->len < sizeof(struct bt_hci_evt_le_per_adv_response_report)) {
1964 		LOG_ERR("Invalid response report");
1965 
1966 		return;
1967 	}
1968 
1969 	evt = net_buf_pull_mem(buf, sizeof(struct bt_hci_evt_le_per_adv_response_report));
1970 	adv = bt_hci_adv_lookup_handle(evt->adv_handle);
1971 	if (!adv) {
1972 		LOG_ERR("Unknown advertising handle %d", evt->adv_handle);
1973 
1974 		return;
1975 	}
1976 
1977 	info.subevent = evt->subevent;
1978 	info.tx_status = evt->tx_status;
1979 
1980 	for (uint8_t i = 0; i < evt->num_responses; i++) {
1981 		if (buf->len < sizeof(struct bt_hci_evt_le_per_adv_response)) {
1982 			LOG_ERR("Invalid response report");
1983 
1984 			return;
1985 		}
1986 
1987 		response = net_buf_pull_mem(buf, sizeof(struct bt_hci_evt_le_per_adv_response));
1988 		info.tx_power = response->tx_power;
1989 		info.rssi = response->rssi;
1990 		info.cte_type = bt_get_df_cte_type(response->cte_type);
1991 		info.response_slot = response->response_slot;
1992 
1993 		if (buf->len < response->data_length) {
1994 			LOG_ERR("Invalid response report");
1995 
1996 			return;
1997 		}
1998 
1999 		if (response->data_status == BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_PARTIAL) {
2000 			LOG_WRN("Incomplete response report received, discarding");
2001 			(void)net_buf_pull_mem(buf, response->data_length);
2002 		} else if (response->data_status == BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_RX_FAILED) {
2003 			(void)net_buf_pull_mem(buf, response->data_length);
2004 
2005 			if (adv->cb && adv->cb->pawr_response) {
2006 				adv->cb->pawr_response(adv, &info, NULL);
2007 			}
2008 		} else if (response->data_status == BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_COMPLETE) {
2009 			net_buf_simple_init_with_data(&data,
2010 						      net_buf_pull_mem(buf, response->data_length),
2011 						      response->data_length);
2012 
2013 			if (adv->cb && adv->cb->pawr_response) {
2014 				adv->cb->pawr_response(adv, &info, &data);
2015 			}
2016 		} else {
2017 			LOG_ERR("Invalid data status %d", response->data_status);
2018 			(void)net_buf_pull_mem(buf, response->data_length);
2019 		}
2020 	}
2021 }
2022 #endif /* CONFIG_BT_PER_ADV_RSP */
2023 
2024 #if defined(CONFIG_BT_PER_ADV_SYNC_TRANSFER_SENDER)
bt_le_per_adv_set_info_transfer(const struct bt_le_ext_adv * adv,const struct bt_conn * conn,uint16_t service_data)2025 int bt_le_per_adv_set_info_transfer(const struct bt_le_ext_adv *adv,
2026 				    const struct bt_conn *conn,
2027 				    uint16_t service_data)
2028 {
2029 	struct bt_hci_cp_le_per_adv_set_info_transfer *cp;
2030 	struct net_buf *buf;
2031 
2032 
2033 	if (!BT_FEAT_LE_EXT_PER_ADV(bt_dev.le.features)) {
2034 		return -ENOTSUP;
2035 	} else if (!BT_FEAT_LE_PAST_SEND(bt_dev.le.features)) {
2036 		return -ENOTSUP;
2037 	}
2038 
2039 	buf = bt_hci_cmd_alloc(K_FOREVER);
2040 	if (!buf) {
2041 		return -ENOBUFS;
2042 	}
2043 
2044 	cp = net_buf_add(buf, sizeof(*cp));
2045 	(void)memset(cp, 0, sizeof(*cp));
2046 
2047 	cp->conn_handle = sys_cpu_to_le16(conn->handle);
2048 	cp->adv_handle = adv->handle;
2049 	cp->service_data = sys_cpu_to_le16(service_data);
2050 
2051 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_PER_ADV_SET_INFO_TRANSFER, buf,
2052 				    NULL);
2053 }
2054 #endif /* CONFIG_BT_PER_ADV_SYNC_TRANSFER_SENDER */
2055 #endif /* CONFIG_BT_PER_ADV */
2056 
2057 #if defined(CONFIG_BT_EXT_ADV)
2058 #if defined(CONFIG_BT_BROADCASTER)
bt_hci_le_adv_set_terminated(struct net_buf * buf)2059 void bt_hci_le_adv_set_terminated(struct net_buf *buf)
2060 {
2061 	struct bt_hci_evt_le_adv_set_terminated *evt;
2062 	struct bt_le_ext_adv *adv;
2063 	uint16_t conn_handle;
2064 #if defined(CONFIG_BT_CONN) && (CONFIG_BT_EXT_ADV_MAX_ADV_SET > 1)
2065 	bool was_adv_enabled;
2066 #endif
2067 
2068 	evt = (void *)buf->data;
2069 	adv = bt_hci_adv_lookup_handle(evt->adv_handle);
2070 	conn_handle = sys_le16_to_cpu(evt->conn_handle);
2071 
2072 	LOG_DBG("status 0x%02x %s adv_handle %u conn_handle 0x%02x num %u",
2073 		evt->status, bt_hci_err_to_str(evt->status),
2074 		evt->adv_handle, conn_handle, evt->num_completed_ext_adv_evts);
2075 
2076 	if (!adv) {
2077 		LOG_ERR("No valid adv");
2078 		return;
2079 	}
2080 
2081 	(void)bt_le_lim_adv_cancel_timeout(adv);
2082 
2083 #if defined(CONFIG_BT_CONN) && (CONFIG_BT_EXT_ADV_MAX_ADV_SET > 1)
2084 	was_adv_enabled = atomic_test_bit(adv->flags, BT_ADV_ENABLED);
2085 #endif
2086 
2087 	atomic_clear_bit(adv->flags, BT_ADV_ENABLED);
2088 
2089 #if defined(CONFIG_BT_CONN) && (CONFIG_BT_EXT_ADV_MAX_ADV_SET > 1)
2090 	bt_dev.adv_conn_id = adv->id;
2091 	for (int i = 0; i < ARRAY_SIZE(bt_dev.cached_conn_complete); i++) {
2092 		if (bt_dev.cached_conn_complete[i].valid &&
2093 		    bt_dev.cached_conn_complete[i].evt.handle == evt->conn_handle) {
2094 			if (was_adv_enabled) {
2095 				/* Process the cached connection complete event
2096 				 * now that the corresponding advertising set is known.
2097 				 *
2098 				 * If the advertiser has been stopped before the connection
2099 				 * complete event has been raised to the application, we
2100 				 * discard the event.
2101 				 */
2102 				bt_hci_le_enh_conn_complete(&bt_dev.cached_conn_complete[i].evt);
2103 			}
2104 			bt_dev.cached_conn_complete[i].valid = false;
2105 		}
2106 	}
2107 #endif
2108 
2109 	if (evt->status && IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
2110 	    atomic_test_bit(adv->flags, BT_ADV_CONNECTABLE)) {
2111 		/* This will call connected callback for high duty cycle
2112 		 * directed advertiser timeout.
2113 		 */
2114 		le_adv_stop_free_conn(adv, evt->status);
2115 	}
2116 
2117 	if (IS_ENABLED(CONFIG_BT_CONN) && !evt->status) {
2118 		struct bt_conn *conn = bt_conn_lookup_handle(conn_handle, BT_CONN_TYPE_LE);
2119 
2120 		if (conn) {
2121 			if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
2122 			    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
2123 				/* Set Responder address unless already set */
2124 				conn->le.resp_addr.type = BT_ADDR_LE_RANDOM;
2125 				if (bt_addr_eq(&conn->le.resp_addr.a, BT_ADDR_ANY)) {
2126 					bt_addr_copy(&conn->le.resp_addr.a,
2127 						     &adv->random_addr.a);
2128 				}
2129 			} else if (adv->options & BT_LE_ADV_OPT_USE_NRPA) {
2130 				bt_addr_le_copy(&conn->le.resp_addr,
2131 						&adv->random_addr);
2132 			} else {
2133 				bt_addr_le_copy(&conn->le.resp_addr,
2134 					&bt_dev.id_addr[conn->id]);
2135 			}
2136 
2137 			if (adv->cb && adv->cb->connected) {
2138 				struct bt_le_ext_adv_connected_info info = {
2139 					.conn = conn,
2140 				};
2141 
2142 				adv->cb->connected(adv, &info);
2143 			}
2144 
2145 			bt_conn_unref(conn);
2146 		}
2147 	}
2148 
2149 	if (atomic_test_and_clear_bit(adv->flags, BT_ADV_LIMITED)) {
2150 		bt_id_adv_limited_stopped(adv);
2151 
2152 #if defined(CONFIG_BT_SMP)
2153 		bt_id_pending_keys_update();
2154 #endif
2155 
2156 		if (adv->cb && adv->cb->sent) {
2157 			struct bt_le_ext_adv_sent_info info = {
2158 				.num_sent = evt->num_completed_ext_adv_evts,
2159 			};
2160 
2161 			adv->cb->sent(adv, &info);
2162 		}
2163 	}
2164 
2165 	if (adv == bt_dev.adv) {
2166 		bt_le_adv_delete_legacy();
2167 	}
2168 }
2169 
bt_hci_le_scan_req_received(struct net_buf * buf)2170 void bt_hci_le_scan_req_received(struct net_buf *buf)
2171 {
2172 	struct bt_hci_evt_le_scan_req_received *evt;
2173 	struct bt_le_ext_adv *adv;
2174 
2175 	evt = (void *)buf->data;
2176 	adv = bt_hci_adv_lookup_handle(evt->handle);
2177 
2178 	LOG_DBG("handle %u peer %s", evt->handle, bt_addr_le_str(&evt->addr));
2179 
2180 	if (!adv) {
2181 		LOG_ERR("No valid adv");
2182 		return;
2183 	}
2184 
2185 	if (adv->cb && adv->cb->scanned) {
2186 		struct bt_le_ext_adv_scanned_info info;
2187 		bt_addr_le_t id_addr;
2188 
2189 		if (bt_addr_le_is_resolved(&evt->addr)) {
2190 			bt_addr_le_copy_resolved(&id_addr, &evt->addr);
2191 		} else {
2192 			bt_addr_le_copy(&id_addr,
2193 					bt_lookup_id_addr(adv->id, &evt->addr));
2194 		}
2195 
2196 		info.addr = &id_addr;
2197 		adv->cb->scanned(adv, &info);
2198 	}
2199 }
2200 #endif /* defined(CONFIG_BT_BROADCASTER) */
2201 #endif /* defined(CONFIG_BT_EXT_ADV) */
2202