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