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