xref: /netbsd-src/sys/dev/bluetooth/bcsp.c (revision 7fa608457b817eca6e0977b37f758ae064f3c99c)
1 /*	$NetBSD: bcsp.c,v 1.8 2007/11/11 12:59:06 plunky Exp $	*/
2 /*
3  * Copyright (c) 2007 KIYOHARA Takashi
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
19  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
23  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
24  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __KERNEL_RCSID(0, "$NetBSD: bcsp.c,v 1.8 2007/11/11 12:59:06 plunky Exp $");
30 
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/callout.h>
34 #include <sys/conf.h>
35 #include <sys/device.h>
36 #include <sys/errno.h>
37 #include <sys/fcntl.h>
38 #include <sys/kauth.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/proc.h>
43 #include <sys/sysctl.h>
44 #include <sys/syslimits.h>
45 #include <sys/systm.h>
46 #include <sys/tty.h>
47 
48 #include <netbt/bluetooth.h>
49 #include <netbt/hci.h>
50 
51 #include <dev/bluetooth/bcsp.h>
52 #include <dev/bluetooth/btuart.h>
53 
54 #include "ioconf.h"
55 
56 #ifdef BCSP_DEBUG
57 #ifdef DPRINTF
58 #undef DPRINTF
59 #endif
60 #ifdef DPRINTFN
61 #undef DPRINTFN
62 #endif
63 
64 #define DPRINTF(x)	printf x
65 #define DPRINTFN(n, x)	do { if (bcsp_debug > (n)) printf x; } while (0)
66 int bcsp_debug = 3;
67 #else
68 #undef DPRINTF
69 #undef DPRINTFN
70 
71 #define DPRINTF(x)
72 #define DPRINTFN(n, x)
73 #endif
74 
75 struct bcsp_softc {
76 	device_t sc_dev;
77 
78 	struct tty *sc_tp;
79 	struct hci_unit sc_unit;		/* Bluetooth HCI Unit */
80 
81 	int sc_baud;
82 	int sc_init_baud;
83 
84 	/* variables of SLIP Layer */
85 	struct mbuf *sc_txp;			/* outgoing packet */
86 	struct mbuf *sc_rxp;			/* incoming packet */
87 	int sc_slip_txrsv;			/* reserved byte data */
88 	int sc_slip_rxexp;			/* expected byte data */
89 	void (*sc_transmit_callback)(struct bcsp_softc *, struct mbuf *);
90 
91 	/* variables of Packet Integrity Layer */
92 	int sc_pi_txcrc;			/* use CRC, if true */
93 
94 	/* variables of MUX Layer */
95 	bool sc_mux_send_ack;			/* flag for send_ack */
96 	bool sc_mux_choke;			/* Choke signal */
97 	struct timeval sc_mux_lastrx;		/* Last Rx Pkt Time */
98 
99 	/* variables of Sequencing Layer */
100 	MBUFQ_HEAD() sc_seqq;			/* Sequencing Layer queue */
101 	MBUFQ_HEAD() sc_seq_retryq;		/* retry queue */
102 	uint32_t sc_seq_txseq;
103 	uint32_t sc_seq_txack;
104 	uint32_t sc_seq_expected_rxseq;
105 	uint32_t sc_seq_winspace;
106 	uint32_t sc_seq_retries;
107 	callout_t sc_seq_timer;
108 	uint32_t sc_seq_timeout;
109 	uint32_t sc_seq_winsize;
110 	uint32_t sc_seq_retry_limit;
111 
112 	/* variables of Datagram Queue Layer */
113 	MBUFQ_HEAD() sc_dgq;			/* Datagram Queue Layer queue */
114 
115 	/* variables of BCSP Link Establishment Protocol */
116 	bool sc_le_muzzled;
117 	bcsp_le_state_t sc_le_state;
118 	callout_t sc_le_timer;
119 
120 	struct sysctllog *sc_log;		/* sysctl log */
121 };
122 
123 void bcspattach(int);
124 static int bcsp_match(struct device *, struct cfdata *, void *);
125 static void bcsp_attach(struct device *, struct device *, void *);
126 static int bcsp_detach(struct device *, int);
127 
128 /* tty functions */
129 static int bcspopen(dev_t, struct tty *);
130 static int bcspclose(struct tty *, int);
131 static int bcspioctl(struct tty *, u_long, void *, int, struct lwp *);
132 
133 static int bcsp_slip_transmit(struct tty *);
134 static int bcsp_slip_receive(int, struct tty *);
135 
136 static void bcsp_pktintegrity_transmit(struct bcsp_softc *);
137 static void bcsp_pktintegrity_receive(struct bcsp_softc *, struct mbuf *);
138 static void bcsp_crc_update(uint16_t *, uint8_t);
139 static uint16_t bcsp_crc_reverse(uint16_t);
140 
141 static void bcsp_mux_transmit(struct bcsp_softc *sc);
142 static void bcsp_mux_receive(struct bcsp_softc *sc, struct mbuf *m);
143 static __inline void bcsp_send_ack_command(struct bcsp_softc *sc);
144 static __inline struct mbuf *bcsp_create_ackpkt(void);
145 static __inline void bcsp_set_choke(struct bcsp_softc *, bool);
146 
147 static void bcsp_sequencing_receive(struct bcsp_softc *, struct mbuf *);
148 static bool bcsp_tx_reliable_pkt(struct bcsp_softc *, struct mbuf *, u_int);
149 static __inline u_int bcsp_get_txack(struct bcsp_softc *);
150 static void bcsp_signal_rxack(struct bcsp_softc *, uint32_t);
151 static void bcsp_reliabletx_callback(struct bcsp_softc *, struct mbuf *);
152 static void bcsp_timer_timeout(void *);
153 static void bcsp_sequencing_reset(struct bcsp_softc *);
154 
155 static void bcsp_datagramq_receive(struct bcsp_softc *, struct mbuf *);
156 static bool bcsp_tx_unreliable_pkt(struct bcsp_softc *, struct mbuf *, u_int);
157 static void bcsp_unreliabletx_callback(struct bcsp_softc *, struct mbuf *);
158 
159 static int bcsp_start_le(struct hci_unit *);
160 static void bcsp_terminate_le(struct hci_unit *);
161 static void bcsp_input_le(struct hci_unit *, struct mbuf *);
162 static void bcsp_le_timeout(void *);
163 
164 /* bluetooth hci functions */
165 static int bcsp_enable(device_t);
166 static void bcsp_disable(device_t);
167 static void bcsp_start(device_t);
168 
169 #ifdef BCSP_DEBUG
170 static void bcsp_packet_print(struct mbuf *m);
171 #endif
172 
173 
174 /*
175  * It doesn't need to be exported, as only bcspattach() uses it,
176  * but there's no "official" way to make it static.
177  */
178 CFATTACH_DECL_NEW(bcsp, sizeof(struct bcsp_softc),
179     bcsp_match, bcsp_attach, bcsp_detach, NULL);
180 
181 static struct linesw bcsp_disc = {
182 	.l_name = "bcsp",
183 	.l_open = bcspopen,
184 	.l_close = bcspclose,
185 	.l_read = ttyerrio,
186 	.l_write = ttyerrio,
187 	.l_ioctl = bcspioctl,
188 	.l_rint = bcsp_slip_receive,
189 	.l_start = bcsp_slip_transmit,
190 	.l_modem = ttymodem,
191 	.l_poll = ttyerrpoll
192 };
193 
194 
195 /* ARGSUSED */
196 void
197 bcspattach(int num __unused)
198 {
199 	int error;
200 
201 	error = ttyldisc_attach(&bcsp_disc);
202 	if (error) {
203 		aprint_error("%s: unable to register line discipline, "
204 		    "error = %d\n", bcsp_cd.cd_name, error);
205 		return;
206 	}
207 
208 	error = config_cfattach_attach(bcsp_cd.cd_name, &bcsp_ca);
209 	if (error) {
210 		aprint_error("%s: unable to register cfattach, error = %d\n",
211 		    bcsp_cd.cd_name, error);
212 		config_cfdriver_detach(&bcsp_cd);
213 		(void) ttyldisc_detach(&bcsp_disc);
214 	}
215 }
216 
217 /*
218  * Autoconf match routine.
219  *
220  * XXX: unused: config_attach_pseudo(9) does not call ca_match.
221  */
222 /* ARGSUSED */
223 static int
224 bcsp_match(struct device *self __unused, struct cfdata *cfdata __unused,
225 	   void *arg __unused)
226 {
227 
228 	/* pseudo-device; always present */
229 	return 1;
230 }
231 
232 /*
233  * Autoconf attach routine.  Called by config_attach_pseudo(9) when we
234  * open the line discipline.
235  */
236 /* ARGSUSED */
237 static void
238 bcsp_attach(struct device *parent __unused, struct device *self,
239 	    void *aux __unused)
240 {
241 	struct bcsp_softc *sc = device_private(self);
242 	const struct sysctlnode *node;
243 	int rc, bcsp_node_num;
244 
245 	aprint_normal("\n");
246 	aprint_naive("\n");
247 
248 	sc->sc_dev = self;
249 	callout_init(&sc->sc_seq_timer, 0);
250 	callout_setfunc(&sc->sc_seq_timer, bcsp_timer_timeout, sc);
251 	callout_init(&sc->sc_le_timer, 0);
252 	callout_setfunc(&sc->sc_le_timer, bcsp_le_timeout, sc);
253 	sc->sc_seq_timeout = BCSP_SEQ_TX_TIMEOUT;
254 	sc->sc_seq_winsize = BCSP_SEQ_TX_WINSIZE;
255 	sc->sc_seq_retry_limit = BCSP_SEQ_TX_RETRY_LIMIT;
256 	MBUFQ_INIT(&sc->sc_seqq);
257 	MBUFQ_INIT(&sc->sc_seq_retryq);
258 	MBUFQ_INIT(&sc->sc_dgq);
259 
260 	/* Attach Bluetooth unit */
261 	sc->sc_unit.hci_dev = self;
262 	sc->sc_unit.hci_enable = bcsp_enable;
263 	sc->sc_unit.hci_disable = bcsp_disable;
264 	sc->sc_unit.hci_start_cmd = bcsp_start;
265 	sc->sc_unit.hci_start_acl = bcsp_start;
266 	sc->sc_unit.hci_start_sco = bcsp_start;
267 	sc->sc_unit.hci_ipl = makeiplcookie(IPL_TTY);
268 	hci_attach(&sc->sc_unit);
269 
270 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, NULL,
271 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "hw", NULL,
272 	    NULL, 0, NULL, 0, CTL_HW, CTL_EOL)) != 0) {
273 		goto err;
274 	}
275 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
276 	    0, CTLTYPE_NODE, device_xname(self),
277 	    SYSCTL_DESCR("bcsp controls"),
278 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0) {
279 		goto err;
280 	}
281 	bcsp_node_num = node->sysctl_num;
282 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
283 	    CTLFLAG_READWRITE, CTLTYPE_INT,
284 	    "muzzled", SYSCTL_DESCR("muzzled for Link-establishment Layer"),
285 	    NULL, 0, &sc->sc_le_muzzled,
286 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
287 		goto err;
288 	}
289 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
290 	    CTLFLAG_READWRITE, CTLTYPE_INT,
291 	    "txcrc", SYSCTL_DESCR("txcrc for Packet Integrity Layer"),
292 	    NULL, 0, &sc->sc_pi_txcrc,
293 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
294 		goto err;
295 	}
296 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
297 	    CTLFLAG_READWRITE, CTLTYPE_INT,
298 	    "timeout", SYSCTL_DESCR("timeout for Sequencing Layer"),
299 	    NULL, 0, &sc->sc_seq_timeout,
300 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
301 		goto err;
302 	}
303 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
304 	    CTLFLAG_READWRITE, CTLTYPE_INT,
305 	    "winsize", SYSCTL_DESCR("winsize for Sequencing Layer"),
306 	    NULL, 0, &sc->sc_seq_winsize,
307 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
308 		goto err;
309 	}
310 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
311 	    CTLFLAG_READWRITE, CTLTYPE_INT,
312 	    "retry_limit", SYSCTL_DESCR("retry limit for Sequencing Layer"),
313 	    NULL, 0, &sc->sc_seq_retry_limit,
314 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
315 		goto err;
316 	}
317 	return;
318 
319 err:
320 	aprint_error_dev(self, "sysctl_createv failed (rc = %d)\n", rc);
321 }
322 
323 /*
324  * Autoconf detach routine.  Called when we close the line discipline.
325  */
326 /* ARGSUSED */
327 static int
328 bcsp_detach(struct device *self, int flags __unused)
329 {
330 	struct bcsp_softc *sc = device_private(self);
331 
332 	hci_detach(&sc->sc_unit);
333 
334 	callout_stop(&sc->sc_seq_timer);
335 	callout_destroy(&sc->sc_seq_timer);
336 
337 	callout_stop(&sc->sc_le_timer);
338 	callout_destroy(&sc->sc_le_timer);
339 
340 	return 0;
341 }
342 
343 
344 /*
345  * Line discipline functions.
346  */
347 /* ARGSUSED */
348 static int
349 bcspopen(dev_t device __unused, struct tty *tp)
350 {
351 	struct bcsp_softc *sc;
352 	struct cfdata *cfdata;
353 	struct lwp *l = curlwp;		/* XXX */
354 	int error, unit, s;
355 	static char name[] = "bcsp";
356 
357 	if ((error = kauth_authorize_device_tty(l->l_cred,
358 	    KAUTH_GENERIC_ISSUSER, tp)) != 0)
359 		return error;
360 
361 	s = spltty();
362 
363 	if (tp->t_linesw == &bcsp_disc) {
364 		sc = tp->t_sc;
365 		if (sc != NULL) {
366 			splx(s);
367 			return EBUSY;
368 		}
369 	}
370 
371 	KASSERT(tp->t_oproc != NULL);
372 
373 	cfdata = malloc(sizeof(struct cfdata), M_DEVBUF, M_WAITOK);
374 	for (unit = 0; unit < bcsp_cd.cd_ndevs; unit++)
375 		if (bcsp_cd.cd_devs[unit] == NULL)
376 			break;
377 	cfdata->cf_name = name;
378 	cfdata->cf_atname = name;
379 	cfdata->cf_unit = unit;
380 	cfdata->cf_fstate = FSTATE_STAR;
381 
382 	aprint_normal("%s%d at tty major %d minor %d",
383 	    name, unit, major(tp->t_dev), minor(tp->t_dev));
384 	sc = (struct bcsp_softc *)config_attach_pseudo(cfdata);
385 	if (sc == NULL) {
386 		splx(s);
387 		return EIO;
388 	}
389 
390 	mutex_spin_enter(&tty_lock);
391 	tp->t_sc = sc;
392 	sc->sc_tp = tp;
393 	ttyflush(tp, FREAD | FWRITE);
394 	mutex_spin_exit(&tty_lock);
395 
396 	splx(s);
397 
398 	sc->sc_slip_txrsv = BCSP_SLIP_PKTSTART;
399 	bcsp_sequencing_reset(sc);
400 
401 	/* start link-establishment */
402 	bcsp_start_le(&sc->sc_unit);
403 
404 	return 0;
405 }
406 
407 /* ARGSUSED */
408 static int
409 bcspclose(struct tty *tp, int flag __unused)
410 {
411 	struct bcsp_softc *sc = tp->t_sc;
412 	struct cfdata *cfdata;
413 	int s;
414 
415 	/* terminate link-establishment */
416 	bcsp_terminate_le(&sc->sc_unit);
417 
418 	s = spltty();
419 
420 	MBUFQ_DRAIN(&sc->sc_dgq);
421 	bcsp_sequencing_reset(sc);
422 
423 	mutex_spin_enter(&tty_lock);
424 	ttyflush(tp, FREAD | FWRITE);
425 	mutex_spin_exit(&tty_lock);	/* XXX */
426 	ttyldisc_release(tp->t_linesw);
427 	tp->t_linesw = ttyldisc_default();
428 	if (sc != NULL) {
429 		tp->t_sc = NULL;
430 		if (sc->sc_tp == tp) {
431 			cfdata = device_cfdata(sc->sc_dev);
432 			config_detach(sc->sc_dev, 0);
433 			free(cfdata, M_DEVBUF);
434 		}
435 
436 	}
437 	splx(s);
438 	return 0;
439 }
440 
441 /* ARGSUSED */
442 static int
443 bcspioctl(struct tty *tp, u_long cmd, void *data, int flag __unused,
444 	  struct lwp *l __unused)
445 {
446 	struct bcsp_softc *sc = tp->t_sc;
447 	int error;
448 
449 	if (sc == NULL || tp != sc->sc_tp)
450 		return EPASSTHROUGH;
451 
452 	error = 0;
453 	switch (cmd) {
454 	default:
455 		error = EPASSTHROUGH;
456 		break;
457 	}
458 
459 	return error;
460 }
461 
462 
463 /*
464  * UART Driver Layer is supported by com-driver.
465  */
466 
467 /*
468  * BCSP SLIP Layer functions:
469  *   Supports to transmit/receive a byte stream.
470  *   SLIP protocol described in Internet standard RFC 1055.
471  */
472 static int
473 bcsp_slip_transmit(struct tty *tp)
474 {
475 	struct bcsp_softc *sc = tp->t_sc;
476 	struct mbuf *m;
477 	int count, rlen;
478 	uint8_t *rptr;
479 
480 	m = sc->sc_txp;
481 	if (m == NULL) {
482 		sc->sc_unit.hci_flags &= ~BTF_XMIT;
483 		bcsp_mux_transmit(sc);
484 		return 0;
485 	}
486 
487 	count = 0;
488 	rlen = 0;
489 	rptr = mtod(m, uint8_t *);
490 
491 	if (sc->sc_slip_txrsv != 0) {
492 #ifdef BCSP_DEBUG
493 		if (sc->sc_slip_txrsv == BCSP_SLIP_PKTSTART)
494 			DPRINTFN(4, ("%s: slip transmit start\n",
495 			    device_xname(sc->sc_dev));
496 		else
497 			DPRINTFN(4, ("0x%02x ", sc->sc_slip_txrsv));
498 #endif
499 
500 		if (putc(sc->sc_slip_txrsv, &tp->t_outq) < 0)
501 			return 0;
502 		count++;
503 
504 		if (sc->sc_slip_txrsv == BCSP_SLIP_ESCAPE_PKTEND ||
505 		    sc->sc_slip_txrsv == BCSP_SLIP_ESCAPE_ESCAPE) {
506 			rlen++;
507 			rptr++;
508 		}
509 		sc->sc_slip_txrsv = 0;
510 	}
511 
512 	for(;;) {
513 		if (rlen >= m->m_len) {
514 			m = m->m_next;
515 			if (m == NULL) {
516 				if (putc(BCSP_SLIP_PKTEND, &tp->t_outq) < 0)
517 					break;
518 
519 				DPRINTFN(4, ("\n%s: slip transmit end\n",
520 				    device_xname(sc->sc_dev)));
521 
522 				m = sc->sc_txp;
523 				sc->sc_txp = NULL;
524 				sc->sc_slip_txrsv = BCSP_SLIP_PKTSTART;
525 
526 				sc->sc_transmit_callback(sc, m);
527 				m = NULL;
528 				break;
529 			}
530 
531 			rlen = 0;
532 			rptr = mtod(m, uint8_t *);
533 			continue;
534 		}
535 
536 		if (*rptr == BCSP_SLIP_PKTEND) {
537 			if (putc(BCSP_SLIP_ESCAPE, &tp->t_outq) < 0)
538 				break;
539 			count++;
540 			DPRINTFN(4, (" esc "));
541 
542 			if (putc(BCSP_SLIP_ESCAPE_PKTEND, &tp->t_outq) < 0) {
543 				sc->sc_slip_txrsv = BCSP_SLIP_ESCAPE_PKTEND;
544 				break;
545 			}
546 			DPRINTFN(4, ("0x%02x ", BCSP_SLIP_ESCAPE_PKTEND));
547 		} else if (*rptr == BCSP_SLIP_ESCAPE) {
548 			if (putc(BCSP_SLIP_ESCAPE, &tp->t_outq) < 0)
549 				break;
550 			count++;
551 			DPRINTFN(4, (" esc "));
552 
553 			if (putc(BCSP_SLIP_ESCAPE_ESCAPE, &tp->t_outq) < 0) {
554 				sc->sc_slip_txrsv = BCSP_SLIP_ESCAPE_ESCAPE;
555 				break;
556 			}
557 			DPRINTFN(4, ("0x%02x ", BCSP_SLIP_ESCAPE_ESCAPE));
558 		} else {
559 			if (putc(*rptr++, &tp->t_outq) < 0)
560 				break;
561 			DPRINTFN(4, ("0x%02x ", *(rptr - 1)));
562 		}
563 		rlen++;
564 		count++;
565 	}
566 	if (m != NULL)
567 		m_adj(m, rlen);
568 
569 	sc->sc_unit.hci_stats.byte_tx += count;
570 
571 	if (tp->t_outq.c_cc != 0)
572 		(*tp->t_oproc)(tp);
573 
574 	return 0;
575 }
576 
577 static int
578 bcsp_slip_receive(int c, struct tty *tp)
579 {
580 	struct bcsp_softc *sc = tp->t_sc;
581 	struct mbuf *m = sc->sc_rxp;
582 	int discard = 0;
583 	const char *errstr;
584 
585 	c &= TTY_CHARMASK;
586 
587 	/* If we already started a packet, find the trailing end of it. */
588 	if (m) {
589 		while (m->m_next)
590 			m = m->m_next;
591 
592 		if (M_TRAILINGSPACE(m) == 0) {
593 			/* extend mbuf */
594 			MGET(m->m_next, M_DONTWAIT, MT_DATA);
595 			if (m->m_next == NULL) {
596 				aprint_error_dev(sc->sc_dev,
597 				    "out of memory\n");
598 				++sc->sc_unit.hci_stats.err_rx;
599 				return 0;	/* (lost sync) */
600 			}
601 
602 			m = m->m_next;
603 			m->m_pkthdr.len = m->m_len = 0;
604 		}
605 	} else
606 		if (c != BCSP_SLIP_PKTSTART) {
607 			discard = 1;
608 			errstr = "not sync";
609 			goto discarded;
610 		}
611 
612 	switch (c) {
613 	case BCSP_SLIP_PKTSTART /* or _PKTEND */:
614 		if (m == NULL) {
615 			/* BCSP_SLIP_PKTSTART */
616 
617 			DPRINTFN(4, ("%s: slip receive start\n",
618 			    device_xname(sc->sc_dev)));
619 
620 			/* new packet */
621 			MGETHDR(m, M_DONTWAIT, MT_DATA);
622 			if (m == NULL) {
623 				aprint_error_dev(sc->sc_dev,
624 				    "out of memory\n");
625 				++sc->sc_unit.hci_stats.err_rx;
626 				return 0;	/* (lost sync) */
627 			}
628 
629 			sc->sc_rxp = m;
630 			m->m_pkthdr.len = m->m_len = 0;
631 			sc->sc_slip_rxexp = 0;
632 		} else {
633 			/* BCSP_SLIP_PKTEND */
634 
635 			if (m == sc->sc_rxp && m->m_len == 0) {
636 				DPRINTFN(4, ("%s: resynchronises\n",
637 				    device_xname(sc->sc_dev)));
638 
639 				sc->sc_unit.hci_stats.byte_rx++;
640 				return 0;
641 			}
642 
643 			DPRINTFN(4, ("%s%s: slip receive end\n",
644 			    (m->m_len % 16 != 0) ? "\n" :  "",
645 			    device_xname(sc->sc_dev)));
646 
647 			bcsp_pktintegrity_receive(sc, sc->sc_rxp);
648 			sc->sc_rxp = NULL;
649 			sc->sc_slip_rxexp = BCSP_SLIP_PKTSTART;
650 		}
651 		sc->sc_unit.hci_stats.byte_rx++;
652 		return 0;
653 
654 	case BCSP_SLIP_ESCAPE:
655 
656 		DPRINTFN(4, ("  esc"));
657 
658 		if (sc->sc_slip_rxexp == BCSP_SLIP_ESCAPE) {
659 			discard = 1;
660 			errstr = "waiting 0xdc or 0xdb";
661 		} else
662 			sc->sc_slip_rxexp = BCSP_SLIP_ESCAPE;
663 		break;
664 
665 	default:
666 		DPRINTFN(4, (" 0x%02x%s",
667 		    c, (m->m_len % 16 == 15) ? "\n" :  ""));
668 
669 		switch (sc->sc_slip_rxexp) {
670 		case BCSP_SLIP_PKTSTART:
671 			discard = 1;
672 			errstr = "waiting 0xc0";
673 			break;
674 
675 		case BCSP_SLIP_ESCAPE:
676 			if (c == BCSP_SLIP_ESCAPE_PKTEND)
677 				mtod(m, uint8_t *)[m->m_len++] =
678 				    BCSP_SLIP_PKTEND;
679 			else if (c == BCSP_SLIP_ESCAPE_ESCAPE)
680 				mtod(m, uint8_t *)[m->m_len++] =
681 				    BCSP_SLIP_ESCAPE;
682 			else {
683 				discard = 1;
684 				errstr = "unknown escape";
685 			}
686 			sc->sc_slip_rxexp = 0;
687 			break;
688 
689 		default:
690 			mtod(m, uint8_t *)[m->m_len++] = c;
691 		}
692 		sc->sc_rxp->m_pkthdr.len++;
693 	}
694 	if (discard) {
695 discarded:
696 		DPRINTFN(4, ("%s: receives unexpected byte 0x%02x: %s\n",
697 		    device_xname(sc->sc_dev), c, errstr));
698 	}
699 	sc->sc_unit.hci_stats.byte_rx++;
700 
701 	return 0;
702 }
703 
704 
705 /*
706  * BCSP Packet Integrity Layer functions:
707  *   handling Payload Length, Checksum, CRC.
708  */
709 static void
710 bcsp_pktintegrity_transmit(struct bcsp_softc *sc)
711 {
712 	struct mbuf *_m, *m = sc->sc_txp;
713 	bcsp_hdr_t *hdrp = mtod(m, bcsp_hdr_t *);
714 	int pktlen, pldlen;
715 
716 	DPRINTFN(3, ("%s: pi transmit\n", device_xname(sc->sc_dev)));
717 
718 	for (pktlen = 0, _m = m; _m != NULL; _m = _m->m_next)
719 		pktlen += _m->m_len;
720 	pldlen = pktlen - sizeof(bcsp_hdr_t);
721 
722 	if (sc->sc_pi_txcrc)
723 		hdrp->flags |= BCSP_FLAGS_CRC_PRESENT;
724 
725 	BCSP_SET_PLEN(hdrp, pldlen);
726 	BCSP_SET_CSUM(hdrp);
727 
728 	if (sc->sc_pi_txcrc) {
729 		int n = 0;
730 		uint16_t crc = 0xffff;
731 		uint8_t *buf;
732 
733 		for (_m = m; _m != NULL; _m = _m->m_next) {
734 			buf = mtod(_m, uint8_t *);
735 			for (n = 0; n < _m->m_len; n++)
736 				bcsp_crc_update(&crc, *(buf + n));
737 		}
738 		crc = htobe16(bcsp_crc_reverse(crc));
739 		m_copyback(m, pktlen, sizeof(crc), &crc);
740 	}
741 
742 #ifdef BCSP_DEBUG
743 	if (bcsp_debug == 4)
744 		bcsp_packet_print(m);
745 #endif
746 
747 	bcsp_slip_transmit(sc->sc_tp);
748 }
749 
750 static void
751 bcsp_pktintegrity_receive(struct bcsp_softc *sc, struct mbuf *m)
752 {
753 	bcsp_hdr_t *hdrp;
754 	struct mbuf *_m;
755 	u_int pktlen, pldlen;
756 	int discard = 0;
757 	uint16_t crc = 0xffff;
758 	const char *errstr;
759 
760 	DPRINTFN(3, ("%s: pi receive\n", device_xname(sc->sc_dev)));
761 #ifdef BCSP_DEBUG
762 	if (bcsp_debug == 4)
763 		bcsp_packet_print(m);
764 #endif
765 
766 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
767 
768 	hdrp = mtod(m, bcsp_hdr_t *);
769 	for (pktlen = 0, _m = m; _m != NULL; _m = _m->m_next)
770 		pktlen += _m->m_len;
771 	pldlen = pktlen - sizeof(bcsp_hdr_t) -
772 	    ((hdrp->flags & BCSP_FLAGS_CRC_PRESENT) ? sizeof(crc) : 0);
773 	if (pldlen > 0xfff) {
774 		discard = 1;
775 		errstr = "Payload Length";
776 		goto discarded;
777 	}
778 	if (hdrp->csum != BCSP_GET_CSUM(hdrp)) {
779 		discard = 1;
780 		errstr = "Checksum";
781 		goto discarded;
782 	}
783 	if (BCSP_GET_PLEN(hdrp) != pldlen) {
784 		discard = 1;
785 		errstr = "Payload Length";
786 		goto discarded;
787 	}
788 	if (hdrp->flags & BCSP_FLAGS_CRC_PRESENT) {
789 		int i, n;
790 		uint16_t crc0;
791 		uint8_t *buf;
792 
793 		i = 0;
794 		n = 0;
795 		for (_m = m; _m != NULL; _m = _m->m_next) {
796 			buf = mtod(m, uint8_t *);
797 			for (n = 0;
798 			    n < _m->m_len && i < sizeof(bcsp_hdr_t) + pldlen;
799 			    n++, i++)
800 				bcsp_crc_update(&crc, *(buf + n));
801 		}
802 
803 		m_copydata(_m, n, sizeof(crc0), &crc0);
804 		if (be16toh(crc0) != bcsp_crc_reverse(crc)) {
805 			discard = 1;
806 			errstr = "CRC";
807 		} else
808 			/* Shaves CRC */
809 			m_adj(m, (int)(0 - sizeof(crc)));
810 	}
811 
812 	if (discard) {
813 discarded:
814 		DPRINTFN(3, ("%s: receives unexpected packet: %s\n",
815 		    device_xname(sc->sc_dev), errstr));
816 		m_freem(m);
817 	} else
818 		bcsp_mux_receive(sc, m);
819 }
820 
821 static const uint16_t crctbl[] = {
822 	0x0000, 0x1081, 0x2102, 0x3183,
823 	0x4204, 0x5285, 0x6306, 0x7387,
824 	0x8408, 0x9489, 0xa50a, 0xb58b,
825 	0xc60c, 0xd68d, 0xe70e, 0xf78f,
826 };
827 
828 static void
829 bcsp_crc_update(uint16_t *crc, uint8_t d)
830 {
831 	uint16_t reg = *crc;
832 
833 	reg = (reg >> 4) ^ crctbl[(reg ^ d) & 0x000f];
834 	reg = (reg >> 4) ^ crctbl[(reg ^ (d >> 4)) & 0x000f];
835 
836 	*crc = reg;
837 }
838 
839 static uint16_t
840 bcsp_crc_reverse(uint16_t crc)
841 {
842 	uint16_t b, rev;
843 
844 	for (b = 0, rev = 0; b < 16; b++) {
845 		rev = rev << 1;
846 		rev |= (crc & 1);
847 		crc = crc >> 1;
848 	}
849 
850 	return rev;
851 }
852 
853 
854 /*
855  * BCSP MUX Layer functions
856  */
857 static void
858 bcsp_mux_transmit(struct bcsp_softc *sc)
859 {
860 	struct hci_unit *unit = &sc->sc_unit;
861 	struct mbuf *m;
862 	bcsp_hdr_t *hdrp;
863 
864 	DPRINTFN(2, ("%s: mux transmit: hci_flags=0x%x, choke=%d",
865 	    device_xname(sc->sc_dev), unit->hci_flags, sc->sc_mux_choke));
866 
867 	if (sc->sc_mux_choke) {
868 		struct mbuf *_m = NULL;
869 
870 		/* In this case, send only Link Establishment packet */
871 		for (m = MBUFQ_FIRST(&sc->sc_dgq); m != NULL;
872 		    _m = m, m = MBUFQ_NEXT(m)) {
873 			hdrp = mtod(m, bcsp_hdr_t *);
874 			if (hdrp->ident == BCSP_CHANNEL_LE) {
875 				if (m == MBUFQ_FIRST(&sc->sc_dgq))
876 					MBUFQ_DEQUEUE(&sc->sc_dgq, m);
877 				else {
878 					if (m->m_nextpkt == NULL)
879 						sc->sc_dgq.mq_last =
880 						    &_m->m_nextpkt;
881 					_m->m_nextpkt = m->m_nextpkt;
882 					m->m_nextpkt = NULL;
883 				}
884 				goto transmit;
885 			}
886 		}
887 		DPRINTFN(2, ("\n"));
888 		return;
889 	}
890 
891 	/*
892 	 * The MUX Layer always gives priority to packets from the Datagram
893 	 * Queue Layer over the Sequencing Layer.
894 	 */
895 	if (MBUFQ_FIRST(&sc->sc_dgq)) {
896 		MBUFQ_DEQUEUE(&sc->sc_dgq, m);
897 		goto transmit;
898 	}
899 	if (MBUFQ_FIRST(&sc->sc_seqq)) {
900 		MBUFQ_DEQUEUE(&sc->sc_seqq, m);
901 		hdrp = mtod(m, bcsp_hdr_t *);
902 		hdrp->flags |= BCSP_FLAGS_PROTOCOL_REL;		/* Reliable */
903 		goto transmit;
904 	}
905 	bcsp_start(sc->sc_dev);
906 	if (sc->sc_mux_send_ack == true) {
907 		m = bcsp_create_ackpkt();
908 		if (m != NULL)
909 			goto transmit;
910 		aprint_error_dev(sc->sc_dev, "out of memory\n");
911 		++unit->hci_stats.err_tx;
912 	}
913 
914 	/* Nothing to send */
915 	DPRINTFN(2, ("\n"));
916 	return;
917 
918 transmit:
919 	DPRINTFN(2, (", txack=%d, send_ack=%d\n",
920 	    bcsp_get_txack(sc), sc->sc_mux_send_ack));
921 
922 	hdrp = mtod(m, bcsp_hdr_t *);
923 	hdrp->flags |=
924 	    (bcsp_get_txack(sc) << BCSP_FLAGS_ACK_SHIFT) & BCSP_FLAGS_ACK_MASK;
925 	if (sc->sc_mux_send_ack == true)
926 		sc->sc_mux_send_ack = false;
927 
928 #ifdef BCSP_DEBUG
929 	if (bcsp_debug == 3)
930 		bcsp_packet_print(m);
931 #endif
932 
933 	sc->sc_txp = m;
934 	bcsp_pktintegrity_transmit(sc);
935 }
936 
937 static void
938 bcsp_mux_receive(struct bcsp_softc *sc, struct mbuf *m)
939 {
940 	bcsp_hdr_t *hdrp = mtod(m, bcsp_hdr_t *);
941 	const u_int rxack = BCSP_FLAGS_ACK(hdrp->flags);
942 
943 	DPRINTFN(2, ("%s: mux receive: flags=0x%x, ident=%d, rxack=%d\n",
944 	    device_xname(sc->sc_dev), hdrp->flags, hdrp->ident, rxack));
945 #ifdef BCSP_DEBUG
946 	if (bcsp_debug == 3)
947 		bcsp_packet_print(m);
948 #endif
949 
950 	bcsp_signal_rxack(sc, rxack);
951 
952 	microtime(&sc->sc_mux_lastrx);
953 
954 	/* if the Ack Packet received then discard */
955 	if (BCSP_FLAGS_SEQ(hdrp->flags) == 0 &&
956 	    hdrp->ident == BCSP_IDENT_ACKPKT &&
957 	    BCSP_GET_PLEN(hdrp) == 0) {
958 		m_freem(m);
959 		return;
960 	}
961 
962 	if (hdrp->flags & BCSP_FLAGS_PROTOCOL_REL)
963 		bcsp_sequencing_receive(sc, m);
964 	else
965 		bcsp_datagramq_receive(sc, m);
966 }
967 
968 static __inline void
969 bcsp_send_ack_command(struct bcsp_softc *sc)
970 {
971 
972 	DPRINTFN(2, ("%s: mux send_ack_command\n", device_xname(sc->sc_dev)));
973 
974 	sc->sc_mux_send_ack = true;
975 }
976 
977 static __inline struct mbuf *
978 bcsp_create_ackpkt()
979 {
980 	struct mbuf *m;
981 	bcsp_hdr_t *hdrp;
982 
983 	MGETHDR(m, M_DONTWAIT, MT_DATA);
984 	if (m != NULL) {
985 		m->m_pkthdr.len = m->m_len = sizeof(bcsp_hdr_t);
986 		hdrp = mtod(m, bcsp_hdr_t *);
987 		/*
988 		 * An Ack Packet has the following fields:
989 		 *	Ack Field:			txack (not set yet)
990 		 *	Seq Field:			0
991 		 *	Protocol Identifier Field:	0
992 		 *	Protocol Type Field:		Any value
993 		 *	Payload Length Field:		0
994 		 */
995 		memset(hdrp, 0, sizeof(bcsp_hdr_t));
996 	}
997 	return m;
998 }
999 
1000 static __inline void
1001 bcsp_set_choke(struct bcsp_softc *sc, bool choke)
1002 {
1003 
1004 	DPRINTFN(2, ("%s: mux set choke=%d\n", device_xname(sc->sc_dev), choke));
1005 
1006 	sc->sc_mux_choke = choke;
1007 }
1008 
1009 
1010 /*
1011  * BCSP Sequencing Layer functions
1012  */
1013 static void
1014 bcsp_sequencing_receive(struct bcsp_softc *sc, struct mbuf *m)
1015 {
1016 	bcsp_hdr_t hdr;
1017 	uint32_t rxseq;
1018 
1019 	m_copydata(m, 0, sizeof(bcsp_hdr_t), &hdr);
1020 	rxseq = BCSP_FLAGS_SEQ(hdr.flags);
1021 
1022 	DPRINTFN(1, ("%s: seq receive: rxseq=%d, expected %d\n",
1023 	    device_xname(sc->sc_dev), rxseq, sc->sc_seq_expected_rxseq));
1024 #ifdef BCSP_DEBUG
1025 	if (bcsp_debug == 2)
1026 		bcsp_packet_print(m);
1027 #endif
1028 
1029 	/*
1030 	 * We remove the header of BCSP and add the 'uint8_t type' of
1031 	 * hci_*_hdr_t to the head.
1032 	 */
1033 	m_adj(m, sizeof(bcsp_hdr_t) - sizeof(uint8_t));
1034 
1035 	if (rxseq != sc->sc_seq_expected_rxseq) {
1036 		m_freem(m);
1037 
1038 		/* send ack packet, if needly */
1039 		bcsp_mux_transmit(sc);
1040 
1041 		return;
1042 	}
1043 
1044 	switch (hdr.ident) {
1045 	case BCSP_CHANNEL_HCI_CMDEVT:
1046 		*(mtod(m, uint8_t *)) = HCI_EVENT_PKT;
1047 		hci_input_event(&sc->sc_unit, m);
1048 		sc->sc_unit.hci_stats.evt_rx++;
1049 		break;
1050 
1051 	case BCSP_CHANNEL_HCI_ACL:
1052 		*(mtod(m, uint8_t *)) = HCI_ACL_DATA_PKT;
1053 		hci_input_acl(&sc->sc_unit, m);
1054 		sc->sc_unit.hci_stats.acl_rx++;
1055 		break;
1056 
1057 	case BCSP_CHANNEL_HCI_SCO:
1058 		*(mtod(m, uint8_t *)) = HCI_SCO_DATA_PKT;
1059 		hci_input_sco(&sc->sc_unit, m);
1060 		sc->sc_unit.hci_stats.sco_rx++;
1061 		break;
1062 
1063 	case BCSP_CHANNEL_HQ:
1064 	case BCSP_CHANNEL_DEVMGT:
1065 	case BCSP_CHANNEL_L2CAP:
1066 	case BCSP_CHANNEL_RFCOMM:
1067 	case BCSP_CHANNEL_SDP:
1068 	case BCSP_CHANNEL_DFU:
1069 	case BCSP_CHANNEL_VM:
1070 	default:
1071 		aprint_error_dev(sc->sc_dev,
1072 		    "received reliable packet with not support channel %d\n",
1073 		    hdr.ident);
1074 		m_freem(m);
1075 		break;
1076 	}
1077 
1078 	sc->sc_seq_expected_rxseq =
1079 	    (sc->sc_seq_expected_rxseq + 1) & BCSP_FLAGS_SEQ_MASK;
1080 	sc->sc_seq_txack = sc->sc_seq_expected_rxseq;
1081 	bcsp_send_ack_command(sc);
1082 }
1083 
1084 static bool
1085 bcsp_tx_reliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1086 {
1087 	bcsp_hdr_t *hdrp;
1088 	struct mbuf *_m;
1089 	u_int pldlen;
1090 	int s;
1091 
1092 	DPRINTFN(1, ("%s: seq transmit:"
1093 	    "protocol_id=%d, winspace=%d, txseq=%d\n", device_xname(sc->sc_dev),
1094 	    protocol_id, sc->sc_seq_winspace, sc->sc_seq_txseq));
1095 
1096 	for (pldlen = 0, _m = m; _m != NULL; _m = _m->m_next) {
1097 		if (_m->m_len < 0)
1098 			return false;
1099 		pldlen += _m->m_len;
1100 	}
1101 	if (pldlen > 0xfff)
1102 		return false;
1103 	if (protocol_id == BCSP_IDENT_ACKPKT || protocol_id > 15)
1104 		return false;
1105 
1106 	if (sc->sc_seq_winspace == 0)
1107 		return false;
1108 
1109 	M_PREPEND(m, sizeof(bcsp_hdr_t), M_DONTWAIT);
1110 	if (m == NULL) {
1111 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1112 		return false;
1113 	}
1114 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
1115 
1116 	hdrp = mtod(m, bcsp_hdr_t *);
1117 	memset(hdrp, 0, sizeof(bcsp_hdr_t));
1118 	hdrp->flags |= sc->sc_seq_txseq;
1119 	hdrp->ident = protocol_id;
1120 
1121 	callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1122 
1123 	s = splserial();
1124 	MBUFQ_ENQUEUE(&sc->sc_seqq, m);
1125 	splx(s);
1126 	sc->sc_transmit_callback = bcsp_reliabletx_callback;
1127 
1128 #ifdef BCSP_DEBUG
1129 	if (bcsp_debug == 2)
1130 		bcsp_packet_print(m);
1131 #endif
1132 
1133 	sc->sc_seq_txseq = (sc->sc_seq_txseq + 1) & BCSP_FLAGS_SEQ_MASK;
1134 	sc->sc_seq_winspace--;
1135 	_m = m_copym(m, 0, M_COPYALL, M_DONTWAIT);
1136 	if (_m == NULL) {
1137 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1138 		return false;
1139 	}
1140 	MBUFQ_ENQUEUE(&sc->sc_seq_retryq, _m);
1141 	bcsp_mux_transmit(sc);
1142 
1143 	return true;
1144 }
1145 
1146 #if 0
1147 static bool
1148 bcsp_rx_reliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1149 {
1150 
1151 	return false;
1152 }
1153 
1154 /* XXXX:  I can't understand meaning this function... */
1155 static __inline void
1156 bcsp_link_failed(struct bcsp_softc *sc)
1157 {
1158 
1159 	return (sc->sc_seq_retries >= sc->sc_seq_retry_limit);
1160 }
1161 #endif
1162 
1163 static __inline u_int
1164 bcsp_get_txack(struct bcsp_softc *sc)
1165 {
1166 
1167 	return sc->sc_seq_txack;
1168 }
1169 
1170 static void
1171 bcsp_signal_rxack(struct bcsp_softc *sc, uint32_t rxack)
1172 {
1173 	bcsp_hdr_t *hdrp;
1174 	struct mbuf *m;
1175 	uint32_t seqno = (rxack - 1) & BCSP_FLAGS_SEQ_MASK;
1176 	int s;
1177 
1178 	DPRINTFN(1, ("%s: seq signal rxack: rxack=%d\n",
1179 	    device_xname(sc->sc_dev), rxack));
1180 
1181 	s = splserial();
1182 	m = MBUFQ_FIRST(&sc->sc_seq_retryq);
1183 	while (m != NULL) {
1184 		hdrp = mtod(m, bcsp_hdr_t *);
1185 		if (BCSP_FLAGS_SEQ(hdrp->flags) == seqno) {
1186 			struct mbuf *m0;
1187 
1188 			for (m0 = MBUFQ_FIRST(&sc->sc_seq_retryq);
1189 			    m0 != MBUFQ_NEXT(m);
1190 			    m0 = MBUFQ_FIRST(&sc->sc_seq_retryq)) {
1191 				MBUFQ_DEQUEUE(&sc->sc_seq_retryq, m0);
1192 				m_freem(m0);
1193 				sc->sc_seq_winspace++;
1194 			}
1195 			break;
1196 		}
1197 		m = MBUFQ_NEXT(m);
1198 	}
1199 	splx(s);
1200 	sc->sc_seq_retries = 0;
1201 
1202 	if (sc->sc_seq_winspace == sc->sc_seq_winsize)
1203 		callout_stop(&sc->sc_seq_timer);
1204 	else
1205 		callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1206 }
1207 
1208 static void
1209 bcsp_reliabletx_callback(struct bcsp_softc *sc, struct mbuf *m)
1210 {
1211 
1212 	m_freem(m);
1213 }
1214 
1215 static void
1216 bcsp_timer_timeout(void *arg)
1217 {
1218 	struct bcsp_softc *sc = arg;
1219 	struct mbuf *m, *_m;
1220 	int s, i = 0;
1221 
1222 	DPRINTFN(1, ("%s: seq timeout: retries=%d\n",
1223 	    device_xname(sc->sc_dev), sc->sc_seq_retries));
1224 
1225 	s = splserial();
1226 	for (m = MBUFQ_FIRST(&sc->sc_seq_retryq); m != NULL;
1227 	    m = MBUFQ_NEXT(m)) {
1228 		_m = m_copym(m, 0, M_COPYALL, M_DONTWAIT);
1229 		if (_m == NULL) {
1230 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1231 			return;
1232 		}
1233 		MBUFQ_ENQUEUE(&sc->sc_seqq, _m);
1234 		i++;
1235 	}
1236 	splx(s);
1237 
1238 	if (i != 0) {
1239 		if (++sc->sc_seq_retries < sc->sc_seq_retry_limit)
1240 			callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1241 		else {
1242 			aprint_error_dev(sc->sc_dev,
1243 			    "reached the retry limit."
1244 			    " restart the link-establishment\n");
1245 			bcsp_sequencing_reset(sc);
1246 			bcsp_start_le(&sc->sc_unit);
1247 			return;
1248 		}
1249 	}
1250 	bcsp_mux_transmit(sc);
1251 }
1252 
1253 static void
1254 bcsp_sequencing_reset(struct bcsp_softc *sc)
1255 {
1256 	int s;
1257 
1258 	s = splserial();
1259 	MBUFQ_DRAIN(&sc->sc_seqq);
1260 	MBUFQ_DRAIN(&sc->sc_seq_retryq);
1261 	splx(s);
1262 
1263 
1264 	sc->sc_seq_txseq = 0;
1265 	sc->sc_seq_txack = 0;
1266 	sc->sc_seq_winspace = sc->sc_seq_winsize;
1267 	sc->sc_seq_retries = 0;
1268 	callout_stop(&sc->sc_seq_timer);
1269 
1270 	sc->sc_mux_send_ack = false;
1271 
1272 	/* XXXX: expected_rxseq should be set by MUX Layer */
1273 	sc->sc_seq_expected_rxseq = 0;
1274 }
1275 
1276 
1277 /*
1278  * BCSP Datagram Queue Layer functions
1279  */
1280 static void
1281 bcsp_datagramq_receive(struct bcsp_softc *sc, struct mbuf *m)
1282 {
1283 	bcsp_hdr_t hdr;
1284 
1285 	DPRINTFN(1, ("%s: dgq receive\n", device_xname(sc->sc_dev)));
1286 #ifdef BCSP_DEBUG
1287 	if (bcsp_debug == 2)
1288 		bcsp_packet_print(m);
1289 #endif
1290 
1291 	m_copydata(m, 0, sizeof(bcsp_hdr_t), &hdr);
1292 
1293 	switch (hdr.ident) {
1294 	case BCSP_CHANNEL_LE:
1295 		m_adj(m, sizeof(bcsp_hdr_t));
1296 		bcsp_input_le(&sc->sc_unit, m);
1297 		break;
1298 
1299 	case BCSP_CHANNEL_HCI_SCO:
1300 		/*
1301 		 * We remove the header of BCSP and add the 'uint8_t type' of
1302 		 * hci_scodata_hdr_t to the head.
1303 		 */
1304 		m_adj(m, sizeof(bcsp_hdr_t) - sizeof(uint8_t));
1305 		*(mtod(m, uint8_t *)) = HCI_SCO_DATA_PKT;
1306 		hci_input_sco(&sc->sc_unit, m);
1307 		sc->sc_unit.hci_stats.sco_rx++;
1308 		break;
1309 
1310 	default:
1311 		aprint_error_dev(sc->sc_dev,
1312 		    "received unreliable packet with not support channel %d\n",
1313 		    hdr.ident);
1314 		m_freem(m);
1315 		break;
1316 	}
1317 }
1318 
1319 static bool
1320 bcsp_tx_unreliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1321 {
1322 	bcsp_hdr_t *hdrp;
1323 	struct mbuf *_m;
1324 	u_int pldlen;
1325 	int s;
1326 
1327 	DPRINTFN(1, ("%s: dgq transmit: protocol_id=%d,",
1328 	    device_xname(sc->sc_dev), protocol_id));
1329 
1330 	for (pldlen = 0, _m = m; _m != NULL; _m = m->m_next) {
1331 		if (_m->m_len < 0)
1332 			return false;
1333 		pldlen += _m->m_len;
1334 	}
1335 	DPRINTFN(1, (" pldlen=%d\n", pldlen));
1336 	if (pldlen > 0xfff)
1337 		return false;
1338 	if (protocol_id == BCSP_IDENT_ACKPKT || protocol_id > 15)
1339 		return false;
1340 
1341 	M_PREPEND(m, sizeof(bcsp_hdr_t), M_DONTWAIT);
1342 	if (m == NULL) {
1343 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1344 		return false;
1345 	}
1346 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
1347 
1348 	hdrp = mtod(m, bcsp_hdr_t *);
1349 	memset(hdrp, 0, sizeof(bcsp_hdr_t));
1350 	hdrp->ident = protocol_id;
1351 
1352 	s = splserial();
1353 	MBUFQ_ENQUEUE(&sc->sc_dgq, m);
1354 	splx(s);
1355 	sc->sc_transmit_callback = bcsp_unreliabletx_callback;
1356 
1357 #ifdef BCSP_DEBUG
1358 	if (bcsp_debug == 2)
1359 		bcsp_packet_print(m);
1360 #endif
1361 
1362 	bcsp_mux_transmit(sc);
1363 
1364 	return true;
1365 }
1366 
1367 #if 0
1368 static bool
1369 bcsp_rx_unreliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1370 {
1371 
1372 	return false;
1373 }
1374 #endif
1375 
1376 static void
1377 bcsp_unreliabletx_callback(struct bcsp_softc *sc, struct mbuf *m)
1378 {
1379 
1380 	if (M_GETCTX(m, void *) == NULL)
1381 		m_freem(m);
1382 	else
1383 		hci_complete_sco(&sc->sc_unit, m);
1384 }
1385 
1386 
1387 /*
1388  * BlueCore Link Establishment Protocol functions
1389  */
1390 static const uint8_t sync[] = BCSP_LE_SYNC;
1391 static const uint8_t syncresp[] = BCSP_LE_SYNCRESP;
1392 static const uint8_t conf[] = BCSP_LE_CONF;
1393 static const uint8_t confresp[] = BCSP_LE_CONFRESP;
1394 
1395 static int
1396 bcsp_start_le(struct hci_unit *unit)
1397 {
1398 	struct bcsp_softc *sc = device_private(unit->hci_dev);
1399 
1400 	DPRINTF(("%s: start link-establish\n", device_xname(sc->sc_dev)));
1401 
1402 	bcsp_set_choke(sc, true);
1403 
1404 	if (!sc->sc_le_muzzled) {
1405 		struct mbuf *m;
1406 
1407 		m = m_gethdr(M_WAIT, MT_DATA);
1408 		m->m_pkthdr.len = m->m_len = 0;
1409 		m_copyback(m, 0, sizeof(sync), sync);
1410 		if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE)) {
1411 			aprint_error_dev(sc->sc_dev,
1412 			    "le-packet transmit failed\n");
1413 			return EINVAL;
1414 		}
1415 	}
1416 	callout_schedule(&sc->sc_le_timer, BCSP_LE_TSHY_TIMEOUT);
1417 
1418 	sc->sc_le_state = le_state_shy;
1419 	return 0;
1420 }
1421 
1422 static void
1423 bcsp_terminate_le(struct hci_unit *unit)
1424 {
1425 	struct bcsp_softc *sc = device_private(unit->hci_dev);
1426 	struct mbuf *m;
1427 
1428 	/* terminate link-establishment */
1429 	callout_stop(&sc->sc_le_timer);
1430 	bcsp_set_choke(sc, true);
1431 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1432 	if (m == NULL)
1433 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1434 	else {
1435 		/* length of le packets is 4 */
1436 		m->m_pkthdr.len = m->m_len = 0;
1437 		m_copyback(m, 0, sizeof(sync), sync);
1438 		if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1439 			aprint_error_dev(sc->sc_dev,
1440 			    "link-establishment terminations failed\n");
1441 	}
1442 }
1443 
1444 static void
1445 bcsp_input_le(struct hci_unit *unit, struct mbuf *m)
1446 {
1447 	struct bcsp_softc *sc = device_private(unit->hci_dev);
1448 	uint32_t *rcvpkt;
1449 	int i;
1450 	const uint8_t *rplypkt;
1451 	static struct {
1452 		const char *type;
1453 		const uint8_t *datap;
1454 	} pkt[] = {
1455 		{ "sync",	sync },
1456 		{ "sync-resp",	syncresp },
1457 		{ "conf",	conf },
1458 		{ "conf-resp",	confresp },
1459 
1460 		{ NULL, 0 }
1461 	};
1462 
1463 	DPRINTFN(0, ("%s: le input: state %d, muzzled %d\n",
1464 	    device_xname(sc->sc_dev), sc->sc_le_state, sc->sc_le_muzzled));
1465 #ifdef BCSP_DEBUG
1466 	if (bcsp_debug == 1)
1467 		bcsp_packet_print(m);
1468 #endif
1469 
1470 	rcvpkt = mtod(m, uint32_t *);
1471 
1472 	/* length of le packets is 4 */
1473 	if (m->m_len == sizeof(uint32_t))
1474 		for (i = 0; pkt[i].type != NULL; i++)
1475 			if (*(const uint32_t *)pkt[i].datap == *rcvpkt)
1476 				break;
1477 	if (m->m_len != sizeof(uint32_t) || pkt[i].type == NULL) {
1478 		aprint_error_dev(sc->sc_dev, "received unknown packet\n");
1479 		m_freem(m);
1480 		return;
1481 	}
1482 
1483 	rplypkt = NULL;
1484 	switch (sc->sc_le_state) {
1485 	case le_state_shy:
1486 		if (*rcvpkt == *(const uint32_t *)sync) {
1487 			sc->sc_le_muzzled = false;
1488 			rplypkt = syncresp;
1489 		} else if (*rcvpkt == *(const uint32_t *)syncresp) {
1490 			DPRINTF(("%s: state change to curious\n",
1491 			    device_xname(sc->sc_dev)));
1492 
1493 			rplypkt = conf;
1494 			callout_schedule(&sc->sc_le_timer,
1495 			    BCSP_LE_TCONF_TIMEOUT);
1496 			sc->sc_le_state = le_state_curious;
1497 		} else
1498 			aprint_error_dev(sc->sc_dev,
1499 			    "received an unknown packet at shy\n");
1500 		break;
1501 
1502 	case le_state_curious:
1503 		if (*rcvpkt == *(const uint32_t *)sync)
1504 			rplypkt = syncresp;
1505 		else if (*rcvpkt == *(const uint32_t *)conf)
1506 			rplypkt = confresp;
1507 		else if (*rcvpkt == *(const uint32_t *)confresp) {
1508 			DPRINTF(("%s: state change to garrulous:\n",
1509 			    device_xname(sc->sc_dev)));
1510 
1511 			bcsp_set_choke(sc, false);
1512 			callout_stop(&sc->sc_le_timer);
1513 			sc->sc_le_state = le_state_garrulous;
1514 		} else
1515 			aprint_error_dev(sc->sc_dev,
1516 			    "received unknown packet at curious\n");
1517 		break;
1518 
1519 	case le_state_garrulous:
1520 		if (*rcvpkt == *(const uint32_t *)conf)
1521 			rplypkt = confresp;
1522 		else if (*rcvpkt == *(const uint32_t *)sync) {
1523 			/* XXXXX */
1524 			aprint_error_dev(sc->sc_dev,
1525 			    "received sync! peer to reset?\n");
1526 
1527 			bcsp_sequencing_reset(sc);
1528 			rplypkt = sync;
1529 			sc->sc_le_state = le_state_shy;
1530 		} else
1531 			aprint_error_dev(sc->sc_dev,
1532 			    "received unknown packet at garrulous\n");
1533 		break;
1534 	}
1535 
1536 	m_freem(m);
1537 
1538 	if (rplypkt != NULL) {
1539 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1540 		if (m == NULL)
1541 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1542 		else {
1543 			/* length of le packets is 4 */
1544 			m->m_pkthdr.len = m->m_len = 0;
1545 			m_copyback(m, 0, 4, rplypkt);
1546 			if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1547 				aprint_error_dev(sc->sc_dev,
1548 				    "le-packet transmit failed\n");
1549 		}
1550 	}
1551 }
1552 
1553 static void
1554 bcsp_le_timeout(void *arg)
1555 {
1556 	struct bcsp_softc *sc = arg;
1557 	struct mbuf *m;
1558 	int timeout;
1559 	const uint8_t *sndpkt = NULL;
1560 
1561 	DPRINTFN(0, ("%s: le timeout: state %d, muzzled %d\n",
1562 	    device_xname(sc->sc_dev), sc->sc_le_state, sc->sc_le_muzzled));
1563 
1564 	switch (sc->sc_le_state) {
1565 	case le_state_shy:
1566 		if (!sc->sc_le_muzzled)
1567 			sndpkt = sync;
1568 		timeout = BCSP_LE_TSHY_TIMEOUT;
1569 		break;
1570 
1571 	case le_state_curious:
1572 		sndpkt = conf;
1573 		timeout = BCSP_LE_TCONF_TIMEOUT;
1574 		break;
1575 
1576 	default:
1577 		aprint_error_dev(sc->sc_dev,
1578 		    "timeout happen at unknown state %d\n", sc->sc_le_state);
1579 		return;
1580 	}
1581 
1582 	if (sndpkt != NULL) {
1583 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1584 		if (m == NULL)
1585 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1586 		else {
1587 			/* length of le packets is 4 */
1588 			m->m_pkthdr.len = m->m_len = 0;
1589 			m_copyback(m, 0, 4, sndpkt);
1590 			if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1591 				aprint_error_dev(sc->sc_dev,
1592 				    "le-packet transmit failed\n");
1593 		}
1594 	}
1595 
1596 	callout_schedule(&sc->sc_le_timer, timeout);
1597 }
1598 
1599 
1600 /*
1601  * BlueCore Serial Protocol functions.
1602  */
1603 static int
1604 bcsp_enable(device_t self)
1605 {
1606 	struct bcsp_softc *sc = device_private(self);
1607 	struct hci_unit *unit = &sc->sc_unit;
1608 
1609 	if (unit->hci_flags & BTF_RUNNING)
1610 		return 0;
1611 
1612 	unit->hci_flags |= BTF_RUNNING;
1613 	unit->hci_flags &= ~BTF_XMIT;
1614 
1615 	return 0;
1616 }
1617 
1618 static void
1619 bcsp_disable(device_t self)
1620 {
1621 	struct bcsp_softc *sc = device_private(self);
1622 	struct hci_unit *unit = &sc->sc_unit;
1623 
1624 	if ((unit->hci_flags & BTF_RUNNING) == 0)
1625 		return;
1626 
1627 	if (sc->sc_rxp) {
1628 		m_freem(sc->sc_rxp);
1629 		sc->sc_rxp = NULL;
1630 	}
1631 
1632 	if (sc->sc_txp) {
1633 		m_freem(sc->sc_txp);
1634 		sc->sc_txp = NULL;
1635 	}
1636 
1637 	unit->hci_flags &= ~BTF_RUNNING;
1638 }
1639 
1640 static void
1641 bcsp_start(device_t self)
1642 {
1643 	struct bcsp_softc *sc = device_private(self);
1644 	struct hci_unit *unit = &sc->sc_unit;
1645 	struct mbuf *m;
1646 
1647 	KASSERT((unit->hci_flags & BTF_XMIT) == 0);
1648 	KASSERT(sc->sc_txp == NULL);
1649 
1650 	if (MBUFQ_FIRST(&unit->hci_acltxq)) {
1651 		MBUFQ_DEQUEUE(&unit->hci_acltxq, m);
1652 		unit->hci_stats.acl_tx++;
1653 		M_SETCTX(m, NULL);
1654 		m_adj(m, sizeof(uint8_t));
1655 		unit->hci_flags |= BTF_XMIT;
1656 		bcsp_tx_reliable_pkt(sc, m, BCSP_CHANNEL_HCI_ACL);
1657 	}
1658 
1659 	if (MBUFQ_FIRST(&unit->hci_cmdq)) {
1660 		MBUFQ_DEQUEUE(&unit->hci_cmdq, m);
1661 		unit->hci_stats.cmd_tx++;
1662 		M_SETCTX(m, NULL);
1663 		m_adj(m, sizeof(uint8_t));
1664 		unit->hci_flags |= BTF_XMIT;
1665 		bcsp_tx_reliable_pkt(sc, m, BCSP_CHANNEL_HCI_CMDEVT);
1666 	}
1667 
1668 	if (MBUFQ_FIRST(&unit->hci_scotxq)) {
1669 		MBUFQ_DEQUEUE(&unit->hci_scotxq, m);
1670 		unit->hci_stats.sco_tx++;
1671 		/* XXXX: We can transmit with reliable */
1672 		m_adj(m, sizeof(uint8_t));
1673 		unit->hci_flags |= BTF_XMIT;
1674 		bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_HCI_SCO);
1675 	}
1676 
1677 	return;
1678 }
1679 
1680 
1681 #ifdef BCSP_DEBUG
1682 static void
1683 bcsp_packet_print(struct mbuf *m)
1684 {
1685 	int i;
1686 	uint8_t *p;
1687 
1688 	for ( ; m != NULL; m = m->m_next) {
1689 		p = mtod(m, uint8_t *);
1690 		for (i = 0; i < m->m_len; i++) {
1691 			if (i % 16 == 0)
1692 				printf(" ");
1693 			printf(" %02x", *(p + i));
1694 			if (i % 16 == 15)
1695 				printf("\n");
1696 		}
1697 		printf("\n");
1698 	}
1699 }
1700 #endif
1701