xref: /netbsd-src/sys/dev/bluetooth/bcsp.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: bcsp.c,v 1.31 2019/01/24 09:33:03 knakahara 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.31 2019/01/24 09:33:03 knakahara 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 static int bcsp_match(device_t, cfdata_t, void *);
135 static void bcsp_attach(device_t, device_t, void *);
136 static int bcsp_detach(device_t, int);
137 
138 /* tty functions */
139 static int bcspopen(dev_t, struct tty *);
140 static int bcspclose(struct tty *, int);
141 static int bcspioctl(struct tty *, u_long, void *, int, struct lwp *);
142 
143 static int bcsp_slip_transmit(struct tty *);
144 static int bcsp_slip_receive(int, struct tty *);
145 
146 static void bcsp_pktintegrity_transmit(struct bcsp_softc *);
147 static void bcsp_pktintegrity_receive(struct bcsp_softc *, struct mbuf *);
148 static void bcsp_crc_update(uint16_t *, uint8_t);
149 static uint16_t bcsp_crc_reverse(uint16_t);
150 
151 static void bcsp_mux_transmit(struct bcsp_softc *sc);
152 static void bcsp_mux_receive(struct bcsp_softc *sc, struct mbuf *m);
153 static __inline void bcsp_send_ack_command(struct bcsp_softc *sc);
154 static __inline struct mbuf *bcsp_create_ackpkt(void);
155 static __inline void bcsp_set_choke(struct bcsp_softc *, bool);
156 
157 static void bcsp_sequencing_receive(struct bcsp_softc *, struct mbuf *);
158 static bool bcsp_tx_reliable_pkt(struct bcsp_softc *, struct mbuf *, u_int);
159 static __inline u_int bcsp_get_txack(struct bcsp_softc *);
160 static void bcsp_signal_rxack(struct bcsp_softc *, uint32_t);
161 static void bcsp_reliabletx_callback(struct bcsp_softc *, struct mbuf *);
162 static void bcsp_timer_timeout(void *);
163 static void bcsp_sequencing_reset(struct bcsp_softc *);
164 
165 static void bcsp_datagramq_receive(struct bcsp_softc *, struct mbuf *);
166 static bool bcsp_tx_unreliable_pkt(struct bcsp_softc *, struct mbuf *, u_int);
167 static void bcsp_unreliabletx_callback(struct bcsp_softc *, struct mbuf *);
168 
169 static int bcsp_start_le(struct bcsp_softc *);
170 static void bcsp_terminate_le(struct bcsp_softc *);
171 static void bcsp_input_le(struct bcsp_softc *, struct mbuf *);
172 static void bcsp_le_timeout(void *);
173 
174 static void bcsp_start(struct bcsp_softc *);
175 
176 /* bluetooth hci functions */
177 static int bcsp_enable(device_t);
178 static void bcsp_disable(device_t);
179 static void bcsp_output_cmd(device_t, struct mbuf *);
180 static void bcsp_output_acl(device_t, struct mbuf *);
181 static void bcsp_output_sco(device_t, struct mbuf *);
182 static void bcsp_stats(device_t, struct bt_stats *, int);
183 
184 #ifdef BCSP_DEBUG
185 static void bcsp_packet_print(struct mbuf *m);
186 #endif
187 
188 
189 /*
190  * It doesn't need to be exported, as only bcspattach() uses it,
191  * but there's no "official" way to make it static.
192  */
193 CFATTACH_DECL_NEW(bcsp, sizeof(struct bcsp_softc),
194     bcsp_match, bcsp_attach, bcsp_detach, NULL);
195 
196 static struct linesw bcsp_disc = {
197 	.l_name = "bcsp",
198 	.l_open = bcspopen,
199 	.l_close = bcspclose,
200 	.l_read = ttyerrio,
201 	.l_write = ttyerrio,
202 	.l_ioctl = bcspioctl,
203 	.l_rint = bcsp_slip_receive,
204 	.l_start = bcsp_slip_transmit,
205 	.l_modem = ttymodem,
206 	.l_poll = ttyerrpoll
207 };
208 
209 static const struct hci_if bcsp_hci = {
210 	.enable = bcsp_enable,
211 	.disable = bcsp_disable,
212 	.output_cmd = bcsp_output_cmd,
213 	.output_acl = bcsp_output_acl,
214 	.output_sco = bcsp_output_sco,
215 	.get_stats = bcsp_stats,
216 	.ipl = IPL_TTY,
217 };
218 
219 /* ARGSUSED */
220 void
221 bcspattach(int num __unused)
222 {
223 	int error;
224 
225 	error = ttyldisc_attach(&bcsp_disc);
226 	if (error) {
227 		aprint_error("%s: unable to register line discipline, "
228 		    "error = %d\n", bcsp_cd.cd_name, error);
229 		return;
230 	}
231 
232 	error = config_cfattach_attach(bcsp_cd.cd_name, &bcsp_ca);
233 	if (error) {
234 		aprint_error("%s: unable to register cfattach, error = %d\n",
235 		    bcsp_cd.cd_name, error);
236 		config_cfdriver_detach(&bcsp_cd);
237 		(void) ttyldisc_detach(&bcsp_disc);
238 	}
239 }
240 
241 /*
242  * Autoconf match routine.
243  *
244  * XXX: unused: config_attach_pseudo(9) does not call ca_match.
245  */
246 /* ARGSUSED */
247 static int
248 bcsp_match(device_t self __unused, cfdata_t cfdata __unused,
249 	   void *arg __unused)
250 {
251 
252 	/* pseudo-device; always present */
253 	return 1;
254 }
255 
256 /*
257  * Autoconf attach routine.  Called by config_attach_pseudo(9) when we
258  * open the line discipline.
259  */
260 /* ARGSUSED */
261 static void
262 bcsp_attach(device_t parent __unused, device_t self, void *aux __unused)
263 {
264 	struct bcsp_softc *sc = device_private(self);
265 	const struct sysctlnode *node;
266 	int rc, bcsp_node_num;
267 
268 	aprint_normal("\n");
269 	aprint_naive("\n");
270 
271 	sc->sc_dev = self;
272 	callout_init(&sc->sc_seq_timer, 0);
273 	callout_setfunc(&sc->sc_seq_timer, bcsp_timer_timeout, sc);
274 	callout_init(&sc->sc_le_timer, 0);
275 	callout_setfunc(&sc->sc_le_timer, bcsp_le_timeout, sc);
276 	sc->sc_seq_timeout = BCSP_SEQ_TX_TIMEOUT;
277 	sc->sc_seq_winsize = BCSP_SEQ_TX_WINSIZE;
278 	sc->sc_seq_retry_limit = BCSP_SEQ_TX_RETRY_LIMIT;
279 	MBUFQ_INIT(&sc->sc_seqq);
280 	MBUFQ_INIT(&sc->sc_seq_retryq);
281 	MBUFQ_INIT(&sc->sc_dgq);
282 	MBUFQ_INIT(&sc->sc_cmdq);
283 	MBUFQ_INIT(&sc->sc_aclq);
284 	MBUFQ_INIT(&sc->sc_scoq);
285 
286 	/* Attach Bluetooth unit */
287 	sc->sc_unit = hci_attach_pcb(&bcsp_hci, self, 0);
288 
289 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
290 	    0, CTLTYPE_NODE, device_xname(self),
291 	    SYSCTL_DESCR("bcsp controls"),
292 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0) {
293 		goto err;
294 	}
295 	bcsp_node_num = node->sysctl_num;
296 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
297 	    CTLFLAG_READWRITE, CTLTYPE_BOOL,
298 	    "muzzled", SYSCTL_DESCR("muzzled for Link-establishment Layer"),
299 	    NULL, 0, &sc->sc_le_muzzled,
300 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
301 		goto err;
302 	}
303 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
304 	    CTLFLAG_READWRITE, CTLTYPE_INT,
305 	    "txcrc", SYSCTL_DESCR("txcrc for Packet Integrity Layer"),
306 	    NULL, 0, &sc->sc_pi_txcrc,
307 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
308 		goto err;
309 	}
310 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
311 	    CTLFLAG_READWRITE, CTLTYPE_INT,
312 	    "timeout", SYSCTL_DESCR("timeout for Sequencing Layer"),
313 	    NULL, 0, &sc->sc_seq_timeout,
314 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
315 		goto err;
316 	}
317 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
318 	    CTLFLAG_READWRITE, CTLTYPE_INT,
319 	    "winsize", SYSCTL_DESCR("winsize for Sequencing Layer"),
320 	    NULL, 0, &sc->sc_seq_winsize,
321 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
322 		goto err;
323 	}
324 	if ((rc = sysctl_createv(&sc->sc_log, 0, NULL, &node,
325 	    CTLFLAG_READWRITE, CTLTYPE_INT,
326 	    "retry_limit", SYSCTL_DESCR("retry limit for Sequencing Layer"),
327 	    NULL, 0, &sc->sc_seq_retry_limit,
328 	    0, CTL_HW, bcsp_node_num, CTL_CREATE, CTL_EOL)) != 0) {
329 		goto err;
330 	}
331 	return;
332 
333 err:
334 	aprint_error_dev(self, "sysctl_createv failed (rc = %d)\n", rc);
335 }
336 
337 /*
338  * Autoconf detach routine.  Called when we close the line discipline.
339  */
340 /* ARGSUSED */
341 static int
342 bcsp_detach(device_t self, int flags __unused)
343 {
344 	struct bcsp_softc *sc = device_private(self);
345 
346 	if (sc->sc_unit != NULL) {
347 		hci_detach_pcb(sc->sc_unit);
348 		sc->sc_unit = NULL;
349 	}
350 
351 	callout_halt(&sc->sc_seq_timer, NULL);
352 	callout_destroy(&sc->sc_seq_timer);
353 
354 	callout_halt(&sc->sc_le_timer, NULL);
355 	callout_destroy(&sc->sc_le_timer);
356 
357 	return 0;
358 }
359 
360 
361 /*
362  * Line discipline functions.
363  */
364 /* ARGSUSED */
365 static int
366 bcspopen(dev_t device __unused, struct tty *tp)
367 {
368 	struct bcsp_softc *sc;
369 	device_t dev;
370 	cfdata_t cfdata;
371 	struct lwp *l = curlwp;		/* XXX */
372 	int error, unit, s;
373 	static char name[] = "bcsp";
374 
375 	error = kauth_authorize_device(l->l_cred, KAUTH_DEVICE_BLUETOOTH_BCSP,
376 	    KAUTH_ARG(KAUTH_REQ_DEVICE_BLUETOOTH_BCSP_ADD), NULL, NULL, NULL);
377 	if (error)
378 		return (error);
379 
380 	s = spltty();
381 
382 	if (tp->t_linesw == &bcsp_disc) {
383 		sc = tp->t_sc;
384 		if (sc != NULL) {
385 			splx(s);
386 			return EBUSY;
387 		}
388 	}
389 
390 	KASSERT(tp->t_oproc != NULL);
391 
392 	cfdata = malloc(sizeof(struct cfdata), M_DEVBUF, M_WAITOK);
393 	for (unit = 0; unit < bcsp_cd.cd_ndevs; unit++)
394 		if (device_lookup(&bcsp_cd, unit) == NULL)
395 			break;
396 	cfdata->cf_name = name;
397 	cfdata->cf_atname = name;
398 	cfdata->cf_unit = unit;
399 	cfdata->cf_fstate = FSTATE_STAR;
400 
401 	aprint_normal("%s%d at tty major %llu minor %llu",
402 	    name, unit, (unsigned long long)major(tp->t_dev),
403 	    (unsigned long long)minor(tp->t_dev));
404 	dev = config_attach_pseudo(cfdata);
405 	if (dev == NULL) {
406 		splx(s);
407 		return EIO;
408 	}
409 	sc = device_private(dev);
410 
411 	mutex_spin_enter(&tty_lock);
412 	tp->t_sc = sc;
413 	sc->sc_tp = tp;
414 	ttyflush(tp, FREAD | FWRITE);
415 	mutex_spin_exit(&tty_lock);
416 
417 	splx(s);
418 
419 	sc->sc_slip_txrsv = BCSP_SLIP_PKTSTART;
420 	bcsp_sequencing_reset(sc);
421 
422 	/* start link-establishment */
423 	bcsp_start_le(sc);
424 
425 	return 0;
426 }
427 
428 /* ARGSUSED */
429 static int
430 bcspclose(struct tty *tp, int flag __unused)
431 {
432 	struct bcsp_softc *sc = tp->t_sc;
433 	cfdata_t cfdata;
434 	int s;
435 
436 	/* terminate link-establishment */
437 	bcsp_terminate_le(sc);
438 
439 	s = spltty();
440 
441 	MBUFQ_DRAIN(&sc->sc_dgq);
442 	bcsp_sequencing_reset(sc);
443 
444 	mutex_spin_enter(&tty_lock);
445 	ttyflush(tp, FREAD | FWRITE);
446 	mutex_spin_exit(&tty_lock);	/* XXX */
447 	ttyldisc_release(tp->t_linesw);
448 	tp->t_linesw = ttyldisc_default();
449 	if (sc != NULL) {
450 		tp->t_sc = NULL;
451 		if (sc->sc_tp == tp) {
452 			cfdata = device_cfdata(sc->sc_dev);
453 			config_detach(sc->sc_dev, 0);
454 			free(cfdata, M_DEVBUF);
455 		}
456 
457 	}
458 	splx(s);
459 	return 0;
460 }
461 
462 /* ARGSUSED */
463 static int
464 bcspioctl(struct tty *tp, u_long cmd, void *data, int flag __unused,
465 	  struct lwp *l __unused)
466 {
467 	struct bcsp_softc *sc = tp->t_sc;
468 	int error;
469 
470 	/*
471 	 * XXX
472 	 * This function can be called without KERNEL_LOCK when caller's
473 	 * struct cdevsw is set D_MPSAFE. Is KERNEL_LOCK required?
474 	 */
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 			goto out;
1137 		pldlen += _m->m_len;
1138 	}
1139 	if (pldlen > 0xfff)
1140 		goto out;
1141 	if (protocol_id == BCSP_IDENT_ACKPKT || protocol_id > 15)
1142 		goto out;
1143 
1144 	if (sc->sc_seq_winspace == 0)
1145 		goto out;
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 		goto out;
1177 	}
1178 	MBUFQ_ENQUEUE(&sc->sc_seq_retryq, _m);
1179 	bcsp_mux_transmit(sc);
1180 
1181 	return true;
1182 out:
1183 	m_freem(m);
1184 	return false;
1185 }
1186 
1187 #if 0
1188 static bool
1189 bcsp_rx_reliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1190 {
1191 
1192 	return false;
1193 }
1194 
1195 /* XXXX:  I can't understand meaning this function... */
1196 static __inline void
1197 bcsp_link_failed(struct bcsp_softc *sc)
1198 {
1199 
1200 	return (sc->sc_seq_retries >= sc->sc_seq_retry_limit);
1201 }
1202 #endif
1203 
1204 static __inline u_int
1205 bcsp_get_txack(struct bcsp_softc *sc)
1206 {
1207 
1208 	return sc->sc_seq_txack;
1209 }
1210 
1211 static void
1212 bcsp_signal_rxack(struct bcsp_softc *sc, uint32_t rxack)
1213 {
1214 	bcsp_hdr_t *hdrp;
1215 	struct mbuf *m;
1216 	uint32_t seqno = (rxack - 1) & BCSP_FLAGS_SEQ_MASK;
1217 	int s;
1218 
1219 	DPRINTFN(1, ("%s: seq signal rxack: rxack=%d\n",
1220 	    device_xname(sc->sc_dev), rxack));
1221 
1222 	s = splserial();
1223 	m = MBUFQ_FIRST(&sc->sc_seq_retryq);
1224 	while (m != NULL) {
1225 		hdrp = mtod(m, bcsp_hdr_t *);
1226 		if (BCSP_FLAGS_SEQ(hdrp->flags) == seqno) {
1227 			struct mbuf *m0;
1228 
1229 			for (m0 = MBUFQ_FIRST(&sc->sc_seq_retryq);
1230 			    m0 != MBUFQ_NEXT(m);
1231 			    m0 = MBUFQ_FIRST(&sc->sc_seq_retryq)) {
1232 				MBUFQ_DEQUEUE(&sc->sc_seq_retryq, m0);
1233 				m_freem(m0);
1234 				sc->sc_seq_winspace++;
1235 			}
1236 			break;
1237 		}
1238 		m = MBUFQ_NEXT(m);
1239 	}
1240 	splx(s);
1241 	sc->sc_seq_retries = 0;
1242 
1243 	if (sc->sc_seq_winspace == sc->sc_seq_winsize)
1244 		callout_stop(&sc->sc_seq_timer);
1245 	else
1246 		callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1247 }
1248 
1249 static void
1250 bcsp_reliabletx_callback(struct bcsp_softc *sc, struct mbuf *m)
1251 {
1252 
1253 	m_freem(m);
1254 }
1255 
1256 static void
1257 bcsp_timer_timeout(void *arg)
1258 {
1259 	struct bcsp_softc *sc = arg;
1260 	struct mbuf *m, *_m;
1261 	int s, i = 0;
1262 
1263 	DPRINTFN(1, ("%s: seq timeout: retries=%d\n",
1264 	    device_xname(sc->sc_dev), sc->sc_seq_retries));
1265 
1266 	s = splserial();
1267 	for (m = MBUFQ_FIRST(&sc->sc_seq_retryq); m != NULL;
1268 	    m = MBUFQ_NEXT(m)) {
1269 		_m = m_copym(m, 0, M_COPYALL, M_DONTWAIT);
1270 		if (_m == NULL) {
1271 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1272 			return;
1273 		}
1274 		MBUFQ_ENQUEUE(&sc->sc_seqq, _m);
1275 		i++;
1276 	}
1277 	splx(s);
1278 
1279 	if (i != 0) {
1280 		if (++sc->sc_seq_retries < sc->sc_seq_retry_limit)
1281 			callout_schedule(&sc->sc_seq_timer, sc->sc_seq_timeout);
1282 		else {
1283 			aprint_error_dev(sc->sc_dev,
1284 			    "reached the retry limit."
1285 			    " restart the link-establishment\n");
1286 			bcsp_sequencing_reset(sc);
1287 			bcsp_start_le(sc);
1288 			return;
1289 		}
1290 	}
1291 	bcsp_mux_transmit(sc);
1292 }
1293 
1294 static void
1295 bcsp_sequencing_reset(struct bcsp_softc *sc)
1296 {
1297 	int s;
1298 
1299 	s = splserial();
1300 	MBUFQ_DRAIN(&sc->sc_seqq);
1301 	MBUFQ_DRAIN(&sc->sc_seq_retryq);
1302 	splx(s);
1303 
1304 
1305 	sc->sc_seq_txseq = 0;
1306 	sc->sc_seq_txack = 0;
1307 	sc->sc_seq_winspace = sc->sc_seq_winsize;
1308 	sc->sc_seq_retries = 0;
1309 	callout_stop(&sc->sc_seq_timer);
1310 
1311 	sc->sc_mux_send_ack = false;
1312 
1313 	/* XXXX: expected_rxseq should be set by MUX Layer */
1314 	sc->sc_seq_expected_rxseq = 0;
1315 }
1316 
1317 
1318 /*
1319  * BCSP Datagram Queue Layer functions
1320  */
1321 static void
1322 bcsp_datagramq_receive(struct bcsp_softc *sc, struct mbuf *m)
1323 {
1324 	bcsp_hdr_t hdr;
1325 
1326 	DPRINTFN(1, ("%s: dgq receive\n", device_xname(sc->sc_dev)));
1327 #ifdef BCSP_DEBUG
1328 	if (bcsp_debug == 2)
1329 		bcsp_packet_print(m);
1330 #endif
1331 
1332 	m_copydata(m, 0, sizeof(bcsp_hdr_t), &hdr);
1333 
1334 	switch (hdr.ident) {
1335 	case BCSP_CHANNEL_LE:
1336 		m_adj(m, sizeof(bcsp_hdr_t));
1337 		bcsp_input_le(sc, m);
1338 		break;
1339 
1340 	case BCSP_CHANNEL_HCI_SCO:
1341 		/*
1342 		 * We remove the header of BCSP and add the 'uint8_t type' of
1343 		 * hci_scodata_hdr_t to the head.
1344 		 */
1345 		m_adj(m, sizeof(bcsp_hdr_t) - sizeof(uint8_t));
1346 		*(mtod(m, uint8_t *)) = HCI_SCO_DATA_PKT;
1347 		if (!hci_input_sco(sc->sc_unit, m))
1348 			sc->sc_stats.err_rx++;
1349 
1350 		sc->sc_stats.sco_rx++;
1351 		break;
1352 
1353 	default:
1354 		aprint_error_dev(sc->sc_dev,
1355 		    "received unreliable packet with not support channel %d\n",
1356 		    hdr.ident);
1357 		m_freem(m);
1358 		break;
1359 	}
1360 }
1361 
1362 static bool
1363 bcsp_tx_unreliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1364 {
1365 	bcsp_hdr_t *hdrp;
1366 	struct mbuf *_m;
1367 	u_int pldlen;
1368 	int s;
1369 
1370 	DPRINTFN(1, ("%s: dgq transmit: protocol_id=%d,",
1371 	    device_xname(sc->sc_dev), protocol_id));
1372 
1373 	for (pldlen = 0, _m = m; _m != NULL; _m = m->m_next) {
1374 		if (_m->m_len < 0)
1375 			goto out;
1376 		pldlen += _m->m_len;
1377 	}
1378 	DPRINTFN(1, (" pldlen=%d\n", pldlen));
1379 	if (pldlen > 0xfff)
1380 		goto out;
1381 	if (protocol_id == BCSP_IDENT_ACKPKT || protocol_id > 15)
1382 		goto out;
1383 
1384 	M_PREPEND(m, sizeof(bcsp_hdr_t), M_DONTWAIT);
1385 	if (m == NULL) {
1386 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1387 		return false;
1388 	}
1389 	KASSERT(m->m_len >= sizeof(bcsp_hdr_t));
1390 
1391 	hdrp = mtod(m, bcsp_hdr_t *);
1392 	memset(hdrp, 0, sizeof(bcsp_hdr_t));
1393 	hdrp->ident = protocol_id;
1394 
1395 	s = splserial();
1396 	MBUFQ_ENQUEUE(&sc->sc_dgq, m);
1397 	splx(s);
1398 	sc->sc_transmit_callback = bcsp_unreliabletx_callback;
1399 
1400 #ifdef BCSP_DEBUG
1401 	if (bcsp_debug == 2)
1402 		bcsp_packet_print(m);
1403 #endif
1404 
1405 	bcsp_mux_transmit(sc);
1406 
1407 	return true;
1408 out:
1409 	m_freem(m);
1410 	return false;
1411 }
1412 
1413 #if 0
1414 static bool
1415 bcsp_rx_unreliable_pkt(struct bcsp_softc *sc, struct mbuf *m, u_int protocol_id)
1416 {
1417 
1418 	return false;
1419 }
1420 #endif
1421 
1422 static void
1423 bcsp_unreliabletx_callback(struct bcsp_softc *sc, struct mbuf *m)
1424 {
1425 
1426 	if (M_GETCTX(m, void *) == NULL)
1427 		m_freem(m);
1428 	else if (!hci_complete_sco(sc->sc_unit, m))
1429 		sc->sc_stats.err_tx++;
1430 }
1431 
1432 
1433 /*
1434  * BlueCore Link Establishment Protocol functions
1435  */
1436 static const uint8_t sync[] = BCSP_LE_SYNC;
1437 static const uint8_t syncresp[] = BCSP_LE_SYNCRESP;
1438 static const uint8_t conf[] = BCSP_LE_CONF;
1439 static const uint8_t confresp[] = BCSP_LE_CONFRESP;
1440 
1441 static int
1442 bcsp_start_le(struct bcsp_softc *sc)
1443 {
1444 
1445 	DPRINTF(("%s: start link-establish\n", device_xname(sc->sc_dev)));
1446 
1447 	bcsp_set_choke(sc, true);
1448 
1449 	if (!sc->sc_le_muzzled) {
1450 		struct mbuf *m;
1451 
1452 		m = m_gethdr(M_WAIT, MT_DATA);
1453 		m->m_pkthdr.len = m->m_len = 0;
1454 		m_copyback(m, 0, sizeof(sync), sync);
1455 		if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE)) {
1456 			aprint_error_dev(sc->sc_dev,
1457 			    "le-packet transmit failed\n");
1458 			return EINVAL;
1459 		}
1460 	}
1461 	callout_schedule(&sc->sc_le_timer, BCSP_LE_TSHY_TIMEOUT);
1462 
1463 	sc->sc_le_state = le_state_shy;
1464 	return 0;
1465 }
1466 
1467 static void
1468 bcsp_terminate_le(struct bcsp_softc *sc)
1469 {
1470 	struct mbuf *m;
1471 
1472 	/* terminate link-establishment */
1473 	callout_stop(&sc->sc_le_timer);
1474 	bcsp_set_choke(sc, true);
1475 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1476 	if (m == NULL)
1477 		aprint_error_dev(sc->sc_dev, "out of memory\n");
1478 	else {
1479 		/* length of le packets is 4 */
1480 		m->m_pkthdr.len = m->m_len = 0;
1481 		m_copyback(m, 0, sizeof(sync), sync);
1482 		if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1483 			aprint_error_dev(sc->sc_dev,
1484 			    "link-establishment terminations failed\n");
1485 	}
1486 }
1487 
1488 static void
1489 bcsp_input_le(struct bcsp_softc *sc, struct mbuf *m)
1490 {
1491 	uint32_t *rcvpkt;
1492 	int i;
1493 	const uint8_t *rplypkt;
1494 	static struct {
1495 		const char *type;
1496 		const uint8_t *datap;
1497 	} pkt[] = {
1498 		{ "sync",	sync },
1499 		{ "sync-resp",	syncresp },
1500 		{ "conf",	conf },
1501 		{ "conf-resp",	confresp },
1502 
1503 		{ NULL, 0 }
1504 	};
1505 
1506 	DPRINTFN(0, ("%s: le input: state %d, muzzled %d\n",
1507 	    device_xname(sc->sc_dev), sc->sc_le_state, sc->sc_le_muzzled));
1508 #ifdef BCSP_DEBUG
1509 	if (bcsp_debug == 1)
1510 		bcsp_packet_print(m);
1511 #endif
1512 
1513 	rcvpkt = mtod(m, uint32_t *);
1514 	i = 0;
1515 
1516 	/* length of le packets is 4 */
1517 	if (m->m_len == sizeof(uint32_t))
1518 		for (i = 0; pkt[i].type != NULL; i++)
1519 			if (*(const uint32_t *)pkt[i].datap == *rcvpkt)
1520 				break;
1521 	if (m->m_len != sizeof(uint32_t) || pkt[i].type == NULL) {
1522 		aprint_error_dev(sc->sc_dev, "received unknown packet\n");
1523 		m_freem(m);
1524 		return;
1525 	}
1526 
1527 	rplypkt = NULL;
1528 	switch (sc->sc_le_state) {
1529 	case le_state_shy:
1530 		if (*rcvpkt == *(const uint32_t *)sync) {
1531 			sc->sc_le_muzzled = false;
1532 			rplypkt = syncresp;
1533 		} else if (*rcvpkt == *(const uint32_t *)syncresp) {
1534 			DPRINTF(("%s: state change to curious\n",
1535 			    device_xname(sc->sc_dev)));
1536 
1537 			rplypkt = conf;
1538 			callout_schedule(&sc->sc_le_timer,
1539 			    BCSP_LE_TCONF_TIMEOUT);
1540 			sc->sc_le_state = le_state_curious;
1541 		} else
1542 			aprint_error_dev(sc->sc_dev,
1543 			    "received an unknown packet at shy\n");
1544 		break;
1545 
1546 	case le_state_curious:
1547 		if (*rcvpkt == *(const uint32_t *)sync)
1548 			rplypkt = syncresp;
1549 		else if (*rcvpkt == *(const uint32_t *)conf)
1550 			rplypkt = confresp;
1551 		else if (*rcvpkt == *(const uint32_t *)confresp) {
1552 			DPRINTF(("%s: state change to garrulous:\n",
1553 			    device_xname(sc->sc_dev)));
1554 
1555 			bcsp_set_choke(sc, false);
1556 			callout_stop(&sc->sc_le_timer);
1557 			sc->sc_le_state = le_state_garrulous;
1558 		} else
1559 			aprint_error_dev(sc->sc_dev,
1560 			    "received unknown packet at curious\n");
1561 		break;
1562 
1563 	case le_state_garrulous:
1564 		if (*rcvpkt == *(const uint32_t *)conf)
1565 			rplypkt = confresp;
1566 		else if (*rcvpkt == *(const uint32_t *)sync) {
1567 			/* XXXXX */
1568 			aprint_error_dev(sc->sc_dev,
1569 			    "received sync! peer to reset?\n");
1570 
1571 			bcsp_sequencing_reset(sc);
1572 			rplypkt = sync;
1573 			sc->sc_le_state = le_state_shy;
1574 		} else
1575 			aprint_error_dev(sc->sc_dev,
1576 			    "received unknown packet at garrulous\n");
1577 		break;
1578 	}
1579 
1580 	m_freem(m);
1581 
1582 	if (rplypkt != NULL) {
1583 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1584 		if (m == NULL)
1585 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1586 		else {
1587 			/* length of le packets is 4 */
1588 			m->m_pkthdr.len = m->m_len = 0;
1589 			m_copyback(m, 0, 4, rplypkt);
1590 			if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1591 				aprint_error_dev(sc->sc_dev,
1592 				    "le-packet transmit failed\n");
1593 		}
1594 	}
1595 }
1596 
1597 static void
1598 bcsp_le_timeout(void *arg)
1599 {
1600 	struct bcsp_softc *sc = arg;
1601 	struct mbuf *m;
1602 	int timeout;
1603 	const uint8_t *sndpkt = NULL;
1604 
1605 	DPRINTFN(0, ("%s: le timeout: state %d, muzzled %d\n",
1606 	    device_xname(sc->sc_dev), sc->sc_le_state, sc->sc_le_muzzled));
1607 
1608 	switch (sc->sc_le_state) {
1609 	case le_state_shy:
1610 		if (!sc->sc_le_muzzled)
1611 			sndpkt = sync;
1612 		timeout = BCSP_LE_TSHY_TIMEOUT;
1613 		break;
1614 
1615 	case le_state_curious:
1616 		sndpkt = conf;
1617 		timeout = BCSP_LE_TCONF_TIMEOUT;
1618 		break;
1619 
1620 	default:
1621 		aprint_error_dev(sc->sc_dev,
1622 		    "timeout happen at unknown state %d\n", sc->sc_le_state);
1623 		return;
1624 	}
1625 
1626 	if (sndpkt != NULL) {
1627 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1628 		if (m == NULL)
1629 			aprint_error_dev(sc->sc_dev, "out of memory\n");
1630 		else {
1631 			/* length of le packets is 4 */
1632 			m->m_pkthdr.len = m->m_len = 0;
1633 			m_copyback(m, 0, 4, sndpkt);
1634 			if (!bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_LE))
1635 				aprint_error_dev(sc->sc_dev,
1636 				    "le-packet transmit failed\n");
1637 		}
1638 	}
1639 
1640 	callout_schedule(&sc->sc_le_timer, timeout);
1641 }
1642 
1643 
1644 /*
1645  * BlueCore Serial Protocol functions.
1646  */
1647 static int
1648 bcsp_enable(device_t self)
1649 {
1650 	struct bcsp_softc *sc = device_private(self);
1651 	int s;
1652 
1653 	if (sc->sc_flags & BCSP_ENABLED)
1654 		return 0;
1655 
1656 	s = spltty();
1657 
1658 	sc->sc_flags |= BCSP_ENABLED;
1659 	sc->sc_flags &= ~BCSP_XMIT;
1660 
1661 	splx(s);
1662 
1663 	return 0;
1664 }
1665 
1666 static void
1667 bcsp_disable(device_t self)
1668 {
1669 	struct bcsp_softc *sc = device_private(self);
1670 	int s;
1671 
1672 	if ((sc->sc_flags & BCSP_ENABLED) == 0)
1673 		return;
1674 
1675 	s = spltty();
1676 
1677 	if (sc->sc_rxp) {
1678 		m_freem(sc->sc_rxp);
1679 		sc->sc_rxp = NULL;
1680 	}
1681 
1682 	if (sc->sc_txp) {
1683 		m_freem(sc->sc_txp);
1684 		sc->sc_txp = NULL;
1685 	}
1686 
1687 	MBUFQ_DRAIN(&sc->sc_cmdq);
1688 	MBUFQ_DRAIN(&sc->sc_aclq);
1689 	MBUFQ_DRAIN(&sc->sc_scoq);
1690 
1691 	sc->sc_flags &= ~BCSP_ENABLED;
1692 	splx(s);
1693 }
1694 
1695 static void
1696 bcsp_start(struct bcsp_softc *sc)
1697 {
1698 	struct mbuf *m;
1699 
1700 	KASSERT((sc->sc_flags & BCSP_XMIT) == 0);
1701 	KASSERT(sc->sc_txp == NULL);
1702 
1703 	if (MBUFQ_FIRST(&sc->sc_aclq)) {
1704 		MBUFQ_DEQUEUE(&sc->sc_aclq, m);
1705 		sc->sc_stats.acl_tx++;
1706 		sc->sc_flags |= BCSP_XMIT;
1707 		bcsp_tx_reliable_pkt(sc, m, BCSP_CHANNEL_HCI_ACL);
1708 	}
1709 
1710 	if (MBUFQ_FIRST(&sc->sc_cmdq)) {
1711 		MBUFQ_DEQUEUE(&sc->sc_cmdq, m);
1712 		sc->sc_stats.cmd_tx++;
1713 		sc->sc_flags |= BCSP_XMIT;
1714 		bcsp_tx_reliable_pkt(sc, m, BCSP_CHANNEL_HCI_CMDEVT);
1715 	}
1716 
1717 	if (MBUFQ_FIRST(&sc->sc_scoq)) {
1718 		MBUFQ_DEQUEUE(&sc->sc_scoq, m);
1719 		sc->sc_stats.sco_tx++;
1720 		/* XXXX: We can transmit with reliable */
1721 		sc->sc_flags |= BCSP_XMIT;
1722 		bcsp_tx_unreliable_pkt(sc, m, BCSP_CHANNEL_HCI_SCO);
1723 	}
1724 
1725 	return;
1726 }
1727 
1728 static void
1729 bcsp_output_cmd(device_t self, struct mbuf *m)
1730 {
1731 	struct bcsp_softc *sc = device_private(self);
1732 	int s;
1733 
1734 	KASSERT(sc->sc_flags & BCSP_ENABLED);
1735 
1736 	m_adj(m, sizeof(uint8_t));
1737 	M_SETCTX(m, NULL);
1738 
1739 	s = spltty();
1740 	MBUFQ_ENQUEUE(&sc->sc_cmdq, m);
1741 	if ((sc->sc_flags & BCSP_XMIT) == 0)
1742 		bcsp_start(sc);
1743 
1744 	splx(s);
1745 }
1746 
1747 static void
1748 bcsp_output_acl(device_t self, struct mbuf *m)
1749 {
1750 	struct bcsp_softc *sc = device_private(self);
1751 	int s;
1752 
1753 	KASSERT(sc->sc_flags & BCSP_ENABLED);
1754 
1755 	m_adj(m, sizeof(uint8_t));
1756 	M_SETCTX(m, NULL);
1757 
1758 	s = spltty();
1759 	MBUFQ_ENQUEUE(&sc->sc_aclq, m);
1760 	if ((sc->sc_flags & BCSP_XMIT) == 0)
1761 		bcsp_start(sc);
1762 
1763 	splx(s);
1764 }
1765 
1766 static void
1767 bcsp_output_sco(device_t self, struct mbuf *m)
1768 {
1769 	struct bcsp_softc *sc = device_private(self);
1770 	int s;
1771 
1772 	KASSERT(sc->sc_flags & BCSP_ENABLED);
1773 
1774 	m_adj(m, sizeof(uint8_t));
1775 
1776 	s = spltty();
1777 	MBUFQ_ENQUEUE(&sc->sc_scoq, m);
1778 	if ((sc->sc_flags & BCSP_XMIT) == 0)
1779 		bcsp_start(sc);
1780 
1781 	splx(s);
1782 }
1783 
1784 static void
1785 bcsp_stats(device_t self, struct bt_stats *dest, int flush)
1786 {
1787 	struct bcsp_softc *sc = device_private(self);
1788 	int s;
1789 
1790 	s = spltty();
1791 	memcpy(dest, &sc->sc_stats, sizeof(struct bt_stats));
1792 
1793 	if (flush)
1794 		memset(&sc->sc_stats, 0, sizeof(struct bt_stats));
1795 
1796 	splx(s);
1797 }
1798 
1799 
1800 #ifdef BCSP_DEBUG
1801 static void
1802 bcsp_packet_print(struct mbuf *m)
1803 {
1804 	int i;
1805 	uint8_t *p;
1806 
1807 	for ( ; m != NULL; m = m->m_next) {
1808 		p = mtod(m, uint8_t *);
1809 		for (i = 0; i < m->m_len; i++) {
1810 			if (i % 16 == 0)
1811 				printf(" ");
1812 			printf(" %02x", *(p + i));
1813 			if (i % 16 == 15)
1814 				printf("\n");
1815 		}
1816 		printf("\n");
1817 	}
1818 }
1819 #endif
1820