xref: /netbsd-src/sys/netbt/hci_link.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: hci_link.c,v 1.20 2008/04/24 11:38:37 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 2005 Iain Hibbert.
5  * Copyright (c) 2006 Itronix Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of Itronix Inc. may not be used to endorse
17  *    or promote products derived from this software without specific
18  *    prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
24  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27  * ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __KERNEL_RCSID(0, "$NetBSD: hci_link.c,v 1.20 2008/04/24 11:38:37 ad Exp $");
35 
36 #include <sys/param.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/proc.h>
41 #include <sys/queue.h>
42 #include <sys/systm.h>
43 
44 #include <netbt/bluetooth.h>
45 #include <netbt/hci.h>
46 #include <netbt/l2cap.h>
47 #include <netbt/sco.h>
48 
49 /*******************************************************************************
50  *
51  *	HCI ACL Connections
52  */
53 
54 /*
55  * Automatically expire unused ACL connections after this number of
56  * seconds (if zero, do not expire unused connections) [sysctl]
57  */
58 int hci_acl_expiry = 10;	/* seconds */
59 
60 /*
61  * hci_acl_open(unit, bdaddr)
62  *
63  * open ACL connection to remote bdaddr. Only one ACL connection is permitted
64  * between any two Bluetooth devices, so we look for an existing one before
65  * trying to start a new one.
66  */
67 struct hci_link *
68 hci_acl_open(struct hci_unit *unit, bdaddr_t *bdaddr)
69 {
70 	struct hci_link *link;
71 	struct hci_memo *memo;
72 	hci_create_con_cp cp;
73 	int err;
74 
75 	KASSERT(unit != NULL);
76 	KASSERT(bdaddr != NULL);
77 
78 	link = hci_link_lookup_bdaddr(unit, bdaddr, HCI_LINK_ACL);
79 	if (link == NULL) {
80 		link = hci_link_alloc(unit, bdaddr, HCI_LINK_ACL);
81 		if (link == NULL)
82 			return NULL;
83 	}
84 
85 	switch(link->hl_state) {
86 	case HCI_LINK_CLOSED:
87 		/*
88 		 * open connection to remote device
89 		 */
90 		memset(&cp, 0, sizeof(cp));
91 		bdaddr_copy(&cp.bdaddr, bdaddr);
92 		cp.pkt_type = htole16(unit->hci_packet_type);
93 
94 		memo = hci_memo_find(unit, bdaddr);
95 		if (memo != NULL) {
96 			cp.page_scan_rep_mode = memo->page_scan_rep_mode;
97 			cp.page_scan_mode = memo->page_scan_mode;
98 			cp.clock_offset = memo->clock_offset;
99 		}
100 
101 		if (unit->hci_link_policy & HCI_LINK_POLICY_ENABLE_ROLE_SWITCH)
102 			cp.accept_role_switch = 1;
103 
104 		err = hci_send_cmd(unit, HCI_CMD_CREATE_CON, &cp, sizeof(cp));
105 		if (err) {
106 			hci_link_free(link, err);
107 			return NULL;
108 		}
109 
110 		link->hl_flags |= HCI_LINK_CREATE_CON;
111 		link->hl_state = HCI_LINK_WAIT_CONNECT;
112 		break;
113 
114 	case HCI_LINK_WAIT_CONNECT:
115 	case HCI_LINK_WAIT_AUTH:
116 	case HCI_LINK_WAIT_ENCRYPT:
117 	case HCI_LINK_WAIT_SECURE:
118 		/*
119 		 * somebody else already trying to connect, we just
120 		 * sit on the bench with them..
121 		 */
122 		break;
123 
124 	case HCI_LINK_OPEN:
125 		/*
126 		 * If already open, halt any expiry timeouts. We dont need
127 		 * to care about already invoking timeouts since refcnt >0
128 		 * will keep the link alive.
129 		 */
130 		callout_stop(&link->hl_expire);
131 		break;
132 
133 	default:
134 		UNKNOWN(link->hl_state);
135 		return NULL;
136 	}
137 
138 	/* open */
139 	link->hl_refcnt++;
140 
141 	return link;
142 }
143 
144 /*
145  * Close ACL connection. When there are no more references to this link,
146  * we can either close it down or schedule a delayed closedown.
147  */
148 void
149 hci_acl_close(struct hci_link *link, int err)
150 {
151 
152 	KASSERT(link != NULL);
153 
154 	if (--link->hl_refcnt == 0) {
155 		if (link->hl_state == HCI_LINK_CLOSED)
156 			hci_link_free(link, err);
157 		else if (hci_acl_expiry > 0)
158 			callout_schedule(&link->hl_expire, hci_acl_expiry * hz);
159 	}
160 }
161 
162 /*
163  * Incoming ACL connection.
164  *
165  * For now, we accept all connections but it would be better to check
166  * the L2CAP listen list and only accept when there is a listener
167  * available.
168  *
169  * There should not be a link to the same bdaddr already, we check
170  * anyway though its left unhandled for now.
171  */
172 struct hci_link *
173 hci_acl_newconn(struct hci_unit *unit, bdaddr_t *bdaddr)
174 {
175 	struct hci_link *link;
176 
177 	link = hci_link_lookup_bdaddr(unit, bdaddr, HCI_LINK_ACL);
178 	if (link != NULL)
179 		return NULL;
180 
181 	link = hci_link_alloc(unit, bdaddr, HCI_LINK_ACL);
182 	if (link != NULL) {
183 		link->hl_state = HCI_LINK_WAIT_CONNECT;
184 
185 		if (hci_acl_expiry > 0)
186 			callout_schedule(&link->hl_expire, hci_acl_expiry * hz);
187 	}
188 
189 	return link;
190 }
191 
192 void
193 hci_acl_timeout(void *arg)
194 {
195 	struct hci_link *link = arg;
196 	hci_discon_cp cp;
197 	int err;
198 
199 	mutex_enter(bt_lock);
200 	callout_ack(&link->hl_expire);
201 
202 	if (link->hl_refcnt > 0)
203 		goto out;
204 
205 	DPRINTF("link #%d expired\n", link->hl_handle);
206 
207 	switch (link->hl_state) {
208 	case HCI_LINK_CLOSED:
209 	case HCI_LINK_WAIT_CONNECT:
210 		hci_link_free(link, ECONNRESET);
211 		break;
212 
213 	case HCI_LINK_WAIT_AUTH:
214 	case HCI_LINK_WAIT_ENCRYPT:
215 	case HCI_LINK_WAIT_SECURE:
216 	case HCI_LINK_OPEN:
217 		cp.con_handle = htole16(link->hl_handle);
218 		cp.reason = 0x13; /* "Remote User Terminated Connection" */
219 
220 		err = hci_send_cmd(link->hl_unit, HCI_CMD_DISCONNECT,
221 					&cp, sizeof(cp));
222 
223 		if (err) {
224 			DPRINTF("error %d sending HCI_CMD_DISCONNECT\n",
225 			    err);
226 		}
227 
228 		break;
229 
230 	default:
231 		UNKNOWN(link->hl_state);
232 		break;
233 	}
234 
235 out:
236 	mutex_exit(bt_lock);
237 }
238 
239 /*
240  * Initiate any Link Mode change requests.
241  */
242 int
243 hci_acl_setmode(struct hci_link *link)
244 {
245 	int err;
246 
247 	KASSERT(link != NULL);
248 	KASSERT(link->hl_unit != NULL);
249 
250 	if (link->hl_state != HCI_LINK_OPEN)
251 		return EINPROGRESS;
252 
253 	if ((link->hl_flags & HCI_LINK_AUTH_REQ)
254 	    && !(link->hl_flags & HCI_LINK_AUTH)) {
255 		hci_auth_req_cp cp;
256 
257 		DPRINTF("requesting auth for handle #%d\n",
258 			link->hl_handle);
259 
260 		link->hl_state = HCI_LINK_WAIT_AUTH;
261 		cp.con_handle = htole16(link->hl_handle);
262 		err = hci_send_cmd(link->hl_unit, HCI_CMD_AUTH_REQ,
263 				   &cp, sizeof(cp));
264 
265 		return (err == 0 ? EINPROGRESS : err);
266 	}
267 
268 	if ((link->hl_flags & HCI_LINK_ENCRYPT_REQ)
269 	    && !(link->hl_flags & HCI_LINK_ENCRYPT)) {
270 		hci_set_con_encryption_cp cp;
271 
272 		/* XXX we should check features for encryption capability */
273 
274 		DPRINTF("requesting encryption for handle #%d\n",
275 			link->hl_handle);
276 
277 		link->hl_state = HCI_LINK_WAIT_ENCRYPT;
278 		cp.con_handle = htole16(link->hl_handle);
279 		cp.encryption_enable = 0x01;
280 
281 		err = hci_send_cmd(link->hl_unit, HCI_CMD_SET_CON_ENCRYPTION,
282 				   &cp, sizeof(cp));
283 
284 		return (err == 0 ? EINPROGRESS : err);
285 	}
286 
287 	if ((link->hl_flags & HCI_LINK_SECURE_REQ)) {
288 		hci_change_con_link_key_cp cp;
289 
290 		/* always change link key for SECURE requests */
291 		link->hl_flags &= ~HCI_LINK_SECURE;
292 
293 		DPRINTF("changing link key for handle #%d\n",
294 			link->hl_handle);
295 
296 		link->hl_state = HCI_LINK_WAIT_SECURE;
297 		cp.con_handle = htole16(link->hl_handle);
298 
299 		err = hci_send_cmd(link->hl_unit, HCI_CMD_CHANGE_CON_LINK_KEY,
300 				   &cp, sizeof(cp));
301 
302 		return (err == 0 ? EINPROGRESS : err);
303 	}
304 
305 	return 0;
306 }
307 
308 /*
309  * Link Mode changed.
310  *
311  * This is called from event handlers when the mode change
312  * is complete. We notify upstream and restart the link.
313  */
314 void
315 hci_acl_linkmode(struct hci_link *link)
316 {
317 	struct l2cap_channel *chan, *next;
318 	int err, mode = 0;
319 
320 	DPRINTF("handle #%d, auth %s, encrypt %s, secure %s\n",
321 		link->hl_handle,
322 		(link->hl_flags & HCI_LINK_AUTH ? "on" : "off"),
323 		(link->hl_flags & HCI_LINK_ENCRYPT ? "on" : "off"),
324 		(link->hl_flags & HCI_LINK_SECURE ? "on" : "off"));
325 
326 	if (link->hl_flags & HCI_LINK_AUTH)
327 		mode |= L2CAP_LM_AUTH;
328 
329 	if (link->hl_flags & HCI_LINK_ENCRYPT)
330 		mode |= L2CAP_LM_ENCRYPT;
331 
332 	if (link->hl_flags & HCI_LINK_SECURE)
333 		mode |= L2CAP_LM_SECURE;
334 
335 	/*
336 	 * The link state will only be OPEN here if the mode change
337 	 * was successful. So, we can proceed with L2CAP connections,
338 	 * or notify already establshed channels, to allow any that
339 	 * are dissatisfied to disconnect before we restart.
340 	 */
341 	next = LIST_FIRST(&l2cap_active_list);
342 	while ((chan = next) != NULL) {
343 		next = LIST_NEXT(chan, lc_ncid);
344 
345 		if (chan->lc_link != link)
346 			continue;
347 
348 		switch(chan->lc_state) {
349 		case L2CAP_WAIT_SEND_CONNECT_REQ: /* we are connecting */
350 			if ((mode & chan->lc_mode) != chan->lc_mode) {
351 				l2cap_close(chan, ECONNABORTED);
352 				break;
353 			}
354 
355 			chan->lc_state = L2CAP_WAIT_RECV_CONNECT_RSP;
356 			err = l2cap_send_connect_req(chan);
357 			if (err) {
358 				l2cap_close(chan, err);
359 				break;
360 			}
361 			break;
362 
363 		case L2CAP_WAIT_SEND_CONNECT_RSP: /* they are connecting */
364 			if ((mode & chan->lc_mode) != chan->lc_mode) {
365 				l2cap_send_connect_rsp(link, chan->lc_ident,
366 							0, chan->lc_rcid,
367 							L2CAP_SECURITY_BLOCK);
368 
369 				l2cap_close(chan, ECONNABORTED);
370 				break;
371 			}
372 
373 			l2cap_send_connect_rsp(link, chan->lc_ident,
374 						chan->lc_lcid, chan->lc_rcid,
375 						L2CAP_SUCCESS);
376 
377 			chan->lc_state = L2CAP_WAIT_CONFIG;
378 			chan->lc_flags |= (L2CAP_WAIT_CONFIG_RSP | L2CAP_WAIT_CONFIG_REQ);
379 			err = l2cap_send_config_req(chan);
380 			if (err) {
381 				l2cap_close(chan, err);
382 				break;
383 			}
384 			break;
385 
386 		case L2CAP_WAIT_RECV_CONNECT_RSP:
387 		case L2CAP_WAIT_CONFIG:
388 		case L2CAP_OPEN: /* already established */
389 			(*chan->lc_proto->linkmode)(chan->lc_upper, mode);
390 			break;
391 
392 		default:
393 			break;
394 		}
395 	}
396 
397 	link->hl_state = HCI_LINK_OPEN;
398 	hci_acl_start(link);
399 }
400 
401 /*
402  * Receive ACL Data
403  *
404  * we accumulate packet fragments on the hci_link structure
405  * until a full L2CAP frame is ready, then send it on.
406  */
407 void
408 hci_acl_recv(struct mbuf *m, struct hci_unit *unit)
409 {
410 	struct hci_link *link;
411 	hci_acldata_hdr_t hdr;
412 	uint16_t handle, want;
413 	int pb, got;
414 
415 	KASSERT(m != NULL);
416 	KASSERT(unit != NULL);
417 
418 	KASSERT(m->m_pkthdr.len >= sizeof(hdr));
419 	m_copydata(m, 0, sizeof(hdr), &hdr);
420 	m_adj(m, sizeof(hdr));
421 
422 #ifdef DIAGNOSTIC
423 	if (hdr.type != HCI_ACL_DATA_PKT) {
424 		aprint_error_dev(unit->hci_dev, "bad ACL packet type\n");
425 		goto bad;
426 	}
427 
428 	if (m->m_pkthdr.len != le16toh(hdr.length)) {
429 		aprint_error_dev(unit->hci_dev,
430 		    "bad ACL packet length (%d != %d)\n",
431 		    m->m_pkthdr.len, le16toh(hdr.length));
432 		goto bad;
433 	}
434 #endif
435 
436 	hdr.length = le16toh(hdr.length);
437 	hdr.con_handle = le16toh(hdr.con_handle);
438 	handle = HCI_CON_HANDLE(hdr.con_handle);
439 	pb = HCI_PB_FLAG(hdr.con_handle);
440 
441 	link = hci_link_lookup_handle(unit, handle);
442 	if (link == NULL) {
443 		hci_discon_cp cp;
444 
445 		DPRINTF("%s: dumping packet for unknown handle #%d\n",
446 			device_xname(unit->hci_dev), handle);
447 
448 		/*
449 		 * There is no way to find out what this connection handle is
450 		 * for, just get rid of it. This may happen, if a USB dongle
451 		 * is plugged into a self powered hub and does not reset when
452 		 * the system is shut down.
453 		 */
454 		cp.con_handle = htole16(handle);
455 		cp.reason = 0x13; /* "Remote User Terminated Connection" */
456 		hci_send_cmd(unit, HCI_CMD_DISCONNECT, &cp, sizeof(cp));
457 		goto bad;
458 	}
459 
460 	switch (pb) {
461 	case HCI_PACKET_START:
462 		if (link->hl_rxp != NULL)
463 			aprint_error_dev(unit->hci_dev,
464 			    "dropped incomplete ACL packet\n");
465 
466 		if (m->m_pkthdr.len < sizeof(l2cap_hdr_t)) {
467 			aprint_error_dev(unit->hci_dev, "short ACL packet\n");
468 			goto bad;
469 		}
470 
471 		link->hl_rxp = m;
472 		got = m->m_pkthdr.len;
473 		break;
474 
475 	case HCI_PACKET_FRAGMENT:
476 		if (link->hl_rxp == NULL) {
477 			aprint_error_dev(unit->hci_dev,
478 			    "unexpected packet fragment\n");
479 
480 			goto bad;
481 		}
482 
483 		got = m->m_pkthdr.len + link->hl_rxp->m_pkthdr.len;
484 		m_cat(link->hl_rxp, m);
485 		m = link->hl_rxp;
486 		m->m_pkthdr.len = got;
487 		break;
488 
489 	default:
490 		aprint_error_dev(unit->hci_dev, "unknown packet type\n");
491 		goto bad;
492 	}
493 
494 	m_copydata(m, 0, sizeof(want), &want);
495 	want = le16toh(want) + sizeof(l2cap_hdr_t) - got;
496 
497 	if (want > 0)
498 		return;
499 
500 	link->hl_rxp = NULL;
501 
502 	if (want == 0) {
503 		l2cap_recv_frame(m, link);
504 		return;
505 	}
506 
507 bad:
508 	m_freem(m);
509 }
510 
511 /*
512  * Send ACL data on link
513  *
514  * We must fragment packets into chunks of less than unit->hci_max_acl_size and
515  * prepend a relevant ACL header to each fragment. We keep a PDU structure
516  * attached to the link, so that completed fragments can be marked off and
517  * more data requested from above once the PDU is sent.
518  */
519 int
520 hci_acl_send(struct mbuf *m, struct hci_link *link,
521 		struct l2cap_channel *chan)
522 {
523 	struct l2cap_pdu *pdu;
524 	struct mbuf *n = NULL;
525 	int plen, mlen, num = 0;
526 
527 	KASSERT(link != NULL);
528 	KASSERT(m != NULL);
529 	KASSERT(m->m_flags & M_PKTHDR);
530 	KASSERT(m->m_pkthdr.len > 0);
531 
532 	if (link->hl_state == HCI_LINK_CLOSED) {
533 		m_freem(m);
534 		return ENETDOWN;
535 	}
536 
537 	pdu = pool_get(&l2cap_pdu_pool, PR_NOWAIT);
538 	if (pdu == NULL)
539 		goto nomem;
540 
541 	pdu->lp_chan = chan;
542 	pdu->lp_pending = 0;
543 	MBUFQ_INIT(&pdu->lp_data);
544 
545 	plen = m->m_pkthdr.len;
546 	mlen = link->hl_unit->hci_max_acl_size;
547 
548 	DPRINTFN(5, "%s: handle #%d, plen = %d, max = %d\n",
549 		device_xname(link->hl_unit->hci_dev), link->hl_handle, plen, mlen);
550 
551 	while (plen > 0) {
552 		if (plen > mlen) {
553 			n = m_split(m, mlen, M_DONTWAIT);
554 			if (n == NULL)
555 				goto nomem;
556 		} else {
557 			mlen = plen;
558 		}
559 
560 		if (num++ == 0)
561 			m->m_flags |= M_PROTO1;	/* tag first fragment */
562 
563 		DPRINTFN(10, "chunk of %d (plen = %d) bytes\n", mlen, plen);
564 		MBUFQ_ENQUEUE(&pdu->lp_data, m);
565 		m = n;
566 		plen -= mlen;
567 	}
568 
569 	TAILQ_INSERT_TAIL(&link->hl_txq, pdu, lp_next);
570 	link->hl_txqlen += num;
571 
572 	hci_acl_start(link);
573 
574 	return 0;
575 
576 nomem:
577 	if (m) m_freem(m);
578 	if (pdu) {
579 		MBUFQ_DRAIN(&pdu->lp_data);
580 		pool_put(&l2cap_pdu_pool, pdu);
581 	}
582 
583 	return ENOMEM;
584 }
585 
586 /*
587  * Start sending ACL data on link.
588  *
589  *	This is called when the queue may need restarting: as new data
590  * is queued, after link mode changes have completed, or when device
591  * buffers have cleared.
592  *
593  *	We may use all the available packet slots. The reason that we add
594  * the ACL encapsulation here rather than in hci_acl_send() is that L2CAP
595  * signal packets may be queued before the handle is given to us..
596  */
597 void
598 hci_acl_start(struct hci_link *link)
599 {
600 	struct hci_unit *unit;
601 	hci_acldata_hdr_t *hdr;
602 	struct l2cap_pdu *pdu;
603 	struct mbuf *m;
604 	uint16_t handle;
605 
606 	KASSERT(link != NULL);
607 
608 	unit = link->hl_unit;
609 	KASSERT(unit != NULL);
610 
611 	/* this is mainly to block ourselves (below) */
612 	if (link->hl_state != HCI_LINK_OPEN)
613 		return;
614 
615 	if (link->hl_txqlen == 0 || unit->hci_num_acl_pkts == 0)
616 		return;
617 
618 	/* find first PDU with data to send */
619 	pdu = TAILQ_FIRST(&link->hl_txq);
620 	for (;;) {
621 		if (pdu == NULL)
622 			return;
623 
624 		if (MBUFQ_FIRST(&pdu->lp_data) != NULL)
625 			break;
626 
627 		pdu = TAILQ_NEXT(pdu, lp_next);
628 	}
629 
630 	while (unit->hci_num_acl_pkts > 0) {
631 		MBUFQ_DEQUEUE(&pdu->lp_data, m);
632 		KASSERT(m != NULL);
633 
634 		if (m->m_flags & M_PROTO1)
635 			handle = HCI_MK_CON_HANDLE(link->hl_handle,
636 						HCI_PACKET_START, 0);
637 		else
638 			handle = HCI_MK_CON_HANDLE(link->hl_handle,
639 						HCI_PACKET_FRAGMENT, 0);
640 
641 		M_PREPEND(m, sizeof(*hdr), M_DONTWAIT);
642 		if (m == NULL)
643 			break;
644 
645 		hdr = mtod(m, hci_acldata_hdr_t *);
646 		hdr->type = HCI_ACL_DATA_PKT;
647 		hdr->con_handle = htole16(handle);
648 		hdr->length = htole16(m->m_pkthdr.len - sizeof(*hdr));
649 
650 		link->hl_txqlen--;
651 		pdu->lp_pending++;
652 
653 		hci_output_acl(unit, m);
654 
655 		if (MBUFQ_FIRST(&pdu->lp_data) == NULL) {
656 			if (pdu->lp_chan) {
657 				/*
658 				 * This should enable streaming of PDUs - when
659 				 * we have placed all the fragments on the acl
660 				 * output queue, we trigger the L2CAP layer to
661 				 * send us down one more. Use a false state so
662 				 * we dont run into ourselves coming back from
663 				 * the future..
664 				 */
665 				link->hl_state = HCI_LINK_BLOCK;
666 				l2cap_start(pdu->lp_chan);
667 				link->hl_state = HCI_LINK_OPEN;
668 			}
669 
670 			pdu = TAILQ_NEXT(pdu, lp_next);
671 			if (pdu == NULL)
672 				break;
673 		}
674 	}
675 
676 	/*
677 	 * We had our turn now, move to the back of the queue to let
678 	 * other links have a go at the output buffers..
679 	 */
680 	if (TAILQ_NEXT(link, hl_next)) {
681 		TAILQ_REMOVE(&unit->hci_links, link, hl_next);
682 		TAILQ_INSERT_TAIL(&unit->hci_links, link, hl_next);
683 	}
684 }
685 
686 /*
687  * Confirm ACL packets cleared from Controller buffers. We scan our PDU
688  * list to clear pending fragments and signal upstream for more data
689  * when a PDU is complete.
690  */
691 void
692 hci_acl_complete(struct hci_link *link, int num)
693 {
694 	struct l2cap_pdu *pdu;
695 	struct l2cap_channel *chan;
696 
697 	DPRINTFN(5, "handle #%d (%d)\n", link->hl_handle, num);
698 
699 	while (num > 0) {
700 		pdu = TAILQ_FIRST(&link->hl_txq);
701 		if (pdu == NULL) {
702 			aprint_error_dev(link->hl_unit->hci_dev,
703 			    "%d packets completed on handle #%x but none pending!\n",
704 			    num, link->hl_handle);
705 
706 			return;
707 		}
708 
709 		if (num >= pdu->lp_pending) {
710 			num -= pdu->lp_pending;
711 			pdu->lp_pending = 0;
712 
713 			if (MBUFQ_FIRST(&pdu->lp_data) == NULL) {
714 				TAILQ_REMOVE(&link->hl_txq, pdu, lp_next);
715 				chan = pdu->lp_chan;
716 				if (chan != NULL) {
717 					chan->lc_pending--;
718 					(*chan->lc_proto->complete)
719 							(chan->lc_upper, 1);
720 
721 					if (chan->lc_pending == 0)
722 						l2cap_start(chan);
723 				}
724 
725 				pool_put(&l2cap_pdu_pool, pdu);
726 			}
727 		} else {
728 			pdu->lp_pending -= num;
729 			num = 0;
730 		}
731 	}
732 }
733 
734 /*******************************************************************************
735  *
736  *	HCI SCO Connections
737  */
738 
739 /*
740  * Incoming SCO Connection. We check the list for anybody willing
741  * to take it.
742  */
743 struct hci_link *
744 hci_sco_newconn(struct hci_unit *unit, bdaddr_t *bdaddr)
745 {
746 	struct sockaddr_bt laddr, raddr;
747 	struct sco_pcb *pcb, *new;
748 	struct hci_link *sco, *acl;
749 
750 	memset(&laddr, 0, sizeof(laddr));
751 	laddr.bt_len = sizeof(laddr);
752 	laddr.bt_family = AF_BLUETOOTH;
753 	bdaddr_copy(&laddr.bt_bdaddr, &unit->hci_bdaddr);
754 
755 	memset(&raddr, 0, sizeof(raddr));
756 	raddr.bt_len = sizeof(raddr);
757 	raddr.bt_family = AF_BLUETOOTH;
758 	bdaddr_copy(&raddr.bt_bdaddr, bdaddr);
759 
760 	/*
761 	 * There should already be an ACL link up and running before
762 	 * the controller sends us SCO connection requests, but you
763 	 * never know..
764 	 */
765 	acl = hci_link_lookup_bdaddr(unit, bdaddr, HCI_LINK_ACL);
766 	if (acl == NULL || acl->hl_state != HCI_LINK_OPEN)
767 		return NULL;
768 
769 	LIST_FOREACH(pcb, &sco_pcb, sp_next) {
770 		if ((pcb->sp_flags & SP_LISTENING) == 0)
771 			continue;
772 
773 		new = (*pcb->sp_proto->newconn)(pcb->sp_upper, &laddr, &raddr);
774 		if (new == NULL)
775 			continue;
776 
777 		/*
778 		 * Ok, got new pcb so we can start a new link and fill
779 		 * in all the details.
780 		 */
781 		bdaddr_copy(&new->sp_laddr, &unit->hci_bdaddr);
782 		bdaddr_copy(&new->sp_raddr, bdaddr);
783 
784 		sco = hci_link_alloc(unit, bdaddr, HCI_LINK_SCO);
785 		if (sco == NULL) {
786 			sco_detach(&new);
787 			return NULL;
788 		}
789 
790 		sco->hl_link = hci_acl_open(unit, bdaddr);
791 		KASSERT(sco->hl_link == acl);
792 
793 		sco->hl_sco = new;
794 		new->sp_link = sco;
795 
796 		new->sp_mtu = unit->hci_max_sco_size;
797 		return sco;
798 	}
799 
800 	return NULL;
801 }
802 
803 /*
804  * receive SCO packet, we only need to strip the header and send
805  * it to the right handler
806  */
807 void
808 hci_sco_recv(struct mbuf *m, struct hci_unit *unit)
809 {
810 	struct hci_link *link;
811 	hci_scodata_hdr_t hdr;
812 	uint16_t handle;
813 
814 	KASSERT(m != NULL);
815 	KASSERT(unit != NULL);
816 
817 	KASSERT(m->m_pkthdr.len >= sizeof(hdr));
818 	m_copydata(m, 0, sizeof(hdr), &hdr);
819 	m_adj(m, sizeof(hdr));
820 
821 #ifdef DIAGNOSTIC
822 	if (hdr.type != HCI_SCO_DATA_PKT) {
823 		aprint_error_dev(unit->hci_dev, "bad SCO packet type\n");
824 		goto bad;
825 	}
826 
827 	if (m->m_pkthdr.len != hdr.length) {
828 		aprint_error_dev(unit->hci_dev,
829 		    "bad SCO packet length (%d != %d)\n",
830 		    m->m_pkthdr.len, hdr.length);
831 
832 		goto bad;
833 	}
834 #endif
835 
836 	hdr.con_handle = le16toh(hdr.con_handle);
837 	handle = HCI_CON_HANDLE(hdr.con_handle);
838 
839 	link = hci_link_lookup_handle(unit, handle);
840 	if (link == NULL || link->hl_type == HCI_LINK_ACL) {
841 		DPRINTF("%s: dumping packet for unknown handle #%d\n",
842 			device_xname(unit->hci_dev), handle);
843 
844 		goto bad;
845 	}
846 
847 	(*link->hl_sco->sp_proto->input)(link->hl_sco->sp_upper, m);
848 	return;
849 
850 bad:
851 	m_freem(m);
852 }
853 
854 void
855 hci_sco_start(struct hci_link *link)
856 {
857 }
858 
859 /*
860  * SCO packets have completed at the controller, so we can
861  * signal up to free the buffer space.
862  */
863 void
864 hci_sco_complete(struct hci_link *link, int num)
865 {
866 
867 	DPRINTFN(5, "handle #%d (num=%d)\n", link->hl_handle, num);
868 	link->hl_sco->sp_pending--;
869 	(*link->hl_sco->sp_proto->complete)(link->hl_sco->sp_upper, num);
870 }
871 
872 /*******************************************************************************
873  *
874  *	Generic HCI Connection alloc/free/lookup etc
875  */
876 
877 struct hci_link *
878 hci_link_alloc(struct hci_unit *unit, bdaddr_t *bdaddr, uint8_t type)
879 {
880 	struct hci_link *link;
881 
882 	KASSERT(unit != NULL);
883 
884 	link = malloc(sizeof(struct hci_link), M_BLUETOOTH, M_NOWAIT | M_ZERO);
885 	if (link == NULL)
886 		return NULL;
887 
888 	link->hl_unit = unit;
889 	link->hl_type = type;
890 	link->hl_state = HCI_LINK_CLOSED;
891 	bdaddr_copy(&link->hl_bdaddr, bdaddr);
892 
893 	/* init ACL portion */
894 	callout_init(&link->hl_expire, 0);
895 	callout_setfunc(&link->hl_expire, hci_acl_timeout, link);
896 
897 	TAILQ_INIT(&link->hl_txq);	/* outgoing packets */
898 	TAILQ_INIT(&link->hl_reqs);	/* request queue */
899 
900 	link->hl_mtu = L2CAP_MTU_DEFAULT;		/* L2CAP signal mtu */
901 	link->hl_flush = L2CAP_FLUSH_TIMO_DEFAULT;	/* flush timeout */
902 
903 	/* init SCO portion */
904 	MBUFQ_INIT(&link->hl_data);
905 
906 	/* attach to unit */
907 	TAILQ_INSERT_TAIL(&unit->hci_links, link, hl_next);
908 	return link;
909 }
910 
911 void
912 hci_link_free(struct hci_link *link, int err)
913 {
914 	struct l2cap_req *req;
915 	struct l2cap_pdu *pdu;
916 	struct l2cap_channel *chan, *next;
917 
918 	KASSERT(link != NULL);
919 
920 	DPRINTF("#%d, type = %d, state = %d, refcnt = %d\n",
921 		link->hl_handle, link->hl_type,
922 		link->hl_state, link->hl_refcnt);
923 
924 	/* ACL reference count */
925 	if (link->hl_refcnt > 0) {
926 		next = LIST_FIRST(&l2cap_active_list);
927 		while ((chan = next) != NULL) {
928 			next = LIST_NEXT(chan, lc_ncid);
929 			if (chan->lc_link == link)
930 				l2cap_close(chan, err);
931 		}
932 	}
933 	KASSERT(link->hl_refcnt == 0);
934 
935 	/* ACL L2CAP requests.. */
936 	while ((req = TAILQ_FIRST(&link->hl_reqs)) != NULL)
937 		l2cap_request_free(req);
938 
939 	KASSERT(TAILQ_EMPTY(&link->hl_reqs));
940 
941 	/* ACL outgoing data queue */
942 	while ((pdu = TAILQ_FIRST(&link->hl_txq)) != NULL) {
943 		TAILQ_REMOVE(&link->hl_txq, pdu, lp_next);
944 		MBUFQ_DRAIN(&pdu->lp_data);
945 		if (pdu->lp_pending)
946 			link->hl_unit->hci_num_acl_pkts += pdu->lp_pending;
947 
948 		pool_put(&l2cap_pdu_pool, pdu);
949 	}
950 
951 	KASSERT(TAILQ_EMPTY(&link->hl_txq));
952 
953 	/* ACL incoming data packet */
954 	if (link->hl_rxp != NULL) {
955 		m_freem(link->hl_rxp);
956 		link->hl_rxp = NULL;
957 	}
958 
959 	/* SCO master ACL link */
960 	if (link->hl_link != NULL) {
961 		hci_acl_close(link->hl_link, err);
962 		link->hl_link = NULL;
963 	}
964 
965 	/* SCO pcb */
966 	if (link->hl_sco != NULL) {
967 		struct sco_pcb *pcb;
968 
969 		pcb = link->hl_sco;
970 		pcb->sp_link = NULL;
971 		link->hl_sco = NULL;
972 		(*pcb->sp_proto->disconnected)(pcb->sp_upper, err);
973 	}
974 
975 	/* flush any SCO data */
976 	MBUFQ_DRAIN(&link->hl_data);
977 
978 	/*
979 	 * Halt the callout - if its already running we cannot free the
980 	 * link structure but the timeout function will call us back in
981 	 * any case.
982 	 */
983 	link->hl_state = HCI_LINK_CLOSED;
984 	callout_stop(&link->hl_expire);
985 	if (callout_invoking(&link->hl_expire))
986 		return;
987 
988 	callout_destroy(&link->hl_expire);
989 
990 	/*
991 	 * If we made a note of clock offset, keep it in a memo
992 	 * to facilitate reconnections to this device
993 	 */
994 	if (link->hl_clock != 0) {
995 		struct hci_memo *memo;
996 
997 		memo = hci_memo_new(link->hl_unit, &link->hl_bdaddr);
998 		if (memo != NULL)
999 			memo->clock_offset = link->hl_clock;
1000 	}
1001 
1002 	TAILQ_REMOVE(&link->hl_unit->hci_links, link, hl_next);
1003 	free(link, M_BLUETOOTH);
1004 }
1005 
1006 /*
1007  * Lookup HCI link by address and type. Note that for SCO links there may
1008  * be more than one link per address, so we only return links with no
1009  * handle (ie new links)
1010  */
1011 struct hci_link *
1012 hci_link_lookup_bdaddr(struct hci_unit *unit, bdaddr_t *bdaddr, uint8_t type)
1013 {
1014 	struct hci_link *link;
1015 
1016 	KASSERT(unit != NULL);
1017 	KASSERT(bdaddr != NULL);
1018 
1019 	TAILQ_FOREACH(link, &unit->hci_links, hl_next) {
1020 		if (link->hl_type != type)
1021 			continue;
1022 
1023 		if (type == HCI_LINK_SCO && link->hl_handle != 0)
1024 			continue;
1025 
1026 		if (bdaddr_same(&link->hl_bdaddr, bdaddr))
1027 			break;
1028 	}
1029 
1030 	return link;
1031 }
1032 
1033 struct hci_link *
1034 hci_link_lookup_handle(struct hci_unit *unit, uint16_t handle)
1035 {
1036 	struct hci_link *link;
1037 
1038 	KASSERT(unit != NULL);
1039 
1040 	TAILQ_FOREACH(link, &unit->hci_links, hl_next) {
1041 		if (handle == link->hl_handle)
1042 			break;
1043 	}
1044 
1045 	return link;
1046 }
1047