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