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