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