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