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