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