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