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