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