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