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