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