Bluetooth: Support the "discoverable" adv flag
[firefly-linux-kernel-4.4.55.git] / net / bluetooth / mgmt.c
1 /*
2    BlueZ - Bluetooth protocol stack for Linux
3
4    Copyright (C) 2010  Nokia Corporation
5    Copyright (C) 2011-2012 Intel Corporation
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License version 2 as
9    published by the Free Software Foundation;
10
11    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
14    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
15    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
16    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
21    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
22    SOFTWARE IS DISCLAIMED.
23 */
24
25 /* Bluetooth HCI Management interface */
26
27 #include <linux/module.h>
28 #include <asm/unaligned.h>
29
30 #include <net/bluetooth/bluetooth.h>
31 #include <net/bluetooth/hci_core.h>
32 #include <net/bluetooth/hci_sock.h>
33 #include <net/bluetooth/l2cap.h>
34 #include <net/bluetooth/mgmt.h>
35
36 #include "hci_request.h"
37 #include "smp.h"
38 #include "mgmt_util.h"
39
40 #define MGMT_VERSION    1
41 #define MGMT_REVISION   9
42
43 static const u16 mgmt_commands[] = {
44         MGMT_OP_READ_INDEX_LIST,
45         MGMT_OP_READ_INFO,
46         MGMT_OP_SET_POWERED,
47         MGMT_OP_SET_DISCOVERABLE,
48         MGMT_OP_SET_CONNECTABLE,
49         MGMT_OP_SET_FAST_CONNECTABLE,
50         MGMT_OP_SET_BONDABLE,
51         MGMT_OP_SET_LINK_SECURITY,
52         MGMT_OP_SET_SSP,
53         MGMT_OP_SET_HS,
54         MGMT_OP_SET_LE,
55         MGMT_OP_SET_DEV_CLASS,
56         MGMT_OP_SET_LOCAL_NAME,
57         MGMT_OP_ADD_UUID,
58         MGMT_OP_REMOVE_UUID,
59         MGMT_OP_LOAD_LINK_KEYS,
60         MGMT_OP_LOAD_LONG_TERM_KEYS,
61         MGMT_OP_DISCONNECT,
62         MGMT_OP_GET_CONNECTIONS,
63         MGMT_OP_PIN_CODE_REPLY,
64         MGMT_OP_PIN_CODE_NEG_REPLY,
65         MGMT_OP_SET_IO_CAPABILITY,
66         MGMT_OP_PAIR_DEVICE,
67         MGMT_OP_CANCEL_PAIR_DEVICE,
68         MGMT_OP_UNPAIR_DEVICE,
69         MGMT_OP_USER_CONFIRM_REPLY,
70         MGMT_OP_USER_CONFIRM_NEG_REPLY,
71         MGMT_OP_USER_PASSKEY_REPLY,
72         MGMT_OP_USER_PASSKEY_NEG_REPLY,
73         MGMT_OP_READ_LOCAL_OOB_DATA,
74         MGMT_OP_ADD_REMOTE_OOB_DATA,
75         MGMT_OP_REMOVE_REMOTE_OOB_DATA,
76         MGMT_OP_START_DISCOVERY,
77         MGMT_OP_STOP_DISCOVERY,
78         MGMT_OP_CONFIRM_NAME,
79         MGMT_OP_BLOCK_DEVICE,
80         MGMT_OP_UNBLOCK_DEVICE,
81         MGMT_OP_SET_DEVICE_ID,
82         MGMT_OP_SET_ADVERTISING,
83         MGMT_OP_SET_BREDR,
84         MGMT_OP_SET_STATIC_ADDRESS,
85         MGMT_OP_SET_SCAN_PARAMS,
86         MGMT_OP_SET_SECURE_CONN,
87         MGMT_OP_SET_DEBUG_KEYS,
88         MGMT_OP_SET_PRIVACY,
89         MGMT_OP_LOAD_IRKS,
90         MGMT_OP_GET_CONN_INFO,
91         MGMT_OP_GET_CLOCK_INFO,
92         MGMT_OP_ADD_DEVICE,
93         MGMT_OP_REMOVE_DEVICE,
94         MGMT_OP_LOAD_CONN_PARAM,
95         MGMT_OP_READ_UNCONF_INDEX_LIST,
96         MGMT_OP_READ_CONFIG_INFO,
97         MGMT_OP_SET_EXTERNAL_CONFIG,
98         MGMT_OP_SET_PUBLIC_ADDRESS,
99         MGMT_OP_START_SERVICE_DISCOVERY,
100         MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
101         MGMT_OP_READ_EXT_INDEX_LIST,
102         MGMT_OP_READ_ADV_FEATURES,
103         MGMT_OP_ADD_ADVERTISING,
104         MGMT_OP_REMOVE_ADVERTISING,
105 };
106
107 static const u16 mgmt_events[] = {
108         MGMT_EV_CONTROLLER_ERROR,
109         MGMT_EV_INDEX_ADDED,
110         MGMT_EV_INDEX_REMOVED,
111         MGMT_EV_NEW_SETTINGS,
112         MGMT_EV_CLASS_OF_DEV_CHANGED,
113         MGMT_EV_LOCAL_NAME_CHANGED,
114         MGMT_EV_NEW_LINK_KEY,
115         MGMT_EV_NEW_LONG_TERM_KEY,
116         MGMT_EV_DEVICE_CONNECTED,
117         MGMT_EV_DEVICE_DISCONNECTED,
118         MGMT_EV_CONNECT_FAILED,
119         MGMT_EV_PIN_CODE_REQUEST,
120         MGMT_EV_USER_CONFIRM_REQUEST,
121         MGMT_EV_USER_PASSKEY_REQUEST,
122         MGMT_EV_AUTH_FAILED,
123         MGMT_EV_DEVICE_FOUND,
124         MGMT_EV_DISCOVERING,
125         MGMT_EV_DEVICE_BLOCKED,
126         MGMT_EV_DEVICE_UNBLOCKED,
127         MGMT_EV_DEVICE_UNPAIRED,
128         MGMT_EV_PASSKEY_NOTIFY,
129         MGMT_EV_NEW_IRK,
130         MGMT_EV_NEW_CSRK,
131         MGMT_EV_DEVICE_ADDED,
132         MGMT_EV_DEVICE_REMOVED,
133         MGMT_EV_NEW_CONN_PARAM,
134         MGMT_EV_UNCONF_INDEX_ADDED,
135         MGMT_EV_UNCONF_INDEX_REMOVED,
136         MGMT_EV_NEW_CONFIG_OPTIONS,
137         MGMT_EV_EXT_INDEX_ADDED,
138         MGMT_EV_EXT_INDEX_REMOVED,
139         MGMT_EV_LOCAL_OOB_DATA_UPDATED,
140         MGMT_EV_ADVERTISING_ADDED,
141         MGMT_EV_ADVERTISING_REMOVED,
142 };
143
144 static const u16 mgmt_untrusted_commands[] = {
145         MGMT_OP_READ_INDEX_LIST,
146         MGMT_OP_READ_INFO,
147         MGMT_OP_READ_UNCONF_INDEX_LIST,
148         MGMT_OP_READ_CONFIG_INFO,
149         MGMT_OP_READ_EXT_INDEX_LIST,
150 };
151
152 static const u16 mgmt_untrusted_events[] = {
153         MGMT_EV_INDEX_ADDED,
154         MGMT_EV_INDEX_REMOVED,
155         MGMT_EV_NEW_SETTINGS,
156         MGMT_EV_CLASS_OF_DEV_CHANGED,
157         MGMT_EV_LOCAL_NAME_CHANGED,
158         MGMT_EV_UNCONF_INDEX_ADDED,
159         MGMT_EV_UNCONF_INDEX_REMOVED,
160         MGMT_EV_NEW_CONFIG_OPTIONS,
161         MGMT_EV_EXT_INDEX_ADDED,
162         MGMT_EV_EXT_INDEX_REMOVED,
163 };
164
165 #define CACHE_TIMEOUT   msecs_to_jiffies(2 * 1000)
166
167 #define ZERO_KEY "\x00\x00\x00\x00\x00\x00\x00\x00" \
168                  "\x00\x00\x00\x00\x00\x00\x00\x00"
169
170 /* HCI to MGMT error code conversion table */
171 static u8 mgmt_status_table[] = {
172         MGMT_STATUS_SUCCESS,
173         MGMT_STATUS_UNKNOWN_COMMAND,    /* Unknown Command */
174         MGMT_STATUS_NOT_CONNECTED,      /* No Connection */
175         MGMT_STATUS_FAILED,             /* Hardware Failure */
176         MGMT_STATUS_CONNECT_FAILED,     /* Page Timeout */
177         MGMT_STATUS_AUTH_FAILED,        /* Authentication Failed */
178         MGMT_STATUS_AUTH_FAILED,        /* PIN or Key Missing */
179         MGMT_STATUS_NO_RESOURCES,       /* Memory Full */
180         MGMT_STATUS_TIMEOUT,            /* Connection Timeout */
181         MGMT_STATUS_NO_RESOURCES,       /* Max Number of Connections */
182         MGMT_STATUS_NO_RESOURCES,       /* Max Number of SCO Connections */
183         MGMT_STATUS_ALREADY_CONNECTED,  /* ACL Connection Exists */
184         MGMT_STATUS_BUSY,               /* Command Disallowed */
185         MGMT_STATUS_NO_RESOURCES,       /* Rejected Limited Resources */
186         MGMT_STATUS_REJECTED,           /* Rejected Security */
187         MGMT_STATUS_REJECTED,           /* Rejected Personal */
188         MGMT_STATUS_TIMEOUT,            /* Host Timeout */
189         MGMT_STATUS_NOT_SUPPORTED,      /* Unsupported Feature */
190         MGMT_STATUS_INVALID_PARAMS,     /* Invalid Parameters */
191         MGMT_STATUS_DISCONNECTED,       /* OE User Ended Connection */
192         MGMT_STATUS_NO_RESOURCES,       /* OE Low Resources */
193         MGMT_STATUS_DISCONNECTED,       /* OE Power Off */
194         MGMT_STATUS_DISCONNECTED,       /* Connection Terminated */
195         MGMT_STATUS_BUSY,               /* Repeated Attempts */
196         MGMT_STATUS_REJECTED,           /* Pairing Not Allowed */
197         MGMT_STATUS_FAILED,             /* Unknown LMP PDU */
198         MGMT_STATUS_NOT_SUPPORTED,      /* Unsupported Remote Feature */
199         MGMT_STATUS_REJECTED,           /* SCO Offset Rejected */
200         MGMT_STATUS_REJECTED,           /* SCO Interval Rejected */
201         MGMT_STATUS_REJECTED,           /* Air Mode Rejected */
202         MGMT_STATUS_INVALID_PARAMS,     /* Invalid LMP Parameters */
203         MGMT_STATUS_FAILED,             /* Unspecified Error */
204         MGMT_STATUS_NOT_SUPPORTED,      /* Unsupported LMP Parameter Value */
205         MGMT_STATUS_FAILED,             /* Role Change Not Allowed */
206         MGMT_STATUS_TIMEOUT,            /* LMP Response Timeout */
207         MGMT_STATUS_FAILED,             /* LMP Error Transaction Collision */
208         MGMT_STATUS_FAILED,             /* LMP PDU Not Allowed */
209         MGMT_STATUS_REJECTED,           /* Encryption Mode Not Accepted */
210         MGMT_STATUS_FAILED,             /* Unit Link Key Used */
211         MGMT_STATUS_NOT_SUPPORTED,      /* QoS Not Supported */
212         MGMT_STATUS_TIMEOUT,            /* Instant Passed */
213         MGMT_STATUS_NOT_SUPPORTED,      /* Pairing Not Supported */
214         MGMT_STATUS_FAILED,             /* Transaction Collision */
215         MGMT_STATUS_INVALID_PARAMS,     /* Unacceptable Parameter */
216         MGMT_STATUS_REJECTED,           /* QoS Rejected */
217         MGMT_STATUS_NOT_SUPPORTED,      /* Classification Not Supported */
218         MGMT_STATUS_REJECTED,           /* Insufficient Security */
219         MGMT_STATUS_INVALID_PARAMS,     /* Parameter Out Of Range */
220         MGMT_STATUS_BUSY,               /* Role Switch Pending */
221         MGMT_STATUS_FAILED,             /* Slot Violation */
222         MGMT_STATUS_FAILED,             /* Role Switch Failed */
223         MGMT_STATUS_INVALID_PARAMS,     /* EIR Too Large */
224         MGMT_STATUS_NOT_SUPPORTED,      /* Simple Pairing Not Supported */
225         MGMT_STATUS_BUSY,               /* Host Busy Pairing */
226         MGMT_STATUS_REJECTED,           /* Rejected, No Suitable Channel */
227         MGMT_STATUS_BUSY,               /* Controller Busy */
228         MGMT_STATUS_INVALID_PARAMS,     /* Unsuitable Connection Interval */
229         MGMT_STATUS_TIMEOUT,            /* Directed Advertising Timeout */
230         MGMT_STATUS_AUTH_FAILED,        /* Terminated Due to MIC Failure */
231         MGMT_STATUS_CONNECT_FAILED,     /* Connection Establishment Failed */
232         MGMT_STATUS_CONNECT_FAILED,     /* MAC Connection Failed */
233 };
234
235 static u8 mgmt_status(u8 hci_status)
236 {
237         if (hci_status < ARRAY_SIZE(mgmt_status_table))
238                 return mgmt_status_table[hci_status];
239
240         return MGMT_STATUS_FAILED;
241 }
242
243 static int mgmt_index_event(u16 event, struct hci_dev *hdev, void *data,
244                             u16 len, int flag)
245 {
246         return mgmt_send_event(event, hdev, HCI_CHANNEL_CONTROL, data, len,
247                                flag, NULL);
248 }
249
250 static int mgmt_limited_event(u16 event, struct hci_dev *hdev, void *data,
251                               u16 len, int flag, struct sock *skip_sk)
252 {
253         return mgmt_send_event(event, hdev, HCI_CHANNEL_CONTROL, data, len,
254                                flag, skip_sk);
255 }
256
257 static int mgmt_generic_event(u16 event, struct hci_dev *hdev, void *data,
258                               u16 len, struct sock *skip_sk)
259 {
260         return mgmt_send_event(event, hdev, HCI_CHANNEL_CONTROL, data, len,
261                                HCI_MGMT_GENERIC_EVENTS, skip_sk);
262 }
263
264 static int mgmt_event(u16 event, struct hci_dev *hdev, void *data, u16 len,
265                       struct sock *skip_sk)
266 {
267         return mgmt_send_event(event, hdev, HCI_CHANNEL_CONTROL, data, len,
268                                HCI_SOCK_TRUSTED, skip_sk);
269 }
270
271 static int read_version(struct sock *sk, struct hci_dev *hdev, void *data,
272                         u16 data_len)
273 {
274         struct mgmt_rp_read_version rp;
275
276         BT_DBG("sock %p", sk);
277
278         rp.version = MGMT_VERSION;
279         rp.revision = cpu_to_le16(MGMT_REVISION);
280
281         return mgmt_cmd_complete(sk, MGMT_INDEX_NONE, MGMT_OP_READ_VERSION, 0,
282                                  &rp, sizeof(rp));
283 }
284
285 static int read_commands(struct sock *sk, struct hci_dev *hdev, void *data,
286                          u16 data_len)
287 {
288         struct mgmt_rp_read_commands *rp;
289         u16 num_commands, num_events;
290         size_t rp_size;
291         int i, err;
292
293         BT_DBG("sock %p", sk);
294
295         if (hci_sock_test_flag(sk, HCI_SOCK_TRUSTED)) {
296                 num_commands = ARRAY_SIZE(mgmt_commands);
297                 num_events = ARRAY_SIZE(mgmt_events);
298         } else {
299                 num_commands = ARRAY_SIZE(mgmt_untrusted_commands);
300                 num_events = ARRAY_SIZE(mgmt_untrusted_events);
301         }
302
303         rp_size = sizeof(*rp) + ((num_commands + num_events) * sizeof(u16));
304
305         rp = kmalloc(rp_size, GFP_KERNEL);
306         if (!rp)
307                 return -ENOMEM;
308
309         rp->num_commands = cpu_to_le16(num_commands);
310         rp->num_events = cpu_to_le16(num_events);
311
312         if (hci_sock_test_flag(sk, HCI_SOCK_TRUSTED)) {
313                 __le16 *opcode = rp->opcodes;
314
315                 for (i = 0; i < num_commands; i++, opcode++)
316                         put_unaligned_le16(mgmt_commands[i], opcode);
317
318                 for (i = 0; i < num_events; i++, opcode++)
319                         put_unaligned_le16(mgmt_events[i], opcode);
320         } else {
321                 __le16 *opcode = rp->opcodes;
322
323                 for (i = 0; i < num_commands; i++, opcode++)
324                         put_unaligned_le16(mgmt_untrusted_commands[i], opcode);
325
326                 for (i = 0; i < num_events; i++, opcode++)
327                         put_unaligned_le16(mgmt_untrusted_events[i], opcode);
328         }
329
330         err = mgmt_cmd_complete(sk, MGMT_INDEX_NONE, MGMT_OP_READ_COMMANDS, 0,
331                                 rp, rp_size);
332         kfree(rp);
333
334         return err;
335 }
336
337 static int read_index_list(struct sock *sk, struct hci_dev *hdev, void *data,
338                            u16 data_len)
339 {
340         struct mgmt_rp_read_index_list *rp;
341         struct hci_dev *d;
342         size_t rp_len;
343         u16 count;
344         int err;
345
346         BT_DBG("sock %p", sk);
347
348         read_lock(&hci_dev_list_lock);
349
350         count = 0;
351         list_for_each_entry(d, &hci_dev_list, list) {
352                 if (d->dev_type == HCI_BREDR &&
353                     !hci_dev_test_flag(d, HCI_UNCONFIGURED))
354                         count++;
355         }
356
357         rp_len = sizeof(*rp) + (2 * count);
358         rp = kmalloc(rp_len, GFP_ATOMIC);
359         if (!rp) {
360                 read_unlock(&hci_dev_list_lock);
361                 return -ENOMEM;
362         }
363
364         count = 0;
365         list_for_each_entry(d, &hci_dev_list, list) {
366                 if (hci_dev_test_flag(d, HCI_SETUP) ||
367                     hci_dev_test_flag(d, HCI_CONFIG) ||
368                     hci_dev_test_flag(d, HCI_USER_CHANNEL))
369                         continue;
370
371                 /* Devices marked as raw-only are neither configured
372                  * nor unconfigured controllers.
373                  */
374                 if (test_bit(HCI_QUIRK_RAW_DEVICE, &d->quirks))
375                         continue;
376
377                 if (d->dev_type == HCI_BREDR &&
378                     !hci_dev_test_flag(d, HCI_UNCONFIGURED)) {
379                         rp->index[count++] = cpu_to_le16(d->id);
380                         BT_DBG("Added hci%u", d->id);
381                 }
382         }
383
384         rp->num_controllers = cpu_to_le16(count);
385         rp_len = sizeof(*rp) + (2 * count);
386
387         read_unlock(&hci_dev_list_lock);
388
389         err = mgmt_cmd_complete(sk, MGMT_INDEX_NONE, MGMT_OP_READ_INDEX_LIST,
390                                 0, rp, rp_len);
391
392         kfree(rp);
393
394         return err;
395 }
396
397 static int read_unconf_index_list(struct sock *sk, struct hci_dev *hdev,
398                                   void *data, u16 data_len)
399 {
400         struct mgmt_rp_read_unconf_index_list *rp;
401         struct hci_dev *d;
402         size_t rp_len;
403         u16 count;
404         int err;
405
406         BT_DBG("sock %p", sk);
407
408         read_lock(&hci_dev_list_lock);
409
410         count = 0;
411         list_for_each_entry(d, &hci_dev_list, list) {
412                 if (d->dev_type == HCI_BREDR &&
413                     hci_dev_test_flag(d, HCI_UNCONFIGURED))
414                         count++;
415         }
416
417         rp_len = sizeof(*rp) + (2 * count);
418         rp = kmalloc(rp_len, GFP_ATOMIC);
419         if (!rp) {
420                 read_unlock(&hci_dev_list_lock);
421                 return -ENOMEM;
422         }
423
424         count = 0;
425         list_for_each_entry(d, &hci_dev_list, list) {
426                 if (hci_dev_test_flag(d, HCI_SETUP) ||
427                     hci_dev_test_flag(d, HCI_CONFIG) ||
428                     hci_dev_test_flag(d, HCI_USER_CHANNEL))
429                         continue;
430
431                 /* Devices marked as raw-only are neither configured
432                  * nor unconfigured controllers.
433                  */
434                 if (test_bit(HCI_QUIRK_RAW_DEVICE, &d->quirks))
435                         continue;
436
437                 if (d->dev_type == HCI_BREDR &&
438                     hci_dev_test_flag(d, HCI_UNCONFIGURED)) {
439                         rp->index[count++] = cpu_to_le16(d->id);
440                         BT_DBG("Added hci%u", d->id);
441                 }
442         }
443
444         rp->num_controllers = cpu_to_le16(count);
445         rp_len = sizeof(*rp) + (2 * count);
446
447         read_unlock(&hci_dev_list_lock);
448
449         err = mgmt_cmd_complete(sk, MGMT_INDEX_NONE,
450                                 MGMT_OP_READ_UNCONF_INDEX_LIST, 0, rp, rp_len);
451
452         kfree(rp);
453
454         return err;
455 }
456
457 static int read_ext_index_list(struct sock *sk, struct hci_dev *hdev,
458                                void *data, u16 data_len)
459 {
460         struct mgmt_rp_read_ext_index_list *rp;
461         struct hci_dev *d;
462         size_t rp_len;
463         u16 count;
464         int err;
465
466         BT_DBG("sock %p", sk);
467
468         read_lock(&hci_dev_list_lock);
469
470         count = 0;
471         list_for_each_entry(d, &hci_dev_list, list) {
472                 if (d->dev_type == HCI_BREDR || d->dev_type == HCI_AMP)
473                         count++;
474         }
475
476         rp_len = sizeof(*rp) + (sizeof(rp->entry[0]) * count);
477         rp = kmalloc(rp_len, GFP_ATOMIC);
478         if (!rp) {
479                 read_unlock(&hci_dev_list_lock);
480                 return -ENOMEM;
481         }
482
483         count = 0;
484         list_for_each_entry(d, &hci_dev_list, list) {
485                 if (hci_dev_test_flag(d, HCI_SETUP) ||
486                     hci_dev_test_flag(d, HCI_CONFIG) ||
487                     hci_dev_test_flag(d, HCI_USER_CHANNEL))
488                         continue;
489
490                 /* Devices marked as raw-only are neither configured
491                  * nor unconfigured controllers.
492                  */
493                 if (test_bit(HCI_QUIRK_RAW_DEVICE, &d->quirks))
494                         continue;
495
496                 if (d->dev_type == HCI_BREDR) {
497                         if (hci_dev_test_flag(d, HCI_UNCONFIGURED))
498                                 rp->entry[count].type = 0x01;
499                         else
500                                 rp->entry[count].type = 0x00;
501                 } else if (d->dev_type == HCI_AMP) {
502                         rp->entry[count].type = 0x02;
503                 } else {
504                         continue;
505                 }
506
507                 rp->entry[count].bus = d->bus;
508                 rp->entry[count++].index = cpu_to_le16(d->id);
509                 BT_DBG("Added hci%u", d->id);
510         }
511
512         rp->num_controllers = cpu_to_le16(count);
513         rp_len = sizeof(*rp) + (sizeof(rp->entry[0]) * count);
514
515         read_unlock(&hci_dev_list_lock);
516
517         /* If this command is called at least once, then all the
518          * default index and unconfigured index events are disabled
519          * and from now on only extended index events are used.
520          */
521         hci_sock_set_flag(sk, HCI_MGMT_EXT_INDEX_EVENTS);
522         hci_sock_clear_flag(sk, HCI_MGMT_INDEX_EVENTS);
523         hci_sock_clear_flag(sk, HCI_MGMT_UNCONF_INDEX_EVENTS);
524
525         err = mgmt_cmd_complete(sk, MGMT_INDEX_NONE,
526                                 MGMT_OP_READ_EXT_INDEX_LIST, 0, rp, rp_len);
527
528         kfree(rp);
529
530         return err;
531 }
532
533 static bool is_configured(struct hci_dev *hdev)
534 {
535         if (test_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks) &&
536             !hci_dev_test_flag(hdev, HCI_EXT_CONFIGURED))
537                 return false;
538
539         if (test_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks) &&
540             !bacmp(&hdev->public_addr, BDADDR_ANY))
541                 return false;
542
543         return true;
544 }
545
546 static __le32 get_missing_options(struct hci_dev *hdev)
547 {
548         u32 options = 0;
549
550         if (test_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks) &&
551             !hci_dev_test_flag(hdev, HCI_EXT_CONFIGURED))
552                 options |= MGMT_OPTION_EXTERNAL_CONFIG;
553
554         if (test_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks) &&
555             !bacmp(&hdev->public_addr, BDADDR_ANY))
556                 options |= MGMT_OPTION_PUBLIC_ADDRESS;
557
558         return cpu_to_le32(options);
559 }
560
561 static int new_options(struct hci_dev *hdev, struct sock *skip)
562 {
563         __le32 options = get_missing_options(hdev);
564
565         return mgmt_generic_event(MGMT_EV_NEW_CONFIG_OPTIONS, hdev, &options,
566                                   sizeof(options), skip);
567 }
568
569 static int send_options_rsp(struct sock *sk, u16 opcode, struct hci_dev *hdev)
570 {
571         __le32 options = get_missing_options(hdev);
572
573         return mgmt_cmd_complete(sk, hdev->id, opcode, 0, &options,
574                                  sizeof(options));
575 }
576
577 static int read_config_info(struct sock *sk, struct hci_dev *hdev,
578                             void *data, u16 data_len)
579 {
580         struct mgmt_rp_read_config_info rp;
581         u32 options = 0;
582
583         BT_DBG("sock %p %s", sk, hdev->name);
584
585         hci_dev_lock(hdev);
586
587         memset(&rp, 0, sizeof(rp));
588         rp.manufacturer = cpu_to_le16(hdev->manufacturer);
589
590         if (test_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks))
591                 options |= MGMT_OPTION_EXTERNAL_CONFIG;
592
593         if (hdev->set_bdaddr)
594                 options |= MGMT_OPTION_PUBLIC_ADDRESS;
595
596         rp.supported_options = cpu_to_le32(options);
597         rp.missing_options = get_missing_options(hdev);
598
599         hci_dev_unlock(hdev);
600
601         return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_READ_CONFIG_INFO, 0,
602                                  &rp, sizeof(rp));
603 }
604
605 static u32 get_supported_settings(struct hci_dev *hdev)
606 {
607         u32 settings = 0;
608
609         settings |= MGMT_SETTING_POWERED;
610         settings |= MGMT_SETTING_BONDABLE;
611         settings |= MGMT_SETTING_DEBUG_KEYS;
612         settings |= MGMT_SETTING_CONNECTABLE;
613         settings |= MGMT_SETTING_DISCOVERABLE;
614
615         if (lmp_bredr_capable(hdev)) {
616                 if (hdev->hci_ver >= BLUETOOTH_VER_1_2)
617                         settings |= MGMT_SETTING_FAST_CONNECTABLE;
618                 settings |= MGMT_SETTING_BREDR;
619                 settings |= MGMT_SETTING_LINK_SECURITY;
620
621                 if (lmp_ssp_capable(hdev)) {
622                         settings |= MGMT_SETTING_SSP;
623                         settings |= MGMT_SETTING_HS;
624                 }
625
626                 if (lmp_sc_capable(hdev))
627                         settings |= MGMT_SETTING_SECURE_CONN;
628         }
629
630         if (lmp_le_capable(hdev)) {
631                 settings |= MGMT_SETTING_LE;
632                 settings |= MGMT_SETTING_ADVERTISING;
633                 settings |= MGMT_SETTING_SECURE_CONN;
634                 settings |= MGMT_SETTING_PRIVACY;
635                 settings |= MGMT_SETTING_STATIC_ADDRESS;
636         }
637
638         if (test_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks) ||
639             hdev->set_bdaddr)
640                 settings |= MGMT_SETTING_CONFIGURATION;
641
642         return settings;
643 }
644
645 static u32 get_current_settings(struct hci_dev *hdev)
646 {
647         u32 settings = 0;
648
649         if (hdev_is_powered(hdev))
650                 settings |= MGMT_SETTING_POWERED;
651
652         if (hci_dev_test_flag(hdev, HCI_CONNECTABLE))
653                 settings |= MGMT_SETTING_CONNECTABLE;
654
655         if (hci_dev_test_flag(hdev, HCI_FAST_CONNECTABLE))
656                 settings |= MGMT_SETTING_FAST_CONNECTABLE;
657
658         if (hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
659                 settings |= MGMT_SETTING_DISCOVERABLE;
660
661         if (hci_dev_test_flag(hdev, HCI_BONDABLE))
662                 settings |= MGMT_SETTING_BONDABLE;
663
664         if (hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
665                 settings |= MGMT_SETTING_BREDR;
666
667         if (hci_dev_test_flag(hdev, HCI_LE_ENABLED))
668                 settings |= MGMT_SETTING_LE;
669
670         if (hci_dev_test_flag(hdev, HCI_LINK_SECURITY))
671                 settings |= MGMT_SETTING_LINK_SECURITY;
672
673         if (hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
674                 settings |= MGMT_SETTING_SSP;
675
676         if (hci_dev_test_flag(hdev, HCI_HS_ENABLED))
677                 settings |= MGMT_SETTING_HS;
678
679         if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
680                 settings |= MGMT_SETTING_ADVERTISING;
681
682         if (hci_dev_test_flag(hdev, HCI_SC_ENABLED))
683                 settings |= MGMT_SETTING_SECURE_CONN;
684
685         if (hci_dev_test_flag(hdev, HCI_KEEP_DEBUG_KEYS))
686                 settings |= MGMT_SETTING_DEBUG_KEYS;
687
688         if (hci_dev_test_flag(hdev, HCI_PRIVACY))
689                 settings |= MGMT_SETTING_PRIVACY;
690
691         /* The current setting for static address has two purposes. The
692          * first is to indicate if the static address will be used and
693          * the second is to indicate if it is actually set.
694          *
695          * This means if the static address is not configured, this flag
696          * will never be set. If the address is configured, then if the
697          * address is actually used decides if the flag is set or not.
698          *
699          * For single mode LE only controllers and dual-mode controllers
700          * with BR/EDR disabled, the existence of the static address will
701          * be evaluated.
702          */
703         if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
704             !hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) ||
705             !bacmp(&hdev->bdaddr, BDADDR_ANY)) {
706                 if (bacmp(&hdev->static_addr, BDADDR_ANY))
707                         settings |= MGMT_SETTING_STATIC_ADDRESS;
708         }
709
710         return settings;
711 }
712
713 #define PNP_INFO_SVCLASS_ID             0x1200
714
715 static u8 *create_uuid16_list(struct hci_dev *hdev, u8 *data, ptrdiff_t len)
716 {
717         u8 *ptr = data, *uuids_start = NULL;
718         struct bt_uuid *uuid;
719
720         if (len < 4)
721                 return ptr;
722
723         list_for_each_entry(uuid, &hdev->uuids, list) {
724                 u16 uuid16;
725
726                 if (uuid->size != 16)
727                         continue;
728
729                 uuid16 = get_unaligned_le16(&uuid->uuid[12]);
730                 if (uuid16 < 0x1100)
731                         continue;
732
733                 if (uuid16 == PNP_INFO_SVCLASS_ID)
734                         continue;
735
736                 if (!uuids_start) {
737                         uuids_start = ptr;
738                         uuids_start[0] = 1;
739                         uuids_start[1] = EIR_UUID16_ALL;
740                         ptr += 2;
741                 }
742
743                 /* Stop if not enough space to put next UUID */
744                 if ((ptr - data) + sizeof(u16) > len) {
745                         uuids_start[1] = EIR_UUID16_SOME;
746                         break;
747                 }
748
749                 *ptr++ = (uuid16 & 0x00ff);
750                 *ptr++ = (uuid16 & 0xff00) >> 8;
751                 uuids_start[0] += sizeof(uuid16);
752         }
753
754         return ptr;
755 }
756
757 static u8 *create_uuid32_list(struct hci_dev *hdev, u8 *data, ptrdiff_t len)
758 {
759         u8 *ptr = data, *uuids_start = NULL;
760         struct bt_uuid *uuid;
761
762         if (len < 6)
763                 return ptr;
764
765         list_for_each_entry(uuid, &hdev->uuids, list) {
766                 if (uuid->size != 32)
767                         continue;
768
769                 if (!uuids_start) {
770                         uuids_start = ptr;
771                         uuids_start[0] = 1;
772                         uuids_start[1] = EIR_UUID32_ALL;
773                         ptr += 2;
774                 }
775
776                 /* Stop if not enough space to put next UUID */
777                 if ((ptr - data) + sizeof(u32) > len) {
778                         uuids_start[1] = EIR_UUID32_SOME;
779                         break;
780                 }
781
782                 memcpy(ptr, &uuid->uuid[12], sizeof(u32));
783                 ptr += sizeof(u32);
784                 uuids_start[0] += sizeof(u32);
785         }
786
787         return ptr;
788 }
789
790 static u8 *create_uuid128_list(struct hci_dev *hdev, u8 *data, ptrdiff_t len)
791 {
792         u8 *ptr = data, *uuids_start = NULL;
793         struct bt_uuid *uuid;
794
795         if (len < 18)
796                 return ptr;
797
798         list_for_each_entry(uuid, &hdev->uuids, list) {
799                 if (uuid->size != 128)
800                         continue;
801
802                 if (!uuids_start) {
803                         uuids_start = ptr;
804                         uuids_start[0] = 1;
805                         uuids_start[1] = EIR_UUID128_ALL;
806                         ptr += 2;
807                 }
808
809                 /* Stop if not enough space to put next UUID */
810                 if ((ptr - data) + 16 > len) {
811                         uuids_start[1] = EIR_UUID128_SOME;
812                         break;
813                 }
814
815                 memcpy(ptr, uuid->uuid, 16);
816                 ptr += 16;
817                 uuids_start[0] += 16;
818         }
819
820         return ptr;
821 }
822
823 static struct mgmt_pending_cmd *pending_find(u16 opcode, struct hci_dev *hdev)
824 {
825         return mgmt_pending_find(HCI_CHANNEL_CONTROL, opcode, hdev);
826 }
827
828 static struct mgmt_pending_cmd *pending_find_data(u16 opcode,
829                                                   struct hci_dev *hdev,
830                                                   const void *data)
831 {
832         return mgmt_pending_find_data(HCI_CHANNEL_CONTROL, opcode, hdev, data);
833 }
834
835 static u8 create_default_scan_rsp_data(struct hci_dev *hdev, u8 *ptr)
836 {
837         u8 ad_len = 0;
838         size_t name_len;
839
840         name_len = strlen(hdev->dev_name);
841         if (name_len > 0) {
842                 size_t max_len = HCI_MAX_AD_LENGTH - ad_len - 2;
843
844                 if (name_len > max_len) {
845                         name_len = max_len;
846                         ptr[1] = EIR_NAME_SHORT;
847                 } else
848                         ptr[1] = EIR_NAME_COMPLETE;
849
850                 ptr[0] = name_len + 1;
851
852                 memcpy(ptr + 2, hdev->dev_name, name_len);
853
854                 ad_len += (name_len + 2);
855                 ptr += (name_len + 2);
856         }
857
858         return ad_len;
859 }
860
861 static u8 create_instance_scan_rsp_data(struct hci_dev *hdev, u8 *ptr)
862 {
863         /* TODO: Set the appropriate entries based on advertising instance flags
864          * here once flags other than 0 are supported.
865          */
866         memcpy(ptr, hdev->adv_instance.scan_rsp_data,
867                hdev->adv_instance.scan_rsp_len);
868
869         return hdev->adv_instance.scan_rsp_len;
870 }
871
872 static void update_scan_rsp_data_for_instance(struct hci_request *req,
873                                               u8 instance)
874 {
875         struct hci_dev *hdev = req->hdev;
876         struct hci_cp_le_set_scan_rsp_data cp;
877         u8 len;
878
879         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
880                 return;
881
882         memset(&cp, 0, sizeof(cp));
883
884         if (instance)
885                 len = create_instance_scan_rsp_data(hdev, cp.data);
886         else
887                 len = create_default_scan_rsp_data(hdev, cp.data);
888
889         if (hdev->scan_rsp_data_len == len &&
890             !memcmp(cp.data, hdev->scan_rsp_data, len))
891                 return;
892
893         memcpy(hdev->scan_rsp_data, cp.data, sizeof(cp.data));
894         hdev->scan_rsp_data_len = len;
895
896         cp.length = len;
897
898         hci_req_add(req, HCI_OP_LE_SET_SCAN_RSP_DATA, sizeof(cp), &cp);
899 }
900
901 static void update_scan_rsp_data(struct hci_request *req)
902 {
903         struct hci_dev *hdev = req->hdev;
904         u8 instance;
905
906         /* The "Set Advertising" setting supersedes the "Add Advertising"
907          * setting. Here we set the scan response data based on which
908          * setting was set. When neither apply, default to the global settings,
909          * represented by instance "0".
910          */
911         if (hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE) &&
912             !hci_dev_test_flag(hdev, HCI_ADVERTISING))
913                 instance = 0x01;
914         else
915                 instance = 0x00;
916
917         update_scan_rsp_data_for_instance(req, instance);
918 }
919
920 static u8 get_adv_discov_flags(struct hci_dev *hdev)
921 {
922         struct mgmt_pending_cmd *cmd;
923
924         /* If there's a pending mgmt command the flags will not yet have
925          * their final values, so check for this first.
926          */
927         cmd = pending_find(MGMT_OP_SET_DISCOVERABLE, hdev);
928         if (cmd) {
929                 struct mgmt_mode *cp = cmd->param;
930                 if (cp->val == 0x01)
931                         return LE_AD_GENERAL;
932                 else if (cp->val == 0x02)
933                         return LE_AD_LIMITED;
934         } else {
935                 if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE))
936                         return LE_AD_LIMITED;
937                 else if (hci_dev_test_flag(hdev, HCI_DISCOVERABLE))
938                         return LE_AD_GENERAL;
939         }
940
941         return 0;
942 }
943
944 static u8 create_default_adv_data(struct hci_dev *hdev, u8 *ptr)
945 {
946         u8 ad_len = 0, flags = 0;
947
948         flags |= get_adv_discov_flags(hdev);
949
950         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
951                 flags |= LE_AD_NO_BREDR;
952
953         if (flags) {
954                 BT_DBG("adv flags 0x%02x", flags);
955
956                 ptr[0] = 2;
957                 ptr[1] = EIR_FLAGS;
958                 ptr[2] = flags;
959
960                 ad_len += 3;
961                 ptr += 3;
962         }
963
964         if (hdev->adv_tx_power != HCI_TX_POWER_INVALID) {
965                 ptr[0] = 2;
966                 ptr[1] = EIR_TX_POWER;
967                 ptr[2] = (u8) hdev->adv_tx_power;
968
969                 ad_len += 3;
970                 ptr += 3;
971         }
972
973         return ad_len;
974 }
975
976 static u8 create_instance_adv_data(struct hci_dev *hdev, u8 *ptr)
977 {
978         u8 ad_len = 0, flags = 0;
979
980         if (hdev->adv_instance.flags & MGMT_ADV_FLAG_DISCOV)
981                 flags |= LE_AD_GENERAL;
982
983         if (flags) {
984                 if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
985                         flags |= LE_AD_NO_BREDR;
986
987                 ptr[0] = 0x02;
988                 ptr[1] = EIR_FLAGS;
989                 ptr[2] = flags;
990
991                 ad_len += 3;
992                 ptr += 3;
993         }
994
995         memcpy(ptr, hdev->adv_instance.adv_data,
996                hdev->adv_instance.adv_data_len);
997         ad_len += hdev->adv_instance.adv_data_len;
998
999         return ad_len;
1000 }
1001
1002 static void update_adv_data_for_instance(struct hci_request *req, u8 instance)
1003 {
1004         struct hci_dev *hdev = req->hdev;
1005         struct hci_cp_le_set_adv_data cp;
1006         u8 len;
1007
1008         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
1009                 return;
1010
1011         memset(&cp, 0, sizeof(cp));
1012
1013         if (instance)
1014                 len = create_instance_adv_data(hdev, cp.data);
1015         else
1016                 len = create_default_adv_data(hdev, cp.data);
1017
1018         /* There's nothing to do if the data hasn't changed */
1019         if (hdev->adv_data_len == len &&
1020             memcmp(cp.data, hdev->adv_data, len) == 0)
1021                 return;
1022
1023         memcpy(hdev->adv_data, cp.data, sizeof(cp.data));
1024         hdev->adv_data_len = len;
1025
1026         cp.length = len;
1027
1028         hci_req_add(req, HCI_OP_LE_SET_ADV_DATA, sizeof(cp), &cp);
1029 }
1030
1031 static u8 get_current_adv_instance(struct hci_dev *hdev)
1032 {
1033         /* The "Set Advertising" setting supersedes the "Add Advertising"
1034          * setting. Here we set the advertising data based on which
1035          * setting was set. When neither apply, default to the global settings,
1036          * represented by instance "0".
1037          */
1038         if (hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE) &&
1039             !hci_dev_test_flag(hdev, HCI_ADVERTISING))
1040                 return 0x01;
1041
1042         return 0x00;
1043 }
1044
1045 static bool get_connectable(struct hci_dev *hdev)
1046 {
1047         struct mgmt_pending_cmd *cmd;
1048
1049         /* If there's a pending mgmt command the flag will not yet have
1050          * it's final value, so check for this first.
1051          */
1052         cmd = pending_find(MGMT_OP_SET_CONNECTABLE, hdev);
1053         if (cmd) {
1054                 struct mgmt_mode *cp = cmd->param;
1055
1056                 return cp->val;
1057         }
1058
1059         return hci_dev_test_flag(hdev, HCI_CONNECTABLE);
1060 }
1061
1062 static u32 get_adv_instance_flags(struct hci_dev *hdev, u8 instance)
1063 {
1064         u32 flags;
1065
1066         if (instance > 0x01)
1067                 return 0;
1068
1069         if (instance == 1)
1070                 return hdev->adv_instance.flags;
1071
1072         flags = 0;
1073
1074         /* For instance 0, assemble the flags from global settings */
1075         if (hci_dev_test_flag(hdev, HCI_ADVERTISING_CONNECTABLE) ||
1076             get_connectable(hdev))
1077                 flags |= MGMT_ADV_FLAG_CONNECTABLE;
1078
1079         /* TODO: Add the rest of the flags */
1080
1081         return flags;
1082 }
1083
1084 static void update_adv_data(struct hci_request *req)
1085 {
1086         struct hci_dev *hdev = req->hdev;
1087         u8 instance = get_current_adv_instance(hdev);
1088
1089         update_adv_data_for_instance(req, instance);
1090 }
1091
1092 int mgmt_update_adv_data(struct hci_dev *hdev)
1093 {
1094         struct hci_request req;
1095
1096         hci_req_init(&req, hdev);
1097         update_adv_data(&req);
1098
1099         return hci_req_run(&req, NULL);
1100 }
1101
1102 static void create_eir(struct hci_dev *hdev, u8 *data)
1103 {
1104         u8 *ptr = data;
1105         size_t name_len;
1106
1107         name_len = strlen(hdev->dev_name);
1108
1109         if (name_len > 0) {
1110                 /* EIR Data type */
1111                 if (name_len > 48) {
1112                         name_len = 48;
1113                         ptr[1] = EIR_NAME_SHORT;
1114                 } else
1115                         ptr[1] = EIR_NAME_COMPLETE;
1116
1117                 /* EIR Data length */
1118                 ptr[0] = name_len + 1;
1119
1120                 memcpy(ptr + 2, hdev->dev_name, name_len);
1121
1122                 ptr += (name_len + 2);
1123         }
1124
1125         if (hdev->inq_tx_power != HCI_TX_POWER_INVALID) {
1126                 ptr[0] = 2;
1127                 ptr[1] = EIR_TX_POWER;
1128                 ptr[2] = (u8) hdev->inq_tx_power;
1129
1130                 ptr += 3;
1131         }
1132
1133         if (hdev->devid_source > 0) {
1134                 ptr[0] = 9;
1135                 ptr[1] = EIR_DEVICE_ID;
1136
1137                 put_unaligned_le16(hdev->devid_source, ptr + 2);
1138                 put_unaligned_le16(hdev->devid_vendor, ptr + 4);
1139                 put_unaligned_le16(hdev->devid_product, ptr + 6);
1140                 put_unaligned_le16(hdev->devid_version, ptr + 8);
1141
1142                 ptr += 10;
1143         }
1144
1145         ptr = create_uuid16_list(hdev, ptr, HCI_MAX_EIR_LENGTH - (ptr - data));
1146         ptr = create_uuid32_list(hdev, ptr, HCI_MAX_EIR_LENGTH - (ptr - data));
1147         ptr = create_uuid128_list(hdev, ptr, HCI_MAX_EIR_LENGTH - (ptr - data));
1148 }
1149
1150 static void update_eir(struct hci_request *req)
1151 {
1152         struct hci_dev *hdev = req->hdev;
1153         struct hci_cp_write_eir cp;
1154
1155         if (!hdev_is_powered(hdev))
1156                 return;
1157
1158         if (!lmp_ext_inq_capable(hdev))
1159                 return;
1160
1161         if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
1162                 return;
1163
1164         if (hci_dev_test_flag(hdev, HCI_SERVICE_CACHE))
1165                 return;
1166
1167         memset(&cp, 0, sizeof(cp));
1168
1169         create_eir(hdev, cp.data);
1170
1171         if (memcmp(cp.data, hdev->eir, sizeof(cp.data)) == 0)
1172                 return;
1173
1174         memcpy(hdev->eir, cp.data, sizeof(cp.data));
1175
1176         hci_req_add(req, HCI_OP_WRITE_EIR, sizeof(cp), &cp);
1177 }
1178
1179 static u8 get_service_classes(struct hci_dev *hdev)
1180 {
1181         struct bt_uuid *uuid;
1182         u8 val = 0;
1183
1184         list_for_each_entry(uuid, &hdev->uuids, list)
1185                 val |= uuid->svc_hint;
1186
1187         return val;
1188 }
1189
1190 static void update_class(struct hci_request *req)
1191 {
1192         struct hci_dev *hdev = req->hdev;
1193         u8 cod[3];
1194
1195         BT_DBG("%s", hdev->name);
1196
1197         if (!hdev_is_powered(hdev))
1198                 return;
1199
1200         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
1201                 return;
1202
1203         if (hci_dev_test_flag(hdev, HCI_SERVICE_CACHE))
1204                 return;
1205
1206         cod[0] = hdev->minor_class;
1207         cod[1] = hdev->major_class;
1208         cod[2] = get_service_classes(hdev);
1209
1210         if (hci_dev_test_flag(hdev, HCI_LIMITED_DISCOVERABLE))
1211                 cod[1] |= 0x20;
1212
1213         if (memcmp(cod, hdev->dev_class, 3) == 0)
1214                 return;
1215
1216         hci_req_add(req, HCI_OP_WRITE_CLASS_OF_DEV, sizeof(cod), cod);
1217 }
1218
1219 static void disable_advertising(struct hci_request *req)
1220 {
1221         u8 enable = 0x00;
1222
1223         hci_req_add(req, HCI_OP_LE_SET_ADV_ENABLE, sizeof(enable), &enable);
1224 }
1225
1226 static void enable_advertising(struct hci_request *req)
1227 {
1228         struct hci_dev *hdev = req->hdev;
1229         struct hci_cp_le_set_adv_param cp;
1230         u8 own_addr_type, enable = 0x01;
1231         bool connectable;
1232         u8 instance;
1233         u32 flags;
1234
1235         if (hci_conn_num(hdev, LE_LINK) > 0)
1236                 return;
1237
1238         if (hci_dev_test_flag(hdev, HCI_LE_ADV))
1239                 disable_advertising(req);
1240
1241         /* Clear the HCI_LE_ADV bit temporarily so that the
1242          * hci_update_random_address knows that it's safe to go ahead
1243          * and write a new random address. The flag will be set back on
1244          * as soon as the SET_ADV_ENABLE HCI command completes.
1245          */
1246         hci_dev_clear_flag(hdev, HCI_LE_ADV);
1247
1248         instance = get_current_adv_instance(hdev);
1249         flags = get_adv_instance_flags(hdev, instance);
1250         connectable = (flags & MGMT_ADV_FLAG_CONNECTABLE);
1251
1252         /* Set require_privacy to true only when non-connectable
1253          * advertising is used. In that case it is fine to use a
1254          * non-resolvable private address.
1255          */
1256         if (hci_update_random_address(req, !connectable, &own_addr_type) < 0)
1257                 return;
1258
1259         memset(&cp, 0, sizeof(cp));
1260         cp.min_interval = cpu_to_le16(hdev->le_adv_min_interval);
1261         cp.max_interval = cpu_to_le16(hdev->le_adv_max_interval);
1262         cp.type = connectable ? LE_ADV_IND : LE_ADV_NONCONN_IND;
1263         cp.own_address_type = own_addr_type;
1264         cp.channel_map = hdev->le_adv_channel_map;
1265
1266         hci_req_add(req, HCI_OP_LE_SET_ADV_PARAM, sizeof(cp), &cp);
1267
1268         hci_req_add(req, HCI_OP_LE_SET_ADV_ENABLE, sizeof(enable), &enable);
1269 }
1270
1271 static void service_cache_off(struct work_struct *work)
1272 {
1273         struct hci_dev *hdev = container_of(work, struct hci_dev,
1274                                             service_cache.work);
1275         struct hci_request req;
1276
1277         if (!hci_dev_test_and_clear_flag(hdev, HCI_SERVICE_CACHE))
1278                 return;
1279
1280         hci_req_init(&req, hdev);
1281
1282         hci_dev_lock(hdev);
1283
1284         update_eir(&req);
1285         update_class(&req);
1286
1287         hci_dev_unlock(hdev);
1288
1289         hci_req_run(&req, NULL);
1290 }
1291
1292 static void rpa_expired(struct work_struct *work)
1293 {
1294         struct hci_dev *hdev = container_of(work, struct hci_dev,
1295                                             rpa_expired.work);
1296         struct hci_request req;
1297
1298         BT_DBG("");
1299
1300         hci_dev_set_flag(hdev, HCI_RPA_EXPIRED);
1301
1302         if (!hci_dev_test_flag(hdev, HCI_ADVERTISING))
1303                 return;
1304
1305         /* The generation of a new RPA and programming it into the
1306          * controller happens in the enable_advertising() function.
1307          */
1308         hci_req_init(&req, hdev);
1309         enable_advertising(&req);
1310         hci_req_run(&req, NULL);
1311 }
1312
1313 static void mgmt_init_hdev(struct sock *sk, struct hci_dev *hdev)
1314 {
1315         if (hci_dev_test_and_set_flag(hdev, HCI_MGMT))
1316                 return;
1317
1318         INIT_DELAYED_WORK(&hdev->service_cache, service_cache_off);
1319         INIT_DELAYED_WORK(&hdev->rpa_expired, rpa_expired);
1320
1321         /* Non-mgmt controlled devices get this bit set
1322          * implicitly so that pairing works for them, however
1323          * for mgmt we require user-space to explicitly enable
1324          * it
1325          */
1326         hci_dev_clear_flag(hdev, HCI_BONDABLE);
1327 }
1328
1329 static int read_controller_info(struct sock *sk, struct hci_dev *hdev,
1330                                 void *data, u16 data_len)
1331 {
1332         struct mgmt_rp_read_info rp;
1333
1334         BT_DBG("sock %p %s", sk, hdev->name);
1335
1336         hci_dev_lock(hdev);
1337
1338         memset(&rp, 0, sizeof(rp));
1339
1340         bacpy(&rp.bdaddr, &hdev->bdaddr);
1341
1342         rp.version = hdev->hci_ver;
1343         rp.manufacturer = cpu_to_le16(hdev->manufacturer);
1344
1345         rp.supported_settings = cpu_to_le32(get_supported_settings(hdev));
1346         rp.current_settings = cpu_to_le32(get_current_settings(hdev));
1347
1348         memcpy(rp.dev_class, hdev->dev_class, 3);
1349
1350         memcpy(rp.name, hdev->dev_name, sizeof(hdev->dev_name));
1351         memcpy(rp.short_name, hdev->short_name, sizeof(hdev->short_name));
1352
1353         hci_dev_unlock(hdev);
1354
1355         return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_READ_INFO, 0, &rp,
1356                                  sizeof(rp));
1357 }
1358
1359 static int send_settings_rsp(struct sock *sk, u16 opcode, struct hci_dev *hdev)
1360 {
1361         __le32 settings = cpu_to_le32(get_current_settings(hdev));
1362
1363         return mgmt_cmd_complete(sk, hdev->id, opcode, 0, &settings,
1364                                  sizeof(settings));
1365 }
1366
1367 static void clean_up_hci_complete(struct hci_dev *hdev, u8 status, u16 opcode)
1368 {
1369         BT_DBG("%s status 0x%02x", hdev->name, status);
1370
1371         if (hci_conn_count(hdev) == 0) {
1372                 cancel_delayed_work(&hdev->power_off);
1373                 queue_work(hdev->req_workqueue, &hdev->power_off.work);
1374         }
1375 }
1376
1377 static bool hci_stop_discovery(struct hci_request *req)
1378 {
1379         struct hci_dev *hdev = req->hdev;
1380         struct hci_cp_remote_name_req_cancel cp;
1381         struct inquiry_entry *e;
1382
1383         switch (hdev->discovery.state) {
1384         case DISCOVERY_FINDING:
1385                 if (test_bit(HCI_INQUIRY, &hdev->flags))
1386                         hci_req_add(req, HCI_OP_INQUIRY_CANCEL, 0, NULL);
1387
1388                 if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
1389                         cancel_delayed_work(&hdev->le_scan_disable);
1390                         hci_req_add_le_scan_disable(req);
1391                 }
1392
1393                 return true;
1394
1395         case DISCOVERY_RESOLVING:
1396                 e = hci_inquiry_cache_lookup_resolve(hdev, BDADDR_ANY,
1397                                                      NAME_PENDING);
1398                 if (!e)
1399                         break;
1400
1401                 bacpy(&cp.bdaddr, &e->data.bdaddr);
1402                 hci_req_add(req, HCI_OP_REMOTE_NAME_REQ_CANCEL, sizeof(cp),
1403                             &cp);
1404
1405                 return true;
1406
1407         default:
1408                 /* Passive scanning */
1409                 if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
1410                         hci_req_add_le_scan_disable(req);
1411                         return true;
1412                 }
1413
1414                 break;
1415         }
1416
1417         return false;
1418 }
1419
1420 static void advertising_added(struct sock *sk, struct hci_dev *hdev,
1421                               u8 instance)
1422 {
1423         struct mgmt_ev_advertising_added ev;
1424
1425         ev.instance = instance;
1426
1427         mgmt_event(MGMT_EV_ADVERTISING_ADDED, hdev, &ev, sizeof(ev), sk);
1428 }
1429
1430 static void advertising_removed(struct sock *sk, struct hci_dev *hdev,
1431                                 u8 instance)
1432 {
1433         struct mgmt_ev_advertising_removed ev;
1434
1435         ev.instance = instance;
1436
1437         mgmt_event(MGMT_EV_ADVERTISING_REMOVED, hdev, &ev, sizeof(ev), sk);
1438 }
1439
1440 static void clear_adv_instance(struct hci_dev *hdev)
1441 {
1442         struct hci_request req;
1443
1444         if (!hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE))
1445                 return;
1446
1447         if (hdev->adv_instance.timeout)
1448                 cancel_delayed_work(&hdev->adv_instance.timeout_exp);
1449
1450         memset(&hdev->adv_instance, 0, sizeof(hdev->adv_instance));
1451         advertising_removed(NULL, hdev, 1);
1452         hci_dev_clear_flag(hdev, HCI_ADVERTISING_INSTANCE);
1453
1454         if (!hdev_is_powered(hdev) ||
1455             hci_dev_test_flag(hdev, HCI_ADVERTISING))
1456                 return;
1457
1458         hci_req_init(&req, hdev);
1459         disable_advertising(&req);
1460         hci_req_run(&req, NULL);
1461 }
1462
1463 static int clean_up_hci_state(struct hci_dev *hdev)
1464 {
1465         struct hci_request req;
1466         struct hci_conn *conn;
1467         bool discov_stopped;
1468         int err;
1469
1470         hci_req_init(&req, hdev);
1471
1472         if (test_bit(HCI_ISCAN, &hdev->flags) ||
1473             test_bit(HCI_PSCAN, &hdev->flags)) {
1474                 u8 scan = 0x00;
1475                 hci_req_add(&req, HCI_OP_WRITE_SCAN_ENABLE, 1, &scan);
1476         }
1477
1478         if (hdev->adv_instance.timeout)
1479                 clear_adv_instance(hdev);
1480
1481         if (hci_dev_test_flag(hdev, HCI_LE_ADV))
1482                 disable_advertising(&req);
1483
1484         discov_stopped = hci_stop_discovery(&req);
1485
1486         list_for_each_entry(conn, &hdev->conn_hash.list, list) {
1487                 struct hci_cp_disconnect dc;
1488                 struct hci_cp_reject_conn_req rej;
1489
1490                 switch (conn->state) {
1491                 case BT_CONNECTED:
1492                 case BT_CONFIG:
1493                         dc.handle = cpu_to_le16(conn->handle);
1494                         dc.reason = 0x15; /* Terminated due to Power Off */
1495                         hci_req_add(&req, HCI_OP_DISCONNECT, sizeof(dc), &dc);
1496                         break;
1497                 case BT_CONNECT:
1498                         if (conn->type == LE_LINK)
1499                                 hci_req_add(&req, HCI_OP_LE_CREATE_CONN_CANCEL,
1500                                             0, NULL);
1501                         else if (conn->type == ACL_LINK)
1502                                 hci_req_add(&req, HCI_OP_CREATE_CONN_CANCEL,
1503                                             6, &conn->dst);
1504                         break;
1505                 case BT_CONNECT2:
1506                         bacpy(&rej.bdaddr, &conn->dst);
1507                         rej.reason = 0x15; /* Terminated due to Power Off */
1508                         if (conn->type == ACL_LINK)
1509                                 hci_req_add(&req, HCI_OP_REJECT_CONN_REQ,
1510                                             sizeof(rej), &rej);
1511                         else if (conn->type == SCO_LINK)
1512                                 hci_req_add(&req, HCI_OP_REJECT_SYNC_CONN_REQ,
1513                                             sizeof(rej), &rej);
1514                         break;
1515                 }
1516         }
1517
1518         err = hci_req_run(&req, clean_up_hci_complete);
1519         if (!err && discov_stopped)
1520                 hci_discovery_set_state(hdev, DISCOVERY_STOPPING);
1521
1522         return err;
1523 }
1524
1525 static int set_powered(struct sock *sk, struct hci_dev *hdev, void *data,
1526                        u16 len)
1527 {
1528         struct mgmt_mode *cp = data;
1529         struct mgmt_pending_cmd *cmd;
1530         int err;
1531
1532         BT_DBG("request for %s", hdev->name);
1533
1534         if (cp->val != 0x00 && cp->val != 0x01)
1535                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_POWERED,
1536                                        MGMT_STATUS_INVALID_PARAMS);
1537
1538         hci_dev_lock(hdev);
1539
1540         if (pending_find(MGMT_OP_SET_POWERED, hdev)) {
1541                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_POWERED,
1542                                       MGMT_STATUS_BUSY);
1543                 goto failed;
1544         }
1545
1546         if (hci_dev_test_and_clear_flag(hdev, HCI_AUTO_OFF)) {
1547                 cancel_delayed_work(&hdev->power_off);
1548
1549                 if (cp->val) {
1550                         mgmt_pending_add(sk, MGMT_OP_SET_POWERED, hdev,
1551                                          data, len);
1552                         err = mgmt_powered(hdev, 1);
1553                         goto failed;
1554                 }
1555         }
1556
1557         if (!!cp->val == hdev_is_powered(hdev)) {
1558                 err = send_settings_rsp(sk, MGMT_OP_SET_POWERED, hdev);
1559                 goto failed;
1560         }
1561
1562         cmd = mgmt_pending_add(sk, MGMT_OP_SET_POWERED, hdev, data, len);
1563         if (!cmd) {
1564                 err = -ENOMEM;
1565                 goto failed;
1566         }
1567
1568         if (cp->val) {
1569                 queue_work(hdev->req_workqueue, &hdev->power_on);
1570                 err = 0;
1571         } else {
1572                 /* Disconnect connections, stop scans, etc */
1573                 err = clean_up_hci_state(hdev);
1574                 if (!err)
1575                         queue_delayed_work(hdev->req_workqueue, &hdev->power_off,
1576                                            HCI_POWER_OFF_TIMEOUT);
1577
1578                 /* ENODATA means there were no HCI commands queued */
1579                 if (err == -ENODATA) {
1580                         cancel_delayed_work(&hdev->power_off);
1581                         queue_work(hdev->req_workqueue, &hdev->power_off.work);
1582                         err = 0;
1583                 }
1584         }
1585
1586 failed:
1587         hci_dev_unlock(hdev);
1588         return err;
1589 }
1590
1591 static int new_settings(struct hci_dev *hdev, struct sock *skip)
1592 {
1593         __le32 ev = cpu_to_le32(get_current_settings(hdev));
1594
1595         return mgmt_generic_event(MGMT_EV_NEW_SETTINGS, hdev, &ev,
1596                                   sizeof(ev), skip);
1597 }
1598
1599 int mgmt_new_settings(struct hci_dev *hdev)
1600 {
1601         return new_settings(hdev, NULL);
1602 }
1603
1604 struct cmd_lookup {
1605         struct sock *sk;
1606         struct hci_dev *hdev;
1607         u8 mgmt_status;
1608 };
1609
1610 static void settings_rsp(struct mgmt_pending_cmd *cmd, void *data)
1611 {
1612         struct cmd_lookup *match = data;
1613
1614         send_settings_rsp(cmd->sk, cmd->opcode, match->hdev);
1615
1616         list_del(&cmd->list);
1617
1618         if (match->sk == NULL) {
1619                 match->sk = cmd->sk;
1620                 sock_hold(match->sk);
1621         }
1622
1623         mgmt_pending_free(cmd);
1624 }
1625
1626 static void cmd_status_rsp(struct mgmt_pending_cmd *cmd, void *data)
1627 {
1628         u8 *status = data;
1629
1630         mgmt_cmd_status(cmd->sk, cmd->index, cmd->opcode, *status);
1631         mgmt_pending_remove(cmd);
1632 }
1633
1634 static void cmd_complete_rsp(struct mgmt_pending_cmd *cmd, void *data)
1635 {
1636         if (cmd->cmd_complete) {
1637                 u8 *status = data;
1638
1639                 cmd->cmd_complete(cmd, *status);
1640                 mgmt_pending_remove(cmd);
1641
1642                 return;
1643         }
1644
1645         cmd_status_rsp(cmd, data);
1646 }
1647
1648 static int generic_cmd_complete(struct mgmt_pending_cmd *cmd, u8 status)
1649 {
1650         return mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode, status,
1651                                  cmd->param, cmd->param_len);
1652 }
1653
1654 static int addr_cmd_complete(struct mgmt_pending_cmd *cmd, u8 status)
1655 {
1656         return mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode, status,
1657                                  cmd->param, sizeof(struct mgmt_addr_info));
1658 }
1659
1660 static u8 mgmt_bredr_support(struct hci_dev *hdev)
1661 {
1662         if (!lmp_bredr_capable(hdev))
1663                 return MGMT_STATUS_NOT_SUPPORTED;
1664         else if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
1665                 return MGMT_STATUS_REJECTED;
1666         else
1667                 return MGMT_STATUS_SUCCESS;
1668 }
1669
1670 static u8 mgmt_le_support(struct hci_dev *hdev)
1671 {
1672         if (!lmp_le_capable(hdev))
1673                 return MGMT_STATUS_NOT_SUPPORTED;
1674         else if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
1675                 return MGMT_STATUS_REJECTED;
1676         else
1677                 return MGMT_STATUS_SUCCESS;
1678 }
1679
1680 static void set_discoverable_complete(struct hci_dev *hdev, u8 status,
1681                                       u16 opcode)
1682 {
1683         struct mgmt_pending_cmd *cmd;
1684         struct mgmt_mode *cp;
1685         struct hci_request req;
1686         bool changed;
1687
1688         BT_DBG("status 0x%02x", status);
1689
1690         hci_dev_lock(hdev);
1691
1692         cmd = pending_find(MGMT_OP_SET_DISCOVERABLE, hdev);
1693         if (!cmd)
1694                 goto unlock;
1695
1696         if (status) {
1697                 u8 mgmt_err = mgmt_status(status);
1698                 mgmt_cmd_status(cmd->sk, cmd->index, cmd->opcode, mgmt_err);
1699                 hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
1700                 goto remove_cmd;
1701         }
1702
1703         cp = cmd->param;
1704         if (cp->val) {
1705                 changed = !hci_dev_test_and_set_flag(hdev, HCI_DISCOVERABLE);
1706
1707                 if (hdev->discov_timeout > 0) {
1708                         int to = msecs_to_jiffies(hdev->discov_timeout * 1000);
1709                         queue_delayed_work(hdev->workqueue, &hdev->discov_off,
1710                                            to);
1711                 }
1712         } else {
1713                 changed = hci_dev_test_and_clear_flag(hdev, HCI_DISCOVERABLE);
1714         }
1715
1716         send_settings_rsp(cmd->sk, MGMT_OP_SET_DISCOVERABLE, hdev);
1717
1718         if (changed)
1719                 new_settings(hdev, cmd->sk);
1720
1721         /* When the discoverable mode gets changed, make sure
1722          * that class of device has the limited discoverable
1723          * bit correctly set. Also update page scan based on whitelist
1724          * entries.
1725          */
1726         hci_req_init(&req, hdev);
1727         __hci_update_page_scan(&req);
1728         update_class(&req);
1729         hci_req_run(&req, NULL);
1730
1731 remove_cmd:
1732         mgmt_pending_remove(cmd);
1733
1734 unlock:
1735         hci_dev_unlock(hdev);
1736 }
1737
1738 static int set_discoverable(struct sock *sk, struct hci_dev *hdev, void *data,
1739                             u16 len)
1740 {
1741         struct mgmt_cp_set_discoverable *cp = data;
1742         struct mgmt_pending_cmd *cmd;
1743         struct hci_request req;
1744         u16 timeout;
1745         u8 scan;
1746         int err;
1747
1748         BT_DBG("request for %s", hdev->name);
1749
1750         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED) &&
1751             !hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
1752                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DISCOVERABLE,
1753                                        MGMT_STATUS_REJECTED);
1754
1755         if (cp->val != 0x00 && cp->val != 0x01 && cp->val != 0x02)
1756                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DISCOVERABLE,
1757                                        MGMT_STATUS_INVALID_PARAMS);
1758
1759         timeout = __le16_to_cpu(cp->timeout);
1760
1761         /* Disabling discoverable requires that no timeout is set,
1762          * and enabling limited discoverable requires a timeout.
1763          */
1764         if ((cp->val == 0x00 && timeout > 0) ||
1765             (cp->val == 0x02 && timeout == 0))
1766                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DISCOVERABLE,
1767                                        MGMT_STATUS_INVALID_PARAMS);
1768
1769         hci_dev_lock(hdev);
1770
1771         if (!hdev_is_powered(hdev) && timeout > 0) {
1772                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DISCOVERABLE,
1773                                       MGMT_STATUS_NOT_POWERED);
1774                 goto failed;
1775         }
1776
1777         if (pending_find(MGMT_OP_SET_DISCOVERABLE, hdev) ||
1778             pending_find(MGMT_OP_SET_CONNECTABLE, hdev)) {
1779                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DISCOVERABLE,
1780                                       MGMT_STATUS_BUSY);
1781                 goto failed;
1782         }
1783
1784         if (!hci_dev_test_flag(hdev, HCI_CONNECTABLE)) {
1785                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DISCOVERABLE,
1786                                       MGMT_STATUS_REJECTED);
1787                 goto failed;
1788         }
1789
1790         if (!hdev_is_powered(hdev)) {
1791                 bool changed = false;
1792
1793                 /* Setting limited discoverable when powered off is
1794                  * not a valid operation since it requires a timeout
1795                  * and so no need to check HCI_LIMITED_DISCOVERABLE.
1796                  */
1797                 if (!!cp->val != hci_dev_test_flag(hdev, HCI_DISCOVERABLE)) {
1798                         hci_dev_change_flag(hdev, HCI_DISCOVERABLE);
1799                         changed = true;
1800                 }
1801
1802                 err = send_settings_rsp(sk, MGMT_OP_SET_DISCOVERABLE, hdev);
1803                 if (err < 0)
1804                         goto failed;
1805
1806                 if (changed)
1807                         err = new_settings(hdev, sk);
1808
1809                 goto failed;
1810         }
1811
1812         /* If the current mode is the same, then just update the timeout
1813          * value with the new value. And if only the timeout gets updated,
1814          * then no need for any HCI transactions.
1815          */
1816         if (!!cp->val == hci_dev_test_flag(hdev, HCI_DISCOVERABLE) &&
1817             (cp->val == 0x02) == hci_dev_test_flag(hdev,
1818                                                    HCI_LIMITED_DISCOVERABLE)) {
1819                 cancel_delayed_work(&hdev->discov_off);
1820                 hdev->discov_timeout = timeout;
1821
1822                 if (cp->val && hdev->discov_timeout > 0) {
1823                         int to = msecs_to_jiffies(hdev->discov_timeout * 1000);
1824                         queue_delayed_work(hdev->workqueue, &hdev->discov_off,
1825                                            to);
1826                 }
1827
1828                 err = send_settings_rsp(sk, MGMT_OP_SET_DISCOVERABLE, hdev);
1829                 goto failed;
1830         }
1831
1832         cmd = mgmt_pending_add(sk, MGMT_OP_SET_DISCOVERABLE, hdev, data, len);
1833         if (!cmd) {
1834                 err = -ENOMEM;
1835                 goto failed;
1836         }
1837
1838         /* Cancel any potential discoverable timeout that might be
1839          * still active and store new timeout value. The arming of
1840          * the timeout happens in the complete handler.
1841          */
1842         cancel_delayed_work(&hdev->discov_off);
1843         hdev->discov_timeout = timeout;
1844
1845         /* Limited discoverable mode */
1846         if (cp->val == 0x02)
1847                 hci_dev_set_flag(hdev, HCI_LIMITED_DISCOVERABLE);
1848         else
1849                 hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
1850
1851         hci_req_init(&req, hdev);
1852
1853         /* The procedure for LE-only controllers is much simpler - just
1854          * update the advertising data.
1855          */
1856         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
1857                 goto update_ad;
1858
1859         scan = SCAN_PAGE;
1860
1861         if (cp->val) {
1862                 struct hci_cp_write_current_iac_lap hci_cp;
1863
1864                 if (cp->val == 0x02) {
1865                         /* Limited discoverable mode */
1866                         hci_cp.num_iac = min_t(u8, hdev->num_iac, 2);
1867                         hci_cp.iac_lap[0] = 0x00;       /* LIAC */
1868                         hci_cp.iac_lap[1] = 0x8b;
1869                         hci_cp.iac_lap[2] = 0x9e;
1870                         hci_cp.iac_lap[3] = 0x33;       /* GIAC */
1871                         hci_cp.iac_lap[4] = 0x8b;
1872                         hci_cp.iac_lap[5] = 0x9e;
1873                 } else {
1874                         /* General discoverable mode */
1875                         hci_cp.num_iac = 1;
1876                         hci_cp.iac_lap[0] = 0x33;       /* GIAC */
1877                         hci_cp.iac_lap[1] = 0x8b;
1878                         hci_cp.iac_lap[2] = 0x9e;
1879                 }
1880
1881                 hci_req_add(&req, HCI_OP_WRITE_CURRENT_IAC_LAP,
1882                             (hci_cp.num_iac * 3) + 1, &hci_cp);
1883
1884                 scan |= SCAN_INQUIRY;
1885         } else {
1886                 hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
1887         }
1888
1889         hci_req_add(&req, HCI_OP_WRITE_SCAN_ENABLE, sizeof(scan), &scan);
1890
1891 update_ad:
1892         update_adv_data(&req);
1893
1894         err = hci_req_run(&req, set_discoverable_complete);
1895         if (err < 0)
1896                 mgmt_pending_remove(cmd);
1897
1898 failed:
1899         hci_dev_unlock(hdev);
1900         return err;
1901 }
1902
1903 static void write_fast_connectable(struct hci_request *req, bool enable)
1904 {
1905         struct hci_dev *hdev = req->hdev;
1906         struct hci_cp_write_page_scan_activity acp;
1907         u8 type;
1908
1909         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
1910                 return;
1911
1912         if (hdev->hci_ver < BLUETOOTH_VER_1_2)
1913                 return;
1914
1915         if (enable) {
1916                 type = PAGE_SCAN_TYPE_INTERLACED;
1917
1918                 /* 160 msec page scan interval */
1919                 acp.interval = cpu_to_le16(0x0100);
1920         } else {
1921                 type = PAGE_SCAN_TYPE_STANDARD; /* default */
1922
1923                 /* default 1.28 sec page scan */
1924                 acp.interval = cpu_to_le16(0x0800);
1925         }
1926
1927         acp.window = cpu_to_le16(0x0012);
1928
1929         if (__cpu_to_le16(hdev->page_scan_interval) != acp.interval ||
1930             __cpu_to_le16(hdev->page_scan_window) != acp.window)
1931                 hci_req_add(req, HCI_OP_WRITE_PAGE_SCAN_ACTIVITY,
1932                             sizeof(acp), &acp);
1933
1934         if (hdev->page_scan_type != type)
1935                 hci_req_add(req, HCI_OP_WRITE_PAGE_SCAN_TYPE, 1, &type);
1936 }
1937
1938 static void set_connectable_complete(struct hci_dev *hdev, u8 status,
1939                                      u16 opcode)
1940 {
1941         struct mgmt_pending_cmd *cmd;
1942         struct mgmt_mode *cp;
1943         bool conn_changed, discov_changed;
1944
1945         BT_DBG("status 0x%02x", status);
1946
1947         hci_dev_lock(hdev);
1948
1949         cmd = pending_find(MGMT_OP_SET_CONNECTABLE, hdev);
1950         if (!cmd)
1951                 goto unlock;
1952
1953         if (status) {
1954                 u8 mgmt_err = mgmt_status(status);
1955                 mgmt_cmd_status(cmd->sk, cmd->index, cmd->opcode, mgmt_err);
1956                 goto remove_cmd;
1957         }
1958
1959         cp = cmd->param;
1960         if (cp->val) {
1961                 conn_changed = !hci_dev_test_and_set_flag(hdev,
1962                                                           HCI_CONNECTABLE);
1963                 discov_changed = false;
1964         } else {
1965                 conn_changed = hci_dev_test_and_clear_flag(hdev,
1966                                                            HCI_CONNECTABLE);
1967                 discov_changed = hci_dev_test_and_clear_flag(hdev,
1968                                                              HCI_DISCOVERABLE);
1969         }
1970
1971         send_settings_rsp(cmd->sk, MGMT_OP_SET_CONNECTABLE, hdev);
1972
1973         if (conn_changed || discov_changed) {
1974                 new_settings(hdev, cmd->sk);
1975                 hci_update_page_scan(hdev);
1976                 if (discov_changed)
1977                         mgmt_update_adv_data(hdev);
1978                 hci_update_background_scan(hdev);
1979         }
1980
1981 remove_cmd:
1982         mgmt_pending_remove(cmd);
1983
1984 unlock:
1985         hci_dev_unlock(hdev);
1986 }
1987
1988 static int set_connectable_update_settings(struct hci_dev *hdev,
1989                                            struct sock *sk, u8 val)
1990 {
1991         bool changed = false;
1992         int err;
1993
1994         if (!!val != hci_dev_test_flag(hdev, HCI_CONNECTABLE))
1995                 changed = true;
1996
1997         if (val) {
1998                 hci_dev_set_flag(hdev, HCI_CONNECTABLE);
1999         } else {
2000                 hci_dev_clear_flag(hdev, HCI_CONNECTABLE);
2001                 hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
2002         }
2003
2004         err = send_settings_rsp(sk, MGMT_OP_SET_CONNECTABLE, hdev);
2005         if (err < 0)
2006                 return err;
2007
2008         if (changed) {
2009                 hci_update_page_scan(hdev);
2010                 hci_update_background_scan(hdev);
2011                 return new_settings(hdev, sk);
2012         }
2013
2014         return 0;
2015 }
2016
2017 static int set_connectable(struct sock *sk, struct hci_dev *hdev, void *data,
2018                            u16 len)
2019 {
2020         struct mgmt_mode *cp = data;
2021         struct mgmt_pending_cmd *cmd;
2022         struct hci_request req;
2023         u8 scan;
2024         int err;
2025
2026         BT_DBG("request for %s", hdev->name);
2027
2028         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED) &&
2029             !hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
2030                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_CONNECTABLE,
2031                                        MGMT_STATUS_REJECTED);
2032
2033         if (cp->val != 0x00 && cp->val != 0x01)
2034                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_CONNECTABLE,
2035                                        MGMT_STATUS_INVALID_PARAMS);
2036
2037         hci_dev_lock(hdev);
2038
2039         if (!hdev_is_powered(hdev)) {
2040                 err = set_connectable_update_settings(hdev, sk, cp->val);
2041                 goto failed;
2042         }
2043
2044         if (pending_find(MGMT_OP_SET_DISCOVERABLE, hdev) ||
2045             pending_find(MGMT_OP_SET_CONNECTABLE, hdev)) {
2046                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_CONNECTABLE,
2047                                       MGMT_STATUS_BUSY);
2048                 goto failed;
2049         }
2050
2051         cmd = mgmt_pending_add(sk, MGMT_OP_SET_CONNECTABLE, hdev, data, len);
2052         if (!cmd) {
2053                 err = -ENOMEM;
2054                 goto failed;
2055         }
2056
2057         hci_req_init(&req, hdev);
2058
2059         /* If BR/EDR is not enabled and we disable advertising as a
2060          * by-product of disabling connectable, we need to update the
2061          * advertising flags.
2062          */
2063         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
2064                 if (!cp->val) {
2065                         hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
2066                         hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
2067                 }
2068                 update_adv_data(&req);
2069         } else if (cp->val != test_bit(HCI_PSCAN, &hdev->flags)) {
2070                 if (cp->val) {
2071                         scan = SCAN_PAGE;
2072                 } else {
2073                         /* If we don't have any whitelist entries just
2074                          * disable all scanning. If there are entries
2075                          * and we had both page and inquiry scanning
2076                          * enabled then fall back to only page scanning.
2077                          * Otherwise no changes are needed.
2078                          */
2079                         if (list_empty(&hdev->whitelist))
2080                                 scan = SCAN_DISABLED;
2081                         else if (test_bit(HCI_ISCAN, &hdev->flags))
2082                                 scan = SCAN_PAGE;
2083                         else
2084                                 goto no_scan_update;
2085
2086                         if (test_bit(HCI_ISCAN, &hdev->flags) &&
2087                             hdev->discov_timeout > 0)
2088                                 cancel_delayed_work(&hdev->discov_off);
2089                 }
2090
2091                 hci_req_add(&req, HCI_OP_WRITE_SCAN_ENABLE, 1, &scan);
2092         }
2093
2094 no_scan_update:
2095         /* Update the advertising parameters if necessary */
2096         if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
2097                 enable_advertising(&req);
2098
2099         err = hci_req_run(&req, set_connectable_complete);
2100         if (err < 0) {
2101                 mgmt_pending_remove(cmd);
2102                 if (err == -ENODATA)
2103                         err = set_connectable_update_settings(hdev, sk,
2104                                                               cp->val);
2105                 goto failed;
2106         }
2107
2108 failed:
2109         hci_dev_unlock(hdev);
2110         return err;
2111 }
2112
2113 static int set_bondable(struct sock *sk, struct hci_dev *hdev, void *data,
2114                         u16 len)
2115 {
2116         struct mgmt_mode *cp = data;
2117         bool changed;
2118         int err;
2119
2120         BT_DBG("request for %s", hdev->name);
2121
2122         if (cp->val != 0x00 && cp->val != 0x01)
2123                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BONDABLE,
2124                                        MGMT_STATUS_INVALID_PARAMS);
2125
2126         hci_dev_lock(hdev);
2127
2128         if (cp->val)
2129                 changed = !hci_dev_test_and_set_flag(hdev, HCI_BONDABLE);
2130         else
2131                 changed = hci_dev_test_and_clear_flag(hdev, HCI_BONDABLE);
2132
2133         err = send_settings_rsp(sk, MGMT_OP_SET_BONDABLE, hdev);
2134         if (err < 0)
2135                 goto unlock;
2136
2137         if (changed)
2138                 err = new_settings(hdev, sk);
2139
2140 unlock:
2141         hci_dev_unlock(hdev);
2142         return err;
2143 }
2144
2145 static int set_link_security(struct sock *sk, struct hci_dev *hdev, void *data,
2146                              u16 len)
2147 {
2148         struct mgmt_mode *cp = data;
2149         struct mgmt_pending_cmd *cmd;
2150         u8 val, status;
2151         int err;
2152
2153         BT_DBG("request for %s", hdev->name);
2154
2155         status = mgmt_bredr_support(hdev);
2156         if (status)
2157                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LINK_SECURITY,
2158                                        status);
2159
2160         if (cp->val != 0x00 && cp->val != 0x01)
2161                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LINK_SECURITY,
2162                                        MGMT_STATUS_INVALID_PARAMS);
2163
2164         hci_dev_lock(hdev);
2165
2166         if (!hdev_is_powered(hdev)) {
2167                 bool changed = false;
2168
2169                 if (!!cp->val != hci_dev_test_flag(hdev, HCI_LINK_SECURITY)) {
2170                         hci_dev_change_flag(hdev, HCI_LINK_SECURITY);
2171                         changed = true;
2172                 }
2173
2174                 err = send_settings_rsp(sk, MGMT_OP_SET_LINK_SECURITY, hdev);
2175                 if (err < 0)
2176                         goto failed;
2177
2178                 if (changed)
2179                         err = new_settings(hdev, sk);
2180
2181                 goto failed;
2182         }
2183
2184         if (pending_find(MGMT_OP_SET_LINK_SECURITY, hdev)) {
2185                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LINK_SECURITY,
2186                                       MGMT_STATUS_BUSY);
2187                 goto failed;
2188         }
2189
2190         val = !!cp->val;
2191
2192         if (test_bit(HCI_AUTH, &hdev->flags) == val) {
2193                 err = send_settings_rsp(sk, MGMT_OP_SET_LINK_SECURITY, hdev);
2194                 goto failed;
2195         }
2196
2197         cmd = mgmt_pending_add(sk, MGMT_OP_SET_LINK_SECURITY, hdev, data, len);
2198         if (!cmd) {
2199                 err = -ENOMEM;
2200                 goto failed;
2201         }
2202
2203         err = hci_send_cmd(hdev, HCI_OP_WRITE_AUTH_ENABLE, sizeof(val), &val);
2204         if (err < 0) {
2205                 mgmt_pending_remove(cmd);
2206                 goto failed;
2207         }
2208
2209 failed:
2210         hci_dev_unlock(hdev);
2211         return err;
2212 }
2213
2214 static int set_ssp(struct sock *sk, struct hci_dev *hdev, void *data, u16 len)
2215 {
2216         struct mgmt_mode *cp = data;
2217         struct mgmt_pending_cmd *cmd;
2218         u8 status;
2219         int err;
2220
2221         BT_DBG("request for %s", hdev->name);
2222
2223         status = mgmt_bredr_support(hdev);
2224         if (status)
2225                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SSP, status);
2226
2227         if (!lmp_ssp_capable(hdev))
2228                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SSP,
2229                                        MGMT_STATUS_NOT_SUPPORTED);
2230
2231         if (cp->val != 0x00 && cp->val != 0x01)
2232                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SSP,
2233                                        MGMT_STATUS_INVALID_PARAMS);
2234
2235         hci_dev_lock(hdev);
2236
2237         if (!hdev_is_powered(hdev)) {
2238                 bool changed;
2239
2240                 if (cp->val) {
2241                         changed = !hci_dev_test_and_set_flag(hdev,
2242                                                              HCI_SSP_ENABLED);
2243                 } else {
2244                         changed = hci_dev_test_and_clear_flag(hdev,
2245                                                               HCI_SSP_ENABLED);
2246                         if (!changed)
2247                                 changed = hci_dev_test_and_clear_flag(hdev,
2248                                                                       HCI_HS_ENABLED);
2249                         else
2250                                 hci_dev_clear_flag(hdev, HCI_HS_ENABLED);
2251                 }
2252
2253                 err = send_settings_rsp(sk, MGMT_OP_SET_SSP, hdev);
2254                 if (err < 0)
2255                         goto failed;
2256
2257                 if (changed)
2258                         err = new_settings(hdev, sk);
2259
2260                 goto failed;
2261         }
2262
2263         if (pending_find(MGMT_OP_SET_SSP, hdev)) {
2264                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SSP,
2265                                       MGMT_STATUS_BUSY);
2266                 goto failed;
2267         }
2268
2269         if (!!cp->val == hci_dev_test_flag(hdev, HCI_SSP_ENABLED)) {
2270                 err = send_settings_rsp(sk, MGMT_OP_SET_SSP, hdev);
2271                 goto failed;
2272         }
2273
2274         cmd = mgmt_pending_add(sk, MGMT_OP_SET_SSP, hdev, data, len);
2275         if (!cmd) {
2276                 err = -ENOMEM;
2277                 goto failed;
2278         }
2279
2280         if (!cp->val && hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS))
2281                 hci_send_cmd(hdev, HCI_OP_WRITE_SSP_DEBUG_MODE,
2282                              sizeof(cp->val), &cp->val);
2283
2284         err = hci_send_cmd(hdev, HCI_OP_WRITE_SSP_MODE, 1, &cp->val);
2285         if (err < 0) {
2286                 mgmt_pending_remove(cmd);
2287                 goto failed;
2288         }
2289
2290 failed:
2291         hci_dev_unlock(hdev);
2292         return err;
2293 }
2294
2295 static int set_hs(struct sock *sk, struct hci_dev *hdev, void *data, u16 len)
2296 {
2297         struct mgmt_mode *cp = data;
2298         bool changed;
2299         u8 status;
2300         int err;
2301
2302         BT_DBG("request for %s", hdev->name);
2303
2304         status = mgmt_bredr_support(hdev);
2305         if (status)
2306                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_HS, status);
2307
2308         if (!lmp_ssp_capable(hdev))
2309                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_HS,
2310                                        MGMT_STATUS_NOT_SUPPORTED);
2311
2312         if (!hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
2313                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_HS,
2314                                        MGMT_STATUS_REJECTED);
2315
2316         if (cp->val != 0x00 && cp->val != 0x01)
2317                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_HS,
2318                                        MGMT_STATUS_INVALID_PARAMS);
2319
2320         hci_dev_lock(hdev);
2321
2322         if (pending_find(MGMT_OP_SET_SSP, hdev)) {
2323                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_HS,
2324                                       MGMT_STATUS_BUSY);
2325                 goto unlock;
2326         }
2327
2328         if (cp->val) {
2329                 changed = !hci_dev_test_and_set_flag(hdev, HCI_HS_ENABLED);
2330         } else {
2331                 if (hdev_is_powered(hdev)) {
2332                         err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_HS,
2333                                               MGMT_STATUS_REJECTED);
2334                         goto unlock;
2335                 }
2336
2337                 changed = hci_dev_test_and_clear_flag(hdev, HCI_HS_ENABLED);
2338         }
2339
2340         err = send_settings_rsp(sk, MGMT_OP_SET_HS, hdev);
2341         if (err < 0)
2342                 goto unlock;
2343
2344         if (changed)
2345                 err = new_settings(hdev, sk);
2346
2347 unlock:
2348         hci_dev_unlock(hdev);
2349         return err;
2350 }
2351
2352 static void le_enable_complete(struct hci_dev *hdev, u8 status, u16 opcode)
2353 {
2354         struct cmd_lookup match = { NULL, hdev };
2355
2356         hci_dev_lock(hdev);
2357
2358         if (status) {
2359                 u8 mgmt_err = mgmt_status(status);
2360
2361                 mgmt_pending_foreach(MGMT_OP_SET_LE, hdev, cmd_status_rsp,
2362                                      &mgmt_err);
2363                 goto unlock;
2364         }
2365
2366         mgmt_pending_foreach(MGMT_OP_SET_LE, hdev, settings_rsp, &match);
2367
2368         new_settings(hdev, match.sk);
2369
2370         if (match.sk)
2371                 sock_put(match.sk);
2372
2373         /* Make sure the controller has a good default for
2374          * advertising data. Restrict the update to when LE
2375          * has actually been enabled. During power on, the
2376          * update in powered_update_hci will take care of it.
2377          */
2378         if (hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
2379                 struct hci_request req;
2380
2381                 hci_req_init(&req, hdev);
2382                 update_adv_data(&req);
2383                 update_scan_rsp_data(&req);
2384                 __hci_update_background_scan(&req);
2385                 hci_req_run(&req, NULL);
2386         }
2387
2388 unlock:
2389         hci_dev_unlock(hdev);
2390 }
2391
2392 static int set_le(struct sock *sk, struct hci_dev *hdev, void *data, u16 len)
2393 {
2394         struct mgmt_mode *cp = data;
2395         struct hci_cp_write_le_host_supported hci_cp;
2396         struct mgmt_pending_cmd *cmd;
2397         struct hci_request req;
2398         int err;
2399         u8 val, enabled;
2400
2401         BT_DBG("request for %s", hdev->name);
2402
2403         if (!lmp_le_capable(hdev))
2404                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LE,
2405                                        MGMT_STATUS_NOT_SUPPORTED);
2406
2407         if (cp->val != 0x00 && cp->val != 0x01)
2408                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LE,
2409                                        MGMT_STATUS_INVALID_PARAMS);
2410
2411         /* Bluetooth single mode LE only controllers or dual-mode
2412          * controllers configured as LE only devices, do not allow
2413          * switching LE off. These have either LE enabled explicitly
2414          * or BR/EDR has been previously switched off.
2415          *
2416          * When trying to enable an already enabled LE, then gracefully
2417          * send a positive response. Trying to disable it however will
2418          * result into rejection.
2419          */
2420         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
2421                 if (cp->val == 0x01)
2422                         return send_settings_rsp(sk, MGMT_OP_SET_LE, hdev);
2423
2424                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LE,
2425                                        MGMT_STATUS_REJECTED);
2426         }
2427
2428         hci_dev_lock(hdev);
2429
2430         val = !!cp->val;
2431         enabled = lmp_host_le_capable(hdev);
2432
2433         if (!hdev_is_powered(hdev) || val == enabled) {
2434                 bool changed = false;
2435
2436                 if (val != hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
2437                         hci_dev_change_flag(hdev, HCI_LE_ENABLED);
2438                         changed = true;
2439                 }
2440
2441                 if (!val && hci_dev_test_flag(hdev, HCI_ADVERTISING)) {
2442                         hci_dev_clear_flag(hdev, HCI_ADVERTISING);
2443                         changed = true;
2444                 }
2445
2446                 err = send_settings_rsp(sk, MGMT_OP_SET_LE, hdev);
2447                 if (err < 0)
2448                         goto unlock;
2449
2450                 if (changed)
2451                         err = new_settings(hdev, sk);
2452
2453                 goto unlock;
2454         }
2455
2456         if (pending_find(MGMT_OP_SET_LE, hdev) ||
2457             pending_find(MGMT_OP_SET_ADVERTISING, hdev)) {
2458                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_LE,
2459                                       MGMT_STATUS_BUSY);
2460                 goto unlock;
2461         }
2462
2463         cmd = mgmt_pending_add(sk, MGMT_OP_SET_LE, hdev, data, len);
2464         if (!cmd) {
2465                 err = -ENOMEM;
2466                 goto unlock;
2467         }
2468
2469         hci_req_init(&req, hdev);
2470
2471         memset(&hci_cp, 0, sizeof(hci_cp));
2472
2473         if (val) {
2474                 hci_cp.le = val;
2475                 hci_cp.simul = 0x00;
2476         } else {
2477                 if (hci_dev_test_flag(hdev, HCI_LE_ADV))
2478                         disable_advertising(&req);
2479         }
2480
2481         hci_req_add(&req, HCI_OP_WRITE_LE_HOST_SUPPORTED, sizeof(hci_cp),
2482                     &hci_cp);
2483
2484         err = hci_req_run(&req, le_enable_complete);
2485         if (err < 0)
2486                 mgmt_pending_remove(cmd);
2487
2488 unlock:
2489         hci_dev_unlock(hdev);
2490         return err;
2491 }
2492
2493 /* This is a helper function to test for pending mgmt commands that can
2494  * cause CoD or EIR HCI commands. We can only allow one such pending
2495  * mgmt command at a time since otherwise we cannot easily track what
2496  * the current values are, will be, and based on that calculate if a new
2497  * HCI command needs to be sent and if yes with what value.
2498  */
2499 static bool pending_eir_or_class(struct hci_dev *hdev)
2500 {
2501         struct mgmt_pending_cmd *cmd;
2502
2503         list_for_each_entry(cmd, &hdev->mgmt_pending, list) {
2504                 switch (cmd->opcode) {
2505                 case MGMT_OP_ADD_UUID:
2506                 case MGMT_OP_REMOVE_UUID:
2507                 case MGMT_OP_SET_DEV_CLASS:
2508                 case MGMT_OP_SET_POWERED:
2509                         return true;
2510                 }
2511         }
2512
2513         return false;
2514 }
2515
2516 static const u8 bluetooth_base_uuid[] = {
2517                         0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80,
2518                         0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2519 };
2520
2521 static u8 get_uuid_size(const u8 *uuid)
2522 {
2523         u32 val;
2524
2525         if (memcmp(uuid, bluetooth_base_uuid, 12))
2526                 return 128;
2527
2528         val = get_unaligned_le32(&uuid[12]);
2529         if (val > 0xffff)
2530                 return 32;
2531
2532         return 16;
2533 }
2534
2535 static void mgmt_class_complete(struct hci_dev *hdev, u16 mgmt_op, u8 status)
2536 {
2537         struct mgmt_pending_cmd *cmd;
2538
2539         hci_dev_lock(hdev);
2540
2541         cmd = pending_find(mgmt_op, hdev);
2542         if (!cmd)
2543                 goto unlock;
2544
2545         mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode,
2546                           mgmt_status(status), hdev->dev_class, 3);
2547
2548         mgmt_pending_remove(cmd);
2549
2550 unlock:
2551         hci_dev_unlock(hdev);
2552 }
2553
2554 static void add_uuid_complete(struct hci_dev *hdev, u8 status, u16 opcode)
2555 {
2556         BT_DBG("status 0x%02x", status);
2557
2558         mgmt_class_complete(hdev, MGMT_OP_ADD_UUID, status);
2559 }
2560
2561 static int add_uuid(struct sock *sk, struct hci_dev *hdev, void *data, u16 len)
2562 {
2563         struct mgmt_cp_add_uuid *cp = data;
2564         struct mgmt_pending_cmd *cmd;
2565         struct hci_request req;
2566         struct bt_uuid *uuid;
2567         int err;
2568
2569         BT_DBG("request for %s", hdev->name);
2570
2571         hci_dev_lock(hdev);
2572
2573         if (pending_eir_or_class(hdev)) {
2574                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_UUID,
2575                                       MGMT_STATUS_BUSY);
2576                 goto failed;
2577         }
2578
2579         uuid = kmalloc(sizeof(*uuid), GFP_KERNEL);
2580         if (!uuid) {
2581                 err = -ENOMEM;
2582                 goto failed;
2583         }
2584
2585         memcpy(uuid->uuid, cp->uuid, 16);
2586         uuid->svc_hint = cp->svc_hint;
2587         uuid->size = get_uuid_size(cp->uuid);
2588
2589         list_add_tail(&uuid->list, &hdev->uuids);
2590
2591         hci_req_init(&req, hdev);
2592
2593         update_class(&req);
2594         update_eir(&req);
2595
2596         err = hci_req_run(&req, add_uuid_complete);
2597         if (err < 0) {
2598                 if (err != -ENODATA)
2599                         goto failed;
2600
2601                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_ADD_UUID, 0,
2602                                         hdev->dev_class, 3);
2603                 goto failed;
2604         }
2605
2606         cmd = mgmt_pending_add(sk, MGMT_OP_ADD_UUID, hdev, data, len);
2607         if (!cmd) {
2608                 err = -ENOMEM;
2609                 goto failed;
2610         }
2611
2612         err = 0;
2613
2614 failed:
2615         hci_dev_unlock(hdev);
2616         return err;
2617 }
2618
2619 static bool enable_service_cache(struct hci_dev *hdev)
2620 {
2621         if (!hdev_is_powered(hdev))
2622                 return false;
2623
2624         if (!hci_dev_test_and_set_flag(hdev, HCI_SERVICE_CACHE)) {
2625                 queue_delayed_work(hdev->workqueue, &hdev->service_cache,
2626                                    CACHE_TIMEOUT);
2627                 return true;
2628         }
2629
2630         return false;
2631 }
2632
2633 static void remove_uuid_complete(struct hci_dev *hdev, u8 status, u16 opcode)
2634 {
2635         BT_DBG("status 0x%02x", status);
2636
2637         mgmt_class_complete(hdev, MGMT_OP_REMOVE_UUID, status);
2638 }
2639
2640 static int remove_uuid(struct sock *sk, struct hci_dev *hdev, void *data,
2641                        u16 len)
2642 {
2643         struct mgmt_cp_remove_uuid *cp = data;
2644         struct mgmt_pending_cmd *cmd;
2645         struct bt_uuid *match, *tmp;
2646         u8 bt_uuid_any[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
2647         struct hci_request req;
2648         int err, found;
2649
2650         BT_DBG("request for %s", hdev->name);
2651
2652         hci_dev_lock(hdev);
2653
2654         if (pending_eir_or_class(hdev)) {
2655                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_REMOVE_UUID,
2656                                       MGMT_STATUS_BUSY);
2657                 goto unlock;
2658         }
2659
2660         if (memcmp(cp->uuid, bt_uuid_any, 16) == 0) {
2661                 hci_uuids_clear(hdev);
2662
2663                 if (enable_service_cache(hdev)) {
2664                         err = mgmt_cmd_complete(sk, hdev->id,
2665                                                 MGMT_OP_REMOVE_UUID,
2666                                                 0, hdev->dev_class, 3);
2667                         goto unlock;
2668                 }
2669
2670                 goto update_class;
2671         }
2672
2673         found = 0;
2674
2675         list_for_each_entry_safe(match, tmp, &hdev->uuids, list) {
2676                 if (memcmp(match->uuid, cp->uuid, 16) != 0)
2677                         continue;
2678
2679                 list_del(&match->list);
2680                 kfree(match);
2681                 found++;
2682         }
2683
2684         if (found == 0) {
2685                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_REMOVE_UUID,
2686                                       MGMT_STATUS_INVALID_PARAMS);
2687                 goto unlock;
2688         }
2689
2690 update_class:
2691         hci_req_init(&req, hdev);
2692
2693         update_class(&req);
2694         update_eir(&req);
2695
2696         err = hci_req_run(&req, remove_uuid_complete);
2697         if (err < 0) {
2698                 if (err != -ENODATA)
2699                         goto unlock;
2700
2701                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_REMOVE_UUID, 0,
2702                                         hdev->dev_class, 3);
2703                 goto unlock;
2704         }
2705
2706         cmd = mgmt_pending_add(sk, MGMT_OP_REMOVE_UUID, hdev, data, len);
2707         if (!cmd) {
2708                 err = -ENOMEM;
2709                 goto unlock;
2710         }
2711
2712         err = 0;
2713
2714 unlock:
2715         hci_dev_unlock(hdev);
2716         return err;
2717 }
2718
2719 static void set_class_complete(struct hci_dev *hdev, u8 status, u16 opcode)
2720 {
2721         BT_DBG("status 0x%02x", status);
2722
2723         mgmt_class_complete(hdev, MGMT_OP_SET_DEV_CLASS, status);
2724 }
2725
2726 static int set_dev_class(struct sock *sk, struct hci_dev *hdev, void *data,
2727                          u16 len)
2728 {
2729         struct mgmt_cp_set_dev_class *cp = data;
2730         struct mgmt_pending_cmd *cmd;
2731         struct hci_request req;
2732         int err;
2733
2734         BT_DBG("request for %s", hdev->name);
2735
2736         if (!lmp_bredr_capable(hdev))
2737                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEV_CLASS,
2738                                        MGMT_STATUS_NOT_SUPPORTED);
2739
2740         hci_dev_lock(hdev);
2741
2742         if (pending_eir_or_class(hdev)) {
2743                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEV_CLASS,
2744                                       MGMT_STATUS_BUSY);
2745                 goto unlock;
2746         }
2747
2748         if ((cp->minor & 0x03) != 0 || (cp->major & 0xe0) != 0) {
2749                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEV_CLASS,
2750                                       MGMT_STATUS_INVALID_PARAMS);
2751                 goto unlock;
2752         }
2753
2754         hdev->major_class = cp->major;
2755         hdev->minor_class = cp->minor;
2756
2757         if (!hdev_is_powered(hdev)) {
2758                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_DEV_CLASS, 0,
2759                                         hdev->dev_class, 3);
2760                 goto unlock;
2761         }
2762
2763         hci_req_init(&req, hdev);
2764
2765         if (hci_dev_test_and_clear_flag(hdev, HCI_SERVICE_CACHE)) {
2766                 hci_dev_unlock(hdev);
2767                 cancel_delayed_work_sync(&hdev->service_cache);
2768                 hci_dev_lock(hdev);
2769                 update_eir(&req);
2770         }
2771
2772         update_class(&req);
2773
2774         err = hci_req_run(&req, set_class_complete);
2775         if (err < 0) {
2776                 if (err != -ENODATA)
2777                         goto unlock;
2778
2779                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_DEV_CLASS, 0,
2780                                         hdev->dev_class, 3);
2781                 goto unlock;
2782         }
2783
2784         cmd = mgmt_pending_add(sk, MGMT_OP_SET_DEV_CLASS, hdev, data, len);
2785         if (!cmd) {
2786                 err = -ENOMEM;
2787                 goto unlock;
2788         }
2789
2790         err = 0;
2791
2792 unlock:
2793         hci_dev_unlock(hdev);
2794         return err;
2795 }
2796
2797 static int load_link_keys(struct sock *sk, struct hci_dev *hdev, void *data,
2798                           u16 len)
2799 {
2800         struct mgmt_cp_load_link_keys *cp = data;
2801         const u16 max_key_count = ((U16_MAX - sizeof(*cp)) /
2802                                    sizeof(struct mgmt_link_key_info));
2803         u16 key_count, expected_len;
2804         bool changed;
2805         int i;
2806
2807         BT_DBG("request for %s", hdev->name);
2808
2809         if (!lmp_bredr_capable(hdev))
2810                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LINK_KEYS,
2811                                        MGMT_STATUS_NOT_SUPPORTED);
2812
2813         key_count = __le16_to_cpu(cp->key_count);
2814         if (key_count > max_key_count) {
2815                 BT_ERR("load_link_keys: too big key_count value %u",
2816                        key_count);
2817                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LINK_KEYS,
2818                                        MGMT_STATUS_INVALID_PARAMS);
2819         }
2820
2821         expected_len = sizeof(*cp) + key_count *
2822                                         sizeof(struct mgmt_link_key_info);
2823         if (expected_len != len) {
2824                 BT_ERR("load_link_keys: expected %u bytes, got %u bytes",
2825                        expected_len, len);
2826                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LINK_KEYS,
2827                                        MGMT_STATUS_INVALID_PARAMS);
2828         }
2829
2830         if (cp->debug_keys != 0x00 && cp->debug_keys != 0x01)
2831                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LINK_KEYS,
2832                                        MGMT_STATUS_INVALID_PARAMS);
2833
2834         BT_DBG("%s debug_keys %u key_count %u", hdev->name, cp->debug_keys,
2835                key_count);
2836
2837         for (i = 0; i < key_count; i++) {
2838                 struct mgmt_link_key_info *key = &cp->keys[i];
2839
2840                 if (key->addr.type != BDADDR_BREDR || key->type > 0x08)
2841                         return mgmt_cmd_status(sk, hdev->id,
2842                                                MGMT_OP_LOAD_LINK_KEYS,
2843                                                MGMT_STATUS_INVALID_PARAMS);
2844         }
2845
2846         hci_dev_lock(hdev);
2847
2848         hci_link_keys_clear(hdev);
2849
2850         if (cp->debug_keys)
2851                 changed = !hci_dev_test_and_set_flag(hdev, HCI_KEEP_DEBUG_KEYS);
2852         else
2853                 changed = hci_dev_test_and_clear_flag(hdev,
2854                                                       HCI_KEEP_DEBUG_KEYS);
2855
2856         if (changed)
2857                 new_settings(hdev, NULL);
2858
2859         for (i = 0; i < key_count; i++) {
2860                 struct mgmt_link_key_info *key = &cp->keys[i];
2861
2862                 /* Always ignore debug keys and require a new pairing if
2863                  * the user wants to use them.
2864                  */
2865                 if (key->type == HCI_LK_DEBUG_COMBINATION)
2866                         continue;
2867
2868                 hci_add_link_key(hdev, NULL, &key->addr.bdaddr, key->val,
2869                                  key->type, key->pin_len, NULL);
2870         }
2871
2872         mgmt_cmd_complete(sk, hdev->id, MGMT_OP_LOAD_LINK_KEYS, 0, NULL, 0);
2873
2874         hci_dev_unlock(hdev);
2875
2876         return 0;
2877 }
2878
2879 static int device_unpaired(struct hci_dev *hdev, bdaddr_t *bdaddr,
2880                            u8 addr_type, struct sock *skip_sk)
2881 {
2882         struct mgmt_ev_device_unpaired ev;
2883
2884         bacpy(&ev.addr.bdaddr, bdaddr);
2885         ev.addr.type = addr_type;
2886
2887         return mgmt_event(MGMT_EV_DEVICE_UNPAIRED, hdev, &ev, sizeof(ev),
2888                           skip_sk);
2889 }
2890
2891 static int unpair_device(struct sock *sk, struct hci_dev *hdev, void *data,
2892                          u16 len)
2893 {
2894         struct mgmt_cp_unpair_device *cp = data;
2895         struct mgmt_rp_unpair_device rp;
2896         struct hci_cp_disconnect dc;
2897         struct mgmt_pending_cmd *cmd;
2898         struct hci_conn *conn;
2899         int err;
2900
2901         memset(&rp, 0, sizeof(rp));
2902         bacpy(&rp.addr.bdaddr, &cp->addr.bdaddr);
2903         rp.addr.type = cp->addr.type;
2904
2905         if (!bdaddr_type_is_valid(cp->addr.type))
2906                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNPAIR_DEVICE,
2907                                          MGMT_STATUS_INVALID_PARAMS,
2908                                          &rp, sizeof(rp));
2909
2910         if (cp->disconnect != 0x00 && cp->disconnect != 0x01)
2911                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNPAIR_DEVICE,
2912                                          MGMT_STATUS_INVALID_PARAMS,
2913                                          &rp, sizeof(rp));
2914
2915         hci_dev_lock(hdev);
2916
2917         if (!hdev_is_powered(hdev)) {
2918                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNPAIR_DEVICE,
2919                                         MGMT_STATUS_NOT_POWERED, &rp,
2920                                         sizeof(rp));
2921                 goto unlock;
2922         }
2923
2924         if (cp->addr.type == BDADDR_BREDR) {
2925                 /* If disconnection is requested, then look up the
2926                  * connection. If the remote device is connected, it
2927                  * will be later used to terminate the link.
2928                  *
2929                  * Setting it to NULL explicitly will cause no
2930                  * termination of the link.
2931                  */
2932                 if (cp->disconnect)
2933                         conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK,
2934                                                        &cp->addr.bdaddr);
2935                 else
2936                         conn = NULL;
2937
2938                 err = hci_remove_link_key(hdev, &cp->addr.bdaddr);
2939         } else {
2940                 u8 addr_type;
2941
2942                 conn = hci_conn_hash_lookup_ba(hdev, LE_LINK,
2943                                                &cp->addr.bdaddr);
2944                 if (conn) {
2945                         /* Defer clearing up the connection parameters
2946                          * until closing to give a chance of keeping
2947                          * them if a repairing happens.
2948                          */
2949                         set_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags);
2950
2951                         /* If disconnection is not requested, then
2952                          * clear the connection variable so that the
2953                          * link is not terminated.
2954                          */
2955                         if (!cp->disconnect)
2956                                 conn = NULL;
2957                 }
2958
2959                 if (cp->addr.type == BDADDR_LE_PUBLIC)
2960                         addr_type = ADDR_LE_DEV_PUBLIC;
2961                 else
2962                         addr_type = ADDR_LE_DEV_RANDOM;
2963
2964                 hci_remove_irk(hdev, &cp->addr.bdaddr, addr_type);
2965
2966                 err = hci_remove_ltk(hdev, &cp->addr.bdaddr, addr_type);
2967         }
2968
2969         if (err < 0) {
2970                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNPAIR_DEVICE,
2971                                         MGMT_STATUS_NOT_PAIRED, &rp,
2972                                         sizeof(rp));
2973                 goto unlock;
2974         }
2975
2976         /* If the connection variable is set, then termination of the
2977          * link is requested.
2978          */
2979         if (!conn) {
2980                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNPAIR_DEVICE, 0,
2981                                         &rp, sizeof(rp));
2982                 device_unpaired(hdev, &cp->addr.bdaddr, cp->addr.type, sk);
2983                 goto unlock;
2984         }
2985
2986         cmd = mgmt_pending_add(sk, MGMT_OP_UNPAIR_DEVICE, hdev, cp,
2987                                sizeof(*cp));
2988         if (!cmd) {
2989                 err = -ENOMEM;
2990                 goto unlock;
2991         }
2992
2993         cmd->cmd_complete = addr_cmd_complete;
2994
2995         dc.handle = cpu_to_le16(conn->handle);
2996         dc.reason = 0x13; /* Remote User Terminated Connection */
2997         err = hci_send_cmd(hdev, HCI_OP_DISCONNECT, sizeof(dc), &dc);
2998         if (err < 0)
2999                 mgmt_pending_remove(cmd);
3000
3001 unlock:
3002         hci_dev_unlock(hdev);
3003         return err;
3004 }
3005
3006 static int disconnect(struct sock *sk, struct hci_dev *hdev, void *data,
3007                       u16 len)
3008 {
3009         struct mgmt_cp_disconnect *cp = data;
3010         struct mgmt_rp_disconnect rp;
3011         struct mgmt_pending_cmd *cmd;
3012         struct hci_conn *conn;
3013         int err;
3014
3015         BT_DBG("");
3016
3017         memset(&rp, 0, sizeof(rp));
3018         bacpy(&rp.addr.bdaddr, &cp->addr.bdaddr);
3019         rp.addr.type = cp->addr.type;
3020
3021         if (!bdaddr_type_is_valid(cp->addr.type))
3022                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_DISCONNECT,
3023                                          MGMT_STATUS_INVALID_PARAMS,
3024                                          &rp, sizeof(rp));
3025
3026         hci_dev_lock(hdev);
3027
3028         if (!test_bit(HCI_UP, &hdev->flags)) {
3029                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_DISCONNECT,
3030                                         MGMT_STATUS_NOT_POWERED, &rp,
3031                                         sizeof(rp));
3032                 goto failed;
3033         }
3034
3035         if (pending_find(MGMT_OP_DISCONNECT, hdev)) {
3036                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_DISCONNECT,
3037                                         MGMT_STATUS_BUSY, &rp, sizeof(rp));
3038                 goto failed;
3039         }
3040
3041         if (cp->addr.type == BDADDR_BREDR)
3042                 conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK,
3043                                                &cp->addr.bdaddr);
3044         else
3045                 conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->addr.bdaddr);
3046
3047         if (!conn || conn->state == BT_OPEN || conn->state == BT_CLOSED) {
3048                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_DISCONNECT,
3049                                         MGMT_STATUS_NOT_CONNECTED, &rp,
3050                                         sizeof(rp));
3051                 goto failed;
3052         }
3053
3054         cmd = mgmt_pending_add(sk, MGMT_OP_DISCONNECT, hdev, data, len);
3055         if (!cmd) {
3056                 err = -ENOMEM;
3057                 goto failed;
3058         }
3059
3060         cmd->cmd_complete = generic_cmd_complete;
3061
3062         err = hci_disconnect(conn, HCI_ERROR_REMOTE_USER_TERM);
3063         if (err < 0)
3064                 mgmt_pending_remove(cmd);
3065
3066 failed:
3067         hci_dev_unlock(hdev);
3068         return err;
3069 }
3070
3071 static u8 link_to_bdaddr(u8 link_type, u8 addr_type)
3072 {
3073         switch (link_type) {
3074         case LE_LINK:
3075                 switch (addr_type) {
3076                 case ADDR_LE_DEV_PUBLIC:
3077                         return BDADDR_LE_PUBLIC;
3078
3079                 default:
3080                         /* Fallback to LE Random address type */
3081                         return BDADDR_LE_RANDOM;
3082                 }
3083
3084         default:
3085                 /* Fallback to BR/EDR type */
3086                 return BDADDR_BREDR;
3087         }
3088 }
3089
3090 static int get_connections(struct sock *sk, struct hci_dev *hdev, void *data,
3091                            u16 data_len)
3092 {
3093         struct mgmt_rp_get_connections *rp;
3094         struct hci_conn *c;
3095         size_t rp_len;
3096         int err;
3097         u16 i;
3098
3099         BT_DBG("");
3100
3101         hci_dev_lock(hdev);
3102
3103         if (!hdev_is_powered(hdev)) {
3104                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_GET_CONNECTIONS,
3105                                       MGMT_STATUS_NOT_POWERED);
3106                 goto unlock;
3107         }
3108
3109         i = 0;
3110         list_for_each_entry(c, &hdev->conn_hash.list, list) {
3111                 if (test_bit(HCI_CONN_MGMT_CONNECTED, &c->flags))
3112                         i++;
3113         }
3114
3115         rp_len = sizeof(*rp) + (i * sizeof(struct mgmt_addr_info));
3116         rp = kmalloc(rp_len, GFP_KERNEL);
3117         if (!rp) {
3118                 err = -ENOMEM;
3119                 goto unlock;
3120         }
3121
3122         i = 0;
3123         list_for_each_entry(c, &hdev->conn_hash.list, list) {
3124                 if (!test_bit(HCI_CONN_MGMT_CONNECTED, &c->flags))
3125                         continue;
3126                 bacpy(&rp->addr[i].bdaddr, &c->dst);
3127                 rp->addr[i].type = link_to_bdaddr(c->type, c->dst_type);
3128                 if (c->type == SCO_LINK || c->type == ESCO_LINK)
3129                         continue;
3130                 i++;
3131         }
3132
3133         rp->conn_count = cpu_to_le16(i);
3134
3135         /* Recalculate length in case of filtered SCO connections, etc */
3136         rp_len = sizeof(*rp) + (i * sizeof(struct mgmt_addr_info));
3137
3138         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CONNECTIONS, 0, rp,
3139                                 rp_len);
3140
3141         kfree(rp);
3142
3143 unlock:
3144         hci_dev_unlock(hdev);
3145         return err;
3146 }
3147
3148 static int send_pin_code_neg_reply(struct sock *sk, struct hci_dev *hdev,
3149                                    struct mgmt_cp_pin_code_neg_reply *cp)
3150 {
3151         struct mgmt_pending_cmd *cmd;
3152         int err;
3153
3154         cmd = mgmt_pending_add(sk, MGMT_OP_PIN_CODE_NEG_REPLY, hdev, cp,
3155                                sizeof(*cp));
3156         if (!cmd)
3157                 return -ENOMEM;
3158
3159         err = hci_send_cmd(hdev, HCI_OP_PIN_CODE_NEG_REPLY,
3160                            sizeof(cp->addr.bdaddr), &cp->addr.bdaddr);
3161         if (err < 0)
3162                 mgmt_pending_remove(cmd);
3163
3164         return err;
3165 }
3166
3167 static int pin_code_reply(struct sock *sk, struct hci_dev *hdev, void *data,
3168                           u16 len)
3169 {
3170         struct hci_conn *conn;
3171         struct mgmt_cp_pin_code_reply *cp = data;
3172         struct hci_cp_pin_code_reply reply;
3173         struct mgmt_pending_cmd *cmd;
3174         int err;
3175
3176         BT_DBG("");
3177
3178         hci_dev_lock(hdev);
3179
3180         if (!hdev_is_powered(hdev)) {
3181                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_PIN_CODE_REPLY,
3182                                       MGMT_STATUS_NOT_POWERED);
3183                 goto failed;
3184         }
3185
3186         conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &cp->addr.bdaddr);
3187         if (!conn) {
3188                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_PIN_CODE_REPLY,
3189                                       MGMT_STATUS_NOT_CONNECTED);
3190                 goto failed;
3191         }
3192
3193         if (conn->pending_sec_level == BT_SECURITY_HIGH && cp->pin_len != 16) {
3194                 struct mgmt_cp_pin_code_neg_reply ncp;
3195
3196                 memcpy(&ncp.addr, &cp->addr, sizeof(ncp.addr));
3197
3198                 BT_ERR("PIN code is not 16 bytes long");
3199
3200                 err = send_pin_code_neg_reply(sk, hdev, &ncp);
3201                 if (err >= 0)
3202                         err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_PIN_CODE_REPLY,
3203                                               MGMT_STATUS_INVALID_PARAMS);
3204
3205                 goto failed;
3206         }
3207
3208         cmd = mgmt_pending_add(sk, MGMT_OP_PIN_CODE_REPLY, hdev, data, len);
3209         if (!cmd) {
3210                 err = -ENOMEM;
3211                 goto failed;
3212         }
3213
3214         cmd->cmd_complete = addr_cmd_complete;
3215
3216         bacpy(&reply.bdaddr, &cp->addr.bdaddr);
3217         reply.pin_len = cp->pin_len;
3218         memcpy(reply.pin_code, cp->pin_code, sizeof(reply.pin_code));
3219
3220         err = hci_send_cmd(hdev, HCI_OP_PIN_CODE_REPLY, sizeof(reply), &reply);
3221         if (err < 0)
3222                 mgmt_pending_remove(cmd);
3223
3224 failed:
3225         hci_dev_unlock(hdev);
3226         return err;
3227 }
3228
3229 static int set_io_capability(struct sock *sk, struct hci_dev *hdev, void *data,
3230                              u16 len)
3231 {
3232         struct mgmt_cp_set_io_capability *cp = data;
3233
3234         BT_DBG("");
3235
3236         if (cp->io_capability > SMP_IO_KEYBOARD_DISPLAY)
3237                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_IO_CAPABILITY,
3238                                          MGMT_STATUS_INVALID_PARAMS, NULL, 0);
3239
3240         hci_dev_lock(hdev);
3241
3242         hdev->io_capability = cp->io_capability;
3243
3244         BT_DBG("%s IO capability set to 0x%02x", hdev->name,
3245                hdev->io_capability);
3246
3247         hci_dev_unlock(hdev);
3248
3249         return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_IO_CAPABILITY, 0,
3250                                  NULL, 0);
3251 }
3252
3253 static struct mgmt_pending_cmd *find_pairing(struct hci_conn *conn)
3254 {
3255         struct hci_dev *hdev = conn->hdev;
3256         struct mgmt_pending_cmd *cmd;
3257
3258         list_for_each_entry(cmd, &hdev->mgmt_pending, list) {
3259                 if (cmd->opcode != MGMT_OP_PAIR_DEVICE)
3260                         continue;
3261
3262                 if (cmd->user_data != conn)
3263                         continue;
3264
3265                 return cmd;
3266         }
3267
3268         return NULL;
3269 }
3270
3271 static int pairing_complete(struct mgmt_pending_cmd *cmd, u8 status)
3272 {
3273         struct mgmt_rp_pair_device rp;
3274         struct hci_conn *conn = cmd->user_data;
3275         int err;
3276
3277         bacpy(&rp.addr.bdaddr, &conn->dst);
3278         rp.addr.type = link_to_bdaddr(conn->type, conn->dst_type);
3279
3280         err = mgmt_cmd_complete(cmd->sk, cmd->index, MGMT_OP_PAIR_DEVICE,
3281                                 status, &rp, sizeof(rp));
3282
3283         /* So we don't get further callbacks for this connection */
3284         conn->connect_cfm_cb = NULL;
3285         conn->security_cfm_cb = NULL;
3286         conn->disconn_cfm_cb = NULL;
3287
3288         hci_conn_drop(conn);
3289
3290         /* The device is paired so there is no need to remove
3291          * its connection parameters anymore.
3292          */
3293         clear_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags);
3294
3295         hci_conn_put(conn);
3296
3297         return err;
3298 }
3299
3300 void mgmt_smp_complete(struct hci_conn *conn, bool complete)
3301 {
3302         u8 status = complete ? MGMT_STATUS_SUCCESS : MGMT_STATUS_FAILED;
3303         struct mgmt_pending_cmd *cmd;
3304
3305         cmd = find_pairing(conn);
3306         if (cmd) {
3307                 cmd->cmd_complete(cmd, status);
3308                 mgmt_pending_remove(cmd);
3309         }
3310 }
3311
3312 static void pairing_complete_cb(struct hci_conn *conn, u8 status)
3313 {
3314         struct mgmt_pending_cmd *cmd;
3315
3316         BT_DBG("status %u", status);
3317
3318         cmd = find_pairing(conn);
3319         if (!cmd) {
3320                 BT_DBG("Unable to find a pending command");
3321                 return;
3322         }
3323
3324         cmd->cmd_complete(cmd, mgmt_status(status));
3325         mgmt_pending_remove(cmd);
3326 }
3327
3328 static void le_pairing_complete_cb(struct hci_conn *conn, u8 status)
3329 {
3330         struct mgmt_pending_cmd *cmd;
3331
3332         BT_DBG("status %u", status);
3333
3334         if (!status)
3335                 return;
3336
3337         cmd = find_pairing(conn);
3338         if (!cmd) {
3339                 BT_DBG("Unable to find a pending command");
3340                 return;
3341         }
3342
3343         cmd->cmd_complete(cmd, mgmt_status(status));
3344         mgmt_pending_remove(cmd);
3345 }
3346
3347 static int pair_device(struct sock *sk, struct hci_dev *hdev, void *data,
3348                        u16 len)
3349 {
3350         struct mgmt_cp_pair_device *cp = data;
3351         struct mgmt_rp_pair_device rp;
3352         struct mgmt_pending_cmd *cmd;
3353         u8 sec_level, auth_type;
3354         struct hci_conn *conn;
3355         int err;
3356
3357         BT_DBG("");
3358
3359         memset(&rp, 0, sizeof(rp));
3360         bacpy(&rp.addr.bdaddr, &cp->addr.bdaddr);
3361         rp.addr.type = cp->addr.type;
3362
3363         if (!bdaddr_type_is_valid(cp->addr.type))
3364                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_PAIR_DEVICE,
3365                                          MGMT_STATUS_INVALID_PARAMS,
3366                                          &rp, sizeof(rp));
3367
3368         if (cp->io_cap > SMP_IO_KEYBOARD_DISPLAY)
3369                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_PAIR_DEVICE,
3370                                          MGMT_STATUS_INVALID_PARAMS,
3371                                          &rp, sizeof(rp));
3372
3373         hci_dev_lock(hdev);
3374
3375         if (!hdev_is_powered(hdev)) {
3376                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_PAIR_DEVICE,
3377                                         MGMT_STATUS_NOT_POWERED, &rp,
3378                                         sizeof(rp));
3379                 goto unlock;
3380         }
3381
3382         if (hci_bdaddr_is_paired(hdev, &cp->addr.bdaddr, cp->addr.type)) {
3383                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_PAIR_DEVICE,
3384                                         MGMT_STATUS_ALREADY_PAIRED, &rp,
3385                                         sizeof(rp));
3386                 goto unlock;
3387         }
3388
3389         sec_level = BT_SECURITY_MEDIUM;
3390         auth_type = HCI_AT_DEDICATED_BONDING;
3391
3392         if (cp->addr.type == BDADDR_BREDR) {
3393                 conn = hci_connect_acl(hdev, &cp->addr.bdaddr, sec_level,
3394                                        auth_type);
3395         } else {
3396                 u8 addr_type;
3397
3398                 /* Convert from L2CAP channel address type to HCI address type
3399                  */
3400                 if (cp->addr.type == BDADDR_LE_PUBLIC)
3401                         addr_type = ADDR_LE_DEV_PUBLIC;
3402                 else
3403                         addr_type = ADDR_LE_DEV_RANDOM;
3404
3405                 /* When pairing a new device, it is expected to remember
3406                  * this device for future connections. Adding the connection
3407                  * parameter information ahead of time allows tracking
3408                  * of the slave preferred values and will speed up any
3409                  * further connection establishment.
3410                  *
3411                  * If connection parameters already exist, then they
3412                  * will be kept and this function does nothing.
3413                  */
3414                 hci_conn_params_add(hdev, &cp->addr.bdaddr, addr_type);
3415
3416                 conn = hci_connect_le(hdev, &cp->addr.bdaddr, addr_type,
3417                                       sec_level, HCI_LE_CONN_TIMEOUT,
3418                                       HCI_ROLE_MASTER);
3419         }
3420
3421         if (IS_ERR(conn)) {
3422                 int status;
3423
3424                 if (PTR_ERR(conn) == -EBUSY)
3425                         status = MGMT_STATUS_BUSY;
3426                 else if (PTR_ERR(conn) == -EOPNOTSUPP)
3427                         status = MGMT_STATUS_NOT_SUPPORTED;
3428                 else if (PTR_ERR(conn) == -ECONNREFUSED)
3429                         status = MGMT_STATUS_REJECTED;
3430                 else
3431                         status = MGMT_STATUS_CONNECT_FAILED;
3432
3433                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_PAIR_DEVICE,
3434                                         status, &rp, sizeof(rp));
3435                 goto unlock;
3436         }
3437
3438         if (conn->connect_cfm_cb) {
3439                 hci_conn_drop(conn);
3440                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_PAIR_DEVICE,
3441                                         MGMT_STATUS_BUSY, &rp, sizeof(rp));
3442                 goto unlock;
3443         }
3444
3445         cmd = mgmt_pending_add(sk, MGMT_OP_PAIR_DEVICE, hdev, data, len);
3446         if (!cmd) {
3447                 err = -ENOMEM;
3448                 hci_conn_drop(conn);
3449                 goto unlock;
3450         }
3451
3452         cmd->cmd_complete = pairing_complete;
3453
3454         /* For LE, just connecting isn't a proof that the pairing finished */
3455         if (cp->addr.type == BDADDR_BREDR) {
3456                 conn->connect_cfm_cb = pairing_complete_cb;
3457                 conn->security_cfm_cb = pairing_complete_cb;
3458                 conn->disconn_cfm_cb = pairing_complete_cb;
3459         } else {
3460                 conn->connect_cfm_cb = le_pairing_complete_cb;
3461                 conn->security_cfm_cb = le_pairing_complete_cb;
3462                 conn->disconn_cfm_cb = le_pairing_complete_cb;
3463         }
3464
3465         conn->io_capability = cp->io_cap;
3466         cmd->user_data = hci_conn_get(conn);
3467
3468         if ((conn->state == BT_CONNECTED || conn->state == BT_CONFIG) &&
3469             hci_conn_security(conn, sec_level, auth_type, true)) {
3470                 cmd->cmd_complete(cmd, 0);
3471                 mgmt_pending_remove(cmd);
3472         }
3473
3474         err = 0;
3475
3476 unlock:
3477         hci_dev_unlock(hdev);
3478         return err;
3479 }
3480
3481 static int cancel_pair_device(struct sock *sk, struct hci_dev *hdev, void *data,
3482                               u16 len)
3483 {
3484         struct mgmt_addr_info *addr = data;
3485         struct mgmt_pending_cmd *cmd;
3486         struct hci_conn *conn;
3487         int err;
3488
3489         BT_DBG("");
3490
3491         hci_dev_lock(hdev);
3492
3493         if (!hdev_is_powered(hdev)) {
3494                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_CANCEL_PAIR_DEVICE,
3495                                       MGMT_STATUS_NOT_POWERED);
3496                 goto unlock;
3497         }
3498
3499         cmd = pending_find(MGMT_OP_PAIR_DEVICE, hdev);
3500         if (!cmd) {
3501                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_CANCEL_PAIR_DEVICE,
3502                                       MGMT_STATUS_INVALID_PARAMS);
3503                 goto unlock;
3504         }
3505
3506         conn = cmd->user_data;
3507
3508         if (bacmp(&addr->bdaddr, &conn->dst) != 0) {
3509                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_CANCEL_PAIR_DEVICE,
3510                                       MGMT_STATUS_INVALID_PARAMS);
3511                 goto unlock;
3512         }
3513
3514         cmd->cmd_complete(cmd, MGMT_STATUS_CANCELLED);
3515         mgmt_pending_remove(cmd);
3516
3517         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_CANCEL_PAIR_DEVICE, 0,
3518                                 addr, sizeof(*addr));
3519 unlock:
3520         hci_dev_unlock(hdev);
3521         return err;
3522 }
3523
3524 static int user_pairing_resp(struct sock *sk, struct hci_dev *hdev,
3525                              struct mgmt_addr_info *addr, u16 mgmt_op,
3526                              u16 hci_op, __le32 passkey)
3527 {
3528         struct mgmt_pending_cmd *cmd;
3529         struct hci_conn *conn;
3530         int err;
3531
3532         hci_dev_lock(hdev);
3533
3534         if (!hdev_is_powered(hdev)) {
3535                 err = mgmt_cmd_complete(sk, hdev->id, mgmt_op,
3536                                         MGMT_STATUS_NOT_POWERED, addr,
3537                                         sizeof(*addr));
3538                 goto done;
3539         }
3540
3541         if (addr->type == BDADDR_BREDR)
3542                 conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &addr->bdaddr);
3543         else
3544                 conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &addr->bdaddr);
3545
3546         if (!conn) {
3547                 err = mgmt_cmd_complete(sk, hdev->id, mgmt_op,
3548                                         MGMT_STATUS_NOT_CONNECTED, addr,
3549                                         sizeof(*addr));
3550                 goto done;
3551         }
3552
3553         if (addr->type == BDADDR_LE_PUBLIC || addr->type == BDADDR_LE_RANDOM) {
3554                 err = smp_user_confirm_reply(conn, mgmt_op, passkey);
3555                 if (!err)
3556                         err = mgmt_cmd_complete(sk, hdev->id, mgmt_op,
3557                                                 MGMT_STATUS_SUCCESS, addr,
3558                                                 sizeof(*addr));
3559                 else
3560                         err = mgmt_cmd_complete(sk, hdev->id, mgmt_op,
3561                                                 MGMT_STATUS_FAILED, addr,
3562                                                 sizeof(*addr));
3563
3564                 goto done;
3565         }
3566
3567         cmd = mgmt_pending_add(sk, mgmt_op, hdev, addr, sizeof(*addr));
3568         if (!cmd) {
3569                 err = -ENOMEM;
3570                 goto done;
3571         }
3572
3573         cmd->cmd_complete = addr_cmd_complete;
3574
3575         /* Continue with pairing via HCI */
3576         if (hci_op == HCI_OP_USER_PASSKEY_REPLY) {
3577                 struct hci_cp_user_passkey_reply cp;
3578
3579                 bacpy(&cp.bdaddr, &addr->bdaddr);
3580                 cp.passkey = passkey;
3581                 err = hci_send_cmd(hdev, hci_op, sizeof(cp), &cp);
3582         } else
3583                 err = hci_send_cmd(hdev, hci_op, sizeof(addr->bdaddr),
3584                                    &addr->bdaddr);
3585
3586         if (err < 0)
3587                 mgmt_pending_remove(cmd);
3588
3589 done:
3590         hci_dev_unlock(hdev);
3591         return err;
3592 }
3593
3594 static int pin_code_neg_reply(struct sock *sk, struct hci_dev *hdev,
3595                               void *data, u16 len)
3596 {
3597         struct mgmt_cp_pin_code_neg_reply *cp = data;
3598
3599         BT_DBG("");
3600
3601         return user_pairing_resp(sk, hdev, &cp->addr,
3602                                 MGMT_OP_PIN_CODE_NEG_REPLY,
3603                                 HCI_OP_PIN_CODE_NEG_REPLY, 0);
3604 }
3605
3606 static int user_confirm_reply(struct sock *sk, struct hci_dev *hdev, void *data,
3607                               u16 len)
3608 {
3609         struct mgmt_cp_user_confirm_reply *cp = data;
3610
3611         BT_DBG("");
3612
3613         if (len != sizeof(*cp))
3614                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_USER_CONFIRM_REPLY,
3615                                        MGMT_STATUS_INVALID_PARAMS);
3616
3617         return user_pairing_resp(sk, hdev, &cp->addr,
3618                                  MGMT_OP_USER_CONFIRM_REPLY,
3619                                  HCI_OP_USER_CONFIRM_REPLY, 0);
3620 }
3621
3622 static int user_confirm_neg_reply(struct sock *sk, struct hci_dev *hdev,
3623                                   void *data, u16 len)
3624 {
3625         struct mgmt_cp_user_confirm_neg_reply *cp = data;
3626
3627         BT_DBG("");
3628
3629         return user_pairing_resp(sk, hdev, &cp->addr,
3630                                  MGMT_OP_USER_CONFIRM_NEG_REPLY,
3631                                  HCI_OP_USER_CONFIRM_NEG_REPLY, 0);
3632 }
3633
3634 static int user_passkey_reply(struct sock *sk, struct hci_dev *hdev, void *data,
3635                               u16 len)
3636 {
3637         struct mgmt_cp_user_passkey_reply *cp = data;
3638
3639         BT_DBG("");
3640
3641         return user_pairing_resp(sk, hdev, &cp->addr,
3642                                  MGMT_OP_USER_PASSKEY_REPLY,
3643                                  HCI_OP_USER_PASSKEY_REPLY, cp->passkey);
3644 }
3645
3646 static int user_passkey_neg_reply(struct sock *sk, struct hci_dev *hdev,
3647                                   void *data, u16 len)
3648 {
3649         struct mgmt_cp_user_passkey_neg_reply *cp = data;
3650
3651         BT_DBG("");
3652
3653         return user_pairing_resp(sk, hdev, &cp->addr,
3654                                  MGMT_OP_USER_PASSKEY_NEG_REPLY,
3655                                  HCI_OP_USER_PASSKEY_NEG_REPLY, 0);
3656 }
3657
3658 static void update_name(struct hci_request *req)
3659 {
3660         struct hci_dev *hdev = req->hdev;
3661         struct hci_cp_write_local_name cp;
3662
3663         memcpy(cp.name, hdev->dev_name, sizeof(cp.name));
3664
3665         hci_req_add(req, HCI_OP_WRITE_LOCAL_NAME, sizeof(cp), &cp);
3666 }
3667
3668 static void set_name_complete(struct hci_dev *hdev, u8 status, u16 opcode)
3669 {
3670         struct mgmt_cp_set_local_name *cp;
3671         struct mgmt_pending_cmd *cmd;
3672
3673         BT_DBG("status 0x%02x", status);
3674
3675         hci_dev_lock(hdev);
3676
3677         cmd = pending_find(MGMT_OP_SET_LOCAL_NAME, hdev);
3678         if (!cmd)
3679                 goto unlock;
3680
3681         cp = cmd->param;
3682
3683         if (status)
3684                 mgmt_cmd_status(cmd->sk, hdev->id, MGMT_OP_SET_LOCAL_NAME,
3685                                 mgmt_status(status));
3686         else
3687                 mgmt_cmd_complete(cmd->sk, hdev->id, MGMT_OP_SET_LOCAL_NAME, 0,
3688                                   cp, sizeof(*cp));
3689
3690         mgmt_pending_remove(cmd);
3691
3692 unlock:
3693         hci_dev_unlock(hdev);
3694 }
3695
3696 static int set_local_name(struct sock *sk, struct hci_dev *hdev, void *data,
3697                           u16 len)
3698 {
3699         struct mgmt_cp_set_local_name *cp = data;
3700         struct mgmt_pending_cmd *cmd;
3701         struct hci_request req;
3702         int err;
3703
3704         BT_DBG("");
3705
3706         hci_dev_lock(hdev);
3707
3708         /* If the old values are the same as the new ones just return a
3709          * direct command complete event.
3710          */
3711         if (!memcmp(hdev->dev_name, cp->name, sizeof(hdev->dev_name)) &&
3712             !memcmp(hdev->short_name, cp->short_name,
3713                     sizeof(hdev->short_name))) {
3714                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_LOCAL_NAME, 0,
3715                                         data, len);
3716                 goto failed;
3717         }
3718
3719         memcpy(hdev->short_name, cp->short_name, sizeof(hdev->short_name));
3720
3721         if (!hdev_is_powered(hdev)) {
3722                 memcpy(hdev->dev_name, cp->name, sizeof(hdev->dev_name));
3723
3724                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_LOCAL_NAME, 0,
3725                                         data, len);
3726                 if (err < 0)
3727                         goto failed;
3728
3729                 err = mgmt_generic_event(MGMT_EV_LOCAL_NAME_CHANGED, hdev,
3730                                          data, len, sk);
3731
3732                 goto failed;
3733         }
3734
3735         cmd = mgmt_pending_add(sk, MGMT_OP_SET_LOCAL_NAME, hdev, data, len);
3736         if (!cmd) {
3737                 err = -ENOMEM;
3738                 goto failed;
3739         }
3740
3741         memcpy(hdev->dev_name, cp->name, sizeof(hdev->dev_name));
3742
3743         hci_req_init(&req, hdev);
3744
3745         if (lmp_bredr_capable(hdev)) {
3746                 update_name(&req);
3747                 update_eir(&req);
3748         }
3749
3750         /* The name is stored in the scan response data and so
3751          * no need to udpate the advertising data here.
3752          */
3753         if (lmp_le_capable(hdev))
3754                 update_scan_rsp_data(&req);
3755
3756         err = hci_req_run(&req, set_name_complete);
3757         if (err < 0)
3758                 mgmt_pending_remove(cmd);
3759
3760 failed:
3761         hci_dev_unlock(hdev);
3762         return err;
3763 }
3764
3765 static int read_local_oob_data(struct sock *sk, struct hci_dev *hdev,
3766                                void *data, u16 data_len)
3767 {
3768         struct mgmt_pending_cmd *cmd;
3769         int err;
3770
3771         BT_DBG("%s", hdev->name);
3772
3773         hci_dev_lock(hdev);
3774
3775         if (!hdev_is_powered(hdev)) {
3776                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_READ_LOCAL_OOB_DATA,
3777                                       MGMT_STATUS_NOT_POWERED);
3778                 goto unlock;
3779         }
3780
3781         if (!lmp_ssp_capable(hdev)) {
3782                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_READ_LOCAL_OOB_DATA,
3783                                       MGMT_STATUS_NOT_SUPPORTED);
3784                 goto unlock;
3785         }
3786
3787         if (pending_find(MGMT_OP_READ_LOCAL_OOB_DATA, hdev)) {
3788                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_READ_LOCAL_OOB_DATA,
3789                                       MGMT_STATUS_BUSY);
3790                 goto unlock;
3791         }
3792
3793         cmd = mgmt_pending_add(sk, MGMT_OP_READ_LOCAL_OOB_DATA, hdev, NULL, 0);
3794         if (!cmd) {
3795                 err = -ENOMEM;
3796                 goto unlock;
3797         }
3798
3799         if (bredr_sc_enabled(hdev))
3800                 err = hci_send_cmd(hdev, HCI_OP_READ_LOCAL_OOB_EXT_DATA,
3801                                    0, NULL);
3802         else
3803                 err = hci_send_cmd(hdev, HCI_OP_READ_LOCAL_OOB_DATA, 0, NULL);
3804
3805         if (err < 0)
3806                 mgmt_pending_remove(cmd);
3807
3808 unlock:
3809         hci_dev_unlock(hdev);
3810         return err;
3811 }
3812
3813 static int add_remote_oob_data(struct sock *sk, struct hci_dev *hdev,
3814                                void *data, u16 len)
3815 {
3816         struct mgmt_addr_info *addr = data;
3817         int err;
3818
3819         BT_DBG("%s ", hdev->name);
3820
3821         if (!bdaddr_type_is_valid(addr->type))
3822                 return mgmt_cmd_complete(sk, hdev->id,
3823                                          MGMT_OP_ADD_REMOTE_OOB_DATA,
3824                                          MGMT_STATUS_INVALID_PARAMS,
3825                                          addr, sizeof(*addr));
3826
3827         hci_dev_lock(hdev);
3828
3829         if (len == MGMT_ADD_REMOTE_OOB_DATA_SIZE) {
3830                 struct mgmt_cp_add_remote_oob_data *cp = data;
3831                 u8 status;
3832
3833                 if (cp->addr.type != BDADDR_BREDR) {
3834                         err = mgmt_cmd_complete(sk, hdev->id,
3835                                                 MGMT_OP_ADD_REMOTE_OOB_DATA,
3836                                                 MGMT_STATUS_INVALID_PARAMS,
3837                                                 &cp->addr, sizeof(cp->addr));
3838                         goto unlock;
3839                 }
3840
3841                 err = hci_add_remote_oob_data(hdev, &cp->addr.bdaddr,
3842                                               cp->addr.type, cp->hash,
3843                                               cp->rand, NULL, NULL);
3844                 if (err < 0)
3845                         status = MGMT_STATUS_FAILED;
3846                 else
3847                         status = MGMT_STATUS_SUCCESS;
3848
3849                 err = mgmt_cmd_complete(sk, hdev->id,
3850                                         MGMT_OP_ADD_REMOTE_OOB_DATA, status,
3851                                         &cp->addr, sizeof(cp->addr));
3852         } else if (len == MGMT_ADD_REMOTE_OOB_EXT_DATA_SIZE) {
3853                 struct mgmt_cp_add_remote_oob_ext_data *cp = data;
3854                 u8 *rand192, *hash192, *rand256, *hash256;
3855                 u8 status;
3856
3857                 if (bdaddr_type_is_le(cp->addr.type)) {
3858                         /* Enforce zero-valued 192-bit parameters as
3859                          * long as legacy SMP OOB isn't implemented.
3860                          */
3861                         if (memcmp(cp->rand192, ZERO_KEY, 16) ||
3862                             memcmp(cp->hash192, ZERO_KEY, 16)) {
3863                                 err = mgmt_cmd_complete(sk, hdev->id,
3864                                                         MGMT_OP_ADD_REMOTE_OOB_DATA,
3865                                                         MGMT_STATUS_INVALID_PARAMS,
3866                                                         addr, sizeof(*addr));
3867                                 goto unlock;
3868                         }
3869
3870                         rand192 = NULL;
3871                         hash192 = NULL;
3872                 } else {
3873                         /* In case one of the P-192 values is set to zero,
3874                          * then just disable OOB data for P-192.
3875                          */
3876                         if (!memcmp(cp->rand192, ZERO_KEY, 16) ||
3877                             !memcmp(cp->hash192, ZERO_KEY, 16)) {
3878                                 rand192 = NULL;
3879                                 hash192 = NULL;
3880                         } else {
3881                                 rand192 = cp->rand192;
3882                                 hash192 = cp->hash192;
3883                         }
3884                 }
3885
3886                 /* In case one of the P-256 values is set to zero, then just
3887                  * disable OOB data for P-256.
3888                  */
3889                 if (!memcmp(cp->rand256, ZERO_KEY, 16) ||
3890                     !memcmp(cp->hash256, ZERO_KEY, 16)) {
3891                         rand256 = NULL;
3892                         hash256 = NULL;
3893                 } else {
3894                         rand256 = cp->rand256;
3895                         hash256 = cp->hash256;
3896                 }
3897
3898                 err = hci_add_remote_oob_data(hdev, &cp->addr.bdaddr,
3899                                               cp->addr.type, hash192, rand192,
3900                                               hash256, rand256);
3901                 if (err < 0)
3902                         status = MGMT_STATUS_FAILED;
3903                 else
3904                         status = MGMT_STATUS_SUCCESS;
3905
3906                 err = mgmt_cmd_complete(sk, hdev->id,
3907                                         MGMT_OP_ADD_REMOTE_OOB_DATA,
3908                                         status, &cp->addr, sizeof(cp->addr));
3909         } else {
3910                 BT_ERR("add_remote_oob_data: invalid length of %u bytes", len);
3911                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_REMOTE_OOB_DATA,
3912                                       MGMT_STATUS_INVALID_PARAMS);
3913         }
3914
3915 unlock:
3916         hci_dev_unlock(hdev);
3917         return err;
3918 }
3919
3920 static int remove_remote_oob_data(struct sock *sk, struct hci_dev *hdev,
3921                                   void *data, u16 len)
3922 {
3923         struct mgmt_cp_remove_remote_oob_data *cp = data;
3924         u8 status;
3925         int err;
3926
3927         BT_DBG("%s", hdev->name);
3928
3929         if (cp->addr.type != BDADDR_BREDR)
3930                 return mgmt_cmd_complete(sk, hdev->id,
3931                                          MGMT_OP_REMOVE_REMOTE_OOB_DATA,
3932                                          MGMT_STATUS_INVALID_PARAMS,
3933                                          &cp->addr, sizeof(cp->addr));
3934
3935         hci_dev_lock(hdev);
3936
3937         if (!bacmp(&cp->addr.bdaddr, BDADDR_ANY)) {
3938                 hci_remote_oob_data_clear(hdev);
3939                 status = MGMT_STATUS_SUCCESS;
3940                 goto done;
3941         }
3942
3943         err = hci_remove_remote_oob_data(hdev, &cp->addr.bdaddr, cp->addr.type);
3944         if (err < 0)
3945                 status = MGMT_STATUS_INVALID_PARAMS;
3946         else
3947                 status = MGMT_STATUS_SUCCESS;
3948
3949 done:
3950         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_REMOVE_REMOTE_OOB_DATA,
3951                                 status, &cp->addr, sizeof(cp->addr));
3952
3953         hci_dev_unlock(hdev);
3954         return err;
3955 }
3956
3957 static bool trigger_bredr_inquiry(struct hci_request *req, u8 *status)
3958 {
3959         struct hci_dev *hdev = req->hdev;
3960         struct hci_cp_inquiry cp;
3961         /* General inquiry access code (GIAC) */
3962         u8 lap[3] = { 0x33, 0x8b, 0x9e };
3963
3964         *status = mgmt_bredr_support(hdev);
3965         if (*status)
3966                 return false;
3967
3968         if (hci_dev_test_flag(hdev, HCI_INQUIRY)) {
3969                 *status = MGMT_STATUS_BUSY;
3970                 return false;
3971         }
3972
3973         hci_inquiry_cache_flush(hdev);
3974
3975         memset(&cp, 0, sizeof(cp));
3976         memcpy(&cp.lap, lap, sizeof(cp.lap));
3977         cp.length = DISCOV_BREDR_INQUIRY_LEN;
3978
3979         hci_req_add(req, HCI_OP_INQUIRY, sizeof(cp), &cp);
3980
3981         return true;
3982 }
3983
3984 static bool trigger_le_scan(struct hci_request *req, u16 interval, u8 *status)
3985 {
3986         struct hci_dev *hdev = req->hdev;
3987         struct hci_cp_le_set_scan_param param_cp;
3988         struct hci_cp_le_set_scan_enable enable_cp;
3989         u8 own_addr_type;
3990         int err;
3991
3992         *status = mgmt_le_support(hdev);
3993         if (*status)
3994                 return false;
3995
3996         if (hci_dev_test_flag(hdev, HCI_LE_ADV)) {
3997                 /* Don't let discovery abort an outgoing connection attempt
3998                  * that's using directed advertising.
3999                  */
4000                 if (hci_conn_hash_lookup_state(hdev, LE_LINK, BT_CONNECT)) {
4001                         *status = MGMT_STATUS_REJECTED;
4002                         return false;
4003                 }
4004
4005                 disable_advertising(req);
4006         }
4007
4008         /* If controller is scanning, it means the background scanning is
4009          * running. Thus, we should temporarily stop it in order to set the
4010          * discovery scanning parameters.
4011          */
4012         if (hci_dev_test_flag(hdev, HCI_LE_SCAN))
4013                 hci_req_add_le_scan_disable(req);
4014
4015         /* All active scans will be done with either a resolvable private
4016          * address (when privacy feature has been enabled) or non-resolvable
4017          * private address.
4018          */
4019         err = hci_update_random_address(req, true, &own_addr_type);
4020         if (err < 0) {
4021                 *status = MGMT_STATUS_FAILED;
4022                 return false;
4023         }
4024
4025         memset(&param_cp, 0, sizeof(param_cp));
4026         param_cp.type = LE_SCAN_ACTIVE;
4027         param_cp.interval = cpu_to_le16(interval);
4028         param_cp.window = cpu_to_le16(DISCOV_LE_SCAN_WIN);
4029         param_cp.own_address_type = own_addr_type;
4030
4031         hci_req_add(req, HCI_OP_LE_SET_SCAN_PARAM, sizeof(param_cp),
4032                     &param_cp);
4033
4034         memset(&enable_cp, 0, sizeof(enable_cp));
4035         enable_cp.enable = LE_SCAN_ENABLE;
4036         enable_cp.filter_dup = LE_SCAN_FILTER_DUP_ENABLE;
4037
4038         hci_req_add(req, HCI_OP_LE_SET_SCAN_ENABLE, sizeof(enable_cp),
4039                     &enable_cp);
4040
4041         return true;
4042 }
4043
4044 static bool trigger_discovery(struct hci_request *req, u8 *status)
4045 {
4046         struct hci_dev *hdev = req->hdev;
4047
4048         switch (hdev->discovery.type) {
4049         case DISCOV_TYPE_BREDR:
4050                 if (!trigger_bredr_inquiry(req, status))
4051                         return false;
4052                 break;
4053
4054         case DISCOV_TYPE_INTERLEAVED:
4055                 if (test_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY,
4056                              &hdev->quirks)) {
4057                         /* During simultaneous discovery, we double LE scan
4058                          * interval. We must leave some time for the controller
4059                          * to do BR/EDR inquiry.
4060                          */
4061                         if (!trigger_le_scan(req, DISCOV_LE_SCAN_INT * 2,
4062                                              status))
4063                                 return false;
4064
4065                         if (!trigger_bredr_inquiry(req, status))
4066                                 return false;
4067
4068                         return true;
4069                 }
4070
4071                 if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
4072                         *status = MGMT_STATUS_NOT_SUPPORTED;
4073                         return false;
4074                 }
4075                 /* fall through */
4076
4077         case DISCOV_TYPE_LE:
4078                 if (!trigger_le_scan(req, DISCOV_LE_SCAN_INT, status))
4079                         return false;
4080                 break;
4081
4082         default:
4083                 *status = MGMT_STATUS_INVALID_PARAMS;
4084                 return false;
4085         }
4086
4087         return true;
4088 }
4089
4090 static void start_discovery_complete(struct hci_dev *hdev, u8 status,
4091                                      u16 opcode)
4092 {
4093         struct mgmt_pending_cmd *cmd;
4094         unsigned long timeout;
4095
4096         BT_DBG("status %d", status);
4097
4098         hci_dev_lock(hdev);
4099
4100         cmd = pending_find(MGMT_OP_START_DISCOVERY, hdev);
4101         if (!cmd)
4102                 cmd = pending_find(MGMT_OP_START_SERVICE_DISCOVERY, hdev);
4103
4104         if (cmd) {
4105                 cmd->cmd_complete(cmd, mgmt_status(status));
4106                 mgmt_pending_remove(cmd);
4107         }
4108
4109         if (status) {
4110                 hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
4111                 goto unlock;
4112         }
4113
4114         hci_discovery_set_state(hdev, DISCOVERY_FINDING);
4115
4116         /* If the scan involves LE scan, pick proper timeout to schedule
4117          * hdev->le_scan_disable that will stop it.
4118          */
4119         switch (hdev->discovery.type) {
4120         case DISCOV_TYPE_LE:
4121                 timeout = msecs_to_jiffies(DISCOV_LE_TIMEOUT);
4122                 break;
4123         case DISCOV_TYPE_INTERLEAVED:
4124                  /* When running simultaneous discovery, the LE scanning time
4125                  * should occupy the whole discovery time sine BR/EDR inquiry
4126                  * and LE scanning are scheduled by the controller.
4127                  *
4128                  * For interleaving discovery in comparison, BR/EDR inquiry
4129                  * and LE scanning are done sequentially with separate
4130                  * timeouts.
4131                  */
4132                 if (test_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks))
4133                         timeout = msecs_to_jiffies(DISCOV_LE_TIMEOUT);
4134                 else
4135                         timeout = msecs_to_jiffies(hdev->discov_interleaved_timeout);
4136                 break;
4137         case DISCOV_TYPE_BREDR:
4138                 timeout = 0;
4139                 break;
4140         default:
4141                 BT_ERR("Invalid discovery type %d", hdev->discovery.type);
4142                 timeout = 0;
4143                 break;
4144         }
4145
4146         if (timeout) {
4147                 /* When service discovery is used and the controller has
4148                  * a strict duplicate filter, it is important to remember
4149                  * the start and duration of the scan. This is required
4150                  * for restarting scanning during the discovery phase.
4151                  */
4152                 if (test_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER,
4153                              &hdev->quirks) &&
4154                     hdev->discovery.result_filtering) {
4155                         hdev->discovery.scan_start = jiffies;
4156                         hdev->discovery.scan_duration = timeout;
4157                 }
4158
4159                 queue_delayed_work(hdev->workqueue,
4160                                    &hdev->le_scan_disable, timeout);
4161         }
4162
4163 unlock:
4164         hci_dev_unlock(hdev);
4165 }
4166
4167 static int start_discovery(struct sock *sk, struct hci_dev *hdev,
4168                            void *data, u16 len)
4169 {
4170         struct mgmt_cp_start_discovery *cp = data;
4171         struct mgmt_pending_cmd *cmd;
4172         struct hci_request req;
4173         u8 status;
4174         int err;
4175
4176         BT_DBG("%s", hdev->name);
4177
4178         hci_dev_lock(hdev);
4179
4180         if (!hdev_is_powered(hdev)) {
4181                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_START_DISCOVERY,
4182                                         MGMT_STATUS_NOT_POWERED,
4183                                         &cp->type, sizeof(cp->type));
4184                 goto failed;
4185         }
4186
4187         if (hdev->discovery.state != DISCOVERY_STOPPED ||
4188             hci_dev_test_flag(hdev, HCI_PERIODIC_INQ)) {
4189                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_START_DISCOVERY,
4190                                         MGMT_STATUS_BUSY, &cp->type,
4191                                         sizeof(cp->type));
4192                 goto failed;
4193         }
4194
4195         cmd = mgmt_pending_add(sk, MGMT_OP_START_DISCOVERY, hdev, data, len);
4196         if (!cmd) {
4197                 err = -ENOMEM;
4198                 goto failed;
4199         }
4200
4201         cmd->cmd_complete = generic_cmd_complete;
4202
4203         /* Clear the discovery filter first to free any previously
4204          * allocated memory for the UUID list.
4205          */
4206         hci_discovery_filter_clear(hdev);
4207
4208         hdev->discovery.type = cp->type;
4209         hdev->discovery.report_invalid_rssi = false;
4210
4211         hci_req_init(&req, hdev);
4212
4213         if (!trigger_discovery(&req, &status)) {
4214                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_START_DISCOVERY,
4215                                         status, &cp->type, sizeof(cp->type));
4216                 mgmt_pending_remove(cmd);
4217                 goto failed;
4218         }
4219
4220         err = hci_req_run(&req, start_discovery_complete);
4221         if (err < 0) {
4222                 mgmt_pending_remove(cmd);
4223                 goto failed;
4224         }
4225
4226         hci_discovery_set_state(hdev, DISCOVERY_STARTING);
4227
4228 failed:
4229         hci_dev_unlock(hdev);
4230         return err;
4231 }
4232
4233 static int service_discovery_cmd_complete(struct mgmt_pending_cmd *cmd,
4234                                           u8 status)
4235 {
4236         return mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode, status,
4237                                  cmd->param, 1);
4238 }
4239
4240 static int start_service_discovery(struct sock *sk, struct hci_dev *hdev,
4241                                    void *data, u16 len)
4242 {
4243         struct mgmt_cp_start_service_discovery *cp = data;
4244         struct mgmt_pending_cmd *cmd;
4245         struct hci_request req;
4246         const u16 max_uuid_count = ((U16_MAX - sizeof(*cp)) / 16);
4247         u16 uuid_count, expected_len;
4248         u8 status;
4249         int err;
4250
4251         BT_DBG("%s", hdev->name);
4252
4253         hci_dev_lock(hdev);
4254
4255         if (!hdev_is_powered(hdev)) {
4256                 err = mgmt_cmd_complete(sk, hdev->id,
4257                                         MGMT_OP_START_SERVICE_DISCOVERY,
4258                                         MGMT_STATUS_NOT_POWERED,
4259                                         &cp->type, sizeof(cp->type));
4260                 goto failed;
4261         }
4262
4263         if (hdev->discovery.state != DISCOVERY_STOPPED ||
4264             hci_dev_test_flag(hdev, HCI_PERIODIC_INQ)) {
4265                 err = mgmt_cmd_complete(sk, hdev->id,
4266                                         MGMT_OP_START_SERVICE_DISCOVERY,
4267                                         MGMT_STATUS_BUSY, &cp->type,
4268                                         sizeof(cp->type));
4269                 goto failed;
4270         }
4271
4272         uuid_count = __le16_to_cpu(cp->uuid_count);
4273         if (uuid_count > max_uuid_count) {
4274                 BT_ERR("service_discovery: too big uuid_count value %u",
4275                        uuid_count);
4276                 err = mgmt_cmd_complete(sk, hdev->id,
4277                                         MGMT_OP_START_SERVICE_DISCOVERY,
4278                                         MGMT_STATUS_INVALID_PARAMS, &cp->type,
4279                                         sizeof(cp->type));
4280                 goto failed;
4281         }
4282
4283         expected_len = sizeof(*cp) + uuid_count * 16;
4284         if (expected_len != len) {
4285                 BT_ERR("service_discovery: expected %u bytes, got %u bytes",
4286                        expected_len, len);
4287                 err = mgmt_cmd_complete(sk, hdev->id,
4288                                         MGMT_OP_START_SERVICE_DISCOVERY,
4289                                         MGMT_STATUS_INVALID_PARAMS, &cp->type,
4290                                         sizeof(cp->type));
4291                 goto failed;
4292         }
4293
4294         cmd = mgmt_pending_add(sk, MGMT_OP_START_SERVICE_DISCOVERY,
4295                                hdev, data, len);
4296         if (!cmd) {
4297                 err = -ENOMEM;
4298                 goto failed;
4299         }
4300
4301         cmd->cmd_complete = service_discovery_cmd_complete;
4302
4303         /* Clear the discovery filter first to free any previously
4304          * allocated memory for the UUID list.
4305          */
4306         hci_discovery_filter_clear(hdev);
4307
4308         hdev->discovery.result_filtering = true;
4309         hdev->discovery.type = cp->type;
4310         hdev->discovery.rssi = cp->rssi;
4311         hdev->discovery.uuid_count = uuid_count;
4312
4313         if (uuid_count > 0) {
4314                 hdev->discovery.uuids = kmemdup(cp->uuids, uuid_count * 16,
4315                                                 GFP_KERNEL);
4316                 if (!hdev->discovery.uuids) {
4317                         err = mgmt_cmd_complete(sk, hdev->id,
4318                                                 MGMT_OP_START_SERVICE_DISCOVERY,
4319                                                 MGMT_STATUS_FAILED,
4320                                                 &cp->type, sizeof(cp->type));
4321                         mgmt_pending_remove(cmd);
4322                         goto failed;
4323                 }
4324         }
4325
4326         hci_req_init(&req, hdev);
4327
4328         if (!trigger_discovery(&req, &status)) {
4329                 err = mgmt_cmd_complete(sk, hdev->id,
4330                                         MGMT_OP_START_SERVICE_DISCOVERY,
4331                                         status, &cp->type, sizeof(cp->type));
4332                 mgmt_pending_remove(cmd);
4333                 goto failed;
4334         }
4335
4336         err = hci_req_run(&req, start_discovery_complete);
4337         if (err < 0) {
4338                 mgmt_pending_remove(cmd);
4339                 goto failed;
4340         }
4341
4342         hci_discovery_set_state(hdev, DISCOVERY_STARTING);
4343
4344 failed:
4345         hci_dev_unlock(hdev);
4346         return err;
4347 }
4348
4349 static void stop_discovery_complete(struct hci_dev *hdev, u8 status, u16 opcode)
4350 {
4351         struct mgmt_pending_cmd *cmd;
4352
4353         BT_DBG("status %d", status);
4354
4355         hci_dev_lock(hdev);
4356
4357         cmd = pending_find(MGMT_OP_STOP_DISCOVERY, hdev);
4358         if (cmd) {
4359                 cmd->cmd_complete(cmd, mgmt_status(status));
4360                 mgmt_pending_remove(cmd);
4361         }
4362
4363         if (!status)
4364                 hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
4365
4366         hci_dev_unlock(hdev);
4367 }
4368
4369 static int stop_discovery(struct sock *sk, struct hci_dev *hdev, void *data,
4370                           u16 len)
4371 {
4372         struct mgmt_cp_stop_discovery *mgmt_cp = data;
4373         struct mgmt_pending_cmd *cmd;
4374         struct hci_request req;
4375         int err;
4376
4377         BT_DBG("%s", hdev->name);
4378
4379         hci_dev_lock(hdev);
4380
4381         if (!hci_discovery_active(hdev)) {
4382                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_STOP_DISCOVERY,
4383                                         MGMT_STATUS_REJECTED, &mgmt_cp->type,
4384                                         sizeof(mgmt_cp->type));
4385                 goto unlock;
4386         }
4387
4388         if (hdev->discovery.type != mgmt_cp->type) {
4389                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_STOP_DISCOVERY,
4390                                         MGMT_STATUS_INVALID_PARAMS,
4391                                         &mgmt_cp->type, sizeof(mgmt_cp->type));
4392                 goto unlock;
4393         }
4394
4395         cmd = mgmt_pending_add(sk, MGMT_OP_STOP_DISCOVERY, hdev, data, len);
4396         if (!cmd) {
4397                 err = -ENOMEM;
4398                 goto unlock;
4399         }
4400
4401         cmd->cmd_complete = generic_cmd_complete;
4402
4403         hci_req_init(&req, hdev);
4404
4405         hci_stop_discovery(&req);
4406
4407         err = hci_req_run(&req, stop_discovery_complete);
4408         if (!err) {
4409                 hci_discovery_set_state(hdev, DISCOVERY_STOPPING);
4410                 goto unlock;
4411         }
4412
4413         mgmt_pending_remove(cmd);
4414
4415         /* If no HCI commands were sent we're done */
4416         if (err == -ENODATA) {
4417                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_STOP_DISCOVERY, 0,
4418                                         &mgmt_cp->type, sizeof(mgmt_cp->type));
4419                 hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
4420         }
4421
4422 unlock:
4423         hci_dev_unlock(hdev);
4424         return err;
4425 }
4426
4427 static int confirm_name(struct sock *sk, struct hci_dev *hdev, void *data,
4428                         u16 len)
4429 {
4430         struct mgmt_cp_confirm_name *cp = data;
4431         struct inquiry_entry *e;
4432         int err;
4433
4434         BT_DBG("%s", hdev->name);
4435
4436         hci_dev_lock(hdev);
4437
4438         if (!hci_discovery_active(hdev)) {
4439                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_CONFIRM_NAME,
4440                                         MGMT_STATUS_FAILED, &cp->addr,
4441                                         sizeof(cp->addr));
4442                 goto failed;
4443         }
4444
4445         e = hci_inquiry_cache_lookup_unknown(hdev, &cp->addr.bdaddr);
4446         if (!e) {
4447                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_CONFIRM_NAME,
4448                                         MGMT_STATUS_INVALID_PARAMS, &cp->addr,
4449                                         sizeof(cp->addr));
4450                 goto failed;
4451         }
4452
4453         if (cp->name_known) {
4454                 e->name_state = NAME_KNOWN;
4455                 list_del(&e->list);
4456         } else {
4457                 e->name_state = NAME_NEEDED;
4458                 hci_inquiry_cache_update_resolve(hdev, e);
4459         }
4460
4461         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_CONFIRM_NAME, 0,
4462                                 &cp->addr, sizeof(cp->addr));
4463
4464 failed:
4465         hci_dev_unlock(hdev);
4466         return err;
4467 }
4468
4469 static int block_device(struct sock *sk, struct hci_dev *hdev, void *data,
4470                         u16 len)
4471 {
4472         struct mgmt_cp_block_device *cp = data;
4473         u8 status;
4474         int err;
4475
4476         BT_DBG("%s", hdev->name);
4477
4478         if (!bdaddr_type_is_valid(cp->addr.type))
4479                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_BLOCK_DEVICE,
4480                                          MGMT_STATUS_INVALID_PARAMS,
4481                                          &cp->addr, sizeof(cp->addr));
4482
4483         hci_dev_lock(hdev);
4484
4485         err = hci_bdaddr_list_add(&hdev->blacklist, &cp->addr.bdaddr,
4486                                   cp->addr.type);
4487         if (err < 0) {
4488                 status = MGMT_STATUS_FAILED;
4489                 goto done;
4490         }
4491
4492         mgmt_event(MGMT_EV_DEVICE_BLOCKED, hdev, &cp->addr, sizeof(cp->addr),
4493                    sk);
4494         status = MGMT_STATUS_SUCCESS;
4495
4496 done:
4497         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_BLOCK_DEVICE, status,
4498                                 &cp->addr, sizeof(cp->addr));
4499
4500         hci_dev_unlock(hdev);
4501
4502         return err;
4503 }
4504
4505 static int unblock_device(struct sock *sk, struct hci_dev *hdev, void *data,
4506                           u16 len)
4507 {
4508         struct mgmt_cp_unblock_device *cp = data;
4509         u8 status;
4510         int err;
4511
4512         BT_DBG("%s", hdev->name);
4513
4514         if (!bdaddr_type_is_valid(cp->addr.type))
4515                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNBLOCK_DEVICE,
4516                                          MGMT_STATUS_INVALID_PARAMS,
4517                                          &cp->addr, sizeof(cp->addr));
4518
4519         hci_dev_lock(hdev);
4520
4521         err = hci_bdaddr_list_del(&hdev->blacklist, &cp->addr.bdaddr,
4522                                   cp->addr.type);
4523         if (err < 0) {
4524                 status = MGMT_STATUS_INVALID_PARAMS;
4525                 goto done;
4526         }
4527
4528         mgmt_event(MGMT_EV_DEVICE_UNBLOCKED, hdev, &cp->addr, sizeof(cp->addr),
4529                    sk);
4530         status = MGMT_STATUS_SUCCESS;
4531
4532 done:
4533         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_UNBLOCK_DEVICE, status,
4534                                 &cp->addr, sizeof(cp->addr));
4535
4536         hci_dev_unlock(hdev);
4537
4538         return err;
4539 }
4540
4541 static int set_device_id(struct sock *sk, struct hci_dev *hdev, void *data,
4542                          u16 len)
4543 {
4544         struct mgmt_cp_set_device_id *cp = data;
4545         struct hci_request req;
4546         int err;
4547         __u16 source;
4548
4549         BT_DBG("%s", hdev->name);
4550
4551         source = __le16_to_cpu(cp->source);
4552
4553         if (source > 0x0002)
4554                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEVICE_ID,
4555                                        MGMT_STATUS_INVALID_PARAMS);
4556
4557         hci_dev_lock(hdev);
4558
4559         hdev->devid_source = source;
4560         hdev->devid_vendor = __le16_to_cpu(cp->vendor);
4561         hdev->devid_product = __le16_to_cpu(cp->product);
4562         hdev->devid_version = __le16_to_cpu(cp->version);
4563
4564         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_DEVICE_ID, 0,
4565                                 NULL, 0);
4566
4567         hci_req_init(&req, hdev);
4568         update_eir(&req);
4569         hci_req_run(&req, NULL);
4570
4571         hci_dev_unlock(hdev);
4572
4573         return err;
4574 }
4575
4576 static void enable_advertising_instance(struct hci_dev *hdev, u8 status,
4577                                         u16 opcode)
4578 {
4579         BT_DBG("status %d", status);
4580 }
4581
4582 static void set_advertising_complete(struct hci_dev *hdev, u8 status,
4583                                      u16 opcode)
4584 {
4585         struct cmd_lookup match = { NULL, hdev };
4586         struct hci_request req;
4587
4588         hci_dev_lock(hdev);
4589
4590         if (status) {
4591                 u8 mgmt_err = mgmt_status(status);
4592
4593                 mgmt_pending_foreach(MGMT_OP_SET_ADVERTISING, hdev,
4594                                      cmd_status_rsp, &mgmt_err);
4595                 goto unlock;
4596         }
4597
4598         if (hci_dev_test_flag(hdev, HCI_LE_ADV))
4599                 hci_dev_set_flag(hdev, HCI_ADVERTISING);
4600         else
4601                 hci_dev_clear_flag(hdev, HCI_ADVERTISING);
4602
4603         mgmt_pending_foreach(MGMT_OP_SET_ADVERTISING, hdev, settings_rsp,
4604                              &match);
4605
4606         new_settings(hdev, match.sk);
4607
4608         if (match.sk)
4609                 sock_put(match.sk);
4610
4611         /* If "Set Advertising" was just disabled and instance advertising was
4612          * set up earlier, then enable the advertising instance.
4613          */
4614         if (hci_dev_test_flag(hdev, HCI_ADVERTISING) ||
4615             !hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE))
4616                 goto unlock;
4617
4618         hci_req_init(&req, hdev);
4619
4620         update_adv_data(&req);
4621         enable_advertising(&req);
4622
4623         if (hci_req_run(&req, enable_advertising_instance) < 0)
4624                 BT_ERR("Failed to re-configure advertising");
4625
4626 unlock:
4627         hci_dev_unlock(hdev);
4628 }
4629
4630 static int set_advertising(struct sock *sk, struct hci_dev *hdev, void *data,
4631                            u16 len)
4632 {
4633         struct mgmt_mode *cp = data;
4634         struct mgmt_pending_cmd *cmd;
4635         struct hci_request req;
4636         u8 val, status;
4637         int err;
4638
4639         BT_DBG("request for %s", hdev->name);
4640
4641         status = mgmt_le_support(hdev);
4642         if (status)
4643                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_ADVERTISING,
4644                                        status);
4645
4646         if (cp->val != 0x00 && cp->val != 0x01 && cp->val != 0x02)
4647                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_ADVERTISING,
4648                                        MGMT_STATUS_INVALID_PARAMS);
4649
4650         hci_dev_lock(hdev);
4651
4652         val = !!cp->val;
4653
4654         /* The following conditions are ones which mean that we should
4655          * not do any HCI communication but directly send a mgmt
4656          * response to user space (after toggling the flag if
4657          * necessary).
4658          */
4659         if (!hdev_is_powered(hdev) ||
4660             (val == hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
4661              (cp->val == 0x02) == hci_dev_test_flag(hdev, HCI_ADVERTISING_CONNECTABLE)) ||
4662             hci_conn_num(hdev, LE_LINK) > 0 ||
4663             (hci_dev_test_flag(hdev, HCI_LE_SCAN) &&
4664              hdev->le_scan_type == LE_SCAN_ACTIVE)) {
4665                 bool changed;
4666
4667                 if (cp->val) {
4668                         changed = !hci_dev_test_and_set_flag(hdev, HCI_ADVERTISING);
4669                         if (cp->val == 0x02)
4670                                 hci_dev_set_flag(hdev, HCI_ADVERTISING_CONNECTABLE);
4671                         else
4672                                 hci_dev_clear_flag(hdev, HCI_ADVERTISING_CONNECTABLE);
4673                 } else {
4674                         changed = hci_dev_test_and_clear_flag(hdev, HCI_ADVERTISING);
4675                         hci_dev_clear_flag(hdev, HCI_ADVERTISING_CONNECTABLE);
4676                 }
4677
4678                 err = send_settings_rsp(sk, MGMT_OP_SET_ADVERTISING, hdev);
4679                 if (err < 0)
4680                         goto unlock;
4681
4682                 if (changed)
4683                         err = new_settings(hdev, sk);
4684
4685                 goto unlock;
4686         }
4687
4688         if (pending_find(MGMT_OP_SET_ADVERTISING, hdev) ||
4689             pending_find(MGMT_OP_SET_LE, hdev)) {
4690                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_ADVERTISING,
4691                                       MGMT_STATUS_BUSY);
4692                 goto unlock;
4693         }
4694
4695         cmd = mgmt_pending_add(sk, MGMT_OP_SET_ADVERTISING, hdev, data, len);
4696         if (!cmd) {
4697                 err = -ENOMEM;
4698                 goto unlock;
4699         }
4700
4701         hci_req_init(&req, hdev);
4702
4703         if (cp->val == 0x02)
4704                 hci_dev_set_flag(hdev, HCI_ADVERTISING_CONNECTABLE);
4705         else
4706                 hci_dev_clear_flag(hdev, HCI_ADVERTISING_CONNECTABLE);
4707
4708         if (val) {
4709                 /* Switch to instance "0" for the Set Advertising setting. */
4710                 update_adv_data_for_instance(&req, 0);
4711                 update_scan_rsp_data_for_instance(&req, 0);
4712                 enable_advertising(&req);
4713         } else {
4714                 disable_advertising(&req);
4715         }
4716
4717         err = hci_req_run(&req, set_advertising_complete);
4718         if (err < 0)
4719                 mgmt_pending_remove(cmd);
4720
4721 unlock:
4722         hci_dev_unlock(hdev);
4723         return err;
4724 }
4725
4726 static int set_static_address(struct sock *sk, struct hci_dev *hdev,
4727                               void *data, u16 len)
4728 {
4729         struct mgmt_cp_set_static_address *cp = data;
4730         int err;
4731
4732         BT_DBG("%s", hdev->name);
4733
4734         if (!lmp_le_capable(hdev))
4735                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_STATIC_ADDRESS,
4736                                        MGMT_STATUS_NOT_SUPPORTED);
4737
4738         if (hdev_is_powered(hdev))
4739                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_STATIC_ADDRESS,
4740                                        MGMT_STATUS_REJECTED);
4741
4742         if (bacmp(&cp->bdaddr, BDADDR_ANY)) {
4743                 if (!bacmp(&cp->bdaddr, BDADDR_NONE))
4744                         return mgmt_cmd_status(sk, hdev->id,
4745                                                MGMT_OP_SET_STATIC_ADDRESS,
4746                                                MGMT_STATUS_INVALID_PARAMS);
4747
4748                 /* Two most significant bits shall be set */
4749                 if ((cp->bdaddr.b[5] & 0xc0) != 0xc0)
4750                         return mgmt_cmd_status(sk, hdev->id,
4751                                                MGMT_OP_SET_STATIC_ADDRESS,
4752                                                MGMT_STATUS_INVALID_PARAMS);
4753         }
4754
4755         hci_dev_lock(hdev);
4756
4757         bacpy(&hdev->static_addr, &cp->bdaddr);
4758
4759         err = send_settings_rsp(sk, MGMT_OP_SET_STATIC_ADDRESS, hdev);
4760         if (err < 0)
4761                 goto unlock;
4762
4763         err = new_settings(hdev, sk);
4764
4765 unlock:
4766         hci_dev_unlock(hdev);
4767         return err;
4768 }
4769
4770 static int set_scan_params(struct sock *sk, struct hci_dev *hdev,
4771                            void *data, u16 len)
4772 {
4773         struct mgmt_cp_set_scan_params *cp = data;
4774         __u16 interval, window;
4775         int err;
4776
4777         BT_DBG("%s", hdev->name);
4778
4779         if (!lmp_le_capable(hdev))
4780                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SCAN_PARAMS,
4781                                        MGMT_STATUS_NOT_SUPPORTED);
4782
4783         interval = __le16_to_cpu(cp->interval);
4784
4785         if (interval < 0x0004 || interval > 0x4000)
4786                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SCAN_PARAMS,
4787                                        MGMT_STATUS_INVALID_PARAMS);
4788
4789         window = __le16_to_cpu(cp->window);
4790
4791         if (window < 0x0004 || window > 0x4000)
4792                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SCAN_PARAMS,
4793                                        MGMT_STATUS_INVALID_PARAMS);
4794
4795         if (window > interval)
4796                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SCAN_PARAMS,
4797                                        MGMT_STATUS_INVALID_PARAMS);
4798
4799         hci_dev_lock(hdev);
4800
4801         hdev->le_scan_interval = interval;
4802         hdev->le_scan_window = window;
4803
4804         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_SET_SCAN_PARAMS, 0,
4805                                 NULL, 0);
4806
4807         /* If background scan is running, restart it so new parameters are
4808          * loaded.
4809          */
4810         if (hci_dev_test_flag(hdev, HCI_LE_SCAN) &&
4811             hdev->discovery.state == DISCOVERY_STOPPED) {
4812                 struct hci_request req;
4813
4814                 hci_req_init(&req, hdev);
4815
4816                 hci_req_add_le_scan_disable(&req);
4817                 hci_req_add_le_passive_scan(&req);
4818
4819                 hci_req_run(&req, NULL);
4820         }
4821
4822         hci_dev_unlock(hdev);
4823
4824         return err;
4825 }
4826
4827 static void fast_connectable_complete(struct hci_dev *hdev, u8 status,
4828                                       u16 opcode)
4829 {
4830         struct mgmt_pending_cmd *cmd;
4831
4832         BT_DBG("status 0x%02x", status);
4833
4834         hci_dev_lock(hdev);
4835
4836         cmd = pending_find(MGMT_OP_SET_FAST_CONNECTABLE, hdev);
4837         if (!cmd)
4838                 goto unlock;
4839
4840         if (status) {
4841                 mgmt_cmd_status(cmd->sk, hdev->id, MGMT_OP_SET_FAST_CONNECTABLE,
4842                                 mgmt_status(status));
4843         } else {
4844                 struct mgmt_mode *cp = cmd->param;
4845
4846                 if (cp->val)
4847                         hci_dev_set_flag(hdev, HCI_FAST_CONNECTABLE);
4848                 else
4849                         hci_dev_clear_flag(hdev, HCI_FAST_CONNECTABLE);
4850
4851                 send_settings_rsp(cmd->sk, MGMT_OP_SET_FAST_CONNECTABLE, hdev);
4852                 new_settings(hdev, cmd->sk);
4853         }
4854
4855         mgmt_pending_remove(cmd);
4856
4857 unlock:
4858         hci_dev_unlock(hdev);
4859 }
4860
4861 static int set_fast_connectable(struct sock *sk, struct hci_dev *hdev,
4862                                 void *data, u16 len)
4863 {
4864         struct mgmt_mode *cp = data;
4865         struct mgmt_pending_cmd *cmd;
4866         struct hci_request req;
4867         int err;
4868
4869         BT_DBG("%s", hdev->name);
4870
4871         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) ||
4872             hdev->hci_ver < BLUETOOTH_VER_1_2)
4873                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_FAST_CONNECTABLE,
4874                                        MGMT_STATUS_NOT_SUPPORTED);
4875
4876         if (cp->val != 0x00 && cp->val != 0x01)
4877                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_FAST_CONNECTABLE,
4878                                        MGMT_STATUS_INVALID_PARAMS);
4879
4880         hci_dev_lock(hdev);
4881
4882         if (pending_find(MGMT_OP_SET_FAST_CONNECTABLE, hdev)) {
4883                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_FAST_CONNECTABLE,
4884                                       MGMT_STATUS_BUSY);
4885                 goto unlock;
4886         }
4887
4888         if (!!cp->val == hci_dev_test_flag(hdev, HCI_FAST_CONNECTABLE)) {
4889                 err = send_settings_rsp(sk, MGMT_OP_SET_FAST_CONNECTABLE,
4890                                         hdev);
4891                 goto unlock;
4892         }
4893
4894         if (!hdev_is_powered(hdev)) {
4895                 hci_dev_change_flag(hdev, HCI_FAST_CONNECTABLE);
4896                 err = send_settings_rsp(sk, MGMT_OP_SET_FAST_CONNECTABLE,
4897                                         hdev);
4898                 new_settings(hdev, sk);
4899                 goto unlock;
4900         }
4901
4902         cmd = mgmt_pending_add(sk, MGMT_OP_SET_FAST_CONNECTABLE, hdev,
4903                                data, len);
4904         if (!cmd) {
4905                 err = -ENOMEM;
4906                 goto unlock;
4907         }
4908
4909         hci_req_init(&req, hdev);
4910
4911         write_fast_connectable(&req, cp->val);
4912
4913         err = hci_req_run(&req, fast_connectable_complete);
4914         if (err < 0) {
4915                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_FAST_CONNECTABLE,
4916                                       MGMT_STATUS_FAILED);
4917                 mgmt_pending_remove(cmd);
4918         }
4919
4920 unlock:
4921         hci_dev_unlock(hdev);
4922
4923         return err;
4924 }
4925
4926 static void set_bredr_complete(struct hci_dev *hdev, u8 status, u16 opcode)
4927 {
4928         struct mgmt_pending_cmd *cmd;
4929
4930         BT_DBG("status 0x%02x", status);
4931
4932         hci_dev_lock(hdev);
4933
4934         cmd = pending_find(MGMT_OP_SET_BREDR, hdev);
4935         if (!cmd)
4936                 goto unlock;
4937
4938         if (status) {
4939                 u8 mgmt_err = mgmt_status(status);
4940
4941                 /* We need to restore the flag if related HCI commands
4942                  * failed.
4943                  */
4944                 hci_dev_clear_flag(hdev, HCI_BREDR_ENABLED);
4945
4946                 mgmt_cmd_status(cmd->sk, cmd->index, cmd->opcode, mgmt_err);
4947         } else {
4948                 send_settings_rsp(cmd->sk, MGMT_OP_SET_BREDR, hdev);
4949                 new_settings(hdev, cmd->sk);
4950         }
4951
4952         mgmt_pending_remove(cmd);
4953
4954 unlock:
4955         hci_dev_unlock(hdev);
4956 }
4957
4958 static int set_bredr(struct sock *sk, struct hci_dev *hdev, void *data, u16 len)
4959 {
4960         struct mgmt_mode *cp = data;
4961         struct mgmt_pending_cmd *cmd;
4962         struct hci_request req;
4963         int err;
4964
4965         BT_DBG("request for %s", hdev->name);
4966
4967         if (!lmp_bredr_capable(hdev) || !lmp_le_capable(hdev))
4968                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BREDR,
4969                                        MGMT_STATUS_NOT_SUPPORTED);
4970
4971         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
4972                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BREDR,
4973                                        MGMT_STATUS_REJECTED);
4974
4975         if (cp->val != 0x00 && cp->val != 0x01)
4976                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BREDR,
4977                                        MGMT_STATUS_INVALID_PARAMS);
4978
4979         hci_dev_lock(hdev);
4980
4981         if (cp->val == hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
4982                 err = send_settings_rsp(sk, MGMT_OP_SET_BREDR, hdev);
4983                 goto unlock;
4984         }
4985
4986         if (!hdev_is_powered(hdev)) {
4987                 if (!cp->val) {
4988                         hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
4989                         hci_dev_clear_flag(hdev, HCI_SSP_ENABLED);
4990                         hci_dev_clear_flag(hdev, HCI_LINK_SECURITY);
4991                         hci_dev_clear_flag(hdev, HCI_FAST_CONNECTABLE);
4992                         hci_dev_clear_flag(hdev, HCI_HS_ENABLED);
4993                 }
4994
4995                 hci_dev_change_flag(hdev, HCI_BREDR_ENABLED);
4996
4997                 err = send_settings_rsp(sk, MGMT_OP_SET_BREDR, hdev);
4998                 if (err < 0)
4999                         goto unlock;
5000
5001                 err = new_settings(hdev, sk);
5002                 goto unlock;
5003         }
5004
5005         /* Reject disabling when powered on */
5006         if (!cp->val) {
5007                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BREDR,
5008                                       MGMT_STATUS_REJECTED);
5009                 goto unlock;
5010         } else {
5011                 /* When configuring a dual-mode controller to operate
5012                  * with LE only and using a static address, then switching
5013                  * BR/EDR back on is not allowed.
5014                  *
5015                  * Dual-mode controllers shall operate with the public
5016                  * address as its identity address for BR/EDR and LE. So
5017                  * reject the attempt to create an invalid configuration.
5018                  *
5019                  * The same restrictions applies when secure connections
5020                  * has been enabled. For BR/EDR this is a controller feature
5021                  * while for LE it is a host stack feature. This means that
5022                  * switching BR/EDR back on when secure connections has been
5023                  * enabled is not a supported transaction.
5024                  */
5025                 if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) &&
5026                     (bacmp(&hdev->static_addr, BDADDR_ANY) ||
5027                      hci_dev_test_flag(hdev, HCI_SC_ENABLED))) {
5028                         err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BREDR,
5029                                               MGMT_STATUS_REJECTED);
5030                         goto unlock;
5031                 }
5032         }
5033
5034         if (pending_find(MGMT_OP_SET_BREDR, hdev)) {
5035                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_BREDR,
5036                                       MGMT_STATUS_BUSY);
5037                 goto unlock;
5038         }
5039
5040         cmd = mgmt_pending_add(sk, MGMT_OP_SET_BREDR, hdev, data, len);
5041         if (!cmd) {
5042                 err = -ENOMEM;
5043                 goto unlock;
5044         }
5045
5046         /* We need to flip the bit already here so that update_adv_data
5047          * generates the correct flags.
5048          */
5049         hci_dev_set_flag(hdev, HCI_BREDR_ENABLED);
5050
5051         hci_req_init(&req, hdev);
5052
5053         write_fast_connectable(&req, false);
5054         __hci_update_page_scan(&req);
5055
5056         /* Since only the advertising data flags will change, there
5057          * is no need to update the scan response data.
5058          */
5059         update_adv_data(&req);
5060
5061         err = hci_req_run(&req, set_bredr_complete);
5062         if (err < 0)
5063                 mgmt_pending_remove(cmd);
5064
5065 unlock:
5066         hci_dev_unlock(hdev);
5067         return err;
5068 }
5069
5070 static void sc_enable_complete(struct hci_dev *hdev, u8 status, u16 opcode)
5071 {
5072         struct mgmt_pending_cmd *cmd;
5073         struct mgmt_mode *cp;
5074
5075         BT_DBG("%s status %u", hdev->name, status);
5076
5077         hci_dev_lock(hdev);
5078
5079         cmd = pending_find(MGMT_OP_SET_SECURE_CONN, hdev);
5080         if (!cmd)
5081                 goto unlock;
5082
5083         if (status) {
5084                 mgmt_cmd_status(cmd->sk, cmd->index, cmd->opcode,
5085                                 mgmt_status(status));
5086                 goto remove;
5087         }
5088
5089         cp = cmd->param;
5090
5091         switch (cp->val) {
5092         case 0x00:
5093                 hci_dev_clear_flag(hdev, HCI_SC_ENABLED);
5094                 hci_dev_clear_flag(hdev, HCI_SC_ONLY);
5095                 break;
5096         case 0x01:
5097                 hci_dev_set_flag(hdev, HCI_SC_ENABLED);
5098                 hci_dev_clear_flag(hdev, HCI_SC_ONLY);
5099                 break;
5100         case 0x02:
5101                 hci_dev_set_flag(hdev, HCI_SC_ENABLED);
5102                 hci_dev_set_flag(hdev, HCI_SC_ONLY);
5103                 break;
5104         }
5105
5106         send_settings_rsp(cmd->sk, MGMT_OP_SET_SECURE_CONN, hdev);
5107         new_settings(hdev, cmd->sk);
5108
5109 remove:
5110         mgmt_pending_remove(cmd);
5111 unlock:
5112         hci_dev_unlock(hdev);
5113 }
5114
5115 static int set_secure_conn(struct sock *sk, struct hci_dev *hdev,
5116                            void *data, u16 len)
5117 {
5118         struct mgmt_mode *cp = data;
5119         struct mgmt_pending_cmd *cmd;
5120         struct hci_request req;
5121         u8 val;
5122         int err;
5123
5124         BT_DBG("request for %s", hdev->name);
5125
5126         if (!lmp_sc_capable(hdev) &&
5127             !hci_dev_test_flag(hdev, HCI_LE_ENABLED))
5128                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SECURE_CONN,
5129                                        MGMT_STATUS_NOT_SUPPORTED);
5130
5131         if (hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) &&
5132             lmp_sc_capable(hdev) &&
5133             !hci_dev_test_flag(hdev, HCI_SSP_ENABLED))
5134                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SECURE_CONN,
5135                                        MGMT_STATUS_REJECTED);
5136
5137         if (cp->val != 0x00 && cp->val != 0x01 && cp->val != 0x02)
5138                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SECURE_CONN,
5139                                   MGMT_STATUS_INVALID_PARAMS);
5140
5141         hci_dev_lock(hdev);
5142
5143         if (!hdev_is_powered(hdev) || !lmp_sc_capable(hdev) ||
5144             !hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
5145                 bool changed;
5146
5147                 if (cp->val) {
5148                         changed = !hci_dev_test_and_set_flag(hdev,
5149                                                              HCI_SC_ENABLED);
5150                         if (cp->val == 0x02)
5151                                 hci_dev_set_flag(hdev, HCI_SC_ONLY);
5152                         else
5153                                 hci_dev_clear_flag(hdev, HCI_SC_ONLY);
5154                 } else {
5155                         changed = hci_dev_test_and_clear_flag(hdev,
5156                                                               HCI_SC_ENABLED);
5157                         hci_dev_clear_flag(hdev, HCI_SC_ONLY);
5158                 }
5159
5160                 err = send_settings_rsp(sk, MGMT_OP_SET_SECURE_CONN, hdev);
5161                 if (err < 0)
5162                         goto failed;
5163
5164                 if (changed)
5165                         err = new_settings(hdev, sk);
5166
5167                 goto failed;
5168         }
5169
5170         if (pending_find(MGMT_OP_SET_SECURE_CONN, hdev)) {
5171                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_SECURE_CONN,
5172                                       MGMT_STATUS_BUSY);
5173                 goto failed;
5174         }
5175
5176         val = !!cp->val;
5177
5178         if (val == hci_dev_test_flag(hdev, HCI_SC_ENABLED) &&
5179             (cp->val == 0x02) == hci_dev_test_flag(hdev, HCI_SC_ONLY)) {
5180                 err = send_settings_rsp(sk, MGMT_OP_SET_SECURE_CONN, hdev);
5181                 goto failed;
5182         }
5183
5184         cmd = mgmt_pending_add(sk, MGMT_OP_SET_SECURE_CONN, hdev, data, len);
5185         if (!cmd) {
5186                 err = -ENOMEM;
5187                 goto failed;
5188         }
5189
5190         hci_req_init(&req, hdev);
5191         hci_req_add(&req, HCI_OP_WRITE_SC_SUPPORT, 1, &val);
5192         err = hci_req_run(&req, sc_enable_complete);
5193         if (err < 0) {
5194                 mgmt_pending_remove(cmd);
5195                 goto failed;
5196         }
5197
5198 failed:
5199         hci_dev_unlock(hdev);
5200         return err;
5201 }
5202
5203 static int set_debug_keys(struct sock *sk, struct hci_dev *hdev,
5204                           void *data, u16 len)
5205 {
5206         struct mgmt_mode *cp = data;
5207         bool changed, use_changed;
5208         int err;
5209
5210         BT_DBG("request for %s", hdev->name);
5211
5212         if (cp->val != 0x00 && cp->val != 0x01 && cp->val != 0x02)
5213                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_DEBUG_KEYS,
5214                                        MGMT_STATUS_INVALID_PARAMS);
5215
5216         hci_dev_lock(hdev);
5217
5218         if (cp->val)
5219                 changed = !hci_dev_test_and_set_flag(hdev, HCI_KEEP_DEBUG_KEYS);
5220         else
5221                 changed = hci_dev_test_and_clear_flag(hdev,
5222                                                       HCI_KEEP_DEBUG_KEYS);
5223
5224         if (cp->val == 0x02)
5225                 use_changed = !hci_dev_test_and_set_flag(hdev,
5226                                                          HCI_USE_DEBUG_KEYS);
5227         else
5228                 use_changed = hci_dev_test_and_clear_flag(hdev,
5229                                                           HCI_USE_DEBUG_KEYS);
5230
5231         if (hdev_is_powered(hdev) && use_changed &&
5232             hci_dev_test_flag(hdev, HCI_SSP_ENABLED)) {
5233                 u8 mode = (cp->val == 0x02) ? 0x01 : 0x00;
5234                 hci_send_cmd(hdev, HCI_OP_WRITE_SSP_DEBUG_MODE,
5235                              sizeof(mode), &mode);
5236         }
5237
5238         err = send_settings_rsp(sk, MGMT_OP_SET_DEBUG_KEYS, hdev);
5239         if (err < 0)
5240                 goto unlock;
5241
5242         if (changed)
5243                 err = new_settings(hdev, sk);
5244
5245 unlock:
5246         hci_dev_unlock(hdev);
5247         return err;
5248 }
5249
5250 static int set_privacy(struct sock *sk, struct hci_dev *hdev, void *cp_data,
5251                        u16 len)
5252 {
5253         struct mgmt_cp_set_privacy *cp = cp_data;
5254         bool changed;
5255         int err;
5256
5257         BT_DBG("request for %s", hdev->name);
5258
5259         if (!lmp_le_capable(hdev))
5260                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_PRIVACY,
5261                                        MGMT_STATUS_NOT_SUPPORTED);
5262
5263         if (cp->privacy != 0x00 && cp->privacy != 0x01)
5264                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_PRIVACY,
5265                                        MGMT_STATUS_INVALID_PARAMS);
5266
5267         if (hdev_is_powered(hdev))
5268                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_PRIVACY,
5269                                        MGMT_STATUS_REJECTED);
5270
5271         hci_dev_lock(hdev);
5272
5273         /* If user space supports this command it is also expected to
5274          * handle IRKs. Therefore, set the HCI_RPA_RESOLVING flag.
5275          */
5276         hci_dev_set_flag(hdev, HCI_RPA_RESOLVING);
5277
5278         if (cp->privacy) {
5279                 changed = !hci_dev_test_and_set_flag(hdev, HCI_PRIVACY);
5280                 memcpy(hdev->irk, cp->irk, sizeof(hdev->irk));
5281                 hci_dev_set_flag(hdev, HCI_RPA_EXPIRED);
5282         } else {
5283                 changed = hci_dev_test_and_clear_flag(hdev, HCI_PRIVACY);
5284                 memset(hdev->irk, 0, sizeof(hdev->irk));
5285                 hci_dev_clear_flag(hdev, HCI_RPA_EXPIRED);
5286         }
5287
5288         err = send_settings_rsp(sk, MGMT_OP_SET_PRIVACY, hdev);
5289         if (err < 0)
5290                 goto unlock;
5291
5292         if (changed)
5293                 err = new_settings(hdev, sk);
5294
5295 unlock:
5296         hci_dev_unlock(hdev);
5297         return err;
5298 }
5299
5300 static bool irk_is_valid(struct mgmt_irk_info *irk)
5301 {
5302         switch (irk->addr.type) {
5303         case BDADDR_LE_PUBLIC:
5304                 return true;
5305
5306         case BDADDR_LE_RANDOM:
5307                 /* Two most significant bits shall be set */
5308                 if ((irk->addr.bdaddr.b[5] & 0xc0) != 0xc0)
5309                         return false;
5310                 return true;
5311         }
5312
5313         return false;
5314 }
5315
5316 static int load_irks(struct sock *sk, struct hci_dev *hdev, void *cp_data,
5317                      u16 len)
5318 {
5319         struct mgmt_cp_load_irks *cp = cp_data;
5320         const u16 max_irk_count = ((U16_MAX - sizeof(*cp)) /
5321                                    sizeof(struct mgmt_irk_info));
5322         u16 irk_count, expected_len;
5323         int i, err;
5324
5325         BT_DBG("request for %s", hdev->name);
5326
5327         if (!lmp_le_capable(hdev))
5328                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_IRKS,
5329                                        MGMT_STATUS_NOT_SUPPORTED);
5330
5331         irk_count = __le16_to_cpu(cp->irk_count);
5332         if (irk_count > max_irk_count) {
5333                 BT_ERR("load_irks: too big irk_count value %u", irk_count);
5334                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_IRKS,
5335                                        MGMT_STATUS_INVALID_PARAMS);
5336         }
5337
5338         expected_len = sizeof(*cp) + irk_count * sizeof(struct mgmt_irk_info);
5339         if (expected_len != len) {
5340                 BT_ERR("load_irks: expected %u bytes, got %u bytes",
5341                        expected_len, len);
5342                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_IRKS,
5343                                        MGMT_STATUS_INVALID_PARAMS);
5344         }
5345
5346         BT_DBG("%s irk_count %u", hdev->name, irk_count);
5347
5348         for (i = 0; i < irk_count; i++) {
5349                 struct mgmt_irk_info *key = &cp->irks[i];
5350
5351                 if (!irk_is_valid(key))
5352                         return mgmt_cmd_status(sk, hdev->id,
5353                                                MGMT_OP_LOAD_IRKS,
5354                                                MGMT_STATUS_INVALID_PARAMS);
5355         }
5356
5357         hci_dev_lock(hdev);
5358
5359         hci_smp_irks_clear(hdev);
5360
5361         for (i = 0; i < irk_count; i++) {
5362                 struct mgmt_irk_info *irk = &cp->irks[i];
5363                 u8 addr_type;
5364
5365                 if (irk->addr.type == BDADDR_LE_PUBLIC)
5366                         addr_type = ADDR_LE_DEV_PUBLIC;
5367                 else
5368                         addr_type = ADDR_LE_DEV_RANDOM;
5369
5370                 hci_add_irk(hdev, &irk->addr.bdaddr, addr_type, irk->val,
5371                             BDADDR_ANY);
5372         }
5373
5374         hci_dev_set_flag(hdev, HCI_RPA_RESOLVING);
5375
5376         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_LOAD_IRKS, 0, NULL, 0);
5377
5378         hci_dev_unlock(hdev);
5379
5380         return err;
5381 }
5382
5383 static bool ltk_is_valid(struct mgmt_ltk_info *key)
5384 {
5385         if (key->master != 0x00 && key->master != 0x01)
5386                 return false;
5387
5388         switch (key->addr.type) {
5389         case BDADDR_LE_PUBLIC:
5390                 return true;
5391
5392         case BDADDR_LE_RANDOM:
5393                 /* Two most significant bits shall be set */
5394                 if ((key->addr.bdaddr.b[5] & 0xc0) != 0xc0)
5395                         return false;
5396                 return true;
5397         }
5398
5399         return false;
5400 }
5401
5402 static int load_long_term_keys(struct sock *sk, struct hci_dev *hdev,
5403                                void *cp_data, u16 len)
5404 {
5405         struct mgmt_cp_load_long_term_keys *cp = cp_data;
5406         const u16 max_key_count = ((U16_MAX - sizeof(*cp)) /
5407                                    sizeof(struct mgmt_ltk_info));
5408         u16 key_count, expected_len;
5409         int i, err;
5410
5411         BT_DBG("request for %s", hdev->name);
5412
5413         if (!lmp_le_capable(hdev))
5414                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LONG_TERM_KEYS,
5415                                        MGMT_STATUS_NOT_SUPPORTED);
5416
5417         key_count = __le16_to_cpu(cp->key_count);
5418         if (key_count > max_key_count) {
5419                 BT_ERR("load_ltks: too big key_count value %u", key_count);
5420                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LONG_TERM_KEYS,
5421                                        MGMT_STATUS_INVALID_PARAMS);
5422         }
5423
5424         expected_len = sizeof(*cp) + key_count *
5425                                         sizeof(struct mgmt_ltk_info);
5426         if (expected_len != len) {
5427                 BT_ERR("load_keys: expected %u bytes, got %u bytes",
5428                        expected_len, len);
5429                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_LONG_TERM_KEYS,
5430                                        MGMT_STATUS_INVALID_PARAMS);
5431         }
5432
5433         BT_DBG("%s key_count %u", hdev->name, key_count);
5434
5435         for (i = 0; i < key_count; i++) {
5436                 struct mgmt_ltk_info *key = &cp->keys[i];
5437
5438                 if (!ltk_is_valid(key))
5439                         return mgmt_cmd_status(sk, hdev->id,
5440                                                MGMT_OP_LOAD_LONG_TERM_KEYS,
5441                                                MGMT_STATUS_INVALID_PARAMS);
5442         }
5443
5444         hci_dev_lock(hdev);
5445
5446         hci_smp_ltks_clear(hdev);
5447
5448         for (i = 0; i < key_count; i++) {
5449                 struct mgmt_ltk_info *key = &cp->keys[i];
5450                 u8 type, addr_type, authenticated;
5451
5452                 if (key->addr.type == BDADDR_LE_PUBLIC)
5453                         addr_type = ADDR_LE_DEV_PUBLIC;
5454                 else
5455                         addr_type = ADDR_LE_DEV_RANDOM;
5456
5457                 switch (key->type) {
5458                 case MGMT_LTK_UNAUTHENTICATED:
5459                         authenticated = 0x00;
5460                         type = key->master ? SMP_LTK : SMP_LTK_SLAVE;
5461                         break;
5462                 case MGMT_LTK_AUTHENTICATED:
5463                         authenticated = 0x01;
5464                         type = key->master ? SMP_LTK : SMP_LTK_SLAVE;
5465                         break;
5466                 case MGMT_LTK_P256_UNAUTH:
5467                         authenticated = 0x00;
5468                         type = SMP_LTK_P256;
5469                         break;
5470                 case MGMT_LTK_P256_AUTH:
5471                         authenticated = 0x01;
5472                         type = SMP_LTK_P256;
5473                         break;
5474                 case MGMT_LTK_P256_DEBUG:
5475                         authenticated = 0x00;
5476                         type = SMP_LTK_P256_DEBUG;
5477                 default:
5478                         continue;
5479                 }
5480
5481                 hci_add_ltk(hdev, &key->addr.bdaddr, addr_type, type,
5482                             authenticated, key->val, key->enc_size, key->ediv,
5483                             key->rand);
5484         }
5485
5486         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_LOAD_LONG_TERM_KEYS, 0,
5487                            NULL, 0);
5488
5489         hci_dev_unlock(hdev);
5490
5491         return err;
5492 }
5493
5494 static int conn_info_cmd_complete(struct mgmt_pending_cmd *cmd, u8 status)
5495 {
5496         struct hci_conn *conn = cmd->user_data;
5497         struct mgmt_rp_get_conn_info rp;
5498         int err;
5499
5500         memcpy(&rp.addr, cmd->param, sizeof(rp.addr));
5501
5502         if (status == MGMT_STATUS_SUCCESS) {
5503                 rp.rssi = conn->rssi;
5504                 rp.tx_power = conn->tx_power;
5505                 rp.max_tx_power = conn->max_tx_power;
5506         } else {
5507                 rp.rssi = HCI_RSSI_INVALID;
5508                 rp.tx_power = HCI_TX_POWER_INVALID;
5509                 rp.max_tx_power = HCI_TX_POWER_INVALID;
5510         }
5511
5512         err = mgmt_cmd_complete(cmd->sk, cmd->index, MGMT_OP_GET_CONN_INFO,
5513                                 status, &rp, sizeof(rp));
5514
5515         hci_conn_drop(conn);
5516         hci_conn_put(conn);
5517
5518         return err;
5519 }
5520
5521 static void conn_info_refresh_complete(struct hci_dev *hdev, u8 hci_status,
5522                                        u16 opcode)
5523 {
5524         struct hci_cp_read_rssi *cp;
5525         struct mgmt_pending_cmd *cmd;
5526         struct hci_conn *conn;
5527         u16 handle;
5528         u8 status;
5529
5530         BT_DBG("status 0x%02x", hci_status);
5531
5532         hci_dev_lock(hdev);
5533
5534         /* Commands sent in request are either Read RSSI or Read Transmit Power
5535          * Level so we check which one was last sent to retrieve connection
5536          * handle.  Both commands have handle as first parameter so it's safe to
5537          * cast data on the same command struct.
5538          *
5539          * First command sent is always Read RSSI and we fail only if it fails.
5540          * In other case we simply override error to indicate success as we
5541          * already remembered if TX power value is actually valid.
5542          */
5543         cp = hci_sent_cmd_data(hdev, HCI_OP_READ_RSSI);
5544         if (!cp) {
5545                 cp = hci_sent_cmd_data(hdev, HCI_OP_READ_TX_POWER);
5546                 status = MGMT_STATUS_SUCCESS;
5547         } else {
5548                 status = mgmt_status(hci_status);
5549         }
5550
5551         if (!cp) {
5552                 BT_ERR("invalid sent_cmd in conn_info response");
5553                 goto unlock;
5554         }
5555
5556         handle = __le16_to_cpu(cp->handle);
5557         conn = hci_conn_hash_lookup_handle(hdev, handle);
5558         if (!conn) {
5559                 BT_ERR("unknown handle (%d) in conn_info response", handle);
5560                 goto unlock;
5561         }
5562
5563         cmd = pending_find_data(MGMT_OP_GET_CONN_INFO, hdev, conn);
5564         if (!cmd)
5565                 goto unlock;
5566
5567         cmd->cmd_complete(cmd, status);
5568         mgmt_pending_remove(cmd);
5569
5570 unlock:
5571         hci_dev_unlock(hdev);
5572 }
5573
5574 static int get_conn_info(struct sock *sk, struct hci_dev *hdev, void *data,
5575                          u16 len)
5576 {
5577         struct mgmt_cp_get_conn_info *cp = data;
5578         struct mgmt_rp_get_conn_info rp;
5579         struct hci_conn *conn;
5580         unsigned long conn_info_age;
5581         int err = 0;
5582
5583         BT_DBG("%s", hdev->name);
5584
5585         memset(&rp, 0, sizeof(rp));
5586         bacpy(&rp.addr.bdaddr, &cp->addr.bdaddr);
5587         rp.addr.type = cp->addr.type;
5588
5589         if (!bdaddr_type_is_valid(cp->addr.type))
5590                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CONN_INFO,
5591                                          MGMT_STATUS_INVALID_PARAMS,
5592                                          &rp, sizeof(rp));
5593
5594         hci_dev_lock(hdev);
5595
5596         if (!hdev_is_powered(hdev)) {
5597                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CONN_INFO,
5598                                         MGMT_STATUS_NOT_POWERED, &rp,
5599                                         sizeof(rp));
5600                 goto unlock;
5601         }
5602
5603         if (cp->addr.type == BDADDR_BREDR)
5604                 conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK,
5605                                                &cp->addr.bdaddr);
5606         else
5607                 conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, &cp->addr.bdaddr);
5608
5609         if (!conn || conn->state != BT_CONNECTED) {
5610                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CONN_INFO,
5611                                         MGMT_STATUS_NOT_CONNECTED, &rp,
5612                                         sizeof(rp));
5613                 goto unlock;
5614         }
5615
5616         if (pending_find_data(MGMT_OP_GET_CONN_INFO, hdev, conn)) {
5617                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CONN_INFO,
5618                                         MGMT_STATUS_BUSY, &rp, sizeof(rp));
5619                 goto unlock;
5620         }
5621
5622         /* To avoid client trying to guess when to poll again for information we
5623          * calculate conn info age as random value between min/max set in hdev.
5624          */
5625         conn_info_age = hdev->conn_info_min_age +
5626                         prandom_u32_max(hdev->conn_info_max_age -
5627                                         hdev->conn_info_min_age);
5628
5629         /* Query controller to refresh cached values if they are too old or were
5630          * never read.
5631          */
5632         if (time_after(jiffies, conn->conn_info_timestamp +
5633                        msecs_to_jiffies(conn_info_age)) ||
5634             !conn->conn_info_timestamp) {
5635                 struct hci_request req;
5636                 struct hci_cp_read_tx_power req_txp_cp;
5637                 struct hci_cp_read_rssi req_rssi_cp;
5638                 struct mgmt_pending_cmd *cmd;
5639
5640                 hci_req_init(&req, hdev);
5641                 req_rssi_cp.handle = cpu_to_le16(conn->handle);
5642                 hci_req_add(&req, HCI_OP_READ_RSSI, sizeof(req_rssi_cp),
5643                             &req_rssi_cp);
5644
5645                 /* For LE links TX power does not change thus we don't need to
5646                  * query for it once value is known.
5647                  */
5648                 if (!bdaddr_type_is_le(cp->addr.type) ||
5649                     conn->tx_power == HCI_TX_POWER_INVALID) {
5650                         req_txp_cp.handle = cpu_to_le16(conn->handle);
5651                         req_txp_cp.type = 0x00;
5652                         hci_req_add(&req, HCI_OP_READ_TX_POWER,
5653                                     sizeof(req_txp_cp), &req_txp_cp);
5654                 }
5655
5656                 /* Max TX power needs to be read only once per connection */
5657                 if (conn->max_tx_power == HCI_TX_POWER_INVALID) {
5658                         req_txp_cp.handle = cpu_to_le16(conn->handle);
5659                         req_txp_cp.type = 0x01;
5660                         hci_req_add(&req, HCI_OP_READ_TX_POWER,
5661                                     sizeof(req_txp_cp), &req_txp_cp);
5662                 }
5663
5664                 err = hci_req_run(&req, conn_info_refresh_complete);
5665                 if (err < 0)
5666                         goto unlock;
5667
5668                 cmd = mgmt_pending_add(sk, MGMT_OP_GET_CONN_INFO, hdev,
5669                                        data, len);
5670                 if (!cmd) {
5671                         err = -ENOMEM;
5672                         goto unlock;
5673                 }
5674
5675                 hci_conn_hold(conn);
5676                 cmd->user_data = hci_conn_get(conn);
5677                 cmd->cmd_complete = conn_info_cmd_complete;
5678
5679                 conn->conn_info_timestamp = jiffies;
5680         } else {
5681                 /* Cache is valid, just reply with values cached in hci_conn */
5682                 rp.rssi = conn->rssi;
5683                 rp.tx_power = conn->tx_power;
5684                 rp.max_tx_power = conn->max_tx_power;
5685
5686                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CONN_INFO,
5687                                         MGMT_STATUS_SUCCESS, &rp, sizeof(rp));
5688         }
5689
5690 unlock:
5691         hci_dev_unlock(hdev);
5692         return err;
5693 }
5694
5695 static int clock_info_cmd_complete(struct mgmt_pending_cmd *cmd, u8 status)
5696 {
5697         struct hci_conn *conn = cmd->user_data;
5698         struct mgmt_rp_get_clock_info rp;
5699         struct hci_dev *hdev;
5700         int err;
5701
5702         memset(&rp, 0, sizeof(rp));
5703         memcpy(&rp.addr, &cmd->param, sizeof(rp.addr));
5704
5705         if (status)
5706                 goto complete;
5707
5708         hdev = hci_dev_get(cmd->index);
5709         if (hdev) {
5710                 rp.local_clock = cpu_to_le32(hdev->clock);
5711                 hci_dev_put(hdev);
5712         }
5713
5714         if (conn) {
5715                 rp.piconet_clock = cpu_to_le32(conn->clock);
5716                 rp.accuracy = cpu_to_le16(conn->clock_accuracy);
5717         }
5718
5719 complete:
5720         err = mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode, status, &rp,
5721                                 sizeof(rp));
5722
5723         if (conn) {
5724                 hci_conn_drop(conn);
5725                 hci_conn_put(conn);
5726         }
5727
5728         return err;
5729 }
5730
5731 static void get_clock_info_complete(struct hci_dev *hdev, u8 status, u16 opcode)
5732 {
5733         struct hci_cp_read_clock *hci_cp;
5734         struct mgmt_pending_cmd *cmd;
5735         struct hci_conn *conn;
5736
5737         BT_DBG("%s status %u", hdev->name, status);
5738
5739         hci_dev_lock(hdev);
5740
5741         hci_cp = hci_sent_cmd_data(hdev, HCI_OP_READ_CLOCK);
5742         if (!hci_cp)
5743                 goto unlock;
5744
5745         if (hci_cp->which) {
5746                 u16 handle = __le16_to_cpu(hci_cp->handle);
5747                 conn = hci_conn_hash_lookup_handle(hdev, handle);
5748         } else {
5749                 conn = NULL;
5750         }
5751
5752         cmd = pending_find_data(MGMT_OP_GET_CLOCK_INFO, hdev, conn);
5753         if (!cmd)
5754                 goto unlock;
5755
5756         cmd->cmd_complete(cmd, mgmt_status(status));
5757         mgmt_pending_remove(cmd);
5758
5759 unlock:
5760         hci_dev_unlock(hdev);
5761 }
5762
5763 static int get_clock_info(struct sock *sk, struct hci_dev *hdev, void *data,
5764                          u16 len)
5765 {
5766         struct mgmt_cp_get_clock_info *cp = data;
5767         struct mgmt_rp_get_clock_info rp;
5768         struct hci_cp_read_clock hci_cp;
5769         struct mgmt_pending_cmd *cmd;
5770         struct hci_request req;
5771         struct hci_conn *conn;
5772         int err;
5773
5774         BT_DBG("%s", hdev->name);
5775
5776         memset(&rp, 0, sizeof(rp));
5777         bacpy(&rp.addr.bdaddr, &cp->addr.bdaddr);
5778         rp.addr.type = cp->addr.type;
5779
5780         if (cp->addr.type != BDADDR_BREDR)
5781                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CLOCK_INFO,
5782                                          MGMT_STATUS_INVALID_PARAMS,
5783                                          &rp, sizeof(rp));
5784
5785         hci_dev_lock(hdev);
5786
5787         if (!hdev_is_powered(hdev)) {
5788                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_GET_CLOCK_INFO,
5789                                         MGMT_STATUS_NOT_POWERED, &rp,
5790                                         sizeof(rp));
5791                 goto unlock;
5792         }
5793
5794         if (bacmp(&cp->addr.bdaddr, BDADDR_ANY)) {
5795                 conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK,
5796                                                &cp->addr.bdaddr);
5797                 if (!conn || conn->state != BT_CONNECTED) {
5798                         err = mgmt_cmd_complete(sk, hdev->id,
5799                                                 MGMT_OP_GET_CLOCK_INFO,
5800                                                 MGMT_STATUS_NOT_CONNECTED,
5801                                                 &rp, sizeof(rp));
5802                         goto unlock;
5803                 }
5804         } else {
5805                 conn = NULL;
5806         }
5807
5808         cmd = mgmt_pending_add(sk, MGMT_OP_GET_CLOCK_INFO, hdev, data, len);
5809         if (!cmd) {
5810                 err = -ENOMEM;
5811                 goto unlock;
5812         }
5813
5814         cmd->cmd_complete = clock_info_cmd_complete;
5815
5816         hci_req_init(&req, hdev);
5817
5818         memset(&hci_cp, 0, sizeof(hci_cp));
5819         hci_req_add(&req, HCI_OP_READ_CLOCK, sizeof(hci_cp), &hci_cp);
5820
5821         if (conn) {
5822                 hci_conn_hold(conn);
5823                 cmd->user_data = hci_conn_get(conn);
5824
5825                 hci_cp.handle = cpu_to_le16(conn->handle);
5826                 hci_cp.which = 0x01; /* Piconet clock */
5827                 hci_req_add(&req, HCI_OP_READ_CLOCK, sizeof(hci_cp), &hci_cp);
5828         }
5829
5830         err = hci_req_run(&req, get_clock_info_complete);
5831         if (err < 0)
5832                 mgmt_pending_remove(cmd);
5833
5834 unlock:
5835         hci_dev_unlock(hdev);
5836         return err;
5837 }
5838
5839 static bool is_connected(struct hci_dev *hdev, bdaddr_t *addr, u8 type)
5840 {
5841         struct hci_conn *conn;
5842
5843         conn = hci_conn_hash_lookup_ba(hdev, LE_LINK, addr);
5844         if (!conn)
5845                 return false;
5846
5847         if (conn->dst_type != type)
5848                 return false;
5849
5850         if (conn->state != BT_CONNECTED)
5851                 return false;
5852
5853         return true;
5854 }
5855
5856 /* This function requires the caller holds hdev->lock */
5857 static int hci_conn_params_set(struct hci_request *req, bdaddr_t *addr,
5858                                u8 addr_type, u8 auto_connect)
5859 {
5860         struct hci_dev *hdev = req->hdev;
5861         struct hci_conn_params *params;
5862
5863         params = hci_conn_params_add(hdev, addr, addr_type);
5864         if (!params)
5865                 return -EIO;
5866
5867         if (params->auto_connect == auto_connect)
5868                 return 0;
5869
5870         list_del_init(&params->action);
5871
5872         switch (auto_connect) {
5873         case HCI_AUTO_CONN_DISABLED:
5874         case HCI_AUTO_CONN_LINK_LOSS:
5875                 __hci_update_background_scan(req);
5876                 break;
5877         case HCI_AUTO_CONN_REPORT:
5878                 list_add(&params->action, &hdev->pend_le_reports);
5879                 __hci_update_background_scan(req);
5880                 break;
5881         case HCI_AUTO_CONN_DIRECT:
5882         case HCI_AUTO_CONN_ALWAYS:
5883                 if (!is_connected(hdev, addr, addr_type)) {
5884                         list_add(&params->action, &hdev->pend_le_conns);
5885                         __hci_update_background_scan(req);
5886                 }
5887                 break;
5888         }
5889
5890         params->auto_connect = auto_connect;
5891
5892         BT_DBG("addr %pMR (type %u) auto_connect %u", addr, addr_type,
5893                auto_connect);
5894
5895         return 0;
5896 }
5897
5898 static void device_added(struct sock *sk, struct hci_dev *hdev,
5899                          bdaddr_t *bdaddr, u8 type, u8 action)
5900 {
5901         struct mgmt_ev_device_added ev;
5902
5903         bacpy(&ev.addr.bdaddr, bdaddr);
5904         ev.addr.type = type;
5905         ev.action = action;
5906
5907         mgmt_event(MGMT_EV_DEVICE_ADDED, hdev, &ev, sizeof(ev), sk);
5908 }
5909
5910 static void add_device_complete(struct hci_dev *hdev, u8 status, u16 opcode)
5911 {
5912         struct mgmt_pending_cmd *cmd;
5913
5914         BT_DBG("status 0x%02x", status);
5915
5916         hci_dev_lock(hdev);
5917
5918         cmd = pending_find(MGMT_OP_ADD_DEVICE, hdev);
5919         if (!cmd)
5920                 goto unlock;
5921
5922         cmd->cmd_complete(cmd, mgmt_status(status));
5923         mgmt_pending_remove(cmd);
5924
5925 unlock:
5926         hci_dev_unlock(hdev);
5927 }
5928
5929 static int add_device(struct sock *sk, struct hci_dev *hdev,
5930                       void *data, u16 len)
5931 {
5932         struct mgmt_cp_add_device *cp = data;
5933         struct mgmt_pending_cmd *cmd;
5934         struct hci_request req;
5935         u8 auto_conn, addr_type;
5936         int err;
5937
5938         BT_DBG("%s", hdev->name);
5939
5940         if (!bdaddr_type_is_valid(cp->addr.type) ||
5941             !bacmp(&cp->addr.bdaddr, BDADDR_ANY))
5942                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_ADD_DEVICE,
5943                                          MGMT_STATUS_INVALID_PARAMS,
5944                                          &cp->addr, sizeof(cp->addr));
5945
5946         if (cp->action != 0x00 && cp->action != 0x01 && cp->action != 0x02)
5947                 return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_ADD_DEVICE,
5948                                          MGMT_STATUS_INVALID_PARAMS,
5949                                          &cp->addr, sizeof(cp->addr));
5950
5951         hci_req_init(&req, hdev);
5952
5953         hci_dev_lock(hdev);
5954
5955         cmd = mgmt_pending_add(sk, MGMT_OP_ADD_DEVICE, hdev, data, len);
5956         if (!cmd) {
5957                 err = -ENOMEM;
5958                 goto unlock;
5959         }
5960
5961         cmd->cmd_complete = addr_cmd_complete;
5962
5963         if (cp->addr.type == BDADDR_BREDR) {
5964                 /* Only incoming connections action is supported for now */
5965                 if (cp->action != 0x01) {
5966                         err = cmd->cmd_complete(cmd,
5967                                                 MGMT_STATUS_INVALID_PARAMS);
5968                         mgmt_pending_remove(cmd);
5969                         goto unlock;
5970                 }
5971
5972                 err = hci_bdaddr_list_add(&hdev->whitelist, &cp->addr.bdaddr,
5973                                           cp->addr.type);
5974                 if (err)
5975                         goto unlock;
5976
5977                 __hci_update_page_scan(&req);
5978
5979                 goto added;
5980         }
5981
5982         if (cp->addr.type == BDADDR_LE_PUBLIC)
5983                 addr_type = ADDR_LE_DEV_PUBLIC;
5984         else
5985                 addr_type = ADDR_LE_DEV_RANDOM;
5986
5987         if (cp->action == 0x02)
5988                 auto_conn = HCI_AUTO_CONN_ALWAYS;
5989         else if (cp->action == 0x01)
5990                 auto_conn = HCI_AUTO_CONN_DIRECT;
5991         else
5992                 auto_conn = HCI_AUTO_CONN_REPORT;
5993
5994         /* If the connection parameters don't exist for this device,
5995          * they will be created and configured with defaults.
5996          */
5997         if (hci_conn_params_set(&req, &cp->addr.bdaddr, addr_type,
5998                                 auto_conn) < 0) {
5999                 err = cmd->cmd_complete(cmd, MGMT_STATUS_FAILED);
6000                 mgmt_pending_remove(cmd);
6001                 goto unlock;
6002         }
6003
6004 added:
6005         device_added(sk, hdev, &cp->addr.bdaddr, cp->addr.type, cp->action);
6006
6007         err = hci_req_run(&req, add_device_complete);
6008         if (err < 0) {
6009                 /* ENODATA means no HCI commands were needed (e.g. if
6010                  * the adapter is powered off).
6011                  */
6012                 if (err == -ENODATA)
6013                         err = cmd->cmd_complete(cmd, MGMT_STATUS_SUCCESS);
6014                 mgmt_pending_remove(cmd);
6015         }
6016
6017 unlock:
6018         hci_dev_unlock(hdev);
6019         return err;
6020 }
6021
6022 static void device_removed(struct sock *sk, struct hci_dev *hdev,
6023                            bdaddr_t *bdaddr, u8 type)
6024 {
6025         struct mgmt_ev_device_removed ev;
6026
6027         bacpy(&ev.addr.bdaddr, bdaddr);
6028         ev.addr.type = type;
6029
6030         mgmt_event(MGMT_EV_DEVICE_REMOVED, hdev, &ev, sizeof(ev), sk);
6031 }
6032
6033 static void remove_device_complete(struct hci_dev *hdev, u8 status, u16 opcode)
6034 {
6035         struct mgmt_pending_cmd *cmd;
6036
6037         BT_DBG("status 0x%02x", status);
6038
6039         hci_dev_lock(hdev);
6040
6041         cmd = pending_find(MGMT_OP_REMOVE_DEVICE, hdev);
6042         if (!cmd)
6043                 goto unlock;
6044
6045         cmd->cmd_complete(cmd, mgmt_status(status));
6046         mgmt_pending_remove(cmd);
6047
6048 unlock:
6049         hci_dev_unlock(hdev);
6050 }
6051
6052 static int remove_device(struct sock *sk, struct hci_dev *hdev,
6053                          void *data, u16 len)
6054 {
6055         struct mgmt_cp_remove_device *cp = data;
6056         struct mgmt_pending_cmd *cmd;
6057         struct hci_request req;
6058         int err;
6059
6060         BT_DBG("%s", hdev->name);
6061
6062         hci_req_init(&req, hdev);
6063
6064         hci_dev_lock(hdev);
6065
6066         cmd = mgmt_pending_add(sk, MGMT_OP_REMOVE_DEVICE, hdev, data, len);
6067         if (!cmd) {
6068                 err = -ENOMEM;
6069                 goto unlock;
6070         }
6071
6072         cmd->cmd_complete = addr_cmd_complete;
6073
6074         if (bacmp(&cp->addr.bdaddr, BDADDR_ANY)) {
6075                 struct hci_conn_params *params;
6076                 u8 addr_type;
6077
6078                 if (!bdaddr_type_is_valid(cp->addr.type)) {
6079                         err = cmd->cmd_complete(cmd,
6080                                                 MGMT_STATUS_INVALID_PARAMS);
6081                         mgmt_pending_remove(cmd);
6082                         goto unlock;
6083                 }
6084
6085                 if (cp->addr.type == BDADDR_BREDR) {
6086                         err = hci_bdaddr_list_del(&hdev->whitelist,
6087                                                   &cp->addr.bdaddr,
6088                                                   cp->addr.type);
6089                         if (err) {
6090                                 err = cmd->cmd_complete(cmd,
6091                                                         MGMT_STATUS_INVALID_PARAMS);
6092                                 mgmt_pending_remove(cmd);
6093                                 goto unlock;
6094                         }
6095
6096                         __hci_update_page_scan(&req);
6097
6098                         device_removed(sk, hdev, &cp->addr.bdaddr,
6099                                        cp->addr.type);
6100                         goto complete;
6101                 }
6102
6103                 if (cp->addr.type == BDADDR_LE_PUBLIC)
6104                         addr_type = ADDR_LE_DEV_PUBLIC;
6105                 else
6106                         addr_type = ADDR_LE_DEV_RANDOM;
6107
6108                 params = hci_conn_params_lookup(hdev, &cp->addr.bdaddr,
6109                                                 addr_type);
6110                 if (!params) {
6111                         err = cmd->cmd_complete(cmd,
6112                                                 MGMT_STATUS_INVALID_PARAMS);
6113                         mgmt_pending_remove(cmd);
6114                         goto unlock;
6115                 }
6116
6117                 if (params->auto_connect == HCI_AUTO_CONN_DISABLED) {
6118                         err = cmd->cmd_complete(cmd,
6119                                                 MGMT_STATUS_INVALID_PARAMS);
6120                         mgmt_pending_remove(cmd);
6121                         goto unlock;
6122                 }
6123
6124                 list_del(&params->action);
6125                 list_del(&params->list);
6126                 kfree(params);
6127                 __hci_update_background_scan(&req);
6128
6129                 device_removed(sk, hdev, &cp->addr.bdaddr, cp->addr.type);
6130         } else {
6131                 struct hci_conn_params *p, *tmp;
6132                 struct bdaddr_list *b, *btmp;
6133
6134                 if (cp->addr.type) {
6135                         err = cmd->cmd_complete(cmd,
6136                                                 MGMT_STATUS_INVALID_PARAMS);
6137                         mgmt_pending_remove(cmd);
6138                         goto unlock;
6139                 }
6140
6141                 list_for_each_entry_safe(b, btmp, &hdev->whitelist, list) {
6142                         device_removed(sk, hdev, &b->bdaddr, b->bdaddr_type);
6143                         list_del(&b->list);
6144                         kfree(b);
6145                 }
6146
6147                 __hci_update_page_scan(&req);
6148
6149                 list_for_each_entry_safe(p, tmp, &hdev->le_conn_params, list) {
6150                         if (p->auto_connect == HCI_AUTO_CONN_DISABLED)
6151                                 continue;
6152                         device_removed(sk, hdev, &p->addr, p->addr_type);
6153                         list_del(&p->action);
6154                         list_del(&p->list);
6155                         kfree(p);
6156                 }
6157
6158                 BT_DBG("All LE connection parameters were removed");
6159
6160                 __hci_update_background_scan(&req);
6161         }
6162
6163 complete:
6164         err = hci_req_run(&req, remove_device_complete);
6165         if (err < 0) {
6166                 /* ENODATA means no HCI commands were needed (e.g. if
6167                  * the adapter is powered off).
6168                  */
6169                 if (err == -ENODATA)
6170                         err = cmd->cmd_complete(cmd, MGMT_STATUS_SUCCESS);
6171                 mgmt_pending_remove(cmd);
6172         }
6173
6174 unlock:
6175         hci_dev_unlock(hdev);
6176         return err;
6177 }
6178
6179 static int load_conn_param(struct sock *sk, struct hci_dev *hdev, void *data,
6180                            u16 len)
6181 {
6182         struct mgmt_cp_load_conn_param *cp = data;
6183         const u16 max_param_count = ((U16_MAX - sizeof(*cp)) /
6184                                      sizeof(struct mgmt_conn_param));
6185         u16 param_count, expected_len;
6186         int i;
6187
6188         if (!lmp_le_capable(hdev))
6189                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_CONN_PARAM,
6190                                        MGMT_STATUS_NOT_SUPPORTED);
6191
6192         param_count = __le16_to_cpu(cp->param_count);
6193         if (param_count > max_param_count) {
6194                 BT_ERR("load_conn_param: too big param_count value %u",
6195                        param_count);
6196                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_CONN_PARAM,
6197                                        MGMT_STATUS_INVALID_PARAMS);
6198         }
6199
6200         expected_len = sizeof(*cp) + param_count *
6201                                         sizeof(struct mgmt_conn_param);
6202         if (expected_len != len) {
6203                 BT_ERR("load_conn_param: expected %u bytes, got %u bytes",
6204                        expected_len, len);
6205                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_LOAD_CONN_PARAM,
6206                                        MGMT_STATUS_INVALID_PARAMS);
6207         }
6208
6209         BT_DBG("%s param_count %u", hdev->name, param_count);
6210
6211         hci_dev_lock(hdev);
6212
6213         hci_conn_params_clear_disabled(hdev);
6214
6215         for (i = 0; i < param_count; i++) {
6216                 struct mgmt_conn_param *param = &cp->params[i];
6217                 struct hci_conn_params *hci_param;
6218                 u16 min, max, latency, timeout;
6219                 u8 addr_type;
6220
6221                 BT_DBG("Adding %pMR (type %u)", &param->addr.bdaddr,
6222                        param->addr.type);
6223
6224                 if (param->addr.type == BDADDR_LE_PUBLIC) {
6225                         addr_type = ADDR_LE_DEV_PUBLIC;
6226                 } else if (param->addr.type == BDADDR_LE_RANDOM) {
6227                         addr_type = ADDR_LE_DEV_RANDOM;
6228                 } else {
6229                         BT_ERR("Ignoring invalid connection parameters");
6230                         continue;
6231                 }
6232
6233                 min = le16_to_cpu(param->min_interval);
6234                 max = le16_to_cpu(param->max_interval);
6235                 latency = le16_to_cpu(param->latency);
6236                 timeout = le16_to_cpu(param->timeout);
6237
6238                 BT_DBG("min 0x%04x max 0x%04x latency 0x%04x timeout 0x%04x",
6239                        min, max, latency, timeout);
6240
6241                 if (hci_check_conn_params(min, max, latency, timeout) < 0) {
6242                         BT_ERR("Ignoring invalid connection parameters");
6243                         continue;
6244                 }
6245
6246                 hci_param = hci_conn_params_add(hdev, &param->addr.bdaddr,
6247                                                 addr_type);
6248                 if (!hci_param) {
6249                         BT_ERR("Failed to add connection parameters");
6250                         continue;
6251                 }
6252
6253                 hci_param->conn_min_interval = min;
6254                 hci_param->conn_max_interval = max;
6255                 hci_param->conn_latency = latency;
6256                 hci_param->supervision_timeout = timeout;
6257         }
6258
6259         hci_dev_unlock(hdev);
6260
6261         return mgmt_cmd_complete(sk, hdev->id, MGMT_OP_LOAD_CONN_PARAM, 0,
6262                                  NULL, 0);
6263 }
6264
6265 static int set_external_config(struct sock *sk, struct hci_dev *hdev,
6266                                void *data, u16 len)
6267 {
6268         struct mgmt_cp_set_external_config *cp = data;
6269         bool changed;
6270         int err;
6271
6272         BT_DBG("%s", hdev->name);
6273
6274         if (hdev_is_powered(hdev))
6275                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_EXTERNAL_CONFIG,
6276                                        MGMT_STATUS_REJECTED);
6277
6278         if (cp->config != 0x00 && cp->config != 0x01)
6279                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_EXTERNAL_CONFIG,
6280                                          MGMT_STATUS_INVALID_PARAMS);
6281
6282         if (!test_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks))
6283                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_EXTERNAL_CONFIG,
6284                                        MGMT_STATUS_NOT_SUPPORTED);
6285
6286         hci_dev_lock(hdev);
6287
6288         if (cp->config)
6289                 changed = !hci_dev_test_and_set_flag(hdev, HCI_EXT_CONFIGURED);
6290         else
6291                 changed = hci_dev_test_and_clear_flag(hdev, HCI_EXT_CONFIGURED);
6292
6293         err = send_options_rsp(sk, MGMT_OP_SET_EXTERNAL_CONFIG, hdev);
6294         if (err < 0)
6295                 goto unlock;
6296
6297         if (!changed)
6298                 goto unlock;
6299
6300         err = new_options(hdev, sk);
6301
6302         if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED) == is_configured(hdev)) {
6303                 mgmt_index_removed(hdev);
6304
6305                 if (hci_dev_test_and_change_flag(hdev, HCI_UNCONFIGURED)) {
6306                         hci_dev_set_flag(hdev, HCI_CONFIG);
6307                         hci_dev_set_flag(hdev, HCI_AUTO_OFF);
6308
6309                         queue_work(hdev->req_workqueue, &hdev->power_on);
6310                 } else {
6311                         set_bit(HCI_RAW, &hdev->flags);
6312                         mgmt_index_added(hdev);
6313                 }
6314         }
6315
6316 unlock:
6317         hci_dev_unlock(hdev);
6318         return err;
6319 }
6320
6321 static int set_public_address(struct sock *sk, struct hci_dev *hdev,
6322                               void *data, u16 len)
6323 {
6324         struct mgmt_cp_set_public_address *cp = data;
6325         bool changed;
6326         int err;
6327
6328         BT_DBG("%s", hdev->name);
6329
6330         if (hdev_is_powered(hdev))
6331                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_PUBLIC_ADDRESS,
6332                                        MGMT_STATUS_REJECTED);
6333
6334         if (!bacmp(&cp->bdaddr, BDADDR_ANY))
6335                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_PUBLIC_ADDRESS,
6336                                        MGMT_STATUS_INVALID_PARAMS);
6337
6338         if (!hdev->set_bdaddr)
6339                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_SET_PUBLIC_ADDRESS,
6340                                        MGMT_STATUS_NOT_SUPPORTED);
6341
6342         hci_dev_lock(hdev);
6343
6344         changed = !!bacmp(&hdev->public_addr, &cp->bdaddr);
6345         bacpy(&hdev->public_addr, &cp->bdaddr);
6346
6347         err = send_options_rsp(sk, MGMT_OP_SET_PUBLIC_ADDRESS, hdev);
6348         if (err < 0)
6349                 goto unlock;
6350
6351         if (!changed)
6352                 goto unlock;
6353
6354         if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED))
6355                 err = new_options(hdev, sk);
6356
6357         if (is_configured(hdev)) {
6358                 mgmt_index_removed(hdev);
6359
6360                 hci_dev_clear_flag(hdev, HCI_UNCONFIGURED);
6361
6362                 hci_dev_set_flag(hdev, HCI_CONFIG);
6363                 hci_dev_set_flag(hdev, HCI_AUTO_OFF);
6364
6365                 queue_work(hdev->req_workqueue, &hdev->power_on);
6366         }
6367
6368 unlock:
6369         hci_dev_unlock(hdev);
6370         return err;
6371 }
6372
6373 static inline u16 eir_append_data(u8 *eir, u16 eir_len, u8 type, u8 *data,
6374                                   u8 data_len)
6375 {
6376         eir[eir_len++] = sizeof(type) + data_len;
6377         eir[eir_len++] = type;
6378         memcpy(&eir[eir_len], data, data_len);
6379         eir_len += data_len;
6380
6381         return eir_len;
6382 }
6383
6384 static int read_local_oob_ext_data(struct sock *sk, struct hci_dev *hdev,
6385                                    void *data, u16 data_len)
6386 {
6387         struct mgmt_cp_read_local_oob_ext_data *cp = data;
6388         struct mgmt_rp_read_local_oob_ext_data *rp;
6389         size_t rp_len;
6390         u16 eir_len;
6391         u8 status, flags, role, addr[7], hash[16], rand[16];
6392         int err;
6393
6394         BT_DBG("%s", hdev->name);
6395
6396         if (!hdev_is_powered(hdev))
6397                 return mgmt_cmd_complete(sk, hdev->id,
6398                                          MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
6399                                          MGMT_STATUS_NOT_POWERED,
6400                                          &cp->type, sizeof(cp->type));
6401
6402         switch (cp->type) {
6403         case BIT(BDADDR_BREDR):
6404                 status = mgmt_bredr_support(hdev);
6405                 if (status)
6406                         return mgmt_cmd_complete(sk, hdev->id,
6407                                                  MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
6408                                                  status, &cp->type,
6409                                                  sizeof(cp->type));
6410                 eir_len = 5;
6411                 break;
6412         case (BIT(BDADDR_LE_PUBLIC) | BIT(BDADDR_LE_RANDOM)):
6413                 status = mgmt_le_support(hdev);
6414                 if (status)
6415                         return mgmt_cmd_complete(sk, hdev->id,
6416                                                  MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
6417                                                  status, &cp->type,
6418                                                  sizeof(cp->type));
6419                 eir_len = 9 + 3 + 18 + 18 + 3;
6420                 break;
6421         default:
6422                 return mgmt_cmd_complete(sk, hdev->id,
6423                                          MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
6424                                          MGMT_STATUS_INVALID_PARAMS,
6425                                          &cp->type, sizeof(cp->type));
6426         }
6427
6428         hci_dev_lock(hdev);
6429
6430         rp_len = sizeof(*rp) + eir_len;
6431         rp = kmalloc(rp_len, GFP_ATOMIC);
6432         if (!rp) {
6433                 hci_dev_unlock(hdev);
6434                 return -ENOMEM;
6435         }
6436
6437         eir_len = 0;
6438         switch (cp->type) {
6439         case BIT(BDADDR_BREDR):
6440                 eir_len = eir_append_data(rp->eir, eir_len, EIR_CLASS_OF_DEV,
6441                                           hdev->dev_class, 3);
6442                 break;
6443         case (BIT(BDADDR_LE_PUBLIC) | BIT(BDADDR_LE_RANDOM)):
6444                 if (hci_dev_test_flag(hdev, HCI_SC_ENABLED) &&
6445                     smp_generate_oob(hdev, hash, rand) < 0) {
6446                         hci_dev_unlock(hdev);
6447                         err = mgmt_cmd_complete(sk, hdev->id,
6448                                                 MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
6449                                                 MGMT_STATUS_FAILED,
6450                                                 &cp->type, sizeof(cp->type));
6451                         goto done;
6452                 }
6453
6454                 if (hci_dev_test_flag(hdev, HCI_PRIVACY)) {
6455                         memcpy(addr, &hdev->rpa, 6);
6456                         addr[6] = 0x01;
6457                 } else if (hci_dev_test_flag(hdev, HCI_FORCE_STATIC_ADDR) ||
6458                            !bacmp(&hdev->bdaddr, BDADDR_ANY) ||
6459                            (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED) &&
6460                             bacmp(&hdev->static_addr, BDADDR_ANY))) {
6461                         memcpy(addr, &hdev->static_addr, 6);
6462                         addr[6] = 0x01;
6463                 } else {
6464                         memcpy(addr, &hdev->bdaddr, 6);
6465                         addr[6] = 0x00;
6466                 }
6467
6468                 eir_len = eir_append_data(rp->eir, eir_len, EIR_LE_BDADDR,
6469                                           addr, sizeof(addr));
6470
6471                 if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
6472                         role = 0x02;
6473                 else
6474                         role = 0x01;
6475
6476                 eir_len = eir_append_data(rp->eir, eir_len, EIR_LE_ROLE,
6477                                           &role, sizeof(role));
6478
6479                 if (hci_dev_test_flag(hdev, HCI_SC_ENABLED)) {
6480                         eir_len = eir_append_data(rp->eir, eir_len,
6481                                                   EIR_LE_SC_CONFIRM,
6482                                                   hash, sizeof(hash));
6483
6484                         eir_len = eir_append_data(rp->eir, eir_len,
6485                                                   EIR_LE_SC_RANDOM,
6486                                                   rand, sizeof(rand));
6487                 }
6488
6489                 flags = get_adv_discov_flags(hdev);
6490
6491                 if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED))
6492                         flags |= LE_AD_NO_BREDR;
6493
6494                 eir_len = eir_append_data(rp->eir, eir_len, EIR_FLAGS,
6495                                           &flags, sizeof(flags));
6496                 break;
6497         }
6498
6499         rp->type = cp->type;
6500         rp->eir_len = cpu_to_le16(eir_len);
6501
6502         hci_dev_unlock(hdev);
6503
6504         hci_sock_set_flag(sk, HCI_MGMT_OOB_DATA_EVENTS);
6505
6506         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_READ_LOCAL_OOB_EXT_DATA,
6507                                 MGMT_STATUS_SUCCESS, rp, sizeof(*rp) + eir_len);
6508         if (err < 0)
6509                 goto done;
6510
6511         err = mgmt_limited_event(MGMT_EV_LOCAL_OOB_DATA_UPDATED, hdev,
6512                                  rp, sizeof(*rp) + eir_len,
6513                                  HCI_MGMT_OOB_DATA_EVENTS, sk);
6514
6515 done:
6516         kfree(rp);
6517
6518         return err;
6519 }
6520
6521 static int read_adv_features(struct sock *sk, struct hci_dev *hdev,
6522                              void *data, u16 data_len)
6523 {
6524         struct mgmt_rp_read_adv_features *rp;
6525         size_t rp_len;
6526         int err;
6527         bool instance;
6528
6529         BT_DBG("%s", hdev->name);
6530
6531         hci_dev_lock(hdev);
6532
6533         rp_len = sizeof(*rp);
6534
6535         /* Currently only one instance is supported, so just add 1 to the
6536          * response length.
6537          */
6538         instance = hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE);
6539         if (instance)
6540                 rp_len++;
6541
6542         rp = kmalloc(rp_len, GFP_ATOMIC);
6543         if (!rp) {
6544                 hci_dev_unlock(hdev);
6545                 return -ENOMEM;
6546         }
6547
6548         rp->supported_flags = cpu_to_le32(0);
6549         rp->max_adv_data_len = HCI_MAX_AD_LENGTH;
6550         rp->max_scan_rsp_len = HCI_MAX_AD_LENGTH;
6551         rp->max_instances = 1;
6552
6553         /* Currently only one instance is supported, so simply return the
6554          * current instance number.
6555          */
6556         if (instance) {
6557                 rp->num_instances = 1;
6558                 rp->instance[0] = 1;
6559         } else {
6560                 rp->num_instances = 0;
6561         }
6562
6563         hci_dev_unlock(hdev);
6564
6565         err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_READ_ADV_FEATURES,
6566                                 MGMT_STATUS_SUCCESS, rp, rp_len);
6567
6568         kfree(rp);
6569
6570         return err;
6571 }
6572
6573 static bool tlv_data_is_valid(struct hci_dev *hdev, u32 adv_flags, u8 *data,
6574                               u8 len, bool is_adv_data)
6575 {
6576         u8 max_len = HCI_MAX_AD_LENGTH;
6577         int i, cur_len;
6578         bool flags_managed = false;
6579
6580         if (is_adv_data && (adv_flags & MGMT_ADV_FLAG_DISCOV)) {
6581                 flags_managed = true;
6582                 max_len -= 3;
6583         }
6584
6585         if (len > max_len)
6586                 return false;
6587
6588         /* Make sure that the data is correctly formatted. */
6589         for (i = 0, cur_len = 0; i < len; i += (cur_len + 1)) {
6590                 cur_len = data[i];
6591
6592                 if (flags_managed && data[i + 1] == EIR_FLAGS)
6593                         return false;
6594
6595                 /* If the current field length would exceed the total data
6596                  * length, then it's invalid.
6597                  */
6598                 if (i + cur_len >= len)
6599                         return false;
6600         }
6601
6602         return true;
6603 }
6604
6605 static void add_advertising_complete(struct hci_dev *hdev, u8 status,
6606                                      u16 opcode)
6607 {
6608         struct mgmt_pending_cmd *cmd;
6609         struct mgmt_rp_add_advertising rp;
6610
6611         BT_DBG("status %d", status);
6612
6613         hci_dev_lock(hdev);
6614
6615         cmd = pending_find(MGMT_OP_ADD_ADVERTISING, hdev);
6616
6617         if (status) {
6618                 hci_dev_clear_flag(hdev, HCI_ADVERTISING_INSTANCE);
6619                 memset(&hdev->adv_instance, 0, sizeof(hdev->adv_instance));
6620                 advertising_removed(cmd ? cmd->sk : NULL, hdev, 1);
6621         }
6622
6623         if (!cmd)
6624                 goto unlock;
6625
6626         rp.instance = 0x01;
6627
6628         if (status)
6629                 mgmt_cmd_status(cmd->sk, cmd->index, cmd->opcode,
6630                                 mgmt_status(status));
6631         else
6632                 mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode,
6633                                   mgmt_status(status), &rp, sizeof(rp));
6634
6635         mgmt_pending_remove(cmd);
6636
6637 unlock:
6638         hci_dev_unlock(hdev);
6639 }
6640
6641 static void adv_timeout_expired(struct work_struct *work)
6642 {
6643         struct hci_dev *hdev = container_of(work, struct hci_dev,
6644                                             adv_instance.timeout_exp.work);
6645
6646         hdev->adv_instance.timeout = 0;
6647
6648         hci_dev_lock(hdev);
6649         clear_adv_instance(hdev);
6650         hci_dev_unlock(hdev);
6651 }
6652
6653 static int add_advertising(struct sock *sk, struct hci_dev *hdev,
6654                            void *data, u16 data_len)
6655 {
6656         struct mgmt_cp_add_advertising *cp = data;
6657         struct mgmt_rp_add_advertising rp;
6658         u32 flags;
6659         u8 status;
6660         u16 timeout;
6661         int err;
6662         struct mgmt_pending_cmd *cmd;
6663         struct hci_request req;
6664
6665         BT_DBG("%s", hdev->name);
6666
6667         status = mgmt_le_support(hdev);
6668         if (status)
6669                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
6670                                        status);
6671
6672         flags = __le32_to_cpu(cp->flags);
6673         timeout = __le16_to_cpu(cp->timeout);
6674
6675         /* The current implementation only supports adding one instance */
6676         if (cp->instance != 0x01)
6677                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
6678                                        MGMT_STATUS_INVALID_PARAMS);
6679
6680         hci_dev_lock(hdev);
6681
6682         if (timeout && !hdev_is_powered(hdev)) {
6683                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
6684                                       MGMT_STATUS_REJECTED);
6685                 goto unlock;
6686         }
6687
6688         if (pending_find(MGMT_OP_ADD_ADVERTISING, hdev) ||
6689             pending_find(MGMT_OP_REMOVE_ADVERTISING, hdev) ||
6690             pending_find(MGMT_OP_SET_LE, hdev)) {
6691                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
6692                                       MGMT_STATUS_BUSY);
6693                 goto unlock;
6694         }
6695
6696         if (!tlv_data_is_valid(hdev, flags, cp->data, cp->adv_data_len, true) ||
6697             !tlv_data_is_valid(hdev, flags, cp->data + cp->adv_data_len,
6698                                cp->scan_rsp_len, false)) {
6699                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
6700                                       MGMT_STATUS_INVALID_PARAMS);
6701                 goto unlock;
6702         }
6703
6704         INIT_DELAYED_WORK(&hdev->adv_instance.timeout_exp, adv_timeout_expired);
6705
6706         hdev->adv_instance.flags = flags;
6707         hdev->adv_instance.adv_data_len = cp->adv_data_len;
6708         hdev->adv_instance.scan_rsp_len = cp->scan_rsp_len;
6709
6710         if (cp->adv_data_len)
6711                 memcpy(hdev->adv_instance.adv_data, cp->data, cp->adv_data_len);
6712
6713         if (cp->scan_rsp_len)
6714                 memcpy(hdev->adv_instance.scan_rsp_data,
6715                        cp->data + cp->adv_data_len, cp->scan_rsp_len);
6716
6717         if (hdev->adv_instance.timeout)
6718                 cancel_delayed_work(&hdev->adv_instance.timeout_exp);
6719
6720         hdev->adv_instance.timeout = timeout;
6721
6722         if (timeout)
6723                 queue_delayed_work(hdev->workqueue,
6724                                    &hdev->adv_instance.timeout_exp,
6725                                    msecs_to_jiffies(timeout * 1000));
6726
6727         if (!hci_dev_test_and_set_flag(hdev, HCI_ADVERTISING_INSTANCE))
6728                 advertising_added(sk, hdev, 1);
6729
6730         /* If the HCI_ADVERTISING flag is set or the device isn't powered then
6731          * we have no HCI communication to make. Simply return.
6732          */
6733         if (!hdev_is_powered(hdev) ||
6734             hci_dev_test_flag(hdev, HCI_ADVERTISING)) {
6735                 rp.instance = 0x01;
6736                 err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
6737                                         MGMT_STATUS_SUCCESS, &rp, sizeof(rp));
6738                 goto unlock;
6739         }
6740
6741         /* We're good to go, update advertising data, parameters, and start
6742          * advertising.
6743          */
6744         cmd = mgmt_pending_add(sk, MGMT_OP_ADD_ADVERTISING, hdev, data,
6745                                data_len);
6746         if (!cmd) {
6747                 err = -ENOMEM;
6748                 goto unlock;
6749         }
6750
6751         hci_req_init(&req, hdev);
6752
6753         update_adv_data(&req);
6754         update_scan_rsp_data(&req);
6755         enable_advertising(&req);
6756
6757         err = hci_req_run(&req, add_advertising_complete);
6758         if (err < 0)
6759                 mgmt_pending_remove(cmd);
6760
6761 unlock:
6762         hci_dev_unlock(hdev);
6763
6764         return err;
6765 }
6766
6767 static void remove_advertising_complete(struct hci_dev *hdev, u8 status,
6768                                         u16 opcode)
6769 {
6770         struct mgmt_pending_cmd *cmd;
6771         struct mgmt_rp_remove_advertising rp;
6772
6773         BT_DBG("status %d", status);
6774
6775         hci_dev_lock(hdev);
6776
6777         /* A failure status here only means that we failed to disable
6778          * advertising. Otherwise, the advertising instance has been removed,
6779          * so report success.
6780          */
6781         cmd = pending_find(MGMT_OP_REMOVE_ADVERTISING, hdev);
6782         if (!cmd)
6783                 goto unlock;
6784
6785         rp.instance = 1;
6786
6787         mgmt_cmd_complete(cmd->sk, cmd->index, cmd->opcode, MGMT_STATUS_SUCCESS,
6788                           &rp, sizeof(rp));
6789         mgmt_pending_remove(cmd);
6790
6791 unlock:
6792         hci_dev_unlock(hdev);
6793 }
6794
6795 static int remove_advertising(struct sock *sk, struct hci_dev *hdev,
6796                               void *data, u16 data_len)
6797 {
6798         struct mgmt_cp_remove_advertising *cp = data;
6799         struct mgmt_rp_remove_advertising rp;
6800         int err;
6801         struct mgmt_pending_cmd *cmd;
6802         struct hci_request req;
6803
6804         BT_DBG("%s", hdev->name);
6805
6806         /* The current implementation only allows modifying instance no 1. A
6807          * value of 0 indicates that all instances should be cleared.
6808          */
6809         if (cp->instance > 1)
6810                 return mgmt_cmd_status(sk, hdev->id, MGMT_OP_REMOVE_ADVERTISING,
6811                                        MGMT_STATUS_INVALID_PARAMS);
6812
6813         hci_dev_lock(hdev);
6814
6815         if (pending_find(MGMT_OP_ADD_ADVERTISING, hdev) ||
6816             pending_find(MGMT_OP_REMOVE_ADVERTISING, hdev) ||
6817             pending_find(MGMT_OP_SET_LE, hdev)) {
6818                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_REMOVE_ADVERTISING,
6819                                       MGMT_STATUS_BUSY);
6820                 goto unlock;
6821         }
6822
6823         if (!hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE)) {
6824                 err = mgmt_cmd_status(sk, hdev->id, MGMT_OP_REMOVE_ADVERTISING,
6825                                       MGMT_STATUS_INVALID_PARAMS);
6826                 goto unlock;
6827         }
6828
6829         if (hdev->adv_instance.timeout)
6830                 cancel_delayed_work(&hdev->adv_instance.timeout_exp);
6831
6832         memset(&hdev->adv_instance, 0, sizeof(hdev->adv_instance));
6833
6834         advertising_removed(sk, hdev, 1);
6835
6836         hci_dev_clear_flag(hdev, HCI_ADVERTISING_INSTANCE);
6837
6838         /* If the HCI_ADVERTISING flag is set or the device isn't powered then
6839          * we have no HCI communication to make. Simply return.
6840          */
6841         if (!hdev_is_powered(hdev) ||
6842             hci_dev_test_flag(hdev, HCI_ADVERTISING)) {
6843                 rp.instance = 1;
6844                 err = mgmt_cmd_complete(sk, hdev->id,
6845                                         MGMT_OP_REMOVE_ADVERTISING,
6846                                         MGMT_STATUS_SUCCESS, &rp, sizeof(rp));
6847                 goto unlock;
6848         }
6849
6850         cmd = mgmt_pending_add(sk, MGMT_OP_REMOVE_ADVERTISING, hdev, data,
6851                                data_len);
6852         if (!cmd) {
6853                 err = -ENOMEM;
6854                 goto unlock;
6855         }
6856
6857         hci_req_init(&req, hdev);
6858         disable_advertising(&req);
6859
6860         err = hci_req_run(&req, remove_advertising_complete);
6861         if (err < 0)
6862                 mgmt_pending_remove(cmd);
6863
6864 unlock:
6865         hci_dev_unlock(hdev);
6866
6867         return err;
6868 }
6869
6870 static const struct hci_mgmt_handler mgmt_handlers[] = {
6871         { NULL }, /* 0x0000 (no command) */
6872         { read_version,            MGMT_READ_VERSION_SIZE,
6873                                                 HCI_MGMT_NO_HDEV |
6874                                                 HCI_MGMT_UNTRUSTED },
6875         { read_commands,           MGMT_READ_COMMANDS_SIZE,
6876                                                 HCI_MGMT_NO_HDEV |
6877                                                 HCI_MGMT_UNTRUSTED },
6878         { read_index_list,         MGMT_READ_INDEX_LIST_SIZE,
6879                                                 HCI_MGMT_NO_HDEV |
6880                                                 HCI_MGMT_UNTRUSTED },
6881         { read_controller_info,    MGMT_READ_INFO_SIZE,
6882                                                 HCI_MGMT_UNTRUSTED },
6883         { set_powered,             MGMT_SETTING_SIZE },
6884         { set_discoverable,        MGMT_SET_DISCOVERABLE_SIZE },
6885         { set_connectable,         MGMT_SETTING_SIZE },
6886         { set_fast_connectable,    MGMT_SETTING_SIZE },
6887         { set_bondable,            MGMT_SETTING_SIZE },
6888         { set_link_security,       MGMT_SETTING_SIZE },
6889         { set_ssp,                 MGMT_SETTING_SIZE },
6890         { set_hs,                  MGMT_SETTING_SIZE },
6891         { set_le,                  MGMT_SETTING_SIZE },
6892         { set_dev_class,           MGMT_SET_DEV_CLASS_SIZE },
6893         { set_local_name,          MGMT_SET_LOCAL_NAME_SIZE },
6894         { add_uuid,                MGMT_ADD_UUID_SIZE },
6895         { remove_uuid,             MGMT_REMOVE_UUID_SIZE },
6896         { load_link_keys,          MGMT_LOAD_LINK_KEYS_SIZE,
6897                                                 HCI_MGMT_VAR_LEN },
6898         { load_long_term_keys,     MGMT_LOAD_LONG_TERM_KEYS_SIZE,
6899                                                 HCI_MGMT_VAR_LEN },
6900         { disconnect,              MGMT_DISCONNECT_SIZE },
6901         { get_connections,         MGMT_GET_CONNECTIONS_SIZE },
6902         { pin_code_reply,          MGMT_PIN_CODE_REPLY_SIZE },
6903         { pin_code_neg_reply,      MGMT_PIN_CODE_NEG_REPLY_SIZE },
6904         { set_io_capability,       MGMT_SET_IO_CAPABILITY_SIZE },
6905         { pair_device,             MGMT_PAIR_DEVICE_SIZE },
6906         { cancel_pair_device,      MGMT_CANCEL_PAIR_DEVICE_SIZE },
6907         { unpair_device,           MGMT_UNPAIR_DEVICE_SIZE },
6908         { user_confirm_reply,      MGMT_USER_CONFIRM_REPLY_SIZE },
6909         { user_confirm_neg_reply,  MGMT_USER_CONFIRM_NEG_REPLY_SIZE },
6910         { user_passkey_reply,      MGMT_USER_PASSKEY_REPLY_SIZE },
6911         { user_passkey_neg_reply,  MGMT_USER_PASSKEY_NEG_REPLY_SIZE },
6912         { read_local_oob_data,     MGMT_READ_LOCAL_OOB_DATA_SIZE },
6913         { add_remote_oob_data,     MGMT_ADD_REMOTE_OOB_DATA_SIZE,
6914                                                 HCI_MGMT_VAR_LEN },
6915         { remove_remote_oob_data,  MGMT_REMOVE_REMOTE_OOB_DATA_SIZE },
6916         { start_discovery,         MGMT_START_DISCOVERY_SIZE },
6917         { stop_discovery,          MGMT_STOP_DISCOVERY_SIZE },
6918         { confirm_name,            MGMT_CONFIRM_NAME_SIZE },
6919         { block_device,            MGMT_BLOCK_DEVICE_SIZE },
6920         { unblock_device,          MGMT_UNBLOCK_DEVICE_SIZE },
6921         { set_device_id,           MGMT_SET_DEVICE_ID_SIZE },
6922         { set_advertising,         MGMT_SETTING_SIZE },
6923         { set_bredr,               MGMT_SETTING_SIZE },
6924         { set_static_address,      MGMT_SET_STATIC_ADDRESS_SIZE },
6925         { set_scan_params,         MGMT_SET_SCAN_PARAMS_SIZE },
6926         { set_secure_conn,         MGMT_SETTING_SIZE },
6927         { set_debug_keys,          MGMT_SETTING_SIZE },
6928         { set_privacy,             MGMT_SET_PRIVACY_SIZE },
6929         { load_irks,               MGMT_LOAD_IRKS_SIZE,
6930                                                 HCI_MGMT_VAR_LEN },
6931         { get_conn_info,           MGMT_GET_CONN_INFO_SIZE },
6932         { get_clock_info,          MGMT_GET_CLOCK_INFO_SIZE },
6933         { add_device,              MGMT_ADD_DEVICE_SIZE },
6934         { remove_device,           MGMT_REMOVE_DEVICE_SIZE },
6935         { load_conn_param,         MGMT_LOAD_CONN_PARAM_SIZE,
6936                                                 HCI_MGMT_VAR_LEN },
6937         { read_unconf_index_list,  MGMT_READ_UNCONF_INDEX_LIST_SIZE,
6938                                                 HCI_MGMT_NO_HDEV |
6939                                                 HCI_MGMT_UNTRUSTED },
6940         { read_config_info,        MGMT_READ_CONFIG_INFO_SIZE,
6941                                                 HCI_MGMT_UNCONFIGURED |
6942                                                 HCI_MGMT_UNTRUSTED },
6943         { set_external_config,     MGMT_SET_EXTERNAL_CONFIG_SIZE,
6944                                                 HCI_MGMT_UNCONFIGURED },
6945         { set_public_address,      MGMT_SET_PUBLIC_ADDRESS_SIZE,
6946                                                 HCI_MGMT_UNCONFIGURED },
6947         { start_service_discovery, MGMT_START_SERVICE_DISCOVERY_SIZE,
6948                                                 HCI_MGMT_VAR_LEN },
6949         { read_local_oob_ext_data, MGMT_READ_LOCAL_OOB_EXT_DATA_SIZE },
6950         { read_ext_index_list,     MGMT_READ_EXT_INDEX_LIST_SIZE,
6951                                                 HCI_MGMT_NO_HDEV |
6952                                                 HCI_MGMT_UNTRUSTED },
6953         { read_adv_features,       MGMT_READ_ADV_FEATURES_SIZE },
6954         { add_advertising,         MGMT_ADD_ADVERTISING_SIZE,
6955                                                 HCI_MGMT_VAR_LEN },
6956         { remove_advertising,      MGMT_REMOVE_ADVERTISING_SIZE },
6957 };
6958
6959 void mgmt_index_added(struct hci_dev *hdev)
6960 {
6961         struct mgmt_ev_ext_index ev;
6962
6963         if (test_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks))
6964                 return;
6965
6966         switch (hdev->dev_type) {
6967         case HCI_BREDR:
6968                 if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
6969                         mgmt_index_event(MGMT_EV_UNCONF_INDEX_ADDED, hdev,
6970                                          NULL, 0, HCI_MGMT_UNCONF_INDEX_EVENTS);
6971                         ev.type = 0x01;
6972                 } else {
6973                         mgmt_index_event(MGMT_EV_INDEX_ADDED, hdev, NULL, 0,
6974                                          HCI_MGMT_INDEX_EVENTS);
6975                         ev.type = 0x00;
6976                 }
6977                 break;
6978         case HCI_AMP:
6979                 ev.type = 0x02;
6980                 break;
6981         default:
6982                 return;
6983         }
6984
6985         ev.bus = hdev->bus;
6986
6987         mgmt_index_event(MGMT_EV_EXT_INDEX_ADDED, hdev, &ev, sizeof(ev),
6988                          HCI_MGMT_EXT_INDEX_EVENTS);
6989 }
6990
6991 void mgmt_index_removed(struct hci_dev *hdev)
6992 {
6993         struct mgmt_ev_ext_index ev;
6994         u8 status = MGMT_STATUS_INVALID_INDEX;
6995
6996         if (test_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks))
6997                 return;
6998
6999         switch (hdev->dev_type) {
7000         case HCI_BREDR:
7001                 mgmt_pending_foreach(0, hdev, cmd_complete_rsp, &status);
7002
7003                 if (hci_dev_test_flag(hdev, HCI_UNCONFIGURED)) {
7004                         mgmt_index_event(MGMT_EV_UNCONF_INDEX_REMOVED, hdev,
7005                                          NULL, 0, HCI_MGMT_UNCONF_INDEX_EVENTS);
7006                         ev.type = 0x01;
7007                 } else {
7008                         mgmt_index_event(MGMT_EV_INDEX_REMOVED, hdev, NULL, 0,
7009                                          HCI_MGMT_INDEX_EVENTS);
7010                         ev.type = 0x00;
7011                 }
7012                 break;
7013         case HCI_AMP:
7014                 ev.type = 0x02;
7015                 break;
7016         default:
7017                 return;
7018         }
7019
7020         ev.bus = hdev->bus;
7021
7022         mgmt_index_event(MGMT_EV_EXT_INDEX_REMOVED, hdev, &ev, sizeof(ev),
7023                          HCI_MGMT_EXT_INDEX_EVENTS);
7024 }
7025
7026 /* This function requires the caller holds hdev->lock */
7027 static void restart_le_actions(struct hci_request *req)
7028 {
7029         struct hci_dev *hdev = req->hdev;
7030         struct hci_conn_params *p;
7031
7032         list_for_each_entry(p, &hdev->le_conn_params, list) {
7033                 /* Needed for AUTO_OFF case where might not "really"
7034                  * have been powered off.
7035                  */
7036                 list_del_init(&p->action);
7037
7038                 switch (p->auto_connect) {
7039                 case HCI_AUTO_CONN_DIRECT:
7040                 case HCI_AUTO_CONN_ALWAYS:
7041                         list_add(&p->action, &hdev->pend_le_conns);
7042                         break;
7043                 case HCI_AUTO_CONN_REPORT:
7044                         list_add(&p->action, &hdev->pend_le_reports);
7045                         break;
7046                 default:
7047                         break;
7048                 }
7049         }
7050
7051         __hci_update_background_scan(req);
7052 }
7053
7054 static void powered_complete(struct hci_dev *hdev, u8 status, u16 opcode)
7055 {
7056         struct cmd_lookup match = { NULL, hdev };
7057
7058         BT_DBG("status 0x%02x", status);
7059
7060         if (!status) {
7061                 /* Register the available SMP channels (BR/EDR and LE) only
7062                  * when successfully powering on the controller. This late
7063                  * registration is required so that LE SMP can clearly
7064                  * decide if the public address or static address is used.
7065                  */
7066                 smp_register(hdev);
7067         }
7068
7069         hci_dev_lock(hdev);
7070
7071         mgmt_pending_foreach(MGMT_OP_SET_POWERED, hdev, settings_rsp, &match);
7072
7073         new_settings(hdev, match.sk);
7074
7075         hci_dev_unlock(hdev);
7076
7077         if (match.sk)
7078                 sock_put(match.sk);
7079 }
7080
7081 static int powered_update_hci(struct hci_dev *hdev)
7082 {
7083         struct hci_request req;
7084         u8 link_sec;
7085
7086         hci_req_init(&req, hdev);
7087
7088         if (hci_dev_test_flag(hdev, HCI_SSP_ENABLED) &&
7089             !lmp_host_ssp_capable(hdev)) {
7090                 u8 mode = 0x01;
7091
7092                 hci_req_add(&req, HCI_OP_WRITE_SSP_MODE, sizeof(mode), &mode);
7093
7094                 if (bredr_sc_enabled(hdev) && !lmp_host_sc_capable(hdev)) {
7095                         u8 support = 0x01;
7096
7097                         hci_req_add(&req, HCI_OP_WRITE_SC_SUPPORT,
7098                                     sizeof(support), &support);
7099                 }
7100         }
7101
7102         if (hci_dev_test_flag(hdev, HCI_LE_ENABLED) &&
7103             lmp_bredr_capable(hdev)) {
7104                 struct hci_cp_write_le_host_supported cp;
7105
7106                 cp.le = 0x01;
7107                 cp.simul = 0x00;
7108
7109                 /* Check first if we already have the right
7110                  * host state (host features set)
7111                  */
7112                 if (cp.le != lmp_host_le_capable(hdev) ||
7113                     cp.simul != lmp_host_le_br_capable(hdev))
7114                         hci_req_add(&req, HCI_OP_WRITE_LE_HOST_SUPPORTED,
7115                                     sizeof(cp), &cp);
7116         }
7117
7118         if (lmp_le_capable(hdev)) {
7119                 /* Make sure the controller has a good default for
7120                  * advertising data. This also applies to the case
7121                  * where BR/EDR was toggled during the AUTO_OFF phase.
7122                  */
7123                 if (hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
7124                         update_adv_data(&req);
7125                         update_scan_rsp_data(&req);
7126                 }
7127
7128                 if (hci_dev_test_flag(hdev, HCI_ADVERTISING) ||
7129                     hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE))
7130                         enable_advertising(&req);
7131
7132                 restart_le_actions(&req);
7133         }
7134
7135         link_sec = hci_dev_test_flag(hdev, HCI_LINK_SECURITY);
7136         if (link_sec != test_bit(HCI_AUTH, &hdev->flags))
7137                 hci_req_add(&req, HCI_OP_WRITE_AUTH_ENABLE,
7138                             sizeof(link_sec), &link_sec);
7139
7140         if (lmp_bredr_capable(hdev)) {
7141                 if (hci_dev_test_flag(hdev, HCI_FAST_CONNECTABLE))
7142                         write_fast_connectable(&req, true);
7143                 else
7144                         write_fast_connectable(&req, false);
7145                 __hci_update_page_scan(&req);
7146                 update_class(&req);
7147                 update_name(&req);
7148                 update_eir(&req);
7149         }
7150
7151         return hci_req_run(&req, powered_complete);
7152 }
7153
7154 int mgmt_powered(struct hci_dev *hdev, u8 powered)
7155 {
7156         struct cmd_lookup match = { NULL, hdev };
7157         u8 status, zero_cod[] = { 0, 0, 0 };
7158         int err;
7159
7160         if (!hci_dev_test_flag(hdev, HCI_MGMT))
7161                 return 0;
7162
7163         if (powered) {
7164                 if (powered_update_hci(hdev) == 0)
7165                         return 0;
7166
7167                 mgmt_pending_foreach(MGMT_OP_SET_POWERED, hdev, settings_rsp,
7168                                      &match);
7169                 goto new_settings;
7170         }
7171
7172         mgmt_pending_foreach(MGMT_OP_SET_POWERED, hdev, settings_rsp, &match);
7173
7174         /* If the power off is because of hdev unregistration let
7175          * use the appropriate INVALID_INDEX status. Otherwise use
7176          * NOT_POWERED. We cover both scenarios here since later in
7177          * mgmt_index_removed() any hci_conn callbacks will have already
7178          * been triggered, potentially causing misleading DISCONNECTED
7179          * status responses.
7180          */
7181         if (hci_dev_test_flag(hdev, HCI_UNREGISTER))
7182                 status = MGMT_STATUS_INVALID_INDEX;
7183         else
7184                 status = MGMT_STATUS_NOT_POWERED;
7185
7186         mgmt_pending_foreach(0, hdev, cmd_complete_rsp, &status);
7187
7188         if (memcmp(hdev->dev_class, zero_cod, sizeof(zero_cod)) != 0)
7189                 mgmt_generic_event(MGMT_EV_CLASS_OF_DEV_CHANGED, hdev,
7190                                    zero_cod, sizeof(zero_cod), NULL);
7191
7192 new_settings:
7193         err = new_settings(hdev, match.sk);
7194
7195         if (match.sk)
7196                 sock_put(match.sk);
7197
7198         return err;
7199 }
7200
7201 void mgmt_set_powered_failed(struct hci_dev *hdev, int err)
7202 {
7203         struct mgmt_pending_cmd *cmd;
7204         u8 status;
7205
7206         cmd = pending_find(MGMT_OP_SET_POWERED, hdev);
7207         if (!cmd)
7208                 return;
7209
7210         if (err == -ERFKILL)
7211                 status = MGMT_STATUS_RFKILLED;
7212         else
7213                 status = MGMT_STATUS_FAILED;
7214
7215         mgmt_cmd_status(cmd->sk, hdev->id, MGMT_OP_SET_POWERED, status);
7216
7217         mgmt_pending_remove(cmd);
7218 }
7219
7220 void mgmt_discoverable_timeout(struct hci_dev *hdev)
7221 {
7222         struct hci_request req;
7223
7224         hci_dev_lock(hdev);
7225
7226         /* When discoverable timeout triggers, then just make sure
7227          * the limited discoverable flag is cleared. Even in the case
7228          * of a timeout triggered from general discoverable, it is
7229          * safe to unconditionally clear the flag.
7230          */
7231         hci_dev_clear_flag(hdev, HCI_LIMITED_DISCOVERABLE);
7232         hci_dev_clear_flag(hdev, HCI_DISCOVERABLE);
7233
7234         hci_req_init(&req, hdev);
7235         if (hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
7236                 u8 scan = SCAN_PAGE;
7237                 hci_req_add(&req, HCI_OP_WRITE_SCAN_ENABLE,
7238                             sizeof(scan), &scan);
7239         }
7240         update_class(&req);
7241
7242         /* Advertising instances don't use the global discoverable setting, so
7243          * only update AD if advertising was enabled using Set Advertising.
7244          */
7245         if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
7246                 update_adv_data(&req);
7247
7248         hci_req_run(&req, NULL);
7249
7250         hdev->discov_timeout = 0;
7251
7252         new_settings(hdev, NULL);
7253
7254         hci_dev_unlock(hdev);
7255 }
7256
7257 void mgmt_new_link_key(struct hci_dev *hdev, struct link_key *key,
7258                        bool persistent)
7259 {
7260         struct mgmt_ev_new_link_key ev;
7261
7262         memset(&ev, 0, sizeof(ev));
7263
7264         ev.store_hint = persistent;
7265         bacpy(&ev.key.addr.bdaddr, &key->bdaddr);
7266         ev.key.addr.type = BDADDR_BREDR;
7267         ev.key.type = key->type;
7268         memcpy(ev.key.val, key->val, HCI_LINK_KEY_SIZE);
7269         ev.key.pin_len = key->pin_len;
7270
7271         mgmt_event(MGMT_EV_NEW_LINK_KEY, hdev, &ev, sizeof(ev), NULL);
7272 }
7273
7274 static u8 mgmt_ltk_type(struct smp_ltk *ltk)
7275 {
7276         switch (ltk->type) {
7277         case SMP_LTK:
7278         case SMP_LTK_SLAVE:
7279                 if (ltk->authenticated)
7280                         return MGMT_LTK_AUTHENTICATED;
7281                 return MGMT_LTK_UNAUTHENTICATED;
7282         case SMP_LTK_P256:
7283                 if (ltk->authenticated)
7284                         return MGMT_LTK_P256_AUTH;
7285                 return MGMT_LTK_P256_UNAUTH;
7286         case SMP_LTK_P256_DEBUG:
7287                 return MGMT_LTK_P256_DEBUG;
7288         }
7289
7290         return MGMT_LTK_UNAUTHENTICATED;
7291 }
7292
7293 void mgmt_new_ltk(struct hci_dev *hdev, struct smp_ltk *key, bool persistent)
7294 {
7295         struct mgmt_ev_new_long_term_key ev;
7296
7297         memset(&ev, 0, sizeof(ev));
7298
7299         /* Devices using resolvable or non-resolvable random addresses
7300          * without providing an indentity resolving key don't require
7301          * to store long term keys. Their addresses will change the
7302          * next time around.
7303          *
7304          * Only when a remote device provides an identity address
7305          * make sure the long term key is stored. If the remote
7306          * identity is known, the long term keys are internally
7307          * mapped to the identity address. So allow static random
7308          * and public addresses here.
7309          */
7310         if (key->bdaddr_type == ADDR_LE_DEV_RANDOM &&
7311             (key->bdaddr.b[5] & 0xc0) != 0xc0)
7312                 ev.store_hint = 0x00;
7313         else
7314                 ev.store_hint = persistent;
7315
7316         bacpy(&ev.key.addr.bdaddr, &key->bdaddr);
7317         ev.key.addr.type = link_to_bdaddr(LE_LINK, key->bdaddr_type);
7318         ev.key.type = mgmt_ltk_type(key);
7319         ev.key.enc_size = key->enc_size;
7320         ev.key.ediv = key->ediv;
7321         ev.key.rand = key->rand;
7322
7323         if (key->type == SMP_LTK)
7324                 ev.key.master = 1;
7325
7326         memcpy(ev.key.val, key->val, sizeof(key->val));
7327
7328         mgmt_event(MGMT_EV_NEW_LONG_TERM_KEY, hdev, &ev, sizeof(ev), NULL);
7329 }
7330
7331 void mgmt_new_irk(struct hci_dev *hdev, struct smp_irk *irk)
7332 {
7333         struct mgmt_ev_new_irk ev;
7334
7335         memset(&ev, 0, sizeof(ev));
7336
7337         /* For identity resolving keys from devices that are already
7338          * using a public address or static random address, do not
7339          * ask for storing this key. The identity resolving key really
7340          * is only mandatory for devices using resovlable random
7341          * addresses.
7342          *
7343          * Storing all identity resolving keys has the downside that
7344          * they will be also loaded on next boot of they system. More
7345          * identity resolving keys, means more time during scanning is
7346          * needed to actually resolve these addresses.
7347          */
7348         if (bacmp(&irk->rpa, BDADDR_ANY))
7349                 ev.store_hint = 0x01;
7350         else
7351                 ev.store_hint = 0x00;
7352
7353         bacpy(&ev.rpa, &irk->rpa);
7354         bacpy(&ev.irk.addr.bdaddr, &irk->bdaddr);
7355         ev.irk.addr.type = link_to_bdaddr(LE_LINK, irk->addr_type);
7356         memcpy(ev.irk.val, irk->val, sizeof(irk->val));
7357
7358         mgmt_event(MGMT_EV_NEW_IRK, hdev, &ev, sizeof(ev), NULL);
7359 }
7360
7361 void mgmt_new_csrk(struct hci_dev *hdev, struct smp_csrk *csrk,
7362                    bool persistent)
7363 {
7364         struct mgmt_ev_new_csrk ev;
7365
7366         memset(&ev, 0, sizeof(ev));
7367
7368         /* Devices using resolvable or non-resolvable random addresses
7369          * without providing an indentity resolving key don't require
7370          * to store signature resolving keys. Their addresses will change
7371          * the next time around.
7372          *
7373          * Only when a remote device provides an identity address
7374          * make sure the signature resolving key is stored. So allow
7375          * static random and public addresses here.
7376          */
7377         if (csrk->bdaddr_type == ADDR_LE_DEV_RANDOM &&
7378             (csrk->bdaddr.b[5] & 0xc0) != 0xc0)
7379                 ev.store_hint = 0x00;
7380         else
7381                 ev.store_hint = persistent;
7382
7383         bacpy(&ev.key.addr.bdaddr, &csrk->bdaddr);
7384         ev.key.addr.type = link_to_bdaddr(LE_LINK, csrk->bdaddr_type);
7385         ev.key.type = csrk->type;
7386         memcpy(ev.key.val, csrk->val, sizeof(csrk->val));
7387
7388         mgmt_event(MGMT_EV_NEW_CSRK, hdev, &ev, sizeof(ev), NULL);
7389 }
7390
7391 void mgmt_new_conn_param(struct hci_dev *hdev, bdaddr_t *bdaddr,
7392                          u8 bdaddr_type, u8 store_hint, u16 min_interval,
7393                          u16 max_interval, u16 latency, u16 timeout)
7394 {
7395         struct mgmt_ev_new_conn_param ev;
7396
7397         if (!hci_is_identity_address(bdaddr, bdaddr_type))
7398                 return;
7399
7400         memset(&ev, 0, sizeof(ev));
7401         bacpy(&ev.addr.bdaddr, bdaddr);
7402         ev.addr.type = link_to_bdaddr(LE_LINK, bdaddr_type);
7403         ev.store_hint = store_hint;
7404         ev.min_interval = cpu_to_le16(min_interval);
7405         ev.max_interval = cpu_to_le16(max_interval);
7406         ev.latency = cpu_to_le16(latency);
7407         ev.timeout = cpu_to_le16(timeout);
7408
7409         mgmt_event(MGMT_EV_NEW_CONN_PARAM, hdev, &ev, sizeof(ev), NULL);
7410 }
7411
7412 void mgmt_device_connected(struct hci_dev *hdev, struct hci_conn *conn,
7413                            u32 flags, u8 *name, u8 name_len)
7414 {
7415         char buf[512];
7416         struct mgmt_ev_device_connected *ev = (void *) buf;
7417         u16 eir_len = 0;
7418
7419         bacpy(&ev->addr.bdaddr, &conn->dst);
7420         ev->addr.type = link_to_bdaddr(conn->type, conn->dst_type);
7421
7422         ev->flags = __cpu_to_le32(flags);
7423
7424         /* We must ensure that the EIR Data fields are ordered and
7425          * unique. Keep it simple for now and avoid the problem by not
7426          * adding any BR/EDR data to the LE adv.
7427          */
7428         if (conn->le_adv_data_len > 0) {
7429                 memcpy(&ev->eir[eir_len],
7430                        conn->le_adv_data, conn->le_adv_data_len);
7431                 eir_len = conn->le_adv_data_len;
7432         } else {
7433                 if (name_len > 0)
7434                         eir_len = eir_append_data(ev->eir, 0, EIR_NAME_COMPLETE,
7435                                                   name, name_len);
7436
7437                 if (memcmp(conn->dev_class, "\0\0\0", 3) != 0)
7438                         eir_len = eir_append_data(ev->eir, eir_len,
7439                                                   EIR_CLASS_OF_DEV,
7440                                                   conn->dev_class, 3);
7441         }
7442
7443         ev->eir_len = cpu_to_le16(eir_len);
7444
7445         mgmt_event(MGMT_EV_DEVICE_CONNECTED, hdev, buf,
7446                     sizeof(*ev) + eir_len, NULL);
7447 }
7448
7449 static void disconnect_rsp(struct mgmt_pending_cmd *cmd, void *data)
7450 {
7451         struct sock **sk = data;
7452
7453         cmd->cmd_complete(cmd, 0);
7454
7455         *sk = cmd->sk;
7456         sock_hold(*sk);
7457
7458         mgmt_pending_remove(cmd);
7459 }
7460
7461 static void unpair_device_rsp(struct mgmt_pending_cmd *cmd, void *data)
7462 {
7463         struct hci_dev *hdev = data;
7464         struct mgmt_cp_unpair_device *cp = cmd->param;
7465
7466         device_unpaired(hdev, &cp->addr.bdaddr, cp->addr.type, cmd->sk);
7467
7468         cmd->cmd_complete(cmd, 0);
7469         mgmt_pending_remove(cmd);
7470 }
7471
7472 bool mgmt_powering_down(struct hci_dev *hdev)
7473 {
7474         struct mgmt_pending_cmd *cmd;
7475         struct mgmt_mode *cp;
7476
7477         cmd = pending_find(MGMT_OP_SET_POWERED, hdev);
7478         if (!cmd)
7479                 return false;
7480
7481         cp = cmd->param;
7482         if (!cp->val)
7483                 return true;
7484
7485         return false;
7486 }
7487
7488 void mgmt_device_disconnected(struct hci_dev *hdev, bdaddr_t *bdaddr,
7489                               u8 link_type, u8 addr_type, u8 reason,
7490                               bool mgmt_connected)
7491 {
7492         struct mgmt_ev_device_disconnected ev;
7493         struct sock *sk = NULL;
7494
7495         /* The connection is still in hci_conn_hash so test for 1
7496          * instead of 0 to know if this is the last one.
7497          */
7498         if (mgmt_powering_down(hdev) && hci_conn_count(hdev) == 1) {
7499                 cancel_delayed_work(&hdev->power_off);
7500                 queue_work(hdev->req_workqueue, &hdev->power_off.work);
7501         }
7502
7503         if (!mgmt_connected)
7504                 return;
7505
7506         if (link_type != ACL_LINK && link_type != LE_LINK)
7507                 return;
7508
7509         mgmt_pending_foreach(MGMT_OP_DISCONNECT, hdev, disconnect_rsp, &sk);
7510
7511         bacpy(&ev.addr.bdaddr, bdaddr);
7512         ev.addr.type = link_to_bdaddr(link_type, addr_type);
7513         ev.reason = reason;
7514
7515         mgmt_event(MGMT_EV_DEVICE_DISCONNECTED, hdev, &ev, sizeof(ev), sk);
7516
7517         if (sk)
7518                 sock_put(sk);
7519
7520         mgmt_pending_foreach(MGMT_OP_UNPAIR_DEVICE, hdev, unpair_device_rsp,
7521                              hdev);
7522 }
7523
7524 void mgmt_disconnect_failed(struct hci_dev *hdev, bdaddr_t *bdaddr,
7525                             u8 link_type, u8 addr_type, u8 status)
7526 {
7527         u8 bdaddr_type = link_to_bdaddr(link_type, addr_type);
7528         struct mgmt_cp_disconnect *cp;
7529         struct mgmt_pending_cmd *cmd;
7530
7531         mgmt_pending_foreach(MGMT_OP_UNPAIR_DEVICE, hdev, unpair_device_rsp,
7532                              hdev);
7533
7534         cmd = pending_find(MGMT_OP_DISCONNECT, hdev);
7535         if (!cmd)
7536                 return;
7537
7538         cp = cmd->param;
7539
7540         if (bacmp(bdaddr, &cp->addr.bdaddr))
7541                 return;
7542
7543         if (cp->addr.type != bdaddr_type)
7544                 return;
7545
7546         cmd->cmd_complete(cmd, mgmt_status(status));
7547         mgmt_pending_remove(cmd);
7548 }
7549
7550 void mgmt_connect_failed(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 link_type,
7551                          u8 addr_type, u8 status)
7552 {
7553         struct mgmt_ev_connect_failed ev;
7554
7555         /* The connection is still in hci_conn_hash so test for 1
7556          * instead of 0 to know if this is the last one.
7557          */
7558         if (mgmt_powering_down(hdev) && hci_conn_count(hdev) == 1) {
7559                 cancel_delayed_work(&hdev->power_off);
7560                 queue_work(hdev->req_workqueue, &hdev->power_off.work);
7561         }
7562
7563         bacpy(&ev.addr.bdaddr, bdaddr);
7564         ev.addr.type = link_to_bdaddr(link_type, addr_type);
7565         ev.status = mgmt_status(status);
7566
7567         mgmt_event(MGMT_EV_CONNECT_FAILED, hdev, &ev, sizeof(ev), NULL);
7568 }
7569
7570 void mgmt_pin_code_request(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 secure)
7571 {
7572         struct mgmt_ev_pin_code_request ev;
7573
7574         bacpy(&ev.addr.bdaddr, bdaddr);
7575         ev.addr.type = BDADDR_BREDR;
7576         ev.secure = secure;
7577
7578         mgmt_event(MGMT_EV_PIN_CODE_REQUEST, hdev, &ev, sizeof(ev), NULL);
7579 }
7580
7581 void mgmt_pin_code_reply_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7582                                   u8 status)
7583 {
7584         struct mgmt_pending_cmd *cmd;
7585
7586         cmd = pending_find(MGMT_OP_PIN_CODE_REPLY, hdev);
7587         if (!cmd)
7588                 return;
7589
7590         cmd->cmd_complete(cmd, mgmt_status(status));
7591         mgmt_pending_remove(cmd);
7592 }
7593
7594 void mgmt_pin_code_neg_reply_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7595                                       u8 status)
7596 {
7597         struct mgmt_pending_cmd *cmd;
7598
7599         cmd = pending_find(MGMT_OP_PIN_CODE_NEG_REPLY, hdev);
7600         if (!cmd)
7601                 return;
7602
7603         cmd->cmd_complete(cmd, mgmt_status(status));
7604         mgmt_pending_remove(cmd);
7605 }
7606
7607 int mgmt_user_confirm_request(struct hci_dev *hdev, bdaddr_t *bdaddr,
7608                               u8 link_type, u8 addr_type, u32 value,
7609                               u8 confirm_hint)
7610 {
7611         struct mgmt_ev_user_confirm_request ev;
7612
7613         BT_DBG("%s", hdev->name);
7614
7615         bacpy(&ev.addr.bdaddr, bdaddr);
7616         ev.addr.type = link_to_bdaddr(link_type, addr_type);
7617         ev.confirm_hint = confirm_hint;
7618         ev.value = cpu_to_le32(value);
7619
7620         return mgmt_event(MGMT_EV_USER_CONFIRM_REQUEST, hdev, &ev, sizeof(ev),
7621                           NULL);
7622 }
7623
7624 int mgmt_user_passkey_request(struct hci_dev *hdev, bdaddr_t *bdaddr,
7625                               u8 link_type, u8 addr_type)
7626 {
7627         struct mgmt_ev_user_passkey_request ev;
7628
7629         BT_DBG("%s", hdev->name);
7630
7631         bacpy(&ev.addr.bdaddr, bdaddr);
7632         ev.addr.type = link_to_bdaddr(link_type, addr_type);
7633
7634         return mgmt_event(MGMT_EV_USER_PASSKEY_REQUEST, hdev, &ev, sizeof(ev),
7635                           NULL);
7636 }
7637
7638 static int user_pairing_resp_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7639                                       u8 link_type, u8 addr_type, u8 status,
7640                                       u8 opcode)
7641 {
7642         struct mgmt_pending_cmd *cmd;
7643
7644         cmd = pending_find(opcode, hdev);
7645         if (!cmd)
7646                 return -ENOENT;
7647
7648         cmd->cmd_complete(cmd, mgmt_status(status));
7649         mgmt_pending_remove(cmd);
7650
7651         return 0;
7652 }
7653
7654 int mgmt_user_confirm_reply_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7655                                      u8 link_type, u8 addr_type, u8 status)
7656 {
7657         return user_pairing_resp_complete(hdev, bdaddr, link_type, addr_type,
7658                                           status, MGMT_OP_USER_CONFIRM_REPLY);
7659 }
7660
7661 int mgmt_user_confirm_neg_reply_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7662                                          u8 link_type, u8 addr_type, u8 status)
7663 {
7664         return user_pairing_resp_complete(hdev, bdaddr, link_type, addr_type,
7665                                           status,
7666                                           MGMT_OP_USER_CONFIRM_NEG_REPLY);
7667 }
7668
7669 int mgmt_user_passkey_reply_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7670                                      u8 link_type, u8 addr_type, u8 status)
7671 {
7672         return user_pairing_resp_complete(hdev, bdaddr, link_type, addr_type,
7673                                           status, MGMT_OP_USER_PASSKEY_REPLY);
7674 }
7675
7676 int mgmt_user_passkey_neg_reply_complete(struct hci_dev *hdev, bdaddr_t *bdaddr,
7677                                          u8 link_type, u8 addr_type, u8 status)
7678 {
7679         return user_pairing_resp_complete(hdev, bdaddr, link_type, addr_type,
7680                                           status,
7681                                           MGMT_OP_USER_PASSKEY_NEG_REPLY);
7682 }
7683
7684 int mgmt_user_passkey_notify(struct hci_dev *hdev, bdaddr_t *bdaddr,
7685                              u8 link_type, u8 addr_type, u32 passkey,
7686                              u8 entered)
7687 {
7688         struct mgmt_ev_passkey_notify ev;
7689
7690         BT_DBG("%s", hdev->name);
7691
7692         bacpy(&ev.addr.bdaddr, bdaddr);
7693         ev.addr.type = link_to_bdaddr(link_type, addr_type);
7694         ev.passkey = __cpu_to_le32(passkey);
7695         ev.entered = entered;
7696
7697         return mgmt_event(MGMT_EV_PASSKEY_NOTIFY, hdev, &ev, sizeof(ev), NULL);
7698 }
7699
7700 void mgmt_auth_failed(struct hci_conn *conn, u8 hci_status)
7701 {
7702         struct mgmt_ev_auth_failed ev;
7703         struct mgmt_pending_cmd *cmd;
7704         u8 status = mgmt_status(hci_status);
7705
7706         bacpy(&ev.addr.bdaddr, &conn->dst);
7707         ev.addr.type = link_to_bdaddr(conn->type, conn->dst_type);
7708         ev.status = status;
7709
7710         cmd = find_pairing(conn);
7711
7712         mgmt_event(MGMT_EV_AUTH_FAILED, conn->hdev, &ev, sizeof(ev),
7713                     cmd ? cmd->sk : NULL);
7714
7715         if (cmd) {
7716                 cmd->cmd_complete(cmd, status);
7717                 mgmt_pending_remove(cmd);
7718         }
7719 }
7720
7721 void mgmt_auth_enable_complete(struct hci_dev *hdev, u8 status)
7722 {
7723         struct cmd_lookup match = { NULL, hdev };
7724         bool changed;
7725
7726         if (status) {
7727                 u8 mgmt_err = mgmt_status(status);
7728                 mgmt_pending_foreach(MGMT_OP_SET_LINK_SECURITY, hdev,
7729                                      cmd_status_rsp, &mgmt_err);
7730                 return;
7731         }
7732
7733         if (test_bit(HCI_AUTH, &hdev->flags))
7734                 changed = !hci_dev_test_and_set_flag(hdev, HCI_LINK_SECURITY);
7735         else
7736                 changed = hci_dev_test_and_clear_flag(hdev, HCI_LINK_SECURITY);
7737
7738         mgmt_pending_foreach(MGMT_OP_SET_LINK_SECURITY, hdev, settings_rsp,
7739                              &match);
7740
7741         if (changed)
7742                 new_settings(hdev, match.sk);
7743
7744         if (match.sk)
7745                 sock_put(match.sk);
7746 }
7747
7748 static void clear_eir(struct hci_request *req)
7749 {
7750         struct hci_dev *hdev = req->hdev;
7751         struct hci_cp_write_eir cp;
7752
7753         if (!lmp_ext_inq_capable(hdev))
7754                 return;
7755
7756         memset(hdev->eir, 0, sizeof(hdev->eir));
7757
7758         memset(&cp, 0, sizeof(cp));
7759
7760         hci_req_add(req, HCI_OP_WRITE_EIR, sizeof(cp), &cp);
7761 }
7762
7763 void mgmt_ssp_enable_complete(struct hci_dev *hdev, u8 enable, u8 status)
7764 {
7765         struct cmd_lookup match = { NULL, hdev };
7766         struct hci_request req;
7767         bool changed = false;
7768
7769         if (status) {
7770                 u8 mgmt_err = mgmt_status(status);
7771
7772                 if (enable && hci_dev_test_and_clear_flag(hdev,
7773                                                           HCI_SSP_ENABLED)) {
7774                         hci_dev_clear_flag(hdev, HCI_HS_ENABLED);
7775                         new_settings(hdev, NULL);
7776                 }
7777
7778                 mgmt_pending_foreach(MGMT_OP_SET_SSP, hdev, cmd_status_rsp,
7779                                      &mgmt_err);
7780                 return;
7781         }
7782
7783         if (enable) {
7784                 changed = !hci_dev_test_and_set_flag(hdev, HCI_SSP_ENABLED);
7785         } else {
7786                 changed = hci_dev_test_and_clear_flag(hdev, HCI_SSP_ENABLED);
7787                 if (!changed)
7788                         changed = hci_dev_test_and_clear_flag(hdev,
7789                                                               HCI_HS_ENABLED);
7790                 else
7791                         hci_dev_clear_flag(hdev, HCI_HS_ENABLED);
7792         }
7793
7794         mgmt_pending_foreach(MGMT_OP_SET_SSP, hdev, settings_rsp, &match);
7795
7796         if (changed)
7797                 new_settings(hdev, match.sk);
7798
7799         if (match.sk)
7800                 sock_put(match.sk);
7801
7802         hci_req_init(&req, hdev);
7803
7804         if (hci_dev_test_flag(hdev, HCI_SSP_ENABLED)) {
7805                 if (hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS))
7806                         hci_req_add(&req, HCI_OP_WRITE_SSP_DEBUG_MODE,
7807                                     sizeof(enable), &enable);
7808                 update_eir(&req);
7809         } else {
7810                 clear_eir(&req);
7811         }
7812
7813         hci_req_run(&req, NULL);
7814 }
7815
7816 static void sk_lookup(struct mgmt_pending_cmd *cmd, void *data)
7817 {
7818         struct cmd_lookup *match = data;
7819
7820         if (match->sk == NULL) {
7821                 match->sk = cmd->sk;
7822                 sock_hold(match->sk);
7823         }
7824 }
7825
7826 void mgmt_set_class_of_dev_complete(struct hci_dev *hdev, u8 *dev_class,
7827                                     u8 status)
7828 {
7829         struct cmd_lookup match = { NULL, hdev, mgmt_status(status) };
7830
7831         mgmt_pending_foreach(MGMT_OP_SET_DEV_CLASS, hdev, sk_lookup, &match);
7832         mgmt_pending_foreach(MGMT_OP_ADD_UUID, hdev, sk_lookup, &match);
7833         mgmt_pending_foreach(MGMT_OP_REMOVE_UUID, hdev, sk_lookup, &match);
7834
7835         if (!status)
7836                 mgmt_generic_event(MGMT_EV_CLASS_OF_DEV_CHANGED, hdev,
7837                                    dev_class, 3, NULL);
7838
7839         if (match.sk)
7840                 sock_put(match.sk);
7841 }
7842
7843 void mgmt_set_local_name_complete(struct hci_dev *hdev, u8 *name, u8 status)
7844 {
7845         struct mgmt_cp_set_local_name ev;
7846         struct mgmt_pending_cmd *cmd;
7847
7848         if (status)
7849                 return;
7850
7851         memset(&ev, 0, sizeof(ev));
7852         memcpy(ev.name, name, HCI_MAX_NAME_LENGTH);
7853         memcpy(ev.short_name, hdev->short_name, HCI_MAX_SHORT_NAME_LENGTH);
7854
7855         cmd = pending_find(MGMT_OP_SET_LOCAL_NAME, hdev);
7856         if (!cmd) {
7857                 memcpy(hdev->dev_name, name, sizeof(hdev->dev_name));
7858
7859                 /* If this is a HCI command related to powering on the
7860                  * HCI dev don't send any mgmt signals.
7861                  */
7862                 if (pending_find(MGMT_OP_SET_POWERED, hdev))
7863                         return;
7864         }
7865
7866         mgmt_generic_event(MGMT_EV_LOCAL_NAME_CHANGED, hdev, &ev, sizeof(ev),
7867                            cmd ? cmd->sk : NULL);
7868 }
7869
7870 void mgmt_read_local_oob_data_complete(struct hci_dev *hdev, u8 *hash192,
7871                                        u8 *rand192, u8 *hash256, u8 *rand256,
7872                                        u8 status)
7873 {
7874         struct mgmt_pending_cmd *cmd;
7875
7876         BT_DBG("%s status %u", hdev->name, status);
7877
7878         cmd = pending_find(MGMT_OP_READ_LOCAL_OOB_DATA, hdev);
7879         if (!cmd)
7880                 return;
7881
7882         if (status) {
7883                 mgmt_cmd_status(cmd->sk, hdev->id, MGMT_OP_READ_LOCAL_OOB_DATA,
7884                                 mgmt_status(status));
7885         } else {
7886                 struct mgmt_rp_read_local_oob_data rp;
7887                 size_t rp_size = sizeof(rp);
7888
7889                 memcpy(rp.hash192, hash192, sizeof(rp.hash192));
7890                 memcpy(rp.rand192, rand192, sizeof(rp.rand192));
7891
7892                 if (bredr_sc_enabled(hdev) && hash256 && rand256) {
7893                         memcpy(rp.hash256, hash256, sizeof(rp.hash256));
7894                         memcpy(rp.rand256, rand256, sizeof(rp.rand256));
7895                 } else {
7896                         rp_size -= sizeof(rp.hash256) + sizeof(rp.rand256);
7897                 }
7898
7899                 mgmt_cmd_complete(cmd->sk, hdev->id,
7900                                   MGMT_OP_READ_LOCAL_OOB_DATA, 0,
7901                                   &rp, rp_size);
7902         }
7903
7904         mgmt_pending_remove(cmd);
7905 }
7906
7907 static inline bool has_uuid(u8 *uuid, u16 uuid_count, u8 (*uuids)[16])
7908 {
7909         int i;
7910
7911         for (i = 0; i < uuid_count; i++) {
7912                 if (!memcmp(uuid, uuids[i], 16))
7913                         return true;
7914         }
7915
7916         return false;
7917 }
7918
7919 static bool eir_has_uuids(u8 *eir, u16 eir_len, u16 uuid_count, u8 (*uuids)[16])
7920 {
7921         u16 parsed = 0;
7922
7923         while (parsed < eir_len) {
7924                 u8 field_len = eir[0];
7925                 u8 uuid[16];
7926                 int i;
7927
7928                 if (field_len == 0)
7929                         break;
7930
7931                 if (eir_len - parsed < field_len + 1)
7932                         break;
7933
7934                 switch (eir[1]) {
7935                 case EIR_UUID16_ALL:
7936                 case EIR_UUID16_SOME:
7937                         for (i = 0; i + 3 <= field_len; i += 2) {
7938                                 memcpy(uuid, bluetooth_base_uuid, 16);
7939                                 uuid[13] = eir[i + 3];
7940                                 uuid[12] = eir[i + 2];
7941                                 if (has_uuid(uuid, uuid_count, uuids))
7942                                         return true;
7943                         }
7944                         break;
7945                 case EIR_UUID32_ALL:
7946                 case EIR_UUID32_SOME:
7947                         for (i = 0; i + 5 <= field_len; i += 4) {
7948                                 memcpy(uuid, bluetooth_base_uuid, 16);
7949                                 uuid[15] = eir[i + 5];
7950                                 uuid[14] = eir[i + 4];
7951                                 uuid[13] = eir[i + 3];
7952                                 uuid[12] = eir[i + 2];
7953                                 if (has_uuid(uuid, uuid_count, uuids))
7954                                         return true;
7955                         }
7956                         break;
7957                 case EIR_UUID128_ALL:
7958                 case EIR_UUID128_SOME:
7959                         for (i = 0; i + 17 <= field_len; i += 16) {
7960                                 memcpy(uuid, eir + i + 2, 16);
7961                                 if (has_uuid(uuid, uuid_count, uuids))
7962                                         return true;
7963                         }
7964                         break;
7965                 }
7966
7967                 parsed += field_len + 1;
7968                 eir += field_len + 1;
7969         }
7970
7971         return false;
7972 }
7973
7974 static void restart_le_scan(struct hci_dev *hdev)
7975 {
7976         /* If controller is not scanning we are done. */
7977         if (!hci_dev_test_flag(hdev, HCI_LE_SCAN))
7978                 return;
7979
7980         if (time_after(jiffies + DISCOV_LE_RESTART_DELAY,
7981                        hdev->discovery.scan_start +
7982                        hdev->discovery.scan_duration))
7983                 return;
7984
7985         queue_delayed_work(hdev->workqueue, &hdev->le_scan_restart,
7986                            DISCOV_LE_RESTART_DELAY);
7987 }
7988
7989 static bool is_filter_match(struct hci_dev *hdev, s8 rssi, u8 *eir,
7990                             u16 eir_len, u8 *scan_rsp, u8 scan_rsp_len)
7991 {
7992         /* If a RSSI threshold has been specified, and
7993          * HCI_QUIRK_STRICT_DUPLICATE_FILTER is not set, then all results with
7994          * a RSSI smaller than the RSSI threshold will be dropped. If the quirk
7995          * is set, let it through for further processing, as we might need to
7996          * restart the scan.
7997          *
7998          * For BR/EDR devices (pre 1.2) providing no RSSI during inquiry,
7999          * the results are also dropped.
8000          */
8001         if (hdev->discovery.rssi != HCI_RSSI_INVALID &&
8002             (rssi == HCI_RSSI_INVALID ||
8003             (rssi < hdev->discovery.rssi &&
8004              !test_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks))))
8005                 return  false;
8006
8007         if (hdev->discovery.uuid_count != 0) {
8008                 /* If a list of UUIDs is provided in filter, results with no
8009                  * matching UUID should be dropped.
8010                  */
8011                 if (!eir_has_uuids(eir, eir_len, hdev->discovery.uuid_count,
8012                                    hdev->discovery.uuids) &&
8013                     !eir_has_uuids(scan_rsp, scan_rsp_len,
8014                                    hdev->discovery.uuid_count,
8015                                    hdev->discovery.uuids))
8016                         return false;
8017         }
8018
8019         /* If duplicate filtering does not report RSSI changes, then restart
8020          * scanning to ensure updated result with updated RSSI values.
8021          */
8022         if (test_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks)) {
8023                 restart_le_scan(hdev);
8024
8025                 /* Validate RSSI value against the RSSI threshold once more. */
8026                 if (hdev->discovery.rssi != HCI_RSSI_INVALID &&
8027                     rssi < hdev->discovery.rssi)
8028                         return false;
8029         }
8030
8031         return true;
8032 }
8033
8034 void mgmt_device_found(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 link_type,
8035                        u8 addr_type, u8 *dev_class, s8 rssi, u32 flags,
8036                        u8 *eir, u16 eir_len, u8 *scan_rsp, u8 scan_rsp_len)
8037 {
8038         char buf[512];
8039         struct mgmt_ev_device_found *ev = (void *)buf;
8040         size_t ev_size;
8041
8042         /* Don't send events for a non-kernel initiated discovery. With
8043          * LE one exception is if we have pend_le_reports > 0 in which
8044          * case we're doing passive scanning and want these events.
8045          */
8046         if (!hci_discovery_active(hdev)) {
8047                 if (link_type == ACL_LINK)
8048                         return;
8049                 if (link_type == LE_LINK && list_empty(&hdev->pend_le_reports))
8050                         return;
8051         }
8052
8053         if (hdev->discovery.result_filtering) {
8054                 /* We are using service discovery */
8055                 if (!is_filter_match(hdev, rssi, eir, eir_len, scan_rsp,
8056                                      scan_rsp_len))
8057                         return;
8058         }
8059
8060         /* Make sure that the buffer is big enough. The 5 extra bytes
8061          * are for the potential CoD field.
8062          */
8063         if (sizeof(*ev) + eir_len + scan_rsp_len + 5 > sizeof(buf))
8064                 return;
8065
8066         memset(buf, 0, sizeof(buf));
8067
8068         /* In case of device discovery with BR/EDR devices (pre 1.2), the
8069          * RSSI value was reported as 0 when not available. This behavior
8070          * is kept when using device discovery. This is required for full
8071          * backwards compatibility with the API.
8072          *
8073          * However when using service discovery, the value 127 will be
8074          * returned when the RSSI is not available.
8075          */
8076         if (rssi == HCI_RSSI_INVALID && !hdev->discovery.report_invalid_rssi &&
8077             link_type == ACL_LINK)
8078                 rssi = 0;
8079
8080         bacpy(&ev->addr.bdaddr, bdaddr);
8081         ev->addr.type = link_to_bdaddr(link_type, addr_type);
8082         ev->rssi = rssi;
8083         ev->flags = cpu_to_le32(flags);
8084
8085         if (eir_len > 0)
8086                 /* Copy EIR or advertising data into event */
8087                 memcpy(ev->eir, eir, eir_len);
8088
8089         if (dev_class && !eir_has_data_type(ev->eir, eir_len, EIR_CLASS_OF_DEV))
8090                 eir_len = eir_append_data(ev->eir, eir_len, EIR_CLASS_OF_DEV,
8091                                           dev_class, 3);
8092
8093         if (scan_rsp_len > 0)
8094                 /* Append scan response data to event */
8095                 memcpy(ev->eir + eir_len, scan_rsp, scan_rsp_len);
8096
8097         ev->eir_len = cpu_to_le16(eir_len + scan_rsp_len);
8098         ev_size = sizeof(*ev) + eir_len + scan_rsp_len;
8099
8100         mgmt_event(MGMT_EV_DEVICE_FOUND, hdev, ev, ev_size, NULL);
8101 }
8102
8103 void mgmt_remote_name(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 link_type,
8104                       u8 addr_type, s8 rssi, u8 *name, u8 name_len)
8105 {
8106         struct mgmt_ev_device_found *ev;
8107         char buf[sizeof(*ev) + HCI_MAX_NAME_LENGTH + 2];
8108         u16 eir_len;
8109
8110         ev = (struct mgmt_ev_device_found *) buf;
8111
8112         memset(buf, 0, sizeof(buf));
8113
8114         bacpy(&ev->addr.bdaddr, bdaddr);
8115         ev->addr.type = link_to_bdaddr(link_type, addr_type);
8116         ev->rssi = rssi;
8117
8118         eir_len = eir_append_data(ev->eir, 0, EIR_NAME_COMPLETE, name,
8119                                   name_len);
8120
8121         ev->eir_len = cpu_to_le16(eir_len);
8122
8123         mgmt_event(MGMT_EV_DEVICE_FOUND, hdev, ev, sizeof(*ev) + eir_len, NULL);
8124 }
8125
8126 void mgmt_discovering(struct hci_dev *hdev, u8 discovering)
8127 {
8128         struct mgmt_ev_discovering ev;
8129
8130         BT_DBG("%s discovering %u", hdev->name, discovering);
8131
8132         memset(&ev, 0, sizeof(ev));
8133         ev.type = hdev->discovery.type;
8134         ev.discovering = discovering;
8135
8136         mgmt_event(MGMT_EV_DISCOVERING, hdev, &ev, sizeof(ev), NULL);
8137 }
8138
8139 static void adv_enable_complete(struct hci_dev *hdev, u8 status, u16 opcode)
8140 {
8141         BT_DBG("%s status %u", hdev->name, status);
8142 }
8143
8144 void mgmt_reenable_advertising(struct hci_dev *hdev)
8145 {
8146         struct hci_request req;
8147
8148         if (!hci_dev_test_flag(hdev, HCI_ADVERTISING) &&
8149             !hci_dev_test_flag(hdev, HCI_ADVERTISING_INSTANCE))
8150                 return;
8151
8152         hci_req_init(&req, hdev);
8153         enable_advertising(&req);
8154         hci_req_run(&req, adv_enable_complete);
8155 }
8156
8157 static struct hci_mgmt_chan chan = {
8158         .channel        = HCI_CHANNEL_CONTROL,
8159         .handler_count  = ARRAY_SIZE(mgmt_handlers),
8160         .handlers       = mgmt_handlers,
8161         .hdev_init      = mgmt_init_hdev,
8162 };
8163
8164 int mgmt_init(void)
8165 {
8166         return hci_mgmt_chan_register(&chan);
8167 }
8168
8169 void mgmt_exit(void)
8170 {
8171         hci_mgmt_chan_unregister(&chan);
8172 }