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