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