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