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