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