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