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