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