No empty .Rs/.Re
[netbsd-mini2440.git] / sys / net / if_strip.c
blob4584e51256db7802f5a8bd28e27ef4fa543f8c65
1 /* $NetBSD: if_strip.c,v 1.92 2009/04/18 14:58:05 tsutsui Exp $ */
2 /* from: NetBSD: if_sl.c,v 1.38 1996/02/13 22:00:23 christos Exp $ */
4 /*
5 * Copyright 1996 The Board of Trustees of The Leland Stanford
6 * Junior University. All Rights Reserved.
8 * Permission to use, copy, modify, and distribute this
9 * software and its documentation for any purpose and without
10 * fee is hereby granted, provided that the above copyright
11 * notice appear in all copies. Stanford University
12 * makes no representations about the suitability of this
13 * software for any purpose. It is provided "as is" without
14 * express or implied warranty.
17 * This driver was contributed by Jonathan Stone.
19 * Starmode Radio IP interface (STRIP) for Metricom wireless radio.
20 * This STRIP driver assumes address resolution of IP addresses to
21 * Metricom MAC addresses is done via local link-level routes.
22 * The link-level addresses are entered as an 8-digit packed BCD number.
23 * To add a route for a radio at IP address 10.1.2.3, with radio
24 * address '1234-5678', reachable via interface strip0, use the command
26 * route add -host 10.1.2.3 -link strip0:12:34:56:78
31 * Copyright (c) 1987, 1989, 1992, 1993
32 * The Regents of the University of California. All rights reserved.
34 * Redistribution and use in source and binary forms, with or without
35 * modification, are permitted provided that the following conditions
36 * are met:
37 * 1. Redistributions of source code must retain the above copyright
38 * notice, this list of conditions and the following disclaimer.
39 * 2. Redistributions in binary form must reproduce the above copyright
40 * notice, this list of conditions and the following disclaimer in the
41 * documentation and/or other materials provided with the distribution.
42 * 3. Neither the name of the University nor the names of its contributors
43 * may be used to endorse or promote products derived from this software
44 * without specific prior written permission.
46 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56 * SUCH DAMAGE.
58 * @(#)if_sl.c 8.6 (Berkeley) 2/1/94
62 * Derived from: Serial Line interface written by Rick Adams (rick@seismo.gov)
64 * Rick Adams
65 * Center for Seismic Studies
66 * 1300 N 17th Street, Suite 1450
67 * Arlington, Virginia 22209
68 * (703)276-7900
69 * rick@seismo.ARPA
70 * seismo!rick
72 * Pounded on heavily by Chris Torek (chris@mimsy.umd.edu, umcp-cs!chris).
73 * N.B.: this belongs in netinet, not net, the way it stands now.
74 * Should have a link-layer type designation, but wouldn't be
75 * backwards-compatible.
77 * Converted to 4.3BSD Beta by Chris Torek.
78 * Other changes made at Berkeley, based in part on code by Kirk Smith.
79 * W. Jolitz added slip abort.
81 * Hacked almost beyond recognition by Van Jacobson (van@helios.ee.lbl.gov).
82 * Added priority queuing for "interactive" traffic; hooks for TCP
83 * header compression; ICMP filtering (at 2400 baud, some cretin
84 * pinging you can use up all your bandwidth). Made low clist behavior
85 * more robust and slightly less likely to hang serial line.
86 * Sped up a bunch of things.
89 #include <sys/cdefs.h>
90 __KERNEL_RCSID(0, "$NetBSD: if_strip.c,v 1.92 2009/04/18 14:58:05 tsutsui Exp $");
92 #include "opt_inet.h"
93 #include "bpfilter.h"
95 #include <sys/param.h>
96 #include <sys/proc.h>
97 #include <sys/mbuf.h>
98 #include <sys/buf.h>
99 #include <sys/dkstat.h>
100 #include <sys/socket.h>
101 #include <sys/ioctl.h>
102 #include <sys/file.h>
103 #include <sys/conf.h>
104 #include <sys/tty.h>
105 #include <sys/kernel.h>
106 #if __NetBSD__
107 #include <sys/systm.h>
108 #include <sys/callout.h>
109 #include <sys/kauth.h>
110 #endif
111 #include <sys/syslog.h>
112 #include <sys/cpu.h>
113 #include <sys/intr.h>
114 #include <sys/socketvar.h>
116 #include <net/if.h>
117 #include <net/if_dl.h>
118 #include <net/if_types.h>
119 #include <net/netisr.h>
120 #include <net/route.h>
122 #ifdef INET
123 #include <netinet/in.h>
124 #include <netinet/in_systm.h>
125 #include <netinet/in_var.h>
126 #include <netinet/ip.h>
127 #endif
129 #include <net/slcompress.h>
130 #include <net/if_stripvar.h>
131 #include <net/slip.h>
133 #ifdef __NetBSD__ /* XXX -- jrs */
134 typedef u_char ttychar_t;
135 #else
136 typedef char ttychar_t;
137 #endif
139 #if NBPFILTER > 0
140 #include <sys/time.h>
141 #include <net/bpf.h>
142 #endif
145 * SLMAX is a hard limit on input packet size. To simplify the code
146 * and improve performance, we require that packets fit in an mbuf
147 * cluster, and if we get a compressed packet, there's enough extra
148 * room to expand the header into a max length tcp/ip header (128
149 * bytes). So, SLMAX can be at most
150 * MCLBYTES - 128
152 * SLMTU is a hard limit on output packet size. To insure good
153 * interactive response, SLMTU wants to be the smallest size that
154 * amortizes the header cost. Remember that even with
155 * type-of-service queuing, we have to wait for any in-progress
156 * packet to finish. I.e., we wait, on the average, 1/2 * mtu /
157 * cps, where cps is the line speed in characters per second.
158 * E.g., 533ms wait for a 1024 byte MTU on a 9600 baud line. The
159 * average compressed header size is 6-8 bytes so any MTU > 90
160 * bytes will give us 90% of the line bandwidth. A 100ms wait is
161 * tolerable (500ms is not), so want an MTU around 296. (Since TCP
162 * will send 256 byte segments (to allow for 40 byte headers), the
163 * typical packet size on the wire will be around 260 bytes). In
164 * 4.3tahoe+ systems, we can set an MTU in a route so we do that &
165 * leave the interface MTU relatively high (so we don't IP fragment
166 * when acting as a gateway to someone using a stupid MTU).
168 * Similar considerations apply to SLIP_HIWAT: It's the amount of
169 * data that will be queued 'downstream' of us (i.e., in clists
170 * waiting to be picked up by the tty output interrupt). If we
171 * queue a lot of data downstream, it's immune to our t.o.s. queuing.
172 * E.g., if SLIP_HIWAT is 1024, the interactive traffic in mixed
173 * telnet/ftp will see a 1 sec wait, independent of the mtu (the
174 * wait is dependent on the ftp window size but that's typically
175 * 1k - 4k). So, we want SLIP_HIWAT just big enough to amortize
176 * the cost (in idle time on the wire) of the tty driver running
177 * off the end of its clists & having to call back slstart for a
178 * new packet. For a tty interface with any buffering at all, this
179 * cost will be zero. Even with a totally brain dead interface (like
180 * the one on a typical workstation), the cost will be <= 1 character
181 * time. So, setting SLIP_HIWAT to ~100 guarantees that we'll lose
182 * at most 1% while maintaining good interactive response.
184 #define BUFOFFSET (128+sizeof(struct ifnet **)+SLIP_HDRLEN)
185 #define SLMAX (MCLBYTES - BUFOFFSET)
186 #define SLBUFSIZE (SLMAX + BUFOFFSET)
187 #define SLMTU 1100 /* XXX -- appromaximated. 1024 may be safer. */
189 #define STRIP_MTU_ONWIRE (SLMTU + 20 + STRIP_HDRLEN) /* (2*SLMTU+2 in sl.c */
192 #define SLIP_HIWAT roundup(50,CBSIZE)
194 /* This is a NetBSD-1.0 or later kernel. */
195 #define CCOUNT(q) ((q)->c_cc)
198 #ifndef __NetBSD__ /* XXX - cgd */
199 #define CLISTRESERVE 1024 /* Can't let clists get too low */
200 #endif /* !__NetBSD__ */
203 * SLIP ABORT ESCAPE MECHANISM:
204 * (inspired by HAYES modem escape arrangement)
205 * 1sec escape 1sec escape 1sec escape { 1sec escape 1sec escape }
206 * within window time signals a "soft" exit from slip mode by remote end
207 * if the IFF_DEBUG flag is on.
209 #define ABT_ESC '\033' /* can't be t_intr - distant host must know it*/
210 #define ABT_IDLE 1 /* in seconds - idle before an escape */
211 #define ABT_COUNT 3 /* count of escapes for abort */
212 #define ABT_WINDOW (ABT_COUNT*2+2) /* in seconds - time to count */
214 static int strip_clone_create(struct if_clone *, int);
215 static int strip_clone_destroy(struct ifnet *);
217 static LIST_HEAD(, strip_softc) strip_softc_list;
219 struct if_clone strip_cloner =
220 IF_CLONE_INITIALIZER("strip", strip_clone_create, strip_clone_destroy);
222 #define STRIP_FRAME_END 0x0D /* carriage return */
224 static void stripintr(void *);
226 static int stripinit(struct strip_softc *);
227 static struct mbuf *strip_btom(struct strip_softc *, int);
230 * STRIP header: '*' + modem address (dddd-dddd) + '*' + mactype ('SIP0')
231 * A Metricom packet looks like this: *<address>*<key><payload><CR>
232 * eg. *0000-1164*SIP0<payload><CR>
236 #define STRIP_ENCAP_SIZE(X) ((36) + (X)*65/64 + 2)
237 #define STRIP_HDRLEN 15
238 #define STRIP_MAC_ADDR_LEN 9
241 * Star mode packet header.
242 * (may be used for encapsulations other than STRIP.)
244 #define STARMODE_ADDR_LEN 11
245 struct st_header {
246 u_char starmode_addr[STARMODE_ADDR_LEN];
247 u_char starmode_type[4];
251 * Forward declarations for Metricom-specific functions.
252 * Ideally, these would be in a library and shared across
253 * different STRIP implementations: *BSD, Linux, etc.
256 static u_char* UnStuffData(u_char *src, u_char *end, u_char
257 *dest, u_long dest_length);
259 static u_char* StuffData(u_char *src, u_long length, u_char *dest,
260 u_char **code_ptr_ptr);
262 static void RecvErr(const char *msg, struct strip_softc *sc);
263 static void RecvErr_Message(struct strip_softc *strip_info,
264 u_char *sendername, const u_char *msg);
265 void strip_resetradio(struct strip_softc *sc, struct tty *tp);
266 void strip_proberadio(struct strip_softc *sc, struct tty *tp);
267 void strip_watchdog(struct ifnet *ifp);
268 void strip_sendbody(struct strip_softc *sc, struct mbuf *m);
269 int strip_newpacket(struct strip_softc *sc, u_char *ptr, u_char *end);
270 void strip_send(struct strip_softc *sc, struct mbuf *m0);
272 void strip_timeout(void *x);
274 #ifdef DEBUG
275 #define DPRINTF(x) printf x
276 #else
277 #define DPRINTF(x)
278 #endif
283 * Radio reset macros.
284 * The Metricom radios are not particularly well-designed for
285 * use in packet mode (starmode). There's no easy way to tell
286 * when the radio is in starmode. Worse, when the radios are reset
287 * or power-cycled, they come back up in Hayes AT-emulation mode,
288 * and there's no good way for this driver to tell.
289 * We deal with this by peridically tickling the radio
290 * with an invalid starmode command. If the radio doesn't
291 * respond with an error, the driver knows to reset the radio.
294 /* Radio-reset finite state machine (if_watchdog) callback rate, in seconds */
295 #define STRIP_WATCHDOG_INTERVAL 5
297 /* Period between intrusive radio probes, in seconds */
298 #define ST_PROBE_INTERVAL 10
300 /* Grace period for radio to answer probe, in seconds */
301 #define ST_PROBERESPONSE_INTERVAL 2
303 /* Be less agressive about repeated resetting. */
304 #define STRIP_RESET_INTERVAL 5
307 * We received a response from the radio that indicates it's in
308 * star mode. Clear any pending probe or reset timer.
309 * Don't probe radio again for standard polling interval.
311 #define CLEAR_RESET_TIMER(sc) \
312 do {\
313 (sc)->sc_state = ST_ALIVE; \
314 (sc)->sc_statetimo = time_second + ST_PROBE_INTERVAL; \
315 } while (/*CONSTCOND*/ 0)
318 * we received a response from the radio that indicates it's crashed
319 * out of starmode into Hayse mode. Reset it ASAP.
321 #define FORCE_RESET(sc) \
322 do {\
323 (sc)->sc_statetimo = time_second - 1; \
324 (sc)->sc_state = ST_DEAD; \
325 /*(sc)->sc_if.if_timer = 0;*/ \
326 } while (/*CONSTCOND*/ 0)
328 #define RADIO_PROBE_TIMEOUT(sc) \
329 ((sc)-> sc_statetimo > time_second)
331 static int stripclose(struct tty *, int);
332 static int stripinput(int, struct tty *);
333 static int stripioctl(struct ifnet *, u_long, void *);
334 static int stripopen(dev_t, struct tty *);
335 static int stripoutput(struct ifnet *,
336 struct mbuf *, const struct sockaddr *, struct rtentry *);
337 static int stripstart(struct tty *);
338 static int striptioctl(struct tty *, u_long, void *, int, struct lwp *);
340 static struct linesw strip_disc = {
341 .l_name = "strip",
342 .l_open = stripopen,
343 .l_close = stripclose,
344 .l_read = ttyerrio,
345 .l_write = ttyerrio,
346 .l_ioctl = striptioctl,
347 .l_rint = stripinput,
348 .l_start = stripstart,
349 .l_modem = nullmodem,
350 .l_poll = ttyerrpoll
353 void
354 stripattach(void)
356 if (ttyldisc_attach(&strip_disc) != 0)
357 panic("stripattach");
358 LIST_INIT(&strip_softc_list);
359 if_clone_attach(&strip_cloner);
362 static int
363 strip_clone_create(struct if_clone *ifc, int unit)
365 struct strip_softc *sc;
367 sc = malloc(sizeof(*sc), M_DEVBUF, M_WAIT|M_ZERO);
368 sc->sc_unit = unit;
369 if_initname(&sc->sc_if, ifc->ifc_name, unit);
370 callout_init(&sc->sc_timo_ch, 0);
371 sc->sc_if.if_softc = sc;
372 sc->sc_if.if_mtu = SLMTU;
373 sc->sc_if.if_flags = 0;
374 sc->sc_if.if_type = IFT_OTHER;
375 #if 0
376 sc->sc_if.if_flags |= SC_AUTOCOMP /* | IFF_POINTOPOINT | IFF_MULTICAST*/;
377 #endif
378 sc->sc_if.if_type = IFT_SLIP;
379 sc->sc_if.if_ioctl = stripioctl;
380 sc->sc_if.if_output = stripoutput;
381 sc->sc_if.if_dlt = DLT_SLIP;
382 sc->sc_fastq.ifq_maxlen = 32;
383 IFQ_SET_READY(&sc->sc_if.if_snd);
385 sc->sc_if.if_watchdog = strip_watchdog;
386 if_attach(&sc->sc_if);
387 if_alloc_sadl(&sc->sc_if);
388 #if NBPFILTER > 0
389 bpfattach(&sc->sc_if, DLT_SLIP, SLIP_HDRLEN);
390 #endif
391 LIST_INSERT_HEAD(&strip_softc_list, sc, sc_iflist);
392 return 0;
395 static int
396 strip_clone_destroy(struct ifnet *ifp)
398 struct strip_softc *sc = (struct strip_softc *)ifp->if_softc;
400 if (sc->sc_ttyp != NULL)
401 return EBUSY; /* Not removing it */
403 LIST_REMOVE(sc, sc_iflist);
405 #if NBPFILTER > 0
406 bpfdetach(ifp);
407 #endif
408 if_detach(ifp);
410 free(sc, M_DEVBUF);
411 return 0;
414 static int
415 stripinit(struct strip_softc *sc)
417 u_char *p;
419 if (sc->sc_mbuf == NULL) {
420 sc->sc_mbuf = m_get(M_WAIT, MT_DATA);
421 m_clget(sc->sc_mbuf, M_WAIT);
423 sc->sc_ep = (u_char *) sc->sc_mbuf->m_ext.ext_buf +
424 sc->sc_mbuf->m_ext.ext_size;
425 sc->sc_mp = sc->sc_pktstart = (u_char *) sc->sc_mbuf->m_ext.ext_buf +
426 BUFOFFSET;
428 /* Get contiguous buffer in which to de-bytestuff/rll-decode input */
429 if (sc->sc_rxbuf == NULL) {
430 p = (u_char *)malloc(MCLBYTES, M_DEVBUF, M_WAITOK);
431 if (p)
432 sc->sc_rxbuf = p + SLBUFSIZE - SLMAX;
433 else {
434 printf("%s: can't allocate input buffer\n",
435 sc->sc_if.if_xname);
436 sc->sc_if.if_flags &= ~IFF_UP;
437 return (0);
441 /* Get contiguous buffer in which to bytestuff/rll-encode output */
442 if (sc->sc_txbuf == NULL) {
443 p = (u_char *)malloc(MCLBYTES, M_DEVBUF, M_WAITOK);
444 if (p)
445 sc->sc_txbuf = (u_char *)p + SLBUFSIZE - SLMAX;
446 else {
447 printf("%s: can't allocate buffer\n",
448 sc->sc_if.if_xname);
450 sc->sc_if.if_flags &= ~IFF_UP;
451 return (0);
455 #ifdef INET
456 sl_compress_init(&sc->sc_comp);
457 #endif
459 /* Initialize radio probe/reset state machine */
460 sc->sc_state = ST_DEAD; /* assumet the worst. */
461 sc->sc_statetimo = time_second; /* do reset immediately */
463 return (1);
467 * Line specific open routine.
468 * Attach the given tty to the first available sl unit.
470 /* ARGSUSED */
472 stripopen(dev_t dev, struct tty *tp)
474 struct lwp *l = curlwp; /* XXX */
475 struct strip_softc *sc;
476 int error;
478 error = kauth_authorize_network(l->l_cred,
479 KAUTH_NETWORK_INTERFACE_STRIP,
480 KAUTH_REQ_NETWORK_INTERFACE_STRIP_ADD, NULL, NULL, NULL);
481 if (error)
482 return (error);
484 if (tp->t_linesw == &strip_disc)
485 return (0);
487 LIST_FOREACH(sc, &strip_softc_list, sc_iflist) {
488 if (sc->sc_ttyp == NULL) {
489 sc->sc_si = softint_establish(SOFTINT_NET,
490 stripintr, sc);
491 if (stripinit(sc) == 0) {
492 softint_disestablish(sc->sc_si);
493 return (ENOBUFS);
495 mutex_spin_enter(&tty_lock);
496 tp->t_sc = (void *)sc;
497 sc->sc_ttyp = tp;
498 sc->sc_if.if_baudrate = tp->t_ospeed;
499 ttyflush(tp, FREAD | FWRITE);
501 * Make sure tty output queue is large enough
502 * to hold a full-sized packet (including frame
503 * end, and a possible extra frame end).
504 * A full-sized of 65/64) *SLMTU bytes (because
505 * of escapes and clever RLL bytestuffing),
506 * plus frame header, and add two on for frame ends.
508 if (tp->t_outq.c_cn < STRIP_MTU_ONWIRE) {
509 sc->sc_oldbufsize = tp->t_outq.c_cn;
510 sc->sc_oldbufquot = tp->t_outq.c_cq != 0;
512 mutex_spin_exit(&tty_lock);
513 clfree(&tp->t_outq);
514 error = clalloc(&tp->t_outq, 3*SLMTU, 0);
515 if (error) {
516 softint_disestablish(sc->sc_si);
518 * clalloc() might return -1 which
519 * is no good, so we need to return
520 * something else.
522 return (ENOMEM);
524 mutex_spin_enter(&tty_lock);
525 } else
526 sc->sc_oldbufsize = sc->sc_oldbufquot = 0;
527 strip_resetradio(sc, tp);
528 mutex_spin_exit(&tty_lock);
531 * Start the watchdog timer to get the radio
532 * "probe-for-death"/reset machine going.
534 sc->sc_if.if_timer = STRIP_WATCHDOG_INTERVAL;
536 return (0);
539 return (ENXIO);
543 * Line specific close routine.
544 * Detach the tty from the strip unit.
546 static int
547 stripclose(struct tty *tp, int flag)
549 struct strip_softc *sc;
550 int s;
552 ttywflush(tp);
553 sc = tp->t_sc;
555 if (sc != NULL) {
556 softint_disestablish(sc->sc_si);
557 s = splnet();
559 * Cancel watchdog timer, which stops the "probe-for-death"/
560 * reset machine.
562 sc->sc_if.if_timer = 0;
563 if_down(&sc->sc_if);
564 IF_PURGE(&sc->sc_fastq);
565 splx(s);
567 s = spltty();
568 ttyldisc_release(tp->t_linesw);
569 tp->t_linesw = ttyldisc_default();
570 tp->t_state = 0;
572 sc->sc_ttyp = NULL;
573 tp->t_sc = NULL;
575 m_freem(sc->sc_mbuf);
576 sc->sc_mbuf = NULL;
577 sc->sc_ep = sc->sc_mp = sc->sc_pktstart = NULL;
578 IF_PURGE(&sc->sc_inq);
580 /* XXX */
581 free((void *)(sc->sc_rxbuf - SLBUFSIZE + SLMAX), M_DEVBUF);
582 sc->sc_rxbuf = NULL;
584 /* XXX */
585 free((void *)(sc->sc_txbuf - SLBUFSIZE + SLMAX), M_DEVBUF);
586 sc->sc_txbuf = NULL;
588 if (sc->sc_flags & SC_TIMEOUT) {
589 callout_stop(&sc->sc_timo_ch);
590 sc->sc_flags &= ~SC_TIMEOUT;
594 * If necessary, install a new outq buffer of the
595 * appropriate size.
597 if (sc->sc_oldbufsize != 0) {
598 clfree(&tp->t_outq);
599 clalloc(&tp->t_outq, sc->sc_oldbufsize,
600 sc->sc_oldbufquot);
602 splx(s);
605 return (0);
609 * Line specific (tty) ioctl routine.
610 * Provide a way to get the sl unit number.
612 /* ARGSUSED */
614 striptioctl(struct tty *tp, u_long cmd, void *data, int flag,
615 struct lwp *l)
617 struct strip_softc *sc = (struct strip_softc *)tp->t_sc;
619 switch (cmd) {
620 case SLIOCGUNIT:
621 *(int *)data = sc->sc_unit;
622 break;
624 default:
625 return (EPASSTHROUGH);
627 return (0);
631 * Take an mbuf chain containing a STRIP packet (no link-level header),
632 * byte-stuff (escape) it, and enqueue it on the tty send queue.
634 void
635 strip_sendbody(struct strip_softc *sc, struct mbuf *m)
637 struct tty *tp = sc->sc_ttyp;
638 u_char *dp = sc->sc_txbuf;
639 struct mbuf *m2;
640 int len;
641 u_char *rllstate_ptr = NULL;
643 while (m) {
644 if (m->m_len != 0) {
646 * Byte-stuff/run-length encode this mbuf's data
647 * into the output buffer.
648 * XXX Note that chained calls to stuffdata()
649 * require that the stuffed data be left in the
650 * output buffer until the entire packet is encoded.
652 dp = StuffData(mtod(m, u_char *), m->m_len, dp,
653 &rllstate_ptr);
655 MFREE(m, m2);
656 m = m2;
660 * Put the entire stuffed packet into the tty output queue.
662 len = dp - sc->sc_txbuf;
663 if (b_to_q((ttychar_t *)sc->sc_txbuf, len, &tp->t_outq)) {
664 if (sc->sc_if.if_flags & IFF_DEBUG)
665 addlog("%s: tty output overflow\n",
666 sc->sc_if.if_xname);
667 return;
669 sc->sc_if.if_obytes += len;
673 * Send a STRIP packet. Must be called at spltty().
675 void
676 strip_send(struct strip_softc *sc, struct mbuf *m0)
678 struct tty *tp = sc->sc_ttyp;
679 struct st_header *hdr;
682 * Send starmode header (unstuffed).
684 hdr = mtod(m0, struct st_header *);
685 if (b_to_q((ttychar_t *)hdr, STRIP_HDRLEN, &tp->t_outq)) {
686 if (sc->sc_if.if_flags & IFF_DEBUG)
687 addlog("%s: outq overflow writing header\n",
688 sc->sc_if.if_xname);
689 m_freem(m0);
690 return;
693 m_adj(m0, sizeof(struct st_header));
695 /* Byte-stuff and run-length encode the remainder of the packet. */
696 strip_sendbody(sc, m0);
698 if (putc(STRIP_FRAME_END, &tp->t_outq)) {
700 * Not enough room. Remove a char to make room
701 * and end the packet normally.
702 * If you get many collisions (more than one or two
703 * a day) you probably do not have enough clists
704 * and you should increase "nclist" in param.c.
706 (void) unputc(&tp->t_outq);
707 (void) putc(STRIP_FRAME_END, &tp->t_outq);
708 sc->sc_if.if_collisions++;
709 } else {
710 ++sc->sc_if.if_obytes;
711 sc->sc_if.if_opackets++;
715 * If a radio probe is due now, append it to this packet rather
716 * than waiting until the watchdog routine next runs.
718 if (time_second >= sc->sc_statetimo && sc->sc_state == ST_ALIVE)
719 strip_proberadio(sc, tp);
723 * Queue a packet. Start transmission if not active.
724 * Compression happens in stripintr(); if we do it here, IP TOS
725 * will cause us to not compress "background" packets, because
726 * ordering gets trashed. It can be done for all packets in stripintr().
729 stripoutput(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
730 struct rtentry *rt)
732 struct strip_softc *sc = ifp->if_softc;
733 struct ip *ip;
734 struct st_header *shp;
735 const u_char *dldst; /* link-level next-hop */
736 struct ifqueue *ifq;
737 int s, error;
738 u_char dl_addrbuf[STARMODE_ADDR_LEN+1];
739 ALTQ_DECL(struct altq_pktattr pktattr;)
742 * Verify tty line is up and alive.
744 if (sc->sc_ttyp == NULL) {
745 m_freem(m);
746 return (ENETDOWN); /* sort of */
748 if ((sc->sc_ttyp->t_state & TS_CARR_ON) == 0 &&
749 (sc->sc_ttyp->t_cflag & CLOCAL) == 0) {
750 m_freem(m);
751 return (EHOSTUNREACH);
754 #ifdef DEBUG
755 if (rt) {
756 printf("stripout, rt: dst af%d gw af%d",
757 rt_getkey(rt)->sa_family, rt->rt_gateway->sa_family);
758 if (rt_getkey(rt)->sa_family == AF_INET)
759 printf(" dst %x",
760 satocsin(rt_getkey(rt))->sin_addr.s_addr);
761 printf("\n");
763 #endif
764 switch (dst->sa_family) {
765 case AF_INET:
766 if (rt != NULL && rt->rt_gwroute != NULL)
767 rt = rt->rt_gwroute;
769 /* assume rt is never NULL */
770 if (rt == NULL || rt->rt_gateway->sa_family != AF_LINK
771 || satocsdl(rt->rt_gateway)->sdl_alen != ifp->if_addrlen) {
772 DPRINTF(("strip: could not arp starmode addr %x\n",
773 satocsin(dst)->sin_addr.s_addr));
774 m_freem(m);
775 return (EHOSTUNREACH);
777 dldst = CLLADDR(satocsdl(rt->rt_gateway));
778 break;
780 case AF_LINK:
781 dldst = CLLADDR(satocsdl(dst));
782 break;
784 default:
786 * `Cannot happen' (see stripioctl). Someday we will extend
787 * the line protocol to support other address families.
789 printf("%s: af %d not supported\n", sc->sc_if.if_xname,
790 dst->sa_family);
791 m_freem(m);
792 sc->sc_if.if_noproto++;
793 return (EAFNOSUPPORT);
796 ip = mtod(m, struct ip *);
797 #ifdef INET
798 if (sc->sc_if.if_flags & SC_NOICMP && ip->ip_p == IPPROTO_ICMP) {
799 m_freem(m);
800 return (ENETRESET); /* XXX ? */
802 if ((ip->ip_tos & IPTOS_LOWDELAY) != 0
803 #ifdef ALTQ
804 && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
805 #endif
807 ifq = &sc->sc_fastq;
808 else
809 #endif
810 ifq = NULL;
813 * Add local net header. If no space in first mbuf,
814 * add another.
816 M_PREPEND(m, sizeof(struct st_header), M_DONTWAIT);
817 if (m == 0) {
818 DPRINTF(("strip: could not prepend starmode header\n"));
819 return (ENOBUFS);
823 * Unpack BCD route entry into an ASCII starmode address.
825 dl_addrbuf[0] = '*';
827 dl_addrbuf[1] = ((dldst[0] >> 4) & 0x0f) + '0';
828 dl_addrbuf[2] = ((dldst[0] ) & 0x0f) + '0';
830 dl_addrbuf[3] = ((dldst[1] >> 4) & 0x0f) + '0';
831 dl_addrbuf[4] = ((dldst[1] ) & 0x0f) + '0';
833 dl_addrbuf[5] = '-';
835 dl_addrbuf[6] = ((dldst[2] >> 4) & 0x0f) + '0';
836 dl_addrbuf[7] = ((dldst[2] ) & 0x0f) + '0';
838 dl_addrbuf[8] = ((dldst[3] >> 4) & 0x0f) + '0';
839 dl_addrbuf[9] = ((dldst[3] ) & 0x0f) + '0';
841 dl_addrbuf[10] = '*';
842 dl_addrbuf[11] = 0;
843 dldst = dl_addrbuf;
845 shp = mtod(m, struct st_header *);
846 memcpy(&shp->starmode_type, "SIP0", sizeof(shp->starmode_type));
848 memcpy(shp->starmode_addr, dldst, sizeof(shp->starmode_addr));
850 s = spltty();
851 if (sc->sc_oqlen && sc->sc_ttyp->t_outq.c_cc == sc->sc_oqlen) {
852 struct bintime bt;
854 /* if output's been stalled for too long, and restart */
855 getbinuptime(&bt);
856 bintime_sub(&bt, &sc->sc_lastpacket);
857 if (bt.sec > 0) {
858 DPRINTF(("stripoutput: stalled, resetting\n"));
859 sc->sc_otimeout++;
860 stripstart(sc->sc_ttyp);
863 splx(s);
865 s = splnet();
866 if ((error = ifq_enqueue2(ifp, ifq, m ALTQ_COMMA
867 ALTQ_DECL(&pktattr))) != 0) {
868 splx(s);
869 return error;
871 getbinuptime(&sc->sc_lastpacket);
872 splx(s);
874 s = spltty();
875 stripstart(sc->sc_ttyp);
876 splx(s);
878 return (0);
883 * Start output on interface. Get another datagram
884 * to send from the interface queue and map it to
885 * the interface before starting output.
889 stripstart(struct tty *tp)
891 struct strip_softc *sc = tp->t_sc;
894 * If there is more in the output queue, just send it now.
895 * We are being called in lieu of ttstart and must do what
896 * it would.
898 if (tp->t_outq.c_cc != 0) {
899 (*tp->t_oproc)(tp);
900 if (tp->t_outq.c_cc > SLIP_HIWAT)
901 return (0);
905 * This happens briefly when the line shuts down.
907 if (sc == NULL)
908 return (0);
909 softint_schedule(sc->sc_si);
910 return (0);
914 * Copy data buffer to mbuf chain; add ifnet pointer.
916 static struct mbuf *
917 strip_btom(struct strip_softc *sc, int len)
919 struct mbuf *m;
922 * Allocate a new input buffer and swap.
924 m = sc->sc_mbuf;
925 MGETHDR(sc->sc_mbuf, M_DONTWAIT, MT_DATA);
926 if (sc->sc_mbuf == NULL) {
927 sc->sc_mbuf = m;
928 return (NULL);
930 MCLGET(sc->sc_mbuf, M_DONTWAIT);
931 if ((sc->sc_mbuf->m_flags & M_EXT) == 0) {
932 m_freem(sc->sc_mbuf);
933 sc->sc_mbuf = m;
934 return (NULL);
936 sc->sc_ep = (u_char *) sc->sc_mbuf->m_ext.ext_buf +
937 sc->sc_mbuf->m_ext.ext_size;
939 m->m_data = sc->sc_pktstart;
941 m->m_pkthdr.len = m->m_len = len;
942 m->m_pkthdr.rcvif = &sc->sc_if;
943 return (m);
947 * tty interface receiver interrupt.
949 * Called with a single char from the tty receiver interrupt; put
950 * the char into the buffer containing a partial packet. If the
951 * char is a packet delimiter, decapsulate the packet, wrap it in
952 * an mbuf, and put it on the protocol input queue.
955 stripinput(int c, struct tty *tp)
957 struct strip_softc *sc;
958 struct mbuf *m;
959 int len;
961 tk_nin++;
962 sc = (struct strip_softc *)tp->t_sc;
963 if (sc == NULL)
964 return (0);
965 if (c & TTY_ERRORMASK || ((tp->t_state & TS_CARR_ON) == 0 &&
966 (tp->t_cflag & CLOCAL) == 0)) {
967 sc->sc_flags |= SC_ERROR;
968 DPRINTF(("strip: input, error %x\n", c)); /* XXX */
969 return (0);
971 c &= TTY_CHARMASK;
973 ++sc->sc_if.if_ibytes;
976 * Accumulate characters until we see a frame terminator (\r).
978 switch (c) {
980 case '\n':
982 * Error message strings from the modem are terminated with
983 * \r\n. This driver interprets the \r as a packet terminator.
984 * If the first character in a packet is a \n, drop it.
985 * (it can never be the first char of a vaild frame).
987 if (sc->sc_mp - sc->sc_pktstart == 0)
988 break;
990 /* Fall through to */
992 default:
993 if (sc->sc_mp < sc->sc_ep) {
994 *sc->sc_mp++ = c;
995 } else {
996 sc->sc_flags |= SC_ERROR;
997 goto error;
999 return (0);
1001 case STRIP_FRAME_END:
1002 break;
1007 * We only reach here if we see a CR delimiting a packet.
1011 len = sc->sc_mp - sc->sc_pktstart;
1013 #ifdef XDEBUG
1014 if (len < 15 || sc->sc_flags & SC_ERROR)
1015 printf("stripinput: end of pkt, len %d, err %d\n",
1016 len, sc->sc_flags & SC_ERROR); /*XXX*/
1017 #endif
1018 if(sc->sc_flags & SC_ERROR) {
1019 sc->sc_flags &= ~SC_ERROR;
1020 addlog("%s: sc error flag set. terminating packet\n",
1021 sc->sc_if.if_xname);
1022 goto newpack;
1026 * We have a frame.
1027 * Process an IP packet, ARP packet, AppleTalk packet,
1028 * AT command resposne, or Starmode error.
1030 len = strip_newpacket(sc, sc->sc_pktstart, sc->sc_mp);
1031 if (len <= 1)
1032 /* less than min length packet - ignore */
1033 goto newpack;
1035 m = strip_btom(sc, len);
1036 if (m == NULL)
1037 goto error;
1039 IF_ENQUEUE(&sc->sc_inq, m);
1040 softint_schedule(sc->sc_si);
1041 goto newpack;
1043 error:
1044 sc->sc_if.if_ierrors++;
1046 newpack:
1047 sc->sc_mp = sc->sc_pktstart = (u_char *) sc->sc_mbuf->m_ext.ext_buf +
1048 BUFOFFSET;
1050 return (0);
1053 static void
1054 stripintr(void *arg)
1056 struct strip_softc *sc = arg;
1057 struct tty *tp = sc->sc_ttyp;
1058 struct mbuf *m;
1059 int s, len;
1060 u_char *pktstart;
1061 #ifdef INET
1062 u_char c;
1063 #endif
1064 #if NBPFILTER > 0
1065 u_char chdr[CHDR_LEN];
1066 #endif
1068 KASSERT(tp != NULL);
1071 * Output processing loop.
1073 mutex_enter(softnet_lock);
1074 for (;;) {
1075 #ifdef INET
1076 struct ip *ip;
1077 #endif
1078 #if NBPFILTER > 0
1079 struct mbuf *bpf_m;
1080 #endif
1083 * Do not remove the packet from the queue if it
1084 * doesn't look like it will fit into the current
1085 * serial output queue (STRIP_MTU_ONWIRE, or
1086 * Starmode header + 20 bytes + 4 bytes in case we
1087 * have to probe the radio).
1089 s = spltty();
1090 if (tp->t_outq.c_cn - tp->t_outq.c_cc <
1091 STRIP_MTU_ONWIRE + 4) {
1092 splx(s);
1093 break;
1095 splx(s);
1098 * Get a packet and send it to the radio.
1100 s = splnet();
1101 IF_DEQUEUE(&sc->sc_fastq, m);
1102 if (m)
1103 sc->sc_if.if_omcasts++; /* XXX */
1104 else
1105 IFQ_DEQUEUE(&sc->sc_if.if_snd, m);
1106 splx(s);
1108 if (m == NULL)
1109 break;
1112 * We do the header compression here rather than in
1113 * stripoutput() because the packets will be out of
1114 * order if we are using TOS queueing, and the
1115 * connection ID compression will get munged when
1116 * this happens.
1118 #if NBPFILTER > 0
1119 if (sc->sc_if.if_bpf) {
1121 * We need to save the TCP/IP header before
1122 * it's compressed. To avoid complicated
1123 * code, we just make a deep copy of the
1124 * entire packet (since this is a serial
1125 * line, packets should be short and/or the
1126 * copy should be negligible cost compared
1127 * to the packet transmission time).
1129 bpf_m = m_dup(m, 0, M_COPYALL, M_DONTWAIT);
1130 } else
1131 bpf_m = NULL;
1132 #endif
1133 #ifdef INET
1134 if ((ip = mtod(m, struct ip *))->ip_p == IPPROTO_TCP) {
1135 if (sc->sc_if.if_flags & SC_COMPRESS)
1136 *mtod(m, u_char *) |=
1137 sl_compress_tcp(m, ip,
1138 &sc->sc_comp, 1);
1140 #endif
1141 #if NBPFILTER > 0
1142 if (sc->sc_if.if_bpf && bpf_m != NULL)
1143 bpf_mtap_sl_out(sc->sc_if.if_bpf, mtod(m, u_char *),
1144 bpf_m);
1145 #endif
1146 getbinuptime(&sc->sc_lastpacket);
1148 s = spltty();
1149 strip_send(sc, m);
1152 * We now have characters in the output queue,
1153 * kick the serial port.
1155 if (tp->t_outq.c_cc != 0)
1156 (*tp->t_oproc)(tp);
1157 splx(s);
1161 * Input processing loop.
1163 for (;;) {
1164 s = spltty();
1165 IF_DEQUEUE(&sc->sc_inq, m);
1166 splx(s);
1167 if (m == NULL)
1168 break;
1169 pktstart = mtod(m, u_char *);
1170 len = m->m_pkthdr.len;
1171 #if NBPFILTER > 0
1172 if (sc->sc_if.if_bpf) {
1174 * Save the compressed header, so we
1175 * can tack it on later. Note that we
1176 * will end up copying garbage in come
1177 * cases but this is okay. We remember
1178 * where the buffer started so we can
1179 * compute the new header length.
1181 memcpy(chdr, pktstart, CHDR_LEN);
1183 #endif /* NBPFILTER > 0 */
1184 #ifdef INET
1185 if ((c = (*pktstart & 0xf0)) != (IPVERSION << 4)) {
1186 if (c & 0x80)
1187 c = TYPE_COMPRESSED_TCP;
1188 else if (c == TYPE_UNCOMPRESSED_TCP)
1189 *pktstart &= 0x4f; /* XXX */
1191 * We've got something that's not an IP
1192 * packet. If compression is enabled,
1193 * try to decompress it. Otherwise, if
1194 * `auto-enable' compression is on and
1195 * it's a reasonable packet, decompress
1196 * it and then enable compression.
1197 * Otherwise, drop it.
1199 if (sc->sc_if.if_flags & SC_COMPRESS) {
1200 len = sl_uncompress_tcp(&pktstart, len,
1201 (u_int)c, &sc->sc_comp);
1202 if (len <= 0) {
1203 m_freem(m);
1204 continue;
1206 } else if ((sc->sc_if.if_flags & SC_AUTOCOMP) &&
1207 c == TYPE_UNCOMPRESSED_TCP && len >= 40) {
1208 len = sl_uncompress_tcp(&pktstart, len,
1209 (u_int)c, &sc->sc_comp);
1210 if (len <= 0) {
1211 m_freem(m);
1212 continue;
1214 sc->sc_if.if_flags |= SC_COMPRESS;
1215 } else {
1216 m_freem(m);
1217 continue;
1220 #endif
1221 m->m_data = (void *) pktstart;
1222 m->m_pkthdr.len = m->m_len = len;
1223 #if NBPFILTER > 0
1224 if (sc->sc_if.if_bpf) {
1225 bpf_mtap_sl_in(sc->sc_if.if_bpf, chdr, &m);
1226 if (m == NULL)
1227 continue;
1229 #endif
1231 * If the packet will fit into a single
1232 * header mbuf, copy it into one, to save
1233 * memory.
1235 if (m->m_pkthdr.len < MHLEN) {
1236 struct mbuf *n;
1237 int pktlen;
1239 MGETHDR(n, M_DONTWAIT, MT_DATA);
1240 pktlen = m->m_pkthdr.len;
1241 M_MOVE_PKTHDR(n, m);
1242 memcpy(mtod(n, void *), mtod(m, void *), pktlen);
1243 n->m_len = m->m_len;
1244 m_freem(m);
1245 m = n;
1248 sc->sc_if.if_ipackets++;
1249 getbinuptime(&sc->sc_lastpacket);
1251 #ifdef INET
1252 s = splnet();
1253 if (IF_QFULL(&ipintrq)) {
1254 IF_DROP(&ipintrq);
1255 sc->sc_if.if_ierrors++;
1256 sc->sc_if.if_iqdrops++;
1257 m_freem(m);
1258 } else {
1259 IF_ENQUEUE(&ipintrq, m);
1260 schednetisr(NETISR_IP);
1262 splx(s);
1263 #endif
1265 mutex_exit(softnet_lock);
1269 * Process an ioctl request.
1272 stripioctl(struct ifnet *ifp, u_long cmd, void *data)
1274 struct ifaddr *ifa = (struct ifaddr *)data;
1275 struct ifreq *ifr;
1276 int s, error = 0;
1278 s = splnet();
1280 switch (cmd) {
1282 case SIOCINITIFADDR:
1283 if (ifa->ifa_addr->sa_family == AF_INET)
1284 ifp->if_flags |= IFF_UP;
1285 else
1286 error = EAFNOSUPPORT;
1287 break;
1289 case SIOCSIFDSTADDR:
1290 if (ifa->ifa_addr->sa_family != AF_INET)
1291 error = EAFNOSUPPORT;
1292 break;
1294 case SIOCADDMULTI:
1295 case SIOCDELMULTI:
1296 ifr = (struct ifreq *)data;
1297 if (ifr == 0) {
1298 error = EAFNOSUPPORT; /* XXX */
1299 break;
1301 switch (ifreq_getaddr(cmd, ifr)->sa_family) {
1303 #ifdef INET
1304 case AF_INET:
1305 break;
1306 #endif
1308 default:
1309 error = EAFNOSUPPORT;
1310 break;
1312 break;
1314 default:
1315 error = ifioctl_common(ifp, cmd, data);
1317 splx(s);
1318 return (error);
1323 * Strip subroutines
1327 * Set a radio into starmode.
1328 * Must be called at spltty().
1330 void
1331 strip_resetradio(struct strip_softc *sc, struct tty *tp)
1333 #if 0
1334 static ttychar_t InitString[] =
1335 "\r\n\r\n\r\nat\r\n\r\n\r\nate0dt**starmode\r\n**\r\n";
1336 #else
1337 static ttychar_t InitString[] =
1338 "\r\rat\r\r\rate0q1dt**starmode\r**\r";
1339 #endif
1340 int i;
1343 * XXX Perhaps flush tty output queue?
1346 if ((i = b_to_q(InitString, sizeof(InitString) - 1, &tp->t_outq))) {
1347 printf("resetradio: %d chars didn't fit in tty queue\n", i);
1348 return;
1350 sc->sc_if.if_obytes += sizeof(InitString) - 1;
1353 * Assume the radio is still dead, so we can detect repeated
1354 * resets (perhaps the radio is disconnected, powered off, or
1355 * is so badlyhung it needs powercycling.
1357 sc->sc_state = ST_DEAD;
1358 getbinuptime(&sc->sc_lastpacket);
1359 sc->sc_statetimo = time_second + STRIP_RESET_INTERVAL;
1362 * XXX Does calling the tty output routine now help resets?
1364 (*sc->sc_ttyp->t_oproc)(tp);
1369 * Send an invalid starmode packet to the radio, to induce an error message
1370 * indicating the radio is in starmode.
1371 * Update the state machine to indicate a response is expected.
1372 * Either the radio answers, which will be caught by the parser,
1373 * or the watchdog will start resetting.
1375 * NOTE: drops chars directly on the tty output queue.
1376 * should be caled at spl >= spltty.
1378 void
1379 strip_proberadio(struct strip_softc *sc, struct tty *tp)
1382 int overflow;
1383 const char *strip_probestr = "**";
1385 if (sc->sc_if.if_flags & IFF_DEBUG)
1386 addlog("%s: attempting to probe radio\n", sc->sc_if.if_xname);
1388 overflow = b_to_q((const ttychar_t *)strip_probestr, 2, &tp->t_outq);
1389 if (overflow == 0) {
1390 if (sc->sc_if.if_flags & IFF_DEBUG)
1391 addlog("%s:: sent probe to radio\n",
1392 sc->sc_if.if_xname);
1393 /* Go to probe-sent state, set timeout accordingly. */
1394 sc->sc_state = ST_PROBE_SENT;
1395 sc->sc_statetimo = time_second + ST_PROBERESPONSE_INTERVAL;
1396 } else {
1397 addlog("%s: incomplete probe, tty queue %d bytes overfull\n",
1398 sc->sc_if.if_xname, overflow);
1403 #ifdef DEBUG
1404 static const char *strip_statenames[] = {
1405 "Alive",
1406 "Probe sent, awaiting answer",
1407 "Probe not answered, resetting"
1409 #endif
1413 * Timeout routine -- try to start more output.
1414 * Will be needed to make strip work on ptys.
1416 void
1417 strip_timeout(void *x)
1419 struct strip_softc *sc = (struct strip_softc *) x;
1420 struct tty *tp = sc->sc_ttyp;
1421 int s;
1423 s = spltty();
1424 sc->sc_flags &= ~SC_TIMEOUT;
1425 stripstart(tp);
1426 splx(s);
1431 * Strip watchdog routine.
1432 * The radio hardware is balky. When sent long packets or bursts of small
1433 * packets, the radios crash and reboots into Hayes-emulation mode.
1434 * The transmit-side machinery, the error parser, and strip_watchdog()
1435 * implement a simple finite state machine.
1437 * We attempt to send a probe to the radio every ST_PROBE seconds. There
1438 * is no direct way to tell if the radio is in starmode, so we send it a
1439 * malformed starmode packet -- a frame with no destination address --
1440 * and expect to an "name missing" error response from the radio within
1441 * 1 second. If we hear such a response, we assume the radio is alive
1442 * for the next ST_PROBE seconds.
1443 * If we don't hear a starmode-error response from the radio, we reset it.
1445 * Probes, and parsing of error responses, are normally done inside the send
1446 * and receive side respectively. This watchdog routine examines the
1447 * state-machine variables. If there are no packets to send to the radio
1448 * during an entire probe interval, strip_output will not be called,
1449 * so we send a probe on its behalf.
1451 void
1452 strip_watchdog(struct ifnet *ifp)
1454 struct strip_softc *sc = ifp->if_softc;
1455 struct tty *tp = sc->sc_ttyp;
1458 * Just punt if the line has been closed.
1460 if (tp == NULL)
1461 return;
1463 #ifdef DEBUG
1464 if (ifp->if_flags & IFF_DEBUG)
1465 addlog("\n%s: in watchdog, state %s timeout %lld\n",
1466 ifp->if_xname,
1467 ((unsigned) sc->sc_state < 3) ?
1468 strip_statenames[sc->sc_state] : "<<illegal state>>",
1469 (long long)(sc->sc_statetimo - time_second));
1470 #endif
1473 * If time in this state hasn't yet expired, return.
1475 if ((ifp->if_flags & IFF_UP) == 0 || sc->sc_statetimo > time_second) {
1476 goto done;
1480 * The time in the current state has expired.
1481 * Take appropriate action and advance FSA to the next state.
1483 switch (sc->sc_state) {
1484 case ST_ALIVE:
1486 * A probe is due but we haven't piggybacked one on a packet.
1487 * Send a probe now.
1489 strip_proberadio(sc, sc->sc_ttyp);
1490 (*tp->t_oproc)(tp);
1491 break;
1493 case ST_PROBE_SENT:
1495 * Probe sent but no response within timeout. Reset.
1497 addlog("%s: no answer to probe, resetting radio\n",
1498 ifp->if_xname);
1499 strip_resetradio(sc, sc->sc_ttyp);
1500 ifp->if_oerrors++;
1501 break;
1503 case ST_DEAD:
1505 * The radio has been sent a reset but didn't respond.
1506 * XXX warn user to remove AC adaptor and battery,
1507 * wait 5 secs, and replace.
1509 addlog("%s: radio reset but not responding, Trying again\n",
1510 ifp->if_xname);
1511 strip_resetradio(sc, sc->sc_ttyp);
1512 ifp->if_oerrors++;
1513 break;
1515 default:
1516 /* Cannot happen. To be safe, do a reset. */
1517 addlog("%s: %s %d, resetting\n",
1518 sc->sc_if.if_xname,
1519 "radio-reset finite-state machine in invalid state",
1520 sc->sc_state);
1521 strip_resetradio(sc, sc->sc_ttyp);
1522 sc->sc_state = ST_DEAD;
1523 break;
1526 done:
1527 ifp->if_timer = STRIP_WATCHDOG_INTERVAL;
1528 return;
1533 * The following bytestuffing and run-length encoding/decoding
1534 * functions are taken, with permission from Stuart Cheshire,
1535 * from the MosquitonNet strip driver for Linux.
1536 * XXX Linux style left intact, to ease folding in updates from
1537 * the Mosquitonet group.
1542 * Process a received packet.
1545 strip_newpacket(struct strip_softc *sc, u_char *ptr, u_char *end)
1547 int len = ptr - end;
1548 u_char *name, *name_end;
1549 u_int packetlen;
1551 /* Ignore empty lines */
1552 if (len == 0) return 0;
1554 /* Catch 'OK' responses which show radio has fallen out of starmode */
1555 if (len >= 2 && ptr[0] == 'O' && ptr[1] == 'K') {
1556 printf("%s: Radio is back in AT command mode: will reset\n",
1557 sc->sc_if.if_xname);
1558 FORCE_RESET(sc); /* Do reset ASAP */
1559 return 0;
1562 /* Check for start of address marker, and then skip over it */
1563 if (*ptr != '*') {
1564 /* Catch other error messages */
1565 if (ptr[0] == 'E' && ptr[1] == 'R' && ptr[2] == 'R' && ptr[3] == '_')
1566 RecvErr_Message(sc, NULL, ptr+4);
1567 /* XXX what should the message above be? */
1568 else {
1569 RecvErr("No initial *", sc);
1570 addlog("(len = %d)\n", len);
1572 return 0;
1575 /* skip the '*' */
1576 ptr++;
1578 /* Skip the return address */
1579 name = ptr;
1580 while (ptr < end && *ptr != '*')
1581 ptr++;
1583 /* Check for end of address marker, and skip over it */
1584 if (ptr == end) {
1585 RecvErr("No second *", sc);
1586 return 0;
1588 name_end = ptr++;
1590 /* Check for SRIP key, and skip over it */
1591 if (ptr[0] != 'S' || ptr[1] != 'I' || ptr[2] != 'P' || ptr[3] != '0') {
1592 if (ptr[0] == 'E' && ptr[1] == 'R' && ptr[2] == 'R' &&
1593 ptr[3] == '_') {
1594 *name_end = 0;
1595 RecvErr_Message(sc, name, ptr+4);
1597 else RecvErr("No SRIP key", sc);
1598 return 0;
1600 ptr += 4;
1602 /* Decode start of the IP packet header */
1603 ptr = UnStuffData(ptr, end, sc->sc_rxbuf, 4);
1604 if (ptr == 0) {
1605 RecvErr("Runt packet (hdr)", sc);
1606 return 0;
1610 * The STRIP bytestuff/RLL encoding has no explicit length
1611 * of the decoded packet. Decode start of IP header, get the
1612 * IP header length and decode that many bytes in total.
1614 packetlen = ((uint16_t)sc->sc_rxbuf[2] << 8) | sc->sc_rxbuf[3];
1616 #ifdef DIAGNOSTIC
1617 #if 0
1618 printf("Packet %02x.%02x.%02x.%02x\n",
1619 sc->sc_rxbuf[0], sc->sc_rxbuf[1],
1620 sc->sc_rxbuf[2], sc->sc_rxbuf[3]);
1621 printf("Got %d byte packet\n", packetlen);
1622 #endif
1623 #endif
1625 /* Decode remainder of the IP packer */
1626 ptr = UnStuffData(ptr, end, sc->sc_rxbuf+4, packetlen-4);
1627 if (ptr == 0) {
1628 RecvErr("Short packet", sc);
1629 return 0;
1632 /* XXX redundant copy */
1633 memcpy(sc->sc_pktstart, sc->sc_rxbuf, packetlen );
1634 return (packetlen);
1639 * Stuffing scheme:
1640 * 00 Unused (reserved character)
1641 * 01-3F Run of 2-64 different characters
1642 * 40-7F Run of 1-64 different characters plus a single zero at the end
1643 * 80-BF Run of 1-64 of the same character
1644 * C0-FF Run of 1-64 zeroes (ASCII 0)
1646 typedef enum
1648 Stuff_Diff = 0x00,
1649 Stuff_DiffZero = 0x40,
1650 Stuff_Same = 0x80,
1651 Stuff_Zero = 0xC0,
1652 Stuff_NoCode = 0xFF, /* Special code, meaning no code selected */
1654 Stuff_CodeMask = 0xC0,
1655 Stuff_CountMask = 0x3F,
1656 Stuff_MaxCount = 0x3F,
1657 Stuff_Magic = 0x0D /* The value we are eliminating */
1658 } StuffingCode;
1661 * StuffData encodes the data starting at "src" for "length" bytes.
1662 * It writes it to the buffer pointed to by "dest" (which must be at least
1663 * as long as 1 + 65/64 of the input length). The output may be up to 1.6%
1664 * larger than the input for pathological input, but will usually be smaller.
1665 * StuffData returns the new value of the dest pointer as its result.
1667 * "code_ptr_ptr" points to a "u_char *" which is used to hold
1668 * encoding state between calls, allowing an encoded packet to be
1669 * incrementally built up from small parts.
1670 * On the first call, the "u_char *" pointed to should be initialized
1671 * to NULL; between subsequent calls the calling routine should leave
1672 * the value alone and simply pass it back unchanged so that the
1673 * encoder can recover its current state.
1676 #define StuffData_FinishBlock(X) \
1677 (*code_ptr = (X) ^ Stuff_Magic, code = Stuff_NoCode)
1679 static u_char*
1680 StuffData(u_char *src, u_long length, u_char *dest, u_char **code_ptr_ptr)
1682 u_char *end = src + length;
1683 u_char *code_ptr = *code_ptr_ptr;
1684 u_char code = Stuff_NoCode, count = 0;
1686 if (!length) return (dest);
1688 if (code_ptr) { /* Recover state from last call, if applicable */
1689 code = (*code_ptr ^ Stuff_Magic) & Stuff_CodeMask;
1690 count = (*code_ptr ^ Stuff_Magic) & Stuff_CountMask;
1693 while (src < end) {
1694 switch (code) {
1696 * Stuff_NoCode: If no current code, select one
1698 case Stuff_NoCode:
1699 code_ptr = dest++; /* Record where we're going to put this code */
1700 count = 0; /* Reset the count (zero means one instance) */
1701 /* Tentatively start a new block */
1702 if (*src == 0) {
1703 code = Stuff_Zero;
1704 src++;
1705 } else {
1706 code = Stuff_Same;
1707 *dest++ = *src++ ^ Stuff_Magic;
1709 /* Note: We optimistically assume run of same -- which will be */
1710 /* fixed later in Stuff_Same if it turns out not to be true. */
1711 break;
1714 * Stuff_Zero: We already have at least one zero encoded
1716 case Stuff_Zero:
1718 /* If another zero, count it, else finish this code block */
1719 if (*src == 0) {
1720 count++;
1721 src++;
1722 } else
1723 StuffData_FinishBlock(Stuff_Zero + count);
1724 break;
1727 * Stuff_Same: We already have at least one byte encoded
1729 case Stuff_Same:
1730 /* If another one the same, count it */
1731 if ((*src ^ Stuff_Magic) == code_ptr[1]) {
1732 count++;
1733 src++;
1734 break;
1736 /* else, this byte does not match this block. */
1737 /* If we already have two or more bytes encoded, finish this code block */
1738 if (count) {
1739 StuffData_FinishBlock(Stuff_Same + count);
1740 break;
1742 /* else, we only have one so far, so switch to Stuff_Diff code */
1743 code = Stuff_Diff; /* and fall through to Stuff_Diff case below */
1745 case Stuff_Diff: /* Stuff_Diff: We have at least two *different* bytes encoded */
1746 /* If this is a zero, must encode a Stuff_DiffZero, and begin a new block */
1747 if (*src == 0)
1748 StuffData_FinishBlock(Stuff_DiffZero + count);
1749 /* else, if we have three in a row, it is worth starting a Stuff_Same block */
1750 else if ((*src ^ Stuff_Magic) == dest[-1] && dest[-1] == dest[-2])
1752 code += count-2;
1753 if (code == Stuff_Diff)
1754 code = Stuff_Same;
1755 StuffData_FinishBlock(code);
1756 code_ptr = dest-2;
1757 /* dest[-1] already holds the correct value */
1758 count = 2; /* 2 means three bytes encoded */
1759 code = Stuff_Same;
1761 /* else, another different byte, so add it to the block */
1762 else {
1763 *dest++ = *src ^ Stuff_Magic;
1764 count++;
1766 src++; /* Consume the byte */
1767 break;
1770 if (count == Stuff_MaxCount)
1771 StuffData_FinishBlock(code + count);
1773 if (code == Stuff_NoCode)
1774 *code_ptr_ptr = NULL;
1775 else {
1776 *code_ptr_ptr = code_ptr;
1777 StuffData_FinishBlock(code + count);
1780 return (dest);
1786 * UnStuffData decodes the data at "src", up to (but not including)
1787 * "end". It writes the decoded data into the buffer pointed to by
1788 * "dst", up to a maximum of "dst_length", and returns the new
1789 * value of "src" so that a follow-on call can read more data,
1790 * continuing from where the first left off.
1792 * There are three types of results:
1793 * 1. The source data runs out before extracting "dst_length" bytes:
1794 * UnStuffData returns NULL to indicate failure.
1795 * 2. The source data produces exactly "dst_length" bytes:
1796 * UnStuffData returns new_src = end to indicate that all bytes
1797 * were consumed.
1798 * 3. "dst_length" bytes are extracted, with more
1799 * remaining. UnStuffData returns new_src < end to indicate that
1800 * there are more bytes to be read.
1802 * Note: The decoding may be dstructive, in that it may alter the
1803 * source data in the process of decoding it (this is necessary to
1804 * allow a follow-on call to resume correctly).
1807 static u_char*
1808 UnStuffData(u_char *src, u_char *end, u_char *dst, u_long dst_length)
1810 u_char *dst_end = dst + dst_length;
1812 /* Sanity check */
1813 if (!src || !end || !dst || !dst_length)
1814 return (NULL);
1816 while (src < end && dst < dst_end)
1818 int count = (*src ^ Stuff_Magic) & Stuff_CountMask;
1819 switch ((*src ^ Stuff_Magic) & Stuff_CodeMask)
1821 case Stuff_Diff:
1822 if (src+1+count >= end)
1823 return (NULL);
1826 *dst++ = *++src ^ Stuff_Magic;
1828 while(--count >= 0 && dst < dst_end);
1829 if (count < 0)
1830 src += 1;
1831 else
1832 if (count == 0)
1833 *src = Stuff_Same ^ Stuff_Magic;
1834 else
1835 *src = (Stuff_Diff + count) ^ Stuff_Magic;
1836 break;
1837 case Stuff_DiffZero:
1838 if (src+1+count >= end)
1839 return (NULL);
1842 *dst++ = *++src ^ Stuff_Magic;
1844 while(--count >= 0 && dst < dst_end);
1845 if (count < 0)
1846 *src = Stuff_Zero ^ Stuff_Magic;
1847 else
1848 *src = (Stuff_DiffZero + count) ^ Stuff_Magic;
1849 break;
1850 case Stuff_Same:
1851 if (src+1 >= end)
1852 return (NULL);
1855 *dst++ = src[1] ^ Stuff_Magic;
1857 while(--count >= 0 && dst < dst_end);
1858 if (count < 0)
1859 src += 2;
1860 else
1861 *src = (Stuff_Same + count) ^ Stuff_Magic;
1862 break;
1863 case Stuff_Zero:
1866 *dst++ = 0;
1868 while(--count >= 0 && dst < dst_end);
1869 if (count < 0)
1870 src += 1;
1871 else
1872 *src = (Stuff_Zero + count) ^ Stuff_Magic;
1873 break;
1877 if (dst < dst_end)
1878 return (NULL);
1879 else
1880 return (src);
1886 * Log an error mesesage (for a packet received with errors?)
1887 * from the STRIP driver.
1889 static void
1890 RecvErr(const char *msg, struct strip_softc *sc)
1892 #define MAX_RecErr 80
1893 u_char *ptr = sc->sc_pktstart;
1894 u_char *end = sc->sc_mp;
1895 u_char pkt_text[MAX_RecErr], *p = pkt_text;
1896 *p++ = '\"';
1897 while (ptr < end && p < &pkt_text[MAX_RecErr-4]) {
1898 if (*ptr == '\\') {
1899 *p++ = '\\';
1900 *p++ = '\\';
1901 } else if (*ptr >= 32 && *ptr <= 126)
1902 *p++ = *ptr;
1903 else {
1904 snprintf(p, sizeof(pkt_text) - (p - pkt_text),
1905 "\\%02x", *ptr);
1906 p += 3;
1908 ptr++;
1911 if (ptr == end) *p++ = '\"';
1912 *p++ = 0;
1913 addlog("%s: %13s : %s\n", sc->sc_if.if_xname, msg, pkt_text);
1915 sc->sc_if.if_ierrors++;
1920 * Parse an error message from the radio.
1922 static void
1923 RecvErr_Message(struct strip_softc *strip_info, u_char *sendername,
1924 const u_char *msg)
1926 static const char ERR_001[] = "001"; /* Not in StarMode! */
1927 static const char ERR_002[] = "002"; /* Remap handle */
1928 static const char ERR_003[] = "003"; /* Can't resolve name */
1929 static const char ERR_004[] = "004"; /* Name too small or missing */
1930 static const char ERR_005[] = "005"; /* Bad count specification */
1931 static const char ERR_006[] = "006"; /* Header too big */
1932 static const char ERR_007[] = "007"; /* Body too big */
1933 static const char ERR_008[] = "008"; /* Bad character in name */
1934 static const char ERR_009[] = "009"; /* No count or line terminator */
1936 char * if_name;
1938 if_name = strip_info->sc_if.if_xname;
1940 if (!strncmp(msg, ERR_001, sizeof(ERR_001)-1))
1942 RecvErr("radio error message:", strip_info);
1943 addlog("%s: Radio %s is not in StarMode\n",
1944 if_name, sendername);
1946 else if (!strncmp(msg, ERR_002, sizeof(ERR_002)-1))
1948 RecvErr("radio error message:", strip_info);
1949 #ifdef notyet /*Kernel doesn't have scanf!*/
1950 int handle;
1951 u_char newname[64];
1952 sscanf(msg, "ERR_002 Remap handle &%d to name %s", &handle, newname);
1953 addlog("%s: Radio name %s is handle %d\n",
1954 if_name, newname, handle);
1955 #endif
1957 else if (!strncmp(msg, ERR_003, sizeof(ERR_003)-1))
1959 RecvErr("radio error message:", strip_info);
1960 addlog("%s: Destination radio name is unknown\n", if_name);
1962 else if (!strncmp(msg, ERR_004, sizeof(ERR_004)-1)) {
1964 * The radio reports it got a badly-framed starmode packet
1965 * from us; so it must me in starmode.
1967 if (strip_info->sc_if.if_flags & IFF_DEBUG)
1968 addlog("%s: radio responded to probe\n", if_name);
1969 if (strip_info->sc_state == ST_DEAD) {
1970 /* A successful reset... */
1971 addlog("%s: Radio back in starmode\n", if_name);
1973 CLEAR_RESET_TIMER(strip_info);
1975 else if (!strncmp(msg, ERR_005, sizeof(ERR_005)-1))
1976 RecvErr("radio error message:", strip_info);
1977 else if (!strncmp(msg, ERR_006, sizeof(ERR_006)-1))
1978 RecvErr("radio error message:", strip_info);
1979 else if (!strncmp(msg, ERR_007, sizeof(ERR_007)-1))
1982 * Note: This error knocks the radio back into
1983 * command mode.
1985 RecvErr("radio error message:", strip_info);
1986 printf("%s: Error! Packet size too big for radio.",
1987 if_name);
1988 FORCE_RESET(strip_info);
1990 else if (!strncmp(msg, ERR_008, sizeof(ERR_008)-1))
1992 RecvErr("radio error message:", strip_info);
1993 printf("%s: Radio name contains illegal character\n",
1994 if_name);
1996 else if (!strncmp(msg, ERR_009, sizeof(ERR_009)-1))
1997 RecvErr("radio error message:", strip_info);
1998 else {
1999 addlog("failed to parse ]%3s[\n", msg);
2000 RecvErr("unparsed radio error message:", strip_info);