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