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