xref: /openbmc/linux/net/bluetooth/hci_conn.c (revision 5c816641)
1 /*
2    BlueZ - Bluetooth protocol stack for Linux
3    Copyright (c) 2000-2001, 2010, Code Aurora Forum. All rights reserved.
4 
5    Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License version 2 as
9    published by the Free Software Foundation;
10 
11    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
14    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
15    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
16    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 
20    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
21    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
22    SOFTWARE IS DISCLAIMED.
23 */
24 
25 /* Bluetooth HCI connection handling. */
26 
27 #include <linux/export.h>
28 #include <linux/debugfs.h>
29 
30 #include <net/bluetooth/bluetooth.h>
31 #include <net/bluetooth/hci_core.h>
32 #include <net/bluetooth/l2cap.h>
33 
34 #include "hci_request.h"
35 #include "smp.h"
36 #include "a2mp.h"
37 
38 struct sco_param {
39 	u16 pkt_type;
40 	u16 max_latency;
41 	u8  retrans_effort;
42 };
43 
44 static const struct sco_param esco_param_cvsd[] = {
45 	{ EDR_ESCO_MASK & ~ESCO_2EV3, 0x000a,	0x01 }, /* S3 */
46 	{ EDR_ESCO_MASK & ~ESCO_2EV3, 0x0007,	0x01 }, /* S2 */
47 	{ EDR_ESCO_MASK | ESCO_EV3,   0x0007,	0x01 }, /* S1 */
48 	{ EDR_ESCO_MASK | ESCO_HV3,   0xffff,	0x01 }, /* D1 */
49 	{ EDR_ESCO_MASK | ESCO_HV1,   0xffff,	0x01 }, /* D0 */
50 };
51 
52 static const struct sco_param sco_param_cvsd[] = {
53 	{ EDR_ESCO_MASK | ESCO_HV3,   0xffff,	0xff }, /* D1 */
54 	{ EDR_ESCO_MASK | ESCO_HV1,   0xffff,	0xff }, /* D0 */
55 };
56 
57 static const struct sco_param esco_param_msbc[] = {
58 	{ EDR_ESCO_MASK & ~ESCO_2EV3, 0x000d,	0x02 }, /* T2 */
59 	{ EDR_ESCO_MASK | ESCO_EV3,   0x0008,	0x02 }, /* T1 */
60 };
61 
62 /* This function requires the caller holds hdev->lock */
63 static void hci_connect_le_scan_cleanup(struct hci_conn *conn)
64 {
65 	struct hci_conn_params *params;
66 	struct hci_dev *hdev = conn->hdev;
67 	struct smp_irk *irk;
68 	bdaddr_t *bdaddr;
69 	u8 bdaddr_type;
70 
71 	bdaddr = &conn->dst;
72 	bdaddr_type = conn->dst_type;
73 
74 	/* Check if we need to convert to identity address */
75 	irk = hci_get_irk(hdev, bdaddr, bdaddr_type);
76 	if (irk) {
77 		bdaddr = &irk->bdaddr;
78 		bdaddr_type = irk->addr_type;
79 	}
80 
81 	params = hci_pend_le_action_lookup(&hdev->pend_le_conns, bdaddr,
82 					   bdaddr_type);
83 	if (!params || !params->explicit_connect)
84 		return;
85 
86 	/* The connection attempt was doing scan for new RPA, and is
87 	 * in scan phase. If params are not associated with any other
88 	 * autoconnect action, remove them completely. If they are, just unmark
89 	 * them as waiting for connection, by clearing explicit_connect field.
90 	 */
91 	params->explicit_connect = false;
92 
93 	list_del_init(&params->action);
94 
95 	switch (params->auto_connect) {
96 	case HCI_AUTO_CONN_EXPLICIT:
97 		hci_conn_params_del(hdev, bdaddr, bdaddr_type);
98 		/* return instead of break to avoid duplicate scan update */
99 		return;
100 	case HCI_AUTO_CONN_DIRECT:
101 	case HCI_AUTO_CONN_ALWAYS:
102 		list_add(&params->action, &hdev->pend_le_conns);
103 		break;
104 	case HCI_AUTO_CONN_REPORT:
105 		list_add(&params->action, &hdev->pend_le_reports);
106 		break;
107 	default:
108 		break;
109 	}
110 
111 	hci_update_passive_scan(hdev);
112 }
113 
114 static void hci_conn_cleanup(struct hci_conn *conn)
115 {
116 	struct hci_dev *hdev = conn->hdev;
117 
118 	if (test_bit(HCI_CONN_PARAM_REMOVAL_PEND, &conn->flags))
119 		hci_conn_params_del(conn->hdev, &conn->dst, conn->dst_type);
120 
121 	hci_chan_list_flush(conn);
122 
123 	hci_conn_hash_del(hdev, conn);
124 
125 	if (conn->type == SCO_LINK || conn->type == ESCO_LINK) {
126 		switch (conn->setting & SCO_AIRMODE_MASK) {
127 		case SCO_AIRMODE_CVSD:
128 		case SCO_AIRMODE_TRANSP:
129 			if (hdev->notify)
130 				hdev->notify(hdev, HCI_NOTIFY_DISABLE_SCO);
131 			break;
132 		}
133 	} else {
134 		if (hdev->notify)
135 			hdev->notify(hdev, HCI_NOTIFY_CONN_DEL);
136 	}
137 
138 	hci_conn_del_sysfs(conn);
139 
140 	debugfs_remove_recursive(conn->debugfs);
141 
142 	hci_dev_put(hdev);
143 
144 	hci_conn_put(conn);
145 }
146 
147 static void le_scan_cleanup(struct work_struct *work)
148 {
149 	struct hci_conn *conn = container_of(work, struct hci_conn,
150 					     le_scan_cleanup);
151 	struct hci_dev *hdev = conn->hdev;
152 	struct hci_conn *c = NULL;
153 
154 	BT_DBG("%s hcon %p", hdev->name, conn);
155 
156 	hci_dev_lock(hdev);
157 
158 	/* Check that the hci_conn is still around */
159 	rcu_read_lock();
160 	list_for_each_entry_rcu(c, &hdev->conn_hash.list, list) {
161 		if (c == conn)
162 			break;
163 	}
164 	rcu_read_unlock();
165 
166 	if (c == conn) {
167 		hci_connect_le_scan_cleanup(conn);
168 		hci_conn_cleanup(conn);
169 	}
170 
171 	hci_dev_unlock(hdev);
172 	hci_dev_put(hdev);
173 	hci_conn_put(conn);
174 }
175 
176 static void hci_connect_le_scan_remove(struct hci_conn *conn)
177 {
178 	BT_DBG("%s hcon %p", conn->hdev->name, conn);
179 
180 	/* We can't call hci_conn_del/hci_conn_cleanup here since that
181 	 * could deadlock with another hci_conn_del() call that's holding
182 	 * hci_dev_lock and doing cancel_delayed_work_sync(&conn->disc_work).
183 	 * Instead, grab temporary extra references to the hci_dev and
184 	 * hci_conn and perform the necessary cleanup in a separate work
185 	 * callback.
186 	 */
187 
188 	hci_dev_hold(conn->hdev);
189 	hci_conn_get(conn);
190 
191 	/* Even though we hold a reference to the hdev, many other
192 	 * things might get cleaned up meanwhile, including the hdev's
193 	 * own workqueue, so we can't use that for scheduling.
194 	 */
195 	schedule_work(&conn->le_scan_cleanup);
196 }
197 
198 static void hci_acl_create_connection(struct hci_conn *conn)
199 {
200 	struct hci_dev *hdev = conn->hdev;
201 	struct inquiry_entry *ie;
202 	struct hci_cp_create_conn cp;
203 
204 	BT_DBG("hcon %p", conn);
205 
206 	/* Many controllers disallow HCI Create Connection while it is doing
207 	 * HCI Inquiry. So we cancel the Inquiry first before issuing HCI Create
208 	 * Connection. This may cause the MGMT discovering state to become false
209 	 * without user space's request but it is okay since the MGMT Discovery
210 	 * APIs do not promise that discovery should be done forever. Instead,
211 	 * the user space monitors the status of MGMT discovering and it may
212 	 * request for discovery again when this flag becomes false.
213 	 */
214 	if (test_bit(HCI_INQUIRY, &hdev->flags)) {
215 		/* Put this connection to "pending" state so that it will be
216 		 * executed after the inquiry cancel command complete event.
217 		 */
218 		conn->state = BT_CONNECT2;
219 		hci_send_cmd(hdev, HCI_OP_INQUIRY_CANCEL, 0, NULL);
220 		return;
221 	}
222 
223 	conn->state = BT_CONNECT;
224 	conn->out = true;
225 	conn->role = HCI_ROLE_MASTER;
226 
227 	conn->attempt++;
228 
229 	conn->link_policy = hdev->link_policy;
230 
231 	memset(&cp, 0, sizeof(cp));
232 	bacpy(&cp.bdaddr, &conn->dst);
233 	cp.pscan_rep_mode = 0x02;
234 
235 	ie = hci_inquiry_cache_lookup(hdev, &conn->dst);
236 	if (ie) {
237 		if (inquiry_entry_age(ie) <= INQUIRY_ENTRY_AGE_MAX) {
238 			cp.pscan_rep_mode = ie->data.pscan_rep_mode;
239 			cp.pscan_mode     = ie->data.pscan_mode;
240 			cp.clock_offset   = ie->data.clock_offset |
241 					    cpu_to_le16(0x8000);
242 		}
243 
244 		memcpy(conn->dev_class, ie->data.dev_class, 3);
245 	}
246 
247 	cp.pkt_type = cpu_to_le16(conn->pkt_type);
248 	if (lmp_rswitch_capable(hdev) && !(hdev->link_mode & HCI_LM_MASTER))
249 		cp.role_switch = 0x01;
250 	else
251 		cp.role_switch = 0x00;
252 
253 	hci_send_cmd(hdev, HCI_OP_CREATE_CONN, sizeof(cp), &cp);
254 }
255 
256 int hci_disconnect(struct hci_conn *conn, __u8 reason)
257 {
258 	BT_DBG("hcon %p", conn);
259 
260 	/* When we are central of an established connection and it enters
261 	 * the disconnect timeout, then go ahead and try to read the
262 	 * current clock offset.  Processing of the result is done
263 	 * within the event handling and hci_clock_offset_evt function.
264 	 */
265 	if (conn->type == ACL_LINK && conn->role == HCI_ROLE_MASTER &&
266 	    (conn->state == BT_CONNECTED || conn->state == BT_CONFIG)) {
267 		struct hci_dev *hdev = conn->hdev;
268 		struct hci_cp_read_clock_offset clkoff_cp;
269 
270 		clkoff_cp.handle = cpu_to_le16(conn->handle);
271 		hci_send_cmd(hdev, HCI_OP_READ_CLOCK_OFFSET, sizeof(clkoff_cp),
272 			     &clkoff_cp);
273 	}
274 
275 	return hci_abort_conn(conn, reason);
276 }
277 
278 static void hci_add_sco(struct hci_conn *conn, __u16 handle)
279 {
280 	struct hci_dev *hdev = conn->hdev;
281 	struct hci_cp_add_sco cp;
282 
283 	BT_DBG("hcon %p", conn);
284 
285 	conn->state = BT_CONNECT;
286 	conn->out = true;
287 
288 	conn->attempt++;
289 
290 	cp.handle   = cpu_to_le16(handle);
291 	cp.pkt_type = cpu_to_le16(conn->pkt_type);
292 
293 	hci_send_cmd(hdev, HCI_OP_ADD_SCO, sizeof(cp), &cp);
294 }
295 
296 static bool find_next_esco_param(struct hci_conn *conn,
297 				 const struct sco_param *esco_param, int size)
298 {
299 	for (; conn->attempt <= size; conn->attempt++) {
300 		if (lmp_esco_2m_capable(conn->link) ||
301 		    (esco_param[conn->attempt - 1].pkt_type & ESCO_2EV3))
302 			break;
303 		BT_DBG("hcon %p skipped attempt %d, eSCO 2M not supported",
304 		       conn, conn->attempt);
305 	}
306 
307 	return conn->attempt <= size;
308 }
309 
310 static bool hci_enhanced_setup_sync_conn(struct hci_conn *conn, __u16 handle)
311 {
312 	struct hci_dev *hdev = conn->hdev;
313 	struct hci_cp_enhanced_setup_sync_conn cp;
314 	const struct sco_param *param;
315 
316 	bt_dev_dbg(hdev, "hcon %p", conn);
317 
318 	/* for offload use case, codec needs to configured before opening SCO */
319 	if (conn->codec.data_path)
320 		hci_req_configure_datapath(hdev, &conn->codec);
321 
322 	conn->state = BT_CONNECT;
323 	conn->out = true;
324 
325 	conn->attempt++;
326 
327 	memset(&cp, 0x00, sizeof(cp));
328 
329 	cp.handle   = cpu_to_le16(handle);
330 
331 	cp.tx_bandwidth   = cpu_to_le32(0x00001f40);
332 	cp.rx_bandwidth   = cpu_to_le32(0x00001f40);
333 
334 	switch (conn->codec.id) {
335 	case BT_CODEC_MSBC:
336 		if (!find_next_esco_param(conn, esco_param_msbc,
337 					  ARRAY_SIZE(esco_param_msbc)))
338 			return false;
339 
340 		param = &esco_param_msbc[conn->attempt - 1];
341 		cp.tx_coding_format.id = 0x05;
342 		cp.rx_coding_format.id = 0x05;
343 		cp.tx_codec_frame_size = __cpu_to_le16(60);
344 		cp.rx_codec_frame_size = __cpu_to_le16(60);
345 		cp.in_bandwidth = __cpu_to_le32(32000);
346 		cp.out_bandwidth = __cpu_to_le32(32000);
347 		cp.in_coding_format.id = 0x04;
348 		cp.out_coding_format.id = 0x04;
349 		cp.in_coded_data_size = __cpu_to_le16(16);
350 		cp.out_coded_data_size = __cpu_to_le16(16);
351 		cp.in_pcm_data_format = 2;
352 		cp.out_pcm_data_format = 2;
353 		cp.in_pcm_sample_payload_msb_pos = 0;
354 		cp.out_pcm_sample_payload_msb_pos = 0;
355 		cp.in_data_path = conn->codec.data_path;
356 		cp.out_data_path = conn->codec.data_path;
357 		cp.in_transport_unit_size = 1;
358 		cp.out_transport_unit_size = 1;
359 		break;
360 
361 	case BT_CODEC_TRANSPARENT:
362 		if (!find_next_esco_param(conn, esco_param_msbc,
363 					  ARRAY_SIZE(esco_param_msbc)))
364 			return false;
365 		param = &esco_param_msbc[conn->attempt - 1];
366 		cp.tx_coding_format.id = 0x03;
367 		cp.rx_coding_format.id = 0x03;
368 		cp.tx_codec_frame_size = __cpu_to_le16(60);
369 		cp.rx_codec_frame_size = __cpu_to_le16(60);
370 		cp.in_bandwidth = __cpu_to_le32(0x1f40);
371 		cp.out_bandwidth = __cpu_to_le32(0x1f40);
372 		cp.in_coding_format.id = 0x03;
373 		cp.out_coding_format.id = 0x03;
374 		cp.in_coded_data_size = __cpu_to_le16(16);
375 		cp.out_coded_data_size = __cpu_to_le16(16);
376 		cp.in_pcm_data_format = 2;
377 		cp.out_pcm_data_format = 2;
378 		cp.in_pcm_sample_payload_msb_pos = 0;
379 		cp.out_pcm_sample_payload_msb_pos = 0;
380 		cp.in_data_path = conn->codec.data_path;
381 		cp.out_data_path = conn->codec.data_path;
382 		cp.in_transport_unit_size = 1;
383 		cp.out_transport_unit_size = 1;
384 		break;
385 
386 	case BT_CODEC_CVSD:
387 		if (lmp_esco_capable(conn->link)) {
388 			if (!find_next_esco_param(conn, esco_param_cvsd,
389 						  ARRAY_SIZE(esco_param_cvsd)))
390 				return false;
391 			param = &esco_param_cvsd[conn->attempt - 1];
392 		} else {
393 			if (conn->attempt > ARRAY_SIZE(sco_param_cvsd))
394 				return false;
395 			param = &sco_param_cvsd[conn->attempt - 1];
396 		}
397 		cp.tx_coding_format.id = 2;
398 		cp.rx_coding_format.id = 2;
399 		cp.tx_codec_frame_size = __cpu_to_le16(60);
400 		cp.rx_codec_frame_size = __cpu_to_le16(60);
401 		cp.in_bandwidth = __cpu_to_le32(16000);
402 		cp.out_bandwidth = __cpu_to_le32(16000);
403 		cp.in_coding_format.id = 4;
404 		cp.out_coding_format.id = 4;
405 		cp.in_coded_data_size = __cpu_to_le16(16);
406 		cp.out_coded_data_size = __cpu_to_le16(16);
407 		cp.in_pcm_data_format = 2;
408 		cp.out_pcm_data_format = 2;
409 		cp.in_pcm_sample_payload_msb_pos = 0;
410 		cp.out_pcm_sample_payload_msb_pos = 0;
411 		cp.in_data_path = conn->codec.data_path;
412 		cp.out_data_path = conn->codec.data_path;
413 		cp.in_transport_unit_size = 16;
414 		cp.out_transport_unit_size = 16;
415 		break;
416 	default:
417 		return false;
418 	}
419 
420 	cp.retrans_effort = param->retrans_effort;
421 	cp.pkt_type = __cpu_to_le16(param->pkt_type);
422 	cp.max_latency = __cpu_to_le16(param->max_latency);
423 
424 	if (hci_send_cmd(hdev, HCI_OP_ENHANCED_SETUP_SYNC_CONN, sizeof(cp), &cp) < 0)
425 		return false;
426 
427 	return true;
428 }
429 
430 static bool hci_setup_sync_conn(struct hci_conn *conn, __u16 handle)
431 {
432 	struct hci_dev *hdev = conn->hdev;
433 	struct hci_cp_setup_sync_conn cp;
434 	const struct sco_param *param;
435 
436 	bt_dev_dbg(hdev, "hcon %p", conn);
437 
438 	conn->state = BT_CONNECT;
439 	conn->out = true;
440 
441 	conn->attempt++;
442 
443 	cp.handle   = cpu_to_le16(handle);
444 
445 	cp.tx_bandwidth   = cpu_to_le32(0x00001f40);
446 	cp.rx_bandwidth   = cpu_to_le32(0x00001f40);
447 	cp.voice_setting  = cpu_to_le16(conn->setting);
448 
449 	switch (conn->setting & SCO_AIRMODE_MASK) {
450 	case SCO_AIRMODE_TRANSP:
451 		if (!find_next_esco_param(conn, esco_param_msbc,
452 					  ARRAY_SIZE(esco_param_msbc)))
453 			return false;
454 		param = &esco_param_msbc[conn->attempt - 1];
455 		break;
456 	case SCO_AIRMODE_CVSD:
457 		if (lmp_esco_capable(conn->link)) {
458 			if (!find_next_esco_param(conn, esco_param_cvsd,
459 						  ARRAY_SIZE(esco_param_cvsd)))
460 				return false;
461 			param = &esco_param_cvsd[conn->attempt - 1];
462 		} else {
463 			if (conn->attempt > ARRAY_SIZE(sco_param_cvsd))
464 				return false;
465 			param = &sco_param_cvsd[conn->attempt - 1];
466 		}
467 		break;
468 	default:
469 		return false;
470 	}
471 
472 	cp.retrans_effort = param->retrans_effort;
473 	cp.pkt_type = __cpu_to_le16(param->pkt_type);
474 	cp.max_latency = __cpu_to_le16(param->max_latency);
475 
476 	if (hci_send_cmd(hdev, HCI_OP_SETUP_SYNC_CONN, sizeof(cp), &cp) < 0)
477 		return false;
478 
479 	return true;
480 }
481 
482 bool hci_setup_sync(struct hci_conn *conn, __u16 handle)
483 {
484 	if (enhanced_sco_capable(conn->hdev))
485 		return hci_enhanced_setup_sync_conn(conn, handle);
486 
487 	return hci_setup_sync_conn(conn, handle);
488 }
489 
490 u8 hci_le_conn_update(struct hci_conn *conn, u16 min, u16 max, u16 latency,
491 		      u16 to_multiplier)
492 {
493 	struct hci_dev *hdev = conn->hdev;
494 	struct hci_conn_params *params;
495 	struct hci_cp_le_conn_update cp;
496 
497 	hci_dev_lock(hdev);
498 
499 	params = hci_conn_params_lookup(hdev, &conn->dst, conn->dst_type);
500 	if (params) {
501 		params->conn_min_interval = min;
502 		params->conn_max_interval = max;
503 		params->conn_latency = latency;
504 		params->supervision_timeout = to_multiplier;
505 	}
506 
507 	hci_dev_unlock(hdev);
508 
509 	memset(&cp, 0, sizeof(cp));
510 	cp.handle		= cpu_to_le16(conn->handle);
511 	cp.conn_interval_min	= cpu_to_le16(min);
512 	cp.conn_interval_max	= cpu_to_le16(max);
513 	cp.conn_latency		= cpu_to_le16(latency);
514 	cp.supervision_timeout	= cpu_to_le16(to_multiplier);
515 	cp.min_ce_len		= cpu_to_le16(0x0000);
516 	cp.max_ce_len		= cpu_to_le16(0x0000);
517 
518 	hci_send_cmd(hdev, HCI_OP_LE_CONN_UPDATE, sizeof(cp), &cp);
519 
520 	if (params)
521 		return 0x01;
522 
523 	return 0x00;
524 }
525 
526 void hci_le_start_enc(struct hci_conn *conn, __le16 ediv, __le64 rand,
527 		      __u8 ltk[16], __u8 key_size)
528 {
529 	struct hci_dev *hdev = conn->hdev;
530 	struct hci_cp_le_start_enc cp;
531 
532 	BT_DBG("hcon %p", conn);
533 
534 	memset(&cp, 0, sizeof(cp));
535 
536 	cp.handle = cpu_to_le16(conn->handle);
537 	cp.rand = rand;
538 	cp.ediv = ediv;
539 	memcpy(cp.ltk, ltk, key_size);
540 
541 	hci_send_cmd(hdev, HCI_OP_LE_START_ENC, sizeof(cp), &cp);
542 }
543 
544 /* Device _must_ be locked */
545 void hci_sco_setup(struct hci_conn *conn, __u8 status)
546 {
547 	struct hci_conn *sco = conn->link;
548 
549 	if (!sco)
550 		return;
551 
552 	BT_DBG("hcon %p", conn);
553 
554 	if (!status) {
555 		if (lmp_esco_capable(conn->hdev))
556 			hci_setup_sync(sco, conn->handle);
557 		else
558 			hci_add_sco(sco, conn->handle);
559 	} else {
560 		hci_connect_cfm(sco, status);
561 		hci_conn_del(sco);
562 	}
563 }
564 
565 static void hci_conn_timeout(struct work_struct *work)
566 {
567 	struct hci_conn *conn = container_of(work, struct hci_conn,
568 					     disc_work.work);
569 	int refcnt = atomic_read(&conn->refcnt);
570 
571 	BT_DBG("hcon %p state %s", conn, state_to_string(conn->state));
572 
573 	WARN_ON(refcnt < 0);
574 
575 	/* FIXME: It was observed that in pairing failed scenario, refcnt
576 	 * drops below 0. Probably this is because l2cap_conn_del calls
577 	 * l2cap_chan_del for each channel, and inside l2cap_chan_del conn is
578 	 * dropped. After that loop hci_chan_del is called which also drops
579 	 * conn. For now make sure that ACL is alive if refcnt is higher then 0,
580 	 * otherwise drop it.
581 	 */
582 	if (refcnt > 0)
583 		return;
584 
585 	/* LE connections in scanning state need special handling */
586 	if (conn->state == BT_CONNECT && conn->type == LE_LINK &&
587 	    test_bit(HCI_CONN_SCANNING, &conn->flags)) {
588 		hci_connect_le_scan_remove(conn);
589 		return;
590 	}
591 
592 	hci_abort_conn(conn, hci_proto_disconn_ind(conn));
593 }
594 
595 /* Enter sniff mode */
596 static void hci_conn_idle(struct work_struct *work)
597 {
598 	struct hci_conn *conn = container_of(work, struct hci_conn,
599 					     idle_work.work);
600 	struct hci_dev *hdev = conn->hdev;
601 
602 	BT_DBG("hcon %p mode %d", conn, conn->mode);
603 
604 	if (!lmp_sniff_capable(hdev) || !lmp_sniff_capable(conn))
605 		return;
606 
607 	if (conn->mode != HCI_CM_ACTIVE || !(conn->link_policy & HCI_LP_SNIFF))
608 		return;
609 
610 	if (lmp_sniffsubr_capable(hdev) && lmp_sniffsubr_capable(conn)) {
611 		struct hci_cp_sniff_subrate cp;
612 		cp.handle             = cpu_to_le16(conn->handle);
613 		cp.max_latency        = cpu_to_le16(0);
614 		cp.min_remote_timeout = cpu_to_le16(0);
615 		cp.min_local_timeout  = cpu_to_le16(0);
616 		hci_send_cmd(hdev, HCI_OP_SNIFF_SUBRATE, sizeof(cp), &cp);
617 	}
618 
619 	if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) {
620 		struct hci_cp_sniff_mode cp;
621 		cp.handle       = cpu_to_le16(conn->handle);
622 		cp.max_interval = cpu_to_le16(hdev->sniff_max_interval);
623 		cp.min_interval = cpu_to_le16(hdev->sniff_min_interval);
624 		cp.attempt      = cpu_to_le16(4);
625 		cp.timeout      = cpu_to_le16(1);
626 		hci_send_cmd(hdev, HCI_OP_SNIFF_MODE, sizeof(cp), &cp);
627 	}
628 }
629 
630 static void hci_conn_auto_accept(struct work_struct *work)
631 {
632 	struct hci_conn *conn = container_of(work, struct hci_conn,
633 					     auto_accept_work.work);
634 
635 	hci_send_cmd(conn->hdev, HCI_OP_USER_CONFIRM_REPLY, sizeof(conn->dst),
636 		     &conn->dst);
637 }
638 
639 static void le_disable_advertising(struct hci_dev *hdev)
640 {
641 	if (ext_adv_capable(hdev)) {
642 		struct hci_cp_le_set_ext_adv_enable cp;
643 
644 		cp.enable = 0x00;
645 		cp.num_of_sets = 0x00;
646 
647 		hci_send_cmd(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE, sizeof(cp),
648 			     &cp);
649 	} else {
650 		u8 enable = 0x00;
651 		hci_send_cmd(hdev, HCI_OP_LE_SET_ADV_ENABLE, sizeof(enable),
652 			     &enable);
653 	}
654 }
655 
656 static void le_conn_timeout(struct work_struct *work)
657 {
658 	struct hci_conn *conn = container_of(work, struct hci_conn,
659 					     le_conn_timeout.work);
660 	struct hci_dev *hdev = conn->hdev;
661 
662 	BT_DBG("");
663 
664 	/* We could end up here due to having done directed advertising,
665 	 * so clean up the state if necessary. This should however only
666 	 * happen with broken hardware or if low duty cycle was used
667 	 * (which doesn't have a timeout of its own).
668 	 */
669 	if (conn->role == HCI_ROLE_SLAVE) {
670 		/* Disable LE Advertising */
671 		le_disable_advertising(hdev);
672 		hci_le_conn_failed(conn, HCI_ERROR_ADVERTISING_TIMEOUT);
673 		return;
674 	}
675 
676 	hci_abort_conn(conn, HCI_ERROR_REMOTE_USER_TERM);
677 }
678 
679 struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type, bdaddr_t *dst,
680 			      u8 role)
681 {
682 	struct hci_conn *conn;
683 
684 	BT_DBG("%s dst %pMR", hdev->name, dst);
685 
686 	conn = kzalloc(sizeof(*conn), GFP_KERNEL);
687 	if (!conn)
688 		return NULL;
689 
690 	bacpy(&conn->dst, dst);
691 	bacpy(&conn->src, &hdev->bdaddr);
692 	conn->hdev  = hdev;
693 	conn->type  = type;
694 	conn->role  = role;
695 	conn->mode  = HCI_CM_ACTIVE;
696 	conn->state = BT_OPEN;
697 	conn->auth_type = HCI_AT_GENERAL_BONDING;
698 	conn->io_capability = hdev->io_capability;
699 	conn->remote_auth = 0xff;
700 	conn->key_type = 0xff;
701 	conn->rssi = HCI_RSSI_INVALID;
702 	conn->tx_power = HCI_TX_POWER_INVALID;
703 	conn->max_tx_power = HCI_TX_POWER_INVALID;
704 
705 	set_bit(HCI_CONN_POWER_SAVE, &conn->flags);
706 	conn->disc_timeout = HCI_DISCONN_TIMEOUT;
707 
708 	/* Set Default Authenticated payload timeout to 30s */
709 	conn->auth_payload_timeout = DEFAULT_AUTH_PAYLOAD_TIMEOUT;
710 
711 	if (conn->role == HCI_ROLE_MASTER)
712 		conn->out = true;
713 
714 	switch (type) {
715 	case ACL_LINK:
716 		conn->pkt_type = hdev->pkt_type & ACL_PTYPE_MASK;
717 		break;
718 	case LE_LINK:
719 		/* conn->src should reflect the local identity address */
720 		hci_copy_identity_address(hdev, &conn->src, &conn->src_type);
721 		break;
722 	case SCO_LINK:
723 		if (lmp_esco_capable(hdev))
724 			conn->pkt_type = (hdev->esco_type & SCO_ESCO_MASK) |
725 					(hdev->esco_type & EDR_ESCO_MASK);
726 		else
727 			conn->pkt_type = hdev->pkt_type & SCO_PTYPE_MASK;
728 		break;
729 	case ESCO_LINK:
730 		conn->pkt_type = hdev->esco_type & ~EDR_ESCO_MASK;
731 		break;
732 	}
733 
734 	skb_queue_head_init(&conn->data_q);
735 
736 	INIT_LIST_HEAD(&conn->chan_list);
737 
738 	INIT_DELAYED_WORK(&conn->disc_work, hci_conn_timeout);
739 	INIT_DELAYED_WORK(&conn->auto_accept_work, hci_conn_auto_accept);
740 	INIT_DELAYED_WORK(&conn->idle_work, hci_conn_idle);
741 	INIT_DELAYED_WORK(&conn->le_conn_timeout, le_conn_timeout);
742 	INIT_WORK(&conn->le_scan_cleanup, le_scan_cleanup);
743 
744 	atomic_set(&conn->refcnt, 0);
745 
746 	hci_dev_hold(hdev);
747 
748 	hci_conn_hash_add(hdev, conn);
749 
750 	/* The SCO and eSCO connections will only be notified when their
751 	 * setup has been completed. This is different to ACL links which
752 	 * can be notified right away.
753 	 */
754 	if (conn->type != SCO_LINK && conn->type != ESCO_LINK) {
755 		if (hdev->notify)
756 			hdev->notify(hdev, HCI_NOTIFY_CONN_ADD);
757 	}
758 
759 	hci_conn_init_sysfs(conn);
760 
761 	return conn;
762 }
763 
764 int hci_conn_del(struct hci_conn *conn)
765 {
766 	struct hci_dev *hdev = conn->hdev;
767 
768 	BT_DBG("%s hcon %p handle %d", hdev->name, conn, conn->handle);
769 
770 	cancel_delayed_work_sync(&conn->disc_work);
771 	cancel_delayed_work_sync(&conn->auto_accept_work);
772 	cancel_delayed_work_sync(&conn->idle_work);
773 
774 	if (conn->type == ACL_LINK) {
775 		struct hci_conn *sco = conn->link;
776 		if (sco)
777 			sco->link = NULL;
778 
779 		/* Unacked frames */
780 		hdev->acl_cnt += conn->sent;
781 	} else if (conn->type == LE_LINK) {
782 		cancel_delayed_work(&conn->le_conn_timeout);
783 
784 		if (hdev->le_pkts)
785 			hdev->le_cnt += conn->sent;
786 		else
787 			hdev->acl_cnt += conn->sent;
788 	} else {
789 		struct hci_conn *acl = conn->link;
790 		if (acl) {
791 			acl->link = NULL;
792 			hci_conn_drop(acl);
793 		}
794 	}
795 
796 	if (conn->amp_mgr)
797 		amp_mgr_put(conn->amp_mgr);
798 
799 	skb_queue_purge(&conn->data_q);
800 
801 	/* Remove the connection from the list and cleanup its remaining
802 	 * state. This is a separate function since for some cases like
803 	 * BT_CONNECT_SCAN we *only* want the cleanup part without the
804 	 * rest of hci_conn_del.
805 	 */
806 	hci_conn_cleanup(conn);
807 
808 	return 0;
809 }
810 
811 struct hci_dev *hci_get_route(bdaddr_t *dst, bdaddr_t *src, uint8_t src_type)
812 {
813 	int use_src = bacmp(src, BDADDR_ANY);
814 	struct hci_dev *hdev = NULL, *d;
815 
816 	BT_DBG("%pMR -> %pMR", src, dst);
817 
818 	read_lock(&hci_dev_list_lock);
819 
820 	list_for_each_entry(d, &hci_dev_list, list) {
821 		if (!test_bit(HCI_UP, &d->flags) ||
822 		    hci_dev_test_flag(d, HCI_USER_CHANNEL) ||
823 		    d->dev_type != HCI_PRIMARY)
824 			continue;
825 
826 		/* Simple routing:
827 		 *   No source address - find interface with bdaddr != dst
828 		 *   Source address    - find interface with bdaddr == src
829 		 */
830 
831 		if (use_src) {
832 			bdaddr_t id_addr;
833 			u8 id_addr_type;
834 
835 			if (src_type == BDADDR_BREDR) {
836 				if (!lmp_bredr_capable(d))
837 					continue;
838 				bacpy(&id_addr, &d->bdaddr);
839 				id_addr_type = BDADDR_BREDR;
840 			} else {
841 				if (!lmp_le_capable(d))
842 					continue;
843 
844 				hci_copy_identity_address(d, &id_addr,
845 							  &id_addr_type);
846 
847 				/* Convert from HCI to three-value type */
848 				if (id_addr_type == ADDR_LE_DEV_PUBLIC)
849 					id_addr_type = BDADDR_LE_PUBLIC;
850 				else
851 					id_addr_type = BDADDR_LE_RANDOM;
852 			}
853 
854 			if (!bacmp(&id_addr, src) && id_addr_type == src_type) {
855 				hdev = d; break;
856 			}
857 		} else {
858 			if (bacmp(&d->bdaddr, dst)) {
859 				hdev = d; break;
860 			}
861 		}
862 	}
863 
864 	if (hdev)
865 		hdev = hci_dev_hold(hdev);
866 
867 	read_unlock(&hci_dev_list_lock);
868 	return hdev;
869 }
870 EXPORT_SYMBOL(hci_get_route);
871 
872 /* This function requires the caller holds hdev->lock */
873 void hci_le_conn_failed(struct hci_conn *conn, u8 status)
874 {
875 	struct hci_dev *hdev = conn->hdev;
876 	struct hci_conn_params *params;
877 
878 	params = hci_pend_le_action_lookup(&hdev->pend_le_conns, &conn->dst,
879 					   conn->dst_type);
880 	if (params && params->conn) {
881 		hci_conn_drop(params->conn);
882 		hci_conn_put(params->conn);
883 		params->conn = NULL;
884 	}
885 
886 	conn->state = BT_CLOSED;
887 
888 	/* If the status indicates successful cancellation of
889 	 * the attempt (i.e. Unknown Connection Id) there's no point of
890 	 * notifying failure since we'll go back to keep trying to
891 	 * connect. The only exception is explicit connect requests
892 	 * where a timeout + cancel does indicate an actual failure.
893 	 */
894 	if (status != HCI_ERROR_UNKNOWN_CONN_ID ||
895 	    (params && params->explicit_connect))
896 		mgmt_connect_failed(hdev, &conn->dst, conn->type,
897 				    conn->dst_type, status);
898 
899 	hci_connect_cfm(conn, status);
900 
901 	hci_conn_del(conn);
902 
903 	/* Since we may have temporarily stopped the background scanning in
904 	 * favor of connection establishment, we should restart it.
905 	 */
906 	hci_update_passive_scan(hdev);
907 
908 	/* Enable advertising in case this was a failed connection
909 	 * attempt as a peripheral.
910 	 */
911 	hci_enable_advertising(hdev);
912 }
913 
914 static void create_le_conn_complete(struct hci_dev *hdev, void *data, int err)
915 {
916 	struct hci_conn *conn = data;
917 
918 	hci_dev_lock(hdev);
919 
920 	if (!err) {
921 		hci_connect_le_scan_cleanup(conn);
922 		goto done;
923 	}
924 
925 	bt_dev_err(hdev, "request failed to create LE connection: err %d", err);
926 
927 	if (!conn)
928 		goto done;
929 
930 	hci_le_conn_failed(conn, err);
931 
932 done:
933 	hci_dev_unlock(hdev);
934 }
935 
936 static int hci_connect_le_sync(struct hci_dev *hdev, void *data)
937 {
938 	struct hci_conn *conn = data;
939 
940 	bt_dev_dbg(hdev, "conn %p", conn);
941 
942 	return hci_le_create_conn_sync(hdev, conn);
943 }
944 
945 struct hci_conn *hci_connect_le(struct hci_dev *hdev, bdaddr_t *dst,
946 				u8 dst_type, bool dst_resolved, u8 sec_level,
947 				u16 conn_timeout, u8 role)
948 {
949 	struct hci_conn *conn;
950 	struct smp_irk *irk;
951 	int err;
952 
953 	/* Let's make sure that le is enabled.*/
954 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
955 		if (lmp_le_capable(hdev))
956 			return ERR_PTR(-ECONNREFUSED);
957 
958 		return ERR_PTR(-EOPNOTSUPP);
959 	}
960 
961 	/* Since the controller supports only one LE connection attempt at a
962 	 * time, we return -EBUSY if there is any connection attempt running.
963 	 */
964 	if (hci_lookup_le_connect(hdev))
965 		return ERR_PTR(-EBUSY);
966 
967 	/* If there's already a connection object but it's not in
968 	 * scanning state it means it must already be established, in
969 	 * which case we can't do anything else except report a failure
970 	 * to connect.
971 	 */
972 	conn = hci_conn_hash_lookup_le(hdev, dst, dst_type);
973 	if (conn && !test_bit(HCI_CONN_SCANNING, &conn->flags)) {
974 		return ERR_PTR(-EBUSY);
975 	}
976 
977 	/* Check if the destination address has been resolved by the controller
978 	 * since if it did then the identity address shall be used.
979 	 */
980 	if (!dst_resolved) {
981 		/* When given an identity address with existing identity
982 		 * resolving key, the connection needs to be established
983 		 * to a resolvable random address.
984 		 *
985 		 * Storing the resolvable random address is required here
986 		 * to handle connection failures. The address will later
987 		 * be resolved back into the original identity address
988 		 * from the connect request.
989 		 */
990 		irk = hci_find_irk_by_addr(hdev, dst, dst_type);
991 		if (irk && bacmp(&irk->rpa, BDADDR_ANY)) {
992 			dst = &irk->rpa;
993 			dst_type = ADDR_LE_DEV_RANDOM;
994 		}
995 	}
996 
997 	if (conn) {
998 		bacpy(&conn->dst, dst);
999 	} else {
1000 		conn = hci_conn_add(hdev, LE_LINK, dst, role);
1001 		if (!conn)
1002 			return ERR_PTR(-ENOMEM);
1003 		hci_conn_hold(conn);
1004 		conn->pending_sec_level = sec_level;
1005 	}
1006 
1007 	conn->dst_type = dst_type;
1008 	conn->sec_level = BT_SECURITY_LOW;
1009 	conn->conn_timeout = conn_timeout;
1010 
1011 	conn->state = BT_CONNECT;
1012 	clear_bit(HCI_CONN_SCANNING, &conn->flags);
1013 
1014 	err = hci_cmd_sync_queue(hdev, hci_connect_le_sync, conn,
1015 				 create_le_conn_complete);
1016 	if (err) {
1017 		hci_conn_del(conn);
1018 		return ERR_PTR(err);
1019 	}
1020 
1021 	return conn;
1022 }
1023 
1024 static bool is_connected(struct hci_dev *hdev, bdaddr_t *addr, u8 type)
1025 {
1026 	struct hci_conn *conn;
1027 
1028 	conn = hci_conn_hash_lookup_le(hdev, addr, type);
1029 	if (!conn)
1030 		return false;
1031 
1032 	if (conn->state != BT_CONNECTED)
1033 		return false;
1034 
1035 	return true;
1036 }
1037 
1038 /* This function requires the caller holds hdev->lock */
1039 static int hci_explicit_conn_params_set(struct hci_dev *hdev,
1040 					bdaddr_t *addr, u8 addr_type)
1041 {
1042 	struct hci_conn_params *params;
1043 
1044 	if (is_connected(hdev, addr, addr_type))
1045 		return -EISCONN;
1046 
1047 	params = hci_conn_params_lookup(hdev, addr, addr_type);
1048 	if (!params) {
1049 		params = hci_conn_params_add(hdev, addr, addr_type);
1050 		if (!params)
1051 			return -ENOMEM;
1052 
1053 		/* If we created new params, mark them to be deleted in
1054 		 * hci_connect_le_scan_cleanup. It's different case than
1055 		 * existing disabled params, those will stay after cleanup.
1056 		 */
1057 		params->auto_connect = HCI_AUTO_CONN_EXPLICIT;
1058 	}
1059 
1060 	/* We're trying to connect, so make sure params are at pend_le_conns */
1061 	if (params->auto_connect == HCI_AUTO_CONN_DISABLED ||
1062 	    params->auto_connect == HCI_AUTO_CONN_REPORT ||
1063 	    params->auto_connect == HCI_AUTO_CONN_EXPLICIT) {
1064 		list_del_init(&params->action);
1065 		list_add(&params->action, &hdev->pend_le_conns);
1066 	}
1067 
1068 	params->explicit_connect = true;
1069 
1070 	BT_DBG("addr %pMR (type %u) auto_connect %u", addr, addr_type,
1071 	       params->auto_connect);
1072 
1073 	return 0;
1074 }
1075 
1076 /* This function requires the caller holds hdev->lock */
1077 struct hci_conn *hci_connect_le_scan(struct hci_dev *hdev, bdaddr_t *dst,
1078 				     u8 dst_type, u8 sec_level,
1079 				     u16 conn_timeout,
1080 				     enum conn_reasons conn_reason)
1081 {
1082 	struct hci_conn *conn;
1083 
1084 	/* Let's make sure that le is enabled.*/
1085 	if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED)) {
1086 		if (lmp_le_capable(hdev))
1087 			return ERR_PTR(-ECONNREFUSED);
1088 
1089 		return ERR_PTR(-EOPNOTSUPP);
1090 	}
1091 
1092 	/* Some devices send ATT messages as soon as the physical link is
1093 	 * established. To be able to handle these ATT messages, the user-
1094 	 * space first establishes the connection and then starts the pairing
1095 	 * process.
1096 	 *
1097 	 * So if a hci_conn object already exists for the following connection
1098 	 * attempt, we simply update pending_sec_level and auth_type fields
1099 	 * and return the object found.
1100 	 */
1101 	conn = hci_conn_hash_lookup_le(hdev, dst, dst_type);
1102 	if (conn) {
1103 		if (conn->pending_sec_level < sec_level)
1104 			conn->pending_sec_level = sec_level;
1105 		goto done;
1106 	}
1107 
1108 	BT_DBG("requesting refresh of dst_addr");
1109 
1110 	conn = hci_conn_add(hdev, LE_LINK, dst, HCI_ROLE_MASTER);
1111 	if (!conn)
1112 		return ERR_PTR(-ENOMEM);
1113 
1114 	if (hci_explicit_conn_params_set(hdev, dst, dst_type) < 0) {
1115 		hci_conn_del(conn);
1116 		return ERR_PTR(-EBUSY);
1117 	}
1118 
1119 	conn->state = BT_CONNECT;
1120 	set_bit(HCI_CONN_SCANNING, &conn->flags);
1121 	conn->dst_type = dst_type;
1122 	conn->sec_level = BT_SECURITY_LOW;
1123 	conn->pending_sec_level = sec_level;
1124 	conn->conn_timeout = conn_timeout;
1125 	conn->conn_reason = conn_reason;
1126 
1127 	hci_update_passive_scan(hdev);
1128 
1129 done:
1130 	hci_conn_hold(conn);
1131 	return conn;
1132 }
1133 
1134 struct hci_conn *hci_connect_acl(struct hci_dev *hdev, bdaddr_t *dst,
1135 				 u8 sec_level, u8 auth_type,
1136 				 enum conn_reasons conn_reason)
1137 {
1138 	struct hci_conn *acl;
1139 
1140 	if (!hci_dev_test_flag(hdev, HCI_BREDR_ENABLED)) {
1141 		if (lmp_bredr_capable(hdev))
1142 			return ERR_PTR(-ECONNREFUSED);
1143 
1144 		return ERR_PTR(-EOPNOTSUPP);
1145 	}
1146 
1147 	acl = hci_conn_hash_lookup_ba(hdev, ACL_LINK, dst);
1148 	if (!acl) {
1149 		acl = hci_conn_add(hdev, ACL_LINK, dst, HCI_ROLE_MASTER);
1150 		if (!acl)
1151 			return ERR_PTR(-ENOMEM);
1152 	}
1153 
1154 	hci_conn_hold(acl);
1155 
1156 	acl->conn_reason = conn_reason;
1157 	if (acl->state == BT_OPEN || acl->state == BT_CLOSED) {
1158 		acl->sec_level = BT_SECURITY_LOW;
1159 		acl->pending_sec_level = sec_level;
1160 		acl->auth_type = auth_type;
1161 		hci_acl_create_connection(acl);
1162 	}
1163 
1164 	return acl;
1165 }
1166 
1167 struct hci_conn *hci_connect_sco(struct hci_dev *hdev, int type, bdaddr_t *dst,
1168 				 __u16 setting, struct bt_codec *codec)
1169 {
1170 	struct hci_conn *acl;
1171 	struct hci_conn *sco;
1172 
1173 	acl = hci_connect_acl(hdev, dst, BT_SECURITY_LOW, HCI_AT_NO_BONDING,
1174 			      CONN_REASON_SCO_CONNECT);
1175 	if (IS_ERR(acl))
1176 		return acl;
1177 
1178 	sco = hci_conn_hash_lookup_ba(hdev, type, dst);
1179 	if (!sco) {
1180 		sco = hci_conn_add(hdev, type, dst, HCI_ROLE_MASTER);
1181 		if (!sco) {
1182 			hci_conn_drop(acl);
1183 			return ERR_PTR(-ENOMEM);
1184 		}
1185 	}
1186 
1187 	acl->link = sco;
1188 	sco->link = acl;
1189 
1190 	hci_conn_hold(sco);
1191 
1192 	sco->setting = setting;
1193 	sco->codec = *codec;
1194 
1195 	if (acl->state == BT_CONNECTED &&
1196 	    (sco->state == BT_OPEN || sco->state == BT_CLOSED)) {
1197 		set_bit(HCI_CONN_POWER_SAVE, &acl->flags);
1198 		hci_conn_enter_active_mode(acl, BT_POWER_FORCE_ACTIVE_ON);
1199 
1200 		if (test_bit(HCI_CONN_MODE_CHANGE_PEND, &acl->flags)) {
1201 			/* defer SCO setup until mode change completed */
1202 			set_bit(HCI_CONN_SCO_SETUP_PEND, &acl->flags);
1203 			return sco;
1204 		}
1205 
1206 		hci_sco_setup(acl, 0x00);
1207 	}
1208 
1209 	return sco;
1210 }
1211 
1212 /* Check link security requirement */
1213 int hci_conn_check_link_mode(struct hci_conn *conn)
1214 {
1215 	BT_DBG("hcon %p", conn);
1216 
1217 	/* In Secure Connections Only mode, it is required that Secure
1218 	 * Connections is used and the link is encrypted with AES-CCM
1219 	 * using a P-256 authenticated combination key.
1220 	 */
1221 	if (hci_dev_test_flag(conn->hdev, HCI_SC_ONLY)) {
1222 		if (!hci_conn_sc_enabled(conn) ||
1223 		    !test_bit(HCI_CONN_AES_CCM, &conn->flags) ||
1224 		    conn->key_type != HCI_LK_AUTH_COMBINATION_P256)
1225 			return 0;
1226 	}
1227 
1228 	 /* AES encryption is required for Level 4:
1229 	  *
1230 	  * BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 3, Part C
1231 	  * page 1319:
1232 	  *
1233 	  * 128-bit equivalent strength for link and encryption keys
1234 	  * required using FIPS approved algorithms (E0 not allowed,
1235 	  * SAFER+ not allowed, and P-192 not allowed; encryption key
1236 	  * not shortened)
1237 	  */
1238 	if (conn->sec_level == BT_SECURITY_FIPS &&
1239 	    !test_bit(HCI_CONN_AES_CCM, &conn->flags)) {
1240 		bt_dev_err(conn->hdev,
1241 			   "Invalid security: Missing AES-CCM usage");
1242 		return 0;
1243 	}
1244 
1245 	if (hci_conn_ssp_enabled(conn) &&
1246 	    !test_bit(HCI_CONN_ENCRYPT, &conn->flags))
1247 		return 0;
1248 
1249 	return 1;
1250 }
1251 
1252 /* Authenticate remote device */
1253 static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
1254 {
1255 	BT_DBG("hcon %p", conn);
1256 
1257 	if (conn->pending_sec_level > sec_level)
1258 		sec_level = conn->pending_sec_level;
1259 
1260 	if (sec_level > conn->sec_level)
1261 		conn->pending_sec_level = sec_level;
1262 	else if (test_bit(HCI_CONN_AUTH, &conn->flags))
1263 		return 1;
1264 
1265 	/* Make sure we preserve an existing MITM requirement*/
1266 	auth_type |= (conn->auth_type & 0x01);
1267 
1268 	conn->auth_type = auth_type;
1269 
1270 	if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->flags)) {
1271 		struct hci_cp_auth_requested cp;
1272 
1273 		cp.handle = cpu_to_le16(conn->handle);
1274 		hci_send_cmd(conn->hdev, HCI_OP_AUTH_REQUESTED,
1275 			     sizeof(cp), &cp);
1276 
1277 		/* If we're already encrypted set the REAUTH_PEND flag,
1278 		 * otherwise set the ENCRYPT_PEND.
1279 		 */
1280 		if (test_bit(HCI_CONN_ENCRYPT, &conn->flags))
1281 			set_bit(HCI_CONN_REAUTH_PEND, &conn->flags);
1282 		else
1283 			set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags);
1284 	}
1285 
1286 	return 0;
1287 }
1288 
1289 /* Encrypt the link */
1290 static void hci_conn_encrypt(struct hci_conn *conn)
1291 {
1292 	BT_DBG("hcon %p", conn);
1293 
1294 	if (!test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) {
1295 		struct hci_cp_set_conn_encrypt cp;
1296 		cp.handle  = cpu_to_le16(conn->handle);
1297 		cp.encrypt = 0x01;
1298 		hci_send_cmd(conn->hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(cp),
1299 			     &cp);
1300 	}
1301 }
1302 
1303 /* Enable security */
1304 int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type,
1305 		      bool initiator)
1306 {
1307 	BT_DBG("hcon %p", conn);
1308 
1309 	if (conn->type == LE_LINK)
1310 		return smp_conn_security(conn, sec_level);
1311 
1312 	/* For sdp we don't need the link key. */
1313 	if (sec_level == BT_SECURITY_SDP)
1314 		return 1;
1315 
1316 	/* For non 2.1 devices and low security level we don't need the link
1317 	   key. */
1318 	if (sec_level == BT_SECURITY_LOW && !hci_conn_ssp_enabled(conn))
1319 		return 1;
1320 
1321 	/* For other security levels we need the link key. */
1322 	if (!test_bit(HCI_CONN_AUTH, &conn->flags))
1323 		goto auth;
1324 
1325 	/* An authenticated FIPS approved combination key has sufficient
1326 	 * security for security level 4. */
1327 	if (conn->key_type == HCI_LK_AUTH_COMBINATION_P256 &&
1328 	    sec_level == BT_SECURITY_FIPS)
1329 		goto encrypt;
1330 
1331 	/* An authenticated combination key has sufficient security for
1332 	   security level 3. */
1333 	if ((conn->key_type == HCI_LK_AUTH_COMBINATION_P192 ||
1334 	     conn->key_type == HCI_LK_AUTH_COMBINATION_P256) &&
1335 	    sec_level == BT_SECURITY_HIGH)
1336 		goto encrypt;
1337 
1338 	/* An unauthenticated combination key has sufficient security for
1339 	   security level 1 and 2. */
1340 	if ((conn->key_type == HCI_LK_UNAUTH_COMBINATION_P192 ||
1341 	     conn->key_type == HCI_LK_UNAUTH_COMBINATION_P256) &&
1342 	    (sec_level == BT_SECURITY_MEDIUM || sec_level == BT_SECURITY_LOW))
1343 		goto encrypt;
1344 
1345 	/* A combination key has always sufficient security for the security
1346 	   levels 1 or 2. High security level requires the combination key
1347 	   is generated using maximum PIN code length (16).
1348 	   For pre 2.1 units. */
1349 	if (conn->key_type == HCI_LK_COMBINATION &&
1350 	    (sec_level == BT_SECURITY_MEDIUM || sec_level == BT_SECURITY_LOW ||
1351 	     conn->pin_length == 16))
1352 		goto encrypt;
1353 
1354 auth:
1355 	if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags))
1356 		return 0;
1357 
1358 	if (initiator)
1359 		set_bit(HCI_CONN_AUTH_INITIATOR, &conn->flags);
1360 
1361 	if (!hci_conn_auth(conn, sec_level, auth_type))
1362 		return 0;
1363 
1364 encrypt:
1365 	if (test_bit(HCI_CONN_ENCRYPT, &conn->flags)) {
1366 		/* Ensure that the encryption key size has been read,
1367 		 * otherwise stall the upper layer responses.
1368 		 */
1369 		if (!conn->enc_key_size)
1370 			return 0;
1371 
1372 		/* Nothing else needed, all requirements are met */
1373 		return 1;
1374 	}
1375 
1376 	hci_conn_encrypt(conn);
1377 	return 0;
1378 }
1379 EXPORT_SYMBOL(hci_conn_security);
1380 
1381 /* Check secure link requirement */
1382 int hci_conn_check_secure(struct hci_conn *conn, __u8 sec_level)
1383 {
1384 	BT_DBG("hcon %p", conn);
1385 
1386 	/* Accept if non-secure or higher security level is required */
1387 	if (sec_level != BT_SECURITY_HIGH && sec_level != BT_SECURITY_FIPS)
1388 		return 1;
1389 
1390 	/* Accept if secure or higher security level is already present */
1391 	if (conn->sec_level == BT_SECURITY_HIGH ||
1392 	    conn->sec_level == BT_SECURITY_FIPS)
1393 		return 1;
1394 
1395 	/* Reject not secure link */
1396 	return 0;
1397 }
1398 EXPORT_SYMBOL(hci_conn_check_secure);
1399 
1400 /* Switch role */
1401 int hci_conn_switch_role(struct hci_conn *conn, __u8 role)
1402 {
1403 	BT_DBG("hcon %p", conn);
1404 
1405 	if (role == conn->role)
1406 		return 1;
1407 
1408 	if (!test_and_set_bit(HCI_CONN_RSWITCH_PEND, &conn->flags)) {
1409 		struct hci_cp_switch_role cp;
1410 		bacpy(&cp.bdaddr, &conn->dst);
1411 		cp.role = role;
1412 		hci_send_cmd(conn->hdev, HCI_OP_SWITCH_ROLE, sizeof(cp), &cp);
1413 	}
1414 
1415 	return 0;
1416 }
1417 EXPORT_SYMBOL(hci_conn_switch_role);
1418 
1419 /* Enter active mode */
1420 void hci_conn_enter_active_mode(struct hci_conn *conn, __u8 force_active)
1421 {
1422 	struct hci_dev *hdev = conn->hdev;
1423 
1424 	BT_DBG("hcon %p mode %d", conn, conn->mode);
1425 
1426 	if (conn->mode != HCI_CM_SNIFF)
1427 		goto timer;
1428 
1429 	if (!test_bit(HCI_CONN_POWER_SAVE, &conn->flags) && !force_active)
1430 		goto timer;
1431 
1432 	if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->flags)) {
1433 		struct hci_cp_exit_sniff_mode cp;
1434 		cp.handle = cpu_to_le16(conn->handle);
1435 		hci_send_cmd(hdev, HCI_OP_EXIT_SNIFF_MODE, sizeof(cp), &cp);
1436 	}
1437 
1438 timer:
1439 	if (hdev->idle_timeout > 0)
1440 		queue_delayed_work(hdev->workqueue, &conn->idle_work,
1441 				   msecs_to_jiffies(hdev->idle_timeout));
1442 }
1443 
1444 /* Drop all connection on the device */
1445 void hci_conn_hash_flush(struct hci_dev *hdev)
1446 {
1447 	struct hci_conn_hash *h = &hdev->conn_hash;
1448 	struct hci_conn *c, *n;
1449 
1450 	BT_DBG("hdev %s", hdev->name);
1451 
1452 	list_for_each_entry_safe(c, n, &h->list, list) {
1453 		c->state = BT_CLOSED;
1454 
1455 		hci_disconn_cfm(c, HCI_ERROR_LOCAL_HOST_TERM);
1456 		hci_conn_del(c);
1457 	}
1458 }
1459 
1460 /* Check pending connect attempts */
1461 void hci_conn_check_pending(struct hci_dev *hdev)
1462 {
1463 	struct hci_conn *conn;
1464 
1465 	BT_DBG("hdev %s", hdev->name);
1466 
1467 	hci_dev_lock(hdev);
1468 
1469 	conn = hci_conn_hash_lookup_state(hdev, ACL_LINK, BT_CONNECT2);
1470 	if (conn)
1471 		hci_acl_create_connection(conn);
1472 
1473 	hci_dev_unlock(hdev);
1474 }
1475 
1476 static u32 get_link_mode(struct hci_conn *conn)
1477 {
1478 	u32 link_mode = 0;
1479 
1480 	if (conn->role == HCI_ROLE_MASTER)
1481 		link_mode |= HCI_LM_MASTER;
1482 
1483 	if (test_bit(HCI_CONN_ENCRYPT, &conn->flags))
1484 		link_mode |= HCI_LM_ENCRYPT;
1485 
1486 	if (test_bit(HCI_CONN_AUTH, &conn->flags))
1487 		link_mode |= HCI_LM_AUTH;
1488 
1489 	if (test_bit(HCI_CONN_SECURE, &conn->flags))
1490 		link_mode |= HCI_LM_SECURE;
1491 
1492 	if (test_bit(HCI_CONN_FIPS, &conn->flags))
1493 		link_mode |= HCI_LM_FIPS;
1494 
1495 	return link_mode;
1496 }
1497 
1498 int hci_get_conn_list(void __user *arg)
1499 {
1500 	struct hci_conn *c;
1501 	struct hci_conn_list_req req, *cl;
1502 	struct hci_conn_info *ci;
1503 	struct hci_dev *hdev;
1504 	int n = 0, size, err;
1505 
1506 	if (copy_from_user(&req, arg, sizeof(req)))
1507 		return -EFAULT;
1508 
1509 	if (!req.conn_num || req.conn_num > (PAGE_SIZE * 2) / sizeof(*ci))
1510 		return -EINVAL;
1511 
1512 	size = sizeof(req) + req.conn_num * sizeof(*ci);
1513 
1514 	cl = kmalloc(size, GFP_KERNEL);
1515 	if (!cl)
1516 		return -ENOMEM;
1517 
1518 	hdev = hci_dev_get(req.dev_id);
1519 	if (!hdev) {
1520 		kfree(cl);
1521 		return -ENODEV;
1522 	}
1523 
1524 	ci = cl->conn_info;
1525 
1526 	hci_dev_lock(hdev);
1527 	list_for_each_entry(c, &hdev->conn_hash.list, list) {
1528 		bacpy(&(ci + n)->bdaddr, &c->dst);
1529 		(ci + n)->handle = c->handle;
1530 		(ci + n)->type  = c->type;
1531 		(ci + n)->out   = c->out;
1532 		(ci + n)->state = c->state;
1533 		(ci + n)->link_mode = get_link_mode(c);
1534 		if (++n >= req.conn_num)
1535 			break;
1536 	}
1537 	hci_dev_unlock(hdev);
1538 
1539 	cl->dev_id = hdev->id;
1540 	cl->conn_num = n;
1541 	size = sizeof(req) + n * sizeof(*ci);
1542 
1543 	hci_dev_put(hdev);
1544 
1545 	err = copy_to_user(arg, cl, size);
1546 	kfree(cl);
1547 
1548 	return err ? -EFAULT : 0;
1549 }
1550 
1551 int hci_get_conn_info(struct hci_dev *hdev, void __user *arg)
1552 {
1553 	struct hci_conn_info_req req;
1554 	struct hci_conn_info ci;
1555 	struct hci_conn *conn;
1556 	char __user *ptr = arg + sizeof(req);
1557 
1558 	if (copy_from_user(&req, arg, sizeof(req)))
1559 		return -EFAULT;
1560 
1561 	hci_dev_lock(hdev);
1562 	conn = hci_conn_hash_lookup_ba(hdev, req.type, &req.bdaddr);
1563 	if (conn) {
1564 		bacpy(&ci.bdaddr, &conn->dst);
1565 		ci.handle = conn->handle;
1566 		ci.type  = conn->type;
1567 		ci.out   = conn->out;
1568 		ci.state = conn->state;
1569 		ci.link_mode = get_link_mode(conn);
1570 	}
1571 	hci_dev_unlock(hdev);
1572 
1573 	if (!conn)
1574 		return -ENOENT;
1575 
1576 	return copy_to_user(ptr, &ci, sizeof(ci)) ? -EFAULT : 0;
1577 }
1578 
1579 int hci_get_auth_info(struct hci_dev *hdev, void __user *arg)
1580 {
1581 	struct hci_auth_info_req req;
1582 	struct hci_conn *conn;
1583 
1584 	if (copy_from_user(&req, arg, sizeof(req)))
1585 		return -EFAULT;
1586 
1587 	hci_dev_lock(hdev);
1588 	conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &req.bdaddr);
1589 	if (conn)
1590 		req.type = conn->auth_type;
1591 	hci_dev_unlock(hdev);
1592 
1593 	if (!conn)
1594 		return -ENOENT;
1595 
1596 	return copy_to_user(arg, &req, sizeof(req)) ? -EFAULT : 0;
1597 }
1598 
1599 struct hci_chan *hci_chan_create(struct hci_conn *conn)
1600 {
1601 	struct hci_dev *hdev = conn->hdev;
1602 	struct hci_chan *chan;
1603 
1604 	BT_DBG("%s hcon %p", hdev->name, conn);
1605 
1606 	if (test_bit(HCI_CONN_DROP, &conn->flags)) {
1607 		BT_DBG("Refusing to create new hci_chan");
1608 		return NULL;
1609 	}
1610 
1611 	chan = kzalloc(sizeof(*chan), GFP_KERNEL);
1612 	if (!chan)
1613 		return NULL;
1614 
1615 	chan->conn = hci_conn_get(conn);
1616 	skb_queue_head_init(&chan->data_q);
1617 	chan->state = BT_CONNECTED;
1618 
1619 	list_add_rcu(&chan->list, &conn->chan_list);
1620 
1621 	return chan;
1622 }
1623 
1624 void hci_chan_del(struct hci_chan *chan)
1625 {
1626 	struct hci_conn *conn = chan->conn;
1627 	struct hci_dev *hdev = conn->hdev;
1628 
1629 	BT_DBG("%s hcon %p chan %p", hdev->name, conn, chan);
1630 
1631 	list_del_rcu(&chan->list);
1632 
1633 	synchronize_rcu();
1634 
1635 	/* Prevent new hci_chan's to be created for this hci_conn */
1636 	set_bit(HCI_CONN_DROP, &conn->flags);
1637 
1638 	hci_conn_put(conn);
1639 
1640 	skb_queue_purge(&chan->data_q);
1641 	kfree(chan);
1642 }
1643 
1644 void hci_chan_list_flush(struct hci_conn *conn)
1645 {
1646 	struct hci_chan *chan, *n;
1647 
1648 	BT_DBG("hcon %p", conn);
1649 
1650 	list_for_each_entry_safe(chan, n, &conn->chan_list, list)
1651 		hci_chan_del(chan);
1652 }
1653 
1654 static struct hci_chan *__hci_chan_lookup_handle(struct hci_conn *hcon,
1655 						 __u16 handle)
1656 {
1657 	struct hci_chan *hchan;
1658 
1659 	list_for_each_entry(hchan, &hcon->chan_list, list) {
1660 		if (hchan->handle == handle)
1661 			return hchan;
1662 	}
1663 
1664 	return NULL;
1665 }
1666 
1667 struct hci_chan *hci_chan_lookup_handle(struct hci_dev *hdev, __u16 handle)
1668 {
1669 	struct hci_conn_hash *h = &hdev->conn_hash;
1670 	struct hci_conn *hcon;
1671 	struct hci_chan *hchan = NULL;
1672 
1673 	rcu_read_lock();
1674 
1675 	list_for_each_entry_rcu(hcon, &h->list, list) {
1676 		hchan = __hci_chan_lookup_handle(hcon, handle);
1677 		if (hchan)
1678 			break;
1679 	}
1680 
1681 	rcu_read_unlock();
1682 
1683 	return hchan;
1684 }
1685 
1686 u32 hci_conn_get_phy(struct hci_conn *conn)
1687 {
1688 	u32 phys = 0;
1689 
1690 	/* BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 2, Part B page 471:
1691 	 * Table 6.2: Packets defined for synchronous, asynchronous, and
1692 	 * CPB logical transport types.
1693 	 */
1694 	switch (conn->type) {
1695 	case SCO_LINK:
1696 		/* SCO logical transport (1 Mb/s):
1697 		 * HV1, HV2, HV3 and DV.
1698 		 */
1699 		phys |= BT_PHY_BR_1M_1SLOT;
1700 
1701 		break;
1702 
1703 	case ACL_LINK:
1704 		/* ACL logical transport (1 Mb/s) ptt=0:
1705 		 * DH1, DM3, DH3, DM5 and DH5.
1706 		 */
1707 		phys |= BT_PHY_BR_1M_1SLOT;
1708 
1709 		if (conn->pkt_type & (HCI_DM3 | HCI_DH3))
1710 			phys |= BT_PHY_BR_1M_3SLOT;
1711 
1712 		if (conn->pkt_type & (HCI_DM5 | HCI_DH5))
1713 			phys |= BT_PHY_BR_1M_5SLOT;
1714 
1715 		/* ACL logical transport (2 Mb/s) ptt=1:
1716 		 * 2-DH1, 2-DH3 and 2-DH5.
1717 		 */
1718 		if (!(conn->pkt_type & HCI_2DH1))
1719 			phys |= BT_PHY_EDR_2M_1SLOT;
1720 
1721 		if (!(conn->pkt_type & HCI_2DH3))
1722 			phys |= BT_PHY_EDR_2M_3SLOT;
1723 
1724 		if (!(conn->pkt_type & HCI_2DH5))
1725 			phys |= BT_PHY_EDR_2M_5SLOT;
1726 
1727 		/* ACL logical transport (3 Mb/s) ptt=1:
1728 		 * 3-DH1, 3-DH3 and 3-DH5.
1729 		 */
1730 		if (!(conn->pkt_type & HCI_3DH1))
1731 			phys |= BT_PHY_EDR_3M_1SLOT;
1732 
1733 		if (!(conn->pkt_type & HCI_3DH3))
1734 			phys |= BT_PHY_EDR_3M_3SLOT;
1735 
1736 		if (!(conn->pkt_type & HCI_3DH5))
1737 			phys |= BT_PHY_EDR_3M_5SLOT;
1738 
1739 		break;
1740 
1741 	case ESCO_LINK:
1742 		/* eSCO logical transport (1 Mb/s): EV3, EV4 and EV5 */
1743 		phys |= BT_PHY_BR_1M_1SLOT;
1744 
1745 		if (!(conn->pkt_type & (ESCO_EV4 | ESCO_EV5)))
1746 			phys |= BT_PHY_BR_1M_3SLOT;
1747 
1748 		/* eSCO logical transport (2 Mb/s): 2-EV3, 2-EV5 */
1749 		if (!(conn->pkt_type & ESCO_2EV3))
1750 			phys |= BT_PHY_EDR_2M_1SLOT;
1751 
1752 		if (!(conn->pkt_type & ESCO_2EV5))
1753 			phys |= BT_PHY_EDR_2M_3SLOT;
1754 
1755 		/* eSCO logical transport (3 Mb/s): 3-EV3, 3-EV5 */
1756 		if (!(conn->pkt_type & ESCO_3EV3))
1757 			phys |= BT_PHY_EDR_3M_1SLOT;
1758 
1759 		if (!(conn->pkt_type & ESCO_3EV5))
1760 			phys |= BT_PHY_EDR_3M_3SLOT;
1761 
1762 		break;
1763 
1764 	case LE_LINK:
1765 		if (conn->le_tx_phy & HCI_LE_SET_PHY_1M)
1766 			phys |= BT_PHY_LE_1M_TX;
1767 
1768 		if (conn->le_rx_phy & HCI_LE_SET_PHY_1M)
1769 			phys |= BT_PHY_LE_1M_RX;
1770 
1771 		if (conn->le_tx_phy & HCI_LE_SET_PHY_2M)
1772 			phys |= BT_PHY_LE_2M_TX;
1773 
1774 		if (conn->le_rx_phy & HCI_LE_SET_PHY_2M)
1775 			phys |= BT_PHY_LE_2M_RX;
1776 
1777 		if (conn->le_tx_phy & HCI_LE_SET_PHY_CODED)
1778 			phys |= BT_PHY_LE_CODED_TX;
1779 
1780 		if (conn->le_rx_phy & HCI_LE_SET_PHY_CODED)
1781 			phys |= BT_PHY_LE_CODED_RX;
1782 
1783 		break;
1784 	}
1785 
1786 	return phys;
1787 }
1788