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