xref: /openbmc/linux/net/bluetooth/hci_sync.c (revision 94ab3170)
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_request.h"
16 #include "hci_codec.h"
17 #include "hci_debugfs.h"
18 #include "smp.h"
19 #include "eir.h"
20 #include "msft.h"
21 #include "aosp.h"
22 #include "leds.h"
23 
24 static void hci_cmd_sync_complete(struct hci_dev *hdev, u8 result, u16 opcode,
25 				  struct sk_buff *skb)
26 {
27 	bt_dev_dbg(hdev, "result 0x%2.2x", result);
28 
29 	if (hdev->req_status != HCI_REQ_PEND)
30 		return;
31 
32 	hdev->req_result = result;
33 	hdev->req_status = HCI_REQ_DONE;
34 
35 	/* Free the request command so it is not used as response */
36 	kfree_skb(hdev->req_skb);
37 	hdev->req_skb = NULL;
38 
39 	if (skb) {
40 		struct sock *sk = hci_skb_sk(skb);
41 
42 		/* Drop sk reference if set */
43 		if (sk)
44 			sock_put(sk);
45 
46 		hdev->req_rsp = skb_get(skb);
47 	}
48 
49 	wake_up_interruptible(&hdev->req_wait_q);
50 }
51 
52 static struct sk_buff *hci_cmd_sync_alloc(struct hci_dev *hdev, u16 opcode,
53 					  u32 plen, const void *param,
54 					  struct sock *sk)
55 {
56 	int len = HCI_COMMAND_HDR_SIZE + plen;
57 	struct hci_command_hdr *hdr;
58 	struct sk_buff *skb;
59 
60 	skb = bt_skb_alloc(len, GFP_ATOMIC);
61 	if (!skb)
62 		return NULL;
63 
64 	hdr = skb_put(skb, HCI_COMMAND_HDR_SIZE);
65 	hdr->opcode = cpu_to_le16(opcode);
66 	hdr->plen   = plen;
67 
68 	if (plen)
69 		skb_put_data(skb, param, plen);
70 
71 	bt_dev_dbg(hdev, "skb len %d", skb->len);
72 
73 	hci_skb_pkt_type(skb) = HCI_COMMAND_PKT;
74 	hci_skb_opcode(skb) = opcode;
75 
76 	/* Grab a reference if command needs to be associated with a sock (e.g.
77 	 * likely mgmt socket that initiated the command).
78 	 */
79 	if (sk) {
80 		hci_skb_sk(skb) = sk;
81 		sock_hold(sk);
82 	}
83 
84 	return skb;
85 }
86 
87 static void hci_cmd_sync_add(struct hci_request *req, u16 opcode, u32 plen,
88 			     const void *param, u8 event, struct sock *sk)
89 {
90 	struct hci_dev *hdev = req->hdev;
91 	struct sk_buff *skb;
92 
93 	bt_dev_dbg(hdev, "opcode 0x%4.4x plen %d", opcode, plen);
94 
95 	/* If an error occurred during request building, there is no point in
96 	 * queueing the HCI command. We can simply return.
97 	 */
98 	if (req->err)
99 		return;
100 
101 	skb = hci_cmd_sync_alloc(hdev, opcode, plen, param, sk);
102 	if (!skb) {
103 		bt_dev_err(hdev, "no memory for command (opcode 0x%4.4x)",
104 			   opcode);
105 		req->err = -ENOMEM;
106 		return;
107 	}
108 
109 	if (skb_queue_empty(&req->cmd_q))
110 		bt_cb(skb)->hci.req_flags |= HCI_REQ_START;
111 
112 	hci_skb_event(skb) = event;
113 
114 	skb_queue_tail(&req->cmd_q, skb);
115 }
116 
117 static int hci_cmd_sync_run(struct hci_request *req)
118 {
119 	struct hci_dev *hdev = req->hdev;
120 	struct sk_buff *skb;
121 	unsigned long flags;
122 
123 	bt_dev_dbg(hdev, "length %u", skb_queue_len(&req->cmd_q));
124 
125 	/* If an error occurred during request building, remove all HCI
126 	 * commands queued on the HCI request queue.
127 	 */
128 	if (req->err) {
129 		skb_queue_purge(&req->cmd_q);
130 		return req->err;
131 	}
132 
133 	/* Do not allow empty requests */
134 	if (skb_queue_empty(&req->cmd_q))
135 		return -ENODATA;
136 
137 	skb = skb_peek_tail(&req->cmd_q);
138 	bt_cb(skb)->hci.req_complete_skb = hci_cmd_sync_complete;
139 	bt_cb(skb)->hci.req_flags |= HCI_REQ_SKB;
140 
141 	spin_lock_irqsave(&hdev->cmd_q.lock, flags);
142 	skb_queue_splice_tail(&req->cmd_q, &hdev->cmd_q);
143 	spin_unlock_irqrestore(&hdev->cmd_q.lock, flags);
144 
145 	queue_work(hdev->workqueue, &hdev->cmd_work);
146 
147 	return 0;
148 }
149 
150 /* This function requires the caller holds hdev->req_lock. */
151 struct sk_buff *__hci_cmd_sync_sk(struct hci_dev *hdev, u16 opcode, u32 plen,
152 				  const void *param, u8 event, u32 timeout,
153 				  struct sock *sk)
154 {
155 	struct hci_request req;
156 	struct sk_buff *skb;
157 	int err = 0;
158 
159 	bt_dev_dbg(hdev, "Opcode 0x%4.4x", opcode);
160 
161 	hci_req_init(&req, hdev);
162 
163 	hci_cmd_sync_add(&req, opcode, plen, param, event, sk);
164 
165 	hdev->req_status = HCI_REQ_PEND;
166 
167 	err = hci_cmd_sync_run(&req);
168 	if (err < 0)
169 		return ERR_PTR(err);
170 
171 	err = wait_event_interruptible_timeout(hdev->req_wait_q,
172 					       hdev->req_status != HCI_REQ_PEND,
173 					       timeout);
174 
175 	if (err == -ERESTARTSYS)
176 		return ERR_PTR(-EINTR);
177 
178 	switch (hdev->req_status) {
179 	case HCI_REQ_DONE:
180 		err = -bt_to_errno(hdev->req_result);
181 		break;
182 
183 	case HCI_REQ_CANCELED:
184 		err = -hdev->req_result;
185 		break;
186 
187 	default:
188 		err = -ETIMEDOUT;
189 		break;
190 	}
191 
192 	hdev->req_status = 0;
193 	hdev->req_result = 0;
194 	skb = hdev->req_rsp;
195 	hdev->req_rsp = NULL;
196 
197 	bt_dev_dbg(hdev, "end: err %d", err);
198 
199 	if (err < 0) {
200 		kfree_skb(skb);
201 		return ERR_PTR(err);
202 	}
203 
204 	return skb;
205 }
206 EXPORT_SYMBOL(__hci_cmd_sync_sk);
207 
208 /* This function requires the caller holds hdev->req_lock. */
209 struct sk_buff *__hci_cmd_sync(struct hci_dev *hdev, u16 opcode, u32 plen,
210 			       const void *param, u32 timeout)
211 {
212 	return __hci_cmd_sync_sk(hdev, opcode, plen, param, 0, timeout, NULL);
213 }
214 EXPORT_SYMBOL(__hci_cmd_sync);
215 
216 /* Send HCI command and wait for command complete event */
217 struct sk_buff *hci_cmd_sync(struct hci_dev *hdev, u16 opcode, u32 plen,
218 			     const void *param, u32 timeout)
219 {
220 	struct sk_buff *skb;
221 
222 	if (!test_bit(HCI_UP, &hdev->flags))
223 		return ERR_PTR(-ENETDOWN);
224 
225 	bt_dev_dbg(hdev, "opcode 0x%4.4x plen %d", opcode, plen);
226 
227 	hci_req_sync_lock(hdev);
228 	skb = __hci_cmd_sync(hdev, opcode, plen, param, timeout);
229 	hci_req_sync_unlock(hdev);
230 
231 	return skb;
232 }
233 EXPORT_SYMBOL(hci_cmd_sync);
234 
235 /* This function requires the caller holds hdev->req_lock. */
236 struct sk_buff *__hci_cmd_sync_ev(struct hci_dev *hdev, u16 opcode, u32 plen,
237 				  const void *param, u8 event, u32 timeout)
238 {
239 	return __hci_cmd_sync_sk(hdev, opcode, plen, param, event, timeout,
240 				 NULL);
241 }
242 EXPORT_SYMBOL(__hci_cmd_sync_ev);
243 
244 /* This function requires the caller holds hdev->req_lock. */
245 int __hci_cmd_sync_status_sk(struct hci_dev *hdev, u16 opcode, u32 plen,
246 			     const void *param, u8 event, u32 timeout,
247 			     struct sock *sk)
248 {
249 	struct sk_buff *skb;
250 	u8 status;
251 
252 	skb = __hci_cmd_sync_sk(hdev, opcode, plen, param, event, timeout, sk);
253 	if (IS_ERR(skb)) {
254 		if (!event)
255 			bt_dev_err(hdev, "Opcode 0x%4.4x failed: %ld", opcode,
256 				   PTR_ERR(skb));
257 		return PTR_ERR(skb);
258 	}
259 
260 	/* If command return a status event skb will be set to NULL as there are
261 	 * no parameters, in case of failure IS_ERR(skb) would have be set to
262 	 * the actual error would be found with PTR_ERR(skb).
263 	 */
264 	if (!skb)
265 		return 0;
266 
267 	status = skb->data[0];
268 
269 	kfree_skb(skb);
270 
271 	return status;
272 }
273 EXPORT_SYMBOL(__hci_cmd_sync_status_sk);
274 
275 int __hci_cmd_sync_status(struct hci_dev *hdev, u16 opcode, u32 plen,
276 			  const void *param, u32 timeout)
277 {
278 	return __hci_cmd_sync_status_sk(hdev, opcode, plen, param, 0, timeout,
279 					NULL);
280 }
281 EXPORT_SYMBOL(__hci_cmd_sync_status);
282 
283 int hci_cmd_sync_status(struct hci_dev *hdev, u16 opcode, u32 plen,
284 			const void *param, u32 timeout)
285 {
286 	int err;
287 
288 	hci_req_sync_lock(hdev);
289 	err = __hci_cmd_sync_status(hdev, opcode, plen, param, timeout);
290 	hci_req_sync_unlock(hdev);
291 
292 	return err;
293 }
294 EXPORT_SYMBOL(hci_cmd_sync_status);
295 
296 static void hci_cmd_sync_work(struct work_struct *work)
297 {
298 	struct hci_dev *hdev = container_of(work, struct hci_dev, cmd_sync_work);
299 
300 	bt_dev_dbg(hdev, "");
301 
302 	/* Dequeue all entries and run them */
303 	while (1) {
304 		struct hci_cmd_sync_work_entry *entry;
305 
306 		mutex_lock(&hdev->cmd_sync_work_lock);
307 		entry = list_first_entry_or_null(&hdev->cmd_sync_work_list,
308 						 struct hci_cmd_sync_work_entry,
309 						 list);
310 		if (entry)
311 			list_del(&entry->list);
312 		mutex_unlock(&hdev->cmd_sync_work_lock);
313 
314 		if (!entry)
315 			break;
316 
317 		bt_dev_dbg(hdev, "entry %p", entry);
318 
319 		if (entry->func) {
320 			int err;
321 
322 			hci_req_sync_lock(hdev);
323 			err = entry->func(hdev, entry->data);
324 			if (entry->destroy)
325 				entry->destroy(hdev, entry->data, err);
326 			hci_req_sync_unlock(hdev);
327 		}
328 
329 		kfree(entry);
330 	}
331 }
332 
333 static void hci_cmd_sync_cancel_work(struct work_struct *work)
334 {
335 	struct hci_dev *hdev = container_of(work, struct hci_dev, cmd_sync_cancel_work);
336 
337 	cancel_delayed_work_sync(&hdev->cmd_timer);
338 	cancel_delayed_work_sync(&hdev->ncmd_timer);
339 	atomic_set(&hdev->cmd_cnt, 1);
340 
341 	wake_up_interruptible(&hdev->req_wait_q);
342 }
343 
344 static int hci_scan_disable_sync(struct hci_dev *hdev);
345 static int scan_disable_sync(struct hci_dev *hdev, void *data)
346 {
347 	return hci_scan_disable_sync(hdev);
348 }
349 
350 static int hci_inquiry_sync(struct hci_dev *hdev, u8 length);
351 static int interleaved_inquiry_sync(struct hci_dev *hdev, void *data)
352 {
353 	return hci_inquiry_sync(hdev, DISCOV_INTERLEAVED_INQUIRY_LEN);
354 }
355 
356 static void le_scan_disable(struct work_struct *work)
357 {
358 	struct hci_dev *hdev = container_of(work, struct hci_dev,
359 					    le_scan_disable.work);
360 	int status;
361 
362 	bt_dev_dbg(hdev, "");
363 	hci_dev_lock(hdev);
364 
365 	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN))
366 		goto _return;
367 
368 	cancel_delayed_work(&hdev->le_scan_restart);
369 
370 	status = hci_cmd_sync_queue(hdev, scan_disable_sync, NULL, NULL);
371 	if (status) {
372 		bt_dev_err(hdev, "failed to disable LE scan: %d", status);
373 		goto _return;
374 	}
375 
376 	hdev->discovery.scan_start = 0;
377 
378 	/* If we were running LE only scan, change discovery state. If
379 	 * we were running both LE and BR/EDR inquiry simultaneously,
380 	 * and BR/EDR inquiry is already finished, stop discovery,
381 	 * otherwise BR/EDR inquiry will stop discovery when finished.
382 	 * If we will resolve remote device name, do not change
383 	 * discovery state.
384 	 */
385 
386 	if (hdev->discovery.type == DISCOV_TYPE_LE)
387 		goto discov_stopped;
388 
389 	if (hdev->discovery.type != DISCOV_TYPE_INTERLEAVED)
390 		goto _return;
391 
392 	if (test_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks)) {
393 		if (!test_bit(HCI_INQUIRY, &hdev->flags) &&
394 		    hdev->discovery.state != DISCOVERY_RESOLVING)
395 			goto discov_stopped;
396 
397 		goto _return;
398 	}
399 
400 	status = hci_cmd_sync_queue(hdev, interleaved_inquiry_sync, NULL, NULL);
401 	if (status) {
402 		bt_dev_err(hdev, "inquiry failed: status %d", status);
403 		goto discov_stopped;
404 	}
405 
406 	goto _return;
407 
408 discov_stopped:
409 	hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
410 
411 _return:
412 	hci_dev_unlock(hdev);
413 }
414 
415 static int hci_le_set_scan_enable_sync(struct hci_dev *hdev, u8 val,
416 				       u8 filter_dup);
417 static int hci_le_scan_restart_sync(struct hci_dev *hdev)
418 {
419 	/* If controller is not scanning we are done. */
420 	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN))
421 		return 0;
422 
423 	if (hdev->scanning_paused) {
424 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
425 		return 0;
426 	}
427 
428 	hci_le_set_scan_enable_sync(hdev, LE_SCAN_DISABLE, 0x00);
429 	return hci_le_set_scan_enable_sync(hdev, LE_SCAN_ENABLE,
430 					   LE_SCAN_FILTER_DUP_ENABLE);
431 }
432 
433 static void le_scan_restart(struct work_struct *work)
434 {
435 	struct hci_dev *hdev = container_of(work, struct hci_dev,
436 					    le_scan_restart.work);
437 	unsigned long timeout, duration, scan_start, now;
438 	int status;
439 
440 	bt_dev_dbg(hdev, "");
441 
442 	status = hci_le_scan_restart_sync(hdev);
443 	if (status) {
444 		bt_dev_err(hdev, "failed to restart LE scan: status %d",
445 			   status);
446 		return;
447 	}
448 
449 	hci_dev_lock(hdev);
450 
451 	if (!test_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks) ||
452 	    !hdev->discovery.scan_start)
453 		goto unlock;
454 
455 	/* When the scan was started, hdev->le_scan_disable has been queued
456 	 * after duration from scan_start. During scan restart this job
457 	 * has been canceled, and we need to queue it again after proper
458 	 * timeout, to make sure that scan does not run indefinitely.
459 	 */
460 	duration = hdev->discovery.scan_duration;
461 	scan_start = hdev->discovery.scan_start;
462 	now = jiffies;
463 	if (now - scan_start <= duration) {
464 		int elapsed;
465 
466 		if (now >= scan_start)
467 			elapsed = now - scan_start;
468 		else
469 			elapsed = ULONG_MAX - scan_start + now;
470 
471 		timeout = duration - elapsed;
472 	} else {
473 		timeout = 0;
474 	}
475 
476 	queue_delayed_work(hdev->req_workqueue,
477 			   &hdev->le_scan_disable, timeout);
478 
479 unlock:
480 	hci_dev_unlock(hdev);
481 }
482 
483 static int reenable_adv_sync(struct hci_dev *hdev, void *data)
484 {
485 	bt_dev_dbg(hdev, "");
486 
487 	if (!hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
488 	    list_empty(&hdev->adv_instances))
489 		return 0;
490 
491 	if (hdev->cur_adv_instance) {
492 		return hci_schedule_adv_instance_sync(hdev,
493 						      hdev->cur_adv_instance,
494 						      true);
495 	} else {
496 		if (ext_adv_capable(hdev)) {
497 			hci_start_ext_adv_sync(hdev, 0x00);
498 		} else {
499 			hci_update_adv_data_sync(hdev, 0x00);
500 			hci_update_scan_rsp_data_sync(hdev, 0x00);
501 			hci_enable_advertising_sync(hdev);
502 		}
503 	}
504 
505 	return 0;
506 }
507 
508 static void reenable_adv(struct work_struct *work)
509 {
510 	struct hci_dev *hdev = container_of(work, struct hci_dev,
511 					    reenable_adv_work);
512 	int status;
513 
514 	bt_dev_dbg(hdev, "");
515 
516 	hci_dev_lock(hdev);
517 
518 	status = hci_cmd_sync_queue(hdev, reenable_adv_sync, NULL, NULL);
519 	if (status)
520 		bt_dev_err(hdev, "failed to reenable ADV: %d", status);
521 
522 	hci_dev_unlock(hdev);
523 }
524 
525 static void cancel_adv_timeout(struct hci_dev *hdev)
526 {
527 	if (hdev->adv_instance_timeout) {
528 		hdev->adv_instance_timeout = 0;
529 		cancel_delayed_work(&hdev->adv_instance_expire);
530 	}
531 }
532 
533 /* For a single instance:
534  * - force == true: The instance will be removed even when its remaining
535  *   lifetime is not zero.
536  * - force == false: the instance will be deactivated but kept stored unless
537  *   the remaining lifetime is zero.
538  *
539  * For instance == 0x00:
540  * - force == true: All instances will be removed regardless of their timeout
541  *   setting.
542  * - force == false: Only instances that have a timeout will be removed.
543  */
544 int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk,
545 				u8 instance, bool force)
546 {
547 	struct adv_info *adv_instance, *n, *next_instance = NULL;
548 	int err;
549 	u8 rem_inst;
550 
551 	/* Cancel any timeout concerning the removed instance(s). */
552 	if (!instance || hdev->cur_adv_instance == instance)
553 		cancel_adv_timeout(hdev);
554 
555 	/* Get the next instance to advertise BEFORE we remove
556 	 * the current one. This can be the same instance again
557 	 * if there is only one instance.
558 	 */
559 	if (instance && hdev->cur_adv_instance == instance)
560 		next_instance = hci_get_next_instance(hdev, instance);
561 
562 	if (instance == 0x00) {
563 		list_for_each_entry_safe(adv_instance, n, &hdev->adv_instances,
564 					 list) {
565 			if (!(force || adv_instance->timeout))
566 				continue;
567 
568 			rem_inst = adv_instance->instance;
569 			err = hci_remove_adv_instance(hdev, rem_inst);
570 			if (!err)
571 				mgmt_advertising_removed(sk, hdev, rem_inst);
572 		}
573 	} else {
574 		adv_instance = hci_find_adv_instance(hdev, instance);
575 
576 		if (force || (adv_instance && adv_instance->timeout &&
577 			      !adv_instance->remaining_time)) {
578 			/* Don't advertise a removed instance. */
579 			if (next_instance &&
580 			    next_instance->instance == instance)
581 				next_instance = NULL;
582 
583 			err = hci_remove_adv_instance(hdev, instance);
584 			if (!err)
585 				mgmt_advertising_removed(sk, hdev, instance);
586 		}
587 	}
588 
589 	if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING))
590 		return 0;
591 
592 	if (next_instance && !ext_adv_capable(hdev))
593 		return hci_schedule_adv_instance_sync(hdev,
594 						      next_instance->instance,
595 						      false);
596 
597 	return 0;
598 }
599 
600 static int adv_timeout_expire_sync(struct hci_dev *hdev, void *data)
601 {
602 	u8 instance = *(u8 *)data;
603 
604 	kfree(data);
605 
606 	hci_clear_adv_instance_sync(hdev, NULL, instance, false);
607 
608 	if (list_empty(&hdev->adv_instances))
609 		return hci_disable_advertising_sync(hdev);
610 
611 	return 0;
612 }
613 
614 static void adv_timeout_expire(struct work_struct *work)
615 {
616 	u8 *inst_ptr;
617 	struct hci_dev *hdev = container_of(work, struct hci_dev,
618 					    adv_instance_expire.work);
619 
620 	bt_dev_dbg(hdev, "");
621 
622 	hci_dev_lock(hdev);
623 
624 	hdev->adv_instance_timeout = 0;
625 
626 	if (hdev->cur_adv_instance == 0x00)
627 		goto unlock;
628 
629 	inst_ptr = kmalloc(1, GFP_KERNEL);
630 	if (!inst_ptr)
631 		goto unlock;
632 
633 	*inst_ptr = hdev->cur_adv_instance;
634 	hci_cmd_sync_queue(hdev, adv_timeout_expire_sync, inst_ptr, NULL);
635 
636 unlock:
637 	hci_dev_unlock(hdev);
638 }
639 
640 void hci_cmd_sync_init(struct hci_dev *hdev)
641 {
642 	INIT_WORK(&hdev->cmd_sync_work, hci_cmd_sync_work);
643 	INIT_LIST_HEAD(&hdev->cmd_sync_work_list);
644 	mutex_init(&hdev->cmd_sync_work_lock);
645 	mutex_init(&hdev->unregister_lock);
646 
647 	INIT_WORK(&hdev->cmd_sync_cancel_work, hci_cmd_sync_cancel_work);
648 	INIT_WORK(&hdev->reenable_adv_work, reenable_adv);
649 	INIT_DELAYED_WORK(&hdev->le_scan_disable, le_scan_disable);
650 	INIT_DELAYED_WORK(&hdev->le_scan_restart, le_scan_restart);
651 	INIT_DELAYED_WORK(&hdev->adv_instance_expire, adv_timeout_expire);
652 }
653 
654 void hci_cmd_sync_clear(struct hci_dev *hdev)
655 {
656 	struct hci_cmd_sync_work_entry *entry, *tmp;
657 
658 	cancel_work_sync(&hdev->cmd_sync_work);
659 	cancel_work_sync(&hdev->reenable_adv_work);
660 
661 	mutex_lock(&hdev->cmd_sync_work_lock);
662 	list_for_each_entry_safe(entry, tmp, &hdev->cmd_sync_work_list, list) {
663 		if (entry->destroy)
664 			entry->destroy(hdev, entry->data, -ECANCELED);
665 
666 		list_del(&entry->list);
667 		kfree(entry);
668 	}
669 	mutex_unlock(&hdev->cmd_sync_work_lock);
670 }
671 
672 void hci_cmd_sync_cancel(struct hci_dev *hdev, int err)
673 {
674 	bt_dev_dbg(hdev, "err 0x%2.2x", err);
675 
676 	if (hdev->req_status == HCI_REQ_PEND) {
677 		hdev->req_result = err;
678 		hdev->req_status = HCI_REQ_CANCELED;
679 
680 		queue_work(hdev->workqueue, &hdev->cmd_sync_cancel_work);
681 	}
682 }
683 EXPORT_SYMBOL(hci_cmd_sync_cancel);
684 
685 /* Cancel ongoing command request synchronously:
686  *
687  * - Set result and mark status to HCI_REQ_CANCELED
688  * - Wakeup command sync thread
689  */
690 void hci_cmd_sync_cancel_sync(struct hci_dev *hdev, int err)
691 {
692 	bt_dev_dbg(hdev, "err 0x%2.2x", err);
693 
694 	if (hdev->req_status == HCI_REQ_PEND) {
695 		/* req_result is __u32 so error must be positive to be properly
696 		 * propagated.
697 		 */
698 		hdev->req_result = err < 0 ? -err : err;
699 		hdev->req_status = HCI_REQ_CANCELED;
700 
701 		wake_up_interruptible(&hdev->req_wait_q);
702 	}
703 }
704 EXPORT_SYMBOL(hci_cmd_sync_cancel_sync);
705 
706 /* Submit HCI command to be run in as cmd_sync_work:
707  *
708  * - hdev must _not_ be unregistered
709  */
710 int hci_cmd_sync_submit(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
711 			void *data, hci_cmd_sync_work_destroy_t destroy)
712 {
713 	struct hci_cmd_sync_work_entry *entry;
714 	int err = 0;
715 
716 	mutex_lock(&hdev->unregister_lock);
717 	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
718 		err = -ENODEV;
719 		goto unlock;
720 	}
721 
722 	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
723 	if (!entry) {
724 		err = -ENOMEM;
725 		goto unlock;
726 	}
727 	entry->func = func;
728 	entry->data = data;
729 	entry->destroy = destroy;
730 
731 	mutex_lock(&hdev->cmd_sync_work_lock);
732 	list_add_tail(&entry->list, &hdev->cmd_sync_work_list);
733 	mutex_unlock(&hdev->cmd_sync_work_lock);
734 
735 	queue_work(hdev->req_workqueue, &hdev->cmd_sync_work);
736 
737 unlock:
738 	mutex_unlock(&hdev->unregister_lock);
739 	return err;
740 }
741 EXPORT_SYMBOL(hci_cmd_sync_submit);
742 
743 /* Queue HCI command:
744  *
745  * - hdev must be running
746  */
747 int hci_cmd_sync_queue(struct hci_dev *hdev, hci_cmd_sync_work_func_t func,
748 		       void *data, hci_cmd_sync_work_destroy_t destroy)
749 {
750 	/* Only queue command if hdev is running which means it had been opened
751 	 * and is either on init phase or is already up.
752 	 */
753 	if (!test_bit(HCI_RUNNING, &hdev->flags))
754 		return -ENETDOWN;
755 
756 	return hci_cmd_sync_submit(hdev, func, data, destroy);
757 }
758 EXPORT_SYMBOL(hci_cmd_sync_queue);
759 
760 int hci_update_eir_sync(struct hci_dev *hdev)
761 {
762 	struct hci_cp_write_eir cp;
763 
764 	bt_dev_dbg(hdev, "");
765 
766 	if (!hdev_is_powered(hdev))
767 		return 0;
768 
769 	if (!lmp_ext_inq_capable(hdev))
770 		return 0;
771 
772 	if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
773 		return 0;
774 
775 	if (hci_dev_test_flag(hdev, HCI_SERVICE_CACHE))
776 		return 0;
777 
778 	memset(&cp, 0, sizeof(cp));
779 
780 	eir_create(hdev, cp.data);
781 
782 	if (memcmp(cp.data, hdev->eir, sizeof(cp.data)) == 0)
783 		return 0;
784 
785 	memcpy(hdev->eir, cp.data, sizeof(cp.data));
786 
787 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_EIR, sizeof(cp), &cp,
788 				     HCI_CMD_TIMEOUT);
789 }
790 
791 static u8 get_service_classes(struct hci_dev *hdev)
792 {
793 	struct bt_uuid *uuid;
794 	u8 val = 0;
795 
796 	list_for_each_entry(uuid, &hdev->uuids, list)
797 		val |= uuid->svc_hint;
798 
799 	return val;
800 }
801 
802 int hci_update_class_sync(struct hci_dev *hdev)
803 {
804 	u8 cod[3];
805 
806 	bt_dev_dbg(hdev, "");
807 
808 	if (!hdev_is_powered(hdev))
809 		return 0;
810 
811 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
812 		return 0;
813 
814 	if (hci_dev_test_flag(hdev, HCI_SERVICE_CACHE))
815 		return 0;
816 
817 	cod[0] = hdev->minor_class;
818 	cod[1] = hdev->major_class;
819 	cod[2] = get_service_classes(hdev);
820 
821 	if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE))
822 		cod[1] |= 0x20;
823 
824 	if (memcmp(cod, hdev->dev_class, 3) == 0)
825 		return 0;
826 
827 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_CLASS_OF_DEV,
828 				     sizeof(cod), cod, HCI_CMD_TIMEOUT);
829 }
830 
831 static bool is_advertising_allowed(struct hci_dev *hdev, bool connectable)
832 {
833 	/* If there is no connection we are OK to advertise. */
834 	if (hci_conn_num(hdev, LE_LINK) == 0)
835 		return true;
836 
837 	/* Check le_states if there is any connection in peripheral role. */
838 	if (hdev->conn_hash.le_num_peripheral > 0) {
839 		/* Peripheral connection state and non connectable mode
840 		 * bit 20.
841 		 */
842 		if (!connectable && !(hdev->le_states[2] & 0x10))
843 			return false;
844 
845 		/* Peripheral connection state and connectable mode bit 38
846 		 * and scannable bit 21.
847 		 */
848 		if (connectable && (!(hdev->le_states[4] & 0x40) ||
849 				    !(hdev->le_states[2] & 0x20)))
850 			return false;
851 	}
852 
853 	/* Check le_states if there is any connection in central role. */
854 	if (hci_conn_num(hdev, LE_LINK) != hdev->conn_hash.le_num_peripheral) {
855 		/* Central connection state and non connectable mode bit 18. */
856 		if (!connectable && !(hdev->le_states[2] & 0x02))
857 			return false;
858 
859 		/* Central connection state and connectable mode bit 35 and
860 		 * scannable 19.
861 		 */
862 		if (connectable && (!(hdev->le_states[4] & 0x08) ||
863 				    !(hdev->le_states[2] & 0x08)))
864 			return false;
865 	}
866 
867 	return true;
868 }
869 
870 static bool adv_use_rpa(struct hci_dev *hdev, uint32_t flags)
871 {
872 	/* If privacy is not enabled don't use RPA */
873 	if (!hci_dev_test_flag(hdev, HCI_PRIVACY))
874 		return false;
875 
876 	/* If basic privacy mode is enabled use RPA */
877 	if (!hci_dev_test_flag(hdev, HCI_LIMITED_PRIVACY))
878 		return true;
879 
880 	/* If limited privacy mode is enabled don't use RPA if we're
881 	 * both discoverable and bondable.
882 	 */
883 	if ((flags & MGMT_ADV_FLAG_DISCOV) &&
884 	    hci_dev_test_flag(hdev, HCI_BONDABLE))
885 		return false;
886 
887 	/* We're neither bondable nor discoverable in the limited
888 	 * privacy mode, therefore use RPA.
889 	 */
890 	return true;
891 }
892 
893 static int hci_set_random_addr_sync(struct hci_dev *hdev, bdaddr_t *rpa)
894 {
895 	/* If we're advertising or initiating an LE connection we can't
896 	 * go ahead and change the random address at this time. This is
897 	 * because the eventual initiator address used for the
898 	 * subsequently created connection will be undefined (some
899 	 * controllers use the new address and others the one we had
900 	 * when the operation started).
901 	 *
902 	 * In this kind of scenario skip the update and let the random
903 	 * address be updated at the next cycle.
904 	 */
905 	if (hci_dev_test_flag(hdev, HCI_LE_ADV) ||
906 	    hci_lookup_le_connect(hdev)) {
907 		bt_dev_dbg(hdev, "Deferring random address update");
908 		hci_dev_set_flag(hdev, HCI_RPA_EXPIRED);
909 		return 0;
910 	}
911 
912 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_RANDOM_ADDR,
913 				     6, rpa, HCI_CMD_TIMEOUT);
914 }
915 
916 int hci_update_random_address_sync(struct hci_dev *hdev, bool require_privacy,
917 				   bool rpa, u8 *own_addr_type)
918 {
919 	int err;
920 
921 	/* If privacy is enabled use a resolvable private address. If
922 	 * current RPA has expired or there is something else than
923 	 * the current RPA in use, then generate a new one.
924 	 */
925 	if (rpa) {
926 		/* If Controller supports LL Privacy use own address type is
927 		 * 0x03
928 		 */
929 		if (use_ll_privacy(hdev))
930 			*own_addr_type = ADDR_LE_DEV_RANDOM_RESOLVED;
931 		else
932 			*own_addr_type = ADDR_LE_DEV_RANDOM;
933 
934 		/* Check if RPA is valid */
935 		if (rpa_valid(hdev))
936 			return 0;
937 
938 		err = smp_generate_rpa(hdev, hdev->irk, &hdev->rpa);
939 		if (err < 0) {
940 			bt_dev_err(hdev, "failed to generate new RPA");
941 			return err;
942 		}
943 
944 		err = hci_set_random_addr_sync(hdev, &hdev->rpa);
945 		if (err)
946 			return err;
947 
948 		return 0;
949 	}
950 
951 	/* In case of required privacy without resolvable private address,
952 	 * use an non-resolvable private address. This is useful for active
953 	 * scanning and non-connectable advertising.
954 	 */
955 	if (require_privacy) {
956 		bdaddr_t nrpa;
957 
958 		while (true) {
959 			/* The non-resolvable private address is generated
960 			 * from random six bytes with the two most significant
961 			 * bits cleared.
962 			 */
963 			get_random_bytes(&nrpa, 6);
964 			nrpa.b[5] &= 0x3f;
965 
966 			/* The non-resolvable private address shall not be
967 			 * equal to the public address.
968 			 */
969 			if (bacmp(&hdev->bdaddr, &nrpa))
970 				break;
971 		}
972 
973 		*own_addr_type = ADDR_LE_DEV_RANDOM;
974 
975 		return hci_set_random_addr_sync(hdev, &nrpa);
976 	}
977 
978 	/* If forcing static address is in use or there is no public
979 	 * address use the static address as random address (but skip
980 	 * the HCI command if the current random address is already the
981 	 * static one.
982 	 *
983 	 * In case BR/EDR has been disabled on a dual-mode controller
984 	 * and a static address has been configured, then use that
985 	 * address instead of the public BR/EDR address.
986 	 */
987 	if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
988 	    !bacmp(&hdev->bdaddr, BDADDR_ANY) ||
989 	    (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) &&
990 	     bacmp(&hdev->static_addr, BDADDR_ANY))) {
991 		*own_addr_type = ADDR_LE_DEV_RANDOM;
992 		if (bacmp(&hdev->static_addr, &hdev->random_addr))
993 			return hci_set_random_addr_sync(hdev,
994 							&hdev->static_addr);
995 		return 0;
996 	}
997 
998 	/* Neither privacy nor static address is being used so use a
999 	 * public address.
1000 	 */
1001 	*own_addr_type = ADDR_LE_DEV_PUBLIC;
1002 
1003 	return 0;
1004 }
1005 
1006 static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
1007 {
1008 	struct hci_cp_le_set_ext_adv_enable *cp;
1009 	struct hci_cp_ext_adv_set *set;
1010 	u8 data[sizeof(*cp) + sizeof(*set) * 1];
1011 	u8 size;
1012 
1013 	/* If request specifies an instance that doesn't exist, fail */
1014 	if (instance > 0) {
1015 		struct adv_info *adv;
1016 
1017 		adv = hci_find_adv_instance(hdev, instance);
1018 		if (!adv)
1019 			return -EINVAL;
1020 
1021 		/* If not enabled there is nothing to do */
1022 		if (!adv->enabled)
1023 			return 0;
1024 	}
1025 
1026 	memset(data, 0, sizeof(data));
1027 
1028 	cp = (void *)data;
1029 	set = (void *)cp->data;
1030 
1031 	/* Instance 0x00 indicates all advertising instances will be disabled */
1032 	cp->num_of_sets = !!instance;
1033 	cp->enable = 0x00;
1034 
1035 	set->handle = instance;
1036 
1037 	size = sizeof(*cp) + sizeof(*set) * cp->num_of_sets;
1038 
1039 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
1040 				     size, data, HCI_CMD_TIMEOUT);
1041 }
1042 
1043 static int hci_set_adv_set_random_addr_sync(struct hci_dev *hdev, u8 instance,
1044 					    bdaddr_t *random_addr)
1045 {
1046 	struct hci_cp_le_set_adv_set_rand_addr cp;
1047 	int err;
1048 
1049 	if (!instance) {
1050 		/* Instance 0x00 doesn't have an adv_info, instead it uses
1051 		 * hdev->random_addr to track its address so whenever it needs
1052 		 * to be updated this also set the random address since
1053 		 * hdev->random_addr is shared with scan state machine.
1054 		 */
1055 		err = hci_set_random_addr_sync(hdev, random_addr);
1056 		if (err)
1057 			return err;
1058 	}
1059 
1060 	memset(&cp, 0, sizeof(cp));
1061 
1062 	cp.handle = instance;
1063 	bacpy(&cp.bdaddr, random_addr);
1064 
1065 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_SET_RAND_ADDR,
1066 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1067 }
1068 
1069 int hci_setup_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
1070 {
1071 	struct hci_cp_le_set_ext_adv_params cp;
1072 	bool connectable;
1073 	u32 flags;
1074 	bdaddr_t random_addr;
1075 	u8 own_addr_type;
1076 	int err;
1077 	struct adv_info *adv;
1078 	bool secondary_adv;
1079 
1080 	if (instance > 0) {
1081 		adv = hci_find_adv_instance(hdev, instance);
1082 		if (!adv)
1083 			return -EINVAL;
1084 	} else {
1085 		adv = NULL;
1086 	}
1087 
1088 	/* Updating parameters of an active instance will return a
1089 	 * Command Disallowed error, so we must first disable the
1090 	 * instance if it is active.
1091 	 */
1092 	if (adv && !adv->pending) {
1093 		err = hci_disable_ext_adv_instance_sync(hdev, instance);
1094 		if (err)
1095 			return err;
1096 	}
1097 
1098 	flags = hci_adv_instance_flags(hdev, instance);
1099 
1100 	/* If the "connectable" instance flag was not set, then choose between
1101 	 * ADV_IND and ADV_NONCONN_IND based on the global connectable setting.
1102 	 */
1103 	connectable = (flags & MGMT_ADV_FLAG_CONNECTABLE) ||
1104 		      mgmt_get_connectable(hdev);
1105 
1106 	if (!is_advertising_allowed(hdev, connectable))
1107 		return -EPERM;
1108 
1109 	/* Set require_privacy to true only when non-connectable
1110 	 * advertising is used. In that case it is fine to use a
1111 	 * non-resolvable private address.
1112 	 */
1113 	err = hci_get_random_address(hdev, !connectable,
1114 				     adv_use_rpa(hdev, flags), adv,
1115 				     &own_addr_type, &random_addr);
1116 	if (err < 0)
1117 		return err;
1118 
1119 	memset(&cp, 0, sizeof(cp));
1120 
1121 	if (adv) {
1122 		hci_cpu_to_le24(adv->min_interval, cp.min_interval);
1123 		hci_cpu_to_le24(adv->max_interval, cp.max_interval);
1124 		cp.tx_power = adv->tx_power;
1125 	} else {
1126 		hci_cpu_to_le24(hdev->le_adv_min_interval, cp.min_interval);
1127 		hci_cpu_to_le24(hdev->le_adv_max_interval, cp.max_interval);
1128 		cp.tx_power = HCI_ADV_TX_POWER_NO_PREFERENCE;
1129 	}
1130 
1131 	secondary_adv = (flags & MGMT_ADV_FLAG_SEC_MASK);
1132 
1133 	if (connectable) {
1134 		if (secondary_adv)
1135 			cp.evt_properties = cpu_to_le16(LE_EXT_ADV_CONN_IND);
1136 		else
1137 			cp.evt_properties = cpu_to_le16(LE_LEGACY_ADV_IND);
1138 	} else if (hci_adv_instance_is_scannable(hdev, instance) ||
1139 		   (flags & MGMT_ADV_PARAM_SCAN_RSP)) {
1140 		if (secondary_adv)
1141 			cp.evt_properties = cpu_to_le16(LE_EXT_ADV_SCAN_IND);
1142 		else
1143 			cp.evt_properties = cpu_to_le16(LE_LEGACY_ADV_SCAN_IND);
1144 	} else {
1145 		if (secondary_adv)
1146 			cp.evt_properties = cpu_to_le16(LE_EXT_ADV_NON_CONN_IND);
1147 		else
1148 			cp.evt_properties = cpu_to_le16(LE_LEGACY_NONCONN_IND);
1149 	}
1150 
1151 	/* If Own_Address_Type equals 0x02 or 0x03, the Peer_Address parameter
1152 	 * contains the peer’s Identity Address and the Peer_Address_Type
1153 	 * parameter contains the peer’s Identity Type (i.e., 0x00 or 0x01).
1154 	 * These parameters are used to locate the corresponding local IRK in
1155 	 * the resolving list; this IRK is used to generate their own address
1156 	 * used in the advertisement.
1157 	 */
1158 	if (own_addr_type == ADDR_LE_DEV_RANDOM_RESOLVED)
1159 		hci_copy_identity_address(hdev, &cp.peer_addr,
1160 					  &cp.peer_addr_type);
1161 
1162 	cp.own_addr_type = own_addr_type;
1163 	cp.channel_map = hdev->le_adv_channel_map;
1164 	cp.handle = instance;
1165 
1166 	if (flags & MGMT_ADV_FLAG_SEC_2M) {
1167 		cp.primary_phy = HCI_ADV_PHY_1M;
1168 		cp.secondary_phy = HCI_ADV_PHY_2M;
1169 	} else if (flags & MGMT_ADV_FLAG_SEC_CODED) {
1170 		cp.primary_phy = HCI_ADV_PHY_CODED;
1171 		cp.secondary_phy = HCI_ADV_PHY_CODED;
1172 	} else {
1173 		/* In all other cases use 1M */
1174 		cp.primary_phy = HCI_ADV_PHY_1M;
1175 		cp.secondary_phy = HCI_ADV_PHY_1M;
1176 	}
1177 
1178 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_PARAMS,
1179 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1180 	if (err)
1181 		return err;
1182 
1183 	if ((own_addr_type == ADDR_LE_DEV_RANDOM ||
1184 	     own_addr_type == ADDR_LE_DEV_RANDOM_RESOLVED) &&
1185 	    bacmp(&random_addr, BDADDR_ANY)) {
1186 		/* Check if random address need to be updated */
1187 		if (adv) {
1188 			if (!bacmp(&random_addr, &adv->random_addr))
1189 				return 0;
1190 		} else {
1191 			if (!bacmp(&random_addr, &hdev->random_addr))
1192 				return 0;
1193 		}
1194 
1195 		return hci_set_adv_set_random_addr_sync(hdev, instance,
1196 							&random_addr);
1197 	}
1198 
1199 	return 0;
1200 }
1201 
1202 static int hci_set_ext_scan_rsp_data_sync(struct hci_dev *hdev, u8 instance)
1203 {
1204 	struct {
1205 		struct hci_cp_le_set_ext_scan_rsp_data cp;
1206 		u8 data[HCI_MAX_EXT_AD_LENGTH];
1207 	} pdu;
1208 	u8 len;
1209 	struct adv_info *adv = NULL;
1210 	int err;
1211 
1212 	memset(&pdu, 0, sizeof(pdu));
1213 
1214 	if (instance) {
1215 		adv = hci_find_adv_instance(hdev, instance);
1216 		if (!adv || !adv->scan_rsp_changed)
1217 			return 0;
1218 	}
1219 
1220 	len = eir_create_scan_rsp(hdev, instance, pdu.data);
1221 
1222 	pdu.cp.handle = instance;
1223 	pdu.cp.length = len;
1224 	pdu.cp.operation = LE_SET_ADV_DATA_OP_COMPLETE;
1225 	pdu.cp.frag_pref = LE_SET_ADV_DATA_NO_FRAG;
1226 
1227 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_SCAN_RSP_DATA,
1228 				    sizeof(pdu.cp) + len, &pdu.cp,
1229 				    HCI_CMD_TIMEOUT);
1230 	if (err)
1231 		return err;
1232 
1233 	if (adv) {
1234 		adv->scan_rsp_changed = false;
1235 	} else {
1236 		memcpy(hdev->scan_rsp_data, pdu.data, len);
1237 		hdev->scan_rsp_data_len = len;
1238 	}
1239 
1240 	return 0;
1241 }
1242 
1243 static int __hci_set_scan_rsp_data_sync(struct hci_dev *hdev, u8 instance)
1244 {
1245 	struct hci_cp_le_set_scan_rsp_data cp;
1246 	u8 len;
1247 
1248 	memset(&cp, 0, sizeof(cp));
1249 
1250 	len = eir_create_scan_rsp(hdev, instance, cp.data);
1251 
1252 	if (hdev->scan_rsp_data_len == len &&
1253 	    !memcmp(cp.data, hdev->scan_rsp_data, len))
1254 		return 0;
1255 
1256 	memcpy(hdev->scan_rsp_data, cp.data, sizeof(cp.data));
1257 	hdev->scan_rsp_data_len = len;
1258 
1259 	cp.length = len;
1260 
1261 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_SCAN_RSP_DATA,
1262 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1263 }
1264 
1265 int hci_update_scan_rsp_data_sync(struct hci_dev *hdev, u8 instance)
1266 {
1267 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
1268 		return 0;
1269 
1270 	if (ext_adv_capable(hdev))
1271 		return hci_set_ext_scan_rsp_data_sync(hdev, instance);
1272 
1273 	return __hci_set_scan_rsp_data_sync(hdev, instance);
1274 }
1275 
1276 int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance)
1277 {
1278 	struct hci_cp_le_set_ext_adv_enable *cp;
1279 	struct hci_cp_ext_adv_set *set;
1280 	u8 data[sizeof(*cp) + sizeof(*set) * 1];
1281 	struct adv_info *adv;
1282 
1283 	if (instance > 0) {
1284 		adv = hci_find_adv_instance(hdev, instance);
1285 		if (!adv)
1286 			return -EINVAL;
1287 		/* If already enabled there is nothing to do */
1288 		if (adv->enabled)
1289 			return 0;
1290 	} else {
1291 		adv = NULL;
1292 	}
1293 
1294 	cp = (void *)data;
1295 	set = (void *)cp->data;
1296 
1297 	memset(cp, 0, sizeof(*cp));
1298 
1299 	cp->enable = 0x01;
1300 	cp->num_of_sets = 0x01;
1301 
1302 	memset(set, 0, sizeof(*set));
1303 
1304 	set->handle = instance;
1305 
1306 	/* Set duration per instance since controller is responsible for
1307 	 * scheduling it.
1308 	 */
1309 	if (adv && adv->timeout) {
1310 		u16 duration = adv->timeout * MSEC_PER_SEC;
1311 
1312 		/* Time = N * 10 ms */
1313 		set->duration = cpu_to_le16(duration / 10);
1314 	}
1315 
1316 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
1317 				     sizeof(*cp) +
1318 				     sizeof(*set) * cp->num_of_sets,
1319 				     data, HCI_CMD_TIMEOUT);
1320 }
1321 
1322 int hci_start_ext_adv_sync(struct hci_dev *hdev, u8 instance)
1323 {
1324 	int err;
1325 
1326 	err = hci_setup_ext_adv_instance_sync(hdev, instance);
1327 	if (err)
1328 		return err;
1329 
1330 	err = hci_set_ext_scan_rsp_data_sync(hdev, instance);
1331 	if (err)
1332 		return err;
1333 
1334 	return hci_enable_ext_advertising_sync(hdev, instance);
1335 }
1336 
1337 int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance)
1338 {
1339 	struct hci_cp_le_set_per_adv_enable cp;
1340 	struct adv_info *adv = NULL;
1341 
1342 	/* If periodic advertising already disabled there is nothing to do. */
1343 	adv = hci_find_adv_instance(hdev, instance);
1344 	if (!adv || !adv->periodic || !adv->enabled)
1345 		return 0;
1346 
1347 	memset(&cp, 0, sizeof(cp));
1348 
1349 	cp.enable = 0x00;
1350 	cp.handle = instance;
1351 
1352 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE,
1353 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1354 }
1355 
1356 static int hci_set_per_adv_params_sync(struct hci_dev *hdev, u8 instance,
1357 				       u16 min_interval, u16 max_interval)
1358 {
1359 	struct hci_cp_le_set_per_adv_params cp;
1360 
1361 	memset(&cp, 0, sizeof(cp));
1362 
1363 	if (!min_interval)
1364 		min_interval = DISCOV_LE_PER_ADV_INT_MIN;
1365 
1366 	if (!max_interval)
1367 		max_interval = DISCOV_LE_PER_ADV_INT_MAX;
1368 
1369 	cp.handle = instance;
1370 	cp.min_interval = cpu_to_le16(min_interval);
1371 	cp.max_interval = cpu_to_le16(max_interval);
1372 	cp.periodic_properties = 0x0000;
1373 
1374 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_PARAMS,
1375 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1376 }
1377 
1378 static int hci_set_per_adv_data_sync(struct hci_dev *hdev, u8 instance)
1379 {
1380 	struct {
1381 		struct hci_cp_le_set_per_adv_data cp;
1382 		u8 data[HCI_MAX_PER_AD_LENGTH];
1383 	} pdu;
1384 	u8 len;
1385 
1386 	memset(&pdu, 0, sizeof(pdu));
1387 
1388 	if (instance) {
1389 		struct adv_info *adv = hci_find_adv_instance(hdev, instance);
1390 
1391 		if (!adv || !adv->periodic)
1392 			return 0;
1393 	}
1394 
1395 	len = eir_create_per_adv_data(hdev, instance, pdu.data);
1396 
1397 	pdu.cp.length = len;
1398 	pdu.cp.handle = instance;
1399 	pdu.cp.operation = LE_SET_ADV_DATA_OP_COMPLETE;
1400 
1401 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_DATA,
1402 				     sizeof(pdu.cp) + len, &pdu,
1403 				     HCI_CMD_TIMEOUT);
1404 }
1405 
1406 static int hci_enable_per_advertising_sync(struct hci_dev *hdev, u8 instance)
1407 {
1408 	struct hci_cp_le_set_per_adv_enable cp;
1409 	struct adv_info *adv = NULL;
1410 
1411 	/* If periodic advertising already enabled there is nothing to do. */
1412 	adv = hci_find_adv_instance(hdev, instance);
1413 	if (adv && adv->periodic && adv->enabled)
1414 		return 0;
1415 
1416 	memset(&cp, 0, sizeof(cp));
1417 
1418 	cp.enable = 0x01;
1419 	cp.handle = instance;
1420 
1421 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PER_ADV_ENABLE,
1422 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1423 }
1424 
1425 /* Checks if periodic advertising data contains a Basic Announcement and if it
1426  * does generates a Broadcast ID and add Broadcast Announcement.
1427  */
1428 static int hci_adv_bcast_annoucement(struct hci_dev *hdev, struct adv_info *adv)
1429 {
1430 	u8 bid[3];
1431 	u8 ad[4 + 3];
1432 
1433 	/* Skip if NULL adv as instance 0x00 is used for general purpose
1434 	 * advertising so it cannot used for the likes of Broadcast Announcement
1435 	 * as it can be overwritten at any point.
1436 	 */
1437 	if (!adv)
1438 		return 0;
1439 
1440 	/* Check if PA data doesn't contains a Basic Audio Announcement then
1441 	 * there is nothing to do.
1442 	 */
1443 	if (!eir_get_service_data(adv->per_adv_data, adv->per_adv_data_len,
1444 				  0x1851, NULL))
1445 		return 0;
1446 
1447 	/* Check if advertising data already has a Broadcast Announcement since
1448 	 * the process may want to control the Broadcast ID directly and in that
1449 	 * case the kernel shall no interfere.
1450 	 */
1451 	if (eir_get_service_data(adv->adv_data, adv->adv_data_len, 0x1852,
1452 				 NULL))
1453 		return 0;
1454 
1455 	/* Generate Broadcast ID */
1456 	get_random_bytes(bid, sizeof(bid));
1457 	eir_append_service_data(ad, 0, 0x1852, bid, sizeof(bid));
1458 	hci_set_adv_instance_data(hdev, adv->instance, sizeof(ad), ad, 0, NULL);
1459 
1460 	return hci_update_adv_data_sync(hdev, adv->instance);
1461 }
1462 
1463 int hci_start_per_adv_sync(struct hci_dev *hdev, u8 instance, u8 data_len,
1464 			   u8 *data, u32 flags, u16 min_interval,
1465 			   u16 max_interval, u16 sync_interval)
1466 {
1467 	struct adv_info *adv = NULL;
1468 	int err;
1469 	bool added = false;
1470 
1471 	hci_disable_per_advertising_sync(hdev, instance);
1472 
1473 	if (instance) {
1474 		adv = hci_find_adv_instance(hdev, instance);
1475 		/* Create an instance if that could not be found */
1476 		if (!adv) {
1477 			adv = hci_add_per_instance(hdev, instance, flags,
1478 						   data_len, data,
1479 						   sync_interval,
1480 						   sync_interval);
1481 			if (IS_ERR(adv))
1482 				return PTR_ERR(adv);
1483 			adv->pending = false;
1484 			added = true;
1485 		}
1486 	}
1487 
1488 	/* Start advertising */
1489 	err = hci_start_ext_adv_sync(hdev, instance);
1490 	if (err < 0)
1491 		goto fail;
1492 
1493 	err = hci_adv_bcast_annoucement(hdev, adv);
1494 	if (err < 0)
1495 		goto fail;
1496 
1497 	err = hci_set_per_adv_params_sync(hdev, instance, min_interval,
1498 					  max_interval);
1499 	if (err < 0)
1500 		goto fail;
1501 
1502 	err = hci_set_per_adv_data_sync(hdev, instance);
1503 	if (err < 0)
1504 		goto fail;
1505 
1506 	err = hci_enable_per_advertising_sync(hdev, instance);
1507 	if (err < 0)
1508 		goto fail;
1509 
1510 	return 0;
1511 
1512 fail:
1513 	if (added)
1514 		hci_remove_adv_instance(hdev, instance);
1515 
1516 	return err;
1517 }
1518 
1519 static int hci_start_adv_sync(struct hci_dev *hdev, u8 instance)
1520 {
1521 	int err;
1522 
1523 	if (ext_adv_capable(hdev))
1524 		return hci_start_ext_adv_sync(hdev, instance);
1525 
1526 	err = hci_update_adv_data_sync(hdev, instance);
1527 	if (err)
1528 		return err;
1529 
1530 	err = hci_update_scan_rsp_data_sync(hdev, instance);
1531 	if (err)
1532 		return err;
1533 
1534 	return hci_enable_advertising_sync(hdev);
1535 }
1536 
1537 int hci_enable_advertising_sync(struct hci_dev *hdev)
1538 {
1539 	struct adv_info *adv_instance;
1540 	struct hci_cp_le_set_adv_param cp;
1541 	u8 own_addr_type, enable = 0x01;
1542 	bool connectable;
1543 	u16 adv_min_interval, adv_max_interval;
1544 	u32 flags;
1545 	u8 status;
1546 
1547 	if (ext_adv_capable(hdev))
1548 		return hci_enable_ext_advertising_sync(hdev,
1549 						       hdev->cur_adv_instance);
1550 
1551 	flags = hci_adv_instance_flags(hdev, hdev->cur_adv_instance);
1552 	adv_instance = hci_find_adv_instance(hdev, hdev->cur_adv_instance);
1553 
1554 	/* If the "connectable" instance flag was not set, then choose between
1555 	 * ADV_IND and ADV_NONCONN_IND based on the global connectable setting.
1556 	 */
1557 	connectable = (flags & MGMT_ADV_FLAG_CONNECTABLE) ||
1558 		      mgmt_get_connectable(hdev);
1559 
1560 	if (!is_advertising_allowed(hdev, connectable))
1561 		return -EINVAL;
1562 
1563 	status = hci_disable_advertising_sync(hdev);
1564 	if (status)
1565 		return status;
1566 
1567 	/* Clear the HCI_LE_ADV bit temporarily so that the
1568 	 * hci_update_random_address knows that it's safe to go ahead
1569 	 * and write a new random address. The flag will be set back on
1570 	 * as soon as the SET_ADV_ENABLE HCI command completes.
1571 	 */
1572 	hci_dev_clear_flag(hdev, HCI_LE_ADV);
1573 
1574 	/* Set require_privacy to true only when non-connectable
1575 	 * advertising is used. In that case it is fine to use a
1576 	 * non-resolvable private address.
1577 	 */
1578 	status = hci_update_random_address_sync(hdev, !connectable,
1579 						adv_use_rpa(hdev, flags),
1580 						&own_addr_type);
1581 	if (status)
1582 		return status;
1583 
1584 	memset(&cp, 0, sizeof(cp));
1585 
1586 	if (adv_instance) {
1587 		adv_min_interval = adv_instance->min_interval;
1588 		adv_max_interval = adv_instance->max_interval;
1589 	} else {
1590 		adv_min_interval = hdev->le_adv_min_interval;
1591 		adv_max_interval = hdev->le_adv_max_interval;
1592 	}
1593 
1594 	if (connectable) {
1595 		cp.type = LE_ADV_IND;
1596 	} else {
1597 		if (hci_adv_instance_is_scannable(hdev, hdev->cur_adv_instance))
1598 			cp.type = LE_ADV_SCAN_IND;
1599 		else
1600 			cp.type = LE_ADV_NONCONN_IND;
1601 
1602 		if (!hci_dev_test_flag(hdev, HCI_DISCOVERABLE) ||
1603 		    hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE)) {
1604 			adv_min_interval = DISCOV_LE_FAST_ADV_INT_MIN;
1605 			adv_max_interval = DISCOV_LE_FAST_ADV_INT_MAX;
1606 		}
1607 	}
1608 
1609 	cp.min_interval = cpu_to_le16(adv_min_interval);
1610 	cp.max_interval = cpu_to_le16(adv_max_interval);
1611 	cp.own_address_type = own_addr_type;
1612 	cp.channel_map = hdev->le_adv_channel_map;
1613 
1614 	status = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_PARAM,
1615 				       sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1616 	if (status)
1617 		return status;
1618 
1619 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_ENABLE,
1620 				     sizeof(enable), &enable, HCI_CMD_TIMEOUT);
1621 }
1622 
1623 static int enable_advertising_sync(struct hci_dev *hdev, void *data)
1624 {
1625 	return hci_enable_advertising_sync(hdev);
1626 }
1627 
1628 int hci_enable_advertising(struct hci_dev *hdev)
1629 {
1630 	if (!hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
1631 	    list_empty(&hdev->adv_instances))
1632 		return 0;
1633 
1634 	return hci_cmd_sync_queue(hdev, enable_advertising_sync, NULL, NULL);
1635 }
1636 
1637 int hci_remove_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance,
1638 				     struct sock *sk)
1639 {
1640 	int err;
1641 
1642 	if (!ext_adv_capable(hdev))
1643 		return 0;
1644 
1645 	err = hci_disable_ext_adv_instance_sync(hdev, instance);
1646 	if (err)
1647 		return err;
1648 
1649 	/* If request specifies an instance that doesn't exist, fail */
1650 	if (instance > 0 && !hci_find_adv_instance(hdev, instance))
1651 		return -EINVAL;
1652 
1653 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_REMOVE_ADV_SET,
1654 					sizeof(instance), &instance, 0,
1655 					HCI_CMD_TIMEOUT, sk);
1656 }
1657 
1658 static int remove_ext_adv_sync(struct hci_dev *hdev, void *data)
1659 {
1660 	struct adv_info *adv = data;
1661 	u8 instance = 0;
1662 
1663 	if (adv)
1664 		instance = adv->instance;
1665 
1666 	return hci_remove_ext_adv_instance_sync(hdev, instance, NULL);
1667 }
1668 
1669 int hci_remove_ext_adv_instance(struct hci_dev *hdev, u8 instance)
1670 {
1671 	struct adv_info *adv = NULL;
1672 
1673 	if (instance) {
1674 		adv = hci_find_adv_instance(hdev, instance);
1675 		if (!adv)
1676 			return -EINVAL;
1677 	}
1678 
1679 	return hci_cmd_sync_queue(hdev, remove_ext_adv_sync, adv, NULL);
1680 }
1681 
1682 int hci_le_terminate_big_sync(struct hci_dev *hdev, u8 handle, u8 reason)
1683 {
1684 	struct hci_cp_le_term_big cp;
1685 
1686 	memset(&cp, 0, sizeof(cp));
1687 	cp.handle = handle;
1688 	cp.reason = reason;
1689 
1690 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_TERM_BIG,
1691 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1692 }
1693 
1694 static int hci_set_ext_adv_data_sync(struct hci_dev *hdev, u8 instance)
1695 {
1696 	struct {
1697 		struct hci_cp_le_set_ext_adv_data cp;
1698 		u8 data[HCI_MAX_EXT_AD_LENGTH];
1699 	} pdu;
1700 	u8 len;
1701 	struct adv_info *adv = NULL;
1702 	int err;
1703 
1704 	memset(&pdu, 0, sizeof(pdu));
1705 
1706 	if (instance) {
1707 		adv = hci_find_adv_instance(hdev, instance);
1708 		if (!adv || !adv->adv_data_changed)
1709 			return 0;
1710 	}
1711 
1712 	len = eir_create_adv_data(hdev, instance, pdu.data);
1713 
1714 	pdu.cp.length = len;
1715 	pdu.cp.handle = instance;
1716 	pdu.cp.operation = LE_SET_ADV_DATA_OP_COMPLETE;
1717 	pdu.cp.frag_pref = LE_SET_ADV_DATA_NO_FRAG;
1718 
1719 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_DATA,
1720 				    sizeof(pdu.cp) + len, &pdu.cp,
1721 				    HCI_CMD_TIMEOUT);
1722 	if (err)
1723 		return err;
1724 
1725 	/* Update data if the command succeed */
1726 	if (adv) {
1727 		adv->adv_data_changed = false;
1728 	} else {
1729 		memcpy(hdev->adv_data, pdu.data, len);
1730 		hdev->adv_data_len = len;
1731 	}
1732 
1733 	return 0;
1734 }
1735 
1736 static int hci_set_adv_data_sync(struct hci_dev *hdev, u8 instance)
1737 {
1738 	struct hci_cp_le_set_adv_data cp;
1739 	u8 len;
1740 
1741 	memset(&cp, 0, sizeof(cp));
1742 
1743 	len = eir_create_adv_data(hdev, instance, cp.data);
1744 
1745 	/* There's nothing to do if the data hasn't changed */
1746 	if (hdev->adv_data_len == len &&
1747 	    memcmp(cp.data, hdev->adv_data, len) == 0)
1748 		return 0;
1749 
1750 	memcpy(hdev->adv_data, cp.data, sizeof(cp.data));
1751 	hdev->adv_data_len = len;
1752 
1753 	cp.length = len;
1754 
1755 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_DATA,
1756 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1757 }
1758 
1759 int hci_update_adv_data_sync(struct hci_dev *hdev, u8 instance)
1760 {
1761 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
1762 		return 0;
1763 
1764 	if (ext_adv_capable(hdev))
1765 		return hci_set_ext_adv_data_sync(hdev, instance);
1766 
1767 	return hci_set_adv_data_sync(hdev, instance);
1768 }
1769 
1770 int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance,
1771 				   bool force)
1772 {
1773 	struct adv_info *adv = NULL;
1774 	u16 timeout;
1775 
1776 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING) && !ext_adv_capable(hdev))
1777 		return -EPERM;
1778 
1779 	if (hdev->adv_instance_timeout)
1780 		return -EBUSY;
1781 
1782 	adv = hci_find_adv_instance(hdev, instance);
1783 	if (!adv)
1784 		return -ENOENT;
1785 
1786 	/* A zero timeout means unlimited advertising. As long as there is
1787 	 * only one instance, duration should be ignored. We still set a timeout
1788 	 * in case further instances are being added later on.
1789 	 *
1790 	 * If the remaining lifetime of the instance is more than the duration
1791 	 * then the timeout corresponds to the duration, otherwise it will be
1792 	 * reduced to the remaining instance lifetime.
1793 	 */
1794 	if (adv->timeout == 0 || adv->duration <= adv->remaining_time)
1795 		timeout = adv->duration;
1796 	else
1797 		timeout = adv->remaining_time;
1798 
1799 	/* The remaining time is being reduced unless the instance is being
1800 	 * advertised without time limit.
1801 	 */
1802 	if (adv->timeout)
1803 		adv->remaining_time = adv->remaining_time - timeout;
1804 
1805 	/* Only use work for scheduling instances with legacy advertising */
1806 	if (!ext_adv_capable(hdev)) {
1807 		hdev->adv_instance_timeout = timeout;
1808 		queue_delayed_work(hdev->req_workqueue,
1809 				   &hdev->adv_instance_expire,
1810 				   msecs_to_jiffies(timeout * 1000));
1811 	}
1812 
1813 	/* If we're just re-scheduling the same instance again then do not
1814 	 * execute any HCI commands. This happens when a single instance is
1815 	 * being advertised.
1816 	 */
1817 	if (!force && hdev->cur_adv_instance == instance &&
1818 	    hci_dev_test_flag(hdev, HCI_LE_ADV))
1819 		return 0;
1820 
1821 	hdev->cur_adv_instance = instance;
1822 
1823 	return hci_start_adv_sync(hdev, instance);
1824 }
1825 
1826 static int hci_clear_adv_sets_sync(struct hci_dev *hdev, struct sock *sk)
1827 {
1828 	int err;
1829 
1830 	if (!ext_adv_capable(hdev))
1831 		return 0;
1832 
1833 	/* Disable instance 0x00 to disable all instances */
1834 	err = hci_disable_ext_adv_instance_sync(hdev, 0x00);
1835 	if (err)
1836 		return err;
1837 
1838 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_CLEAR_ADV_SETS,
1839 					0, NULL, 0, HCI_CMD_TIMEOUT, sk);
1840 }
1841 
1842 static int hci_clear_adv_sync(struct hci_dev *hdev, struct sock *sk, bool force)
1843 {
1844 	struct adv_info *adv, *n;
1845 	int err = 0;
1846 
1847 	if (ext_adv_capable(hdev))
1848 		/* Remove all existing sets */
1849 		err = hci_clear_adv_sets_sync(hdev, sk);
1850 	if (ext_adv_capable(hdev))
1851 		return err;
1852 
1853 	/* This is safe as long as there is no command send while the lock is
1854 	 * held.
1855 	 */
1856 	hci_dev_lock(hdev);
1857 
1858 	/* Cleanup non-ext instances */
1859 	list_for_each_entry_safe(adv, n, &hdev->adv_instances, list) {
1860 		u8 instance = adv->instance;
1861 		int err;
1862 
1863 		if (!(force || adv->timeout))
1864 			continue;
1865 
1866 		err = hci_remove_adv_instance(hdev, instance);
1867 		if (!err)
1868 			mgmt_advertising_removed(sk, hdev, instance);
1869 	}
1870 
1871 	hci_dev_unlock(hdev);
1872 
1873 	return 0;
1874 }
1875 
1876 static int hci_remove_adv_sync(struct hci_dev *hdev, u8 instance,
1877 			       struct sock *sk)
1878 {
1879 	int err = 0;
1880 
1881 	/* If we use extended advertising, instance has to be removed first. */
1882 	if (ext_adv_capable(hdev))
1883 		err = hci_remove_ext_adv_instance_sync(hdev, instance, sk);
1884 	if (ext_adv_capable(hdev))
1885 		return err;
1886 
1887 	/* This is safe as long as there is no command send while the lock is
1888 	 * held.
1889 	 */
1890 	hci_dev_lock(hdev);
1891 
1892 	err = hci_remove_adv_instance(hdev, instance);
1893 	if (!err)
1894 		mgmt_advertising_removed(sk, hdev, instance);
1895 
1896 	hci_dev_unlock(hdev);
1897 
1898 	return err;
1899 }
1900 
1901 /* For a single instance:
1902  * - force == true: The instance will be removed even when its remaining
1903  *   lifetime is not zero.
1904  * - force == false: the instance will be deactivated but kept stored unless
1905  *   the remaining lifetime is zero.
1906  *
1907  * For instance == 0x00:
1908  * - force == true: All instances will be removed regardless of their timeout
1909  *   setting.
1910  * - force == false: Only instances that have a timeout will be removed.
1911  */
1912 int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk,
1913 				u8 instance, bool force)
1914 {
1915 	struct adv_info *next = NULL;
1916 	int err;
1917 
1918 	/* Cancel any timeout concerning the removed instance(s). */
1919 	if (!instance || hdev->cur_adv_instance == instance)
1920 		cancel_adv_timeout(hdev);
1921 
1922 	/* Get the next instance to advertise BEFORE we remove
1923 	 * the current one. This can be the same instance again
1924 	 * if there is only one instance.
1925 	 */
1926 	if (hdev->cur_adv_instance == instance)
1927 		next = hci_get_next_instance(hdev, instance);
1928 
1929 	if (!instance) {
1930 		err = hci_clear_adv_sync(hdev, sk, force);
1931 		if (err)
1932 			return err;
1933 	} else {
1934 		struct adv_info *adv = hci_find_adv_instance(hdev, instance);
1935 
1936 		if (force || (adv && adv->timeout && !adv->remaining_time)) {
1937 			/* Don't advertise a removed instance. */
1938 			if (next && next->instance == instance)
1939 				next = NULL;
1940 
1941 			err = hci_remove_adv_sync(hdev, instance, sk);
1942 			if (err)
1943 				return err;
1944 		}
1945 	}
1946 
1947 	if (!hdev_is_powered(hdev) || hci_dev_test_flag(hdev, HCI_ADVERTISING))
1948 		return 0;
1949 
1950 	if (next && !ext_adv_capable(hdev))
1951 		hci_schedule_adv_instance_sync(hdev, next->instance, false);
1952 
1953 	return 0;
1954 }
1955 
1956 int hci_read_rssi_sync(struct hci_dev *hdev, __le16 handle)
1957 {
1958 	struct hci_cp_read_rssi cp;
1959 
1960 	cp.handle = handle;
1961 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_RSSI,
1962 					sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1963 }
1964 
1965 int hci_read_clock_sync(struct hci_dev *hdev, struct hci_cp_read_clock *cp)
1966 {
1967 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_CLOCK,
1968 					sizeof(*cp), cp, HCI_CMD_TIMEOUT);
1969 }
1970 
1971 int hci_read_tx_power_sync(struct hci_dev *hdev, __le16 handle, u8 type)
1972 {
1973 	struct hci_cp_read_tx_power cp;
1974 
1975 	cp.handle = handle;
1976 	cp.type = type;
1977 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_TX_POWER,
1978 					sizeof(cp), &cp, HCI_CMD_TIMEOUT);
1979 }
1980 
1981 int hci_disable_advertising_sync(struct hci_dev *hdev)
1982 {
1983 	u8 enable = 0x00;
1984 	int err = 0;
1985 
1986 	/* If controller is not advertising we are done. */
1987 	if (!hci_dev_test_flag(hdev, HCI_LE_ADV))
1988 		return 0;
1989 
1990 	if (ext_adv_capable(hdev))
1991 		err = hci_disable_ext_adv_instance_sync(hdev, 0x00);
1992 	if (ext_adv_capable(hdev))
1993 		return err;
1994 
1995 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_ENABLE,
1996 				     sizeof(enable), &enable, HCI_CMD_TIMEOUT);
1997 }
1998 
1999 static int hci_le_set_ext_scan_enable_sync(struct hci_dev *hdev, u8 val,
2000 					   u8 filter_dup)
2001 {
2002 	struct hci_cp_le_set_ext_scan_enable cp;
2003 
2004 	memset(&cp, 0, sizeof(cp));
2005 	cp.enable = val;
2006 
2007 	if (hci_dev_test_flag(hdev, HCI_MESH))
2008 		cp.filter_dup = LE_SCAN_FILTER_DUP_DISABLE;
2009 	else
2010 		cp.filter_dup = filter_dup;
2011 
2012 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_SCAN_ENABLE,
2013 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2014 }
2015 
2016 static int hci_le_set_scan_enable_sync(struct hci_dev *hdev, u8 val,
2017 				       u8 filter_dup)
2018 {
2019 	struct hci_cp_le_set_scan_enable cp;
2020 
2021 	if (use_ext_scan(hdev))
2022 		return hci_le_set_ext_scan_enable_sync(hdev, val, filter_dup);
2023 
2024 	memset(&cp, 0, sizeof(cp));
2025 	cp.enable = val;
2026 
2027 	if (val && hci_dev_test_flag(hdev, HCI_MESH))
2028 		cp.filter_dup = LE_SCAN_FILTER_DUP_DISABLE;
2029 	else
2030 		cp.filter_dup = filter_dup;
2031 
2032 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_SCAN_ENABLE,
2033 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2034 }
2035 
2036 static int hci_le_set_addr_resolution_enable_sync(struct hci_dev *hdev, u8 val)
2037 {
2038 	if (!use_ll_privacy(hdev))
2039 		return 0;
2040 
2041 	/* If controller is not/already resolving we are done. */
2042 	if (val == hci_dev_test_flag(hdev, HCI_LL_RPA_RESOLUTION))
2043 		return 0;
2044 
2045 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADDR_RESOLV_ENABLE,
2046 				     sizeof(val), &val, HCI_CMD_TIMEOUT);
2047 }
2048 
2049 static int hci_scan_disable_sync(struct hci_dev *hdev)
2050 {
2051 	int err;
2052 
2053 	/* If controller is not scanning we are done. */
2054 	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN))
2055 		return 0;
2056 
2057 	if (hdev->scanning_paused) {
2058 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
2059 		return 0;
2060 	}
2061 
2062 	err = hci_le_set_scan_enable_sync(hdev, LE_SCAN_DISABLE, 0x00);
2063 	if (err) {
2064 		bt_dev_err(hdev, "Unable to disable scanning: %d", err);
2065 		return err;
2066 	}
2067 
2068 	return err;
2069 }
2070 
2071 static bool scan_use_rpa(struct hci_dev *hdev)
2072 {
2073 	return hci_dev_test_flag(hdev, HCI_PRIVACY);
2074 }
2075 
2076 static void hci_start_interleave_scan(struct hci_dev *hdev)
2077 {
2078 	hdev->interleave_scan_state = INTERLEAVE_SCAN_NO_FILTER;
2079 	queue_delayed_work(hdev->req_workqueue,
2080 			   &hdev->interleave_scan, 0);
2081 }
2082 
2083 static bool is_interleave_scanning(struct hci_dev *hdev)
2084 {
2085 	return hdev->interleave_scan_state != INTERLEAVE_SCAN_NONE;
2086 }
2087 
2088 static void cancel_interleave_scan(struct hci_dev *hdev)
2089 {
2090 	bt_dev_dbg(hdev, "cancelling interleave scan");
2091 
2092 	cancel_delayed_work_sync(&hdev->interleave_scan);
2093 
2094 	hdev->interleave_scan_state = INTERLEAVE_SCAN_NONE;
2095 }
2096 
2097 /* Return true if interleave_scan wasn't started until exiting this function,
2098  * otherwise, return false
2099  */
2100 static bool hci_update_interleaved_scan_sync(struct hci_dev *hdev)
2101 {
2102 	/* Do interleaved scan only if all of the following are true:
2103 	 * - There is at least one ADV monitor
2104 	 * - At least one pending LE connection or one device to be scanned for
2105 	 * - Monitor offloading is not supported
2106 	 * If so, we should alternate between allowlist scan and one without
2107 	 * any filters to save power.
2108 	 */
2109 	bool use_interleaving = hci_is_adv_monitoring(hdev) &&
2110 				!(list_empty(&hdev->pend_le_conns) &&
2111 				  list_empty(&hdev->pend_le_reports)) &&
2112 				hci_get_adv_monitor_offload_ext(hdev) ==
2113 				    HCI_ADV_MONITOR_EXT_NONE;
2114 	bool is_interleaving = is_interleave_scanning(hdev);
2115 
2116 	if (use_interleaving && !is_interleaving) {
2117 		hci_start_interleave_scan(hdev);
2118 		bt_dev_dbg(hdev, "starting interleave scan");
2119 		return true;
2120 	}
2121 
2122 	if (!use_interleaving && is_interleaving)
2123 		cancel_interleave_scan(hdev);
2124 
2125 	return false;
2126 }
2127 
2128 /* Removes connection to resolve list if needed.*/
2129 static int hci_le_del_resolve_list_sync(struct hci_dev *hdev,
2130 					bdaddr_t *bdaddr, u8 bdaddr_type)
2131 {
2132 	struct hci_cp_le_del_from_resolv_list cp;
2133 	struct bdaddr_list_with_irk *entry;
2134 
2135 	if (!use_ll_privacy(hdev))
2136 		return 0;
2137 
2138 	/* Check if the IRK has been programmed */
2139 	entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, bdaddr,
2140 						bdaddr_type);
2141 	if (!entry)
2142 		return 0;
2143 
2144 	cp.bdaddr_type = bdaddr_type;
2145 	bacpy(&cp.bdaddr, bdaddr);
2146 
2147 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_DEL_FROM_RESOLV_LIST,
2148 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2149 }
2150 
2151 static int hci_le_del_accept_list_sync(struct hci_dev *hdev,
2152 				       bdaddr_t *bdaddr, u8 bdaddr_type)
2153 {
2154 	struct hci_cp_le_del_from_accept_list cp;
2155 	int err;
2156 
2157 	/* Check if device is on accept list before removing it */
2158 	if (!hci_bdaddr_list_lookup(&hdev->le_accept_list, bdaddr, bdaddr_type))
2159 		return 0;
2160 
2161 	cp.bdaddr_type = bdaddr_type;
2162 	bacpy(&cp.bdaddr, bdaddr);
2163 
2164 	/* Ignore errors when removing from resolving list as that is likely
2165 	 * that the device was never added.
2166 	 */
2167 	hci_le_del_resolve_list_sync(hdev, &cp.bdaddr, cp.bdaddr_type);
2168 
2169 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_DEL_FROM_ACCEPT_LIST,
2170 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2171 	if (err) {
2172 		bt_dev_err(hdev, "Unable to remove from allow list: %d", err);
2173 		return err;
2174 	}
2175 
2176 	bt_dev_dbg(hdev, "Remove %pMR (0x%x) from allow list", &cp.bdaddr,
2177 		   cp.bdaddr_type);
2178 
2179 	return 0;
2180 }
2181 
2182 struct conn_params {
2183 	bdaddr_t addr;
2184 	u8 addr_type;
2185 	hci_conn_flags_t flags;
2186 	u8 privacy_mode;
2187 };
2188 
2189 /* Adds connection to resolve list if needed.
2190  * Setting params to NULL programs local hdev->irk
2191  */
2192 static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,
2193 					struct conn_params *params)
2194 {
2195 	struct hci_cp_le_add_to_resolv_list cp;
2196 	struct smp_irk *irk;
2197 	struct bdaddr_list_with_irk *entry;
2198 	struct hci_conn_params *p;
2199 
2200 	if (!use_ll_privacy(hdev))
2201 		return 0;
2202 
2203 	/* Attempt to program local identity address, type and irk if params is
2204 	 * NULL.
2205 	 */
2206 	if (!params) {
2207 		if (!hci_dev_test_flag(hdev, HCI_PRIVACY))
2208 			return 0;
2209 
2210 		hci_copy_identity_address(hdev, &cp.bdaddr, &cp.bdaddr_type);
2211 		memcpy(cp.peer_irk, hdev->irk, 16);
2212 		goto done;
2213 	}
2214 
2215 	irk = hci_find_irk_by_addr(hdev, &params->addr, params->addr_type);
2216 	if (!irk)
2217 		return 0;
2218 
2219 	/* Check if the IK has _not_ been programmed yet. */
2220 	entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list,
2221 						&params->addr,
2222 						params->addr_type);
2223 	if (entry)
2224 		return 0;
2225 
2226 	cp.bdaddr_type = params->addr_type;
2227 	bacpy(&cp.bdaddr, &params->addr);
2228 	memcpy(cp.peer_irk, irk->val, 16);
2229 
2230 	/* Default privacy mode is always Network */
2231 	params->privacy_mode = HCI_NETWORK_PRIVACY;
2232 
2233 	rcu_read_lock();
2234 	p = hci_pend_le_action_lookup(&hdev->pend_le_conns,
2235 				      &params->addr, params->addr_type);
2236 	if (!p)
2237 		p = hci_pend_le_action_lookup(&hdev->pend_le_reports,
2238 					      &params->addr, params->addr_type);
2239 	if (p)
2240 		WRITE_ONCE(p->privacy_mode, HCI_NETWORK_PRIVACY);
2241 	rcu_read_unlock();
2242 
2243 done:
2244 	if (hci_dev_test_flag(hdev, HCI_PRIVACY))
2245 		memcpy(cp.local_irk, hdev->irk, 16);
2246 	else
2247 		memset(cp.local_irk, 0, 16);
2248 
2249 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_ADD_TO_RESOLV_LIST,
2250 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2251 }
2252 
2253 /* Set Device Privacy Mode. */
2254 static int hci_le_set_privacy_mode_sync(struct hci_dev *hdev,
2255 					struct conn_params *params)
2256 {
2257 	struct hci_cp_le_set_privacy_mode cp;
2258 	struct smp_irk *irk;
2259 
2260 	/* If device privacy mode has already been set there is nothing to do */
2261 	if (params->privacy_mode == HCI_DEVICE_PRIVACY)
2262 		return 0;
2263 
2264 	/* Check if HCI_CONN_FLAG_DEVICE_PRIVACY has been set as it also
2265 	 * indicates that LL Privacy has been enabled and
2266 	 * HCI_OP_LE_SET_PRIVACY_MODE is supported.
2267 	 */
2268 	if (!(params->flags & HCI_CONN_FLAG_DEVICE_PRIVACY))
2269 		return 0;
2270 
2271 	irk = hci_find_irk_by_addr(hdev, &params->addr, params->addr_type);
2272 	if (!irk)
2273 		return 0;
2274 
2275 	memset(&cp, 0, sizeof(cp));
2276 	cp.bdaddr_type = irk->addr_type;
2277 	bacpy(&cp.bdaddr, &irk->bdaddr);
2278 	cp.mode = HCI_DEVICE_PRIVACY;
2279 
2280 	/* Note: params->privacy_mode is not updated since it is a copy */
2281 
2282 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_PRIVACY_MODE,
2283 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2284 }
2285 
2286 /* Adds connection to allow list if needed, if the device uses RPA (has IRK)
2287  * this attempts to program the device in the resolving list as well and
2288  * properly set the privacy mode.
2289  */
2290 static int hci_le_add_accept_list_sync(struct hci_dev *hdev,
2291 				       struct conn_params *params,
2292 				       u8 *num_entries)
2293 {
2294 	struct hci_cp_le_add_to_accept_list cp;
2295 	int err;
2296 
2297 	/* During suspend, only wakeable devices can be in acceptlist */
2298 	if (hdev->suspended &&
2299 	    !(params->flags & HCI_CONN_FLAG_REMOTE_WAKEUP)) {
2300 		hci_le_del_accept_list_sync(hdev, &params->addr,
2301 					    params->addr_type);
2302 		return 0;
2303 	}
2304 
2305 	/* Select filter policy to accept all advertising */
2306 	if (*num_entries >= hdev->le_accept_list_size)
2307 		return -ENOSPC;
2308 
2309 	/* Accept list can not be used with RPAs */
2310 	if (!use_ll_privacy(hdev) &&
2311 	    hci_find_irk_by_addr(hdev, &params->addr, params->addr_type))
2312 		return -EINVAL;
2313 
2314 	/* Attempt to program the device in the resolving list first to avoid
2315 	 * having to rollback in case it fails since the resolving list is
2316 	 * dynamic it can probably be smaller than the accept list.
2317 	 */
2318 	err = hci_le_add_resolve_list_sync(hdev, params);
2319 	if (err) {
2320 		bt_dev_err(hdev, "Unable to add to resolve list: %d", err);
2321 		return err;
2322 	}
2323 
2324 	/* Set Privacy Mode */
2325 	err = hci_le_set_privacy_mode_sync(hdev, params);
2326 	if (err) {
2327 		bt_dev_err(hdev, "Unable to set privacy mode: %d", err);
2328 		return err;
2329 	}
2330 
2331 	/* Check if already in accept list */
2332 	if (hci_bdaddr_list_lookup(&hdev->le_accept_list, &params->addr,
2333 				   params->addr_type))
2334 		return 0;
2335 
2336 	*num_entries += 1;
2337 	cp.bdaddr_type = params->addr_type;
2338 	bacpy(&cp.bdaddr, &params->addr);
2339 
2340 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_ADD_TO_ACCEPT_LIST,
2341 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2342 	if (err) {
2343 		bt_dev_err(hdev, "Unable to add to allow list: %d", err);
2344 		/* Rollback the device from the resolving list */
2345 		hci_le_del_resolve_list_sync(hdev, &cp.bdaddr, cp.bdaddr_type);
2346 		return err;
2347 	}
2348 
2349 	bt_dev_dbg(hdev, "Add %pMR (0x%x) to allow list", &cp.bdaddr,
2350 		   cp.bdaddr_type);
2351 
2352 	return 0;
2353 }
2354 
2355 /* This function disables/pause all advertising instances */
2356 static int hci_pause_advertising_sync(struct hci_dev *hdev)
2357 {
2358 	int err;
2359 	int old_state;
2360 
2361 	/* If already been paused there is nothing to do. */
2362 	if (hdev->advertising_paused)
2363 		return 0;
2364 
2365 	bt_dev_dbg(hdev, "Pausing directed advertising");
2366 
2367 	/* Stop directed advertising */
2368 	old_state = hci_dev_test_flag(hdev, HCI_ADVERTISING);
2369 	if (old_state) {
2370 		/* When discoverable timeout triggers, then just make sure
2371 		 * the limited discoverable flag is cleared. Even in the case
2372 		 * of a timeout triggered from general discoverable, it is
2373 		 * safe to unconditionally clear the flag.
2374 		 */
2375 		hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
2376 		hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
2377 		hdev->discov_timeout = 0;
2378 	}
2379 
2380 	bt_dev_dbg(hdev, "Pausing advertising instances");
2381 
2382 	/* Call to disable any advertisements active on the controller.
2383 	 * This will succeed even if no advertisements are configured.
2384 	 */
2385 	err = hci_disable_advertising_sync(hdev);
2386 	if (err)
2387 		return err;
2388 
2389 	/* If we are using software rotation, pause the loop */
2390 	if (!ext_adv_capable(hdev))
2391 		cancel_adv_timeout(hdev);
2392 
2393 	hdev->advertising_paused = true;
2394 	hdev->advertising_old_state = old_state;
2395 
2396 	return 0;
2397 }
2398 
2399 /* This function enables all user advertising instances */
2400 static int hci_resume_advertising_sync(struct hci_dev *hdev)
2401 {
2402 	struct adv_info *adv, *tmp;
2403 	int err;
2404 
2405 	/* If advertising has not been paused there is nothing  to do. */
2406 	if (!hdev->advertising_paused)
2407 		return 0;
2408 
2409 	/* Resume directed advertising */
2410 	hdev->advertising_paused = false;
2411 	if (hdev->advertising_old_state) {
2412 		hci_dev_set_flag(hdev, HCI_ADVERTISING);
2413 		hdev->advertising_old_state = 0;
2414 	}
2415 
2416 	bt_dev_dbg(hdev, "Resuming advertising instances");
2417 
2418 	if (ext_adv_capable(hdev)) {
2419 		/* Call for each tracked instance to be re-enabled */
2420 		list_for_each_entry_safe(adv, tmp, &hdev->adv_instances, list) {
2421 			err = hci_enable_ext_advertising_sync(hdev,
2422 							      adv->instance);
2423 			if (!err)
2424 				continue;
2425 
2426 			/* If the instance cannot be resumed remove it */
2427 			hci_remove_ext_adv_instance_sync(hdev, adv->instance,
2428 							 NULL);
2429 		}
2430 	} else {
2431 		/* Schedule for most recent instance to be restarted and begin
2432 		 * the software rotation loop
2433 		 */
2434 		err = hci_schedule_adv_instance_sync(hdev,
2435 						     hdev->cur_adv_instance,
2436 						     true);
2437 	}
2438 
2439 	hdev->advertising_paused = false;
2440 
2441 	return err;
2442 }
2443 
2444 static int hci_pause_addr_resolution(struct hci_dev *hdev)
2445 {
2446 	int err;
2447 
2448 	if (!use_ll_privacy(hdev))
2449 		return 0;
2450 
2451 	if (!hci_dev_test_flag(hdev, HCI_LL_RPA_RESOLUTION))
2452 		return 0;
2453 
2454 	/* Cannot disable addr resolution if scanning is enabled or
2455 	 * when initiating an LE connection.
2456 	 */
2457 	if (hci_dev_test_flag(hdev, HCI_LE_SCAN) ||
2458 	    hci_lookup_le_connect(hdev)) {
2459 		bt_dev_err(hdev, "Command not allowed when scan/LE connect");
2460 		return -EPERM;
2461 	}
2462 
2463 	/* Cannot disable addr resolution if advertising is enabled. */
2464 	err = hci_pause_advertising_sync(hdev);
2465 	if (err) {
2466 		bt_dev_err(hdev, "Pause advertising failed: %d", err);
2467 		return err;
2468 	}
2469 
2470 	err = hci_le_set_addr_resolution_enable_sync(hdev, 0x00);
2471 	if (err)
2472 		bt_dev_err(hdev, "Unable to disable Address Resolution: %d",
2473 			   err);
2474 
2475 	/* Return if address resolution is disabled and RPA is not used. */
2476 	if (!err && scan_use_rpa(hdev))
2477 		return 0;
2478 
2479 	hci_resume_advertising_sync(hdev);
2480 	return err;
2481 }
2482 
2483 struct sk_buff *hci_read_local_oob_data_sync(struct hci_dev *hdev,
2484 					     bool extended, struct sock *sk)
2485 {
2486 	u16 opcode = extended ? HCI_OP_READ_LOCAL_OOB_EXT_DATA :
2487 					HCI_OP_READ_LOCAL_OOB_DATA;
2488 
2489 	return __hci_cmd_sync_sk(hdev, opcode, 0, NULL, 0, HCI_CMD_TIMEOUT, sk);
2490 }
2491 
2492 static struct conn_params *conn_params_copy(struct list_head *list, size_t *n)
2493 {
2494 	struct hci_conn_params *params;
2495 	struct conn_params *p;
2496 	size_t i;
2497 
2498 	rcu_read_lock();
2499 
2500 	i = 0;
2501 	list_for_each_entry_rcu(params, list, action)
2502 		++i;
2503 	*n = i;
2504 
2505 	rcu_read_unlock();
2506 
2507 	p = kvcalloc(*n, sizeof(struct conn_params), GFP_KERNEL);
2508 	if (!p)
2509 		return NULL;
2510 
2511 	rcu_read_lock();
2512 
2513 	i = 0;
2514 	list_for_each_entry_rcu(params, list, action) {
2515 		/* Racing adds are handled in next scan update */
2516 		if (i >= *n)
2517 			break;
2518 
2519 		/* No hdev->lock, but: addr, addr_type are immutable.
2520 		 * privacy_mode is only written by us or in
2521 		 * hci_cc_le_set_privacy_mode that we wait for.
2522 		 * We should be idempotent so MGMT updating flags
2523 		 * while we are processing is OK.
2524 		 */
2525 		bacpy(&p[i].addr, &params->addr);
2526 		p[i].addr_type = params->addr_type;
2527 		p[i].flags = READ_ONCE(params->flags);
2528 		p[i].privacy_mode = READ_ONCE(params->privacy_mode);
2529 		++i;
2530 	}
2531 
2532 	rcu_read_unlock();
2533 
2534 	*n = i;
2535 	return p;
2536 }
2537 
2538 /* Device must not be scanning when updating the accept list.
2539  *
2540  * Update is done using the following sequence:
2541  *
2542  * use_ll_privacy((Disable Advertising) -> Disable Resolving List) ->
2543  * Remove Devices From Accept List ->
2544  * (has IRK && use_ll_privacy(Remove Devices From Resolving List))->
2545  * Add Devices to Accept List ->
2546  * (has IRK && use_ll_privacy(Remove Devices From Resolving List)) ->
2547  * use_ll_privacy(Enable Resolving List -> (Enable Advertising)) ->
2548  * Enable Scanning
2549  *
2550  * In case of failure advertising shall be restored to its original state and
2551  * return would disable accept list since either accept or resolving list could
2552  * not be programmed.
2553  *
2554  */
2555 static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
2556 {
2557 	struct conn_params *params;
2558 	struct bdaddr_list *b, *t;
2559 	u8 num_entries = 0;
2560 	bool pend_conn, pend_report;
2561 	u8 filter_policy;
2562 	size_t i, n;
2563 	int err;
2564 
2565 	/* Pause advertising if resolving list can be used as controllers
2566 	 * cannot accept resolving list modifications while advertising.
2567 	 */
2568 	if (use_ll_privacy(hdev)) {
2569 		err = hci_pause_advertising_sync(hdev);
2570 		if (err) {
2571 			bt_dev_err(hdev, "pause advertising failed: %d", err);
2572 			return 0x00;
2573 		}
2574 	}
2575 
2576 	/* Disable address resolution while reprogramming accept list since
2577 	 * devices that do have an IRK will be programmed in the resolving list
2578 	 * when LL Privacy is enabled.
2579 	 */
2580 	err = hci_le_set_addr_resolution_enable_sync(hdev, 0x00);
2581 	if (err) {
2582 		bt_dev_err(hdev, "Unable to disable LL privacy: %d", err);
2583 		goto done;
2584 	}
2585 
2586 	/* Go through the current accept list programmed into the
2587 	 * controller one by one and check if that address is connected or is
2588 	 * still in the list of pending connections or list of devices to
2589 	 * report. If not present in either list, then remove it from
2590 	 * the controller.
2591 	 */
2592 	list_for_each_entry_safe(b, t, &hdev->le_accept_list, list) {
2593 		if (hci_conn_hash_lookup_le(hdev, &b->bdaddr, b->bdaddr_type))
2594 			continue;
2595 
2596 		/* Pointers not dereferenced, no locks needed */
2597 		pend_conn = hci_pend_le_action_lookup(&hdev->pend_le_conns,
2598 						      &b->bdaddr,
2599 						      b->bdaddr_type);
2600 		pend_report = hci_pend_le_action_lookup(&hdev->pend_le_reports,
2601 							&b->bdaddr,
2602 							b->bdaddr_type);
2603 
2604 		/* If the device is not likely to connect or report,
2605 		 * remove it from the acceptlist.
2606 		 */
2607 		if (!pend_conn && !pend_report) {
2608 			hci_le_del_accept_list_sync(hdev, &b->bdaddr,
2609 						    b->bdaddr_type);
2610 			continue;
2611 		}
2612 
2613 		num_entries++;
2614 	}
2615 
2616 	/* Since all no longer valid accept list entries have been
2617 	 * removed, walk through the list of pending connections
2618 	 * and ensure that any new device gets programmed into
2619 	 * the controller.
2620 	 *
2621 	 * If the list of the devices is larger than the list of
2622 	 * available accept list entries in the controller, then
2623 	 * just abort and return filer policy value to not use the
2624 	 * accept list.
2625 	 *
2626 	 * The list and params may be mutated while we wait for events,
2627 	 * so make a copy and iterate it.
2628 	 */
2629 
2630 	params = conn_params_copy(&hdev->pend_le_conns, &n);
2631 	if (!params) {
2632 		err = -ENOMEM;
2633 		goto done;
2634 	}
2635 
2636 	for (i = 0; i < n; ++i) {
2637 		err = hci_le_add_accept_list_sync(hdev, &params[i],
2638 						  &num_entries);
2639 		if (err) {
2640 			kvfree(params);
2641 			goto done;
2642 		}
2643 	}
2644 
2645 	kvfree(params);
2646 
2647 	/* After adding all new pending connections, walk through
2648 	 * the list of pending reports and also add these to the
2649 	 * accept list if there is still space. Abort if space runs out.
2650 	 */
2651 
2652 	params = conn_params_copy(&hdev->pend_le_reports, &n);
2653 	if (!params) {
2654 		err = -ENOMEM;
2655 		goto done;
2656 	}
2657 
2658 	for (i = 0; i < n; ++i) {
2659 		err = hci_le_add_accept_list_sync(hdev, &params[i],
2660 						  &num_entries);
2661 		if (err) {
2662 			kvfree(params);
2663 			goto done;
2664 		}
2665 	}
2666 
2667 	kvfree(params);
2668 
2669 	/* Use the allowlist unless the following conditions are all true:
2670 	 * - We are not currently suspending
2671 	 * - There are 1 or more ADV monitors registered and it's not offloaded
2672 	 * - Interleaved scanning is not currently using the allowlist
2673 	 */
2674 	if (!idr_is_empty(&hdev->adv_monitors_idr) && !hdev->suspended &&
2675 	    hci_get_adv_monitor_offload_ext(hdev) == HCI_ADV_MONITOR_EXT_NONE &&
2676 	    hdev->interleave_scan_state != INTERLEAVE_SCAN_ALLOWLIST)
2677 		err = -EINVAL;
2678 
2679 done:
2680 	filter_policy = err ? 0x00 : 0x01;
2681 
2682 	/* Enable address resolution when LL Privacy is enabled. */
2683 	err = hci_le_set_addr_resolution_enable_sync(hdev, 0x01);
2684 	if (err)
2685 		bt_dev_err(hdev, "Unable to enable LL privacy: %d", err);
2686 
2687 	/* Resume advertising if it was paused */
2688 	if (use_ll_privacy(hdev))
2689 		hci_resume_advertising_sync(hdev);
2690 
2691 	/* Select filter policy to use accept list */
2692 	return filter_policy;
2693 }
2694 
2695 static void hci_le_scan_phy_params(struct hci_cp_le_scan_phy_params *cp,
2696 				   u8 type, u16 interval, u16 window)
2697 {
2698 	cp->type = type;
2699 	cp->interval = cpu_to_le16(interval);
2700 	cp->window = cpu_to_le16(window);
2701 }
2702 
2703 static int hci_le_set_ext_scan_param_sync(struct hci_dev *hdev, u8 type,
2704 					  u16 interval, u16 window,
2705 					  u8 own_addr_type, u8 filter_policy)
2706 {
2707 	struct hci_cp_le_set_ext_scan_params *cp;
2708 	struct hci_cp_le_scan_phy_params *phy;
2709 	u8 data[sizeof(*cp) + sizeof(*phy) * 2];
2710 	u8 num_phy = 0x00;
2711 
2712 	cp = (void *)data;
2713 	phy = (void *)cp->data;
2714 
2715 	memset(data, 0, sizeof(data));
2716 
2717 	cp->own_addr_type = own_addr_type;
2718 	cp->filter_policy = filter_policy;
2719 
2720 	/* Check if PA Sync is in progress then select the PHY based on the
2721 	 * hci_conn.iso_qos.
2722 	 */
2723 	if (hci_dev_test_flag(hdev, HCI_PA_SYNC)) {
2724 		struct hci_cp_le_add_to_accept_list *sent;
2725 
2726 		sent = hci_sent_cmd_data(hdev, HCI_OP_LE_ADD_TO_ACCEPT_LIST);
2727 		if (sent) {
2728 			struct hci_conn *conn;
2729 
2730 			conn = hci_conn_hash_lookup_ba(hdev, ISO_LINK,
2731 						       &sent->bdaddr);
2732 			if (conn) {
2733 				struct bt_iso_qos *qos = &conn->iso_qos;
2734 
2735 				if (qos->bcast.in.phy & BT_ISO_PHY_1M ||
2736 				    qos->bcast.in.phy & BT_ISO_PHY_2M) {
2737 					cp->scanning_phys |= LE_SCAN_PHY_1M;
2738 					hci_le_scan_phy_params(phy, type,
2739 							       interval,
2740 							       window);
2741 					num_phy++;
2742 					phy++;
2743 				}
2744 
2745 				if (qos->bcast.in.phy & BT_ISO_PHY_CODED) {
2746 					cp->scanning_phys |= LE_SCAN_PHY_CODED;
2747 					hci_le_scan_phy_params(phy, type,
2748 							       interval * 3,
2749 							       window * 3);
2750 					num_phy++;
2751 					phy++;
2752 				}
2753 
2754 				if (num_phy)
2755 					goto done;
2756 			}
2757 		}
2758 	}
2759 
2760 	if (scan_1m(hdev) || scan_2m(hdev)) {
2761 		cp->scanning_phys |= LE_SCAN_PHY_1M;
2762 		hci_le_scan_phy_params(phy, type, interval, window);
2763 		num_phy++;
2764 		phy++;
2765 	}
2766 
2767 	if (scan_coded(hdev)) {
2768 		cp->scanning_phys |= LE_SCAN_PHY_CODED;
2769 		hci_le_scan_phy_params(phy, type, interval * 3, window * 3);
2770 		num_phy++;
2771 		phy++;
2772 	}
2773 
2774 done:
2775 	if (!num_phy)
2776 		return -EINVAL;
2777 
2778 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_SCAN_PARAMS,
2779 				     sizeof(*cp) + sizeof(*phy) * num_phy,
2780 				     data, HCI_CMD_TIMEOUT);
2781 }
2782 
2783 static int hci_le_set_scan_param_sync(struct hci_dev *hdev, u8 type,
2784 				      u16 interval, u16 window,
2785 				      u8 own_addr_type, u8 filter_policy)
2786 {
2787 	struct hci_cp_le_set_scan_param cp;
2788 
2789 	if (use_ext_scan(hdev))
2790 		return hci_le_set_ext_scan_param_sync(hdev, type, interval,
2791 						      window, own_addr_type,
2792 						      filter_policy);
2793 
2794 	memset(&cp, 0, sizeof(cp));
2795 	cp.type = type;
2796 	cp.interval = cpu_to_le16(interval);
2797 	cp.window = cpu_to_le16(window);
2798 	cp.own_address_type = own_addr_type;
2799 	cp.filter_policy = filter_policy;
2800 
2801 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_SCAN_PARAM,
2802 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
2803 }
2804 
2805 static int hci_start_scan_sync(struct hci_dev *hdev, u8 type, u16 interval,
2806 			       u16 window, u8 own_addr_type, u8 filter_policy,
2807 			       u8 filter_dup)
2808 {
2809 	int err;
2810 
2811 	if (hdev->scanning_paused) {
2812 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
2813 		return 0;
2814 	}
2815 
2816 	err = hci_le_set_scan_param_sync(hdev, type, interval, window,
2817 					 own_addr_type, filter_policy);
2818 	if (err)
2819 		return err;
2820 
2821 	return hci_le_set_scan_enable_sync(hdev, LE_SCAN_ENABLE, filter_dup);
2822 }
2823 
2824 static int hci_passive_scan_sync(struct hci_dev *hdev)
2825 {
2826 	u8 own_addr_type;
2827 	u8 filter_policy;
2828 	u16 window, interval;
2829 	u8 filter_dups = LE_SCAN_FILTER_DUP_ENABLE;
2830 	int err;
2831 
2832 	if (hdev->scanning_paused) {
2833 		bt_dev_dbg(hdev, "Scanning is paused for suspend");
2834 		return 0;
2835 	}
2836 
2837 	err = hci_scan_disable_sync(hdev);
2838 	if (err) {
2839 		bt_dev_err(hdev, "disable scanning failed: %d", err);
2840 		return err;
2841 	}
2842 
2843 	/* Set require_privacy to false since no SCAN_REQ are send
2844 	 * during passive scanning. Not using an non-resolvable address
2845 	 * here is important so that peer devices using direct
2846 	 * advertising with our address will be correctly reported
2847 	 * by the controller.
2848 	 */
2849 	if (hci_update_random_address_sync(hdev, false, scan_use_rpa(hdev),
2850 					   &own_addr_type))
2851 		return 0;
2852 
2853 	if (hdev->enable_advmon_interleave_scan &&
2854 	    hci_update_interleaved_scan_sync(hdev))
2855 		return 0;
2856 
2857 	bt_dev_dbg(hdev, "interleave state %d", hdev->interleave_scan_state);
2858 
2859 	/* Adding or removing entries from the accept list must
2860 	 * happen before enabling scanning. The controller does
2861 	 * not allow accept list modification while scanning.
2862 	 */
2863 	filter_policy = hci_update_accept_list_sync(hdev);
2864 
2865 	/* If suspended and filter_policy set to 0x00 (no acceptlist) then
2866 	 * passive scanning cannot be started since that would require the host
2867 	 * to be woken up to process the reports.
2868 	 */
2869 	if (hdev->suspended && !filter_policy) {
2870 		/* Check if accept list is empty then there is no need to scan
2871 		 * while suspended.
2872 		 */
2873 		if (list_empty(&hdev->le_accept_list))
2874 			return 0;
2875 
2876 		/* If there are devices is the accept_list that means some
2877 		 * devices could not be programmed which in non-suspended case
2878 		 * means filter_policy needs to be set to 0x00 so the host needs
2879 		 * to filter, but since this is treating suspended case we
2880 		 * can ignore device needing host to filter to allow devices in
2881 		 * the acceptlist to be able to wakeup the system.
2882 		 */
2883 		filter_policy = 0x01;
2884 	}
2885 
2886 	/* When the controller is using random resolvable addresses and
2887 	 * with that having LE privacy enabled, then controllers with
2888 	 * Extended Scanner Filter Policies support can now enable support
2889 	 * for handling directed advertising.
2890 	 *
2891 	 * So instead of using filter polices 0x00 (no acceptlist)
2892 	 * and 0x01 (acceptlist enabled) use the new filter policies
2893 	 * 0x02 (no acceptlist) and 0x03 (acceptlist enabled).
2894 	 */
2895 	if (hci_dev_test_flag(hdev, HCI_PRIVACY) &&
2896 	    (hdev->le_features[0] & HCI_LE_EXT_SCAN_POLICY))
2897 		filter_policy |= 0x02;
2898 
2899 	if (hdev->suspended) {
2900 		window = hdev->le_scan_window_suspend;
2901 		interval = hdev->le_scan_int_suspend;
2902 	} else if (hci_is_le_conn_scanning(hdev)) {
2903 		window = hdev->le_scan_window_connect;
2904 		interval = hdev->le_scan_int_connect;
2905 	} else if (hci_is_adv_monitoring(hdev)) {
2906 		window = hdev->le_scan_window_adv_monitor;
2907 		interval = hdev->le_scan_int_adv_monitor;
2908 
2909 		/* Disable duplicates filter when scanning for advertisement
2910 		 * monitor for the following reasons.
2911 		 *
2912 		 * For HW pattern filtering (ex. MSFT), Realtek and Qualcomm
2913 		 * controllers ignore RSSI_Sampling_Period when the duplicates
2914 		 * filter is enabled.
2915 		 *
2916 		 * For SW pattern filtering, when we're not doing interleaved
2917 		 * scanning, it is necessary to disable duplicates filter,
2918 		 * otherwise hosts can only receive one advertisement and it's
2919 		 * impossible to know if a peer is still in range.
2920 		 */
2921 		filter_dups = LE_SCAN_FILTER_DUP_DISABLE;
2922 	} else {
2923 		window = hdev->le_scan_window;
2924 		interval = hdev->le_scan_interval;
2925 	}
2926 
2927 	/* Disable all filtering for Mesh */
2928 	if (hci_dev_test_flag(hdev, HCI_MESH)) {
2929 		filter_policy = 0;
2930 		filter_dups = LE_SCAN_FILTER_DUP_DISABLE;
2931 	}
2932 
2933 	bt_dev_dbg(hdev, "LE passive scan with acceptlist = %d", filter_policy);
2934 
2935 	return hci_start_scan_sync(hdev, LE_SCAN_PASSIVE, interval, window,
2936 				   own_addr_type, filter_policy, filter_dups);
2937 }
2938 
2939 /* This function controls the passive scanning based on hdev->pend_le_conns
2940  * list. If there are pending LE connection we start the background scanning,
2941  * otherwise we stop it in the following sequence:
2942  *
2943  * If there are devices to scan:
2944  *
2945  * Disable Scanning -> Update Accept List ->
2946  * use_ll_privacy((Disable Advertising) -> Disable Resolving List ->
2947  * Update Resolving List -> Enable Resolving List -> (Enable Advertising)) ->
2948  * Enable Scanning
2949  *
2950  * Otherwise:
2951  *
2952  * Disable Scanning
2953  */
2954 int hci_update_passive_scan_sync(struct hci_dev *hdev)
2955 {
2956 	int err;
2957 
2958 	if (!test_bit(HCI_UP, &hdev->flags) ||
2959 	    test_bit(HCI_INIT, &hdev->flags) ||
2960 	    hci_dev_test_flag(hdev, HCI_SETUP) ||
2961 	    hci_dev_test_flag(hdev, HCI_CONFIG) ||
2962 	    hci_dev_test_flag(hdev, HCI_AUTO_OFF) ||
2963 	    hci_dev_test_flag(hdev, HCI_UNREGISTER))
2964 		return 0;
2965 
2966 	/* No point in doing scanning if LE support hasn't been enabled */
2967 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
2968 		return 0;
2969 
2970 	/* If discovery is active don't interfere with it */
2971 	if (hdev->discovery.state != DISCOVERY_STOPPED)
2972 		return 0;
2973 
2974 	/* Reset RSSI and UUID filters when starting background scanning
2975 	 * since these filters are meant for service discovery only.
2976 	 *
2977 	 * The Start Discovery and Start Service Discovery operations
2978 	 * ensure to set proper values for RSSI threshold and UUID
2979 	 * filter list. So it is safe to just reset them here.
2980 	 */
2981 	hci_discovery_filter_clear(hdev);
2982 
2983 	bt_dev_dbg(hdev, "ADV monitoring is %s",
2984 		   hci_is_adv_monitoring(hdev) ? "on" : "off");
2985 
2986 	if (!hci_dev_test_flag(hdev, HCI_MESH) &&
2987 	    list_empty(&hdev->pend_le_conns) &&
2988 	    list_empty(&hdev->pend_le_reports) &&
2989 	    !hci_is_adv_monitoring(hdev) &&
2990 	    !hci_dev_test_flag(hdev, HCI_PA_SYNC)) {
2991 		/* If there is no pending LE connections or devices
2992 		 * to be scanned for or no ADV monitors, we should stop the
2993 		 * background scanning.
2994 		 */
2995 
2996 		bt_dev_dbg(hdev, "stopping background scanning");
2997 
2998 		err = hci_scan_disable_sync(hdev);
2999 		if (err)
3000 			bt_dev_err(hdev, "stop background scanning failed: %d",
3001 				   err);
3002 	} else {
3003 		/* If there is at least one pending LE connection, we should
3004 		 * keep the background scan running.
3005 		 */
3006 
3007 		/* If controller is connecting, we should not start scanning
3008 		 * since some controllers are not able to scan and connect at
3009 		 * the same time.
3010 		 */
3011 		if (hci_lookup_le_connect(hdev))
3012 			return 0;
3013 
3014 		bt_dev_dbg(hdev, "start background scanning");
3015 
3016 		err = hci_passive_scan_sync(hdev);
3017 		if (err)
3018 			bt_dev_err(hdev, "start background scanning failed: %d",
3019 				   err);
3020 	}
3021 
3022 	return err;
3023 }
3024 
3025 static int update_scan_sync(struct hci_dev *hdev, void *data)
3026 {
3027 	return hci_update_scan_sync(hdev);
3028 }
3029 
3030 int hci_update_scan(struct hci_dev *hdev)
3031 {
3032 	return hci_cmd_sync_queue(hdev, update_scan_sync, NULL, NULL);
3033 }
3034 
3035 static int update_passive_scan_sync(struct hci_dev *hdev, void *data)
3036 {
3037 	return hci_update_passive_scan_sync(hdev);
3038 }
3039 
3040 int hci_update_passive_scan(struct hci_dev *hdev)
3041 {
3042 	/* Only queue if it would have any effect */
3043 	if (!test_bit(HCI_UP, &hdev->flags) ||
3044 	    test_bit(HCI_INIT, &hdev->flags) ||
3045 	    hci_dev_test_flag(hdev, HCI_SETUP) ||
3046 	    hci_dev_test_flag(hdev, HCI_CONFIG) ||
3047 	    hci_dev_test_flag(hdev, HCI_AUTO_OFF) ||
3048 	    hci_dev_test_flag(hdev, HCI_UNREGISTER))
3049 		return 0;
3050 
3051 	return hci_cmd_sync_queue(hdev, update_passive_scan_sync, NULL, NULL);
3052 }
3053 
3054 int hci_write_sc_support_sync(struct hci_dev *hdev, u8 val)
3055 {
3056 	int err;
3057 
3058 	if (!bredr_sc_enabled(hdev) || lmp_host_sc_capable(hdev))
3059 		return 0;
3060 
3061 	err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SC_SUPPORT,
3062 				    sizeof(val), &val, HCI_CMD_TIMEOUT);
3063 
3064 	if (!err) {
3065 		if (val) {
3066 			hdev->features[1][0] |= LMP_HOST_SC;
3067 			hci_dev_set_flag(hdev, HCI_SC_ENABLED);
3068 		} else {
3069 			hdev->features[1][0] &= ~LMP_HOST_SC;
3070 			hci_dev_clear_flag(hdev, HCI_SC_ENABLED);
3071 		}
3072 	}
3073 
3074 	return err;
3075 }
3076 
3077 int hci_write_ssp_mode_sync(struct hci_dev *hdev, u8 mode)
3078 {
3079 	int err;
3080 
3081 	if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED) ||
3082 	    lmp_host_ssp_capable(hdev))
3083 		return 0;
3084 
3085 	if (!mode && hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS)) {
3086 		__hci_cmd_sync_status(hdev, HCI_OP_WRITE_SSP_DEBUG_MODE,
3087 				      sizeof(mode), &mode, HCI_CMD_TIMEOUT);
3088 	}
3089 
3090 	err = __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SSP_MODE,
3091 				    sizeof(mode), &mode, HCI_CMD_TIMEOUT);
3092 	if (err)
3093 		return err;
3094 
3095 	return hci_write_sc_support_sync(hdev, 0x01);
3096 }
3097 
3098 int hci_write_le_host_supported_sync(struct hci_dev *hdev, u8 le, u8 simul)
3099 {
3100 	struct hci_cp_write_le_host_supported cp;
3101 
3102 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED) ||
3103 	    !lmp_bredr_capable(hdev))
3104 		return 0;
3105 
3106 	/* Check first if we already have the right host state
3107 	 * (host features set)
3108 	 */
3109 	if (le == lmp_host_le_capable(hdev) &&
3110 	    simul == lmp_host_le_br_capable(hdev))
3111 		return 0;
3112 
3113 	memset(&cp, 0, sizeof(cp));
3114 
3115 	cp.le = le;
3116 	cp.simul = simul;
3117 
3118 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LE_HOST_SUPPORTED,
3119 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3120 }
3121 
3122 static int hci_powered_update_adv_sync(struct hci_dev *hdev)
3123 {
3124 	struct adv_info *adv, *tmp;
3125 	int err;
3126 
3127 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
3128 		return 0;
3129 
3130 	/* If RPA Resolution has not been enable yet it means the
3131 	 * resolving list is empty and we should attempt to program the
3132 	 * local IRK in order to support using own_addr_type
3133 	 * ADDR_LE_DEV_RANDOM_RESOLVED (0x03).
3134 	 */
3135 	if (!hci_dev_test_flag(hdev, HCI_LL_RPA_RESOLUTION)) {
3136 		hci_le_add_resolve_list_sync(hdev, NULL);
3137 		hci_le_set_addr_resolution_enable_sync(hdev, 0x01);
3138 	}
3139 
3140 	/* Make sure the controller has a good default for
3141 	 * advertising data. This also applies to the case
3142 	 * where BR/EDR was toggled during the AUTO_OFF phase.
3143 	 */
3144 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING) ||
3145 	    list_empty(&hdev->adv_instances)) {
3146 		if (ext_adv_capable(hdev)) {
3147 			err = hci_setup_ext_adv_instance_sync(hdev, 0x00);
3148 			if (!err)
3149 				hci_update_scan_rsp_data_sync(hdev, 0x00);
3150 		} else {
3151 			err = hci_update_adv_data_sync(hdev, 0x00);
3152 			if (!err)
3153 				hci_update_scan_rsp_data_sync(hdev, 0x00);
3154 		}
3155 
3156 		if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
3157 			hci_enable_advertising_sync(hdev);
3158 	}
3159 
3160 	/* Call for each tracked instance to be scheduled */
3161 	list_for_each_entry_safe(adv, tmp, &hdev->adv_instances, list)
3162 		hci_schedule_adv_instance_sync(hdev, adv->instance, true);
3163 
3164 	return 0;
3165 }
3166 
3167 static int hci_write_auth_enable_sync(struct hci_dev *hdev)
3168 {
3169 	u8 link_sec;
3170 
3171 	link_sec = hci_dev_test_flag(hdev, HCI_LINK_SECURITY);
3172 	if (link_sec == test_bit(HCI_AUTH, &hdev->flags))
3173 		return 0;
3174 
3175 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_AUTH_ENABLE,
3176 				     sizeof(link_sec), &link_sec,
3177 				     HCI_CMD_TIMEOUT);
3178 }
3179 
3180 int hci_write_fast_connectable_sync(struct hci_dev *hdev, bool enable)
3181 {
3182 	struct hci_cp_write_page_scan_activity cp;
3183 	u8 type;
3184 	int err = 0;
3185 
3186 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
3187 		return 0;
3188 
3189 	if (hdev->hci_ver < BLUETOOTH_VER_1_2)
3190 		return 0;
3191 
3192 	memset(&cp, 0, sizeof(cp));
3193 
3194 	if (enable) {
3195 		type = PAGE_SCAN_TYPE_INTERLACED;
3196 
3197 		/* 160 msec page scan interval */
3198 		cp.interval = cpu_to_le16(0x0100);
3199 	} else {
3200 		type = hdev->def_page_scan_type;
3201 		cp.interval = cpu_to_le16(hdev->def_page_scan_int);
3202 	}
3203 
3204 	cp.window = cpu_to_le16(hdev->def_page_scan_window);
3205 
3206 	if (__cpu_to_le16(hdev->page_scan_interval) != cp.interval ||
3207 	    __cpu_to_le16(hdev->page_scan_window) != cp.window) {
3208 		err = __hci_cmd_sync_status(hdev,
3209 					    HCI_OP_WRITE_PAGE_SCAN_ACTIVITY,
3210 					    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3211 		if (err)
3212 			return err;
3213 	}
3214 
3215 	if (hdev->page_scan_type != type)
3216 		err = __hci_cmd_sync_status(hdev,
3217 					    HCI_OP_WRITE_PAGE_SCAN_TYPE,
3218 					    sizeof(type), &type,
3219 					    HCI_CMD_TIMEOUT);
3220 
3221 	return err;
3222 }
3223 
3224 static bool disconnected_accept_list_entries(struct hci_dev *hdev)
3225 {
3226 	struct bdaddr_list *b;
3227 
3228 	list_for_each_entry(b, &hdev->accept_list, list) {
3229 		struct hci_conn *conn;
3230 
3231 		conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &b->bdaddr);
3232 		if (!conn)
3233 			return true;
3234 
3235 		if (conn->state != BT_CONNECTED && conn->state != BT_CONFIG)
3236 			return true;
3237 	}
3238 
3239 	return false;
3240 }
3241 
3242 static int hci_write_scan_enable_sync(struct hci_dev *hdev, u8 val)
3243 {
3244 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SCAN_ENABLE,
3245 					    sizeof(val), &val,
3246 					    HCI_CMD_TIMEOUT);
3247 }
3248 
3249 int hci_update_scan_sync(struct hci_dev *hdev)
3250 {
3251 	u8 scan;
3252 
3253 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
3254 		return 0;
3255 
3256 	if (!hdev_is_powered(hdev))
3257 		return 0;
3258 
3259 	if (mgmt_powering_down(hdev))
3260 		return 0;
3261 
3262 	if (hdev->scanning_paused)
3263 		return 0;
3264 
3265 	if (hci_dev_test_flag(hdev, HCI_CONNECTABLE) ||
3266 	    disconnected_accept_list_entries(hdev))
3267 		scan = SCAN_PAGE;
3268 	else
3269 		scan = SCAN_DISABLED;
3270 
3271 	if (hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
3272 		scan |= SCAN_INQUIRY;
3273 
3274 	if (test_bit(HCI_PSCAN, &hdev->flags) == !!(scan & SCAN_PAGE) &&
3275 	    test_bit(HCI_ISCAN, &hdev->flags) == !!(scan & SCAN_INQUIRY))
3276 		return 0;
3277 
3278 	return hci_write_scan_enable_sync(hdev, scan);
3279 }
3280 
3281 int hci_update_name_sync(struct hci_dev *hdev)
3282 {
3283 	struct hci_cp_write_local_name cp;
3284 
3285 	memset(&cp, 0, sizeof(cp));
3286 
3287 	memcpy(cp.name, hdev->dev_name, sizeof(cp.name));
3288 
3289 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LOCAL_NAME,
3290 					    sizeof(cp), &cp,
3291 					    HCI_CMD_TIMEOUT);
3292 }
3293 
3294 /* This function perform powered update HCI command sequence after the HCI init
3295  * sequence which end up resetting all states, the sequence is as follows:
3296  *
3297  * HCI_SSP_ENABLED(Enable SSP)
3298  * HCI_LE_ENABLED(Enable LE)
3299  * HCI_LE_ENABLED(use_ll_privacy(Add local IRK to Resolving List) ->
3300  * Update adv data)
3301  * Enable Authentication
3302  * lmp_bredr_capable(Set Fast Connectable -> Set Scan Type -> Set Class ->
3303  * Set Name -> Set EIR)
3304  * HCI_FORCE_STATIC_ADDR | BDADDR_ANY && !HCI_BREDR_ENABLED (Set Static Address)
3305  */
3306 int hci_powered_update_sync(struct hci_dev *hdev)
3307 {
3308 	int err;
3309 
3310 	/* Register the available SMP channels (BR/EDR and LE) only when
3311 	 * successfully powering on the controller. This late
3312 	 * registration is required so that LE SMP can clearly decide if
3313 	 * the public address or static address is used.
3314 	 */
3315 	smp_register(hdev);
3316 
3317 	err = hci_write_ssp_mode_sync(hdev, 0x01);
3318 	if (err)
3319 		return err;
3320 
3321 	err = hci_write_le_host_supported_sync(hdev, 0x01, 0x00);
3322 	if (err)
3323 		return err;
3324 
3325 	err = hci_powered_update_adv_sync(hdev);
3326 	if (err)
3327 		return err;
3328 
3329 	err = hci_write_auth_enable_sync(hdev);
3330 	if (err)
3331 		return err;
3332 
3333 	if (lmp_bredr_capable(hdev)) {
3334 		if (hci_dev_test_flag(hdev, HCI_FAST_CONNECTABLE))
3335 			hci_write_fast_connectable_sync(hdev, true);
3336 		else
3337 			hci_write_fast_connectable_sync(hdev, false);
3338 		hci_update_scan_sync(hdev);
3339 		hci_update_class_sync(hdev);
3340 		hci_update_name_sync(hdev);
3341 		hci_update_eir_sync(hdev);
3342 	}
3343 
3344 	/* If forcing static address is in use or there is no public
3345 	 * address use the static address as random address (but skip
3346 	 * the HCI command if the current random address is already the
3347 	 * static one.
3348 	 *
3349 	 * In case BR/EDR has been disabled on a dual-mode controller
3350 	 * and a static address has been configured, then use that
3351 	 * address instead of the public BR/EDR address.
3352 	 */
3353 	if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
3354 	    (!bacmp(&hdev->bdaddr, BDADDR_ANY) &&
3355 	    !hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))) {
3356 		if (bacmp(&hdev->static_addr, BDADDR_ANY))
3357 			return hci_set_random_addr_sync(hdev,
3358 							&hdev->static_addr);
3359 	}
3360 
3361 	return 0;
3362 }
3363 
3364 /**
3365  * hci_dev_get_bd_addr_from_property - Get the Bluetooth Device Address
3366  *				       (BD_ADDR) for a HCI device from
3367  *				       a firmware node property.
3368  * @hdev:	The HCI device
3369  *
3370  * Search the firmware node for 'local-bd-address'.
3371  *
3372  * All-zero BD addresses are rejected, because those could be properties
3373  * that exist in the firmware tables, but were not updated by the firmware. For
3374  * example, the DTS could define 'local-bd-address', with zero BD addresses.
3375  */
3376 static void hci_dev_get_bd_addr_from_property(struct hci_dev *hdev)
3377 {
3378 	struct fwnode_handle *fwnode = dev_fwnode(hdev->dev.parent);
3379 	bdaddr_t ba;
3380 	int ret;
3381 
3382 	ret = fwnode_property_read_u8_array(fwnode, "local-bd-address",
3383 					    (u8 *)&ba, sizeof(ba));
3384 	if (ret < 0 || !bacmp(&ba, BDADDR_ANY))
3385 		return;
3386 
3387 	if (test_bit(HCI_QUIRK_BDADDR_PROPERTY_BROKEN, &hdev->quirks))
3388 		baswap(&hdev->public_addr, &ba);
3389 	else
3390 		bacpy(&hdev->public_addr, &ba);
3391 }
3392 
3393 struct hci_init_stage {
3394 	int (*func)(struct hci_dev *hdev);
3395 };
3396 
3397 /* Run init stage NULL terminated function table */
3398 static int hci_init_stage_sync(struct hci_dev *hdev,
3399 			       const struct hci_init_stage *stage)
3400 {
3401 	size_t i;
3402 
3403 	for (i = 0; stage[i].func; i++) {
3404 		int err;
3405 
3406 		err = stage[i].func(hdev);
3407 		if (err)
3408 			return err;
3409 	}
3410 
3411 	return 0;
3412 }
3413 
3414 /* Read Local Version */
3415 static int hci_read_local_version_sync(struct hci_dev *hdev)
3416 {
3417 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_VERSION,
3418 				     0, NULL, HCI_CMD_TIMEOUT);
3419 }
3420 
3421 /* Read BD Address */
3422 static int hci_read_bd_addr_sync(struct hci_dev *hdev)
3423 {
3424 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_BD_ADDR,
3425 				     0, NULL, HCI_CMD_TIMEOUT);
3426 }
3427 
3428 #define HCI_INIT(_func) \
3429 { \
3430 	.func = _func, \
3431 }
3432 
3433 static const struct hci_init_stage hci_init0[] = {
3434 	/* HCI_OP_READ_LOCAL_VERSION */
3435 	HCI_INIT(hci_read_local_version_sync),
3436 	/* HCI_OP_READ_BD_ADDR */
3437 	HCI_INIT(hci_read_bd_addr_sync),
3438 	{}
3439 };
3440 
3441 int hci_reset_sync(struct hci_dev *hdev)
3442 {
3443 	int err;
3444 
3445 	set_bit(HCI_RESET, &hdev->flags);
3446 
3447 	err = __hci_cmd_sync_status(hdev, HCI_OP_RESET, 0, NULL,
3448 				    HCI_CMD_TIMEOUT);
3449 	if (err)
3450 		return err;
3451 
3452 	return 0;
3453 }
3454 
3455 static int hci_init0_sync(struct hci_dev *hdev)
3456 {
3457 	int err;
3458 
3459 	bt_dev_dbg(hdev, "");
3460 
3461 	/* Reset */
3462 	if (!test_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks)) {
3463 		err = hci_reset_sync(hdev);
3464 		if (err)
3465 			return err;
3466 	}
3467 
3468 	return hci_init_stage_sync(hdev, hci_init0);
3469 }
3470 
3471 static int hci_unconf_init_sync(struct hci_dev *hdev)
3472 {
3473 	int err;
3474 
3475 	if (test_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks))
3476 		return 0;
3477 
3478 	err = hci_init0_sync(hdev);
3479 	if (err < 0)
3480 		return err;
3481 
3482 	if (hci_dev_test_flag(hdev, HCI_SETUP))
3483 		hci_debugfs_create_basic(hdev);
3484 
3485 	return 0;
3486 }
3487 
3488 /* Read Local Supported Features. */
3489 static int hci_read_local_features_sync(struct hci_dev *hdev)
3490 {
3491 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_FEATURES,
3492 				     0, NULL, HCI_CMD_TIMEOUT);
3493 }
3494 
3495 /* BR Controller init stage 1 command sequence */
3496 static const struct hci_init_stage br_init1[] = {
3497 	/* HCI_OP_READ_LOCAL_FEATURES */
3498 	HCI_INIT(hci_read_local_features_sync),
3499 	/* HCI_OP_READ_LOCAL_VERSION */
3500 	HCI_INIT(hci_read_local_version_sync),
3501 	/* HCI_OP_READ_BD_ADDR */
3502 	HCI_INIT(hci_read_bd_addr_sync),
3503 	{}
3504 };
3505 
3506 /* Read Local Commands */
3507 static int hci_read_local_cmds_sync(struct hci_dev *hdev)
3508 {
3509 	/* All Bluetooth 1.2 and later controllers should support the
3510 	 * HCI command for reading the local supported commands.
3511 	 *
3512 	 * Unfortunately some controllers indicate Bluetooth 1.2 support,
3513 	 * but do not have support for this command. If that is the case,
3514 	 * the driver can quirk the behavior and skip reading the local
3515 	 * supported commands.
3516 	 */
3517 	if (hdev->hci_ver > BLUETOOTH_VER_1_1 &&
3518 	    !test_bit(HCI_QUIRK_BROKEN_LOCAL_COMMANDS, &hdev->quirks))
3519 		return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_COMMANDS,
3520 					     0, NULL, HCI_CMD_TIMEOUT);
3521 
3522 	return 0;
3523 }
3524 
3525 static int hci_init1_sync(struct hci_dev *hdev)
3526 {
3527 	int err;
3528 
3529 	bt_dev_dbg(hdev, "");
3530 
3531 	/* Reset */
3532 	if (!test_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks)) {
3533 		err = hci_reset_sync(hdev);
3534 		if (err)
3535 			return err;
3536 	}
3537 
3538 	return hci_init_stage_sync(hdev, br_init1);
3539 }
3540 
3541 /* Read Buffer Size (ACL mtu, max pkt, etc.) */
3542 static int hci_read_buffer_size_sync(struct hci_dev *hdev)
3543 {
3544 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_BUFFER_SIZE,
3545 				     0, NULL, HCI_CMD_TIMEOUT);
3546 }
3547 
3548 /* Read Class of Device */
3549 static int hci_read_dev_class_sync(struct hci_dev *hdev)
3550 {
3551 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_CLASS_OF_DEV,
3552 				     0, NULL, HCI_CMD_TIMEOUT);
3553 }
3554 
3555 /* Read Local Name */
3556 static int hci_read_local_name_sync(struct hci_dev *hdev)
3557 {
3558 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_NAME,
3559 				     0, NULL, HCI_CMD_TIMEOUT);
3560 }
3561 
3562 /* Read Voice Setting */
3563 static int hci_read_voice_setting_sync(struct hci_dev *hdev)
3564 {
3565 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_VOICE_SETTING,
3566 				     0, NULL, HCI_CMD_TIMEOUT);
3567 }
3568 
3569 /* Read Number of Supported IAC */
3570 static int hci_read_num_supported_iac_sync(struct hci_dev *hdev)
3571 {
3572 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_NUM_SUPPORTED_IAC,
3573 				     0, NULL, HCI_CMD_TIMEOUT);
3574 }
3575 
3576 /* Read Current IAC LAP */
3577 static int hci_read_current_iac_lap_sync(struct hci_dev *hdev)
3578 {
3579 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_CURRENT_IAC_LAP,
3580 				     0, NULL, HCI_CMD_TIMEOUT);
3581 }
3582 
3583 static int hci_set_event_filter_sync(struct hci_dev *hdev, u8 flt_type,
3584 				     u8 cond_type, bdaddr_t *bdaddr,
3585 				     u8 auto_accept)
3586 {
3587 	struct hci_cp_set_event_filter cp;
3588 
3589 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
3590 		return 0;
3591 
3592 	if (test_bit(HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL, &hdev->quirks))
3593 		return 0;
3594 
3595 	memset(&cp, 0, sizeof(cp));
3596 	cp.flt_type = flt_type;
3597 
3598 	if (flt_type != HCI_FLT_CLEAR_ALL) {
3599 		cp.cond_type = cond_type;
3600 		bacpy(&cp.addr_conn_flt.bdaddr, bdaddr);
3601 		cp.addr_conn_flt.auto_accept = auto_accept;
3602 	}
3603 
3604 	return __hci_cmd_sync_status(hdev, HCI_OP_SET_EVENT_FLT,
3605 				     flt_type == HCI_FLT_CLEAR_ALL ?
3606 				     sizeof(cp.flt_type) : sizeof(cp), &cp,
3607 				     HCI_CMD_TIMEOUT);
3608 }
3609 
3610 static int hci_clear_event_filter_sync(struct hci_dev *hdev)
3611 {
3612 	if (!hci_dev_test_flag(hdev, HCI_EVENT_FILTER_CONFIGURED))
3613 		return 0;
3614 
3615 	/* In theory the state machine should not reach here unless
3616 	 * a hci_set_event_filter_sync() call succeeds, but we do
3617 	 * the check both for parity and as a future reminder.
3618 	 */
3619 	if (test_bit(HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL, &hdev->quirks))
3620 		return 0;
3621 
3622 	return hci_set_event_filter_sync(hdev, HCI_FLT_CLEAR_ALL, 0x00,
3623 					 BDADDR_ANY, 0x00);
3624 }
3625 
3626 /* Connection accept timeout ~20 secs */
3627 static int hci_write_ca_timeout_sync(struct hci_dev *hdev)
3628 {
3629 	__le16 param = cpu_to_le16(0x7d00);
3630 
3631 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_CA_TIMEOUT,
3632 				     sizeof(param), &param, HCI_CMD_TIMEOUT);
3633 }
3634 
3635 /* BR Controller init stage 2 command sequence */
3636 static const struct hci_init_stage br_init2[] = {
3637 	/* HCI_OP_READ_BUFFER_SIZE */
3638 	HCI_INIT(hci_read_buffer_size_sync),
3639 	/* HCI_OP_READ_CLASS_OF_DEV */
3640 	HCI_INIT(hci_read_dev_class_sync),
3641 	/* HCI_OP_READ_LOCAL_NAME */
3642 	HCI_INIT(hci_read_local_name_sync),
3643 	/* HCI_OP_READ_VOICE_SETTING */
3644 	HCI_INIT(hci_read_voice_setting_sync),
3645 	/* HCI_OP_READ_NUM_SUPPORTED_IAC */
3646 	HCI_INIT(hci_read_num_supported_iac_sync),
3647 	/* HCI_OP_READ_CURRENT_IAC_LAP */
3648 	HCI_INIT(hci_read_current_iac_lap_sync),
3649 	/* HCI_OP_SET_EVENT_FLT */
3650 	HCI_INIT(hci_clear_event_filter_sync),
3651 	/* HCI_OP_WRITE_CA_TIMEOUT */
3652 	HCI_INIT(hci_write_ca_timeout_sync),
3653 	{}
3654 };
3655 
3656 static int hci_write_ssp_mode_1_sync(struct hci_dev *hdev)
3657 {
3658 	u8 mode = 0x01;
3659 
3660 	if (!lmp_ssp_capable(hdev) || !hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
3661 		return 0;
3662 
3663 	/* When SSP is available, then the host features page
3664 	 * should also be available as well. However some
3665 	 * controllers list the max_page as 0 as long as SSP
3666 	 * has not been enabled. To achieve proper debugging
3667 	 * output, force the minimum max_page to 1 at least.
3668 	 */
3669 	hdev->max_page = 0x01;
3670 
3671 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SSP_MODE,
3672 				     sizeof(mode), &mode, HCI_CMD_TIMEOUT);
3673 }
3674 
3675 static int hci_write_eir_sync(struct hci_dev *hdev)
3676 {
3677 	struct hci_cp_write_eir cp;
3678 
3679 	if (!lmp_ssp_capable(hdev) || hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
3680 		return 0;
3681 
3682 	memset(hdev->eir, 0, sizeof(hdev->eir));
3683 	memset(&cp, 0, sizeof(cp));
3684 
3685 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_EIR, sizeof(cp), &cp,
3686 				     HCI_CMD_TIMEOUT);
3687 }
3688 
3689 static int hci_write_inquiry_mode_sync(struct hci_dev *hdev)
3690 {
3691 	u8 mode;
3692 
3693 	if (!lmp_inq_rssi_capable(hdev) &&
3694 	    !test_bit(HCI_QUIRK_FIXUP_INQUIRY_MODE, &hdev->quirks))
3695 		return 0;
3696 
3697 	/* If Extended Inquiry Result events are supported, then
3698 	 * they are clearly preferred over Inquiry Result with RSSI
3699 	 * events.
3700 	 */
3701 	mode = lmp_ext_inq_capable(hdev) ? 0x02 : 0x01;
3702 
3703 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_INQUIRY_MODE,
3704 				     sizeof(mode), &mode, HCI_CMD_TIMEOUT);
3705 }
3706 
3707 static int hci_read_inq_rsp_tx_power_sync(struct hci_dev *hdev)
3708 {
3709 	if (!lmp_inq_tx_pwr_capable(hdev))
3710 		return 0;
3711 
3712 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_INQ_RSP_TX_POWER,
3713 				     0, NULL, HCI_CMD_TIMEOUT);
3714 }
3715 
3716 static int hci_read_local_ext_features_sync(struct hci_dev *hdev, u8 page)
3717 {
3718 	struct hci_cp_read_local_ext_features cp;
3719 
3720 	if (!lmp_ext_feat_capable(hdev))
3721 		return 0;
3722 
3723 	memset(&cp, 0, sizeof(cp));
3724 	cp.page = page;
3725 
3726 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_EXT_FEATURES,
3727 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3728 }
3729 
3730 static int hci_read_local_ext_features_1_sync(struct hci_dev *hdev)
3731 {
3732 	return hci_read_local_ext_features_sync(hdev, 0x01);
3733 }
3734 
3735 /* HCI Controller init stage 2 command sequence */
3736 static const struct hci_init_stage hci_init2[] = {
3737 	/* HCI_OP_READ_LOCAL_COMMANDS */
3738 	HCI_INIT(hci_read_local_cmds_sync),
3739 	/* HCI_OP_WRITE_SSP_MODE */
3740 	HCI_INIT(hci_write_ssp_mode_1_sync),
3741 	/* HCI_OP_WRITE_EIR */
3742 	HCI_INIT(hci_write_eir_sync),
3743 	/* HCI_OP_WRITE_INQUIRY_MODE */
3744 	HCI_INIT(hci_write_inquiry_mode_sync),
3745 	/* HCI_OP_READ_INQ_RSP_TX_POWER */
3746 	HCI_INIT(hci_read_inq_rsp_tx_power_sync),
3747 	/* HCI_OP_READ_LOCAL_EXT_FEATURES */
3748 	HCI_INIT(hci_read_local_ext_features_1_sync),
3749 	/* HCI_OP_WRITE_AUTH_ENABLE */
3750 	HCI_INIT(hci_write_auth_enable_sync),
3751 	{}
3752 };
3753 
3754 /* Read LE Buffer Size */
3755 static int hci_le_read_buffer_size_sync(struct hci_dev *hdev)
3756 {
3757 	/* Use Read LE Buffer Size V2 if supported */
3758 	if (iso_capable(hdev) && hdev->commands[41] & 0x20)
3759 		return __hci_cmd_sync_status(hdev,
3760 					     HCI_OP_LE_READ_BUFFER_SIZE_V2,
3761 					     0, NULL, HCI_CMD_TIMEOUT);
3762 
3763 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_BUFFER_SIZE,
3764 				     0, NULL, HCI_CMD_TIMEOUT);
3765 }
3766 
3767 /* Read LE Local Supported Features */
3768 static int hci_le_read_local_features_sync(struct hci_dev *hdev)
3769 {
3770 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_LOCAL_FEATURES,
3771 				     0, NULL, HCI_CMD_TIMEOUT);
3772 }
3773 
3774 /* Read LE Supported States */
3775 static int hci_le_read_supported_states_sync(struct hci_dev *hdev)
3776 {
3777 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_SUPPORTED_STATES,
3778 				     0, NULL, HCI_CMD_TIMEOUT);
3779 }
3780 
3781 /* LE Controller init stage 2 command sequence */
3782 static const struct hci_init_stage le_init2[] = {
3783 	/* HCI_OP_LE_READ_LOCAL_FEATURES */
3784 	HCI_INIT(hci_le_read_local_features_sync),
3785 	/* HCI_OP_LE_READ_BUFFER_SIZE */
3786 	HCI_INIT(hci_le_read_buffer_size_sync),
3787 	/* HCI_OP_LE_READ_SUPPORTED_STATES */
3788 	HCI_INIT(hci_le_read_supported_states_sync),
3789 	{}
3790 };
3791 
3792 static int hci_init2_sync(struct hci_dev *hdev)
3793 {
3794 	int err;
3795 
3796 	bt_dev_dbg(hdev, "");
3797 
3798 	err = hci_init_stage_sync(hdev, hci_init2);
3799 	if (err)
3800 		return err;
3801 
3802 	if (lmp_bredr_capable(hdev)) {
3803 		err = hci_init_stage_sync(hdev, br_init2);
3804 		if (err)
3805 			return err;
3806 	} else {
3807 		hci_dev_clear_flag(hdev, HCI_BREDR_ENABLED);
3808 	}
3809 
3810 	if (lmp_le_capable(hdev)) {
3811 		err = hci_init_stage_sync(hdev, le_init2);
3812 		if (err)
3813 			return err;
3814 		/* LE-only controllers have LE implicitly enabled */
3815 		if (!lmp_bredr_capable(hdev))
3816 			hci_dev_set_flag(hdev, HCI_LE_ENABLED);
3817 	}
3818 
3819 	return 0;
3820 }
3821 
3822 static int hci_set_event_mask_sync(struct hci_dev *hdev)
3823 {
3824 	/* The second byte is 0xff instead of 0x9f (two reserved bits
3825 	 * disabled) since a Broadcom 1.2 dongle doesn't respond to the
3826 	 * command otherwise.
3827 	 */
3828 	u8 events[8] = { 0xff, 0xff, 0xfb, 0xff, 0x00, 0x00, 0x00, 0x00 };
3829 
3830 	/* CSR 1.1 dongles does not accept any bitfield so don't try to set
3831 	 * any event mask for pre 1.2 devices.
3832 	 */
3833 	if (hdev->hci_ver < BLUETOOTH_VER_1_2)
3834 		return 0;
3835 
3836 	if (lmp_bredr_capable(hdev)) {
3837 		events[4] |= 0x01; /* Flow Specification Complete */
3838 
3839 		/* Don't set Disconnect Complete and mode change when
3840 		 * suspended as that would wakeup the host when disconnecting
3841 		 * due to suspend.
3842 		 */
3843 		if (hdev->suspended) {
3844 			events[0] &= 0xef;
3845 			events[2] &= 0xf7;
3846 		}
3847 	} else {
3848 		/* Use a different default for LE-only devices */
3849 		memset(events, 0, sizeof(events));
3850 		events[1] |= 0x20; /* Command Complete */
3851 		events[1] |= 0x40; /* Command Status */
3852 		events[1] |= 0x80; /* Hardware Error */
3853 
3854 		/* If the controller supports the Disconnect command, enable
3855 		 * the corresponding event. In addition enable packet flow
3856 		 * control related events.
3857 		 */
3858 		if (hdev->commands[0] & 0x20) {
3859 			/* Don't set Disconnect Complete when suspended as that
3860 			 * would wakeup the host when disconnecting due to
3861 			 * suspend.
3862 			 */
3863 			if (!hdev->suspended)
3864 				events[0] |= 0x10; /* Disconnection Complete */
3865 			events[2] |= 0x04; /* Number of Completed Packets */
3866 			events[3] |= 0x02; /* Data Buffer Overflow */
3867 		}
3868 
3869 		/* If the controller supports the Read Remote Version
3870 		 * Information command, enable the corresponding event.
3871 		 */
3872 		if (hdev->commands[2] & 0x80)
3873 			events[1] |= 0x08; /* Read Remote Version Information
3874 					    * Complete
3875 					    */
3876 
3877 		if (hdev->le_features[0] & HCI_LE_ENCRYPTION) {
3878 			events[0] |= 0x80; /* Encryption Change */
3879 			events[5] |= 0x80; /* Encryption Key Refresh Complete */
3880 		}
3881 	}
3882 
3883 	if (lmp_inq_rssi_capable(hdev) ||
3884 	    test_bit(HCI_QUIRK_FIXUP_INQUIRY_MODE, &hdev->quirks))
3885 		events[4] |= 0x02; /* Inquiry Result with RSSI */
3886 
3887 	if (lmp_ext_feat_capable(hdev))
3888 		events[4] |= 0x04; /* Read Remote Extended Features Complete */
3889 
3890 	if (lmp_esco_capable(hdev)) {
3891 		events[5] |= 0x08; /* Synchronous Connection Complete */
3892 		events[5] |= 0x10; /* Synchronous Connection Changed */
3893 	}
3894 
3895 	if (lmp_sniffsubr_capable(hdev))
3896 		events[5] |= 0x20; /* Sniff Subrating */
3897 
3898 	if (lmp_pause_enc_capable(hdev))
3899 		events[5] |= 0x80; /* Encryption Key Refresh Complete */
3900 
3901 	if (lmp_ext_inq_capable(hdev))
3902 		events[5] |= 0x40; /* Extended Inquiry Result */
3903 
3904 	if (lmp_no_flush_capable(hdev))
3905 		events[7] |= 0x01; /* Enhanced Flush Complete */
3906 
3907 	if (lmp_lsto_capable(hdev))
3908 		events[6] |= 0x80; /* Link Supervision Timeout Changed */
3909 
3910 	if (lmp_ssp_capable(hdev)) {
3911 		events[6] |= 0x01;	/* IO Capability Request */
3912 		events[6] |= 0x02;	/* IO Capability Response */
3913 		events[6] |= 0x04;	/* User Confirmation Request */
3914 		events[6] |= 0x08;	/* User Passkey Request */
3915 		events[6] |= 0x10;	/* Remote OOB Data Request */
3916 		events[6] |= 0x20;	/* Simple Pairing Complete */
3917 		events[7] |= 0x04;	/* User Passkey Notification */
3918 		events[7] |= 0x08;	/* Keypress Notification */
3919 		events[7] |= 0x10;	/* Remote Host Supported
3920 					 * Features Notification
3921 					 */
3922 	}
3923 
3924 	if (lmp_le_capable(hdev))
3925 		events[7] |= 0x20;	/* LE Meta-Event */
3926 
3927 	return __hci_cmd_sync_status(hdev, HCI_OP_SET_EVENT_MASK,
3928 				     sizeof(events), events, HCI_CMD_TIMEOUT);
3929 }
3930 
3931 static int hci_read_stored_link_key_sync(struct hci_dev *hdev)
3932 {
3933 	struct hci_cp_read_stored_link_key cp;
3934 
3935 	if (!(hdev->commands[6] & 0x20) ||
3936 	    test_bit(HCI_QUIRK_BROKEN_STORED_LINK_KEY, &hdev->quirks))
3937 		return 0;
3938 
3939 	memset(&cp, 0, sizeof(cp));
3940 	bacpy(&cp.bdaddr, BDADDR_ANY);
3941 	cp.read_all = 0x01;
3942 
3943 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_STORED_LINK_KEY,
3944 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3945 }
3946 
3947 static int hci_setup_link_policy_sync(struct hci_dev *hdev)
3948 {
3949 	struct hci_cp_write_def_link_policy cp;
3950 	u16 link_policy = 0;
3951 
3952 	if (!(hdev->commands[5] & 0x10))
3953 		return 0;
3954 
3955 	memset(&cp, 0, sizeof(cp));
3956 
3957 	if (lmp_rswitch_capable(hdev))
3958 		link_policy |= HCI_LP_RSWITCH;
3959 	if (lmp_hold_capable(hdev))
3960 		link_policy |= HCI_LP_HOLD;
3961 	if (lmp_sniff_capable(hdev))
3962 		link_policy |= HCI_LP_SNIFF;
3963 	if (lmp_park_capable(hdev))
3964 		link_policy |= HCI_LP_PARK;
3965 
3966 	cp.policy = cpu_to_le16(link_policy);
3967 
3968 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_DEF_LINK_POLICY,
3969 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
3970 }
3971 
3972 static int hci_read_page_scan_activity_sync(struct hci_dev *hdev)
3973 {
3974 	if (!(hdev->commands[8] & 0x01))
3975 		return 0;
3976 
3977 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_PAGE_SCAN_ACTIVITY,
3978 				     0, NULL, HCI_CMD_TIMEOUT);
3979 }
3980 
3981 static int hci_read_def_err_data_reporting_sync(struct hci_dev *hdev)
3982 {
3983 	if (!(hdev->commands[18] & 0x04) ||
3984 	    !(hdev->features[0][6] & LMP_ERR_DATA_REPORTING) ||
3985 	    test_bit(HCI_QUIRK_BROKEN_ERR_DATA_REPORTING, &hdev->quirks))
3986 		return 0;
3987 
3988 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_DEF_ERR_DATA_REPORTING,
3989 				     0, NULL, HCI_CMD_TIMEOUT);
3990 }
3991 
3992 static int hci_read_page_scan_type_sync(struct hci_dev *hdev)
3993 {
3994 	/* Some older Broadcom based Bluetooth 1.2 controllers do not
3995 	 * support the Read Page Scan Type command. Check support for
3996 	 * this command in the bit mask of supported commands.
3997 	 */
3998 	if (!(hdev->commands[13] & 0x01))
3999 		return 0;
4000 
4001 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_PAGE_SCAN_TYPE,
4002 				     0, NULL, HCI_CMD_TIMEOUT);
4003 }
4004 
4005 /* Read features beyond page 1 if available */
4006 static int hci_read_local_ext_features_all_sync(struct hci_dev *hdev)
4007 {
4008 	u8 page;
4009 	int err;
4010 
4011 	if (!lmp_ext_feat_capable(hdev))
4012 		return 0;
4013 
4014 	for (page = 2; page < HCI_MAX_PAGES && page <= hdev->max_page;
4015 	     page++) {
4016 		err = hci_read_local_ext_features_sync(hdev, page);
4017 		if (err)
4018 			return err;
4019 	}
4020 
4021 	return 0;
4022 }
4023 
4024 /* HCI Controller init stage 3 command sequence */
4025 static const struct hci_init_stage hci_init3[] = {
4026 	/* HCI_OP_SET_EVENT_MASK */
4027 	HCI_INIT(hci_set_event_mask_sync),
4028 	/* HCI_OP_READ_STORED_LINK_KEY */
4029 	HCI_INIT(hci_read_stored_link_key_sync),
4030 	/* HCI_OP_WRITE_DEF_LINK_POLICY */
4031 	HCI_INIT(hci_setup_link_policy_sync),
4032 	/* HCI_OP_READ_PAGE_SCAN_ACTIVITY */
4033 	HCI_INIT(hci_read_page_scan_activity_sync),
4034 	/* HCI_OP_READ_DEF_ERR_DATA_REPORTING */
4035 	HCI_INIT(hci_read_def_err_data_reporting_sync),
4036 	/* HCI_OP_READ_PAGE_SCAN_TYPE */
4037 	HCI_INIT(hci_read_page_scan_type_sync),
4038 	/* HCI_OP_READ_LOCAL_EXT_FEATURES */
4039 	HCI_INIT(hci_read_local_ext_features_all_sync),
4040 	{}
4041 };
4042 
4043 static int hci_le_set_event_mask_sync(struct hci_dev *hdev)
4044 {
4045 	u8 events[8];
4046 
4047 	if (!lmp_le_capable(hdev))
4048 		return 0;
4049 
4050 	memset(events, 0, sizeof(events));
4051 
4052 	if (hdev->le_features[0] & HCI_LE_ENCRYPTION)
4053 		events[0] |= 0x10;	/* LE Long Term Key Request */
4054 
4055 	/* If controller supports the Connection Parameters Request
4056 	 * Link Layer Procedure, enable the corresponding event.
4057 	 */
4058 	if (hdev->le_features[0] & HCI_LE_CONN_PARAM_REQ_PROC)
4059 		/* LE Remote Connection Parameter Request */
4060 		events[0] |= 0x20;
4061 
4062 	/* If the controller supports the Data Length Extension
4063 	 * feature, enable the corresponding event.
4064 	 */
4065 	if (hdev->le_features[0] & HCI_LE_DATA_LEN_EXT)
4066 		events[0] |= 0x40;	/* LE Data Length Change */
4067 
4068 	/* If the controller supports LL Privacy feature or LE Extended Adv,
4069 	 * enable the corresponding event.
4070 	 */
4071 	if (use_enhanced_conn_complete(hdev))
4072 		events[1] |= 0x02;	/* LE Enhanced Connection Complete */
4073 
4074 	/* If the controller supports Extended Scanner Filter
4075 	 * Policies, enable the corresponding event.
4076 	 */
4077 	if (hdev->le_features[0] & HCI_LE_EXT_SCAN_POLICY)
4078 		events[1] |= 0x04;	/* LE Direct Advertising Report */
4079 
4080 	/* If the controller supports Channel Selection Algorithm #2
4081 	 * feature, enable the corresponding event.
4082 	 */
4083 	if (hdev->le_features[1] & HCI_LE_CHAN_SEL_ALG2)
4084 		events[2] |= 0x08;	/* LE Channel Selection Algorithm */
4085 
4086 	/* If the controller supports the LE Set Scan Enable command,
4087 	 * enable the corresponding advertising report event.
4088 	 */
4089 	if (hdev->commands[26] & 0x08)
4090 		events[0] |= 0x02;	/* LE Advertising Report */
4091 
4092 	/* If the controller supports the LE Create Connection
4093 	 * command, enable the corresponding event.
4094 	 */
4095 	if (hdev->commands[26] & 0x10)
4096 		events[0] |= 0x01;	/* LE Connection Complete */
4097 
4098 	/* If the controller supports the LE Connection Update
4099 	 * command, enable the corresponding event.
4100 	 */
4101 	if (hdev->commands[27] & 0x04)
4102 		events[0] |= 0x04;	/* LE Connection Update Complete */
4103 
4104 	/* If the controller supports the LE Read Remote Used Features
4105 	 * command, enable the corresponding event.
4106 	 */
4107 	if (hdev->commands[27] & 0x20)
4108 		/* LE Read Remote Used Features Complete */
4109 		events[0] |= 0x08;
4110 
4111 	/* If the controller supports the LE Read Local P-256
4112 	 * Public Key command, enable the corresponding event.
4113 	 */
4114 	if (hdev->commands[34] & 0x02)
4115 		/* LE Read Local P-256 Public Key Complete */
4116 		events[0] |= 0x80;
4117 
4118 	/* If the controller supports the LE Generate DHKey
4119 	 * command, enable the corresponding event.
4120 	 */
4121 	if (hdev->commands[34] & 0x04)
4122 		events[1] |= 0x01;	/* LE Generate DHKey Complete */
4123 
4124 	/* If the controller supports the LE Set Default PHY or
4125 	 * LE Set PHY commands, enable the corresponding event.
4126 	 */
4127 	if (hdev->commands[35] & (0x20 | 0x40))
4128 		events[1] |= 0x08;        /* LE PHY Update Complete */
4129 
4130 	/* If the controller supports LE Set Extended Scan Parameters
4131 	 * and LE Set Extended Scan Enable commands, enable the
4132 	 * corresponding event.
4133 	 */
4134 	if (use_ext_scan(hdev))
4135 		events[1] |= 0x10;	/* LE Extended Advertising Report */
4136 
4137 	/* If the controller supports the LE Extended Advertising
4138 	 * command, enable the corresponding event.
4139 	 */
4140 	if (ext_adv_capable(hdev))
4141 		events[2] |= 0x02;	/* LE Advertising Set Terminated */
4142 
4143 	if (cis_capable(hdev)) {
4144 		events[3] |= 0x01;	/* LE CIS Established */
4145 		if (cis_peripheral_capable(hdev))
4146 			events[3] |= 0x02; /* LE CIS Request */
4147 	}
4148 
4149 	if (bis_capable(hdev)) {
4150 		events[1] |= 0x20;	/* LE PA Report */
4151 		events[1] |= 0x40;	/* LE PA Sync Established */
4152 		events[3] |= 0x04;	/* LE Create BIG Complete */
4153 		events[3] |= 0x08;	/* LE Terminate BIG Complete */
4154 		events[3] |= 0x10;	/* LE BIG Sync Established */
4155 		events[3] |= 0x20;	/* LE BIG Sync Loss */
4156 		events[4] |= 0x02;	/* LE BIG Info Advertising Report */
4157 	}
4158 
4159 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EVENT_MASK,
4160 				     sizeof(events), events, HCI_CMD_TIMEOUT);
4161 }
4162 
4163 /* Read LE Advertising Channel TX Power */
4164 static int hci_le_read_adv_tx_power_sync(struct hci_dev *hdev)
4165 {
4166 	if ((hdev->commands[25] & 0x40) && !ext_adv_capable(hdev)) {
4167 		/* HCI TS spec forbids mixing of legacy and extended
4168 		 * advertising commands wherein READ_ADV_TX_POWER is
4169 		 * also included. So do not call it if extended adv
4170 		 * is supported otherwise controller will return
4171 		 * COMMAND_DISALLOWED for extended commands.
4172 		 */
4173 		return __hci_cmd_sync_status(hdev,
4174 					       HCI_OP_LE_READ_ADV_TX_POWER,
4175 					       0, NULL, HCI_CMD_TIMEOUT);
4176 	}
4177 
4178 	return 0;
4179 }
4180 
4181 /* Read LE Min/Max Tx Power*/
4182 static int hci_le_read_tx_power_sync(struct hci_dev *hdev)
4183 {
4184 	if (!(hdev->commands[38] & 0x80) ||
4185 	    test_bit(HCI_QUIRK_BROKEN_READ_TRANSMIT_POWER, &hdev->quirks))
4186 		return 0;
4187 
4188 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_TRANSMIT_POWER,
4189 				     0, NULL, HCI_CMD_TIMEOUT);
4190 }
4191 
4192 /* Read LE Accept List Size */
4193 static int hci_le_read_accept_list_size_sync(struct hci_dev *hdev)
4194 {
4195 	if (!(hdev->commands[26] & 0x40))
4196 		return 0;
4197 
4198 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_ACCEPT_LIST_SIZE,
4199 				     0, NULL, HCI_CMD_TIMEOUT);
4200 }
4201 
4202 /* Clear LE Accept List */
4203 static int hci_le_clear_accept_list_sync(struct hci_dev *hdev)
4204 {
4205 	if (!(hdev->commands[26] & 0x80))
4206 		return 0;
4207 
4208 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CLEAR_ACCEPT_LIST, 0, NULL,
4209 				     HCI_CMD_TIMEOUT);
4210 }
4211 
4212 /* Read LE Resolving List Size */
4213 static int hci_le_read_resolv_list_size_sync(struct hci_dev *hdev)
4214 {
4215 	if (!(hdev->commands[34] & 0x40))
4216 		return 0;
4217 
4218 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_RESOLV_LIST_SIZE,
4219 				     0, NULL, HCI_CMD_TIMEOUT);
4220 }
4221 
4222 /* Clear LE Resolving List */
4223 static int hci_le_clear_resolv_list_sync(struct hci_dev *hdev)
4224 {
4225 	if (!(hdev->commands[34] & 0x20))
4226 		return 0;
4227 
4228 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CLEAR_RESOLV_LIST, 0, NULL,
4229 				     HCI_CMD_TIMEOUT);
4230 }
4231 
4232 /* Set RPA timeout */
4233 static int hci_le_set_rpa_timeout_sync(struct hci_dev *hdev)
4234 {
4235 	__le16 timeout = cpu_to_le16(hdev->rpa_timeout);
4236 
4237 	if (!(hdev->commands[35] & 0x04) ||
4238 	    test_bit(HCI_QUIRK_BROKEN_SET_RPA_TIMEOUT, &hdev->quirks))
4239 		return 0;
4240 
4241 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_RPA_TIMEOUT,
4242 				     sizeof(timeout), &timeout,
4243 				     HCI_CMD_TIMEOUT);
4244 }
4245 
4246 /* Read LE Maximum Data Length */
4247 static int hci_le_read_max_data_len_sync(struct hci_dev *hdev)
4248 {
4249 	if (!(hdev->le_features[0] & HCI_LE_DATA_LEN_EXT))
4250 		return 0;
4251 
4252 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_MAX_DATA_LEN, 0, NULL,
4253 				     HCI_CMD_TIMEOUT);
4254 }
4255 
4256 /* Read LE Suggested Default Data Length */
4257 static int hci_le_read_def_data_len_sync(struct hci_dev *hdev)
4258 {
4259 	if (!(hdev->le_features[0] & HCI_LE_DATA_LEN_EXT))
4260 		return 0;
4261 
4262 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_READ_DEF_DATA_LEN, 0, NULL,
4263 				     HCI_CMD_TIMEOUT);
4264 }
4265 
4266 /* Read LE Number of Supported Advertising Sets */
4267 static int hci_le_read_num_support_adv_sets_sync(struct hci_dev *hdev)
4268 {
4269 	if (!ext_adv_capable(hdev))
4270 		return 0;
4271 
4272 	return __hci_cmd_sync_status(hdev,
4273 				     HCI_OP_LE_READ_NUM_SUPPORTED_ADV_SETS,
4274 				     0, NULL, HCI_CMD_TIMEOUT);
4275 }
4276 
4277 /* Write LE Host Supported */
4278 static int hci_set_le_support_sync(struct hci_dev *hdev)
4279 {
4280 	struct hci_cp_write_le_host_supported cp;
4281 
4282 	/* LE-only devices do not support explicit enablement */
4283 	if (!lmp_bredr_capable(hdev))
4284 		return 0;
4285 
4286 	memset(&cp, 0, sizeof(cp));
4287 
4288 	if (hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
4289 		cp.le = 0x01;
4290 		cp.simul = 0x00;
4291 	}
4292 
4293 	if (cp.le == lmp_host_le_capable(hdev))
4294 		return 0;
4295 
4296 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_LE_HOST_SUPPORTED,
4297 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4298 }
4299 
4300 /* LE Set Host Feature */
4301 static int hci_le_set_host_feature_sync(struct hci_dev *hdev)
4302 {
4303 	struct hci_cp_le_set_host_feature cp;
4304 
4305 	if (!iso_capable(hdev))
4306 		return 0;
4307 
4308 	memset(&cp, 0, sizeof(cp));
4309 
4310 	/* Isochronous Channels (Host Support) */
4311 	cp.bit_number = 32;
4312 	cp.bit_value = 1;
4313 
4314 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_HOST_FEATURE,
4315 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4316 }
4317 
4318 /* LE Controller init stage 3 command sequence */
4319 static const struct hci_init_stage le_init3[] = {
4320 	/* HCI_OP_LE_SET_EVENT_MASK */
4321 	HCI_INIT(hci_le_set_event_mask_sync),
4322 	/* HCI_OP_LE_READ_ADV_TX_POWER */
4323 	HCI_INIT(hci_le_read_adv_tx_power_sync),
4324 	/* HCI_OP_LE_READ_TRANSMIT_POWER */
4325 	HCI_INIT(hci_le_read_tx_power_sync),
4326 	/* HCI_OP_LE_READ_ACCEPT_LIST_SIZE */
4327 	HCI_INIT(hci_le_read_accept_list_size_sync),
4328 	/* HCI_OP_LE_CLEAR_ACCEPT_LIST */
4329 	HCI_INIT(hci_le_clear_accept_list_sync),
4330 	/* HCI_OP_LE_READ_RESOLV_LIST_SIZE */
4331 	HCI_INIT(hci_le_read_resolv_list_size_sync),
4332 	/* HCI_OP_LE_CLEAR_RESOLV_LIST */
4333 	HCI_INIT(hci_le_clear_resolv_list_sync),
4334 	/* HCI_OP_LE_SET_RPA_TIMEOUT */
4335 	HCI_INIT(hci_le_set_rpa_timeout_sync),
4336 	/* HCI_OP_LE_READ_MAX_DATA_LEN */
4337 	HCI_INIT(hci_le_read_max_data_len_sync),
4338 	/* HCI_OP_LE_READ_DEF_DATA_LEN */
4339 	HCI_INIT(hci_le_read_def_data_len_sync),
4340 	/* HCI_OP_LE_READ_NUM_SUPPORTED_ADV_SETS */
4341 	HCI_INIT(hci_le_read_num_support_adv_sets_sync),
4342 	/* HCI_OP_WRITE_LE_HOST_SUPPORTED */
4343 	HCI_INIT(hci_set_le_support_sync),
4344 	/* HCI_OP_LE_SET_HOST_FEATURE */
4345 	HCI_INIT(hci_le_set_host_feature_sync),
4346 	{}
4347 };
4348 
4349 static int hci_init3_sync(struct hci_dev *hdev)
4350 {
4351 	int err;
4352 
4353 	bt_dev_dbg(hdev, "");
4354 
4355 	err = hci_init_stage_sync(hdev, hci_init3);
4356 	if (err)
4357 		return err;
4358 
4359 	if (lmp_le_capable(hdev))
4360 		return hci_init_stage_sync(hdev, le_init3);
4361 
4362 	return 0;
4363 }
4364 
4365 static int hci_delete_stored_link_key_sync(struct hci_dev *hdev)
4366 {
4367 	struct hci_cp_delete_stored_link_key cp;
4368 
4369 	/* Some Broadcom based Bluetooth controllers do not support the
4370 	 * Delete Stored Link Key command. They are clearly indicating its
4371 	 * absence in the bit mask of supported commands.
4372 	 *
4373 	 * Check the supported commands and only if the command is marked
4374 	 * as supported send it. If not supported assume that the controller
4375 	 * does not have actual support for stored link keys which makes this
4376 	 * command redundant anyway.
4377 	 *
4378 	 * Some controllers indicate that they support handling deleting
4379 	 * stored link keys, but they don't. The quirk lets a driver
4380 	 * just disable this command.
4381 	 */
4382 	if (!(hdev->commands[6] & 0x80) ||
4383 	    test_bit(HCI_QUIRK_BROKEN_STORED_LINK_KEY, &hdev->quirks))
4384 		return 0;
4385 
4386 	memset(&cp, 0, sizeof(cp));
4387 	bacpy(&cp.bdaddr, BDADDR_ANY);
4388 	cp.delete_all = 0x01;
4389 
4390 	return __hci_cmd_sync_status(hdev, HCI_OP_DELETE_STORED_LINK_KEY,
4391 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4392 }
4393 
4394 static int hci_set_event_mask_page_2_sync(struct hci_dev *hdev)
4395 {
4396 	u8 events[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
4397 	bool changed = false;
4398 
4399 	/* Set event mask page 2 if the HCI command for it is supported */
4400 	if (!(hdev->commands[22] & 0x04))
4401 		return 0;
4402 
4403 	/* If Connectionless Peripheral Broadcast central role is supported
4404 	 * enable all necessary events for it.
4405 	 */
4406 	if (lmp_cpb_central_capable(hdev)) {
4407 		events[1] |= 0x40;	/* Triggered Clock Capture */
4408 		events[1] |= 0x80;	/* Synchronization Train Complete */
4409 		events[2] |= 0x08;	/* Truncated Page Complete */
4410 		events[2] |= 0x20;	/* CPB Channel Map Change */
4411 		changed = true;
4412 	}
4413 
4414 	/* If Connectionless Peripheral Broadcast peripheral role is supported
4415 	 * enable all necessary events for it.
4416 	 */
4417 	if (lmp_cpb_peripheral_capable(hdev)) {
4418 		events[2] |= 0x01;	/* Synchronization Train Received */
4419 		events[2] |= 0x02;	/* CPB Receive */
4420 		events[2] |= 0x04;	/* CPB Timeout */
4421 		events[2] |= 0x10;	/* Peripheral Page Response Timeout */
4422 		changed = true;
4423 	}
4424 
4425 	/* Enable Authenticated Payload Timeout Expired event if supported */
4426 	if (lmp_ping_capable(hdev) || hdev->le_features[0] & HCI_LE_PING) {
4427 		events[2] |= 0x80;
4428 		changed = true;
4429 	}
4430 
4431 	/* Some Broadcom based controllers indicate support for Set Event
4432 	 * Mask Page 2 command, but then actually do not support it. Since
4433 	 * the default value is all bits set to zero, the command is only
4434 	 * required if the event mask has to be changed. In case no change
4435 	 * to the event mask is needed, skip this command.
4436 	 */
4437 	if (!changed)
4438 		return 0;
4439 
4440 	return __hci_cmd_sync_status(hdev, HCI_OP_SET_EVENT_MASK_PAGE_2,
4441 				     sizeof(events), events, HCI_CMD_TIMEOUT);
4442 }
4443 
4444 /* Read local codec list if the HCI command is supported */
4445 static int hci_read_local_codecs_sync(struct hci_dev *hdev)
4446 {
4447 	if (hdev->commands[45] & 0x04)
4448 		hci_read_supported_codecs_v2(hdev);
4449 	else if (hdev->commands[29] & 0x20)
4450 		hci_read_supported_codecs(hdev);
4451 
4452 	return 0;
4453 }
4454 
4455 /* Read local pairing options if the HCI command is supported */
4456 static int hci_read_local_pairing_opts_sync(struct hci_dev *hdev)
4457 {
4458 	if (!(hdev->commands[41] & 0x08))
4459 		return 0;
4460 
4461 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_LOCAL_PAIRING_OPTS,
4462 				     0, NULL, HCI_CMD_TIMEOUT);
4463 }
4464 
4465 /* Get MWS transport configuration if the HCI command is supported */
4466 static int hci_get_mws_transport_config_sync(struct hci_dev *hdev)
4467 {
4468 	if (!mws_transport_config_capable(hdev))
4469 		return 0;
4470 
4471 	return __hci_cmd_sync_status(hdev, HCI_OP_GET_MWS_TRANSPORT_CONFIG,
4472 				     0, NULL, HCI_CMD_TIMEOUT);
4473 }
4474 
4475 /* Check for Synchronization Train support */
4476 static int hci_read_sync_train_params_sync(struct hci_dev *hdev)
4477 {
4478 	if (!lmp_sync_train_capable(hdev))
4479 		return 0;
4480 
4481 	return __hci_cmd_sync_status(hdev, HCI_OP_READ_SYNC_TRAIN_PARAMS,
4482 				     0, NULL, HCI_CMD_TIMEOUT);
4483 }
4484 
4485 /* Enable Secure Connections if supported and configured */
4486 static int hci_write_sc_support_1_sync(struct hci_dev *hdev)
4487 {
4488 	u8 support = 0x01;
4489 
4490 	if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED) ||
4491 	    !bredr_sc_enabled(hdev))
4492 		return 0;
4493 
4494 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_SC_SUPPORT,
4495 				     sizeof(support), &support,
4496 				     HCI_CMD_TIMEOUT);
4497 }
4498 
4499 /* Set erroneous data reporting if supported to the wideband speech
4500  * setting value
4501  */
4502 static int hci_set_err_data_report_sync(struct hci_dev *hdev)
4503 {
4504 	struct hci_cp_write_def_err_data_reporting cp;
4505 	bool enabled = hci_dev_test_flag(hdev, HCI_WIDEBAND_SPEECH_ENABLED);
4506 
4507 	if (!(hdev->commands[18] & 0x08) ||
4508 	    !(hdev->features[0][6] & LMP_ERR_DATA_REPORTING) ||
4509 	    test_bit(HCI_QUIRK_BROKEN_ERR_DATA_REPORTING, &hdev->quirks))
4510 		return 0;
4511 
4512 	if (enabled == hdev->err_data_reporting)
4513 		return 0;
4514 
4515 	memset(&cp, 0, sizeof(cp));
4516 	cp.err_data_reporting = enabled ? ERR_DATA_REPORTING_ENABLED :
4517 				ERR_DATA_REPORTING_DISABLED;
4518 
4519 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_DEF_ERR_DATA_REPORTING,
4520 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4521 }
4522 
4523 static const struct hci_init_stage hci_init4[] = {
4524 	 /* HCI_OP_DELETE_STORED_LINK_KEY */
4525 	HCI_INIT(hci_delete_stored_link_key_sync),
4526 	/* HCI_OP_SET_EVENT_MASK_PAGE_2 */
4527 	HCI_INIT(hci_set_event_mask_page_2_sync),
4528 	/* HCI_OP_READ_LOCAL_CODECS */
4529 	HCI_INIT(hci_read_local_codecs_sync),
4530 	 /* HCI_OP_READ_LOCAL_PAIRING_OPTS */
4531 	HCI_INIT(hci_read_local_pairing_opts_sync),
4532 	 /* HCI_OP_GET_MWS_TRANSPORT_CONFIG */
4533 	HCI_INIT(hci_get_mws_transport_config_sync),
4534 	 /* HCI_OP_READ_SYNC_TRAIN_PARAMS */
4535 	HCI_INIT(hci_read_sync_train_params_sync),
4536 	/* HCI_OP_WRITE_SC_SUPPORT */
4537 	HCI_INIT(hci_write_sc_support_1_sync),
4538 	/* HCI_OP_WRITE_DEF_ERR_DATA_REPORTING */
4539 	HCI_INIT(hci_set_err_data_report_sync),
4540 	{}
4541 };
4542 
4543 /* Set Suggested Default Data Length to maximum if supported */
4544 static int hci_le_set_write_def_data_len_sync(struct hci_dev *hdev)
4545 {
4546 	struct hci_cp_le_write_def_data_len cp;
4547 
4548 	if (!(hdev->le_features[0] & HCI_LE_DATA_LEN_EXT))
4549 		return 0;
4550 
4551 	memset(&cp, 0, sizeof(cp));
4552 	cp.tx_len = cpu_to_le16(hdev->le_max_tx_len);
4553 	cp.tx_time = cpu_to_le16(hdev->le_max_tx_time);
4554 
4555 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_WRITE_DEF_DATA_LEN,
4556 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4557 }
4558 
4559 /* Set Default PHY parameters if command is supported, enables all supported
4560  * PHYs according to the LE Features bits.
4561  */
4562 static int hci_le_set_default_phy_sync(struct hci_dev *hdev)
4563 {
4564 	struct hci_cp_le_set_default_phy cp;
4565 
4566 	if (!(hdev->commands[35] & 0x20)) {
4567 		/* If the command is not supported it means only 1M PHY is
4568 		 * supported.
4569 		 */
4570 		hdev->le_tx_def_phys = HCI_LE_SET_PHY_1M;
4571 		hdev->le_rx_def_phys = HCI_LE_SET_PHY_1M;
4572 		return 0;
4573 	}
4574 
4575 	memset(&cp, 0, sizeof(cp));
4576 	cp.all_phys = 0x00;
4577 	cp.tx_phys = HCI_LE_SET_PHY_1M;
4578 	cp.rx_phys = HCI_LE_SET_PHY_1M;
4579 
4580 	/* Enables 2M PHY if supported */
4581 	if (le_2m_capable(hdev)) {
4582 		cp.tx_phys |= HCI_LE_SET_PHY_2M;
4583 		cp.rx_phys |= HCI_LE_SET_PHY_2M;
4584 	}
4585 
4586 	/* Enables Coded PHY if supported */
4587 	if (le_coded_capable(hdev)) {
4588 		cp.tx_phys |= HCI_LE_SET_PHY_CODED;
4589 		cp.rx_phys |= HCI_LE_SET_PHY_CODED;
4590 	}
4591 
4592 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_DEFAULT_PHY,
4593 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
4594 }
4595 
4596 static const struct hci_init_stage le_init4[] = {
4597 	/* HCI_OP_LE_WRITE_DEF_DATA_LEN */
4598 	HCI_INIT(hci_le_set_write_def_data_len_sync),
4599 	/* HCI_OP_LE_SET_DEFAULT_PHY */
4600 	HCI_INIT(hci_le_set_default_phy_sync),
4601 	{}
4602 };
4603 
4604 static int hci_init4_sync(struct hci_dev *hdev)
4605 {
4606 	int err;
4607 
4608 	bt_dev_dbg(hdev, "");
4609 
4610 	err = hci_init_stage_sync(hdev, hci_init4);
4611 	if (err)
4612 		return err;
4613 
4614 	if (lmp_le_capable(hdev))
4615 		return hci_init_stage_sync(hdev, le_init4);
4616 
4617 	return 0;
4618 }
4619 
4620 static int hci_init_sync(struct hci_dev *hdev)
4621 {
4622 	int err;
4623 
4624 	err = hci_init1_sync(hdev);
4625 	if (err < 0)
4626 		return err;
4627 
4628 	if (hci_dev_test_flag(hdev, HCI_SETUP))
4629 		hci_debugfs_create_basic(hdev);
4630 
4631 	err = hci_init2_sync(hdev);
4632 	if (err < 0)
4633 		return err;
4634 
4635 	err = hci_init3_sync(hdev);
4636 	if (err < 0)
4637 		return err;
4638 
4639 	err = hci_init4_sync(hdev);
4640 	if (err < 0)
4641 		return err;
4642 
4643 	/* This function is only called when the controller is actually in
4644 	 * configured state. When the controller is marked as unconfigured,
4645 	 * this initialization procedure is not run.
4646 	 *
4647 	 * It means that it is possible that a controller runs through its
4648 	 * setup phase and then discovers missing settings. If that is the
4649 	 * case, then this function will not be called. It then will only
4650 	 * be called during the config phase.
4651 	 *
4652 	 * So only when in setup phase or config phase, create the debugfs
4653 	 * entries and register the SMP channels.
4654 	 */
4655 	if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
4656 	    !hci_dev_test_flag(hdev, HCI_CONFIG))
4657 		return 0;
4658 
4659 	if (hci_dev_test_and_set_flag(hdev, HCI_DEBUGFS_CREATED))
4660 		return 0;
4661 
4662 	hci_debugfs_create_common(hdev);
4663 
4664 	if (lmp_bredr_capable(hdev))
4665 		hci_debugfs_create_bredr(hdev);
4666 
4667 	if (lmp_le_capable(hdev))
4668 		hci_debugfs_create_le(hdev);
4669 
4670 	return 0;
4671 }
4672 
4673 #define HCI_QUIRK_BROKEN(_quirk, _desc) { HCI_QUIRK_BROKEN_##_quirk, _desc }
4674 
4675 static const struct {
4676 	unsigned long quirk;
4677 	const char *desc;
4678 } hci_broken_table[] = {
4679 	HCI_QUIRK_BROKEN(LOCAL_COMMANDS,
4680 			 "HCI Read Local Supported Commands not supported"),
4681 	HCI_QUIRK_BROKEN(STORED_LINK_KEY,
4682 			 "HCI Delete Stored Link Key command is advertised, "
4683 			 "but not supported."),
4684 	HCI_QUIRK_BROKEN(ERR_DATA_REPORTING,
4685 			 "HCI Read Default Erroneous Data Reporting command is "
4686 			 "advertised, but not supported."),
4687 	HCI_QUIRK_BROKEN(READ_TRANSMIT_POWER,
4688 			 "HCI Read Transmit Power Level command is advertised, "
4689 			 "but not supported."),
4690 	HCI_QUIRK_BROKEN(FILTER_CLEAR_ALL,
4691 			 "HCI Set Event Filter command not supported."),
4692 	HCI_QUIRK_BROKEN(ENHANCED_SETUP_SYNC_CONN,
4693 			 "HCI Enhanced Setup Synchronous Connection command is "
4694 			 "advertised, but not supported."),
4695 	HCI_QUIRK_BROKEN(SET_RPA_TIMEOUT,
4696 			 "HCI LE Set Random Private Address Timeout command is "
4697 			 "advertised, but not supported."),
4698 	HCI_QUIRK_BROKEN(LE_CODED,
4699 			 "HCI LE Coded PHY feature bit is set, "
4700 			 "but its usage is not supported.")
4701 };
4702 
4703 /* This function handles hdev setup stage:
4704  *
4705  * Calls hdev->setup
4706  * Setup address if HCI_QUIRK_USE_BDADDR_PROPERTY is set.
4707  */
4708 static int hci_dev_setup_sync(struct hci_dev *hdev)
4709 {
4710 	int ret = 0;
4711 	bool invalid_bdaddr;
4712 	size_t i;
4713 
4714 	if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
4715 	    !test_bit(HCI_QUIRK_NON_PERSISTENT_SETUP, &hdev->quirks))
4716 		return 0;
4717 
4718 	bt_dev_dbg(hdev, "");
4719 
4720 	hci_sock_dev_event(hdev, HCI_DEV_SETUP);
4721 
4722 	if (hdev->setup)
4723 		ret = hdev->setup(hdev);
4724 
4725 	for (i = 0; i < ARRAY_SIZE(hci_broken_table); i++) {
4726 		if (test_bit(hci_broken_table[i].quirk, &hdev->quirks))
4727 			bt_dev_warn(hdev, "%s", hci_broken_table[i].desc);
4728 	}
4729 
4730 	/* The transport driver can set the quirk to mark the
4731 	 * BD_ADDR invalid before creating the HCI device or in
4732 	 * its setup callback.
4733 	 */
4734 	invalid_bdaddr = test_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks) ||
4735 			 test_bit(HCI_QUIRK_USE_BDADDR_PROPERTY, &hdev->quirks);
4736 	if (!ret) {
4737 		if (test_bit(HCI_QUIRK_USE_BDADDR_PROPERTY, &hdev->quirks) &&
4738 		    !bacmp(&hdev->public_addr, BDADDR_ANY))
4739 			hci_dev_get_bd_addr_from_property(hdev);
4740 
4741 		if (invalid_bdaddr && bacmp(&hdev->public_addr, BDADDR_ANY) &&
4742 		    hdev->set_bdaddr) {
4743 			ret = hdev->set_bdaddr(hdev, &hdev->public_addr);
4744 			if (!ret)
4745 				invalid_bdaddr = false;
4746 		}
4747 	}
4748 
4749 	/* The transport driver can set these quirks before
4750 	 * creating the HCI device or in its setup callback.
4751 	 *
4752 	 * For the invalid BD_ADDR quirk it is possible that
4753 	 * it becomes a valid address if the bootloader does
4754 	 * provide it (see above).
4755 	 *
4756 	 * In case any of them is set, the controller has to
4757 	 * start up as unconfigured.
4758 	 */
4759 	if (test_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks) ||
4760 	    invalid_bdaddr)
4761 		hci_dev_set_flag(hdev, HCI_UNCONFIGURED);
4762 
4763 	/* For an unconfigured controller it is required to
4764 	 * read at least the version information provided by
4765 	 * the Read Local Version Information command.
4766 	 *
4767 	 * If the set_bdaddr driver callback is provided, then
4768 	 * also the original Bluetooth public device address
4769 	 * will be read using the Read BD Address command.
4770 	 */
4771 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
4772 		return hci_unconf_init_sync(hdev);
4773 
4774 	return ret;
4775 }
4776 
4777 /* This function handles hdev init stage:
4778  *
4779  * Calls hci_dev_setup_sync to perform setup stage
4780  * Calls hci_init_sync to perform HCI command init sequence
4781  */
4782 static int hci_dev_init_sync(struct hci_dev *hdev)
4783 {
4784 	int ret;
4785 
4786 	bt_dev_dbg(hdev, "");
4787 
4788 	atomic_set(&hdev->cmd_cnt, 1);
4789 	set_bit(HCI_INIT, &hdev->flags);
4790 
4791 	ret = hci_dev_setup_sync(hdev);
4792 
4793 	if (hci_dev_test_flag(hdev, HCI_CONFIG)) {
4794 		/* If public address change is configured, ensure that
4795 		 * the address gets programmed. If the driver does not
4796 		 * support changing the public address, fail the power
4797 		 * on procedure.
4798 		 */
4799 		if (bacmp(&hdev->public_addr, BDADDR_ANY) &&
4800 		    hdev->set_bdaddr)
4801 			ret = hdev->set_bdaddr(hdev, &hdev->public_addr);
4802 		else
4803 			ret = -EADDRNOTAVAIL;
4804 	}
4805 
4806 	if (!ret) {
4807 		if (!hci_dev_test_flag(hdev, HCI_UNCONFIGURED) &&
4808 		    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
4809 			ret = hci_init_sync(hdev);
4810 			if (!ret && hdev->post_init)
4811 				ret = hdev->post_init(hdev);
4812 		}
4813 	}
4814 
4815 	/* If the HCI Reset command is clearing all diagnostic settings,
4816 	 * then they need to be reprogrammed after the init procedure
4817 	 * completed.
4818 	 */
4819 	if (test_bit(HCI_QUIRK_NON_PERSISTENT_DIAG, &hdev->quirks) &&
4820 	    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
4821 	    hci_dev_test_flag(hdev, HCI_VENDOR_DIAG) && hdev->set_diag)
4822 		ret = hdev->set_diag(hdev, true);
4823 
4824 	if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
4825 		msft_do_open(hdev);
4826 		aosp_do_open(hdev);
4827 	}
4828 
4829 	clear_bit(HCI_INIT, &hdev->flags);
4830 
4831 	return ret;
4832 }
4833 
4834 int hci_dev_open_sync(struct hci_dev *hdev)
4835 {
4836 	int ret;
4837 
4838 	bt_dev_dbg(hdev, "");
4839 
4840 	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
4841 		ret = -ENODEV;
4842 		goto done;
4843 	}
4844 
4845 	if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
4846 	    !hci_dev_test_flag(hdev, HCI_CONFIG)) {
4847 		/* Check for rfkill but allow the HCI setup stage to
4848 		 * proceed (which in itself doesn't cause any RF activity).
4849 		 */
4850 		if (hci_dev_test_flag(hdev, HCI_RFKILLED)) {
4851 			ret = -ERFKILL;
4852 			goto done;
4853 		}
4854 
4855 		/* Check for valid public address or a configured static
4856 		 * random address, but let the HCI setup proceed to
4857 		 * be able to determine if there is a public address
4858 		 * or not.
4859 		 *
4860 		 * In case of user channel usage, it is not important
4861 		 * if a public address or static random address is
4862 		 * available.
4863 		 */
4864 		if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
4865 		    !bacmp(&hdev->bdaddr, BDADDR_ANY) &&
4866 		    !bacmp(&hdev->static_addr, BDADDR_ANY)) {
4867 			ret = -EADDRNOTAVAIL;
4868 			goto done;
4869 		}
4870 	}
4871 
4872 	if (test_bit(HCI_UP, &hdev->flags)) {
4873 		ret = -EALREADY;
4874 		goto done;
4875 	}
4876 
4877 	if (hdev->open(hdev)) {
4878 		ret = -EIO;
4879 		goto done;
4880 	}
4881 
4882 	hci_devcd_reset(hdev);
4883 
4884 	set_bit(HCI_RUNNING, &hdev->flags);
4885 	hci_sock_dev_event(hdev, HCI_DEV_OPEN);
4886 
4887 	ret = hci_dev_init_sync(hdev);
4888 	if (!ret) {
4889 		hci_dev_hold(hdev);
4890 		hci_dev_set_flag(hdev, HCI_RPA_EXPIRED);
4891 		hci_adv_instances_set_rpa_expired(hdev, true);
4892 		set_bit(HCI_UP, &hdev->flags);
4893 		hci_sock_dev_event(hdev, HCI_DEV_UP);
4894 		hci_leds_update_powered(hdev, true);
4895 		if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
4896 		    !hci_dev_test_flag(hdev, HCI_CONFIG) &&
4897 		    !hci_dev_test_flag(hdev, HCI_UNCONFIGURED) &&
4898 		    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
4899 		    hci_dev_test_flag(hdev, HCI_MGMT)) {
4900 			ret = hci_powered_update_sync(hdev);
4901 			mgmt_power_on(hdev, ret);
4902 		}
4903 	} else {
4904 		/* Init failed, cleanup */
4905 		flush_work(&hdev->tx_work);
4906 
4907 		/* Since hci_rx_work() is possible to awake new cmd_work
4908 		 * it should be flushed first to avoid unexpected call of
4909 		 * hci_cmd_work()
4910 		 */
4911 		flush_work(&hdev->rx_work);
4912 		flush_work(&hdev->cmd_work);
4913 
4914 		skb_queue_purge(&hdev->cmd_q);
4915 		skb_queue_purge(&hdev->rx_q);
4916 
4917 		if (hdev->flush)
4918 			hdev->flush(hdev);
4919 
4920 		if (hdev->sent_cmd) {
4921 			cancel_delayed_work_sync(&hdev->cmd_timer);
4922 			kfree_skb(hdev->sent_cmd);
4923 			hdev->sent_cmd = NULL;
4924 		}
4925 
4926 		if (hdev->req_skb) {
4927 			kfree_skb(hdev->req_skb);
4928 			hdev->req_skb = NULL;
4929 		}
4930 
4931 		clear_bit(HCI_RUNNING, &hdev->flags);
4932 		hci_sock_dev_event(hdev, HCI_DEV_CLOSE);
4933 
4934 		hdev->close(hdev);
4935 		hdev->flags &= BIT(HCI_RAW);
4936 	}
4937 
4938 done:
4939 	return ret;
4940 }
4941 
4942 /* This function requires the caller holds hdev->lock */
4943 static void hci_pend_le_actions_clear(struct hci_dev *hdev)
4944 {
4945 	struct hci_conn_params *p;
4946 
4947 	list_for_each_entry(p, &hdev->le_conn_params, list) {
4948 		hci_pend_le_list_del_init(p);
4949 		if (p->conn) {
4950 			hci_conn_drop(p->conn);
4951 			hci_conn_put(p->conn);
4952 			p->conn = NULL;
4953 		}
4954 	}
4955 
4956 	BT_DBG("All LE pending actions cleared");
4957 }
4958 
4959 static int hci_dev_shutdown(struct hci_dev *hdev)
4960 {
4961 	int err = 0;
4962 	/* Similar to how we first do setup and then set the exclusive access
4963 	 * bit for userspace, we must first unset userchannel and then clean up.
4964 	 * Otherwise, the kernel can't properly use the hci channel to clean up
4965 	 * the controller (some shutdown routines require sending additional
4966 	 * commands to the controller for example).
4967 	 */
4968 	bool was_userchannel =
4969 		hci_dev_test_and_clear_flag(hdev, HCI_USER_CHANNEL);
4970 
4971 	if (!hci_dev_test_flag(hdev, HCI_UNREGISTER) &&
4972 	    test_bit(HCI_UP, &hdev->flags)) {
4973 		/* Execute vendor specific shutdown routine */
4974 		if (hdev->shutdown)
4975 			err = hdev->shutdown(hdev);
4976 	}
4977 
4978 	if (was_userchannel)
4979 		hci_dev_set_flag(hdev, HCI_USER_CHANNEL);
4980 
4981 	return err;
4982 }
4983 
4984 int hci_dev_close_sync(struct hci_dev *hdev)
4985 {
4986 	bool auto_off;
4987 	int err = 0;
4988 
4989 	bt_dev_dbg(hdev, "");
4990 
4991 	cancel_delayed_work(&hdev->power_off);
4992 	cancel_delayed_work(&hdev->ncmd_timer);
4993 	cancel_delayed_work(&hdev->le_scan_disable);
4994 	cancel_delayed_work(&hdev->le_scan_restart);
4995 
4996 	hci_request_cancel_all(hdev);
4997 
4998 	if (hdev->adv_instance_timeout) {
4999 		cancel_delayed_work_sync(&hdev->adv_instance_expire);
5000 		hdev->adv_instance_timeout = 0;
5001 	}
5002 
5003 	err = hci_dev_shutdown(hdev);
5004 
5005 	if (!test_and_clear_bit(HCI_UP, &hdev->flags)) {
5006 		cancel_delayed_work_sync(&hdev->cmd_timer);
5007 		return err;
5008 	}
5009 
5010 	hci_leds_update_powered(hdev, false);
5011 
5012 	/* Flush RX and TX works */
5013 	flush_work(&hdev->tx_work);
5014 	flush_work(&hdev->rx_work);
5015 
5016 	if (hdev->discov_timeout > 0) {
5017 		hdev->discov_timeout = 0;
5018 		hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
5019 		hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
5020 	}
5021 
5022 	if (hci_dev_test_and_clear_flag(hdev, HCI_SERVICE_CACHE))
5023 		cancel_delayed_work(&hdev->service_cache);
5024 
5025 	if (hci_dev_test_flag(hdev, HCI_MGMT)) {
5026 		struct adv_info *adv_instance;
5027 
5028 		cancel_delayed_work_sync(&hdev->rpa_expired);
5029 
5030 		list_for_each_entry(adv_instance, &hdev->adv_instances, list)
5031 			cancel_delayed_work_sync(&adv_instance->rpa_expired_cb);
5032 	}
5033 
5034 	/* Avoid potential lockdep warnings from the *_flush() calls by
5035 	 * ensuring the workqueue is empty up front.
5036 	 */
5037 	drain_workqueue(hdev->workqueue);
5038 
5039 	hci_dev_lock(hdev);
5040 
5041 	hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
5042 
5043 	auto_off = hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF);
5044 
5045 	if (!auto_off && !hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
5046 	    hci_dev_test_flag(hdev, HCI_MGMT))
5047 		__mgmt_power_off(hdev);
5048 
5049 	hci_inquiry_cache_flush(hdev);
5050 	hci_pend_le_actions_clear(hdev);
5051 	hci_conn_hash_flush(hdev);
5052 	/* Prevent data races on hdev->smp_data or hdev->smp_bredr_data */
5053 	smp_unregister(hdev);
5054 	hci_dev_unlock(hdev);
5055 
5056 	hci_sock_dev_event(hdev, HCI_DEV_DOWN);
5057 
5058 	if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
5059 		aosp_do_close(hdev);
5060 		msft_do_close(hdev);
5061 	}
5062 
5063 	if (hdev->flush)
5064 		hdev->flush(hdev);
5065 
5066 	/* Reset device */
5067 	skb_queue_purge(&hdev->cmd_q);
5068 	atomic_set(&hdev->cmd_cnt, 1);
5069 	if (test_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks) &&
5070 	    !auto_off && !hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
5071 		set_bit(HCI_INIT, &hdev->flags);
5072 		hci_reset_sync(hdev);
5073 		clear_bit(HCI_INIT, &hdev->flags);
5074 	}
5075 
5076 	/* flush cmd  work */
5077 	flush_work(&hdev->cmd_work);
5078 
5079 	/* Drop queues */
5080 	skb_queue_purge(&hdev->rx_q);
5081 	skb_queue_purge(&hdev->cmd_q);
5082 	skb_queue_purge(&hdev->raw_q);
5083 
5084 	/* Drop last sent command */
5085 	if (hdev->sent_cmd) {
5086 		cancel_delayed_work_sync(&hdev->cmd_timer);
5087 		kfree_skb(hdev->sent_cmd);
5088 		hdev->sent_cmd = NULL;
5089 	}
5090 
5091 	/* Drop last request */
5092 	if (hdev->req_skb) {
5093 		kfree_skb(hdev->req_skb);
5094 		hdev->req_skb = NULL;
5095 	}
5096 
5097 	clear_bit(HCI_RUNNING, &hdev->flags);
5098 	hci_sock_dev_event(hdev, HCI_DEV_CLOSE);
5099 
5100 	/* After this point our queues are empty and no tasks are scheduled. */
5101 	hdev->close(hdev);
5102 
5103 	/* Clear flags */
5104 	hdev->flags &= BIT(HCI_RAW);
5105 	hci_dev_clear_volatile_flags(hdev);
5106 
5107 	memset(hdev->eir, 0, sizeof(hdev->eir));
5108 	memset(hdev->dev_class, 0, sizeof(hdev->dev_class));
5109 	bacpy(&hdev->random_addr, BDADDR_ANY);
5110 	hci_codec_list_clear(&hdev->local_codecs);
5111 
5112 	hci_dev_put(hdev);
5113 	return err;
5114 }
5115 
5116 /* This function perform power on HCI command sequence as follows:
5117  *
5118  * If controller is already up (HCI_UP) performs hci_powered_update_sync
5119  * sequence otherwise run hci_dev_open_sync which will follow with
5120  * hci_powered_update_sync after the init sequence is completed.
5121  */
5122 static int hci_power_on_sync(struct hci_dev *hdev)
5123 {
5124 	int err;
5125 
5126 	if (test_bit(HCI_UP, &hdev->flags) &&
5127 	    hci_dev_test_flag(hdev, HCI_MGMT) &&
5128 	    hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF)) {
5129 		cancel_delayed_work(&hdev->power_off);
5130 		return hci_powered_update_sync(hdev);
5131 	}
5132 
5133 	err = hci_dev_open_sync(hdev);
5134 	if (err < 0)
5135 		return err;
5136 
5137 	/* During the HCI setup phase, a few error conditions are
5138 	 * ignored and they need to be checked now. If they are still
5139 	 * valid, it is important to return the device back off.
5140 	 */
5141 	if (hci_dev_test_flag(hdev, HCI_RFKILLED) ||
5142 	    hci_dev_test_flag(hdev, HCI_UNCONFIGURED) ||
5143 	    (!bacmp(&hdev->bdaddr, BDADDR_ANY) &&
5144 	     !bacmp(&hdev->static_addr, BDADDR_ANY))) {
5145 		hci_dev_clear_flag(hdev, HCI_AUTO_OFF);
5146 		hci_dev_close_sync(hdev);
5147 	} else if (hci_dev_test_flag(hdev, HCI_AUTO_OFF)) {
5148 		queue_delayed_work(hdev->req_workqueue, &hdev->power_off,
5149 				   HCI_AUTO_OFF_TIMEOUT);
5150 	}
5151 
5152 	if (hci_dev_test_and_clear_flag(hdev, HCI_SETUP)) {
5153 		/* For unconfigured devices, set the HCI_RAW flag
5154 		 * so that userspace can easily identify them.
5155 		 */
5156 		if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
5157 			set_bit(HCI_RAW, &hdev->flags);
5158 
5159 		/* For fully configured devices, this will send
5160 		 * the Index Added event. For unconfigured devices,
5161 		 * it will send Unconfigued Index Added event.
5162 		 *
5163 		 * Devices with HCI_QUIRK_RAW_DEVICE are ignored
5164 		 * and no event will be send.
5165 		 */
5166 		mgmt_index_added(hdev);
5167 	} else if (hci_dev_test_and_clear_flag(hdev, HCI_CONFIG)) {
5168 		/* When the controller is now configured, then it
5169 		 * is important to clear the HCI_RAW flag.
5170 		 */
5171 		if (!hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
5172 			clear_bit(HCI_RAW, &hdev->flags);
5173 
5174 		/* Powering on the controller with HCI_CONFIG set only
5175 		 * happens with the transition from unconfigured to
5176 		 * configured. This will send the Index Added event.
5177 		 */
5178 		mgmt_index_added(hdev);
5179 	}
5180 
5181 	return 0;
5182 }
5183 
5184 static int hci_remote_name_cancel_sync(struct hci_dev *hdev, bdaddr_t *addr)
5185 {
5186 	struct hci_cp_remote_name_req_cancel cp;
5187 
5188 	memset(&cp, 0, sizeof(cp));
5189 	bacpy(&cp.bdaddr, addr);
5190 
5191 	return __hci_cmd_sync_status(hdev, HCI_OP_REMOTE_NAME_REQ_CANCEL,
5192 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5193 }
5194 
5195 int hci_stop_discovery_sync(struct hci_dev *hdev)
5196 {
5197 	struct discovery_state *d = &hdev->discovery;
5198 	struct inquiry_entry *e;
5199 	int err;
5200 
5201 	bt_dev_dbg(hdev, "state %u", hdev->discovery.state);
5202 
5203 	if (d->state == DISCOVERY_FINDING || d->state == DISCOVERY_STOPPING) {
5204 		if (test_bit(HCI_INQUIRY, &hdev->flags)) {
5205 			err = __hci_cmd_sync_status(hdev, HCI_OP_INQUIRY_CANCEL,
5206 						    0, NULL, HCI_CMD_TIMEOUT);
5207 			if (err)
5208 				return err;
5209 		}
5210 
5211 		if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
5212 			cancel_delayed_work(&hdev->le_scan_disable);
5213 			cancel_delayed_work(&hdev->le_scan_restart);
5214 
5215 			err = hci_scan_disable_sync(hdev);
5216 			if (err)
5217 				return err;
5218 		}
5219 
5220 	} else {
5221 		err = hci_scan_disable_sync(hdev);
5222 		if (err)
5223 			return err;
5224 	}
5225 
5226 	/* Resume advertising if it was paused */
5227 	if (use_ll_privacy(hdev))
5228 		hci_resume_advertising_sync(hdev);
5229 
5230 	/* No further actions needed for LE-only discovery */
5231 	if (d->type == DISCOV_TYPE_LE)
5232 		return 0;
5233 
5234 	if (d->state == DISCOVERY_RESOLVING || d->state == DISCOVERY_STOPPING) {
5235 		e = hci_inquiry_cache_lookup_resolve(hdev, BDADDR_ANY,
5236 						     NAME_PENDING);
5237 		if (!e)
5238 			return 0;
5239 
5240 		return hci_remote_name_cancel_sync(hdev, &e->data.bdaddr);
5241 	}
5242 
5243 	return 0;
5244 }
5245 
5246 static int hci_disconnect_sync(struct hci_dev *hdev, struct hci_conn *conn,
5247 			       u8 reason)
5248 {
5249 	struct hci_cp_disconnect cp;
5250 
5251 	if (test_bit(HCI_CONN_BIG_CREATED, &conn->flags)) {
5252 		/* This is a BIS connection, hci_conn_del will
5253 		 * do the necessary cleanup.
5254 		 */
5255 		hci_dev_lock(hdev);
5256 		hci_conn_failed(conn, reason);
5257 		hci_dev_unlock(hdev);
5258 
5259 		return 0;
5260 	}
5261 
5262 	memset(&cp, 0, sizeof(cp));
5263 	cp.handle = cpu_to_le16(conn->handle);
5264 	cp.reason = reason;
5265 
5266 	/* Wait for HCI_EV_DISCONN_COMPLETE, not HCI_EV_CMD_STATUS, when the
5267 	 * reason is anything but HCI_ERROR_REMOTE_POWER_OFF. This reason is
5268 	 * used when suspending or powering off, where we don't want to wait
5269 	 * for the peer's response.
5270 	 */
5271 	if (reason != HCI_ERROR_REMOTE_POWER_OFF)
5272 		return __hci_cmd_sync_status_sk(hdev, HCI_OP_DISCONNECT,
5273 						sizeof(cp), &cp,
5274 						HCI_EV_DISCONN_COMPLETE,
5275 						HCI_CMD_TIMEOUT, NULL);
5276 
5277 	return __hci_cmd_sync_status(hdev, HCI_OP_DISCONNECT, sizeof(cp), &cp,
5278 				     HCI_CMD_TIMEOUT);
5279 }
5280 
5281 static int hci_le_connect_cancel_sync(struct hci_dev *hdev,
5282 				      struct hci_conn *conn, u8 reason)
5283 {
5284 	/* Return reason if scanning since the connection shall probably be
5285 	 * cleanup directly.
5286 	 */
5287 	if (test_bit(HCI_CONN_SCANNING, &conn->flags))
5288 		return reason;
5289 
5290 	if (conn->role == HCI_ROLE_SLAVE ||
5291 	    test_and_set_bit(HCI_CONN_CANCEL, &conn->flags))
5292 		return 0;
5293 
5294 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_CREATE_CONN_CANCEL,
5295 				     0, NULL, HCI_CMD_TIMEOUT);
5296 }
5297 
5298 static int hci_connect_cancel_sync(struct hci_dev *hdev, struct hci_conn *conn,
5299 				   u8 reason)
5300 {
5301 	if (conn->type == LE_LINK)
5302 		return hci_le_connect_cancel_sync(hdev, conn, reason);
5303 
5304 	if (conn->type == ISO_LINK) {
5305 		/* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
5306 		 * page 1857:
5307 		 *
5308 		 * If this command is issued for a CIS on the Central and the
5309 		 * CIS is successfully terminated before being established,
5310 		 * then an HCI_LE_CIS_Established event shall also be sent for
5311 		 * this CIS with the Status Operation Cancelled by Host (0x44).
5312 		 */
5313 		if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags))
5314 			return hci_disconnect_sync(hdev, conn, reason);
5315 
5316 		/* CIS with no Create CIS sent have nothing to cancel */
5317 		if (bacmp(&conn->dst, BDADDR_ANY))
5318 			return HCI_ERROR_LOCAL_HOST_TERM;
5319 
5320 		/* There is no way to cancel a BIS without terminating the BIG
5321 		 * which is done later on connection cleanup.
5322 		 */
5323 		return 0;
5324 	}
5325 
5326 	if (hdev->hci_ver < BLUETOOTH_VER_1_2)
5327 		return 0;
5328 
5329 	/* Wait for HCI_EV_CONN_COMPLETE, not HCI_EV_CMD_STATUS, when the
5330 	 * reason is anything but HCI_ERROR_REMOTE_POWER_OFF. This reason is
5331 	 * used when suspending or powering off, where we don't want to wait
5332 	 * for the peer's response.
5333 	 */
5334 	if (reason != HCI_ERROR_REMOTE_POWER_OFF)
5335 		return __hci_cmd_sync_status_sk(hdev, HCI_OP_CREATE_CONN_CANCEL,
5336 						6, &conn->dst,
5337 						HCI_EV_CONN_COMPLETE,
5338 						HCI_CMD_TIMEOUT, NULL);
5339 
5340 	return __hci_cmd_sync_status(hdev, HCI_OP_CREATE_CONN_CANCEL,
5341 				     6, &conn->dst, HCI_CMD_TIMEOUT);
5342 }
5343 
5344 static int hci_reject_sco_sync(struct hci_dev *hdev, struct hci_conn *conn,
5345 			       u8 reason)
5346 {
5347 	struct hci_cp_reject_sync_conn_req cp;
5348 
5349 	memset(&cp, 0, sizeof(cp));
5350 	bacpy(&cp.bdaddr, &conn->dst);
5351 	cp.reason = reason;
5352 
5353 	/* SCO rejection has its own limited set of
5354 	 * allowed error values (0x0D-0x0F).
5355 	 */
5356 	if (reason < 0x0d || reason > 0x0f)
5357 		cp.reason = HCI_ERROR_REJ_LIMITED_RESOURCES;
5358 
5359 	return __hci_cmd_sync_status(hdev, HCI_OP_REJECT_SYNC_CONN_REQ,
5360 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5361 }
5362 
5363 static int hci_le_reject_cis_sync(struct hci_dev *hdev, struct hci_conn *conn,
5364 				  u8 reason)
5365 {
5366 	struct hci_cp_le_reject_cis cp;
5367 
5368 	memset(&cp, 0, sizeof(cp));
5369 	cp.handle = cpu_to_le16(conn->handle);
5370 	cp.reason = reason;
5371 
5372 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_REJECT_CIS,
5373 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5374 }
5375 
5376 static int hci_reject_conn_sync(struct hci_dev *hdev, struct hci_conn *conn,
5377 				u8 reason)
5378 {
5379 	struct hci_cp_reject_conn_req cp;
5380 
5381 	if (conn->type == ISO_LINK)
5382 		return hci_le_reject_cis_sync(hdev, conn, reason);
5383 
5384 	if (conn->type == SCO_LINK || conn->type == ESCO_LINK)
5385 		return hci_reject_sco_sync(hdev, conn, reason);
5386 
5387 	memset(&cp, 0, sizeof(cp));
5388 	bacpy(&cp.bdaddr, &conn->dst);
5389 	cp.reason = reason;
5390 
5391 	return __hci_cmd_sync_status(hdev, HCI_OP_REJECT_CONN_REQ,
5392 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5393 }
5394 
5395 int hci_abort_conn_sync(struct hci_dev *hdev, struct hci_conn *conn, u8 reason)
5396 {
5397 	int err = 0;
5398 	u16 handle = conn->handle;
5399 	bool disconnect = false;
5400 	struct hci_conn *c;
5401 
5402 	switch (conn->state) {
5403 	case BT_CONNECTED:
5404 	case BT_CONFIG:
5405 		err = hci_disconnect_sync(hdev, conn, reason);
5406 		break;
5407 	case BT_CONNECT:
5408 		err = hci_connect_cancel_sync(hdev, conn, reason);
5409 		break;
5410 	case BT_CONNECT2:
5411 		err = hci_reject_conn_sync(hdev, conn, reason);
5412 		break;
5413 	case BT_OPEN:
5414 	case BT_BOUND:
5415 		break;
5416 	default:
5417 		disconnect = true;
5418 		break;
5419 	}
5420 
5421 	hci_dev_lock(hdev);
5422 
5423 	/* Check if the connection has been cleaned up concurrently */
5424 	c = hci_conn_hash_lookup_handle(hdev, handle);
5425 	if (!c || c != conn) {
5426 		err = 0;
5427 		goto unlock;
5428 	}
5429 
5430 	/* Cleanup hci_conn object if it cannot be cancelled as it
5431 	 * likelly means the controller and host stack are out of sync
5432 	 * or in case of LE it was still scanning so it can be cleanup
5433 	 * safely.
5434 	 */
5435 	if (disconnect) {
5436 		conn->state = BT_CLOSED;
5437 		hci_disconn_cfm(conn, reason);
5438 		hci_conn_del(conn);
5439 	} else {
5440 		hci_conn_failed(conn, reason);
5441 	}
5442 
5443 unlock:
5444 	hci_dev_unlock(hdev);
5445 	return err;
5446 }
5447 
5448 static int hci_disconnect_all_sync(struct hci_dev *hdev, u8 reason)
5449 {
5450 	struct list_head *head = &hdev->conn_hash.list;
5451 	struct hci_conn *conn;
5452 
5453 	rcu_read_lock();
5454 	while ((conn = list_first_or_null_rcu(head, struct hci_conn, list))) {
5455 		/* Make sure the connection is not freed while unlocking */
5456 		conn = hci_conn_get(conn);
5457 		rcu_read_unlock();
5458 		/* Disregard possible errors since hci_conn_del shall have been
5459 		 * called even in case of errors had occurred since it would
5460 		 * then cause hci_conn_failed to be called which calls
5461 		 * hci_conn_del internally.
5462 		 */
5463 		hci_abort_conn_sync(hdev, conn, reason);
5464 		hci_conn_put(conn);
5465 		rcu_read_lock();
5466 	}
5467 	rcu_read_unlock();
5468 
5469 	return 0;
5470 }
5471 
5472 /* This function perform power off HCI command sequence as follows:
5473  *
5474  * Clear Advertising
5475  * Stop Discovery
5476  * Disconnect all connections
5477  * hci_dev_close_sync
5478  */
5479 static int hci_power_off_sync(struct hci_dev *hdev)
5480 {
5481 	int err;
5482 
5483 	/* If controller is already down there is nothing to do */
5484 	if (!test_bit(HCI_UP, &hdev->flags))
5485 		return 0;
5486 
5487 	if (test_bit(HCI_ISCAN, &hdev->flags) ||
5488 	    test_bit(HCI_PSCAN, &hdev->flags)) {
5489 		err = hci_write_scan_enable_sync(hdev, 0x00);
5490 		if (err)
5491 			return err;
5492 	}
5493 
5494 	err = hci_clear_adv_sync(hdev, NULL, false);
5495 	if (err)
5496 		return err;
5497 
5498 	err = hci_stop_discovery_sync(hdev);
5499 	if (err)
5500 		return err;
5501 
5502 	/* Terminated due to Power Off */
5503 	err = hci_disconnect_all_sync(hdev, HCI_ERROR_REMOTE_POWER_OFF);
5504 	if (err)
5505 		return err;
5506 
5507 	return hci_dev_close_sync(hdev);
5508 }
5509 
5510 int hci_set_powered_sync(struct hci_dev *hdev, u8 val)
5511 {
5512 	if (val)
5513 		return hci_power_on_sync(hdev);
5514 
5515 	return hci_power_off_sync(hdev);
5516 }
5517 
5518 static int hci_write_iac_sync(struct hci_dev *hdev)
5519 {
5520 	struct hci_cp_write_current_iac_lap cp;
5521 
5522 	if (!hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
5523 		return 0;
5524 
5525 	memset(&cp, 0, sizeof(cp));
5526 
5527 	if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE)) {
5528 		/* Limited discoverable mode */
5529 		cp.num_iac = min_t(u8, hdev->num_iac, 2);
5530 		cp.iac_lap[0] = 0x00;	/* LIAC */
5531 		cp.iac_lap[1] = 0x8b;
5532 		cp.iac_lap[2] = 0x9e;
5533 		cp.iac_lap[3] = 0x33;	/* GIAC */
5534 		cp.iac_lap[4] = 0x8b;
5535 		cp.iac_lap[5] = 0x9e;
5536 	} else {
5537 		/* General discoverable mode */
5538 		cp.num_iac = 1;
5539 		cp.iac_lap[0] = 0x33;	/* GIAC */
5540 		cp.iac_lap[1] = 0x8b;
5541 		cp.iac_lap[2] = 0x9e;
5542 	}
5543 
5544 	return __hci_cmd_sync_status(hdev, HCI_OP_WRITE_CURRENT_IAC_LAP,
5545 				     (cp.num_iac * 3) + 1, &cp,
5546 				     HCI_CMD_TIMEOUT);
5547 }
5548 
5549 int hci_update_discoverable_sync(struct hci_dev *hdev)
5550 {
5551 	int err = 0;
5552 
5553 	if (hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
5554 		err = hci_write_iac_sync(hdev);
5555 		if (err)
5556 			return err;
5557 
5558 		err = hci_update_scan_sync(hdev);
5559 		if (err)
5560 			return err;
5561 
5562 		err = hci_update_class_sync(hdev);
5563 		if (err)
5564 			return err;
5565 	}
5566 
5567 	/* Advertising instances don't use the global discoverable setting, so
5568 	 * only update AD if advertising was enabled using Set Advertising.
5569 	 */
5570 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING)) {
5571 		err = hci_update_adv_data_sync(hdev, 0x00);
5572 		if (err)
5573 			return err;
5574 
5575 		/* Discoverable mode affects the local advertising
5576 		 * address in limited privacy mode.
5577 		 */
5578 		if (hci_dev_test_flag(hdev, HCI_LIMITED_PRIVACY)) {
5579 			if (ext_adv_capable(hdev))
5580 				err = hci_start_ext_adv_sync(hdev, 0x00);
5581 			else
5582 				err = hci_enable_advertising_sync(hdev);
5583 		}
5584 	}
5585 
5586 	return err;
5587 }
5588 
5589 static int update_discoverable_sync(struct hci_dev *hdev, void *data)
5590 {
5591 	return hci_update_discoverable_sync(hdev);
5592 }
5593 
5594 int hci_update_discoverable(struct hci_dev *hdev)
5595 {
5596 	/* Only queue if it would have any effect */
5597 	if (hdev_is_powered(hdev) &&
5598 	    hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
5599 	    hci_dev_test_flag(hdev, HCI_DISCOVERABLE) &&
5600 	    hci_dev_test_flag(hdev, HCI_LIMITED_PRIVACY))
5601 		return hci_cmd_sync_queue(hdev, update_discoverable_sync, NULL,
5602 					  NULL);
5603 
5604 	return 0;
5605 }
5606 
5607 int hci_update_connectable_sync(struct hci_dev *hdev)
5608 {
5609 	int err;
5610 
5611 	err = hci_update_scan_sync(hdev);
5612 	if (err)
5613 		return err;
5614 
5615 	/* If BR/EDR is not enabled and we disable advertising as a
5616 	 * by-product of disabling connectable, we need to update the
5617 	 * advertising flags.
5618 	 */
5619 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
5620 		err = hci_update_adv_data_sync(hdev, hdev->cur_adv_instance);
5621 
5622 	/* Update the advertising parameters if necessary */
5623 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING) ||
5624 	    !list_empty(&hdev->adv_instances)) {
5625 		if (ext_adv_capable(hdev))
5626 			err = hci_start_ext_adv_sync(hdev,
5627 						     hdev->cur_adv_instance);
5628 		else
5629 			err = hci_enable_advertising_sync(hdev);
5630 
5631 		if (err)
5632 			return err;
5633 	}
5634 
5635 	return hci_update_passive_scan_sync(hdev);
5636 }
5637 
5638 static int hci_inquiry_sync(struct hci_dev *hdev, u8 length)
5639 {
5640 	const u8 giac[3] = { 0x33, 0x8b, 0x9e };
5641 	const u8 liac[3] = { 0x00, 0x8b, 0x9e };
5642 	struct hci_cp_inquiry cp;
5643 
5644 	bt_dev_dbg(hdev, "");
5645 
5646 	if (test_bit(HCI_INQUIRY, &hdev->flags))
5647 		return 0;
5648 
5649 	hci_dev_lock(hdev);
5650 	hci_inquiry_cache_flush(hdev);
5651 	hci_dev_unlock(hdev);
5652 
5653 	memset(&cp, 0, sizeof(cp));
5654 
5655 	if (hdev->discovery.limited)
5656 		memcpy(&cp.lap, liac, sizeof(cp.lap));
5657 	else
5658 		memcpy(&cp.lap, giac, sizeof(cp.lap));
5659 
5660 	cp.length = length;
5661 
5662 	return __hci_cmd_sync_status(hdev, HCI_OP_INQUIRY,
5663 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
5664 }
5665 
5666 static int hci_active_scan_sync(struct hci_dev *hdev, uint16_t interval)
5667 {
5668 	u8 own_addr_type;
5669 	/* Accept list is not used for discovery */
5670 	u8 filter_policy = 0x00;
5671 	/* Default is to enable duplicates filter */
5672 	u8 filter_dup = LE_SCAN_FILTER_DUP_ENABLE;
5673 	int err;
5674 
5675 	bt_dev_dbg(hdev, "");
5676 
5677 	/* If controller is scanning, it means the passive scanning is
5678 	 * running. Thus, we should temporarily stop it in order to set the
5679 	 * discovery scanning parameters.
5680 	 */
5681 	err = hci_scan_disable_sync(hdev);
5682 	if (err) {
5683 		bt_dev_err(hdev, "Unable to disable scanning: %d", err);
5684 		return err;
5685 	}
5686 
5687 	cancel_interleave_scan(hdev);
5688 
5689 	/* Pause address resolution for active scan and stop advertising if
5690 	 * privacy is enabled.
5691 	 */
5692 	err = hci_pause_addr_resolution(hdev);
5693 	if (err)
5694 		goto failed;
5695 
5696 	/* All active scans will be done with either a resolvable private
5697 	 * address (when privacy feature has been enabled) or non-resolvable
5698 	 * private address.
5699 	 */
5700 	err = hci_update_random_address_sync(hdev, true, scan_use_rpa(hdev),
5701 					     &own_addr_type);
5702 	if (err < 0)
5703 		own_addr_type = ADDR_LE_DEV_PUBLIC;
5704 
5705 	if (hci_is_adv_monitoring(hdev)) {
5706 		/* Duplicate filter should be disabled when some advertisement
5707 		 * monitor is activated, otherwise AdvMon can only receive one
5708 		 * advertisement for one peer(*) during active scanning, and
5709 		 * might report loss to these peers.
5710 		 *
5711 		 * Note that different controllers have different meanings of
5712 		 * |duplicate|. Some of them consider packets with the same
5713 		 * address as duplicate, and others consider packets with the
5714 		 * same address and the same RSSI as duplicate. Although in the
5715 		 * latter case we don't need to disable duplicate filter, but
5716 		 * it is common to have active scanning for a short period of
5717 		 * time, the power impact should be neglectable.
5718 		 */
5719 		filter_dup = LE_SCAN_FILTER_DUP_DISABLE;
5720 	}
5721 
5722 	err = hci_start_scan_sync(hdev, LE_SCAN_ACTIVE, interval,
5723 				  hdev->le_scan_window_discovery,
5724 				  own_addr_type, filter_policy, filter_dup);
5725 	if (!err)
5726 		return err;
5727 
5728 failed:
5729 	/* Resume advertising if it was paused */
5730 	if (use_ll_privacy(hdev))
5731 		hci_resume_advertising_sync(hdev);
5732 
5733 	/* Resume passive scanning */
5734 	hci_update_passive_scan_sync(hdev);
5735 	return err;
5736 }
5737 
5738 static int hci_start_interleaved_discovery_sync(struct hci_dev *hdev)
5739 {
5740 	int err;
5741 
5742 	bt_dev_dbg(hdev, "");
5743 
5744 	err = hci_active_scan_sync(hdev, hdev->le_scan_int_discovery * 2);
5745 	if (err)
5746 		return err;
5747 
5748 	return hci_inquiry_sync(hdev, DISCOV_BREDR_INQUIRY_LEN);
5749 }
5750 
5751 int hci_start_discovery_sync(struct hci_dev *hdev)
5752 {
5753 	unsigned long timeout;
5754 	int err;
5755 
5756 	bt_dev_dbg(hdev, "type %u", hdev->discovery.type);
5757 
5758 	switch (hdev->discovery.type) {
5759 	case DISCOV_TYPE_BREDR:
5760 		return hci_inquiry_sync(hdev, DISCOV_BREDR_INQUIRY_LEN);
5761 	case DISCOV_TYPE_INTERLEAVED:
5762 		/* When running simultaneous discovery, the LE scanning time
5763 		 * should occupy the whole discovery time sine BR/EDR inquiry
5764 		 * and LE scanning are scheduled by the controller.
5765 		 *
5766 		 * For interleaving discovery in comparison, BR/EDR inquiry
5767 		 * and LE scanning are done sequentially with separate
5768 		 * timeouts.
5769 		 */
5770 		if (test_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY,
5771 			     &hdev->quirks)) {
5772 			timeout = msecs_to_jiffies(DISCOV_LE_TIMEOUT);
5773 			/* During simultaneous discovery, we double LE scan
5774 			 * interval. We must leave some time for the controller
5775 			 * to do BR/EDR inquiry.
5776 			 */
5777 			err = hci_start_interleaved_discovery_sync(hdev);
5778 			break;
5779 		}
5780 
5781 		timeout = msecs_to_jiffies(hdev->discov_interleaved_timeout);
5782 		err = hci_active_scan_sync(hdev, hdev->le_scan_int_discovery);
5783 		break;
5784 	case DISCOV_TYPE_LE:
5785 		timeout = msecs_to_jiffies(DISCOV_LE_TIMEOUT);
5786 		err = hci_active_scan_sync(hdev, hdev->le_scan_int_discovery);
5787 		break;
5788 	default:
5789 		return -EINVAL;
5790 	}
5791 
5792 	if (err)
5793 		return err;
5794 
5795 	bt_dev_dbg(hdev, "timeout %u ms", jiffies_to_msecs(timeout));
5796 
5797 	/* When service discovery is used and the controller has a
5798 	 * strict duplicate filter, it is important to remember the
5799 	 * start and duration of the scan. This is required for
5800 	 * restarting scanning during the discovery phase.
5801 	 */
5802 	if (test_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks) &&
5803 	    hdev->discovery.result_filtering) {
5804 		hdev->discovery.scan_start = jiffies;
5805 		hdev->discovery.scan_duration = timeout;
5806 	}
5807 
5808 	queue_delayed_work(hdev->req_workqueue, &hdev->le_scan_disable,
5809 			   timeout);
5810 	return 0;
5811 }
5812 
5813 static void hci_suspend_monitor_sync(struct hci_dev *hdev)
5814 {
5815 	switch (hci_get_adv_monitor_offload_ext(hdev)) {
5816 	case HCI_ADV_MONITOR_EXT_MSFT:
5817 		msft_suspend_sync(hdev);
5818 		break;
5819 	default:
5820 		return;
5821 	}
5822 }
5823 
5824 /* This function disables discovery and mark it as paused */
5825 static int hci_pause_discovery_sync(struct hci_dev *hdev)
5826 {
5827 	int old_state = hdev->discovery.state;
5828 	int err;
5829 
5830 	/* If discovery already stopped/stopping/paused there nothing to do */
5831 	if (old_state == DISCOVERY_STOPPED || old_state == DISCOVERY_STOPPING ||
5832 	    hdev->discovery_paused)
5833 		return 0;
5834 
5835 	hci_discovery_set_state(hdev, DISCOVERY_STOPPING);
5836 	err = hci_stop_discovery_sync(hdev);
5837 	if (err)
5838 		return err;
5839 
5840 	hdev->discovery_paused = true;
5841 	hdev->discovery_old_state = old_state;
5842 	hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
5843 
5844 	return 0;
5845 }
5846 
5847 static int hci_update_event_filter_sync(struct hci_dev *hdev)
5848 {
5849 	struct bdaddr_list_with_flags *b;
5850 	u8 scan = SCAN_DISABLED;
5851 	bool scanning = test_bit(HCI_PSCAN, &hdev->flags);
5852 	int err;
5853 
5854 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
5855 		return 0;
5856 
5857 	/* Some fake CSR controllers lock up after setting this type of
5858 	 * filter, so avoid sending the request altogether.
5859 	 */
5860 	if (test_bit(HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL, &hdev->quirks))
5861 		return 0;
5862 
5863 	/* Always clear event filter when starting */
5864 	hci_clear_event_filter_sync(hdev);
5865 
5866 	list_for_each_entry(b, &hdev->accept_list, list) {
5867 		if (!(b->flags & HCI_CONN_FLAG_REMOTE_WAKEUP))
5868 			continue;
5869 
5870 		bt_dev_dbg(hdev, "Adding event filters for %pMR", &b->bdaddr);
5871 
5872 		err =  hci_set_event_filter_sync(hdev, HCI_FLT_CONN_SETUP,
5873 						 HCI_CONN_SETUP_ALLOW_BDADDR,
5874 						 &b->bdaddr,
5875 						 HCI_CONN_SETUP_AUTO_ON);
5876 		if (err)
5877 			bt_dev_dbg(hdev, "Failed to set event filter for %pMR",
5878 				   &b->bdaddr);
5879 		else
5880 			scan = SCAN_PAGE;
5881 	}
5882 
5883 	if (scan && !scanning)
5884 		hci_write_scan_enable_sync(hdev, scan);
5885 	else if (!scan && scanning)
5886 		hci_write_scan_enable_sync(hdev, scan);
5887 
5888 	return 0;
5889 }
5890 
5891 /* This function disables scan (BR and LE) and mark it as paused */
5892 static int hci_pause_scan_sync(struct hci_dev *hdev)
5893 {
5894 	if (hdev->scanning_paused)
5895 		return 0;
5896 
5897 	/* Disable page scan if enabled */
5898 	if (test_bit(HCI_PSCAN, &hdev->flags))
5899 		hci_write_scan_enable_sync(hdev, SCAN_DISABLED);
5900 
5901 	hci_scan_disable_sync(hdev);
5902 
5903 	hdev->scanning_paused = true;
5904 
5905 	return 0;
5906 }
5907 
5908 /* This function performs the HCI suspend procedures in the follow order:
5909  *
5910  * Pause discovery (active scanning/inquiry)
5911  * Pause Directed Advertising/Advertising
5912  * Pause Scanning (passive scanning in case discovery was not active)
5913  * Disconnect all connections
5914  * Set suspend_status to BT_SUSPEND_DISCONNECT if hdev cannot wakeup
5915  * otherwise:
5916  * Update event mask (only set events that are allowed to wake up the host)
5917  * Update event filter (with devices marked with HCI_CONN_FLAG_REMOTE_WAKEUP)
5918  * Update passive scanning (lower duty cycle)
5919  * Set suspend_status to BT_SUSPEND_CONFIGURE_WAKE
5920  */
5921 int hci_suspend_sync(struct hci_dev *hdev)
5922 {
5923 	int err;
5924 
5925 	/* If marked as suspended there nothing to do */
5926 	if (hdev->suspended)
5927 		return 0;
5928 
5929 	/* Mark device as suspended */
5930 	hdev->suspended = true;
5931 
5932 	/* Pause discovery if not already stopped */
5933 	hci_pause_discovery_sync(hdev);
5934 
5935 	/* Pause other advertisements */
5936 	hci_pause_advertising_sync(hdev);
5937 
5938 	/* Suspend monitor filters */
5939 	hci_suspend_monitor_sync(hdev);
5940 
5941 	/* Prevent disconnects from causing scanning to be re-enabled */
5942 	hci_pause_scan_sync(hdev);
5943 
5944 	if (hci_conn_count(hdev)) {
5945 		/* Soft disconnect everything (power off) */
5946 		err = hci_disconnect_all_sync(hdev, HCI_ERROR_REMOTE_POWER_OFF);
5947 		if (err) {
5948 			/* Set state to BT_RUNNING so resume doesn't notify */
5949 			hdev->suspend_state = BT_RUNNING;
5950 			hci_resume_sync(hdev);
5951 			return err;
5952 		}
5953 
5954 		/* Update event mask so only the allowed event can wakeup the
5955 		 * host.
5956 		 */
5957 		hci_set_event_mask_sync(hdev);
5958 	}
5959 
5960 	/* Only configure accept list if disconnect succeeded and wake
5961 	 * isn't being prevented.
5962 	 */
5963 	if (!hdev->wakeup || !hdev->wakeup(hdev)) {
5964 		hdev->suspend_state = BT_SUSPEND_DISCONNECT;
5965 		return 0;
5966 	}
5967 
5968 	/* Unpause to take care of updating scanning params */
5969 	hdev->scanning_paused = false;
5970 
5971 	/* Enable event filter for paired devices */
5972 	hci_update_event_filter_sync(hdev);
5973 
5974 	/* Update LE passive scan if enabled */
5975 	hci_update_passive_scan_sync(hdev);
5976 
5977 	/* Pause scan changes again. */
5978 	hdev->scanning_paused = true;
5979 
5980 	hdev->suspend_state = BT_SUSPEND_CONFIGURE_WAKE;
5981 
5982 	return 0;
5983 }
5984 
5985 /* This function resumes discovery */
5986 static int hci_resume_discovery_sync(struct hci_dev *hdev)
5987 {
5988 	int err;
5989 
5990 	/* If discovery not paused there nothing to do */
5991 	if (!hdev->discovery_paused)
5992 		return 0;
5993 
5994 	hdev->discovery_paused = false;
5995 
5996 	hci_discovery_set_state(hdev, DISCOVERY_STARTING);
5997 
5998 	err = hci_start_discovery_sync(hdev);
5999 
6000 	hci_discovery_set_state(hdev, err ? DISCOVERY_STOPPED :
6001 				DISCOVERY_FINDING);
6002 
6003 	return err;
6004 }
6005 
6006 static void hci_resume_monitor_sync(struct hci_dev *hdev)
6007 {
6008 	switch (hci_get_adv_monitor_offload_ext(hdev)) {
6009 	case HCI_ADV_MONITOR_EXT_MSFT:
6010 		msft_resume_sync(hdev);
6011 		break;
6012 	default:
6013 		return;
6014 	}
6015 }
6016 
6017 /* This function resume scan and reset paused flag */
6018 static int hci_resume_scan_sync(struct hci_dev *hdev)
6019 {
6020 	if (!hdev->scanning_paused)
6021 		return 0;
6022 
6023 	hdev->scanning_paused = false;
6024 
6025 	hci_update_scan_sync(hdev);
6026 
6027 	/* Reset passive scanning to normal */
6028 	hci_update_passive_scan_sync(hdev);
6029 
6030 	return 0;
6031 }
6032 
6033 /* This function performs the HCI suspend procedures in the follow order:
6034  *
6035  * Restore event mask
6036  * Clear event filter
6037  * Update passive scanning (normal duty cycle)
6038  * Resume Directed Advertising/Advertising
6039  * Resume discovery (active scanning/inquiry)
6040  */
6041 int hci_resume_sync(struct hci_dev *hdev)
6042 {
6043 	/* If not marked as suspended there nothing to do */
6044 	if (!hdev->suspended)
6045 		return 0;
6046 
6047 	hdev->suspended = false;
6048 
6049 	/* Restore event mask */
6050 	hci_set_event_mask_sync(hdev);
6051 
6052 	/* Clear any event filters and restore scan state */
6053 	hci_clear_event_filter_sync(hdev);
6054 
6055 	/* Resume scanning */
6056 	hci_resume_scan_sync(hdev);
6057 
6058 	/* Resume monitor filters */
6059 	hci_resume_monitor_sync(hdev);
6060 
6061 	/* Resume other advertisements */
6062 	hci_resume_advertising_sync(hdev);
6063 
6064 	/* Resume discovery */
6065 	hci_resume_discovery_sync(hdev);
6066 
6067 	return 0;
6068 }
6069 
6070 static bool conn_use_rpa(struct hci_conn *conn)
6071 {
6072 	struct hci_dev *hdev = conn->hdev;
6073 
6074 	return hci_dev_test_flag(hdev, HCI_PRIVACY);
6075 }
6076 
6077 static int hci_le_ext_directed_advertising_sync(struct hci_dev *hdev,
6078 						struct hci_conn *conn)
6079 {
6080 	struct hci_cp_le_set_ext_adv_params cp;
6081 	int err;
6082 	bdaddr_t random_addr;
6083 	u8 own_addr_type;
6084 
6085 	err = hci_update_random_address_sync(hdev, false, conn_use_rpa(conn),
6086 					     &own_addr_type);
6087 	if (err)
6088 		return err;
6089 
6090 	/* Set require_privacy to false so that the remote device has a
6091 	 * chance of identifying us.
6092 	 */
6093 	err = hci_get_random_address(hdev, false, conn_use_rpa(conn), NULL,
6094 				     &own_addr_type, &random_addr);
6095 	if (err)
6096 		return err;
6097 
6098 	memset(&cp, 0, sizeof(cp));
6099 
6100 	cp.evt_properties = cpu_to_le16(LE_LEGACY_ADV_DIRECT_IND);
6101 	cp.channel_map = hdev->le_adv_channel_map;
6102 	cp.tx_power = HCI_TX_POWER_INVALID;
6103 	cp.primary_phy = HCI_ADV_PHY_1M;
6104 	cp.secondary_phy = HCI_ADV_PHY_1M;
6105 	cp.handle = 0x00; /* Use instance 0 for directed adv */
6106 	cp.own_addr_type = own_addr_type;
6107 	cp.peer_addr_type = conn->dst_type;
6108 	bacpy(&cp.peer_addr, &conn->dst);
6109 
6110 	/* As per Core Spec 5.2 Vol 2, PART E, Sec 7.8.53, for
6111 	 * advertising_event_property LE_LEGACY_ADV_DIRECT_IND
6112 	 * does not supports advertising data when the advertising set already
6113 	 * contains some, the controller shall return erroc code 'Invalid
6114 	 * HCI Command Parameters(0x12).
6115 	 * So it is required to remove adv set for handle 0x00. since we use
6116 	 * instance 0 for directed adv.
6117 	 */
6118 	err = hci_remove_ext_adv_instance_sync(hdev, cp.handle, NULL);
6119 	if (err)
6120 		return err;
6121 
6122 	err = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_PARAMS,
6123 				    sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6124 	if (err)
6125 		return err;
6126 
6127 	/* Check if random address need to be updated */
6128 	if (own_addr_type == ADDR_LE_DEV_RANDOM &&
6129 	    bacmp(&random_addr, BDADDR_ANY) &&
6130 	    bacmp(&random_addr, &hdev->random_addr)) {
6131 		err = hci_set_adv_set_random_addr_sync(hdev, 0x00,
6132 						       &random_addr);
6133 		if (err)
6134 			return err;
6135 	}
6136 
6137 	return hci_enable_ext_advertising_sync(hdev, 0x00);
6138 }
6139 
6140 static int hci_le_directed_advertising_sync(struct hci_dev *hdev,
6141 					    struct hci_conn *conn)
6142 {
6143 	struct hci_cp_le_set_adv_param cp;
6144 	u8 status;
6145 	u8 own_addr_type;
6146 	u8 enable;
6147 
6148 	if (ext_adv_capable(hdev))
6149 		return hci_le_ext_directed_advertising_sync(hdev, conn);
6150 
6151 	/* Clear the HCI_LE_ADV bit temporarily so that the
6152 	 * hci_update_random_address knows that it's safe to go ahead
6153 	 * and write a new random address. The flag will be set back on
6154 	 * as soon as the SET_ADV_ENABLE HCI command completes.
6155 	 */
6156 	hci_dev_clear_flag(hdev, HCI_LE_ADV);
6157 
6158 	/* Set require_privacy to false so that the remote device has a
6159 	 * chance of identifying us.
6160 	 */
6161 	status = hci_update_random_address_sync(hdev, false, conn_use_rpa(conn),
6162 						&own_addr_type);
6163 	if (status)
6164 		return status;
6165 
6166 	memset(&cp, 0, sizeof(cp));
6167 
6168 	/* Some controllers might reject command if intervals are not
6169 	 * within range for undirected advertising.
6170 	 * BCM20702A0 is known to be affected by this.
6171 	 */
6172 	cp.min_interval = cpu_to_le16(0x0020);
6173 	cp.max_interval = cpu_to_le16(0x0020);
6174 
6175 	cp.type = LE_ADV_DIRECT_IND;
6176 	cp.own_address_type = own_addr_type;
6177 	cp.direct_addr_type = conn->dst_type;
6178 	bacpy(&cp.direct_addr, &conn->dst);
6179 	cp.channel_map = hdev->le_adv_channel_map;
6180 
6181 	status = __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_PARAM,
6182 				       sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6183 	if (status)
6184 		return status;
6185 
6186 	enable = 0x01;
6187 
6188 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_ADV_ENABLE,
6189 				     sizeof(enable), &enable, HCI_CMD_TIMEOUT);
6190 }
6191 
6192 static void set_ext_conn_params(struct hci_conn *conn,
6193 				struct hci_cp_le_ext_conn_param *p)
6194 {
6195 	struct hci_dev *hdev = conn->hdev;
6196 
6197 	memset(p, 0, sizeof(*p));
6198 
6199 	p->scan_interval = cpu_to_le16(hdev->le_scan_int_connect);
6200 	p->scan_window = cpu_to_le16(hdev->le_scan_window_connect);
6201 	p->conn_interval_min = cpu_to_le16(conn->le_conn_min_interval);
6202 	p->conn_interval_max = cpu_to_le16(conn->le_conn_max_interval);
6203 	p->conn_latency = cpu_to_le16(conn->le_conn_latency);
6204 	p->supervision_timeout = cpu_to_le16(conn->le_supv_timeout);
6205 	p->min_ce_len = cpu_to_le16(0x0000);
6206 	p->max_ce_len = cpu_to_le16(0x0000);
6207 }
6208 
6209 static int hci_le_ext_create_conn_sync(struct hci_dev *hdev,
6210 				       struct hci_conn *conn, u8 own_addr_type)
6211 {
6212 	struct hci_cp_le_ext_create_conn *cp;
6213 	struct hci_cp_le_ext_conn_param *p;
6214 	u8 data[sizeof(*cp) + sizeof(*p) * 3];
6215 	u32 plen;
6216 
6217 	cp = (void *)data;
6218 	p = (void *)cp->data;
6219 
6220 	memset(cp, 0, sizeof(*cp));
6221 
6222 	bacpy(&cp->peer_addr, &conn->dst);
6223 	cp->peer_addr_type = conn->dst_type;
6224 	cp->own_addr_type = own_addr_type;
6225 
6226 	plen = sizeof(*cp);
6227 
6228 	if (scan_1m(hdev)) {
6229 		cp->phys |= LE_SCAN_PHY_1M;
6230 		set_ext_conn_params(conn, p);
6231 
6232 		p++;
6233 		plen += sizeof(*p);
6234 	}
6235 
6236 	if (scan_2m(hdev)) {
6237 		cp->phys |= LE_SCAN_PHY_2M;
6238 		set_ext_conn_params(conn, p);
6239 
6240 		p++;
6241 		plen += sizeof(*p);
6242 	}
6243 
6244 	if (scan_coded(hdev)) {
6245 		cp->phys |= LE_SCAN_PHY_CODED;
6246 		set_ext_conn_params(conn, p);
6247 
6248 		plen += sizeof(*p);
6249 	}
6250 
6251 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_EXT_CREATE_CONN,
6252 					plen, data,
6253 					HCI_EV_LE_ENHANCED_CONN_COMPLETE,
6254 					conn->conn_timeout, NULL);
6255 }
6256 
6257 int hci_le_create_conn_sync(struct hci_dev *hdev, struct hci_conn *conn)
6258 {
6259 	struct hci_cp_le_create_conn cp;
6260 	struct hci_conn_params *params;
6261 	u8 own_addr_type;
6262 	int err;
6263 
6264 	/* If requested to connect as peripheral use directed advertising */
6265 	if (conn->role == HCI_ROLE_SLAVE) {
6266 		/* If we're active scanning and simultaneous roles is not
6267 		 * enabled simply reject the attempt.
6268 		 */
6269 		if (hci_dev_test_flag(hdev, HCI_LE_SCAN) &&
6270 		    hdev->le_scan_type == LE_SCAN_ACTIVE &&
6271 		    !hci_dev_test_flag(hdev, HCI_LE_SIMULTANEOUS_ROLES)) {
6272 			hci_conn_del(conn);
6273 			return -EBUSY;
6274 		}
6275 
6276 		/* Pause advertising while doing directed advertising. */
6277 		hci_pause_advertising_sync(hdev);
6278 
6279 		err = hci_le_directed_advertising_sync(hdev, conn);
6280 		goto done;
6281 	}
6282 
6283 	/* Disable advertising if simultaneous roles is not in use. */
6284 	if (!hci_dev_test_flag(hdev, HCI_LE_SIMULTANEOUS_ROLES))
6285 		hci_pause_advertising_sync(hdev);
6286 
6287 	params = hci_conn_params_lookup(hdev, &conn->dst, conn->dst_type);
6288 	if (params) {
6289 		conn->le_conn_min_interval = params->conn_min_interval;
6290 		conn->le_conn_max_interval = params->conn_max_interval;
6291 		conn->le_conn_latency = params->conn_latency;
6292 		conn->le_supv_timeout = params->supervision_timeout;
6293 	} else {
6294 		conn->le_conn_min_interval = hdev->le_conn_min_interval;
6295 		conn->le_conn_max_interval = hdev->le_conn_max_interval;
6296 		conn->le_conn_latency = hdev->le_conn_latency;
6297 		conn->le_supv_timeout = hdev->le_supv_timeout;
6298 	}
6299 
6300 	/* If controller is scanning, we stop it since some controllers are
6301 	 * not able to scan and connect at the same time. Also set the
6302 	 * HCI_LE_SCAN_INTERRUPTED flag so that the command complete
6303 	 * handler for scan disabling knows to set the correct discovery
6304 	 * state.
6305 	 */
6306 	if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
6307 		hci_scan_disable_sync(hdev);
6308 		hci_dev_set_flag(hdev, HCI_LE_SCAN_INTERRUPTED);
6309 	}
6310 
6311 	/* Update random address, but set require_privacy to false so
6312 	 * that we never connect with an non-resolvable address.
6313 	 */
6314 	err = hci_update_random_address_sync(hdev, false, conn_use_rpa(conn),
6315 					     &own_addr_type);
6316 	if (err)
6317 		goto done;
6318 
6319 	if (use_ext_conn(hdev)) {
6320 		err = hci_le_ext_create_conn_sync(hdev, conn, own_addr_type);
6321 		goto done;
6322 	}
6323 
6324 	memset(&cp, 0, sizeof(cp));
6325 
6326 	cp.scan_interval = cpu_to_le16(hdev->le_scan_int_connect);
6327 	cp.scan_window = cpu_to_le16(hdev->le_scan_window_connect);
6328 
6329 	bacpy(&cp.peer_addr, &conn->dst);
6330 	cp.peer_addr_type = conn->dst_type;
6331 	cp.own_address_type = own_addr_type;
6332 	cp.conn_interval_min = cpu_to_le16(conn->le_conn_min_interval);
6333 	cp.conn_interval_max = cpu_to_le16(conn->le_conn_max_interval);
6334 	cp.conn_latency = cpu_to_le16(conn->le_conn_latency);
6335 	cp.supervision_timeout = cpu_to_le16(conn->le_supv_timeout);
6336 	cp.min_ce_len = cpu_to_le16(0x0000);
6337 	cp.max_ce_len = cpu_to_le16(0x0000);
6338 
6339 	/* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E page 2261:
6340 	 *
6341 	 * If this event is unmasked and the HCI_LE_Connection_Complete event
6342 	 * is unmasked, only the HCI_LE_Enhanced_Connection_Complete event is
6343 	 * sent when a new connection has been created.
6344 	 */
6345 	err = __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_CREATE_CONN,
6346 				       sizeof(cp), &cp,
6347 				       use_enhanced_conn_complete(hdev) ?
6348 				       HCI_EV_LE_ENHANCED_CONN_COMPLETE :
6349 				       HCI_EV_LE_CONN_COMPLETE,
6350 				       conn->conn_timeout, NULL);
6351 
6352 done:
6353 	if (err == -ETIMEDOUT)
6354 		hci_le_connect_cancel_sync(hdev, conn, 0x00);
6355 
6356 	/* Re-enable advertising after the connection attempt is finished. */
6357 	hci_resume_advertising_sync(hdev);
6358 	return err;
6359 }
6360 
6361 int hci_le_create_cis_sync(struct hci_dev *hdev)
6362 {
6363 	struct {
6364 		struct hci_cp_le_create_cis cp;
6365 		struct hci_cis cis[0x1f];
6366 	} cmd;
6367 	struct hci_conn *conn;
6368 	u8 cig = BT_ISO_QOS_CIG_UNSET;
6369 
6370 	/* The spec allows only one pending LE Create CIS command at a time. If
6371 	 * the command is pending now, don't do anything. We check for pending
6372 	 * connections after each CIS Established event.
6373 	 *
6374 	 * BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
6375 	 * page 2566:
6376 	 *
6377 	 * If the Host issues this command before all the
6378 	 * HCI_LE_CIS_Established events from the previous use of the
6379 	 * command have been generated, the Controller shall return the
6380 	 * error code Command Disallowed (0x0C).
6381 	 *
6382 	 * BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 4, Part E
6383 	 * page 2567:
6384 	 *
6385 	 * When the Controller receives the HCI_LE_Create_CIS command, the
6386 	 * Controller sends the HCI_Command_Status event to the Host. An
6387 	 * HCI_LE_CIS_Established event will be generated for each CIS when it
6388 	 * is established or if it is disconnected or considered lost before
6389 	 * being established; until all the events are generated, the command
6390 	 * remains pending.
6391 	 */
6392 
6393 	memset(&cmd, 0, sizeof(cmd));
6394 
6395 	hci_dev_lock(hdev);
6396 
6397 	rcu_read_lock();
6398 
6399 	/* Wait until previous Create CIS has completed */
6400 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
6401 		if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags))
6402 			goto done;
6403 	}
6404 
6405 	/* Find CIG with all CIS ready */
6406 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
6407 		struct hci_conn *link;
6408 
6409 		if (hci_conn_check_create_cis(conn))
6410 			continue;
6411 
6412 		cig = conn->iso_qos.ucast.cig;
6413 
6414 		list_for_each_entry_rcu(link, &hdev->conn_hash.list, list) {
6415 			if (hci_conn_check_create_cis(link) > 0 &&
6416 			    link->iso_qos.ucast.cig == cig &&
6417 			    link->state != BT_CONNECTED) {
6418 				cig = BT_ISO_QOS_CIG_UNSET;
6419 				break;
6420 			}
6421 		}
6422 
6423 		if (cig != BT_ISO_QOS_CIG_UNSET)
6424 			break;
6425 	}
6426 
6427 	if (cig == BT_ISO_QOS_CIG_UNSET)
6428 		goto done;
6429 
6430 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
6431 		struct hci_cis *cis = &cmd.cis[cmd.cp.num_cis];
6432 
6433 		if (hci_conn_check_create_cis(conn) ||
6434 		    conn->iso_qos.ucast.cig != cig)
6435 			continue;
6436 
6437 		set_bit(HCI_CONN_CREATE_CIS, &conn->flags);
6438 		cis->acl_handle = cpu_to_le16(conn->parent->handle);
6439 		cis->cis_handle = cpu_to_le16(conn->handle);
6440 		cmd.cp.num_cis++;
6441 
6442 		if (cmd.cp.num_cis >= ARRAY_SIZE(cmd.cis))
6443 			break;
6444 	}
6445 
6446 done:
6447 	rcu_read_unlock();
6448 
6449 	hci_dev_unlock(hdev);
6450 
6451 	if (!cmd.cp.num_cis)
6452 		return 0;
6453 
6454 	/* Wait for HCI_LE_CIS_Established */
6455 	return __hci_cmd_sync_status_sk(hdev, HCI_OP_LE_CREATE_CIS,
6456 					sizeof(cmd.cp) + sizeof(cmd.cis[0]) *
6457 					cmd.cp.num_cis, &cmd,
6458 					HCI_EVT_LE_CIS_ESTABLISHED,
6459 					conn->conn_timeout, NULL);
6460 }
6461 
6462 int hci_le_remove_cig_sync(struct hci_dev *hdev, u8 handle)
6463 {
6464 	struct hci_cp_le_remove_cig cp;
6465 
6466 	memset(&cp, 0, sizeof(cp));
6467 	cp.cig_id = handle;
6468 
6469 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_REMOVE_CIG, sizeof(cp),
6470 				     &cp, HCI_CMD_TIMEOUT);
6471 }
6472 
6473 int hci_le_big_terminate_sync(struct hci_dev *hdev, u8 handle)
6474 {
6475 	struct hci_cp_le_big_term_sync cp;
6476 
6477 	memset(&cp, 0, sizeof(cp));
6478 	cp.handle = handle;
6479 
6480 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_BIG_TERM_SYNC,
6481 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6482 }
6483 
6484 int hci_le_pa_terminate_sync(struct hci_dev *hdev, u16 handle)
6485 {
6486 	struct hci_cp_le_pa_term_sync cp;
6487 
6488 	memset(&cp, 0, sizeof(cp));
6489 	cp.handle = cpu_to_le16(handle);
6490 
6491 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_PA_TERM_SYNC,
6492 				     sizeof(cp), &cp, HCI_CMD_TIMEOUT);
6493 }
6494 
6495 int hci_get_random_address(struct hci_dev *hdev, bool require_privacy,
6496 			   bool use_rpa, struct adv_info *adv_instance,
6497 			   u8 *own_addr_type, bdaddr_t *rand_addr)
6498 {
6499 	int err;
6500 
6501 	bacpy(rand_addr, BDADDR_ANY);
6502 
6503 	/* If privacy is enabled use a resolvable private address. If
6504 	 * current RPA has expired then generate a new one.
6505 	 */
6506 	if (use_rpa) {
6507 		/* If Controller supports LL Privacy use own address type is
6508 		 * 0x03
6509 		 */
6510 		if (use_ll_privacy(hdev))
6511 			*own_addr_type = ADDR_LE_DEV_RANDOM_RESOLVED;
6512 		else
6513 			*own_addr_type = ADDR_LE_DEV_RANDOM;
6514 
6515 		if (adv_instance) {
6516 			if (adv_rpa_valid(adv_instance))
6517 				return 0;
6518 		} else {
6519 			if (rpa_valid(hdev))
6520 				return 0;
6521 		}
6522 
6523 		err = smp_generate_rpa(hdev, hdev->irk, &hdev->rpa);
6524 		if (err < 0) {
6525 			bt_dev_err(hdev, "failed to generate new RPA");
6526 			return err;
6527 		}
6528 
6529 		bacpy(rand_addr, &hdev->rpa);
6530 
6531 		return 0;
6532 	}
6533 
6534 	/* In case of required privacy without resolvable private address,
6535 	 * use an non-resolvable private address. This is useful for
6536 	 * non-connectable advertising.
6537 	 */
6538 	if (require_privacy) {
6539 		bdaddr_t nrpa;
6540 
6541 		while (true) {
6542 			/* The non-resolvable private address is generated
6543 			 * from random six bytes with the two most significant
6544 			 * bits cleared.
6545 			 */
6546 			get_random_bytes(&nrpa, 6);
6547 			nrpa.b[5] &= 0x3f;
6548 
6549 			/* The non-resolvable private address shall not be
6550 			 * equal to the public address.
6551 			 */
6552 			if (bacmp(&hdev->bdaddr, &nrpa))
6553 				break;
6554 		}
6555 
6556 		*own_addr_type = ADDR_LE_DEV_RANDOM;
6557 		bacpy(rand_addr, &nrpa);
6558 
6559 		return 0;
6560 	}
6561 
6562 	/* No privacy so use a public address. */
6563 	*own_addr_type = ADDR_LE_DEV_PUBLIC;
6564 
6565 	return 0;
6566 }
6567 
6568 static int _update_adv_data_sync(struct hci_dev *hdev, void *data)
6569 {
6570 	u8 instance = PTR_UINT(data);
6571 
6572 	return hci_update_adv_data_sync(hdev, instance);
6573 }
6574 
6575 int hci_update_adv_data(struct hci_dev *hdev, u8 instance)
6576 {
6577 	return hci_cmd_sync_queue(hdev, _update_adv_data_sync,
6578 				  UINT_PTR(instance), NULL);
6579 }
6580