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