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