xref: /linux/net/bluetooth/hci_core.c (revision 8d3e5e6fe6d0be5634b28788abf5685d571b13a4)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3    BlueZ - Bluetooth protocol stack for Linux
4    Copyright (C) 2000-2001 Qualcomm Incorporated
5    Copyright (C) 2011 ProFUSION Embedded Systems
6 
7    Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
8 
9    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
12    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
13    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
14    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 
18    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
19    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
20    SOFTWARE IS DISCLAIMED.
21 */
22 
23 /* Bluetooth HCI core. */
24 
25 #include <linux/export.h>
26 #include <linux/rfkill.h>
27 #include <linux/debugfs.h>
28 #include <linux/crypto.h>
29 #include <linux/kcov.h>
30 #include <linux/property.h>
31 #include <linux/suspend.h>
32 #include <linux/wait.h>
33 #include <linux/unaligned.h>
34 
35 #include <net/bluetooth/bluetooth.h>
36 #include <net/bluetooth/hci_core.h>
37 #include <net/bluetooth/l2cap.h>
38 #include <net/bluetooth/mgmt.h>
39 
40 #include "hci_debugfs.h"
41 #include "smp.h"
42 #include "leds.h"
43 #include "msft.h"
44 #include "aosp.h"
45 #include "hci_codec.h"
46 
47 static void hci_rx_work(struct work_struct *work);
48 static void hci_cmd_work(struct work_struct *work);
49 static void hci_tx_work(struct work_struct *work);
50 
51 /* HCI device list */
52 LIST_HEAD(hci_dev_list);
53 DEFINE_RWLOCK(hci_dev_list_lock);
54 
55 /* HCI callback list */
56 LIST_HEAD(hci_cb_list);
57 DEFINE_MUTEX(hci_cb_list_lock);
58 
59 /* HCI ID Numbering */
60 static DEFINE_IDA(hci_index_ida);
61 
62 /* Get HCI device by index.
63  * Device is held on return. */
64 static struct hci_dev *__hci_dev_get(int index, int *srcu_index)
65 	__context_unsafe(/* conditional locking */)
66 {
67 	struct hci_dev *hdev = NULL, *d;
68 
69 	BT_DBG("%d", index);
70 
71 	if (index < 0)
72 		return NULL;
73 
74 	read_lock(&hci_dev_list_lock);
75 	list_for_each_entry(d, &hci_dev_list, list) {
76 		if (d->id == index) {
77 			hdev = hci_dev_hold(d);
78 			if (srcu_index)
79 				*srcu_index = srcu_read_lock(&d->srcu);
80 			break;
81 		}
82 	}
83 	read_unlock(&hci_dev_list_lock);
84 	return hdev;
85 }
86 
87 struct hci_dev *hci_dev_get(int index)
88 {
89 	return __hci_dev_get(index, NULL);
90 }
91 
92 static struct hci_dev *hci_dev_get_srcu(int index, int *srcu_index)
93 	__context_unsafe(/* conditional locking vs return */)
94 {
95 	return __hci_dev_get(index, srcu_index);
96 }
97 
98 static void hci_dev_put_srcu(struct hci_dev *hdev, int srcu_index)
99 	__context_unsafe(/* conditional locking vs return */)
100 {
101 	srcu_read_unlock(&hdev->srcu, srcu_index);
102 	hci_dev_put(hdev);
103 }
104 
105 /* ---- Inquiry support ---- */
106 
107 bool hci_discovery_active(struct hci_dev *hdev)
108 {
109 	struct discovery_state *discov = &hdev->discovery;
110 
111 	switch (discov->state) {
112 	case DISCOVERY_FINDING:
113 	case DISCOVERY_RESOLVING:
114 		return true;
115 
116 	default:
117 		return false;
118 	}
119 }
120 EXPORT_SYMBOL(hci_discovery_active);
121 
122 void hci_discovery_set_state(struct hci_dev *hdev, int state)
123 {
124 	int old_state = hdev->discovery.state;
125 
126 	if (old_state == state)
127 		return;
128 
129 	hdev->discovery.state = state;
130 
131 	switch (state) {
132 	case DISCOVERY_STOPPED:
133 		hci_update_passive_scan(hdev);
134 
135 		if (old_state != DISCOVERY_STARTING)
136 			mgmt_discovering(hdev, 0);
137 		break;
138 	case DISCOVERY_STARTING:
139 		break;
140 	case DISCOVERY_FINDING:
141 		mgmt_discovering(hdev, 1);
142 		break;
143 	case DISCOVERY_RESOLVING:
144 		break;
145 	case DISCOVERY_STOPPING:
146 		break;
147 	}
148 
149 	bt_dev_dbg(hdev, "state %u -> %u", old_state, state);
150 }
151 
152 void hci_inquiry_cache_flush(struct hci_dev *hdev)
153 {
154 	struct discovery_state *cache = &hdev->discovery;
155 	struct inquiry_entry *p, *n;
156 
157 	list_for_each_entry_safe(p, n, &cache->all, all) {
158 		list_del(&p->all);
159 		kfree(p);
160 	}
161 
162 	INIT_LIST_HEAD(&cache->unknown);
163 	INIT_LIST_HEAD(&cache->resolve);
164 }
165 
166 struct inquiry_entry *hci_inquiry_cache_lookup(struct hci_dev *hdev,
167 					       bdaddr_t *bdaddr)
168 {
169 	struct discovery_state *cache = &hdev->discovery;
170 	struct inquiry_entry *e;
171 
172 	BT_DBG("cache %p, %pMR", cache, bdaddr);
173 
174 	list_for_each_entry(e, &cache->all, all) {
175 		if (!bacmp(&e->data.bdaddr, bdaddr))
176 			return e;
177 	}
178 
179 	return NULL;
180 }
181 
182 struct inquiry_entry *hci_inquiry_cache_lookup_unknown(struct hci_dev *hdev,
183 						       bdaddr_t *bdaddr)
184 {
185 	struct discovery_state *cache = &hdev->discovery;
186 	struct inquiry_entry *e;
187 
188 	BT_DBG("cache %p, %pMR", cache, bdaddr);
189 
190 	list_for_each_entry(e, &cache->unknown, list) {
191 		if (!bacmp(&e->data.bdaddr, bdaddr))
192 			return e;
193 	}
194 
195 	return NULL;
196 }
197 
198 struct inquiry_entry *hci_inquiry_cache_lookup_resolve(struct hci_dev *hdev,
199 						       bdaddr_t *bdaddr,
200 						       int state)
201 {
202 	struct discovery_state *cache = &hdev->discovery;
203 	struct inquiry_entry *e;
204 
205 	BT_DBG("cache %p bdaddr %pMR state %d", cache, bdaddr, state);
206 
207 	list_for_each_entry(e, &cache->resolve, list) {
208 		if (!bacmp(bdaddr, BDADDR_ANY) && e->name_state == state)
209 			return e;
210 		if (!bacmp(&e->data.bdaddr, bdaddr))
211 			return e;
212 	}
213 
214 	return NULL;
215 }
216 
217 void hci_inquiry_cache_update_resolve(struct hci_dev *hdev,
218 				      struct inquiry_entry *ie)
219 {
220 	struct discovery_state *cache = &hdev->discovery;
221 	struct list_head *pos = &cache->resolve;
222 	struct inquiry_entry *p;
223 
224 	list_del(&ie->list);
225 
226 	list_for_each_entry(p, &cache->resolve, list) {
227 		if (p->name_state != NAME_PENDING &&
228 		    abs(p->data.rssi) >= abs(ie->data.rssi))
229 			break;
230 		pos = &p->list;
231 	}
232 
233 	list_add(&ie->list, pos);
234 }
235 
236 u32 hci_inquiry_cache_update(struct hci_dev *hdev, struct inquiry_data *data,
237 			     bool name_known)
238 {
239 	struct discovery_state *cache = &hdev->discovery;
240 	struct inquiry_entry *ie;
241 	u32 flags = 0;
242 
243 	BT_DBG("cache %p, %pMR", cache, &data->bdaddr);
244 
245 	hci_remove_remote_oob_data(hdev, &data->bdaddr, BDADDR_BREDR);
246 
247 	if (!data->ssp_mode)
248 		flags |= MGMT_DEV_FOUND_LEGACY_PAIRING;
249 
250 	ie = hci_inquiry_cache_lookup(hdev, &data->bdaddr);
251 	if (ie) {
252 		if (!ie->data.ssp_mode)
253 			flags |= MGMT_DEV_FOUND_LEGACY_PAIRING;
254 
255 		if (ie->name_state == NAME_NEEDED &&
256 		    data->rssi != ie->data.rssi) {
257 			ie->data.rssi = data->rssi;
258 			hci_inquiry_cache_update_resolve(hdev, ie);
259 		}
260 
261 		goto update;
262 	}
263 
264 	/* Entry not in the cache. Add new one. */
265 	ie = kzalloc_obj(*ie);
266 	if (!ie) {
267 		flags |= MGMT_DEV_FOUND_CONFIRM_NAME;
268 		goto done;
269 	}
270 
271 	list_add(&ie->all, &cache->all);
272 
273 	if (name_known) {
274 		ie->name_state = NAME_KNOWN;
275 	} else {
276 		ie->name_state = NAME_NOT_KNOWN;
277 		list_add(&ie->list, &cache->unknown);
278 	}
279 
280 update:
281 	if (name_known && ie->name_state != NAME_KNOWN &&
282 	    ie->name_state != NAME_PENDING) {
283 		ie->name_state = NAME_KNOWN;
284 		list_del(&ie->list);
285 	}
286 
287 	memcpy(&ie->data, data, sizeof(*data));
288 	ie->timestamp = jiffies;
289 	cache->timestamp = jiffies;
290 
291 	if (ie->name_state == NAME_NOT_KNOWN)
292 		flags |= MGMT_DEV_FOUND_CONFIRM_NAME;
293 
294 done:
295 	return flags;
296 }
297 
298 static int inquiry_cache_dump(struct hci_dev *hdev, int num, __u8 *buf)
299 {
300 	struct discovery_state *cache = &hdev->discovery;
301 	struct inquiry_info *info = (struct inquiry_info *) buf;
302 	struct inquiry_entry *e;
303 	int copied = 0;
304 
305 	list_for_each_entry(e, &cache->all, all) {
306 		struct inquiry_data *data = &e->data;
307 
308 		if (copied >= num)
309 			break;
310 
311 		bacpy(&info->bdaddr, &data->bdaddr);
312 		info->pscan_rep_mode	= data->pscan_rep_mode;
313 		info->pscan_period_mode	= data->pscan_period_mode;
314 		info->pscan_mode	= data->pscan_mode;
315 		memcpy(info->dev_class, data->dev_class, 3);
316 		info->clock_offset	= data->clock_offset;
317 
318 		info++;
319 		copied++;
320 	}
321 
322 	BT_DBG("cache %p, copied %d", cache, copied);
323 	return copied;
324 }
325 
326 int hci_inquiry(void __user *arg)
327 {
328 	__u8 __user *ptr = arg;
329 	struct hci_inquiry_req ir;
330 	struct hci_dev *hdev;
331 	int err = 0, do_inquiry = 0, max_rsp;
332 	__u8 *buf;
333 
334 	if (copy_from_user(&ir, ptr, sizeof(ir)))
335 		return -EFAULT;
336 
337 	hdev = hci_dev_get(ir.dev_id);
338 	if (!hdev)
339 		return -ENODEV;
340 
341 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
342 		err = -EBUSY;
343 		goto done;
344 	}
345 
346 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
347 		err = -EOPNOTSUPP;
348 		goto done;
349 	}
350 
351 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
352 		err = -EOPNOTSUPP;
353 		goto done;
354 	}
355 
356 	/* Restrict maximum inquiry length to 60 seconds */
357 	if (ir.length > 60) {
358 		err = -EINVAL;
359 		goto done;
360 	}
361 
362 	hci_dev_lock(hdev);
363 	if (inquiry_cache_age(hdev) > INQUIRY_CACHE_AGE_MAX ||
364 	    inquiry_cache_empty(hdev) || ir.flags & IREQ_CACHE_FLUSH) {
365 		hci_inquiry_cache_flush(hdev);
366 		do_inquiry = 1;
367 	}
368 	hci_dev_unlock(hdev);
369 
370 	if (do_inquiry) {
371 		hci_req_sync_lock(hdev);
372 		err = hci_inquiry_sync(hdev, ir.length, ir.num_rsp);
373 		hci_req_sync_unlock(hdev);
374 
375 		if (err < 0)
376 			goto done;
377 
378 		/* Wait until Inquiry procedure finishes (HCI_INQUIRY flag is
379 		 * cleared). If it is interrupted by a signal, return -EINTR.
380 		 */
381 		if (wait_on_bit(&hdev->flags, HCI_INQUIRY,
382 				TASK_INTERRUPTIBLE)) {
383 			err = -EINTR;
384 			goto done;
385 		}
386 	}
387 
388 	/* for unlimited number of responses we will use buffer with
389 	 * 255 entries
390 	 */
391 	max_rsp = (ir.num_rsp == 0) ? 255 : ir.num_rsp;
392 
393 	/* cache_dump can't sleep. Therefore we allocate temp buffer and then
394 	 * copy it to the user space.
395 	 */
396 	buf = kmalloc_array(max_rsp, sizeof(struct inquiry_info), GFP_KERNEL);
397 	if (!buf) {
398 		err = -ENOMEM;
399 		goto done;
400 	}
401 
402 	hci_dev_lock(hdev);
403 	ir.num_rsp = inquiry_cache_dump(hdev, max_rsp, buf);
404 	hci_dev_unlock(hdev);
405 
406 	BT_DBG("num_rsp %d", ir.num_rsp);
407 
408 	if (!copy_to_user(ptr, &ir, sizeof(ir))) {
409 		ptr += sizeof(ir);
410 		if (copy_to_user(ptr, buf, sizeof(struct inquiry_info) *
411 				 ir.num_rsp))
412 			err = -EFAULT;
413 	} else
414 		err = -EFAULT;
415 
416 	kfree(buf);
417 
418 done:
419 	hci_dev_put(hdev);
420 	return err;
421 }
422 
423 static int hci_dev_do_open(struct hci_dev *hdev)
424 {
425 	int ret = 0;
426 
427 	BT_DBG("%s %p", hdev->name, hdev);
428 
429 	hci_req_sync_lock(hdev);
430 
431 	ret = hci_dev_open_sync(hdev);
432 
433 	hci_req_sync_unlock(hdev);
434 	return ret;
435 }
436 
437 /* ---- HCI ioctl helpers ---- */
438 
439 int hci_dev_open(__u16 dev)
440 {
441 	struct hci_dev *hdev;
442 	int err;
443 
444 	hdev = hci_dev_get(dev);
445 	if (!hdev)
446 		return -ENODEV;
447 
448 	/* Devices that are marked as unconfigured can only be powered
449 	 * up as user channel. Trying to bring them up as normal devices
450 	 * will result into a failure. Only user channel operation is
451 	 * possible.
452 	 *
453 	 * When this function is called for a user channel, the flag
454 	 * HCI_USER_CHANNEL will be set first before attempting to
455 	 * open the device.
456 	 */
457 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED) &&
458 	    !hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
459 		err = -EOPNOTSUPP;
460 		goto done;
461 	}
462 
463 	/* We need to ensure that no other power on/off work is pending
464 	 * before proceeding to call hci_dev_do_open. This is
465 	 * particularly important if the setup procedure has not yet
466 	 * completed.
467 	 */
468 	if (hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF))
469 		cancel_delayed_work(&hdev->power_off);
470 
471 	/* After this call it is guaranteed that the setup procedure
472 	 * has finished. This means that error conditions like RFKILL
473 	 * or no valid public or static random address apply.
474 	 */
475 	flush_workqueue(hdev->req_workqueue);
476 
477 	/* For controllers not using the management interface and that
478 	 * are brought up using legacy ioctl, set the HCI_BONDABLE bit
479 	 * so that pairing works for them. Once the management interface
480 	 * is in use this bit will be cleared again and userspace has
481 	 * to explicitly enable it.
482 	 */
483 	if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
484 	    !hci_dev_test_flag(hdev, HCI_MGMT))
485 		hci_dev_set_flag(hdev, HCI_BONDABLE);
486 
487 	err = hci_dev_do_open(hdev);
488 
489 done:
490 	hci_dev_put(hdev);
491 	return err;
492 }
493 
494 int hci_dev_do_close(struct hci_dev *hdev)
495 {
496 	int err;
497 
498 	BT_DBG("%s %p", hdev->name, hdev);
499 
500 	hci_req_sync_lock(hdev);
501 
502 	err = hci_dev_close_sync(hdev);
503 
504 	hci_req_sync_unlock(hdev);
505 
506 	return err;
507 }
508 
509 int hci_dev_close(__u16 dev)
510 {
511 	struct hci_dev *hdev;
512 	int err;
513 
514 	hdev = hci_dev_get(dev);
515 	if (!hdev)
516 		return -ENODEV;
517 
518 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
519 		err = -EBUSY;
520 		goto done;
521 	}
522 
523 	cancel_work_sync(&hdev->power_on);
524 	if (hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF))
525 		cancel_delayed_work(&hdev->power_off);
526 
527 	err = hci_dev_do_close(hdev);
528 
529 done:
530 	hci_dev_put(hdev);
531 	return err;
532 }
533 
534 static int hci_dev_do_reset(struct hci_dev *hdev)
535 {
536 	int ret;
537 
538 	BT_DBG("%s %p", hdev->name, hdev);
539 
540 	hci_req_sync_lock(hdev);
541 
542 	ret = hci_dev_close_sync(hdev);
543 	if (!ret)
544 		ret = hci_dev_open_sync(hdev);
545 
546 	hci_req_sync_unlock(hdev);
547 	return ret;
548 }
549 
550 int hci_dev_reset(__u16 dev)
551 {
552 	struct hci_dev *hdev;
553 	int err, srcu_index;
554 
555 	hdev = hci_dev_get_srcu(dev, &srcu_index);
556 	if (!hdev)
557 		return -ENODEV;
558 
559 	if (!test_bit(HCI_UP, &hdev->flags)) {
560 		err = -ENETDOWN;
561 		goto done;
562 	}
563 
564 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
565 		err = -EBUSY;
566 		goto done;
567 	}
568 
569 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
570 		err = -EOPNOTSUPP;
571 		goto done;
572 	}
573 
574 	err = hci_dev_do_reset(hdev);
575 
576 done:
577 	hci_dev_put_srcu(hdev, srcu_index);
578 	return err;
579 }
580 
581 int hci_dev_reset_stat(__u16 dev)
582 {
583 	struct hci_dev *hdev;
584 	int ret = 0;
585 
586 	hdev = hci_dev_get(dev);
587 	if (!hdev)
588 		return -ENODEV;
589 
590 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
591 		ret = -EBUSY;
592 		goto done;
593 	}
594 
595 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
596 		ret = -EOPNOTSUPP;
597 		goto done;
598 	}
599 
600 	memset(&hdev->stat, 0, sizeof(struct hci_dev_stats));
601 
602 done:
603 	hci_dev_put(hdev);
604 	return ret;
605 }
606 
607 static void hci_update_passive_scan_state(struct hci_dev *hdev, u8 scan)
608 {
609 	bool conn_changed, discov_changed;
610 
611 	BT_DBG("%s scan 0x%02x", hdev->name, scan);
612 
613 	if ((scan & SCAN_PAGE))
614 		conn_changed = !hci_dev_test_and_set_flag(hdev,
615 							  HCI_CONNECTABLE);
616 	else
617 		conn_changed = hci_dev_test_and_clear_flag(hdev,
618 							   HCI_CONNECTABLE);
619 
620 	if ((scan & SCAN_INQUIRY)) {
621 		discov_changed = !hci_dev_test_and_set_flag(hdev,
622 							    HCI_DISCOVERABLE);
623 	} else {
624 		hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
625 		discov_changed = hci_dev_test_and_clear_flag(hdev,
626 							     HCI_DISCOVERABLE);
627 	}
628 
629 	if (!hci_dev_test_flag(hdev, HCI_MGMT))
630 		return;
631 
632 	if (conn_changed || discov_changed) {
633 		/* In case this was disabled through mgmt */
634 		hci_dev_set_flag(hdev, HCI_BREDR_ENABLED);
635 
636 		if (hci_dev_test_flag(hdev, HCI_LE_ENABLED))
637 			hci_update_adv_data(hdev, hdev->cur_adv_instance);
638 
639 		mgmt_new_settings(hdev);
640 	}
641 }
642 
643 int hci_dev_cmd(unsigned int cmd, void __user *arg)
644 {
645 	struct hci_dev *hdev;
646 	struct hci_dev_req dr;
647 	__le16 policy;
648 	int err = 0;
649 
650 	if (copy_from_user(&dr, arg, sizeof(dr)))
651 		return -EFAULT;
652 
653 	hdev = hci_dev_get(dr.dev_id);
654 	if (!hdev)
655 		return -ENODEV;
656 
657 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
658 		err = -EBUSY;
659 		goto done;
660 	}
661 
662 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
663 		err = -EOPNOTSUPP;
664 		goto done;
665 	}
666 
667 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
668 		err = -EOPNOTSUPP;
669 		goto done;
670 	}
671 
672 	switch (cmd) {
673 	case HCISETAUTH:
674 		err = hci_cmd_sync_status(hdev, HCI_OP_WRITE_AUTH_ENABLE,
675 					  1, &dr.dev_opt, HCI_CMD_TIMEOUT);
676 		break;
677 
678 	case HCISETENCRYPT:
679 		if (!lmp_encrypt_capable(hdev)) {
680 			err = -EOPNOTSUPP;
681 			break;
682 		}
683 
684 		if (!test_bit(HCI_AUTH, &hdev->flags)) {
685 			/* Auth must be enabled first */
686 			err = hci_cmd_sync_status(hdev,
687 						  HCI_OP_WRITE_AUTH_ENABLE,
688 						  1, &dr.dev_opt,
689 						  HCI_CMD_TIMEOUT);
690 			if (err)
691 				break;
692 		}
693 
694 		err = hci_cmd_sync_status(hdev, HCI_OP_WRITE_ENCRYPT_MODE,
695 					  1, &dr.dev_opt, HCI_CMD_TIMEOUT);
696 		break;
697 
698 	case HCISETSCAN:
699 		err = hci_cmd_sync_status(hdev, HCI_OP_WRITE_SCAN_ENABLE,
700 					  1, &dr.dev_opt, HCI_CMD_TIMEOUT);
701 
702 		/* Ensure that the connectable and discoverable states
703 		 * get correctly modified as this was a non-mgmt change.
704 		 */
705 		if (!err)
706 			hci_update_passive_scan_state(hdev, dr.dev_opt);
707 		break;
708 
709 	case HCISETLINKPOL:
710 		policy = cpu_to_le16(dr.dev_opt);
711 
712 		err = hci_cmd_sync_status(hdev, HCI_OP_WRITE_DEF_LINK_POLICY,
713 					  2, &policy, HCI_CMD_TIMEOUT);
714 		break;
715 
716 	case HCISETLINKMODE:
717 		hdev->link_mode = ((__u16) dr.dev_opt) &
718 					(HCI_LM_MASTER | HCI_LM_ACCEPT);
719 		break;
720 
721 	case HCISETPTYPE:
722 		if (hdev->pkt_type == (__u16) dr.dev_opt)
723 			break;
724 
725 		hdev->pkt_type = (__u16) dr.dev_opt;
726 		mgmt_phy_configuration_changed(hdev, NULL);
727 		break;
728 
729 	case HCISETACLMTU:
730 		hdev->acl_mtu  = *((__u16 *) &dr.dev_opt + 1);
731 		hdev->acl_pkts = *((__u16 *) &dr.dev_opt + 0);
732 		break;
733 
734 	case HCISETSCOMTU:
735 		hdev->sco_mtu  = *((__u16 *) &dr.dev_opt + 1);
736 		hdev->sco_pkts = *((__u16 *) &dr.dev_opt + 0);
737 		break;
738 
739 	default:
740 		err = -EINVAL;
741 		break;
742 	}
743 
744 done:
745 	hci_dev_put(hdev);
746 	return err;
747 }
748 
749 int hci_get_dev_list(void __user *arg)
750 {
751 	struct hci_dev *hdev;
752 	struct hci_dev_list_req *dl;
753 	struct hci_dev_req *dr;
754 	int n = 0, err;
755 	__u16 dev_num;
756 
757 	if (get_user(dev_num, (__u16 __user *) arg))
758 		return -EFAULT;
759 
760 	if (!dev_num || dev_num > (PAGE_SIZE * 2) / sizeof(*dr))
761 		return -EINVAL;
762 
763 	dl = kzalloc_flex(*dl, dev_req, dev_num);
764 	if (!dl)
765 		return -ENOMEM;
766 
767 	dl->dev_num = dev_num;
768 	dr = dl->dev_req;
769 
770 	read_lock(&hci_dev_list_lock);
771 	list_for_each_entry(hdev, &hci_dev_list, list) {
772 		unsigned long flags = hdev->flags;
773 
774 		/* When the auto-off is configured it means the transport
775 		 * is running, but in that case still indicate that the
776 		 * device is actually down.
777 		 */
778 		if (hci_dev_test_flag(hdev, HCI_AUTO_OFF))
779 			flags &= ~BIT(HCI_UP);
780 
781 		dr[n].dev_id  = hdev->id;
782 		dr[n].dev_opt = flags;
783 
784 		if (++n >= dev_num)
785 			break;
786 	}
787 	read_unlock(&hci_dev_list_lock);
788 
789 	dl->dev_num = n;
790 	err = copy_to_user(arg, dl, struct_size(dl, dev_req, n));
791 	kfree(dl);
792 
793 	return err ? -EFAULT : 0;
794 }
795 
796 int hci_get_dev_info(void __user *arg)
797 {
798 	struct hci_dev *hdev;
799 	struct hci_dev_info di;
800 	unsigned long flags;
801 	int err = 0;
802 
803 	if (copy_from_user(&di, arg, sizeof(di)))
804 		return -EFAULT;
805 
806 	hdev = hci_dev_get(di.dev_id);
807 	if (!hdev)
808 		return -ENODEV;
809 
810 	/* When the auto-off is configured it means the transport
811 	 * is running, but in that case still indicate that the
812 	 * device is actually down.
813 	 */
814 	if (hci_dev_test_flag(hdev, HCI_AUTO_OFF))
815 		flags = hdev->flags & ~BIT(HCI_UP);
816 	else
817 		flags = hdev->flags;
818 
819 	strscpy(di.name, hdev->name, sizeof(di.name));
820 	di.bdaddr   = hdev->bdaddr;
821 	di.type     = (hdev->bus & 0x0f);
822 	di.flags    = flags;
823 	di.pkt_type = hdev->pkt_type;
824 	if (lmp_bredr_capable(hdev)) {
825 		di.acl_mtu  = hdev->acl_mtu;
826 		di.acl_pkts = hdev->acl_pkts;
827 		di.sco_mtu  = hdev->sco_mtu;
828 		di.sco_pkts = hdev->sco_pkts;
829 	} else {
830 		di.acl_mtu  = hdev->le_mtu;
831 		di.acl_pkts = hdev->le_pkts;
832 		di.sco_mtu  = 0;
833 		di.sco_pkts = 0;
834 	}
835 	di.link_policy = hdev->link_policy;
836 	di.link_mode   = hdev->link_mode;
837 
838 	memcpy(&di.stat, &hdev->stat, sizeof(di.stat));
839 	memcpy(&di.features, &hdev->features, sizeof(di.features));
840 
841 	if (copy_to_user(arg, &di, sizeof(di)))
842 		err = -EFAULT;
843 
844 	hci_dev_put(hdev);
845 
846 	return err;
847 }
848 
849 /* ---- Interface to HCI drivers ---- */
850 
851 static int hci_dev_do_poweroff(struct hci_dev *hdev)
852 {
853 	int err;
854 
855 	BT_DBG("%s %p", hdev->name, hdev);
856 
857 	hci_req_sync_lock(hdev);
858 
859 	err = hci_set_powered_sync(hdev, false);
860 
861 	hci_req_sync_unlock(hdev);
862 
863 	return err;
864 }
865 
866 static int hci_rfkill_set_block(void *data, bool blocked)
867 {
868 	struct hci_dev *hdev = data;
869 	int err;
870 
871 	BT_DBG("%p name %s blocked %d", hdev, hdev->name, blocked);
872 
873 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL))
874 		return -EBUSY;
875 
876 	if (blocked == hci_dev_test_flag(hdev, HCI_RFKILLED))
877 		return 0;
878 
879 	if (blocked) {
880 		hci_dev_set_flag(hdev, HCI_RFKILLED);
881 
882 		if (!hci_dev_test_flag(hdev, HCI_SETUP) &&
883 		    !hci_dev_test_flag(hdev, HCI_CONFIG)) {
884 			err = hci_dev_do_poweroff(hdev);
885 			if (err) {
886 				bt_dev_err(hdev, "Error when powering off device on rfkill (%d)",
887 					   err);
888 
889 				/* Make sure the device is still closed even if
890 				 * anything during power off sequence (eg.
891 				 * disconnecting devices) failed.
892 				 */
893 				hci_dev_do_close(hdev);
894 			}
895 		}
896 	} else {
897 		hci_dev_clear_flag(hdev, HCI_RFKILLED);
898 	}
899 
900 	return 0;
901 }
902 
903 static const struct rfkill_ops hci_rfkill_ops = {
904 	.set_block = hci_rfkill_set_block,
905 };
906 
907 static void hci_power_on(struct work_struct *work)
908 {
909 	struct hci_dev *hdev = container_of(work, struct hci_dev, power_on);
910 	int err;
911 
912 	BT_DBG("%s", hdev->name);
913 
914 	if (test_bit(HCI_UP, &hdev->flags) &&
915 	    hci_dev_test_flag(hdev, HCI_MGMT) &&
916 	    hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF)) {
917 		cancel_delayed_work(&hdev->power_off);
918 		hci_req_sync_lock(hdev);
919 		err = hci_powered_update_sync(hdev);
920 		hci_req_sync_unlock(hdev);
921 		mgmt_power_on(hdev, err);
922 		return;
923 	}
924 
925 	err = hci_dev_do_open(hdev);
926 	if (err < 0) {
927 		hci_dev_lock(hdev);
928 		mgmt_set_powered_failed(hdev, err);
929 		hci_dev_unlock(hdev);
930 		return;
931 	}
932 
933 	/* During the HCI setup phase, a few error conditions are
934 	 * ignored and they need to be checked now. If they are still
935 	 * valid, it is important to turn the device back off.
936 	 */
937 	if (hci_dev_test_flag(hdev, HCI_RFKILLED) ||
938 	    hci_dev_test_flag(hdev, HCI_UNCONFIGURED) ||
939 	    (!bacmp(&hdev->bdaddr, BDADDR_ANY) &&
940 	     !bacmp(&hdev->static_addr, BDADDR_ANY))) {
941 		hci_dev_clear_flag(hdev, HCI_AUTO_OFF);
942 		hci_dev_do_close(hdev);
943 	} else if (hci_dev_test_flag(hdev, HCI_AUTO_OFF)) {
944 		queue_delayed_work(hdev->req_workqueue, &hdev->power_off,
945 				   HCI_AUTO_OFF_TIMEOUT);
946 	}
947 
948 	if (hci_dev_test_and_clear_flag(hdev, HCI_SETUP)) {
949 		/* For unconfigured devices, set the HCI_RAW flag
950 		 * so that userspace can easily identify them.
951 		 */
952 		if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
953 			set_bit(HCI_RAW, &hdev->flags);
954 
955 		/* For fully configured devices, this will send
956 		 * the Index Added event. For unconfigured devices,
957 		 * it will send Unconfigued Index Added event.
958 		 *
959 		 * Devices with HCI_QUIRK_RAW_DEVICE are ignored
960 		 * and no event will be send.
961 		 */
962 		mgmt_index_added(hdev);
963 	} else if (hci_dev_test_and_clear_flag(hdev, HCI_CONFIG)) {
964 		/* When the controller is now configured, then it
965 		 * is important to clear the HCI_RAW flag.
966 		 */
967 		if (!hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
968 			clear_bit(HCI_RAW, &hdev->flags);
969 
970 		/* Powering on the controller with HCI_CONFIG set only
971 		 * happens with the transition from unconfigured to
972 		 * configured. This will send the Index Added event.
973 		 */
974 		mgmt_index_added(hdev);
975 	}
976 }
977 
978 static void hci_power_off(struct work_struct *work)
979 {
980 	struct hci_dev *hdev = container_of(work, struct hci_dev,
981 					    power_off.work);
982 
983 	BT_DBG("%s", hdev->name);
984 
985 	hci_dev_do_close(hdev);
986 }
987 
988 static void hci_error_reset(struct work_struct *work)
989 {
990 	struct hci_dev *hdev = container_of(work, struct hci_dev, error_reset);
991 
992 	hci_dev_hold(hdev);
993 	BT_DBG("%s", hdev->name);
994 
995 	if (hdev->hw_error)
996 		hdev->hw_error(hdev, hdev->hw_error_code);
997 	else
998 		bt_dev_err(hdev, "hardware error 0x%2.2x", hdev->hw_error_code);
999 
1000 	if (!hci_dev_do_close(hdev))
1001 		hci_dev_do_open(hdev);
1002 
1003 	hci_dev_put(hdev);
1004 }
1005 
1006 void hci_uuids_clear(struct hci_dev *hdev)
1007 {
1008 	struct bt_uuid *uuid, *tmp;
1009 
1010 	list_for_each_entry_safe(uuid, tmp, &hdev->uuids, list) {
1011 		list_del(&uuid->list);
1012 		kfree(uuid);
1013 	}
1014 }
1015 
1016 void hci_link_keys_clear(struct hci_dev *hdev)
1017 {
1018 	struct link_key *key, *tmp;
1019 
1020 	mutex_lock(&hdev->link_keys_lock);
1021 
1022 	list_for_each_entry_safe(key, tmp, &hdev->link_keys, list) {
1023 		list_del_rcu(&key->list);
1024 		kfree_rcu(key, rcu);
1025 	}
1026 
1027 	mutex_unlock(&hdev->link_keys_lock);
1028 }
1029 
1030 void hci_smp_ltks_clear(struct hci_dev *hdev)
1031 {
1032 	struct smp_ltk *k, *tmp;
1033 
1034 	list_for_each_entry_safe(k, tmp, &hdev->long_term_keys, list) {
1035 		list_del_rcu(&k->list);
1036 		kfree_rcu(k, rcu);
1037 	}
1038 }
1039 
1040 void hci_smp_irks_clear(struct hci_dev *hdev)
1041 {
1042 	struct smp_irk *k, *tmp;
1043 
1044 	list_for_each_entry_safe(k, tmp, &hdev->identity_resolving_keys, list) {
1045 		list_del_rcu(&k->list);
1046 		kfree_rcu(k, rcu);
1047 	}
1048 }
1049 
1050 void hci_blocked_keys_clear(struct hci_dev *hdev)
1051 {
1052 	struct blocked_key *b, *tmp;
1053 
1054 	list_for_each_entry_safe(b, tmp, &hdev->blocked_keys, list) {
1055 		list_del_rcu(&b->list);
1056 		kfree_rcu(b, rcu);
1057 	}
1058 }
1059 
1060 bool hci_is_blocked_key(struct hci_dev *hdev, u8 type, u8 val[16])
1061 {
1062 	bool blocked = false;
1063 	struct blocked_key *b;
1064 
1065 	rcu_read_lock();
1066 	list_for_each_entry_rcu(b, &hdev->blocked_keys, list) {
1067 		if (b->type == type && !memcmp(b->val, val, sizeof(b->val))) {
1068 			blocked = true;
1069 			break;
1070 		}
1071 	}
1072 
1073 	rcu_read_unlock();
1074 	return blocked;
1075 }
1076 
1077 struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr)
1078 {
1079 	struct link_key *k;
1080 
1081 	rcu_read_lock();
1082 	list_for_each_entry_rcu(k, &hdev->link_keys, list) {
1083 		if (bacmp(bdaddr, &k->bdaddr) == 0) {
1084 			if (hci_is_blocked_key(hdev,
1085 					       HCI_BLOCKED_KEY_TYPE_LINKKEY,
1086 					       k->val)) {
1087 				bt_dev_warn_ratelimited(hdev,
1088 							"Link key blocked for %pMR",
1089 							&k->bdaddr);
1090 				k = NULL;
1091 			}
1092 
1093 			rcu_read_unlock();
1094 			return k;
1095 		}
1096 	}
1097 	rcu_read_unlock();
1098 
1099 	return NULL;
1100 }
1101 
1102 static bool hci_persistent_key(struct hci_dev *hdev, struct hci_conn *conn,
1103 			       u8 key_type, u8 old_key_type)
1104 {
1105 	/* Legacy key */
1106 	if (key_type < 0x03)
1107 		return true;
1108 
1109 	/* Debug keys are insecure so don't store them persistently */
1110 	if (key_type == HCI_LK_DEBUG_COMBINATION)
1111 		return false;
1112 
1113 	/* Changed combination key and there's no previous one */
1114 	if (key_type == HCI_LK_CHANGED_COMBINATION && old_key_type == 0xff)
1115 		return false;
1116 
1117 	/* Security mode 3 case */
1118 	if (!conn)
1119 		return true;
1120 
1121 	/* BR/EDR key derived using SC from an LE link */
1122 	if (conn->type == LE_LINK)
1123 		return true;
1124 
1125 	/* Neither local nor remote side had no-bonding as requirement */
1126 	if (conn->auth_type > 0x01 && conn->remote_auth > 0x01)
1127 		return true;
1128 
1129 	/* Local side had dedicated bonding as requirement */
1130 	if (conn->auth_type == 0x02 || conn->auth_type == 0x03)
1131 		return true;
1132 
1133 	/* Remote side had dedicated bonding as requirement */
1134 	if (conn->remote_auth == 0x02 || conn->remote_auth == 0x03)
1135 		return true;
1136 
1137 	/* If none of the above criteria match, then don't store the key
1138 	 * persistently */
1139 	return false;
1140 }
1141 
1142 static u8 ltk_role(u8 type)
1143 {
1144 	if (type == SMP_LTK)
1145 		return HCI_ROLE_MASTER;
1146 
1147 	return HCI_ROLE_SLAVE;
1148 }
1149 
1150 struct smp_ltk *hci_find_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,
1151 			     u8 addr_type, u8 role)
1152 {
1153 	struct smp_ltk *k;
1154 
1155 	rcu_read_lock();
1156 	list_for_each_entry_rcu(k, &hdev->long_term_keys, list) {
1157 		if (addr_type != k->bdaddr_type || bacmp(bdaddr, &k->bdaddr))
1158 			continue;
1159 
1160 		if (smp_ltk_is_sc(k) || ltk_role(k->type) == role) {
1161 			if (hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_LTK,
1162 					       k->val)) {
1163 				bt_dev_warn_ratelimited(hdev,
1164 							"LTK blocked for %pMR",
1165 							&k->bdaddr);
1166 				rcu_read_unlock();
1167 				return NULL;
1168 			}
1169 
1170 			rcu_read_unlock();
1171 			return k;
1172 		}
1173 	}
1174 	rcu_read_unlock();
1175 
1176 	return NULL;
1177 }
1178 
1179 struct smp_irk *hci_find_irk_by_rpa(struct hci_dev *hdev, bdaddr_t *rpa)
1180 {
1181 	struct smp_irk *irk_to_return = NULL;
1182 	struct smp_irk *irk;
1183 
1184 	rcu_read_lock();
1185 	list_for_each_entry_rcu(irk, &hdev->identity_resolving_keys, list) {
1186 		if (!bacmp(&irk->rpa, rpa)) {
1187 			irk_to_return = irk;
1188 			goto done;
1189 		}
1190 	}
1191 
1192 	list_for_each_entry_rcu(irk, &hdev->identity_resolving_keys, list) {
1193 		if (smp_irk_matches(hdev, irk->val, rpa)) {
1194 			bacpy(&irk->rpa, rpa);
1195 			irk_to_return = irk;
1196 			goto done;
1197 		}
1198 	}
1199 
1200 done:
1201 	if (irk_to_return && hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_IRK,
1202 						irk_to_return->val)) {
1203 		bt_dev_warn_ratelimited(hdev, "Identity key blocked for %pMR",
1204 					&irk_to_return->bdaddr);
1205 		irk_to_return = NULL;
1206 	}
1207 
1208 	rcu_read_unlock();
1209 
1210 	return irk_to_return;
1211 }
1212 
1213 struct smp_irk *hci_find_irk_by_addr(struct hci_dev *hdev, bdaddr_t *bdaddr,
1214 				     u8 addr_type)
1215 {
1216 	struct smp_irk *irk_to_return = NULL;
1217 	struct smp_irk *irk;
1218 
1219 	/* Identity Address must be public or static random */
1220 	if (addr_type == ADDR_LE_DEV_RANDOM && (bdaddr->b[5] & 0xc0) != 0xc0)
1221 		return NULL;
1222 
1223 	rcu_read_lock();
1224 	list_for_each_entry_rcu(irk, &hdev->identity_resolving_keys, list) {
1225 		if (addr_type == irk->addr_type &&
1226 		    bacmp(bdaddr, &irk->bdaddr) == 0) {
1227 			irk_to_return = irk;
1228 			break;
1229 		}
1230 	}
1231 
1232 	if (irk_to_return && hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_IRK,
1233 						irk_to_return->val)) {
1234 		bt_dev_warn_ratelimited(hdev, "Identity key blocked for %pMR",
1235 					&irk_to_return->bdaddr);
1236 		irk_to_return = NULL;
1237 	}
1238 
1239 	rcu_read_unlock();
1240 
1241 	return irk_to_return;
1242 }
1243 
1244 /* This function requires the caller holds hdev->link_keys_lock */
1245 struct link_key *__hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn,
1246 				    bdaddr_t *bdaddr, u8 *val, u8 type,
1247 				    u8 pin_len, bool *persistent)
1248 {
1249 	struct link_key *key, *old_key;
1250 	u8 old_key_type;
1251 
1252 	lockdep_assert_held(&hdev->link_keys_lock);
1253 
1254 	old_key = hci_find_link_key(hdev, bdaddr);
1255 	if (old_key) {
1256 		old_key_type = old_key->type;
1257 		key = old_key;
1258 	} else {
1259 		old_key_type = conn ? conn->key_type : 0xff;
1260 		key = kzalloc_obj(*key);
1261 		if (!key)
1262 			return NULL;
1263 	}
1264 
1265 	BT_DBG("%s key for %pMR type %u", hdev->name, bdaddr, type);
1266 
1267 	/* Some buggy controller combinations generate a changed
1268 	 * combination key for legacy pairing even when there's no
1269 	 * previous key */
1270 	if (type == HCI_LK_CHANGED_COMBINATION &&
1271 	    (!conn || conn->remote_auth == 0xff) && old_key_type == 0xff) {
1272 		type = HCI_LK_COMBINATION;
1273 		if (conn)
1274 			conn->key_type = type;
1275 	}
1276 
1277 	bacpy(&key->bdaddr, bdaddr);
1278 	memcpy(key->val, val, HCI_LINK_KEY_SIZE);
1279 	key->pin_len = pin_len;
1280 
1281 	if (type == HCI_LK_CHANGED_COMBINATION)
1282 		key->type = old_key_type;
1283 	else
1284 		key->type = type;
1285 
1286 	if (!old_key)
1287 		list_add_rcu(&key->list, &hdev->link_keys);
1288 
1289 	if (persistent)
1290 		*persistent = hci_persistent_key(hdev, conn, type,
1291 						 old_key_type);
1292 
1293 	return key;
1294 }
1295 
1296 /* The writers of hdev->link_keys are serialized with hdev->link_keys_lock
1297  * so the list can be modified without hdev->lock (e.g. from SMP, where it
1298  * can't be taken after the l2cap channel lock). The returned key is only
1299  * safe to use while hdev->lock is held, callers without it must use
1300  * __hci_add_link_key() and keep hdev->link_keys_lock while using the key.
1301  */
1302 struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn,
1303 				  bdaddr_t *bdaddr, u8 *val, u8 type,
1304 				  u8 pin_len, bool *persistent)
1305 {
1306 	struct link_key *key;
1307 
1308 	mutex_lock(&hdev->link_keys_lock);
1309 	key = __hci_add_link_key(hdev, conn, bdaddr, val, type, pin_len,
1310 				 persistent);
1311 	mutex_unlock(&hdev->link_keys_lock);
1312 
1313 	return key;
1314 }
1315 
1316 struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,
1317 			    u8 addr_type, u8 type, u8 authenticated,
1318 			    u8 tk[16], u8 enc_size, __le16 ediv, __le64 rand)
1319 {
1320 	struct smp_ltk *key, *old_key;
1321 	u8 role = ltk_role(type);
1322 
1323 	old_key = hci_find_ltk(hdev, bdaddr, addr_type, role);
1324 	if (old_key)
1325 		key = old_key;
1326 	else {
1327 		key = kzalloc_obj(*key);
1328 		if (!key)
1329 			return NULL;
1330 	}
1331 
1332 	bacpy(&key->bdaddr, bdaddr);
1333 	key->bdaddr_type = addr_type;
1334 	memcpy(key->val, tk, sizeof(key->val));
1335 	key->authenticated = authenticated;
1336 	key->ediv = ediv;
1337 	key->rand = rand;
1338 	key->enc_size = enc_size;
1339 	key->type = type;
1340 
1341 	if (!old_key)
1342 		list_add_rcu(&key->list, &hdev->long_term_keys);
1343 
1344 	return key;
1345 }
1346 
1347 struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr,
1348 			    u8 addr_type, u8 val[16], bdaddr_t *rpa)
1349 {
1350 	struct smp_irk *irk, *old_irk;
1351 
1352 	old_irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type);
1353 	irk = old_irk;
1354 	if (!irk) {
1355 		irk = kzalloc_obj(*irk);
1356 		if (!irk)
1357 			return NULL;
1358 
1359 		bacpy(&irk->bdaddr, bdaddr);
1360 		irk->addr_type = addr_type;
1361 
1362 	}
1363 
1364 	memcpy(irk->val, val, 16);
1365 	bacpy(&irk->rpa, rpa);
1366 
1367 	if (!old_irk)
1368 		list_add_rcu(&irk->list, &hdev->identity_resolving_keys);
1369 
1370 	return irk;
1371 }
1372 
1373 int hci_remove_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr)
1374 {
1375 	struct link_key *key;
1376 
1377 	mutex_lock(&hdev->link_keys_lock);
1378 
1379 	key = hci_find_link_key(hdev, bdaddr);
1380 	if (!key) {
1381 		mutex_unlock(&hdev->link_keys_lock);
1382 		return -ENOENT;
1383 	}
1384 
1385 	BT_DBG("%s removing %pMR", hdev->name, bdaddr);
1386 
1387 	list_del_rcu(&key->list);
1388 	kfree_rcu(key, rcu);
1389 
1390 	mutex_unlock(&hdev->link_keys_lock);
1391 
1392 	return 0;
1393 }
1394 
1395 /* Remove a key previously returned by hci_add_link_key(), unlike
1396  * hci_remove_link_key() this also works for keys that are blocked.
1397  */
1398 void hci_del_link_key(struct hci_dev *hdev, struct link_key *key)
1399 {
1400 	struct link_key *k;
1401 
1402 	mutex_lock(&hdev->link_keys_lock);
1403 
1404 	list_for_each_entry(k, &hdev->link_keys, list) {
1405 		if (k == key) {
1406 			list_del_rcu(&key->list);
1407 			kfree_rcu(key, rcu);
1408 			break;
1409 		}
1410 	}
1411 
1412 	mutex_unlock(&hdev->link_keys_lock);
1413 }
1414 
1415 int hci_remove_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 bdaddr_type)
1416 {
1417 	struct smp_ltk *k, *tmp;
1418 	int removed = 0;
1419 
1420 	list_for_each_entry_safe(k, tmp, &hdev->long_term_keys, list) {
1421 		if (bacmp(bdaddr, &k->bdaddr) || k->bdaddr_type != bdaddr_type)
1422 			continue;
1423 
1424 		BT_DBG("%s removing %pMR", hdev->name, bdaddr);
1425 
1426 		list_del_rcu(&k->list);
1427 		kfree_rcu(k, rcu);
1428 		removed++;
1429 	}
1430 
1431 	return removed ? 0 : -ENOENT;
1432 }
1433 
1434 void hci_remove_irk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 addr_type)
1435 {
1436 	struct smp_irk *k, *tmp;
1437 
1438 	list_for_each_entry_safe(k, tmp, &hdev->identity_resolving_keys, list) {
1439 		if (bacmp(bdaddr, &k->bdaddr) || k->addr_type != addr_type)
1440 			continue;
1441 
1442 		BT_DBG("%s removing %pMR", hdev->name, bdaddr);
1443 
1444 		list_del_rcu(&k->list);
1445 		kfree_rcu(k, rcu);
1446 	}
1447 }
1448 
1449 bool hci_bdaddr_is_paired(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 type)
1450 {
1451 	struct smp_ltk *k;
1452 	struct smp_irk *irk;
1453 	u8 addr_type;
1454 
1455 	if (type == BDADDR_BREDR) {
1456 		if (hci_find_link_key(hdev, bdaddr))
1457 			return true;
1458 		return false;
1459 	}
1460 
1461 	/* Convert to HCI addr type which struct smp_ltk uses */
1462 	if (type == BDADDR_LE_PUBLIC)
1463 		addr_type = ADDR_LE_DEV_PUBLIC;
1464 	else
1465 		addr_type = ADDR_LE_DEV_RANDOM;
1466 
1467 	irk = hci_get_irk(hdev, bdaddr, addr_type);
1468 	if (irk) {
1469 		bdaddr = &irk->bdaddr;
1470 		addr_type = irk->addr_type;
1471 	}
1472 
1473 	rcu_read_lock();
1474 	list_for_each_entry_rcu(k, &hdev->long_term_keys, list) {
1475 		if (k->bdaddr_type == addr_type && !bacmp(bdaddr, &k->bdaddr)) {
1476 			rcu_read_unlock();
1477 			return true;
1478 		}
1479 	}
1480 	rcu_read_unlock();
1481 
1482 	return false;
1483 }
1484 
1485 /* HCI command timer function */
1486 static void hci_cmd_timeout(struct work_struct *work)
1487 {
1488 	struct hci_dev *hdev = container_of(work, struct hci_dev,
1489 					    cmd_timer.work);
1490 
1491 	if (hdev->req_skb) {
1492 		u16 opcode = hci_skb_opcode(hdev->req_skb);
1493 
1494 		bt_dev_err(hdev, "command 0x%4.4x tx timeout", opcode);
1495 
1496 		hci_cmd_sync_cancel_sync(hdev, ETIMEDOUT);
1497 	} else {
1498 		bt_dev_err(hdev, "command tx timeout");
1499 	}
1500 
1501 	if (hdev->reset)
1502 		hdev->reset(hdev);
1503 
1504 	atomic_set(&hdev->cmd_cnt, 1);
1505 	queue_work(hdev->workqueue, &hdev->cmd_work);
1506 }
1507 
1508 /* HCI ncmd timer function */
1509 static void hci_ncmd_timeout(struct work_struct *work)
1510 {
1511 	struct hci_dev *hdev = container_of(work, struct hci_dev,
1512 					    ncmd_timer.work);
1513 
1514 	bt_dev_err(hdev, "Controller not accepting commands anymore: ncmd = 0");
1515 
1516 	/* During HCI_INIT phase no events can be injected if the ncmd timer
1517 	 * triggers since the procedure has its own timeout handling.
1518 	 */
1519 	if (test_bit(HCI_INIT, &hdev->flags))
1520 		return;
1521 
1522 	/* This is an irrecoverable state, inject hardware error event */
1523 	hci_reset_dev(hdev);
1524 }
1525 
1526 struct oob_data *hci_find_remote_oob_data(struct hci_dev *hdev,
1527 					  bdaddr_t *bdaddr, u8 bdaddr_type)
1528 {
1529 	struct oob_data *data;
1530 
1531 	list_for_each_entry(data, &hdev->remote_oob_data, list) {
1532 		if (bacmp(bdaddr, &data->bdaddr) != 0)
1533 			continue;
1534 		if (data->bdaddr_type != bdaddr_type)
1535 			continue;
1536 		return data;
1537 	}
1538 
1539 	return NULL;
1540 }
1541 
1542 int hci_remove_remote_oob_data(struct hci_dev *hdev, bdaddr_t *bdaddr,
1543 			       u8 bdaddr_type)
1544 {
1545 	struct oob_data *data;
1546 
1547 	data = hci_find_remote_oob_data(hdev, bdaddr, bdaddr_type);
1548 	if (!data)
1549 		return -ENOENT;
1550 
1551 	BT_DBG("%s removing %pMR (%u)", hdev->name, bdaddr, bdaddr_type);
1552 
1553 	mutex_lock(&hdev->remote_oob_lock);
1554 	list_del(&data->list);
1555 	kfree(data);
1556 	mutex_unlock(&hdev->remote_oob_lock);
1557 
1558 	return 0;
1559 }
1560 
1561 void hci_remote_oob_data_clear(struct hci_dev *hdev)
1562 {
1563 	struct oob_data *data, *n;
1564 
1565 	mutex_lock(&hdev->remote_oob_lock);
1566 	list_for_each_entry_safe(data, n, &hdev->remote_oob_data, list) {
1567 		list_del(&data->list);
1568 		kfree(data);
1569 	}
1570 	mutex_unlock(&hdev->remote_oob_lock);
1571 }
1572 
1573 int hci_add_remote_oob_data(struct hci_dev *hdev, bdaddr_t *bdaddr,
1574 			    u8 bdaddr_type, u8 *hash192, u8 *rand192,
1575 			    u8 *hash256, u8 *rand256)
1576 {
1577 	struct oob_data *data;
1578 
1579 	mutex_lock(&hdev->remote_oob_lock);
1580 	data = hci_find_remote_oob_data(hdev, bdaddr, bdaddr_type);
1581 	if (!data) {
1582 		data = kmalloc_obj(*data);
1583 		if (!data) {
1584 			mutex_unlock(&hdev->remote_oob_lock);
1585 			return -ENOMEM;
1586 		}
1587 
1588 		bacpy(&data->bdaddr, bdaddr);
1589 		data->bdaddr_type = bdaddr_type;
1590 		list_add(&data->list, &hdev->remote_oob_data);
1591 	}
1592 
1593 	if (hash192 && rand192) {
1594 		memcpy(data->hash192, hash192, sizeof(data->hash192));
1595 		memcpy(data->rand192, rand192, sizeof(data->rand192));
1596 		if (hash256 && rand256)
1597 			data->present = 0x03;
1598 	} else {
1599 		memset(data->hash192, 0, sizeof(data->hash192));
1600 		memset(data->rand192, 0, sizeof(data->rand192));
1601 		if (hash256 && rand256)
1602 			data->present = 0x02;
1603 		else
1604 			data->present = 0x00;
1605 	}
1606 
1607 	if (hash256 && rand256) {
1608 		memcpy(data->hash256, hash256, sizeof(data->hash256));
1609 		memcpy(data->rand256, rand256, sizeof(data->rand256));
1610 	} else {
1611 		memset(data->hash256, 0, sizeof(data->hash256));
1612 		memset(data->rand256, 0, sizeof(data->rand256));
1613 		if (hash192 && rand192)
1614 			data->present = 0x01;
1615 	}
1616 
1617 	BT_DBG("%s for %pMR", hdev->name, bdaddr);
1618 
1619 	mutex_unlock(&hdev->remote_oob_lock);
1620 
1621 	return 0;
1622 }
1623 
1624 /* This function requires the caller holds hdev->lock */
1625 struct adv_info *hci_find_adv_instance(struct hci_dev *hdev, u8 instance)
1626 {
1627 	struct adv_info *adv_instance;
1628 
1629 	list_for_each_entry(adv_instance, &hdev->adv_instances, list) {
1630 		if (adv_instance->instance == instance)
1631 			return adv_instance;
1632 	}
1633 
1634 	return NULL;
1635 }
1636 
1637 /* This function requires the caller holds hdev->lock */
1638 struct adv_info *hci_find_adv_sid(struct hci_dev *hdev, u8 sid)
1639 {
1640 	struct adv_info *adv;
1641 
1642 	list_for_each_entry(adv, &hdev->adv_instances, list) {
1643 		if (adv->sid == sid)
1644 			return adv;
1645 	}
1646 
1647 	return NULL;
1648 }
1649 
1650 /* This function requires the caller holds hdev->lock */
1651 struct adv_info *hci_get_next_instance(struct hci_dev *hdev, u8 instance)
1652 {
1653 	struct adv_info *cur_instance;
1654 
1655 	cur_instance = hci_find_adv_instance(hdev, instance);
1656 	if (!cur_instance)
1657 		return NULL;
1658 
1659 	if (cur_instance == list_last_entry(&hdev->adv_instances,
1660 					    struct adv_info, list))
1661 		return list_first_entry(&hdev->adv_instances,
1662 						 struct adv_info, list);
1663 	else
1664 		return list_next_entry(cur_instance, list);
1665 }
1666 
1667 /* This function requires the caller holds hdev->lock */
1668 void hci_free_adv_instance(struct hci_dev *hdev, struct adv_info *adv_instance)
1669 {
1670 	BT_DBG("%s removing %dMR", hdev->name, adv_instance->instance);
1671 
1672 	if (hdev->cur_adv_instance == adv_instance->instance) {
1673 		if (hdev->adv_instance_timeout) {
1674 			cancel_delayed_work(&hdev->adv_instance_expire);
1675 			hdev->adv_instance_timeout = false;
1676 		}
1677 		hdev->cur_adv_instance = 0x00;
1678 	}
1679 
1680 	cancel_delayed_work_sync(&adv_instance->rpa_expired_cb);
1681 
1682 	list_del(&adv_instance->list);
1683 	kfree(adv_instance);
1684 
1685 	hdev->adv_instance_cnt--;
1686 }
1687 
1688 /* This function requires the caller holds hdev->lock */
1689 int hci_remove_adv_instance(struct hci_dev *hdev, u8 instance)
1690 {
1691 	struct adv_info *adv_instance;
1692 
1693 	adv_instance = hci_find_adv_instance(hdev, instance);
1694 	if (!adv_instance)
1695 		return -ENOENT;
1696 
1697 	hci_free_adv_instance(hdev, adv_instance);
1698 
1699 	return 0;
1700 }
1701 
1702 void hci_adv_instances_set_rpa_expired(struct hci_dev *hdev, bool rpa_expired)
1703 {
1704 	struct adv_info *adv_instance, *n;
1705 
1706 	list_for_each_entry_safe(adv_instance, n, &hdev->adv_instances, list)
1707 		adv_instance->rpa_expired = rpa_expired;
1708 }
1709 
1710 /* This function requires the caller holds hdev->lock */
1711 void hci_adv_instances_clear(struct hci_dev *hdev)
1712 {
1713 	struct adv_info *adv_instance, *n;
1714 
1715 	if (hdev->adv_instance_timeout) {
1716 		disable_delayed_work(&hdev->adv_instance_expire);
1717 		hdev->adv_instance_timeout = false;
1718 	}
1719 
1720 	list_for_each_entry_safe(adv_instance, n, &hdev->adv_instances, list) {
1721 		disable_delayed_work_sync(&adv_instance->rpa_expired_cb);
1722 		list_del(&adv_instance->list);
1723 		kfree(adv_instance);
1724 	}
1725 
1726 	hdev->adv_instance_cnt = 0;
1727 	hdev->cur_adv_instance = 0x00;
1728 }
1729 
1730 static void adv_instance_rpa_expired(struct work_struct *work)
1731 {
1732 	struct adv_info *adv_instance = container_of(work, struct adv_info,
1733 						     rpa_expired_cb.work);
1734 
1735 	BT_DBG("");
1736 
1737 	adv_instance->rpa_expired = true;
1738 }
1739 
1740 /* This function requires the caller holds hdev->lock */
1741 struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance,
1742 				      u32 flags, u16 adv_data_len, u8 *adv_data,
1743 				      u16 scan_rsp_len, u8 *scan_rsp_data,
1744 				      u16 timeout, u16 duration, s8 tx_power,
1745 				      u32 min_interval, u32 max_interval,
1746 				      u8 mesh_handle)
1747 {
1748 	struct adv_info *adv;
1749 
1750 	adv = hci_find_adv_instance(hdev, instance);
1751 	if (adv) {
1752 		memset(adv->adv_data, 0, sizeof(adv->adv_data));
1753 		memset(adv->scan_rsp_data, 0, sizeof(adv->scan_rsp_data));
1754 		memset(adv->per_adv_data, 0, sizeof(adv->per_adv_data));
1755 	} else {
1756 		if (hdev->adv_instance_cnt >= hdev->le_num_of_adv_sets ||
1757 		    instance < 1 || instance > hdev->le_num_of_adv_sets + 1)
1758 			return ERR_PTR(-EOVERFLOW);
1759 
1760 		adv = kzalloc_obj(*adv);
1761 		if (!adv)
1762 			return ERR_PTR(-ENOMEM);
1763 
1764 		INIT_DELAYED_WORK(&adv->rpa_expired_cb,
1765 				  adv_instance_rpa_expired);
1766 
1767 		adv->pending = true;
1768 		adv->instance = instance;
1769 
1770 		/* If controller support only one set and the instance is set to
1771 		 * 1 then there is no option other than using handle 0x00.
1772 		 */
1773 		if (hdev->le_num_of_adv_sets == 1 && instance == 1)
1774 			adv->handle = 0x00;
1775 		else
1776 			adv->handle = instance;
1777 
1778 		list_add(&adv->list, &hdev->adv_instances);
1779 		hdev->adv_instance_cnt++;
1780 	}
1781 
1782 	adv->flags = flags;
1783 	adv->min_interval = min_interval;
1784 	adv->max_interval = max_interval;
1785 	adv->tx_power = tx_power;
1786 	/* Defining a mesh_handle changes the timing units to ms,
1787 	 * rather than seconds, and ties the instance to the requested
1788 	 * mesh_tx queue.
1789 	 */
1790 	adv->mesh = mesh_handle;
1791 
1792 	hci_set_adv_instance_data(hdev, instance, adv_data_len, adv_data,
1793 				  scan_rsp_len, scan_rsp_data);
1794 
1795 	adv->timeout = timeout;
1796 	adv->remaining_time = timeout;
1797 
1798 	if (duration == 0)
1799 		adv->duration = hdev->def_multi_adv_rotation_duration;
1800 	else
1801 		adv->duration = duration;
1802 
1803 	BT_DBG("%s for %dMR", hdev->name, instance);
1804 
1805 	return adv;
1806 }
1807 
1808 /* This function requires the caller holds hdev->lock */
1809 struct adv_info *hci_add_per_instance(struct hci_dev *hdev, u8 instance, u8 sid,
1810 				      u32 flags, u8 data_len, u8 *data,
1811 				      u32 min_interval, u32 max_interval)
1812 {
1813 	struct adv_info *adv;
1814 
1815 	adv = hci_add_adv_instance(hdev, instance, flags, 0, NULL, 0, NULL,
1816 				   0, 0, HCI_ADV_TX_POWER_NO_PREFERENCE,
1817 				   min_interval, max_interval, 0);
1818 	if (IS_ERR(adv))
1819 		return adv;
1820 
1821 	adv->sid = sid;
1822 	adv->periodic = true;
1823 	adv->per_adv_data_len = data_len;
1824 
1825 	if (data)
1826 		memcpy(adv->per_adv_data, data, data_len);
1827 
1828 	return adv;
1829 }
1830 
1831 /* This function requires the caller holds hdev->lock */
1832 int hci_set_adv_instance_data(struct hci_dev *hdev, u8 instance,
1833 			      u16 adv_data_len, u8 *adv_data,
1834 			      u16 scan_rsp_len, u8 *scan_rsp_data)
1835 {
1836 	struct adv_info *adv;
1837 
1838 	adv = hci_find_adv_instance(hdev, instance);
1839 
1840 	/* If advertisement doesn't exist, we can't modify its data */
1841 	if (!adv)
1842 		return -ENOENT;
1843 
1844 	if (adv_data_len && ADV_DATA_CMP(adv, adv_data, adv_data_len)) {
1845 		memset(adv->adv_data, 0, sizeof(adv->adv_data));
1846 		memcpy(adv->adv_data, adv_data, adv_data_len);
1847 		adv->adv_data_len = adv_data_len;
1848 		adv->adv_data_changed = true;
1849 	}
1850 
1851 	if (scan_rsp_len && SCAN_RSP_CMP(adv, scan_rsp_data, scan_rsp_len)) {
1852 		memset(adv->scan_rsp_data, 0, sizeof(adv->scan_rsp_data));
1853 		memcpy(adv->scan_rsp_data, scan_rsp_data, scan_rsp_len);
1854 		adv->scan_rsp_len = scan_rsp_len;
1855 		adv->scan_rsp_changed = true;
1856 	}
1857 
1858 	/* Mark as changed if there are flags which would affect it */
1859 	if (((adv->flags & MGMT_ADV_FLAG_APPEARANCE) && hdev->appearance) ||
1860 	    adv->flags & MGMT_ADV_FLAG_LOCAL_NAME)
1861 		adv->scan_rsp_changed = true;
1862 
1863 	return 0;
1864 }
1865 
1866 /* This function requires the caller holds hdev->lock */
1867 u32 hci_adv_instance_flags(struct hci_dev *hdev, u8 instance)
1868 {
1869 	u32 flags;
1870 	struct adv_info *adv;
1871 
1872 	if (instance == 0x00) {
1873 		/* Instance 0 always manages the "Tx Power" and "Flags"
1874 		 * fields
1875 		 */
1876 		flags = MGMT_ADV_FLAG_TX_POWER | MGMT_ADV_FLAG_MANAGED_FLAGS;
1877 
1878 		/* For instance 0, the HCI_ADVERTISING_CONNECTABLE setting
1879 		 * corresponds to the "connectable" instance flag.
1880 		 */
1881 		if (hci_dev_test_flag(hdev, HCI_ADVERTISING_CONNECTABLE))
1882 			flags |= MGMT_ADV_FLAG_CONNECTABLE;
1883 
1884 		if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE))
1885 			flags |= MGMT_ADV_FLAG_LIMITED_DISCOV;
1886 		else if (hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
1887 			flags |= MGMT_ADV_FLAG_DISCOV;
1888 
1889 		return flags;
1890 	}
1891 
1892 	adv = hci_find_adv_instance(hdev, instance);
1893 
1894 	/* Return 0 when we got an invalid instance identifier. */
1895 	if (!adv)
1896 		return 0;
1897 
1898 	return adv->flags;
1899 }
1900 
1901 bool hci_adv_instance_is_scannable(struct hci_dev *hdev, u8 instance)
1902 {
1903 	struct adv_info *adv;
1904 
1905 	/* Instance 0x00 always set local name */
1906 	if (instance == 0x00)
1907 		return true;
1908 
1909 	adv = hci_find_adv_instance(hdev, instance);
1910 	if (!adv)
1911 		return false;
1912 
1913 	if (adv->flags & MGMT_ADV_FLAG_APPEARANCE ||
1914 	    adv->flags & MGMT_ADV_FLAG_LOCAL_NAME)
1915 		return true;
1916 
1917 	return adv->scan_rsp_len ? true : false;
1918 }
1919 
1920 /* This function requires the caller holds hdev->lock */
1921 void hci_adv_monitors_clear(struct hci_dev *hdev)
1922 {
1923 	struct adv_monitor *monitor;
1924 	int handle;
1925 
1926 	idr_for_each_entry(&hdev->adv_monitors_idr, monitor, handle)
1927 		hci_free_adv_monitor(hdev, monitor);
1928 
1929 	idr_destroy(&hdev->adv_monitors_idr);
1930 }
1931 
1932 /* Frees the monitor structure and do some bookkeepings.
1933  * This function requires the caller holds hdev->lock.
1934  */
1935 void hci_free_adv_monitor(struct hci_dev *hdev, struct adv_monitor *monitor)
1936 {
1937 	struct adv_pattern *pattern;
1938 	struct adv_pattern *tmp;
1939 
1940 	if (!monitor)
1941 		return;
1942 
1943 	list_for_each_entry_safe(pattern, tmp, &monitor->patterns, list) {
1944 		list_del(&pattern->list);
1945 		kfree(pattern);
1946 	}
1947 
1948 	if (monitor->handle)
1949 		idr_remove(&hdev->adv_monitors_idr, monitor->handle);
1950 
1951 	if (monitor->state != ADV_MONITOR_STATE_NOT_REGISTERED)
1952 		hdev->adv_monitors_cnt--;
1953 
1954 	kfree(monitor);
1955 }
1956 
1957 /* Assigns handle to a monitor, and if offloading is supported and power is on,
1958  * also attempts to forward the request to the controller.
1959  * This function requires the caller holds hci_req_sync_lock.
1960  */
1961 int hci_add_adv_monitor(struct hci_dev *hdev, struct adv_monitor *monitor)
1962 {
1963 	int min, max, handle;
1964 	int status = 0;
1965 
1966 	if (!monitor)
1967 		return -EINVAL;
1968 
1969 	hci_dev_lock(hdev);
1970 
1971 	min = HCI_MIN_ADV_MONITOR_HANDLE;
1972 	max = HCI_MIN_ADV_MONITOR_HANDLE + HCI_MAX_ADV_MONITOR_NUM_HANDLES;
1973 	handle = idr_alloc(&hdev->adv_monitors_idr, monitor, min, max,
1974 			   GFP_KERNEL);
1975 
1976 	hci_dev_unlock(hdev);
1977 
1978 	if (handle < 0)
1979 		return handle;
1980 
1981 	monitor->handle = handle;
1982 
1983 	if (!hdev_is_powered(hdev))
1984 		return status;
1985 
1986 	switch (hci_get_adv_monitor_offload_ext(hdev)) {
1987 	case HCI_ADV_MONITOR_EXT_NONE:
1988 		bt_dev_dbg(hdev, "add monitor %d status %d",
1989 			   monitor->handle, status);
1990 		/* Message was not forwarded to controller - not an error */
1991 		break;
1992 
1993 	case HCI_ADV_MONITOR_EXT_MSFT:
1994 		status = msft_add_monitor_pattern(hdev, monitor);
1995 		bt_dev_dbg(hdev, "add monitor %d msft status %d",
1996 			   handle, status);
1997 		break;
1998 	}
1999 
2000 	return status;
2001 }
2002 
2003 /* Attempts to tell the controller and free the monitor. If somehow the
2004  * controller doesn't have a corresponding handle, remove anyway.
2005  * This function requires the caller holds hci_req_sync_lock.
2006  */
2007 static int hci_remove_adv_monitor(struct hci_dev *hdev,
2008 				  struct adv_monitor *monitor)
2009 {
2010 	int status = 0;
2011 	int handle;
2012 
2013 	switch (hci_get_adv_monitor_offload_ext(hdev)) {
2014 	case HCI_ADV_MONITOR_EXT_NONE: /* also goes here when powered off */
2015 		bt_dev_dbg(hdev, "remove monitor %d status %d",
2016 			   monitor->handle, status);
2017 		goto free_monitor;
2018 
2019 	case HCI_ADV_MONITOR_EXT_MSFT:
2020 		handle = monitor->handle;
2021 		status = msft_remove_monitor(hdev, monitor);
2022 		bt_dev_dbg(hdev, "remove monitor %d msft status %d",
2023 			   handle, status);
2024 		break;
2025 	}
2026 
2027 	/* In case no matching handle registered, just free the monitor */
2028 	if (status == -ENOENT)
2029 		goto free_monitor;
2030 
2031 	return status;
2032 
2033 free_monitor:
2034 	if (status == -ENOENT)
2035 		bt_dev_warn(hdev, "Removing monitor with no matching handle %d",
2036 			    monitor->handle);
2037 
2038 	hci_dev_lock(hdev);
2039 	hci_free_adv_monitor(hdev, monitor);
2040 	hci_dev_unlock(hdev);
2041 
2042 	/* The monitor is gone, not having been known by the controller is not
2043 	 * an error for the caller.
2044 	 */
2045 	return status == -ENOENT ? 0 : status;
2046 }
2047 
2048 /* This function requires the caller holds hci_req_sync_lock */
2049 int hci_remove_single_adv_monitor(struct hci_dev *hdev, u16 handle)
2050 {
2051 	struct adv_monitor *monitor;
2052 
2053 	hci_dev_lock(hdev);
2054 	monitor = idr_find(&hdev->adv_monitors_idr, handle);
2055 	hci_dev_unlock(hdev);
2056 
2057 	if (!monitor)
2058 		return -EINVAL;
2059 
2060 	return hci_remove_adv_monitor(hdev, monitor);
2061 }
2062 
2063 /* This function requires the caller holds hci_req_sync_lock */
2064 int hci_remove_all_adv_monitor(struct hci_dev *hdev)
2065 {
2066 	struct adv_monitor *monitor;
2067 	int idr_next_id = 0;
2068 	int status = 0;
2069 
2070 	while (1) {
2071 		hci_dev_lock(hdev);
2072 		monitor = idr_get_next(&hdev->adv_monitors_idr, &idr_next_id);
2073 		hci_dev_unlock(hdev);
2074 
2075 		if (!monitor)
2076 			break;
2077 
2078 		status = hci_remove_adv_monitor(hdev, monitor);
2079 		if (status)
2080 			return status;
2081 
2082 		idr_next_id++;
2083 	}
2084 
2085 	return status;
2086 }
2087 
2088 /* This function requires the caller holds hdev->lock */
2089 bool hci_is_adv_monitoring(struct hci_dev *hdev)
2090 {
2091 	return !idr_is_empty(&hdev->adv_monitors_idr);
2092 }
2093 
2094 int hci_get_adv_monitor_offload_ext(struct hci_dev *hdev)
2095 {
2096 	if (msft_monitor_supported(hdev))
2097 		return HCI_ADV_MONITOR_EXT_MSFT;
2098 
2099 	return HCI_ADV_MONITOR_EXT_NONE;
2100 }
2101 
2102 struct bdaddr_list *hci_bdaddr_list_lookup(struct list_head *bdaddr_list,
2103 					 bdaddr_t *bdaddr, u8 type)
2104 {
2105 	struct bdaddr_list *b;
2106 
2107 	list_for_each_entry(b, bdaddr_list, list) {
2108 		if (!bacmp(&b->bdaddr, bdaddr) && b->bdaddr_type == type)
2109 			return b;
2110 	}
2111 
2112 	return NULL;
2113 }
2114 
2115 struct bdaddr_list_with_irk *hci_bdaddr_list_lookup_with_irk(
2116 				struct list_head *bdaddr_list, bdaddr_t *bdaddr,
2117 				u8 type)
2118 {
2119 	struct bdaddr_list_with_irk *b;
2120 
2121 	list_for_each_entry(b, bdaddr_list, list) {
2122 		if (!bacmp(&b->bdaddr, bdaddr) && b->bdaddr_type == type)
2123 			return b;
2124 	}
2125 
2126 	return NULL;
2127 }
2128 
2129 struct bdaddr_list_with_flags *
2130 hci_bdaddr_list_lookup_with_flags(struct list_head *bdaddr_list,
2131 				  bdaddr_t *bdaddr, u8 type)
2132 {
2133 	struct bdaddr_list_with_flags *b;
2134 
2135 	list_for_each_entry(b, bdaddr_list, list) {
2136 		if (!bacmp(&b->bdaddr, bdaddr) && b->bdaddr_type == type)
2137 			return b;
2138 	}
2139 
2140 	return NULL;
2141 }
2142 
2143 void hci_bdaddr_list_clear(struct list_head *bdaddr_list)
2144 {
2145 	struct bdaddr_list *b, *n;
2146 
2147 	list_for_each_entry_safe(b, n, bdaddr_list, list) {
2148 		list_del(&b->list);
2149 		kfree(b);
2150 	}
2151 }
2152 
2153 int hci_bdaddr_list_add(struct list_head *list, bdaddr_t *bdaddr, u8 type)
2154 {
2155 	struct bdaddr_list *entry;
2156 
2157 	if (!bacmp(bdaddr, BDADDR_ANY))
2158 		return -EBADF;
2159 
2160 	if (hci_bdaddr_list_lookup(list, bdaddr, type))
2161 		return -EEXIST;
2162 
2163 	entry = kzalloc_obj(*entry);
2164 	if (!entry)
2165 		return -ENOMEM;
2166 
2167 	bacpy(&entry->bdaddr, bdaddr);
2168 	entry->bdaddr_type = type;
2169 
2170 	list_add(&entry->list, list);
2171 
2172 	return 0;
2173 }
2174 
2175 int hci_bdaddr_list_add_with_irk(struct list_head *list, bdaddr_t *bdaddr,
2176 					u8 type, u8 *peer_irk, u8 *local_irk)
2177 {
2178 	struct bdaddr_list_with_irk *entry;
2179 
2180 	if (!bacmp(bdaddr, BDADDR_ANY))
2181 		return -EBADF;
2182 
2183 	if (hci_bdaddr_list_lookup(list, bdaddr, type))
2184 		return -EEXIST;
2185 
2186 	entry = kzalloc_obj(*entry);
2187 	if (!entry)
2188 		return -ENOMEM;
2189 
2190 	bacpy(&entry->bdaddr, bdaddr);
2191 	entry->bdaddr_type = type;
2192 
2193 	if (peer_irk)
2194 		memcpy(entry->peer_irk, peer_irk, 16);
2195 
2196 	if (local_irk)
2197 		memcpy(entry->local_irk, local_irk, 16);
2198 
2199 	list_add(&entry->list, list);
2200 
2201 	return 0;
2202 }
2203 
2204 int hci_bdaddr_list_add_with_flags(struct list_head *list, bdaddr_t *bdaddr,
2205 				   u8 type, u32 flags)
2206 {
2207 	struct bdaddr_list_with_flags *entry;
2208 
2209 	if (!bacmp(bdaddr, BDADDR_ANY))
2210 		return -EBADF;
2211 
2212 	if (hci_bdaddr_list_lookup(list, bdaddr, type))
2213 		return -EEXIST;
2214 
2215 	entry = kzalloc_obj(*entry);
2216 	if (!entry)
2217 		return -ENOMEM;
2218 
2219 	bacpy(&entry->bdaddr, bdaddr);
2220 	entry->bdaddr_type = type;
2221 	entry->flags = flags;
2222 
2223 	list_add(&entry->list, list);
2224 
2225 	return 0;
2226 }
2227 
2228 int hci_bdaddr_list_del(struct list_head *list, bdaddr_t *bdaddr, u8 type)
2229 {
2230 	struct bdaddr_list *entry;
2231 
2232 	if (!bacmp(bdaddr, BDADDR_ANY)) {
2233 		hci_bdaddr_list_clear(list);
2234 		return 0;
2235 	}
2236 
2237 	entry = hci_bdaddr_list_lookup(list, bdaddr, type);
2238 	if (!entry)
2239 		return -ENOENT;
2240 
2241 	list_del(&entry->list);
2242 	kfree(entry);
2243 
2244 	return 0;
2245 }
2246 
2247 int hci_bdaddr_list_del_with_irk(struct list_head *list, bdaddr_t *bdaddr,
2248 							u8 type)
2249 {
2250 	struct bdaddr_list_with_irk *entry;
2251 
2252 	if (!bacmp(bdaddr, BDADDR_ANY)) {
2253 		hci_bdaddr_list_clear(list);
2254 		return 0;
2255 	}
2256 
2257 	entry = hci_bdaddr_list_lookup_with_irk(list, bdaddr, type);
2258 	if (!entry)
2259 		return -ENOENT;
2260 
2261 	list_del(&entry->list);
2262 	kfree(entry);
2263 
2264 	return 0;
2265 }
2266 
2267 /* This function requires the caller holds hdev->lock */
2268 struct hci_conn_params *hci_conn_params_lookup(struct hci_dev *hdev,
2269 					       bdaddr_t *addr, u8 addr_type)
2270 {
2271 	struct hci_conn_params *params;
2272 
2273 	list_for_each_entry(params, &hdev->le_conn_params, list) {
2274 		if (bacmp(&params->addr, addr) == 0 &&
2275 		    params->addr_type == addr_type) {
2276 			return params;
2277 		}
2278 	}
2279 
2280 	return NULL;
2281 }
2282 
2283 /* This function requires the caller holds hdev->lock or rcu_read_lock */
2284 struct hci_conn_params *hci_pend_le_action_lookup(struct list_head *list,
2285 						  bdaddr_t *addr, u8 addr_type)
2286 {
2287 	struct hci_conn_params *param;
2288 
2289 	rcu_read_lock();
2290 
2291 	list_for_each_entry_rcu(param, list, action) {
2292 		if (bacmp(&param->addr, addr) == 0 &&
2293 		    param->addr_type == addr_type) {
2294 			rcu_read_unlock();
2295 			return param;
2296 		}
2297 	}
2298 
2299 	rcu_read_unlock();
2300 
2301 	return NULL;
2302 }
2303 
2304 /* This function requires the caller holds hdev->lock */
2305 void hci_pend_le_list_del_init(struct hci_conn_params *param)
2306 {
2307 	if (list_empty(&param->action))
2308 		return;
2309 
2310 	list_del_rcu(&param->action);
2311 	synchronize_rcu();
2312 	INIT_LIST_HEAD(&param->action);
2313 }
2314 
2315 /* This function requires the caller holds hdev->lock */
2316 void hci_pend_le_list_add(struct hci_conn_params *param,
2317 			  struct list_head *list)
2318 {
2319 	list_add_rcu(&param->action, list);
2320 }
2321 
2322 /* This function requires the caller holds hdev->lock */
2323 struct hci_conn_params *hci_conn_params_add(struct hci_dev *hdev,
2324 					    bdaddr_t *addr, u8 addr_type)
2325 {
2326 	struct hci_conn_params *params;
2327 
2328 	params = hci_conn_params_lookup(hdev, addr, addr_type);
2329 	if (params)
2330 		return params;
2331 
2332 	params = kzalloc_obj(*params);
2333 	if (!params) {
2334 		bt_dev_err(hdev, "out of memory");
2335 		return NULL;
2336 	}
2337 
2338 	bacpy(&params->addr, addr);
2339 	params->addr_type = addr_type;
2340 
2341 	list_add(&params->list, &hdev->le_conn_params);
2342 	INIT_LIST_HEAD(&params->action);
2343 
2344 	params->conn_min_interval = hdev->le_conn_min_interval;
2345 	params->conn_max_interval = hdev->le_conn_max_interval;
2346 	params->conn_latency = hdev->le_conn_latency;
2347 	params->supervision_timeout = hdev->le_supv_timeout;
2348 	params->auto_connect = HCI_AUTO_CONN_DISABLED;
2349 
2350 	BT_DBG("addr %pMR (type %u)", addr, addr_type);
2351 
2352 	return params;
2353 }
2354 
2355 void hci_conn_params_free(struct hci_conn_params *params)
2356 {
2357 	hci_pend_le_list_del_init(params);
2358 
2359 	if (params->conn) {
2360 		hci_conn_drop(params->conn);
2361 		hci_conn_put(params->conn);
2362 	}
2363 
2364 	list_del(&params->list);
2365 	kfree(params);
2366 }
2367 
2368 /* This function requires the caller holds hdev->lock */
2369 void hci_conn_params_del(struct hci_dev *hdev, bdaddr_t *addr, u8 addr_type)
2370 {
2371 	struct hci_conn_params *params;
2372 
2373 	params = hci_conn_params_lookup(hdev, addr, addr_type);
2374 	if (!params)
2375 		return;
2376 
2377 	hci_conn_params_free(params);
2378 
2379 	hci_update_passive_scan(hdev);
2380 
2381 	BT_DBG("addr %pMR (type %u)", addr, addr_type);
2382 }
2383 
2384 /* This function requires the caller holds hdev->lock */
2385 void hci_conn_params_clear_disabled(struct hci_dev *hdev)
2386 {
2387 	struct hci_conn_params *params, *tmp;
2388 
2389 	list_for_each_entry_safe(params, tmp, &hdev->le_conn_params, list) {
2390 		if (params->auto_connect != HCI_AUTO_CONN_DISABLED)
2391 			continue;
2392 
2393 		/* If trying to establish one time connection to disabled
2394 		 * device, leave the params, but mark them as just once.
2395 		 */
2396 		if (params->explicit_connect) {
2397 			params->auto_connect = HCI_AUTO_CONN_EXPLICIT;
2398 			continue;
2399 		}
2400 
2401 		hci_conn_params_free(params);
2402 	}
2403 
2404 	BT_DBG("All LE disabled connection parameters were removed");
2405 }
2406 
2407 /* This function requires the caller holds hdev->lock */
2408 static void hci_conn_params_clear_all(struct hci_dev *hdev)
2409 {
2410 	struct hci_conn_params *params, *tmp;
2411 
2412 	list_for_each_entry_safe(params, tmp, &hdev->le_conn_params, list)
2413 		hci_conn_params_free(params);
2414 
2415 	BT_DBG("All LE connection parameters were removed");
2416 }
2417 
2418 /* Copy the Identity Address of the controller.
2419  *
2420  * If the controller has a public BD_ADDR, then by default use that one.
2421  * If this is a LE only controller without a public address, default to
2422  * the static random address.
2423  *
2424  * For debugging purposes it is possible to force controllers with a
2425  * public address to use the static random address instead.
2426  *
2427  * In case BR/EDR has been disabled on a dual-mode controller and
2428  * userspace has configured a static address, then that address
2429  * becomes the identity address instead of the public BR/EDR address.
2430  */
2431 void hci_copy_identity_address(struct hci_dev *hdev, bdaddr_t *bdaddr,
2432 			       u8 *bdaddr_type)
2433 {
2434 	if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
2435 	    !bacmp(&hdev->bdaddr, BDADDR_ANY) ||
2436 	    (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) &&
2437 	     bacmp(&hdev->static_addr, BDADDR_ANY))) {
2438 		bacpy(bdaddr, &hdev->static_addr);
2439 		*bdaddr_type = ADDR_LE_DEV_RANDOM;
2440 	} else {
2441 		bacpy(bdaddr, &hdev->bdaddr);
2442 		*bdaddr_type = ADDR_LE_DEV_PUBLIC;
2443 	}
2444 }
2445 
2446 static void hci_clear_wake_reason(struct hci_dev *hdev)
2447 {
2448 	hci_dev_lock(hdev);
2449 
2450 	hdev->wake_reason = 0;
2451 	bacpy(&hdev->wake_addr, BDADDR_ANY);
2452 	hdev->wake_addr_type = 0;
2453 
2454 	hci_dev_unlock(hdev);
2455 }
2456 
2457 static int hci_suspend_notifier(struct notifier_block *nb, unsigned long action,
2458 				void *data)
2459 {
2460 	struct hci_dev *hdev =
2461 		container_of(nb, struct hci_dev, suspend_notifier);
2462 	int ret = 0;
2463 
2464 	/* Userspace has full control of this device. Do nothing. */
2465 	if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL))
2466 		return NOTIFY_DONE;
2467 
2468 	/* To avoid a potential race with hci_unregister_dev. */
2469 	hci_dev_hold(hdev);
2470 
2471 	switch (action) {
2472 	case PM_HIBERNATION_PREPARE:
2473 	case PM_SUSPEND_PREPARE:
2474 		ret = hci_suspend_dev(hdev);
2475 		break;
2476 	case PM_POST_HIBERNATION:
2477 	case PM_POST_SUSPEND:
2478 		ret = hci_resume_dev(hdev);
2479 		break;
2480 	}
2481 
2482 	if (ret)
2483 		bt_dev_err(hdev, "Suspend notifier action (%lu) failed: %d",
2484 			   action, ret);
2485 
2486 	hci_dev_put(hdev);
2487 	return NOTIFY_DONE;
2488 }
2489 
2490 /* Alloc HCI device */
2491 struct hci_dev *hci_alloc_dev_priv(int sizeof_priv)
2492 {
2493 	struct hci_dev *hdev;
2494 	unsigned int alloc_size;
2495 
2496 	alloc_size = sizeof(*hdev);
2497 	if (sizeof_priv) {
2498 		/* Fixme: May need ALIGN-ment? */
2499 		alloc_size += sizeof_priv;
2500 	}
2501 
2502 	hdev = kzalloc(alloc_size, GFP_KERNEL);
2503 	if (!hdev)
2504 		return NULL;
2505 
2506 	if (init_srcu_struct(&hdev->srcu)) {
2507 		kfree(hdev);
2508 		return NULL;
2509 	}
2510 
2511 	hdev->pkt_type  = (HCI_DM1 | HCI_DH1 | HCI_HV1);
2512 	hdev->esco_type = (ESCO_HV1);
2513 	hdev->link_mode = (HCI_LM_ACCEPT);
2514 	hdev->num_iac = 0x01;		/* One IAC support is mandatory */
2515 	hdev->io_capability = 0x03;	/* No Input No Output */
2516 	hdev->manufacturer = 0xffff;	/* Default to internal use */
2517 	hdev->inq_tx_power = HCI_TX_POWER_INVALID;
2518 	hdev->adv_tx_power = HCI_TX_POWER_INVALID;
2519 	hdev->adv_instance_cnt = 0;
2520 	hdev->cur_adv_instance = 0x00;
2521 	hdev->adv_instance_timeout = false;
2522 
2523 	hdev->advmon_allowlist_duration = 300;
2524 	hdev->advmon_no_filter_duration = 500;
2525 	hdev->enable_advmon_interleave_scan = 0x00;	/* Default to disable */
2526 
2527 	hdev->sniff_max_interval = 800;
2528 	hdev->sniff_min_interval = 80;
2529 
2530 	hdev->le_adv_channel_map = 0x07;
2531 	hdev->le_adv_min_interval = 0x0800;
2532 	hdev->le_adv_max_interval = 0x0800;
2533 	hdev->le_scan_interval = DISCOV_LE_SCAN_INT_FAST;
2534 	hdev->le_scan_window = DISCOV_LE_SCAN_WIN_FAST;
2535 	hdev->le_scan_int_suspend = DISCOV_LE_SCAN_INT_SLOW1;
2536 	hdev->le_scan_window_suspend = DISCOV_LE_SCAN_WIN_SLOW1;
2537 	hdev->le_scan_int_discovery = DISCOV_LE_SCAN_INT;
2538 	hdev->le_scan_window_discovery = DISCOV_LE_SCAN_WIN;
2539 	hdev->le_scan_int_adv_monitor = DISCOV_LE_SCAN_INT_FAST;
2540 	hdev->le_scan_window_adv_monitor = DISCOV_LE_SCAN_WIN_FAST;
2541 	hdev->le_scan_int_connect = DISCOV_LE_SCAN_INT_CONN;
2542 	hdev->le_scan_window_connect = DISCOV_LE_SCAN_WIN_CONN;
2543 	hdev->le_conn_min_interval = 0x0018;
2544 	hdev->le_conn_max_interval = 0x0028;
2545 	hdev->le_conn_latency = 0x0000;
2546 	hdev->le_supv_timeout = 0x002a;
2547 	hdev->le_def_tx_len = 0x001b;
2548 	hdev->le_def_tx_time = 0x0148;
2549 	hdev->le_max_tx_len = 0x001b;
2550 	hdev->le_max_tx_time = 0x0148;
2551 	hdev->le_max_rx_len = 0x001b;
2552 	hdev->le_max_rx_time = 0x0148;
2553 	hdev->le_max_key_size = SMP_MAX_ENC_KEY_SIZE;
2554 	hdev->le_min_key_size = SMP_MIN_ENC_KEY_SIZE;
2555 	hdev->le_tx_def_phys = HCI_LE_SET_PHY_1M;
2556 	hdev->le_rx_def_phys = HCI_LE_SET_PHY_1M;
2557 	hdev->le_num_of_adv_sets = HCI_MAX_ADV_INSTANCES;
2558 	hdev->def_multi_adv_rotation_duration = HCI_DEFAULT_ADV_DURATION;
2559 	hdev->def_le_autoconnect_timeout = HCI_LE_CONN_TIMEOUT;
2560 	hdev->min_le_tx_power = HCI_TX_POWER_INVALID;
2561 	hdev->max_le_tx_power = HCI_TX_POWER_INVALID;
2562 
2563 	hdev->rpa_timeout = HCI_DEFAULT_RPA_TIMEOUT;
2564 	hdev->discov_interleaved_timeout = DISCOV_INTERLEAVED_TIMEOUT;
2565 	hdev->conn_info_min_age = DEFAULT_CONN_INFO_MIN_AGE;
2566 	hdev->conn_info_max_age = DEFAULT_CONN_INFO_MAX_AGE;
2567 	hdev->auth_payload_timeout = DEFAULT_AUTH_PAYLOAD_TIMEOUT;
2568 	hdev->min_enc_key_size = HCI_MIN_ENC_KEY_SIZE;
2569 
2570 	/* default 1.28 sec page scan */
2571 	hdev->def_page_scan_type = PAGE_SCAN_TYPE_STANDARD;
2572 	hdev->def_page_scan_int = 0x0800;
2573 	hdev->def_page_scan_window = 0x0012;
2574 
2575 	mutex_init(&hdev->lock);
2576 	mutex_init(&hdev->link_keys_lock);
2577 	mutex_init(&hdev->req_lock);
2578 	mutex_init(&hdev->mgmt_pending_lock);
2579 	mutex_init(&hdev->remote_oob_lock);
2580 
2581 	ida_init(&hdev->unset_handle_ida);
2582 
2583 	INIT_LIST_HEAD(&hdev->mesh_pending);
2584 	INIT_LIST_HEAD(&hdev->mgmt_pending);
2585 	INIT_LIST_HEAD(&hdev->reject_list);
2586 	INIT_LIST_HEAD(&hdev->accept_list);
2587 	INIT_LIST_HEAD(&hdev->uuids);
2588 	INIT_LIST_HEAD(&hdev->link_keys);
2589 	INIT_LIST_HEAD(&hdev->long_term_keys);
2590 	INIT_LIST_HEAD(&hdev->identity_resolving_keys);
2591 	INIT_LIST_HEAD(&hdev->remote_oob_data);
2592 	INIT_LIST_HEAD(&hdev->le_accept_list);
2593 	INIT_LIST_HEAD(&hdev->le_resolv_list);
2594 	INIT_LIST_HEAD(&hdev->le_conn_params);
2595 	INIT_LIST_HEAD(&hdev->pend_le_conns);
2596 	INIT_LIST_HEAD(&hdev->pend_le_reports);
2597 	INIT_LIST_HEAD(&hdev->conn_hash.list);
2598 	INIT_LIST_HEAD(&hdev->adv_instances);
2599 	INIT_LIST_HEAD(&hdev->blocked_keys);
2600 	INIT_LIST_HEAD(&hdev->monitored_devices);
2601 
2602 	INIT_LIST_HEAD(&hdev->local_codecs);
2603 	INIT_WORK(&hdev->rx_work, hci_rx_work);
2604 	INIT_WORK(&hdev->cmd_work, hci_cmd_work);
2605 	INIT_WORK(&hdev->tx_work, hci_tx_work);
2606 	INIT_WORK(&hdev->power_on, hci_power_on);
2607 	INIT_WORK(&hdev->error_reset, hci_error_reset);
2608 
2609 	hci_cmd_sync_init(hdev);
2610 
2611 	INIT_DELAYED_WORK(&hdev->power_off, hci_power_off);
2612 
2613 	skb_queue_head_init(&hdev->rx_q);
2614 	skb_queue_head_init(&hdev->cmd_q);
2615 	skb_queue_head_init(&hdev->raw_q);
2616 
2617 	init_waitqueue_head(&hdev->req_wait_q);
2618 
2619 	INIT_DELAYED_WORK(&hdev->cmd_timer, hci_cmd_timeout);
2620 	INIT_DELAYED_WORK(&hdev->ncmd_timer, hci_ncmd_timeout);
2621 
2622 	hci_devcd_setup(hdev);
2623 
2624 	hci_init_sysfs(hdev);
2625 	discovery_init(hdev);
2626 
2627 	return hdev;
2628 }
2629 EXPORT_SYMBOL(hci_alloc_dev_priv);
2630 
2631 /* Free HCI device */
2632 void hci_free_dev(struct hci_dev *hdev)
2633 {
2634 	/* will free via device release */
2635 	put_device(&hdev->dev);
2636 }
2637 EXPORT_SYMBOL(hci_free_dev);
2638 
2639 /* Register HCI device */
2640 int hci_register_dev(struct hci_dev *hdev)
2641 {
2642 	int id, error;
2643 
2644 	if (!hdev->open || !hdev->close || !hdev->send)
2645 		return -EINVAL;
2646 
2647 	id = ida_alloc_max(&hci_index_ida, HCI_MAX_ID - 1, GFP_KERNEL);
2648 	if (id < 0)
2649 		return id;
2650 
2651 	error = dev_set_name(&hdev->dev, "hci%u", id);
2652 	if (error) {
2653 		ida_free(&hci_index_ida, id);
2654 		return error;
2655 	}
2656 
2657 	hdev->name = dev_name(&hdev->dev);
2658 	hdev->id = id;
2659 
2660 	BT_DBG("%p name %s bus %d", hdev, hdev->name, hdev->bus);
2661 
2662 	hdev->workqueue = alloc_ordered_workqueue("%s", WQ_HIGHPRI, hdev->name);
2663 	if (!hdev->workqueue) {
2664 		error = -ENOMEM;
2665 		goto err;
2666 	}
2667 
2668 	hdev->req_workqueue = alloc_ordered_workqueue("%s", WQ_HIGHPRI,
2669 						      hdev->name);
2670 	if (!hdev->req_workqueue) {
2671 		destroy_workqueue(hdev->workqueue);
2672 		error = -ENOMEM;
2673 		goto err;
2674 	}
2675 
2676 	if (!IS_ERR_OR_NULL(bt_debugfs))
2677 		hdev->debugfs = debugfs_create_dir(hdev->name, bt_debugfs);
2678 
2679 	error = device_add(&hdev->dev);
2680 	if (error < 0)
2681 		goto err_wqueue;
2682 
2683 	hci_leds_init(hdev);
2684 
2685 	hdev->rfkill = rfkill_alloc(hdev->name, &hdev->dev,
2686 				    RFKILL_TYPE_BLUETOOTH, &hci_rfkill_ops,
2687 				    hdev);
2688 	if (hdev->rfkill) {
2689 		if (rfkill_register(hdev->rfkill) < 0) {
2690 			rfkill_destroy(hdev->rfkill);
2691 			hdev->rfkill = NULL;
2692 		}
2693 	}
2694 
2695 	if (hdev->rfkill && rfkill_blocked(hdev->rfkill))
2696 		hci_dev_set_flag(hdev, HCI_RFKILLED);
2697 
2698 	hci_dev_set_flag(hdev, HCI_SETUP);
2699 	hci_dev_set_flag(hdev, HCI_AUTO_OFF);
2700 
2701 	/* Assume BR/EDR support until proven otherwise (such as
2702 	 * through reading supported features during init.
2703 	 */
2704 	hci_dev_set_flag(hdev, HCI_BREDR_ENABLED);
2705 
2706 	write_lock(&hci_dev_list_lock);
2707 	list_add(&hdev->list, &hci_dev_list);
2708 	write_unlock(&hci_dev_list_lock);
2709 
2710 	/* Devices that are marked for raw-only usage are unconfigured
2711 	 * and should not be included in normal operation.
2712 	 */
2713 	if (hci_test_quirk(hdev, HCI_QUIRK_RAW_DEVICE))
2714 		hci_dev_set_flag(hdev, HCI_UNCONFIGURED);
2715 
2716 	/* Mark Remote Wakeup connection flag as supported if driver has wakeup
2717 	 * callback.
2718 	 */
2719 	if (hdev->wakeup)
2720 		hdev->conn_flags |= HCI_CONN_FLAG_REMOTE_WAKEUP;
2721 
2722 	hci_sock_dev_event(hdev, HCI_DEV_REG);
2723 	hci_dev_hold(hdev);
2724 
2725 	error = hci_register_suspend_notifier(hdev);
2726 	if (error)
2727 		BT_WARN("register suspend notifier failed error:%d\n", error);
2728 
2729 	idr_init(&hdev->adv_monitors_idr);
2730 	msft_register(hdev);
2731 
2732 	queue_work(hdev->req_workqueue, &hdev->power_on);
2733 
2734 	return id;
2735 
2736 err_wqueue:
2737 	debugfs_remove_recursive(hdev->debugfs);
2738 	destroy_workqueue(hdev->workqueue);
2739 	destroy_workqueue(hdev->req_workqueue);
2740 err:
2741 	ida_free(&hci_index_ida, hdev->id);
2742 
2743 	return error;
2744 }
2745 EXPORT_SYMBOL(hci_register_dev);
2746 
2747 /* Unregister HCI device */
2748 void hci_unregister_dev(struct hci_dev *hdev)
2749 {
2750 	BT_DBG("%p name %s bus %d", hdev, hdev->name, hdev->bus);
2751 
2752 	mutex_lock(&hdev->unregister_lock);
2753 	hci_dev_set_flag(hdev, HCI_UNREGISTER);
2754 	mutex_unlock(&hdev->unregister_lock);
2755 
2756 	write_lock(&hci_dev_list_lock);
2757 	list_del(&hdev->list);
2758 	write_unlock(&hci_dev_list_lock);
2759 
2760 	synchronize_srcu(&hdev->srcu);
2761 	cleanup_srcu_struct(&hdev->srcu);
2762 
2763 	disable_work_sync(&hdev->rx_work);
2764 	disable_work_sync(&hdev->cmd_work);
2765 	disable_work_sync(&hdev->tx_work);
2766 	disable_work_sync(&hdev->power_on);
2767 	disable_work_sync(&hdev->error_reset);
2768 	disable_delayed_work_sync(&hdev->cmd_timer);
2769 	disable_delayed_work_sync(&hdev->ncmd_timer);
2770 	hci_devcd_shutdown(hdev);
2771 
2772 	hci_cmd_sync_clear(hdev);
2773 
2774 	hci_unregister_suspend_notifier(hdev);
2775 
2776 	hci_dev_do_close(hdev);
2777 
2778 	if (!test_bit(HCI_INIT, &hdev->flags) &&
2779 	    !hci_dev_test_flag(hdev, HCI_SETUP) &&
2780 	    !hci_dev_test_flag(hdev, HCI_CONFIG)) {
2781 		hci_dev_lock(hdev);
2782 		mgmt_index_removed(hdev);
2783 		hci_dev_unlock(hdev);
2784 	}
2785 
2786 	/* mgmt_index_removed should take care of emptying the
2787 	 * pending list */
2788 	BUG_ON(!list_empty(&hdev->mgmt_pending));
2789 
2790 	hci_sock_dev_event(hdev, HCI_DEV_UNREG);
2791 
2792 	if (hdev->rfkill) {
2793 		rfkill_unregister(hdev->rfkill);
2794 		rfkill_destroy(hdev->rfkill);
2795 	}
2796 
2797 	device_del(&hdev->dev);
2798 	/* Actual cleanup is deferred until hci_release_dev(). */
2799 	hci_dev_put(hdev);
2800 }
2801 EXPORT_SYMBOL(hci_unregister_dev);
2802 
2803 /* Release HCI device */
2804 void hci_release_dev(struct hci_dev *hdev)
2805 {
2806 	debugfs_remove_recursive(hdev->debugfs);
2807 	kfree_const(hdev->hw_info);
2808 	kfree_const(hdev->fw_info);
2809 
2810 	destroy_workqueue(hdev->workqueue);
2811 	destroy_workqueue(hdev->req_workqueue);
2812 
2813 	hci_dev_lock(hdev);
2814 	hci_bdaddr_list_clear(&hdev->reject_list);
2815 	hci_bdaddr_list_clear(&hdev->accept_list);
2816 	hci_uuids_clear(hdev);
2817 	hci_link_keys_clear(hdev);
2818 	hci_smp_ltks_clear(hdev);
2819 	hci_smp_irks_clear(hdev);
2820 	hci_remote_oob_data_clear(hdev);
2821 	hci_adv_instances_clear(hdev);
2822 	hci_adv_monitors_clear(hdev);
2823 	hci_bdaddr_list_clear(&hdev->le_accept_list);
2824 	hci_bdaddr_list_clear(&hdev->le_resolv_list);
2825 	hci_conn_params_clear_all(hdev);
2826 	hci_discovery_filter_clear(hdev);
2827 	hci_blocked_keys_clear(hdev);
2828 	hci_codec_list_clear(&hdev->local_codecs);
2829 	msft_release(hdev);
2830 	hci_dev_unlock(hdev);
2831 
2832 	ida_destroy(&hdev->unset_handle_ida);
2833 	ida_free(&hci_index_ida, hdev->id);
2834 	kfree_skb(hdev->sent_cmd);
2835 	kfree_skb(hdev->req_skb);
2836 	kfree_skb(hdev->recv_event);
2837 	kfree(hdev);
2838 }
2839 EXPORT_SYMBOL(hci_release_dev);
2840 
2841 int hci_register_suspend_notifier(struct hci_dev *hdev)
2842 {
2843 	int ret = 0;
2844 
2845 	if (!hdev->suspend_notifier.notifier_call &&
2846 	    !hci_test_quirk(hdev, HCI_QUIRK_NO_SUSPEND_NOTIFIER)) {
2847 		hdev->suspend_notifier.notifier_call = hci_suspend_notifier;
2848 		ret = register_pm_notifier(&hdev->suspend_notifier);
2849 	}
2850 
2851 	return ret;
2852 }
2853 
2854 int hci_unregister_suspend_notifier(struct hci_dev *hdev)
2855 {
2856 	int ret = 0;
2857 
2858 	if (hdev->suspend_notifier.notifier_call) {
2859 		ret = unregister_pm_notifier(&hdev->suspend_notifier);
2860 		if (!ret)
2861 			hdev->suspend_notifier.notifier_call = NULL;
2862 	}
2863 
2864 	return ret;
2865 }
2866 
2867 /* Cancel ongoing command synchronously:
2868  *
2869  * - Cancel command timer
2870  * - Reset command counter
2871  * - Cancel command request
2872  */
2873 static void hci_cancel_cmd_sync(struct hci_dev *hdev, int err)
2874 {
2875 	bt_dev_dbg(hdev, "err 0x%2.2x", err);
2876 
2877 	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
2878 		disable_delayed_work_sync(&hdev->cmd_timer);
2879 		disable_delayed_work_sync(&hdev->ncmd_timer);
2880 	} else  {
2881 		cancel_delayed_work_sync(&hdev->cmd_timer);
2882 		cancel_delayed_work_sync(&hdev->ncmd_timer);
2883 	}
2884 
2885 	atomic_set(&hdev->cmd_cnt, 1);
2886 
2887 	hci_cmd_sync_cancel_sync(hdev, err);
2888 }
2889 
2890 /* Suspend HCI device */
2891 int hci_suspend_dev(struct hci_dev *hdev)
2892 {
2893 	int ret;
2894 
2895 	bt_dev_dbg(hdev, "");
2896 
2897 	/* Suspend should only act on when powered. */
2898 	if (!hdev_is_powered(hdev) ||
2899 	    hci_dev_test_flag(hdev, HCI_UNREGISTER))
2900 		return 0;
2901 
2902 	/* If powering down don't attempt to suspend */
2903 	if (mgmt_powering_down(hdev))
2904 		return 0;
2905 
2906 	/* Cancel potentially blocking sync operation before suspend */
2907 	hci_cancel_cmd_sync(hdev, EHOSTDOWN);
2908 
2909 	hci_req_sync_lock(hdev);
2910 	ret = hci_suspend_sync(hdev);
2911 	hci_req_sync_unlock(hdev);
2912 
2913 	hci_clear_wake_reason(hdev);
2914 	mgmt_suspending(hdev, hdev->suspend_state);
2915 
2916 	hci_sock_dev_event(hdev, HCI_DEV_SUSPEND);
2917 	return ret;
2918 }
2919 EXPORT_SYMBOL(hci_suspend_dev);
2920 
2921 /* Resume HCI device */
2922 int hci_resume_dev(struct hci_dev *hdev)
2923 {
2924 	int ret;
2925 
2926 	bt_dev_dbg(hdev, "");
2927 
2928 	/* Resume should only act on when powered. */
2929 	if (!hdev_is_powered(hdev) ||
2930 	    hci_dev_test_flag(hdev, HCI_UNREGISTER))
2931 		return 0;
2932 
2933 	/* If powering down don't attempt to resume */
2934 	if (mgmt_powering_down(hdev))
2935 		return 0;
2936 
2937 	hci_req_sync_lock(hdev);
2938 	ret = hci_resume_sync(hdev);
2939 	hci_req_sync_unlock(hdev);
2940 
2941 	mgmt_resuming(hdev, hdev->wake_reason, &hdev->wake_addr,
2942 		      hdev->wake_addr_type);
2943 
2944 	hci_sock_dev_event(hdev, HCI_DEV_RESUME);
2945 	return ret;
2946 }
2947 EXPORT_SYMBOL(hci_resume_dev);
2948 
2949 /* Reset HCI device */
2950 int __hci_reset_dev(struct hci_dev *hdev, u8 hw_err_code)
2951 {
2952 	const u8 hw_err[] = { HCI_EV_HARDWARE_ERROR, 0x01, hw_err_code };
2953 	struct sk_buff *skb;
2954 
2955 	skb = bt_skb_alloc(3, GFP_ATOMIC);
2956 	if (!skb)
2957 		return -ENOMEM;
2958 
2959 	hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
2960 	skb_put_data(skb, hw_err, 3);
2961 
2962 	bt_dev_err(hdev, "Injecting HCI hardware error event");
2963 
2964 	/* Send Hardware Error to upper stack */
2965 	return hci_recv_frame(hdev, skb);
2966 }
2967 EXPORT_SYMBOL(__hci_reset_dev);
2968 
2969 static u8 hci_dev_classify_pkt_type(struct hci_dev *hdev, struct sk_buff *skb)
2970 {
2971 	if (hdev->classify_pkt_type)
2972 		return hdev->classify_pkt_type(hdev, skb);
2973 
2974 	return hci_skb_pkt_type(skb);
2975 }
2976 
2977 /* Receive frame from HCI drivers */
2978 int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb)
2979 {
2980 	u8 dev_pkt_type;
2981 
2982 	/* Pairs with synchronize_rcu() in hci_dev_close_sync(), so rx_work is
2983 	 * not queued once the workqueue is being drained.
2984 	 */
2985 	rcu_read_lock();
2986 
2987 	if (!hdev || (!test_bit(HCI_UP, &hdev->flags)
2988 		      && !test_bit(HCI_INIT, &hdev->flags))) {
2989 		rcu_read_unlock();
2990 		kfree_skb(skb);
2991 		return -ENXIO;
2992 	}
2993 
2994 	/* Check if the driver agree with packet type classification */
2995 	dev_pkt_type = hci_dev_classify_pkt_type(hdev, skb);
2996 	if (hci_skb_pkt_type(skb) != dev_pkt_type) {
2997 		hci_skb_pkt_type(skb) = dev_pkt_type;
2998 	}
2999 
3000 	switch (hci_skb_pkt_type(skb)) {
3001 	case HCI_EVENT_PKT:
3002 		break;
3003 	case HCI_ACLDATA_PKT:
3004 		/* Detect if ISO packet has been sent as ACL */
3005 		if (hci_conn_num(hdev, CIS_LINK) ||
3006 		    hci_conn_num(hdev, BIS_LINK) ||
3007 			hci_conn_num(hdev, PA_LINK)) {
3008 			__u8 type;
3009 
3010 			type = hci_conn_lookup_type(hdev, hci_acl_handle(skb));
3011 			if (type == CIS_LINK || type == BIS_LINK ||
3012 			    type == PA_LINK)
3013 				hci_skb_pkt_type(skb) = HCI_ISODATA_PKT;
3014 		}
3015 		break;
3016 	case HCI_SCODATA_PKT:
3017 		break;
3018 	case HCI_ISODATA_PKT:
3019 		break;
3020 	case HCI_VENDOR_PKT:
3021 		break;
3022 	case HCI_DRV_PKT:
3023 		break;
3024 	default:
3025 		rcu_read_unlock();
3026 		kfree_skb(skb);
3027 		return -EINVAL;
3028 	}
3029 
3030 	/* Incoming skb */
3031 	bt_cb(skb)->incoming = 1;
3032 
3033 	/* Time stamp */
3034 	__net_timestamp(skb);
3035 
3036 	skb_queue_tail(&hdev->rx_q, skb);
3037 	queue_work(hdev->workqueue, &hdev->rx_work);
3038 
3039 	rcu_read_unlock();
3040 
3041 	return 0;
3042 }
3043 EXPORT_SYMBOL(hci_recv_frame);
3044 
3045 /* Receive diagnostic message from HCI drivers */
3046 int hci_recv_diag(struct hci_dev *hdev, struct sk_buff *skb)
3047 {
3048 	/* Mark as diagnostic packet */
3049 	hci_skb_pkt_type(skb) = HCI_DIAG_PKT;
3050 
3051 	/* Time stamp */
3052 	__net_timestamp(skb);
3053 
3054 	skb_queue_tail(&hdev->rx_q, skb);
3055 	queue_work(hdev->workqueue, &hdev->rx_work);
3056 
3057 	return 0;
3058 }
3059 EXPORT_SYMBOL(hci_recv_diag);
3060 
3061 void hci_set_hw_info(struct hci_dev *hdev, const char *fmt, ...)
3062 {
3063 	va_list vargs;
3064 
3065 	va_start(vargs, fmt);
3066 	kfree_const(hdev->hw_info);
3067 	hdev->hw_info = kvasprintf_const(GFP_KERNEL, fmt, vargs);
3068 	va_end(vargs);
3069 }
3070 EXPORT_SYMBOL(hci_set_hw_info);
3071 
3072 void hci_set_fw_info(struct hci_dev *hdev, const char *fmt, ...)
3073 {
3074 	va_list vargs;
3075 
3076 	va_start(vargs, fmt);
3077 	kfree_const(hdev->fw_info);
3078 	hdev->fw_info = kvasprintf_const(GFP_KERNEL, fmt, vargs);
3079 	va_end(vargs);
3080 }
3081 EXPORT_SYMBOL(hci_set_fw_info);
3082 
3083 /* ---- Interface to upper protocols ---- */
3084 
3085 int hci_register_cb(struct hci_cb *cb)
3086 {
3087 	BT_DBG("%p name %s", cb, cb->name);
3088 
3089 	mutex_lock(&hci_cb_list_lock);
3090 	list_add_tail(&cb->list, &hci_cb_list);
3091 	mutex_unlock(&hci_cb_list_lock);
3092 
3093 	return 0;
3094 }
3095 EXPORT_SYMBOL(hci_register_cb);
3096 
3097 int hci_unregister_cb(struct hci_cb *cb)
3098 {
3099 	BT_DBG("%p name %s", cb, cb->name);
3100 
3101 	mutex_lock(&hci_cb_list_lock);
3102 	list_del(&cb->list);
3103 	mutex_unlock(&hci_cb_list_lock);
3104 
3105 	return 0;
3106 }
3107 EXPORT_SYMBOL(hci_unregister_cb);
3108 
3109 static int hci_send_frame(struct hci_dev *hdev, struct sk_buff *skb)
3110 {
3111 	int err;
3112 
3113 	BT_DBG("%s type %d len %d", hdev->name, hci_skb_pkt_type(skb),
3114 	       skb->len);
3115 
3116 	/* Time stamp */
3117 	__net_timestamp(skb);
3118 
3119 	/* Send copy to monitor */
3120 	hci_send_to_monitor(hdev, skb);
3121 
3122 	if (atomic_read(&hdev->promisc)) {
3123 		/* Send copy to the sockets */
3124 		hci_send_to_sock(hdev, skb);
3125 	}
3126 
3127 	/* Get rid of skb owner, prior to sending to the driver. */
3128 	skb_orphan(skb);
3129 
3130 	if (!test_bit(HCI_RUNNING, &hdev->flags)) {
3131 		kfree_skb(skb);
3132 		return -EINVAL;
3133 	}
3134 
3135 	if (hci_skb_pkt_type(skb) == HCI_DRV_PKT) {
3136 		/* Intercept HCI Drv packet here and don't go with hdev->send
3137 		 * callback.
3138 		 */
3139 		err = hci_drv_process_cmd(hdev, skb);
3140 		kfree_skb(skb);
3141 		return err;
3142 	}
3143 
3144 	err = hdev->send(hdev, skb);
3145 	if (err < 0) {
3146 		bt_dev_err(hdev, "sending frame failed (%d)", err);
3147 		kfree_skb(skb);
3148 		return err;
3149 	}
3150 
3151 	return 0;
3152 }
3153 
3154 static int hci_send_conn_frame(struct hci_dev *hdev, struct hci_conn *conn,
3155 			       struct sk_buff *skb)
3156 {
3157 	hci_conn_tx_queue(conn, skb);
3158 	return hci_send_frame(hdev, skb);
3159 }
3160 
3161 /**
3162  * hci_send_vendor_frame - Send an HCI_VENDOR_PKT frame to the HCI driver
3163  * @hdev: The HCI device
3164  * @iter: iov_iter carrying the frame
3165  *
3166  * Return: 0 on success, or a negative errno on failure.
3167  */
3168 int hci_send_vendor_frame(struct hci_dev *hdev, struct iov_iter *iter)
3169 {
3170 	struct sk_buff *skb;
3171 	unsigned int len;
3172 
3173 	if (WARN_ON(!iov_iter_is_kvec(iter)))
3174 		return -EINVAL;
3175 
3176 	/* Vendor frames are opaque, the caller guarantees the size. */
3177 	len = (unsigned int)iov_iter_count(iter);
3178 	if (!len)
3179 		return -EINVAL;
3180 
3181 	skb = bt_skb_alloc(len, GFP_KERNEL);
3182 	if (!skb)
3183 		return -ENOMEM;
3184 
3185 	if (!copy_from_iter_full(skb_put(skb, len), len, iter)) {
3186 		kfree_skb(skb);
3187 		return -EFAULT;
3188 	}
3189 
3190 	hci_skb_pkt_type(skb) = HCI_VENDOR_PKT;
3191 
3192 	return hci_send_frame(hdev, skb);
3193 }
3194 EXPORT_SYMBOL(hci_send_vendor_frame);
3195 
3196 /* Send HCI command */
3197 int hci_send_cmd(struct hci_dev *hdev, __u16 opcode, __u32 plen,
3198 		 const void *param)
3199 {
3200 	struct sk_buff *skb;
3201 
3202 	BT_DBG("%s opcode 0x%4.4x plen %d", hdev->name, opcode, plen);
3203 
3204 	skb = hci_cmd_sync_alloc(hdev, opcode, plen, param, NULL);
3205 	if (!skb) {
3206 		bt_dev_err(hdev, "no memory for command");
3207 		return -ENOMEM;
3208 	}
3209 
3210 	/* Stand-alone HCI commands must be flagged as
3211 	 * single-command requests.
3212 	 */
3213 	bt_cb(skb)->hci.req_flags |= HCI_REQ_START;
3214 
3215 	skb_queue_tail(&hdev->cmd_q, skb);
3216 	queue_work(hdev->workqueue, &hdev->cmd_work);
3217 
3218 	return 0;
3219 }
3220 
3221 int __hci_cmd_send(struct hci_dev *hdev, u16 opcode, u32 plen,
3222 		   const void *param)
3223 {
3224 	struct sk_buff *skb;
3225 
3226 	if (hci_opcode_ogf(opcode) != 0x3f) {
3227 		/* A controller receiving a command shall respond with either
3228 		 * a Command Status Event or a Command Complete Event.
3229 		 * Therefore, all standard HCI commands must be sent via the
3230 		 * standard API, using hci_send_cmd or hci_cmd_sync helpers.
3231 		 * Some vendors do not comply with this rule for vendor-specific
3232 		 * commands and do not return any event. We want to support
3233 		 * unresponded commands for such cases only.
3234 		 */
3235 		bt_dev_err(hdev, "unresponded command not supported");
3236 		return -EINVAL;
3237 	}
3238 
3239 	skb = hci_cmd_sync_alloc(hdev, opcode, plen, param, NULL);
3240 	if (!skb) {
3241 		bt_dev_err(hdev, "no memory for command (opcode 0x%4.4x)",
3242 			   opcode);
3243 		return -ENOMEM;
3244 	}
3245 
3246 	hci_send_frame(hdev, skb);
3247 
3248 	return 0;
3249 }
3250 EXPORT_SYMBOL(__hci_cmd_send);
3251 
3252 /* Get data from the previously sent command */
3253 static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode,
3254 			  size_t *len)
3255 {
3256 	struct hci_command_hdr *hdr;
3257 
3258 	if (!skb || skb->len < HCI_COMMAND_HDR_SIZE)
3259 		return NULL;
3260 
3261 	hdr = (void *)skb->data;
3262 
3263 	if (hdr->opcode != cpu_to_le16(opcode))
3264 		return NULL;
3265 
3266 	if (len)
3267 		*len = skb->len - HCI_COMMAND_HDR_SIZE;
3268 
3269 	return skb->data + HCI_COMMAND_HDR_SIZE;
3270 }
3271 
3272 /* Get data from the previously sent command */
3273 void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode, size_t *len)
3274 {
3275 	void *data;
3276 
3277 	/* Check if opcode matches last sent command */
3278 	data = hci_cmd_data(hdev->sent_cmd, opcode, len);
3279 	if (!data)
3280 		/* Check if opcode matches last request */
3281 		data = hci_cmd_data(hdev->req_skb, opcode, len);
3282 
3283 	return data;
3284 }
3285 
3286 /* Get data from the previously sent command */
3287 void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode)
3288 {
3289 	return hci_sent_cmd_data_len(hdev, opcode, NULL);
3290 }
3291 
3292 /* Get data from last received event */
3293 void *hci_recv_event_data(struct hci_dev *hdev, __u8 event)
3294 {
3295 	struct hci_event_hdr *hdr;
3296 	int offset;
3297 
3298 	if (!hdev->recv_event)
3299 		return NULL;
3300 
3301 	hdr = (void *)hdev->recv_event->data;
3302 	offset = sizeof(*hdr);
3303 
3304 	if (hdr->evt != event) {
3305 		/* In case of LE metaevent check the subevent match */
3306 		if (hdr->evt == HCI_EV_LE_META) {
3307 			struct hci_ev_le_meta *ev;
3308 
3309 			ev = (void *)hdev->recv_event->data + offset;
3310 			offset += sizeof(*ev);
3311 			if (ev->subevent == event)
3312 				goto found;
3313 		}
3314 		return NULL;
3315 	}
3316 
3317 found:
3318 	bt_dev_dbg(hdev, "event 0x%2.2x", event);
3319 
3320 	return hdev->recv_event->data + offset;
3321 }
3322 
3323 /* Send ACL data */
3324 static void hci_add_acl_hdr(struct sk_buff *skb, __u16 handle, __u16 flags)
3325 {
3326 	struct hci_acl_hdr *hdr;
3327 	int len = skb->len;
3328 
3329 	skb_push(skb, HCI_ACL_HDR_SIZE);
3330 	skb_reset_transport_header(skb);
3331 	hdr = (struct hci_acl_hdr *)skb_transport_header(skb);
3332 	hdr->handle = cpu_to_le16(hci_handle_pack(handle, flags));
3333 	hdr->dlen   = cpu_to_le16(len);
3334 }
3335 
3336 static void hci_queue_acl(struct hci_chan *chan, struct sk_buff_head *queue,
3337 			  struct sk_buff *skb, __u16 flags)
3338 {
3339 	struct hci_conn *conn = chan->conn;
3340 	struct hci_dev *hdev = conn->hdev;
3341 	struct sk_buff *list;
3342 
3343 	skb->len = skb_headlen(skb);
3344 	skb->data_len = 0;
3345 
3346 	hci_skb_pkt_type(skb) = HCI_ACLDATA_PKT;
3347 
3348 	hci_add_acl_hdr(skb, conn->handle, flags);
3349 
3350 	list = skb_shinfo(skb)->frag_list;
3351 	if (!list) {
3352 		/* Non fragmented */
3353 		BT_DBG("%s nonfrag skb %p len %d", hdev->name, skb, skb->len);
3354 
3355 		skb_queue_tail(queue, skb);
3356 	} else {
3357 		/* Fragmented */
3358 		BT_DBG("%s frag %p len %d", hdev->name, skb, skb->len);
3359 
3360 		skb_shinfo(skb)->frag_list = NULL;
3361 
3362 		/* Queue all fragments atomically. We need to use spin_lock_bh
3363 		 * here because of 6LoWPAN links, as there this function is
3364 		 * called from softirq and using normal spin lock could cause
3365 		 * deadlocks.
3366 		 */
3367 		spin_lock_bh(&queue->lock);
3368 
3369 		__skb_queue_tail(queue, skb);
3370 
3371 		flags &= ~ACL_START;
3372 		flags |= ACL_CONT;
3373 		do {
3374 			skb = list; list = list->next;
3375 
3376 			hci_skb_pkt_type(skb) = HCI_ACLDATA_PKT;
3377 			hci_add_acl_hdr(skb, conn->handle, flags);
3378 
3379 			BT_DBG("%s frag %p len %d", hdev->name, skb, skb->len);
3380 
3381 			__skb_queue_tail(queue, skb);
3382 		} while (list);
3383 
3384 		spin_unlock_bh(&queue->lock);
3385 	}
3386 
3387 	bt_dev_dbg(hdev, "chan %p queued %d", chan, skb_queue_len(queue));
3388 }
3389 
3390 /* Queue hdev->tx_work, unless hdev->workqueue is being drained by
3391  * hci_dev_close_sync(), which would otherwise WARN and drop the work.
3392  */
3393 static void hci_sched_tx(struct hci_dev *hdev)
3394 {
3395 	rcu_read_lock();
3396 	if (!hci_dev_test_flag(hdev, HCI_CMD_DRAIN_WORKQUEUE))
3397 		queue_work(hdev->workqueue, &hdev->tx_work);
3398 	rcu_read_unlock();
3399 }
3400 
3401 void hci_send_acl(struct hci_chan *chan, struct sk_buff *skb, __u16 flags)
3402 {
3403 	struct hci_dev *hdev = chan->conn->hdev;
3404 
3405 	BT_DBG("%s chan %p flags 0x%4.4x", hdev->name, chan, flags);
3406 
3407 	hci_queue_acl(chan, &chan->data_q, skb, flags);
3408 
3409 	hci_sched_tx(hdev);
3410 }
3411 
3412 /* Send SCO data */
3413 void hci_send_sco(struct hci_conn *conn, struct sk_buff *skb)
3414 {
3415 	struct hci_dev *hdev = conn->hdev;
3416 	struct hci_sco_hdr hdr;
3417 
3418 	BT_DBG("%s len %d", hdev->name, skb->len);
3419 
3420 	hdr.handle = cpu_to_le16(conn->handle);
3421 	hdr.dlen   = skb->len;
3422 
3423 	skb_push(skb, HCI_SCO_HDR_SIZE);
3424 	skb_reset_transport_header(skb);
3425 	memcpy(skb_transport_header(skb), &hdr, HCI_SCO_HDR_SIZE);
3426 
3427 	hci_skb_pkt_type(skb) = HCI_SCODATA_PKT;
3428 
3429 	skb_queue_tail(&conn->data_q, skb);
3430 
3431 	bt_dev_dbg(hdev, "hcon %p queued %d", conn,
3432 		   skb_queue_len(&conn->data_q));
3433 
3434 	hci_sched_tx(hdev);
3435 }
3436 
3437 /* Send ISO data */
3438 static void hci_add_iso_hdr(struct sk_buff *skb, __u16 handle, __u8 flags)
3439 {
3440 	struct hci_iso_hdr *hdr;
3441 	int len = skb->len;
3442 
3443 	skb_push(skb, HCI_ISO_HDR_SIZE);
3444 	skb_reset_transport_header(skb);
3445 	hdr = (struct hci_iso_hdr *)skb_transport_header(skb);
3446 	hdr->handle = cpu_to_le16(hci_handle_pack(handle, flags));
3447 	hdr->dlen   = cpu_to_le16(len);
3448 }
3449 
3450 static void hci_queue_iso(struct hci_conn *conn, struct sk_buff_head *queue,
3451 			  struct sk_buff *skb)
3452 {
3453 	struct hci_dev *hdev = conn->hdev;
3454 	struct sk_buff *list;
3455 	__u16 flags;
3456 
3457 	skb->len = skb_headlen(skb);
3458 	skb->data_len = 0;
3459 
3460 	hci_skb_pkt_type(skb) = HCI_ISODATA_PKT;
3461 
3462 	list = skb_shinfo(skb)->frag_list;
3463 
3464 	flags = hci_iso_flags_pack(list ? ISO_START : ISO_SINGLE, 0x00);
3465 	hci_add_iso_hdr(skb, conn->handle, flags);
3466 
3467 	if (!list) {
3468 		/* Non fragmented */
3469 		BT_DBG("%s nonfrag skb %p len %d", hdev->name, skb, skb->len);
3470 
3471 		skb_queue_tail(queue, skb);
3472 	} else {
3473 		/* Fragmented */
3474 		BT_DBG("%s frag %p len %d", hdev->name, skb, skb->len);
3475 
3476 		skb_shinfo(skb)->frag_list = NULL;
3477 
3478 		spin_lock_bh(&queue->lock);
3479 
3480 		__skb_queue_tail(queue, skb);
3481 
3482 		do {
3483 			skb = list; list = list->next;
3484 
3485 			hci_skb_pkt_type(skb) = HCI_ISODATA_PKT;
3486 			flags = hci_iso_flags_pack(list ? ISO_CONT : ISO_END,
3487 						   0x00);
3488 			hci_add_iso_hdr(skb, conn->handle, flags);
3489 
3490 			BT_DBG("%s frag %p len %d", hdev->name, skb, skb->len);
3491 
3492 			__skb_queue_tail(queue, skb);
3493 		} while (list);
3494 
3495 		spin_unlock_bh(&queue->lock);
3496 	}
3497 
3498 	bt_dev_dbg(hdev, "hcon %p queued %d", conn, skb_queue_len(queue));
3499 }
3500 
3501 void hci_send_iso(struct hci_conn *conn, struct sk_buff *skb)
3502 {
3503 	struct hci_dev *hdev = conn->hdev;
3504 
3505 	BT_DBG("%s len %d", hdev->name, skb->len);
3506 
3507 	hci_queue_iso(conn, &conn->data_q, skb);
3508 
3509 	hci_sched_tx(hdev);
3510 }
3511 
3512 /* ---- HCI TX task (outgoing data) ---- */
3513 
3514 /* HCI Connection scheduler */
3515 static inline void hci_quote_sent(struct hci_conn *conn, int num, int *quote)
3516 {
3517 	struct hci_dev *hdev;
3518 	int cnt, q;
3519 
3520 	if (!conn) {
3521 		*quote = 0;
3522 		return;
3523 	}
3524 
3525 	hdev = conn->hdev;
3526 
3527 	switch (conn->type) {
3528 	case ACL_LINK:
3529 		cnt = hdev->acl_cnt;
3530 		break;
3531 	case SCO_LINK:
3532 	case ESCO_LINK:
3533 		cnt = hdev->sco_cnt;
3534 		break;
3535 	case LE_LINK:
3536 		cnt = hdev->le_mtu ? hdev->le_cnt : hdev->acl_cnt;
3537 		break;
3538 	case CIS_LINK:
3539 	case BIS_LINK:
3540 	case PA_LINK:
3541 		cnt = hdev->iso_cnt;
3542 		break;
3543 	default:
3544 		cnt = 0;
3545 		bt_dev_err(hdev, "unknown link type %d", conn->type);
3546 	}
3547 
3548 	q = cnt / num;
3549 	*quote = q ? q : 1;
3550 }
3551 
3552 static struct hci_conn *hci_low_sent(struct hci_dev *hdev, __u8 type,
3553 				     int *quote)
3554 {
3555 	struct hci_conn_hash *h = &hdev->conn_hash;
3556 	struct hci_conn *conn = NULL, *c;
3557 	unsigned int num = 0, min = ~0;
3558 
3559 	rcu_read_lock();
3560 
3561 	list_for_each_entry_rcu(c, &h->list, list) {
3562 		if (c->type != type ||
3563 		    skb_queue_empty(&c->data_q))
3564 			continue;
3565 
3566 		bt_dev_dbg(hdev, "hcon %p state %s queued %d", c,
3567 			   state_to_string(c->state),
3568 			   skb_queue_len(&c->data_q));
3569 
3570 		if (c->state != BT_CONNECTED && c->state != BT_CONFIG)
3571 			continue;
3572 
3573 		num++;
3574 
3575 		if (c->sent < min) {
3576 			min  = c->sent;
3577 			conn = c;
3578 		}
3579 
3580 		if (hci_conn_num(hdev, type) == num)
3581 			break;
3582 	}
3583 
3584 	rcu_read_unlock();
3585 
3586 	hci_quote_sent(conn, num, quote);
3587 
3588 	BT_DBG("conn %p quote %d", conn, *quote);
3589 	return conn;
3590 }
3591 
3592 static void hci_link_tx_to(struct hci_dev *hdev, __u8 type)
3593 {
3594 	struct hci_conn_hash *h = &hdev->conn_hash;
3595 	struct hci_conn *c;
3596 
3597 	bt_dev_err(hdev, "link tx timeout");
3598 
3599 	hci_dev_lock(hdev);
3600 
3601 	/* Kill stalled connections */
3602 	list_for_each_entry(c, &h->list, list) {
3603 		if (c->type == type && c->sent) {
3604 			bt_dev_err(hdev, "killing stalled connection %pMR",
3605 				   &c->dst);
3606 			hci_disconnect(c, HCI_ERROR_REMOTE_USER_TERM);
3607 		}
3608 	}
3609 
3610 	hci_dev_unlock(hdev);
3611 }
3612 
3613 static struct hci_chan *hci_chan_sent(struct hci_dev *hdev, __u8 type,
3614 				      int *quote)
3615 {
3616 	struct hci_conn_hash *h = &hdev->conn_hash;
3617 	struct hci_chan *chan = NULL;
3618 	unsigned int num = 0, min = ~0, cur_prio = 0;
3619 	struct hci_conn *conn;
3620 	int conn_num = 0;
3621 
3622 	BT_DBG("%s", hdev->name);
3623 
3624 	rcu_read_lock();
3625 
3626 	list_for_each_entry_rcu(conn, &h->list, list) {
3627 		struct hci_chan *tmp;
3628 
3629 		if (conn->type != type)
3630 			continue;
3631 
3632 		if (conn->state != BT_CONNECTED && conn->state != BT_CONFIG)
3633 			continue;
3634 
3635 		conn_num++;
3636 
3637 		list_for_each_entry_rcu(tmp, &conn->chan_list, list) {
3638 			struct sk_buff *skb;
3639 
3640 			if (skb_queue_empty(&tmp->data_q))
3641 				continue;
3642 
3643 			skb = skb_peek(&tmp->data_q);
3644 			if (skb->priority < cur_prio)
3645 				continue;
3646 
3647 			if (skb->priority > cur_prio) {
3648 				num = 0;
3649 				min = ~0;
3650 				cur_prio = skb->priority;
3651 			}
3652 
3653 			num++;
3654 
3655 			if (conn->sent < min) {
3656 				min  = conn->sent;
3657 				chan = tmp;
3658 			}
3659 		}
3660 
3661 		if (hci_conn_num(hdev, type) == conn_num)
3662 			break;
3663 	}
3664 
3665 	rcu_read_unlock();
3666 
3667 	if (!chan)
3668 		return NULL;
3669 
3670 	hci_quote_sent(chan->conn, num, quote);
3671 
3672 	BT_DBG("chan %p quote %d", chan, *quote);
3673 	return chan;
3674 }
3675 
3676 static void hci_prio_recalculate(struct hci_dev *hdev, __u8 type)
3677 {
3678 	struct hci_conn_hash *h = &hdev->conn_hash;
3679 	struct hci_conn *conn;
3680 	int num = 0;
3681 
3682 	BT_DBG("%s", hdev->name);
3683 
3684 	rcu_read_lock();
3685 
3686 	list_for_each_entry_rcu(conn, &h->list, list) {
3687 		struct hci_chan *chan;
3688 
3689 		if (conn->type != type)
3690 			continue;
3691 
3692 		if (conn->state != BT_CONNECTED && conn->state != BT_CONFIG)
3693 			continue;
3694 
3695 		num++;
3696 
3697 		list_for_each_entry_rcu(chan, &conn->chan_list, list) {
3698 			struct sk_buff *skb;
3699 
3700 			if (chan->sent) {
3701 				chan->sent = 0;
3702 				continue;
3703 			}
3704 
3705 			if (skb_queue_empty(&chan->data_q))
3706 				continue;
3707 
3708 			skb = skb_peek(&chan->data_q);
3709 			if (skb->priority >= HCI_PRIO_MAX - 1)
3710 				continue;
3711 
3712 			skb->priority = HCI_PRIO_MAX - 1;
3713 
3714 			BT_DBG("chan %p skb %p promoted to %d", chan, skb,
3715 			       skb->priority);
3716 		}
3717 
3718 		if (hci_conn_num(hdev, type) == num)
3719 			break;
3720 	}
3721 
3722 	rcu_read_unlock();
3723 
3724 }
3725 
3726 static void __check_timeout(struct hci_dev *hdev, unsigned int cnt, u8 type)
3727 {
3728 	unsigned long timeout;
3729 
3730 	if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
3731 		return;
3732 
3733 	switch (type) {
3734 	case ACL_LINK:
3735 		/* tx timeout must be longer than maximum link supervision
3736 		 * timeout (40.9 seconds)
3737 		 */
3738 		timeout = hdev->acl_last_tx + HCI_ACL_TX_TIMEOUT;
3739 		break;
3740 	case LE_LINK:
3741 		/* tx timeout must be longer than maximum link supervision
3742 		 * timeout (40.9 seconds)
3743 		 */
3744 		timeout = hdev->le_last_tx + HCI_ACL_TX_TIMEOUT;
3745 		break;
3746 	case CIS_LINK:
3747 	case BIS_LINK:
3748 	case PA_LINK:
3749 		/* tx timeout must be longer than the maximum transport latency
3750 		 * (8.388607 seconds)
3751 		 */
3752 		timeout = hdev->iso_last_tx + HCI_ISO_TX_TIMEOUT;
3753 		break;
3754 	default:
3755 		return;
3756 	}
3757 
3758 	if (!cnt && time_after(jiffies, timeout))
3759 		hci_link_tx_to(hdev, type);
3760 }
3761 
3762 /* Schedule SCO */
3763 static void __hci_sched_sco(struct hci_dev *hdev, __u8 type)
3764 {
3765 	struct hci_conn *conn;
3766 	struct sk_buff *skb;
3767 	int quote, *cnt;
3768 	unsigned int pkts = hdev->sco_pkts;
3769 
3770 	lockdep_assert_held(&hdev->lock);
3771 
3772 	bt_dev_dbg(hdev, "type %u", type);
3773 
3774 	if (!hci_conn_num(hdev, type) || !pkts)
3775 		return;
3776 
3777 	/* Use sco_pkts if flow control has not been enabled which will limit
3778 	 * the amount of buffer sent in a row.
3779 	 */
3780 	if (!hci_dev_test_flag(hdev, HCI_SCO_FLOWCTL))
3781 		cnt = &pkts;
3782 	else
3783 		cnt = &hdev->sco_cnt;
3784 
3785 	while (*cnt && (conn = hci_low_sent(hdev, type, &quote))) {
3786 		while (quote-- && (skb = skb_dequeue(&conn->data_q))) {
3787 			BT_DBG("skb %p len %d", skb, skb->len);
3788 			hci_send_conn_frame(hdev, conn, skb);
3789 
3790 			conn->sent++;
3791 			if (conn->sent == ~0)
3792 				conn->sent = 0;
3793 			(*cnt)--;
3794 		}
3795 	}
3796 
3797 	/* Rescheduled if all packets were sent and flow control is not enabled
3798 	 * as there could be more packets queued that could not be sent and
3799 	 * since no HCI_EV_NUM_COMP_PKTS event will be generated the reschedule
3800 	 * needs to be forced.
3801 	 */
3802 	if (!pkts && !hci_dev_test_flag(hdev, HCI_SCO_FLOWCTL))
3803 		queue_work(hdev->workqueue, &hdev->tx_work);
3804 }
3805 
3806 static void hci_sched_sco(struct hci_dev *hdev, __u8 type)
3807 {
3808 	hci_dev_lock(hdev);
3809 	__hci_sched_sco(hdev, type);
3810 	hci_dev_unlock(hdev);
3811 }
3812 
3813 static void hci_sched_acl_pkt(struct hci_dev *hdev)
3814 {
3815 	unsigned int cnt = hdev->acl_cnt;
3816 	struct hci_chan *chan;
3817 	struct sk_buff *skb;
3818 	int quote;
3819 
3820 	__check_timeout(hdev, cnt, ACL_LINK);
3821 
3822 	hci_dev_lock(hdev);
3823 
3824 	while (hdev->acl_cnt &&
3825 	       (chan = hci_chan_sent(hdev, ACL_LINK, &quote))) {
3826 		u32 priority = (skb_peek(&chan->data_q))->priority;
3827 		while (quote-- && (skb = skb_peek(&chan->data_q))) {
3828 			BT_DBG("chan %p skb %p len %d priority %u", chan, skb,
3829 			       skb->len, skb->priority);
3830 
3831 			/* Stop if priority has changed */
3832 			if (skb->priority < priority)
3833 				break;
3834 
3835 			skb = skb_dequeue(&chan->data_q);
3836 
3837 			hci_conn_enter_active_mode(chan->conn,
3838 						   bt_cb(skb)->force_active);
3839 
3840 			hci_send_conn_frame(hdev, chan->conn, skb);
3841 			hdev->acl_last_tx = jiffies;
3842 
3843 			hdev->acl_cnt--;
3844 			chan->sent++;
3845 			chan->conn->sent++;
3846 
3847 			/* Send pending SCO packets right away */
3848 			__hci_sched_sco(hdev, SCO_LINK);
3849 			__hci_sched_sco(hdev, ESCO_LINK);
3850 		}
3851 	}
3852 
3853 	if (cnt != hdev->acl_cnt)
3854 		hci_prio_recalculate(hdev, ACL_LINK);
3855 
3856 	hci_dev_unlock(hdev);
3857 }
3858 
3859 static void hci_sched_acl(struct hci_dev *hdev)
3860 {
3861 	BT_DBG("%s", hdev->name);
3862 
3863 	/* No ACL link over BR/EDR controller */
3864 	if (!hci_conn_num(hdev, ACL_LINK))
3865 		return;
3866 
3867 	hci_sched_acl_pkt(hdev);
3868 }
3869 
3870 static void hci_sched_le(struct hci_dev *hdev)
3871 {
3872 	struct hci_chan *chan;
3873 	struct sk_buff *skb;
3874 	int quote, *cnt, tmp;
3875 
3876 	BT_DBG("%s", hdev->name);
3877 
3878 	if (!hci_conn_num(hdev, LE_LINK))
3879 		return;
3880 
3881 	cnt = hdev->le_pkts ? &hdev->le_cnt : &hdev->acl_cnt;
3882 
3883 	__check_timeout(hdev, *cnt, LE_LINK);
3884 
3885 	hci_dev_lock(hdev);
3886 
3887 	tmp = *cnt;
3888 	while (*cnt && (chan = hci_chan_sent(hdev, LE_LINK, &quote))) {
3889 		u32 priority = (skb_peek(&chan->data_q))->priority;
3890 		while (quote-- && (skb = skb_peek(&chan->data_q))) {
3891 			BT_DBG("chan %p skb %p len %d priority %u", chan, skb,
3892 			       skb->len, skb->priority);
3893 
3894 			/* Stop if priority has changed */
3895 			if (skb->priority < priority)
3896 				break;
3897 
3898 			skb = skb_dequeue(&chan->data_q);
3899 
3900 			hci_send_conn_frame(hdev, chan->conn, skb);
3901 			hdev->le_last_tx = jiffies;
3902 
3903 			(*cnt)--;
3904 			chan->sent++;
3905 			chan->conn->sent++;
3906 
3907 			/* Send pending SCO packets right away */
3908 			__hci_sched_sco(hdev, SCO_LINK);
3909 			__hci_sched_sco(hdev, ESCO_LINK);
3910 		}
3911 	}
3912 
3913 	if (*cnt != tmp)
3914 		hci_prio_recalculate(hdev, LE_LINK);
3915 
3916 	hci_dev_unlock(hdev);
3917 }
3918 
3919 /* Schedule iso */
3920 static void hci_sched_iso(struct hci_dev *hdev, __u8 type)
3921 {
3922 	struct hci_conn *conn;
3923 	struct sk_buff *skb;
3924 	int quote, *cnt;
3925 
3926 	BT_DBG("%s", hdev->name);
3927 
3928 	if (!hci_conn_num(hdev, type))
3929 		return;
3930 
3931 	cnt = &hdev->iso_cnt;
3932 
3933 	__check_timeout(hdev, *cnt, type);
3934 
3935 	hci_dev_lock(hdev);
3936 
3937 	while (*cnt && (conn = hci_low_sent(hdev, type, &quote))) {
3938 		while (quote-- && (skb = skb_dequeue(&conn->data_q))) {
3939 			BT_DBG("skb %p len %d", skb, skb->len);
3940 
3941 			hci_send_conn_frame(hdev, conn, skb);
3942 			hdev->iso_last_tx = jiffies;
3943 
3944 			conn->sent++;
3945 			if (conn->sent == ~0)
3946 				conn->sent = 0;
3947 			(*cnt)--;
3948 		}
3949 	}
3950 
3951 	hci_dev_unlock(hdev);
3952 }
3953 
3954 static void hci_tx_work(struct work_struct *work)
3955 {
3956 	struct hci_dev *hdev = container_of(work, struct hci_dev, tx_work);
3957 	struct sk_buff *skb;
3958 
3959 	BT_DBG("%s acl %d sco %d le %d iso %d", hdev->name, hdev->acl_cnt,
3960 	       hdev->sco_cnt, hdev->le_cnt, hdev->iso_cnt);
3961 
3962 	if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) {
3963 		/* Schedule queues and send stuff to HCI driver */
3964 		hci_sched_sco(hdev, SCO_LINK);
3965 		hci_sched_sco(hdev, ESCO_LINK);
3966 		hci_sched_iso(hdev, CIS_LINK);
3967 		hci_sched_iso(hdev, BIS_LINK);
3968 		hci_sched_iso(hdev, PA_LINK);
3969 		hci_sched_acl(hdev);
3970 		hci_sched_le(hdev);
3971 	}
3972 
3973 	/* Send next queued raw (unknown type) packet */
3974 	while ((skb = skb_dequeue(&hdev->raw_q)))
3975 		hci_send_frame(hdev, skb);
3976 }
3977 
3978 /* ----- HCI RX task (incoming data processing) ----- */
3979 
3980 /* ACL data packet */
3981 static void hci_acldata_packet(struct hci_dev *hdev, struct sk_buff *skb)
3982 {
3983 	struct hci_acl_hdr *hdr;
3984 	__u16 handle, flags;
3985 	int err;
3986 
3987 	hdr = skb_pull_data(skb, sizeof(*hdr));
3988 	if (!hdr) {
3989 		bt_dev_err(hdev, "ACL packet too small");
3990 		kfree_skb(skb);
3991 		return;
3992 	}
3993 
3994 	handle = __le16_to_cpu(hdr->handle);
3995 	flags  = hci_flags(handle);
3996 	handle = hci_handle(handle);
3997 
3998 	bt_dev_dbg(hdev, "len %d handle 0x%4.4x flags 0x%4.4x", skb->len,
3999 		   handle, flags);
4000 
4001 	hdev->stat.acl_rx++;
4002 
4003 	err = l2cap_recv_acldata(hdev, handle, skb, flags);
4004 	if (err == -ENOENT)
4005 		bt_dev_err(hdev, "ACL packet for unknown connection handle %d",
4006 			   handle);
4007 	else if (err)
4008 		bt_dev_dbg(hdev, "ACL packet recv for handle %d failed: %d",
4009 			   handle, err);
4010 }
4011 
4012 /* SCO data packet */
4013 static void hci_scodata_packet(struct hci_dev *hdev, struct sk_buff *skb)
4014 {
4015 	struct hci_sco_hdr *hdr;
4016 	__u16 handle, flags;
4017 	int err;
4018 
4019 	hdr = skb_pull_data(skb, sizeof(*hdr));
4020 	if (!hdr) {
4021 		bt_dev_err(hdev, "SCO packet too small");
4022 		kfree_skb(skb);
4023 		return;
4024 	}
4025 
4026 	handle = __le16_to_cpu(hdr->handle);
4027 	flags  = hci_flags(handle);
4028 	handle = hci_handle(handle);
4029 
4030 	bt_dev_dbg(hdev, "len %d handle 0x%4.4x flags 0x%4.4x", skb->len,
4031 		   handle, flags);
4032 
4033 	hdev->stat.sco_rx++;
4034 
4035 	hci_skb_pkt_status(skb) = flags & 0x03;
4036 
4037 	err = sco_recv_scodata(hdev, handle, skb);
4038 	if (err == -ENOENT)
4039 		bt_dev_err_ratelimited(hdev, "SCO packet for unknown connection handle %d",
4040 				       handle);
4041 	else if (err)
4042 		bt_dev_dbg(hdev, "SCO packet recv for handle %d failed: %d",
4043 			   handle, err);
4044 }
4045 
4046 static void hci_isodata_packet(struct hci_dev *hdev, struct sk_buff *skb)
4047 {
4048 	struct hci_iso_hdr *hdr;
4049 	__u16 handle, flags;
4050 	int err;
4051 
4052 	hdr = skb_pull_data(skb, sizeof(*hdr));
4053 	if (!hdr) {
4054 		bt_dev_err(hdev, "ISO packet too small");
4055 		kfree_skb(skb);
4056 		return;
4057 	}
4058 
4059 	handle = __le16_to_cpu(hdr->handle);
4060 	flags  = hci_flags(handle);
4061 	handle = hci_handle(handle);
4062 
4063 	bt_dev_dbg(hdev, "len %d handle 0x%4.4x flags 0x%4.4x", skb->len,
4064 		   handle, flags);
4065 
4066 	err = iso_recv(hdev, handle, skb, flags);
4067 	if (err == -ENOENT)
4068 		bt_dev_err_ratelimited(hdev, "ISO packet for unknown connection handle %d",
4069 				       handle);
4070 	else if (err)
4071 		bt_dev_dbg(hdev, "ISO packet recv for handle %d failed: %d",
4072 			   handle, err);
4073 }
4074 
4075 static bool hci_req_is_complete(struct hci_dev *hdev)
4076 {
4077 	struct sk_buff *skb;
4078 
4079 	skb = skb_peek(&hdev->cmd_q);
4080 	if (!skb)
4081 		return true;
4082 
4083 	return (bt_cb(skb)->hci.req_flags & HCI_REQ_START);
4084 }
4085 
4086 static void hci_resend_last(struct hci_dev *hdev)
4087 {
4088 	struct hci_command_hdr *sent;
4089 	struct sk_buff *skb;
4090 	u16 opcode;
4091 
4092 	if (!hdev->sent_cmd)
4093 		return;
4094 
4095 	sent = (void *) hdev->sent_cmd->data;
4096 	opcode = __le16_to_cpu(sent->opcode);
4097 	if (opcode == HCI_OP_RESET)
4098 		return;
4099 
4100 	skb = skb_clone(hdev->sent_cmd, GFP_KERNEL);
4101 	if (!skb)
4102 		return;
4103 
4104 	skb_queue_head(&hdev->cmd_q, skb);
4105 	queue_work(hdev->workqueue, &hdev->cmd_work);
4106 }
4107 
4108 void hci_req_cmd_complete(struct hci_dev *hdev, u16 opcode, u8 status,
4109 			  hci_req_complete_t *req_complete,
4110 			  hci_req_complete_skb_t *req_complete_skb)
4111 {
4112 	struct sk_buff *skb;
4113 	unsigned long flags;
4114 
4115 	BT_DBG("opcode 0x%04x status 0x%02x", opcode, status);
4116 
4117 	/* If the completed command doesn't match the last one that was
4118 	 * sent we need to do special handling of it.
4119 	 */
4120 	if (!hci_sent_cmd_data(hdev, opcode)) {
4121 		/* Some CSR based controllers generate a spontaneous
4122 		 * reset complete event during init and any pending
4123 		 * command will never be completed. In such a case we
4124 		 * need to resend whatever was the last sent
4125 		 * command.
4126 		 */
4127 		if (test_bit(HCI_INIT, &hdev->flags) && opcode == HCI_OP_RESET)
4128 			hci_resend_last(hdev);
4129 
4130 		return;
4131 	}
4132 
4133 	/* If we reach this point this event matches the last command sent */
4134 	hci_dev_clear_flag(hdev, HCI_CMD_PENDING);
4135 
4136 	/* If the command succeeded and there's still more commands in
4137 	 * this request the request is not yet complete.
4138 	 */
4139 	if (!status && !hci_req_is_complete(hdev))
4140 		return;
4141 
4142 	skb = hdev->req_skb;
4143 
4144 	/* If this was the last command in a request the complete
4145 	 * callback would be found in hdev->req_skb instead of the
4146 	 * command queue (hdev->cmd_q).
4147 	 */
4148 	if (skb && bt_cb(skb)->hci.req_flags & HCI_REQ_SKB) {
4149 		*req_complete_skb = bt_cb(skb)->hci.req_complete_skb;
4150 		return;
4151 	}
4152 
4153 	if (skb && bt_cb(skb)->hci.req_complete) {
4154 		*req_complete = bt_cb(skb)->hci.req_complete;
4155 		return;
4156 	}
4157 
4158 	/* Remove all pending commands belonging to this request */
4159 	spin_lock_irqsave(&hdev->cmd_q.lock, flags);
4160 	while ((skb = __skb_dequeue(&hdev->cmd_q))) {
4161 		if (bt_cb(skb)->hci.req_flags & HCI_REQ_START) {
4162 			__skb_queue_head(&hdev->cmd_q, skb);
4163 			break;
4164 		}
4165 
4166 		if (bt_cb(skb)->hci.req_flags & HCI_REQ_SKB)
4167 			*req_complete_skb = bt_cb(skb)->hci.req_complete_skb;
4168 		else
4169 			*req_complete = bt_cb(skb)->hci.req_complete;
4170 		dev_kfree_skb_irq(skb);
4171 	}
4172 	spin_unlock_irqrestore(&hdev->cmd_q.lock, flags);
4173 }
4174 
4175 static void hci_rx_work(struct work_struct *work)
4176 {
4177 	struct hci_dev *hdev = container_of(work, struct hci_dev, rx_work);
4178 	struct sk_buff *skb;
4179 
4180 	BT_DBG("%s", hdev->name);
4181 
4182 	/* The kcov_remote functions used for collecting packet parsing
4183 	 * coverage information from this background thread and associate
4184 	 * the coverage with the syscall's thread which originally injected
4185 	 * the packet. This helps fuzzing the kernel.
4186 	 */
4187 	for (; (skb = skb_dequeue(&hdev->rx_q)); kcov_remote_stop()) {
4188 		kcov_remote_start_common(skb_get_kcov_handle(skb));
4189 
4190 		/* Send copy to monitor */
4191 		hci_send_to_monitor(hdev, skb);
4192 
4193 		if (atomic_read(&hdev->promisc)) {
4194 			/* Send copy to the sockets */
4195 			hci_send_to_sock(hdev, skb);
4196 		}
4197 
4198 		/* If the device has been opened in HCI_USER_CHANNEL,
4199 		 * the userspace has exclusive access to device.
4200 		 * When device is HCI_INIT, we still need to process
4201 		 * the data packets to the driver in order
4202 		 * to complete its setup().
4203 		 */
4204 		if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL) &&
4205 		    !test_bit(HCI_INIT, &hdev->flags)) {
4206 			kfree_skb(skb);
4207 			continue;
4208 		}
4209 
4210 		if (test_bit(HCI_INIT, &hdev->flags)) {
4211 			/* Don't process data packets in this states. */
4212 			switch (hci_skb_pkt_type(skb)) {
4213 			case HCI_ACLDATA_PKT:
4214 			case HCI_SCODATA_PKT:
4215 			case HCI_ISODATA_PKT:
4216 				kfree_skb(skb);
4217 				continue;
4218 			}
4219 		}
4220 
4221 		/* Process frame */
4222 		switch (hci_skb_pkt_type(skb)) {
4223 		case HCI_EVENT_PKT:
4224 			BT_DBG("%s Event packet", hdev->name);
4225 			hci_event_packet(hdev, skb);
4226 			break;
4227 
4228 		case HCI_ACLDATA_PKT:
4229 			BT_DBG("%s ACL data packet", hdev->name);
4230 			hci_acldata_packet(hdev, skb);
4231 			break;
4232 
4233 		case HCI_SCODATA_PKT:
4234 			BT_DBG("%s SCO data packet", hdev->name);
4235 			hci_scodata_packet(hdev, skb);
4236 			break;
4237 
4238 		case HCI_ISODATA_PKT:
4239 			BT_DBG("%s ISO data packet", hdev->name);
4240 			hci_isodata_packet(hdev, skb);
4241 			break;
4242 
4243 		case HCI_VENDOR_PKT:
4244 			BT_DBG("%s Vendor packet", hdev->name);
4245 			if (hdev->recv_vendor_pkt)
4246 				hdev->recv_vendor_pkt(hdev, skb);
4247 			else
4248 				kfree_skb(skb);
4249 			break;
4250 
4251 		default:
4252 			kfree_skb(skb);
4253 			break;
4254 		}
4255 	}
4256 }
4257 
4258 static int hci_send_cmd_sync(struct hci_dev *hdev, struct sk_buff *skb)
4259 {
4260 	int err;
4261 
4262 	bt_dev_dbg(hdev, "skb %p", skb);
4263 
4264 	hci_dev_lock(hdev);
4265 	kfree_skb(hdev->sent_cmd);
4266 
4267 	hdev->sent_cmd = skb_clone(skb, GFP_KERNEL);
4268 	hci_dev_unlock(hdev);
4269 	if (!hdev->sent_cmd) {
4270 		skb_queue_head(&hdev->cmd_q, skb);
4271 		queue_work(hdev->workqueue, &hdev->cmd_work);
4272 		return -ENOMEM;
4273 	}
4274 
4275 	if (hci_skb_opcode(skb) != HCI_OP_NOP) {
4276 		err = hci_send_frame(hdev, skb);
4277 		if (err < 0) {
4278 			hci_cmd_sync_cancel_sync(hdev, -err);
4279 			return err;
4280 		}
4281 		atomic_dec(&hdev->cmd_cnt);
4282 	} else {
4283 		err = -ENODATA;
4284 		kfree_skb(skb);
4285 	}
4286 
4287 	if (READ_ONCE(hdev->req_status) == HCI_REQ_PEND &&
4288 	    !hci_dev_test_and_set_flag(hdev, HCI_CMD_PENDING)) {
4289 		hci_dev_lock(hdev);
4290 		kfree_skb(hdev->req_skb);
4291 		hdev->req_skb = skb_get(hdev->sent_cmd);
4292 		hci_dev_unlock(hdev);
4293 	}
4294 
4295 	return err;
4296 }
4297 
4298 static void hci_cmd_work(struct work_struct *work)
4299 {
4300 	struct hci_dev *hdev = container_of(work, struct hci_dev, cmd_work);
4301 	struct sk_buff *skb;
4302 	int err;
4303 
4304 	BT_DBG("%s cmd_cnt %d cmd queued %d", hdev->name,
4305 	       atomic_read(&hdev->cmd_cnt), skb_queue_len(&hdev->cmd_q));
4306 
4307 	/* Send queued commands */
4308 	if (atomic_read(&hdev->cmd_cnt)) {
4309 		skb = skb_dequeue(&hdev->cmd_q);
4310 		if (!skb)
4311 			return;
4312 
4313 		err = hci_send_cmd_sync(hdev, skb);
4314 		if (err)
4315 			return;
4316 
4317 		rcu_read_lock();
4318 		if (test_bit(HCI_RESET, &hdev->flags) ||
4319 		    hci_dev_test_flag(hdev, HCI_CMD_DRAIN_WORKQUEUE))
4320 			cancel_delayed_work(&hdev->cmd_timer);
4321 		else
4322 			queue_delayed_work(hdev->workqueue, &hdev->cmd_timer,
4323 					   HCI_CMD_TIMEOUT);
4324 		rcu_read_unlock();
4325 	}
4326 }
4327