xref: /netbsd-src/sys/dev/bluetooth/bcsp.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: bcsp.c,v 1.22 2013/10/17 21:22:01 christos 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.22 2013/10/17 21:22:01 christos 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, cfdata_t, 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, cfdata_t 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_BOOL,
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 	cfdata_t cfdata;
377 	struct lwp *l = curlwp;		/* XXX */
378 	int error, unit, s;
379 	static char name[] = "bcsp";
380 
381 	error = kauth_authorize_device(l->l_cred, KAUTH_DEVICE_BLUETOOTH_BCSP,
382 	    KAUTH_ARG(KAUTH_REQ_DEVICE_BLUETOOTH_BCSP_ADD), NULL, NULL, NULL);
383 	if (error)
384 		return (error);
385 
386 	s = spltty();
387 
388 	if (tp->t_linesw == &bcsp_disc) {
389 		sc = tp->t_sc;
390 		if (sc != NULL) {
391 			splx(s);
392 			return EBUSY;
393 		}
394 	}
395 
396 	KASSERT(tp->t_oproc != NULL);
397 
398 	cfdata = malloc(sizeof(struct cfdata), M_DEVBUF, M_WAITOK);
399 	for (unit = 0; unit < bcsp_cd.cd_ndevs; unit++)
400 		if (device_lookup(&bcsp_cd, unit) == NULL)
401 			break;
402 	cfdata->cf_name = name;
403 	cfdata->cf_atname = name;
404 	cfdata->cf_unit = unit;
405 	cfdata->cf_fstate = FSTATE_STAR;
406 
407 	aprint_normal("%s%d at tty major %llu minor %llu",
408 	    name, unit, (unsigned long long)major(tp->t_dev),
409 	    (unsigned long long)minor(tp->t_dev));
410 	dev = config_attach_pseudo(cfdata);
411 	if (dev == NULL) {
412 		splx(s);
413 		return EIO;
414 	}
415 	sc = device_private(dev);
416 
417 	mutex_spin_enter(&tty_lock);
418 	tp->t_sc = sc;
419 	sc->sc_tp = tp;
420 	ttyflush(tp, FREAD | FWRITE);
421 	mutex_spin_exit(&tty_lock);
422 
423 	splx(s);
424 
425 	sc->sc_slip_txrsv = BCSP_SLIP_PKTSTART;
426 	bcsp_sequencing_reset(sc);
427 
428 	/* start link-establishment */
429 	bcsp_start_le(sc);
430 
431 	return 0;
432 }
433 
434 /* ARGSUSED */
435 static int
436 bcspclose(struct tty *tp, int flag __unused)
437 {
438 	struct bcsp_softc *sc = tp->t_sc;
439 	cfdata_t cfdata;
440 	int s;
441 
442 	/* terminate link-establishment */
443 	bcsp_terminate_le(sc);
444 
445 	s = spltty();
446 
447 	MBUFQ_DRAIN(&sc->sc_dgq);
448 	bcsp_sequencing_reset(sc);
449 
450 	mutex_spin_enter(&tty_lock);
451 	ttyflush(tp, FREAD | FWRITE);
452 	mutex_spin_exit(&tty_lock);	/* XXX */
453 	ttyldisc_release(tp->t_linesw);
454 	tp->t_linesw = ttyldisc_default();
455 	if (sc != NULL) {
456 		tp->t_sc = NULL;
457 		if (sc->sc_tp == tp) {
458 			cfdata = device_cfdata(sc->sc_dev);
459 			config_detach(sc->sc_dev, 0);
460 			free(cfdata, M_DEVBUF);
461 		}
462 
463 	}
464 	splx(s);
465 	return 0;
466 }
467 
468 /* ARGSUSED */
469 static int
470 bcspioctl(struct tty *tp, u_long cmd, void *data, int flag __unused,
471 	  struct lwp *l __unused)
472 {
473 	struct bcsp_softc *sc = tp->t_sc;
474 	int error;
475 
476 	if (sc == NULL || tp != sc->sc_tp)
477 		return EPASSTHROUGH;
478 
479 	error = 0;
480 	switch (cmd) {
481 	default:
482 		error = EPASSTHROUGH;
483 		break;
484 	}
485 
486 	return error;
487 }
488 
489 
490 /*
491  * UART Driver Layer is supported by com-driver.
492  */
493 
494 /*
495  * BCSP SLIP Layer functions:
496  *   Supports to transmit/receive a byte stream.
497  *   SLIP protocol described in Internet standard RFC 1055.
498  */
499 static int
500 bcsp_slip_transmit(struct tty *tp)
501 {
502 	struct bcsp_softc *sc = tp->t_sc;
503 	struct mbuf *m;
504 	int count, rlen;
505 	uint8_t *rptr;
506 
507 	m = sc->sc_txp;
508 	if (m == NULL) {
509 		sc->sc_flags &= ~BCSP_XMIT;
510 		bcsp_mux_transmit(sc);
511 		return 0;
512 	}
513 
514 	count = 0;
515 	rlen = 0;
516 	rptr = mtod(m, uint8_t *);
517 
518 	if (sc->sc_slip_txrsv != 0) {
519 #ifdef BCSP_DEBUG
520 		if (sc->sc_slip_txrsv == BCSP_SLIP_PKTSTART)
521 			DPRINTFN(4, ("%s: slip transmit start\n",
522 			    device_xname(sc->sc_dev)));
523 		else
524 			DPRINTFN(4, ("0x%02x ", sc->sc_slip_txrsv));
525 #endif
526 
527 		if (putc(sc->sc_slip_txrsv, &tp->t_outq) < 0)
528 			return 0;
529 		count++;
530 
531 		if (sc->sc_slip_txrsv == BCSP_SLIP_ESCAPE_PKTEND ||
532 		    sc->sc_slip_txrsv == BCSP_SLIP_ESCAPE_ESCAPE) {
533 			rlen++;
534 			rptr++;
535 		}
536 		sc->sc_slip_txrsv = 0;
537 	}
538 
539 	for(;;) {
540 		if (rlen >= m->m_len) {
541 			m = m->m_next;
542 			if (m == NULL) {
543 				if (putc(BCSP_SLIP_PKTEND, &tp->t_outq) < 0)
544 					break;
545 
546 				DPRINTFN(4, ("\n%s: slip transmit end\n",
547 				    device_xname(sc->sc_dev)));
548 
549 				m = sc->sc_txp;
550 				sc->sc_txp = NULL;
551 				sc->sc_slip_txrsv = BCSP_SLIP_PKTSTART;
552 
553 				sc->sc_transmit_callback(sc, m);
554 				m = NULL;
555 				break;
556 			}
557 
558 			rlen = 0;
559 			rptr = mtod(m, uint8_t *);
560 			continue;
561 		}
562 
563 		if (*rptr == BCSP_SLIP_PKTEND) {
564 			if (putc(BCSP_SLIP_ESCAPE, &tp->t_outq) < 0)
565 				break;
566 			count++;
567 			DPRINTFN(4, (" esc "));
568 
569 			if (putc(BCSP_SLIP_ESCAPE_PKTEND, &tp->t_outq) < 0) {
570 				sc->sc_slip_txrsv = BCSP_SLIP_ESCAPE_PKTEND;
571 				break;
572 			}
573 			DPRINTFN(4, ("0x%02x ", BCSP_SLIP_ESCAPE_PKTEND));
574 			rptr++;
575 		} else if (*rptr == BCSP_SLIP_ESCAPE) {
576 			if (putc(BCSP_SLIP_ESCAPE, &tp->t_outq) < 0)
577 				break;
578 			count++;
579 			DPRINTFN(4, (" esc "));
580 
581 			if (putc(BCSP_SLIP_ESCAPE_ESCAPE, &tp->t_outq) < 0) {
582 				sc->sc_slip_txrsv = BCSP_SLIP_ESCAPE_ESCAPE;
583 				break;
584 			}
585 			DPRINTFN(4, ("0x%02x ", BCSP_SLIP_ESCAPE_ESCAPE));
586 			rptr++;
587 		} else {
588 			if (putc(*rptr++, &tp->t_outq) < 0)
589 				break;
590 			DPRINTFN(4, ("0x%02x ", *(rptr - 1)));
591 		}
592 		rlen++;
593 		count++;
594 	}
595 	if (m != NULL)
596 		m_adj(m, rlen);
597 
598 	sc->sc_stats.byte_tx += count;
599 
600 	if (tp->t_outq.c_cc != 0)
601 		(*tp->t_oproc)(tp);
602 
603 	return 0;
604 }
605 
606 static int
607 bcsp_slip_receive(int c, struct tty *tp)
608 {
609 	struct bcsp_softc *sc = tp->t_sc;
610 	struct mbuf *m = sc->sc_rxp;
611 	int discard = 0;
612 	const char *errstr;
613 
614 	c &= TTY_CHARMASK;
615 
616 	/* If we already started a packet, find the trailing end of it. */
617 	if (m) {
618 		while (m->m_next)
619 			m = m->m_next;
620 
621 		if (M_TRAILINGSPACE(m) == 0) {
622 			/* extend mbuf */
623 			MGET(m->m_next, M_DONTWAIT, MT_DATA);
624 			if (m->m_next == NULL) {
625 				aprint_error_dev(sc->sc_dev,
626 				    "out of memory\n");
627 				sc->sc_stats.err_rx++;
628 				return 0;	/* (lost sync) */
629 			}
630 
631 			m = m->m_next;
632 			m->m_len = 0;
633 		}
634 	} else
635 		if (c != BCSP_SLIP_PKTSTART) {
636 			discard = 1;
637 			errstr = "not sync";
638 			goto discarded;
639 		}
640 
641 	switch (c) {
642 	case BCSP_SLIP_PKTSTART /* or _PKTEND */:
643 		if (m == NULL) {
644 			/* BCSP_SLIP_PKTSTART */
645 
646 			DPRINTFN(4, ("%s: slip receive start\n",
647 			    device_xname(sc->sc_dev)));
648 
649 			/* new packet */
650 			MGETHDR(m, M_DONTWAIT, MT_DATA);
651 			if (m == NULL) {
652 				aprint_error_dev(sc->sc_dev,
653 				    "out of memory\n");
654 				sc->sc_stats.err_rx++;
655 				return 0;	/* (lost sync) */
656 			}
657 
658 			sc->sc_rxp = m;
659 			m->m_pkthdr.len = m->m_len = 0;
660 			sc->sc_slip_rxexp = 0;
661 		} else {
662 			/* BCSP_SLIP_PKTEND */
663 
664 			if (m == sc->sc_rxp && m->m_len == 0) {
665 				DPRINTFN(4, ("%s: resynchronises\n",
666 				    device_xname(sc->sc_dev)));
667 
668 				sc->sc_stats.byte_rx++;
669 				return 0;
670 			}
671 
672 			DPRINTFN(4, ("%s%s: slip receive end\n",
673 			    (m->m_len % 16 != 0) ? "\n" :  "",
674 			    device_xname(sc->sc_dev)));
675 
676 			bcsp_pktintegrity_receive(sc, sc->sc_rxp);
677 			sc->sc_rxp = NULL;
678 			sc->sc_slip_rxexp = BCSP_SLIP_PKTSTART;
679 		}
680 		sc->sc_stats.byte_rx++;
681 		return 0;
682 
683 	case BCSP_SLIP_ESCAPE:
684 
685 		DPRINTFN(4, ("  esc"));
686 
687 		if (sc->sc_slip_rxexp == BCSP_SLIP_ESCAPE) {
688 			discard = 1;
689 			errstr = "waiting 0xdc or 0xdb";
690 		} else
691 			sc->sc_slip_rxexp = BCSP_SLIP_ESCAPE;
692 		break;
693 
694 	default:
695 		DPRINTFN(4, (" 0x%02x%s",
696 		    c, (m->m_len % 16 == 15) ? "\n" :  ""));
697 
698 		switch (sc->sc_slip_rxexp) {
699 		case BCSP_SLIP_PKTSTART:
700 			discard = 1;
701 			errstr = "waiting 0xc0";
702 			break;
703 
704 		case BCSP_SLIP_ESCAPE:
705 			if (c == BCSP_SLIP_ESCAPE_PKTEND)
706 				mtod(m, uint8_t *)[m->m_len++] =
707 				    BCSP_SLIP_PKTEND;
708 			else if (c == BCSP_SLIP_ESCAPE_ESCAPE)
709 				mtod(m, uint8_t *)[m->m_len++] =
710 				    BCSP_SLIP_ESCAPE;
711 			else {
712 				discard = 1;
713 				errstr = "unknown escape";
714 			}
715 			sc->sc_slip_rxexp = 0;
716 			break;
717 
718 		default:
719 			mtod(m, uint8_t *)[m->m_len++] = c;
720 		}
721 		sc->sc_rxp->m_pkthdr.len++;
722 	}
723 	if (discard) {
724 discarded:
725 #ifdef BCSP_DEBUG
726 		DPRINTFN(4, ("%s: receives unexpected byte 0x%02x: %s\n",
727 		    device_xname(sc->sc_dev), c, errstr));
728 #else
729 		__USE(errstr);
730 #endif
731 	}
732 	sc->sc_stats.byte_rx++;
733 
734 	return 0;
735 }
736 
737 
738 /*
739  * BCSP Packet Integrity Layer functions:
740  *   handling Payload Length, Checksum, CRC.
741  */
742 static void
743 bcsp_pktintegrity_transmit(struct bcsp_softc *sc)
744 {
745 	struct mbuf *m = sc->sc_txp;
746 	bcsp_hdr_t *hdrp = mtod(m, bcsp_hdr_t *);
747 	int pldlen;
748 
749 	DPRINTFN(3, ("%s: pi transmit\n", device_xname(sc->sc_dev)));
750 
751 	pldlen = m->m_pkthdr.len - sizeof(bcsp_hdr_t);
752 
753 	if (sc->sc_pi_txcrc)
754 		hdrp->flags |= BCSP_FLAGS_CRC_PRESENT;
755 
756 	BCSP_SET_PLEN(hdrp, pldlen);
757 	BCSP_SET_CSUM(hdrp);
758 
759 	if (sc->sc_pi_txcrc) {
760 		struct mbuf *_m;
761 		int n = 0;
762 		uint16_t crc = 0xffff;
763 		uint8_t *buf;
764 
765 		for (_m = m; _m != NULL; _m = _m->m_next) {
766 			buf = mtod(_m, uint8_t *);
767 			for (n = 0; n < _m->m_len; n++)
768 				bcsp_crc_update(&crc, *(buf + n));
769 		}
770 		crc = htobe16(bcsp_crc_reverse(crc));
771 		m_copyback(m, m->m_pkthdr.len, sizeof(crc), &crc);
772 	}
773 
774 #ifdef BCSP_DEBUG
775 	if (bcsp_debug == 4)
776 		bcsp_packet_print(m);
777 #endif
778 
779 	bcsp_slip_transmit(sc->sc_tp);
780 }
781 
782 static void
783 bcsp_pktintegrity_receive(struct bcsp_softc *sc, struct mbuf *m)
784 {
785 	bcsp_hdr_t *hdrp = mtod(m, bcsp_hdr_t *);
786 	u_int pldlen;
787 	int discard = 0;
788 	uint16_t crc = 0xffff;
789 	const char *errstr
790 
791 	DPRINTFN(3, ("%s: pi receive\n", device_xname(sc->sc_dev)));
792 #ifdef BCSP_DEBUG
793 	if (bcsp_debug == 4)
794 		bcsp_packet_print(m);
795 #endif
796 
797 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
798 
799 	pldlen = m->m_pkthdr.len - sizeof(bcsp_hdr_t) -
800 	    ((hdrp->flags & BCSP_FLAGS_CRC_PRESENT) ? sizeof(crc) : 0);
801 	if (pldlen > 0xfff) {
802 		discard = 1;
803 		errstr = "Payload Length";
804 		goto discarded;
805 	}
806 	if (hdrp->csum != BCSP_GET_CSUM(hdrp)) {
807 		discard = 1;
808 		errstr = "Checksum";
809 		goto discarded;
810 	}
811 	if (BCSP_GET_PLEN(hdrp) != pldlen) {
812 		discard = 1;
813 		errstr = "Payload Length";
814 		goto discarded;
815 	}
816 	if (hdrp->flags & BCSP_FLAGS_CRC_PRESENT) {
817 		struct mbuf *_m;
818 		int i, n;
819 		uint16_t crc0;
820 		uint8_t *buf;
821 
822 		i = 0;
823 		n = 0;
824 		for (_m = m; _m != NULL; _m = _m->m_next) {
825 			buf = mtod(m, uint8_t *);
826 			for (n = 0;
827 			    n < _m->m_len && i < sizeof(bcsp_hdr_t) + pldlen;
828 			    n++, i++)
829 				bcsp_crc_update(&crc, *(buf + n));
830 		}
831 
832 		m_copydata(_m, n, sizeof(crc0), &crc0);
833 		if (be16toh(crc0) != bcsp_crc_reverse(crc)) {
834 			discard = 1;
835 			errstr = "CRC";
836 		} else
837 			/* Shaves CRC */
838 			m_adj(m, (int)(0 - sizeof(crc)));
839 	}
840 
841 	if (discard) {
842 discarded:
843 #ifdef BCSP_DEBUG
844 		DPRINTFN(3, ("%s: receives unexpected packet: %s\n",
845 		    device_xname(sc->sc_dev), errstr));
846 #else
847 		__USE(errstr);
848 #endif
849 		m_freem(m);
850 	} else
851 		bcsp_mux_receive(sc, m);
852 }
853 
854 static const uint16_t crctbl[] = {
855 	0x0000, 0x1081, 0x2102, 0x3183,
856 	0x4204, 0x5285, 0x6306, 0x7387,
857 	0x8408, 0x9489, 0xa50a, 0xb58b,
858 	0xc60c, 0xd68d, 0xe70e, 0xf78f,
859 };
860 
861 static void
862 bcsp_crc_update(uint16_t *crc, uint8_t d)
863 {
864 	uint16_t reg = *crc;
865 
866 	reg = (reg >> 4) ^ crctbl[(reg ^ d) & 0x000f];
867 	reg = (reg >> 4) ^ crctbl[(reg ^ (d >> 4)) & 0x000f];
868 
869 	*crc = reg;
870 }
871 
872 static uint16_t
873 bcsp_crc_reverse(uint16_t crc)
874 {
875 	uint16_t b, rev;
876 
877 	for (b = 0, rev = 0; b < 16; b++) {
878 		rev = rev << 1;
879 		rev |= (crc & 1);
880 		crc = crc >> 1;
881 	}
882 
883 	return rev;
884 }
885 
886 
887 /*
888  * BCSP MUX Layer functions
889  */
890 static void
891 bcsp_mux_transmit(struct bcsp_softc *sc)
892 {
893 	struct mbuf *m;
894 	bcsp_hdr_t *hdrp;
895 
896 	DPRINTFN(2, ("%s: mux transmit: sc_flags=0x%x, choke=%d",
897 	    device_xname(sc->sc_dev), sc->sc_flags, sc->sc_mux_choke));
898 
899 	if (sc->sc_mux_choke) {
900 		struct mbuf *_m = NULL;
901 
902 		/* In this case, send only Link Establishment packet */
903 		for (m = MBUFQ_FIRST(&sc->sc_dgq); m != NULL;
904 		    _m = m, m = MBUFQ_NEXT(m)) {
905 			hdrp = mtod(m, bcsp_hdr_t *);
906 			if (hdrp->ident == BCSP_CHANNEL_LE) {
907 				if (m == MBUFQ_FIRST(&sc->sc_dgq))
908 					MBUFQ_DEQUEUE(&sc->sc_dgq, m);
909 				else {
910 					if (m->m_nextpkt == NULL)
911 						sc->sc_dgq.mq_last =
912 						    &_m->m_nextpkt;
913 					_m->m_nextpkt = m->m_nextpkt;
914 					m->m_nextpkt = NULL;
915 				}
916 				goto transmit;
917 			}
918 		}
919 		DPRINTFN(2, ("\n"));
920 		return;
921 	}
922 
923 	/*
924 	 * The MUX Layer always gives priority to packets from the Datagram
925 	 * Queue Layer over the Sequencing Layer.
926 	 */
927 	if (MBUFQ_FIRST(&sc->sc_dgq)) {
928 		MBUFQ_DEQUEUE(&sc->sc_dgq, m);
929 		goto transmit;
930 	}
931 	if (MBUFQ_FIRST(&sc->sc_seqq)) {
932 		MBUFQ_DEQUEUE(&sc->sc_seqq, m);
933 		hdrp = mtod(m, bcsp_hdr_t *);
934 		hdrp->flags |= BCSP_FLAGS_PROTOCOL_REL;		/* Reliable */
935 		goto transmit;
936 	}
937 	bcsp_start(sc);
938 	if (sc->sc_mux_send_ack == true) {
939 		m = bcsp_create_ackpkt();
940 		if (m != NULL)
941 			goto transmit;
942 		aprint_error_dev(sc->sc_dev, "out of memory\n");
943 		sc->sc_stats.err_tx++;
944 	}
945 
946 	/* Nothing to send */
947 	DPRINTFN(2, ("\n"));
948 	return;
949 
950 transmit:
951 	DPRINTFN(2, (", txack=%d, send_ack=%d\n",
952 	    bcsp_get_txack(sc), sc->sc_mux_send_ack));
953 
954 	hdrp = mtod(m, bcsp_hdr_t *);
955 	hdrp->flags |=
956 	    (bcsp_get_txack(sc) << BCSP_FLAGS_ACK_SHIFT) & BCSP_FLAGS_ACK_MASK;
957 	if (sc->sc_mux_send_ack == true)
958 		sc->sc_mux_send_ack = false;
959 
960 #ifdef BCSP_DEBUG
961 	if (bcsp_debug == 3)
962 		bcsp_packet_print(m);
963 #endif
964 
965 	sc->sc_txp = m;
966 	bcsp_pktintegrity_transmit(sc);
967 }
968 
969 static void
970 bcsp_mux_receive(struct bcsp_softc *sc, struct mbuf *m)
971 {
972 	bcsp_hdr_t *hdrp = mtod(m, bcsp_hdr_t *);
973 	const u_int rxack = BCSP_FLAGS_ACK(hdrp->flags);
974 
975 	DPRINTFN(2, ("%s: mux receive: flags=0x%x, ident=%d, rxack=%d\n",
976 	    device_xname(sc->sc_dev), hdrp->flags, hdrp->ident, rxack));
977 #ifdef BCSP_DEBUG
978 	if (bcsp_debug == 3)
979 		bcsp_packet_print(m);
980 #endif
981 
982 	bcsp_signal_rxack(sc, rxack);
983 
984 	microtime(&sc->sc_mux_lastrx);
985 
986 	/* if the Ack Packet received then discard */
987 	if (BCSP_FLAGS_SEQ(hdrp->flags) == 0 &&
988 	    hdrp->ident == BCSP_IDENT_ACKPKT &&
989 	    BCSP_GET_PLEN(hdrp) == 0) {
990 		m_freem(m);
991 		return;
992 	}
993 
994 	if (hdrp->flags & BCSP_FLAGS_PROTOCOL_REL)
995 		bcsp_sequencing_receive(sc, m);
996 	else
997 		bcsp_datagramq_receive(sc, m);
998 }
999 
1000 static __inline void
1001 bcsp_send_ack_command(struct bcsp_softc *sc)
1002 {
1003 
1004 	DPRINTFN(2, ("%s: mux send_ack_command\n", device_xname(sc->sc_dev)));
1005 
1006 	sc->sc_mux_send_ack = true;
1007 }
1008 
1009 static __inline struct mbuf *
1010 bcsp_create_ackpkt(void)
1011 {
1012 	struct mbuf *m;
1013 	bcsp_hdr_t *hdrp;
1014 
1015 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1016 	if (m != NULL) {
1017 		m->m_pkthdr.len = m->m_len = sizeof(bcsp_hdr_t);
1018 		hdrp = mtod(m, bcsp_hdr_t *);
1019 		/*
1020 		 * An Ack Packet has the following fields:
1021 		 *	Ack Field:			txack (not set yet)
1022 		 *	Seq Field:			0
1023 		 *	Protocol Identifier Field:	0
1024 		 *	Protocol Type Field:		Any value
1025 		 *	Payload Length Field:		0
1026 		 */
1027 		memset(hdrp, 0, sizeof(bcsp_hdr_t));
1028 	}
1029 	return m;
1030 }
1031 
1032 static __inline void
1033 bcsp_set_choke(struct bcsp_softc *sc, bool choke)
1034 {
1035 
1036 	DPRINTFN(2, ("%s: mux set choke=%d\n", device_xname(sc->sc_dev), choke));
1037 
1038 	sc->sc_mux_choke = choke;
1039 }
1040 
1041 
1042 /*
1043  * BCSP Sequencing Layer functions
1044  */
1045 static void
1046 bcsp_sequencing_receive(struct bcsp_softc *sc, struct mbuf *m)
1047 {
1048 	bcsp_hdr_t hdr;
1049 	uint32_t rxseq;
1050 
1051 	m_copydata(m, 0, sizeof(bcsp_hdr_t), &hdr);
1052 	rxseq = BCSP_FLAGS_SEQ(hdr.flags);
1053 
1054 	DPRINTFN(1, ("%s: seq receive: rxseq=%d, expected %d\n",
1055 	    device_xname(sc->sc_dev), rxseq, sc->sc_seq_expected_rxseq));
1056 #ifdef BCSP_DEBUG
1057 	if (bcsp_debug == 2)
1058 		bcsp_packet_print(m);
1059 #endif
1060 
1061 	/*
1062 	 * We remove the header of BCSP and add the 'uint8_t type' of
1063 	 * hci_*_hdr_t to the head.
1064 	 */
1065 	m_adj(m, sizeof(bcsp_hdr_t) - sizeof(uint8_t));
1066 
1067 	if (rxseq != sc->sc_seq_expected_rxseq) {
1068 		m_freem(m);
1069 
1070 		/* send ack packet, if needly */
1071 		bcsp_mux_transmit(sc);
1072 
1073 		return;
1074 	}
1075 
1076 	switch (hdr.ident) {
1077 	case BCSP_CHANNEL_HCI_CMDEVT:
1078 		*(mtod(m, uint8_t *)) = HCI_EVENT_PKT;
1079 		if (!hci_input_event(sc->sc_unit, m))
1080 			sc->sc_stats.err_rx++;
1081 
1082 		sc->sc_stats.evt_rx++;
1083 		break;
1084 
1085 	case BCSP_CHANNEL_HCI_ACL:
1086 		*(mtod(m, uint8_t *)) = HCI_ACL_DATA_PKT;
1087 		if (!hci_input_acl(sc->sc_unit, m))
1088 			sc->sc_stats.err_rx++;
1089 
1090 		sc->sc_stats.acl_rx++;
1091 		break;
1092 
1093 	case BCSP_CHANNEL_HCI_SCO:
1094 		*(mtod(m, uint8_t *)) = HCI_SCO_DATA_PKT;
1095 		if (!hci_input_sco(sc->sc_unit, m))
1096 			sc->sc_stats.err_rx++;
1097 
1098 		sc->sc_stats.sco_rx++;
1099 		break;
1100 
1101 	case BCSP_CHANNEL_HQ:
1102 	case BCSP_CHANNEL_DEVMGT:
1103 	case BCSP_CHANNEL_L2CAP:
1104 	case BCSP_CHANNEL_RFCOMM:
1105 	case BCSP_CHANNEL_SDP:
1106 	case BCSP_CHANNEL_DFU:
1107 	case BCSP_CHANNEL_VM:
1108 	default:
1109 		aprint_error_dev(sc->sc_dev,
1110 		    "received reliable packet with not support channel %d\n",
1111 		    hdr.ident);
1112 		m_freem(m);
1113 		break;
1114 	}
1115 
1116 	sc->sc_seq_expected_rxseq =
1117 	    (sc->sc_seq_expected_rxseq + 1) & BCSP_FLAGS_SEQ_MASK;
1118 	sc->sc_seq_txack = sc->sc_seq_expected_rxseq;
1119 	bcsp_send_ack_command(sc);
1120 }
1121 
1122 static bool
1123 bcsp_tx_reliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1124 {
1125 	bcsp_hdr_t *hdrp;
1126 	struct mbuf *_m;
1127 	u_int pldlen;
1128 	int s;
1129 
1130 	DPRINTFN(1, ("%s: seq transmit:"
1131 	    "protocol_id=%d, winspace=%d, txseq=%d\n", device_xname(sc->sc_dev),
1132 	    protocol_id, sc->sc_seq_winspace, sc->sc_seq_txseq));
1133 
1134 	for (pldlen = 0, _m = m; _m != NULL; _m = _m->m_next) {
1135 		if (_m->m_len < 0)
1136 			return false;
1137 		pldlen += _m->m_len;
1138 	}
1139 	if (pldlen > 0xfff)
1140 		return false;
1141 	if (protocol_id == BCSP_IDENT_ACKPKT || protocol_id > 15)
1142 		return false;
1143 
1144 	if (sc->sc_seq_winspace == 0)
1145 		return false;
1146 
1147 	M_PREPEND(m, sizeof(bcsp_hdr_t), M_DONTWAIT);
1148 	if (m == NULL) {
1149 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1150 		return false;
1151 	}
1152 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
1153 
1154 	hdrp = mtod(m, bcsp_hdr_t *);
1155 	memset(hdrp, 0, sizeof(bcsp_hdr_t));
1156 	hdrp->flags |= sc->sc_seq_txseq;
1157 	hdrp->ident = protocol_id;
1158 
1159 	callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1160 
1161 	s = splserial();
1162 	MBUFQ_ENQUEUE(&sc->sc_seqq, m);
1163 	splx(s);
1164 	sc->sc_transmit_callback = bcsp_reliabletx_callback;
1165 
1166 #ifdef BCSP_DEBUG
1167 	if (bcsp_debug == 2)
1168 		bcsp_packet_print(m);
1169 #endif
1170 
1171 	sc->sc_seq_txseq = (sc->sc_seq_txseq + 1) & BCSP_FLAGS_SEQ_MASK;
1172 	sc->sc_seq_winspace--;
1173 	_m = m_copym(m, 0, M_COPYALL, M_DONTWAIT);
1174 	if (_m == NULL) {
1175 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1176 		return false;
1177 	}
1178 	MBUFQ_ENQUEUE(&sc->sc_seq_retryq, _m);
1179 	bcsp_mux_transmit(sc);
1180 
1181 	return true;
1182 }
1183 
1184 #if 0
1185 static bool
1186 bcsp_rx_reliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1187 {
1188 
1189 	return false;
1190 }
1191 
1192 /* XXXX:  I can't understand meaning this function... */
1193 static __inline void
1194 bcsp_link_failed(struct bcsp_softc *sc)
1195 {
1196 
1197 	return (sc->sc_seq_retries >= sc->sc_seq_retry_limit);
1198 }
1199 #endif
1200 
1201 static __inline u_int
1202 bcsp_get_txack(struct bcsp_softc *sc)
1203 {
1204 
1205 	return sc->sc_seq_txack;
1206 }
1207 
1208 static void
1209 bcsp_signal_rxack(struct bcsp_softc *sc, uint32_t rxack)
1210 {
1211 	bcsp_hdr_t *hdrp;
1212 	struct mbuf *m;
1213 	uint32_t seqno = (rxack - 1) & BCSP_FLAGS_SEQ_MASK;
1214 	int s;
1215 
1216 	DPRINTFN(1, ("%s: seq signal rxack: rxack=%d\n",
1217 	    device_xname(sc->sc_dev), rxack));
1218 
1219 	s = splserial();
1220 	m = MBUFQ_FIRST(&sc->sc_seq_retryq);
1221 	while (m != NULL) {
1222 		hdrp = mtod(m, bcsp_hdr_t *);
1223 		if (BCSP_FLAGS_SEQ(hdrp->flags) == seqno) {
1224 			struct mbuf *m0;
1225 
1226 			for (m0 = MBUFQ_FIRST(&sc->sc_seq_retryq);
1227 			    m0 != MBUFQ_NEXT(m);
1228 			    m0 = MBUFQ_FIRST(&sc->sc_seq_retryq)) {
1229 				MBUFQ_DEQUEUE(&sc->sc_seq_retryq, m0);
1230 				m_freem(m0);
1231 				sc->sc_seq_winspace++;
1232 			}
1233 			break;
1234 		}
1235 		m = MBUFQ_NEXT(m);
1236 	}
1237 	splx(s);
1238 	sc->sc_seq_retries = 0;
1239 
1240 	if (sc->sc_seq_winspace == sc->sc_seq_winsize)
1241 		callout_stop(&sc->sc_seq_timer);
1242 	else
1243 		callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1244 }
1245 
1246 static void
1247 bcsp_reliabletx_callback(struct bcsp_softc *sc, struct mbuf *m)
1248 {
1249 
1250 	m_freem(m);
1251 }
1252 
1253 static void
1254 bcsp_timer_timeout(void *arg)
1255 {
1256 	struct bcsp_softc *sc = arg;
1257 	struct mbuf *m, *_m;
1258 	int s, i = 0;
1259 
1260 	DPRINTFN(1, ("%s: seq timeout: retries=%d\n",
1261 	    device_xname(sc->sc_dev), sc->sc_seq_retries));
1262 
1263 	s = splserial();
1264 	for (m = MBUFQ_FIRST(&sc->sc_seq_retryq); m != NULL;
1265 	    m = MBUFQ_NEXT(m)) {
1266 		_m = m_copym(m, 0, M_COPYALL, M_DONTWAIT);
1267 		if (_m == NULL) {
1268 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1269 			return;
1270 		}
1271 		MBUFQ_ENQUEUE(&sc->sc_seqq, _m);
1272 		i++;
1273 	}
1274 	splx(s);
1275 
1276 	if (i != 0) {
1277 		if (++sc->sc_seq_retries < sc->sc_seq_retry_limit)
1278 			callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1279 		else {
1280 			aprint_error_dev(sc->sc_dev,
1281 			    "reached the retry limit."
1282 			    " restart the link-establishment\n");
1283 			bcsp_sequencing_reset(sc);
1284 			bcsp_start_le(sc);
1285 			return;
1286 		}
1287 	}
1288 	bcsp_mux_transmit(sc);
1289 }
1290 
1291 static void
1292 bcsp_sequencing_reset(struct bcsp_softc *sc)
1293 {
1294 	int s;
1295 
1296 	s = splserial();
1297 	MBUFQ_DRAIN(&sc->sc_seqq);
1298 	MBUFQ_DRAIN(&sc->sc_seq_retryq);
1299 	splx(s);
1300 
1301 
1302 	sc->sc_seq_txseq = 0;
1303 	sc->sc_seq_txack = 0;
1304 	sc->sc_seq_winspace = sc->sc_seq_winsize;
1305 	sc->sc_seq_retries = 0;
1306 	callout_stop(&sc->sc_seq_timer);
1307 
1308 	sc->sc_mux_send_ack = false;
1309 
1310 	/* XXXX: expected_rxseq should be set by MUX Layer */
1311 	sc->sc_seq_expected_rxseq = 0;
1312 }
1313 
1314 
1315 /*
1316  * BCSP Datagram Queue Layer functions
1317  */
1318 static void
1319 bcsp_datagramq_receive(struct bcsp_softc *sc, struct mbuf *m)
1320 {
1321 	bcsp_hdr_t hdr;
1322 
1323 	DPRINTFN(1, ("%s: dgq receive\n", device_xname(sc->sc_dev)));
1324 #ifdef BCSP_DEBUG
1325 	if (bcsp_debug == 2)
1326 		bcsp_packet_print(m);
1327 #endif
1328 
1329 	m_copydata(m, 0, sizeof(bcsp_hdr_t), &hdr);
1330 
1331 	switch (hdr.ident) {
1332 	case BCSP_CHANNEL_LE:
1333 		m_adj(m, sizeof(bcsp_hdr_t));
1334 		bcsp_input_le(sc, m);
1335 		break;
1336 
1337 	case BCSP_CHANNEL_HCI_SCO:
1338 		/*
1339 		 * We remove the header of BCSP and add the 'uint8_t type' of
1340 		 * hci_scodata_hdr_t to the head.
1341 		 */
1342 		m_adj(m, sizeof(bcsp_hdr_t) - sizeof(uint8_t));
1343 		*(mtod(m, uint8_t *)) = HCI_SCO_DATA_PKT;
1344 		if (!hci_input_sco(sc->sc_unit, m))
1345 			sc->sc_stats.err_rx++;
1346 
1347 		sc->sc_stats.sco_rx++;
1348 		break;
1349 
1350 	default:
1351 		aprint_error_dev(sc->sc_dev,
1352 		    "received unreliable packet with not support channel %d\n",
1353 		    hdr.ident);
1354 		m_freem(m);
1355 		break;
1356 	}
1357 }
1358 
1359 static bool
1360 bcsp_tx_unreliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1361 {
1362 	bcsp_hdr_t *hdrp;
1363 	struct mbuf *_m;
1364 	u_int pldlen;
1365 	int s;
1366 
1367 	DPRINTFN(1, ("%s: dgq transmit: protocol_id=%d,",
1368 	    device_xname(sc->sc_dev), protocol_id));
1369 
1370 	for (pldlen = 0, _m = m; _m != NULL; _m = m->m_next) {
1371 		if (_m->m_len < 0)
1372 			return false;
1373 		pldlen += _m->m_len;
1374 	}
1375 	DPRINTFN(1, (" pldlen=%d\n", pldlen));
1376 	if (pldlen > 0xfff)
1377 		return false;
1378 	if (protocol_id == BCSP_IDENT_ACKPKT || protocol_id > 15)
1379 		return false;
1380 
1381 	M_PREPEND(m, sizeof(bcsp_hdr_t), M_DONTWAIT);
1382 	if (m == NULL) {
1383 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1384 		return false;
1385 	}
1386 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
1387 
1388 	hdrp = mtod(m, bcsp_hdr_t *);
1389 	memset(hdrp, 0, sizeof(bcsp_hdr_t));
1390 	hdrp->ident = protocol_id;
1391 
1392 	s = splserial();
1393 	MBUFQ_ENQUEUE(&sc->sc_dgq, m);
1394 	splx(s);
1395 	sc->sc_transmit_callback = bcsp_unreliabletx_callback;
1396 
1397 #ifdef BCSP_DEBUG
1398 	if (bcsp_debug == 2)
1399 		bcsp_packet_print(m);
1400 #endif
1401 
1402 	bcsp_mux_transmit(sc);
1403 
1404 	return true;
1405 }
1406 
1407 #if 0
1408 static bool
1409 bcsp_rx_unreliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1410 {
1411 
1412 	return false;
1413 }
1414 #endif
1415 
1416 static void
1417 bcsp_unreliabletx_callback(struct bcsp_softc *sc, struct mbuf *m)
1418 {
1419 
1420 	if (M_GETCTX(m, void *) == NULL)
1421 		m_freem(m);
1422 	else if (!hci_complete_sco(sc->sc_unit, m))
1423 		sc->sc_stats.err_tx++;
1424 }
1425 
1426 
1427 /*
1428  * BlueCore Link Establishment Protocol functions
1429  */
1430 static const uint8_t sync[] = BCSP_LE_SYNC;
1431 static const uint8_t syncresp[] = BCSP_LE_SYNCRESP;
1432 static const uint8_t conf[] = BCSP_LE_CONF;
1433 static const uint8_t confresp[] = BCSP_LE_CONFRESP;
1434 
1435 static int
1436 bcsp_start_le(struct bcsp_softc *sc)
1437 {
1438 
1439 	DPRINTF(("%s: start link-establish\n", device_xname(sc->sc_dev)));
1440 
1441 	bcsp_set_choke(sc, true);
1442 
1443 	if (!sc->sc_le_muzzled) {
1444 		struct mbuf *m;
1445 
1446 		m = m_gethdr(M_WAIT, MT_DATA);
1447 		m->m_pkthdr.len = m->m_len = 0;
1448 		m_copyback(m, 0, sizeof(sync), sync);
1449 		if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE)) {
1450 			aprint_error_dev(sc->sc_dev,
1451 			    "le-packet transmit failed\n");
1452 			return EINVAL;
1453 		}
1454 	}
1455 	callout_schedule(&sc->sc_le_timer, BCSP_LE_TSHY_TIMEOUT);
1456 
1457 	sc->sc_le_state = le_state_shy;
1458 	return 0;
1459 }
1460 
1461 static void
1462 bcsp_terminate_le(struct bcsp_softc *sc)
1463 {
1464 	struct mbuf *m;
1465 
1466 	/* terminate link-establishment */
1467 	callout_stop(&sc->sc_le_timer);
1468 	bcsp_set_choke(sc, true);
1469 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1470 	if (m == NULL)
1471 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1472 	else {
1473 		/* length of le packets is 4 */
1474 		m->m_pkthdr.len = m->m_len = 0;
1475 		m_copyback(m, 0, sizeof(sync), sync);
1476 		if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1477 			aprint_error_dev(sc->sc_dev,
1478 			    "link-establishment terminations failed\n");
1479 	}
1480 }
1481 
1482 static void
1483 bcsp_input_le(struct bcsp_softc *sc, struct mbuf *m)
1484 {
1485 	uint32_t *rcvpkt;
1486 	int i;
1487 	const uint8_t *rplypkt;
1488 	static struct {
1489 		const char *type;
1490 		const uint8_t *datap;
1491 	} pkt[] = {
1492 		{ "sync",	sync },
1493 		{ "sync-resp",	syncresp },
1494 		{ "conf",	conf },
1495 		{ "conf-resp",	confresp },
1496 
1497 		{ NULL, 0 }
1498 	};
1499 
1500 	DPRINTFN(0, ("%s: le input: state %d, muzzled %d\n",
1501 	    device_xname(sc->sc_dev), sc->sc_le_state, sc->sc_le_muzzled));
1502 #ifdef BCSP_DEBUG
1503 	if (bcsp_debug == 1)
1504 		bcsp_packet_print(m);
1505 #endif
1506 
1507 	rcvpkt = mtod(m, uint32_t *);
1508 	i = 0;
1509 
1510 	/* length of le packets is 4 */
1511 	if (m->m_len == sizeof(uint32_t))
1512 		for (i = 0; pkt[i].type != NULL; i++)
1513 			if (*(const uint32_t *)pkt[i].datap == *rcvpkt)
1514 				break;
1515 	if (m->m_len != sizeof(uint32_t) || pkt[i].type == NULL) {
1516 		aprint_error_dev(sc->sc_dev, "received unknown packet\n");
1517 		m_freem(m);
1518 		return;
1519 	}
1520 
1521 	rplypkt = NULL;
1522 	switch (sc->sc_le_state) {
1523 	case le_state_shy:
1524 		if (*rcvpkt == *(const uint32_t *)sync) {
1525 			sc->sc_le_muzzled = false;
1526 			rplypkt = syncresp;
1527 		} else if (*rcvpkt == *(const uint32_t *)syncresp) {
1528 			DPRINTF(("%s: state change to curious\n",
1529 			    device_xname(sc->sc_dev)));
1530 
1531 			rplypkt = conf;
1532 			callout_schedule(&sc->sc_le_timer,
1533 			    BCSP_LE_TCONF_TIMEOUT);
1534 			sc->sc_le_state = le_state_curious;
1535 		} else
1536 			aprint_error_dev(sc->sc_dev,
1537 			    "received an unknown packet at shy\n");
1538 		break;
1539 
1540 	case le_state_curious:
1541 		if (*rcvpkt == *(const uint32_t *)sync)
1542 			rplypkt = syncresp;
1543 		else if (*rcvpkt == *(const uint32_t *)conf)
1544 			rplypkt = confresp;
1545 		else if (*rcvpkt == *(const uint32_t *)confresp) {
1546 			DPRINTF(("%s: state change to garrulous:\n",
1547 			    device_xname(sc->sc_dev)));
1548 
1549 			bcsp_set_choke(sc, false);
1550 			callout_stop(&sc->sc_le_timer);
1551 			sc->sc_le_state = le_state_garrulous;
1552 		} else
1553 			aprint_error_dev(sc->sc_dev,
1554 			    "received unknown packet at curious\n");
1555 		break;
1556 
1557 	case le_state_garrulous:
1558 		if (*rcvpkt == *(const uint32_t *)conf)
1559 			rplypkt = confresp;
1560 		else if (*rcvpkt == *(const uint32_t *)sync) {
1561 			/* XXXXX */
1562 			aprint_error_dev(sc->sc_dev,
1563 			    "received sync! peer to reset?\n");
1564 
1565 			bcsp_sequencing_reset(sc);
1566 			rplypkt = sync;
1567 			sc->sc_le_state = le_state_shy;
1568 		} else
1569 			aprint_error_dev(sc->sc_dev,
1570 			    "received unknown packet at garrulous\n");
1571 		break;
1572 	}
1573 
1574 	m_freem(m);
1575 
1576 	if (rplypkt != NULL) {
1577 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1578 		if (m == NULL)
1579 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1580 		else {
1581 			/* length of le packets is 4 */
1582 			m->m_pkthdr.len = m->m_len = 0;
1583 			m_copyback(m, 0, 4, rplypkt);
1584 			if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1585 				aprint_error_dev(sc->sc_dev,
1586 				    "le-packet transmit failed\n");
1587 		}
1588 	}
1589 }
1590 
1591 static void
1592 bcsp_le_timeout(void *arg)
1593 {
1594 	struct bcsp_softc *sc = arg;
1595 	struct mbuf *m;
1596 	int timeout;
1597 	const uint8_t *sndpkt = NULL;
1598 
1599 	DPRINTFN(0, ("%s: le timeout: state %d, muzzled %d\n",
1600 	    device_xname(sc->sc_dev), sc->sc_le_state, sc->sc_le_muzzled));
1601 
1602 	switch (sc->sc_le_state) {
1603 	case le_state_shy:
1604 		if (!sc->sc_le_muzzled)
1605 			sndpkt = sync;
1606 		timeout = BCSP_LE_TSHY_TIMEOUT;
1607 		break;
1608 
1609 	case le_state_curious:
1610 		sndpkt = conf;
1611 		timeout = BCSP_LE_TCONF_TIMEOUT;
1612 		break;
1613 
1614 	default:
1615 		aprint_error_dev(sc->sc_dev,
1616 		    "timeout happen at unknown state %d\n", sc->sc_le_state);
1617 		return;
1618 	}
1619 
1620 	if (sndpkt != NULL) {
1621 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1622 		if (m == NULL)
1623 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1624 		else {
1625 			/* length of le packets is 4 */
1626 			m->m_pkthdr.len = m->m_len = 0;
1627 			m_copyback(m, 0, 4, sndpkt);
1628 			if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1629 				aprint_error_dev(sc->sc_dev,
1630 				    "le-packet transmit failed\n");
1631 		}
1632 	}
1633 
1634 	callout_schedule(&sc->sc_le_timer, timeout);
1635 }
1636 
1637 
1638 /*
1639  * BlueCore Serial Protocol functions.
1640  */
1641 static int
1642 bcsp_enable(device_t self)
1643 {
1644 	struct bcsp_softc *sc = device_private(self);
1645 	int s;
1646 
1647 	if (sc->sc_flags & BCSP_ENABLED)
1648 		return 0;
1649 
1650 	s = spltty();
1651 
1652 	sc->sc_flags |= BCSP_ENABLED;
1653 	sc->sc_flags &= ~BCSP_XMIT;
1654 
1655 	splx(s);
1656 
1657 	return 0;
1658 }
1659 
1660 static void
1661 bcsp_disable(device_t self)
1662 {
1663 	struct bcsp_softc *sc = device_private(self);
1664 	int s;
1665 
1666 	if ((sc->sc_flags & BCSP_ENABLED) == 0)
1667 		return;
1668 
1669 	s = spltty();
1670 
1671 	if (sc->sc_rxp) {
1672 		m_freem(sc->sc_rxp);
1673 		sc->sc_rxp = NULL;
1674 	}
1675 
1676 	if (sc->sc_txp) {
1677 		m_freem(sc->sc_txp);
1678 		sc->sc_txp = NULL;
1679 	}
1680 
1681 	MBUFQ_DRAIN(&sc->sc_cmdq);
1682 	MBUFQ_DRAIN(&sc->sc_aclq);
1683 	MBUFQ_DRAIN(&sc->sc_scoq);
1684 
1685 	sc->sc_flags &= ~BCSP_ENABLED;
1686 	splx(s);
1687 }
1688 
1689 static void
1690 bcsp_start(struct bcsp_softc *sc)
1691 {
1692 	struct mbuf *m;
1693 
1694 	KASSERT((sc->sc_flags & BCSP_XMIT) == 0);
1695 	KASSERT(sc->sc_txp == NULL);
1696 
1697 	if (MBUFQ_FIRST(&sc->sc_aclq)) {
1698 		MBUFQ_DEQUEUE(&sc->sc_aclq, m);
1699 		sc->sc_stats.acl_tx++;
1700 		sc->sc_flags |= BCSP_XMIT;
1701 		bcsp_tx_reliable_pkt(sc, m, BCSP_CHANNEL_HCI_ACL);
1702 	}
1703 
1704 	if (MBUFQ_FIRST(&sc->sc_cmdq)) {
1705 		MBUFQ_DEQUEUE(&sc->sc_cmdq, m);
1706 		sc->sc_stats.cmd_tx++;
1707 		sc->sc_flags |= BCSP_XMIT;
1708 		bcsp_tx_reliable_pkt(sc, m, BCSP_CHANNEL_HCI_CMDEVT);
1709 	}
1710 
1711 	if (MBUFQ_FIRST(&sc->sc_scoq)) {
1712 		MBUFQ_DEQUEUE(&sc->sc_scoq, m);
1713 		sc->sc_stats.sco_tx++;
1714 		/* XXXX: We can transmit with reliable */
1715 		sc->sc_flags |= BCSP_XMIT;
1716 		bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_HCI_SCO);
1717 	}
1718 
1719 	return;
1720 }
1721 
1722 static void
1723 bcsp_output_cmd(device_t self, struct mbuf *m)
1724 {
1725 	struct bcsp_softc *sc = device_private(self);
1726 	int s;
1727 
1728 	KASSERT(sc->sc_flags & BCSP_ENABLED);
1729 
1730 	m_adj(m, sizeof(uint8_t));
1731 	M_SETCTX(m, NULL);
1732 
1733 	s = spltty();
1734 	MBUFQ_ENQUEUE(&sc->sc_cmdq, m);
1735 	if ((sc->sc_flags & BCSP_XMIT) == 0)
1736 		bcsp_start(sc);
1737 
1738 	splx(s);
1739 }
1740 
1741 static void
1742 bcsp_output_acl(device_t self, struct mbuf *m)
1743 {
1744 	struct bcsp_softc *sc = device_private(self);
1745 	int s;
1746 
1747 	KASSERT(sc->sc_flags & BCSP_ENABLED);
1748 
1749 	m_adj(m, sizeof(uint8_t));
1750 	M_SETCTX(m, NULL);
1751 
1752 	s = spltty();
1753 	MBUFQ_ENQUEUE(&sc->sc_aclq, m);
1754 	if ((sc->sc_flags & BCSP_XMIT) == 0)
1755 		bcsp_start(sc);
1756 
1757 	splx(s);
1758 }
1759 
1760 static void
1761 bcsp_output_sco(device_t self, struct mbuf *m)
1762 {
1763 	struct bcsp_softc *sc = device_private(self);
1764 	int s;
1765 
1766 	KASSERT(sc->sc_flags & BCSP_ENABLED);
1767 
1768 	m_adj(m, sizeof(uint8_t));
1769 
1770 	s = spltty();
1771 	MBUFQ_ENQUEUE(&sc->sc_scoq, m);
1772 	if ((sc->sc_flags & BCSP_XMIT) == 0)
1773 		bcsp_start(sc);
1774 
1775 	splx(s);
1776 }
1777 
1778 static void
1779 bcsp_stats(device_t self, struct bt_stats *dest, int flush)
1780 {
1781 	struct bcsp_softc *sc = device_private(self);
1782 	int s;
1783 
1784 	s = spltty();
1785 	memcpy(dest, &sc->sc_stats, sizeof(struct bt_stats));
1786 
1787 	if (flush)
1788 		memset(&sc->sc_stats, 0, sizeof(struct bt_stats));
1789 
1790 	splx(s);
1791 }
1792 
1793 
1794 #ifdef BCSP_DEBUG
1795 static void
1796 bcsp_packet_print(struct mbuf *m)
1797 {
1798 	int i;
1799 	uint8_t *p;
1800 
1801 	for ( ; m != NULL; m = m->m_next) {
1802 		p = mtod(m, uint8_t *);
1803 		for (i = 0; i < m->m_len; i++) {
1804 			if (i % 16 == 0)
1805 				printf(" ");
1806 			printf(" %02x", *(p + i));
1807 			if (i % 16 == 15)
1808 				printf("\n");
1809 		}
1810 		printf("\n");
1811 	}
1812 }
1813 #endif
1814