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