usb: gadget: webcam: Make g_webcam loadable again
[platform/kernel/linux-starfive.git] / net / bluetooth / hci_conn.c
1 /*
2    BlueZ - Bluetooth protocol stack for Linux
3    Copyright (c) 2000-2001, 2010, Code Aurora Forum. All rights reserved.
4    Copyright 2023 NXP
5
6    Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License version 2 as
10    published by the Free Software Foundation;
11
12    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
15    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
16    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
17    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20
21    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
22    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
23    SOFTWARE IS DISCLAIMED.
24 */
25
26 /* Bluetooth HCI connection handling. */
27
28 #include <linux/export.h>
29 #include <linux/debugfs.h>
30
31 #include <net/bluetooth/bluetooth.h>
32 #include <net/bluetooth/hci_core.h>
33 #include <net/bluetooth/l2cap.h>
34 #include <net/bluetooth/iso.h>
35 #include <net/bluetooth/mgmt.h>
36
37 #include "hci_request.h"
38 #include "smp.h"
39 #include "a2mp.h"
40 #include "eir.h"
41
42 struct sco_param {
43         u16 pkt_type;
44         u16 max_latency;
45         u8  retrans_effort;
46 };
47
48 struct conn_handle_t {
49         struct hci_conn *conn;
50         __u16 handle;
51 };
52
53 static const struct sco_param esco_param_cvsd[] = {
54         { EDR_ESCO_MASK & ~ESCO_2EV3, 0x000a,   0x01 }, /* S3 */
55         { EDR_ESCO_MASK & ~ESCO_2EV3, 0x0007,   0x01 }, /* S2 */
56         { EDR_ESCO_MASK | ESCO_EV3,   0x0007,   0x01 }, /* S1 */
57         { EDR_ESCO_MASK | ESCO_HV3,   0xffff,   0x01 }, /* D1 */
58         { EDR_ESCO_MASK | ESCO_HV1,   0xffff,   0x01 }, /* D0 */
59 };
60
61 static const struct sco_param sco_param_cvsd[] = {
62         { EDR_ESCO_MASK | ESCO_HV3,   0xffff,   0xff }, /* D1 */
63         { EDR_ESCO_MASK | ESCO_HV1,   0xffff,   0xff }, /* D0 */
64 };
65
66 static const struct sco_param esco_param_msbc[] = {
67         { EDR_ESCO_MASK & ~ESCO_2EV3, 0x000d,   0x02 }, /* T2 */
68         { EDR_ESCO_MASK | ESCO_EV3,   0x0008,   0x02 }, /* T1 */
69 };
70
71 /* This function requires the caller holds hdev->lock */
72 static void hci_connect_le_scan_cleanup(struct hci_conn *conn, u8 status)
73 {
74         struct hci_conn_params *params;
75         struct hci_dev *hdev = conn->hdev;
76         struct smp_irk *irk;
77         bdaddr_t *bdaddr;
78         u8 bdaddr_type;
79
80         bdaddr = &conn->dst;
81         bdaddr_type = conn->dst_type;
82
83         /* Check if we need to convert to identity address */
84         irk = hci_get_irk(hdev, bdaddr, bdaddr_type);
85         if (irk) {
86                 bdaddr = &irk->bdaddr;
87                 bdaddr_type = irk->addr_type;
88         }
89
90         params = hci_pend_le_action_lookup(&hdev->pend_le_conns, bdaddr,
91                                            bdaddr_type);
92         if (!params)
93                 return;
94
95         if (params->conn) {
96                 hci_conn_drop(params->conn);
97                 hci_conn_put(params->conn);
98                 params->conn = NULL;
99         }
100
101         if (!params->explicit_connect)
102                 return;
103
104         /* If the status indicates successful cancellation of
105          * the attempt (i.e. Unknown Connection Id) there's no point of
106          * notifying failure since we'll go back to keep trying to
107          * connect. The only exception is explicit connect requests
108          * where a timeout + cancel does indicate an actual failure.
109          */
110         if (status && status != HCI_ERROR_UNKNOWN_CONN_ID)
111                 mgmt_connect_failed(hdev, &conn->dst, conn->type,
112                                     conn->dst_type, status);
113
114         /* The connection attempt was doing scan for new RPA, and is
115          * in scan phase. If params are not associated with any other
116          * autoconnect action, remove them completely. If they are, just unmark
117          * them as waiting for connection, by clearing explicit_connect field.
118          */
119         params->explicit_connect = false;
120
121         hci_pend_le_list_del_init(params);
122
123         switch (params->auto_connect) {
124         case HCI_AUTO_CONN_EXPLICIT:
125                 hci_conn_params_del(hdev, bdaddr, bdaddr_type);
126                 /* return instead of break to avoid duplicate scan update */
127                 return;
128         case HCI_AUTO_CONN_DIRECT:
129         case HCI_AUTO_CONN_ALWAYS:
130                 hci_pend_le_list_add(params, &hdev->pend_le_conns);
131                 break;
132         case HCI_AUTO_CONN_REPORT:
133                 hci_pend_le_list_add(params, &hdev->pend_le_reports);
134                 break;
135         default:
136                 break;
137         }
138
139         hci_update_passive_scan(hdev);
140 }
141
142 static void hci_conn_cleanup(struct hci_conn *conn)
143 {
144         struct hci_dev *hdev = conn->hdev;
145
146         if (test_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags))
147                 hci_conn_params_del(conn->hdev, &conn->dst, conn->dst_type);
148
149         if (test_and_clear_bit(HCI_CONN_FLUSH_KEY, &conn->flags))
150                 hci_remove_link_key(hdev, &conn->dst);
151
152         hci_chan_list_flush(conn);
153
154         hci_conn_hash_del(hdev, conn);
155
156         if (HCI_CONN_HANDLE_UNSET(conn->handle))
157                 ida_free(&hdev->unset_handle_ida, conn->handle);
158
159         if (conn->cleanup)
160                 conn->cleanup(conn);
161
162         if (conn->type == SCO_LINK || conn->type == ESCO_LINK) {
163                 switch (conn->setting & SCO_AIRMODE_MASK) {
164                 case SCO_AIRMODE_CVSD:
165                 case SCO_AIRMODE_TRANSP:
166                         if (hdev->notify)
167                                 hdev->notify(hdev, HCI_NOTIFY_DISABLE_SCO);
168                         break;
169                 }
170         } else {
171                 if (hdev->notify)
172                         hdev->notify(hdev, HCI_NOTIFY_CONN_DEL);
173         }
174
175         debugfs_remove_recursive(conn->debugfs);
176
177         hci_conn_del_sysfs(conn);
178
179         hci_dev_put(hdev);
180 }
181
182 static void hci_acl_create_connection(struct hci_conn *conn)
183 {
184         struct hci_dev *hdev = conn->hdev;
185         struct inquiry_entry *ie;
186         struct hci_cp_create_conn cp;
187
188         BT_DBG("hcon %p", conn);
189
190         /* Many controllers disallow HCI Create Connection while it is doing
191          * HCI Inquiry. So we cancel the Inquiry first before issuing HCI Create
192          * Connection. This may cause the MGMT discovering state to become false
193          * without user space's request but it is okay since the MGMT Discovery
194          * APIs do not promise that discovery should be done forever. Instead,
195          * the user space monitors the status of MGMT discovering and it may
196          * request for discovery again when this flag becomes false.
197          */
198         if (test_bit(HCI_INQUIRY, &hdev->flags)) {
199                 /* Put this connection to "pending" state so that it will be
200                  * executed after the inquiry cancel command complete event.
201                  */
202                 conn->state = BT_CONNECT2;
203                 hci_send_cmd(hdev, HCI_OP_INQUIRY_CANCEL, 0, NULL);
204                 return;
205         }
206
207         conn->state = BT_CONNECT;
208         conn->out = true;
209         conn->role = HCI_ROLE_MASTER;
210
211         conn->attempt++;
212
213         conn->link_policy = hdev->link_policy;
214
215         memset(&cp, 0, sizeof(cp));
216         bacpy(&cp.bdaddr, &conn->dst);
217         cp.pscan_rep_mode = 0x02;
218
219         ie = hci_inquiry_cache_lookup(hdev, &conn->dst);
220         if (ie) {
221                 if (inquiry_entry_age(ie) <= INQUIRY_ENTRY_AGE_MAX) {
222                         cp.pscan_rep_mode = ie->data.pscan_rep_mode;
223                         cp.pscan_mode     = ie->data.pscan_mode;
224                         cp.clock_offset   = ie->data.clock_offset |
225                                             cpu_to_le16(0x8000);
226                 }
227
228                 memcpy(conn->dev_class, ie->data.dev_class, 3);
229         }
230
231         cp.pkt_type = cpu_to_le16(conn->pkt_type);
232         if (lmp_rswitch_capable(hdev) && !(hdev->link_mode & HCI_LM_MASTER))
233                 cp.role_switch = 0x01;
234         else
235                 cp.role_switch = 0x00;
236
237         hci_send_cmd(hdev, HCI_OP_CREATE_CONN, sizeof(cp), &cp);
238 }
239
240 int hci_disconnect(struct hci_conn *conn, __u8 reason)
241 {
242         BT_DBG("hcon %p", conn);
243
244         /* When we are central of an established connection and it enters
245          * the disconnect timeout, then go ahead and try to read the
246          * current clock offset.  Processing of the result is done
247          * within the event handling and hci_clock_offset_evt function.
248          */
249         if (conn->type == ACL_LINK && conn->role == HCI_ROLE_MASTER &&
250             (conn->state == BT_CONNECTED || conn->state == BT_CONFIG)) {
251                 struct hci_dev *hdev = conn->hdev;
252                 struct hci_cp_read_clock_offset clkoff_cp;
253
254                 clkoff_cp.handle = cpu_to_le16(conn->handle);
255                 hci_send_cmd(hdev, HCI_OP_READ_CLOCK_OFFSET, sizeof(clkoff_cp),
256                              &clkoff_cp);
257         }
258
259         return hci_abort_conn(conn, reason);
260 }
261
262 static void hci_add_sco(struct hci_conn *conn, __u16 handle)
263 {
264         struct hci_dev *hdev = conn->hdev;
265         struct hci_cp_add_sco cp;
266
267         BT_DBG("hcon %p", conn);
268
269         conn->state = BT_CONNECT;
270         conn->out = true;
271
272         conn->attempt++;
273
274         cp.handle   = cpu_to_le16(handle);
275         cp.pkt_type = cpu_to_le16(conn->pkt_type);
276
277         hci_send_cmd(hdev, HCI_OP_ADD_SCO, sizeof(cp), &cp);
278 }
279
280 static bool find_next_esco_param(struct hci_conn *conn,
281                                  const struct sco_param *esco_param, int size)
282 {
283         if (!conn->parent)
284                 return false;
285
286         for (; conn->attempt <= size; conn->attempt++) {
287                 if (lmp_esco_2m_capable(conn->parent) ||
288                     (esco_param[conn->attempt - 1].pkt_type & ESCO_2EV3))
289                         break;
290                 BT_DBG("hcon %p skipped attempt %d, eSCO 2M not supported",
291                        conn, conn->attempt);
292         }
293
294         return conn->attempt <= size;
295 }
296
297 static int configure_datapath_sync(struct hci_dev *hdev, struct bt_codec *codec)
298 {
299         int err;
300         __u8 vnd_len, *vnd_data = NULL;
301         struct hci_op_configure_data_path *cmd = NULL;
302
303         err = hdev->get_codec_config_data(hdev, ESCO_LINK, codec, &vnd_len,
304                                           &vnd_data);
305         if (err < 0)
306                 goto error;
307
308         cmd = kzalloc(sizeof(*cmd) + vnd_len, GFP_KERNEL);
309         if (!cmd) {
310                 err = -ENOMEM;
311                 goto error;
312         }
313
314         err = hdev->get_data_path_id(hdev, &cmd->data_path_id);
315         if (err < 0)
316                 goto error;
317
318         cmd->vnd_len = vnd_len;
319         memcpy(cmd->vnd_data, vnd_data, vnd_len);
320
321         cmd->direction = 0x00;
322         __hci_cmd_sync_status(hdev, HCI_CONFIGURE_DATA_PATH,
323                               sizeof(*cmd) + vnd_len, cmd, HCI_CMD_TIMEOUT);
324
325         cmd->direction = 0x01;
326         err = __hci_cmd_sync_status(hdev, HCI_CONFIGURE_DATA_PATH,
327                                     sizeof(*cmd) + vnd_len, cmd,
328                                     HCI_CMD_TIMEOUT);
329 error:
330
331         kfree(cmd);
332         kfree(vnd_data);
333         return err;
334 }
335
336 static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data)
337 {
338         struct conn_handle_t *conn_handle = data;
339         struct hci_conn *conn = conn_handle->conn;
340         __u16 handle = conn_handle->handle;
341         struct hci_cp_enhanced_setup_sync_conn cp;
342         const struct sco_param *param;
343
344         kfree(conn_handle);
345
346         bt_dev_dbg(hdev, "hcon %p", conn);
347
348         /* for offload use case, codec needs to configured before opening SCO */
349         if (conn->codec.data_path)
350                 configure_datapath_sync(hdev, &conn->codec);
351
352         conn->state = BT_CONNECT;
353         conn->out = true;
354
355         conn->attempt++;
356
357         memset(&cp, 0x00, sizeof(cp));
358
359         cp.handle   = cpu_to_le16(handle);
360
361         cp.tx_bandwidth   = cpu_to_le32(0x00001f40);
362         cp.rx_bandwidth   = cpu_to_le32(0x00001f40);
363
364         switch (conn->codec.id) {
365         case BT_CODEC_MSBC:
366                 if (!find_next_esco_param(conn, esco_param_msbc,
367                                           ARRAY_SIZE(esco_param_msbc)))
368                         return -EINVAL;
369
370                 param = &esco_param_msbc[conn->attempt - 1];
371                 cp.tx_coding_format.id = 0x05;
372                 cp.rx_coding_format.id = 0x05;
373                 cp.tx_codec_frame_size = __cpu_to_le16(60);
374                 cp.rx_codec_frame_size = __cpu_to_le16(60);
375                 cp.in_bandwidth = __cpu_to_le32(32000);
376                 cp.out_bandwidth = __cpu_to_le32(32000);
377                 cp.in_coding_format.id = 0x04;
378                 cp.out_coding_format.id = 0x04;
379                 cp.in_coded_data_size = __cpu_to_le16(16);
380                 cp.out_coded_data_size = __cpu_to_le16(16);
381                 cp.in_pcm_data_format = 2;
382                 cp.out_pcm_data_format = 2;
383                 cp.in_pcm_sample_payload_msb_pos = 0;
384                 cp.out_pcm_sample_payload_msb_pos = 0;
385                 cp.in_data_path = conn->codec.data_path;
386                 cp.out_data_path = conn->codec.data_path;
387                 cp.in_transport_unit_size = 1;
388                 cp.out_transport_unit_size = 1;
389                 break;
390
391         case BT_CODEC_TRANSPARENT:
392                 if (!find_next_esco_param(conn, esco_param_msbc,
393                                           ARRAY_SIZE(esco_param_msbc)))
394                         return false;
395                 param = &esco_param_msbc[conn->attempt - 1];
396                 cp.tx_coding_format.id = 0x03;
397                 cp.rx_coding_format.id = 0x03;
398                 cp.tx_codec_frame_size = __cpu_to_le16(60);
399                 cp.rx_codec_frame_size = __cpu_to_le16(60);
400                 cp.in_bandwidth = __cpu_to_le32(0x1f40);
401                 cp.out_bandwidth = __cpu_to_le32(0x1f40);
402                 cp.in_coding_format.id = 0x03;
403                 cp.out_coding_format.id = 0x03;
404                 cp.in_coded_data_size = __cpu_to_le16(16);
405                 cp.out_coded_data_size = __cpu_to_le16(16);
406                 cp.in_pcm_data_format = 2;
407                 cp.out_pcm_data_format = 2;
408                 cp.in_pcm_sample_payload_msb_pos = 0;
409                 cp.out_pcm_sample_payload_msb_pos = 0;
410                 cp.in_data_path = conn->codec.data_path;
411                 cp.out_data_path = conn->codec.data_path;
412                 cp.in_transport_unit_size = 1;
413                 cp.out_transport_unit_size = 1;
414                 break;
415
416         case BT_CODEC_CVSD:
417                 if (conn->parent && lmp_esco_capable(conn->parent)) {
418                         if (!find_next_esco_param(conn, esco_param_cvsd,
419                                                   ARRAY_SIZE(esco_param_cvsd)))
420                                 return -EINVAL;
421                         param = &esco_param_cvsd[conn->attempt - 1];
422                 } else {
423                         if (conn->attempt > ARRAY_SIZE(sco_param_cvsd))
424                                 return -EINVAL;
425                         param = &sco_param_cvsd[conn->attempt - 1];
426                 }
427                 cp.tx_coding_format.id = 2;
428                 cp.rx_coding_format.id = 2;
429                 cp.tx_codec_frame_size = __cpu_to_le16(60);
430                 cp.rx_codec_frame_size = __cpu_to_le16(60);
431                 cp.in_bandwidth = __cpu_to_le32(16000);
432                 cp.out_bandwidth = __cpu_to_le32(16000);
433                 cp.in_coding_format.id = 4;
434                 cp.out_coding_format.id = 4;
435                 cp.in_coded_data_size = __cpu_to_le16(16);
436                 cp.out_coded_data_size = __cpu_to_le16(16);
437                 cp.in_pcm_data_format = 2;
438                 cp.out_pcm_data_format = 2;
439                 cp.in_pcm_sample_payload_msb_pos = 0;
440                 cp.out_pcm_sample_payload_msb_pos = 0;
441                 cp.in_data_path = conn->codec.data_path;
442                 cp.out_data_path = conn->codec.data_path;
443                 cp.in_transport_unit_size = 16;
444                 cp.out_transport_unit_size = 16;
445                 break;
446         default:
447                 return -EINVAL;
448         }
449
450         cp.retrans_effort = param->retrans_effort;
451         cp.pkt_type = __cpu_to_le16(param->pkt_type);
452         cp.max_latency = __cpu_to_le16(param->max_latency);
453
454         if (hci_send_cmd(hdev, HCI_OP_ENHANCED_SETUP_SYNC_CONN, sizeof(cp), &cp) < 0)
455                 return -EIO;
456
457         return 0;
458 }
459
460 static bool hci_setup_sync_conn(struct hci_conn *conn, __u16 handle)
461 {
462         struct hci_dev *hdev = conn->hdev;
463         struct hci_cp_setup_sync_conn cp;
464         const struct sco_param *param;
465
466         bt_dev_dbg(hdev, "hcon %p", conn);
467
468         conn->state = BT_CONNECT;
469         conn->out = true;
470
471         conn->attempt++;
472
473         cp.handle   = cpu_to_le16(handle);
474
475         cp.tx_bandwidth   = cpu_to_le32(0x00001f40);
476         cp.rx_bandwidth   = cpu_to_le32(0x00001f40);
477         cp.voice_setting  = cpu_to_le16(conn->setting);
478
479         switch (conn->setting & SCO_AIRMODE_MASK) {
480         case SCO_AIRMODE_TRANSP:
481                 if (!find_next_esco_param(conn, esco_param_msbc,
482                                           ARRAY_SIZE(esco_param_msbc)))
483                         return false;
484                 param = &esco_param_msbc[conn->attempt - 1];
485                 break;
486         case SCO_AIRMODE_CVSD:
487                 if (conn->parent && lmp_esco_capable(conn->parent)) {
488                         if (!find_next_esco_param(conn, esco_param_cvsd,
489                                                   ARRAY_SIZE(esco_param_cvsd)))
490                                 return false;
491                         param = &esco_param_cvsd[conn->attempt - 1];
492                 } else {
493                         if (conn->attempt > ARRAY_SIZE(sco_param_cvsd))
494                                 return false;
495                         param = &sco_param_cvsd[conn->attempt - 1];
496                 }
497                 break;
498         default:
499                 return false;
500         }
501
502         cp.retrans_effort = param->retrans_effort;
503         cp.pkt_type = __cpu_to_le16(param->pkt_type);
504         cp.max_latency = __cpu_to_le16(param->max_latency);
505
506         if (hci_send_cmd(hdev, HCI_OP_SETUP_SYNC_CONN, sizeof(cp), &cp) < 0)
507                 return false;
508
509         return true;
510 }
511
512 bool hci_setup_sync(struct hci_conn *conn, __u16 handle)
513 {
514         int result;
515         struct conn_handle_t *conn_handle;
516
517         if (enhanced_sync_conn_capable(conn->hdev)) {
518                 conn_handle = kzalloc(sizeof(*conn_handle), GFP_KERNEL);
519
520                 if (!conn_handle)
521                         return false;
522
523                 conn_handle->conn = conn;
524                 conn_handle->handle = handle;
525                 result = hci_cmd_sync_queue(conn->hdev, hci_enhanced_setup_sync,
526                                             conn_handle, NULL);
527                 if (result < 0)
528                         kfree(conn_handle);
529
530                 return result == 0;
531         }
532
533         return hci_setup_sync_conn(conn, handle);
534 }
535
536 u8 hci_le_conn_update(struct hci_conn *conn, u16 min, u16 max, u16 latency,
537                       u16 to_multiplier)
538 {
539         struct hci_dev *hdev = conn->hdev;
540         struct hci_conn_params *params;
541         struct hci_cp_le_conn_update cp;
542
543         hci_dev_lock(hdev);
544
545         params = hci_conn_params_lookup(hdev, &conn->dst, conn->dst_type);
546         if (params) {
547                 params->conn_min_interval = min;
548                 params->conn_max_interval = max;
549                 params->conn_latency = latency;
550                 params->supervision_timeout = to_multiplier;
551         }
552
553         hci_dev_unlock(hdev);
554
555         memset(&cp, 0, sizeof(cp));
556         cp.handle               = cpu_to_le16(conn->handle);
557         cp.conn_interval_min    = cpu_to_le16(min);
558         cp.conn_interval_max    = cpu_to_le16(max);
559         cp.conn_latency         = cpu_to_le16(latency);
560         cp.supervision_timeout  = cpu_to_le16(to_multiplier);
561         cp.min_ce_len           = cpu_to_le16(0x0000);
562         cp.max_ce_len           = cpu_to_le16(0x0000);
563
564         hci_send_cmd(hdev, HCI_OP_LE_CONN_UPDATE, sizeof(cp), &cp);
565
566         if (params)
567                 return 0x01;
568
569         return 0x00;
570 }
571
572 void hci_le_start_enc(struct hci_conn *conn, __le16 ediv, __le64 rand,
573                       __u8 ltk[16], __u8 key_size)
574 {
575         struct hci_dev *hdev = conn->hdev;
576         struct hci_cp_le_start_enc cp;
577
578         BT_DBG("hcon %p", conn);
579
580         memset(&cp, 0, sizeof(cp));
581
582         cp.handle = cpu_to_le16(conn->handle);
583         cp.rand = rand;
584         cp.ediv = ediv;
585         memcpy(cp.ltk, ltk, key_size);
586
587         hci_send_cmd(hdev, HCI_OP_LE_START_ENC, sizeof(cp), &cp);
588 }
589
590 /* Device _must_ be locked */
591 void hci_sco_setup(struct hci_conn *conn, __u8 status)
592 {
593         struct hci_link *link;
594
595         link = list_first_entry_or_null(&conn->link_list, struct hci_link, list);
596         if (!link || !link->conn)
597                 return;
598
599         BT_DBG("hcon %p", conn);
600
601         if (!status) {
602                 if (lmp_esco_capable(conn->hdev))
603                         hci_setup_sync(link->conn, conn->handle);
604                 else
605                         hci_add_sco(link->conn, conn->handle);
606         } else {
607                 hci_connect_cfm(link->conn, status);
608                 hci_conn_del(link->conn);
609         }
610 }
611
612 static void hci_conn_timeout(struct work_struct *work)
613 {
614         struct hci_conn *conn = container_of(work, struct hci_conn,
615                                              disc_work.work);
616         int refcnt = atomic_read(&conn->refcnt);
617
618         BT_DBG("hcon %p state %s", conn, state_to_string(conn->state));
619
620         WARN_ON(refcnt < 0);
621
622         /* FIXME: It was observed that in pairing failed scenario, refcnt
623          * drops below 0. Probably this is because l2cap_conn_del calls
624          * l2cap_chan_del for each channel, and inside l2cap_chan_del conn is
625          * dropped. After that loop hci_chan_del is called which also drops
626          * conn. For now make sure that ACL is alive if refcnt is higher then 0,
627          * otherwise drop it.
628          */
629         if (refcnt > 0)
630                 return;
631
632         hci_abort_conn(conn, hci_proto_disconn_ind(conn));
633 }
634
635 /* Enter sniff mode */
636 static void hci_conn_idle(struct work_struct *work)
637 {
638         struct hci_conn *conn = container_of(work, struct hci_conn,
639                                              idle_work.work);
640         struct hci_dev *hdev = conn->hdev;
641
642         BT_DBG("hcon %p mode %d", conn, conn->mode);
643
644         if (!lmp_sniff_capable(hdev) || !lmp_sniff_capable(conn))
645                 return;
646
647         if (conn->mode != HCI_CM_ACTIVE || !(conn->link_policy & HCI_LP_SNIFF))
648                 return;
649
650         if (lmp_sniffsubr_capable(hdev) && lmp_sniffsubr_capable(conn)) {
651                 struct hci_cp_sniff_subrate cp;
652                 cp.handle             = cpu_to_le16(conn->handle);
653                 cp.max_latency        = cpu_to_le16(0);
654                 cp.min_remote_timeout = cpu_to_le16(0);
655                 cp.min_local_timeout  = cpu_to_le16(0);
656                 hci_send_cmd(hdev, HCI_OP_SNIFF_SUBRATE, sizeof(cp), &cp);
657         }
658
659         if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) {
660                 struct hci_cp_sniff_mode cp;
661                 cp.handle       = cpu_to_le16(conn->handle);
662                 cp.max_interval = cpu_to_le16(hdev->sniff_max_interval);
663                 cp.min_interval = cpu_to_le16(hdev->sniff_min_interval);
664                 cp.attempt      = cpu_to_le16(4);
665                 cp.timeout      = cpu_to_le16(1);
666                 hci_send_cmd(hdev, HCI_OP_SNIFF_MODE, sizeof(cp), &cp);
667         }
668 }
669
670 static void hci_conn_auto_accept(struct work_struct *work)
671 {
672         struct hci_conn *conn = container_of(work, struct hci_conn,
673                                              auto_accept_work.work);
674
675         hci_send_cmd(conn->hdev, HCI_OP_USER_CONFIRM_REPLY, sizeof(conn->dst),
676                      &conn->dst);
677 }
678
679 static void le_disable_advertising(struct hci_dev *hdev)
680 {
681         if (ext_adv_capable(hdev)) {
682                 struct hci_cp_le_set_ext_adv_enable cp;
683
684                 cp.enable = 0x00;
685                 cp.num_of_sets = 0x00;
686
687                 hci_send_cmd(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE, sizeof(cp),
688                              &cp);
689         } else {
690                 u8 enable = 0x00;
691                 hci_send_cmd(hdev, HCI_OP_LE_SET_ADV_ENABLE, sizeof(enable),
692                              &enable);
693         }
694 }
695
696 static void le_conn_timeout(struct work_struct *work)
697 {
698         struct hci_conn *conn = container_of(work, struct hci_conn,
699                                              le_conn_timeout.work);
700         struct hci_dev *hdev = conn->hdev;
701
702         BT_DBG("");
703
704         /* We could end up here due to having done directed advertising,
705          * so clean up the state if necessary. This should however only
706          * happen with broken hardware or if low duty cycle was used
707          * (which doesn't have a timeout of its own).
708          */
709         if (conn->role == HCI_ROLE_SLAVE) {
710                 /* Disable LE Advertising */
711                 le_disable_advertising(hdev);
712                 hci_dev_lock(hdev);
713                 hci_conn_failed(conn, HCI_ERROR_ADVERTISING_TIMEOUT);
714                 hci_dev_unlock(hdev);
715                 return;
716         }
717
718         hci_abort_conn(conn, HCI_ERROR_REMOTE_USER_TERM);
719 }
720
721 struct iso_cig_params {
722         struct hci_cp_le_set_cig_params cp;
723         struct hci_cis_params cis[0x1f];
724 };
725
726 struct iso_list_data {
727         union {
728                 u8  cig;
729                 u8  big;
730         };
731         union {
732                 u8  cis;
733                 u8  bis;
734                 u16 sync_handle;
735         };
736         int count;
737         bool big_term;
738         bool pa_sync_term;
739         bool big_sync_term;
740 };
741
742 static void bis_list(struct hci_conn *conn, void *data)
743 {
744         struct iso_list_data *d = data;
745
746         /* Skip if not broadcast/ANY address */
747         if (bacmp(&conn->dst, BDADDR_ANY))
748                 return;
749
750         if (d->big != conn->iso_qos.bcast.big || d->bis == BT_ISO_QOS_BIS_UNSET ||
751             d->bis != conn->iso_qos.bcast.bis)
752                 return;
753
754         d->count++;
755 }
756
757 static int terminate_big_sync(struct hci_dev *hdev, void *data)
758 {
759         struct iso_list_data *d = data;
760
761         bt_dev_dbg(hdev, "big 0x%2.2x bis 0x%2.2x", d->big, d->bis);
762
763         hci_remove_ext_adv_instance_sync(hdev, d->bis, NULL);
764
765         /* Only terminate BIG if it has been created */
766         if (!d->big_term)
767                 return 0;
768
769         return hci_le_terminate_big_sync(hdev, d->big,
770                                          HCI_ERROR_LOCAL_HOST_TERM);
771 }
772
773 static void terminate_big_destroy(struct hci_dev *hdev, void *data, int err)
774 {
775         kfree(data);
776 }
777
778 static int hci_le_terminate_big(struct hci_dev *hdev, struct hci_conn *conn)
779 {
780         struct iso_list_data *d;
781         int ret;
782
783         bt_dev_dbg(hdev, "big 0x%2.2x bis 0x%2.2x", conn->iso_qos.bcast.big,
784                    conn->iso_qos.bcast.bis);
785
786         d = kzalloc(sizeof(*d), GFP_KERNEL);
787         if (!d)
788                 return -ENOMEM;
789
790         d->big = conn->iso_qos.bcast.big;
791         d->bis = conn->iso_qos.bcast.bis;
792         d->big_term = test_and_clear_bit(HCI_CONN_BIG_CREATED, &conn->flags);
793
794         ret = hci_cmd_sync_queue(hdev, terminate_big_sync, d,
795                                  terminate_big_destroy);
796         if (ret)
797                 kfree(d);
798
799         return ret;
800 }
801
802 static int big_terminate_sync(struct hci_dev *hdev, void *data)
803 {
804         struct iso_list_data *d = data;
805
806         bt_dev_dbg(hdev, "big 0x%2.2x sync_handle 0x%4.4x", d->big,
807                    d->sync_handle);
808
809         if (d->big_sync_term)
810                 hci_le_big_terminate_sync(hdev, d->big);
811
812         if (d->pa_sync_term)
813                 return hci_le_pa_terminate_sync(hdev, d->sync_handle);
814
815         return 0;
816 }
817
818 static int hci_le_big_terminate(struct hci_dev *hdev, u8 big, struct hci_conn *conn)
819 {
820         struct iso_list_data *d;
821         int ret;
822
823         bt_dev_dbg(hdev, "big 0x%2.2x sync_handle 0x%4.4x", big, conn->sync_handle);
824
825         d = kzalloc(sizeof(*d), GFP_KERNEL);
826         if (!d)
827                 return -ENOMEM;
828
829         d->big = big;
830         d->sync_handle = conn->sync_handle;
831         d->pa_sync_term = test_and_clear_bit(HCI_CONN_PA_SYNC, &conn->flags);
832         d->big_sync_term = test_and_clear_bit(HCI_CONN_BIG_SYNC, &conn->flags);
833
834         ret = hci_cmd_sync_queue(hdev, big_terminate_sync, d,
835                                  terminate_big_destroy);
836         if (ret)
837                 kfree(d);
838
839         return ret;
840 }
841
842 /* Cleanup BIS connection
843  *
844  * Detects if there any BIS left connected in a BIG
845  * broadcaster: Remove advertising instance and terminate BIG.
846  * broadcaster receiver: Teminate BIG sync and terminate PA sync.
847  */
848 static void bis_cleanup(struct hci_conn *conn)
849 {
850         struct hci_dev *hdev = conn->hdev;
851         struct hci_conn *bis;
852
853         bt_dev_dbg(hdev, "conn %p", conn);
854
855         if (conn->role == HCI_ROLE_MASTER) {
856                 if (!test_and_clear_bit(HCI_CONN_PER_ADV, &conn->flags))
857                         return;
858
859                 /* Check if ISO connection is a BIS and terminate advertising
860                  * set and BIG if there are no other connections using it.
861                  */
862                 bis = hci_conn_hash_lookup_big(hdev, conn->iso_qos.bcast.big);
863                 if (bis)
864                         return;
865
866                 hci_le_terminate_big(hdev, conn);
867         } else {
868                 bis = hci_conn_hash_lookup_big_any_dst(hdev,
869                                                        conn->iso_qos.bcast.big);
870
871                 if (bis)
872                         return;
873
874                 hci_le_big_terminate(hdev, conn->iso_qos.bcast.big,
875                                      conn);
876         }
877 }
878
879 static int remove_cig_sync(struct hci_dev *hdev, void *data)
880 {
881         u8 handle = PTR_UINT(data);
882
883         return hci_le_remove_cig_sync(hdev, handle);
884 }
885
886 static int hci_le_remove_cig(struct hci_dev *hdev, u8 handle)
887 {
888         bt_dev_dbg(hdev, "handle 0x%2.2x", handle);
889
890         return hci_cmd_sync_queue(hdev, remove_cig_sync, UINT_PTR(handle),
891                                   NULL);
892 }
893
894 static void find_cis(struct hci_conn *conn, void *data)
895 {
896         struct iso_list_data *d = data;
897
898         /* Ignore broadcast or if CIG don't match */
899         if (!bacmp(&conn->dst, BDADDR_ANY) || d->cig != conn->iso_qos.ucast.cig)
900                 return;
901
902         d->count++;
903 }
904
905 /* Cleanup CIS connection:
906  *
907  * Detects if there any CIS left connected in a CIG and remove it.
908  */
909 static void cis_cleanup(struct hci_conn *conn)
910 {
911         struct hci_dev *hdev = conn->hdev;
912         struct iso_list_data d;
913
914         if (conn->iso_qos.ucast.cig == BT_ISO_QOS_CIG_UNSET)
915                 return;
916
917         memset(&d, 0, sizeof(d));
918         d.cig = conn->iso_qos.ucast.cig;
919
920         /* Check if ISO connection is a CIS and remove CIG if there are
921          * no other connections using it.
922          */
923         hci_conn_hash_list_state(hdev, find_cis, ISO_LINK, BT_BOUND, &d);
924         hci_conn_hash_list_state(hdev, find_cis, ISO_LINK, BT_CONNECT, &d);
925         hci_conn_hash_list_state(hdev, find_cis, ISO_LINK, BT_CONNECTED, &d);
926         if (d.count)
927                 return;
928
929         hci_le_remove_cig(hdev, conn->iso_qos.ucast.cig);
930 }
931
932 static int hci_conn_hash_alloc_unset(struct hci_dev *hdev)
933 {
934         return ida_alloc_range(&hdev->unset_handle_ida, HCI_CONN_HANDLE_MAX + 1,
935                                U16_MAX, GFP_ATOMIC);
936 }
937
938 struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type, bdaddr_t *dst,
939                               u8 role, u16 handle)
940 {
941         struct hci_conn *conn;
942
943         bt_dev_dbg(hdev, "dst %pMR handle 0x%4.4x", dst, handle);
944
945         conn = kzalloc(sizeof(*conn), GFP_KERNEL);
946         if (!conn)
947                 return NULL;
948
949         bacpy(&conn->dst, dst);
950         bacpy(&conn->src, &hdev->bdaddr);
951         conn->handle = handle;
952         conn->hdev  = hdev;
953         conn->type  = type;
954         conn->role  = role;
955         conn->mode  = HCI_CM_ACTIVE;
956         conn->state = BT_OPEN;
957         conn->auth_type = HCI_AT_GENERAL_BONDING;
958         conn->io_capability = hdev->io_capability;
959         conn->remote_auth = 0xff;
960         conn->key_type = 0xff;
961         conn->rssi = HCI_RSSI_INVALID;
962         conn->tx_power = HCI_TX_POWER_INVALID;
963         conn->max_tx_power = HCI_TX_POWER_INVALID;
964         conn->sync_handle = HCI_SYNC_HANDLE_INVALID;
965
966         set_bit(HCI_CONN_POWER_SAVE, &conn->flags);
967         conn->disc_timeout = HCI_DISCONN_TIMEOUT;
968
969         /* Set Default Authenticated payload timeout to 30s */
970         conn->auth_payload_timeout = DEFAULT_AUTH_PAYLOAD_TIMEOUT;
971
972         if (conn->role == HCI_ROLE_MASTER)
973                 conn->out = true;
974
975         switch (type) {
976         case ACL_LINK:
977                 conn->pkt_type = hdev->pkt_type & ACL_PTYPE_MASK;
978                 break;
979         case LE_LINK:
980                 /* conn->src should reflect the local identity address */
981                 hci_copy_identity_address(hdev, &conn->src, &conn->src_type);
982                 break;
983         case ISO_LINK:
984                 /* conn->src should reflect the local identity address */
985                 hci_copy_identity_address(hdev, &conn->src, &conn->src_type);
986
987                 /* set proper cleanup function */
988                 if (!bacmp(dst, BDADDR_ANY))
989                         conn->cleanup = bis_cleanup;
990                 else if (conn->role == HCI_ROLE_MASTER)
991                         conn->cleanup = cis_cleanup;
992
993                 break;
994         case SCO_LINK:
995                 if (lmp_esco_capable(hdev))
996                         conn->pkt_type = (hdev->esco_type & SCO_ESCO_MASK) |
997                                         (hdev->esco_type & EDR_ESCO_MASK);
998                 else
999                         conn->pkt_type = hdev->pkt_type & SCO_PTYPE_MASK;
1000                 break;
1001         case ESCO_LINK:
1002                 conn->pkt_type = hdev->esco_type & ~EDR_ESCO_MASK;
1003                 break;
1004         }
1005
1006         skb_queue_head_init(&conn->data_q);
1007
1008         INIT_LIST_HEAD(&conn->chan_list);
1009         INIT_LIST_HEAD(&conn->link_list);
1010
1011         INIT_DELAYED_WORK(&conn->disc_work, hci_conn_timeout);
1012         INIT_DELAYED_WORK(&conn->auto_accept_work, hci_conn_auto_accept);
1013         INIT_DELAYED_WORK(&conn->idle_work, hci_conn_idle);
1014         INIT_DELAYED_WORK(&conn->le_conn_timeout, le_conn_timeout);
1015
1016         atomic_set(&conn->refcnt, 0);
1017
1018         hci_dev_hold(hdev);
1019
1020         hci_conn_hash_add(hdev, conn);
1021
1022         /* The SCO and eSCO connections will only be notified when their
1023          * setup has been completed. This is different to ACL links which
1024          * can be notified right away.
1025          */
1026         if (conn->type != SCO_LINK && conn->type != ESCO_LINK) {
1027                 if (hdev->notify)
1028                         hdev->notify(hdev, HCI_NOTIFY_CONN_ADD);
1029         }
1030
1031         hci_conn_init_sysfs(conn);
1032
1033         return conn;
1034 }
1035
1036 struct hci_conn *hci_conn_add_unset(struct hci_dev *hdev, int type,
1037                                     bdaddr_t *dst, u8 role)
1038 {
1039         int handle;
1040
1041         bt_dev_dbg(hdev, "dst %pMR", dst);
1042
1043         handle = hci_conn_hash_alloc_unset(hdev);
1044         if (unlikely(handle < 0))
1045                 return NULL;
1046
1047         return hci_conn_add(hdev, type, dst, role, handle);
1048 }
1049
1050 static void hci_conn_cleanup_child(struct hci_conn *conn, u8 reason)
1051 {
1052         if (!reason)
1053                 reason = HCI_ERROR_REMOTE_USER_TERM;
1054
1055         /* Due to race, SCO/ISO conn might be not established yet at this point,
1056          * and nothing else will clean it up. In other cases it is done via HCI
1057          * events.
1058          */
1059         switch (conn->type) {
1060         case SCO_LINK:
1061         case ESCO_LINK:
1062                 if (HCI_CONN_HANDLE_UNSET(conn->handle))
1063                         hci_conn_failed(conn, reason);
1064                 break;
1065         case ISO_LINK:
1066                 if (conn->state != BT_CONNECTED &&
1067                     !test_bit(HCI_CONN_CREATE_CIS, &conn->flags))
1068                         hci_conn_failed(conn, reason);
1069                 break;
1070         }
1071 }
1072
1073 static void hci_conn_unlink(struct hci_conn *conn)
1074 {
1075         struct hci_dev *hdev = conn->hdev;
1076
1077         bt_dev_dbg(hdev, "hcon %p", conn);
1078
1079         if (!conn->parent) {
1080                 struct hci_link *link, *t;
1081
1082                 list_for_each_entry_safe(link, t, &conn->link_list, list) {
1083                         struct hci_conn *child = link->conn;
1084
1085                         hci_conn_unlink(child);
1086
1087                         /* If hdev is down it means
1088                          * hci_dev_close_sync/hci_conn_hash_flush is in progress
1089                          * and links don't need to be cleanup as all connections
1090                          * would be cleanup.
1091                          */
1092                         if (!test_bit(HCI_UP, &hdev->flags))
1093                                 continue;
1094
1095                         hci_conn_cleanup_child(child, conn->abort_reason);
1096                 }
1097
1098                 return;
1099         }
1100
1101         if (!conn->link)
1102                 return;
1103
1104         list_del_rcu(&conn->link->list);
1105         synchronize_rcu();
1106
1107         hci_conn_drop(conn->parent);
1108         hci_conn_put(conn->parent);
1109         conn->parent = NULL;
1110
1111         kfree(conn->link);
1112         conn->link = NULL;
1113 }
1114
1115 void hci_conn_del(struct hci_conn *conn)
1116 {
1117         struct hci_dev *hdev = conn->hdev;
1118
1119         BT_DBG("%s hcon %p handle %d", hdev->name, conn, conn->handle);
1120
1121         hci_conn_unlink(conn);
1122
1123         cancel_delayed_work_sync(&conn->disc_work);
1124         cancel_delayed_work_sync(&conn->auto_accept_work);
1125         cancel_delayed_work_sync(&conn->idle_work);
1126
1127         if (conn->type == ACL_LINK) {
1128                 /* Unacked frames */
1129                 hdev->acl_cnt += conn->sent;
1130         } else if (conn->type == LE_LINK) {
1131                 cancel_delayed_work(&conn->le_conn_timeout);
1132
1133                 if (hdev->le_pkts)
1134                         hdev->le_cnt += conn->sent;
1135                 else
1136                         hdev->acl_cnt += conn->sent;
1137         } else {
1138                 /* Unacked ISO frames */
1139                 if (conn->type == ISO_LINK) {
1140                         if (hdev->iso_pkts)
1141                                 hdev->iso_cnt += conn->sent;
1142                         else if (hdev->le_pkts)
1143                                 hdev->le_cnt += conn->sent;
1144                         else
1145                                 hdev->acl_cnt += conn->sent;
1146                 }
1147         }
1148
1149         if (conn->amp_mgr)
1150                 amp_mgr_put(conn->amp_mgr);
1151
1152         skb_queue_purge(&conn->data_q);
1153
1154         /* Remove the connection from the list and cleanup its remaining
1155          * state. This is a separate function since for some cases like
1156          * BT_CONNECT_SCAN we *only* want the cleanup part without the
1157          * rest of hci_conn_del.
1158          */
1159         hci_conn_cleanup(conn);
1160 }
1161
1162 struct hci_dev *hci_get_route(bdaddr_t *dst, bdaddr_t *src, uint8_t src_type)
1163 {
1164         int use_src = bacmp(src, BDADDR_ANY);
1165         struct hci_dev *hdev = NULL, *d;
1166
1167         BT_DBG("%pMR -> %pMR", src, dst);
1168
1169         read_lock(&hci_dev_list_lock);
1170
1171         list_for_each_entry(d, &hci_dev_list, list) {
1172                 if (!test_bit(HCI_UP, &d->flags) ||
1173                     hci_dev_test_flag(d, HCI_USER_CHANNEL) ||
1174                     d->dev_type != HCI_PRIMARY)
1175                         continue;
1176
1177                 /* Simple routing:
1178                  *   No source address - find interface with bdaddr != dst
1179                  *   Source address    - find interface with bdaddr == src
1180                  */
1181
1182                 if (use_src) {
1183                         bdaddr_t id_addr;
1184                         u8 id_addr_type;
1185
1186                         if (src_type == BDADDR_BREDR) {
1187                                 if (!lmp_bredr_capable(d))
1188                                         continue;
1189                                 bacpy(&id_addr, &d->bdaddr);
1190                                 id_addr_type = BDADDR_BREDR;
1191                         } else {
1192                                 if (!lmp_le_capable(d))
1193                                         continue;
1194
1195                                 hci_copy_identity_address(d, &id_addr,
1196                                                           &id_addr_type);
1197
1198                                 /* Convert from HCI to three-value type */
1199                                 if (id_addr_type == ADDR_LE_DEV_PUBLIC)
1200                                         id_addr_type = BDADDR_LE_PUBLIC;
1201                                 else
1202                                         id_addr_type = BDADDR_LE_RANDOM;
1203                         }
1204
1205                         if (!bacmp(&id_addr, src) && id_addr_type == src_type) {
1206                                 hdev = d; break;
1207                         }
1208                 } else {
1209                         if (bacmp(&d->bdaddr, dst)) {
1210                                 hdev = d; break;
1211                         }
1212                 }
1213         }
1214
1215         if (hdev)
1216                 hdev = hci_dev_hold(hdev);
1217
1218         read_unlock(&hci_dev_list_lock);
1219         return hdev;
1220 }
1221 EXPORT_SYMBOL(hci_get_route);
1222
1223 /* This function requires the caller holds hdev->lock */
1224 static void hci_le_conn_failed(struct hci_conn *conn, u8 status)
1225 {
1226         struct hci_dev *hdev = conn->hdev;
1227
1228         hci_connect_le_scan_cleanup(conn, status);
1229
1230         /* Enable advertising in case this was a failed connection
1231          * attempt as a peripheral.
1232          */
1233         hci_enable_advertising(hdev);
1234 }
1235
1236 /* This function requires the caller holds hdev->lock */
1237 void hci_conn_failed(struct hci_conn *conn, u8 status)
1238 {
1239         struct hci_dev *hdev = conn->hdev;
1240
1241         bt_dev_dbg(hdev, "status 0x%2.2x", status);
1242
1243         switch (conn->type) {
1244         case LE_LINK:
1245                 hci_le_conn_failed(conn, status);
1246                 break;
1247         case ACL_LINK:
1248                 mgmt_connect_failed(hdev, &conn->dst, conn->type,
1249                                     conn->dst_type, status);
1250                 break;
1251         }
1252
1253         conn->state = BT_CLOSED;
1254         hci_connect_cfm(conn, status);
1255         hci_conn_del(conn);
1256 }
1257
1258 /* This function requires the caller holds hdev->lock */
1259 u8 hci_conn_set_handle(struct hci_conn *conn, u16 handle)
1260 {
1261         struct hci_dev *hdev = conn->hdev;
1262
1263         bt_dev_dbg(hdev, "hcon %p handle 0x%4.4x", conn, handle);
1264
1265         if (conn->handle == handle)
1266                 return 0;
1267
1268         if (handle > HCI_CONN_HANDLE_MAX) {
1269                 bt_dev_err(hdev, "Invalid handle: 0x%4.4x > 0x%4.4x",
1270                            handle, HCI_CONN_HANDLE_MAX);
1271                 return HCI_ERROR_INVALID_PARAMETERS;
1272         }
1273
1274         /* If abort_reason has been sent it means the connection is being
1275          * aborted and the handle shall not be changed.
1276          */
1277         if (conn->abort_reason)
1278                 return conn->abort_reason;
1279
1280         if (HCI_CONN_HANDLE_UNSET(conn->handle))
1281                 ida_free(&hdev->unset_handle_ida, conn->handle);
1282
1283         conn->handle = handle;
1284
1285         return 0;
1286 }
1287
1288 static void create_le_conn_complete(struct hci_dev *hdev, void *data, int err)
1289 {
1290         struct hci_conn *conn;
1291         u16 handle = PTR_UINT(data);
1292
1293         conn = hci_conn_hash_lookup_handle(hdev, handle);
1294         if (!conn)
1295                 return;
1296
1297         bt_dev_dbg(hdev, "err %d", err);
1298
1299         hci_dev_lock(hdev);
1300
1301         if (!err) {
1302                 hci_connect_le_scan_cleanup(conn, 0x00);
1303                 goto done;
1304         }
1305
1306         /* Check if connection is still pending */
1307         if (conn != hci_lookup_le_connect(hdev))
1308                 goto done;
1309
1310         /* Flush to make sure we send create conn cancel command if needed */
1311         flush_delayed_work(&conn->le_conn_timeout);
1312         hci_conn_failed(conn, bt_status(err));
1313
1314 done:
1315         hci_dev_unlock(hdev);
1316 }
1317
1318 static int hci_connect_le_sync(struct hci_dev *hdev, void *data)
1319 {
1320         struct hci_conn *conn;
1321         u16 handle = PTR_UINT(data);
1322
1323         conn = hci_conn_hash_lookup_handle(hdev, handle);
1324         if (!conn)
1325                 return 0;
1326
1327         bt_dev_dbg(hdev, "conn %p", conn);
1328
1329         clear_bit(HCI_CONN_SCANNING, &conn->flags);
1330         conn->state = BT_CONNECT;
1331
1332         return hci_le_create_conn_sync(hdev, conn);
1333 }
1334
1335 struct hci_conn *hci_connect_le(struct hci_dev *hdev, bdaddr_t *dst,
1336                                 u8 dst_type, bool dst_resolved, u8 sec_level,
1337                                 u16 conn_timeout, u8 role)
1338 {
1339         struct hci_conn *conn;
1340         struct smp_irk *irk;
1341         int err;
1342
1343         /* Let's make sure that le is enabled.*/
1344         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1345                 if (lmp_le_capable(hdev))
1346                         return ERR_PTR(-ECONNREFUSED);
1347
1348                 return ERR_PTR(-EOPNOTSUPP);
1349         }
1350
1351         /* Since the controller supports only one LE connection attempt at a
1352          * time, we return -EBUSY if there is any connection attempt running.
1353          */
1354         if (hci_lookup_le_connect(hdev))
1355                 return ERR_PTR(-EBUSY);
1356
1357         /* If there's already a connection object but it's not in
1358          * scanning state it means it must already be established, in
1359          * which case we can't do anything else except report a failure
1360          * to connect.
1361          */
1362         conn = hci_conn_hash_lookup_le(hdev, dst, dst_type);
1363         if (conn && !test_bit(HCI_CONN_SCANNING, &conn->flags)) {
1364                 return ERR_PTR(-EBUSY);
1365         }
1366
1367         /* Check if the destination address has been resolved by the controller
1368          * since if it did then the identity address shall be used.
1369          */
1370         if (!dst_resolved) {
1371                 /* When given an identity address with existing identity
1372                  * resolving key, the connection needs to be established
1373                  * to a resolvable random address.
1374                  *
1375                  * Storing the resolvable random address is required here
1376                  * to handle connection failures. The address will later
1377                  * be resolved back into the original identity address
1378                  * from the connect request.
1379                  */
1380                 irk = hci_find_irk_by_addr(hdev, dst, dst_type);
1381                 if (irk && bacmp(&irk->rpa, BDADDR_ANY)) {
1382                         dst = &irk->rpa;
1383                         dst_type = ADDR_LE_DEV_RANDOM;
1384                 }
1385         }
1386
1387         if (conn) {
1388                 bacpy(&conn->dst, dst);
1389         } else {
1390                 conn = hci_conn_add_unset(hdev, LE_LINK, dst, role);
1391                 if (!conn)
1392                         return ERR_PTR(-ENOMEM);
1393                 hci_conn_hold(conn);
1394                 conn->pending_sec_level = sec_level;
1395         }
1396
1397         conn->dst_type = dst_type;
1398         conn->sec_level = BT_SECURITY_LOW;
1399         conn->conn_timeout = conn_timeout;
1400
1401         err = hci_cmd_sync_queue(hdev, hci_connect_le_sync,
1402                                  UINT_PTR(conn->handle),
1403                                  create_le_conn_complete);
1404         if (err) {
1405                 hci_conn_del(conn);
1406                 return ERR_PTR(err);
1407         }
1408
1409         return conn;
1410 }
1411
1412 static bool is_connected(struct hci_dev *hdev, bdaddr_t *addr, u8 type)
1413 {
1414         struct hci_conn *conn;
1415
1416         conn = hci_conn_hash_lookup_le(hdev, addr, type);
1417         if (!conn)
1418                 return false;
1419
1420         if (conn->state != BT_CONNECTED)
1421                 return false;
1422
1423         return true;
1424 }
1425
1426 /* This function requires the caller holds hdev->lock */
1427 static int hci_explicit_conn_params_set(struct hci_dev *hdev,
1428                                         bdaddr_t *addr, u8 addr_type)
1429 {
1430         struct hci_conn_params *params;
1431
1432         if (is_connected(hdev, addr, addr_type))
1433                 return -EISCONN;
1434
1435         params = hci_conn_params_lookup(hdev, addr, addr_type);
1436         if (!params) {
1437                 params = hci_conn_params_add(hdev, addr, addr_type);
1438                 if (!params)
1439                         return -ENOMEM;
1440
1441                 /* If we created new params, mark them to be deleted in
1442                  * hci_connect_le_scan_cleanup. It's different case than
1443                  * existing disabled params, those will stay after cleanup.
1444                  */
1445                 params->auto_connect = HCI_AUTO_CONN_EXPLICIT;
1446         }
1447
1448         /* We're trying to connect, so make sure params are at pend_le_conns */
1449         if (params->auto_connect == HCI_AUTO_CONN_DISABLED ||
1450             params->auto_connect == HCI_AUTO_CONN_REPORT ||
1451             params->auto_connect == HCI_AUTO_CONN_EXPLICIT) {
1452                 hci_pend_le_list_del_init(params);
1453                 hci_pend_le_list_add(params, &hdev->pend_le_conns);
1454         }
1455
1456         params->explicit_connect = true;
1457
1458         BT_DBG("addr %pMR (type %u) auto_connect %u", addr, addr_type,
1459                params->auto_connect);
1460
1461         return 0;
1462 }
1463
1464 static int qos_set_big(struct hci_dev *hdev, struct bt_iso_qos *qos)
1465 {
1466         struct hci_conn *conn;
1467         u8  big;
1468
1469         /* Allocate a BIG if not set */
1470         if (qos->bcast.big == BT_ISO_QOS_BIG_UNSET) {
1471                 for (big = 0x00; big < 0xef; big++) {
1472
1473                         conn = hci_conn_hash_lookup_big(hdev, big);
1474                         if (!conn)
1475                                 break;
1476                 }
1477
1478                 if (big == 0xef)
1479                         return -EADDRNOTAVAIL;
1480
1481                 /* Update BIG */
1482                 qos->bcast.big = big;
1483         }
1484
1485         return 0;
1486 }
1487
1488 static int qos_set_bis(struct hci_dev *hdev, struct bt_iso_qos *qos)
1489 {
1490         struct hci_conn *conn;
1491         u8  bis;
1492
1493         /* Allocate BIS if not set */
1494         if (qos->bcast.bis == BT_ISO_QOS_BIS_UNSET) {
1495                 /* Find an unused adv set to advertise BIS, skip instance 0x00
1496                  * since it is reserved as general purpose set.
1497                  */
1498                 for (bis = 0x01; bis < hdev->le_num_of_adv_sets;
1499                      bis++) {
1500
1501                         conn = hci_conn_hash_lookup_bis(hdev, BDADDR_ANY, bis);
1502                         if (!conn)
1503                                 break;
1504                 }
1505
1506                 if (bis == hdev->le_num_of_adv_sets)
1507                         return -EADDRNOTAVAIL;
1508
1509                 /* Update BIS */
1510                 qos->bcast.bis = bis;
1511         }
1512
1513         return 0;
1514 }
1515
1516 /* This function requires the caller holds hdev->lock */
1517 static struct hci_conn *hci_add_bis(struct hci_dev *hdev, bdaddr_t *dst,
1518                                     struct bt_iso_qos *qos, __u8 base_len,
1519                                     __u8 *base)
1520 {
1521         struct hci_conn *conn;
1522         int err;
1523
1524         /* Let's make sure that le is enabled.*/
1525         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1526                 if (lmp_le_capable(hdev))
1527                         return ERR_PTR(-ECONNREFUSED);
1528                 return ERR_PTR(-EOPNOTSUPP);
1529         }
1530
1531         err = qos_set_big(hdev, qos);
1532         if (err)
1533                 return ERR_PTR(err);
1534
1535         err = qos_set_bis(hdev, qos);
1536         if (err)
1537                 return ERR_PTR(err);
1538
1539         /* Check if the LE Create BIG command has already been sent */
1540         conn = hci_conn_hash_lookup_per_adv_bis(hdev, dst, qos->bcast.big,
1541                                                 qos->bcast.big);
1542         if (conn)
1543                 return ERR_PTR(-EADDRINUSE);
1544
1545         /* Check BIS settings against other bound BISes, since all
1546          * BISes in a BIG must have the same value for all parameters
1547          */
1548         conn = hci_conn_hash_lookup_big(hdev, qos->bcast.big);
1549
1550         if (conn && (memcmp(qos, &conn->iso_qos, sizeof(*qos)) ||
1551                      base_len != conn->le_per_adv_data_len ||
1552                      memcmp(conn->le_per_adv_data, base, base_len)))
1553                 return ERR_PTR(-EADDRINUSE);
1554
1555         conn = hci_conn_add_unset(hdev, ISO_LINK, dst, HCI_ROLE_MASTER);
1556         if (!conn)
1557                 return ERR_PTR(-ENOMEM);
1558
1559         conn->state = BT_CONNECT;
1560
1561         hci_conn_hold(conn);
1562         return conn;
1563 }
1564
1565 /* This function requires the caller holds hdev->lock */
1566 struct hci_conn *hci_connect_le_scan(struct hci_dev *hdev, bdaddr_t *dst,
1567                                      u8 dst_type, u8 sec_level,
1568                                      u16 conn_timeout,
1569                                      enum conn_reasons conn_reason)
1570 {
1571         struct hci_conn *conn;
1572
1573         /* Let's make sure that le is enabled.*/
1574         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1575                 if (lmp_le_capable(hdev))
1576                         return ERR_PTR(-ECONNREFUSED);
1577
1578                 return ERR_PTR(-EOPNOTSUPP);
1579         }
1580
1581         /* Some devices send ATT messages as soon as the physical link is
1582          * established. To be able to handle these ATT messages, the user-
1583          * space first establishes the connection and then starts the pairing
1584          * process.
1585          *
1586          * So if a hci_conn object already exists for the following connection
1587          * attempt, we simply update pending_sec_level and auth_type fields
1588          * and return the object found.
1589          */
1590         conn = hci_conn_hash_lookup_le(hdev, dst, dst_type);
1591         if (conn) {
1592                 if (conn->pending_sec_level < sec_level)
1593                         conn->pending_sec_level = sec_level;
1594                 goto done;
1595         }
1596
1597         BT_DBG("requesting refresh of dst_addr");
1598
1599         conn = hci_conn_add_unset(hdev, LE_LINK, dst, HCI_ROLE_MASTER);
1600         if (!conn)
1601                 return ERR_PTR(-ENOMEM);
1602
1603         if (hci_explicit_conn_params_set(hdev, dst, dst_type) < 0) {
1604                 hci_conn_del(conn);
1605                 return ERR_PTR(-EBUSY);
1606         }
1607
1608         conn->state = BT_CONNECT;
1609         set_bit(HCI_CONN_SCANNING, &conn->flags);
1610         conn->dst_type = dst_type;
1611         conn->sec_level = BT_SECURITY_LOW;
1612         conn->pending_sec_level = sec_level;
1613         conn->conn_timeout = conn_timeout;
1614         conn->conn_reason = conn_reason;
1615
1616         hci_update_passive_scan(hdev);
1617
1618 done:
1619         hci_conn_hold(conn);
1620         return conn;
1621 }
1622
1623 struct hci_conn *hci_connect_acl(struct hci_dev *hdev, bdaddr_t *dst,
1624                                  u8 sec_level, u8 auth_type,
1625                                  enum conn_reasons conn_reason)
1626 {
1627         struct hci_conn *acl;
1628
1629         if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
1630                 if (lmp_bredr_capable(hdev))
1631                         return ERR_PTR(-ECONNREFUSED);
1632
1633                 return ERR_PTR(-EOPNOTSUPP);
1634         }
1635
1636         /* Reject outgoing connection to device with same BD ADDR against
1637          * CVE-2020-26555
1638          */
1639         if (!bacmp(&hdev->bdaddr, dst)) {
1640                 bt_dev_dbg(hdev, "Reject connection with same BD_ADDR %pMR\n",
1641                            dst);
1642                 return ERR_PTR(-ECONNREFUSED);
1643         }
1644
1645         acl = hci_conn_hash_lookup_ba(hdev, ACL_LINK, dst);
1646         if (!acl) {
1647                 acl = hci_conn_add_unset(hdev, ACL_LINK, dst, HCI_ROLE_MASTER);
1648                 if (!acl)
1649                         return ERR_PTR(-ENOMEM);
1650         }
1651
1652         hci_conn_hold(acl);
1653
1654         acl->conn_reason = conn_reason;
1655         if (acl->state == BT_OPEN || acl->state == BT_CLOSED) {
1656                 acl->sec_level = BT_SECURITY_LOW;
1657                 acl->pending_sec_level = sec_level;
1658                 acl->auth_type = auth_type;
1659                 hci_acl_create_connection(acl);
1660         }
1661
1662         return acl;
1663 }
1664
1665 static struct hci_link *hci_conn_link(struct hci_conn *parent,
1666                                       struct hci_conn *conn)
1667 {
1668         struct hci_dev *hdev = parent->hdev;
1669         struct hci_link *link;
1670
1671         bt_dev_dbg(hdev, "parent %p hcon %p", parent, conn);
1672
1673         if (conn->link)
1674                 return conn->link;
1675
1676         if (conn->parent)
1677                 return NULL;
1678
1679         link = kzalloc(sizeof(*link), GFP_KERNEL);
1680         if (!link)
1681                 return NULL;
1682
1683         link->conn = hci_conn_hold(conn);
1684         conn->link = link;
1685         conn->parent = hci_conn_get(parent);
1686
1687         /* Use list_add_tail_rcu append to the list */
1688         list_add_tail_rcu(&link->list, &parent->link_list);
1689
1690         return link;
1691 }
1692
1693 struct hci_conn *hci_connect_sco(struct hci_dev *hdev, int type, bdaddr_t *dst,
1694                                  __u16 setting, struct bt_codec *codec)
1695 {
1696         struct hci_conn *acl;
1697         struct hci_conn *sco;
1698         struct hci_link *link;
1699
1700         acl = hci_connect_acl(hdev, dst, BT_SECURITY_LOW, HCI_AT_NO_BONDING,
1701                               CONN_REASON_SCO_CONNECT);
1702         if (IS_ERR(acl))
1703                 return acl;
1704
1705         sco = hci_conn_hash_lookup_ba(hdev, type, dst);
1706         if (!sco) {
1707                 sco = hci_conn_add_unset(hdev, type, dst, HCI_ROLE_MASTER);
1708                 if (!sco) {
1709                         hci_conn_drop(acl);
1710                         return ERR_PTR(-ENOMEM);
1711                 }
1712         }
1713
1714         link = hci_conn_link(acl, sco);
1715         if (!link) {
1716                 hci_conn_drop(acl);
1717                 hci_conn_drop(sco);
1718                 return ERR_PTR(-ENOLINK);
1719         }
1720
1721         sco->setting = setting;
1722         sco->codec = *codec;
1723
1724         if (acl->state == BT_CONNECTED &&
1725             (sco->state == BT_OPEN || sco->state == BT_CLOSED)) {
1726                 set_bit(HCI_CONN_POWER_SAVE, &acl->flags);
1727                 hci_conn_enter_active_mode(acl, BT_POWER_FORCE_ACTIVE_ON);
1728
1729                 if (test_bit(HCI_CONN_MODE_CHANGE_PEND, &acl->flags)) {
1730                         /* defer SCO setup until mode change completed */
1731                         set_bit(HCI_CONN_SCO_SETUP_PEND, &acl->flags);
1732                         return sco;
1733                 }
1734
1735                 hci_sco_setup(acl, 0x00);
1736         }
1737
1738         return sco;
1739 }
1740
1741 static int hci_le_create_big(struct hci_conn *conn, struct bt_iso_qos *qos)
1742 {
1743         struct hci_dev *hdev = conn->hdev;
1744         struct hci_cp_le_create_big cp;
1745         struct iso_list_data data;
1746
1747         memset(&cp, 0, sizeof(cp));
1748
1749         data.big = qos->bcast.big;
1750         data.bis = qos->bcast.bis;
1751         data.count = 0;
1752
1753         /* Create a BIS for each bound connection */
1754         hci_conn_hash_list_state(hdev, bis_list, ISO_LINK,
1755                                  BT_BOUND, &data);
1756
1757         cp.handle = qos->bcast.big;
1758         cp.adv_handle = qos->bcast.bis;
1759         cp.num_bis  = data.count;
1760         hci_cpu_to_le24(qos->bcast.out.interval, cp.bis.sdu_interval);
1761         cp.bis.sdu = cpu_to_le16(qos->bcast.out.sdu);
1762         cp.bis.latency =  cpu_to_le16(qos->bcast.out.latency);
1763         cp.bis.rtn  = qos->bcast.out.rtn;
1764         cp.bis.phy  = qos->bcast.out.phy;
1765         cp.bis.packing = qos->bcast.packing;
1766         cp.bis.framing = qos->bcast.framing;
1767         cp.bis.encryption = qos->bcast.encryption;
1768         memcpy(cp.bis.bcode, qos->bcast.bcode, sizeof(cp.bis.bcode));
1769
1770         return hci_send_cmd(hdev, HCI_OP_LE_CREATE_BIG, sizeof(cp), &cp);
1771 }
1772
1773 static int set_cig_params_sync(struct hci_dev *hdev, void *data)
1774 {
1775         u8 cig_id = PTR_UINT(data);
1776         struct hci_conn *conn;
1777         struct bt_iso_qos *qos;
1778         struct iso_cig_params pdu;
1779         u8 cis_id;
1780
1781         conn = hci_conn_hash_lookup_cig(hdev, cig_id);
1782         if (!conn)
1783                 return 0;
1784
1785         memset(&pdu, 0, sizeof(pdu));
1786
1787         qos = &conn->iso_qos;
1788         pdu.cp.cig_id = cig_id;
1789         hci_cpu_to_le24(qos->ucast.out.interval, pdu.cp.c_interval);
1790         hci_cpu_to_le24(qos->ucast.in.interval, pdu.cp.p_interval);
1791         pdu.cp.sca = qos->ucast.sca;
1792         pdu.cp.packing = qos->ucast.packing;
1793         pdu.cp.framing = qos->ucast.framing;
1794         pdu.cp.c_latency = cpu_to_le16(qos->ucast.out.latency);
1795         pdu.cp.p_latency = cpu_to_le16(qos->ucast.in.latency);
1796
1797         /* Reprogram all CIS(s) with the same CIG, valid range are:
1798          * num_cis: 0x00 to 0x1F
1799          * cis_id: 0x00 to 0xEF
1800          */
1801         for (cis_id = 0x00; cis_id < 0xf0 &&
1802              pdu.cp.num_cis < ARRAY_SIZE(pdu.cis); cis_id++) {
1803                 struct hci_cis_params *cis;
1804
1805                 conn = hci_conn_hash_lookup_cis(hdev, NULL, 0, cig_id, cis_id);
1806                 if (!conn)
1807                         continue;
1808
1809                 qos = &conn->iso_qos;
1810
1811                 cis = &pdu.cis[pdu.cp.num_cis++];
1812                 cis->cis_id = cis_id;
1813                 cis->c_sdu  = cpu_to_le16(conn->iso_qos.ucast.out.sdu);
1814                 cis->p_sdu  = cpu_to_le16(conn->iso_qos.ucast.in.sdu);
1815                 cis->c_phy  = qos->ucast.out.phy ? qos->ucast.out.phy :
1816                               qos->ucast.in.phy;
1817                 cis->p_phy  = qos->ucast.in.phy ? qos->ucast.in.phy :
1818                               qos->ucast.out.phy;
1819                 cis->c_rtn  = qos->ucast.out.rtn;
1820                 cis->p_rtn  = qos->ucast.in.rtn;
1821         }
1822
1823         if (!pdu.cp.num_cis)
1824                 return 0;
1825
1826         return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_CIG_PARAMS,
1827                                      sizeof(pdu.cp) +
1828                                      pdu.cp.num_cis * sizeof(pdu.cis[0]), &pdu,
1829                                      HCI_CMD_TIMEOUT);
1830 }
1831
1832 static bool hci_le_set_cig_params(struct hci_conn *conn, struct bt_iso_qos *qos)
1833 {
1834         struct hci_dev *hdev = conn->hdev;
1835         struct iso_list_data data;
1836
1837         memset(&data, 0, sizeof(data));
1838
1839         /* Allocate first still reconfigurable CIG if not set */
1840         if (qos->ucast.cig == BT_ISO_QOS_CIG_UNSET) {
1841                 for (data.cig = 0x00; data.cig < 0xf0; data.cig++) {
1842                         data.count = 0;
1843
1844                         hci_conn_hash_list_state(hdev, find_cis, ISO_LINK,
1845                                                  BT_CONNECT, &data);
1846                         if (data.count)
1847                                 continue;
1848
1849                         hci_conn_hash_list_state(hdev, find_cis, ISO_LINK,
1850                                                  BT_CONNECTED, &data);
1851                         if (!data.count)
1852                                 break;
1853                 }
1854
1855                 if (data.cig == 0xf0)
1856                         return false;
1857
1858                 /* Update CIG */
1859                 qos->ucast.cig = data.cig;
1860         }
1861
1862         if (qos->ucast.cis != BT_ISO_QOS_CIS_UNSET) {
1863                 if (hci_conn_hash_lookup_cis(hdev, NULL, 0, qos->ucast.cig,
1864                                              qos->ucast.cis))
1865                         return false;
1866                 goto done;
1867         }
1868
1869         /* Allocate first available CIS if not set */
1870         for (data.cig = qos->ucast.cig, data.cis = 0x00; data.cis < 0xf0;
1871              data.cis++) {
1872                 if (!hci_conn_hash_lookup_cis(hdev, NULL, 0, data.cig,
1873                                               data.cis)) {
1874                         /* Update CIS */
1875                         qos->ucast.cis = data.cis;
1876                         break;
1877                 }
1878         }
1879
1880         if (qos->ucast.cis == BT_ISO_QOS_CIS_UNSET)
1881                 return false;
1882
1883 done:
1884         if (hci_cmd_sync_queue(hdev, set_cig_params_sync,
1885                                UINT_PTR(qos->ucast.cig), NULL) < 0)
1886                 return false;
1887
1888         return true;
1889 }
1890
1891 struct hci_conn *hci_bind_cis(struct hci_dev *hdev, bdaddr_t *dst,
1892                               __u8 dst_type, struct bt_iso_qos *qos)
1893 {
1894         struct hci_conn *cis;
1895
1896         cis = hci_conn_hash_lookup_cis(hdev, dst, dst_type, qos->ucast.cig,
1897                                        qos->ucast.cis);
1898         if (!cis) {
1899                 cis = hci_conn_add_unset(hdev, ISO_LINK, dst, HCI_ROLE_MASTER);
1900                 if (!cis)
1901                         return ERR_PTR(-ENOMEM);
1902                 cis->cleanup = cis_cleanup;
1903                 cis->dst_type = dst_type;
1904                 cis->iso_qos.ucast.cig = BT_ISO_QOS_CIG_UNSET;
1905                 cis->iso_qos.ucast.cis = BT_ISO_QOS_CIS_UNSET;
1906         }
1907
1908         if (cis->state == BT_CONNECTED)
1909                 return cis;
1910
1911         /* Check if CIS has been set and the settings matches */
1912         if (cis->state == BT_BOUND &&
1913             !memcmp(&cis->iso_qos, qos, sizeof(*qos)))
1914                 return cis;
1915
1916         /* Update LINK PHYs according to QoS preference */
1917         cis->le_tx_phy = qos->ucast.out.phy;
1918         cis->le_rx_phy = qos->ucast.in.phy;
1919
1920         /* If output interval is not set use the input interval as it cannot be
1921          * 0x000000.
1922          */
1923         if (!qos->ucast.out.interval)
1924                 qos->ucast.out.interval = qos->ucast.in.interval;
1925
1926         /* If input interval is not set use the output interval as it cannot be
1927          * 0x000000.
1928          */
1929         if (!qos->ucast.in.interval)
1930                 qos->ucast.in.interval = qos->ucast.out.interval;
1931
1932         /* If output latency is not set use the input latency as it cannot be
1933          * 0x0000.
1934          */
1935         if (!qos->ucast.out.latency)
1936                 qos->ucast.out.latency = qos->ucast.in.latency;
1937
1938         /* If input latency is not set use the output latency as it cannot be
1939          * 0x0000.
1940          */
1941         if (!qos->ucast.in.latency)
1942                 qos->ucast.in.latency = qos->ucast.out.latency;
1943
1944         if (!hci_le_set_cig_params(cis, qos)) {
1945                 hci_conn_drop(cis);
1946                 return ERR_PTR(-EINVAL);
1947         }
1948
1949         hci_conn_hold(cis);
1950
1951         cis->iso_qos = *qos;
1952         cis->state = BT_BOUND;
1953
1954         return cis;
1955 }
1956
1957 bool hci_iso_setup_path(struct hci_conn *conn)
1958 {
1959         struct hci_dev *hdev = conn->hdev;
1960         struct hci_cp_le_setup_iso_path cmd;
1961
1962         memset(&cmd, 0, sizeof(cmd));
1963
1964         if (conn->iso_qos.ucast.out.sdu) {
1965                 cmd.handle = cpu_to_le16(conn->handle);
1966                 cmd.direction = 0x00; /* Input (Host to Controller) */
1967                 cmd.path = 0x00; /* HCI path if enabled */
1968                 cmd.codec = 0x03; /* Transparent Data */
1969
1970                 if (hci_send_cmd(hdev, HCI_OP_LE_SETUP_ISO_PATH, sizeof(cmd),
1971                                  &cmd) < 0)
1972                         return false;
1973         }
1974
1975         if (conn->iso_qos.ucast.in.sdu) {
1976                 cmd.handle = cpu_to_le16(conn->handle);
1977                 cmd.direction = 0x01; /* Output (Controller to Host) */
1978                 cmd.path = 0x00; /* HCI path if enabled */
1979                 cmd.codec = 0x03; /* Transparent Data */
1980
1981                 if (hci_send_cmd(hdev, HCI_OP_LE_SETUP_ISO_PATH, sizeof(cmd),
1982                                  &cmd) < 0)
1983                         return false;
1984         }
1985
1986         return true;
1987 }
1988
1989 int hci_conn_check_create_cis(struct hci_conn *conn)
1990 {
1991         if (conn->type != ISO_LINK || !bacmp(&conn->dst, BDADDR_ANY))
1992                 return -EINVAL;
1993
1994         if (!conn->parent || conn->parent->state != BT_CONNECTED ||
1995             conn->state != BT_CONNECT || HCI_CONN_HANDLE_UNSET(conn->handle))
1996                 return 1;
1997
1998         return 0;
1999 }
2000
2001 static int hci_create_cis_sync(struct hci_dev *hdev, void *data)
2002 {
2003         return hci_le_create_cis_sync(hdev);
2004 }
2005
2006 int hci_le_create_cis_pending(struct hci_dev *hdev)
2007 {
2008         struct hci_conn *conn;
2009         bool pending = false;
2010
2011         rcu_read_lock();
2012
2013         list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
2014                 if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) {
2015                         rcu_read_unlock();
2016                         return -EBUSY;
2017                 }
2018
2019                 if (!hci_conn_check_create_cis(conn))
2020                         pending = true;
2021         }
2022
2023         rcu_read_unlock();
2024
2025         if (!pending)
2026                 return 0;
2027
2028         /* Queue Create CIS */
2029         return hci_cmd_sync_queue(hdev, hci_create_cis_sync, NULL, NULL);
2030 }
2031
2032 static void hci_iso_qos_setup(struct hci_dev *hdev, struct hci_conn *conn,
2033                               struct bt_iso_io_qos *qos, __u8 phy)
2034 {
2035         /* Only set MTU if PHY is enabled */
2036         if (!qos->sdu && qos->phy) {
2037                 if (hdev->iso_mtu > 0)
2038                         qos->sdu = hdev->iso_mtu;
2039                 else if (hdev->le_mtu > 0)
2040                         qos->sdu = hdev->le_mtu;
2041                 else
2042                         qos->sdu = hdev->acl_mtu;
2043         }
2044
2045         /* Use the same PHY as ACL if set to any */
2046         if (qos->phy == BT_ISO_PHY_ANY)
2047                 qos->phy = phy;
2048
2049         /* Use LE ACL connection interval if not set */
2050         if (!qos->interval)
2051                 /* ACL interval unit in 1.25 ms to us */
2052                 qos->interval = conn->le_conn_interval * 1250;
2053
2054         /* Use LE ACL connection latency if not set */
2055         if (!qos->latency)
2056                 qos->latency = conn->le_conn_latency;
2057 }
2058
2059 static int create_big_sync(struct hci_dev *hdev, void *data)
2060 {
2061         struct hci_conn *conn = data;
2062         struct bt_iso_qos *qos = &conn->iso_qos;
2063         u16 interval, sync_interval = 0;
2064         u32 flags = 0;
2065         int err;
2066
2067         if (qos->bcast.out.phy == 0x02)
2068                 flags |= MGMT_ADV_FLAG_SEC_2M;
2069
2070         /* Align intervals */
2071         interval = (qos->bcast.out.interval / 1250) * qos->bcast.sync_factor;
2072
2073         if (qos->bcast.bis)
2074                 sync_interval = interval * 4;
2075
2076         err = hci_start_per_adv_sync(hdev, qos->bcast.bis, conn->le_per_adv_data_len,
2077                                      conn->le_per_adv_data, flags, interval,
2078                                      interval, sync_interval);
2079         if (err)
2080                 return err;
2081
2082         return hci_le_create_big(conn, &conn->iso_qos);
2083 }
2084
2085 static void create_pa_complete(struct hci_dev *hdev, void *data, int err)
2086 {
2087         struct hci_cp_le_pa_create_sync *cp = data;
2088
2089         bt_dev_dbg(hdev, "");
2090
2091         if (err)
2092                 bt_dev_err(hdev, "Unable to create PA: %d", err);
2093
2094         kfree(cp);
2095 }
2096
2097 static int create_pa_sync(struct hci_dev *hdev, void *data)
2098 {
2099         struct hci_cp_le_pa_create_sync *cp = data;
2100         int err;
2101
2102         err = __hci_cmd_sync_status(hdev, HCI_OP_LE_PA_CREATE_SYNC,
2103                                     sizeof(*cp), cp, HCI_CMD_TIMEOUT);
2104         if (err) {
2105                 hci_dev_clear_flag(hdev, HCI_PA_SYNC);
2106                 return err;
2107         }
2108
2109         return hci_update_passive_scan_sync(hdev);
2110 }
2111
2112 int hci_pa_create_sync(struct hci_dev *hdev, bdaddr_t *dst, __u8 dst_type,
2113                        __u8 sid, struct bt_iso_qos *qos)
2114 {
2115         struct hci_cp_le_pa_create_sync *cp;
2116
2117         if (hci_dev_test_and_set_flag(hdev, HCI_PA_SYNC))
2118                 return -EBUSY;
2119
2120         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
2121         if (!cp) {
2122                 hci_dev_clear_flag(hdev, HCI_PA_SYNC);
2123                 return -ENOMEM;
2124         }
2125
2126         cp->options = qos->bcast.options;
2127         cp->sid = sid;
2128         cp->addr_type = dst_type;
2129         bacpy(&cp->addr, dst);
2130         cp->skip = cpu_to_le16(qos->bcast.skip);
2131         cp->sync_timeout = cpu_to_le16(qos->bcast.sync_timeout);
2132         cp->sync_cte_type = qos->bcast.sync_cte_type;
2133
2134         /* Queue start pa_create_sync and scan */
2135         return hci_cmd_sync_queue(hdev, create_pa_sync, cp, create_pa_complete);
2136 }
2137
2138 int hci_le_big_create_sync(struct hci_dev *hdev, struct hci_conn *hcon,
2139                            struct bt_iso_qos *qos,
2140                            __u16 sync_handle, __u8 num_bis, __u8 bis[])
2141 {
2142         struct _packed {
2143                 struct hci_cp_le_big_create_sync cp;
2144                 __u8  bis[0x11];
2145         } pdu;
2146         int err;
2147
2148         if (num_bis > sizeof(pdu.bis))
2149                 return -EINVAL;
2150
2151         err = qos_set_big(hdev, qos);
2152         if (err)
2153                 return err;
2154
2155         if (hcon)
2156                 hcon->iso_qos.bcast.big = qos->bcast.big;
2157
2158         memset(&pdu, 0, sizeof(pdu));
2159         pdu.cp.handle = qos->bcast.big;
2160         pdu.cp.sync_handle = cpu_to_le16(sync_handle);
2161         pdu.cp.encryption = qos->bcast.encryption;
2162         memcpy(pdu.cp.bcode, qos->bcast.bcode, sizeof(pdu.cp.bcode));
2163         pdu.cp.mse = qos->bcast.mse;
2164         pdu.cp.timeout = cpu_to_le16(qos->bcast.timeout);
2165         pdu.cp.num_bis = num_bis;
2166         memcpy(pdu.bis, bis, num_bis);
2167
2168         return hci_send_cmd(hdev, HCI_OP_LE_BIG_CREATE_SYNC,
2169                             sizeof(pdu.cp) + num_bis, &pdu);
2170 }
2171
2172 static void create_big_complete(struct hci_dev *hdev, void *data, int err)
2173 {
2174         struct hci_conn *conn = data;
2175
2176         bt_dev_dbg(hdev, "conn %p", conn);
2177
2178         if (err) {
2179                 bt_dev_err(hdev, "Unable to create BIG: %d", err);
2180                 hci_connect_cfm(conn, err);
2181                 hci_conn_del(conn);
2182         }
2183 }
2184
2185 struct hci_conn *hci_bind_bis(struct hci_dev *hdev, bdaddr_t *dst,
2186                               struct bt_iso_qos *qos,
2187                               __u8 base_len, __u8 *base)
2188 {
2189         struct hci_conn *conn;
2190         __u8 eir[HCI_MAX_PER_AD_LENGTH];
2191
2192         if (base_len && base)
2193                 base_len = eir_append_service_data(eir, 0,  0x1851,
2194                                                    base, base_len);
2195
2196         /* We need hci_conn object using the BDADDR_ANY as dst */
2197         conn = hci_add_bis(hdev, dst, qos, base_len, eir);
2198         if (IS_ERR(conn))
2199                 return conn;
2200
2201         /* Update LINK PHYs according to QoS preference */
2202         conn->le_tx_phy = qos->bcast.out.phy;
2203         conn->le_tx_phy = qos->bcast.out.phy;
2204
2205         /* Add Basic Announcement into Peridic Adv Data if BASE is set */
2206         if (base_len && base) {
2207                 memcpy(conn->le_per_adv_data,  eir, sizeof(eir));
2208                 conn->le_per_adv_data_len = base_len;
2209         }
2210
2211         hci_iso_qos_setup(hdev, conn, &qos->bcast.out,
2212                           conn->le_tx_phy ? conn->le_tx_phy :
2213                           hdev->le_tx_def_phys);
2214
2215         conn->iso_qos = *qos;
2216         conn->state = BT_BOUND;
2217
2218         return conn;
2219 }
2220
2221 static void bis_mark_per_adv(struct hci_conn *conn, void *data)
2222 {
2223         struct iso_list_data *d = data;
2224
2225         /* Skip if not broadcast/ANY address */
2226         if (bacmp(&conn->dst, BDADDR_ANY))
2227                 return;
2228
2229         if (d->big != conn->iso_qos.bcast.big ||
2230             d->bis == BT_ISO_QOS_BIS_UNSET ||
2231             d->bis != conn->iso_qos.bcast.bis)
2232                 return;
2233
2234         set_bit(HCI_CONN_PER_ADV, &conn->flags);
2235 }
2236
2237 struct hci_conn *hci_connect_bis(struct hci_dev *hdev, bdaddr_t *dst,
2238                                  __u8 dst_type, struct bt_iso_qos *qos,
2239                                  __u8 base_len, __u8 *base)
2240 {
2241         struct hci_conn *conn;
2242         int err;
2243         struct iso_list_data data;
2244
2245         conn = hci_bind_bis(hdev, dst, qos, base_len, base);
2246         if (IS_ERR(conn))
2247                 return conn;
2248
2249         data.big = qos->bcast.big;
2250         data.bis = qos->bcast.bis;
2251
2252         /* Set HCI_CONN_PER_ADV for all bound connections, to mark that
2253          * the start periodic advertising and create BIG commands have
2254          * been queued
2255          */
2256         hci_conn_hash_list_state(hdev, bis_mark_per_adv, ISO_LINK,
2257                                  BT_BOUND, &data);
2258
2259         /* Queue start periodic advertising and create BIG */
2260         err = hci_cmd_sync_queue(hdev, create_big_sync, conn,
2261                                  create_big_complete);
2262         if (err < 0) {
2263                 hci_conn_drop(conn);
2264                 return ERR_PTR(err);
2265         }
2266
2267         return conn;
2268 }
2269
2270 struct hci_conn *hci_connect_cis(struct hci_dev *hdev, bdaddr_t *dst,
2271                                  __u8 dst_type, struct bt_iso_qos *qos)
2272 {
2273         struct hci_conn *le;
2274         struct hci_conn *cis;
2275         struct hci_link *link;
2276
2277         if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
2278                 le = hci_connect_le(hdev, dst, dst_type, false,
2279                                     BT_SECURITY_LOW,
2280                                     HCI_LE_CONN_TIMEOUT,
2281                                     HCI_ROLE_SLAVE);
2282         else
2283                 le = hci_connect_le_scan(hdev, dst, dst_type,
2284                                          BT_SECURITY_LOW,
2285                                          HCI_LE_CONN_TIMEOUT,
2286                                          CONN_REASON_ISO_CONNECT);
2287         if (IS_ERR(le))
2288                 return le;
2289
2290         hci_iso_qos_setup(hdev, le, &qos->ucast.out,
2291                           le->le_tx_phy ? le->le_tx_phy : hdev->le_tx_def_phys);
2292         hci_iso_qos_setup(hdev, le, &qos->ucast.in,
2293                           le->le_rx_phy ? le->le_rx_phy : hdev->le_rx_def_phys);
2294
2295         cis = hci_bind_cis(hdev, dst, dst_type, qos);
2296         if (IS_ERR(cis)) {
2297                 hci_conn_drop(le);
2298                 return cis;
2299         }
2300
2301         link = hci_conn_link(le, cis);
2302         if (!link) {
2303                 hci_conn_drop(le);
2304                 hci_conn_drop(cis);
2305                 return ERR_PTR(-ENOLINK);
2306         }
2307
2308         /* Link takes the refcount */
2309         hci_conn_drop(cis);
2310
2311         cis->state = BT_CONNECT;
2312
2313         hci_le_create_cis_pending(hdev);
2314
2315         return cis;
2316 }
2317
2318 /* Check link security requirement */
2319 int hci_conn_check_link_mode(struct hci_conn *conn)
2320 {
2321         BT_DBG("hcon %p", conn);
2322
2323         /* In Secure Connections Only mode, it is required that Secure
2324          * Connections is used and the link is encrypted with AES-CCM
2325          * using a P-256 authenticated combination key.
2326          */
2327         if (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) {
2328                 if (!hci_conn_sc_enabled(conn) ||
2329                     !test_bit(HCI_CONN_AES_CCM, &conn->flags) ||
2330                     conn->key_type != HCI_LK_AUTH_COMBINATION_P256)
2331                         return 0;
2332         }
2333
2334          /* AES encryption is required for Level 4:
2335           *
2336           * BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 3, Part C
2337           * page 1319:
2338           *
2339           * 128-bit equivalent strength for link and encryption keys
2340           * required using FIPS approved algorithms (E0 not allowed,
2341           * SAFER+ not allowed, and P-192 not allowed; encryption key
2342           * not shortened)
2343           */
2344         if (conn->sec_level == BT_SECURITY_FIPS &&
2345             !test_bit(HCI_CONN_AES_CCM, &conn->flags)) {
2346                 bt_dev_err(conn->hdev,
2347                            "Invalid security: Missing AES-CCM usage");
2348                 return 0;
2349         }
2350
2351         if (hci_conn_ssp_enabled(conn) &&
2352             !test_bit(HCI_CONN_ENCRYPT, &conn->flags))
2353                 return 0;
2354
2355         return 1;
2356 }
2357
2358 /* Authenticate remote device */
2359 static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
2360 {
2361         BT_DBG("hcon %p", conn);
2362
2363         if (conn->pending_sec_level > sec_level)
2364                 sec_level = conn->pending_sec_level;
2365
2366         if (sec_level > conn->sec_level)
2367                 conn->pending_sec_level = sec_level;
2368         else if (test_bit(HCI_CONN_AUTH, &conn->flags))
2369                 return 1;
2370
2371         /* Make sure we preserve an existing MITM requirement*/
2372         auth_type |= (conn->auth_type & 0x01);
2373
2374         conn->auth_type = auth_type;
2375
2376         if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->flags)) {
2377                 struct hci_cp_auth_requested cp;
2378
2379                 cp.handle = cpu_to_le16(conn->handle);
2380                 hci_send_cmd(conn->hdev, HCI_OP_AUTH_REQUESTED,
2381                              sizeof(cp), &cp);
2382
2383                 /* Set the ENCRYPT_PEND to trigger encryption after
2384                  * authentication.
2385                  */
2386                 if (!test_bit(HCI_CONN_ENCRYPT, &conn->flags))
2387                         set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags);
2388         }
2389
2390         return 0;
2391 }
2392
2393 /* Encrypt the link */
2394 static void hci_conn_encrypt(struct hci_conn *conn)
2395 {
2396         BT_DBG("hcon %p", conn);
2397
2398         if (!test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) {
2399                 struct hci_cp_set_conn_encrypt cp;
2400                 cp.handle  = cpu_to_le16(conn->handle);
2401                 cp.encrypt = 0x01;
2402                 hci_send_cmd(conn->hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(cp),
2403                              &cp);
2404         }
2405 }
2406
2407 /* Enable security */
2408 int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type,
2409                       bool initiator)
2410 {
2411         BT_DBG("hcon %p", conn);
2412
2413         if (conn->type == LE_LINK)
2414                 return smp_conn_security(conn, sec_level);
2415
2416         /* For sdp we don't need the link key. */
2417         if (sec_level == BT_SECURITY_SDP)
2418                 return 1;
2419
2420         /* For non 2.1 devices and low security level we don't need the link
2421            key. */
2422         if (sec_level == BT_SECURITY_LOW && !hci_conn_ssp_enabled(conn))
2423                 return 1;
2424
2425         /* For other security levels we need the link key. */
2426         if (!test_bit(HCI_CONN_AUTH, &conn->flags))
2427                 goto auth;
2428
2429         switch (conn->key_type) {
2430         case HCI_LK_AUTH_COMBINATION_P256:
2431                 /* An authenticated FIPS approved combination key has
2432                  * sufficient security for security level 4 or lower.
2433                  */
2434                 if (sec_level <= BT_SECURITY_FIPS)
2435                         goto encrypt;
2436                 break;
2437         case HCI_LK_AUTH_COMBINATION_P192:
2438                 /* An authenticated combination key has sufficient security for
2439                  * security level 3 or lower.
2440                  */
2441                 if (sec_level <= BT_SECURITY_HIGH)
2442                         goto encrypt;
2443                 break;
2444         case HCI_LK_UNAUTH_COMBINATION_P192:
2445         case HCI_LK_UNAUTH_COMBINATION_P256:
2446                 /* An unauthenticated combination key has sufficient security
2447                  * for security level 2 or lower.
2448                  */
2449                 if (sec_level <= BT_SECURITY_MEDIUM)
2450                         goto encrypt;
2451                 break;
2452         case HCI_LK_COMBINATION:
2453                 /* A combination key has always sufficient security for the
2454                  * security levels 2 or lower. High security level requires the
2455                  * combination key is generated using maximum PIN code length
2456                  * (16). For pre 2.1 units.
2457                  */
2458                 if (sec_level <= BT_SECURITY_MEDIUM || conn->pin_length == 16)
2459                         goto encrypt;
2460                 break;
2461         default:
2462                 break;
2463         }
2464
2465 auth:
2466         if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags))
2467                 return 0;
2468
2469         if (initiator)
2470                 set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags);
2471
2472         if (!hci_conn_auth(conn, sec_level, auth_type))
2473                 return 0;
2474
2475 encrypt:
2476         if (test_bit(HCI_CONN_ENCRYPT, &conn->flags)) {
2477                 /* Ensure that the encryption key size has been read,
2478                  * otherwise stall the upper layer responses.
2479                  */
2480                 if (!conn->enc_key_size)
2481                         return 0;
2482
2483                 /* Nothing else needed, all requirements are met */
2484                 return 1;
2485         }
2486
2487         hci_conn_encrypt(conn);
2488         return 0;
2489 }
2490 EXPORT_SYMBOL(hci_conn_security);
2491
2492 /* Check secure link requirement */
2493 int hci_conn_check_secure(struct hci_conn *conn, __u8 sec_level)
2494 {
2495         BT_DBG("hcon %p", conn);
2496
2497         /* Accept if non-secure or higher security level is required */
2498         if (sec_level != BT_SECURITY_HIGH && sec_level != BT_SECURITY_FIPS)
2499                 return 1;
2500
2501         /* Accept if secure or higher security level is already present */
2502         if (conn->sec_level == BT_SECURITY_HIGH ||
2503             conn->sec_level == BT_SECURITY_FIPS)
2504                 return 1;
2505
2506         /* Reject not secure link */
2507         return 0;
2508 }
2509 EXPORT_SYMBOL(hci_conn_check_secure);
2510
2511 /* Switch role */
2512 int hci_conn_switch_role(struct hci_conn *conn, __u8 role)
2513 {
2514         BT_DBG("hcon %p", conn);
2515
2516         if (role == conn->role)
2517                 return 1;
2518
2519         if (!test_and_set_bit(HCI_CONN_RSWITCH_PEND, &conn->flags)) {
2520                 struct hci_cp_switch_role cp;
2521                 bacpy(&cp.bdaddr, &conn->dst);
2522                 cp.role = role;
2523                 hci_send_cmd(conn->hdev, HCI_OP_SWITCH_ROLE, sizeof(cp), &cp);
2524         }
2525
2526         return 0;
2527 }
2528 EXPORT_SYMBOL(hci_conn_switch_role);
2529
2530 /* Enter active mode */
2531 void hci_conn_enter_active_mode(struct hci_conn *conn, __u8 force_active)
2532 {
2533         struct hci_dev *hdev = conn->hdev;
2534
2535         BT_DBG("hcon %p mode %d", conn, conn->mode);
2536
2537         if (conn->mode != HCI_CM_SNIFF)
2538                 goto timer;
2539
2540         if (!test_bit(HCI_CONN_POWER_SAVE, &conn->flags) && !force_active)
2541                 goto timer;
2542
2543         if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) {
2544                 struct hci_cp_exit_sniff_mode cp;
2545                 cp.handle = cpu_to_le16(conn->handle);
2546                 hci_send_cmd(hdev, HCI_OP_EXIT_SNIFF_MODE, sizeof(cp), &cp);
2547         }
2548
2549 timer:
2550         if (hdev->idle_timeout > 0)
2551                 queue_delayed_work(hdev->workqueue, &conn->idle_work,
2552                                    msecs_to_jiffies(hdev->idle_timeout));
2553 }
2554
2555 /* Drop all connection on the device */
2556 void hci_conn_hash_flush(struct hci_dev *hdev)
2557 {
2558         struct list_head *head = &hdev->conn_hash.list;
2559         struct hci_conn *conn;
2560
2561         BT_DBG("hdev %s", hdev->name);
2562
2563         /* We should not traverse the list here, because hci_conn_del
2564          * can remove extra links, which may cause the list traversal
2565          * to hit items that have already been released.
2566          */
2567         while ((conn = list_first_entry_or_null(head,
2568                                                 struct hci_conn,
2569                                                 list)) != NULL) {
2570                 conn->state = BT_CLOSED;
2571                 hci_disconn_cfm(conn, HCI_ERROR_LOCAL_HOST_TERM);
2572                 hci_conn_del(conn);
2573         }
2574 }
2575
2576 /* Check pending connect attempts */
2577 void hci_conn_check_pending(struct hci_dev *hdev)
2578 {
2579         struct hci_conn *conn;
2580
2581         BT_DBG("hdev %s", hdev->name);
2582
2583         hci_dev_lock(hdev);
2584
2585         conn = hci_conn_hash_lookup_state(hdev, ACL_LINK, BT_CONNECT2);
2586         if (conn)
2587                 hci_acl_create_connection(conn);
2588
2589         hci_dev_unlock(hdev);
2590 }
2591
2592 static u32 get_link_mode(struct hci_conn *conn)
2593 {
2594         u32 link_mode = 0;
2595
2596         if (conn->role == HCI_ROLE_MASTER)
2597                 link_mode |= HCI_LM_MASTER;
2598
2599         if (test_bit(HCI_CONN_ENCRYPT, &conn->flags))
2600                 link_mode |= HCI_LM_ENCRYPT;
2601
2602         if (test_bit(HCI_CONN_AUTH, &conn->flags))
2603                 link_mode |= HCI_LM_AUTH;
2604
2605         if (test_bit(HCI_CONN_SECURE, &conn->flags))
2606                 link_mode |= HCI_LM_SECURE;
2607
2608         if (test_bit(HCI_CONN_FIPS, &conn->flags))
2609                 link_mode |= HCI_LM_FIPS;
2610
2611         return link_mode;
2612 }
2613
2614 int hci_get_conn_list(void __user *arg)
2615 {
2616         struct hci_conn *c;
2617         struct hci_conn_list_req req, *cl;
2618         struct hci_conn_info *ci;
2619         struct hci_dev *hdev;
2620         int n = 0, size, err;
2621
2622         if (copy_from_user(&req, arg, sizeof(req)))
2623                 return -EFAULT;
2624
2625         if (!req.conn_num || req.conn_num > (PAGE_SIZE * 2) / sizeof(*ci))
2626                 return -EINVAL;
2627
2628         size = sizeof(req) + req.conn_num * sizeof(*ci);
2629
2630         cl = kmalloc(size, GFP_KERNEL);
2631         if (!cl)
2632                 return -ENOMEM;
2633
2634         hdev = hci_dev_get(req.dev_id);
2635         if (!hdev) {
2636                 kfree(cl);
2637                 return -ENODEV;
2638         }
2639
2640         ci = cl->conn_info;
2641
2642         hci_dev_lock(hdev);
2643         list_for_each_entry(c, &hdev->conn_hash.list, list) {
2644                 bacpy(&(ci + n)->bdaddr, &c->dst);
2645                 (ci + n)->handle = c->handle;
2646                 (ci + n)->type  = c->type;
2647                 (ci + n)->out   = c->out;
2648                 (ci + n)->state = c->state;
2649                 (ci + n)->link_mode = get_link_mode(c);
2650                 if (++n >= req.conn_num)
2651                         break;
2652         }
2653         hci_dev_unlock(hdev);
2654
2655         cl->dev_id = hdev->id;
2656         cl->conn_num = n;
2657         size = sizeof(req) + n * sizeof(*ci);
2658
2659         hci_dev_put(hdev);
2660
2661         err = copy_to_user(arg, cl, size);
2662         kfree(cl);
2663
2664         return err ? -EFAULT : 0;
2665 }
2666
2667 int hci_get_conn_info(struct hci_dev *hdev, void __user *arg)
2668 {
2669         struct hci_conn_info_req req;
2670         struct hci_conn_info ci;
2671         struct hci_conn *conn;
2672         char __user *ptr = arg + sizeof(req);
2673
2674         if (copy_from_user(&req, arg, sizeof(req)))
2675                 return -EFAULT;
2676
2677         hci_dev_lock(hdev);
2678         conn = hci_conn_hash_lookup_ba(hdev, req.type, &req.bdaddr);
2679         if (conn) {
2680                 bacpy(&ci.bdaddr, &conn->dst);
2681                 ci.handle = conn->handle;
2682                 ci.type  = conn->type;
2683                 ci.out   = conn->out;
2684                 ci.state = conn->state;
2685                 ci.link_mode = get_link_mode(conn);
2686         }
2687         hci_dev_unlock(hdev);
2688
2689         if (!conn)
2690                 return -ENOENT;
2691
2692         return copy_to_user(ptr, &ci, sizeof(ci)) ? -EFAULT : 0;
2693 }
2694
2695 int hci_get_auth_info(struct hci_dev *hdev, void __user *arg)
2696 {
2697         struct hci_auth_info_req req;
2698         struct hci_conn *conn;
2699
2700         if (copy_from_user(&req, arg, sizeof(req)))
2701                 return -EFAULT;
2702
2703         hci_dev_lock(hdev);
2704         conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &req.bdaddr);
2705         if (conn)
2706                 req.type = conn->auth_type;
2707         hci_dev_unlock(hdev);
2708
2709         if (!conn)
2710                 return -ENOENT;
2711
2712         return copy_to_user(arg, &req, sizeof(req)) ? -EFAULT : 0;
2713 }
2714
2715 struct hci_chan *hci_chan_create(struct hci_conn *conn)
2716 {
2717         struct hci_dev *hdev = conn->hdev;
2718         struct hci_chan *chan;
2719
2720         BT_DBG("%s hcon %p", hdev->name, conn);
2721
2722         if (test_bit(HCI_CONN_DROP, &conn->flags)) {
2723                 BT_DBG("Refusing to create new hci_chan");
2724                 return NULL;
2725         }
2726
2727         chan = kzalloc(sizeof(*chan), GFP_KERNEL);
2728         if (!chan)
2729                 return NULL;
2730
2731         chan->conn = hci_conn_get(conn);
2732         skb_queue_head_init(&chan->data_q);
2733         chan->state = BT_CONNECTED;
2734
2735         list_add_rcu(&chan->list, &conn->chan_list);
2736
2737         return chan;
2738 }
2739
2740 void hci_chan_del(struct hci_chan *chan)
2741 {
2742         struct hci_conn *conn = chan->conn;
2743         struct hci_dev *hdev = conn->hdev;
2744
2745         BT_DBG("%s hcon %p chan %p", hdev->name, conn, chan);
2746
2747         list_del_rcu(&chan->list);
2748
2749         synchronize_rcu();
2750
2751         /* Prevent new hci_chan's to be created for this hci_conn */
2752         set_bit(HCI_CONN_DROP, &conn->flags);
2753
2754         hci_conn_put(conn);
2755
2756         skb_queue_purge(&chan->data_q);
2757         kfree(chan);
2758 }
2759
2760 void hci_chan_list_flush(struct hci_conn *conn)
2761 {
2762         struct hci_chan *chan, *n;
2763
2764         BT_DBG("hcon %p", conn);
2765
2766         list_for_each_entry_safe(chan, n, &conn->chan_list, list)
2767                 hci_chan_del(chan);
2768 }
2769
2770 static struct hci_chan *__hci_chan_lookup_handle(struct hci_conn *hcon,
2771                                                  __u16 handle)
2772 {
2773         struct hci_chan *hchan;
2774
2775         list_for_each_entry(hchan, &hcon->chan_list, list) {
2776                 if (hchan->handle == handle)
2777                         return hchan;
2778         }
2779
2780         return NULL;
2781 }
2782
2783 struct hci_chan *hci_chan_lookup_handle(struct hci_dev *hdev, __u16 handle)
2784 {
2785         struct hci_conn_hash *h = &hdev->conn_hash;
2786         struct hci_conn *hcon;
2787         struct hci_chan *hchan = NULL;
2788
2789         rcu_read_lock();
2790
2791         list_for_each_entry_rcu(hcon, &h->list, list) {
2792                 hchan = __hci_chan_lookup_handle(hcon, handle);
2793                 if (hchan)
2794                         break;
2795         }
2796
2797         rcu_read_unlock();
2798
2799         return hchan;
2800 }
2801
2802 u32 hci_conn_get_phy(struct hci_conn *conn)
2803 {
2804         u32 phys = 0;
2805
2806         /* BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 2, Part B page 471:
2807          * Table 6.2: Packets defined for synchronous, asynchronous, and
2808          * CPB logical transport types.
2809          */
2810         switch (conn->type) {
2811         case SCO_LINK:
2812                 /* SCO logical transport (1 Mb/s):
2813                  * HV1, HV2, HV3 and DV.
2814                  */
2815                 phys |= BT_PHY_BR_1M_1SLOT;
2816
2817                 break;
2818
2819         case ACL_LINK:
2820                 /* ACL logical transport (1 Mb/s) ptt=0:
2821                  * DH1, DM3, DH3, DM5 and DH5.
2822                  */
2823                 phys |= BT_PHY_BR_1M_1SLOT;
2824
2825                 if (conn->pkt_type & (HCI_DM3 | HCI_DH3))
2826                         phys |= BT_PHY_BR_1M_3SLOT;
2827
2828                 if (conn->pkt_type & (HCI_DM5 | HCI_DH5))
2829                         phys |= BT_PHY_BR_1M_5SLOT;
2830
2831                 /* ACL logical transport (2 Mb/s) ptt=1:
2832                  * 2-DH1, 2-DH3 and 2-DH5.
2833                  */
2834                 if (!(conn->pkt_type & HCI_2DH1))
2835                         phys |= BT_PHY_EDR_2M_1SLOT;
2836
2837                 if (!(conn->pkt_type & HCI_2DH3))
2838                         phys |= BT_PHY_EDR_2M_3SLOT;
2839
2840                 if (!(conn->pkt_type & HCI_2DH5))
2841                         phys |= BT_PHY_EDR_2M_5SLOT;
2842
2843                 /* ACL logical transport (3 Mb/s) ptt=1:
2844                  * 3-DH1, 3-DH3 and 3-DH5.
2845                  */
2846                 if (!(conn->pkt_type & HCI_3DH1))
2847                         phys |= BT_PHY_EDR_3M_1SLOT;
2848
2849                 if (!(conn->pkt_type & HCI_3DH3))
2850                         phys |= BT_PHY_EDR_3M_3SLOT;
2851
2852                 if (!(conn->pkt_type & HCI_3DH5))
2853                         phys |= BT_PHY_EDR_3M_5SLOT;
2854
2855                 break;
2856
2857         case ESCO_LINK:
2858                 /* eSCO logical transport (1 Mb/s): EV3, EV4 and EV5 */
2859                 phys |= BT_PHY_BR_1M_1SLOT;
2860
2861                 if (!(conn->pkt_type & (ESCO_EV4 | ESCO_EV5)))
2862                         phys |= BT_PHY_BR_1M_3SLOT;
2863
2864                 /* eSCO logical transport (2 Mb/s): 2-EV3, 2-EV5 */
2865                 if (!(conn->pkt_type & ESCO_2EV3))
2866                         phys |= BT_PHY_EDR_2M_1SLOT;
2867
2868                 if (!(conn->pkt_type & ESCO_2EV5))
2869                         phys |= BT_PHY_EDR_2M_3SLOT;
2870
2871                 /* eSCO logical transport (3 Mb/s): 3-EV3, 3-EV5 */
2872                 if (!(conn->pkt_type & ESCO_3EV3))
2873                         phys |= BT_PHY_EDR_3M_1SLOT;
2874
2875                 if (!(conn->pkt_type & ESCO_3EV5))
2876                         phys |= BT_PHY_EDR_3M_3SLOT;
2877
2878                 break;
2879
2880         case LE_LINK:
2881                 if (conn->le_tx_phy & HCI_LE_SET_PHY_1M)
2882                         phys |= BT_PHY_LE_1M_TX;
2883
2884                 if (conn->le_rx_phy & HCI_LE_SET_PHY_1M)
2885                         phys |= BT_PHY_LE_1M_RX;
2886
2887                 if (conn->le_tx_phy & HCI_LE_SET_PHY_2M)
2888                         phys |= BT_PHY_LE_2M_TX;
2889
2890                 if (conn->le_rx_phy & HCI_LE_SET_PHY_2M)
2891                         phys |= BT_PHY_LE_2M_RX;
2892
2893                 if (conn->le_tx_phy & HCI_LE_SET_PHY_CODED)
2894                         phys |= BT_PHY_LE_CODED_TX;
2895
2896                 if (conn->le_rx_phy & HCI_LE_SET_PHY_CODED)
2897                         phys |= BT_PHY_LE_CODED_RX;
2898
2899                 break;
2900         }
2901
2902         return phys;
2903 }
2904
2905 static int abort_conn_sync(struct hci_dev *hdev, void *data)
2906 {
2907         struct hci_conn *conn;
2908         u16 handle = PTR_UINT(data);
2909
2910         conn = hci_conn_hash_lookup_handle(hdev, handle);
2911         if (!conn)
2912                 return 0;
2913
2914         return hci_abort_conn_sync(hdev, conn, conn->abort_reason);
2915 }
2916
2917 int hci_abort_conn(struct hci_conn *conn, u8 reason)
2918 {
2919         struct hci_dev *hdev = conn->hdev;
2920
2921         /* If abort_reason has already been set it means the connection is
2922          * already being aborted so don't attempt to overwrite it.
2923          */
2924         if (conn->abort_reason)
2925                 return 0;
2926
2927         bt_dev_dbg(hdev, "handle 0x%2.2x reason 0x%2.2x", conn->handle, reason);
2928
2929         conn->abort_reason = reason;
2930
2931         /* If the connection is pending check the command opcode since that
2932          * might be blocking on hci_cmd_sync_work while waiting its respective
2933          * event so we need to hci_cmd_sync_cancel to cancel it.
2934          *
2935          * hci_connect_le serializes the connection attempts so only one
2936          * connection can be in BT_CONNECT at time.
2937          */
2938         if (conn->state == BT_CONNECT && hdev->req_status == HCI_REQ_PEND) {
2939                 switch (hci_skb_event(hdev->sent_cmd)) {
2940                 case HCI_EV_LE_CONN_COMPLETE:
2941                 case HCI_EV_LE_ENHANCED_CONN_COMPLETE:
2942                 case HCI_EVT_LE_CIS_ESTABLISHED:
2943                         hci_cmd_sync_cancel(hdev, -ECANCELED);
2944                         break;
2945                 }
2946         }
2947
2948         return hci_cmd_sync_queue(hdev, abort_conn_sync, UINT_PTR(conn->handle),
2949                                   NULL);
2950 }