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