xref: /linux/net/bluetooth/hci_sync.c (revision a7d2c94ba2995b5fb766d5ec7086f5e6a2774745)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * BlueZ - Bluetooth protocol stack for Linux
4  *
5  * Copyright (C) 2021 Intel Corporation
6  * Copyright 2023 NXP
7  */
8 
9 #include <linux/property.h>
10 
11 #include <net/bluetooth/bluetooth.h>
12 #include <net/bluetooth/hci_core.h>
13 #include <net/bluetooth/mgmt.h>
14 
15 #include "hci_codec.h"
16 #include "hci_debugfs.h"
17 #include "smp.h"
18 #include "eir.h"
19 #include "msft.h"
20 #include "aosp.h"
21 #include "leds.h"
22 
23 static void hci_cmd_sync_complete(struct hci_dev *hdev, u8 result, u16 opcode,
24 				  struct sk_buff *skb)
25 {
26 	bt_dev_dbg(hdev, "result 0x%2.2x", result);
27 
28 	if (READ_ONCE(hdev->req_status) != HCI_REQ_PEND)
29 		return;
30 
31 	hdev->req_result = result;
32 	WRITE_ONCE(hdev->req_status, HCI_REQ_DONE);
33 
34 	/* Free the request command so it is not used as response, and drop
35 	 * the reference hci_cmd_sync_alloc() took on its sk, if set: the
36 	 * response skb doesn't carry it.
37 	 */
38 	hci_dev_lock(hdev);
39 	if (hdev->req_skb) {
40 		struct sock *sk = hci_skb_sk(hdev->req_skb);
41 
42 		if (sk)
43 			sock_put(sk);
44 	}
45 	kfree_skb(hdev->req_skb);
46 	hdev->req_skb = NULL;
47 	hci_dev_unlock(hdev);
48 
49 	if (skb)
50 		hdev->req_rsp = skb_get(skb);
51 
52 	wake_up_interruptible(&hdev->req_wait_q);
53 }
54 
55 struct sk_buff *hci_cmd_sync_alloc(struct hci_dev *hdev, u16 opcode, u32 plen,
56 				   const void *param, struct sock *sk)
57 {
58 	int len = HCI_COMMAND_HDR_SIZE + plen;
59 	struct hci_command_hdr *hdr;
60 	struct sk_buff *skb;
61 
62 	skb = bt_skb_alloc(len, GFP_ATOMIC);
63 	if (!skb)
64 		return NULL;
65 
66 	hdr = skb_put(skb, HCI_COMMAND_HDR_SIZE);
67 	hdr->opcode = cpu_to_le16(opcode);
68 	hdr->plen   = plen;
69 
70 	if (plen)
71 		skb_put_data(skb, param, plen);
72 
73 	bt_dev_dbg(hdev, "skb len %d", skb->len);
74 
75 	hci_skb_pkt_type(skb) = HCI_COMMAND_PKT;
76 	hci_skb_opcode(skb) = opcode;
77 
78 	/* Grab a reference if command needs to be associated with a sock (e.g.
79 	 * likely mgmt socket that initiated the command).
80 	 */
81 	if (sk) {
82 		hci_skb_sk(skb) = sk;
83 		sock_hold(sk);
84 	}
85 
86 	return skb;
87 }
88 
89 static void hci_cmd_sync_add(struct hci_request *req, u16 opcode, u32 plen,
90 			     const void *param, u8 event, struct sock *sk)
91 {
92 	struct hci_dev *hdev = req->hdev;
93 	struct sk_buff *skb;
94 
95 	bt_dev_dbg(hdev, "opcode 0x%4.4x plen %d", opcode, plen);
96 
97 	/* If an error occurred during request building, there is no point in
98 	 * queueing the HCI command. We can simply return.
99 	 */
100 	if (req->err)
101 		return;
102 
103 	skb = hci_cmd_sync_alloc(hdev, opcode, plen, param, sk);
104 	if (!skb) {
105 		bt_dev_err(hdev, "no memory for command (opcode 0x%4.4x)",
106 			   opcode);
107 		req->err = -ENOMEM;
108 		return;
109 	}
110 
111 	if (skb_queue_empty(&req->cmd_q))
112 		bt_cb(skb)->hci.req_flags |= HCI_REQ_START;
113 
114 	hci_skb_event(skb) = event;
115 
116 	skb_queue_tail(&req->cmd_q, skb);
117 }
118 
119 static int hci_req_sync_run(struct hci_request *req)
120 {
121 	struct hci_dev *hdev = req->hdev;
122 	struct sk_buff *skb;
123 	unsigned long flags;
124 
125 	bt_dev_dbg(hdev, "length %u", skb_queue_len(&req->cmd_q));
126 
127 	/* If an error occurred during request building, remove all HCI
128 	 * commands queued on the HCI request queue.
129 	 */
130 	if (req->err) {
131 		skb_queue_purge(&req->cmd_q);
132 		return req->err;
133 	}
134 
135 	/* Do not allow empty requests */
136 	if (skb_queue_empty(&req->cmd_q))
137 		return -ENODATA;
138 
139 	skb = skb_peek_tail(&req->cmd_q);
140 	bt_cb(skb)->hci.req_complete_skb = hci_cmd_sync_complete;
141 	bt_cb(skb)->hci.req_flags |= HCI_REQ_SKB;
142 
143 	spin_lock_irqsave(&hdev->cmd_q.lock, flags);
144 	skb_queue_splice_tail(&req->cmd_q, &hdev->cmd_q);
145 	spin_unlock_irqrestore(&hdev->cmd_q.lock, flags);
146 
147 	queue_work(hdev->workqueue, &hdev->cmd_work);
148 
149 	return 0;
150 }
151 
152 static void hci_request_init(struct hci_request *req, struct hci_dev *hdev)
153 {
154 	skb_queue_head_init(&req->cmd_q);
155 	req->hdev = hdev;
156 	req->err = 0;
157 }
158 
159 /* This function requires the caller holds hdev->req_lock. */
160 struct sk_buff *__hci_cmd_sync_sk(struct hci_dev *hdev, u16 opcode, u32 plen,
161 				  const void *param, u8 event, u32 timeout,
162 				  struct sock *sk)
163 {
164 	struct hci_request req;
165 	struct sk_buff *skb;
166 	int err = 0;
167 
168 	bt_dev_dbg(hdev, "Opcode 0x%4.4x", opcode);
169 
170 	hci_request_init(&req, hdev);
171 
172 	hci_cmd_sync_add(&req, opcode, plen, param, event, sk);
173 
174 	WRITE_ONCE(hdev->req_status, HCI_REQ_PEND);
175 
176 	err = hci_req_sync_run(&req);
177 	if (err < 0)
178 		return ERR_PTR(err);
179 
180 	err = wait_event_interruptible_timeout(hdev->req_wait_q,
181 					       READ_ONCE(hdev->req_status) != HCI_REQ_PEND,
182 					       timeout);
183 
184 	if (err == -ERESTARTSYS)
185 		return ERR_PTR(-EINTR);
186 
187 	switch (READ_ONCE(hdev->req_status)) {
188 	case HCI_REQ_DONE:
189 		err = -bt_to_errno(hdev->req_result);
190 		break;
191 
192 	case HCI_REQ_CANCELED:
193 		err = -hdev->req_result;
194 		break;
195 
196 	default:
197 		err = -ETIMEDOUT;
198 		break;
199 	}
200 
201 	WRITE_ONCE(hdev->req_status, 0);
202 	hdev->req_result = 0;
203 	skb = hdev->req_rsp;
204 	hdev->req_rsp = NULL;
205 
206 	bt_dev_dbg(hdev, "end: err %d", err);
207 
208 	if (err < 0) {
209 		kfree_skb(skb);
210 		return ERR_PTR(err);
211 	}
212 
213 	/* If command return a status event skb will be set to NULL as there are
214 	 * no parameters.
215 	 */
216 	if (!skb)
217 		return ERR_PTR(-ENODATA);
218 
219 	return skb;
220 }
221 EXPORT_SYMBOL(__hci_cmd_sync_sk);
222 
223 /* This function requires the caller holds hdev->req_lock. */
224 struct sk_buff *__hci_cmd_sync(struct hci_dev *hdev, u16 opcode, u32 plen,
225 			       const void *param, u32 timeout)
226 {
227 	return __hci_cmd_sync_sk(hdev, opcode, plen, param, 0, timeout, NULL);
228 }
229 EXPORT_SYMBOL(__hci_cmd_sync);
230 
231 /* Send HCI command and wait for command complete event */
232 struct sk_buff *hci_cmd_sync(struct hci_dev *hdev, u16 opcode, u32 plen,
233 			     const void *param, u32 timeout)
234 {
235 	struct sk_buff *skb;
236 
237 	if (!test_bit(HCI_UP, &hdev->flags))
238 		return ERR_PTR(-ENETDOWN);
239 
240 	bt_dev_dbg(hdev, "opcode 0x%4.4x plen %d", opcode, plen);
241 
242 	hci_req_sync_lock(hdev);
243 	skb = __hci_cmd_sync(hdev, opcode, plen, param, timeout);
244 	hci_req_sync_unlock(hdev);
245 
246 	return skb;
247 }
248 EXPORT_SYMBOL(hci_cmd_sync);
249 
250 /* This function requires the caller holds hdev->req_lock. */
251 struct sk_buff *__hci_cmd_sync_ev(struct hci_dev *hdev, u16 opcode, u32 plen,
252 				  const void *param, u8 event, u32 timeout)
253 {
254 	return __hci_cmd_sync_sk(hdev, opcode, plen, param, event, timeout,
255 				 NULL);
256 }
257 EXPORT_SYMBOL(__hci_cmd_sync_ev);
258 
259 /* This function requires the caller holds hdev->req_lock. */
260 int __hci_cmd_sync_status_sk(struct hci_dev *hdev, u16 opcode, u32 plen,
261 			     const void *param, u8 event, u32 timeout,
262 			     struct sock *sk)
263 {
264 	struct sk_buff *skb;
265 	u8 status;
266 
267 	skb = __hci_cmd_sync_sk(hdev, opcode, plen, param, event, timeout, sk);
268 
269 	/* If command return a status event, skb will be set to -ENODATA */
270 	if (skb == ERR_PTR(-ENODATA))
271 		return 0;
272 
273 	if (IS_ERR(skb)) {
274 		if (!event)
275 			bt_dev_err(hdev, "Opcode 0x%4.4x failed: %ld", opcode,
276 				   PTR_ERR(skb));
277 		return PTR_ERR(skb);
278 	}
279 
280 	status = skb->data[0];
281 
282 	kfree_skb(skb);
283 
284 	return status;
285 }
286 EXPORT_SYMBOL(__hci_cmd_sync_status_sk);
287 
288 int __hci_cmd_sync_status(struct hci_dev *hdev, u16 opcode, u32 plen,
289 			  const void *param, u32 timeout)
290 {
291 	return __hci_cmd_sync_status_sk(hdev, opcode, plen, param, 0, timeout,
292 					NULL);
293 }
294 EXPORT_SYMBOL(__hci_cmd_sync_status);
295 
296 int hci_cmd_sync_status(struct hci_dev *hdev, u16 opcode, u32 plen,
297 			const void *param, u32 timeout)
298 {
299 	int err;
300 
301 	hci_req_sync_lock(hdev);
302 	err = __hci_cmd_sync_status(hdev, opcode, plen, param, timeout);
303 	hci_req_sync_unlock(hdev);
304 
305 	return err;
306 }
307 EXPORT_SYMBOL(hci_cmd_sync_status);
308 
309 static void hci_cmd_sync_work(struct work_struct *work)
310 {
311 	struct hci_dev *hdev = container_of(work, struct hci_dev, cmd_sync_work);
312 
313 	bt_dev_dbg(hdev, "");
314 
315 	/* Dequeue all entries and run them */
316 	while (1) {
317 		struct hci_cmd_sync_work_entry *entry;
318 
319 		/* Leave the backlog to hci_cmd_sync_clear() */
320 		if (hci_dev_test_flag(hdev, HCI_UNREGISTER))
321 			break;
322 
323 		mutex_lock(&hdev->cmd_sync_work_lock);
324 		entry = list_first_entry_or_null(&hdev->cmd_sync_work_list,
325 						 struct hci_cmd_sync_work_entry,
326 						 list);
327 		if (entry)
328 			list_del(&entry->list);
329 		mutex_unlock(&hdev->cmd_sync_work_lock);
330 
331 		if (!entry)
332 			break;
333 
334 		bt_dev_dbg(hdev, "entry %p", entry);
335 
336 		if (entry->func) {
337 			int err;
338 
339 			hci_req_sync_lock(hdev);
340 			err = entry->func(hdev, entry->data);
341 			if (entry->destroy)
342 				entry->destroy(hdev, entry->data, err);
343 			hci_req_sync_unlock(hdev);
344 		}
345 
346 		kfree(entry);
347 	}
348 }
349 
350 static void hci_cmd_sync_cancel_work(struct work_struct *work)
351 {
352 	struct hci_dev *hdev = container_of(work, struct hci_dev, cmd_sync_cancel_work);
353 
354 	cancel_delayed_work_sync(&hdev->cmd_timer);
355 	cancel_delayed_work_sync(&hdev->ncmd_timer);
356 	atomic_set(&hdev->cmd_cnt, 1);
357 
358 	wake_up_interruptible(&hdev->req_wait_q);
359 }
360 
361 static int hci_scan_disable_sync(struct hci_dev *hdev);
362 static int scan_disable_sync(struct hci_dev *hdev, void *data)
363 {
364 	return hci_scan_disable_sync(hdev);
365 }
366 
367 static int interleaved_inquiry_sync(struct hci_dev *hdev, void *data)
368 {
369 	return hci_inquiry_sync(hdev, DISCOV_INTERLEAVED_INQUIRY_LEN, 0);
370 }
371 
372 static void le_scan_disable(struct work_struct *work)
373 {
374 	struct hci_dev *hdev = container_of(work, struct hci_dev,
375 					    le_scan_disable.work);
376 	int status;
377 
378 	bt_dev_dbg(hdev, "");
379 	hci_dev_lock(hdev);
380 
381 	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
382 		/* The scan of a discovery can be disabled while this work
383 		 * waits for the lock, for example by a Stop Discovery that
384 		 * timed out and still completed, so end the discovery as
385 		 * le_set_scan_enable_complete() does when it cancels this
386 		 * work.
387 		 */
388 		if (hdev->discovery.state == DISCOVERY_FINDING)
389 			goto discov_stopped;
390 
391 		goto _return;
392 	}
393 
394 	status = hci_cmd_sync_queue(hdev, scan_disable_sync, NULL, NULL);
395 	if (status) {
396 		bt_dev_err(hdev, "failed to disable LE scan: %d", status);
397 		goto _return;
398 	}
399 
400 	/* If we were running LE only scan, change discovery state. If
401 	 * we were running both LE and BR/EDR inquiry simultaneously,
402 	 * and BR/EDR inquiry is already finished, stop discovery,
403 	 * otherwise BR/EDR inquiry will stop discovery when finished.
404 	 * If we will resolve remote device name, do not change
405 	 * discovery state.
406 	 */
407 
408 	if (hdev->discovery.type == DISCOV_TYPE_LE)
409 		goto discov_stopped;
410 
411 	if (hdev->discovery.type != DISCOV_TYPE_INTERLEAVED)
412 		goto _return;
413 
414 	if (hci_test_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY)) {
415 		if (!test_bit(HCI_INQUIRY, &hdev->flags) &&
416 		    hdev->discovery.state != DISCOVERY_RESOLVING)
417 			goto discov_stopped;
418 
419 		goto _return;
420 	}
421 
422 	status = hci_cmd_sync_queue(hdev, interleaved_inquiry_sync, NULL, NULL);
423 	if (status) {
424 		bt_dev_err(hdev, "inquiry failed: status %d", status);
425 		goto discov_stopped;
426 	}
427 
428 	goto _return;
429 
430 discov_stopped:
431 	hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
432 
433 _return:
434 	hci_dev_unlock(hdev);
435 }
436 
437 static int hci_le_set_scan_enable_sync(struct hci_dev *hdev, u8 val,
438 				       u8 filter_dup);
439 
440 static int reenable_adv_sync(struct hci_dev *hdev, void *data)
441 {
442 	bt_dev_dbg(hdev, "");
443 
444 	if (!hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
445 	    list_empty(&hdev->adv_instances))
446 		return 0;
447 
448 	if (hdev->cur_adv_instance) {
449 		return hci_schedule_adv_instance_sync(hdev,
450 						      hdev->cur_adv_instance,
451 						      true);
452 	} else {
453 		if (ext_adv_capable(hdev)) {
454 			hci_start_ext_adv_sync(hdev, 0x00);
455 		} else {
456 			hci_update_adv_data_sync(hdev, 0x00);
457 			hci_update_scan_rsp_data_sync(hdev, 0x00);
458 			hci_enable_advertising_sync(hdev);
459 		}
460 	}
461 
462 	return 0;
463 }
464 
465 static void reenable_adv(struct work_struct *work)
466 {
467 	struct hci_dev *hdev = container_of(work, struct hci_dev,
468 					    reenable_adv_work);
469 	int status;
470 
471 	bt_dev_dbg(hdev, "");
472 
473 	hci_dev_lock(hdev);
474 
475 	status = hci_cmd_sync_queue(hdev, reenable_adv_sync, NULL, NULL);
476 	if (status)
477 		bt_dev_err(hdev, "failed to reenable ADV: %d", status);
478 
479 	hci_dev_unlock(hdev);
480 }
481 
482 static void cancel_adv_timeout(struct hci_dev *hdev)
483 {
484 	if (hdev->adv_instance_timeout) {
485 		hdev->adv_instance_timeout = false;
486 		cancel_delayed_work(&hdev->adv_instance_expire);
487 	}
488 }
489 
490 /* For a single instance:
491  * - force == true: The instance will be removed even when its remaining
492  *   lifetime is not zero.
493  * - force == false: the instance will be deactivated but kept stored unless
494  *   the remaining lifetime is zero.
495  *
496  * For instance == 0x00:
497  * - force == true: All instances will be removed regardless of their timeout
498  *   setting.
499  * - force == false: Only instances that have a timeout will be removed.
500  */
501 int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk,
502 				u8 instance, bool force)
503 {
504 	struct adv_info *adv_instance, *n;
505 	u8 next_instance = 0;
506 	int err;
507 	u8 rem_inst;
508 
509 	/* Cancel any timeout concerning the removed instance(s). */
510 	if (!instance || hdev->cur_adv_instance == instance)
511 		cancel_adv_timeout(hdev);
512 
513 	/* This is safe as long as there is no command send while the
514 	 * lock is held.
515 	 */
516 	hci_dev_lock(hdev);
517 
518 	/* Get the next instance to advertise BEFORE we remove
519 	 * the current one. This can be the same instance again
520 	 * if there is only one instance.
521 	 */
522 	if (instance && hdev->cur_adv_instance == instance) {
523 		adv_instance = hci_get_next_instance(hdev, instance);
524 		if (adv_instance)
525 			next_instance = adv_instance->instance;
526 	}
527 
528 	if (instance == 0x00) {
529 		list_for_each_entry_safe(adv_instance, n, &hdev->adv_instances,
530 					 list) {
531 			if (!(force || adv_instance->timeout))
532 				continue;
533 
534 			rem_inst = adv_instance->instance;
535 			err = hci_remove_adv_instance(hdev, rem_inst);
536 			if (!err)
537 				mgmt_advertising_removed(sk, hdev, rem_inst);
538 		}
539 	} else {
540 		adv_instance = hci_find_adv_instance(hdev, instance);
541 
542 		if (force || (adv_instance && adv_instance->timeout &&
543 			      !adv_instance->remaining_time)) {
544 			/* Don't advertise a removed instance. */
545 			if (next_instance == instance)
546 				next_instance = 0;
547 
548 			err = hci_remove_adv_instance(hdev, instance);
549 			if (!err)
550 				mgmt_advertising_removed(sk, hdev, instance);
551 		}
552 	}
553 
554 	hci_dev_unlock(hdev);
555 
556 	if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING))
557 		return 0;
558 
559 	if (next_instance && !ext_adv_capable(hdev))
560 		return hci_schedule_adv_instance_sync(hdev, next_instance,
561 						      false);
562 
563 	return 0;
564 }
565 
566 static int adv_timeout_expire_sync(struct hci_dev *hdev, void *data)
567 {
568 	u8 instance = *(u8 *)data;
569 
570 	hci_clear_adv_instance_sync(hdev, NULL, instance, false);
571 
572 	if (list_empty(&hdev->adv_instances))
573 		return hci_disable_advertising_sync(hdev);
574 
575 	return 0;
576 }
577 
578 static void adv_timeout_expire_destroy(struct hci_dev *hdev, void *data,
579 				       int err)
580 {
581 	kfree(data);
582 }
583 
584 static void adv_timeout_expire(struct work_struct *work)
585 {
586 	u8 *inst_ptr;
587 	struct hci_dev *hdev = container_of(work, struct hci_dev,
588 					    adv_instance_expire.work);
589 
590 	bt_dev_dbg(hdev, "");
591 
592 	hci_dev_lock(hdev);
593 
594 	hdev->adv_instance_timeout = false;
595 
596 	if (hdev->cur_adv_instance == 0x00)
597 		goto unlock;
598 
599 	inst_ptr = kmalloc(1, GFP_KERNEL);
600 	if (!inst_ptr)
601 		goto unlock;
602 
603 	*inst_ptr = hdev->cur_adv_instance;
604 	if (hci_cmd_sync_queue(hdev, adv_timeout_expire_sync, inst_ptr,
605 			       adv_timeout_expire_destroy) < 0)
606 		kfree(inst_ptr);
607 
608 unlock:
609 	hci_dev_unlock(hdev);
610 }
611 
612 static bool is_interleave_scanning(struct hci_dev *hdev)
613 {
614 	return hdev->interleave_scan_state != INTERLEAVE_SCAN_NONE;
615 }
616 
617 static int hci_passive_scan_sync(struct hci_dev *hdev);
618 
619 static void interleave_scan_work(struct work_struct *work)
620 {
621 	struct hci_dev *hdev = container_of(work, struct hci_dev,
622 					    interleave_scan.work);
623 	unsigned long timeout;
624 
625 	if (hdev->interleave_scan_state == INTERLEAVE_SCAN_ALLOWLIST) {
626 		timeout = msecs_to_jiffies(hdev->advmon_allowlist_duration);
627 	} else if (hdev->interleave_scan_state == INTERLEAVE_SCAN_NO_FILTER) {
628 		timeout = msecs_to_jiffies(hdev->advmon_no_filter_duration);
629 	} else {
630 		bt_dev_err(hdev, "unexpected error");
631 		return;
632 	}
633 
634 	hci_passive_scan_sync(hdev);
635 
636 	hci_dev_lock(hdev);
637 
638 	switch (hdev->interleave_scan_state) {
639 	case INTERLEAVE_SCAN_ALLOWLIST:
640 		bt_dev_dbg(hdev, "next state: allowlist");
641 		hdev->interleave_scan_state = INTERLEAVE_SCAN_NO_FILTER;
642 		break;
643 	case INTERLEAVE_SCAN_NO_FILTER:
644 		bt_dev_dbg(hdev, "next state: no filter");
645 		hdev->interleave_scan_state = INTERLEAVE_SCAN_ALLOWLIST;
646 		break;
647 	case INTERLEAVE_SCAN_NONE:
648 		bt_dev_err(hdev, "unexpected error");
649 	}
650 
651 	hci_dev_unlock(hdev);
652 
653 	/* Don't continue interleaving if it was canceled */
654 	if (is_interleave_scanning(hdev))
655 		queue_delayed_work(hdev->req_workqueue,
656 				   &hdev->interleave_scan, timeout);
657 }
658 
659 void hci_cmd_sync_init(struct hci_dev *hdev)
660 {
661 	INIT_WORK(&hdev->cmd_sync_work, hci_cmd_sync_work);
662 	INIT_LIST_HEAD(&hdev->cmd_sync_work_list);
663 	mutex_init(&hdev->cmd_sync_work_lock);
664 	mutex_init(&hdev->unregister_lock);
665 
666 	INIT_WORK(&hdev->cmd_sync_cancel_work, hci_cmd_sync_cancel_work);
667 	INIT_WORK(&hdev->reenable_adv_work, reenable_adv);
668 	INIT_DELAYED_WORK(&hdev->le_scan_disable, le_scan_disable);
669 	INIT_DELAYED_WORK(&hdev->adv_instance_expire, adv_timeout_expire);
670 	INIT_DELAYED_WORK(&hdev->interleave_scan, interleave_scan_work);
671 }
672 
673 static void _hci_cmd_sync_cancel_entry(struct hci_dev *hdev,
674 				       struct hci_cmd_sync_work_entry *entry,
675 				       int err)
676 {
677 	if (entry->destroy)
678 		entry->destroy(hdev, entry->data, err);
679 
680 	list_del(&entry->list);
681 	kfree(entry);
682 }
683 
684 void hci_cmd_sync_clear(struct hci_dev *hdev)
685 {
686 	struct hci_cmd_sync_work_entry *entry, *tmp;
687 
688 	/* cmd_work is disabled, the pending request can only time out */
689 	hci_cmd_sync_cancel_sync(hdev, ENODEV);
690 	cancel_work_sync(&hdev->cmd_sync_work);
691 	cancel_work_sync(&hdev->reenable_adv_work);
692 
693 	mutex_lock(&hdev->cmd_sync_work_lock);
694 	list_for_each_entry_safe(entry, tmp, &hdev->cmd_sync_work_list, list)
695 		_hci_cmd_sync_cancel_entry(hdev, entry, -ECANCELED);
696 	mutex_unlock(&hdev->cmd_sync_work_lock);
697 }
698 
699 void hci_cmd_sync_cancel(struct hci_dev *hdev, int err)
700 {
701 	bt_dev_dbg(hdev, "err 0x%2.2x", err);
702 
703 	if (READ_ONCE(hdev->req_status) == HCI_REQ_PEND) {
704 		hdev->req_result = err;
705 		WRITE_ONCE(hdev->req_status, HCI_REQ_CANCELED);
706 
707 		queue_work(hdev->workqueue, &hdev->cmd_sync_cancel_work);
708 	}
709 }
710 EXPORT_SYMBOL(hci_cmd_sync_cancel);
711 
712 /* Cancel ongoing command request synchronously:
713  *
714  * - Set result and mark status to HCI_REQ_CANCELED
715  * - Wakeup command sync thread
716  */
717 void hci_cmd_sync_cancel_sync(struct hci_dev *hdev, int err)
718 {
719 	bt_dev_dbg(hdev, "err 0x%2.2x", err);
720 
721 	if (READ_ONCE(hdev->req_status) == HCI_REQ_PEND) {
722 		/* req_result is __u32 so error must be positive to be properly
723 		 * propagated.
724 		 */
725 		hdev->req_result = err < 0 ? -err : err;
726 		WRITE_ONCE(hdev->req_status, HCI_REQ_CANCELED);
727 
728 		wake_up_interruptible(&hdev->req_wait_q);
729 	}
730 }
731 EXPORT_SYMBOL(hci_cmd_sync_cancel_sync);
732 
733 /* Submit HCI command to be run in as cmd_sync_work:
734  *
735  * - hdev must _not_ be unregistered
736  */
737 int hci_cmd_sync_submit(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
738 			void *data, hci_cmd_sync_work_destroy_t destroy)
739 {
740 	struct hci_cmd_sync_work_entry *entry;
741 	int err = 0;
742 
743 	mutex_lock(&hdev->unregister_lock);
744 	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
745 		err = -ENODEV;
746 		goto unlock;
747 	}
748 
749 	entry = kmalloc_obj(*entry);
750 	if (!entry) {
751 		err = -ENOMEM;
752 		goto unlock;
753 	}
754 	entry->func = func;
755 	entry->data = data;
756 	entry->destroy = destroy;
757 
758 	mutex_lock(&hdev->cmd_sync_work_lock);
759 	list_add_tail(&entry->list, &hdev->cmd_sync_work_list);
760 	mutex_unlock(&hdev->cmd_sync_work_lock);
761 
762 	queue_work(hdev->req_workqueue, &hdev->cmd_sync_work);
763 
764 unlock:
765 	mutex_unlock(&hdev->unregister_lock);
766 	return err;
767 }
768 EXPORT_SYMBOL(hci_cmd_sync_submit);
769 
770 /* Queue HCI command:
771  *
772  * - hdev must be running
773  */
774 int hci_cmd_sync_queue(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
775 		       void *data, hci_cmd_sync_work_destroy_t destroy)
776 {
777 	/* Only queue command if hdev is running which means it had been opened
778 	 * and is either on init phase or is already up.
779 	 */
780 	if (!test_bit(HCI_RUNNING, &hdev->flags))
781 		return -ENETDOWN;
782 
783 	return hci_cmd_sync_submit(hdev, func, data, destroy);
784 }
785 EXPORT_SYMBOL(hci_cmd_sync_queue);
786 
787 static struct hci_cmd_sync_work_entry *
788 _hci_cmd_sync_lookup_entry(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
789 			   void *data, hci_cmd_sync_work_destroy_t destroy)
790 {
791 	struct hci_cmd_sync_work_entry *entry, *tmp;
792 
793 	list_for_each_entry_safe(entry, tmp, &hdev->cmd_sync_work_list, list) {
794 		if (func && entry->func != func)
795 			continue;
796 
797 		if (data && entry->data != data)
798 			continue;
799 
800 		if (destroy && entry->destroy != destroy)
801 			continue;
802 
803 		return entry;
804 	}
805 
806 	return NULL;
807 }
808 
809 /* Queue HCI command entry once:
810  *
811  * - Lookup if an entry already exist and only if it doesn't creates a new entry
812  *   and queue it.
813  */
814 int hci_cmd_sync_queue_once(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
815 			    void *data, hci_cmd_sync_work_destroy_t destroy)
816 {
817 	if (hci_cmd_sync_lookup_entry(hdev, func, data, destroy))
818 		return -EEXIST;
819 
820 	return hci_cmd_sync_queue(hdev, func, data, destroy);
821 }
822 EXPORT_SYMBOL(hci_cmd_sync_queue_once);
823 
824 /* Run HCI command:
825  *
826  * - hdev must be running
827  * - if on cmd_sync_work then run immediately otherwise queue
828  */
829 int hci_cmd_sync_run(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
830 		     void *data, hci_cmd_sync_work_destroy_t destroy)
831 {
832 	/* Only queue command if hdev is running which means it had been opened
833 	 * and is either on init phase or is already up.
834 	 */
835 	if (!test_bit(HCI_RUNNING, &hdev->flags))
836 		return -ENETDOWN;
837 
838 	/* If on cmd_sync_work then run immediately otherwise queue */
839 	if (current_work() == &hdev->cmd_sync_work) {
840 		int err;
841 
842 		err = func(hdev, data);
843 		if (destroy)
844 			destroy(hdev, data, err);
845 
846 		return 0;
847 	}
848 
849 	return hci_cmd_sync_submit(hdev, func, data, destroy);
850 }
851 EXPORT_SYMBOL(hci_cmd_sync_run);
852 
853 /* Run HCI command entry once:
854  *
855  * - Lookup if an entry already exist and only if it doesn't creates a new entry
856  *   and run it.
857  * - if on cmd_sync_work then run immediately otherwise queue
858  */
859 int hci_cmd_sync_run_once(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
860 			  void *data, hci_cmd_sync_work_destroy_t destroy)
861 {
862 	if (hci_cmd_sync_lookup_entry(hdev, func, data, destroy))
863 		return -EEXIST;
864 
865 	return hci_cmd_sync_run(hdev, func, data, destroy);
866 }
867 EXPORT_SYMBOL(hci_cmd_sync_run_once);
868 
869 /* Lookup HCI command entry:
870  *
871  * - Return first entry that matches by function callback or data or
872  *   destroy callback.
873  */
874 struct hci_cmd_sync_work_entry *
875 hci_cmd_sync_lookup_entry(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
876 			  void *data, hci_cmd_sync_work_destroy_t destroy)
877 {
878 	struct hci_cmd_sync_work_entry *entry;
879 
880 	mutex_lock(&hdev->cmd_sync_work_lock);
881 	entry = _hci_cmd_sync_lookup_entry(hdev, func, data, destroy);
882 	mutex_unlock(&hdev->cmd_sync_work_lock);
883 
884 	return entry;
885 }
886 EXPORT_SYMBOL(hci_cmd_sync_lookup_entry);
887 
888 /* Cancel HCI command entry */
889 void hci_cmd_sync_cancel_entry(struct hci_dev *hdev,
890 			       struct hci_cmd_sync_work_entry *entry)
891 {
892 	mutex_lock(&hdev->cmd_sync_work_lock);
893 	_hci_cmd_sync_cancel_entry(hdev, entry, -ECANCELED);
894 	mutex_unlock(&hdev->cmd_sync_work_lock);
895 }
896 EXPORT_SYMBOL(hci_cmd_sync_cancel_entry);
897 
898 /* Dequeue HCI command entry:
899  *
900  * - Lookup and cancel any entry that matches by function callback or data or
901  *   destroy callback.
902  */
903 bool hci_cmd_sync_dequeue(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
904 			  void *data, hci_cmd_sync_work_destroy_t destroy)
905 {
906 	struct hci_cmd_sync_work_entry *entry;
907 	bool ret = false;
908 
909 	mutex_lock(&hdev->cmd_sync_work_lock);
910 	while ((entry = _hci_cmd_sync_lookup_entry(hdev, func, data,
911 						   destroy))) {
912 		_hci_cmd_sync_cancel_entry(hdev, entry, -ECANCELED);
913 		ret = true;
914 	}
915 	mutex_unlock(&hdev->cmd_sync_work_lock);
916 
917 	return ret;
918 }
919 EXPORT_SYMBOL(hci_cmd_sync_dequeue);
920 
921 int hci_update_eir_sync(struct hci_dev *hdev)
922 {
923 	struct hci_cp_write_eir cp;
924 
925 	bt_dev_dbg(hdev, "");
926 
927 	if (!hdev_is_powered(hdev))
928 		return 0;
929 
930 	if (!lmp_ext_inq_capable(hdev))
931 		return 0;
932 
933 	if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
934 		return 0;
935 
936 	if (hci_dev_test_flag(hdev, HCI_SERVICE_CACHE))
937 		return 0;
938 
939 	memset(&cp, 0, sizeof(cp));
940 
941 	hci_dev_lock(hdev);
942 	eir_create(hdev, cp.data);
943 
944 	if (memcmp(cp.data, hdev->eir, sizeof(cp.data)) == 0) {
945 		hci_dev_unlock(hdev);
946 		return 0;
947 	}
948 
949 	memcpy(hdev->eir, cp.data, sizeof(cp.data));
950 	hci_dev_unlock(hdev);
951 
952 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_EIR, sizeof(cp), &cp,
953 				     HCI_CMD_TIMEOUT);
954 }
955 
956 static u8 get_service_classes(struct hci_dev *hdev)
957 {
958 	struct bt_uuid *uuid;
959 	u8 val = 0;
960 
961 	list_for_each_entry(uuid, &hdev->uuids, list)
962 		val |= uuid->svc_hint;
963 
964 	return val;
965 }
966 
967 int hci_update_class_sync(struct hci_dev *hdev)
968 {
969 	u8 cod[3];
970 
971 	bt_dev_dbg(hdev, "");
972 
973 	if (!hdev_is_powered(hdev))
974 		return 0;
975 
976 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
977 		return 0;
978 
979 	if (hci_dev_test_flag(hdev, HCI_SERVICE_CACHE))
980 		return 0;
981 
982 	hci_dev_lock(hdev);
983 	cod[0] = hdev->minor_class;
984 	cod[1] = hdev->major_class;
985 	cod[2] = get_service_classes(hdev);
986 
987 	if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE))
988 		cod[1] |= 0x20;
989 
990 	if (memcmp(cod, hdev->dev_class, 3) == 0) {
991 		hci_dev_unlock(hdev);
992 		return 0;
993 	}
994 
995 	hci_dev_unlock(hdev);
996 
997 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_CLASS_OF_DEV,
998 				     sizeof(cod), cod, HCI_CMD_TIMEOUT);
999 }
1000 
1001 static bool is_advertising_allowed(struct hci_dev *hdev, bool connectable)
1002 {
1003 	/* If there is no connection we are OK to advertise. */
1004 	if (hci_conn_num(hdev, LE_LINK) == 0)
1005 		return true;
1006 
1007 	/* Check le_states if there is any connection in peripheral role. */
1008 	if (hdev->conn_hash.le_num_peripheral > 0) {
1009 		/* Peripheral connection state and non connectable mode
1010 		 * bit 20.
1011 		 */
1012 		if (!connectable && !(hdev->le_states[2] & 0x10))
1013 			return false;
1014 
1015 		/* Peripheral connection state and connectable mode bit 38
1016 		 * and scannable bit 21.
1017 		 */
1018 		if (connectable && (!(hdev->le_states[4] & 0x40) ||
1019 				    !(hdev->le_states[2] & 0x20)))
1020 			return false;
1021 	}
1022 
1023 	/* Check le_states if there is any connection in central role. */
1024 	if (hci_conn_num(hdev, LE_LINK) != hdev->conn_hash.le_num_peripheral) {
1025 		/* Central connection state and non connectable mode bit 18. */
1026 		if (!connectable && !(hdev->le_states[2] & 0x02))
1027 			return false;
1028 
1029 		/* Central connection state and connectable mode bit 35 and
1030 		 * scannable 19.
1031 		 */
1032 		if (connectable && (!(hdev->le_states[4] & 0x08) ||
1033 				    !(hdev->le_states[2] & 0x08)))
1034 			return false;
1035 	}
1036 
1037 	return true;
1038 }
1039 
1040 static bool adv_use_rpa(struct hci_dev *hdev, uint32_t flags)
1041 {
1042 	/* If privacy is not enabled don't use RPA */
1043 	if (!hci_dev_test_flag(hdev, HCI_PRIVACY))
1044 		return false;
1045 
1046 	/* If basic privacy mode is enabled use RPA */
1047 	if (!hci_dev_test_flag(hdev, HCI_LIMITED_PRIVACY))
1048 		return true;
1049 
1050 	/* If limited privacy mode is enabled don't use RPA if we're
1051 	 * both discoverable and bondable.
1052 	 */
1053 	if ((flags & MGMT_ADV_FLAG_DISCOV) &&
1054 	    hci_dev_test_flag(hdev, HCI_BONDABLE))
1055 		return false;
1056 
1057 	/* We're neither bondable nor discoverable in the limited
1058 	 * privacy mode, therefore use RPA.
1059 	 */
1060 	return true;
1061 }
1062 
1063 static int hci_set_random_addr_sync(struct hci_dev *hdev, bdaddr_t *rpa)
1064 {
1065 	/* If a random_addr has been set we're advertising or initiating an LE
1066 	 * connection we can't go ahead and change the random address at this
1067 	 * time. This is because the eventual initiator address used for the
1068 	 * subsequently created connection will be undefined (some
1069 	 * controllers use the new address and others the one we had
1070 	 * when the operation started).
1071 	 *
1072 	 * In this kind of scenario skip the update and let the random
1073 	 * address be updated at the next cycle.
1074 	 */
1075 	rcu_read_lock();
1076 
1077 	if (bacmp(&hdev->random_addr, BDADDR_ANY) &&
1078 	    (hci_dev_test_flag(hdev, HCI_LE_ADV) ||
1079 	    hci_lookup_le_connect(hdev))) {
1080 		bt_dev_dbg(hdev, "Deferring random address update");
1081 		hci_dev_set_flag(hdev, HCI_RPA_EXPIRED);
1082 		rcu_read_unlock();
1083 		return 0;
1084 	}
1085 
1086 	rcu_read_unlock();
1087 
1088 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_RANDOM_ADDR,
1089 				     6, rpa, HCI_CMD_TIMEOUT);
1090 }
1091 
1092 int hci_update_random_address_sync(struct hci_dev *hdev, bool require_privacy,
1093 				   bool rpa, u8 *own_addr_type)
1094 {
1095 	int err;
1096 
1097 	/* If privacy is enabled use a resolvable private address. If
1098 	 * current RPA has expired or there is something else than
1099 	 * the current RPA in use, then generate a new one.
1100 	 */
1101 	if (rpa) {
1102 		/* If Controller supports LL Privacy use own address type is
1103 		 * 0x03
1104 		 */
1105 		if (ll_privacy_capable(hdev))
1106 			*own_addr_type = ADDR_LE_DEV_RANDOM_RESOLVED;
1107 		else
1108 			*own_addr_type = ADDR_LE_DEV_RANDOM;
1109 
1110 		/* Check if RPA is valid */
1111 		if (rpa_valid(hdev))
1112 			return 0;
1113 
1114 		err = smp_generate_rpa(hdev, hdev->irk, &hdev->rpa);
1115 		if (err < 0) {
1116 			bt_dev_err(hdev, "failed to generate new RPA");
1117 			return err;
1118 		}
1119 
1120 		err = hci_set_random_addr_sync(hdev, &hdev->rpa);
1121 		if (err)
1122 			return err;
1123 
1124 		return 0;
1125 	}
1126 
1127 	/* In case of required privacy without resolvable private address,
1128 	 * use an non-resolvable private address. This is useful for active
1129 	 * scanning and non-connectable advertising.
1130 	 */
1131 	if (require_privacy) {
1132 		bdaddr_t nrpa;
1133 
1134 		while (true) {
1135 			/* The non-resolvable private address is generated
1136 			 * from random six bytes with the two most significant
1137 			 * bits cleared.
1138 			 */
1139 			get_random_bytes(&nrpa, 6);
1140 			nrpa.b[5] &= 0x3f;
1141 
1142 			/* The non-resolvable private address shall not be
1143 			 * equal to the public address.
1144 			 */
1145 			if (bacmp(&hdev->bdaddr, &nrpa))
1146 				break;
1147 		}
1148 
1149 		*own_addr_type = ADDR_LE_DEV_RANDOM;
1150 
1151 		return hci_set_random_addr_sync(hdev, &nrpa);
1152 	}
1153 
1154 	/* If forcing static address is in use or there is no public
1155 	 * address use the static address as random address (but skip
1156 	 * the HCI command if the current random address is already the
1157 	 * static one.
1158 	 *
1159 	 * In case BR/EDR has been disabled on a dual-mode controller
1160 	 * and a static address has been configured, then use that
1161 	 * address instead of the public BR/EDR address.
1162 	 */
1163 	if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
1164 	    !bacmp(&hdev->bdaddr, BDADDR_ANY) ||
1165 	    (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) &&
1166 	     bacmp(&hdev->static_addr, BDADDR_ANY))) {
1167 		*own_addr_type = ADDR_LE_DEV_RANDOM;
1168 		if (bacmp(&hdev->static_addr, &hdev->random_addr))
1169 			return hci_set_random_addr_sync(hdev,
1170 							&hdev->static_addr);
1171 		return 0;
1172 	}
1173 
1174 	/* Neither privacy nor static address is being used so use a
1175 	 * public address.
1176 	 */
1177 	*own_addr_type = ADDR_LE_DEV_PUBLIC;
1178 
1179 	return 0;
1180 }
1181 
1182 /* Check if the advertising set with handle 0x00 is in use, either by instance
1183  * 0 or by an instance sharing its advertising set.
1184  */
1185 static bool hci_ext_adv_handle_0_enabled(struct hci_dev *hdev)
1186 {
1187 	struct adv_info *adv;
1188 	bool enabled;
1189 
1190 	hci_dev_lock(hdev);
1191 
1192 	enabled = hci_dev_test_flag(hdev, HCI_LE_ADV_0);
1193 
1194 	list_for_each_entry(adv, &hdev->adv_instances, list) {
1195 		if (!adv->handle && adv->enabled) {
1196 			enabled = true;
1197 			break;
1198 		}
1199 	}
1200 
1201 	hci_dev_unlock(hdev);
1202 
1203 	return enabled;
1204 }
1205 
1206 int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev)
1207 {
1208 	struct hci_cp_le_set_ext_adv_enable *cp;
1209 	struct hci_cp_ext_adv_set *set;
1210 	u8 data[sizeof(*cp) + sizeof(*set) * 1];
1211 	u8 size;
1212 
1213 	if (!hci_ext_adv_handle_0_enabled(hdev))
1214 		return 0;
1215 
1216 	memset(data, 0, sizeof(data));
1217 
1218 	cp = (void *)data;
1219 	set = (void *)cp->data;
1220 
1221 	cp->num_of_sets = 0x01;
1222 	cp->enable = 0x00;
1223 
1224 	set->handle = 0x00;
1225 
1226 	size = sizeof(*cp) + sizeof(*set) * cp->num_of_sets;
1227 
1228 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
1229 				     size, data, HCI_CMD_TIMEOUT);
1230 }
1231 
1232 static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
1233 {
1234 	struct hci_cp_le_set_ext_adv_enable *cp;
1235 	struct hci_cp_ext_adv_set *set;
1236 	u8 data[sizeof(*cp) + sizeof(*set) * 1];
1237 	u8 size;
1238 	u8 handle = instance;
1239 
1240 	/* If request specifies an instance that doesn't exist, fail */
1241 	if (instance > 0) {
1242 		struct adv_info *adv;
1243 		bool enabled = false;
1244 
1245 		hci_dev_lock(hdev);
1246 		adv = hci_find_adv_instance(hdev, instance);
1247 		if (adv) {
1248 			enabled = adv->enabled;
1249 			handle = adv->handle;
1250 		}
1251 		hci_dev_unlock(hdev);
1252 
1253 		if (!adv)
1254 			return -EINVAL;
1255 
1256 		/* If not enabled there is nothing to do */
1257 		if (!enabled)
1258 			return 0;
1259 	}
1260 
1261 	memset(data, 0, sizeof(data));
1262 
1263 	cp = (void *)data;
1264 	set = (void *)cp->data;
1265 
1266 	/* Instance 0x00 indicates all advertising instances will be disabled */
1267 	cp->num_of_sets = !!instance;
1268 	cp->enable = 0x00;
1269 
1270 	set->handle = handle;
1271 
1272 	size = sizeof(*cp) + sizeof(*set) * cp->num_of_sets;
1273 
1274 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
1275 				     size, data, HCI_CMD_TIMEOUT);
1276 }
1277 
1278 static int hci_set_adv_set_random_addr_sync(struct hci_dev *hdev, u8 instance,
1279 					    bdaddr_t *random_addr)
1280 {
1281 	struct hci_cp_le_set_adv_set_rand_addr cp;
1282 	struct adv_info *adv;
1283 	u8 handle = instance;
1284 	int err;
1285 
1286 	if (!instance) {
1287 		/* Instance 0x00 doesn't have an adv_info, instead it uses
1288 		 * hdev->random_addr to track its address so whenever it needs
1289 		 * to be updated this also set the random address since
1290 		 * hdev->random_addr is shared with scan state machine.
1291 		 */
1292 		err = hci_set_random_addr_sync(hdev, random_addr);
1293 		if (err)
1294 			return err;
1295 	} else {
1296 		hci_dev_lock(hdev);
1297 		adv = hci_find_adv_instance(hdev, instance);
1298 		if (adv)
1299 			handle = adv->handle;
1300 		hci_dev_unlock(hdev);
1301 	}
1302 
1303 	memset(&cp, 0, sizeof(cp));
1304 
1305 	cp.handle = handle;
1306 	bacpy(&cp.bdaddr, random_addr);
1307 
1308 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_SET_RAND_ADDR,
1309 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1310 	if (err || handle == instance)
1311 		return err;
1312 
1313 	/* hci_cc_le_set_adv_set_random_addr() records the address of the
1314 	 * instance numbered as the handle, and leaves handle 0x00 to
1315 	 * hdev->random_addr, so record it here for an instance using another
1316 	 * handle: instance 1 on handle 0x00, on a controller supporting a
1317 	 * single advertising set.
1318 	 */
1319 	hci_dev_lock(hdev);
1320 
1321 	adv = hci_find_adv_instance(hdev, instance);
1322 	if (adv) {
1323 		bacpy(&adv->random_addr, random_addr);
1324 		if (!bacmp(&hdev->rpa, random_addr)) {
1325 			adv->rpa_expired = false;
1326 			queue_delayed_work(hdev->workqueue,
1327 					   &adv->rpa_expired_cb,
1328 					   secs_to_jiffies(hdev->rpa_timeout));
1329 		}
1330 	}
1331 
1332 	hci_dev_unlock(hdev);
1333 
1334 	return 0;
1335 }
1336 
1337 static int
1338 hci_set_ext_adv_params_sync(struct hci_dev *hdev, u8 instance,
1339 			    const struct hci_cp_le_set_ext_adv_params *cp,
1340 			    struct hci_rp_le_set_ext_adv_params *rp)
1341 {
1342 	struct adv_info *adv;
1343 	struct sk_buff *skb;
1344 
1345 	skb = __hci_cmd_sync(hdev, HCI_OP_LE_SET_EXT_ADV_PARAMS, sizeof(*cp),
1346 			     cp, HCI_CMD_TIMEOUT);
1347 
1348 	/* If command return a status event, skb will be set to -ENODATA */
1349 	if (skb == ERR_PTR(-ENODATA))
1350 		return 0;
1351 
1352 	if (IS_ERR(skb)) {
1353 		bt_dev_err(hdev, "Opcode 0x%4.4x failed: %ld",
1354 			   HCI_OP_LE_SET_EXT_ADV_PARAMS, PTR_ERR(skb));
1355 		return PTR_ERR(skb);
1356 	}
1357 
1358 	if (skb->len != sizeof(*rp)) {
1359 		bt_dev_err(hdev, "Invalid response length for 0x%4.4x: %u",
1360 			   HCI_OP_LE_SET_EXT_ADV_PARAMS, skb->len);
1361 		kfree_skb(skb);
1362 		return -EIO;
1363 	}
1364 
1365 	memcpy(rp, skb->data, sizeof(*rp));
1366 	kfree_skb(skb);
1367 
1368 	if (!rp->status) {
1369 		hdev->adv_addr_type = cp->own_addr_type;
1370 		if (!instance) {
1371 			/* Store in hdev for instance 0 */
1372 			hdev->adv_tx_power = rp->tx_power;
1373 		} else {
1374 			hci_dev_lock(hdev);
1375 			adv = hci_find_adv_instance(hdev, instance);
1376 			if (adv)
1377 				adv->tx_power = rp->tx_power;
1378 			hci_dev_unlock(hdev);
1379 		}
1380 	}
1381 
1382 	return rp->status;
1383 }
1384 
1385 static int hci_set_ext_adv_data_sync(struct hci_dev *hdev, u8 instance)
1386 	__context_unsafe(/* conditional locking */)
1387 {
1388 	DEFINE_FLEX(struct hci_cp_le_set_ext_adv_data, pdu, data, length,
1389 		    HCI_MAX_EXT_AD_LENGTH);
1390 	u8 len;
1391 	struct adv_info *adv = NULL;
1392 	int err;
1393 
1394 	if (instance) {
1395 		hci_dev_lock(hdev);
1396 
1397 		adv = hci_find_adv_instance(hdev, instance);
1398 		if (!adv || !adv->adv_data_changed) {
1399 			hci_dev_unlock(hdev);
1400 			return 0;
1401 		}
1402 	}
1403 
1404 	len = eir_create_adv_data(hdev, instance, pdu->data,
1405 				  HCI_MAX_EXT_AD_LENGTH);
1406 
1407 	pdu->length = len;
1408 	pdu->handle = adv ? adv->handle : instance;
1409 	pdu->operation = LE_SET_ADV_DATA_OP_COMPLETE;
1410 	pdu->frag_pref = LE_SET_ADV_DATA_NO_FRAG;
1411 
1412 	if (adv) {
1413 		adv->adv_data_changed = false;
1414 		hci_dev_unlock(hdev);
1415 	}
1416 
1417 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_DATA,
1418 				    struct_size(pdu, data, len), pdu,
1419 				    HCI_CMD_TIMEOUT);
1420 	if (err) {
1421 		if (instance) {
1422 			hci_dev_lock(hdev);
1423 			adv = hci_find_adv_instance(hdev, instance);
1424 			if (adv)
1425 				adv->adv_data_changed = true;
1426 			hci_dev_unlock(hdev);
1427 		}
1428 
1429 		return err;
1430 	}
1431 
1432 	if (!instance) {
1433 		memcpy(hdev->adv_data, pdu->data, len);
1434 		hdev->adv_data_len = len;
1435 	}
1436 
1437 	return 0;
1438 }
1439 
1440 static int hci_set_adv_data_sync(struct hci_dev *hdev, u8 instance)
1441 	__context_unsafe(/* conditional locking */)
1442 {
1443 	struct hci_cp_le_set_adv_data cp;
1444 	u8 len;
1445 
1446 	memset(&cp, 0, sizeof(cp));
1447 
1448 	if (instance)
1449 		hci_dev_lock(hdev);
1450 
1451 	len = eir_create_adv_data(hdev, instance, cp.data, sizeof(cp.data));
1452 
1453 	if (instance)
1454 		hci_dev_unlock(hdev);
1455 
1456 	/* There's nothing to do if the data hasn't changed */
1457 	if (hdev->adv_data_len == len &&
1458 	    memcmp(cp.data, hdev->adv_data, len) == 0)
1459 		return 0;
1460 
1461 	memcpy(hdev->adv_data, cp.data, sizeof(cp.data));
1462 	hdev->adv_data_len = len;
1463 
1464 	cp.length = len;
1465 
1466 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_DATA,
1467 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1468 }
1469 
1470 int hci_update_adv_data_sync(struct hci_dev *hdev, u8 instance)
1471 {
1472 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
1473 		return 0;
1474 
1475 	if (ext_adv_capable(hdev))
1476 		return hci_set_ext_adv_data_sync(hdev, instance);
1477 
1478 	return hci_set_adv_data_sync(hdev, instance);
1479 }
1480 
1481 int hci_setup_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
1482 	__context_unsafe(/* conditional locking */)
1483 {
1484 	struct hci_cp_le_set_ext_adv_params cp;
1485 	struct hci_rp_le_set_ext_adv_params rp;
1486 	bool connectable, require_privacy;
1487 	u32 flags;
1488 	bdaddr_t random_addr;
1489 	u8 own_addr_type;
1490 	int err;
1491 	struct adv_info *adv;
1492 	bool secondary_adv;
1493 
1494 	/* Updating parameters of an active instance will return a
1495 	 * Command Disallowed error, so disable it before taking a snapshot.
1496 	 */
1497 	if (instance > 0) {
1498 		err = hci_disable_ext_adv_instance_sync(hdev, instance);
1499 		if (err)
1500 			return err;
1501 
1502 		hci_dev_lock(hdev);
1503 		adv = hci_find_adv_instance(hdev, instance);
1504 		if (!adv) {
1505 			hci_dev_unlock(hdev);
1506 			return -EINVAL;
1507 		}
1508 	} else {
1509 		/* Disable the advertising set with handle 0x00, including any
1510 		 * instance sharing it, since it is going to be overridden.
1511 		 */
1512 		err = hci_disable_ext_adv_legacy_instance_sync(hdev);
1513 		if (err)
1514 			return err;
1515 
1516 		adv = NULL;
1517 	}
1518 
1519 	flags = hci_adv_instance_flags(hdev, instance);
1520 
1521 	/* If the "connectable" instance flag was not set, then choose between
1522 	 * ADV_IND and ADV_NONCONN_IND based on the global connectable setting.
1523 	 */
1524 	connectable = (flags & MGMT_ADV_FLAG_CONNECTABLE) ||
1525 		      mgmt_get_connectable(hdev);
1526 
1527 	if (!is_advertising_allowed(hdev, connectable)) {
1528 		if (instance)
1529 			hci_dev_unlock(hdev);
1530 		return -EPERM;
1531 	}
1532 
1533 	/* Set require_privacy to true only when non-connectable
1534 	 * advertising is used and it is not periodic.
1535 	 * In that case it is fine to use a non-resolvable private address.
1536 	 */
1537 	require_privacy = !connectable && !(adv && adv->periodic);
1538 
1539 	err = hci_get_random_address(hdev, require_privacy,
1540 				     adv_use_rpa(hdev, flags), adv,
1541 				     &own_addr_type, &random_addr);
1542 	if (err < 0) {
1543 		if (instance)
1544 			hci_dev_unlock(hdev);
1545 		return err;
1546 	}
1547 
1548 	memset(&cp, 0, sizeof(cp));
1549 
1550 	if (adv) {
1551 		hci_cpu_to_le24(adv->min_interval, cp.min_interval);
1552 		hci_cpu_to_le24(adv->max_interval, cp.max_interval);
1553 		cp.tx_power = adv->tx_power;
1554 		cp.sid = adv->sid;
1555 	} else {
1556 		hci_cpu_to_le24(hdev->le_adv_min_interval, cp.min_interval);
1557 		hci_cpu_to_le24(hdev->le_adv_max_interval, cp.max_interval);
1558 		cp.tx_power = HCI_ADV_TX_POWER_NO_PREFERENCE;
1559 		cp.sid = 0x00;
1560 	}
1561 
1562 	secondary_adv = (flags & MGMT_ADV_FLAG_SEC_MASK);
1563 
1564 	if (connectable) {
1565 		if (secondary_adv)
1566 			cp.evt_properties = cpu_to_le16(LE_EXT_ADV_CONN_IND);
1567 		else
1568 			cp.evt_properties = cpu_to_le16(LE_LEGACY_ADV_IND);
1569 	} else if (hci_adv_instance_is_scannable(hdev, instance) ||
1570 		   (flags & MGMT_ADV_PARAM_SCAN_RSP)) {
1571 		if (secondary_adv)
1572 			cp.evt_properties = cpu_to_le16(LE_EXT_ADV_SCAN_IND);
1573 		else
1574 			cp.evt_properties = cpu_to_le16(LE_LEGACY_ADV_SCAN_IND);
1575 	} else {
1576 		if (secondary_adv)
1577 			cp.evt_properties = cpu_to_le16(LE_EXT_ADV_NON_CONN_IND);
1578 		else
1579 			cp.evt_properties = cpu_to_le16(LE_LEGACY_NONCONN_IND);
1580 	}
1581 
1582 	/* If Own_Address_Type equals 0x02 or 0x03, the Peer_Address parameter
1583 	 * contains the peer’s Identity Address and the Peer_Address_Type
1584 	 * parameter contains the peer’s Identity Type (i.e., 0x00 or 0x01).
1585 	 * These parameters are used to locate the corresponding local IRK in
1586 	 * the resolving list; this IRK is used to generate their own address
1587 	 * used in the advertisement.
1588 	 */
1589 	if (own_addr_type == ADDR_LE_DEV_RANDOM_RESOLVED)
1590 		hci_copy_identity_address(hdev, &cp.peer_addr,
1591 					  &cp.peer_addr_type);
1592 
1593 	cp.own_addr_type = own_addr_type;
1594 	cp.channel_map = hdev->le_adv_channel_map;
1595 	cp.handle = adv ? adv->handle : instance;
1596 
1597 	if (instance)
1598 		hci_dev_unlock(hdev);
1599 
1600 	if (flags & MGMT_ADV_FLAG_SEC_2M) {
1601 		cp.primary_phy = HCI_ADV_PHY_1M;
1602 		cp.secondary_phy = HCI_ADV_PHY_2M;
1603 	} else if (flags & MGMT_ADV_FLAG_SEC_CODED) {
1604 		cp.primary_phy = HCI_ADV_PHY_CODED;
1605 		cp.secondary_phy = HCI_ADV_PHY_CODED;
1606 	} else {
1607 		/* In all other cases use 1M */
1608 		cp.primary_phy = HCI_ADV_PHY_1M;
1609 		cp.secondary_phy = HCI_ADV_PHY_1M;
1610 	}
1611 
1612 	err = hci_set_ext_adv_params_sync(hdev, instance, &cp, &rp);
1613 	if (err)
1614 		return err;
1615 
1616 	/* Update adv data as tx power is known now */
1617 	err = hci_set_ext_adv_data_sync(hdev, instance);
1618 	if (err)
1619 		return err;
1620 
1621 	if ((own_addr_type == ADDR_LE_DEV_RANDOM ||
1622 	     own_addr_type == ADDR_LE_DEV_RANDOM_RESOLVED) &&
1623 	    bacmp(&random_addr, BDADDR_ANY)) {
1624 		/* Check if random address need to be updated */
1625 		if (instance) {
1626 			hci_dev_lock(hdev);
1627 			adv = hci_find_adv_instance(hdev, instance);
1628 			if (!adv || !bacmp(&random_addr, &adv->random_addr)) {
1629 				hci_dev_unlock(hdev);
1630 				return 0;
1631 			}
1632 			hci_dev_unlock(hdev);
1633 		} else {
1634 			if (!bacmp(&random_addr, &hdev->random_addr))
1635 				return 0;
1636 		}
1637 
1638 		return hci_set_adv_set_random_addr_sync(hdev, instance,
1639 							&random_addr);
1640 	}
1641 
1642 	return 0;
1643 }
1644 
1645 static int hci_set_ext_scan_rsp_data_sync(struct hci_dev *hdev, u8 instance)
1646 	__context_unsafe(/* conditional locking */)
1647 {
1648 	DEFINE_FLEX(struct hci_cp_le_set_ext_scan_rsp_data, pdu, data, length,
1649 		    HCI_MAX_EXT_AD_LENGTH);
1650 	u8 len;
1651 	struct adv_info *adv = NULL;
1652 	int err;
1653 
1654 	if (instance) {
1655 		hci_dev_lock(hdev);
1656 
1657 		adv = hci_find_adv_instance(hdev, instance);
1658 		if (!adv || !adv->scan_rsp_changed) {
1659 			hci_dev_unlock(hdev);
1660 			return 0;
1661 		}
1662 	}
1663 
1664 	len = eir_create_scan_rsp(hdev, instance, pdu->data);
1665 
1666 	pdu->handle = adv ? adv->handle : instance;
1667 	pdu->length = len;
1668 	pdu->operation = LE_SET_ADV_DATA_OP_COMPLETE;
1669 	pdu->frag_pref = LE_SET_ADV_DATA_NO_FRAG;
1670 
1671 	if (adv) {
1672 		adv->scan_rsp_changed = false;
1673 		hci_dev_unlock(hdev);
1674 	}
1675 
1676 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_SCAN_RSP_DATA,
1677 				    struct_size(pdu, data, len), pdu,
1678 				    HCI_CMD_TIMEOUT);
1679 	if (err) {
1680 		if (instance) {
1681 			hci_dev_lock(hdev);
1682 			adv = hci_find_adv_instance(hdev, instance);
1683 			if (adv)
1684 				adv->scan_rsp_changed = true;
1685 			hci_dev_unlock(hdev);
1686 		}
1687 
1688 		return err;
1689 	}
1690 
1691 	if (!instance) {
1692 		memcpy(hdev->scan_rsp_data, pdu->data, len);
1693 		hdev->scan_rsp_data_len = len;
1694 	}
1695 
1696 	return 0;
1697 }
1698 
1699 static int __hci_set_scan_rsp_data_sync(struct hci_dev *hdev, u8 instance)
1700 	__context_unsafe(/* conditional locking */)
1701 {
1702 	struct hci_cp_le_set_scan_rsp_data cp;
1703 	u8 len;
1704 
1705 	memset(&cp, 0, sizeof(cp));
1706 
1707 	if (instance)
1708 		hci_dev_lock(hdev);
1709 
1710 	len = eir_create_scan_rsp(hdev, instance, cp.data);
1711 
1712 	if (instance)
1713 		hci_dev_unlock(hdev);
1714 
1715 	if (hdev->scan_rsp_data_len == len &&
1716 	    !memcmp(cp.data, hdev->scan_rsp_data, len))
1717 		return 0;
1718 
1719 	memcpy(hdev->scan_rsp_data, cp.data, sizeof(cp.data));
1720 	hdev->scan_rsp_data_len = len;
1721 
1722 	cp.length = len;
1723 
1724 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_SCAN_RSP_DATA,
1725 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1726 }
1727 
1728 int hci_update_scan_rsp_data_sync(struct hci_dev *hdev, u8 instance)
1729 {
1730 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
1731 		return 0;
1732 
1733 	if (ext_adv_capable(hdev))
1734 		return hci_set_ext_scan_rsp_data_sync(hdev, instance);
1735 
1736 	return __hci_set_scan_rsp_data_sync(hdev, instance);
1737 }
1738 
1739 int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance)
1740 {
1741 	struct hci_cp_le_set_ext_adv_enable *cp;
1742 	struct hci_cp_ext_adv_set *set;
1743 	u8 data[sizeof(*cp) + sizeof(*set) * 1];
1744 	u8 handle = instance;
1745 	u32 duration = 0;
1746 
1747 	if (instance > 0) {
1748 		struct adv_info *adv;
1749 
1750 		hci_dev_lock(hdev);
1751 		adv = hci_find_adv_instance(hdev, instance);
1752 		if (!adv) {
1753 			hci_dev_unlock(hdev);
1754 			return -EINVAL;
1755 		}
1756 		/* If already enabled there is nothing to do */
1757 		if (adv->enabled) {
1758 			hci_dev_unlock(hdev);
1759 			return 0;
1760 		}
1761 
1762 		handle = adv->handle;
1763 
1764 		/* Set duration per instance since controller is
1765 		 * responsible for scheduling it.
1766 		 */
1767 		if (adv->timeout)
1768 			duration = adv->mesh ? adv->timeout :
1769 					       adv->timeout * MSEC_PER_SEC;
1770 		hci_dev_unlock(hdev);
1771 	}
1772 
1773 	cp = (void *)data;
1774 	set = (void *)cp->data;
1775 
1776 	memset(cp, 0, sizeof(*cp));
1777 
1778 	cp->enable = 0x01;
1779 	cp->num_of_sets = 0x01;
1780 
1781 	memset(set, 0, sizeof(*set));
1782 
1783 	set->handle = handle;
1784 
1785 	/* Time = N * 10 ms */
1786 	set->duration = cpu_to_le16(min_t(u32, duration / 10, U16_MAX));
1787 
1788 	/* Track which instance owns the advertising set since the handle
1789 	 * alone is ambiguous when instances share handle 0x00, see
1790 	 * hci_cc_le_set_ext_adv_enable.
1791 	 */
1792 	hdev->cur_adv_instance = instance;
1793 
1794 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
1795 				     sizeof(*cp) +
1796 				     sizeof(*set) * cp->num_of_sets,
1797 				     data, HCI_CMD_TIMEOUT);
1798 }
1799 
1800 int hci_start_ext_adv_sync(struct hci_dev *hdev, u8 instance)
1801 {
1802 	int err;
1803 
1804 	err = hci_setup_ext_adv_instance_sync(hdev, instance);
1805 	if (err)
1806 		return err;
1807 
1808 	err = hci_set_ext_scan_rsp_data_sync(hdev, instance);
1809 	if (err)
1810 		return err;
1811 
1812 	return hci_enable_ext_advertising_sync(hdev, instance);
1813 }
1814 
1815 int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance)
1816 {
1817 	struct hci_cp_le_set_per_adv_enable cp;
1818 	struct adv_info *adv;
1819 	bool enabled;
1820 	u8 handle = instance;
1821 	int err;
1822 
1823 	/* If periodic advertising already disabled there is nothing to do. */
1824 	hci_dev_lock(hdev);
1825 	adv = hci_find_adv_instance(hdev, instance);
1826 	enabled = adv && adv->periodic_enabled;
1827 	if (adv)
1828 		handle = adv->handle;
1829 	hci_dev_unlock(hdev);
1830 	if (!enabled)
1831 		return 0;
1832 
1833 	memset(&cp, 0, sizeof(cp));
1834 
1835 	cp.enable = 0x00;
1836 	cp.handle = handle;
1837 
1838 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE,
1839 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1840 	if (err || handle == instance)
1841 		return err;
1842 
1843 	/* Handle 0 is shared with global advertising, so the completion
1844 	 * cannot identify the software instance from the command alone.
1845 	 */
1846 	hci_dev_lock(hdev);
1847 	adv = hci_find_adv_instance(hdev, instance);
1848 	if (adv)
1849 		adv->periodic_enabled = false;
1850 	hci_dev_unlock(hdev);
1851 
1852 	return 0;
1853 }
1854 
1855 /* Map a management instance number to its controller handle. */
1856 static u8 hci_adv_instance_handle(struct hci_dev *hdev, u8 instance)
1857 	__must_not_hold(&hdev->lock)
1858 {
1859 	struct adv_info *adv;
1860 	u8 handle = instance;
1861 
1862 	hci_dev_lock(hdev);
1863 	adv = hci_find_adv_instance(hdev, instance);
1864 	if (adv)
1865 		handle = adv->handle;
1866 	hci_dev_unlock(hdev);
1867 
1868 	return handle;
1869 }
1870 
1871 static int hci_set_per_adv_params_sync(struct hci_dev *hdev, u8 instance,
1872 				       u16 min_interval, u16 max_interval)
1873 {
1874 	struct hci_cp_le_set_per_adv_params cp;
1875 
1876 	memset(&cp, 0, sizeof(cp));
1877 
1878 	if (!min_interval)
1879 		min_interval = DISCOV_LE_PER_ADV_INT_MIN;
1880 
1881 	if (!max_interval)
1882 		max_interval = DISCOV_LE_PER_ADV_INT_MAX;
1883 
1884 	cp.handle = hci_adv_instance_handle(hdev, instance);
1885 	cp.min_interval = cpu_to_le16(min_interval);
1886 	cp.max_interval = cpu_to_le16(max_interval);
1887 	cp.periodic_properties = 0x0000;
1888 
1889 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_PARAMS,
1890 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1891 }
1892 
1893 static int hci_set_per_adv_data_sync(struct hci_dev *hdev, u8 instance)
1894 	__context_unsafe(/* conditional locking */)
1895 {
1896 	DEFINE_FLEX(struct hci_cp_le_set_per_adv_data, pdu, data, length,
1897 		    HCI_MAX_PER_AD_LENGTH);
1898 	u8 len;
1899 	struct adv_info *adv = NULL;
1900 
1901 	if (instance) {
1902 		hci_dev_lock(hdev);
1903 
1904 		adv = hci_find_adv_instance(hdev, instance);
1905 		if (!adv || !adv->periodic) {
1906 			hci_dev_unlock(hdev);
1907 			return 0;
1908 		}
1909 	}
1910 
1911 	len = eir_create_per_adv_data(hdev, instance, pdu->data);
1912 
1913 	pdu->length = len;
1914 	pdu->handle = adv ? adv->handle : instance;
1915 	pdu->operation = LE_SET_ADV_DATA_OP_COMPLETE;
1916 
1917 	if (adv)
1918 		hci_dev_unlock(hdev);
1919 
1920 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_DATA,
1921 				     struct_size(pdu, data, len), pdu,
1922 				     HCI_CMD_TIMEOUT);
1923 }
1924 
1925 static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance)
1926 {
1927 	struct hci_cp_le_set_per_adv_enable cp;
1928 	struct adv_info *adv;
1929 	bool enabled;
1930 	u8 handle = instance;
1931 	int err;
1932 
1933 	/* If periodic advertising already enabled there is nothing to do. */
1934 	hci_dev_lock(hdev);
1935 	adv = hci_find_adv_instance(hdev, instance);
1936 	enabled = adv && adv->periodic_enabled;
1937 	if (adv)
1938 		handle = adv->handle;
1939 	hci_dev_unlock(hdev);
1940 	if (enabled)
1941 		return 0;
1942 
1943 	memset(&cp, 0, sizeof(cp));
1944 
1945 	cp.enable = 0x01;
1946 	cp.handle = handle;
1947 
1948 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE,
1949 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1950 	if (err || handle == instance)
1951 		return err;
1952 
1953 	/* Handle 0 is shared with global advertising, so the completion
1954 	 * cannot identify the software instance from the command alone.
1955 	 */
1956 	hci_dev_lock(hdev);
1957 	adv = hci_find_adv_instance(hdev, instance);
1958 	if (adv)
1959 		adv->periodic_enabled = true;
1960 	hci_dev_unlock(hdev);
1961 
1962 	return 0;
1963 }
1964 
1965 /* Checks if periodic advertising data contains a Basic Announcement and if it
1966  * does generates a Broadcast ID and add Broadcast Announcement.
1967  */
1968 static int hci_adv_bcast_annoucement(struct hci_dev *hdev, u8 instance)
1969 {
1970 	struct adv_info *adv;
1971 	u8 bid[3];
1972 	u8 ad[HCI_MAX_EXT_AD_LENGTH];
1973 	u8 len;
1974 	int err = 0;
1975 
1976 	/* Skip if instance 0x00 as it is used for general purpose
1977 	 * advertising so it cannot used for the likes of Broadcast Announcement
1978 	 * as it can be overwritten at any point.
1979 	 */
1980 	if (!instance)
1981 		return 0;
1982 
1983 	hci_dev_lock(hdev);
1984 
1985 	/* The instance may have been removed while waiting for the
1986 	 * controller, in which case there is nothing to announce.
1987 	 */
1988 	adv = hci_find_adv_instance(hdev, instance);
1989 	if (!adv)
1990 		goto unlock;
1991 
1992 	/* Check if PA data doesn't contains a Basic Audio Announcement then
1993 	 * there is nothing to do.
1994 	 */
1995 	if (!eir_get_service_data(adv->per_adv_data, adv->per_adv_data_len,
1996 				  0x1851, NULL))
1997 		goto unlock;
1998 
1999 	/* Check if advertising data already has a Broadcast Announcement since
2000 	 * the process may want to control the Broadcast ID directly and in that
2001 	 * case the kernel shall no interfere.
2002 	 */
2003 	if (eir_get_service_data(adv->adv_data, adv->adv_data_len, 0x1852,
2004 				 NULL))
2005 		goto unlock;
2006 
2007 	/* Generate Broadcast ID */
2008 	get_random_bytes(bid, sizeof(bid));
2009 	len = eir_append_service_data(ad, 0, 0x1852, bid, sizeof(bid));
2010 	if (adv->adv_data_len > sizeof(ad) - len) {
2011 		bt_dev_err(hdev, "No room for Broadcast Announcement");
2012 		err = -EINVAL;
2013 		goto unlock;
2014 	}
2015 
2016 	memcpy(ad + len, adv->adv_data, adv->adv_data_len);
2017 	hci_set_adv_instance_data(hdev, instance, len + adv->adv_data_len,
2018 				  ad, 0, NULL);
2019 
2020 	hci_dev_unlock(hdev);
2021 
2022 	return hci_update_adv_data_sync(hdev, instance);
2023 
2024 unlock:
2025 	hci_dev_unlock(hdev);
2026 	return err;
2027 }
2028 
2029 int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 sid,
2030 			   u8 data_len, u8 *data, u32 flags, u16 min_interval,
2031 			   u16 max_interval, u16 sync_interval)
2032 {
2033 	struct adv_info *adv;
2034 	u8 bcast_instance = 0;
2035 	int err;
2036 	bool added = false;
2037 
2038 	hci_disable_per_advertising_sync(hdev, instance);
2039 
2040 	if (instance) {
2041 		hci_dev_lock(hdev);
2042 
2043 		adv = hci_find_adv_instance(hdev, instance);
2044 		if (adv) {
2045 			if (sid != HCI_SID_INVALID && adv->sid != sid) {
2046 				/* If the SID don't match attempt to find by
2047 				 * SID.
2048 				 */
2049 				adv = hci_find_adv_sid(hdev, sid);
2050 				if (!adv) {
2051 					hci_dev_unlock(hdev);
2052 					bt_dev_err(hdev,
2053 						   "Unable to find adv_info");
2054 					return -EINVAL;
2055 				}
2056 			}
2057 
2058 			/* Turn it into periodic advertising */
2059 			adv->periodic = true;
2060 			adv->per_adv_data_len = data_len;
2061 			if (data)
2062 				memcpy(adv->per_adv_data, data, data_len);
2063 			adv->flags = flags;
2064 		} else if (!adv) {
2065 			/* Create an instance if that could not be found */
2066 			adv = hci_add_per_instance(hdev, instance, sid, flags,
2067 						   data_len, data,
2068 						   sync_interval,
2069 						   sync_interval);
2070 			if (IS_ERR(adv)) {
2071 				hci_dev_unlock(hdev);
2072 				return PTR_ERR(adv);
2073 			}
2074 			adv->pending = false;
2075 			added = true;
2076 		}
2077 
2078 		bcast_instance = adv->instance;
2079 
2080 		hci_dev_unlock(hdev);
2081 	}
2082 
2083 	/* Start advertising */
2084 	err = hci_start_ext_adv_sync(hdev, instance);
2085 	if (err < 0)
2086 		goto fail;
2087 
2088 	err = hci_adv_bcast_annoucement(hdev, bcast_instance);
2089 	if (err < 0)
2090 		goto fail;
2091 
2092 	err = hci_set_per_adv_params_sync(hdev, instance, min_interval,
2093 					  max_interval);
2094 	if (err < 0)
2095 		goto fail;
2096 
2097 	err = hci_set_per_adv_data_sync(hdev, instance);
2098 	if (err < 0)
2099 		goto fail;
2100 
2101 	err = hci_enable_per_advertising_sync(hdev, instance);
2102 	if (err < 0)
2103 		goto fail;
2104 
2105 	return 0;
2106 
2107 fail:
2108 	if (added) {
2109 		hci_dev_lock(hdev);
2110 		hci_remove_adv_instance(hdev, instance);
2111 		hci_dev_unlock(hdev);
2112 	}
2113 
2114 	return err;
2115 }
2116 
2117 static int hci_start_adv_sync(struct hci_dev *hdev, u8 instance)
2118 {
2119 	int err;
2120 
2121 	if (ext_adv_capable(hdev))
2122 		return hci_start_ext_adv_sync(hdev, instance);
2123 
2124 	err = hci_update_adv_data_sync(hdev, instance);
2125 	if (err)
2126 		return err;
2127 
2128 	err = hci_update_scan_rsp_data_sync(hdev, instance);
2129 	if (err)
2130 		return err;
2131 
2132 	return hci_enable_advertising_sync(hdev);
2133 }
2134 
2135 int hci_enable_advertising_sync(struct hci_dev *hdev)
2136 {
2137 	struct adv_info *adv_instance;
2138 	struct hci_cp_le_set_adv_param cp;
2139 	u8 own_addr_type, enable = 0x01;
2140 	bool connectable;
2141 	u16 adv_min_interval, adv_max_interval;
2142 	bool scannable;
2143 	u32 flags;
2144 	u8 status;
2145 
2146 	if (ext_adv_capable(hdev))
2147 		return hci_enable_ext_advertising_sync(hdev,
2148 						       hdev->cur_adv_instance);
2149 
2150 	/* Snapshot the instance under hdev->lock since it may be removed
2151 	 * while waiting for the commands below to complete.
2152 	 */
2153 	hci_dev_lock(hdev);
2154 
2155 	flags = hci_adv_instance_flags(hdev, hdev->cur_adv_instance);
2156 	scannable = hci_adv_instance_is_scannable(hdev,
2157 						  hdev->cur_adv_instance);
2158 
2159 	adv_instance = hci_find_adv_instance(hdev, hdev->cur_adv_instance);
2160 	if (adv_instance) {
2161 		adv_min_interval = adv_instance->min_interval;
2162 		adv_max_interval = adv_instance->max_interval;
2163 	} else {
2164 		adv_min_interval = hdev->le_adv_min_interval;
2165 		adv_max_interval = hdev->le_adv_max_interval;
2166 	}
2167 
2168 	hci_dev_unlock(hdev);
2169 
2170 	/* If the "connectable" instance flag was not set, then choose between
2171 	 * ADV_IND and ADV_NONCONN_IND based on the global connectable setting.
2172 	 */
2173 	connectable = (flags & MGMT_ADV_FLAG_CONNECTABLE) ||
2174 		      mgmt_get_connectable(hdev);
2175 
2176 	if (!is_advertising_allowed(hdev, connectable))
2177 		return -EINVAL;
2178 
2179 	status = hci_disable_advertising_sync(hdev);
2180 	if (status)
2181 		return status;
2182 
2183 	/* Clear the HCI_LE_ADV bit temporarily so that the
2184 	 * hci_update_random_address knows that it's safe to go ahead
2185 	 * and write a new random address. The flag will be set back on
2186 	 * as soon as the SET_ADV_ENABLE HCI command completes.
2187 	 */
2188 	hci_dev_clear_flag(hdev, HCI_LE_ADV);
2189 
2190 	/* Set require_privacy to true only when non-connectable
2191 	 * advertising is used. In that case it is fine to use a
2192 	 * non-resolvable private address.
2193 	 */
2194 	status = hci_update_random_address_sync(hdev, !connectable,
2195 						adv_use_rpa(hdev, flags),
2196 						&own_addr_type);
2197 	if (status)
2198 		return status;
2199 
2200 	memset(&cp, 0, sizeof(cp));
2201 
2202 	if (connectable) {
2203 		cp.type = LE_ADV_IND;
2204 	} else {
2205 		if (scannable)
2206 			cp.type = LE_ADV_SCAN_IND;
2207 		else
2208 			cp.type = LE_ADV_NONCONN_IND;
2209 
2210 		if (!hci_dev_test_flag(hdev, HCI_DISCOVERABLE) ||
2211 		    hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE)) {
2212 			adv_min_interval = DISCOV_LE_FAST_ADV_INT_MIN;
2213 			adv_max_interval = DISCOV_LE_FAST_ADV_INT_MAX;
2214 		}
2215 	}
2216 
2217 	cp.min_interval = cpu_to_le16(adv_min_interval);
2218 	cp.max_interval = cpu_to_le16(adv_max_interval);
2219 	cp.own_address_type = own_addr_type;
2220 	cp.channel_map = hdev->le_adv_channel_map;
2221 
2222 	status = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_PARAM,
2223 				       sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2224 	if (status)
2225 		return status;
2226 
2227 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_ENABLE,
2228 				     sizeof(enable), &enable, HCI_CMD_TIMEOUT);
2229 }
2230 
2231 static int enable_advertising_sync(struct hci_dev *hdev, void *data)
2232 {
2233 	return hci_enable_advertising_sync(hdev);
2234 }
2235 
2236 int hci_enable_advertising(struct hci_dev *hdev)
2237 {
2238 	if (!hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
2239 	    list_empty(&hdev->adv_instances))
2240 		return 0;
2241 
2242 	return hci_cmd_sync_queue(hdev, enable_advertising_sync, NULL, NULL);
2243 }
2244 
2245 int hci_remove_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance,
2246 				     struct sock *sk)
2247 {
2248 	struct adv_info *adv = NULL;
2249 	u8 handle = instance;
2250 	bool global = false;
2251 	int err;
2252 
2253 	if (!ext_adv_capable(hdev))
2254 		return 0;
2255 
2256 	err = hci_disable_ext_adv_instance_sync(hdev, instance);
2257 	if (err)
2258 		return err;
2259 
2260 	if (instance) {
2261 		hci_dev_lock(hdev);
2262 
2263 		adv = hci_find_adv_instance(hdev, instance);
2264 		if (adv) {
2265 			handle = adv->handle;
2266 
2267 			/* An instance sharing handle 0x00 with Global
2268 			 * Advertising doesn't own the set while Global
2269 			 * Advertising is on, and the set may still be enabled
2270 			 * for it, which the controller would refuse to remove.
2271 			 */
2272 			global = !handle &&
2273 				 (hci_dev_test_flag(hdev, HCI_ADVERTISING) ||
2274 				  hci_dev_test_flag(hdev, HCI_LE_ADV_0));
2275 		}
2276 
2277 		hci_dev_unlock(hdev);
2278 
2279 		/* If request specifies an instance that doesn't exist, fail */
2280 		if (!adv)
2281 			return -EINVAL;
2282 	}
2283 
2284 	if (!global) {
2285 		err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_REMOVE_ADV_SET,
2286 					       sizeof(handle), &handle, 0,
2287 					       HCI_CMD_TIMEOUT, sk);
2288 		if (err)
2289 			return err;
2290 	}
2291 
2292 	/* hci_cc_le_remove_adv_set() removes the instance numbered as the
2293 	 * handle it sent, so remove here an instance using another handle:
2294 	 * instance 1 on handle 0x00, on a controller supporting a single
2295 	 * advertising set. The completion can't tell it from instance 0.
2296 	 */
2297 	if (handle != instance) {
2298 		hci_dev_lock(hdev);
2299 
2300 		if (!hci_remove_adv_instance(hdev, instance))
2301 			mgmt_advertising_removed(sk, hdev, instance);
2302 
2303 		hci_dev_unlock(hdev);
2304 	}
2305 
2306 	return 0;
2307 }
2308 
2309 int hci_le_terminate_big_sync(struct hci_dev *hdev, u8 handle, u8 reason)
2310 {
2311 	struct hci_cp_le_term_big cp;
2312 
2313 	memset(&cp, 0, sizeof(cp));
2314 	cp.handle = handle;
2315 	cp.reason = reason;
2316 
2317 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_TERM_BIG,
2318 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2319 }
2320 
2321 int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance,
2322 				   bool force)
2323 {
2324 	struct adv_info *adv = NULL;
2325 	u16 timeout;
2326 
2327 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING) && !ext_adv_capable(hdev))
2328 		return -EPERM;
2329 
2330 	if (hdev->adv_instance_timeout)
2331 		return -EBUSY;
2332 
2333 	hci_dev_lock(hdev);
2334 
2335 	adv = hci_find_adv_instance(hdev, instance);
2336 	if (!adv) {
2337 		hci_dev_unlock(hdev);
2338 		return -ENOENT;
2339 	}
2340 
2341 	/* A zero timeout means unlimited advertising. As long as there is
2342 	 * only one instance, duration should be ignored. We still set a timeout
2343 	 * in case further instances are being added later on.
2344 	 *
2345 	 * If the remaining lifetime of the instance is more than the duration
2346 	 * then the timeout corresponds to the duration, otherwise it will be
2347 	 * reduced to the remaining instance lifetime.
2348 	 */
2349 	if (adv->timeout == 0 || adv->duration <= adv->remaining_time)
2350 		timeout = adv->duration;
2351 	else
2352 		timeout = adv->remaining_time;
2353 
2354 	/* The remaining time is being reduced unless the instance is being
2355 	 * advertised without time limit.
2356 	 */
2357 	if (adv->timeout)
2358 		adv->remaining_time = adv->remaining_time - timeout;
2359 
2360 	/* Only use work for scheduling instances with legacy advertising */
2361 	if (!ext_adv_capable(hdev)) {
2362 		hdev->adv_instance_timeout = true;
2363 		queue_delayed_work(hdev->req_workqueue,
2364 				   &hdev->adv_instance_expire,
2365 				   adv->mesh ? msecs_to_jiffies(timeout) :
2366 					       secs_to_jiffies(timeout));
2367 	}
2368 
2369 	hci_dev_unlock(hdev);
2370 
2371 	/* If we're just re-scheduling the same instance again then do not
2372 	 * execute any HCI commands. This happens when a single instance is
2373 	 * being advertised.
2374 	 */
2375 	if (!force && hdev->cur_adv_instance == instance &&
2376 	    hci_dev_test_flag(hdev, HCI_LE_ADV))
2377 		return 0;
2378 
2379 	hdev->cur_adv_instance = instance;
2380 
2381 	return hci_start_adv_sync(hdev, instance);
2382 }
2383 
2384 static int hci_clear_adv_sets_sync(struct hci_dev *hdev, struct sock *sk)
2385 {
2386 	int err;
2387 
2388 	if (!ext_adv_capable(hdev))
2389 		return 0;
2390 
2391 	/* Disable instance 0x00 to disable all instances */
2392 	err = hci_disable_ext_adv_instance_sync(hdev, 0x00);
2393 	if (err)
2394 		return err;
2395 
2396 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_CLEAR_ADV_SETS,
2397 					0, NULL, 0, HCI_CMD_TIMEOUT, sk);
2398 }
2399 
2400 static int hci_clear_adv_sync(struct hci_dev *hdev, struct sock *sk, bool force)
2401 {
2402 	struct adv_info *adv, *n;
2403 
2404 	if (ext_adv_capable(hdev))
2405 		/* Remove all existing sets */
2406 		return hci_clear_adv_sets_sync(hdev, sk);
2407 
2408 	/* This is safe as long as there is no command send while the lock is
2409 	 * held.
2410 	 */
2411 	hci_dev_lock(hdev);
2412 
2413 	/* Cleanup non-ext instances */
2414 	list_for_each_entry_safe(adv, n, &hdev->adv_instances, list) {
2415 		u8 instance = adv->instance;
2416 		int err;
2417 
2418 		if (!(force || adv->timeout))
2419 			continue;
2420 
2421 		err = hci_remove_adv_instance(hdev, instance);
2422 		if (!err)
2423 			mgmt_advertising_removed(sk, hdev, instance);
2424 	}
2425 
2426 	hci_dev_unlock(hdev);
2427 
2428 	return 0;
2429 }
2430 
2431 static int hci_remove_adv_sync(struct hci_dev *hdev, u8 instance,
2432 			       struct sock *sk)
2433 {
2434 	int err;
2435 
2436 	/* If we use extended advertising, instance has to be removed first. */
2437 	if (ext_adv_capable(hdev))
2438 		return hci_remove_ext_adv_instance_sync(hdev, instance, sk);
2439 
2440 	/* This is safe as long as there is no command send while the lock is
2441 	 * held.
2442 	 */
2443 	hci_dev_lock(hdev);
2444 
2445 	err = hci_remove_adv_instance(hdev, instance);
2446 	if (!err)
2447 		mgmt_advertising_removed(sk, hdev, instance);
2448 
2449 	hci_dev_unlock(hdev);
2450 
2451 	return err;
2452 }
2453 
2454 /* For a single instance:
2455  * - force == true: The instance will be removed even when its remaining
2456  *   lifetime is not zero.
2457  * - force == false: the instance will be deactivated but kept stored unless
2458  *   the remaining lifetime is zero.
2459  *
2460  * For instance == 0x00:
2461  * - force == true: All instances will be removed regardless of their timeout
2462  *   setting.
2463  * - force == false: Only instances that have a timeout will be removed.
2464  */
2465 int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk,
2466 				u8 instance, bool force)
2467 {
2468 	u8 next_instance = 0;
2469 	int err;
2470 
2471 	/* Cancel any timeout concerning the removed instance(s). */
2472 	if (!instance || hdev->cur_adv_instance == instance)
2473 		cancel_adv_timeout(hdev);
2474 
2475 	/* Get the next instance to advertise BEFORE we remove
2476 	 * the current one. This can be the same instance again
2477 	 * if there is only one instance.
2478 	 */
2479 	if (hdev->cur_adv_instance == instance) {
2480 		struct adv_info *next;
2481 
2482 		hci_dev_lock(hdev);
2483 		next = hci_get_next_instance(hdev, instance);
2484 		if (next)
2485 			next_instance = next->instance;
2486 		hci_dev_unlock(hdev);
2487 	}
2488 
2489 	if (!instance) {
2490 		err = hci_clear_adv_sync(hdev, sk, force);
2491 		if (err)
2492 			return err;
2493 	} else {
2494 		struct adv_info *adv;
2495 		bool remove;
2496 
2497 		hci_dev_lock(hdev);
2498 		adv = hci_find_adv_instance(hdev, instance);
2499 		remove = force ||
2500 			 (adv && adv->timeout && !adv->remaining_time);
2501 		hci_dev_unlock(hdev);
2502 
2503 		if (remove) {
2504 			/* Don't advertise a removed instance. */
2505 			if (next_instance == instance)
2506 				next_instance = 0;
2507 
2508 			err = hci_remove_adv_sync(hdev, instance, sk);
2509 			if (err)
2510 				return err;
2511 		}
2512 	}
2513 
2514 	if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING))
2515 		return 0;
2516 
2517 	if (next_instance && !ext_adv_capable(hdev))
2518 		hci_schedule_adv_instance_sync(hdev, next_instance, false);
2519 
2520 	return 0;
2521 }
2522 
2523 int hci_read_rssi_sync(struct hci_dev *hdev, __le16 handle)
2524 {
2525 	struct hci_cp_read_rssi cp;
2526 
2527 	cp.handle = handle;
2528 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_RSSI,
2529 					sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2530 }
2531 
2532 int hci_read_clock_sync(struct hci_dev *hdev, struct hci_cp_read_clock *cp)
2533 {
2534 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_CLOCK,
2535 					sizeof(*cp), cp, HCI_CMD_TIMEOUT);
2536 }
2537 
2538 int hci_read_tx_power_sync(struct hci_dev *hdev, __le16 handle, u8 type)
2539 {
2540 	struct hci_cp_read_tx_power cp;
2541 
2542 	cp.handle = handle;
2543 	cp.type = type;
2544 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_TX_POWER,
2545 					sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2546 }
2547 
2548 int hci_disable_advertising_sync(struct hci_dev *hdev)
2549 {
2550 	u8 enable = 0x00;
2551 
2552 	/* If controller is not advertising we are done. */
2553 	if (!hci_dev_test_flag(hdev, HCI_LE_ADV))
2554 		return 0;
2555 
2556 	if (ext_adv_capable(hdev))
2557 		return hci_disable_ext_adv_instance_sync(hdev, 0x00);
2558 
2559 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_ENABLE,
2560 				     sizeof(enable), &enable, HCI_CMD_TIMEOUT);
2561 }
2562 
2563 static int hci_le_set_ext_scan_enable_sync(struct hci_dev *hdev, u8 val,
2564 					   u8 filter_dup)
2565 {
2566 	struct hci_cp_le_set_ext_scan_enable cp;
2567 
2568 	memset(&cp, 0, sizeof(cp));
2569 	cp.enable = val;
2570 
2571 	if (hci_dev_test_flag(hdev, HCI_MESH))
2572 		cp.filter_dup = LE_SCAN_FILTER_DUP_DISABLE;
2573 	else
2574 		cp.filter_dup = filter_dup;
2575 
2576 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_SCAN_ENABLE,
2577 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2578 }
2579 
2580 static int hci_le_set_scan_enable_sync(struct hci_dev *hdev, u8 val,
2581 				       u8 filter_dup)
2582 {
2583 	struct hci_cp_le_set_scan_enable cp;
2584 
2585 	if (use_ext_scan(hdev))
2586 		return hci_le_set_ext_scan_enable_sync(hdev, val, filter_dup);
2587 
2588 	memset(&cp, 0, sizeof(cp));
2589 	cp.enable = val;
2590 
2591 	if (val && hci_dev_test_flag(hdev, HCI_MESH))
2592 		cp.filter_dup = LE_SCAN_FILTER_DUP_DISABLE;
2593 	else
2594 		cp.filter_dup = filter_dup;
2595 
2596 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_SCAN_ENABLE,
2597 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2598 }
2599 
2600 static int hci_le_set_addr_resolution_enable_sync(struct hci_dev *hdev, u8 val)
2601 {
2602 	if (!ll_privacy_capable(hdev))
2603 		return 0;
2604 
2605 	/* If controller is not/already resolving we are done. */
2606 	if (val == hci_dev_test_flag(hdev, HCI_LL_RPA_RESOLUTION))
2607 		return 0;
2608 
2609 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADDR_RESOLV_ENABLE,
2610 				     sizeof(val), &val, HCI_CMD_TIMEOUT);
2611 }
2612 
2613 static int hci_scan_disable_sync(struct hci_dev *hdev)
2614 {
2615 	int err;
2616 
2617 	/* If controller is not scanning we are done. */
2618 	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN))
2619 		return 0;
2620 
2621 	if (hdev->scanning_paused) {
2622 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
2623 		return 0;
2624 	}
2625 
2626 	err = hci_le_set_scan_enable_sync(hdev, LE_SCAN_DISABLE, 0x00);
2627 	if (err) {
2628 		bt_dev_err(hdev, "Unable to disable scanning: %d", err);
2629 		return err;
2630 	}
2631 
2632 	return err;
2633 }
2634 
2635 static bool scan_use_rpa(struct hci_dev *hdev)
2636 {
2637 	return hci_dev_test_flag(hdev, HCI_PRIVACY);
2638 }
2639 
2640 static void hci_start_interleave_scan(struct hci_dev *hdev)
2641 {
2642 	hdev->interleave_scan_state = INTERLEAVE_SCAN_NO_FILTER;
2643 	queue_delayed_work(hdev->req_workqueue,
2644 			   &hdev->interleave_scan, 0);
2645 }
2646 
2647 static void cancel_interleave_scan(struct hci_dev *hdev)
2648 {
2649 	bt_dev_dbg(hdev, "cancelling interleave scan");
2650 
2651 	cancel_delayed_work_sync(&hdev->interleave_scan);
2652 
2653 	hdev->interleave_scan_state = INTERLEAVE_SCAN_NONE;
2654 }
2655 
2656 /* Return true if interleave_scan wasn't started until exiting this function,
2657  * otherwise, return false
2658  */
2659 static bool hci_update_interleaved_scan_sync(struct hci_dev *hdev)
2660 {
2661 	/* Do interleaved scan only if all of the following are true:
2662 	 * - There is at least one ADV monitor
2663 	 * - At least one pending LE connection or one device to be scanned for
2664 	 * - Monitor offloading is not supported
2665 	 * If so, we should alternate between allowlist scan and one without
2666 	 * any filters to save power.
2667 	 */
2668 	bool use_interleaving = hci_is_adv_monitoring(hdev) &&
2669 				!(list_empty(&hdev->pend_le_conns) &&
2670 				  list_empty(&hdev->pend_le_reports)) &&
2671 				hci_get_adv_monitor_offload_ext(hdev) ==
2672 				    HCI_ADV_MONITOR_EXT_NONE;
2673 	bool is_interleaving = is_interleave_scanning(hdev);
2674 
2675 	if (use_interleaving && !is_interleaving) {
2676 		hci_start_interleave_scan(hdev);
2677 		bt_dev_dbg(hdev, "starting interleave scan");
2678 		return true;
2679 	}
2680 
2681 	if (!use_interleaving && is_interleaving)
2682 		cancel_interleave_scan(hdev);
2683 
2684 	return false;
2685 }
2686 
2687 /* Removes connection to resolve list if needed.*/
2688 static int hci_le_del_resolve_list_sync(struct hci_dev *hdev,
2689 					bdaddr_t *bdaddr, u8 bdaddr_type)
2690 {
2691 	struct hci_cp_le_del_from_resolv_list cp;
2692 	bool exists;
2693 
2694 	if (!ll_privacy_capable(hdev))
2695 		return 0;
2696 
2697 	/* Check if the IRK has been programmed */
2698 	hci_dev_lock(hdev);
2699 	exists = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list,
2700 						 bdaddr, bdaddr_type);
2701 	hci_dev_unlock(hdev);
2702 	if (!exists)
2703 		return 0;
2704 
2705 	cp.bdaddr_type = bdaddr_type;
2706 	bacpy(&cp.bdaddr, bdaddr);
2707 
2708 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_DEL_FROM_RESOLV_LIST,
2709 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2710 }
2711 
2712 static int hci_le_del_accept_list_sync(struct hci_dev *hdev,
2713 				       bdaddr_t *bdaddr, u8 bdaddr_type)
2714 {
2715 	struct hci_cp_le_del_from_accept_list cp;
2716 	int err;
2717 
2718 	/* Check if device is on accept list before removing it */
2719 	if (!hci_bdaddr_list_lookup(&hdev->le_accept_list, bdaddr, bdaddr_type))
2720 		return 0;
2721 
2722 	cp.bdaddr_type = bdaddr_type;
2723 	bacpy(&cp.bdaddr, bdaddr);
2724 
2725 	/* Ignore errors when removing from resolving list as that is likely
2726 	 * that the device was never added.
2727 	 */
2728 	hci_le_del_resolve_list_sync(hdev, &cp.bdaddr, cp.bdaddr_type);
2729 
2730 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_DEL_FROM_ACCEPT_LIST,
2731 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2732 	if (err) {
2733 		bt_dev_err(hdev, "Unable to remove from allow list: %d", err);
2734 		return err;
2735 	}
2736 
2737 	bt_dev_dbg(hdev, "Remove %pMR (0x%x) from allow list", &cp.bdaddr,
2738 		   cp.bdaddr_type);
2739 
2740 	return 0;
2741 }
2742 
2743 struct conn_params {
2744 	bdaddr_t addr;
2745 	u8 addr_type;
2746 	hci_conn_flags_t flags;
2747 	u8 privacy_mode;
2748 };
2749 
2750 /* Adds connection to resolve list if needed.
2751  * Setting params to NULL programs local hdev->irk
2752  */
2753 static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,
2754 					struct conn_params *params)
2755 {
2756 	struct hci_cp_le_add_to_resolv_list cp;
2757 	struct smp_irk *irk;
2758 	struct hci_conn_params *p;
2759 	bool exists;
2760 
2761 	if (!ll_privacy_capable(hdev))
2762 		return 0;
2763 
2764 	/* Attempt to program local identity address, type and irk if params is
2765 	 * NULL.
2766 	 */
2767 	if (!params) {
2768 		if (!hci_dev_test_flag(hdev, HCI_PRIVACY))
2769 			return 0;
2770 
2771 		hci_copy_identity_address(hdev, &cp.bdaddr, &cp.bdaddr_type);
2772 		memcpy(cp.peer_irk, hdev->irk, 16);
2773 		goto done;
2774 	} else if (!(params->flags & HCI_CONN_FLAG_ADDRESS_RESOLUTION))
2775 		return 0;
2776 
2777 	rcu_read_lock();
2778 
2779 	irk = hci_find_irk_by_addr(hdev, &params->addr, params->addr_type);
2780 	if (!irk) {
2781 		rcu_read_unlock();
2782 		return 0;
2783 	}
2784 
2785 	memcpy(cp.peer_irk, irk->val, 16);
2786 
2787 	rcu_read_unlock();
2788 
2789 	/* Check if the IK has _not_ been programmed yet. */
2790 	hci_dev_lock(hdev);
2791 	exists = hci_bdaddr_list_lookup_with_irk(
2792 		&hdev->le_resolv_list, &params->addr, params->addr_type);
2793 	hci_dev_unlock(hdev);
2794 	if (exists)
2795 		return 0;
2796 
2797 	cp.bdaddr_type = params->addr_type;
2798 	bacpy(&cp.bdaddr, &params->addr);
2799 
2800 	/* Default privacy mode is always Network */
2801 	params->privacy_mode = HCI_NETWORK_PRIVACY;
2802 
2803 	rcu_read_lock();
2804 	p = hci_pend_le_action_lookup(&hdev->pend_le_conns,
2805 				      &params->addr, params->addr_type);
2806 	if (!p)
2807 		p = hci_pend_le_action_lookup(&hdev->pend_le_reports,
2808 					      &params->addr, params->addr_type);
2809 	if (p)
2810 		WRITE_ONCE(p->privacy_mode, HCI_NETWORK_PRIVACY);
2811 	rcu_read_unlock();
2812 
2813 done:
2814 	if (hci_dev_test_flag(hdev, HCI_PRIVACY))
2815 		memcpy(cp.local_irk, hdev->irk, 16);
2816 	else
2817 		memset(cp.local_irk, 0, 16);
2818 
2819 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_ADD_TO_RESOLV_LIST,
2820 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2821 }
2822 
2823 /* Set Device Privacy Mode. */
2824 static int hci_le_set_privacy_mode_sync(struct hci_dev *hdev,
2825 					struct conn_params *params)
2826 {
2827 	struct hci_cp_le_set_privacy_mode cp;
2828 	struct smp_irk *irk;
2829 
2830 	if (!ll_privacy_capable(hdev) ||
2831 	    !(params->flags & HCI_CONN_FLAG_ADDRESS_RESOLUTION))
2832 		return 0;
2833 
2834 	/* If device privacy mode has already been set there is nothing to do */
2835 	if (params->privacy_mode == HCI_DEVICE_PRIVACY)
2836 		return 0;
2837 
2838 	/* Check if HCI_CONN_FLAG_DEVICE_PRIVACY has been set as it also
2839 	 * indicates that LL Privacy has been enabled and
2840 	 * HCI_OP_LE_SET_PRIVACY_MODE is supported.
2841 	 */
2842 	if (!(params->flags & HCI_CONN_FLAG_DEVICE_PRIVACY))
2843 		return 0;
2844 
2845 	rcu_read_lock();
2846 
2847 	irk = hci_find_irk_by_addr(hdev, &params->addr, params->addr_type);
2848 	if (!irk) {
2849 		rcu_read_unlock();
2850 		return 0;
2851 	}
2852 
2853 	memset(&cp, 0, sizeof(cp));
2854 	cp.bdaddr_type = irk->addr_type;
2855 	bacpy(&cp.bdaddr, &irk->bdaddr);
2856 	rcu_read_unlock();
2857 
2858 	cp.mode = HCI_DEVICE_PRIVACY;
2859 
2860 	/* Note: params->privacy_mode is not updated since it is a copy */
2861 
2862 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PRIVACY_MODE,
2863 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2864 }
2865 
2866 /* Adds connection to allow list if needed, if the device uses RPA (has IRK)
2867  * this attempts to program the device in the resolving list as well and
2868  * properly set the privacy mode.
2869  */
2870 static int hci_le_add_accept_list_sync(struct hci_dev *hdev,
2871 				       struct conn_params *params,
2872 				       u8 *num_entries, bool force_filter)
2873 {
2874 	struct hci_cp_le_add_to_accept_list cp;
2875 	int err;
2876 
2877 	/* During suspend, only wakeable devices can be in acceptlist */
2878 	if (hdev->suspended &&
2879 	    !(params->flags & HCI_CONN_FLAG_REMOTE_WAKEUP)) {
2880 		hci_le_del_accept_list_sync(hdev, &params->addr,
2881 					    params->addr_type);
2882 		return 0;
2883 	}
2884 
2885 	/* Host-resolved peers need unfiltered scanning while awake. */
2886 	if (!force_filter && !hdev->suspended && !ll_privacy_capable(hdev) &&
2887 	    hci_find_irk_by_addr(hdev, &params->addr, params->addr_type))
2888 		return -EINVAL;
2889 
2890 	/* Select filter policy to accept all advertising */
2891 	if (*num_entries >= hdev->le_accept_list_size)
2892 		return -ENOSPC;
2893 
2894 	/* Attempt to program the device in the resolving list first to avoid
2895 	 * having to rollback in case it fails since the resolving list is
2896 	 * dynamic it can probably be smaller than the accept list.
2897 	 */
2898 	err = hci_le_add_resolve_list_sync(hdev, params);
2899 	if (err) {
2900 		bt_dev_err(hdev, "Unable to add to resolve list: %d", err);
2901 		return err;
2902 	}
2903 
2904 	/* Set Privacy Mode */
2905 	err = hci_le_set_privacy_mode_sync(hdev, params);
2906 	if (err) {
2907 		bt_dev_err(hdev, "Unable to set privacy mode: %d", err);
2908 		return err;
2909 	}
2910 
2911 	/* Check if already in accept list */
2912 	if (hci_bdaddr_list_lookup(&hdev->le_accept_list, &params->addr,
2913 				   params->addr_type))
2914 		return 0;
2915 
2916 	*num_entries += 1;
2917 	cp.bdaddr_type = params->addr_type;
2918 	bacpy(&cp.bdaddr, &params->addr);
2919 
2920 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_ADD_TO_ACCEPT_LIST,
2921 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2922 	if (err) {
2923 		bt_dev_err(hdev, "Unable to add to allow list: %d", err);
2924 		/* Rollback the device from the resolving list */
2925 		hci_le_del_resolve_list_sync(hdev, &cp.bdaddr, cp.bdaddr_type);
2926 		return err;
2927 	}
2928 
2929 	bt_dev_dbg(hdev, "Add %pMR (0x%x) to allow list", &cp.bdaddr,
2930 		   cp.bdaddr_type);
2931 
2932 	return 0;
2933 }
2934 
2935 /* This function disables/pause all advertising instances */
2936 static int hci_pause_advertising_sync(struct hci_dev *hdev)
2937 {
2938 	int err;
2939 	int old_state;
2940 
2941 	/* If controller is not advertising we are done. */
2942 	if (!hci_dev_test_flag(hdev, HCI_LE_ADV))
2943 		return 0;
2944 
2945 	/* If already been paused there is nothing to do. */
2946 	if (hdev->advertising_paused)
2947 		return 0;
2948 
2949 	bt_dev_dbg(hdev, "Pausing directed advertising");
2950 
2951 	/* Stop directed advertising */
2952 	old_state = hci_dev_test_flag(hdev, HCI_ADVERTISING);
2953 	if (old_state) {
2954 		/* When discoverable timeout triggers, then just make sure
2955 		 * the limited discoverable flag is cleared. Even in the case
2956 		 * of a timeout triggered from general discoverable, it is
2957 		 * safe to unconditionally clear the flag.
2958 		 */
2959 		hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
2960 		hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
2961 		hdev->discov_timeout = 0;
2962 	}
2963 
2964 	bt_dev_dbg(hdev, "Pausing advertising instances");
2965 
2966 	/* Call to disable any advertisements active on the controller.
2967 	 * This will succeed even if no advertisements are configured.
2968 	 */
2969 	err = hci_disable_advertising_sync(hdev);
2970 	if (err)
2971 		return err;
2972 
2973 	/* If we are using software rotation, pause the loop */
2974 	if (!ext_adv_capable(hdev))
2975 		cancel_adv_timeout(hdev);
2976 
2977 	hdev->advertising_paused = true;
2978 	hdev->advertising_old_state = old_state;
2979 
2980 	return 0;
2981 }
2982 
2983 /* Copy the instance identifiers in list order under hdev->lock.
2984  * There are at most U8_MAX instances, with identifiers 1..U8_MAX.
2985  * Callers can then wait for commands without retaining list pointers.
2986  */
2987 static size_t adv_instance_list_copy(struct hci_dev *hdev, u8 *ids)
2988 {
2989 	struct adv_info *adv;
2990 	size_t n = 0;
2991 
2992 	hci_dev_lock(hdev);
2993 
2994 	list_for_each_entry(adv, &hdev->adv_instances, list)
2995 		ids[n++] = adv->instance;
2996 
2997 	hci_dev_unlock(hdev);
2998 
2999 	return n;
3000 }
3001 
3002 /* This function enables all user advertising instances */
3003 static int hci_resume_advertising_sync(struct hci_dev *hdev)
3004 {
3005 	int err = 0;
3006 
3007 	/* If advertising has not been paused there is nothing  to do. */
3008 	if (!hdev->advertising_paused)
3009 		return 0;
3010 
3011 	/* Resume directed advertising */
3012 	hdev->advertising_paused = false;
3013 	if (hdev->advertising_old_state) {
3014 		hci_dev_set_flag(hdev, HCI_ADVERTISING);
3015 		hdev->advertising_old_state = 0;
3016 	}
3017 
3018 	bt_dev_dbg(hdev, "Resuming advertising instances");
3019 
3020 	if (ext_adv_capable(hdev)) {
3021 		u8 ids[U8_MAX];
3022 		size_t i, n;
3023 
3024 		n = adv_instance_list_copy(hdev, ids);
3025 
3026 		/* Call for each tracked instance to be re-enabled */
3027 		for (i = 0; i < n; i++) {
3028 			err = hci_enable_ext_advertising_sync(hdev,
3029 							      ids[i]);
3030 			if (!err)
3031 				continue;
3032 
3033 			/* If the instance cannot be resumed remove it */
3034 			hci_remove_ext_adv_instance_sync(hdev, ids[i],
3035 							 NULL);
3036 		}
3037 
3038 		/* If current advertising instance is set to instance 0x00
3039 		 * then we need to re-enable it.
3040 		 */
3041 		if (hci_dev_test_and_clear_flag(hdev, HCI_LE_ADV_0))
3042 			err = hci_enable_ext_advertising_sync(hdev, 0x00);
3043 	} else if (hdev->cur_adv_instance) {
3044 		/* Schedule for most recent instance to be restarted and begin
3045 		 * the software rotation loop
3046 		 */
3047 		err = hci_schedule_adv_instance_sync(hdev,
3048 						     hdev->cur_adv_instance,
3049 						     true);
3050 	} else if (hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
3051 		   !hci_dev_test_flag(hdev, HCI_LE_ADV)) {
3052 		/* hci_schedule_adv_instance_sync() rejects instance 0x00 while
3053 		 * HCI_ADVERTISING is set, so enable it directly.
3054 		 */
3055 		err = hci_start_adv_sync(hdev, 0x00);
3056 	}
3057 
3058 	hdev->advertising_paused = false;
3059 
3060 	return err;
3061 }
3062 
3063 static int hci_pause_addr_resolution(struct hci_dev *hdev)
3064 {
3065 	int err;
3066 
3067 	if (!ll_privacy_capable(hdev))
3068 		return 0;
3069 
3070 	if (!hci_dev_test_flag(hdev, HCI_LL_RPA_RESOLUTION))
3071 		return 0;
3072 
3073 	/* Cannot disable addr resolution if scanning is enabled or
3074 	 * when initiating an LE connection.
3075 	 */
3076 	rcu_read_lock();
3077 
3078 	if (hci_dev_test_flag(hdev, HCI_LE_SCAN) ||
3079 	    hci_lookup_le_connect(hdev)) {
3080 		rcu_read_unlock();
3081 		bt_dev_err(hdev, "Command not allowed when scan/LE connect");
3082 		return -EPERM;
3083 	}
3084 
3085 	rcu_read_unlock();
3086 
3087 	/* Cannot disable addr resolution if advertising is enabled. */
3088 	err = hci_pause_advertising_sync(hdev);
3089 	if (err) {
3090 		bt_dev_err(hdev, "Pause advertising failed: %d", err);
3091 		return err;
3092 	}
3093 
3094 	err = hci_le_set_addr_resolution_enable_sync(hdev, 0x00);
3095 	if (err)
3096 		bt_dev_err(hdev, "Unable to disable Address Resolution: %d",
3097 			   err);
3098 
3099 	/* Return if address resolution is disabled and RPA is not used. */
3100 	if (!err && scan_use_rpa(hdev))
3101 		return 0;
3102 
3103 	hci_resume_advertising_sync(hdev);
3104 	return err;
3105 }
3106 
3107 struct sk_buff *hci_read_local_oob_data_sync(struct hci_dev *hdev,
3108 					     bool extended, struct sock *sk)
3109 {
3110 	u16 opcode = extended ? HCI_OP_READ_LOCAL_OOB_EXT_DATA :
3111 					HCI_OP_READ_LOCAL_OOB_DATA;
3112 
3113 	return __hci_cmd_sync_sk(hdev, opcode, 0, NULL, 0, HCI_CMD_TIMEOUT, sk);
3114 }
3115 
3116 static struct conn_params *conn_params_copy(struct list_head *list, size_t *n)
3117 {
3118 	struct hci_conn_params *params;
3119 	struct conn_params *p;
3120 	size_t i;
3121 
3122 	rcu_read_lock();
3123 
3124 	i = 0;
3125 	list_for_each_entry_rcu(params, list, action)
3126 		++i;
3127 	*n = i;
3128 
3129 	rcu_read_unlock();
3130 
3131 	p = kvzalloc_objs(struct conn_params, *n);
3132 	if (!p)
3133 		return NULL;
3134 
3135 	rcu_read_lock();
3136 
3137 	i = 0;
3138 	list_for_each_entry_rcu(params, list, action) {
3139 		/* Racing adds are handled in next scan update */
3140 		if (i >= *n)
3141 			break;
3142 
3143 		/* No hdev->lock, but: addr, addr_type are immutable.
3144 		 * privacy_mode is only written by us or in
3145 		 * hci_cc_le_set_privacy_mode that we wait for.
3146 		 * We should be idempotent so MGMT updating flags
3147 		 * while we are processing is OK.
3148 		 */
3149 		bacpy(&p[i].addr, &params->addr);
3150 		p[i].addr_type = params->addr_type;
3151 		p[i].flags = READ_ONCE(params->flags);
3152 		p[i].privacy_mode = READ_ONCE(params->privacy_mode);
3153 		++i;
3154 	}
3155 
3156 	rcu_read_unlock();
3157 
3158 	*n = i;
3159 	return p;
3160 }
3161 
3162 static struct conn_params *le_accept_list_copy(struct hci_dev *hdev,
3163 					       size_t *n)
3164 {
3165 	struct bdaddr_list *entry;
3166 	struct conn_params *params;
3167 	size_t i = 0;
3168 
3169 	hci_dev_lock(hdev);
3170 
3171 	*n = list_count_nodes(&hdev->le_accept_list);
3172 	params = kvzalloc_objs(struct conn_params, *n);
3173 	if (!params)
3174 		goto unlock;
3175 
3176 	list_for_each_entry(entry, &hdev->le_accept_list, list) {
3177 		bacpy(&params[i].addr, &entry->bdaddr);
3178 		params[i].addr_type = entry->bdaddr_type;
3179 		i++;
3180 	}
3181 
3182 unlock:
3183 	hci_dev_unlock(hdev);
3184 	return params;
3185 }
3186 
3187 /* Clear LE Accept List */
3188 static int hci_le_clear_accept_list_sync(struct hci_dev *hdev)
3189 {
3190 	if (!(hdev->commands[26] & 0x80))
3191 		return 0;
3192 
3193 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CLEAR_ACCEPT_LIST, 0, NULL,
3194 				     HCI_CMD_TIMEOUT);
3195 }
3196 
3197 /* Device must not be scanning when updating the accept list.
3198  *
3199  * Update is done using the following sequence:
3200  *
3201  * ll_privacy_capable((Disable Advertising) -> Disable Resolving List) ->
3202  * Remove Devices From Accept List ->
3203  * (has IRK && ll_privacy_capable(Remove Devices From Resolving List))->
3204  * Add Devices to Accept List ->
3205  * (has IRK && ll_privacy_capable(Remove Devices From Resolving List)) ->
3206  * ll_privacy_capable(Enable Resolving List -> (Enable Advertising)) ->
3207  * Enable Scanning
3208  *
3209  * In case of failure advertising shall be restored to its original state and
3210  * return would disable accept list since either accept or resolving list could
3211  * not be programmed.
3212  *
3213  */
3214 static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
3215 {
3216 	struct conn_params *params;
3217 	u8 num_entries = 0;
3218 	bool pend_conn, pend_report;
3219 	u8 filter_policy;
3220 	size_t i, n;
3221 	int err;
3222 
3223 	/* Pause advertising if resolving list can be used as controllers
3224 	 * cannot accept resolving list modifications while advertising.
3225 	 */
3226 	if (ll_privacy_capable(hdev)) {
3227 		err = hci_pause_advertising_sync(hdev);
3228 		if (err) {
3229 			bt_dev_err(hdev, "pause advertising failed: %d", err);
3230 			return 0x00;
3231 		}
3232 	}
3233 
3234 	/* Disable address resolution while reprogramming accept list since
3235 	 * devices that do have an IRK will be programmed in the resolving list
3236 	 * when LL Privacy is enabled.
3237 	 */
3238 	err = hci_le_set_addr_resolution_enable_sync(hdev, 0x00);
3239 	if (err) {
3240 		bt_dev_err(hdev, "Unable to disable LL privacy: %d", err);
3241 		goto done;
3242 	}
3243 
3244 	/* Force address filtering if PA Sync is in progress */
3245 	if (hci_dev_test_flag(hdev, HCI_PA_SYNC)) {
3246 		struct hci_conn *conn;
3247 
3248 		rcu_read_lock();
3249 
3250 		conn = hci_conn_hash_lookup_create_pa_sync(hdev);
3251 		if (conn) {
3252 			struct conn_params pa;
3253 
3254 			memset(&pa, 0, sizeof(pa));
3255 
3256 			bacpy(&pa.addr, &conn->dst);
3257 			pa.addr_type = conn->dst_type;
3258 
3259 			rcu_read_unlock();
3260 
3261 			/* Clear first since there could be addresses left
3262 			 * behind.
3263 			 */
3264 			hci_le_clear_accept_list_sync(hdev);
3265 
3266 			num_entries = 1;
3267 			err = hci_le_add_accept_list_sync(hdev, &pa,
3268 							  &num_entries, true);
3269 			goto done;
3270 		} else {
3271 			rcu_read_unlock();
3272 		}
3273 	}
3274 
3275 	/* Go through the current accept list programmed into the
3276 	 * controller one by one and check if that address is connected or is
3277 	 * still in the list of pending connections or list of devices to
3278 	 * report. If not present in either list, then remove it from
3279 	 * the controller.
3280 	 */
3281 	params = le_accept_list_copy(hdev, &n);
3282 	if (!params) {
3283 		err = -ENOMEM;
3284 		goto done;
3285 	}
3286 
3287 	for (i = 0; i < n; i++) {
3288 		rcu_read_lock();
3289 
3290 		if (hci_conn_hash_lookup_le(hdev, &params[i].addr,
3291 					    params[i].addr_type)) {
3292 			rcu_read_unlock();
3293 			continue;
3294 		}
3295 
3296 		pend_conn = hci_pend_le_action_lookup(&hdev->pend_le_conns,
3297 						      &params[i].addr,
3298 						      params[i].addr_type);
3299 		pend_report = hci_pend_le_action_lookup(
3300 			&hdev->pend_le_reports, &params[i].addr,
3301 			params[i].addr_type);
3302 
3303 		rcu_read_unlock();
3304 
3305 		/* If the device is not likely to connect or report,
3306 		 * remove it from the acceptlist.
3307 		 */
3308 		if (!pend_conn && !pend_report) {
3309 			hci_le_del_accept_list_sync(hdev, &params[i].addr,
3310 						    params[i].addr_type);
3311 			continue;
3312 		}
3313 
3314 		num_entries++;
3315 	}
3316 
3317 	kvfree(params);
3318 
3319 	/* Since all no longer valid accept list entries have been
3320 	 * removed, walk through the list of pending connections
3321 	 * and ensure that any new device gets programmed into
3322 	 * the controller.
3323 	 *
3324 	 * If the list of the devices is larger than the list of
3325 	 * available accept list entries in the controller, then
3326 	 * just abort and return filer policy value to not use the
3327 	 * accept list.
3328 	 *
3329 	 * The list and params may be mutated while we wait for events,
3330 	 * so make a copy and iterate it.
3331 	 */
3332 
3333 	params = conn_params_copy(&hdev->pend_le_conns, &n);
3334 	if (!params) {
3335 		err = -ENOMEM;
3336 		goto done;
3337 	}
3338 
3339 	for (i = 0; i < n; ++i) {
3340 		err = hci_le_add_accept_list_sync(hdev, &params[i],
3341 								&num_entries, false);
3342 		if (err) {
3343 			kvfree(params);
3344 			goto done;
3345 		}
3346 	}
3347 
3348 	kvfree(params);
3349 
3350 	/* After adding all new pending connections, walk through
3351 	 * the list of pending reports and also add these to the
3352 	 * accept list if there is still space. Abort if space runs out.
3353 	 */
3354 
3355 	params = conn_params_copy(&hdev->pend_le_reports, &n);
3356 	if (!params) {
3357 		err = -ENOMEM;
3358 		goto done;
3359 	}
3360 
3361 	for (i = 0; i < n; ++i) {
3362 		err = hci_le_add_accept_list_sync(hdev, &params[i],
3363 								&num_entries, false);
3364 		if (err) {
3365 			kvfree(params);
3366 			goto done;
3367 		}
3368 	}
3369 
3370 	kvfree(params);
3371 
3372 	/* Use the allowlist unless the following conditions are all true:
3373 	 * - We are not currently suspending
3374 	 * - There are 1 or more ADV monitors registered and it's not offloaded
3375 	 * - Interleaved scanning is not currently using the allowlist
3376 	 */
3377 	if (!idr_is_empty(&hdev->adv_monitors_idr) && !hdev->suspended &&
3378 	    hci_get_adv_monitor_offload_ext(hdev) == HCI_ADV_MONITOR_EXT_NONE &&
3379 	    hdev->interleave_scan_state != INTERLEAVE_SCAN_ALLOWLIST)
3380 		err = -EINVAL;
3381 
3382 done:
3383 	filter_policy = err ? 0x00 : 0x01;
3384 
3385 	/* Enable address resolution when LL Privacy is enabled. */
3386 	err = hci_le_set_addr_resolution_enable_sync(hdev, 0x01);
3387 	if (err)
3388 		bt_dev_err(hdev, "Unable to enable LL privacy: %d", err);
3389 
3390 	/* Resume advertising if it was paused */
3391 	if (ll_privacy_capable(hdev))
3392 		hci_resume_advertising_sync(hdev);
3393 
3394 	/* Select filter policy to use accept list */
3395 	return filter_policy;
3396 }
3397 
3398 static void hci_le_scan_phy_params(struct hci_cp_le_scan_phy_params *cp,
3399 				   u8 type, u16 interval, u16 window)
3400 {
3401 	cp->type = type;
3402 	cp->interval = cpu_to_le16(interval);
3403 	cp->window = cpu_to_le16(window);
3404 }
3405 
3406 static int hci_le_set_ext_scan_param_sync(struct hci_dev *hdev, u8 type,
3407 					  u16 interval, u16 window,
3408 					  u8 own_addr_type, u8 filter_policy)
3409 {
3410 	struct hci_cp_le_set_ext_scan_params *cp;
3411 	struct hci_cp_le_scan_phy_params *phy;
3412 	u8 data[sizeof(*cp) + sizeof(*phy) * 2];
3413 	u8 num_phy = 0x00;
3414 
3415 	cp = (void *)data;
3416 	phy = (void *)cp->data;
3417 
3418 	memset(data, 0, sizeof(data));
3419 
3420 	cp->own_addr_type = own_addr_type;
3421 	cp->filter_policy = filter_policy;
3422 
3423 	/* Check if PA Sync is in progress then select the PHY based on the
3424 	 * hci_conn.iso_qos.
3425 	 */
3426 	if (hci_dev_test_flag(hdev, HCI_PA_SYNC)) {
3427 		struct hci_cp_le_add_to_accept_list *sent;
3428 		bdaddr_t bdaddr;
3429 
3430 		hci_dev_lock(hdev);
3431 		sent = hci_sent_cmd_data(hdev, HCI_OP_LE_ADD_TO_ACCEPT_LIST);
3432 		if (sent)
3433 			bacpy(&bdaddr, &sent->bdaddr);
3434 		hci_dev_unlock(hdev);
3435 
3436 		if (sent) {
3437 			struct hci_conn *conn;
3438 
3439 			rcu_read_lock();
3440 
3441 			conn = hci_conn_hash_lookup_ba(hdev, PA_LINK,
3442 						       &bdaddr);
3443 			if (conn) {
3444 				struct bt_iso_qos *qos = &conn->iso_qos;
3445 
3446 				if (qos->bcast.in.phys & BT_ISO_PHY_1M ||
3447 				    qos->bcast.in.phys & BT_ISO_PHY_2M) {
3448 					cp->scanning_phys |= LE_SCAN_PHY_1M;
3449 					hci_le_scan_phy_params(phy, type,
3450 							       interval,
3451 							       window);
3452 					num_phy++;
3453 					phy++;
3454 				}
3455 
3456 				if (qos->bcast.in.phys & BT_ISO_PHY_CODED) {
3457 					cp->scanning_phys |= LE_SCAN_PHY_CODED;
3458 					hci_le_scan_phy_params(phy, type,
3459 							       interval * 3,
3460 							       window * 3);
3461 					num_phy++;
3462 					phy++;
3463 				}
3464 
3465 				rcu_read_unlock();
3466 
3467 				if (num_phy)
3468 					goto done;
3469 			} else {
3470 				rcu_read_unlock();
3471 			}
3472 		}
3473 	}
3474 
3475 	if (scan_1m(hdev) || scan_2m(hdev)) {
3476 		cp->scanning_phys |= LE_SCAN_PHY_1M;
3477 		hci_le_scan_phy_params(phy, type, interval, window);
3478 		num_phy++;
3479 		phy++;
3480 	}
3481 
3482 	if (scan_coded(hdev)) {
3483 		cp->scanning_phys |= LE_SCAN_PHY_CODED;
3484 		hci_le_scan_phy_params(phy, type, interval * 3, window * 3);
3485 		num_phy++;
3486 		phy++;
3487 	}
3488 
3489 done:
3490 	if (!num_phy)
3491 		return -EINVAL;
3492 
3493 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_SCAN_PARAMS,
3494 				     sizeof(*cp) + sizeof(*phy) * num_phy,
3495 				     data, HCI_CMD_TIMEOUT);
3496 }
3497 
3498 static int hci_le_set_scan_param_sync(struct hci_dev *hdev, u8 type,
3499 				      u16 interval, u16 window,
3500 				      u8 own_addr_type, u8 filter_policy)
3501 {
3502 	struct hci_cp_le_set_scan_param cp;
3503 
3504 	if (use_ext_scan(hdev))
3505 		return hci_le_set_ext_scan_param_sync(hdev, type, interval,
3506 						      window, own_addr_type,
3507 						      filter_policy);
3508 
3509 	memset(&cp, 0, sizeof(cp));
3510 	cp.type = type;
3511 	cp.interval = cpu_to_le16(interval);
3512 	cp.window = cpu_to_le16(window);
3513 	cp.own_address_type = own_addr_type;
3514 	cp.filter_policy = filter_policy;
3515 
3516 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_SCAN_PARAM,
3517 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3518 }
3519 
3520 static int hci_start_scan_sync(struct hci_dev *hdev, u8 type, u16 interval,
3521 			       u16 window, u8 own_addr_type, u8 filter_policy,
3522 			       u8 filter_dup)
3523 {
3524 	int err;
3525 
3526 	if (hdev->scanning_paused) {
3527 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
3528 		return 0;
3529 	}
3530 
3531 	err = hci_le_set_scan_param_sync(hdev, type, interval, window,
3532 					 own_addr_type, filter_policy);
3533 	if (err)
3534 		return err;
3535 
3536 	return hci_le_set_scan_enable_sync(hdev, LE_SCAN_ENABLE, filter_dup);
3537 }
3538 
3539 static int hci_passive_scan_sync(struct hci_dev *hdev)
3540 {
3541 	u8 own_addr_type;
3542 	u8 filter_policy;
3543 	u16 window, interval;
3544 	u8 filter_dups = LE_SCAN_FILTER_DUP_ENABLE;
3545 	int err;
3546 
3547 	if (hdev->scanning_paused) {
3548 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
3549 		return 0;
3550 	}
3551 
3552 	err = hci_scan_disable_sync(hdev);
3553 	if (err) {
3554 		bt_dev_err(hdev, "disable scanning failed: %d", err);
3555 		return err;
3556 	}
3557 
3558 	/* Set require_privacy to false since no SCAN_REQ are send
3559 	 * during passive scanning. Not using an non-resolvable address
3560 	 * here is important so that peer devices using direct
3561 	 * advertising with our address will be correctly reported
3562 	 * by the controller.
3563 	 */
3564 	if (hci_update_random_address_sync(hdev, false, scan_use_rpa(hdev),
3565 					   &own_addr_type))
3566 		return 0;
3567 
3568 	if (hdev->enable_advmon_interleave_scan &&
3569 	    hci_update_interleaved_scan_sync(hdev))
3570 		return 0;
3571 
3572 	bt_dev_dbg(hdev, "interleave state %d", hdev->interleave_scan_state);
3573 
3574 	/* Adding or removing entries from the accept list must
3575 	 * happen before enabling scanning. The controller does
3576 	 * not allow accept list modification while scanning.
3577 	 */
3578 	filter_policy = hci_update_accept_list_sync(hdev);
3579 
3580 	/* If suspended and filter_policy set to 0x00 (no acceptlist) then
3581 	 * passive scanning cannot be started since that would require the host
3582 	 * to be woken up to process the reports.
3583 	 */
3584 	if (hdev->suspended && !filter_policy) {
3585 		/* Check if accept list is empty then there is no need to scan
3586 		 * while suspended.
3587 		 */
3588 		if (list_empty(&hdev->le_accept_list))
3589 			return 0;
3590 
3591 		/* If there are devices is the accept_list that means some
3592 		 * devices could not be programmed which in non-suspended case
3593 		 * means filter_policy needs to be set to 0x00 so the host needs
3594 		 * to filter, but since this is treating suspended case we
3595 		 * can ignore device needing host to filter to allow devices in
3596 		 * the acceptlist to be able to wakeup the system.
3597 		 */
3598 		filter_policy = 0x01;
3599 	}
3600 
3601 	/* When the controller is using random resolvable addresses and
3602 	 * with that having LE privacy enabled, then controllers with
3603 	 * Extended Scanner Filter Policies support can now enable support
3604 	 * for handling directed advertising.
3605 	 *
3606 	 * So instead of using filter polices 0x00 (no acceptlist)
3607 	 * and 0x01 (acceptlist enabled) use the new filter policies
3608 	 * 0x02 (no acceptlist) and 0x03 (acceptlist enabled).
3609 	 */
3610 	if (hci_dev_test_flag(hdev, HCI_PRIVACY) &&
3611 	    (hdev->le_features[0] & HCI_LE_EXT_SCAN_POLICY))
3612 		filter_policy |= 0x02;
3613 
3614 	if (hdev->suspended) {
3615 		window = hdev->le_scan_window_suspend;
3616 		interval = hdev->le_scan_int_suspend;
3617 	} else if (hci_is_le_conn_scanning(hdev)) {
3618 		window = hdev->le_scan_window_connect;
3619 		interval = hdev->le_scan_int_connect;
3620 	} else if (hci_is_adv_monitoring(hdev)) {
3621 		window = hdev->le_scan_window_adv_monitor;
3622 		interval = hdev->le_scan_int_adv_monitor;
3623 
3624 		/* Disable duplicates filter when scanning for advertisement
3625 		 * monitor for the following reasons.
3626 		 *
3627 		 * For HW pattern filtering (ex. MSFT), Realtek and Qualcomm
3628 		 * controllers ignore RSSI_Sampling_Period when the duplicates
3629 		 * filter is enabled.
3630 		 *
3631 		 * For SW pattern filtering, when we're not doing interleaved
3632 		 * scanning, it is necessary to disable duplicates filter,
3633 		 * otherwise hosts can only receive one advertisement and it's
3634 		 * impossible to know if a peer is still in range.
3635 		 */
3636 		filter_dups = LE_SCAN_FILTER_DUP_DISABLE;
3637 	} else {
3638 		window = hdev->le_scan_window;
3639 		interval = hdev->le_scan_interval;
3640 	}
3641 
3642 	/* Disable all filtering for Mesh */
3643 	if (hci_dev_test_flag(hdev, HCI_MESH)) {
3644 		filter_policy = 0;
3645 		filter_dups = LE_SCAN_FILTER_DUP_DISABLE;
3646 	}
3647 
3648 	bt_dev_dbg(hdev, "LE passive scan with acceptlist = %d", filter_policy);
3649 
3650 	return hci_start_scan_sync(hdev, LE_SCAN_PASSIVE, interval, window,
3651 				   own_addr_type, filter_policy, filter_dups);
3652 }
3653 
3654 /* This function controls the passive scanning based on hdev->pend_le_conns
3655  * list. If there are pending LE connection we start the background scanning,
3656  * otherwise we stop it in the following sequence:
3657  *
3658  * If there are devices to scan:
3659  *
3660  * Disable Scanning -> Update Accept List ->
3661  * ll_privacy_capable((Disable Advertising) -> Disable Resolving List ->
3662  * Update Resolving List -> Enable Resolving List -> (Enable Advertising)) ->
3663  * Enable Scanning
3664  *
3665  * Otherwise:
3666  *
3667  * Disable Scanning
3668  */
3669 int hci_update_passive_scan_sync(struct hci_dev *hdev)
3670 {
3671 	int err;
3672 
3673 	if (!test_bit(HCI_UP, &hdev->flags) ||
3674 	    test_bit(HCI_INIT, &hdev->flags) ||
3675 	    hci_dev_test_flag(hdev, HCI_SETUP) ||
3676 	    hci_dev_test_flag(hdev, HCI_CONFIG) ||
3677 	    hci_dev_test_flag(hdev, HCI_AUTO_OFF) ||
3678 	    hci_dev_test_flag(hdev, HCI_UNREGISTER))
3679 		return 0;
3680 
3681 	/* No point in doing scanning if LE support hasn't been enabled */
3682 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
3683 		return 0;
3684 
3685 	/* If discovery is active don't interfere with it */
3686 	if (hdev->discovery.state != DISCOVERY_STOPPED)
3687 		return 0;
3688 
3689 	/* Reset RSSI and UUID filters when starting background scanning
3690 	 * since these filters are meant for service discovery only.
3691 	 *
3692 	 * The Start Discovery and Start Service Discovery operations
3693 	 * ensure to set proper values for RSSI threshold and UUID
3694 	 * filter list. So it is safe to just reset them here.
3695 	 */
3696 	hci_discovery_filter_clear(hdev);
3697 
3698 	bt_dev_dbg(hdev, "ADV monitoring is %s",
3699 		   hci_is_adv_monitoring(hdev) ? "on" : "off");
3700 
3701 	if (!hci_dev_test_flag(hdev, HCI_MESH) &&
3702 	    list_empty(&hdev->pend_le_conns) &&
3703 	    list_empty(&hdev->pend_le_reports) &&
3704 	    !hci_is_adv_monitoring(hdev) &&
3705 	    !hci_dev_test_flag(hdev, HCI_PA_SYNC)) {
3706 		/* If there is no pending LE connections or devices
3707 		 * to be scanned for or no ADV monitors, we should stop the
3708 		 * background scanning.
3709 		 */
3710 
3711 		bt_dev_dbg(hdev, "stopping background scanning");
3712 
3713 		err = hci_scan_disable_sync(hdev);
3714 		if (err)
3715 			bt_dev_err(hdev, "stop background scanning failed: %d",
3716 				   err);
3717 	} else {
3718 		/* If there is at least one pending LE connection, we should
3719 		 * keep the background scan running.
3720 		 */
3721 		bool exists;
3722 
3723 		/* If controller is connecting, we should not start scanning
3724 		 * since some controllers are not able to scan and connect at
3725 		 * the same time.
3726 		 */
3727 		rcu_read_lock();
3728 		exists = hci_lookup_le_connect(hdev);
3729 		rcu_read_unlock();
3730 		if (exists)
3731 			return 0;
3732 
3733 		bt_dev_dbg(hdev, "start background scanning");
3734 
3735 		err = hci_passive_scan_sync(hdev);
3736 		if (err)
3737 			bt_dev_err(hdev, "start background scanning failed: %d",
3738 				   err);
3739 	}
3740 
3741 	return err;
3742 }
3743 
3744 static int update_scan_sync(struct hci_dev *hdev, void *data)
3745 {
3746 	return hci_update_scan_sync(hdev);
3747 }
3748 
3749 int hci_update_scan(struct hci_dev *hdev)
3750 {
3751 	return hci_cmd_sync_queue(hdev, update_scan_sync, NULL, NULL);
3752 }
3753 
3754 static int update_passive_scan_sync(struct hci_dev *hdev, void *data)
3755 {
3756 	return hci_update_passive_scan_sync(hdev);
3757 }
3758 
3759 int hci_update_passive_scan(struct hci_dev *hdev)
3760 {
3761 	int err;
3762 
3763 	/* Only queue if it would have any effect */
3764 	if (!test_bit(HCI_UP, &hdev->flags) ||
3765 	    test_bit(HCI_INIT, &hdev->flags) ||
3766 	    hci_dev_test_flag(hdev, HCI_SETUP) ||
3767 	    hci_dev_test_flag(hdev, HCI_CONFIG) ||
3768 	    hci_dev_test_flag(hdev, HCI_AUTO_OFF) ||
3769 	    hci_dev_test_flag(hdev, HCI_UNREGISTER))
3770 		return 0;
3771 
3772 	err = hci_cmd_sync_queue_once(hdev, update_passive_scan_sync, NULL,
3773 				      NULL);
3774 	return (err == -EEXIST) ? 0 : err;
3775 }
3776 
3777 int hci_write_sc_support_sync(struct hci_dev *hdev, u8 val)
3778 {
3779 	int err;
3780 
3781 	if (!bredr_sc_enabled(hdev) || lmp_host_sc_capable(hdev))
3782 		return 0;
3783 
3784 	err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SC_SUPPORT,
3785 				    sizeof(val), &val, HCI_CMD_TIMEOUT);
3786 
3787 	if (!err) {
3788 		if (val) {
3789 			hdev->features[1][0] |= LMP_HOST_SC;
3790 			hci_dev_set_flag(hdev, HCI_SC_ENABLED);
3791 		} else {
3792 			hdev->features[1][0] &= ~LMP_HOST_SC;
3793 			hci_dev_clear_flag(hdev, HCI_SC_ENABLED);
3794 		}
3795 	}
3796 
3797 	return err;
3798 }
3799 
3800 int hci_write_ssp_mode_sync(struct hci_dev *hdev, u8 mode)
3801 {
3802 	int err;
3803 
3804 	if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED) ||
3805 	    lmp_host_ssp_capable(hdev))
3806 		return 0;
3807 
3808 	if (!mode && hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS)) {
3809 		__hci_cmd_sync_status(hdev, HCI_OP_WRITE_SSP_DEBUG_MODE,
3810 				      sizeof(mode), &mode, HCI_CMD_TIMEOUT);
3811 	}
3812 
3813 	err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SSP_MODE,
3814 				    sizeof(mode), &mode, HCI_CMD_TIMEOUT);
3815 	if (err)
3816 		return err;
3817 
3818 	return hci_write_sc_support_sync(hdev, 0x01);
3819 }
3820 
3821 static int hci_le_set_host_feature_sync(struct hci_dev *hdev, u16 bit,
3822 					u8 value);
3823 
3824 int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul)
3825 {
3826 	struct hci_cp_write_le_host_supported cp;
3827 	int err;
3828 
3829 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED) ||
3830 	    !lmp_bredr_capable(hdev))
3831 		return 0;
3832 
3833 	/* Check first if we already have the right host state
3834 	 * (host features set)
3835 	 */
3836 	if (le == lmp_host_le_capable(hdev) &&
3837 	    simul == lmp_host_le_br_capable(hdev))
3838 		return 0;
3839 
3840 	memset(&cp, 0, sizeof(cp));
3841 
3842 	cp.le = le;
3843 	cp.simul = simul;
3844 
3845 	err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LE_HOST_SUPPORTED,
3846 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3847 	if (err || !cis_capable(hdev))
3848 		return err;
3849 
3850 	/* The CIS host feature is set during init based on LE being enabled,
3851 	 * which is not repeated when LE is enabled afterwards, e.g. while the
3852 	 * controller is still auto powered on, so update it here.
3853 	 */
3854 	return hci_le_set_host_feature_sync(hdev, 32, iso_enabled(hdev));
3855 }
3856 
3857 static int hci_powered_update_adv_sync(struct hci_dev *hdev)
3858 {
3859 	u8 ids[U8_MAX];
3860 	size_t i, n;
3861 	int err;
3862 
3863 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
3864 		return 0;
3865 
3866 	/* If RPA Resolution has not been enable yet it means the
3867 	 * resolving list is empty and we should attempt to program the
3868 	 * local IRK in order to support using own_addr_type
3869 	 * ADDR_LE_DEV_RANDOM_RESOLVED (0x03).
3870 	 */
3871 	if (!hci_dev_test_flag(hdev, HCI_LL_RPA_RESOLUTION)) {
3872 		hci_le_add_resolve_list_sync(hdev, NULL);
3873 		hci_le_set_addr_resolution_enable_sync(hdev, 0x01);
3874 	}
3875 
3876 	/* Make sure the controller has a good default for
3877 	 * advertising data. This also applies to the case
3878 	 * where BR/EDR was toggled during the AUTO_OFF phase.
3879 	 */
3880 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
3881 	    list_empty(&hdev->adv_instances)) {
3882 		if (ext_adv_capable(hdev)) {
3883 			err = hci_setup_ext_adv_instance_sync(hdev, 0x00);
3884 			if (!err)
3885 				hci_update_scan_rsp_data_sync(hdev, 0x00);
3886 		} else {
3887 			err = hci_update_adv_data_sync(hdev, 0x00);
3888 			if (!err)
3889 				hci_update_scan_rsp_data_sync(hdev, 0x00);
3890 		}
3891 
3892 		if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
3893 			hci_enable_advertising_sync(hdev);
3894 	}
3895 
3896 	n = adv_instance_list_copy(hdev, ids);
3897 
3898 	/* Call for each tracked instance to be scheduled */
3899 	for (i = 0; i < n; i++)
3900 		hci_schedule_adv_instance_sync(hdev, ids[i], true);
3901 
3902 	return 0;
3903 }
3904 
3905 static int hci_write_auth_enable_sync(struct hci_dev *hdev)
3906 {
3907 	u8 link_sec;
3908 
3909 	link_sec = hci_dev_test_flag(hdev, HCI_LINK_SECURITY);
3910 	if (link_sec == test_bit(HCI_AUTH, &hdev->flags))
3911 		return 0;
3912 
3913 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_AUTH_ENABLE,
3914 				     sizeof(link_sec), &link_sec,
3915 				     HCI_CMD_TIMEOUT);
3916 }
3917 
3918 int hci_write_fast_connectable_sync(struct hci_dev *hdev, bool enable)
3919 {
3920 	struct hci_cp_write_page_scan_activity cp;
3921 	u8 type;
3922 	int err = 0;
3923 
3924 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
3925 		return 0;
3926 
3927 	if (hdev->hci_ver < BLUETOOTH_VER_1_2)
3928 		return 0;
3929 
3930 	memset(&cp, 0, sizeof(cp));
3931 
3932 	if (enable) {
3933 		type = PAGE_SCAN_TYPE_INTERLACED;
3934 
3935 		/* 160 msec page scan interval */
3936 		cp.interval = cpu_to_le16(0x0100);
3937 	} else {
3938 		type = hdev->def_page_scan_type;
3939 		cp.interval = cpu_to_le16(hdev->def_page_scan_int);
3940 	}
3941 
3942 	cp.window = cpu_to_le16(hdev->def_page_scan_window);
3943 
3944 	if (__cpu_to_le16(hdev->page_scan_interval) != cp.interval ||
3945 	    __cpu_to_le16(hdev->page_scan_window) != cp.window) {
3946 		err = __hci_cmd_sync_status(hdev,
3947 					    HCI_OP_WRITE_PAGE_SCAN_ACTIVITY,
3948 					    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3949 		if (err)
3950 			return err;
3951 	}
3952 
3953 	if (hdev->page_scan_type != type)
3954 		err = __hci_cmd_sync_status(hdev,
3955 					    HCI_OP_WRITE_PAGE_SCAN_TYPE,
3956 					    sizeof(type), &type,
3957 					    HCI_CMD_TIMEOUT);
3958 
3959 	return err;
3960 }
3961 
3962 static bool disconnected_accept_list_entries(struct hci_dev *hdev)
3963 	__must_hold(&hdev->lock)
3964 {
3965 	struct bdaddr_list *b;
3966 
3967 	list_for_each_entry(b, &hdev->accept_list, list) {
3968 		struct hci_conn *conn;
3969 
3970 		conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &b->bdaddr);
3971 		if (!conn)
3972 			return true;
3973 
3974 		if (conn->state != BT_CONNECTED && conn->state != BT_CONFIG)
3975 			return true;
3976 	}
3977 
3978 	return false;
3979 }
3980 
3981 static int hci_write_scan_enable_sync(struct hci_dev *hdev, u8 val)
3982 {
3983 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SCAN_ENABLE,
3984 					    sizeof(val), &val,
3985 					    HCI_CMD_TIMEOUT);
3986 }
3987 
3988 int hci_update_scan_sync(struct hci_dev *hdev)
3989 {
3990 	u8 scan;
3991 
3992 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
3993 		return 0;
3994 
3995 	if (!hdev_is_powered(hdev))
3996 		return 0;
3997 
3998 	if (mgmt_powering_down(hdev))
3999 		return 0;
4000 
4001 	if (hdev->scanning_paused)
4002 		return 0;
4003 
4004 	hci_dev_lock(hdev);
4005 
4006 	if (hci_dev_test_flag(hdev, HCI_CONNECTABLE) ||
4007 	    disconnected_accept_list_entries(hdev))
4008 		scan = SCAN_PAGE;
4009 	else
4010 		scan = SCAN_DISABLED;
4011 
4012 	hci_dev_unlock(hdev);
4013 
4014 	if (hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
4015 		scan |= SCAN_INQUIRY;
4016 
4017 	if (test_bit(HCI_PSCAN, &hdev->flags) == !!(scan & SCAN_PAGE) &&
4018 	    test_bit(HCI_ISCAN, &hdev->flags) == !!(scan & SCAN_INQUIRY))
4019 		return 0;
4020 
4021 	return hci_write_scan_enable_sync(hdev, scan);
4022 }
4023 
4024 int hci_update_name_sync(struct hci_dev *hdev, const u8 *name)
4025 {
4026 	struct hci_cp_write_local_name cp;
4027 
4028 	memset(&cp, 0, sizeof(cp));
4029 
4030 	memcpy(cp.name, name, sizeof(cp.name));
4031 
4032 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LOCAL_NAME,
4033 					    sizeof(cp), &cp,
4034 					    HCI_CMD_TIMEOUT);
4035 }
4036 
4037 /* This function perform powered update HCI command sequence after the HCI init
4038  * sequence which end up resetting all states, the sequence is as follows:
4039  *
4040  * HCI_SSP_ENABLED(Enable SSP)
4041  * HCI_LE_ENABLED(Enable LE)
4042  * HCI_LE_ENABLED(ll_privacy_capable(Add local IRK to Resolving List) ->
4043  * Update adv data)
4044  * Enable Authentication
4045  * lmp_bredr_capable(Set Fast Connectable -> Set Scan Type -> Set Class ->
4046  * Set Name -> Set EIR)
4047  * HCI_FORCE_STATIC_ADDR | BDADDR_ANY && !HCI_BREDR_ENABLED (Set Static Address)
4048  */
4049 int hci_powered_update_sync(struct hci_dev *hdev)
4050 {
4051 	int err;
4052 
4053 	/* Register the available SMP channels (BR/EDR and LE) only when
4054 	 * successfully powering on the controller. This late
4055 	 * registration is required so that LE SMP can clearly decide if
4056 	 * the public address or static address is used.
4057 	 */
4058 	hci_dev_lock(hdev);
4059 	smp_register(hdev);
4060 	hci_dev_unlock(hdev);
4061 
4062 	err = hci_write_ssp_mode_sync(hdev, 0x01);
4063 	if (err)
4064 		return err;
4065 
4066 	err = hci_write_le_host_supported_sync(hdev, 0x01, 0x00);
4067 	if (err)
4068 		return err;
4069 
4070 	err = hci_powered_update_adv_sync(hdev);
4071 	if (err)
4072 		return err;
4073 
4074 	err = hci_write_auth_enable_sync(hdev);
4075 	if (err)
4076 		return err;
4077 
4078 	if (lmp_bredr_capable(hdev)) {
4079 		if (hci_dev_test_flag(hdev, HCI_FAST_CONNECTABLE))
4080 			hci_write_fast_connectable_sync(hdev, true);
4081 		else
4082 			hci_write_fast_connectable_sync(hdev, false);
4083 		hci_update_scan_sync(hdev);
4084 		hci_update_class_sync(hdev);
4085 		hci_update_name_sync(hdev, hdev->dev_name);
4086 		hci_update_eir_sync(hdev);
4087 	}
4088 
4089 	/* If forcing static address is in use or there is no public
4090 	 * address use the static address as random address (but skip
4091 	 * the HCI command if the current random address is already the
4092 	 * static one.
4093 	 *
4094 	 * In case BR/EDR has been disabled on a dual-mode controller
4095 	 * and a static address has been configured, then use that
4096 	 * address instead of the public BR/EDR address.
4097 	 */
4098 	if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
4099 	    (!bacmp(&hdev->bdaddr, BDADDR_ANY) &&
4100 	    !hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))) {
4101 		if (bacmp(&hdev->static_addr, BDADDR_ANY))
4102 			return hci_set_random_addr_sync(hdev,
4103 							&hdev->static_addr);
4104 	}
4105 
4106 	return 0;
4107 }
4108 
4109 /**
4110  * hci_dev_get_bd_addr_from_property - Get the Bluetooth Device Address
4111  *				       (BD_ADDR) for a HCI device from
4112  *				       a firmware node property.
4113  * @hdev:	The HCI device
4114  *
4115  * Search the firmware node for 'local-bd-address'.
4116  *
4117  * All-zero BD addresses are rejected, because those could be properties
4118  * that exist in the firmware tables, but were not updated by the firmware. For
4119  * example, the DTS could define 'local-bd-address', with zero BD addresses.
4120  */
4121 static void hci_dev_get_bd_addr_from_property(struct hci_dev *hdev)
4122 {
4123 	struct fwnode_handle *fwnode = dev_fwnode(hdev->dev.parent);
4124 	bdaddr_t ba;
4125 	int ret;
4126 
4127 	ret = fwnode_property_read_u8_array(fwnode, "local-bd-address",
4128 					    (u8 *)&ba, sizeof(ba));
4129 	if (ret < 0 || !bacmp(&ba, BDADDR_ANY))
4130 		return;
4131 
4132 	if (hci_test_quirk(hdev, HCI_QUIRK_BDADDR_PROPERTY_BROKEN))
4133 		baswap(&hdev->public_addr, &ba);
4134 	else
4135 		bacpy(&hdev->public_addr, &ba);
4136 }
4137 
4138 struct hci_init_stage {
4139 	int (*func)(struct hci_dev *hdev);
4140 };
4141 
4142 /* Run init stage NULL terminated function table */
4143 static int hci_init_stage_sync(struct hci_dev *hdev,
4144 			       const struct hci_init_stage *stage)
4145 {
4146 	size_t i;
4147 
4148 	for (i = 0; stage[i].func; i++) {
4149 		int err;
4150 
4151 		err = stage[i].func(hdev);
4152 		if (err)
4153 			return err;
4154 	}
4155 
4156 	return 0;
4157 }
4158 
4159 /* Read Local Version */
4160 static int hci_read_local_version_sync(struct hci_dev *hdev)
4161 {
4162 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_VERSION,
4163 				     0, NULL, HCI_CMD_TIMEOUT);
4164 }
4165 
4166 /* Read BD Address */
4167 static int hci_read_bd_addr_sync(struct hci_dev *hdev)
4168 {
4169 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_BD_ADDR,
4170 				     0, NULL, HCI_CMD_TIMEOUT);
4171 }
4172 
4173 #define HCI_INIT(_func) \
4174 { \
4175 	.func = _func, \
4176 }
4177 
4178 static const struct hci_init_stage hci_init0[] = {
4179 	/* HCI_OP_READ_LOCAL_VERSION */
4180 	HCI_INIT(hci_read_local_version_sync),
4181 	/* HCI_OP_READ_BD_ADDR */
4182 	HCI_INIT(hci_read_bd_addr_sync),
4183 	{}
4184 };
4185 
4186 int hci_reset_sync(struct hci_dev *hdev)
4187 {
4188 	set_bit(HCI_RESET, &hdev->flags);
4189 
4190 	return __hci_cmd_sync_status(hdev, HCI_OP_RESET, 0, NULL,
4191 				     HCI_CMD_TIMEOUT);
4192 }
4193 
4194 /* Send a raw HCI reset for use by vendor drivers */
4195 int __hci_reset_sync(struct hci_dev *hdev)
4196 {
4197 	return __hci_cmd_sync_status(hdev, HCI_OP_RESET, 0, NULL,
4198 				     HCI_INIT_TIMEOUT);
4199 }
4200 EXPORT_SYMBOL(__hci_reset_sync);
4201 
4202 static int hci_init0_sync(struct hci_dev *hdev)
4203 {
4204 	int err;
4205 
4206 	bt_dev_dbg(hdev, "");
4207 
4208 	/* Reset */
4209 	if (!hci_test_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE)) {
4210 		err = hci_reset_sync(hdev);
4211 		if (err)
4212 			return err;
4213 	}
4214 
4215 	return hci_init_stage_sync(hdev, hci_init0);
4216 }
4217 
4218 static int hci_unconf_init_sync(struct hci_dev *hdev)
4219 {
4220 	int err;
4221 
4222 	if (hci_test_quirk(hdev, HCI_QUIRK_RAW_DEVICE))
4223 		return 0;
4224 
4225 	err = hci_init0_sync(hdev);
4226 	if (err < 0)
4227 		return err;
4228 
4229 	if (hci_dev_test_flag(hdev, HCI_SETUP))
4230 		hci_debugfs_create_basic(hdev);
4231 
4232 	return 0;
4233 }
4234 
4235 /* Read Local Supported Features. */
4236 static int hci_read_local_features_sync(struct hci_dev *hdev)
4237 {
4238 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_FEATURES,
4239 				     0, NULL, HCI_CMD_TIMEOUT);
4240 }
4241 
4242 /* BR Controller init stage 1 command sequence */
4243 static const struct hci_init_stage br_init1[] = {
4244 	/* HCI_OP_READ_LOCAL_FEATURES */
4245 	HCI_INIT(hci_read_local_features_sync),
4246 	/* HCI_OP_READ_LOCAL_VERSION */
4247 	HCI_INIT(hci_read_local_version_sync),
4248 	/* HCI_OP_READ_BD_ADDR */
4249 	HCI_INIT(hci_read_bd_addr_sync),
4250 	{}
4251 };
4252 
4253 /* Read Local Commands */
4254 static int hci_read_local_cmds_sync(struct hci_dev *hdev)
4255 {
4256 	/* All Bluetooth 1.2 and later controllers should support the
4257 	 * HCI command for reading the local supported commands.
4258 	 *
4259 	 * Unfortunately some controllers indicate Bluetooth 1.2 support,
4260 	 * but do not have support for this command. If that is the case,
4261 	 * the driver can quirk the behavior and skip reading the local
4262 	 * supported commands.
4263 	 */
4264 	if (hdev->hci_ver > BLUETOOTH_VER_1_1 &&
4265 	    !hci_test_quirk(hdev, HCI_QUIRK_BROKEN_LOCAL_COMMANDS))
4266 		return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_COMMANDS,
4267 					     0, NULL, HCI_CMD_TIMEOUT);
4268 
4269 	return 0;
4270 }
4271 
4272 static int hci_init1_sync(struct hci_dev *hdev)
4273 {
4274 	int err;
4275 
4276 	bt_dev_dbg(hdev, "");
4277 
4278 	/* Reset */
4279 	if (!hci_test_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE)) {
4280 		err = hci_reset_sync(hdev);
4281 		if (err)
4282 			return err;
4283 	}
4284 
4285 	return hci_init_stage_sync(hdev, br_init1);
4286 }
4287 
4288 /* Read Buffer Size (ACL mtu, max pkt, etc.) */
4289 static int hci_read_buffer_size_sync(struct hci_dev *hdev)
4290 {
4291 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_BUFFER_SIZE,
4292 				     0, NULL, HCI_CMD_TIMEOUT);
4293 }
4294 
4295 /* Read Class of Device */
4296 static int hci_read_dev_class_sync(struct hci_dev *hdev)
4297 {
4298 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_CLASS_OF_DEV,
4299 				     0, NULL, HCI_CMD_TIMEOUT);
4300 }
4301 
4302 /* Read Local Name */
4303 static int hci_read_local_name_sync(struct hci_dev *hdev)
4304 {
4305 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_NAME,
4306 				     0, NULL, HCI_CMD_TIMEOUT);
4307 }
4308 
4309 /* Read Voice Setting */
4310 static int hci_read_voice_setting_sync(struct hci_dev *hdev)
4311 {
4312 	if (!read_voice_setting_capable(hdev))
4313 		return 0;
4314 
4315 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_VOICE_SETTING,
4316 				     0, NULL, HCI_CMD_TIMEOUT);
4317 }
4318 
4319 /* Read Number of Supported IAC */
4320 static int hci_read_num_supported_iac_sync(struct hci_dev *hdev)
4321 {
4322 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_NUM_SUPPORTED_IAC,
4323 				     0, NULL, HCI_CMD_TIMEOUT);
4324 }
4325 
4326 /* Read Current IAC LAP */
4327 static int hci_read_current_iac_lap_sync(struct hci_dev *hdev)
4328 {
4329 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_CURRENT_IAC_LAP,
4330 				     0, NULL, HCI_CMD_TIMEOUT);
4331 }
4332 
4333 static int hci_set_event_filter_sync(struct hci_dev *hdev, u8 flt_type,
4334 				     u8 cond_type, bdaddr_t *bdaddr,
4335 				     u8 auto_accept)
4336 {
4337 	struct hci_cp_set_event_filter cp;
4338 
4339 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
4340 		return 0;
4341 
4342 	if (hci_test_quirk(hdev, HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL))
4343 		return 0;
4344 
4345 	memset(&cp, 0, sizeof(cp));
4346 	cp.flt_type = flt_type;
4347 
4348 	if (flt_type != HCI_FLT_CLEAR_ALL) {
4349 		cp.cond_type = cond_type;
4350 		bacpy(&cp.addr_conn_flt.bdaddr, bdaddr);
4351 		cp.addr_conn_flt.auto_accept = auto_accept;
4352 	}
4353 
4354 	return __hci_cmd_sync_status(hdev, HCI_OP_SET_EVENT_FLT,
4355 				     flt_type == HCI_FLT_CLEAR_ALL ?
4356 				     sizeof(cp.flt_type) : sizeof(cp), &cp,
4357 				     HCI_CMD_TIMEOUT);
4358 }
4359 
4360 static int hci_clear_event_filter_sync(struct hci_dev *hdev)
4361 {
4362 	if (!hci_dev_test_flag(hdev, HCI_EVENT_FILTER_CONFIGURED))
4363 		return 0;
4364 
4365 	/* In theory the state machine should not reach here unless
4366 	 * a hci_set_event_filter_sync() call succeeds, but we do
4367 	 * the check both for parity and as a future reminder.
4368 	 */
4369 	if (hci_test_quirk(hdev, HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL))
4370 		return 0;
4371 
4372 	return hci_set_event_filter_sync(hdev, HCI_FLT_CLEAR_ALL, 0x00,
4373 					 BDADDR_ANY, 0x00);
4374 }
4375 
4376 /* Connection accept timeout ~20 secs */
4377 static int hci_write_ca_timeout_sync(struct hci_dev *hdev)
4378 {
4379 	__le16 param = cpu_to_le16(0x7d00);
4380 
4381 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_CA_TIMEOUT,
4382 				     sizeof(param), &param, HCI_CMD_TIMEOUT);
4383 }
4384 
4385 /* Enable SCO flow control if supported */
4386 static int hci_write_sync_flowctl_sync(struct hci_dev *hdev)
4387 {
4388 	struct hci_cp_write_sync_flowctl cp;
4389 	int err;
4390 
4391 	/* Check if the controller supports SCO and HCI_OP_WRITE_SYNC_FLOWCTL */
4392 	if (!lmp_sco_capable(hdev) || !(hdev->commands[10] & BIT(4)) ||
4393 	    !hci_test_quirk(hdev, HCI_QUIRK_SYNC_FLOWCTL_SUPPORTED))
4394 		return 0;
4395 
4396 	memset(&cp, 0, sizeof(cp));
4397 	cp.enable = 0x01;
4398 
4399 	err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SYNC_FLOWCTL,
4400 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4401 	if (!err)
4402 		hci_dev_set_flag(hdev, HCI_SCO_FLOWCTL);
4403 
4404 	return err;
4405 }
4406 
4407 /* BR Controller init stage 2 command sequence */
4408 static const struct hci_init_stage br_init2[] = {
4409 	/* HCI_OP_READ_BUFFER_SIZE */
4410 	HCI_INIT(hci_read_buffer_size_sync),
4411 	/* HCI_OP_READ_CLASS_OF_DEV */
4412 	HCI_INIT(hci_read_dev_class_sync),
4413 	/* HCI_OP_READ_LOCAL_NAME */
4414 	HCI_INIT(hci_read_local_name_sync),
4415 	/* HCI_OP_READ_VOICE_SETTING */
4416 	HCI_INIT(hci_read_voice_setting_sync),
4417 	/* HCI_OP_READ_NUM_SUPPORTED_IAC */
4418 	HCI_INIT(hci_read_num_supported_iac_sync),
4419 	/* HCI_OP_READ_CURRENT_IAC_LAP */
4420 	HCI_INIT(hci_read_current_iac_lap_sync),
4421 	/* HCI_OP_SET_EVENT_FLT */
4422 	HCI_INIT(hci_clear_event_filter_sync),
4423 	/* HCI_OP_WRITE_CA_TIMEOUT */
4424 	HCI_INIT(hci_write_ca_timeout_sync),
4425 	/* HCI_OP_WRITE_SYNC_FLOWCTL */
4426 	HCI_INIT(hci_write_sync_flowctl_sync),
4427 	{}
4428 };
4429 
4430 static int hci_write_ssp_mode_1_sync(struct hci_dev *hdev)
4431 {
4432 	u8 mode = 0x01;
4433 
4434 	if (!lmp_ssp_capable(hdev) || !hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
4435 		return 0;
4436 
4437 	/* When SSP is available, then the host features page
4438 	 * should also be available as well. However some
4439 	 * controllers list the max_page as 0 as long as SSP
4440 	 * has not been enabled. To achieve proper debugging
4441 	 * output, force the minimum max_page to 1 at least.
4442 	 */
4443 	hdev->max_page = 0x01;
4444 
4445 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SSP_MODE,
4446 				     sizeof(mode), &mode, HCI_CMD_TIMEOUT);
4447 }
4448 
4449 static int hci_write_eir_sync(struct hci_dev *hdev)
4450 {
4451 	struct hci_cp_write_eir cp;
4452 
4453 	if (!lmp_ssp_capable(hdev) || hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
4454 		return 0;
4455 
4456 	memset(hdev->eir, 0, sizeof(hdev->eir));
4457 	memset(&cp, 0, sizeof(cp));
4458 
4459 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_EIR, sizeof(cp), &cp,
4460 				     HCI_CMD_TIMEOUT);
4461 }
4462 
4463 static int hci_write_inquiry_mode_sync(struct hci_dev *hdev)
4464 {
4465 	u8 mode;
4466 
4467 	if (!lmp_inq_rssi_capable(hdev) &&
4468 	    !hci_test_quirk(hdev, HCI_QUIRK_FIXUP_INQUIRY_MODE))
4469 		return 0;
4470 
4471 	/* If Extended Inquiry Result events are supported, then
4472 	 * they are clearly preferred over Inquiry Result with RSSI
4473 	 * events.
4474 	 */
4475 	mode = lmp_ext_inq_capable(hdev) ? 0x02 : 0x01;
4476 
4477 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_INQUIRY_MODE,
4478 				     sizeof(mode), &mode, HCI_CMD_TIMEOUT);
4479 }
4480 
4481 static int hci_read_inq_rsp_tx_power_sync(struct hci_dev *hdev)
4482 {
4483 	if (!lmp_inq_tx_pwr_capable(hdev))
4484 		return 0;
4485 
4486 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_INQ_RSP_TX_POWER,
4487 				     0, NULL, HCI_CMD_TIMEOUT);
4488 }
4489 
4490 static int hci_read_local_ext_features_sync(struct hci_dev *hdev, u8 page)
4491 {
4492 	struct hci_cp_read_local_ext_features cp;
4493 
4494 	if (!lmp_ext_feat_capable(hdev))
4495 		return 0;
4496 
4497 	memset(&cp, 0, sizeof(cp));
4498 	cp.page = page;
4499 
4500 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_EXT_FEATURES,
4501 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4502 }
4503 
4504 static int hci_read_local_ext_features_1_sync(struct hci_dev *hdev)
4505 {
4506 	return hci_read_local_ext_features_sync(hdev, 0x01);
4507 }
4508 
4509 /* HCI Controller init stage 2 command sequence */
4510 static const struct hci_init_stage hci_init2[] = {
4511 	/* HCI_OP_READ_LOCAL_COMMANDS */
4512 	HCI_INIT(hci_read_local_cmds_sync),
4513 	/* HCI_OP_WRITE_SSP_MODE */
4514 	HCI_INIT(hci_write_ssp_mode_1_sync),
4515 	/* HCI_OP_WRITE_EIR */
4516 	HCI_INIT(hci_write_eir_sync),
4517 	/* HCI_OP_WRITE_INQUIRY_MODE */
4518 	HCI_INIT(hci_write_inquiry_mode_sync),
4519 	/* HCI_OP_READ_INQ_RSP_TX_POWER */
4520 	HCI_INIT(hci_read_inq_rsp_tx_power_sync),
4521 	/* HCI_OP_READ_LOCAL_EXT_FEATURES */
4522 	HCI_INIT(hci_read_local_ext_features_1_sync),
4523 	/* HCI_OP_WRITE_AUTH_ENABLE */
4524 	HCI_INIT(hci_write_auth_enable_sync),
4525 	{}
4526 };
4527 
4528 /* Read LE Buffer Size */
4529 static int hci_le_read_buffer_size_sync(struct hci_dev *hdev)
4530 {
4531 	/* Use Read LE Buffer Size V2 if supported */
4532 	if (iso_capable(hdev) && hdev->commands[41] & 0x20)
4533 		return __hci_cmd_sync_status(hdev,
4534 					     HCI_OP_LE_READ_BUFFER_SIZE_V2,
4535 					     0, NULL, HCI_CMD_TIMEOUT);
4536 
4537 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_BUFFER_SIZE,
4538 				     0, NULL, HCI_CMD_TIMEOUT);
4539 }
4540 
4541 /* Read LE Local Supported Features */
4542 static int hci_le_read_local_features_sync(struct hci_dev *hdev)
4543 {
4544 	int err;
4545 
4546 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_LOCAL_FEATURES,
4547 				    0, NULL, HCI_CMD_TIMEOUT);
4548 	if (err)
4549 		return err;
4550 
4551 	if (ll_ext_feature_capable(hdev) && hdev->commands[47] & BIT(2))
4552 		return __hci_cmd_sync_status(hdev,
4553 					     HCI_OP_LE_READ_ALL_LOCAL_FEATURES,
4554 					     0, NULL, HCI_CMD_TIMEOUT);
4555 
4556 	return err;
4557 }
4558 
4559 /* Read LE Supported States */
4560 static int hci_le_read_supported_states_sync(struct hci_dev *hdev)
4561 {
4562 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_SUPPORTED_STATES,
4563 				     0, NULL, HCI_CMD_TIMEOUT);
4564 }
4565 
4566 /* LE Controller init stage 2 command sequence */
4567 static const struct hci_init_stage le_init2[] = {
4568 	/* HCI_OP_LE_READ_LOCAL_FEATURES */
4569 	HCI_INIT(hci_le_read_local_features_sync),
4570 	/* HCI_OP_LE_READ_BUFFER_SIZE */
4571 	HCI_INIT(hci_le_read_buffer_size_sync),
4572 	/* HCI_OP_LE_READ_SUPPORTED_STATES */
4573 	HCI_INIT(hci_le_read_supported_states_sync),
4574 	{}
4575 };
4576 
4577 static int hci_init2_sync(struct hci_dev *hdev)
4578 {
4579 	int err;
4580 
4581 	bt_dev_dbg(hdev, "");
4582 
4583 	err = hci_init_stage_sync(hdev, hci_init2);
4584 	if (err)
4585 		return err;
4586 
4587 	if (lmp_bredr_capable(hdev)) {
4588 		err = hci_init_stage_sync(hdev, br_init2);
4589 		if (err)
4590 			return err;
4591 	} else {
4592 		hci_dev_clear_flag(hdev, HCI_BREDR_ENABLED);
4593 	}
4594 
4595 	if (lmp_le_capable(hdev)) {
4596 		err = hci_init_stage_sync(hdev, le_init2);
4597 		if (err)
4598 			return err;
4599 		/* LE-only controllers have LE implicitly enabled */
4600 		if (!lmp_bredr_capable(hdev))
4601 			hci_dev_set_flag(hdev, HCI_LE_ENABLED);
4602 	}
4603 
4604 	return 0;
4605 }
4606 
4607 static int hci_set_event_mask_sync(struct hci_dev *hdev)
4608 {
4609 	/* The second byte is 0xff instead of 0x9f (two reserved bits
4610 	 * disabled) since a Broadcom 1.2 dongle doesn't respond to the
4611 	 * command otherwise.
4612 	 */
4613 	u8 events[8] = { 0xff, 0xff, 0xfb, 0xff, 0x00, 0x00, 0x00, 0x00 };
4614 
4615 	/* CSR 1.1 dongles does not accept any bitfield so don't try to set
4616 	 * any event mask for pre 1.2 devices.
4617 	 */
4618 	if (hdev->hci_ver < BLUETOOTH_VER_1_2)
4619 		return 0;
4620 
4621 	if (lmp_bredr_capable(hdev)) {
4622 		events[4] |= 0x01; /* Flow Specification Complete */
4623 
4624 		/* Don't set Disconnect Complete and mode change when
4625 		 * suspended as that would wakeup the host when disconnecting
4626 		 * due to suspend.
4627 		 */
4628 		if (hdev->suspended) {
4629 			events[0] &= 0xef;
4630 			events[2] &= 0xf7;
4631 		}
4632 	} else {
4633 		/* Use a different default for LE-only devices */
4634 		memset(events, 0, sizeof(events));
4635 		events[1] |= 0x20; /* Command Complete */
4636 		events[1] |= 0x40; /* Command Status */
4637 		events[1] |= 0x80; /* Hardware Error */
4638 
4639 		/* If the controller supports the Disconnect command, enable
4640 		 * the corresponding event. In addition enable packet flow
4641 		 * control related events.
4642 		 */
4643 		if (hdev->commands[0] & 0x20) {
4644 			/* Don't set Disconnect Complete when suspended as that
4645 			 * would wakeup the host when disconnecting due to
4646 			 * suspend.
4647 			 */
4648 			if (!hdev->suspended)
4649 				events[0] |= 0x10; /* Disconnection Complete */
4650 			events[2] |= 0x04; /* Number of Completed Packets */
4651 			events[3] |= 0x02; /* Data Buffer Overflow */
4652 		}
4653 
4654 		/* If the controller supports the Read Remote Version
4655 		 * Information command, enable the corresponding event.
4656 		 */
4657 		if (hdev->commands[2] & 0x80)
4658 			events[1] |= 0x08; /* Read Remote Version Information
4659 					    * Complete
4660 					    */
4661 
4662 		if (hdev->le_features[0] & HCI_LE_ENCRYPTION) {
4663 			events[0] |= 0x80; /* Encryption Change */
4664 			events[5] |= 0x80; /* Encryption Key Refresh Complete */
4665 		}
4666 	}
4667 
4668 	if (lmp_inq_rssi_capable(hdev) ||
4669 	    hci_test_quirk(hdev, HCI_QUIRK_FIXUP_INQUIRY_MODE))
4670 		events[4] |= 0x02; /* Inquiry Result with RSSI */
4671 
4672 	if (lmp_ext_feat_capable(hdev))
4673 		events[4] |= 0x04; /* Read Remote Extended Features Complete */
4674 
4675 	if (lmp_esco_capable(hdev)) {
4676 		events[5] |= 0x08; /* Synchronous Connection Complete */
4677 		events[5] |= 0x10; /* Synchronous Connection Changed */
4678 	}
4679 
4680 	if (lmp_sniffsubr_capable(hdev))
4681 		events[5] |= 0x20; /* Sniff Subrating */
4682 
4683 	if (lmp_pause_enc_capable(hdev))
4684 		events[5] |= 0x80; /* Encryption Key Refresh Complete */
4685 
4686 	if (lmp_ext_inq_capable(hdev))
4687 		events[5] |= 0x40; /* Extended Inquiry Result */
4688 
4689 	if (lmp_no_flush_capable(hdev))
4690 		events[7] |= 0x01; /* Enhanced Flush Complete */
4691 
4692 	if (lmp_lsto_capable(hdev))
4693 		events[6] |= 0x80; /* Link Supervision Timeout Changed */
4694 
4695 	if (lmp_ssp_capable(hdev)) {
4696 		events[6] |= 0x01;	/* IO Capability Request */
4697 		events[6] |= 0x02;	/* IO Capability Response */
4698 		events[6] |= 0x04;	/* User Confirmation Request */
4699 		events[6] |= 0x08;	/* User Passkey Request */
4700 		events[6] |= 0x10;	/* Remote OOB Data Request */
4701 		events[6] |= 0x20;	/* Simple Pairing Complete */
4702 		events[7] |= 0x04;	/* User Passkey Notification */
4703 		events[7] |= 0x08;	/* Keypress Notification */
4704 		events[7] |= 0x10;	/* Remote Host Supported
4705 					 * Features Notification
4706 					 */
4707 	}
4708 
4709 	if (lmp_le_capable(hdev))
4710 		events[7] |= 0x20;	/* LE Meta-Event */
4711 
4712 	return __hci_cmd_sync_status(hdev, HCI_OP_SET_EVENT_MASK,
4713 				     sizeof(events), events, HCI_CMD_TIMEOUT);
4714 }
4715 
4716 static int hci_read_stored_link_key_sync(struct hci_dev *hdev)
4717 {
4718 	struct hci_cp_read_stored_link_key cp;
4719 
4720 	if (!(hdev->commands[6] & 0x20) ||
4721 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY))
4722 		return 0;
4723 
4724 	memset(&cp, 0, sizeof(cp));
4725 	bacpy(&cp.bdaddr, BDADDR_ANY);
4726 	cp.read_all = 0x01;
4727 
4728 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_STORED_LINK_KEY,
4729 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4730 }
4731 
4732 static int hci_setup_link_policy_sync(struct hci_dev *hdev)
4733 {
4734 	struct hci_cp_write_def_link_policy cp;
4735 	u16 link_policy = 0;
4736 
4737 	if (!(hdev->commands[5] & 0x10))
4738 		return 0;
4739 
4740 	memset(&cp, 0, sizeof(cp));
4741 
4742 	if (lmp_rswitch_capable(hdev))
4743 		link_policy |= HCI_LP_RSWITCH;
4744 	if (lmp_hold_capable(hdev))
4745 		link_policy |= HCI_LP_HOLD;
4746 	if (lmp_sniff_capable(hdev))
4747 		link_policy |= HCI_LP_SNIFF;
4748 	if (lmp_park_capable(hdev))
4749 		link_policy |= HCI_LP_PARK;
4750 
4751 	cp.policy = cpu_to_le16(link_policy);
4752 
4753 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_DEF_LINK_POLICY,
4754 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4755 }
4756 
4757 static int hci_read_page_scan_activity_sync(struct hci_dev *hdev)
4758 {
4759 	if (!(hdev->commands[8] & 0x01))
4760 		return 0;
4761 
4762 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_PAGE_SCAN_ACTIVITY,
4763 				     0, NULL, HCI_CMD_TIMEOUT);
4764 }
4765 
4766 static int hci_read_def_err_data_reporting_sync(struct hci_dev *hdev)
4767 {
4768 	if (!(hdev->commands[18] & 0x04) ||
4769 	    !(hdev->features[0][6] & LMP_ERR_DATA_REPORTING) ||
4770 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING))
4771 		return 0;
4772 
4773 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_DEF_ERR_DATA_REPORTING,
4774 				     0, NULL, HCI_CMD_TIMEOUT);
4775 }
4776 
4777 static int hci_read_page_scan_type_sync(struct hci_dev *hdev)
4778 {
4779 	/* Some older Broadcom based Bluetooth 1.2 controllers do not
4780 	 * support the Read Page Scan Type command. Check support for
4781 	 * this command in the bit mask of supported commands.
4782 	 */
4783 	if (!(hdev->commands[13] & 0x01) ||
4784 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_READ_PAGE_SCAN_TYPE))
4785 		return 0;
4786 
4787 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_PAGE_SCAN_TYPE,
4788 				     0, NULL, HCI_CMD_TIMEOUT);
4789 }
4790 
4791 /* Read features beyond page 1 if available */
4792 static int hci_read_local_ext_features_all_sync(struct hci_dev *hdev)
4793 {
4794 	u8 page;
4795 	int err;
4796 
4797 	if (!lmp_ext_feat_capable(hdev))
4798 		return 0;
4799 
4800 	for (page = 2; page < HCI_MAX_PAGES && page <= hdev->max_page;
4801 	     page++) {
4802 		err = hci_read_local_ext_features_sync(hdev, page);
4803 		if (err)
4804 			return err;
4805 	}
4806 
4807 	return 0;
4808 }
4809 
4810 /* HCI Controller init stage 3 command sequence */
4811 static const struct hci_init_stage hci_init3[] = {
4812 	/* HCI_OP_SET_EVENT_MASK */
4813 	HCI_INIT(hci_set_event_mask_sync),
4814 	/* HCI_OP_READ_STORED_LINK_KEY */
4815 	HCI_INIT(hci_read_stored_link_key_sync),
4816 	/* HCI_OP_WRITE_DEF_LINK_POLICY */
4817 	HCI_INIT(hci_setup_link_policy_sync),
4818 	/* HCI_OP_READ_PAGE_SCAN_ACTIVITY */
4819 	HCI_INIT(hci_read_page_scan_activity_sync),
4820 	/* HCI_OP_READ_DEF_ERR_DATA_REPORTING */
4821 	HCI_INIT(hci_read_def_err_data_reporting_sync),
4822 	/* HCI_OP_READ_PAGE_SCAN_TYPE */
4823 	HCI_INIT(hci_read_page_scan_type_sync),
4824 	/* HCI_OP_READ_LOCAL_EXT_FEATURES */
4825 	HCI_INIT(hci_read_local_ext_features_all_sync),
4826 	{}
4827 };
4828 
4829 static int hci_le_set_event_mask_sync(struct hci_dev *hdev)
4830 {
4831 	u8 events[8];
4832 
4833 	if (!lmp_le_capable(hdev))
4834 		return 0;
4835 
4836 	memset(events, 0, sizeof(events));
4837 
4838 	if (hdev->le_features[0] & HCI_LE_ENCRYPTION)
4839 		events[0] |= 0x10;	/* LE Long Term Key Request */
4840 
4841 	/* If controller supports the Connection Parameters Request
4842 	 * Link Layer Procedure, enable the corresponding event.
4843 	 */
4844 	if (hdev->le_features[0] & HCI_LE_CONN_PARAM_REQ_PROC)
4845 		/* LE Remote Connection Parameter Request */
4846 		events[0] |= 0x20;
4847 
4848 	/* If the controller supports the Data Length Extension
4849 	 * feature, enable the corresponding event.
4850 	 */
4851 	if (hdev->le_features[0] & HCI_LE_DATA_LEN_EXT)
4852 		events[0] |= 0x40;	/* LE Data Length Change */
4853 
4854 	/* If the controller supports LL Privacy feature or LE Extended Adv,
4855 	 * enable the corresponding event.
4856 	 */
4857 	if (use_enhanced_conn_complete(hdev))
4858 		events[1] |= 0x02;	/* LE Enhanced Connection Complete */
4859 
4860 	/* Mark Device Privacy if Privacy Mode is supported */
4861 	if (privacy_mode_capable(hdev))
4862 		hdev->conn_flags |= HCI_CONN_FLAG_DEVICE_PRIVACY;
4863 
4864 	/* Mark Address Resolution if LL Privacy is supported */
4865 	if (ll_privacy_capable(hdev))
4866 		hdev->conn_flags |= HCI_CONN_FLAG_ADDRESS_RESOLUTION;
4867 
4868 	/* Mark PAST if supported */
4869 	if (past_capable(hdev))
4870 		hdev->conn_flags |= HCI_CONN_FLAG_PAST;
4871 
4872 	/* If the controller supports Extended Scanner Filter
4873 	 * Policies, enable the corresponding event.
4874 	 */
4875 	if (hdev->le_features[0] & HCI_LE_EXT_SCAN_POLICY)
4876 		events[1] |= 0x04;	/* LE Direct Advertising Report */
4877 
4878 	/* If the controller supports Channel Selection Algorithm #2
4879 	 * feature, enable the corresponding event.
4880 	 */
4881 	if (hdev->le_features[1] & HCI_LE_CHAN_SEL_ALG2)
4882 		events[2] |= 0x08;	/* LE Channel Selection Algorithm */
4883 
4884 	/* If the controller supports the LE Set Scan Enable command,
4885 	 * enable the corresponding advertising report event.
4886 	 */
4887 	if (hdev->commands[26] & 0x08)
4888 		events[0] |= 0x02;	/* LE Advertising Report */
4889 
4890 	/* If the controller supports the LE Create Connection
4891 	 * command, enable the corresponding event.
4892 	 */
4893 	if (hdev->commands[26] & 0x10)
4894 		events[0] |= 0x01;	/* LE Connection Complete */
4895 
4896 	/* If the controller supports the LE Connection Update
4897 	 * command, enable the corresponding event.
4898 	 */
4899 	if (hdev->commands[27] & 0x04)
4900 		events[0] |= 0x04;	/* LE Connection Update Complete */
4901 
4902 	/* If the controller supports the LE Read Remote Used Features
4903 	 * command, enable the corresponding event.
4904 	 */
4905 	if (hdev->commands[27] & 0x20)
4906 		/* LE Read Remote Used Features Complete */
4907 		events[0] |= 0x08;
4908 
4909 	/* If the controller supports the LE Read Local P-256
4910 	 * Public Key command, enable the corresponding event.
4911 	 */
4912 	if (hdev->commands[34] & 0x02)
4913 		/* LE Read Local P-256 Public Key Complete */
4914 		events[0] |= 0x80;
4915 
4916 	/* If the controller supports the LE Generate DHKey
4917 	 * command, enable the corresponding event.
4918 	 */
4919 	if (hdev->commands[34] & 0x04)
4920 		events[1] |= 0x01;	/* LE Generate DHKey Complete */
4921 
4922 	/* If the controller supports the LE Set Default PHY or
4923 	 * LE Set PHY commands, enable the corresponding event.
4924 	 */
4925 	if (hdev->commands[35] & (0x20 | 0x40))
4926 		events[1] |= 0x08;        /* LE PHY Update Complete */
4927 
4928 	/* If the controller supports LE Set Extended Scan Parameters
4929 	 * and LE Set Extended Scan Enable commands, enable the
4930 	 * corresponding event.
4931 	 */
4932 	if (use_ext_scan(hdev))
4933 		events[1] |= 0x10;	/* LE Extended Advertising Report */
4934 
4935 	/* If the controller supports the LE Extended Advertising
4936 	 * command, enable the corresponding event.
4937 	 */
4938 	if (ext_adv_capable(hdev))
4939 		events[2] |= 0x02;	/* LE Advertising Set Terminated */
4940 
4941 	if (past_receiver_capable(hdev))
4942 		events[2] |= 0x80;	/* LE PAST Received */
4943 
4944 	if (cis_capable(hdev)) {
4945 		events[3] |= 0x01;	/* LE CIS Established */
4946 		if (cis_peripheral_capable(hdev))
4947 			events[3] |= 0x02; /* LE CIS Request */
4948 	}
4949 
4950 	if (bis_capable(hdev)) {
4951 		events[1] |= 0x20;	/* LE PA Report */
4952 		events[1] |= 0x40;	/* LE PA Sync Established */
4953 		events[1] |= 0x80;	/* LE PA Sync Lost */
4954 		events[3] |= 0x04;	/* LE Create BIG Complete */
4955 		events[3] |= 0x08;	/* LE Terminate BIG Complete */
4956 		events[3] |= 0x10;	/* LE BIG Sync Established */
4957 		events[3] |= 0x20;	/* LE BIG Sync Loss */
4958 		events[4] |= 0x02;	/* LE BIG Info Advertising Report */
4959 	}
4960 
4961 	if (ll_ext_feature_capable(hdev))
4962 		events[5] |= BIT(2);
4963 
4964 	if (le_cs_capable(hdev)) {
4965 		/* Channel Sounding events */
4966 		events[5] |= 0x08;	/* LE CS Read Remote Supported Cap Complete event */
4967 		events[5] |= 0x10;	/* LE CS Read Remote FAE Table Complete event */
4968 		events[5] |= 0x20;	/* LE CS Security Enable Complete event */
4969 		events[5] |= 0x40;	/* LE CS Config Complete event */
4970 		events[5] |= 0x80;	/* LE CS Procedure Enable Complete event */
4971 		events[6] |= 0x01;	/* LE CS Subevent Result event */
4972 		events[6] |= 0x02;	/* LE CS Subevent Result Continue event */
4973 		events[6] |= 0x04;	/* LE CS Test End Complete event */
4974 	}
4975 
4976 	if (le_sci_capable(hdev))
4977 		events[6] |= 0x40;	/* LE Connection Rate Change event */
4978 
4979 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EVENT_MASK,
4980 				     sizeof(events), events, HCI_CMD_TIMEOUT);
4981 }
4982 
4983 /* Read LE Advertising Channel TX Power */
4984 static int hci_le_read_adv_tx_power_sync(struct hci_dev *hdev)
4985 {
4986 	if ((hdev->commands[25] & 0x40) && !ext_adv_capable(hdev)) {
4987 		/* HCI TS spec forbids mixing of legacy and extended
4988 		 * advertising commands wherein READ_ADV_TX_POWER is
4989 		 * also included. So do not call it if extended adv
4990 		 * is supported otherwise controller will return
4991 		 * COMMAND_DISALLOWED for extended commands.
4992 		 */
4993 		return __hci_cmd_sync_status(hdev,
4994 					       HCI_OP_LE_READ_ADV_TX_POWER,
4995 					       0, NULL, HCI_CMD_TIMEOUT);
4996 	}
4997 
4998 	return 0;
4999 }
5000 
5001 /* Read LE Min/Max Tx Power*/
5002 static int hci_le_read_tx_power_sync(struct hci_dev *hdev)
5003 {
5004 	if (!(hdev->commands[38] & 0x80) ||
5005 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_READ_TRANSMIT_POWER))
5006 		return 0;
5007 
5008 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_TRANSMIT_POWER,
5009 				     0, NULL, HCI_CMD_TIMEOUT);
5010 }
5011 
5012 /* Read LE Accept List Size */
5013 static int hci_le_read_accept_list_size_sync(struct hci_dev *hdev)
5014 {
5015 	if (!(hdev->commands[26] & 0x40))
5016 		return 0;
5017 
5018 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_ACCEPT_LIST_SIZE,
5019 				     0, NULL, HCI_CMD_TIMEOUT);
5020 }
5021 
5022 /* Read LE Resolving List Size */
5023 static int hci_le_read_resolv_list_size_sync(struct hci_dev *hdev)
5024 {
5025 	if (!(hdev->commands[34] & 0x40))
5026 		return 0;
5027 
5028 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_RESOLV_LIST_SIZE,
5029 				     0, NULL, HCI_CMD_TIMEOUT);
5030 }
5031 
5032 /* Clear LE Resolving List */
5033 static int hci_le_clear_resolv_list_sync(struct hci_dev *hdev)
5034 {
5035 	if (!(hdev->commands[34] & 0x20))
5036 		return 0;
5037 
5038 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CLEAR_RESOLV_LIST, 0, NULL,
5039 				     HCI_CMD_TIMEOUT);
5040 }
5041 
5042 /* Set RPA timeout */
5043 static int hci_le_set_rpa_timeout_sync(struct hci_dev *hdev)
5044 {
5045 	__le16 timeout = cpu_to_le16(hdev->rpa_timeout);
5046 
5047 	if (!(hdev->commands[35] & 0x04) ||
5048 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_SET_RPA_TIMEOUT))
5049 		return 0;
5050 
5051 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_RPA_TIMEOUT,
5052 				     sizeof(timeout), &timeout,
5053 				     HCI_CMD_TIMEOUT);
5054 }
5055 
5056 /* Read LE Maximum Data Length */
5057 static int hci_le_read_max_data_len_sync(struct hci_dev *hdev)
5058 {
5059 	if (!(hdev->le_features[0] & HCI_LE_DATA_LEN_EXT))
5060 		return 0;
5061 
5062 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_MAX_DATA_LEN, 0, NULL,
5063 				     HCI_CMD_TIMEOUT);
5064 }
5065 
5066 /* Read LE Suggested Default Data Length */
5067 static int hci_le_read_def_data_len_sync(struct hci_dev *hdev)
5068 {
5069 	if (!(hdev->le_features[0] & HCI_LE_DATA_LEN_EXT))
5070 		return 0;
5071 
5072 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_DEF_DATA_LEN, 0, NULL,
5073 				     HCI_CMD_TIMEOUT);
5074 }
5075 
5076 /* Read LE Number of Supported Advertising Sets */
5077 static int hci_le_read_num_support_adv_sets_sync(struct hci_dev *hdev)
5078 {
5079 	if (!ext_adv_capable(hdev))
5080 		return 0;
5081 
5082 	return __hci_cmd_sync_status(hdev,
5083 				     HCI_OP_LE_READ_NUM_SUPPORTED_ADV_SETS,
5084 				     0, NULL, HCI_CMD_TIMEOUT);
5085 }
5086 
5087 /* Write LE Host Supported */
5088 static int hci_set_le_support_sync(struct hci_dev *hdev)
5089 {
5090 	struct hci_cp_write_le_host_supported cp;
5091 
5092 	/* LE-only devices do not support explicit enablement */
5093 	if (!lmp_bredr_capable(hdev))
5094 		return 0;
5095 
5096 	memset(&cp, 0, sizeof(cp));
5097 
5098 	if (hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
5099 		cp.le = 0x01;
5100 		cp.simul = 0x00;
5101 	}
5102 
5103 	if (cp.le == lmp_host_le_capable(hdev))
5104 		return 0;
5105 
5106 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LE_HOST_SUPPORTED,
5107 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5108 }
5109 
5110 /* LE Set Host Feature V2 */
5111 static int hci_le_set_host_feature_v2_sync(struct hci_dev *hdev, u16 bit,
5112 					   u8 value)
5113 {
5114 	struct hci_cp_le_set_host_feature_v2 cp;
5115 
5116 	memset(&cp, 0, sizeof(cp));
5117 
5118 	/* Connected Isochronous Channels (Host Support) */
5119 	cp.bit_number = cpu_to_le16(bit);
5120 	cp.bit_value = value;
5121 
5122 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_HOST_FEATURE_V2,
5123 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5124 }
5125 
5126 /* LE Set Host Feature */
5127 static int hci_le_set_host_feature_sync(struct hci_dev *hdev, u16 bit, u8 value)
5128 {
5129 	struct hci_cp_le_set_host_feature cp;
5130 
5131 	if (ll_ext_feature_capable(hdev) && hdev->commands[47] & BIT(4))
5132 		return hci_le_set_host_feature_v2_sync(hdev, bit, value);
5133 
5134 	if (bit > 255)
5135 		return 0;
5136 
5137 	memset(&cp, 0, sizeof(cp));
5138 
5139 	/* Connected Isochronous Channels (Host Support) */
5140 	cp.bit_number = bit;
5141 	cp.bit_value = value;
5142 
5143 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_HOST_FEATURE,
5144 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5145 }
5146 
5147 static int hci_le_read_conn_interval_sync(struct hci_dev *hdev)
5148 {
5149 	if (!le_sci_capable(hdev))
5150 		return 0;
5151 
5152 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_CONN_INTERVAL,
5153 				     0, NULL, HCI_CMD_TIMEOUT);
5154 }
5155 
5156 static int hci_le_set_def_rate_sync(struct hci_dev *hdev)
5157 {
5158 	struct hci_cp_le_set_def_rate cp;
5159 	u16 interval_min = 0x000a;	/* 1.25 ms */
5160 	u16 interval_max = 0x0078;	/* 15 ms */
5161 	u16 subrate_max = 0x0004;
5162 	u16 max_latency = 0x0000;
5163 	u32 supv_timeout;
5164 
5165 	if (!le_sci_capable(hdev))
5166 		return 0;
5167 
5168 	/* Clamp the interval range to the controller's minimum supported
5169 	 * connection interval (read via HCI_OP_LE_READ_CONN_INTERVAL) so the
5170 	 * default rate parameters are not rejected. The maximum is raised as
5171 	 * well if needed to keep interval_min <= interval_max.
5172 	 */
5173 	if (hdev->le_min_rate_interval > interval_min) {
5174 		interval_min = hdev->le_min_rate_interval;
5175 		if (interval_min > interval_max)
5176 			interval_max = interval_min;
5177 	}
5178 
5179 	memset(&cp, 0, sizeof(cp));
5180 
5181 	/* Use the HIDS 1.2 recommended Full Range mode values as the default
5182 	 * rate parameters (see HOGP v1.2 spec). Connection intervals are in
5183 	 * units of 0.125 ms and the supervision timeout is in units of 10 ms.
5184 	 */
5185 	cp.interval_min = cpu_to_le16(interval_min);
5186 	cp.interval_max = cpu_to_le16(interval_max);
5187 	cp.subrate_min = cpu_to_le16(0x0001);
5188 	cp.subrate_max = cpu_to_le16(subrate_max);
5189 	cp.max_latency = cpu_to_le16(max_latency);
5190 	cp.cont_num = cpu_to_le16(0x0001);
5191 
5192 	/* HOGP v1.2 recommends a Supervision_Timeout greater than or equal to
5193 	 * (1 + Max_Latency) x Subrate_Max x Connection_Interval_Max x 2, but
5194 	 * the Core spec treats the equality as invalid:
5195 	 *
5196 	 * BLUETOOTH CORE SPECIFICATION Version 6.3 | Vol 4, Part E
5197 	 * 7.8.158. LE Set Default Rate Parameters command
5198 	 *
5199 	 * If Connection_Interval_Max x Subrate_Max x (Max_Latency + 1) is
5200 	 * greater than or equal to Supervision_Timeout x 40, the Controller
5201 	 * shall return the error code Invalid HCI Command Parameters (0x12).
5202 	 *
5203 	 * So default to 2 s, 10x lower than the 20 s used for non-SCI
5204 	 * connections while still well above the minimum required, but make
5205 	 * sure it stays strictly above the minimum in case interval_max has
5206 	 * been raised.
5207 	 */
5208 	supv_timeout = (u32)interval_max * subrate_max * (max_latency + 1);
5209 	supv_timeout = supv_timeout / 40 + 1;
5210 	supv_timeout = clamp_t(u32, max_t(u32, supv_timeout, 0x00c8),
5211 			       0x000a, 0x0c80);
5212 	cp.supv_timeout = cpu_to_le16(supv_timeout);
5213 
5214 	/* The connection event length recommended in requests by a Peripheral
5215 	 * uses units of 125 us with a valid range of 0x0001 to 0x7CFF
5216 	 * (0.125 ms to 3.999875 s), so 0x0000 cannot be used. Also note that
5217 	 * the Controller is not required to use these values:
5218 	 *
5219 	 * BLUETOOTH CORE SPECIFICATION Version 6.2 | Vol 4, Part E
5220 	 * 7.8.158. LE Set Default Rate Parameters command
5221 	 *
5222 	 * The Min_CE_Length and Max_CE_Length parameters provide the
5223 	 * Controller with the expected minimum and maximum length of the
5224 	 * connection events. The Controller is not required to use these
5225 	 * values.
5226 	 *
5227 	 * So it is safe to just use the minimum.
5228 	 */
5229 	cp.min_ce_len = cpu_to_le16(0x0001);
5230 	cp.max_ce_len = cpu_to_le16(0x0001);
5231 
5232 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_DEF_RATE,
5233 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5234 }
5235 
5236 /* Set Host Features, each feature needs to be sent separately since
5237  * HCI_OP_LE_SET_HOST_FEATURE doesn't support setting all of them at once.
5238  */
5239 static int hci_le_set_host_features_sync(struct hci_dev *hdev)
5240 {
5241 	int err = 0;
5242 
5243 	if (cis_capable(hdev)) {
5244 		/* Connected Isochronous Channels (Host Support) */
5245 		err = hci_le_set_host_feature_sync(hdev, 32,
5246 						   (iso_enabled(hdev) ? 0x01 :
5247 						    0x00));
5248 		if (err)
5249 			return err;
5250 	}
5251 
5252 	if (le_cs_capable(hdev)) {
5253 		/* Channel Sounding (Host Support) */
5254 		err = hci_le_set_host_feature_sync(hdev, 47, 0x01);
5255 		if (err)
5256 			return err;
5257 	}
5258 
5259 	if (le_sci_capable(hdev))
5260 		/* Shorter Connection Intervals (Host Support) */
5261 		err = hci_le_set_host_feature_sync(hdev, 73, 0x01);
5262 
5263 	return err;
5264 }
5265 
5266 /* LE Controller init stage 3 command sequence */
5267 static const struct hci_init_stage le_init3[] = {
5268 	/* HCI_OP_LE_SET_EVENT_MASK */
5269 	HCI_INIT(hci_le_set_event_mask_sync),
5270 	/* HCI_OP_LE_READ_ADV_TX_POWER */
5271 	HCI_INIT(hci_le_read_adv_tx_power_sync),
5272 	/* HCI_OP_LE_READ_TRANSMIT_POWER */
5273 	HCI_INIT(hci_le_read_tx_power_sync),
5274 	/* HCI_OP_LE_READ_ACCEPT_LIST_SIZE */
5275 	HCI_INIT(hci_le_read_accept_list_size_sync),
5276 	/* HCI_OP_LE_CLEAR_ACCEPT_LIST */
5277 	HCI_INIT(hci_le_clear_accept_list_sync),
5278 	/* HCI_OP_LE_READ_RESOLV_LIST_SIZE */
5279 	HCI_INIT(hci_le_read_resolv_list_size_sync),
5280 	/* HCI_OP_LE_CLEAR_RESOLV_LIST */
5281 	HCI_INIT(hci_le_clear_resolv_list_sync),
5282 	/* HCI_OP_LE_SET_RPA_TIMEOUT */
5283 	HCI_INIT(hci_le_set_rpa_timeout_sync),
5284 	/* HCI_OP_LE_READ_MAX_DATA_LEN */
5285 	HCI_INIT(hci_le_read_max_data_len_sync),
5286 	/* HCI_OP_LE_READ_DEF_DATA_LEN */
5287 	HCI_INIT(hci_le_read_def_data_len_sync),
5288 	/* HCI_OP_LE_READ_NUM_SUPPORTED_ADV_SETS */
5289 	HCI_INIT(hci_le_read_num_support_adv_sets_sync),
5290 	/* HCI_OP_WRITE_LE_HOST_SUPPORTED */
5291 	HCI_INIT(hci_set_le_support_sync),
5292 	/* HCI_OP_LE_SET_HOST_FEATURE */
5293 	HCI_INIT(hci_le_set_host_features_sync),
5294 	/* HCI_OP_LE_READ_CONN_INTERVAL */
5295 	HCI_INIT(hci_le_read_conn_interval_sync),
5296 	/* HCI_OP_LE_SET_DEF_RATE */
5297 	HCI_INIT(hci_le_set_def_rate_sync),
5298 	{}
5299 };
5300 
5301 static int hci_init3_sync(struct hci_dev *hdev)
5302 {
5303 	int err;
5304 
5305 	bt_dev_dbg(hdev, "");
5306 
5307 	err = hci_init_stage_sync(hdev, hci_init3);
5308 	if (err)
5309 		return err;
5310 
5311 	if (lmp_le_capable(hdev))
5312 		return hci_init_stage_sync(hdev, le_init3);
5313 
5314 	return 0;
5315 }
5316 
5317 static int hci_delete_stored_link_key_sync(struct hci_dev *hdev)
5318 {
5319 	struct hci_cp_delete_stored_link_key cp;
5320 
5321 	/* Some Broadcom based Bluetooth controllers do not support the
5322 	 * Delete Stored Link Key command. They are clearly indicating its
5323 	 * absence in the bit mask of supported commands.
5324 	 *
5325 	 * Check the supported commands and only if the command is marked
5326 	 * as supported send it. If not supported assume that the controller
5327 	 * does not have actual support for stored link keys which makes this
5328 	 * command redundant anyway.
5329 	 *
5330 	 * Some controllers indicate that they support handling deleting
5331 	 * stored link keys, but they don't. The quirk lets a driver
5332 	 * just disable this command.
5333 	 */
5334 	if (!(hdev->commands[6] & 0x80) ||
5335 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY))
5336 		return 0;
5337 
5338 	memset(&cp, 0, sizeof(cp));
5339 	bacpy(&cp.bdaddr, BDADDR_ANY);
5340 	cp.delete_all = 0x01;
5341 
5342 	return __hci_cmd_sync_status(hdev, HCI_OP_DELETE_STORED_LINK_KEY,
5343 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5344 }
5345 
5346 static int hci_set_event_mask_page_2_sync(struct hci_dev *hdev)
5347 {
5348 	u8 events[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
5349 	bool changed = false;
5350 
5351 	/* Set event mask page 2 if the HCI command for it is supported */
5352 	if (!(hdev->commands[22] & 0x04))
5353 		return 0;
5354 
5355 	/* If Connectionless Peripheral Broadcast central role is supported
5356 	 * enable all necessary events for it.
5357 	 */
5358 	if (lmp_cpb_central_capable(hdev)) {
5359 		events[1] |= 0x40;	/* Triggered Clock Capture */
5360 		events[1] |= 0x80;	/* Synchronization Train Complete */
5361 		events[2] |= 0x08;	/* Truncated Page Complete */
5362 		events[2] |= 0x20;	/* CPB Channel Map Change */
5363 		changed = true;
5364 	}
5365 
5366 	/* If Connectionless Peripheral Broadcast peripheral role is supported
5367 	 * enable all necessary events for it.
5368 	 */
5369 	if (lmp_cpb_peripheral_capable(hdev)) {
5370 		events[2] |= 0x01;	/* Synchronization Train Received */
5371 		events[2] |= 0x02;	/* CPB Receive */
5372 		events[2] |= 0x04;	/* CPB Timeout */
5373 		events[2] |= 0x10;	/* Peripheral Page Response Timeout */
5374 		changed = true;
5375 	}
5376 
5377 	/* Enable Authenticated Payload Timeout Expired event if supported */
5378 	if (lmp_ping_capable(hdev) || hdev->le_features[0] & HCI_LE_PING) {
5379 		events[2] |= 0x80;
5380 		changed = true;
5381 	}
5382 
5383 	/* Some Broadcom based controllers indicate support for Set Event
5384 	 * Mask Page 2 command, but then actually do not support it. Since
5385 	 * the default value is all bits set to zero, the command is only
5386 	 * required if the event mask has to be changed. In case no change
5387 	 * to the event mask is needed, skip this command.
5388 	 */
5389 	if (!changed)
5390 		return 0;
5391 
5392 	return __hci_cmd_sync_status(hdev, HCI_OP_SET_EVENT_MASK_PAGE_2,
5393 				     sizeof(events), events, HCI_CMD_TIMEOUT);
5394 }
5395 
5396 /* Read local codec list if the HCI command is supported */
5397 static int hci_read_local_codecs_sync(struct hci_dev *hdev)
5398 {
5399 	if (hdev->commands[45] & 0x04)
5400 		hci_read_supported_codecs_v2(hdev);
5401 	else if (hdev->commands[29] & 0x20)
5402 		hci_read_supported_codecs(hdev);
5403 
5404 	return 0;
5405 }
5406 
5407 /* Read local pairing options if the HCI command is supported */
5408 static int hci_read_local_pairing_opts_sync(struct hci_dev *hdev)
5409 {
5410 	if (!(hdev->commands[41] & 0x08))
5411 		return 0;
5412 
5413 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_PAIRING_OPTS,
5414 				     0, NULL, HCI_CMD_TIMEOUT);
5415 }
5416 
5417 /* Get MWS transport configuration if the HCI command is supported */
5418 static int hci_get_mws_transport_config_sync(struct hci_dev *hdev)
5419 {
5420 	if (!mws_transport_config_capable(hdev))
5421 		return 0;
5422 
5423 	return __hci_cmd_sync_status(hdev, HCI_OP_GET_MWS_TRANSPORT_CONFIG,
5424 				     0, NULL, HCI_CMD_TIMEOUT);
5425 }
5426 
5427 /* Check for Synchronization Train support */
5428 static int hci_read_sync_train_params_sync(struct hci_dev *hdev)
5429 {
5430 	if (!lmp_sync_train_capable(hdev))
5431 		return 0;
5432 
5433 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_SYNC_TRAIN_PARAMS,
5434 				     0, NULL, HCI_CMD_TIMEOUT);
5435 }
5436 
5437 /* Enable Secure Connections if supported and configured */
5438 static int hci_write_sc_support_1_sync(struct hci_dev *hdev)
5439 {
5440 	u8 support = 0x01;
5441 
5442 	if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED) ||
5443 	    !bredr_sc_enabled(hdev))
5444 		return 0;
5445 
5446 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SC_SUPPORT,
5447 				     sizeof(support), &support,
5448 				     HCI_CMD_TIMEOUT);
5449 }
5450 
5451 /* Set erroneous data reporting if supported to the wideband speech
5452  * setting value
5453  */
5454 static int hci_set_err_data_report_sync(struct hci_dev *hdev)
5455 {
5456 	struct hci_cp_write_def_err_data_reporting cp;
5457 	bool enabled = hci_dev_test_flag(hdev, HCI_WIDEBAND_SPEECH_ENABLED);
5458 
5459 	if (!(hdev->commands[18] & 0x08) ||
5460 	    !(hdev->features[0][6] & LMP_ERR_DATA_REPORTING) ||
5461 	    hci_test_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING))
5462 		return 0;
5463 
5464 	if (enabled == hdev->err_data_reporting)
5465 		return 0;
5466 
5467 	memset(&cp, 0, sizeof(cp));
5468 	cp.err_data_reporting = enabled ? ERR_DATA_REPORTING_ENABLED :
5469 				ERR_DATA_REPORTING_DISABLED;
5470 
5471 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_DEF_ERR_DATA_REPORTING,
5472 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5473 }
5474 
5475 static const struct hci_init_stage hci_init4[] = {
5476 	 /* HCI_OP_DELETE_STORED_LINK_KEY */
5477 	HCI_INIT(hci_delete_stored_link_key_sync),
5478 	/* HCI_OP_SET_EVENT_MASK_PAGE_2 */
5479 	HCI_INIT(hci_set_event_mask_page_2_sync),
5480 	/* HCI_OP_READ_LOCAL_CODECS */
5481 	HCI_INIT(hci_read_local_codecs_sync),
5482 	 /* HCI_OP_READ_LOCAL_PAIRING_OPTS */
5483 	HCI_INIT(hci_read_local_pairing_opts_sync),
5484 	 /* HCI_OP_GET_MWS_TRANSPORT_CONFIG */
5485 	HCI_INIT(hci_get_mws_transport_config_sync),
5486 	 /* HCI_OP_READ_SYNC_TRAIN_PARAMS */
5487 	HCI_INIT(hci_read_sync_train_params_sync),
5488 	/* HCI_OP_WRITE_SC_SUPPORT */
5489 	HCI_INIT(hci_write_sc_support_1_sync),
5490 	/* HCI_OP_WRITE_DEF_ERR_DATA_REPORTING */
5491 	HCI_INIT(hci_set_err_data_report_sync),
5492 	{}
5493 };
5494 
5495 /* Set Suggested Default Data Length to maximum if supported */
5496 static int hci_le_set_write_def_data_len_sync(struct hci_dev *hdev)
5497 {
5498 	struct hci_cp_le_write_def_data_len cp;
5499 
5500 	if (!(hdev->le_features[0] & HCI_LE_DATA_LEN_EXT))
5501 		return 0;
5502 
5503 	memset(&cp, 0, sizeof(cp));
5504 	cp.tx_len = cpu_to_le16(hdev->le_max_tx_len);
5505 	cp.tx_time = cpu_to_le16(hdev->le_max_tx_time);
5506 
5507 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_WRITE_DEF_DATA_LEN,
5508 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5509 }
5510 
5511 /* Set Default PHY parameters if command is supported, enables all supported
5512  * PHYs according to the LE Features bits.
5513  */
5514 static int hci_le_set_default_phy_sync(struct hci_dev *hdev)
5515 {
5516 	struct hci_cp_le_set_default_phy cp;
5517 
5518 	if (!(hdev->commands[35] & 0x20)) {
5519 		/* If the command is not supported it means only 1M PHY is
5520 		 * supported.
5521 		 */
5522 		hdev->le_tx_def_phys = HCI_LE_SET_PHY_1M;
5523 		hdev->le_rx_def_phys = HCI_LE_SET_PHY_1M;
5524 		return 0;
5525 	}
5526 
5527 	memset(&cp, 0, sizeof(cp));
5528 	cp.all_phys = 0x00;
5529 	cp.tx_phys = HCI_LE_SET_PHY_1M;
5530 	cp.rx_phys = HCI_LE_SET_PHY_1M;
5531 
5532 	/* Enables 2M PHY if supported */
5533 	if (le_2m_capable(hdev)) {
5534 		cp.tx_phys |= HCI_LE_SET_PHY_2M;
5535 		cp.rx_phys |= HCI_LE_SET_PHY_2M;
5536 	}
5537 
5538 	/* Enables Coded PHY if supported */
5539 	if (le_coded_capable(hdev)) {
5540 		cp.tx_phys |= HCI_LE_SET_PHY_CODED;
5541 		cp.rx_phys |= HCI_LE_SET_PHY_CODED;
5542 	}
5543 
5544 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_DEFAULT_PHY,
5545 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5546 }
5547 
5548 static const struct hci_init_stage le_init4[] = {
5549 	/* HCI_OP_LE_WRITE_DEF_DATA_LEN */
5550 	HCI_INIT(hci_le_set_write_def_data_len_sync),
5551 	/* HCI_OP_LE_SET_DEFAULT_PHY */
5552 	HCI_INIT(hci_le_set_default_phy_sync),
5553 	{}
5554 };
5555 
5556 static int hci_init4_sync(struct hci_dev *hdev)
5557 {
5558 	int err;
5559 
5560 	bt_dev_dbg(hdev, "");
5561 
5562 	err = hci_init_stage_sync(hdev, hci_init4);
5563 	if (err)
5564 		return err;
5565 
5566 	if (lmp_le_capable(hdev))
5567 		return hci_init_stage_sync(hdev, le_init4);
5568 
5569 	return 0;
5570 }
5571 
5572 static int hci_init_sync(struct hci_dev *hdev)
5573 {
5574 	int err;
5575 
5576 	err = hci_init1_sync(hdev);
5577 	if (err < 0)
5578 		return err;
5579 
5580 	if (hci_dev_test_flag(hdev, HCI_SETUP))
5581 		hci_debugfs_create_basic(hdev);
5582 
5583 	err = hci_init2_sync(hdev);
5584 	if (err < 0)
5585 		return err;
5586 
5587 	err = hci_init3_sync(hdev);
5588 	if (err < 0)
5589 		return err;
5590 
5591 	err = hci_init4_sync(hdev);
5592 	if (err < 0)
5593 		return err;
5594 
5595 	/* This function is only called when the controller is actually in
5596 	 * configured state. When the controller is marked as unconfigured,
5597 	 * this initialization procedure is not run.
5598 	 *
5599 	 * It means that it is possible that a controller runs through its
5600 	 * setup phase and then discovers missing settings. If that is the
5601 	 * case, then this function will not be called. It then will only
5602 	 * be called during the config phase.
5603 	 *
5604 	 * So only when in setup phase or config phase, create the debugfs
5605 	 * entries and register the SMP channels.
5606 	 */
5607 	if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
5608 	    !hci_dev_test_flag(hdev, HCI_CONFIG))
5609 		return 0;
5610 
5611 	if (hci_dev_test_and_set_flag(hdev, HCI_DEBUGFS_CREATED))
5612 		return 0;
5613 
5614 	hci_debugfs_create_common(hdev);
5615 
5616 	if (lmp_bredr_capable(hdev))
5617 		hci_debugfs_create_bredr(hdev);
5618 
5619 	if (lmp_le_capable(hdev))
5620 		hci_debugfs_create_le(hdev);
5621 
5622 	return 0;
5623 }
5624 
5625 #define HCI_QUIRK_BROKEN(_quirk, _desc) { HCI_QUIRK_BROKEN_##_quirk, _desc }
5626 
5627 static const struct {
5628 	unsigned long quirk;
5629 	const char *desc;
5630 } hci_broken_table[] = {
5631 	HCI_QUIRK_BROKEN(LOCAL_COMMANDS,
5632 			 "HCI Read Local Supported Commands not supported"),
5633 	HCI_QUIRK_BROKEN(STORED_LINK_KEY,
5634 			 "HCI Delete Stored Link Key command is advertised, "
5635 			 "but not supported."),
5636 	HCI_QUIRK_BROKEN(ERR_DATA_REPORTING,
5637 			 "HCI Read Default Erroneous Data Reporting command is "
5638 			 "advertised, but not supported."),
5639 	HCI_QUIRK_BROKEN(READ_TRANSMIT_POWER,
5640 			 "HCI Read Transmit Power Level command is advertised, "
5641 			 "but not supported."),
5642 	HCI_QUIRK_BROKEN(FILTER_CLEAR_ALL,
5643 			 "HCI Set Event Filter command not supported."),
5644 	HCI_QUIRK_BROKEN(ENHANCED_SETUP_SYNC_CONN,
5645 			 "HCI Enhanced Setup Synchronous Connection command is "
5646 			 "advertised, but not supported."),
5647 	HCI_QUIRK_BROKEN(SET_RPA_TIMEOUT,
5648 			 "HCI LE Set Random Private Address Timeout command is "
5649 			 "advertised, but not supported."),
5650 	HCI_QUIRK_BROKEN(EXT_CREATE_CONN,
5651 			 "HCI LE Extended Create Connection command is "
5652 			 "advertised, but not supported."),
5653 	HCI_QUIRK_BROKEN(WRITE_AUTH_PAYLOAD_TIMEOUT,
5654 			 "HCI WRITE AUTH PAYLOAD TIMEOUT command leads "
5655 			 "to unexpected SMP errors when pairing "
5656 			 "and will not be used."),
5657 	HCI_QUIRK_BROKEN(LE_CODED,
5658 			 "HCI LE Coded PHY feature bit is set, "
5659 			 "but its usage is not supported.")
5660 };
5661 
5662 /* This function handles hdev setup stage:
5663  *
5664  * Calls hdev->setup
5665  * Setup address if HCI_QUIRK_USE_BDADDR_PROPERTY is set.
5666  */
5667 static int hci_dev_setup_sync(struct hci_dev *hdev)
5668 {
5669 	int ret = 0;
5670 	bool invalid_bdaddr;
5671 	size_t i;
5672 
5673 	if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
5674 	    !hci_test_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_SETUP))
5675 		return 0;
5676 
5677 	bt_dev_dbg(hdev, "");
5678 
5679 	hci_sock_dev_event(hdev, HCI_DEV_SETUP);
5680 
5681 	if (hdev->setup)
5682 		ret = hdev->setup(hdev);
5683 
5684 	for (i = 0; i < ARRAY_SIZE(hci_broken_table); i++) {
5685 		if (hci_test_quirk(hdev, hci_broken_table[i].quirk))
5686 			bt_dev_warn(hdev, "%s", hci_broken_table[i].desc);
5687 	}
5688 
5689 	/* The transport driver can set the quirk to mark the
5690 	 * BD_ADDR invalid before creating the HCI device or in
5691 	 * its setup callback.
5692 	 */
5693 	invalid_bdaddr = hci_test_quirk(hdev, HCI_QUIRK_INVALID_BDADDR) ||
5694 			 hci_test_quirk(hdev, HCI_QUIRK_USE_BDADDR_PROPERTY);
5695 	if (!ret) {
5696 		if (hci_test_quirk(hdev, HCI_QUIRK_USE_BDADDR_PROPERTY) &&
5697 		    !bacmp(&hdev->public_addr, BDADDR_ANY))
5698 			hci_dev_get_bd_addr_from_property(hdev);
5699 
5700 		if (invalid_bdaddr && bacmp(&hdev->public_addr, BDADDR_ANY) &&
5701 		    hdev->set_bdaddr) {
5702 			ret = hdev->set_bdaddr(hdev, &hdev->public_addr);
5703 			if (!ret)
5704 				invalid_bdaddr = false;
5705 		}
5706 	}
5707 
5708 	/* The transport driver can set these quirks before
5709 	 * creating the HCI device or in its setup callback.
5710 	 *
5711 	 * For the invalid BD_ADDR quirk it is possible that
5712 	 * it becomes a valid address if the bootloader does
5713 	 * provide it (see above).
5714 	 *
5715 	 * In case any of them is set, the controller has to
5716 	 * start up as unconfigured.
5717 	 */
5718 	if (hci_test_quirk(hdev, HCI_QUIRK_EXTERNAL_CONFIG) ||
5719 	    invalid_bdaddr)
5720 		hci_dev_set_flag(hdev, HCI_UNCONFIGURED);
5721 
5722 	/* For an unconfigured controller it is required to
5723 	 * read at least the version information provided by
5724 	 * the Read Local Version Information command.
5725 	 *
5726 	 * If the set_bdaddr driver callback is provided, then
5727 	 * also the original Bluetooth public device address
5728 	 * will be read using the Read BD Address command.
5729 	 */
5730 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
5731 		return hci_unconf_init_sync(hdev);
5732 
5733 	return ret;
5734 }
5735 
5736 /* This function handles hdev init stage:
5737  *
5738  * Calls hci_dev_setup_sync to perform setup stage
5739  * Calls hci_init_sync to perform HCI command init sequence
5740  */
5741 static int hci_dev_init_sync(struct hci_dev *hdev)
5742 {
5743 	int ret;
5744 
5745 	bt_dev_dbg(hdev, "");
5746 
5747 	atomic_set(&hdev->cmd_cnt, 1);
5748 	set_bit(HCI_INIT, &hdev->flags);
5749 
5750 	ret = hci_dev_setup_sync(hdev);
5751 
5752 	if (hci_dev_test_flag(hdev, HCI_CONFIG)) {
5753 		/* If public address change is configured, ensure that
5754 		 * the address gets programmed. If the driver does not
5755 		 * support changing the public address, fail the power
5756 		 * on procedure.
5757 		 */
5758 		if (bacmp(&hdev->public_addr, BDADDR_ANY) &&
5759 		    hdev->set_bdaddr)
5760 			ret = hdev->set_bdaddr(hdev, &hdev->public_addr);
5761 		else
5762 			ret = -EADDRNOTAVAIL;
5763 	}
5764 
5765 	if (!ret) {
5766 		if (!hci_dev_test_flag(hdev, HCI_UNCONFIGURED) &&
5767 		    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
5768 			ret = hci_init_sync(hdev);
5769 			if (!ret && hdev->post_init)
5770 				ret = hdev->post_init(hdev);
5771 		}
5772 	}
5773 
5774 	/* If the HCI Reset command is clearing all diagnostic settings,
5775 	 * then they need to be reprogrammed after the init procedure
5776 	 * completed.
5777 	 */
5778 	if (hci_test_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_DIAG) &&
5779 	    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
5780 	    hci_dev_test_flag(hdev, HCI_VENDOR_DIAG) && hdev->set_diag)
5781 		ret = hdev->set_diag(hdev, true);
5782 
5783 	if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
5784 		msft_do_open(hdev);
5785 		aosp_do_open(hdev);
5786 	}
5787 
5788 	clear_bit(HCI_INIT, &hdev->flags);
5789 
5790 	return ret;
5791 }
5792 
5793 static void hci_dev_drop_last_cmd_req_and_close(struct hci_dev *hdev)
5794 {
5795 	/* Drop last sent command */
5796 	if (hdev->sent_cmd) {
5797 		cancel_delayed_work_sync(&hdev->cmd_timer);
5798 		kfree_skb(hdev->sent_cmd);
5799 		hdev->sent_cmd = NULL;
5800 	}
5801 
5802 	/* Drop last request */
5803 	if (hdev->req_skb) {
5804 		kfree_skb(hdev->req_skb);
5805 		hdev->req_skb = NULL;
5806 		hci_dev_clear_flag(hdev, HCI_CMD_PENDING);
5807 	}
5808 
5809 	clear_bit(HCI_RUNNING, &hdev->flags);
5810 	hci_sock_dev_event(hdev, HCI_DEV_CLOSE);
5811 
5812 	/* After this point our queues are empty and no tasks are scheduled. */
5813 	hdev->close(hdev);
5814 	hdev->flags &= BIT(HCI_RAW);
5815 }
5816 
5817 int hci_dev_open_sync(struct hci_dev *hdev)
5818 {
5819 	int ret;
5820 
5821 	bt_dev_dbg(hdev, "");
5822 
5823 	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
5824 		ret = -ENODEV;
5825 		goto done;
5826 	}
5827 
5828 	if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
5829 	    !hci_dev_test_flag(hdev, HCI_CONFIG)) {
5830 		/* Check for rfkill but allow the HCI setup stage to
5831 		 * proceed (which in itself doesn't cause any RF activity).
5832 		 */
5833 		if (hci_dev_test_flag(hdev, HCI_RFKILLED)) {
5834 			ret = -ERFKILL;
5835 			goto done;
5836 		}
5837 
5838 		/* Check for valid public address or a configured static
5839 		 * random address, but let the HCI setup proceed to
5840 		 * be able to determine if there is a public address
5841 		 * or not.
5842 		 *
5843 		 * In case of user channel usage, it is not important
5844 		 * if a public address or static random address is
5845 		 * available.
5846 		 */
5847 		if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
5848 		    !bacmp(&hdev->bdaddr, BDADDR_ANY) &&
5849 		    !bacmp(&hdev->static_addr, BDADDR_ANY)) {
5850 			ret = -EADDRNOTAVAIL;
5851 			goto done;
5852 		}
5853 	}
5854 
5855 	if (test_bit(HCI_UP, &hdev->flags)) {
5856 		ret = -EALREADY;
5857 		goto done;
5858 	}
5859 
5860 	if (hdev->open(hdev)) {
5861 		ret = -EIO;
5862 		goto done;
5863 	}
5864 
5865 	hci_dev_lock(hdev);
5866 	hci_devcd_reset(hdev);
5867 	hci_dev_unlock(hdev);
5868 
5869 	set_bit(HCI_RUNNING, &hdev->flags);
5870 	hci_sock_dev_event(hdev, HCI_DEV_OPEN);
5871 
5872 	ret = hci_dev_init_sync(hdev);
5873 	if (!ret) {
5874 		hci_dev_hold(hdev);
5875 		hci_dev_set_flag(hdev, HCI_RPA_EXPIRED);
5876 		hci_dev_lock(hdev);
5877 		hci_adv_instances_set_rpa_expired(hdev, true);
5878 		hci_dev_unlock(hdev);
5879 		set_bit(HCI_UP, &hdev->flags);
5880 		hci_sock_dev_event(hdev, HCI_DEV_UP);
5881 		hci_leds_update_powered(hdev, true);
5882 		if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
5883 		    !hci_dev_test_flag(hdev, HCI_CONFIG) &&
5884 		    !hci_dev_test_flag(hdev, HCI_UNCONFIGURED) &&
5885 		    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
5886 		    hci_dev_test_flag(hdev, HCI_MGMT)) {
5887 			ret = hci_powered_update_sync(hdev);
5888 			mgmt_power_on(hdev, ret);
5889 		}
5890 	} else {
5891 		/* Init failed, cleanup */
5892 		flush_work(&hdev->tx_work);
5893 
5894 		/* Since hci_rx_work() is possible to awake new cmd_work
5895 		 * it should be flushed first to avoid unexpected call of
5896 		 * hci_cmd_work()
5897 		 */
5898 		flush_work(&hdev->rx_work);
5899 		flush_work(&hdev->cmd_work);
5900 
5901 		skb_queue_purge(&hdev->cmd_q);
5902 		skb_queue_purge(&hdev->rx_q);
5903 
5904 		if (hdev->flush)
5905 			hdev->flush(hdev);
5906 
5907 		hci_dev_drop_last_cmd_req_and_close(hdev);
5908 	}
5909 
5910 done:
5911 	return ret;
5912 }
5913 
5914 /* This function requires the caller holds hdev->lock */
5915 static void hci_pend_le_actions_clear(struct hci_dev *hdev)
5916 {
5917 	struct hci_conn_params *p;
5918 
5919 	list_for_each_entry(p, &hdev->le_conn_params, list) {
5920 		hci_pend_le_list_del_init(p);
5921 		if (p->conn) {
5922 			hci_conn_drop(p->conn);
5923 			hci_conn_put(p->conn);
5924 			p->conn = NULL;
5925 		}
5926 	}
5927 
5928 	BT_DBG("All LE pending actions cleared");
5929 }
5930 
5931 static int hci_dev_shutdown(struct hci_dev *hdev)
5932 {
5933 	int err = 0;
5934 	/* Similar to how we first do setup and then set the exclusive access
5935 	 * bit for userspace, we must first unset userchannel and then clean up.
5936 	 * Otherwise, the kernel can't properly use the hci channel to clean up
5937 	 * the controller (some shutdown routines require sending additional
5938 	 * commands to the controller for example).
5939 	 */
5940 	bool was_userchannel =
5941 		hci_dev_test_and_clear_flag(hdev, HCI_USER_CHANNEL);
5942 
5943 	if (!hci_dev_test_flag(hdev, HCI_UNREGISTER) &&
5944 	    test_bit(HCI_UP, &hdev->flags)) {
5945 		/* Execute vendor specific shutdown routine */
5946 		if (hdev->shutdown)
5947 			err = hdev->shutdown(hdev);
5948 	}
5949 
5950 	if (was_userchannel)
5951 		hci_dev_set_flag(hdev, HCI_USER_CHANNEL);
5952 
5953 	return err;
5954 }
5955 
5956 int hci_dev_close_sync(struct hci_dev *hdev)
5957 {
5958 	struct hci_conn *conn;
5959 	bool auto_off;
5960 	int err = 0;
5961 
5962 	bt_dev_dbg(hdev, "");
5963 
5964 	/* Set HCI_DRAIN_WORKQUEUE flag to prevent queuing work during
5965 	 * reset/close. See hci_cmd_work() and handle_cmd_cnt_and_timer().
5966 	 */
5967 	hci_dev_set_flag(hdev, HCI_CMD_DRAIN_WORKQUEUE);
5968 	synchronize_rcu();
5969 
5970 	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
5971 		disable_delayed_work(&hdev->power_off);
5972 		disable_delayed_work(&hdev->ncmd_timer);
5973 		disable_delayed_work(&hdev->le_scan_disable);
5974 	} else {
5975 		cancel_delayed_work(&hdev->power_off);
5976 		cancel_delayed_work(&hdev->ncmd_timer);
5977 		cancel_delayed_work(&hdev->le_scan_disable);
5978 	}
5979 
5980 	hci_cmd_sync_cancel_sync(hdev, ENODEV);
5981 
5982 	cancel_interleave_scan(hdev);
5983 
5984 	if (hdev->adv_instance_timeout) {
5985 		cancel_delayed_work_sync(&hdev->adv_instance_expire);
5986 		hdev->adv_instance_timeout = false;
5987 	}
5988 
5989 	err = hci_dev_shutdown(hdev);
5990 
5991 	if (!test_and_clear_bit(HCI_UP, &hdev->flags)) {
5992 		cancel_delayed_work_sync(&hdev->cmd_timer);
5993 		hci_dev_clear_flag(hdev, HCI_CMD_DRAIN_WORKQUEUE);
5994 		return err;
5995 	}
5996 
5997 	/* Wait for hci_recv_frame() callers that still saw HCI_UP, so that
5998 	 * none of them queues rx_work while the workqueue is drained below.
5999 	 */
6000 	synchronize_rcu();
6001 
6002 	hci_leds_update_powered(hdev, false);
6003 
6004 	/* Flush RX and TX works */
6005 	flush_work(&hdev->tx_work);
6006 	flush_work(&hdev->rx_work);
6007 
6008 	if (hdev->discov_timeout > 0) {
6009 		hdev->discov_timeout = 0;
6010 		hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
6011 		hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
6012 	}
6013 
6014 	if (hci_dev_test_and_clear_flag(hdev, HCI_SERVICE_CACHE))
6015 		cancel_delayed_work(&hdev->service_cache);
6016 
6017 	if (hci_dev_test_flag(hdev, HCI_MGMT)) {
6018 		struct adv_info *adv_instance;
6019 
6020 		cancel_delayed_work_sync(&hdev->rpa_expired);
6021 
6022 		hci_dev_lock(hdev);
6023 		list_for_each_entry(adv_instance, &hdev->adv_instances, list)
6024 			cancel_delayed_work_sync(&adv_instance->rpa_expired_cb);
6025 		hci_dev_unlock(hdev);
6026 	}
6027 
6028 	/* A delayed work whose timer was armed before close would queue
6029 	 * itself while the workqueue is draining. Disable the connection
6030 	 * works so that hci_conn_drop() and the timers can no longer queue
6031 	 * them. The connections are deleted below, so nothing re-enables
6032 	 * them. HCI_UP is clear, so no new connection can be added after
6033 	 * this walk.
6034 	 */
6035 	hci_dev_lock(hdev);
6036 	list_for_each_entry(conn, &hdev->conn_hash.list, list) {
6037 		disable_delayed_work(&conn->disc_work);
6038 		disable_delayed_work(&conn->auto_accept_work);
6039 		disable_delayed_work(&conn->idle_work);
6040 		disable_delayed_work(&conn->le_conn_timeout);
6041 	}
6042 	hci_dev_unlock(hdev);
6043 
6044 	/* Avoid potential lockdep warnings from the *_flush() calls by
6045 	 * ensuring the workqueue is empty up front.
6046 	 */
6047 	drain_workqueue(hdev->workqueue);
6048 
6049 	hci_dev_lock(hdev);
6050 
6051 	hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
6052 
6053 	auto_off = hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF);
6054 
6055 	/* Nothing is going to send the mesh transmissions left, whether or not
6056 	 * mgmt is told about the controller being powered off.
6057 	 */
6058 	mgmt_mesh_flush(hdev);
6059 
6060 	if (!auto_off && !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
6061 	    hci_dev_test_flag(hdev, HCI_MGMT))
6062 		__mgmt_power_off(hdev);
6063 
6064 	hci_inquiry_cache_flush(hdev);
6065 	hci_pend_le_actions_clear(hdev);
6066 	hci_conn_hash_flush(hdev);
6067 	/* Prevent data races on hdev->smp_data or hdev->smp_bredr_data */
6068 	smp_unregister(hdev);
6069 	hci_dev_unlock(hdev);
6070 
6071 	hci_sock_dev_event(hdev, HCI_DEV_DOWN);
6072 
6073 	if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
6074 		aosp_do_close(hdev);
6075 		msft_do_close(hdev);
6076 	}
6077 
6078 	if (hdev->flush)
6079 		hdev->flush(hdev);
6080 
6081 	/* Reset device */
6082 	skb_queue_purge(&hdev->cmd_q);
6083 	atomic_set(&hdev->cmd_cnt, 1);
6084 	hdev->acl_cnt = 0;
6085 	hdev->sco_cnt = 0;
6086 	hdev->le_cnt = 0;
6087 	hdev->iso_cnt = 0;
6088 	if (hci_test_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE) &&
6089 	    !auto_off && !hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
6090 		set_bit(HCI_INIT, &hdev->flags);
6091 		hci_reset_sync(hdev);
6092 		clear_bit(HCI_INIT, &hdev->flags);
6093 	}
6094 
6095 	/* flush cmd  work */
6096 	flush_work(&hdev->cmd_work);
6097 
6098 	/* Drop queues */
6099 	skb_queue_purge(&hdev->rx_q);
6100 	skb_queue_purge(&hdev->cmd_q);
6101 	skb_queue_purge(&hdev->raw_q);
6102 
6103 	/* Drop last sent command, last request and close */
6104 	hci_dev_drop_last_cmd_req_and_close(hdev);
6105 
6106 	/* Clear flags */
6107 	hci_dev_clear_volatile_flags(hdev);
6108 	hci_dev_clear_flag(hdev, HCI_CMD_DRAIN_WORKQUEUE);
6109 
6110 	memset(hdev->eir, 0, sizeof(hdev->eir));
6111 	memset(hdev->dev_class, 0, sizeof(hdev->dev_class));
6112 	bacpy(&hdev->random_addr, BDADDR_ANY);
6113 	hci_dev_lock(hdev);
6114 	hci_codec_list_clear(&hdev->local_codecs);
6115 	hci_dev_unlock(hdev);
6116 
6117 	hci_dev_put(hdev);
6118 	return err;
6119 }
6120 
6121 /* This function perform power on HCI command sequence as follows:
6122  *
6123  * If controller is already up (HCI_UP) performs hci_powered_update_sync
6124  * sequence otherwise run hci_dev_open_sync which will follow with
6125  * hci_powered_update_sync after the init sequence is completed.
6126  */
6127 static int hci_power_on_sync(struct hci_dev *hdev)
6128 {
6129 	int err;
6130 
6131 	if (test_bit(HCI_UP, &hdev->flags) &&
6132 	    hci_dev_test_flag(hdev, HCI_MGMT) &&
6133 	    hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF)) {
6134 		cancel_delayed_work(&hdev->power_off);
6135 		return hci_powered_update_sync(hdev);
6136 	}
6137 
6138 	err = hci_dev_open_sync(hdev);
6139 	if (err < 0)
6140 		return err;
6141 
6142 	/* During the HCI setup phase, a few error conditions are
6143 	 * ignored and they need to be checked now. If they are still
6144 	 * valid, it is important to return the device back off.
6145 	 */
6146 	if (hci_dev_test_flag(hdev, HCI_RFKILLED) ||
6147 	    hci_dev_test_flag(hdev, HCI_UNCONFIGURED) ||
6148 	    (!bacmp(&hdev->bdaddr, BDADDR_ANY) &&
6149 	     !bacmp(&hdev->static_addr, BDADDR_ANY))) {
6150 		hci_dev_clear_flag(hdev, HCI_AUTO_OFF);
6151 		hci_dev_close_sync(hdev);
6152 	} else if (hci_dev_test_flag(hdev, HCI_AUTO_OFF)) {
6153 		queue_delayed_work(hdev->req_workqueue, &hdev->power_off,
6154 				   HCI_AUTO_OFF_TIMEOUT);
6155 	}
6156 
6157 	if (hci_dev_test_and_clear_flag(hdev, HCI_SETUP)) {
6158 		/* For unconfigured devices, set the HCI_RAW flag
6159 		 * so that userspace can easily identify them.
6160 		 */
6161 		if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
6162 			set_bit(HCI_RAW, &hdev->flags);
6163 
6164 		/* For fully configured devices, this will send
6165 		 * the Index Added event. For unconfigured devices,
6166 		 * it will send Unconfigued Index Added event.
6167 		 *
6168 		 * Devices with HCI_QUIRK_RAW_DEVICE are ignored
6169 		 * and no event will be send.
6170 		 */
6171 		mgmt_index_added(hdev);
6172 	} else if (hci_dev_test_and_clear_flag(hdev, HCI_CONFIG)) {
6173 		/* When the controller is now configured, then it
6174 		 * is important to clear the HCI_RAW flag.
6175 		 */
6176 		if (!hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
6177 			clear_bit(HCI_RAW, &hdev->flags);
6178 
6179 		/* Powering on the controller with HCI_CONFIG set only
6180 		 * happens with the transition from unconfigured to
6181 		 * configured. This will send the Index Added event.
6182 		 */
6183 		mgmt_index_added(hdev);
6184 	}
6185 
6186 	return 0;
6187 }
6188 
6189 static int hci_remote_name_cancel_sync(struct hci_dev *hdev, bdaddr_t *addr)
6190 {
6191 	struct hci_cp_remote_name_req_cancel cp;
6192 
6193 	memset(&cp, 0, sizeof(cp));
6194 	bacpy(&cp.bdaddr, addr);
6195 
6196 	return __hci_cmd_sync_status(hdev, HCI_OP_REMOTE_NAME_REQ_CANCEL,
6197 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6198 }
6199 
6200 int hci_stop_discovery_sync(struct hci_dev *hdev)
6201 {
6202 	struct discovery_state *d = &hdev->discovery;
6203 	struct inquiry_entry *e;
6204 	bdaddr_t addr;
6205 	int err;
6206 
6207 	bt_dev_dbg(hdev, "state %u", hdev->discovery.state);
6208 
6209 	if (d->state == DISCOVERY_FINDING || d->state == DISCOVERY_STOPPING) {
6210 		if (test_bit(HCI_INQUIRY, &hdev->flags)) {
6211 			err = __hci_cmd_sync_status(hdev, HCI_OP_INQUIRY_CANCEL,
6212 						    0, NULL, HCI_CMD_TIMEOUT);
6213 			if (err)
6214 				return err;
6215 		}
6216 
6217 		if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
6218 			err = hci_scan_disable_sync(hdev);
6219 			if (err)
6220 				return err;
6221 
6222 			/* Only cancel the LE scan timeout once the scan is
6223 			 * disabled, so that the discovery still ends if
6224 			 * stopping it failed.
6225 			 */
6226 			cancel_delayed_work(&hdev->le_scan_disable);
6227 		}
6228 
6229 	} else {
6230 		err = hci_scan_disable_sync(hdev);
6231 		if (err)
6232 			return err;
6233 	}
6234 
6235 	/* Resume advertising if it was paused */
6236 	if (ll_privacy_capable(hdev))
6237 		hci_resume_advertising_sync(hdev);
6238 
6239 	/* No further actions needed for LE-only discovery */
6240 	if (d->type == DISCOV_TYPE_LE)
6241 		return 0;
6242 
6243 	if (d->state == DISCOVERY_RESOLVING || d->state == DISCOVERY_STOPPING) {
6244 		hci_dev_lock(hdev);
6245 		e = hci_inquiry_cache_lookup_resolve(hdev, BDADDR_ANY,
6246 						     NAME_PENDING);
6247 		if (!e) {
6248 			hci_dev_unlock(hdev);
6249 			return 0;
6250 		}
6251 
6252 		bacpy(&addr, &e->data.bdaddr);
6253 		hci_dev_unlock(hdev);
6254 
6255 		/* Ignore cancel errors since it should interfere with stopping
6256 		 * of the discovery.
6257 		 */
6258 		hci_remote_name_cancel_sync(hdev, &addr);
6259 	}
6260 
6261 	return 0;
6262 }
6263 
6264 static int hci_disconnect_sync(struct hci_dev *hdev, struct hci_conn *conn,
6265 			       u8 reason)
6266 {
6267 	struct hci_cp_disconnect cp;
6268 
6269 	if (conn->type == BIS_LINK || conn->type == PA_LINK) {
6270 		/* This is a BIS connection, hci_conn_del will
6271 		 * do the necessary cleanup.
6272 		 */
6273 		hci_dev_lock(hdev);
6274 		hci_conn_failed(conn, reason);
6275 		hci_dev_unlock(hdev);
6276 
6277 		return 0;
6278 	}
6279 
6280 	memset(&cp, 0, sizeof(cp));
6281 	cp.handle = cpu_to_le16(conn->handle);
6282 	cp.reason = reason;
6283 
6284 	/* Wait for HCI_EV_DISCONN_COMPLETE, not HCI_EV_CMD_STATUS, when the
6285 	 * reason is anything but HCI_ERROR_REMOTE_POWER_OFF. This reason is
6286 	 * used when suspending or powering off, where we don't want to wait
6287 	 * for the peer's response.
6288 	 */
6289 	if (reason != HCI_ERROR_REMOTE_POWER_OFF)
6290 		return __hci_cmd_sync_status_sk(hdev, HCI_OP_DISCONNECT,
6291 						sizeof(cp), &cp,
6292 						HCI_EV_DISCONN_COMPLETE,
6293 						HCI_CMD_TIMEOUT, NULL);
6294 
6295 	return __hci_cmd_sync_status(hdev, HCI_OP_DISCONNECT, sizeof(cp), &cp,
6296 				     HCI_CMD_TIMEOUT);
6297 }
6298 
6299 static int hci_le_connect_cancel_sync(struct hci_dev *hdev,
6300 				      struct hci_conn *conn, u8 reason)
6301 {
6302 	/* Return reason if scanning since the connection shall probably be
6303 	 * cleanup directly.
6304 	 */
6305 	if (test_bit(HCI_CONN_SCANNING, conn->flags))
6306 		return reason;
6307 
6308 	if (conn->role == HCI_ROLE_SLAVE ||
6309 	    test_and_set_bit(HCI_CONN_CANCEL, conn->flags))
6310 		return 0;
6311 
6312 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CREATE_CONN_CANCEL,
6313 				     0, NULL, HCI_CMD_TIMEOUT);
6314 }
6315 
6316 static int hci_connect_cancel_sync(struct hci_dev *hdev, struct hci_conn *conn,
6317 				   u8 reason)
6318 {
6319 	if (conn->type == LE_LINK)
6320 		return hci_le_connect_cancel_sync(hdev, conn, reason);
6321 
6322 	if (conn->type == CIS_LINK) {
6323 		/* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
6324 		 * page 1857:
6325 		 *
6326 		 * If this command is issued for a CIS on the Central and the
6327 		 * CIS is successfully terminated before being established,
6328 		 * then an HCI_LE_CIS_Established event shall also be sent for
6329 		 * this CIS with the Status Operation Cancelled by Host (0x44).
6330 		 */
6331 		if (test_bit(HCI_CONN_CREATE_CIS, conn->flags))
6332 			return hci_disconnect_sync(hdev, conn, reason);
6333 
6334 		/* CIS with no Create CIS sent have nothing to cancel */
6335 		return HCI_ERROR_LOCAL_HOST_TERM;
6336 	}
6337 
6338 	if (conn->type == BIS_LINK || conn->type == PA_LINK) {
6339 		/* There is no way to cancel a BIS without terminating the BIG
6340 		 * which is done later on connection cleanup.
6341 		 */
6342 		return 0;
6343 	}
6344 
6345 	if (hdev->hci_ver < BLUETOOTH_VER_1_2)
6346 		return 0;
6347 
6348 	/* Wait for HCI_EV_CONN_COMPLETE, not HCI_EV_CMD_STATUS, when the
6349 	 * reason is anything but HCI_ERROR_REMOTE_POWER_OFF. This reason is
6350 	 * used when suspending or powering off, where we don't want to wait
6351 	 * for the peer's response.
6352 	 */
6353 	if (reason != HCI_ERROR_REMOTE_POWER_OFF)
6354 		return __hci_cmd_sync_status_sk(hdev, HCI_OP_CREATE_CONN_CANCEL,
6355 						6, &conn->dst,
6356 						HCI_EV_CONN_COMPLETE,
6357 						HCI_CMD_TIMEOUT, NULL);
6358 
6359 	return __hci_cmd_sync_status(hdev, HCI_OP_CREATE_CONN_CANCEL,
6360 				     6, &conn->dst, HCI_CMD_TIMEOUT);
6361 }
6362 
6363 static int hci_reject_sco_sync(struct hci_dev *hdev, struct hci_conn *conn,
6364 			       u8 reason)
6365 {
6366 	struct hci_cp_reject_sync_conn_req cp;
6367 
6368 	memset(&cp, 0, sizeof(cp));
6369 	bacpy(&cp.bdaddr, &conn->dst);
6370 	cp.reason = reason;
6371 
6372 	/* SCO rejection has its own limited set of
6373 	 * allowed error values (0x0D-0x0F).
6374 	 */
6375 	if (reason < 0x0d || reason > 0x0f)
6376 		cp.reason = HCI_ERROR_REJ_LIMITED_RESOURCES;
6377 
6378 	return __hci_cmd_sync_status(hdev, HCI_OP_REJECT_SYNC_CONN_REQ,
6379 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6380 }
6381 
6382 static int hci_le_reject_cis_sync(struct hci_dev *hdev, struct hci_conn *conn,
6383 				  u8 reason)
6384 {
6385 	struct hci_cp_le_reject_cis cp;
6386 
6387 	memset(&cp, 0, sizeof(cp));
6388 	cp.handle = cpu_to_le16(conn->handle);
6389 	cp.reason = reason;
6390 
6391 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_REJECT_CIS,
6392 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6393 }
6394 
6395 static int hci_reject_conn_sync(struct hci_dev *hdev, struct hci_conn *conn,
6396 				u8 reason)
6397 {
6398 	struct hci_cp_reject_conn_req cp;
6399 
6400 	if (conn->type == CIS_LINK)
6401 		return hci_le_reject_cis_sync(hdev, conn, reason);
6402 
6403 	if (conn->type == BIS_LINK || conn->type == PA_LINK)
6404 		return -EINVAL;
6405 
6406 	if (conn->type == SCO_LINK || conn->type == ESCO_LINK)
6407 		return hci_reject_sco_sync(hdev, conn, reason);
6408 
6409 	memset(&cp, 0, sizeof(cp));
6410 	bacpy(&cp.bdaddr, &conn->dst);
6411 	cp.reason = reason;
6412 
6413 	return __hci_cmd_sync_status(hdev, HCI_OP_REJECT_CONN_REQ,
6414 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6415 }
6416 
6417 int hci_abort_conn_sync(struct hci_dev *hdev, struct hci_conn *conn, u8 reason)
6418 {
6419 	int err = 0;
6420 	u16 handle = conn->handle;
6421 	bool disconnect = false;
6422 	struct hci_conn *c;
6423 
6424 	switch (conn->state) {
6425 	case BT_CONNECTED:
6426 	case BT_CONFIG:
6427 		err = hci_disconnect_sync(hdev, conn, reason);
6428 		break;
6429 	case BT_CONNECT:
6430 		err = hci_connect_cancel_sync(hdev, conn, reason);
6431 		break;
6432 	case BT_CONNECT2:
6433 		err = hci_reject_conn_sync(hdev, conn, reason);
6434 		break;
6435 	case BT_OPEN:
6436 	case BT_BOUND:
6437 		break;
6438 	default:
6439 		disconnect = true;
6440 		break;
6441 	}
6442 
6443 	hci_dev_lock(hdev);
6444 
6445 	/* Check if the connection has been cleaned up concurrently */
6446 	c = hci_conn_hash_lookup_handle(hdev, handle);
6447 	if (!c || c != conn) {
6448 		err = 0;
6449 		goto unlock;
6450 	}
6451 
6452 	/* Cleanup hci_conn object if it cannot be cancelled as it
6453 	 * likely means the controller and host stack are out of sync
6454 	 * or in case of LE it was still scanning so it can be cleanup
6455 	 * safely.
6456 	 */
6457 	if (disconnect) {
6458 		conn->state = BT_CLOSED;
6459 		hci_disconn_cfm(conn, reason);
6460 		hci_conn_del(conn);
6461 	} else {
6462 		hci_conn_failed(conn, reason);
6463 	}
6464 
6465 unlock:
6466 	hci_dev_unlock(hdev);
6467 	return err;
6468 }
6469 
6470 static int hci_disconnect_all_sync(struct hci_dev *hdev, u8 reason)
6471 {
6472 	struct list_head *head = &hdev->conn_hash.list;
6473 	struct hci_conn *conn;
6474 
6475 	rcu_read_lock();
6476 	while ((conn = list_first_or_null_rcu(head, struct hci_conn, list))) {
6477 		/* Make sure the connection is not freed while unlocking */
6478 		conn = hci_conn_get(conn);
6479 		rcu_read_unlock();
6480 		/* Disregard possible errors since hci_conn_del shall have been
6481 		 * called even in case of errors had occurred since it would
6482 		 * then cause hci_conn_failed to be called which calls
6483 		 * hci_conn_del internally.
6484 		 */
6485 		hci_abort_conn_sync(hdev, conn, reason);
6486 		hci_conn_put(conn);
6487 		rcu_read_lock();
6488 	}
6489 	rcu_read_unlock();
6490 
6491 	return 0;
6492 }
6493 
6494 /* This function perform power off HCI command sequence as follows:
6495  *
6496  * Clear Advertising
6497  * Stop Discovery
6498  * Disconnect all connections
6499  * hci_dev_close_sync
6500  */
6501 static int hci_power_off_sync(struct hci_dev *hdev)
6502 {
6503 	int err;
6504 
6505 	/* If controller is already down there is nothing to do */
6506 	if (!test_bit(HCI_UP, &hdev->flags))
6507 		return 0;
6508 
6509 	hci_dev_set_flag(hdev, HCI_POWERING_DOWN);
6510 
6511 	if (test_bit(HCI_ISCAN, &hdev->flags) ||
6512 	    test_bit(HCI_PSCAN, &hdev->flags)) {
6513 		err = hci_write_scan_enable_sync(hdev, 0x00);
6514 		if (err)
6515 			goto out;
6516 	}
6517 
6518 	err = hci_clear_adv_sync(hdev, NULL, false);
6519 	if (err)
6520 		goto out;
6521 
6522 	err = hci_stop_discovery_sync(hdev);
6523 	if (err)
6524 		goto out;
6525 
6526 	/* Terminated due to Power Off */
6527 	err = hci_disconnect_all_sync(hdev, HCI_ERROR_REMOTE_POWER_OFF);
6528 	if (err)
6529 		goto out;
6530 
6531 	err = hci_dev_close_sync(hdev);
6532 
6533 out:
6534 	hci_dev_clear_flag(hdev, HCI_POWERING_DOWN);
6535 	return err;
6536 }
6537 
6538 int hci_set_powered_sync(struct hci_dev *hdev, u8 val)
6539 {
6540 	if (val)
6541 		return hci_power_on_sync(hdev);
6542 
6543 	return hci_power_off_sync(hdev);
6544 }
6545 
6546 static int hci_write_iac_sync(struct hci_dev *hdev)
6547 {
6548 	struct hci_cp_write_current_iac_lap cp;
6549 
6550 	if (!hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
6551 		return 0;
6552 
6553 	memset(&cp, 0, sizeof(cp));
6554 
6555 	if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE)) {
6556 		/* Limited discoverable mode */
6557 		cp.num_iac = min_t(u8, hdev->num_iac, 2);
6558 		cp.iac_lap[0] = 0x00;	/* LIAC */
6559 		cp.iac_lap[1] = 0x8b;
6560 		cp.iac_lap[2] = 0x9e;
6561 		cp.iac_lap[3] = 0x33;	/* GIAC */
6562 		cp.iac_lap[4] = 0x8b;
6563 		cp.iac_lap[5] = 0x9e;
6564 	} else {
6565 		/* General discoverable mode */
6566 		cp.num_iac = 1;
6567 		cp.iac_lap[0] = 0x33;	/* GIAC */
6568 		cp.iac_lap[1] = 0x8b;
6569 		cp.iac_lap[2] = 0x9e;
6570 	}
6571 
6572 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_CURRENT_IAC_LAP,
6573 				     (cp.num_iac * 3) + 1, &cp,
6574 				     HCI_CMD_TIMEOUT);
6575 }
6576 
6577 int hci_update_discoverable_sync(struct hci_dev *hdev)
6578 {
6579 	int err = 0;
6580 
6581 	if (hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
6582 		err = hci_write_iac_sync(hdev);
6583 		if (err)
6584 			return err;
6585 
6586 		err = hci_update_scan_sync(hdev);
6587 		if (err)
6588 			return err;
6589 
6590 		err = hci_update_class_sync(hdev);
6591 		if (err)
6592 			return err;
6593 	}
6594 
6595 	/* Advertising instances don't use the global discoverable setting, so
6596 	 * only update AD if advertising was enabled using Set Advertising.
6597 	 */
6598 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING)) {
6599 		err = hci_update_adv_data_sync(hdev, 0x00);
6600 		if (err)
6601 			return err;
6602 
6603 		/* Discoverable mode affects the local advertising
6604 		 * address in limited privacy mode.
6605 		 */
6606 		if (hci_dev_test_flag(hdev, HCI_LIMITED_PRIVACY)) {
6607 			if (ext_adv_capable(hdev))
6608 				err = hci_start_ext_adv_sync(hdev, 0x00);
6609 			else
6610 				err = hci_enable_advertising_sync(hdev);
6611 		}
6612 	}
6613 
6614 	return err;
6615 }
6616 
6617 static int update_discoverable_sync(struct hci_dev *hdev, void *data)
6618 {
6619 	return hci_update_discoverable_sync(hdev);
6620 }
6621 
6622 int hci_update_discoverable(struct hci_dev *hdev)
6623 {
6624 	/* Only queue if it would have any effect */
6625 	if (hdev_is_powered(hdev) &&
6626 	    hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
6627 	    hci_dev_test_flag(hdev, HCI_DISCOVERABLE) &&
6628 	    hci_dev_test_flag(hdev, HCI_LIMITED_PRIVACY))
6629 		return hci_cmd_sync_queue(hdev, update_discoverable_sync, NULL,
6630 					  NULL);
6631 
6632 	return 0;
6633 }
6634 
6635 int hci_update_connectable_sync(struct hci_dev *hdev)
6636 {
6637 	int err;
6638 
6639 	err = hci_update_scan_sync(hdev);
6640 	if (err)
6641 		return err;
6642 
6643 	/* If BR/EDR is not enabled and we disable advertising as a
6644 	 * by-product of disabling connectable, we need to update the
6645 	 * advertising flags.
6646 	 */
6647 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
6648 		err = hci_update_adv_data_sync(hdev, hdev->cur_adv_instance);
6649 
6650 	/* Update the advertising parameters if necessary */
6651 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING) ||
6652 	    !list_empty(&hdev->adv_instances)) {
6653 		if (ext_adv_capable(hdev))
6654 			err = hci_start_ext_adv_sync(hdev,
6655 						     hdev->cur_adv_instance);
6656 		else
6657 			err = hci_enable_advertising_sync(hdev);
6658 
6659 		if (err)
6660 			return err;
6661 	}
6662 
6663 	return hci_update_passive_scan_sync(hdev);
6664 }
6665 
6666 int hci_inquiry_sync(struct hci_dev *hdev, u8 length, u8 num_rsp)
6667 {
6668 	const u8 giac[3] = { 0x33, 0x8b, 0x9e };
6669 	const u8 liac[3] = { 0x00, 0x8b, 0x9e };
6670 	struct hci_cp_inquiry cp;
6671 
6672 	bt_dev_dbg(hdev, "");
6673 
6674 	if (test_bit(HCI_INQUIRY, &hdev->flags))
6675 		return 0;
6676 
6677 	hci_dev_lock(hdev);
6678 	hci_inquiry_cache_flush(hdev);
6679 	hci_dev_unlock(hdev);
6680 
6681 	memset(&cp, 0, sizeof(cp));
6682 
6683 	if (hdev->discovery.limited)
6684 		memcpy(&cp.lap, liac, sizeof(cp.lap));
6685 	else
6686 		memcpy(&cp.lap, giac, sizeof(cp.lap));
6687 
6688 	cp.length = length;
6689 	cp.num_rsp = num_rsp;
6690 
6691 	return __hci_cmd_sync_status(hdev, HCI_OP_INQUIRY,
6692 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6693 }
6694 
6695 static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)
6696 {
6697 	u8 own_addr_type;
6698 	/* Accept list is not used for discovery */
6699 	u8 filter_policy = 0x00;
6700 	/* Default is to enable duplicates filter */
6701 	u8 filter_dup = LE_SCAN_FILTER_DUP_ENABLE;
6702 	bool paused;
6703 	int err;
6704 
6705 	bt_dev_dbg(hdev, "");
6706 
6707 	/* If controller is scanning, it means the passive scanning is
6708 	 * running. Thus, we should temporarily stop it in order to set the
6709 	 * discovery scanning parameters.
6710 	 */
6711 	err = hci_scan_disable_sync(hdev);
6712 	if (err) {
6713 		bt_dev_err(hdev, "Unable to disable scanning: %d", err);
6714 		return err;
6715 	}
6716 
6717 	cancel_interleave_scan(hdev);
6718 
6719 	/* Pause address resolution for active scan and stop advertising if
6720 	 * privacy is enabled.
6721 	 */
6722 	err = hci_pause_addr_resolution(hdev);
6723 	if (err)
6724 		goto failed;
6725 
6726 	/* LE Set Random Address is disallowed while advertising is enabled. */
6727 	paused = !hdev->advertising_paused;
6728 	err = hci_pause_advertising_sync(hdev);
6729 	if (err)
6730 		goto failed;
6731 
6732 	/* All active scans will be done with either a resolvable private
6733 	 * address (when privacy feature has been enabled) or non-resolvable
6734 	 * private address.
6735 	 */
6736 	err = hci_update_random_address_sync(hdev, true, scan_use_rpa(hdev),
6737 					     &own_addr_type);
6738 	if (err < 0)
6739 		own_addr_type = ADDR_LE_DEV_PUBLIC;
6740 
6741 	if (paused)
6742 		hci_resume_advertising_sync(hdev);
6743 
6744 	if (hci_is_adv_monitoring(hdev) ||
6745 	    (hci_test_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER) &&
6746 	    hdev->discovery.result_filtering)) {
6747 		/* Duplicate filter should be disabled when some advertisement
6748 		 * monitor is activated, otherwise AdvMon can only receive one
6749 		 * advertisement for one peer(*) during active scanning, and
6750 		 * might report loss to these peers.
6751 		 *
6752 		 * If controller does strict duplicate filtering and the
6753 		 * discovery requires result filtering disables controller based
6754 		 * filtering since that can cause reports that would match the
6755 		 * host filter to not be reported.
6756 		 */
6757 		filter_dup = LE_SCAN_FILTER_DUP_DISABLE;
6758 	}
6759 
6760 	err = hci_start_scan_sync(hdev, LE_SCAN_ACTIVE, interval,
6761 				  hdev->le_scan_window_discovery,
6762 				  own_addr_type, filter_policy, filter_dup);
6763 	if (!err)
6764 		return err;
6765 
6766 failed:
6767 	/* No-op when advertising was not paused. */
6768 	hci_resume_advertising_sync(hdev);
6769 
6770 	/* Resume passive scanning */
6771 	hci_update_passive_scan_sync(hdev);
6772 	return err;
6773 }
6774 
6775 static int hci_start_interleaved_discovery_sync(struct hci_dev *hdev)
6776 {
6777 	int err;
6778 
6779 	bt_dev_dbg(hdev, "");
6780 
6781 	err = hci_active_scan_sync(hdev, hdev->le_scan_int_discovery * 2);
6782 	if (err)
6783 		return err;
6784 
6785 	return hci_inquiry_sync(hdev, DISCOV_BREDR_INQUIRY_LEN, 0);
6786 }
6787 
6788 int hci_start_discovery_sync(struct hci_dev *hdev)
6789 {
6790 	unsigned long timeout;
6791 	int err;
6792 
6793 	bt_dev_dbg(hdev, "type %u", hdev->discovery.type);
6794 
6795 	switch (hdev->discovery.type) {
6796 	case DISCOV_TYPE_BREDR:
6797 		return hci_inquiry_sync(hdev, DISCOV_BREDR_INQUIRY_LEN, 0);
6798 	case DISCOV_TYPE_INTERLEAVED:
6799 		/* When running simultaneous discovery, the LE scanning time
6800 		 * should occupy the whole discovery time sine BR/EDR inquiry
6801 		 * and LE scanning are scheduled by the controller.
6802 		 *
6803 		 * For interleaving discovery in comparison, BR/EDR inquiry
6804 		 * and LE scanning are done sequentially with separate
6805 		 * timeouts.
6806 		 */
6807 		if (hci_test_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY)) {
6808 			timeout = msecs_to_jiffies(DISCOV_LE_TIMEOUT);
6809 			/* During simultaneous discovery, we double LE scan
6810 			 * interval. We must leave some time for the controller
6811 			 * to do BR/EDR inquiry.
6812 			 */
6813 			err = hci_start_interleaved_discovery_sync(hdev);
6814 			break;
6815 		}
6816 
6817 		timeout = msecs_to_jiffies(hdev->discov_interleaved_timeout);
6818 		err = hci_active_scan_sync(hdev, hdev->le_scan_int_discovery);
6819 		break;
6820 	case DISCOV_TYPE_LE:
6821 		timeout = msecs_to_jiffies(DISCOV_LE_TIMEOUT);
6822 		err = hci_active_scan_sync(hdev, hdev->le_scan_int_discovery);
6823 		break;
6824 	default:
6825 		return -EINVAL;
6826 	}
6827 
6828 	if (err)
6829 		return err;
6830 
6831 	bt_dev_dbg(hdev, "timeout %u ms", jiffies_to_msecs(timeout));
6832 
6833 	queue_delayed_work(hdev->req_workqueue, &hdev->le_scan_disable,
6834 			   timeout);
6835 	return 0;
6836 }
6837 
6838 static void hci_suspend_monitor_sync(struct hci_dev *hdev)
6839 {
6840 	switch (hci_get_adv_monitor_offload_ext(hdev)) {
6841 	case HCI_ADV_MONITOR_EXT_MSFT:
6842 		msft_suspend_sync(hdev);
6843 		break;
6844 	default:
6845 		return;
6846 	}
6847 }
6848 
6849 /* This function disables discovery and mark it as paused */
6850 static int hci_pause_discovery_sync(struct hci_dev *hdev)
6851 {
6852 	int old_state = hdev->discovery.state;
6853 	int err;
6854 
6855 	/* If discovery already stopped/stopping/paused there nothing to do */
6856 	if (old_state == DISCOVERY_STOPPED || old_state == DISCOVERY_STOPPING ||
6857 	    hdev->discovery_paused)
6858 		return 0;
6859 
6860 	hci_discovery_set_state(hdev, DISCOVERY_STOPPING);
6861 
6862 	/* Cancel the LE scan timeout first, so that it does not run while
6863 	 * suspended if the scan cannot be disabled.
6864 	 */
6865 	cancel_delayed_work(&hdev->le_scan_disable);
6866 
6867 	err = hci_stop_discovery_sync(hdev);
6868 	if (err)
6869 		return err;
6870 
6871 	hdev->discovery_paused = true;
6872 	hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
6873 
6874 	return 0;
6875 }
6876 
6877 static int hci_update_event_filter_sync(struct hci_dev *hdev)
6878 {
6879 	struct bdaddr_list_with_flags *b;
6880 	bdaddr_t *accept_list;
6881 	size_t i, num_entries = 0;
6882 	u8 scan = SCAN_DISABLED;
6883 	bool scanning = test_bit(HCI_PSCAN, &hdev->flags);
6884 	int err;
6885 
6886 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
6887 		return 0;
6888 
6889 	/* Some fake CSR controllers lock up after setting this type of
6890 	 * filter, so avoid sending the request altogether.
6891 	 */
6892 	if (hci_test_quirk(hdev, HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL))
6893 		return 0;
6894 
6895 	/* Always clear event filter when starting */
6896 	hci_clear_event_filter_sync(hdev);
6897 
6898 	hci_dev_lock(hdev);
6899 
6900 	list_for_each_entry(b, &hdev->accept_list, list)
6901 		if (b->flags & HCI_CONN_FLAG_REMOTE_WAKEUP)
6902 			num_entries++;
6903 
6904 	if (!num_entries) {
6905 		hci_dev_unlock(hdev);
6906 		goto update_scan;
6907 	}
6908 
6909 	accept_list = kmalloc_objs(*accept_list, num_entries);
6910 	if (!accept_list) {
6911 		hci_dev_unlock(hdev);
6912 		return -ENOMEM;
6913 	}
6914 
6915 	i = 0;
6916 	list_for_each_entry(b, &hdev->accept_list, list)
6917 		if (b->flags & HCI_CONN_FLAG_REMOTE_WAKEUP)
6918 			bacpy(&accept_list[i++], &b->bdaddr);
6919 
6920 	hci_dev_unlock(hdev);
6921 
6922 	for (i = 0; i < num_entries; i++) {
6923 		bt_dev_dbg(hdev, "Adding event filters for %pMR",
6924 			   &accept_list[i]);
6925 
6926 		err = hci_set_event_filter_sync(hdev, HCI_FLT_CONN_SETUP,
6927 						HCI_CONN_SETUP_ALLOW_BDADDR,
6928 					 &accept_list[i],
6929 					 HCI_CONN_SETUP_AUTO_ON);
6930 		if (err)
6931 			bt_dev_err(hdev, "Failed to set event filter for %pMR",
6932 				   &accept_list[i]);
6933 		else
6934 			scan = SCAN_PAGE;
6935 	}
6936 
6937 	kfree(accept_list);
6938 
6939 update_scan:
6940 	if (scan && !scanning)
6941 		hci_write_scan_enable_sync(hdev, scan);
6942 	else if (!scan && scanning)
6943 		hci_write_scan_enable_sync(hdev, scan);
6944 
6945 	return 0;
6946 }
6947 
6948 /* This function disables scan (BR and LE) and mark it as paused */
6949 static int hci_pause_scan_sync(struct hci_dev *hdev)
6950 {
6951 	if (hdev->scanning_paused)
6952 		return 0;
6953 
6954 	/* Disable page scan if enabled */
6955 	if (test_bit(HCI_PSCAN, &hdev->flags))
6956 		hci_write_scan_enable_sync(hdev, SCAN_DISABLED);
6957 
6958 	hci_scan_disable_sync(hdev);
6959 
6960 	hdev->scanning_paused = true;
6961 
6962 	return 0;
6963 }
6964 
6965 /* This function performs the HCI suspend procedures in the follow order:
6966  *
6967  * Pause discovery (active scanning/inquiry)
6968  * Pause Directed Advertising/Advertising
6969  * Pause Scanning (passive scanning in case discovery was not active)
6970  * Disconnect all connections
6971  * Set suspend_status to BT_SUSPEND_DISCONNECT if hdev cannot wakeup
6972  * otherwise:
6973  * Update event mask (only set events that are allowed to wake up the host)
6974  * Update event filter (with devices marked with HCI_CONN_FLAG_REMOTE_WAKEUP)
6975  * Update passive scanning (lower duty cycle)
6976  * Set suspend_status to BT_SUSPEND_CONFIGURE_WAKE
6977  */
6978 int hci_suspend_sync(struct hci_dev *hdev)
6979 {
6980 	int err;
6981 
6982 	/* If marked as suspended there nothing to do */
6983 	if (hdev->suspended)
6984 		return 0;
6985 
6986 	/* Mark device as suspended */
6987 	hdev->suspended = true;
6988 
6989 	/* Pause discovery if not already stopped */
6990 	hci_pause_discovery_sync(hdev);
6991 
6992 	/* Pause other advertisements */
6993 	hci_pause_advertising_sync(hdev);
6994 
6995 	/* Suspend monitor filters */
6996 	hci_suspend_monitor_sync(hdev);
6997 
6998 	/* Prevent disconnects from causing scanning to be re-enabled */
6999 	hci_pause_scan_sync(hdev);
7000 
7001 	if (hci_conn_count(hdev)) {
7002 		/* Soft disconnect everything (power off) */
7003 		err = hci_disconnect_all_sync(hdev, HCI_ERROR_REMOTE_POWER_OFF);
7004 		if (err) {
7005 			/* Set state to BT_RUNNING so resume doesn't notify */
7006 			hdev->suspend_state = BT_RUNNING;
7007 			hci_resume_sync(hdev);
7008 			return err;
7009 		}
7010 
7011 		/* Update event mask so only the allowed event can wakeup the
7012 		 * host.
7013 		 */
7014 		hci_set_event_mask_sync(hdev);
7015 	}
7016 
7017 	/* Only configure accept list if disconnect succeeded and wake
7018 	 * isn't being prevented.
7019 	 */
7020 	if (!hdev->wakeup || !hdev->wakeup(hdev)) {
7021 		hdev->suspend_state = BT_SUSPEND_DISCONNECT;
7022 		return 0;
7023 	}
7024 
7025 	/* Unpause to take care of updating scanning params */
7026 	hdev->scanning_paused = false;
7027 
7028 	/* Enable event filter for paired devices */
7029 	hci_update_event_filter_sync(hdev);
7030 
7031 	/* Update LE passive scan if enabled */
7032 	hci_update_passive_scan_sync(hdev);
7033 
7034 	/* Pause scan changes again. */
7035 	hdev->scanning_paused = true;
7036 
7037 	hdev->suspend_state = BT_SUSPEND_CONFIGURE_WAKE;
7038 
7039 	return 0;
7040 }
7041 
7042 /* This function resumes discovery */
7043 static int hci_resume_discovery_sync(struct hci_dev *hdev)
7044 {
7045 	int err;
7046 
7047 	/* If discovery not paused there nothing to do */
7048 	if (!hdev->discovery_paused)
7049 		return 0;
7050 
7051 	hdev->discovery_paused = false;
7052 
7053 	hci_discovery_set_state(hdev, DISCOVERY_STARTING);
7054 
7055 	err = hci_start_discovery_sync(hdev);
7056 
7057 	hci_discovery_set_state(hdev, err ? DISCOVERY_STOPPED :
7058 				DISCOVERY_FINDING);
7059 
7060 	return err;
7061 }
7062 
7063 static void hci_resume_monitor_sync(struct hci_dev *hdev)
7064 {
7065 	switch (hci_get_adv_monitor_offload_ext(hdev)) {
7066 	case HCI_ADV_MONITOR_EXT_MSFT:
7067 		msft_resume_sync(hdev);
7068 		break;
7069 	default:
7070 		return;
7071 	}
7072 }
7073 
7074 /* This function resume scan and reset paused flag */
7075 static int hci_resume_scan_sync(struct hci_dev *hdev)
7076 {
7077 	if (!hdev->scanning_paused)
7078 		return 0;
7079 
7080 	hdev->scanning_paused = false;
7081 
7082 	hci_update_scan_sync(hdev);
7083 
7084 	/* Reset passive scanning to normal */
7085 	hci_update_passive_scan_sync(hdev);
7086 
7087 	return 0;
7088 }
7089 
7090 /* This function performs the HCI suspend procedures in the follow order:
7091  *
7092  * Restore event mask
7093  * Clear event filter
7094  * Update passive scanning (normal duty cycle)
7095  * Resume Directed Advertising/Advertising
7096  * Resume discovery (active scanning/inquiry)
7097  */
7098 int hci_resume_sync(struct hci_dev *hdev)
7099 {
7100 	/* If not marked as suspended there nothing to do */
7101 	if (!hdev->suspended)
7102 		return 0;
7103 
7104 	hdev->suspended = false;
7105 
7106 	/* Restore event mask */
7107 	hci_set_event_mask_sync(hdev);
7108 
7109 	/* Clear any event filters and restore scan state */
7110 	hci_clear_event_filter_sync(hdev);
7111 
7112 	/* Resume scanning */
7113 	hci_resume_scan_sync(hdev);
7114 
7115 	/* Resume monitor filters */
7116 	hci_resume_monitor_sync(hdev);
7117 
7118 	/* Resume other advertisements */
7119 	hci_resume_advertising_sync(hdev);
7120 
7121 	/* Resume discovery */
7122 	hci_resume_discovery_sync(hdev);
7123 
7124 	return 0;
7125 }
7126 
7127 static bool conn_use_rpa(struct hci_conn *conn)
7128 {
7129 	struct hci_dev *hdev = conn->hdev;
7130 
7131 	return hci_dev_test_flag(hdev, HCI_PRIVACY);
7132 }
7133 
7134 static int hci_le_ext_directed_advertising_sync(struct hci_dev *hdev,
7135 						struct hci_conn *conn)
7136 {
7137 	struct hci_cp_le_set_ext_adv_params cp;
7138 	struct hci_rp_le_set_ext_adv_params rp;
7139 	int err;
7140 	bdaddr_t random_addr;
7141 	u8 own_addr_type;
7142 
7143 	err = hci_update_random_address_sync(hdev, false, conn_use_rpa(conn),
7144 					     &own_addr_type);
7145 	if (err)
7146 		return err;
7147 
7148 	/* Set require_privacy to false so that the remote device has a
7149 	 * chance of identifying us.
7150 	 */
7151 	err = hci_get_random_address(hdev, false, conn_use_rpa(conn), NULL,
7152 				     &own_addr_type, &random_addr);
7153 	if (err)
7154 		return err;
7155 
7156 	memset(&cp, 0, sizeof(cp));
7157 
7158 	cp.evt_properties = cpu_to_le16(LE_LEGACY_ADV_DIRECT_IND);
7159 	cp.channel_map = hdev->le_adv_channel_map;
7160 	cp.tx_power = HCI_TX_POWER_INVALID;
7161 	cp.primary_phy = HCI_ADV_PHY_1M;
7162 	cp.secondary_phy = HCI_ADV_PHY_1M;
7163 	cp.handle = 0x00; /* Use instance 0 for directed adv */
7164 	cp.own_addr_type = own_addr_type;
7165 	cp.peer_addr_type = conn->dst_type;
7166 	bacpy(&cp.peer_addr, &conn->dst);
7167 
7168 	/* As per Core Spec 5.2 Vol 2, PART E, Sec 7.8.53, for
7169 	 * advertising_event_property LE_LEGACY_ADV_DIRECT_IND
7170 	 * does not supports advertising data when the advertising set already
7171 	 * contains some, the controller shall return erroc code 'Invalid
7172 	 * HCI Command Parameters(0x12).
7173 	 * So it is required to remove adv set for handle 0x00. since we use
7174 	 * instance 0 for directed adv.
7175 	 */
7176 	err = hci_remove_ext_adv_instance_sync(hdev, cp.handle, NULL);
7177 	if (err)
7178 		return err;
7179 
7180 	err = hci_set_ext_adv_params_sync(hdev, 0, &cp, &rp);
7181 	if (err)
7182 		return err;
7183 
7184 	/* Update adv data as tx power is known now */
7185 	err = hci_set_ext_adv_data_sync(hdev, cp.handle);
7186 	if (err)
7187 		return err;
7188 
7189 	/* Check if random address need to be updated */
7190 	if (own_addr_type == ADDR_LE_DEV_RANDOM &&
7191 	    bacmp(&random_addr, BDADDR_ANY) &&
7192 	    bacmp(&random_addr, &hdev->random_addr)) {
7193 		err = hci_set_adv_set_random_addr_sync(hdev, 0x00,
7194 						       &random_addr);
7195 		if (err)
7196 			return err;
7197 	}
7198 
7199 	return hci_enable_ext_advertising_sync(hdev, 0x00);
7200 }
7201 
7202 static int hci_le_directed_advertising_sync(struct hci_dev *hdev,
7203 					    struct hci_conn *conn)
7204 {
7205 	struct hci_cp_le_set_adv_param cp;
7206 	u8 status;
7207 	u8 own_addr_type;
7208 	u8 enable;
7209 
7210 	if (ext_adv_capable(hdev))
7211 		return hci_le_ext_directed_advertising_sync(hdev, conn);
7212 
7213 	/* Clear the HCI_LE_ADV bit temporarily so that the
7214 	 * hci_update_random_address knows that it's safe to go ahead
7215 	 * and write a new random address. The flag will be set back on
7216 	 * as soon as the SET_ADV_ENABLE HCI command completes.
7217 	 */
7218 	hci_dev_clear_flag(hdev, HCI_LE_ADV);
7219 
7220 	/* Set require_privacy to false so that the remote device has a
7221 	 * chance of identifying us.
7222 	 */
7223 	status = hci_update_random_address_sync(hdev, false, conn_use_rpa(conn),
7224 						&own_addr_type);
7225 	if (status)
7226 		return status;
7227 
7228 	memset(&cp, 0, sizeof(cp));
7229 
7230 	/* Some controllers might reject command if intervals are not
7231 	 * within range for undirected advertising.
7232 	 * BCM20702A0 is known to be affected by this.
7233 	 */
7234 	cp.min_interval = cpu_to_le16(0x0020);
7235 	cp.max_interval = cpu_to_le16(0x0020);
7236 
7237 	cp.type = LE_ADV_DIRECT_IND;
7238 	cp.own_address_type = own_addr_type;
7239 	cp.direct_addr_type = conn->dst_type;
7240 	bacpy(&cp.direct_addr, &conn->dst);
7241 	cp.channel_map = hdev->le_adv_channel_map;
7242 
7243 	status = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_PARAM,
7244 				       sizeof(cp), &cp, HCI_CMD_TIMEOUT);
7245 	if (status)
7246 		return status;
7247 
7248 	enable = 0x01;
7249 
7250 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_ENABLE,
7251 				     sizeof(enable), &enable, HCI_CMD_TIMEOUT);
7252 }
7253 
7254 static void set_ext_conn_params(struct hci_conn *conn,
7255 				struct hci_cp_le_ext_conn_param *p)
7256 {
7257 	struct hci_dev *hdev = conn->hdev;
7258 
7259 	memset(p, 0, sizeof(*p));
7260 
7261 	p->scan_interval = cpu_to_le16(hdev->le_scan_int_connect);
7262 	p->scan_window = cpu_to_le16(hdev->le_scan_window_connect);
7263 	p->conn_interval_min = cpu_to_le16(conn->le_conn_min_interval);
7264 	p->conn_interval_max = cpu_to_le16(conn->le_conn_max_interval);
7265 	p->conn_latency = cpu_to_le16(conn->le_conn_latency);
7266 	p->supervision_timeout = cpu_to_le16(conn->le_supv_timeout);
7267 	p->min_ce_len = cpu_to_le16(0x0000);
7268 	p->max_ce_len = cpu_to_le16(0x0000);
7269 }
7270 
7271 static int hci_le_ext_create_conn_sync(struct hci_dev *hdev,
7272 				       struct hci_conn *conn, u8 own_addr_type)
7273 {
7274 	struct hci_cp_le_ext_create_conn *cp;
7275 	struct hci_cp_le_ext_conn_param *p;
7276 	u8 data[sizeof(*cp) + sizeof(*p) * 3];
7277 	u32 plen;
7278 
7279 	cp = (void *)data;
7280 	p = (void *)cp->data;
7281 
7282 	memset(cp, 0, sizeof(*cp));
7283 
7284 	bacpy(&cp->peer_addr, &conn->dst);
7285 	cp->peer_addr_type = conn->dst_type;
7286 	cp->own_addr_type = own_addr_type;
7287 
7288 	plen = sizeof(*cp);
7289 
7290 	if (scan_1m(hdev) && (conn->le_adv_phy == HCI_ADV_PHY_1M ||
7291 			      conn->le_adv_sec_phy == HCI_ADV_PHY_1M)) {
7292 		cp->phys |= LE_SCAN_PHY_1M;
7293 		set_ext_conn_params(conn, p);
7294 
7295 		p++;
7296 		plen += sizeof(*p);
7297 	}
7298 
7299 	if (scan_2m(hdev) && (conn->le_adv_phy == HCI_ADV_PHY_2M ||
7300 			      conn->le_adv_sec_phy == HCI_ADV_PHY_2M)) {
7301 		cp->phys |= LE_SCAN_PHY_2M;
7302 		set_ext_conn_params(conn, p);
7303 
7304 		p++;
7305 		plen += sizeof(*p);
7306 	}
7307 
7308 	if (scan_coded(hdev) && (conn->le_adv_phy == HCI_ADV_PHY_CODED ||
7309 				 conn->le_adv_sec_phy == HCI_ADV_PHY_CODED)) {
7310 		cp->phys |= LE_SCAN_PHY_CODED;
7311 		set_ext_conn_params(conn, p);
7312 
7313 		plen += sizeof(*p);
7314 	}
7315 
7316 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_EXT_CREATE_CONN,
7317 					plen, data,
7318 					HCI_EV_LE_ENHANCED_CONN_COMPLETE,
7319 					conn->conn_timeout, NULL);
7320 }
7321 
7322 static int hci_le_create_conn_sync(struct hci_dev *hdev, void *data)
7323 {
7324 	struct hci_cp_le_create_conn cp;
7325 	struct hci_conn_params *params;
7326 	u8 own_addr_type;
7327 	int err;
7328 	struct hci_conn *conn = data;
7329 
7330 	if (!hci_conn_valid(hdev, conn))
7331 		return -ECANCELED;
7332 
7333 	bt_dev_dbg(hdev, "conn %p", conn);
7334 
7335 	clear_bit(HCI_CONN_SCANNING, conn->flags);
7336 	conn->state = BT_CONNECT;
7337 
7338 	/* If requested to connect as peripheral use directed advertising */
7339 	if (conn->role == HCI_ROLE_SLAVE) {
7340 		/* If we're active scanning and simultaneous roles is not
7341 		 * enabled simply reject the attempt.
7342 		 */
7343 		if (hci_dev_test_flag(hdev, HCI_LE_SCAN) &&
7344 		    hdev->le_scan_type == LE_SCAN_ACTIVE &&
7345 		    !hci_dev_test_flag(hdev, HCI_LE_SIMULTANEOUS_ROLES)) {
7346 			conn->state = BT_OPEN;
7347 			hci_abort_conn_sync(hdev, conn,
7348 					    HCI_ERROR_REJ_LIMITED_RESOURCES);
7349 			return -EBUSY;
7350 		}
7351 
7352 		/* Pause advertising while doing directed advertising. */
7353 		hci_pause_advertising_sync(hdev);
7354 
7355 		err = hci_le_directed_advertising_sync(hdev, conn);
7356 		goto done;
7357 	}
7358 
7359 	/* Disable advertising if simultaneous roles is not in use. */
7360 	if (!hci_dev_test_flag(hdev, HCI_LE_SIMULTANEOUS_ROLES))
7361 		hci_pause_advertising_sync(hdev);
7362 
7363 	hci_dev_lock(hdev);
7364 
7365 	params = hci_conn_params_lookup(hdev, &conn->dst, conn->dst_type);
7366 	if (params) {
7367 		conn->le_conn_min_interval = params->conn_min_interval;
7368 		conn->le_conn_max_interval = params->conn_max_interval;
7369 		conn->le_conn_latency = params->conn_latency;
7370 		conn->le_supv_timeout = params->supervision_timeout;
7371 	} else {
7372 		conn->le_conn_min_interval = hdev->le_conn_min_interval;
7373 		conn->le_conn_max_interval = hdev->le_conn_max_interval;
7374 		conn->le_conn_latency = hdev->le_conn_latency;
7375 		conn->le_supv_timeout = hdev->le_supv_timeout;
7376 	}
7377 
7378 	hci_dev_unlock(hdev);
7379 
7380 	/* If controller is scanning, we stop it since some controllers are
7381 	 * not able to scan and connect at the same time. Also set the
7382 	 * HCI_LE_SCAN_INTERRUPTED flag so that the command complete
7383 	 * handler for scan disabling knows to set the correct discovery
7384 	 * state.
7385 	 */
7386 	if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
7387 		hci_dev_set_flag(hdev, HCI_LE_SCAN_INTERRUPTED);
7388 		hci_scan_disable_sync(hdev);
7389 	}
7390 
7391 	/* Update random address, but set require_privacy to false so
7392 	 * that we never connect with an non-resolvable address.
7393 	 */
7394 	err = hci_update_random_address_sync(hdev, false, conn_use_rpa(conn),
7395 					     &own_addr_type);
7396 	if (err)
7397 		goto done;
7398 
7399 	/* Mark create connection in flight so hci_cancel_connect_sync() can
7400 	 * cancel it while blocking on the connection complete event.
7401 	 */
7402 	set_bit(HCI_CONN_CREATE, conn->flags);
7403 
7404 	/* Send command LE Extended Create Connection if supported */
7405 	if (use_ext_conn(hdev)) {
7406 		err = hci_le_ext_create_conn_sync(hdev, conn, own_addr_type);
7407 		goto done;
7408 	}
7409 
7410 	memset(&cp, 0, sizeof(cp));
7411 
7412 	cp.scan_interval = cpu_to_le16(hdev->le_scan_int_connect);
7413 	cp.scan_window = cpu_to_le16(hdev->le_scan_window_connect);
7414 
7415 	bacpy(&cp.peer_addr, &conn->dst);
7416 	cp.peer_addr_type = conn->dst_type;
7417 	cp.own_address_type = own_addr_type;
7418 	cp.conn_interval_min = cpu_to_le16(conn->le_conn_min_interval);
7419 	cp.conn_interval_max = cpu_to_le16(conn->le_conn_max_interval);
7420 	cp.conn_latency = cpu_to_le16(conn->le_conn_latency);
7421 	cp.supervision_timeout = cpu_to_le16(conn->le_supv_timeout);
7422 	cp.min_ce_len = cpu_to_le16(0x0000);
7423 	cp.max_ce_len = cpu_to_le16(0x0000);
7424 
7425 	/* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E page 2261:
7426 	 *
7427 	 * If this event is unmasked and the HCI_LE_Connection_Complete event
7428 	 * is unmasked, only the HCI_LE_Enhanced_Connection_Complete event is
7429 	 * sent when a new connection has been created.
7430 	 */
7431 	err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_CREATE_CONN,
7432 				       sizeof(cp), &cp,
7433 				       use_enhanced_conn_complete(hdev) ?
7434 				       HCI_EV_LE_ENHANCED_CONN_COMPLETE :
7435 				       HCI_EV_LE_CONN_COMPLETE,
7436 				       conn->conn_timeout, NULL);
7437 
7438 done:
7439 	clear_bit(HCI_CONN_CREATE, conn->flags);
7440 
7441 	if (err == -ETIMEDOUT)
7442 		hci_le_connect_cancel_sync(hdev, conn, 0x00);
7443 
7444 	/* Re-enable advertising after the connection attempt is finished. */
7445 	hci_resume_advertising_sync(hdev);
7446 	return err;
7447 }
7448 
7449 int hci_le_create_cis_sync(struct hci_dev *hdev)
7450 {
7451 	DEFINE_FLEX(struct hci_cp_le_create_cis, cmd, cis, num_cis, 0x1f);
7452 	size_t aux_num_cis = 0;
7453 	struct hci_conn *conn;
7454 	u16 timeout = 0;
7455 	u8 cig = BT_ISO_QOS_CIG_UNSET;
7456 
7457 	/* The spec allows only one pending LE Create CIS command at a time. If
7458 	 * the command is pending now, don't do anything. We check for pending
7459 	 * connections after each CIS Established event.
7460 	 *
7461 	 * BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
7462 	 * page 2566:
7463 	 *
7464 	 * If the Host issues this command before all the
7465 	 * HCI_LE_CIS_Established events from the previous use of the
7466 	 * command have been generated, the Controller shall return the
7467 	 * error code Command Disallowed (0x0C).
7468 	 *
7469 	 * BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
7470 	 * page 2567:
7471 	 *
7472 	 * When the Controller receives the HCI_LE_Create_CIS command, the
7473 	 * Controller sends the HCI_Command_Status event to the Host. An
7474 	 * HCI_LE_CIS_Established event will be generated for each CIS when it
7475 	 * is established or if it is disconnected or considered lost before
7476 	 * being established; until all the events are generated, the command
7477 	 * remains pending.
7478 	 */
7479 
7480 	hci_dev_lock(hdev);
7481 
7482 	rcu_read_lock();
7483 
7484 	/* Wait until previous Create CIS has completed */
7485 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
7486 		if (test_bit(HCI_CONN_CREATE_CIS, conn->flags))
7487 			goto done;
7488 	}
7489 
7490 	/* Find CIG with all CIS ready */
7491 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
7492 		struct hci_conn *link;
7493 
7494 		if (hci_conn_check_create_cis(conn))
7495 			continue;
7496 
7497 		cig = conn->iso_qos.ucast.cig;
7498 
7499 		list_for_each_entry_rcu(link, &hdev->conn_hash.list, list) {
7500 			if (hci_conn_check_create_cis(link) > 0 &&
7501 			    link->iso_qos.ucast.cig == cig &&
7502 			    link->state != BT_CONNECTED) {
7503 				cig = BT_ISO_QOS_CIG_UNSET;
7504 				break;
7505 			}
7506 		}
7507 
7508 		if (cig != BT_ISO_QOS_CIG_UNSET)
7509 			break;
7510 	}
7511 
7512 	if (cig == BT_ISO_QOS_CIG_UNSET)
7513 		goto done;
7514 
7515 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
7516 		struct hci_cis *cis = &cmd->cis[aux_num_cis];
7517 
7518 		if (hci_conn_check_create_cis(conn) ||
7519 		    conn->iso_qos.ucast.cig != cig)
7520 			continue;
7521 
7522 		set_bit(HCI_CONN_CREATE_CIS, conn->flags);
7523 		cis->acl_handle = cpu_to_le16(conn->parent->handle);
7524 		cis->cis_handle = cpu_to_le16(conn->handle);
7525 		timeout = conn->conn_timeout;
7526 		aux_num_cis++;
7527 
7528 		if (aux_num_cis >= cmd->num_cis)
7529 			break;
7530 	}
7531 	cmd->num_cis = aux_num_cis;
7532 
7533 done:
7534 	rcu_read_unlock();
7535 
7536 	hci_dev_unlock(hdev);
7537 
7538 	if (!aux_num_cis)
7539 		return 0;
7540 
7541 	/* Wait for HCI_LE_CIS_Established */
7542 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_CREATE_CIS,
7543 					struct_size(cmd, cis, cmd->num_cis),
7544 					cmd, HCI_EVT_LE_CIS_ESTABLISHED,
7545 					timeout, NULL);
7546 }
7547 
7548 int hci_le_remove_cig_sync(struct hci_dev *hdev, u8 handle)
7549 {
7550 	struct hci_cp_le_remove_cig cp;
7551 
7552 	memset(&cp, 0, sizeof(cp));
7553 	cp.cig_id = handle;
7554 
7555 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_REMOVE_CIG, sizeof(cp),
7556 				     &cp, HCI_CMD_TIMEOUT);
7557 }
7558 
7559 int hci_le_big_terminate_sync(struct hci_dev *hdev, u8 handle)
7560 {
7561 	struct hci_cp_le_big_term_sync cp;
7562 
7563 	memset(&cp, 0, sizeof(cp));
7564 	cp.handle = handle;
7565 
7566 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_BIG_TERM_SYNC,
7567 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
7568 }
7569 
7570 int hci_le_pa_terminate_sync(struct hci_dev *hdev, u16 handle)
7571 {
7572 	struct hci_cp_le_pa_term_sync cp;
7573 
7574 	memset(&cp, 0, sizeof(cp));
7575 	cp.handle = cpu_to_le16(handle);
7576 
7577 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_PA_TERM_SYNC,
7578 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
7579 }
7580 
7581 int hci_get_random_address(struct hci_dev *hdev, bool require_privacy,
7582 			   bool use_rpa, struct adv_info *adv_instance,
7583 			   u8 *own_addr_type, bdaddr_t *rand_addr)
7584 {
7585 	int err;
7586 
7587 	bacpy(rand_addr, BDADDR_ANY);
7588 
7589 	/* If privacy is enabled use a resolvable private address. If
7590 	 * current RPA has expired then generate a new one.
7591 	 */
7592 	if (use_rpa) {
7593 		/* If Controller supports LL Privacy use own address type is
7594 		 * 0x03
7595 		 */
7596 		if (ll_privacy_capable(hdev))
7597 			*own_addr_type = ADDR_LE_DEV_RANDOM_RESOLVED;
7598 		else
7599 			*own_addr_type = ADDR_LE_DEV_RANDOM;
7600 
7601 		if (adv_instance) {
7602 			if (adv_rpa_valid(adv_instance))
7603 				return 0;
7604 		} else {
7605 			if (rpa_valid(hdev))
7606 				return 0;
7607 		}
7608 
7609 		err = smp_generate_rpa(hdev, hdev->irk, &hdev->rpa);
7610 		if (err < 0) {
7611 			bt_dev_err(hdev, "failed to generate new RPA");
7612 			return err;
7613 		}
7614 
7615 		bacpy(rand_addr, &hdev->rpa);
7616 
7617 		return 0;
7618 	}
7619 
7620 	/* In case of required privacy without resolvable private address,
7621 	 * use an non-resolvable private address. This is useful for
7622 	 * non-connectable advertising.
7623 	 */
7624 	if (require_privacy) {
7625 		bdaddr_t nrpa;
7626 
7627 		while (true) {
7628 			/* The non-resolvable private address is generated
7629 			 * from random six bytes with the two most significant
7630 			 * bits cleared.
7631 			 */
7632 			get_random_bytes(&nrpa, 6);
7633 			nrpa.b[5] &= 0x3f;
7634 
7635 			/* The non-resolvable private address shall not be
7636 			 * equal to the public address.
7637 			 */
7638 			if (bacmp(&hdev->bdaddr, &nrpa))
7639 				break;
7640 		}
7641 
7642 		*own_addr_type = ADDR_LE_DEV_RANDOM;
7643 		bacpy(rand_addr, &nrpa);
7644 
7645 		return 0;
7646 	}
7647 
7648 	/* No privacy, use the current address */
7649 	hci_copy_identity_address(hdev, rand_addr, own_addr_type);
7650 
7651 	return 0;
7652 }
7653 
7654 static int _update_adv_data_sync(struct hci_dev *hdev, void *data)
7655 {
7656 	u8 instance = PTR_UINT(data);
7657 
7658 	return hci_update_adv_data_sync(hdev, instance);
7659 }
7660 
7661 int hci_update_adv_data(struct hci_dev *hdev, u8 instance)
7662 {
7663 	return hci_cmd_sync_queue(hdev, _update_adv_data_sync,
7664 				  UINT_PTR(instance), NULL);
7665 }
7666 
7667 static int hci_acl_create_conn_sync(struct hci_dev *hdev, void *data)
7668 {
7669 	struct hci_conn *conn = data;
7670 	struct inquiry_entry *ie;
7671 	struct hci_cp_create_conn cp;
7672 	int err;
7673 
7674 	if (!hci_conn_valid(hdev, conn))
7675 		return -ECANCELED;
7676 
7677 	/* Many controllers disallow HCI Create Connection while it is doing
7678 	 * HCI Inquiry. So we cancel the Inquiry first before issuing HCI Create
7679 	 * Connection. This may cause the MGMT discovering state to become false
7680 	 * without user space's request but it is okay since the MGMT Discovery
7681 	 * APIs do not promise that discovery should be done forever. Instead,
7682 	 * the user space monitors the status of MGMT discovering and it may
7683 	 * request for discovery again when this flag becomes false.
7684 	 */
7685 	if (test_bit(HCI_INQUIRY, &hdev->flags)) {
7686 		err = __hci_cmd_sync_status(hdev, HCI_OP_INQUIRY_CANCEL, 0,
7687 					    NULL, HCI_CMD_TIMEOUT);
7688 		if (err)
7689 			bt_dev_warn(hdev, "Failed to cancel inquiry %d", err);
7690 	}
7691 
7692 	conn->state = BT_CONNECT;
7693 	conn->out = true;
7694 	conn->role = HCI_ROLE_MASTER;
7695 
7696 	conn->attempt++;
7697 
7698 	memset(&cp, 0, sizeof(cp));
7699 	bacpy(&cp.bdaddr, &conn->dst);
7700 	cp.pscan_rep_mode = 0x02;
7701 
7702 	hci_dev_lock(hdev);
7703 	ie = hci_inquiry_cache_lookup(hdev, &conn->dst);
7704 	if (ie) {
7705 		if (inquiry_entry_age(ie) <= INQUIRY_ENTRY_AGE_MAX) {
7706 			cp.pscan_rep_mode = ie->data.pscan_rep_mode;
7707 			cp.pscan_mode     = ie->data.pscan_mode;
7708 			cp.clock_offset   = ie->data.clock_offset |
7709 					    cpu_to_le16(0x8000);
7710 		}
7711 
7712 		memcpy(conn->dev_class, ie->data.dev_class, 3);
7713 	}
7714 	hci_dev_unlock(hdev);
7715 
7716 	cp.pkt_type = cpu_to_le16(conn->pkt_type);
7717 	if (lmp_rswitch_capable(hdev) && !(hdev->link_mode & HCI_LM_MASTER))
7718 		cp.role_switch = 0x01;
7719 	else
7720 		cp.role_switch = 0x00;
7721 
7722 	/* Mark create connection in flight so hci_cancel_connect_sync() can
7723 	 * cancel it while blocking on the connection complete event.
7724 	 */
7725 	set_bit(HCI_CONN_CREATE, conn->flags);
7726 
7727 	err = __hci_cmd_sync_status_sk(hdev, HCI_OP_CREATE_CONN,
7728 				       sizeof(cp), &cp,
7729 				       HCI_EV_CONN_COMPLETE,
7730 				       conn->conn_timeout, NULL);
7731 
7732 	clear_bit(HCI_CONN_CREATE, conn->flags);
7733 
7734 	return err;
7735 }
7736 
7737 static void hci_acl_create_conn_sync_complete(struct hci_dev *hdev, void *data,
7738 					      int err)
7739 {
7740 	struct hci_conn *conn = data;
7741 
7742 	hci_conn_put(conn);
7743 }
7744 
7745 int hci_connect_acl_sync(struct hci_dev *hdev, struct hci_conn *conn)
7746 {
7747 	int err;
7748 
7749 	err = hci_cmd_sync_queue_once(hdev, hci_acl_create_conn_sync,
7750 				      hci_conn_get(conn),
7751 				      hci_acl_create_conn_sync_complete);
7752 	if (err)
7753 		hci_conn_put(conn);
7754 	return (err == -EEXIST) ? 0 : err;
7755 }
7756 
7757 static void create_le_conn_complete(struct hci_dev *hdev, void *data, int err)
7758 {
7759 	struct hci_conn *conn = data;
7760 
7761 	bt_dev_dbg(hdev, "err %d", err);
7762 
7763 	if (err == -ECANCELED)
7764 		goto done;
7765 
7766 	hci_dev_lock(hdev);
7767 
7768 	if (!hci_conn_valid(hdev, conn))
7769 		goto unlock;
7770 
7771 	if (!err) {
7772 		hci_connect_le_scan_cleanup(conn, 0x00);
7773 		goto unlock;
7774 	}
7775 
7776 	/* Check if this connection is still pending.
7777 	 *
7778 	 * hci_lookup_le_connect() returns only the first LE connection
7779 	 * in BT_CONNECT, which is not necessarily this one when two are
7780 	 * pending at once, so ask the connection itself.
7781 	 */
7782 	if (conn->state != BT_CONNECT)
7783 		goto unlock;
7784 
7785 	/* Flush to make sure we send create conn cancel command if needed */
7786 	flush_delayed_work(&conn->le_conn_timeout);
7787 	hci_conn_failed(conn, bt_status(err));
7788 
7789 unlock:
7790 	hci_dev_unlock(hdev);
7791 done:
7792 	hci_conn_put(conn);
7793 }
7794 
7795 int hci_connect_le_sync(struct hci_dev *hdev, struct hci_conn *conn)
7796 {
7797 	int err;
7798 
7799 	err = hci_cmd_sync_queue_once(hdev, hci_le_create_conn_sync,
7800 				      hci_conn_get(conn),
7801 				      create_le_conn_complete);
7802 	if (err)
7803 		hci_conn_put(conn);
7804 	return (err == -EEXIST) ? 0 : err;
7805 }
7806 
7807 static int hci_acl_cancel_create_conn_sync(struct hci_dev *hdev,
7808 					   struct hci_conn *conn)
7809 {
7810 	struct hci_cmd_sync_work_entry *entry;
7811 	int err = -EBUSY;
7812 
7813 	/* cmd_sync_work_lock makes the HCI_CONN_CREATE test and the cancel
7814 	 * atomic against the worker, which takes this lock to dequeue every
7815 	 * entry: while it is held no other command can become pending, so
7816 	 * hci_cmd_sync_cancel() cannot cancel an unrelated command.
7817 	 */
7818 	mutex_lock(&hdev->cmd_sync_work_lock);
7819 
7820 	/* In flight: this connection owns the pending request, cancel it. */
7821 	if (test_bit(HCI_CONN_CREATE, conn->flags)) {
7822 		hci_cmd_sync_cancel(hdev, ECANCELED);
7823 		goto unlock;
7824 	}
7825 
7826 	/* Still queued: a successful dequeue means it never started, so there
7827 	 * is nothing to disconnect.
7828 	 */
7829 	entry = _hci_cmd_sync_lookup_entry(hdev, hci_acl_create_conn_sync, conn,
7830 					   NULL);
7831 	if (entry) {
7832 		_hci_cmd_sync_cancel_entry(hdev, entry, -ECANCELED);
7833 		err = 0;
7834 	}
7835 
7836 unlock:
7837 	mutex_unlock(&hdev->cmd_sync_work_lock);
7838 	return err;
7839 }
7840 
7841 static int hci_le_cancel_create_conn_sync(struct hci_dev *hdev,
7842 					  struct hci_conn *conn)
7843 {
7844 	struct hci_cmd_sync_work_entry *entry;
7845 	int err = -EBUSY;
7846 
7847 	/* cmd_sync_work_lock keeps the HCI_CONN_CREATE test and the cancel
7848 	 * atomic against the cmd_sync worker.
7849 	 */
7850 	mutex_lock(&hdev->cmd_sync_work_lock);
7851 
7852 	if (test_bit(HCI_CONN_CREATE, conn->flags)) {
7853 		hci_cmd_sync_cancel(hdev, ECANCELED);
7854 		goto unlock;
7855 	}
7856 
7857 	entry = _hci_cmd_sync_lookup_entry(hdev, hci_le_create_conn_sync, conn,
7858 					   create_le_conn_complete);
7859 	if (entry) {
7860 		_hci_cmd_sync_cancel_entry(hdev, entry, -ECANCELED);
7861 		err = 0;
7862 	}
7863 
7864 unlock:
7865 	mutex_unlock(&hdev->cmd_sync_work_lock);
7866 	return err;
7867 }
7868 
7869 static int hci_cis_cancel_create_conn_sync(struct hci_dev *hdev,
7870 					   struct hci_conn *conn)
7871 {
7872 	/* LE Create CIS is shared by the whole CIG and cannot be dequeued
7873 	 * per-connection, so only an in-flight command can be cancelled.
7874 	 * cmd_sync_work_lock keeps the test and the cancel atomic against the
7875 	 * cmd_sync worker.
7876 	 */
7877 	mutex_lock(&hdev->cmd_sync_work_lock);
7878 
7879 	if (test_bit(HCI_CONN_CREATE_CIS, conn->flags))
7880 		hci_cmd_sync_cancel(hdev, ECANCELED);
7881 
7882 	mutex_unlock(&hdev->cmd_sync_work_lock);
7883 	return -EBUSY;
7884 }
7885 
7886 int hci_cancel_connect_sync(struct hci_dev *hdev, struct hci_conn *conn)
7887 {
7888 	switch (conn->type) {
7889 	case ACL_LINK:
7890 		return hci_acl_cancel_create_conn_sync(hdev, conn);
7891 	case LE_LINK:
7892 		return hci_le_cancel_create_conn_sync(hdev, conn);
7893 	case CIS_LINK:
7894 		return hci_cis_cancel_create_conn_sync(hdev, conn);
7895 	default:
7896 		return -ENOENT;
7897 	}
7898 }
7899 
7900 int hci_le_conn_update_sync(struct hci_dev *hdev, struct hci_conn *conn,
7901 			    struct hci_conn_params *params)
7902 {
7903 	struct hci_cp_le_conn_update cp;
7904 
7905 	memset(&cp, 0, sizeof(cp));
7906 	cp.handle		= cpu_to_le16(conn->handle);
7907 	cp.conn_interval_min	= cpu_to_le16(params->conn_min_interval);
7908 	cp.conn_interval_max	= cpu_to_le16(params->conn_max_interval);
7909 	cp.conn_latency		= cpu_to_le16(params->conn_latency);
7910 	cp.supervision_timeout	= cpu_to_le16(params->supervision_timeout);
7911 	cp.min_ce_len		= cpu_to_le16(0x0000);
7912 	cp.max_ce_len		= cpu_to_le16(0x0000);
7913 
7914 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CONN_UPDATE,
7915 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
7916 }
7917 
7918 static int hci_le_conn_rate_request_sync(struct hci_dev *hdev, void *data)
7919 {
7920 	struct hci_conn *conn = data;
7921 	struct hci_conn_params *params;
7922 	struct hci_cp_le_conn_rate cp;
7923 
7924 	hci_dev_lock(hdev);
7925 
7926 	/* The request was queued asynchronously so re-validate the connection
7927 	 * and its parameters under hdev->lock. The connection may have been
7928 	 * torn down, or may not have a valid handle yet (still connecting),
7929 	 * and the parameters may have been removed in the meantime (e.g. by
7930 	 * Load Connection Parameters). Snapshot the rate values so the
7931 	 * blocking command below can run without holding hdev->lock.
7932 	 */
7933 	if (!hci_conn_valid(hdev, conn) ||
7934 	    HCI_CONN_HANDLE_UNSET(conn->handle)) {
7935 		hci_dev_unlock(hdev);
7936 		return -ECANCELED;
7937 	}
7938 
7939 	params = hci_conn_params_lookup(hdev, &conn->dst, conn->dst_type);
7940 	if (!params) {
7941 		hci_dev_unlock(hdev);
7942 		return -ECANCELED;
7943 	}
7944 
7945 	memset(&cp, 0, sizeof(cp));
7946 	cp.handle	= cpu_to_le16(conn->handle);
7947 	cp.interval_min	= cpu_to_le16(params->rate_min_interval);
7948 	cp.interval_max	= cpu_to_le16(params->rate_max_interval);
7949 	cp.subrate_min	= cpu_to_le16(params->subrate_min);
7950 	cp.subrate_max	= cpu_to_le16(params->subrate_max);
7951 	cp.max_latency	= cpu_to_le16(params->max_latency);
7952 	cp.cont_num	= cpu_to_le16(params->cont_num);
7953 	cp.supv_timeout	= cpu_to_le16(params->rate_supv_timeout);
7954 
7955 	/* The connection event length recommended in requests by a Peripheral
7956 	 * uses units of 125 us with a valid range of 0x0001 to 0x7CFF
7957 	 * (0.125 ms to 3.999875 s), so 0x0000 cannot be used. Also note that
7958 	 * the Controller is not required to use these values:
7959 	 *
7960 	 * BLUETOOTH CORE SPECIFICATION Version 6.2 | Vol 4, Part E
7961 	 * 7.8.157. LE Connection Rate Request command
7962 	 *
7963 	 * The Min_CE_Length and Max_CE_Length parameters provide the
7964 	 * Controller with the expected minimum and maximum length of the
7965 	 * connection events. The Controller is not required to use these
7966 	 * values.
7967 	 *
7968 	 * So it is safe to just use the minimum.
7969 	 */
7970 	cp.min_ce_len	= cpu_to_le16(0x0001);
7971 	cp.max_ce_len	= cpu_to_le16(0x0001);
7972 
7973 	hci_dev_unlock(hdev);
7974 
7975 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CONN_RATE,
7976 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
7977 }
7978 
7979 static void hci_le_conn_rate_request_destroy(struct hci_dev *hdev, void *data,
7980 					     int err)
7981 {
7982 	struct hci_conn *conn = data;
7983 
7984 	hci_conn_put(conn);
7985 }
7986 
7987 int hci_le_conn_rate_request(struct hci_dev *hdev, struct hci_conn *conn)
7988 {
7989 	int err;
7990 
7991 	/* Hold a reference to the connection so it cannot be freed while the
7992 	 * request is pending or running on the cmd_sync worker.
7993 	 */
7994 	err = hci_cmd_sync_queue(hdev, hci_le_conn_rate_request_sync,
7995 				 hci_conn_get(conn),
7996 				 hci_le_conn_rate_request_destroy);
7997 	if (err < 0)
7998 		hci_conn_put(conn);
7999 
8000 	return err;
8001 }
8002 
8003 static void create_pa_complete(struct hci_dev *hdev, void *data, int err)
8004 {
8005 	struct hci_conn *conn = data;
8006 	struct hci_conn *pa_sync;
8007 
8008 	bt_dev_dbg(hdev, "err %d", err);
8009 
8010 	if (err == -ECANCELED)
8011 		goto done;
8012 
8013 	hci_dev_lock(hdev);
8014 
8015 	if (hci_conn_valid(hdev, conn))
8016 		clear_bit(HCI_CONN_CREATE_PA_SYNC, conn->flags);
8017 
8018 	if (!err)
8019 		goto unlock;
8020 
8021 	/* Add connection to indicate PA sync error */
8022 	pa_sync = hci_conn_add_unset(hdev, PA_LINK, BDADDR_ANY, 0,
8023 				     HCI_ROLE_SLAVE);
8024 
8025 	if (IS_ERR(pa_sync))
8026 		goto unlock;
8027 
8028 	set_bit(HCI_CONN_PA_SYNC_FAILED, pa_sync->flags);
8029 
8030 	/* Notify iso layer */
8031 	hci_connect_cfm(pa_sync, bt_status(err));
8032 
8033 unlock:
8034 	hci_dev_unlock(hdev);
8035 done:
8036 	hci_conn_put(conn);
8037 }
8038 
8039 static int hci_le_past_params_sync(struct hci_dev *hdev, struct hci_conn *conn,
8040 				   u16 acl_handle, struct bt_iso_qos *qos)
8041 {
8042 	struct hci_cp_le_past_params cp;
8043 	int err;
8044 
8045 	memset(&cp, 0, sizeof(cp));
8046 	cp.handle = cpu_to_le16(acl_handle);
8047 	/* An HCI_LE_Periodic_Advertising_Sync_Transfer_Received event is sent
8048 	 * to the Host. HCI_LE_Periodic_Advertising_Report events will be
8049 	 * enabled with duplicate filtering enabled.
8050 	 */
8051 	cp.mode = 0x03;
8052 	cp.skip = cpu_to_le16(qos->bcast.skip);
8053 	cp.sync_timeout = cpu_to_le16(qos->bcast.sync_timeout);
8054 	cp.cte_type = qos->bcast.sync_cte_type;
8055 
8056 	/* HCI_LE_PAST_PARAMS command returns a command complete event so it
8057 	 * cannot wait for HCI_EV_LE_PAST_RECEIVED.
8058 	 */
8059 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_PAST_PARAMS,
8060 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
8061 	if (err)
8062 		return err;
8063 
8064 	/* Wait for HCI_EV_LE_PAST_RECEIVED event */
8065 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_NOP, 0, NULL,
8066 					HCI_EV_LE_PAST_RECEIVED,
8067 					conn->conn_timeout, NULL);
8068 }
8069 
8070 static int hci_le_pa_create_sync(struct hci_dev *hdev, void *data)
8071 {
8072 	struct hci_cp_le_pa_create_sync cp;
8073 	struct hci_conn *conn = data, *le;
8074 	struct bt_iso_qos *qos = &conn->iso_qos;
8075 	int err;
8076 
8077 	if (!hci_conn_valid(hdev, conn))
8078 		return -ECANCELED;
8079 
8080 	if (conn->sync_handle != HCI_SYNC_HANDLE_INVALID)
8081 		return -EINVAL;
8082 
8083 	if (hci_dev_test_and_set_flag(hdev, HCI_PA_SYNC))
8084 		return -EBUSY;
8085 
8086 	/* Stop scanning if SID has not been set and active scanning is enabled
8087 	 * so we use passive scanning which will be scanning using the allow
8088 	 * list programmed to contain only the connection address.
8089 	 */
8090 	if (conn->sid == HCI_SID_INVALID &&
8091 	    hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
8092 		hci_scan_disable_sync(hdev);
8093 		hci_dev_set_flag(hdev, HCI_LE_SCAN_INTERRUPTED);
8094 		hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
8095 	}
8096 
8097 	/* Mark HCI_CONN_CREATE_PA_SYNC so hci_update_passive_scan_sync can
8098 	 * program the address in the allow list so PA advertisements can be
8099 	 * received.
8100 	 */
8101 	set_bit(HCI_CONN_CREATE_PA_SYNC, conn->flags);
8102 
8103 	hci_update_passive_scan_sync(hdev);
8104 
8105 	/* Check if PAST is possible:
8106 	 *
8107 	 * 1. Check if an ACL connection with the destination address exists
8108 	 * 2. Check if that HCI_CONN_FLAG_PAST has been set which indicates that
8109 	 *    user really intended to use PAST.
8110 	 */
8111 	hci_dev_lock(hdev);
8112 
8113 	le = hci_conn_hash_lookup_le(hdev, &conn->dst, conn->dst_type);
8114 	if (le) {
8115 		struct hci_conn_params *params;
8116 		hci_conn_flags_t flags = 0;
8117 		u16 le_handle = le->handle;
8118 
8119 		params = hci_conn_params_lookup(hdev, &le->dst, le->dst_type);
8120 		if (params)
8121 			flags = params->flags;
8122 
8123 		hci_dev_unlock(hdev);
8124 
8125 		if (flags & HCI_CONN_FLAG_PAST) {
8126 			err = hci_le_past_params_sync(hdev, conn, le_handle,
8127 						      qos);
8128 			if (!err)
8129 				goto done;
8130 		}
8131 	} else {
8132 		hci_dev_unlock(hdev);
8133 	}
8134 
8135 	/* SID has not been set listen for HCI_EV_LE_EXT_ADV_REPORT to update
8136 	 * it.
8137 	 */
8138 	if (conn->sid == HCI_SID_INVALID) {
8139 		err = __hci_cmd_sync_status_sk(hdev, HCI_OP_NOP, 0, NULL,
8140 					       HCI_EV_LE_EXT_ADV_REPORT,
8141 					       conn->conn_timeout, NULL);
8142 		if (err == -ETIMEDOUT)
8143 			goto done;
8144 	}
8145 
8146 	memset(&cp, 0, sizeof(cp));
8147 	cp.options = qos->bcast.options;
8148 	cp.sid = conn->sid;
8149 	cp.addr_type = conn->dst_type;
8150 	bacpy(&cp.addr, &conn->dst);
8151 	cp.skip = cpu_to_le16(qos->bcast.skip);
8152 	cp.sync_timeout = cpu_to_le16(qos->bcast.sync_timeout);
8153 	cp.sync_cte_type = qos->bcast.sync_cte_type;
8154 
8155 	/* The spec allows only one pending LE Periodic Advertising Create
8156 	 * Sync command at a time so we forcefully wait for PA Sync Established
8157 	 * event since cmd_work can only schedule one command at a time.
8158 	 *
8159 	 * BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
8160 	 * page 2493:
8161 	 *
8162 	 * If the Host issues this command when another HCI_LE_Periodic_
8163 	 * Advertising_Create_Sync command is pending, the Controller shall
8164 	 * return the error code Command Disallowed (0x0C).
8165 	 */
8166 	err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_PA_CREATE_SYNC,
8167 				       sizeof(cp), &cp,
8168 				       HCI_EV_LE_PA_SYNC_ESTABLISHED,
8169 				       conn->conn_timeout, NULL);
8170 	if (err == -ETIMEDOUT)
8171 		__hci_cmd_sync_status(hdev, HCI_OP_LE_PA_CREATE_SYNC_CANCEL,
8172 				      0, NULL, HCI_CMD_TIMEOUT);
8173 
8174 done:
8175 	hci_dev_clear_flag(hdev, HCI_PA_SYNC);
8176 
8177 	/* Update passive scan since HCI_PA_SYNC flag has been cleared */
8178 	hci_update_passive_scan_sync(hdev);
8179 
8180 	return err;
8181 }
8182 
8183 int hci_connect_pa_sync(struct hci_dev *hdev, struct hci_conn *conn)
8184 {
8185 	int err;
8186 
8187 	err = hci_cmd_sync_queue_once(hdev, hci_le_pa_create_sync,
8188 				      hci_conn_get(conn),
8189 				      create_pa_complete);
8190 	if (err)
8191 		hci_conn_put(conn);
8192 	return (err == -EEXIST) ? 0 : err;
8193 }
8194 
8195 static void create_big_complete(struct hci_dev *hdev, void *data, int err)
8196 {
8197 	struct hci_conn *conn = data;
8198 
8199 	bt_dev_dbg(hdev, "err %d", err);
8200 
8201 	if (err == -ECANCELED)
8202 		goto done;
8203 
8204 	clear_bit(HCI_CONN_CREATE_BIG_SYNC, conn->flags);
8205 
8206 done:
8207 	hci_conn_put(conn);
8208 }
8209 
8210 static int hci_le_big_create_sync(struct hci_dev *hdev, void *data)
8211 {
8212 	DEFINE_FLEX(struct hci_cp_le_big_create_sync, cp, bis, num_bis,
8213 		    HCI_MAX_ISO_BIS);
8214 	struct hci_conn *conn = data;
8215 	struct bt_iso_qos *qos = &conn->iso_qos;
8216 	int err;
8217 
8218 	if (!hci_conn_valid(hdev, conn))
8219 		return -ECANCELED;
8220 
8221 	set_bit(HCI_CONN_CREATE_BIG_SYNC, conn->flags);
8222 
8223 	memset(cp, 0, sizeof(*cp));
8224 	cp->handle = qos->bcast.big;
8225 	cp->sync_handle = cpu_to_le16(conn->sync_handle);
8226 	cp->encryption = qos->bcast.encryption;
8227 	memcpy(cp->bcode, qos->bcast.bcode, sizeof(cp->bcode));
8228 	cp->mse = qos->bcast.mse;
8229 	cp->timeout = cpu_to_le16(qos->bcast.timeout);
8230 	cp->num_bis = conn->num_bis;
8231 	memcpy(cp->bis, conn->bis, conn->num_bis);
8232 
8233 	/* The spec allows only one pending LE BIG Create Sync command at
8234 	 * a time, so we forcefully wait for BIG Sync Established event since
8235 	 * cmd_work can only schedule one command at a time.
8236 	 *
8237 	 * BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
8238 	 * page 2586:
8239 	 *
8240 	 * If the Host sends this command when the Controller is in the
8241 	 * process of synchronizing to any BIG, i.e. the HCI_LE_BIG_Sync_
8242 	 * Established event has not been generated, the Controller shall
8243 	 * return the error code Command Disallowed (0x0C).
8244 	 */
8245 	err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_BIG_CREATE_SYNC,
8246 				       struct_size(cp, bis, cp->num_bis), cp,
8247 				       HCI_EVT_LE_BIG_SYNC_ESTABLISHED,
8248 				       conn->conn_timeout, NULL);
8249 	if (err == -ETIMEDOUT)
8250 		hci_le_big_terminate_sync(hdev, cp->handle);
8251 
8252 	return err;
8253 }
8254 
8255 int hci_connect_big_sync(struct hci_dev *hdev, struct hci_conn *conn)
8256 {
8257 	int err;
8258 
8259 	if (!conn)
8260 		return 0;
8261 
8262 	err = hci_cmd_sync_queue_once(hdev, hci_le_big_create_sync,
8263 				      hci_conn_get(conn),
8264 				      create_big_complete);
8265 	if (err)
8266 		hci_conn_put(conn);
8267 	return (err == -EEXIST) ? 0 : err;
8268 }
8269 
8270 struct past_data {
8271 	struct hci_conn *conn;
8272 	struct hci_conn *le;
8273 };
8274 
8275 static void past_complete(struct hci_dev *hdev, void *data, int err)
8276 {
8277 	struct past_data *past = data;
8278 
8279 	bt_dev_dbg(hdev, "err %d", err);
8280 
8281 	hci_conn_put(past->conn);
8282 	hci_conn_put(past->le);
8283 	kfree(past);
8284 }
8285 
8286 static int hci_le_past_set_info_sync(struct hci_dev *hdev, void *data)
8287 {
8288 	struct past_data *past = data;
8289 	struct hci_cp_le_past_set_info cp;
8290 	struct adv_info *adv;
8291 
8292 	hci_dev_lock(hdev);
8293 
8294 	if (!hci_conn_valid(hdev, past->conn) ||
8295 	    !hci_conn_valid(hdev, past->le)) {
8296 		hci_dev_unlock(hdev);
8297 		return -ECANCELED;
8298 	}
8299 
8300 	memset(&cp, 0, sizeof(cp));
8301 	cp.handle = cpu_to_le16(past->le->handle);
8302 	cp.adv_handle = past->conn->iso_qos.bcast.bis;
8303 	adv = hci_find_adv_instance(hdev, cp.adv_handle);
8304 	if (adv)
8305 		cp.adv_handle = adv->handle;
8306 
8307 	hci_dev_unlock(hdev);
8308 
8309 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_PAST_SET_INFO,
8310 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
8311 }
8312 
8313 static int hci_le_past_sync(struct hci_dev *hdev, void *data)
8314 {
8315 	struct past_data *past = data;
8316 	struct hci_cp_le_past cp;
8317 
8318 	hci_dev_lock(hdev);
8319 
8320 	if (!hci_conn_valid(hdev, past->conn) ||
8321 	    !hci_conn_valid(hdev, past->le)) {
8322 		hci_dev_unlock(hdev);
8323 		return -ECANCELED;
8324 	}
8325 
8326 	memset(&cp, 0, sizeof(cp));
8327 	cp.handle = cpu_to_le16(past->le->handle);
8328 	cp.sync_handle = cpu_to_le16(past->conn->sync_handle);
8329 
8330 	hci_dev_unlock(hdev);
8331 
8332 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_PAST,
8333 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
8334 }
8335 
8336 int hci_past_sync(struct hci_conn *conn, struct hci_conn *le)
8337 {
8338 	struct past_data *data;
8339 	int err;
8340 
8341 	if (conn->type != BIS_LINK && conn->type != PA_LINK)
8342 		return -EINVAL;
8343 
8344 	if (!past_sender_capable(conn->hdev))
8345 		return -EOPNOTSUPP;
8346 
8347 	data = kmalloc_obj(*data);
8348 	if (!data)
8349 		return -ENOMEM;
8350 
8351 	data->conn = hci_conn_get(conn);
8352 	data->le = hci_conn_get(le);
8353 
8354 	if (conn->role == HCI_ROLE_MASTER)
8355 		err = hci_cmd_sync_queue_once(conn->hdev,
8356 					      hci_le_past_set_info_sync, data,
8357 					      past_complete);
8358 	else
8359 		err = hci_cmd_sync_queue_once(conn->hdev, hci_le_past_sync,
8360 					      data, past_complete);
8361 
8362 	if (err) {
8363 		hci_conn_put(data->conn);
8364 		hci_conn_put(data->le);
8365 		kfree(data);
8366 	}
8367 
8368 	return (err == -EEXIST) ? 0 : err;
8369 }
8370 
8371 static void le_read_features_complete(struct hci_dev *hdev, void *data, int err)
8372 {
8373 	struct hci_conn *conn = data;
8374 
8375 	bt_dev_dbg(hdev, "err %d", err);
8376 
8377 	hci_conn_drop(conn);
8378 	hci_conn_put(conn);
8379 }
8380 
8381 static int hci_le_read_all_remote_features_sync(struct hci_dev *hdev,
8382 						void *data)
8383 {
8384 	struct hci_conn *conn = data;
8385 	struct hci_cp_le_read_all_remote_features cp;
8386 
8387 	memset(&cp, 0, sizeof(cp));
8388 	cp.handle = cpu_to_le16(conn->handle);
8389 	cp.pages = 10; /* Attempt to read all pages */
8390 
8391 	/* Wait for HCI_EVT_LE_ALL_REMOTE_FEATURES_COMPLETE event otherwise
8392 	 * hci_conn_drop may run prematurely causing a disconnection.
8393 	 */
8394 	return __hci_cmd_sync_status_sk(hdev,
8395 					HCI_OP_LE_READ_ALL_REMOTE_FEATURES,
8396 					sizeof(cp), &cp,
8397 					HCI_EVT_LE_ALL_REMOTE_FEATURES_COMPLETE,
8398 					HCI_CMD_TIMEOUT, NULL);
8399 }
8400 
8401 static int hci_le_read_remote_features_sync(struct hci_dev *hdev, void *data)
8402 {
8403 	struct hci_conn *conn = data;
8404 	struct hci_cp_le_read_remote_features cp;
8405 
8406 	if (!hci_conn_valid(hdev, conn))
8407 		return -ECANCELED;
8408 
8409 	/* Check if LL Extended Feature Set is supported and
8410 	 * HCI_OP_LE_READ_ALL_REMOTE_FEATURES is supported then use that to read
8411 	 * all features.
8412 	 */
8413 	if (ll_ext_feature_capable(hdev) && hdev->commands[47] & BIT(3))
8414 		return hci_le_read_all_remote_features_sync(hdev, data);
8415 
8416 	memset(&cp, 0, sizeof(cp));
8417 	cp.handle = cpu_to_le16(conn->handle);
8418 
8419 	/* Wait for HCI_EV_LE_REMOTE_FEAT_COMPLETE event otherwise
8420 	 * hci_conn_drop may run prematurely causing a disconnection.
8421 	 */
8422 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_READ_REMOTE_FEATURES,
8423 					sizeof(cp), &cp,
8424 					HCI_EV_LE_REMOTE_FEAT_COMPLETE,
8425 					HCI_CMD_TIMEOUT, NULL);
8426 }
8427 
8428 int hci_le_read_remote_features(struct hci_conn *conn)
8429 {
8430 	struct hci_dev *hdev = conn->hdev;
8431 	int err;
8432 
8433 	/* The remote features procedure is defined for central
8434 	 * role only. So only in case of an initiated connection
8435 	 * request the remote features.
8436 	 *
8437 	 * If the local controller supports peripheral-initiated features
8438 	 * exchange, then requesting the remote features in peripheral
8439 	 * role is possible. Otherwise just transition into the
8440 	 * connected state without requesting the remote features.
8441 	 */
8442 	if (conn->out || (hdev->le_features[0] & HCI_LE_PERIPHERAL_FEATURES)) {
8443 		err = hci_cmd_sync_queue_once(hdev,
8444 					      hci_le_read_remote_features_sync,
8445 					      hci_conn_hold(hci_conn_get(conn)),
8446 					      le_read_features_complete);
8447 		if (err) {
8448 			hci_conn_drop(conn);
8449 			hci_conn_put(conn);
8450 		}
8451 	} else {
8452 		err = -EOPNOTSUPP;
8453 	}
8454 
8455 	return (err == -EEXIST) ? 0 : err;
8456 }
8457 
8458 static void pkt_type_changed(struct hci_dev *hdev, void *data, int err)
8459 {
8460 	struct hci_cp_change_conn_ptype *cp = data;
8461 
8462 	bt_dev_dbg(hdev, "err %d", err);
8463 
8464 	kfree(cp);
8465 }
8466 
8467 static int hci_change_conn_ptype_sync(struct hci_dev *hdev, void *data)
8468 {
8469 	struct hci_cp_change_conn_ptype *cp = data;
8470 
8471 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_CHANGE_CONN_PTYPE,
8472 					sizeof(*cp), cp,
8473 					HCI_EV_PKT_TYPE_CHANGE,
8474 					HCI_CMD_TIMEOUT, NULL);
8475 }
8476 
8477 int hci_acl_change_pkt_type(struct hci_conn *conn, u16 pkt_type)
8478 {
8479 	struct hci_dev *hdev = conn->hdev;
8480 	struct hci_cp_change_conn_ptype *cp;
8481 	int err;
8482 
8483 	cp = kmalloc_obj(*cp);
8484 	if (!cp)
8485 		return -ENOMEM;
8486 
8487 	cp->handle = cpu_to_le16(conn->handle);
8488 	cp->pkt_type = cpu_to_le16(pkt_type);
8489 
8490 	err = hci_cmd_sync_queue_once(hdev, hci_change_conn_ptype_sync, cp,
8491 				      pkt_type_changed);
8492 	if (err)
8493 		kfree(cp);
8494 
8495 	return (err == -EEXIST) ? 0 : err;
8496 }
8497 
8498 static void le_phy_update_complete(struct hci_dev *hdev, void *data, int err)
8499 {
8500 	struct hci_cp_le_set_phy *cp = data;
8501 
8502 	bt_dev_dbg(hdev, "err %d", err);
8503 
8504 	kfree(cp);
8505 }
8506 
8507 static int hci_le_set_phy_sync(struct hci_dev *hdev, void *data)
8508 {
8509 	struct hci_cp_le_set_phy *cp = data;
8510 
8511 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_SET_PHY,
8512 					sizeof(*cp), cp,
8513 					HCI_EV_LE_PHY_UPDATE_COMPLETE,
8514 					HCI_CMD_TIMEOUT, NULL);
8515 }
8516 
8517 int hci_le_set_phy(struct hci_conn *conn, u8 tx_phys, u8 rx_phys)
8518 {
8519 	struct hci_dev *hdev = conn->hdev;
8520 	struct hci_cp_le_set_phy *cp;
8521 	int err;
8522 
8523 	cp = kmalloc_obj(*cp);
8524 	if (!cp)
8525 		return -ENOMEM;
8526 
8527 	memset(cp, 0, sizeof(*cp));
8528 	cp->handle = cpu_to_le16(conn->handle);
8529 	cp->tx_phys = tx_phys;
8530 	cp->rx_phys = rx_phys;
8531 
8532 	err = hci_cmd_sync_queue_once(hdev, hci_le_set_phy_sync, cp,
8533 				      le_phy_update_complete);
8534 	if (err)
8535 		kfree(cp);
8536 
8537 	return (err == -EEXIST) ? 0 : err;
8538 }
8539