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