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