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