xref: /linux/net/bluetooth/hci_conn.c (revision bea06c7c1b83bcd0519b91141999369eae6925bd)
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 	atomic_set(&conn->refcnt, 0);
1127 
1128 	hci_dev_hold(hdev);
1129 
1130 	hci_conn_hash_add(hdev, conn);
1131 
1132 	/* The SCO and eSCO connections will only be notified when their
1133 	 * setup has been completed. This is different to ACL links which
1134 	 * can be notified right away.
1135 	 */
1136 	if (conn->type != SCO_LINK && conn->type != ESCO_LINK) {
1137 		if (hdev->notify)
1138 			hdev->notify(hdev, HCI_NOTIFY_CONN_ADD);
1139 	}
1140 
1141 	hci_conn_init_sysfs(conn);
1142 	return conn;
1143 }
1144 
1145 struct hci_conn *hci_conn_add_unset(struct hci_dev *hdev, int type,
1146 				    bdaddr_t *dst, u8 dst_type, u8 role)
1147 {
1148 	int handle;
1149 
1150 	bt_dev_dbg(hdev, "dst %pMR", dst);
1151 
1152 	handle = hci_conn_hash_alloc_unset(hdev);
1153 	if (unlikely(handle < 0))
1154 		return ERR_PTR(-ECONNREFUSED);
1155 
1156 	return __hci_conn_add(hdev, type, dst, dst_type, role, handle);
1157 }
1158 
1159 struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type, bdaddr_t *dst,
1160 			      u8 dst_type, u8 role, u16 handle)
1161 {
1162 	if (handle > HCI_CONN_HANDLE_MAX)
1163 		return ERR_PTR(-EINVAL);
1164 
1165 	return __hci_conn_add(hdev, type, dst, dst_type, role, handle);
1166 }
1167 
1168 static void hci_conn_cleanup_child(struct hci_conn *conn, u8 reason)
1169 {
1170 	if (!reason)
1171 		reason = HCI_ERROR_REMOTE_USER_TERM;
1172 
1173 	/* Due to race, SCO/ISO conn might be not established yet at this point,
1174 	 * and nothing else will clean it up. In other cases it is done via HCI
1175 	 * events.
1176 	 */
1177 	switch (conn->type) {
1178 	case SCO_LINK:
1179 	case ESCO_LINK:
1180 		if (HCI_CONN_HANDLE_UNSET(conn->handle))
1181 			hci_conn_failed(conn, reason);
1182 		break;
1183 	case CIS_LINK:
1184 	case BIS_LINK:
1185 	case PA_LINK:
1186 		if ((conn->state != BT_CONNECTED &&
1187 		    !test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) ||
1188 		    test_bit(HCI_CONN_BIG_CREATED, &conn->flags))
1189 			hci_conn_failed(conn, reason);
1190 		break;
1191 	}
1192 }
1193 
1194 static void hci_conn_unlink(struct hci_conn *conn)
1195 {
1196 	struct hci_dev *hdev = conn->hdev;
1197 
1198 	bt_dev_dbg(hdev, "hcon %p", conn);
1199 
1200 	if (!conn->parent) {
1201 		struct hci_link *link, *t;
1202 
1203 		list_for_each_entry_safe(link, t, &conn->link_list, list) {
1204 			struct hci_conn *child = link->conn;
1205 
1206 			hci_conn_unlink(child);
1207 
1208 			/* If hdev is down it means
1209 			 * hci_dev_close_sync/hci_conn_hash_flush is in progress
1210 			 * and links don't need to be cleanup as all connections
1211 			 * would be cleanup.
1212 			 */
1213 			if (!test_bit(HCI_UP, &hdev->flags))
1214 				continue;
1215 
1216 			hci_conn_cleanup_child(child, conn->abort_reason);
1217 		}
1218 
1219 		return;
1220 	}
1221 
1222 	if (!conn->link)
1223 		return;
1224 
1225 	list_del_rcu(&conn->link->list);
1226 	synchronize_rcu();
1227 
1228 	hci_conn_drop(conn->parent);
1229 	hci_conn_put(conn->parent);
1230 	conn->parent = NULL;
1231 
1232 	kfree(conn->link);
1233 	conn->link = NULL;
1234 }
1235 
1236 void hci_conn_del(struct hci_conn *conn)
1237 {
1238 	struct hci_dev *hdev = conn->hdev;
1239 
1240 	BT_DBG("%s hcon %p handle %d", hdev->name, conn, conn->handle);
1241 
1242 	hci_conn_unlink(conn);
1243 
1244 	disable_delayed_work_sync(&conn->disc_work);
1245 	disable_delayed_work_sync(&conn->auto_accept_work);
1246 	disable_delayed_work_sync(&conn->idle_work);
1247 
1248 	/* Remove the connection from the list so unacked logic can detect when
1249 	 * a certain pool is not being utilized.
1250 	 */
1251 	hci_conn_hash_del(hdev, conn);
1252 
1253 	/* Handle unacked frames:
1254 	 *
1255 	 * - In case there are no connection, or if restoring the buffers
1256 	 *   considered in transist would overflow, restore all buffers to the
1257 	 *   pool.
1258 	 * - Otherwise restore just the buffers considered in transit for the
1259 	 *   hci_conn
1260 	 */
1261 	switch (conn->type) {
1262 	case ACL_LINK:
1263 		if (!hci_conn_num(hdev, ACL_LINK) ||
1264 		    hdev->acl_cnt + conn->sent > hdev->acl_pkts)
1265 			hdev->acl_cnt = hdev->acl_pkts;
1266 		else
1267 			hdev->acl_cnt += conn->sent;
1268 		break;
1269 	case LE_LINK:
1270 		cancel_delayed_work(&conn->le_conn_timeout);
1271 
1272 		if (hdev->le_pkts) {
1273 			if (!hci_conn_num(hdev, LE_LINK) ||
1274 			    hdev->le_cnt + conn->sent > hdev->le_pkts)
1275 				hdev->le_cnt = hdev->le_pkts;
1276 			else
1277 				hdev->le_cnt += conn->sent;
1278 		} else {
1279 			if ((!hci_conn_num(hdev, LE_LINK) &&
1280 			     !hci_conn_num(hdev, ACL_LINK)) ||
1281 			    hdev->acl_cnt + conn->sent > hdev->acl_pkts)
1282 				hdev->acl_cnt = hdev->acl_pkts;
1283 			else
1284 				hdev->acl_cnt += conn->sent;
1285 		}
1286 		break;
1287 	case CIS_LINK:
1288 	case BIS_LINK:
1289 	case PA_LINK:
1290 		if (!hci_iso_count(hdev) ||
1291 		    hdev->iso_cnt + conn->sent > hdev->iso_pkts)
1292 			hdev->iso_cnt = hdev->iso_pkts;
1293 		else
1294 			hdev->iso_cnt += conn->sent;
1295 		break;
1296 	}
1297 
1298 	skb_queue_purge(&conn->data_q);
1299 	skb_queue_purge(&conn->tx_q.queue);
1300 
1301 	/* Remove the connection from the list and cleanup its remaining
1302 	 * state. This is a separate function since for some cases like
1303 	 * BT_CONNECT_SCAN we *only* want the cleanup part without the
1304 	 * rest of hci_conn_del.
1305 	 */
1306 	hci_conn_cleanup(conn);
1307 
1308 	/* Dequeue callbacks using connection pointer as data */
1309 	hci_cmd_sync_dequeue(hdev, NULL, conn, NULL);
1310 }
1311 
1312 struct hci_dev *hci_get_route(bdaddr_t *dst, bdaddr_t *src, uint8_t src_type)
1313 {
1314 	int use_src = bacmp(src, BDADDR_ANY);
1315 	struct hci_dev *hdev = NULL, *d;
1316 
1317 	BT_DBG("%pMR -> %pMR", src, dst);
1318 
1319 	read_lock(&hci_dev_list_lock);
1320 
1321 	list_for_each_entry(d, &hci_dev_list, list) {
1322 		if (!test_bit(HCI_UP, &d->flags) ||
1323 		    hci_dev_test_flag(d, HCI_USER_CHANNEL))
1324 			continue;
1325 
1326 		/* Simple routing:
1327 		 *   No source address - find interface with bdaddr != dst
1328 		 *   Source address    - find interface with bdaddr == src
1329 		 */
1330 
1331 		if (use_src) {
1332 			bdaddr_t id_addr;
1333 			u8 id_addr_type;
1334 
1335 			if (src_type == BDADDR_BREDR) {
1336 				if (!lmp_bredr_capable(d))
1337 					continue;
1338 				bacpy(&id_addr, &d->bdaddr);
1339 				id_addr_type = BDADDR_BREDR;
1340 			} else {
1341 				if (!lmp_le_capable(d))
1342 					continue;
1343 
1344 				hci_copy_identity_address(d, &id_addr,
1345 							  &id_addr_type);
1346 
1347 				/* Convert from HCI to three-value type */
1348 				if (id_addr_type == ADDR_LE_DEV_PUBLIC)
1349 					id_addr_type = BDADDR_LE_PUBLIC;
1350 				else
1351 					id_addr_type = BDADDR_LE_RANDOM;
1352 			}
1353 
1354 			if (!bacmp(&id_addr, src) && id_addr_type == src_type) {
1355 				hdev = d; break;
1356 			}
1357 		} else {
1358 			if (bacmp(&d->bdaddr, dst)) {
1359 				hdev = d; break;
1360 			}
1361 		}
1362 	}
1363 
1364 	if (hdev)
1365 		hdev = hci_dev_hold(hdev);
1366 
1367 	read_unlock(&hci_dev_list_lock);
1368 	return hdev;
1369 }
1370 EXPORT_SYMBOL(hci_get_route);
1371 
1372 /* This function requires the caller holds hdev->lock */
1373 static void hci_le_conn_failed(struct hci_conn *conn, u8 status)
1374 {
1375 	struct hci_dev *hdev = conn->hdev;
1376 
1377 	hci_connect_le_scan_cleanup(conn, status);
1378 
1379 	/* Enable advertising in case this was a failed connection
1380 	 * attempt as a peripheral.
1381 	 */
1382 	hci_enable_advertising(hdev);
1383 }
1384 
1385 /* This function requires the caller holds hdev->lock */
1386 void hci_conn_failed(struct hci_conn *conn, u8 status)
1387 {
1388 	struct hci_dev *hdev = conn->hdev;
1389 
1390 	bt_dev_dbg(hdev, "status 0x%2.2x", status);
1391 
1392 	switch (conn->type) {
1393 	case LE_LINK:
1394 		hci_le_conn_failed(conn, status);
1395 		break;
1396 	case ACL_LINK:
1397 		mgmt_connect_failed(hdev, conn, status);
1398 		break;
1399 	}
1400 
1401 	/* In case of BIG/PA sync failed, clear conn flags so that
1402 	 * the conns will be correctly cleaned up by ISO layer
1403 	 */
1404 	test_and_clear_bit(HCI_CONN_BIG_SYNC_FAILED, &conn->flags);
1405 	test_and_clear_bit(HCI_CONN_PA_SYNC_FAILED, &conn->flags);
1406 
1407 	conn->state = BT_CLOSED;
1408 	hci_connect_cfm(conn, status);
1409 	hci_conn_del(conn);
1410 }
1411 
1412 /* This function requires the caller holds hdev->lock */
1413 u8 hci_conn_set_handle(struct hci_conn *conn, u16 handle)
1414 {
1415 	struct hci_dev *hdev = conn->hdev;
1416 
1417 	bt_dev_dbg(hdev, "hcon %p handle 0x%4.4x", conn, handle);
1418 
1419 	if (conn->handle == handle)
1420 		return 0;
1421 
1422 	if (handle > HCI_CONN_HANDLE_MAX) {
1423 		bt_dev_err(hdev, "Invalid handle: 0x%4.4x > 0x%4.4x",
1424 			   handle, HCI_CONN_HANDLE_MAX);
1425 		return HCI_ERROR_INVALID_PARAMETERS;
1426 	}
1427 
1428 	/* If abort_reason has been sent it means the connection is being
1429 	 * aborted and the handle shall not be changed.
1430 	 */
1431 	if (conn->abort_reason)
1432 		return conn->abort_reason;
1433 
1434 	if (HCI_CONN_HANDLE_UNSET(conn->handle))
1435 		ida_free(&hdev->unset_handle_ida, conn->handle);
1436 
1437 	conn->handle = handle;
1438 
1439 	return 0;
1440 }
1441 
1442 struct hci_conn *hci_connect_le(struct hci_dev *hdev, bdaddr_t *dst,
1443 				u8 dst_type, bool dst_resolved, u8 sec_level,
1444 				u16 conn_timeout, u8 role, u8 phy, u8 sec_phy)
1445 {
1446 	struct hci_conn *conn;
1447 	struct smp_irk *irk;
1448 	int err;
1449 
1450 	/* Let's make sure that le is enabled.*/
1451 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1452 		if (lmp_le_capable(hdev))
1453 			return ERR_PTR(-ECONNREFUSED);
1454 
1455 		return ERR_PTR(-EOPNOTSUPP);
1456 	}
1457 
1458 	/* Since the controller supports only one LE connection attempt at a
1459 	 * time, we return -EBUSY if there is any connection attempt running.
1460 	 */
1461 	if (hci_lookup_le_connect(hdev))
1462 		return ERR_PTR(-EBUSY);
1463 
1464 	/* If there's already a connection object but it's not in
1465 	 * scanning state it means it must already be established, in
1466 	 * which case we can't do anything else except report a failure
1467 	 * to connect.
1468 	 */
1469 	conn = hci_conn_hash_lookup_le(hdev, dst, dst_type);
1470 	if (conn && !test_bit(HCI_CONN_SCANNING, &conn->flags)) {
1471 		return ERR_PTR(-EBUSY);
1472 	}
1473 
1474 	/* Check if the destination address has been resolved by the controller
1475 	 * since if it did then the identity address shall be used.
1476 	 */
1477 	if (!dst_resolved) {
1478 		/* When given an identity address with existing identity
1479 		 * resolving key, the connection needs to be established
1480 		 * to a resolvable random address.
1481 		 *
1482 		 * Storing the resolvable random address is required here
1483 		 * to handle connection failures. The address will later
1484 		 * be resolved back into the original identity address
1485 		 * from the connect request.
1486 		 */
1487 		irk = hci_find_irk_by_addr(hdev, dst, dst_type);
1488 		if (irk && bacmp(&irk->rpa, BDADDR_ANY)) {
1489 			dst = &irk->rpa;
1490 			dst_type = ADDR_LE_DEV_RANDOM;
1491 		}
1492 	}
1493 
1494 	if (conn) {
1495 		bacpy(&conn->dst, dst);
1496 	} else {
1497 		conn = hci_conn_add_unset(hdev, LE_LINK, dst, dst_type, role);
1498 		if (IS_ERR(conn))
1499 			return conn;
1500 		hci_conn_hold(conn);
1501 		conn->pending_sec_level = sec_level;
1502 	}
1503 
1504 	conn->sec_level = BT_SECURITY_LOW;
1505 	conn->conn_timeout = conn_timeout;
1506 	conn->le_adv_phy = phy;
1507 	conn->le_adv_sec_phy = sec_phy;
1508 
1509 	err = hci_connect_le_sync(hdev, conn);
1510 	if (err) {
1511 		hci_conn_del(conn);
1512 		return ERR_PTR(err);
1513 	}
1514 
1515 	return conn;
1516 }
1517 
1518 static bool is_connected(struct hci_dev *hdev, bdaddr_t *addr, u8 type)
1519 {
1520 	struct hci_conn *conn;
1521 
1522 	conn = hci_conn_hash_lookup_le(hdev, addr, type);
1523 	if (!conn)
1524 		return false;
1525 
1526 	if (conn->state != BT_CONNECTED)
1527 		return false;
1528 
1529 	return true;
1530 }
1531 
1532 /* This function requires the caller holds hdev->lock */
1533 static int hci_explicit_conn_params_set(struct hci_dev *hdev,
1534 					bdaddr_t *addr, u8 addr_type)
1535 {
1536 	struct hci_conn_params *params;
1537 
1538 	if (is_connected(hdev, addr, addr_type))
1539 		return -EISCONN;
1540 
1541 	params = hci_conn_params_lookup(hdev, addr, addr_type);
1542 	if (!params) {
1543 		params = hci_conn_params_add(hdev, addr, addr_type);
1544 		if (!params)
1545 			return -ENOMEM;
1546 
1547 		/* If we created new params, mark them to be deleted in
1548 		 * hci_connect_le_scan_cleanup. It's different case than
1549 		 * existing disabled params, those will stay after cleanup.
1550 		 */
1551 		params->auto_connect = HCI_AUTO_CONN_EXPLICIT;
1552 	}
1553 
1554 	/* We're trying to connect, so make sure params are at pend_le_conns */
1555 	if (params->auto_connect == HCI_AUTO_CONN_DISABLED ||
1556 	    params->auto_connect == HCI_AUTO_CONN_REPORT ||
1557 	    params->auto_connect == HCI_AUTO_CONN_EXPLICIT) {
1558 		hci_pend_le_list_del_init(params);
1559 		hci_pend_le_list_add(params, &hdev->pend_le_conns);
1560 	}
1561 
1562 	params->explicit_connect = true;
1563 
1564 	BT_DBG("addr %pMR (type %u) auto_connect %u", addr, addr_type,
1565 	       params->auto_connect);
1566 
1567 	return 0;
1568 }
1569 
1570 static int qos_set_big(struct hci_dev *hdev, struct bt_iso_qos *qos)
1571 {
1572 	struct hci_conn *conn;
1573 	u8  big;
1574 
1575 	/* Allocate a BIG if not set */
1576 	if (qos->bcast.big == BT_ISO_QOS_BIG_UNSET) {
1577 		for (big = 0x00; big < 0xef; big++) {
1578 
1579 			conn = hci_conn_hash_lookup_big(hdev, big);
1580 			if (!conn)
1581 				break;
1582 		}
1583 
1584 		if (big == 0xef)
1585 			return -EADDRNOTAVAIL;
1586 
1587 		/* Update BIG */
1588 		qos->bcast.big = big;
1589 	}
1590 
1591 	return 0;
1592 }
1593 
1594 static int qos_set_bis(struct hci_dev *hdev, struct bt_iso_qos *qos)
1595 {
1596 	struct hci_conn *conn;
1597 	u8  bis;
1598 
1599 	/* Allocate BIS if not set */
1600 	if (qos->bcast.bis == BT_ISO_QOS_BIS_UNSET) {
1601 		if (qos->bcast.big != BT_ISO_QOS_BIG_UNSET) {
1602 			conn = hci_conn_hash_lookup_big(hdev, qos->bcast.big);
1603 
1604 			if (conn) {
1605 				/* If the BIG handle is already matched to an advertising
1606 				 * handle, do not allocate a new one.
1607 				 */
1608 				qos->bcast.bis = conn->iso_qos.bcast.bis;
1609 				return 0;
1610 			}
1611 		}
1612 
1613 		/* Find an unused adv set to advertise BIS, skip instance 0x00
1614 		 * since it is reserved as general purpose set.
1615 		 */
1616 		for (bis = 0x01; bis < hdev->le_num_of_adv_sets;
1617 		     bis++) {
1618 
1619 			conn = hci_conn_hash_lookup_bis(hdev, BDADDR_ANY, bis);
1620 			if (!conn)
1621 				break;
1622 		}
1623 
1624 		if (bis == hdev->le_num_of_adv_sets)
1625 			return -EADDRNOTAVAIL;
1626 
1627 		/* Update BIS */
1628 		qos->bcast.bis = bis;
1629 	}
1630 
1631 	return 0;
1632 }
1633 
1634 /* This function requires the caller holds hdev->lock */
1635 static struct hci_conn *hci_add_bis(struct hci_dev *hdev, bdaddr_t *dst,
1636 				    __u8 sid, struct bt_iso_qos *qos,
1637 				    __u8 base_len, __u8 *base, u16 timeout)
1638 {
1639 	struct hci_conn *conn;
1640 	int err;
1641 
1642 	/* Let's make sure that le is enabled.*/
1643 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1644 		if (lmp_le_capable(hdev))
1645 			return ERR_PTR(-ECONNREFUSED);
1646 		return ERR_PTR(-EOPNOTSUPP);
1647 	}
1648 
1649 	err = qos_set_big(hdev, qos);
1650 	if (err)
1651 		return ERR_PTR(err);
1652 
1653 	err = qos_set_bis(hdev, qos);
1654 	if (err)
1655 		return ERR_PTR(err);
1656 
1657 	/* Check if the LE Create BIG command has already been sent */
1658 	conn = hci_conn_hash_lookup_per_adv_bis(hdev, dst, qos->bcast.big,
1659 						qos->bcast.big);
1660 	if (conn)
1661 		return ERR_PTR(-EADDRINUSE);
1662 
1663 	/* Check BIS settings against other bound BISes, since all
1664 	 * BISes in a BIG must have the same value for all parameters
1665 	 */
1666 	conn = hci_conn_hash_lookup_big(hdev, qos->bcast.big);
1667 
1668 	if (conn && (memcmp(qos, &conn->iso_qos, sizeof(*qos)) ||
1669 		     base_len != conn->le_per_adv_data_len ||
1670 		     memcmp(conn->le_per_adv_data, base, base_len)))
1671 		return ERR_PTR(-EADDRINUSE);
1672 
1673 	conn = hci_conn_add_unset(hdev, BIS_LINK, dst, 0, HCI_ROLE_MASTER);
1674 	if (IS_ERR(conn))
1675 		return conn;
1676 
1677 	conn->state = BT_CONNECT;
1678 	conn->sid = sid;
1679 	conn->conn_timeout = timeout;
1680 
1681 	hci_conn_hold(conn);
1682 	return conn;
1683 }
1684 
1685 /* This function requires the caller holds hdev->lock */
1686 struct hci_conn *hci_connect_le_scan(struct hci_dev *hdev, bdaddr_t *dst,
1687 				     u8 dst_type, u8 sec_level,
1688 				     u16 conn_timeout,
1689 				     enum conn_reasons conn_reason)
1690 {
1691 	struct hci_conn *conn;
1692 
1693 	/* Let's make sure that le is enabled.*/
1694 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1695 		if (lmp_le_capable(hdev))
1696 			return ERR_PTR(-ECONNREFUSED);
1697 
1698 		return ERR_PTR(-EOPNOTSUPP);
1699 	}
1700 
1701 	/* Some devices send ATT messages as soon as the physical link is
1702 	 * established. To be able to handle these ATT messages, the user-
1703 	 * space first establishes the connection and then starts the pairing
1704 	 * process.
1705 	 *
1706 	 * So if a hci_conn object already exists for the following connection
1707 	 * attempt, we simply update pending_sec_level and auth_type fields
1708 	 * and return the object found.
1709 	 */
1710 	conn = hci_conn_hash_lookup_le(hdev, dst, dst_type);
1711 	if (conn) {
1712 		if (conn->pending_sec_level < sec_level)
1713 			conn->pending_sec_level = sec_level;
1714 		goto done;
1715 	}
1716 
1717 	BT_DBG("requesting refresh of dst_addr");
1718 
1719 	conn = hci_conn_add_unset(hdev, LE_LINK, dst, dst_type,
1720 				  HCI_ROLE_MASTER);
1721 	if (IS_ERR(conn))
1722 		return conn;
1723 
1724 	if (hci_explicit_conn_params_set(hdev, dst, dst_type) < 0) {
1725 		hci_conn_del(conn);
1726 		return ERR_PTR(-EBUSY);
1727 	}
1728 
1729 	conn->state = BT_CONNECT;
1730 	set_bit(HCI_CONN_SCANNING, &conn->flags);
1731 	conn->sec_level = BT_SECURITY_LOW;
1732 	conn->pending_sec_level = sec_level;
1733 	conn->conn_timeout = conn_timeout;
1734 	conn->conn_reason = conn_reason;
1735 
1736 	hci_update_passive_scan(hdev);
1737 
1738 done:
1739 	hci_conn_hold(conn);
1740 	return conn;
1741 }
1742 
1743 struct hci_conn *hci_connect_acl(struct hci_dev *hdev, bdaddr_t *dst,
1744 				 u8 sec_level, u8 auth_type,
1745 				 enum conn_reasons conn_reason, u16 timeout)
1746 {
1747 	struct hci_conn *acl;
1748 
1749 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
1750 		if (lmp_bredr_capable(hdev))
1751 			return ERR_PTR(-ECONNREFUSED);
1752 
1753 		return ERR_PTR(-EOPNOTSUPP);
1754 	}
1755 
1756 	/* Reject outgoing connection to device with same BD ADDR against
1757 	 * CVE-2020-26555
1758 	 */
1759 	if (!bacmp(&hdev->bdaddr, dst)) {
1760 		bt_dev_dbg(hdev, "Reject connection with same BD_ADDR %pMR\n",
1761 			   dst);
1762 		return ERR_PTR(-ECONNREFUSED);
1763 	}
1764 
1765 	acl = hci_conn_hash_lookup_ba(hdev, ACL_LINK, dst);
1766 	if (!acl) {
1767 		acl = hci_conn_add_unset(hdev, ACL_LINK, dst, 0,
1768 					 HCI_ROLE_MASTER);
1769 		if (IS_ERR(acl))
1770 			return acl;
1771 	}
1772 
1773 	hci_conn_hold(acl);
1774 
1775 	acl->conn_reason = conn_reason;
1776 	if (acl->state == BT_OPEN || acl->state == BT_CLOSED) {
1777 		int err;
1778 
1779 		acl->sec_level = BT_SECURITY_LOW;
1780 		acl->pending_sec_level = sec_level;
1781 		acl->auth_type = auth_type;
1782 		acl->conn_timeout = timeout;
1783 
1784 		err = hci_connect_acl_sync(hdev, acl);
1785 		if (err) {
1786 			hci_conn_del(acl);
1787 			return ERR_PTR(err);
1788 		}
1789 	}
1790 
1791 	return acl;
1792 }
1793 
1794 static struct hci_link *hci_conn_link(struct hci_conn *parent,
1795 				      struct hci_conn *conn)
1796 {
1797 	struct hci_dev *hdev = parent->hdev;
1798 	struct hci_link *link;
1799 
1800 	bt_dev_dbg(hdev, "parent %p hcon %p", parent, conn);
1801 
1802 	if (conn->link)
1803 		return conn->link;
1804 
1805 	if (conn->parent)
1806 		return NULL;
1807 
1808 	link = kzalloc_obj(*link);
1809 	if (!link)
1810 		return NULL;
1811 
1812 	link->conn = hci_conn_hold(conn);
1813 	conn->link = link;
1814 	conn->parent = hci_conn_get(parent);
1815 
1816 	/* Use list_add_tail_rcu append to the list */
1817 	list_add_tail_rcu(&link->list, &parent->link_list);
1818 
1819 	return link;
1820 }
1821 
1822 struct hci_conn *hci_connect_sco(struct hci_dev *hdev, int type, bdaddr_t *dst,
1823 				 __u16 setting, struct bt_codec *codec,
1824 				 u16 timeout)
1825 {
1826 	struct hci_conn *acl;
1827 	struct hci_conn *sco;
1828 	struct hci_link *link;
1829 
1830 	acl = hci_connect_acl(hdev, dst, BT_SECURITY_LOW, HCI_AT_NO_BONDING,
1831 			      CONN_REASON_SCO_CONNECT, timeout);
1832 	if (IS_ERR(acl))
1833 		return acl;
1834 
1835 	sco = hci_conn_hash_lookup_ba(hdev, type, dst);
1836 	if (!sco) {
1837 		sco = hci_conn_add_unset(hdev, type, dst, 0, HCI_ROLE_MASTER);
1838 		if (IS_ERR(sco)) {
1839 			hci_conn_drop(acl);
1840 			return sco;
1841 		}
1842 	}
1843 
1844 	link = hci_conn_link(acl, sco);
1845 	if (!link) {
1846 		hci_conn_drop(acl);
1847 		hci_conn_drop(sco);
1848 		return ERR_PTR(-ENOLINK);
1849 	}
1850 
1851 	sco->setting = setting;
1852 	sco->codec = *codec;
1853 
1854 	if (acl->state == BT_CONNECTED &&
1855 	    (sco->state == BT_OPEN || sco->state == BT_CLOSED)) {
1856 		set_bit(HCI_CONN_POWER_SAVE, &acl->flags);
1857 		hci_conn_enter_active_mode(acl, BT_POWER_FORCE_ACTIVE_ON);
1858 
1859 		if (test_bit(HCI_CONN_MODE_CHANGE_PEND, &acl->flags)) {
1860 			/* defer SCO setup until mode change completed */
1861 			set_bit(HCI_CONN_SCO_SETUP_PEND, &acl->flags);
1862 			return sco;
1863 		}
1864 
1865 		hci_sco_setup(acl, 0x00);
1866 	}
1867 
1868 	return sco;
1869 }
1870 
1871 static int hci_le_create_big(struct hci_conn *conn, struct bt_iso_qos *qos)
1872 {
1873 	struct hci_dev *hdev = conn->hdev;
1874 	struct hci_cp_le_create_big cp;
1875 	struct iso_list_data data;
1876 
1877 	memset(&cp, 0, sizeof(cp));
1878 
1879 	data.big = qos->bcast.big;
1880 	data.bis = qos->bcast.bis;
1881 	data.count = 0;
1882 
1883 	/* Create a BIS for each bound connection */
1884 	hci_conn_hash_list_state(hdev, bis_list, BIS_LINK,
1885 				 BT_BOUND, &data);
1886 
1887 	cp.handle = qos->bcast.big;
1888 	cp.adv_handle = qos->bcast.bis;
1889 	cp.num_bis  = data.count;
1890 	hci_cpu_to_le24(qos->bcast.out.interval, cp.bis.sdu_interval);
1891 	cp.bis.sdu = cpu_to_le16(qos->bcast.out.sdu);
1892 	cp.bis.latency =  cpu_to_le16(qos->bcast.out.latency);
1893 	cp.bis.rtn  = qos->bcast.out.rtn;
1894 	cp.bis.phy  = qos->bcast.out.phys;
1895 	cp.bis.packing = qos->bcast.packing;
1896 	cp.bis.framing = qos->bcast.framing;
1897 	cp.bis.encryption = qos->bcast.encryption;
1898 	memcpy(cp.bis.bcode, qos->bcast.bcode, sizeof(cp.bis.bcode));
1899 
1900 	return hci_send_cmd(hdev, HCI_OP_LE_CREATE_BIG, sizeof(cp), &cp);
1901 }
1902 
1903 static int set_cig_params_sync(struct hci_dev *hdev, void *data)
1904 {
1905 	DEFINE_FLEX(struct hci_cp_le_set_cig_params, pdu, cis, num_cis, 0x1f);
1906 	u8 cig_id = PTR_UINT(data);
1907 	struct hci_conn *conn;
1908 	struct bt_iso_qos *qos;
1909 	u8 aux_num_cis = 0;
1910 	u8 cis_id;
1911 
1912 	hci_dev_lock(hdev);
1913 
1914 	conn = hci_conn_hash_lookup_cig(hdev, cig_id);
1915 	if (!conn) {
1916 		hci_dev_unlock(hdev);
1917 		return 0;
1918 	}
1919 
1920 	qos = &conn->iso_qos;
1921 	pdu->cig_id = cig_id;
1922 	hci_cpu_to_le24(qos->ucast.out.interval, pdu->c_interval);
1923 	hci_cpu_to_le24(qos->ucast.in.interval, pdu->p_interval);
1924 	pdu->sca = qos->ucast.sca;
1925 	pdu->packing = qos->ucast.packing;
1926 	pdu->framing = qos->ucast.framing;
1927 	pdu->c_latency = cpu_to_le16(qos->ucast.out.latency);
1928 	pdu->p_latency = cpu_to_le16(qos->ucast.in.latency);
1929 
1930 	/* Reprogram all CIS(s) with the same CIG, valid range are:
1931 	 * num_cis: 0x00 to 0x1F
1932 	 * cis_id: 0x00 to 0xEF
1933 	 */
1934 	for (cis_id = 0x00; cis_id < 0xf0 &&
1935 	     aux_num_cis < pdu->num_cis; cis_id++) {
1936 		struct hci_cis_params *cis;
1937 
1938 		conn = hci_conn_hash_lookup_cis(hdev, NULL, 0, cig_id, cis_id);
1939 		if (!conn)
1940 			continue;
1941 
1942 		qos = &conn->iso_qos;
1943 
1944 		cis = &pdu->cis[aux_num_cis++];
1945 		cis->cis_id = cis_id;
1946 		cis->c_sdu  = cpu_to_le16(conn->iso_qos.ucast.out.sdu);
1947 		cis->p_sdu  = cpu_to_le16(conn->iso_qos.ucast.in.sdu);
1948 		cis->c_phys = qos->ucast.out.phys ? qos->ucast.out.phys :
1949 			      qos->ucast.in.phys;
1950 		cis->p_phys = qos->ucast.in.phys ? qos->ucast.in.phys :
1951 			      qos->ucast.out.phys;
1952 		cis->c_rtn  = qos->ucast.out.rtn;
1953 		cis->p_rtn  = qos->ucast.in.rtn;
1954 	}
1955 	pdu->num_cis = aux_num_cis;
1956 
1957 	hci_dev_unlock(hdev);
1958 
1959 	if (!pdu->num_cis)
1960 		return 0;
1961 
1962 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_CIG_PARAMS,
1963 				     struct_size(pdu, cis, pdu->num_cis),
1964 				     pdu, HCI_CMD_TIMEOUT);
1965 }
1966 
1967 static bool hci_le_set_cig_params(struct hci_conn *conn, struct bt_iso_qos *qos)
1968 {
1969 	struct hci_dev *hdev = conn->hdev;
1970 	struct iso_list_data data;
1971 
1972 	memset(&data, 0, sizeof(data));
1973 
1974 	/* Allocate first still reconfigurable CIG if not set */
1975 	if (qos->ucast.cig == BT_ISO_QOS_CIG_UNSET) {
1976 		for (data.cig = 0x00; data.cig < 0xf0; data.cig++) {
1977 			data.count = 0;
1978 
1979 			hci_conn_hash_list_state(hdev, find_cis, CIS_LINK,
1980 						 BT_CONNECT, &data);
1981 			if (data.count)
1982 				continue;
1983 
1984 			hci_conn_hash_list_state(hdev, find_cis, CIS_LINK,
1985 						 BT_CONNECTED, &data);
1986 			if (!data.count)
1987 				break;
1988 		}
1989 
1990 		if (data.cig == 0xf0)
1991 			return false;
1992 
1993 		/* Update CIG */
1994 		qos->ucast.cig = data.cig;
1995 	}
1996 
1997 	if (qos->ucast.cis != BT_ISO_QOS_CIS_UNSET) {
1998 		if (hci_conn_hash_lookup_cis(hdev, NULL, 0, qos->ucast.cig,
1999 					     qos->ucast.cis))
2000 			return false;
2001 		goto done;
2002 	}
2003 
2004 	/* Allocate first available CIS if not set */
2005 	for (data.cig = qos->ucast.cig, data.cis = 0x00; data.cis < 0xf0;
2006 	     data.cis++) {
2007 		if (!hci_conn_hash_lookup_cis(hdev, NULL, 0, data.cig,
2008 					      data.cis)) {
2009 			/* Update CIS */
2010 			qos->ucast.cis = data.cis;
2011 			break;
2012 		}
2013 	}
2014 
2015 	if (qos->ucast.cis == BT_ISO_QOS_CIS_UNSET)
2016 		return false;
2017 
2018 done:
2019 	conn->iso_qos = *qos;
2020 
2021 	if (hci_cmd_sync_queue(hdev, set_cig_params_sync,
2022 			       UINT_PTR(qos->ucast.cig), NULL) < 0)
2023 		return false;
2024 
2025 	return true;
2026 }
2027 
2028 struct hci_conn *hci_bind_cis(struct hci_dev *hdev, bdaddr_t *dst,
2029 			      __u8 dst_type, struct bt_iso_qos *qos,
2030 			      u16 timeout)
2031 {
2032 	struct hci_conn *cis;
2033 
2034 	cis = hci_conn_hash_lookup_cis(hdev, dst, dst_type, qos->ucast.cig,
2035 				       qos->ucast.cis);
2036 	if (!cis) {
2037 		cis = hci_conn_add_unset(hdev, CIS_LINK, dst, dst_type,
2038 					 HCI_ROLE_MASTER);
2039 		if (IS_ERR(cis))
2040 			return cis;
2041 		cis->cleanup = cis_cleanup;
2042 		cis->dst_type = dst_type;
2043 		cis->iso_qos.ucast.cig = BT_ISO_QOS_CIG_UNSET;
2044 		cis->iso_qos.ucast.cis = BT_ISO_QOS_CIS_UNSET;
2045 		cis->conn_timeout = timeout;
2046 	}
2047 
2048 	if (cis->state == BT_CONNECTED)
2049 		return cis;
2050 
2051 	/* Check if CIS has been set and the settings matches */
2052 	if (cis->state == BT_BOUND &&
2053 	    !memcmp(&cis->iso_qos, qos, sizeof(*qos)))
2054 		return cis;
2055 
2056 	/* Update LINK PHYs according to QoS preference */
2057 	cis->le_tx_phy = qos->ucast.out.phys;
2058 	cis->le_rx_phy = qos->ucast.in.phys;
2059 
2060 	/* If output interval is not set use the input interval as it cannot be
2061 	 * 0x000000.
2062 	 */
2063 	if (!qos->ucast.out.interval)
2064 		qos->ucast.out.interval = qos->ucast.in.interval;
2065 
2066 	/* If input interval is not set use the output interval as it cannot be
2067 	 * 0x000000.
2068 	 */
2069 	if (!qos->ucast.in.interval)
2070 		qos->ucast.in.interval = qos->ucast.out.interval;
2071 
2072 	/* If output latency is not set use the input latency as it cannot be
2073 	 * 0x0000.
2074 	 */
2075 	if (!qos->ucast.out.latency)
2076 		qos->ucast.out.latency = qos->ucast.in.latency;
2077 
2078 	/* If input latency is not set use the output latency as it cannot be
2079 	 * 0x0000.
2080 	 */
2081 	if (!qos->ucast.in.latency)
2082 		qos->ucast.in.latency = qos->ucast.out.latency;
2083 
2084 	if (!hci_le_set_cig_params(cis, qos)) {
2085 		hci_conn_drop(cis);
2086 		return ERR_PTR(-EINVAL);
2087 	}
2088 
2089 	hci_conn_hold(cis);
2090 	cis->state = BT_BOUND;
2091 
2092 	return cis;
2093 }
2094 
2095 bool hci_iso_setup_path(struct hci_conn *conn)
2096 {
2097 	struct hci_dev *hdev = conn->hdev;
2098 	struct hci_cp_le_setup_iso_path cmd;
2099 
2100 	memset(&cmd, 0, sizeof(cmd));
2101 
2102 	if (conn->iso_qos.ucast.out.sdu) {
2103 		cmd.handle = cpu_to_le16(conn->handle);
2104 		cmd.direction = 0x00; /* Input (Host to Controller) */
2105 		cmd.path = 0x00; /* HCI path if enabled */
2106 		cmd.codec = 0x03; /* Transparent Data */
2107 
2108 		if (hci_send_cmd(hdev, HCI_OP_LE_SETUP_ISO_PATH, sizeof(cmd),
2109 				 &cmd) < 0)
2110 			return false;
2111 	}
2112 
2113 	if (conn->iso_qos.ucast.in.sdu) {
2114 		cmd.handle = cpu_to_le16(conn->handle);
2115 		cmd.direction = 0x01; /* Output (Controller to Host) */
2116 		cmd.path = 0x00; /* HCI path if enabled */
2117 		cmd.codec = 0x03; /* Transparent Data */
2118 
2119 		if (hci_send_cmd(hdev, HCI_OP_LE_SETUP_ISO_PATH, sizeof(cmd),
2120 				 &cmd) < 0)
2121 			return false;
2122 	}
2123 
2124 	return true;
2125 }
2126 
2127 int hci_conn_check_create_cis(struct hci_conn *conn)
2128 {
2129 	if (conn->type != CIS_LINK)
2130 		return -EINVAL;
2131 
2132 	if (!conn->parent || conn->parent->state != BT_CONNECTED ||
2133 	    conn->state != BT_CONNECT || HCI_CONN_HANDLE_UNSET(conn->handle))
2134 		return 1;
2135 
2136 	return 0;
2137 }
2138 
2139 static int hci_create_cis_sync(struct hci_dev *hdev, void *data)
2140 {
2141 	return hci_le_create_cis_sync(hdev);
2142 }
2143 
2144 int hci_le_create_cis_pending(struct hci_dev *hdev)
2145 {
2146 	struct hci_conn *conn;
2147 	bool pending = false;
2148 
2149 	rcu_read_lock();
2150 
2151 	list_for_each_entry_rcu(conn, &hdev->conn_hash.list, list) {
2152 		if (test_bit(HCI_CONN_CREATE_CIS, &conn->flags)) {
2153 			rcu_read_unlock();
2154 			return -EBUSY;
2155 		}
2156 
2157 		if (!hci_conn_check_create_cis(conn))
2158 			pending = true;
2159 	}
2160 
2161 	rcu_read_unlock();
2162 
2163 	if (!pending)
2164 		return 0;
2165 
2166 	/* Queue Create CIS */
2167 	return hci_cmd_sync_queue(hdev, hci_create_cis_sync, NULL, NULL);
2168 }
2169 
2170 static void hci_iso_qos_setup(struct hci_dev *hdev, struct hci_conn *conn,
2171 			      struct bt_iso_io_qos *qos, __u8 phys)
2172 {
2173 	/* Only set MTU if PHY is enabled */
2174 	if (!qos->sdu && qos->phys)
2175 		qos->sdu = conn->mtu;
2176 
2177 	/* Use the same PHY as ACL if set to any */
2178 	if (qos->phys == BT_ISO_PHY_ANY)
2179 		qos->phys = phys;
2180 
2181 	/* Use LE ACL connection interval if not set */
2182 	if (!qos->interval)
2183 		/* ACL interval unit in 1.25 ms to us */
2184 		qos->interval = conn->le_conn_interval * 1250;
2185 
2186 	/* Use LE ACL connection latency if not set */
2187 	if (!qos->latency)
2188 		qos->latency = conn->le_conn_latency;
2189 }
2190 
2191 static int create_big_sync(struct hci_dev *hdev, void *data)
2192 {
2193 	struct hci_conn *conn = data;
2194 	struct bt_iso_qos *qos = &conn->iso_qos;
2195 	u16 interval, sync_interval = 0;
2196 	u32 flags = 0;
2197 	int err;
2198 
2199 	if (!hci_conn_valid(hdev, conn))
2200 		return -ECANCELED;
2201 
2202 	if (qos->bcast.out.phys == BIT(1))
2203 		flags |= MGMT_ADV_FLAG_SEC_2M;
2204 
2205 	/* Align intervals */
2206 	interval = (qos->bcast.out.interval / 1250) * qos->bcast.sync_factor;
2207 
2208 	if (qos->bcast.bis)
2209 		sync_interval = interval * 4;
2210 
2211 	err = hci_start_per_adv_sync(hdev, qos->bcast.bis, conn->sid,
2212 				     conn->le_per_adv_data_len,
2213 				     conn->le_per_adv_data, flags, interval,
2214 				     interval, sync_interval);
2215 	if (err)
2216 		return err;
2217 
2218 	return hci_le_create_big(conn, &conn->iso_qos);
2219 }
2220 
2221 struct hci_conn *hci_pa_create_sync(struct hci_dev *hdev, bdaddr_t *dst,
2222 				    __u8 dst_type, __u8 sid,
2223 				    struct bt_iso_qos *qos)
2224 {
2225 	struct hci_conn *conn;
2226 
2227 	bt_dev_dbg(hdev, "dst %pMR type %d sid %d", dst, dst_type, sid);
2228 
2229 	conn = hci_conn_add_unset(hdev, PA_LINK, dst, dst_type, HCI_ROLE_SLAVE);
2230 	if (IS_ERR(conn))
2231 		return conn;
2232 
2233 	conn->iso_qos = *qos;
2234 	conn->sid = sid;
2235 	conn->state = BT_LISTEN;
2236 	conn->conn_timeout = msecs_to_jiffies(qos->bcast.sync_timeout * 10);
2237 
2238 	hci_conn_hold(conn);
2239 
2240 	hci_connect_pa_sync(hdev, conn);
2241 
2242 	return conn;
2243 }
2244 
2245 int hci_conn_big_create_sync(struct hci_dev *hdev, struct hci_conn *hcon,
2246 			     struct bt_iso_qos *qos, __u16 sync_handle,
2247 			     __u8 num_bis, __u8 bis[])
2248 {
2249 	int err;
2250 
2251 	if (num_bis < 0x01 || num_bis > ISO_MAX_NUM_BIS)
2252 		return -EINVAL;
2253 
2254 	err = qos_set_big(hdev, qos);
2255 	if (err)
2256 		return err;
2257 
2258 	if (hcon) {
2259 		/* Update hcon QoS */
2260 		hcon->iso_qos = *qos;
2261 
2262 		hcon->num_bis = num_bis;
2263 		memcpy(hcon->bis, bis, num_bis);
2264 		hcon->conn_timeout = msecs_to_jiffies(qos->bcast.timeout * 10);
2265 	}
2266 
2267 	return hci_connect_big_sync(hdev, hcon);
2268 }
2269 
2270 static void create_big_complete(struct hci_dev *hdev, void *data, int err)
2271 {
2272 	struct hci_conn *conn = data;
2273 
2274 	bt_dev_dbg(hdev, "conn %p", conn);
2275 
2276 	if (err == -ECANCELED)
2277 		goto done;
2278 
2279 	hci_dev_lock(hdev);
2280 
2281 	if (!hci_conn_valid(hdev, conn))
2282 		goto unlock;
2283 
2284 	if (err) {
2285 		bt_dev_err(hdev, "Unable to create BIG: %d", err);
2286 		hci_connect_cfm(conn, err);
2287 		hci_conn_del(conn);
2288 	}
2289 
2290 unlock:
2291 	hci_dev_unlock(hdev);
2292 done:
2293 	hci_conn_put(conn);
2294 }
2295 
2296 struct hci_conn *hci_bind_bis(struct hci_dev *hdev, bdaddr_t *dst, __u8 sid,
2297 			      struct bt_iso_qos *qos,
2298 			      __u8 base_len, __u8 *base, u16 timeout)
2299 {
2300 	struct hci_conn *conn;
2301 	struct hci_conn *parent;
2302 	__u8 eir[HCI_MAX_PER_AD_LENGTH];
2303 	struct hci_link *link;
2304 
2305 	/* Look for any BIS that is open for rebinding */
2306 	conn = hci_conn_hash_lookup_big_state(hdev, qos->bcast.big, BT_OPEN,
2307 					      HCI_ROLE_MASTER);
2308 	if (conn) {
2309 		memcpy(qos, &conn->iso_qos, sizeof(*qos));
2310 		conn->state = BT_CONNECTED;
2311 		return conn;
2312 	}
2313 
2314 	if (base_len && base)
2315 		base_len = eir_append_service_data(eir, 0,  0x1851,
2316 						   base, base_len);
2317 
2318 	/* We need hci_conn object using the BDADDR_ANY as dst */
2319 	conn = hci_add_bis(hdev, dst, sid, qos, base_len, eir, timeout);
2320 	if (IS_ERR(conn))
2321 		return conn;
2322 
2323 	/* Update LINK PHYs according to QoS preference */
2324 	conn->le_tx_def_phys = qos->bcast.out.phys;
2325 
2326 	/* Add Basic Announcement into Peridic Adv Data if BASE is set */
2327 	if (base_len && base) {
2328 		memcpy(conn->le_per_adv_data,  eir, sizeof(eir));
2329 		conn->le_per_adv_data_len = base_len;
2330 	}
2331 
2332 	hci_iso_qos_setup(hdev, conn, &qos->bcast.out,
2333 			  conn->le_tx_def_phys ? conn->le_tx_def_phys :
2334 			  hdev->le_tx_def_phys);
2335 
2336 	conn->iso_qos = *qos;
2337 	conn->state = BT_BOUND;
2338 
2339 	/* Link BISes together */
2340 	parent = hci_conn_hash_lookup_big(hdev,
2341 					  conn->iso_qos.bcast.big);
2342 	if (parent && parent != conn) {
2343 		link = hci_conn_link(parent, conn);
2344 		hci_conn_drop(conn);
2345 		if (!link)
2346 			return ERR_PTR(-ENOLINK);
2347 	}
2348 
2349 	return conn;
2350 }
2351 
2352 int hci_past_bis(struct hci_conn *conn, bdaddr_t *dst, __u8 dst_type)
2353 {
2354 	struct hci_conn *le;
2355 
2356 	/* Lookup existing LE connection to rebind to */
2357 	le = hci_conn_hash_lookup_le(conn->hdev, dst, dst_type);
2358 	if (!le)
2359 		return -EINVAL;
2360 
2361 	return hci_past_sync(conn, le);
2362 }
2363 
2364 static void bis_mark_per_adv(struct hci_conn *conn, void *data)
2365 {
2366 	struct iso_list_data *d = data;
2367 
2368 	/* Skip if not broadcast/ANY address */
2369 	if (bacmp(&conn->dst, BDADDR_ANY))
2370 		return;
2371 
2372 	if (d->big != conn->iso_qos.bcast.big ||
2373 	    d->bis == BT_ISO_QOS_BIS_UNSET ||
2374 	    d->bis != conn->iso_qos.bcast.bis)
2375 		return;
2376 
2377 	set_bit(HCI_CONN_PER_ADV, &conn->flags);
2378 }
2379 
2380 struct hci_conn *hci_connect_bis(struct hci_dev *hdev, bdaddr_t *dst,
2381 				 __u8 dst_type, __u8 sid,
2382 				 struct bt_iso_qos *qos,
2383 				 __u8 base_len, __u8 *base, u16 timeout)
2384 {
2385 	struct hci_conn *conn;
2386 	int err;
2387 	struct iso_list_data data;
2388 
2389 	conn = hci_bind_bis(hdev, dst, sid, qos, base_len, base, timeout);
2390 	if (IS_ERR(conn))
2391 		return conn;
2392 
2393 	if (conn->state == BT_CONNECTED)
2394 		return conn;
2395 
2396 	/* Check if SID needs to be allocated then search for the first
2397 	 * available.
2398 	 */
2399 	if (conn->sid == HCI_SID_INVALID) {
2400 		u8 sid;
2401 
2402 		for (sid = 0; sid <= 0x0f; sid++) {
2403 			if (!hci_find_adv_sid(hdev, sid)) {
2404 				conn->sid = sid;
2405 				break;
2406 			}
2407 		}
2408 	}
2409 
2410 	data.big = qos->bcast.big;
2411 	data.bis = qos->bcast.bis;
2412 
2413 	/* Set HCI_CONN_PER_ADV for all bound connections, to mark that
2414 	 * the start periodic advertising and create BIG commands have
2415 	 * been queued
2416 	 */
2417 	hci_conn_hash_list_state(hdev, bis_mark_per_adv, BIS_LINK,
2418 				 BT_BOUND, &data);
2419 
2420 	/* Queue start periodic advertising and create BIG */
2421 	err = hci_cmd_sync_queue(hdev, create_big_sync, hci_conn_get(conn),
2422 				 create_big_complete);
2423 	if (err < 0) {
2424 		hci_conn_drop(conn);
2425 		hci_conn_put(conn);
2426 		return ERR_PTR(err);
2427 	}
2428 
2429 	return conn;
2430 }
2431 
2432 struct hci_conn *hci_connect_cis(struct hci_dev *hdev, bdaddr_t *dst,
2433 				 __u8 dst_type, struct bt_iso_qos *qos,
2434 				 u16 timeout)
2435 {
2436 	struct hci_conn *le;
2437 	struct hci_conn *cis;
2438 	struct hci_link *link;
2439 
2440 	if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
2441 		le = hci_connect_le(hdev, dst, dst_type, false,
2442 				    BT_SECURITY_LOW,
2443 				    HCI_LE_CONN_TIMEOUT,
2444 				    HCI_ROLE_SLAVE, 0, 0);
2445 	else
2446 		le = hci_connect_le_scan(hdev, dst, dst_type,
2447 					 BT_SECURITY_LOW,
2448 					 HCI_LE_CONN_TIMEOUT,
2449 					 CONN_REASON_ISO_CONNECT);
2450 	if (IS_ERR(le))
2451 		return le;
2452 
2453 	hci_iso_qos_setup(hdev, le, &qos->ucast.out,
2454 			  le->le_tx_def_phys ? le->le_tx_def_phys :
2455 			  hdev->le_tx_def_phys);
2456 	hci_iso_qos_setup(hdev, le, &qos->ucast.in,
2457 			  le->le_rx_def_phys ? le->le_rx_def_phys :
2458 			  hdev->le_rx_def_phys);
2459 
2460 	cis = hci_bind_cis(hdev, dst, dst_type, qos, timeout);
2461 	if (IS_ERR(cis)) {
2462 		hci_conn_drop(le);
2463 		return cis;
2464 	}
2465 
2466 	link = hci_conn_link(le, cis);
2467 	hci_conn_drop(cis);
2468 	if (!link) {
2469 		hci_conn_drop(le);
2470 		return ERR_PTR(-ENOLINK);
2471 	}
2472 
2473 	cis->state = BT_CONNECT;
2474 
2475 	hci_le_create_cis_pending(hdev);
2476 
2477 	return cis;
2478 }
2479 
2480 /* Check link security requirement */
2481 int hci_conn_check_link_mode(struct hci_conn *conn)
2482 {
2483 	BT_DBG("hcon %p", conn);
2484 
2485 	/* In Secure Connections Only mode, it is required that Secure
2486 	 * Connections is used and the link is encrypted with AES-CCM
2487 	 * using a P-256 authenticated combination key.
2488 	 */
2489 	if (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) {
2490 		if (!hci_conn_sc_enabled(conn) ||
2491 		    !test_bit(HCI_CONN_AES_CCM, &conn->flags) ||
2492 		    conn->key_type != HCI_LK_AUTH_COMBINATION_P256)
2493 			return 0;
2494 	}
2495 
2496 	 /* AES encryption is required for Level 4:
2497 	  *
2498 	  * BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 3, Part C
2499 	  * page 1319:
2500 	  *
2501 	  * 128-bit equivalent strength for link and encryption keys
2502 	  * required using FIPS approved algorithms (E0 not allowed,
2503 	  * SAFER+ not allowed, and P-192 not allowed; encryption key
2504 	  * not shortened)
2505 	  */
2506 	if (conn->sec_level == BT_SECURITY_FIPS &&
2507 	    !test_bit(HCI_CONN_AES_CCM, &conn->flags)) {
2508 		bt_dev_err(conn->hdev,
2509 			   "Invalid security: Missing AES-CCM usage");
2510 		return 0;
2511 	}
2512 
2513 	if (hci_conn_ssp_enabled(conn) &&
2514 	    !test_bit(HCI_CONN_ENCRYPT, &conn->flags))
2515 		return 0;
2516 
2517 	return 1;
2518 }
2519 
2520 /* Authenticate remote device */
2521 static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
2522 {
2523 	BT_DBG("hcon %p", conn);
2524 
2525 	if (conn->pending_sec_level > sec_level)
2526 		sec_level = conn->pending_sec_level;
2527 
2528 	if (sec_level > conn->sec_level)
2529 		conn->pending_sec_level = sec_level;
2530 	else if (test_bit(HCI_CONN_AUTH, &conn->flags))
2531 		return 1;
2532 
2533 	/* Make sure we preserve an existing MITM requirement*/
2534 	auth_type |= (conn->auth_type & 0x01);
2535 
2536 	conn->auth_type = auth_type;
2537 
2538 	if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->flags)) {
2539 		struct hci_cp_auth_requested cp;
2540 
2541 		cp.handle = cpu_to_le16(conn->handle);
2542 		hci_send_cmd(conn->hdev, HCI_OP_AUTH_REQUESTED,
2543 			     sizeof(cp), &cp);
2544 
2545 		/* Set the ENCRYPT_PEND to trigger encryption after
2546 		 * authentication.
2547 		 */
2548 		if (!test_bit(HCI_CONN_ENCRYPT, &conn->flags))
2549 			set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags);
2550 	}
2551 
2552 	return 0;
2553 }
2554 
2555 /* Encrypt the link */
2556 static void hci_conn_encrypt(struct hci_conn *conn)
2557 {
2558 	BT_DBG("hcon %p", conn);
2559 
2560 	if (!test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) {
2561 		struct hci_cp_set_conn_encrypt cp;
2562 		cp.handle  = cpu_to_le16(conn->handle);
2563 		cp.encrypt = 0x01;
2564 		hci_send_cmd(conn->hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(cp),
2565 			     &cp);
2566 	}
2567 }
2568 
2569 /* Enable security */
2570 int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type,
2571 		      bool initiator)
2572 {
2573 	BT_DBG("hcon %p", conn);
2574 
2575 	if (conn->type == LE_LINK)
2576 		return smp_conn_security(conn, sec_level);
2577 
2578 	/* For sdp we don't need the link key. */
2579 	if (sec_level == BT_SECURITY_SDP)
2580 		return 1;
2581 
2582 	/* For non 2.1 devices and low security level we don't need the link
2583 	   key. */
2584 	if (sec_level == BT_SECURITY_LOW && !hci_conn_ssp_enabled(conn))
2585 		return 1;
2586 
2587 	/* For other security levels we need the link key. */
2588 	if (!test_bit(HCI_CONN_AUTH, &conn->flags))
2589 		goto auth;
2590 
2591 	switch (conn->key_type) {
2592 	case HCI_LK_AUTH_COMBINATION_P256:
2593 		/* An authenticated FIPS approved combination key has
2594 		 * sufficient security for security level 4 or lower.
2595 		 */
2596 		if (sec_level <= BT_SECURITY_FIPS)
2597 			goto encrypt;
2598 		break;
2599 	case HCI_LK_AUTH_COMBINATION_P192:
2600 		/* An authenticated combination key has sufficient security for
2601 		 * security level 3 or lower.
2602 		 */
2603 		if (sec_level <= BT_SECURITY_HIGH)
2604 			goto encrypt;
2605 		break;
2606 	case HCI_LK_UNAUTH_COMBINATION_P192:
2607 	case HCI_LK_UNAUTH_COMBINATION_P256:
2608 		/* An unauthenticated combination key has sufficient security
2609 		 * for security level 2 or lower.
2610 		 */
2611 		if (sec_level <= BT_SECURITY_MEDIUM)
2612 			goto encrypt;
2613 		break;
2614 	case HCI_LK_COMBINATION:
2615 		/* A combination key has always sufficient security for the
2616 		 * security levels 2 or lower. High security level requires the
2617 		 * combination key is generated using maximum PIN code length
2618 		 * (16). For pre 2.1 units.
2619 		 */
2620 		if (sec_level <= BT_SECURITY_MEDIUM || conn->pin_length == 16)
2621 			goto encrypt;
2622 		break;
2623 	default:
2624 		break;
2625 	}
2626 
2627 auth:
2628 	if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags))
2629 		return 0;
2630 
2631 	if (initiator)
2632 		set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags);
2633 
2634 	if (!hci_conn_auth(conn, sec_level, auth_type))
2635 		return 0;
2636 
2637 encrypt:
2638 	if (test_bit(HCI_CONN_ENCRYPT, &conn->flags)) {
2639 		/* Ensure that the encryption key size has been read,
2640 		 * otherwise stall the upper layer responses.
2641 		 */
2642 		if (!conn->enc_key_size)
2643 			return 0;
2644 
2645 		/* Nothing else needed, all requirements are met */
2646 		return 1;
2647 	}
2648 
2649 	hci_conn_encrypt(conn);
2650 	return 0;
2651 }
2652 EXPORT_SYMBOL(hci_conn_security);
2653 
2654 /* Check secure link requirement */
2655 int hci_conn_check_secure(struct hci_conn *conn, __u8 sec_level)
2656 {
2657 	BT_DBG("hcon %p", conn);
2658 
2659 	/* Accept if non-secure or higher security level is required */
2660 	if (sec_level != BT_SECURITY_HIGH && sec_level != BT_SECURITY_FIPS)
2661 		return 1;
2662 
2663 	/* Accept if secure or higher security level is already present */
2664 	if (conn->sec_level == BT_SECURITY_HIGH ||
2665 	    conn->sec_level == BT_SECURITY_FIPS)
2666 		return 1;
2667 
2668 	/* Reject not secure link */
2669 	return 0;
2670 }
2671 EXPORT_SYMBOL(hci_conn_check_secure);
2672 
2673 /* Switch role */
2674 int hci_conn_switch_role(struct hci_conn *conn, __u8 role)
2675 {
2676 	BT_DBG("hcon %p", conn);
2677 
2678 	if (role == conn->role)
2679 		return 1;
2680 
2681 	if (!test_and_set_bit(HCI_CONN_RSWITCH_PEND, &conn->flags)) {
2682 		struct hci_cp_switch_role cp;
2683 		bacpy(&cp.bdaddr, &conn->dst);
2684 		cp.role = role;
2685 		hci_send_cmd(conn->hdev, HCI_OP_SWITCH_ROLE, sizeof(cp), &cp);
2686 	}
2687 
2688 	return 0;
2689 }
2690 EXPORT_SYMBOL(hci_conn_switch_role);
2691 
2692 /* Enter active mode */
2693 void hci_conn_enter_active_mode(struct hci_conn *conn, __u8 force_active)
2694 {
2695 	struct hci_dev *hdev = conn->hdev;
2696 
2697 	BT_DBG("hcon %p mode %d", conn, conn->mode);
2698 
2699 	if (conn->mode != HCI_CM_SNIFF)
2700 		goto timer;
2701 
2702 	if (!test_bit(HCI_CONN_POWER_SAVE, &conn->flags) && !force_active)
2703 		goto timer;
2704 
2705 	if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) {
2706 		struct hci_cp_exit_sniff_mode cp;
2707 		cp.handle = cpu_to_le16(conn->handle);
2708 		hci_send_cmd(hdev, HCI_OP_EXIT_SNIFF_MODE, sizeof(cp), &cp);
2709 	}
2710 
2711 timer:
2712 	if (hdev->idle_timeout > 0)
2713 		mod_delayed_work(hdev->workqueue, &conn->idle_work,
2714 				 msecs_to_jiffies(hdev->idle_timeout));
2715 }
2716 
2717 /* Drop all connection on the device */
2718 void hci_conn_hash_flush(struct hci_dev *hdev)
2719 {
2720 	struct list_head *head = &hdev->conn_hash.list;
2721 	struct hci_conn *conn;
2722 
2723 	BT_DBG("hdev %s", hdev->name);
2724 
2725 	/* We should not traverse the list here, because hci_conn_del
2726 	 * can remove extra links, which may cause the list traversal
2727 	 * to hit items that have already been released.
2728 	 */
2729 	while ((conn = list_first_entry_or_null(head,
2730 						struct hci_conn,
2731 						list)) != NULL) {
2732 		conn->state = BT_CLOSED;
2733 		hci_disconn_cfm(conn, HCI_ERROR_LOCAL_HOST_TERM);
2734 		hci_conn_del(conn);
2735 	}
2736 }
2737 
2738 static u32 get_link_mode(struct hci_conn *conn)
2739 {
2740 	u32 link_mode = 0;
2741 
2742 	if (conn->role == HCI_ROLE_MASTER)
2743 		link_mode |= HCI_LM_MASTER;
2744 
2745 	if (test_bit(HCI_CONN_ENCRYPT, &conn->flags))
2746 		link_mode |= HCI_LM_ENCRYPT;
2747 
2748 	if (test_bit(HCI_CONN_AUTH, &conn->flags))
2749 		link_mode |= HCI_LM_AUTH;
2750 
2751 	if (test_bit(HCI_CONN_SECURE, &conn->flags))
2752 		link_mode |= HCI_LM_SECURE;
2753 
2754 	if (test_bit(HCI_CONN_FIPS, &conn->flags))
2755 		link_mode |= HCI_LM_FIPS;
2756 
2757 	return link_mode;
2758 }
2759 
2760 int hci_get_conn_list(void __user *arg)
2761 {
2762 	struct hci_conn *c;
2763 	struct hci_conn_list_req req, *cl;
2764 	struct hci_conn_info *ci;
2765 	struct hci_dev *hdev;
2766 	int n = 0, size, err;
2767 
2768 	if (copy_from_user(&req, arg, sizeof(req)))
2769 		return -EFAULT;
2770 
2771 	if (!req.conn_num || req.conn_num > (PAGE_SIZE * 2) / sizeof(*ci))
2772 		return -EINVAL;
2773 
2774 	size = sizeof(req) + req.conn_num * sizeof(*ci);
2775 
2776 	cl = kmalloc(size, GFP_KERNEL);
2777 	if (!cl)
2778 		return -ENOMEM;
2779 
2780 	hdev = hci_dev_get(req.dev_id);
2781 	if (!hdev) {
2782 		kfree(cl);
2783 		return -ENODEV;
2784 	}
2785 
2786 	ci = cl->conn_info;
2787 
2788 	hci_dev_lock(hdev);
2789 	list_for_each_entry(c, &hdev->conn_hash.list, list) {
2790 		bacpy(&(ci + n)->bdaddr, &c->dst);
2791 		(ci + n)->handle = c->handle;
2792 		(ci + n)->type  = c->type;
2793 		(ci + n)->out   = c->out;
2794 		(ci + n)->state = c->state;
2795 		(ci + n)->link_mode = get_link_mode(c);
2796 		if (++n >= req.conn_num)
2797 			break;
2798 	}
2799 	hci_dev_unlock(hdev);
2800 
2801 	cl->dev_id = hdev->id;
2802 	cl->conn_num = n;
2803 	size = sizeof(req) + n * sizeof(*ci);
2804 
2805 	hci_dev_put(hdev);
2806 
2807 	err = copy_to_user(arg, cl, size);
2808 	kfree(cl);
2809 
2810 	return err ? -EFAULT : 0;
2811 }
2812 
2813 int hci_get_conn_info(struct hci_dev *hdev, void __user *arg)
2814 {
2815 	struct hci_conn_info_req req;
2816 	struct hci_conn_info ci;
2817 	struct hci_conn *conn;
2818 	char __user *ptr = arg + sizeof(req);
2819 
2820 	if (copy_from_user(&req, arg, sizeof(req)))
2821 		return -EFAULT;
2822 
2823 	hci_dev_lock(hdev);
2824 	conn = hci_conn_hash_lookup_ba(hdev, req.type, &req.bdaddr);
2825 	if (conn) {
2826 		bacpy(&ci.bdaddr, &conn->dst);
2827 		ci.handle = conn->handle;
2828 		ci.type  = conn->type;
2829 		ci.out   = conn->out;
2830 		ci.state = conn->state;
2831 		ci.link_mode = get_link_mode(conn);
2832 	}
2833 	hci_dev_unlock(hdev);
2834 
2835 	if (!conn)
2836 		return -ENOENT;
2837 
2838 	return copy_to_user(ptr, &ci, sizeof(ci)) ? -EFAULT : 0;
2839 }
2840 
2841 int hci_get_auth_info(struct hci_dev *hdev, void __user *arg)
2842 {
2843 	struct hci_auth_info_req req;
2844 	struct hci_conn *conn;
2845 
2846 	if (copy_from_user(&req, arg, sizeof(req)))
2847 		return -EFAULT;
2848 
2849 	hci_dev_lock(hdev);
2850 	conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &req.bdaddr);
2851 	if (conn)
2852 		req.type = conn->auth_type;
2853 	hci_dev_unlock(hdev);
2854 
2855 	if (!conn)
2856 		return -ENOENT;
2857 
2858 	return copy_to_user(arg, &req, sizeof(req)) ? -EFAULT : 0;
2859 }
2860 
2861 struct hci_chan *hci_chan_create(struct hci_conn *conn)
2862 {
2863 	struct hci_dev *hdev = conn->hdev;
2864 	struct hci_chan *chan;
2865 
2866 	BT_DBG("%s hcon %p", hdev->name, conn);
2867 
2868 	if (test_bit(HCI_CONN_DROP, &conn->flags)) {
2869 		BT_DBG("Refusing to create new hci_chan");
2870 		return NULL;
2871 	}
2872 
2873 	chan = kzalloc_obj(*chan);
2874 	if (!chan)
2875 		return NULL;
2876 
2877 	chan->conn = hci_conn_get(conn);
2878 	skb_queue_head_init(&chan->data_q);
2879 	chan->state = BT_CONNECTED;
2880 
2881 	list_add_rcu(&chan->list, &conn->chan_list);
2882 
2883 	return chan;
2884 }
2885 
2886 void hci_chan_del(struct hci_chan *chan)
2887 {
2888 	struct hci_conn *conn = chan->conn;
2889 	struct hci_dev *hdev = conn->hdev;
2890 
2891 	BT_DBG("%s hcon %p chan %p", hdev->name, conn, chan);
2892 
2893 	list_del_rcu(&chan->list);
2894 
2895 	synchronize_rcu();
2896 
2897 	/* Prevent new hci_chan's to be created for this hci_conn */
2898 	set_bit(HCI_CONN_DROP, &conn->flags);
2899 
2900 	hci_conn_put(conn);
2901 
2902 	skb_queue_purge(&chan->data_q);
2903 	kfree(chan);
2904 }
2905 
2906 void hci_chan_list_flush(struct hci_conn *conn)
2907 {
2908 	struct hci_chan *chan, *n;
2909 
2910 	BT_DBG("hcon %p", conn);
2911 
2912 	list_for_each_entry_safe(chan, n, &conn->chan_list, list)
2913 		hci_chan_del(chan);
2914 }
2915 
2916 static struct hci_chan *__hci_chan_lookup_handle(struct hci_conn *hcon,
2917 						 __u16 handle)
2918 {
2919 	struct hci_chan *hchan;
2920 
2921 	list_for_each_entry(hchan, &hcon->chan_list, list) {
2922 		if (hchan->handle == handle)
2923 			return hchan;
2924 	}
2925 
2926 	return NULL;
2927 }
2928 
2929 struct hci_chan *hci_chan_lookup_handle(struct hci_dev *hdev, __u16 handle)
2930 {
2931 	struct hci_conn_hash *h = &hdev->conn_hash;
2932 	struct hci_conn *hcon;
2933 	struct hci_chan *hchan = NULL;
2934 
2935 	rcu_read_lock();
2936 
2937 	list_for_each_entry_rcu(hcon, &h->list, list) {
2938 		hchan = __hci_chan_lookup_handle(hcon, handle);
2939 		if (hchan)
2940 			break;
2941 	}
2942 
2943 	rcu_read_unlock();
2944 
2945 	return hchan;
2946 }
2947 
2948 u32 hci_conn_get_phy(struct hci_conn *conn)
2949 {
2950 	u32 phys = 0;
2951 
2952 	/* BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 2, Part B page 471:
2953 	 * Table 6.2: Packets defined for synchronous, asynchronous, and
2954 	 * CPB logical transport types.
2955 	 */
2956 	switch (conn->type) {
2957 	case SCO_LINK:
2958 		/* SCO logical transport (1 Mb/s):
2959 		 * HV1, HV2, HV3 and DV.
2960 		 */
2961 		phys |= BT_PHY_BR_1M_1SLOT;
2962 
2963 		break;
2964 
2965 	case ACL_LINK:
2966 		/* ACL logical transport (1 Mb/s) ptt=0:
2967 		 * DH1, DM3, DH3, DM5 and DH5.
2968 		 */
2969 		phys |= BT_PHY_BR_1M_1SLOT;
2970 
2971 		if (conn->pkt_type & (HCI_DM3 | HCI_DH3))
2972 			phys |= BT_PHY_BR_1M_3SLOT;
2973 
2974 		if (conn->pkt_type & (HCI_DM5 | HCI_DH5))
2975 			phys |= BT_PHY_BR_1M_5SLOT;
2976 
2977 		/* ACL logical transport (2 Mb/s) ptt=1:
2978 		 * 2-DH1, 2-DH3 and 2-DH5.
2979 		 */
2980 		if (!(conn->pkt_type & HCI_2DH1))
2981 			phys |= BT_PHY_EDR_2M_1SLOT;
2982 
2983 		if (!(conn->pkt_type & HCI_2DH3))
2984 			phys |= BT_PHY_EDR_2M_3SLOT;
2985 
2986 		if (!(conn->pkt_type & HCI_2DH5))
2987 			phys |= BT_PHY_EDR_2M_5SLOT;
2988 
2989 		/* ACL logical transport (3 Mb/s) ptt=1:
2990 		 * 3-DH1, 3-DH3 and 3-DH5.
2991 		 */
2992 		if (!(conn->pkt_type & HCI_3DH1))
2993 			phys |= BT_PHY_EDR_3M_1SLOT;
2994 
2995 		if (!(conn->pkt_type & HCI_3DH3))
2996 			phys |= BT_PHY_EDR_3M_3SLOT;
2997 
2998 		if (!(conn->pkt_type & HCI_3DH5))
2999 			phys |= BT_PHY_EDR_3M_5SLOT;
3000 
3001 		break;
3002 
3003 	case ESCO_LINK:
3004 		/* eSCO logical transport (1 Mb/s): EV3, EV4 and EV5 */
3005 		phys |= BT_PHY_BR_1M_1SLOT;
3006 
3007 		if (!(conn->pkt_type & (ESCO_EV4 | ESCO_EV5)))
3008 			phys |= BT_PHY_BR_1M_3SLOT;
3009 
3010 		/* eSCO logical transport (2 Mb/s): 2-EV3, 2-EV5 */
3011 		if (!(conn->pkt_type & ESCO_2EV3))
3012 			phys |= BT_PHY_EDR_2M_1SLOT;
3013 
3014 		if (!(conn->pkt_type & ESCO_2EV5))
3015 			phys |= BT_PHY_EDR_2M_3SLOT;
3016 
3017 		/* eSCO logical transport (3 Mb/s): 3-EV3, 3-EV5 */
3018 		if (!(conn->pkt_type & ESCO_3EV3))
3019 			phys |= BT_PHY_EDR_3M_1SLOT;
3020 
3021 		if (!(conn->pkt_type & ESCO_3EV5))
3022 			phys |= BT_PHY_EDR_3M_3SLOT;
3023 
3024 		break;
3025 
3026 	case LE_LINK:
3027 		if (conn->le_tx_def_phys & HCI_LE_SET_PHY_1M)
3028 			phys |= BT_PHY_LE_1M_TX;
3029 
3030 		if (conn->le_rx_def_phys & HCI_LE_SET_PHY_1M)
3031 			phys |= BT_PHY_LE_1M_RX;
3032 
3033 		if (conn->le_tx_def_phys & HCI_LE_SET_PHY_2M)
3034 			phys |= BT_PHY_LE_2M_TX;
3035 
3036 		if (conn->le_rx_def_phys & HCI_LE_SET_PHY_2M)
3037 			phys |= BT_PHY_LE_2M_RX;
3038 
3039 		if (conn->le_tx_def_phys & HCI_LE_SET_PHY_CODED)
3040 			phys |= BT_PHY_LE_CODED_TX;
3041 
3042 		if (conn->le_rx_def_phys & HCI_LE_SET_PHY_CODED)
3043 			phys |= BT_PHY_LE_CODED_RX;
3044 
3045 		break;
3046 	}
3047 
3048 	return phys;
3049 }
3050 
3051 static u16 bt_phy_pkt_type(struct hci_conn *conn, u32 phys)
3052 {
3053 	u16 pkt_type = conn->pkt_type;
3054 
3055 	if (phys & BT_PHY_BR_1M_3SLOT)
3056 		pkt_type |= HCI_DM3 | HCI_DH3;
3057 	else
3058 		pkt_type &= ~(HCI_DM3 | HCI_DH3);
3059 
3060 	if (phys & BT_PHY_BR_1M_5SLOT)
3061 		pkt_type |= HCI_DM5 | HCI_DH5;
3062 	else
3063 		pkt_type &= ~(HCI_DM5 | HCI_DH5);
3064 
3065 	if (phys & BT_PHY_EDR_2M_1SLOT)
3066 		pkt_type &= ~HCI_2DH1;
3067 	else
3068 		pkt_type |= HCI_2DH1;
3069 
3070 	if (phys & BT_PHY_EDR_2M_3SLOT)
3071 		pkt_type &= ~HCI_2DH3;
3072 	else
3073 		pkt_type |= HCI_2DH3;
3074 
3075 	if (phys & BT_PHY_EDR_2M_5SLOT)
3076 		pkt_type &= ~HCI_2DH5;
3077 	else
3078 		pkt_type |= HCI_2DH5;
3079 
3080 	if (phys & BT_PHY_EDR_3M_1SLOT)
3081 		pkt_type &= ~HCI_3DH1;
3082 	else
3083 		pkt_type |= HCI_3DH1;
3084 
3085 	if (phys & BT_PHY_EDR_3M_3SLOT)
3086 		pkt_type &= ~HCI_3DH3;
3087 	else
3088 		pkt_type |= HCI_3DH3;
3089 
3090 	if (phys & BT_PHY_EDR_3M_5SLOT)
3091 		pkt_type &= ~HCI_3DH5;
3092 	else
3093 		pkt_type |= HCI_3DH5;
3094 
3095 	return pkt_type;
3096 }
3097 
3098 static int bt_phy_le_phy(u32 phys, u8 *tx_phys, u8 *rx_phys)
3099 {
3100 	if (!tx_phys || !rx_phys)
3101 		return -EINVAL;
3102 
3103 	*tx_phys = 0;
3104 	*rx_phys = 0;
3105 
3106 	if (phys & BT_PHY_LE_1M_TX)
3107 		*tx_phys |= HCI_LE_SET_PHY_1M;
3108 
3109 	if (phys & BT_PHY_LE_1M_RX)
3110 		*rx_phys |= HCI_LE_SET_PHY_1M;
3111 
3112 	if (phys & BT_PHY_LE_2M_TX)
3113 		*tx_phys |= HCI_LE_SET_PHY_2M;
3114 
3115 	if (phys & BT_PHY_LE_2M_RX)
3116 		*rx_phys |= HCI_LE_SET_PHY_2M;
3117 
3118 	if (phys & BT_PHY_LE_CODED_TX)
3119 		*tx_phys |= HCI_LE_SET_PHY_CODED;
3120 
3121 	if (phys & BT_PHY_LE_CODED_RX)
3122 		*rx_phys |= HCI_LE_SET_PHY_CODED;
3123 
3124 	return 0;
3125 }
3126 
3127 int hci_conn_set_phy(struct hci_conn *conn, u32 phys)
3128 {
3129 	u8 tx_phys, rx_phys;
3130 
3131 	switch (conn->type) {
3132 	case SCO_LINK:
3133 	case ESCO_LINK:
3134 		return -EINVAL;
3135 	case ACL_LINK:
3136 		/* Only allow setting BR/EDR PHYs if link type is ACL */
3137 		if (phys & ~BT_PHY_BREDR_MASK)
3138 			return -EINVAL;
3139 
3140 		return hci_acl_change_pkt_type(conn,
3141 					       bt_phy_pkt_type(conn, phys));
3142 	case LE_LINK:
3143 		/* Only allow setting LE PHYs if link type is LE */
3144 		if (phys & ~BT_PHY_LE_MASK)
3145 			return -EINVAL;
3146 
3147 		if (bt_phy_le_phy(phys, &tx_phys, &rx_phys))
3148 			return -EINVAL;
3149 
3150 		return hci_le_set_phy(conn, tx_phys, rx_phys);
3151 	default:
3152 		return -EINVAL;
3153 	}
3154 }
3155 
3156 static int abort_conn_sync(struct hci_dev *hdev, void *data)
3157 {
3158 	struct hci_conn *conn = data;
3159 
3160 	if (!hci_conn_valid(hdev, conn))
3161 		return -ECANCELED;
3162 
3163 	return hci_abort_conn_sync(hdev, conn, conn->abort_reason);
3164 }
3165 
3166 int hci_abort_conn(struct hci_conn *conn, u8 reason)
3167 {
3168 	struct hci_dev *hdev = conn->hdev;
3169 	int err;
3170 
3171 	/* If abort_reason has already been set it means the connection is
3172 	 * already being aborted so don't attempt to overwrite it.
3173 	 */
3174 	if (conn->abort_reason)
3175 		return 0;
3176 
3177 	bt_dev_dbg(hdev, "handle 0x%2.2x reason 0x%2.2x", conn->handle, reason);
3178 
3179 	conn->abort_reason = reason;
3180 
3181 	/* If the connection is pending check the command opcode since that
3182 	 * might be blocking on hci_cmd_sync_work while waiting its respective
3183 	 * event so we need to hci_cmd_sync_cancel to cancel it.
3184 	 *
3185 	 * hci_connect_le serializes the connection attempts so only one
3186 	 * connection can be in BT_CONNECT at time.
3187 	 */
3188 	if (conn->state == BT_CONNECT && READ_ONCE(hdev->req_status) == HCI_REQ_PEND) {
3189 		switch (hci_skb_event(hdev->sent_cmd)) {
3190 		case HCI_EV_CONN_COMPLETE:
3191 		case HCI_EV_LE_CONN_COMPLETE:
3192 		case HCI_EV_LE_ENHANCED_CONN_COMPLETE:
3193 		case HCI_EVT_LE_CIS_ESTABLISHED:
3194 			hci_cmd_sync_cancel(hdev, ECANCELED);
3195 			break;
3196 		}
3197 	/* Cancel connect attempt if still queued/pending */
3198 	} else if (!hci_cancel_connect_sync(hdev, conn)) {
3199 		return 0;
3200 	}
3201 
3202 	/* Run immediately if on cmd_sync_work since this may be called
3203 	 * as a result to MGMT_OP_DISCONNECT/MGMT_OP_UNPAIR which does
3204 	 * already queue its callback on cmd_sync_work.
3205 	 */
3206 	err = hci_cmd_sync_run_once(hdev, abort_conn_sync, conn, NULL);
3207 	return (err == -EEXIST) ? 0 : err;
3208 }
3209 
3210 void hci_setup_tx_timestamp(struct sk_buff *skb, size_t key_offset,
3211 			    const struct sockcm_cookie *sockc)
3212 {
3213 	struct sock *sk = skb ? skb->sk : NULL;
3214 	int key;
3215 
3216 	/* This shall be called on a single skb of those generated by user
3217 	 * sendmsg(), and only when the sendmsg() does not return error to
3218 	 * user. This is required for keeping the tskey that increments here in
3219 	 * sync with possible sendmsg() counting by user.
3220 	 *
3221 	 * Stream sockets shall set key_offset to sendmsg() length in bytes
3222 	 * and call with the last fragment, others to 1 and first fragment.
3223 	 */
3224 
3225 	if (!skb || !sockc || !sk || !key_offset)
3226 		return;
3227 
3228 	sock_tx_timestamp(sk, sockc, &skb_shinfo(skb)->tx_flags);
3229 
3230 	if (sk->sk_type == SOCK_STREAM)
3231 		key = atomic_add_return(key_offset, &sk->sk_tskey);
3232 
3233 	if (sockc->tsflags & SOF_TIMESTAMPING_OPT_ID &&
3234 	    sockc->tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK) {
3235 		if (sockc->tsflags & SOCKCM_FLAG_TS_OPT_ID) {
3236 			skb_shinfo(skb)->tskey = sockc->ts_opt_id;
3237 		} else {
3238 			if (sk->sk_type != SOCK_STREAM)
3239 				key = atomic_inc_return(&sk->sk_tskey);
3240 			skb_shinfo(skb)->tskey = key - 1;
3241 		}
3242 	}
3243 }
3244 
3245 void hci_conn_tx_queue(struct hci_conn *conn, struct sk_buff *skb)
3246 {
3247 	struct tx_queue *comp = &conn->tx_q;
3248 	bool track = false;
3249 
3250 	/* Emit SND now, ie. just before sending to driver */
3251 	if (skb_shinfo(skb)->tx_flags & SKBTX_SW_TSTAMP)
3252 		__skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SND);
3253 
3254 	/* COMPLETION tstamp is emitted for tracked skb later in Number of
3255 	 * Completed Packets event. Available only for flow controlled cases.
3256 	 *
3257 	 * TODO: SCO support without flowctl (needs to be done in drivers)
3258 	 */
3259 	switch (conn->type) {
3260 	case CIS_LINK:
3261 	case BIS_LINK:
3262 	case PA_LINK:
3263 	case ACL_LINK:
3264 	case LE_LINK:
3265 		break;
3266 	case SCO_LINK:
3267 	case ESCO_LINK:
3268 		if (!hci_dev_test_flag(conn->hdev, HCI_SCO_FLOWCTL))
3269 			return;
3270 		break;
3271 	default:
3272 		return;
3273 	}
3274 
3275 	if (skb->sk && (skb_shinfo(skb)->tx_flags & SKBTX_COMPLETION_TSTAMP))
3276 		track = true;
3277 
3278 	/* If nothing is tracked, just count extra skbs at the queue head */
3279 	if (!track && !comp->tracked) {
3280 		comp->extra++;
3281 		return;
3282 	}
3283 
3284 	if (track) {
3285 		skb = skb_clone_sk(skb);
3286 		if (!skb)
3287 			goto count_only;
3288 
3289 		comp->tracked++;
3290 	} else {
3291 		skb = skb_clone(skb, GFP_KERNEL);
3292 		if (!skb)
3293 			goto count_only;
3294 	}
3295 
3296 	skb_queue_tail(&comp->queue, skb);
3297 	return;
3298 
3299 count_only:
3300 	/* Stop tracking skbs, and only count. This will not emit timestamps for
3301 	 * the packets, but if we get here something is more seriously wrong.
3302 	 */
3303 	comp->tracked = 0;
3304 	comp->extra += skb_queue_len(&comp->queue) + 1;
3305 	skb_queue_purge(&comp->queue);
3306 }
3307 
3308 void hci_conn_tx_dequeue(struct hci_conn *conn)
3309 {
3310 	struct tx_queue *comp = &conn->tx_q;
3311 	struct sk_buff *skb;
3312 
3313 	/* If there are tracked skbs, the counted extra go before dequeuing real
3314 	 * skbs, to keep ordering. When nothing is tracked, the ordering doesn't
3315 	 * matter so dequeue real skbs first to get rid of them ASAP.
3316 	 */
3317 	if (comp->extra && (comp->tracked || skb_queue_empty(&comp->queue))) {
3318 		comp->extra--;
3319 		return;
3320 	}
3321 
3322 	skb = skb_dequeue(&comp->queue);
3323 	if (!skb)
3324 		return;
3325 
3326 	if (skb->sk) {
3327 		comp->tracked--;
3328 		__skb_tstamp_tx(skb, NULL, NULL, skb->sk,
3329 				SCM_TSTAMP_COMPLETION);
3330 	}
3331 
3332 	kfree_skb(skb);
3333 }
3334 
3335 u8 *hci_conn_key_enc_size(struct hci_conn *conn)
3336 {
3337 	if (conn->type == ACL_LINK) {
3338 		struct link_key *key;
3339 
3340 		key = hci_find_link_key(conn->hdev, &conn->dst);
3341 		if (!key)
3342 			return NULL;
3343 
3344 		return &key->pin_len;
3345 	} else if (conn->type == LE_LINK) {
3346 		struct smp_ltk *ltk;
3347 
3348 		ltk = hci_find_ltk(conn->hdev, &conn->dst, conn->dst_type,
3349 				   conn->role);
3350 		if (!ltk)
3351 			return NULL;
3352 
3353 		return &ltk->enc_size;
3354 	}
3355 
3356 	return NULL;
3357 }
3358 
3359 int hci_ethtool_ts_info(unsigned int index, int sk_proto,
3360 			struct kernel_ethtool_ts_info *info)
3361 {
3362 	struct hci_dev *hdev;
3363 
3364 	hdev = hci_dev_get(index);
3365 	if (!hdev)
3366 		return -ENODEV;
3367 
3368 	info->so_timestamping =
3369 		SOF_TIMESTAMPING_RX_SOFTWARE |
3370 		SOF_TIMESTAMPING_SOFTWARE;
3371 	info->phc_index = -1;
3372 	info->tx_types = BIT(HWTSTAMP_TX_OFF);
3373 	info->rx_filters = BIT(HWTSTAMP_FILTER_NONE);
3374 
3375 	switch (sk_proto) {
3376 	case BTPROTO_ISO:
3377 	case BTPROTO_L2CAP:
3378 		info->so_timestamping |= SOF_TIMESTAMPING_TX_SOFTWARE;
3379 		info->so_timestamping |= SOF_TIMESTAMPING_TX_COMPLETION;
3380 		break;
3381 	case BTPROTO_SCO:
3382 		info->so_timestamping |= SOF_TIMESTAMPING_TX_SOFTWARE;
3383 		if (hci_dev_test_flag(hdev, HCI_SCO_FLOWCTL))
3384 			info->so_timestamping |= SOF_TIMESTAMPING_TX_COMPLETION;
3385 		break;
3386 	}
3387 
3388 	hci_dev_put(hdev);
3389 	return 0;
3390 }
3391