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