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