if_cx.c revision 123120
1/*
2 * Cronyx-Sigma adapter driver for FreeBSD.
3 * Supports PPP/HDLC and Cisco/HDLC protocol in synchronous mode,
4 * and asyncronous channels with full modem control.
5 * Keepalive protocol implemented in both Cisco and PPP modes.
6 *
7 * Copyright (C) 1994-2002 Cronyx Engineering.
8 * Author: Serge Vakulenko, <vak@cronyx.ru>
9 *
10 * Copyright (C) 1999-2003 Cronyx Engineering.
11 * Rewritten on DDK, ported to NETGRAPH, rewritten for FreeBSD 3.x-5.x by
12 * Kurakin Roman, <rik@cronyx.ru>
13 *
14 * This software is distributed with NO WARRANTIES, not even the implied
15 * warranties for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 *
17 * Authors grant any other persons or organisations a permission to use,
18 * modify and redistribute this software in source and binary forms,
19 * as long as this message is kept with the software, all derivative
20 * works or modified versions.
21 *
22 * Cronyx Id: if_cx.c,v 1.1.2.18 2003/11/27 14:30:03 rik Exp $
23 */
24#include <sys/cdefs.h>
25__FBSDID("$FreeBSD: head/sys/dev/cx/if_cx.c 123120 2003-12-03 07:29:38Z imp $");
26
27#include <sys/param.h>
28
29#if __FreeBSD_version >= 500000
30#   define NCX 1
31#else
32#   include "cx.h"
33#endif
34
35#if NCX > 0
36#include <sys/systm.h>
37#include <sys/kernel.h>
38#include <sys/proc.h>
39#include <sys/mbuf.h>
40#include <sys/sockio.h>
41#include <sys/malloc.h>
42#include <sys/socket.h>
43#include <sys/conf.h>
44#include <sys/errno.h>
45#include <sys/tty.h>
46#if __FreeBSD_version >= 400000
47#   include <sys/bus.h>
48#   include <machine/bus.h>
49#   include <sys/rman.h>
50#   include <isa/isavar.h>
51#endif
52#include <sys/fcntl.h>
53#include <sys/interrupt.h>
54#include <vm/vm.h>
55#include <vm/pmap.h>
56#include <net/if.h>
57#include <machine/cpufunc.h>
58#include <machine/cserial.h>
59#include <machine/clock.h>
60#if __FreeBSD_version < 500000
61#include <machine/ipl.h>
62#include <i386/isa/isa_device.h>
63#endif
64#if __FreeBSD_version >= 400000
65#   include <machine/resource.h>
66#if __FreeBSD_version <= 501000
67#       include <i386/isa/intr_machdep.h>
68#   endif
69#endif
70#if __FreeBSD_version >= 500000
71#   include <dev/cx/machdep.h>
72#   include <dev/cx/cxddk.h>
73#   include <dev/cx/cronyxfw.h>
74#else
75#   include <i386/isa/cronyx/machdep.h>
76#   include <i386/isa/cronyx/cxddk.h>
77#   include <i386/isa/cronyx/cronyxfw.h>
78#endif
79#include "opt_ng_cronyx.h"
80#ifdef NETGRAPH_CRONYX
81#   include "opt_netgraph.h"
82#   include <netgraph/ng_message.h>
83#   include <netgraph/netgraph.h>
84#   if __FreeBSD_version >= 500000
85#       include <dev/cx/ng_cx.h>
86#   else
87#       include <netgraph/ng_cx.h>
88#   endif
89#else
90#   include <net/if_types.h>
91#   if __FreeBSD_version < 500000
92#   include "sppp.h"
93#   if NSPPP <= 0
94#	error The device cp requires sppp or netgraph.
95#   endif
96#   endif
97#   include <net/if_sppp.h>
98#   define PP_CISCO IFF_LINK2
99#if __FreeBSD_version < 400000
100#   include <bpfilter.h>
101#   if NBPFILTER > 0
102#      include <net/bpf.h>
103#   endif
104#else
105#   if __FreeBSD_version < 500000
106#       include <bpf.h>
107#   endif
108#   include <net/bpf.h>
109#   define NBPFILTER NBPF
110#endif
111#endif
112
113#define CX_DEBUG(d,s)	({if (d->chan->debug) {\
114				printf ("%s: ", d->name); printf s;}})
115#define CX_DEBUG2(d,s)	({if (d->chan->debug>1) {\
116				printf ("%s: ", d->name); printf s;}})
117
118#define UNIT(d)         (minor(d) & 0x3f)
119#define IF_CUNIT(d)     (minor(d) & 0x40)
120#define UNIT_CTL        0x3f
121#define CALLOUT(d)      (minor(d) & 0x80)
122#define CDEV_MAJOR	42
123
124typedef struct _async_q {
125	int beg;
126	int end;
127	#define BF_SZ 14400
128	int buf[BF_SZ+1];
129} async_q;
130
131#define AQ_GSZ(q)	((BF_SZ + (q)->end - (q)->beg)%BF_SZ)
132#define AQ_PUSH(q,c)	{*((q)->buf + (q)->end) = c;\
133			(q)->end = ((q)->end + 1)%BF_SZ;}
134#define AQ_POP(q,c)	{c = *((q)->buf + (q)->beg);\
135			(q)->beg = ((q)->beg + 1)%BF_SZ;}
136
137#if __FreeBSD_version >= 400000
138static void cx_identify		__P((driver_t *, device_t));
139static int cx_probe		__P((device_t));
140static int cx_attach		__P((device_t));
141static int cx_detach		__P((device_t));
142
143static device_method_t cx_isa_methods [] = {
144	DEVMETHOD(device_identify,	cx_identify),
145	DEVMETHOD(device_probe,		cx_probe),
146	DEVMETHOD(device_attach,	cx_attach),
147	DEVMETHOD(device_detach,	cx_detach),
148	{0, 0}
149};
150
151typedef struct _bdrv_t {
152	cx_board_t	*board;
153	struct resource	*base_res;
154	struct resource	*drq_res;
155	struct resource	*irq_res;
156	int		base_rid;
157	int		drq_rid;
158	int		irq_rid;
159	void		*intrhand;
160} bdrv_t;
161
162static driver_t cx_isa_driver = {
163	"cx",
164	cx_isa_methods,
165	sizeof (bdrv_t),
166};
167
168static devclass_t cx_devclass;
169#endif
170
171typedef struct _drv_t {
172	char name [8];
173	cx_chan_t *chan;
174	cx_board_t *board;
175	cx_buf_t buf;
176	struct tty tty;
177	struct callout_handle dcd_timeout_handle;
178	unsigned dtrwait;
179	unsigned dtroff;
180	unsigned callout;
181	unsigned lock;
182	int open_dev;
183	int cd;
184	int running;
185	struct	callout_handle dtr_timeout_handle;
186#ifdef NETGRAPH
187	char	nodename [NG_NODELEN+1];
188	hook_p	hook;
189	hook_p	debug_hook;
190	node_p	node;
191	struct	ifqueue lo_queue;
192	struct	ifqueue hi_queue;
193	short	timeout;
194	struct	callout_handle timeout_handle;
195#else
196	struct sppp pp;
197#endif
198#if __FreeBSD_version >= 400000
199	dev_t  devt[3];
200#endif
201	async_q aqueue;
202	#define CX_READ 1
203	#define CX_WRITE 2
204	int intr_action;
205	short atimeout;
206} drv_t;
207
208extern long csigma_fw_len;
209extern const char *csigma_fw_version;
210extern const char *csigma_fw_date;
211extern const char *csigma_fw_copyright;
212extern const cr_dat_tst_t csigma_fw_tvec[];
213extern const u_char csigma_fw_data[];
214static void cx_oproc (struct tty *tp);
215static int cx_param (struct tty *tp, struct termios *t);
216static void cx_stop (struct tty *tp, int flag);
217static void cx_dtrwakeup (void *a);
218static void cx_receive (cx_chan_t *c, char *data, int len);
219static void cx_transmit (cx_chan_t *c, void *attachment, int len);
220static void cx_error (cx_chan_t *c, int data);
221static void cx_modem (cx_chan_t *c);
222static void cx_up (drv_t *d);
223static void cx_start (drv_t *d);
224static void disc_optim(struct tty *tp, struct termios *t);
225#if __FreeBSD_version < 500000
226static swihand_t cx_softintr;
227#else
228static void cx_softintr (void *);
229static void *cx_slow_ih;
230static void *cx_fast_ih;
231#endif
232static void cx_down (drv_t *d);
233static void cx_watchdog (drv_t *d);
234static void cx_carrier (void *arg);
235
236#ifdef NETGRAPH
237extern struct ng_type typestruct;
238#else
239static void cx_ifstart (struct ifnet *ifp);
240static void cx_tlf (struct sppp *sp);
241static void cx_tls (struct sppp *sp);
242static void cx_ifwatchdog (struct ifnet *ifp);
243static int cx_sioctl (struct ifnet *ifp, u_long cmd, caddr_t data);
244static void cx_initialize (void *softc);
245#endif
246
247static cx_board_t *adapter [NCX];
248static drv_t *channel [NCX*NCHAN];
249static struct callout_handle led_timo [NCX];
250static struct callout_handle timeout_handle;
251#if __FreeBSD_version >= 400000
252	extern struct cdevsw cx_cdevsw;
253#endif
254
255static int MY_SOFT_INTR;
256
257/*
258 * Print the mbuf chain, for debug purposes only.
259 */
260static void printmbuf (struct mbuf *m)
261{
262	printf ("mbuf:");
263	for (; m; m=m->m_next) {
264		if (m->m_flags & M_PKTHDR)
265			printf (" HDR %d:", m->m_pkthdr.len);
266		if (m->m_flags & M_EXT)
267			printf (" EXT:");
268		printf (" %d", m->m_len);
269	}
270	printf ("\n");
271}
272
273/*
274 * Make an mbuf from data.
275 */
276static struct mbuf *makembuf (void *buf, u_int len)
277{
278	struct mbuf *m, *o, *p;
279
280	MGETHDR (m, M_DONTWAIT, MT_DATA);
281
282	if (! m)
283		return 0;
284
285	if (len >= MINCLSIZE)
286		MCLGET (m, M_DONTWAIT);
287
288	m->m_pkthdr.len = len;
289	m->m_len = 0;
290
291	p = m;
292	while (len) {
293		u_int n = M_TRAILINGSPACE (p);
294		if (n > len)
295			n = len;
296		if (! n) {
297			/* Allocate new mbuf. */
298			o = p;
299			MGET (p, M_DONTWAIT, MT_DATA);
300			if (! p) {
301				m_freem (m);
302				return 0;
303			}
304			if (len >= MINCLSIZE)
305				MCLGET (p, M_DONTWAIT);
306			p->m_len = 0;
307			o->m_next = p;
308
309			n = M_TRAILINGSPACE (p);
310			if (n > len)
311				n = len;
312		}
313		bcopy (buf, mtod (p, caddr_t) + p->m_len, n);
314
315		p->m_len += n;
316		buf = n + (char*) buf;
317		len -= n;
318	}
319	return m;
320}
321
322/*
323 * Recover after lost transmit interrupts.
324 */
325static void cx_timeout (void *arg)
326{
327	drv_t *d;
328	int s, i;
329
330	for (i=0; i<NCX*NCHAN; ++i) {
331		d = channel[i];
332		if (! d)
333			continue;
334		s = splhigh ();
335		if (d->atimeout == 1 && d->tty.t_state & TS_BUSY) {
336			d->tty.t_state &= ~TS_BUSY;
337			if (d->tty.t_dev) {
338				d->intr_action |= CX_WRITE;
339				MY_SOFT_INTR = 1;
340#if __FreeBSD_version >= 500000
341				swi_sched (cx_fast_ih, 0);
342#else
343				setsofttty ();
344#endif
345			}
346			CX_DEBUG (d, ("cx_timeout\n"));
347		}
348		if (d->atimeout)
349			d->atimeout--;
350		splx (s);
351	}
352	timeout_handle = timeout (cx_timeout, 0, hz*5);
353}
354
355static void cx_led_off (void *arg)
356{
357	cx_board_t *b = arg;
358	int s = splhigh ();
359
360	cx_led (b, 0);
361	led_timo[b->num].callout = 0;
362	splx (s);
363}
364
365/*
366 * Activate interupt handler from DDK.
367 */
368#if __FreeBSD_version >= 400000
369static void cx_intr (void *arg)
370{
371	bdrv_t *bd = arg;
372	cx_board_t *b = bd->board;
373#else
374static void cx_intr (int bnum)
375{
376	cx_board_t *b = adapter [bnum];
377#endif
378	int s = splhigh ();
379
380	/* Turn LED on. */
381	cx_led (b, 1);
382
383	cx_int_handler (b);
384
385	/* Turn LED off 50 msec later. */
386	if (! led_timo[b->num].callout)
387		led_timo[b->num] = timeout (cx_led_off, b, hz/20);
388	splx (s);
389}
390
391static int probe_irq (cx_board_t *b, int irq)
392{
393	int mask, busy, cnt;
394
395	/* Clear pending irq, if any. */
396	cx_probe_irq (b, -irq);
397	DELAY (100);
398	for (cnt=0; cnt<5; ++cnt) {
399		/* Get the mask of pending irqs, assuming they are busy.
400		 * Activate the adapter on given irq. */
401		busy = cx_probe_irq (b, irq);
402		DELAY (100);
403
404		/* Get the mask of active irqs.
405		 * Deactivate our irq. */
406		mask = cx_probe_irq (b, -irq);
407		DELAY (100);
408		if ((mask & ~busy) == 1 << irq) {
409			cx_probe_irq (b, 0);
410			/* printf ("cx%d: irq %d ok, mask=0x%04x, busy=0x%04x\n",
411				b->num, irq, mask, busy); */
412			return 1;
413		}
414	}
415	/* printf ("cx%d: irq %d not functional, mask=0x%04x, busy=0x%04x\n",
416		b->num, irq, mask, busy); */
417	cx_probe_irq (b, 0);
418	return 0;
419}
420
421static short porttab [] = {
422	0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0,
423	0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3c0, 0x3e0, 0
424};
425static char dmatab [] = { 7, 6, 5, 0 };
426static char irqtab [] = { 5, 10, 11, 7, 3, 15, 12, 0 };
427
428#if __FreeBSD_version >= 400000
429static int cx_is_free_res (device_t dev, int rid, int type, u_long start,
430	u_long end, u_long count)
431{
432	struct resource *res;
433
434	if (!(res = bus_alloc_resource (dev, type, &rid, start, end, count,
435	    RF_ALLOCATED)))
436		return 0;
437
438	bus_release_resource (dev, type, rid, res);
439
440	return 1;
441}
442
443static void cx_identify (driver_t *driver, device_t dev)
444{
445	u_long iobase, rescount;
446	int devcount;
447	device_t *devices;
448	device_t child;
449	devclass_t my_devclass;
450	int i, k;
451
452	if ((my_devclass = devclass_find ("cx")) == NULL)
453		return;
454
455	devclass_get_devices (my_devclass, &devices, &devcount);
456
457	if (devcount == 0) {
458		/* We should find all devices by our self. We could alter other
459		 * devices, but we don't have a choise
460		 */
461		for (i = 0; (iobase = porttab [i]) != 0; i++) {
462			if (!cx_is_free_res (dev, 1, SYS_RES_IOPORT,
463			    iobase, iobase + NPORT, NPORT))
464				continue;
465			if (cx_probe_board (iobase, -1, -1) == 0)
466				continue;
467
468			devcount++;
469
470			child = BUS_ADD_CHILD (dev, ISA_ORDER_SPECULATIVE, "cx",
471			    -1);
472
473			if (child == NULL)
474				return;
475
476			device_set_desc_copy (child, "Cronyx Sigma");
477			device_set_driver (child, driver);
478			bus_set_resource (child, SYS_RES_IOPORT, 0,
479			    iobase, NPORT);
480
481			if (devcount >= NCX)
482				break;
483		}
484	} else {
485		static short porttab [] = {
486			0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0,
487			0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3c0, 0x3e0, 0
488		};
489		/* Lets check user choise.
490		 */
491		for (k = 0; k < devcount; k++) {
492			if (bus_get_resource (devices[k], SYS_RES_IOPORT, 0,
493			    &iobase, &rescount) != 0)
494				continue;
495
496			for (i = 0; porttab [i] != 0; i++) {
497				if (porttab [i] != iobase)
498					continue;
499				if (!cx_is_free_res (devices[k], 1, SYS_RES_IOPORT,
500				    iobase, iobase + NPORT, NPORT))
501					continue;
502				if (cx_probe_board (iobase, -1, -1) == 0)
503					continue;
504				porttab [i] = -1;
505				device_set_desc_copy (devices[k], "Cronyx Sigma");
506				break;
507			}
508
509			if (porttab [i] == 0) {
510				device_delete_child (
511				    device_get_parent (devices[k]),
512				    devices [k]);
513				devices[k] = 0;
514				continue;
515			}
516		}
517		for (k = 0; k < devcount; k++) {
518			if (devices[k] == 0)
519				continue;
520			if (bus_get_resource (devices[k], SYS_RES_IOPORT, 0,
521			    &iobase, &rescount) == 0)
522				continue;
523			for (i = 0; (iobase = porttab [i]) != 0; i++) {
524				if (porttab [i] == -1) {
525					continue;
526				}
527				if (!cx_is_free_res (devices[k], 1, SYS_RES_IOPORT,
528				    iobase, iobase + NPORT, NPORT))
529					continue;
530				if (cx_probe_board (iobase, -1, -1) == 0)
531					continue;
532
533				bus_set_resource (devices[k], SYS_RES_IOPORT, 0,
534				    iobase, NPORT);
535				porttab [i] = -1;
536				device_set_desc_copy (devices[k], "Cronyx Sigma");
537				break;
538			}
539			if (porttab [i] == 0) {
540				device_delete_child (
541				    device_get_parent (devices[k]),
542				    devices [k]);
543			}
544		}
545		free (devices, M_TEMP);
546	}
547
548	return;
549}
550
551static int cx_probe (device_t dev)
552{
553	int unit = device_get_unit (dev);
554	int i;
555	u_long iobase, rescount;
556
557	if (!device_get_desc (dev) ||
558	    strcmp (device_get_desc (dev), "Cronyx Sigma"))
559		return ENXIO;
560
561	if (bus_get_resource (dev, SYS_RES_IOPORT, 0, &iobase, &rescount) != 0) {
562		printf ("cx%d: Couldn't get IOPORT\n", unit);
563		return ENXIO;
564	}
565
566	if (!cx_is_free_res (dev, 1, SYS_RES_IOPORT,
567	    iobase, iobase + NPORT, NPORT)) {
568		printf ("cx%d: Resource IOPORT isn't free %lx\n", unit, iobase);
569		return ENXIO;
570	}
571
572	for (i = 0; porttab [i] != 0; i++) {
573		if (porttab [i] == iobase) {
574			porttab [i] = -1;
575			break;
576		}
577	}
578
579	if (porttab [i] == 0) {
580		return ENXIO;
581	}
582
583	if (!cx_probe_board (iobase, -1, -1)) {
584		printf ("cx%d: probing for Sigma at %lx faild\n", unit, iobase);
585		return ENXIO;
586	}
587
588	return 0;
589}
590#else /* __FreeBSD_version < 400000 */
591static int cx_probe (struct isa_device *id)
592{
593	cx_board_t *b;
594	int i;
595
596#ifndef NETGRAPH
597	if (! sppp_attach) {
598		printf ("cx%d: no synchronous PPP driver configured\n",
599			id->id_unit);
600		return 0;
601	}
602#endif
603	if (id->id_iobase < 0) {
604		/* Autodetect the adapter. */
605		for (i=0; ; i++) {
606			if (! porttab[i]) {
607				id->id_iobase = -1;
608				return 0;
609			}
610			id->id_iobase = porttab[i];
611			if (id->id_unit > 0 && adapter[0] && adapter[0]->port == id->id_iobase)
612				continue;
613			if (id->id_unit > 1 && adapter[1] && adapter[1]->port == id->id_iobase)
614				continue;
615			if (! haveseen_isadev (id, CC_IOADDR | CC_QUIET) &&
616 			    cx_probe_board (id->id_iobase, -1, -1))
617 				break;
618		}
619	} else if (! cx_probe_board (id->id_iobase, -1, -1))
620		return 0;
621
622	if (id->id_drq < 0) {
623		/* Find available 16-bit DRQ. */
624
625		for (i=0; ; ++i) {
626			if (! dmatab[i]) {
627				printf ("cx%d: no available drq found\n",
628					id->id_unit);
629				id->id_drq = -1;
630				return 0;
631			}
632			id->id_drq = dmatab[i];
633			if (! haveseen_isadev (id, CC_DRQ | CC_QUIET)
634			    && !isa_dma_acquire (id->id_drq))
635 				break;
636		}
637	}
638
639	b = malloc (sizeof (cx_board_t), M_DEVBUF, M_WAITOK);
640	if (!b) {
641		printf ("cx:%d: Couldn't allocate memory\n", id->id_unit);
642		return (ENXIO);
643	}
644	adapter[id->id_unit] = b;
645	bzero (b, sizeof(cx_board_t));
646
647	if (! cx_open_board (b, id->id_unit, id->id_iobase,
648	    id->id_irq ? ffs (id->id_irq) - 1 : -1, id->id_drq)) {
649		printf ("cx%d: cannot initialize adapter\n", id->id_unit);
650		isa_dma_release (id->id_drq);
651		adapter[id->id_unit] = 0;
652		free (b, M_DEVBUF);
653		return 0;
654	}
655
656	if (id->id_irq) {
657		if (! probe_irq (b, ffs (id->id_irq) - 1))
658			printf ("cx%d: irq %d not functional\n",
659				id->id_unit, ffs (id->id_irq) - 1);
660	} else {
661		/* Find available IRQ. */
662
663		for (i=0; ; ++i) {
664			if (! irqtab[i]) {
665				printf ("cx%d: no available irq found\n",
666					id->id_unit);
667				id->id_irq = -1;
668				isa_dma_release (id->id_drq);
669				adapter[id->id_unit] = 0;
670				free (b, M_DEVBUF);
671				return 0;
672			}
673			id->id_irq = 1 << irqtab[i];
674			if (haveseen_isadev (id, CC_IRQ | CC_QUIET))
675				continue;
676#ifdef KLD_MODULE
677			if (register_intr (irqtab[i], 0, 0, (inthand2_t*)
678			    cx_intr, &net_imask, id->id_unit) != 0)
679				continue;
680			unregister_intr (irqtab[i], (inthand2_t*) cx_intr);
681#endif
682 			if (probe_irq (b, irqtab[i]))
683 				break;
684		}
685	}
686	cx_init (b, b->num, b->port, ffs (id->id_irq) - 1, b->dma);
687	cx_setup_board (b, 0, 0, 0);
688
689	return 1;
690}
691#endif /* __FreeBSD_version < 400000 */
692
693/*
694 * The adapter is present, initialize the driver structures.
695 */
696#if __FreeBSD_version < 400000
697static int cx_attach (struct isa_device *id)
698{
699#else
700static int cx_attach (device_t dev)
701{
702	bdrv_t *bd = device_get_softc (dev);
703	u_long iobase, drq, irq, rescount;
704	int unit = device_get_unit (dev);
705	int i;
706	int s;
707#endif
708	cx_board_t *b;
709	cx_chan_t *c;
710	drv_t *d;
711
712#if __FreeBSD_version >= 400000
713	KASSERT ((bd != NULL), ("cx%d: NULL device softc\n", unit));
714
715	bus_get_resource (dev, SYS_RES_IOPORT, 0, &iobase, &rescount);
716	bd->base_rid = 0;
717	bd->base_res = bus_alloc_resource (dev, SYS_RES_IOPORT, &bd->base_rid,
718		iobase, iobase + NPORT, NPORT, RF_ACTIVE);
719	if (! bd->base_res) {
720		printf ("cx%d: cannot allocate base address\n", unit);
721		return ENXIO;
722	}
723
724	if (bus_get_resource (dev, SYS_RES_DRQ, 0, &drq, &rescount) != 0) {
725		for (i = 0; (drq = dmatab [i]) != 0; i++) {
726			if (!cx_is_free_res (dev, 1, SYS_RES_DRQ,
727			    drq, drq + 1, 1))
728				continue;
729			bus_set_resource (dev, SYS_RES_DRQ, 0, drq, 1);
730			break;
731		}
732
733		if (dmatab[i] == 0) {
734			bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
735				bd->base_res);
736			printf ("cx%d: Couldn't get DRQ\n", unit);
737			return ENXIO;
738		}
739	}
740
741	bd->drq_rid = 0;
742	bd->drq_res = bus_alloc_resource (dev, SYS_RES_DRQ, &bd->drq_rid,
743		drq, drq + 1, 1, RF_ACTIVE);
744	if (! bd->drq_res) {
745		printf ("cx%d: cannot allocate drq\n", unit);
746		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
747			bd->base_res);
748		return ENXIO;
749	}
750
751	if (bus_get_resource (dev, SYS_RES_IRQ, 0, &irq, &rescount) != 0) {
752		for (i = 0; (irq = irqtab [i]) != 0; i++) {
753			if (!cx_is_free_res (dev, 1, SYS_RES_IRQ,
754			    irq, irq + 1, 1))
755				continue;
756			bus_set_resource (dev, SYS_RES_IRQ, 0, irq, 1);
757			break;
758		}
759
760		if (irqtab[i] == 0) {
761			bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
762				bd->drq_res);
763			bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
764				bd->base_res);
765			printf ("cx%d: Couldn't get IRQ\n", unit);
766			return ENXIO;
767		}
768	}
769
770	bd->irq_rid = 0;
771	bd->irq_res = bus_alloc_resource (dev, SYS_RES_IRQ, &bd->irq_rid,
772		irq, irq + 1, 1, RF_ACTIVE);
773	if (! bd->irq_res) {
774		printf ("cx%d: Couldn't allocate irq\n", unit);
775		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
776			bd->drq_res);
777		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
778			bd->base_res);
779		return ENXIO;
780	}
781
782	b = malloc (sizeof (cx_board_t), M_DEVBUF, M_WAITOK);
783	if (!b) {
784		printf ("cx:%d: Couldn't allocate memory\n", unit);
785		return (ENXIO);
786	}
787	adapter[unit] = b;
788	bzero (b, sizeof(cx_board_t));
789
790	if (! cx_open_board (b, unit, iobase, irq, drq)) {
791		printf ("cx%d: error loading firmware\n", unit);
792		free (b, M_DEVBUF);
793		bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid,
794			bd->irq_res);
795		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
796			bd->drq_res);
797		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
798			bd->base_res);
799 		return ENXIO;
800	}
801
802	bd->board = b;
803
804	if (! probe_irq (b, irq)) {
805		printf ("cx%d: irq %ld not functional\n", unit, irq);
806		bd->board = 0;
807		adapter [unit] = 0;
808		free (b, M_DEVBUF);
809		bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid,
810			bd->irq_res);
811		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
812			bd->drq_res);
813		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
814			bd->base_res);
815 		return ENXIO;
816	}
817
818	s = splhigh ();
819	if (bus_setup_intr (dev, bd->irq_res, INTR_TYPE_NET, cx_intr, bd,
820	    &bd->intrhand)) {
821		printf ("cx%d: Can't setup irq %ld\n", unit, irq);
822		bd->board = 0;
823		adapter [unit] = 0;
824		free (b, M_DEVBUF);
825		bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid,
826			bd->irq_res);
827		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
828			bd->drq_res);
829		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
830			bd->base_res);
831		splx (s);
832 		return ENXIO;
833	}
834
835	cx_init (b, b->num, b->port, irq, drq);
836	cx_setup_board (b, 0, 0, 0);
837#else /* __FreeBSD_version >= 400000 */
838	b = adapter[id->id_unit];
839#endif /* __FreeBSD_version >= 400000 */
840
841	printf ("cx%d: <Cronyx-Sigma-%s>\n", b->num, b->name);
842#if __FreeBSD_version < 400000
843	id->id_ointr = cx_intr;
844#endif
845
846	for (c=b->chan; c<b->chan+NCHAN; ++c) {
847#if __FreeBSD_version >= 400000
848		char *dnmt="tty %x";
849		char *dnmc="cua %x";
850#endif
851		if (c->type == T_NONE)
852			continue;
853		d = contigmalloc (sizeof(drv_t), M_DEVBUF, M_WAITOK,
854			0x100000, 0x1000000, 16, 0);
855		channel [b->num*NCHAN + c->num] = d;
856		bzero (d, sizeof(drv_t));
857		sprintf (d->name, "cx%d.%d", b->num, c->num);
858		d->board = b;
859		d->chan = c;
860		d->tty.t_oproc = cx_oproc;
861		d->tty.t_param = cx_param;
862#if __FreeBSD_version >= 400000
863		d->tty.t_stop  = cx_stop;
864#endif
865		d->dtrwait = 3 * hz;	/* Default DTR off timeout is 3 seconds. */
866		d->open_dev = 0;
867		c->sys = d;
868
869		switch (c->type) {
870		case T_SYNC_RS232:
871		case T_SYNC_V35:
872		case T_SYNC_RS449:
873		case T_UNIV:
874		case T_UNIV_RS232:
875		case T_UNIV_RS449:
876		case T_UNIV_V35:
877#ifdef NETGRAPH
878		if (ng_make_node_common (&typestruct, &d->node) != 0) {
879			printf ("%s: cannot make common node\n", d->name);
880			channel [b->num*NCHAN + c->num] = 0;
881			c->sys = 0;
882			contigfree (d, sizeof (d), M_DEVBUF);
883			continue;
884		}
885#if __FreeBSD_version >= 500000
886		NG_NODE_SET_PRIVATE (d->node, d);
887#else
888		d->node->private = d;
889#endif
890		sprintf (d->nodename, "%s%d", NG_CX_NODE_TYPE,
891			 c->board->num*NCHAN + c->num);
892		if (ng_name_node (d->node, d->nodename)) {
893			printf ("%s: cannot name node\n", d->nodename);
894#if __FreeBSD_version >= 500000
895			NG_NODE_UNREF (d->node);
896#else
897			ng_rmnode (d->node);
898			ng_unref (d->node);
899#endif
900			channel [b->num*NCHAN + c->num] = 0;
901			c->sys = 0;
902			contigfree (d, sizeof (d), M_DEVBUF);
903			continue;
904		}
905		d->lo_queue.ifq_maxlen = IFQ_MAXLEN;
906		d->hi_queue.ifq_maxlen = IFQ_MAXLEN;
907#if __FreeBSD_version >= 500000
908		mtx_init (&d->lo_queue.ifq_mtx, "cx_queue_lo", NULL, MTX_DEF);
909		mtx_init (&d->hi_queue.ifq_mtx, "cx_queue_hi", NULL, MTX_DEF);
910#endif
911#else /*NETGRAPH*/
912		d->pp.pp_if.if_softc    = d;
913#if __FreeBSD_version > 501000
914		if_initname (&d->pp.pp_if, "cx", b->num * NCHAN + c->num);
915#else
916		d->pp.pp_if.if_unit     = b->num * NCHAN + c->num;
917		d->pp.pp_if.if_name     = "cx";
918#endif
919		d->pp.pp_if.if_mtu      = PP_MTU;
920		d->pp.pp_if.if_flags    = IFF_POINTOPOINT | IFF_MULTICAST;
921		d->pp.pp_if.if_ioctl    = cx_sioctl;
922		d->pp.pp_if.if_start    = cx_ifstart;
923		d->pp.pp_if.if_watchdog = cx_ifwatchdog;
924		d->pp.pp_if.if_init     = cx_initialize;
925		sppp_attach (&d->pp.pp_if);
926		if_attach (&d->pp.pp_if);
927		d->pp.pp_tlf            = cx_tlf;
928		d->pp.pp_tls		= cx_tls;
929#if __FreeBSD_version >= 400000 || NBPFILTER > 0
930		/* If BPF is in the kernel, call the attach for it.
931		 * Size of PPP header is 4 bytes. */
932		bpfattach (&d->pp.pp_if, DLT_PPP, 4);
933#endif
934#endif /*NETGRAPH*/
935		}
936		cx_start_chan (c, &d->buf, vtophys (&d->buf));
937		cx_register_receive (c, &cx_receive);
938		cx_register_transmit (c, &cx_transmit);
939		cx_register_error (c, &cx_error);
940		cx_register_modem (c, &cx_modem);
941#if __FreeBSD_version >= 400000
942		dnmt[3] = 'x'+b->num;
943		dnmc[3] = 'x'+b->num;
944		d->devt[0] = make_dev (&cx_cdevsw, b->num*NCHAN + c->num, UID_ROOT, GID_WHEEL, 0644, dnmt, b->num*NCHAN + c->num);
945		d->devt[1] = make_dev (&cx_cdevsw, b->num*NCHAN + c->num + 64, UID_ROOT, GID_WHEEL, 0600, "cx%d", b->num*NCHAN + c->num);
946		d->devt[2] = make_dev (&cx_cdevsw, b->num*NCHAN + c->num + 128, UID_ROOT, GID_WHEEL, 0660, dnmc, b->num*NCHAN + c->num);
947	}
948	splx (s);
949
950	return 0;
951#else /* __FreeBSD_version < 400000 */
952	}
953
954	return 1;
955#endif
956}
957
958#if __FreeBSD_version >= 400000
959static int cx_detach (device_t dev)
960{
961	bdrv_t *bd = device_get_softc (dev);
962	cx_board_t *b = bd->board;
963	cx_chan_t *c;
964	int s = splhigh ();
965
966	/* Check if the device is busy (open). */
967	for (c = b->chan; c < b->chan + NCHAN; ++c) {
968		drv_t *d = (drv_t*) c->sys;
969
970		if (!d || d->chan->type == T_NONE)
971			continue;
972		if (d->lock) {
973			splx (s);
974			return EBUSY;
975		}
976		if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN) &&
977		    (d->open_dev|0x2)) {
978			splx (s);
979			return EBUSY;
980		}
981		if (d->running) {
982			splx (s);
983			return EBUSY;
984		}
985	}
986
987	/* Deactivate the timeout routine. And soft interrupt*/
988	if (led_timo[b->num].callout)
989		untimeout (cx_led_off, b, led_timo[b->num]);
990
991	for (c = b->chan; c < b->chan + NCHAN; ++c) {
992		drv_t *d = c->sys;
993
994		if (!d || d->chan->type == T_NONE)
995			continue;
996
997		if (d->dtr_timeout_handle.callout)
998			untimeout (cx_dtrwakeup, d, d->dtr_timeout_handle);
999		if (d->dcd_timeout_handle.callout)
1000			untimeout (cx_carrier, c, d->dcd_timeout_handle);
1001	}
1002	bus_teardown_intr (dev, bd->irq_res, bd->intrhand);
1003	bus_deactivate_resource (dev, SYS_RES_IRQ, bd->irq_rid, bd->irq_res);
1004	bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid, bd->irq_res);
1005
1006	bus_deactivate_resource (dev, SYS_RES_DRQ, bd->drq_rid, bd->drq_res);
1007	bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid, bd->drq_res);
1008
1009	bus_deactivate_resource (dev, SYS_RES_IOPORT, bd->base_rid, bd->irq_res);
1010	bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid, bd->base_res);
1011
1012	cx_close_board (b);
1013
1014	/* Detach the interfaces, free buffer memory. */
1015	for (c = b->chan; c < b->chan + NCHAN; ++c) {
1016		drv_t *d = (drv_t*) c->sys;
1017
1018		if (!d || d->chan->type == T_NONE)
1019			continue;
1020#ifdef NETGRAPH
1021#if __FreeBSD_version >= 500000
1022		if (d->node) {
1023			ng_rmnode_self (d->node);
1024			NG_NODE_UNREF (d->node);
1025			d->node = NULL;
1026		}
1027		mtx_destroy (&d->lo_queue.ifq_mtx);
1028		mtx_destroy (&d->hi_queue.ifq_mtx);
1029#else
1030		ng_rmnode (d->node);
1031		d->node = NULL;
1032#endif
1033#else
1034#if __FreeBSD_version >= 410000 && NBPFILTER > 0
1035		/* Detach from the packet filter list of interfaces. */
1036		bpfdetach (&d->pp.pp_if);
1037#endif
1038		/* Detach from the sync PPP list. */
1039		sppp_detach (&d->pp.pp_if);
1040
1041		if_detach (&d->pp.pp_if);
1042#endif
1043		destroy_dev (d->devt[0]);
1044		destroy_dev (d->devt[1]);
1045		destroy_dev (d->devt[2]);
1046	}
1047
1048	cx_led_off (b);
1049	if (led_timo[b->num].callout)
1050		untimeout (cx_led_off, b, led_timo[b->num]);
1051	splx (s);
1052
1053	s = splhigh ();
1054	for (c = b->chan; c < b->chan + NCHAN; ++c) {
1055		drv_t *d = (drv_t*) c->sys;
1056
1057		if (!d || d->chan->type == T_NONE)
1058			continue;
1059
1060		/* Deallocate buffers. */
1061		contigfree (d, sizeof(d), M_DEVBUF);
1062	}
1063	bd->board = 0;
1064	adapter [b->num] = 0;
1065	free (b, M_DEVBUF);
1066	splx (s);
1067
1068	return 0;
1069}
1070#endif
1071
1072#ifndef NETGRAPH
1073static void cx_ifstart (struct ifnet *ifp)
1074{
1075        drv_t *d = ifp->if_softc;
1076
1077	cx_start (d);
1078}
1079
1080static void cx_ifwatchdog (struct ifnet *ifp)
1081{
1082        drv_t *d = ifp->if_softc;
1083
1084	cx_watchdog (d);
1085}
1086
1087static void cx_tlf (struct sppp *sp)
1088{
1089	drv_t *d = sp->pp_if.if_softc;
1090
1091	CX_DEBUG (d, ("cx_tlf\n"));
1092/*	cx_set_dtr (d->chan, 0);*/
1093/*	cx_set_rts (d->chan, 0);*/
1094	sp->pp_down (sp);
1095}
1096
1097static void cx_tls (struct sppp *sp)
1098{
1099	drv_t *d = sp->pp_if.if_softc;
1100
1101	CX_DEBUG (d, ("cx_tls\n"));
1102	sp->pp_up (sp);
1103}
1104
1105/*
1106 * Initialization of interface.
1107 * It seems to be never called by upper level.
1108 */
1109static void cx_initialize (void *softc)
1110{
1111	drv_t *d = softc;
1112
1113	CX_DEBUG (d, ("cx_initialize\n"));
1114}
1115
1116/*
1117 * Process an ioctl request.
1118 */
1119static int cx_sioctl (struct ifnet *ifp, u_long cmd, caddr_t data)
1120{
1121	drv_t *d = ifp->if_softc;
1122	int error, s, was_up, should_be_up;
1123
1124	/* No socket ioctls while the channel is in async mode. */
1125	if (d->chan->type == T_NONE || d->chan->mode == M_ASYNC)
1126		return EBUSY;
1127
1128	/* Socket ioctls on slave subchannels are not allowed. */
1129	was_up = (ifp->if_flags & IFF_RUNNING) != 0;
1130	error = sppp_ioctl (ifp, cmd, data);
1131	if (error)
1132		return error;
1133
1134	if (! (ifp->if_flags & IFF_DEBUG))
1135		d->chan->debug = 0;
1136	else if (! d->chan->debug)
1137		d->chan->debug = 1;
1138
1139	switch (cmd) {
1140	default:           CX_DEBUG2 (d, ("ioctl 0x%lx\n", cmd)); return 0;
1141	case SIOCADDMULTI: CX_DEBUG2 (d, ("SIOCADDMULTI\n"));     return 0;
1142	case SIOCDELMULTI: CX_DEBUG2 (d, ("SIOCDELMULTI\n"));     return 0;
1143	case SIOCSIFFLAGS: CX_DEBUG2 (d, ("SIOCSIFFLAGS\n"));     break;
1144	case SIOCSIFADDR:  CX_DEBUG2 (d, ("SIOCSIFADDR\n"));      break;
1145	}
1146
1147	/* We get here only in case of SIFFLAGS or SIFADDR. */
1148	s = splhigh ();
1149	should_be_up = (ifp->if_flags & IFF_RUNNING) != 0;
1150	if (!was_up && should_be_up) {
1151		/* Interface goes up -- start it. */
1152		cx_up (d);
1153		cx_start (d);
1154	} else if (was_up && !should_be_up) {
1155		/* Interface is going down -- stop it. */
1156		/* if ((d->pp.pp_flags & PP_FR) || (ifp->if_flags & PP_CISCO))*/
1157		cx_down (d);
1158	}
1159	splx (s);
1160	return 0;
1161}
1162#endif /*NETGRAPH*/
1163
1164/*
1165 * Stop the interface.  Called on splimp().
1166 */
1167static void cx_down (drv_t *d)
1168{
1169	int s = splhigh ();
1170	CX_DEBUG (d, ("cx_down\n"));
1171	cx_set_dtr (d->chan, 0);
1172	cx_set_rts (d->chan, 0);
1173	d->running = 0;
1174	splx (s);
1175}
1176
1177/*
1178 * Start the interface.  Called on splimp().
1179 */
1180static void cx_up (drv_t *d)
1181{
1182	int s = splhigh ();
1183	CX_DEBUG (d, ("cx_up\n"));
1184	cx_set_dtr (d->chan, 1);
1185	cx_set_rts (d->chan, 1);
1186	d->running = 1;
1187	splx (s);
1188}
1189
1190/*
1191 * Start output on the (slave) interface.  Get another datagram to send
1192 * off of the interface queue, and copy it to the interface
1193 * before starting the output.
1194 */
1195static void cx_send (drv_t *d)
1196{
1197	struct mbuf *m;
1198	u_short len;
1199
1200	CX_DEBUG2 (d, ("cx_send\n"));
1201
1202	/* No output if the interface is down. */
1203	if (! d->running)
1204		return;
1205
1206	/* No output if the modem is off. */
1207	if (! cx_get_dsr (d->chan) && ! cx_get_loop(d->chan))
1208		return;
1209
1210	if (cx_buf_free (d->chan)) {
1211		/* Get the packet to send. */
1212#ifdef NETGRAPH
1213		IF_DEQUEUE (&d->hi_queue, m);
1214		if (! m)
1215			IF_DEQUEUE (&d->lo_queue, m);
1216#else
1217		m = sppp_dequeue (&d->pp.pp_if);
1218#endif
1219		if (! m)
1220			return;
1221#if (__FreeBSD_version >= 400000 || NBPFILTER > 0) && !defined (NETGRAPH)
1222		if (d->pp.pp_if.if_bpf)
1223#if __FreeBSD_version >= 500000
1224			BPF_MTAP (&d->pp.pp_if, m);
1225#else
1226			bpf_mtap (&d->pp.pp_if, m);
1227#endif
1228#endif
1229		len = m->m_pkthdr.len;
1230		if (! m->m_next)
1231			cx_send_packet (d->chan, (u_char*)mtod (m, caddr_t),
1232				len, 0);
1233		else {
1234			u_char buf [DMABUFSZ];
1235			m_copydata (m, 0, len, buf);
1236			cx_send_packet (d->chan, buf, len, 0);
1237		}
1238		m_freem (m);
1239
1240		/* Set up transmit timeout, 10 seconds. */
1241#ifdef NETGRAPH
1242		d->timeout = 10;
1243#else
1244		d->pp.pp_if.if_timer = 10;
1245#endif
1246	}
1247#ifndef NETGRAPH
1248	d->pp.pp_if.if_flags |= IFF_OACTIVE;
1249#endif
1250}
1251
1252/*
1253 * Start output on the interface.
1254 * Always called on splimp().
1255 */
1256static void cx_start (drv_t *d)
1257{
1258	int s = splhigh ();
1259	if (d->running) {
1260		if (! d->chan->dtr)
1261			cx_set_dtr (d->chan, 1);
1262		if (! d->chan->rts)
1263			cx_set_rts (d->chan, 1);
1264		cx_send (d);
1265	}
1266	splx (s);
1267}
1268
1269/*
1270 * Handle transmit timeouts.
1271 * Recover after lost transmit interrupts.
1272 * Always called on splimp().
1273 */
1274static void cx_watchdog (drv_t *d)
1275{
1276	int s = splhigh ();
1277	CX_DEBUG (d, ("device timeout\n"));
1278	if (d->running) {
1279		cx_setup_chan (d->chan);
1280		cx_start_chan (d->chan, 0, 0);
1281		cx_set_dtr (d->chan, 1);
1282		cx_set_rts (d->chan, 1);
1283		cx_start (d);
1284	}
1285	splx (s);
1286}
1287
1288/*
1289 * Transmit callback function.
1290 */
1291static void cx_transmit (cx_chan_t *c, void *attachment, int len)
1292{
1293	drv_t *d = c->sys;
1294
1295	if (!d)
1296		return;
1297
1298	if (c->mode == M_ASYNC) {
1299		d->tty.t_state &= ~(TS_BUSY | TS_FLUSH);
1300		d->atimeout = 0;
1301		if (d->tty.t_dev) {
1302			d->intr_action |= CX_WRITE;
1303			MY_SOFT_INTR = 1;
1304#if __FreeBSD_version >= 500000
1305			swi_sched (cx_fast_ih, 0);
1306#else
1307			setsofttty ();
1308#endif
1309		}
1310		return;
1311	}
1312#ifdef NETGRAPH
1313	d->timeout = 0;
1314#else
1315	++d->pp.pp_if.if_opackets;
1316	d->pp.pp_if.if_flags &= ~IFF_OACTIVE;
1317	d->pp.pp_if.if_timer = 0;
1318#endif
1319	cx_start (d);
1320}
1321
1322/*
1323 * Process the received packet.
1324 */
1325static void cx_receive (cx_chan_t *c, char *data, int len)
1326{
1327	drv_t *d = c->sys;
1328	struct mbuf *m;
1329	char *cc = data;
1330#if __FreeBSD_version >= 500000 && defined NETGRAPH
1331	int error;
1332#endif
1333
1334	if (!d)
1335		return;
1336
1337	if (c->mode == M_ASYNC) {
1338		if (d->tty.t_state & TS_ISOPEN) {
1339			async_q *q = &d->aqueue;
1340			int size = BF_SZ - 1 - AQ_GSZ (q);
1341
1342			if (len <= 0 && !size)
1343				return;
1344
1345			if (len > size) {
1346			        c->ierrs++;
1347				cx_error (c, CX_OVERRUN);
1348				len = size - 1;
1349			}
1350
1351			while (len--) {
1352				AQ_PUSH (q, *(unsigned char *)cc);
1353				cc++;
1354			}
1355
1356			d->intr_action |= CX_READ;
1357			MY_SOFT_INTR = 1;
1358#if __FreeBSD_version >= 500000
1359			swi_sched (cx_fast_ih, 0);
1360#else
1361			setsofttty ();
1362#endif
1363		}
1364		return;
1365	}
1366	if (! d->running)
1367		return;
1368
1369	m = makembuf (data, len);
1370	if (! m) {
1371		CX_DEBUG (d, ("no memory for packet\n"));
1372#ifndef NETGRAPH
1373		++d->pp.pp_if.if_iqdrops;
1374#endif
1375		return;
1376	}
1377	if (c->debug > 1)
1378		printmbuf (m);
1379#ifdef NETGRAPH
1380	m->m_pkthdr.rcvif = 0;
1381#if __FreeBSD_version >= 500000
1382	NG_SEND_DATA_ONLY (error, d->hook, m);
1383#else
1384	ng_queue_data (d->hook, m, 0);
1385#endif
1386#else
1387	++d->pp.pp_if.if_ipackets;
1388	m->m_pkthdr.rcvif = &d->pp.pp_if;
1389#if __FreeBSD_version >= 400000 || NBPFILTER > 0
1390	/* Check if there's a BPF listener on this interface.
1391	 * If so, hand off the raw packet to bpf. */
1392	if (d->pp.pp_if.if_bpf)
1393#if __FreeBSD_version >= 500000
1394		BPF_TAP (&d->pp.pp_if, data, len);
1395#else
1396		bpf_tap (&d->pp.pp_if, data, len);
1397#endif
1398#endif
1399	sppp_input (&d->pp.pp_if, m);
1400#endif
1401}
1402
1403#define CONDITION(t,tp) (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))\
1404	    && (!(tp->t_iflag & BRKINT) || (tp->t_iflag & IGNBRK))\
1405	    && (!(tp->t_iflag & PARMRK)\
1406		|| (tp->t_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))\
1407	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))\
1408	    && linesw[tp->t_line].l_rint == ttyinput)
1409
1410/*
1411 * Error callback function.
1412 */
1413static void cx_error (cx_chan_t *c, int data)
1414{
1415	drv_t *d = c->sys;
1416	async_q *q;
1417
1418	if (!d)
1419		return;
1420
1421	q = &(d->aqueue);
1422
1423	switch (data) {
1424	case CX_FRAME:
1425		CX_DEBUG (d, ("frame error\n"));
1426		if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN)
1427			&& (AQ_GSZ (q) < BF_SZ - 1)
1428			&& (!CONDITION((&d->tty.t_termios), (&d->tty))
1429			|| !(d->tty.t_iflag & (IGNPAR | PARMRK)))) {
1430			AQ_PUSH (q, TTY_FE);
1431			d->intr_action |= CX_READ;
1432			MY_SOFT_INTR = 1;
1433#if __FreeBSD_version >= 500000
1434			swi_sched (cx_fast_ih, 0);
1435#else
1436			setsofttty ();
1437#endif
1438		}
1439#ifndef NETGRAPH
1440		else
1441			++d->pp.pp_if.if_ierrors;
1442#endif
1443		break;
1444	case CX_CRC:
1445		CX_DEBUG (d, ("crc error\n"));
1446		if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN)
1447			&& (AQ_GSZ (q) < BF_SZ - 1)
1448			&& (!CONDITION((&d->tty.t_termios), (&d->tty))
1449			|| !(d->tty.t_iflag & INPCK)
1450			|| !(d->tty.t_iflag & (IGNPAR | PARMRK)))) {
1451			AQ_PUSH (q, TTY_PE);
1452			d->intr_action |= CX_READ;
1453			MY_SOFT_INTR = 1;
1454#if __FreeBSD_version >= 500000
1455			swi_sched (cx_fast_ih, 0);
1456#else
1457			setsofttty ();
1458#endif
1459		}
1460#ifndef NETGRAPH
1461		else
1462			++d->pp.pp_if.if_ierrors;
1463#endif
1464		break;
1465	case CX_OVERRUN:
1466		CX_DEBUG (d, ("overrun error\n"));
1467#ifdef TTY_OE
1468		if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN)
1469			&& (AQ_GSZ (q) < BF_SZ - 1)
1470			&& (!CONDITION((&d->tty.t_termios), (&d->tty)))) {
1471			AQ_PUSH (q, TTY_OE);
1472			d->intr_action |= CX_READ;
1473			MY_SOFT_INTR = 1;
1474#if __FreeBSD_version >= 500000
1475			swi_sched (cx_fast_ih, 0);
1476#else
1477			setsofttty ();
1478#endif
1479		}
1480#endif
1481#ifndef NETGRAPH
1482		else {
1483			++d->pp.pp_if.if_collisions;
1484			++d->pp.pp_if.if_ierrors;
1485		}
1486#endif
1487		break;
1488	case CX_OVERFLOW:
1489		CX_DEBUG (d, ("overflow error\n"));
1490#ifndef NETGRAPH
1491		if (c->mode != M_ASYNC)
1492			++d->pp.pp_if.if_ierrors;
1493#endif
1494		break;
1495	case CX_UNDERRUN:
1496		CX_DEBUG (d, ("underrun error\n"));
1497		if (c->mode != M_ASYNC) {
1498#ifdef NETGRAPH
1499			d->timeout = 0;
1500#else
1501			++d->pp.pp_if.if_oerrors;
1502			d->pp.pp_if.if_flags &= ~IFF_OACTIVE;
1503			d->pp.pp_if.if_timer = 0;
1504			cx_start (d);
1505#endif
1506		}
1507		break;
1508	case CX_BREAK:
1509		CX_DEBUG (d, ("break error\n"));
1510		if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN)
1511			&& (AQ_GSZ (q) < BF_SZ - 1)
1512			&& (!CONDITION((&d->tty.t_termios), (&d->tty))
1513			|| !(d->tty.t_iflag & (IGNBRK | BRKINT | PARMRK)))) {
1514			AQ_PUSH (q, TTY_BI);
1515			d->intr_action |= CX_READ;
1516			MY_SOFT_INTR = 1;
1517#if __FreeBSD_version >= 500000
1518			swi_sched (cx_fast_ih, 0);
1519#else
1520			setsofttty ();
1521#endif
1522		}
1523#ifndef NETGRAPH
1524		else
1525			++d->pp.pp_if.if_ierrors;
1526#endif
1527		break;
1528	default:
1529		CX_DEBUG (d, ("error #%d\n", data));
1530	}
1531}
1532
1533#if __FreeBSD_version < 500000
1534static int cx_open (dev_t dev, int flag, int mode, struct proc *p)
1535#else
1536static int cx_open (dev_t dev, int flag, int mode, struct thread *td)
1537#endif
1538{
1539	int unit = UNIT (dev);
1540	drv_t *d;
1541	int error;
1542
1543	if (unit >= NCX*NCHAN || ! (d = channel[unit]))
1544		return ENXIO;
1545	CX_DEBUG2 (d, ("cx_open unit=%d, flag=0x%x, mode=0x%x\n",
1546		    unit, flag, mode));
1547
1548	if (d->chan->mode != M_ASYNC || IF_CUNIT(dev)) {
1549		d->open_dev |= 0x1;
1550		return 0;
1551	}
1552#if __FreeBSD_version >= 400000
1553	dev->si_tty = &d->tty;
1554#endif
1555	d->tty.t_dev = dev;
1556again:
1557	if (d->dtroff) {
1558		error = tsleep (&d->dtrwait, TTIPRI | PCATCH, "cxdtr", 0);
1559		if (error)
1560			return error;
1561		goto again;
1562	}
1563
1564	if ((d->tty.t_state & TS_ISOPEN) && (d->tty.t_state & TS_XCLUDE) &&
1565#if __FreeBSD_version >= 500000
1566		suser (td))
1567#else
1568	    p->p_ucred->cr_uid != 0)
1569#endif
1570		return EBUSY;
1571
1572	if (d->tty.t_state & TS_ISOPEN) {
1573		/*
1574		 * Cannot open /dev/cua if /dev/tty already opened.
1575		 */
1576		if (CALLOUT (dev) && ! d->callout)
1577			return EBUSY;
1578
1579		/*
1580		 * Opening /dev/tty when /dev/cua is already opened.
1581		 * Wait for close, then try again.
1582		 */
1583		if (! CALLOUT (dev) && d->callout) {
1584			if (flag & O_NONBLOCK)
1585				return EBUSY;
1586			error = tsleep (d, TTIPRI | PCATCH, "cxbi", 0);
1587			if (error)
1588				return error;
1589			goto again;
1590		}
1591	} else if (d->lock && ! CALLOUT (dev) && (flag & O_NONBLOCK))
1592		/*
1593		 * We try to open /dev/tty in non-blocking mode
1594		 * while somebody is already waiting for carrier on it.
1595		 */
1596		return EBUSY;
1597	else {
1598		ttychars (&d->tty);
1599		if (d->tty.t_ispeed == 0) {
1600			d->tty.t_iflag = 0;
1601			d->tty.t_oflag = 0;
1602			d->tty.t_lflag = 0;
1603			d->tty.t_cflag = CREAD | CS8 | HUPCL;
1604			d->tty.t_ispeed = d->chan->rxbaud;
1605			d->tty.t_ospeed = d->chan->txbaud;
1606		}
1607		if (CALLOUT (dev))
1608			d->tty.t_cflag |= CLOCAL;
1609		else
1610			d->tty.t_cflag &= ~CLOCAL;
1611		cx_param (&d->tty, &d->tty.t_termios);
1612		ttsetwater (&d->tty);
1613	}
1614
1615	splhigh ();
1616	if (! (d->tty.t_state & TS_ISOPEN)) {
1617		cx_start_chan (d->chan, 0, 0);
1618		cx_set_dtr (d->chan, 1);
1619		cx_set_rts (d->chan, 1);
1620		d->cd = cx_get_cd (d->chan);
1621		if (CALLOUT (dev) || cx_get_cd (d->chan))
1622			(*linesw[d->tty.t_line].l_modem) (&d->tty, 1);
1623	}
1624
1625	if (! (flag & O_NONBLOCK) && ! (d->tty.t_cflag & CLOCAL) &&
1626	    ! (d->tty.t_state & TS_CARR_ON)) {
1627		/* Lock the channel against cxconfig while we are
1628		 * waiting for carrier. */
1629		d->lock++;
1630		error = tsleep (&d->tty.t_rawq, TTIPRI | PCATCH, "cxdcd", 0);
1631		/* Unlock the channel. */
1632		d->lock--;
1633		spl0 ();
1634		if (error)
1635			goto failed;
1636		goto again;
1637	}
1638
1639	error = (*linesw[d->tty.t_line].l_open) (dev, &d->tty);
1640	disc_optim (&d->tty, &d->tty.t_termios);
1641	spl0 ();
1642	if (error) {
1643failed:         if (! (d->tty.t_state & TS_ISOPEN)) {
1644			splhigh ();
1645			cx_set_dtr (d->chan, 0);
1646			cx_set_rts (d->chan, 0);
1647			if (d->dtrwait) {
1648				d->dtr_timeout_handle =
1649				    timeout (cx_dtrwakeup, d, d->dtrwait);
1650				d->dtroff = 1;
1651			}
1652			spl0 ();
1653		}
1654		return error;
1655	}
1656
1657	if (d->tty.t_state & TS_ISOPEN)
1658		d->callout = CALLOUT (dev) ? 1 : 0;
1659
1660	d->open_dev |= 0x2;
1661	CX_DEBUG2 (d, ("cx_open done\n"));
1662	return 0;
1663}
1664
1665#if __FreeBSD_version < 500000
1666static int cx_close (dev_t dev, int flag, int mode, struct proc *p)
1667#else
1668static int cx_close (dev_t dev, int flag, int mode, struct thread *td)
1669#endif
1670{
1671	drv_t *d = channel [UNIT (dev)];
1672	int s;
1673
1674	CX_DEBUG2 (d, ("cx_close\n"));
1675	if ((!(d->open_dev&0x2)) || IF_CUNIT(dev)){
1676		d->open_dev &= ~0x1;
1677		return 0;
1678	}
1679	s = splhigh ();
1680	(*linesw[d->tty.t_line].l_close) (&d->tty, flag);
1681	disc_optim (&d->tty, &d->tty.t_termios);
1682
1683	/* Disable receiver.
1684	 * Transmitter continues sending the queued data. */
1685	cx_enable_receive (d->chan, 0);
1686
1687	/* Clear DTR and RTS. */
1688	if ((d->tty.t_cflag & HUPCL) || ! (d->tty.t_state & TS_ISOPEN)) {
1689		cx_set_dtr (d->chan, 0);
1690		cx_set_rts (d->chan, 0);
1691		if (d->dtrwait) {
1692			d->dtr_timeout_handle =
1693			    timeout (cx_dtrwakeup, d, d->dtrwait);
1694			d->dtroff = 1;
1695		}
1696	}
1697	ttyclose (&d->tty);
1698	splx (s);
1699	d->callout = 0;
1700
1701	/* Wake up bidirectional opens. */
1702	wakeup (d);
1703	d->open_dev &= ~0x2;
1704
1705	return 0;
1706}
1707
1708static int cx_read (dev_t dev, struct uio *uio, int flag)
1709{
1710	drv_t *d = channel [UNIT (dev)];
1711
1712	if (d)	CX_DEBUG2 (d, ("cx_read\n"));
1713	if (!d || d->chan->mode != M_ASYNC || IF_CUNIT(dev))
1714		return EBADF;
1715
1716	return (*linesw[d->tty.t_line].l_read) (&d->tty, uio, flag);
1717}
1718
1719static int cx_write (dev_t dev, struct uio *uio, int flag)
1720{
1721	drv_t *d = channel [UNIT (dev)];
1722
1723	if (d) CX_DEBUG2 (d, ("cx_write\n"));
1724	if (!d || d->chan->mode != M_ASYNC || IF_CUNIT(dev))
1725		return EBADF;
1726
1727	return (*linesw[d->tty.t_line].l_write) (&d->tty, uio, flag);
1728}
1729
1730static int cx_modem_status (drv_t *d)
1731{
1732	int status = 0, s = splhigh ();
1733	/* Already opened by someone or network interface is up? */
1734	if ((d->chan->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN) &&
1735	    (d->open_dev|0x2)) || (d->chan->mode != M_ASYNC && d->running))
1736		status = TIOCM_LE;      /* always enabled while open */
1737
1738	if (cx_get_dsr (d->chan)) status |= TIOCM_DSR;
1739	if (cx_get_cd  (d->chan)) status |= TIOCM_CD;
1740	if (cx_get_cts (d->chan)) status |= TIOCM_CTS;
1741	if (d->chan->dtr)	  status |= TIOCM_DTR;
1742	if (d->chan->rts)	  status |= TIOCM_RTS;
1743	splx (s);
1744	return status;
1745}
1746
1747#if __FreeBSD_version < 500000
1748static int cx_ioctl (dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
1749#else
1750static int cx_ioctl (dev_t dev, u_long cmd, caddr_t data, int flag, struct thread *td)
1751#endif
1752{
1753	drv_t *d = channel [UNIT (dev)];
1754	cx_chan_t *c;
1755	struct serial_statistics *st;
1756	int error, s;
1757	char mask[16];
1758
1759	if (!d || !(c = d->chan))
1760		return EINVAL;
1761
1762	switch (cmd) {
1763	case SERIAL_GETREGISTERED:
1764	        CX_DEBUG2 (d, ("ioctl: getregistered\n"));
1765		bzero (mask, sizeof(mask));
1766		for (s=0; s<NCX*NCHAN; ++s)
1767			if (channel [s])
1768				mask [s/8] |= 1 << (s & 7);
1769	        bcopy (mask, data, sizeof (mask));
1770		return 0;
1771
1772	case SERIAL_GETPORT:
1773	        CX_DEBUG2 (d, ("ioctl: getport\n"));
1774		s = splhigh ();
1775	        *(int *)data = cx_get_port (c);
1776		splx (s);
1777		if (*(int *)data<0)
1778			return (EINVAL);
1779		else
1780			return 0;
1781
1782	case SERIAL_SETPORT:
1783	        CX_DEBUG2 (d, ("ioctl: setproto\n"));
1784	        /* Only for superuser! */
1785#if __FreeBSD_version < 400000
1786	        error = suser (p->p_ucred, &p->p_acflag);
1787#elif __FreeBSD_version < 500000
1788	        error = suser (p);
1789#else /* __FreeBSD_version >= 500000 */
1790	        error = suser (td);
1791#endif /* __FreeBSD_version >= 500000 */
1792	        if (error)
1793	                return error;
1794
1795		s = splhigh ();
1796		cx_set_port (c, *(int *)data);
1797		splx (s);
1798	        return 0;
1799
1800#ifndef NETGRAPH
1801	case SERIAL_GETPROTO:
1802	        CX_DEBUG2 (d, ("ioctl: getproto\n"));
1803		s = splhigh ();
1804	        strcpy ((char*)data, (c->mode == M_ASYNC) ? "async" :
1805			/*(d->pp.pp_flags & PP_FR) ? "fr" :*/
1806			(d->pp.pp_if.if_flags & PP_CISCO) ? "cisco" : "ppp");
1807		splx (s);
1808	        return 0;
1809
1810	case SERIAL_SETPROTO:
1811	        CX_DEBUG2 (d, ("ioctl: setproto\n"));
1812	        /* Only for superuser! */
1813#if __FreeBSD_version < 400000
1814	        error = suser (p->p_ucred, &p->p_acflag);
1815#elif __FreeBSD_version < 500000
1816	        error = suser (p);
1817#else /* __FreeBSD_version >= 500000 */
1818	        error = suser (td);
1819#endif /* __FreeBSD_version >= 500000 */
1820	        if (error)
1821	                return error;
1822	        if (c->mode == M_ASYNC)
1823	                return EBUSY;
1824		if (d->pp.pp_if.if_flags & IFF_RUNNING)
1825			return EBUSY;
1826	        if (! strcmp ("cisco", (char*)data)) {
1827/*	                d->pp.pp_flags &= ~(PP_FR);*/
1828	                d->pp.pp_flags |= PP_KEEPALIVE;
1829	                d->pp.pp_if.if_flags |= PP_CISCO;
1830/*	        } else if (! strcmp ("fr", (char*)data)) {*/
1831/*	                d->pp.pp_if.if_flags &= ~(PP_CISCO);*/
1832/*	                d->pp.pp_flags |= PP_FR | PP_KEEPALIVE;*/
1833	        } else if (! strcmp ("ppp", (char*)data)) {
1834	                d->pp.pp_flags &= ~(/*PP_FR |*/ PP_KEEPALIVE);
1835	                d->pp.pp_if.if_flags &= ~(PP_CISCO);
1836	        } else
1837			return EINVAL;
1838	        return 0;
1839
1840	case SERIAL_GETKEEPALIVE:
1841	        CX_DEBUG2 (d, ("ioctl: getkeepalive\n"));
1842	        if (/*(d->pp.pp_flags & PP_FR) ||*/
1843		    (d->pp.pp_if.if_flags & PP_CISCO) ||
1844		    (c->mode == M_ASYNC))
1845			return EINVAL;
1846		s = splhigh ();
1847	        *(int*)data = (d->pp.pp_flags & PP_KEEPALIVE) ? 1 : 0;
1848		splx (s);
1849	        return 0;
1850
1851	case SERIAL_SETKEEPALIVE:
1852	        CX_DEBUG2 (d, ("ioctl: setkeepalive\n"));
1853	        /* Only for superuser! */
1854#if __FreeBSD_version < 400000
1855	        error = suser (p->p_ucred, &p->p_acflag);
1856#elif __FreeBSD_version < 500000
1857	        error = suser (p);
1858#else /* __FreeBSD_version >= 500000 */
1859	        error = suser (td);
1860#endif /* __FreeBSD_version >= 500000 */
1861	        if (error)
1862	                return error;
1863	        if (/*(d->pp.pp_flags & PP_FR) ||*/
1864			(d->pp.pp_if.if_flags & PP_CISCO))
1865			return EINVAL;
1866		s = splhigh ();
1867	        if (*(int*)data)
1868	                d->pp.pp_flags |= PP_KEEPALIVE;
1869		else
1870	                d->pp.pp_flags &= ~PP_KEEPALIVE;
1871		splx (s);
1872	        return 0;
1873#endif /*NETGRAPH*/
1874
1875	case SERIAL_GETMODE:
1876	        CX_DEBUG2 (d, ("ioctl: getmode\n"));
1877		s = splhigh ();
1878		*(int*)data = (c->mode == M_ASYNC) ?
1879			SERIAL_ASYNC : SERIAL_HDLC;
1880		splx (s);
1881	        return 0;
1882
1883	case SERIAL_SETMODE:
1884	        CX_DEBUG2 (d, ("ioctl: setmode\n"));
1885	        /* Only for superuser! */
1886#if __FreeBSD_version < 400000
1887	        error = suser (p->p_ucred, &p->p_acflag);
1888#elif __FreeBSD_version < 500000
1889	        error = suser (p);
1890#else /* __FreeBSD_version >= 500000 */
1891	        error = suser (td);
1892#endif /* __FreeBSD_version >= 500000 */
1893	        if (error)
1894	                return error;
1895
1896	        /* Somebody is waiting for carrier? */
1897	        if (d->lock)
1898	                return EBUSY;
1899	        /* /dev/ttyXX is already opened by someone? */
1900	        if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN) &&
1901		    (d->open_dev|0x2))
1902	                return EBUSY;
1903	        /* Network interface is up?
1904	         * Cannot change to async mode. */
1905	        if (c->mode != M_ASYNC && d->running &&
1906	            (*(int*)data == SERIAL_ASYNC))
1907	                return EBUSY;
1908
1909		s = splhigh ();
1910		if (c->mode == M_HDLC && *(int*)data == SERIAL_ASYNC) {
1911			cx_set_mode (c, M_ASYNC);
1912			cx_enable_receive (c, 0);
1913			cx_enable_transmit (c, 0);
1914		} else if (c->mode == M_ASYNC && *(int*)data == SERIAL_HDLC) {
1915			cx_set_mode (c, M_HDLC);
1916			cx_enable_receive (c, 1);
1917			cx_enable_transmit (c, 1);
1918		}
1919	        splx (s);
1920		return 0;
1921
1922	case SERIAL_GETSTAT:
1923	        CX_DEBUG2 (d, ("ioctl: getestat\n"));
1924	        st = (struct serial_statistics*) data;
1925		s = splhigh ();
1926	        st->rintr  = c->rintr;
1927	        st->tintr  = c->tintr;
1928	        st->mintr  = c->mintr;
1929	        st->ibytes = c->ibytes;
1930	        st->ipkts  = c->ipkts;
1931	        st->ierrs  = c->ierrs;
1932	        st->obytes = c->obytes;
1933	        st->opkts  = c->opkts;
1934	        st->oerrs  = c->oerrs;
1935		splx (s);
1936	        return 0;
1937
1938	case SERIAL_CLRSTAT:
1939	        CX_DEBUG2 (d, ("ioctl: clrstat\n"));
1940	        /* Only for superuser! */
1941#if __FreeBSD_version < 400000
1942	        error = suser (p->p_ucred, &p->p_acflag);
1943#elif __FreeBSD_version < 500000
1944	        error = suser (p);
1945#else /* __FreeBSD_version >= 500000 */
1946	        error = suser (td);
1947#endif /* __FreeBSD_version >= 500000 */
1948	        if (error)
1949	                return error;
1950		s = splhigh ();
1951		c->rintr = 0;
1952	        c->tintr = 0;
1953	        c->mintr = 0;
1954	        c->ibytes = 0;
1955	        c->ipkts = 0;
1956	        c->ierrs = 0;
1957	        c->obytes = 0;
1958	        c->opkts = 0;
1959	        c->oerrs = 0;
1960		splx (s);
1961	        return 0;
1962
1963	case SERIAL_GETBAUD:
1964	        CX_DEBUG2 (d, ("ioctl: getbaud\n"));
1965	        if (c->mode == M_ASYNC)
1966	                return EINVAL;
1967		s = splhigh ();
1968	        *(long*)data = cx_get_baud(c);
1969		splx (s);
1970	        return 0;
1971
1972	case SERIAL_SETBAUD:
1973	        CX_DEBUG2 (d, ("ioctl: setbaud\n"));
1974	        /* Only for superuser! */
1975#if __FreeBSD_version < 400000
1976	        error = suser (p->p_ucred, &p->p_acflag);
1977#elif __FreeBSD_version < 500000
1978	        error = suser (p);
1979#else /* __FreeBSD_version >= 500000 */
1980	        error = suser (td);
1981#endif /* __FreeBSD_version >= 500000 */
1982	        if (error)
1983	                return error;
1984	        if (c->mode == M_ASYNC)
1985	                return EINVAL;
1986		s = splhigh ();
1987	        cx_set_baud (c, *(long*)data);
1988	        splx (s);
1989	        return 0;
1990
1991	case SERIAL_GETLOOP:
1992	        CX_DEBUG2 (d, ("ioctl: getloop\n"));
1993	        if (c->mode == M_ASYNC)
1994	                return EINVAL;
1995		s = splhigh ();
1996	        *(int*)data = cx_get_loop (c);
1997		splx (s);
1998	        return 0;
1999
2000	case SERIAL_SETLOOP:
2001	        CX_DEBUG2 (d, ("ioctl: setloop\n"));
2002	        /* Only for superuser! */
2003#if __FreeBSD_version < 400000
2004	        error = suser (p->p_ucred, &p->p_acflag);
2005#elif __FreeBSD_version < 500000
2006	        error = suser (p);
2007#else /* __FreeBSD_version >= 500000 */
2008	        error = suser (td);
2009#endif /* __FreeBSD_version >= 500000 */
2010	        if (error)
2011	                return error;
2012	        if (c->mode == M_ASYNC)
2013	                return EINVAL;
2014		s = splhigh ();
2015	        cx_set_loop (c, *(int*)data);
2016	        splx (s);
2017	        return 0;
2018
2019	case SERIAL_GETDPLL:
2020	        CX_DEBUG2 (d, ("ioctl: getdpll\n"));
2021	        if (c->mode == M_ASYNC)
2022	                return EINVAL;
2023		s = splhigh ();
2024	        *(int*)data = cx_get_dpll (c);
2025		splx (s);
2026	        return 0;
2027
2028	case SERIAL_SETDPLL:
2029	        CX_DEBUG2 (d, ("ioctl: setdpll\n"));
2030	        /* Only for superuser! */
2031#if __FreeBSD_version < 400000
2032	        error = suser (p->p_ucred, &p->p_acflag);
2033#elif __FreeBSD_version < 500000
2034	        error = suser (p);
2035#else /* __FreeBSD_version >= 500000 */
2036	        error = suser (td);
2037#endif /* __FreeBSD_version >= 500000 */
2038	        if (error)
2039	                return error;
2040	        if (c->mode == M_ASYNC)
2041	                return EINVAL;
2042		s = splhigh ();
2043	        cx_set_dpll (c, *(int*)data);
2044	        splx (s);
2045	        return 0;
2046
2047	case SERIAL_GETNRZI:
2048	        CX_DEBUG2 (d, ("ioctl: getnrzi\n"));
2049	        if (c->mode == M_ASYNC)
2050	                return EINVAL;
2051		s = splhigh ();
2052	        *(int*)data = cx_get_nrzi (c);
2053		splx (s);
2054	        return 0;
2055
2056	case SERIAL_SETNRZI:
2057	        CX_DEBUG2 (d, ("ioctl: setnrzi\n"));
2058	        /* Only for superuser! */
2059#if __FreeBSD_version < 400000
2060	        error = suser (p->p_ucred, &p->p_acflag);
2061#elif __FreeBSD_version < 500000
2062	        error = suser (p);
2063#else /* __FreeBSD_version >= 500000 */
2064	        error = suser (td);
2065#endif /* __FreeBSD_version >= 500000 */
2066	        if (error)
2067	                return error;
2068	        if (c->mode == M_ASYNC)
2069	                return EINVAL;
2070		s = splhigh ();
2071	        cx_set_nrzi (c, *(int*)data);
2072	        splx (s);
2073	        return 0;
2074
2075	case SERIAL_GETDEBUG:
2076	        CX_DEBUG2 (d, ("ioctl: getdebug\n"));
2077		s = splhigh ();
2078	        *(int*)data = c->debug;
2079		splx (s);
2080	        return 0;
2081
2082	case SERIAL_SETDEBUG:
2083	        CX_DEBUG2 (d, ("ioctl: setdebug\n"));
2084	        /* Only for superuser! */
2085#if __FreeBSD_version < 400000
2086	        error = suser (p->p_ucred, &p->p_acflag);
2087#elif __FreeBSD_version < 500000
2088	        error = suser (p);
2089#else /* __FreeBSD_version >= 500000 */
2090	        error = suser (td);
2091#endif /* __FreeBSD_version >= 500000 */
2092	        if (error)
2093	                return error;
2094		s = splhigh ();
2095	        c->debug = *(int*)data;
2096		splx (s);
2097#ifndef	NETGRAPH
2098		if (d->chan->debug)
2099			d->pp.pp_if.if_flags |= IFF_DEBUG;
2100		else
2101			d->pp.pp_if.if_flags &= (~IFF_DEBUG);
2102#endif
2103	        return 0;
2104	}
2105
2106	if (c->mode == M_ASYNC) {
2107#if __FreeBSD_version >= 500000
2108		error = (*linesw[d->tty.t_line].l_ioctl) (&d->tty, cmd, data, flag, td);
2109#else
2110		error = (*linesw[d->tty.t_line].l_ioctl) (&d->tty, cmd, data, flag, p);
2111#endif
2112		disc_optim (&d->tty, &d->tty.t_termios);
2113		if (error != ENOIOCTL) {
2114			if (error)
2115			CX_DEBUG2 (d, ("l_ioctl: 0x%lx, error %d\n", cmd, error));
2116			return error;
2117		}
2118		error = ttioctl (&d->tty, cmd, data, flag);
2119		disc_optim (&d->tty, &d->tty.t_termios);
2120		if (error != ENOIOCTL) {
2121			if (error)
2122			CX_DEBUG2 (d, ("ttioctl: 0x%lx, error %d\n", cmd, error));
2123			return error;
2124		}
2125	}
2126
2127	switch (cmd) {
2128	case TIOCSBRK:          /* Start sending line break */
2129	        CX_DEBUG2 (d, ("ioctl: tiocsbrk\n"));
2130		s = splhigh ();
2131		cx_send_break (c, 500);
2132		splx (s);
2133	        return 0;
2134
2135	case TIOCCBRK:          /* Stop sending line break */
2136	        CX_DEBUG2 (d, ("ioctl: tioccbrk\n"));
2137	        return 0;
2138
2139	case TIOCSDTR:          /* Set DTR */
2140	        CX_DEBUG2 (d, ("ioctl: tiocsdtr\n"));
2141		s = splhigh ();
2142		cx_set_dtr (c, 1);
2143		splx (s);
2144	        return 0;
2145
2146	case TIOCCDTR:          /* Clear DTR */
2147	        CX_DEBUG2 (d, ("ioctl: tioccdtr\n"));
2148		s = splhigh ();
2149		cx_set_dtr (c, 0);
2150		splx (s);
2151	        return 0;
2152
2153	case TIOCMSET:          /* Set DTR/RTS */
2154	        CX_DEBUG2 (d, ("ioctl: tiocmset\n"));
2155		s = splhigh ();
2156		cx_set_dtr (c, (*(int*)data & TIOCM_DTR) ? 1 : 0);
2157		cx_set_rts (c, (*(int*)data & TIOCM_RTS) ? 1 : 0);
2158		splx (s);
2159	        return 0;
2160
2161	case TIOCMBIS:          /* Add DTR/RTS */
2162	        CX_DEBUG2 (d, ("ioctl: tiocmbis\n"));
2163		s = splhigh ();
2164		if (*(int*)data & TIOCM_DTR) cx_set_dtr (c, 1);
2165		if (*(int*)data & TIOCM_RTS) cx_set_rts (c, 1);
2166		splx (s);
2167	        return 0;
2168
2169	case TIOCMBIC:          /* Clear DTR/RTS */
2170	        CX_DEBUG2 (d, ("ioctl: tiocmbic\n"));
2171		s = splhigh ();
2172		if (*(int*)data & TIOCM_DTR) cx_set_dtr (c, 0);
2173		if (*(int*)data & TIOCM_RTS) cx_set_rts (c, 0);
2174		splx (s);
2175	        return 0;
2176
2177	case TIOCMGET:          /* Get modem status */
2178	        CX_DEBUG2 (d, ("ioctl: tiocmget\n"));
2179		*(int*)data = cx_modem_status (d);
2180	        return 0;
2181
2182#ifdef TIOCMSDTRWAIT
2183	case TIOCMSDTRWAIT:
2184	        CX_DEBUG2 (d, ("ioctl: tiocmsdtrwait\n"));
2185	        /* Only for superuser! */
2186#if __FreeBSD_version < 400000
2187	        error = suser (p->p_ucred, &p->p_acflag);
2188#elif __FreeBSD_version < 500000
2189	        error = suser (p);
2190#else /* __FreeBSD_version >= 500000 */
2191	        error = suser (td);
2192#endif /* __FreeBSD_version >= 500000 */
2193		if (error)
2194			return error;
2195		s = splhigh ();
2196		d->dtrwait = *(int*)data * hz / 100;
2197		splx (s);
2198	        return 0;
2199#endif
2200
2201#ifdef TIOCMGDTRWAIT
2202	case TIOCMGDTRWAIT:
2203	        CX_DEBUG2 (d, ("ioctl: tiocmgdtrwait\n"));
2204		s = splhigh ();
2205		*(int*)data = d->dtrwait * 100 / hz;
2206		splx (s);
2207	        return 0;
2208#endif
2209	}
2210        CX_DEBUG2 (d, ("ioctl: 0x%lx\n", cmd));
2211	return ENOTTY;
2212}
2213
2214/*
2215 * Wake up opens() waiting for DTR ready.
2216 */
2217static void cx_dtrwakeup (void *arg)
2218{
2219	drv_t *d = arg;
2220
2221	d->dtroff = 0;
2222	wakeup (&d->dtrwait);
2223}
2224
2225
2226static void
2227disc_optim(tp, t)
2228	struct tty	*tp;
2229	struct termios	*t;
2230{
2231	if (CONDITION(t,tp))
2232		tp->t_state |= TS_CAN_BYPASS_L_RINT;
2233	else
2234		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2235}
2236
2237#if __FreeBSD_version >= 500000
2238void cx_softintr (void *unused)
2239#else
2240void cx_softintr ()
2241#endif
2242{
2243	drv_t *d;
2244	async_q *q;
2245	int i, s, ic, k;
2246	while (MY_SOFT_INTR) {
2247		MY_SOFT_INTR = 0;
2248		for (i=0; i<NCX*NCHAN; ++i) {
2249			d = channel [i];
2250			if (!d || !d->chan || d->chan->type == T_NONE
2251			    || d->chan->mode != M_ASYNC || !d->tty.t_dev)
2252				continue;
2253			s = splhigh ();
2254			if (d->intr_action & CX_READ) {
2255				q = &(d->aqueue);
2256				if (d->tty.t_state & TS_CAN_BYPASS_L_RINT) {
2257					k = AQ_GSZ(q);
2258					if (d->tty.t_rawq.c_cc + k >
2259						d->tty.t_ihiwat
2260					    && (d->tty.t_cflag & CRTS_IFLOW
2261						|| d->tty.t_iflag & IXOFF)
2262					    && !(d->tty.t_state & TS_TBLOCK))
2263						ttyblock(&d->tty);
2264					d->tty.t_rawcc += k;
2265					while (k>0) {
2266						k--;
2267						AQ_POP (q, ic);
2268						splx (s);
2269						putc (ic, &d->tty.t_rawq);
2270						s = splhigh ();
2271					}
2272					ttwakeup(&d->tty);
2273					if (d->tty.t_state & TS_TTSTOP
2274					    && (d->tty.t_iflag & IXANY
2275						|| d->tty.t_cc[VSTART] ==
2276						d->tty.t_cc[VSTOP])) {
2277						d->tty.t_state &= ~TS_TTSTOP;
2278						d->tty.t_lflag &= ~FLUSHO;
2279						d->intr_action |= CX_WRITE;
2280					}
2281				} else {
2282					while (q->end != q->beg) {
2283						AQ_POP (q, ic);
2284						splx (s);
2285						(*linesw[d->tty.t_line].l_rint)
2286							(ic, &d->tty);
2287						s = splhigh ();
2288					}
2289				}
2290				d->intr_action &= ~CX_READ;
2291			}
2292			splx (s);
2293
2294			s = splhigh ();
2295			if (d->intr_action & CX_WRITE) {
2296				if (d->tty.t_line)
2297					(*linesw[d->tty.t_line].l_start) (&d->tty);
2298				else
2299					cx_oproc (&d->tty);
2300				d->intr_action &= ~CX_WRITE;
2301			}
2302			splx (s);
2303
2304		}
2305	}
2306}
2307
2308/*
2309 * Fill transmitter buffer with data.
2310 */
2311static void cx_oproc (struct tty *tp)
2312{
2313	int s = splhigh (), k;
2314	drv_t *d = channel [UNIT (tp->t_dev)];
2315	static u_char buf[DMABUFSZ];
2316	u_char *p;
2317	u_short len = 0, sublen = 0;
2318
2319	if (!d) {
2320		splx (s);
2321		return;
2322	}
2323
2324	CX_DEBUG2 (d, ("cx_oproc\n"));
2325	if (tp->t_cflag & CRTSCTS && (tp->t_state & TS_TBLOCK) && d->chan->rts)
2326		cx_set_rts (d->chan, 0);
2327	else if (tp->t_cflag & CRTSCTS && ! (tp->t_state & TS_TBLOCK) && ! d->chan->rts)
2328		cx_set_rts (d->chan, 1);
2329
2330	if (! (tp->t_state & (TS_TIMEOUT | TS_TTSTOP))) {
2331		/* Start transmitter. */
2332		cx_enable_transmit (d->chan, 1);
2333
2334		/* Is it busy? */
2335		if (! cx_buf_free (d->chan)) {
2336			tp->t_state |= TS_BUSY;
2337			splx (s);
2338			return;
2339		}
2340		if (tp->t_iflag & IXOFF) {
2341			p = (buf + (DMABUFSZ/2));
2342			sublen = q_to_b (&tp->t_outq, p, (DMABUFSZ/2));
2343			k = sublen;
2344			while (k--) {
2345				/* Send XON/XOFF out of band. */
2346				if (*p == tp->t_cc[VSTOP]) {
2347					cx_xflow_ctl (d->chan, 0);
2348					p++;
2349					continue;
2350				}
2351				if (*p == tp->t_cc[VSTART]) {
2352					cx_xflow_ctl (d->chan, 1);
2353					p++;
2354					continue;
2355				}
2356				buf[len] = *p;
2357				len++;
2358				p++;
2359			}
2360		} else {
2361			p = buf;
2362			len = q_to_b (&tp->t_outq, p, (DMABUFSZ/2));
2363		}
2364		if (len) {
2365			cx_send_packet (d->chan, buf, len, 0);
2366			tp->t_state |= TS_BUSY;
2367			d->atimeout = 10;
2368			CX_DEBUG2 (d, ("out %d bytes\n", len));
2369		}
2370	}
2371	ttwwakeup (tp);
2372	splx (s);
2373}
2374
2375static int cx_param (struct tty *tp, struct termios *t)
2376{
2377	drv_t *d = channel [UNIT (tp->t_dev)];
2378	int s, bits, parity;
2379
2380	if (!d)
2381		return EINVAL;
2382
2383	s = splhigh ();
2384	if (t->c_ospeed == 0) {
2385		/* Clear DTR and RTS. */
2386		cx_set_dtr (d->chan, 0);
2387		splx (s);
2388		CX_DEBUG2 (d, ("cx_param (hangup)\n"));
2389		return 0;
2390	}
2391	CX_DEBUG2 (d, ("cx_param\n"));
2392
2393	/* Check requested parameters. */
2394	if (t->c_ospeed < 300 || t->c_ospeed > 256*1024) {
2395		splx (s);
2396                return EINVAL;
2397	}
2398	if (t->c_ispeed && (t->c_ispeed < 300 || t->c_ispeed > 256*1024)) {
2399		splx (s);
2400                return EINVAL;
2401	}
2402
2403  	/* And copy them to tty and channel structures. */
2404	tp->t_ispeed = t->c_ispeed = tp->t_ospeed = t->c_ospeed;
2405	tp->t_cflag = t->c_cflag;
2406
2407	/* Set character length and parity mode. */
2408	switch (t->c_cflag & CSIZE) {
2409	default:
2410	case CS8: bits = 8; break;
2411	case CS7: bits = 7; break;
2412	case CS6: bits = 6; break;
2413	case CS5: bits = 5; break;
2414	}
2415
2416	parity = ((t->c_cflag & PARENB) ? 1 : 0) *
2417		 (1 + ((t->c_cflag & PARODD) ? 0 : 1));
2418
2419	/* Set current channel number. */
2420	if (! d->chan->dtr)
2421		cx_set_dtr (d->chan, 1);
2422
2423	disc_optim (&d->tty, &d->tty.t_termios);
2424	cx_set_async_param (d->chan, t->c_ospeed, bits, parity, (t->c_cflag & CSTOPB),
2425		!(t->c_cflag & PARENB), (t->c_cflag & CRTSCTS),
2426		(t->c_iflag & IXON), (t->c_iflag & IXANY),
2427		t->c_cc[VSTART], t->c_cc[VSTOP]);
2428	splx (s);
2429	return 0;
2430}
2431
2432#if __FreeBSD_version < 400000
2433static struct tty *cx_devtotty (dev_t dev)
2434{
2435	int unit = UNIT (dev);
2436
2437	if (unit == UNIT_CTL || unit >= NCX*NCHAN || ! channel[unit])
2438		return 0;
2439	return &channel[unit]->tty;
2440}
2441#endif
2442
2443/*
2444 * Stop output on a line
2445 */
2446static void cx_stop (struct tty *tp, int flag)
2447{
2448	drv_t *d = channel [UNIT (tp->t_dev)];
2449	int s;
2450
2451	if (!d)
2452		return;
2453
2454	s = splhigh ();
2455
2456	if (tp->t_state & TS_BUSY) {
2457		/* Stop transmitter */
2458		CX_DEBUG2 (d, ("cx_stop\n"));
2459		cx_transmitter_ctl (d->chan, 0);
2460	}
2461	splx (s);
2462}
2463
2464/*
2465 * Process the (delayed) carrier signal setup.
2466 */
2467static void cx_carrier (void *arg)
2468{
2469	drv_t *d = arg;
2470	cx_chan_t *c = d->chan;
2471	int s, cd;
2472
2473	s = splhigh ();
2474	cd = cx_get_cd (c);
2475	if (d->cd != cd) {
2476		if (cd) {
2477			CX_DEBUG (d, ("carrier on\n"));
2478			d->cd = 1;
2479			splx (s);
2480			(*linesw[d->tty.t_line].l_modem) (&d->tty, 1);
2481		} else {
2482			CX_DEBUG (d, ("carrier loss\n"));
2483			d->cd = 0;
2484			splx (s);
2485			(*linesw[d->tty.t_line].l_modem) (&d->tty, 0);
2486		}
2487	}
2488}
2489
2490/*
2491 * Modem signal callback function.
2492 */
2493static void cx_modem (cx_chan_t *c)
2494{
2495	drv_t *d = c->sys;
2496
2497	if (!d || c->mode != M_ASYNC)
2498		return;
2499	/* Handle carrier detect/loss. */
2500	untimeout (cx_carrier, c, d->dcd_timeout_handle);
2501	/* Carrier changed - delay processing DCD for a while
2502	 * to give both sides some time to initialize. */
2503	d->dcd_timeout_handle = timeout (cx_carrier, d, hz/2);
2504}
2505
2506#if __FreeBSD_version < 400000
2507struct isa_driver cxdriver = { cx_probe, cx_attach, "cx" };
2508static struct cdevsw cx_cdevsw = {
2509	cx_open,	cx_close,	cx_read,	cx_write,
2510	cx_ioctl,	cx_stop,	noreset,	cx_devtotty,
2511	ttpoll,		nommap,		NULL,		"cx",
2512	NULL,		-1,
2513};
2514#elif  __FreeBSD_version < 500000
2515static struct cdevsw cx_cdevsw = {
2516	cx_open,	cx_close,	cx_read,	cx_write,
2517	cx_ioctl,	ttypoll,	nommap,		nostrategy,
2518	"cx",		CDEV_MAJOR,	nodump,		nopsize,
2519	D_TTY,		-1
2520};
2521#elif __FreeBSD_version == 500000
2522static struct cdevsw cx_cdevsw = {
2523	cx_open,	cx_close,	cx_read,	cx_write,
2524	cx_ioctl,	ttypoll,	nommap,		nostrategy,
2525	"cx",		CDEV_MAJOR,	nodump,		nopsize,
2526	D_TTY,
2527	};
2528#elif __FreeBSD_version <= 501000
2529static struct cdevsw cx_cdevsw = {
2530	.d_open     = cx_open,
2531	.d_close    = cx_close,
2532	.d_read     = cx_read,
2533	.d_write    = cx_write,
2534	.d_ioctl    = cx_ioctl,
2535	.d_poll     = ttypoll,
2536	.d_mmap	    = nommap,
2537	.d_strategy = nostrategy,
2538	.d_name     = "cx",
2539	.d_maj      = CDEV_MAJOR,
2540	.d_dump     = nodump,
2541	.d_flags    = D_TTY,
2542};
2543#else /* __FreeBSD_version > 501000 */
2544static struct cdevsw cx_cdevsw = {
2545	.d_open     = cx_open,
2546	.d_close    = cx_close,
2547	.d_read     = cx_read,
2548	.d_write    = cx_write,
2549	.d_ioctl    = cx_ioctl,
2550	.d_poll     = ttypoll,
2551	.d_name     = "cx",
2552	.d_maj      = CDEV_MAJOR,
2553	.d_flags    = D_TTY,
2554};
2555#endif
2556
2557#ifdef NETGRAPH
2558#if __FreeBSD_version >= 500000
2559static int ng_cx_constructor (node_p node)
2560{
2561	drv_t *d = NG_NODE_PRIVATE (node);
2562#else
2563static int ng_cx_constructor (node_p *node)
2564{
2565	drv_t *d = (*node)->private;
2566#endif
2567	CX_DEBUG (d, ("Constructor\n"));
2568	return EINVAL;
2569}
2570
2571static int ng_cx_newhook (node_p node, hook_p hook, const char *name)
2572{
2573	int s;
2574#if __FreeBSD_version >= 500000
2575	drv_t *d = NG_NODE_PRIVATE (node);
2576#else
2577	drv_t *d = node->private;
2578#endif
2579
2580	if (d->chan->mode == M_ASYNC)
2581		return EINVAL;
2582
2583	/* Attach debug hook */
2584	if (strcmp (name, NG_CX_HOOK_DEBUG) == 0) {
2585#if __FreeBSD_version >= 500000
2586		NG_HOOK_SET_PRIVATE (hook, NULL);
2587#else
2588		hook->private = 0;
2589#endif
2590		d->debug_hook = hook;
2591		return 0;
2592	}
2593
2594	/* Check for raw hook */
2595	if (strcmp (name, NG_CX_HOOK_RAW) != 0)
2596		return EINVAL;
2597
2598#if __FreeBSD_version >= 500000
2599	NG_HOOK_SET_PRIVATE (hook, d);
2600#else
2601	hook->private = d;
2602#endif
2603	d->hook = hook;
2604	s = splhigh ();
2605	cx_up (d);
2606	splx (s);
2607	return 0;
2608}
2609
2610static int print_modems (char *s, cx_chan_t *c, int need_header)
2611{
2612	int status = cx_modem_status (c->sys);
2613	int length = 0;
2614
2615	if (need_header)
2616		length += sprintf (s + length, "  LE   DTR  DSR  RTS  CTS  CD\n");
2617	length += sprintf (s + length, "%4s %4s %4s %4s %4s %4s\n",
2618		status & TIOCM_LE  ? "On" : "-",
2619		status & TIOCM_DTR ? "On" : "-",
2620		status & TIOCM_DSR ? "On" : "-",
2621		status & TIOCM_RTS ? "On" : "-",
2622		status & TIOCM_CTS ? "On" : "-",
2623		status & TIOCM_CD  ? "On" : "-");
2624	return length;
2625}
2626
2627static int print_stats (char *s, cx_chan_t *c, int need_header)
2628{
2629	int length = 0;
2630
2631	if (need_header)
2632		length += sprintf (s + length, "  Rintr   Tintr   Mintr   Ibytes   Ipkts   Ierrs   Obytes   Opkts   Oerrs\n");
2633	length += sprintf (s + length, "%7ld %7ld %7ld %8ld %7ld %7ld %8ld %7ld %7ld\n",
2634		c->rintr, c->tintr, c->mintr, c->ibytes, c->ipkts,
2635		c->ierrs, c->obytes, c->opkts, c->oerrs);
2636	return length;
2637}
2638
2639static int print_chan (char *s, cx_chan_t *c)
2640{
2641	drv_t *d = c->sys;
2642	int length = 0;
2643
2644	length += sprintf (s + length, "cx%d", c->board->num * NCHAN + c->num);
2645	if (d->chan->debug)
2646		length += sprintf (s + length, " debug=%d", d->chan->debug);
2647
2648	if (cx_get_baud (c))
2649		length += sprintf (s + length, " %ld", cx_get_baud (c));
2650	else
2651		length += sprintf (s + length, " extclock");
2652
2653	if (c->mode == M_HDLC) {
2654		length += sprintf (s + length, " dpll=%s", cx_get_dpll (c) ? "on" : "off");
2655		length += sprintf (s + length, " nrzi=%s", cx_get_nrzi (c) ? "on" : "off");
2656	}
2657
2658	length += sprintf (s + length, " loop=%s", cx_get_loop (c) ? "on\n" : "off\n");
2659	return length;
2660}
2661
2662#if __FreeBSD_version >= 500000
2663static int ng_cx_rcvmsg (node_p node, item_p item, hook_p lasthook)
2664{
2665	drv_t *d = NG_NODE_PRIVATE (node);
2666	struct ng_mesg *msg;
2667#else
2668static int ng_cx_rcvmsg (node_p node, struct ng_mesg *msg,
2669	const char *retaddr, struct ng_mesg **rptr)
2670{
2671	drv_t *d = node->private;
2672#endif
2673	struct ng_mesg *resp = NULL;
2674	int error = 0;
2675
2676	if (!d)
2677		return EINVAL;
2678
2679	CX_DEBUG (d, ("Rcvmsg\n"));
2680#if __FreeBSD_version >= 500000
2681	NGI_GET_MSG (item, msg);
2682#endif
2683	switch (msg->header.typecookie) {
2684	default:
2685		error = EINVAL;
2686		break;
2687
2688	case NGM_CX_COOKIE:
2689		printf ("Don't forget to implement\n");
2690		error = EINVAL;
2691		break;
2692
2693	case NGM_GENERIC_COOKIE:
2694		switch (msg->header.cmd) {
2695		default:
2696			error = EINVAL;
2697			break;
2698
2699		case NGM_TEXT_STATUS: {
2700			char *s;
2701			int l = 0;
2702			int dl = sizeof (struct ng_mesg) + 730;
2703
2704#if __FreeBSD_version >= 500000
2705			NG_MKRESPONSE (resp, msg, dl, M_NOWAIT);
2706			if (! resp) {
2707				error = ENOMEM;
2708				break;
2709			}
2710#else
2711			MALLOC (resp, struct ng_mesg *, dl,
2712				M_NETGRAPH, M_NOWAIT);
2713			if (! resp) {
2714				error = ENOMEM;
2715				break;
2716			}
2717#endif
2718			bzero (resp, dl);
2719			s = (resp)->data;
2720			l += print_chan (s + l, d->chan);
2721			l += print_stats (s + l, d->chan, 1);
2722			l += print_modems (s + l, d->chan, 1);
2723#if __FreeBSD_version < 500000
2724			(resp)->header.version = NG_VERSION;
2725			(resp)->header.arglen = strlen (s) + 1;
2726			(resp)->header.token = msg->header.token;
2727			(resp)->header.typecookie = NGM_CX_COOKIE;
2728			(resp)->header.cmd = msg->header.cmd;
2729#endif
2730			strncpy ((resp)->header.cmdstr, "status", NG_CMDSTRLEN);
2731			}
2732			break;
2733		}
2734		break;
2735	}
2736#if __FreeBSD_version >= 500000
2737	NG_RESPOND_MSG (error, node, item, resp);
2738	NG_FREE_MSG (msg);
2739#else
2740	*rptr = resp;
2741	FREE (msg, M_NETGRAPH);
2742#endif
2743	return error;
2744}
2745
2746#if __FreeBSD_version >= 500000
2747static int ng_cx_rcvdata (hook_p hook, item_p item)
2748{
2749	drv_t *d = NG_NODE_PRIVATE (NG_HOOK_NODE(hook));
2750	struct mbuf *m;
2751	meta_p meta;
2752#else
2753static int ng_cx_rcvdata (hook_p hook, struct mbuf *m, meta_p meta)
2754{
2755	drv_t *d = hook->node->private;
2756#endif
2757	struct ifqueue *q;
2758	int s;
2759
2760#if __FreeBSD_version >= 500000
2761	NGI_GET_M (item, m);
2762	NGI_GET_META (item, meta);
2763	NG_FREE_ITEM (item);
2764	if (! NG_HOOK_PRIVATE (hook) || ! d) {
2765		NG_FREE_M (m);
2766		NG_FREE_META (meta);
2767#else
2768	if (! hook->private || ! d) {
2769		NG_FREE_DATA (m,meta);
2770#endif
2771		return ENETDOWN;
2772	}
2773	q = (meta && meta->priority > 0) ? &d->hi_queue : &d->lo_queue;
2774	s = splhigh ();
2775#if __FreeBSD_version >= 500000
2776	IF_LOCK (q);
2777	if (_IF_QFULL (q)) {
2778		_IF_DROP (q);
2779		IF_UNLOCK (q);
2780		splx (s);
2781		NG_FREE_M (m);
2782		NG_FREE_META (meta);
2783		return ENOBUFS;
2784	}
2785	_IF_ENQUEUE (q, m);
2786	IF_UNLOCK (q);
2787#else
2788	if (IF_QFULL (q)) {
2789		IF_DROP (q);
2790		splx (s);
2791		NG_FREE_DATA (m, meta);
2792		return ENOBUFS;
2793	}
2794	IF_ENQUEUE (q, m);
2795#endif
2796	cx_start (d);
2797	splx (s);
2798	return 0;
2799}
2800
2801static int ng_cx_rmnode (node_p node)
2802{
2803#if __FreeBSD_version >= 500000
2804	drv_t *d = NG_NODE_PRIVATE (node);
2805
2806	CX_DEBUG (d, ("Rmnode\n"));
2807	if (d && d->running) {
2808		int s = splhigh ();
2809		cx_down (d);
2810		splx (s);
2811	}
2812#ifdef	KLD_MODULE
2813	if (node->nd_flags & NG_REALLY_DIE) {
2814		NG_NODE_SET_PRIVATE (node, NULL);
2815		NG_NODE_UNREF (node);
2816	}
2817	node->nd_flags &= ~NG_INVALID;
2818#endif
2819#else /* __FreeBSD_version < 500000 */
2820	drv_t *d = node->private;
2821	int s;
2822
2823	s = splhigh ();
2824	cx_down (d);
2825	splx (s);
2826	node->flags |= NG_INVALID;
2827	ng_cutlinks (node);
2828#ifdef	KLD_MODULE
2829	ng_unname (node);
2830	ng_unref (node);
2831#else
2832	node->flags &= ~NG_INVALID;
2833#endif
2834#endif
2835	return 0;
2836}
2837
2838static void ng_cx_watchdog (void *arg)
2839{
2840	drv_t *d = arg;
2841
2842	if (d->timeout == 1)
2843		cx_watchdog (d);
2844	if (d->timeout)
2845		d->timeout--;
2846	d->timeout_handle = timeout (ng_cx_watchdog, d, hz);
2847}
2848
2849static int ng_cx_connect (hook_p hook)
2850{
2851#if __FreeBSD_version >= 500000
2852	drv_t *d = NG_NODE_PRIVATE (NG_HOOK_NODE (hook));
2853#else
2854	drv_t *d = hook->node->private;
2855#endif
2856
2857	d->timeout_handle = timeout (ng_cx_watchdog, d, hz);
2858	return 0;
2859}
2860
2861static int ng_cx_disconnect (hook_p hook)
2862{
2863#if __FreeBSD_version >= 500000
2864	drv_t *d = NG_NODE_PRIVATE (NG_HOOK_NODE (hook));
2865#else
2866	drv_t *d = hook->node->private;
2867#endif
2868	int s;
2869
2870	s = splhigh ();
2871#if __FreeBSD_version >= 500000
2872	if (NG_HOOK_PRIVATE (hook))
2873#else
2874	if (hook->private)
2875#endif
2876		cx_down (d);
2877	splx (s);
2878	untimeout (ng_cx_watchdog, d, d->timeout_handle);
2879	return 0;
2880}
2881#endif /*NETGRAPH*/
2882
2883#ifdef KLD_MODULE
2884#if __FreeBSD_version < 400000
2885/*
2886 * Function called when loading the driver.
2887 */
2888static int cx_load (void)
2889{
2890	int i;
2891
2892	for (i=0;i<NCX; ++i) {
2893		struct isa_device id = {-1, &cxdriver, -1, 0, -1, 0, 0, (inthand2_t *)cx_intr, i, 0, 0, 0, 0 ,0 ,1 ,0 ,0};
2894
2895		disable_intr();
2896		if (!cx_probe (&id)) {
2897			enable_intr();
2898			break;
2899		}
2900		cx_attach (&id);
2901		register_intr ((adapter [i])->irq, 0, 0, (inthand2_t*) cx_intr,
2902				&net_imask, id.id_unit);
2903		enable_intr();
2904	}
2905	if (!i) {
2906		/* Deactivate the timeout routine. And soft interrupt*/
2907		untimeout (cx_timeout, 0, timeout_handle);
2908#if __FreeBSD_version >= 500000
2909		ithread_remove_handler (cx_fast_ih);
2910		ithread_remove_handler (cx_slow_ih);
2911#else
2912		unregister_swi (SWI_TTY, cx_softintr);
2913#endif
2914		return ENXIO;
2915	}
2916	return 0;
2917}
2918
2919/*
2920 * Function called when unloading the driver.
2921 */
2922static int cx_unload (void)
2923{
2924	int i, s;
2925
2926	/* Check if the device is busy (open). */
2927	for (i=0; i<NCX*NCHAN; ++i) {
2928		drv_t *d = channel[i];
2929		cx_chan_t *c;
2930
2931		if (!d || (c=d->chan)->type == T_NONE)
2932			continue;
2933		if (d->lock)
2934			return EBUSY;
2935		if (c->mode == M_ASYNC && (d->tty.t_state & TS_ISOPEN) &&
2936			(d->open_dev|0x2))
2937				return EBUSY;
2938		if (d->running)
2939				return EBUSY;
2940
2941	}
2942
2943	s = splhigh ();
2944
2945	/* Deactivate the timeout routine. And soft interrupt*/
2946	untimeout (cx_timeout, 0, timeout_handle);
2947	unregister_swi (SWI_TTY, cx_softintr);
2948
2949	for (i=0; i<NCX*NCHAN; ++i) {
2950		drv_t *d = channel[i];
2951		cx_chan_t *c;
2952
2953		if (!d || (c=d->chan)->type == T_NONE)
2954			continue;
2955
2956		if (d->dtr_timeout_handle.callout)
2957			untimeout (cx_dtrwakeup, d, d->dtr_timeout_handle);
2958		if (d->dcd_timeout_handle.callout)
2959			untimeout (cx_carrier, c, d->dcd_timeout_handle);
2960	}
2961
2962	/* Close all active boards. */
2963	for (i=0; i<NCX; ++i) {
2964		cx_board_t *b = adapter [i];
2965
2966		if (!b || ! b->port)
2967			continue;
2968
2969		cx_close_board (b);
2970	}
2971
2972	for (i=0; i<NCX; ++i) {
2973		cx_board_t *b = adapter [i];
2974
2975		if (!b || ! b->port)
2976			continue;
2977
2978		if (led_timo[i].callout)
2979			untimeout (cx_led_off, b, led_timo[i]);
2980	}
2981
2982	/* OK to unload the driver, unregister the interrupt first. */
2983	for (i=0; i<NCX; ++i) {
2984		cx_board_t *b = adapter [i];
2985
2986		if (!b || ! b->port)
2987			continue;
2988		/* Disable the interrupt request. */
2989		disable_intr();
2990		unregister_intr (b->irq, (inthand2_t *)cx_intr);
2991		isa_dma_release (b->dma);
2992		enable_intr();
2993	}
2994	splx (s);
2995
2996	s = splhigh ();
2997	/* Detach the interfaces, free buffer memory. */
2998	for (i=0; i<NCX*NCHAN; ++i) {
2999		drv_t *d = channel[i];
3000		cx_chan_t *c;
3001
3002		if (!d || (c=d->chan)->type == T_NONE)
3003			continue;
3004
3005#ifndef NETGRAPH
3006#if NBPFILTER > 0
3007		/* Detach from the packet filter list of interfaces. */
3008		{
3009			struct bpf_if *q, **b = &bpf_iflist;
3010
3011			while ((q = *b)) {
3012				if (q->bif_ifp == d->pp.pp_if) {
3013					*b = q->bif_next;
3014					free (q, M_DEVBUF);
3015				}
3016				b = &(q->bif_next);
3017			}
3018		}
3019#endif /* NBPFILTER */
3020		/* Detach from the sync PPP list. */
3021		sppp_detach (&d->pp.pp_if);
3022
3023		/* Detach from the system list of interfaces. */
3024		{
3025			struct ifaddr *ifa;
3026			TAILQ_FOREACH (ifa, &d->pp.pp_if.if_addrhead, ifa_link) {
3027				TAILQ_REMOVE (&d->pp.pp_if.if_addrhead, ifa, ifa_link);
3028				free (ifa, M_IFADDR);
3029			}
3030			TAILQ_REMOVE (&ifnet, &d->pp.pp_if, if_link);
3031		}
3032#endif /* !NETGRAPH */
3033		/* Deallocate buffers. */
3034/*		free (d, M_DEVBUF);*/
3035	}
3036
3037	for (i=0; i<NCX; ++i) {
3038		cx_board_t *b = adapter [i];
3039		adapter [b->num] = 0;
3040		free (b, M_DEVBUF);
3041	}
3042
3043	splx (s);
3044
3045	return 0;
3046}
3047
3048#define devsw(a)	cdevsw[major((a))]
3049#endif /* __FreeBSD_version < 400000 */
3050#endif /* KLD_MODULE */
3051
3052#if __FreeBSD_version < 400000
3053#ifdef KLD_MODULE
3054static int cx_modevent (module_t mod, int type, void *unused)
3055{
3056        dev_t dev;
3057	int result;
3058	static int load_count = 0;
3059
3060	dev = makedev (CDEV_MAJOR, 0);
3061	switch (type) {
3062	case MOD_LOAD:
3063		if (devsw(dev))
3064			return (ENXIO);
3065		load_count ++;
3066		cdevsw_add (&dev, &cx_cdevsw, NULL);
3067 		timeout_handle = timeout (cx_timeout, 0, hz*5);
3068
3069		/* Software interrupt. */
3070		register_swi (SWI_TTY, cx_softintr);
3071
3072		result = cx_load ();
3073 		return result;
3074	case MOD_UNLOAD:
3075		result = cx_unload ();
3076		if (result)
3077			return result;
3078		if (devsw(dev)&&!(load_count-1)) {
3079		cdevsw_add (&dev, NULL, NULL);
3080		}
3081		load_count --;
3082		return result;
3083	case MOD_SHUTDOWN:
3084		break;
3085	}
3086	return 0;
3087}
3088#endif /* KLD_MODULE */
3089#else /* __FreeBSD_version >= 400000 */
3090static int cx_modevent (module_t mod, int type, void *unused)
3091{
3092        dev_t dev;
3093	static int load_count = 0;
3094	struct cdevsw *cdsw;
3095
3096	dev = makedev (CDEV_MAJOR, 0);
3097	switch (type) {
3098	case MOD_LOAD:
3099		if ((cdsw = devsw (dev)) && cdsw->d_maj == CDEV_MAJOR) {
3100			printf ("Sigma driver is already in system\n");
3101			return (EEXIST);
3102		}
3103#if __FreeBSD_version >= 500000 && defined NETGRAPH
3104		if (ng_newtype (&typestruct))
3105			printf ("Failed to register ng_cx\n");
3106#endif
3107		++load_count;
3108#if __FreeBSD_version <= 500000
3109		cdevsw_add (&cx_cdevsw);
3110#endif
3111		timeout_handle = timeout (cx_timeout, 0, hz*5);
3112		/* Software interrupt. */
3113#if __FreeBSD_version < 500000
3114		register_swi (SWI_TTY, cx_softintr);
3115#else
3116		swi_add(&tty_ithd, "tty:cx", cx_softintr, NULL, SWI_TTY, 0,
3117		    &cx_fast_ih);
3118		swi_add(&clk_ithd, "tty:cx", cx_softintr, NULL, SWI_TTY, 0,
3119		    &cx_slow_ih);
3120#endif
3121		break;
3122	case MOD_UNLOAD:
3123		if (load_count == 1) {
3124			printf ("Removing device entry for Sigma\n");
3125#if __FreeBSD_version <= 500000
3126			cdevsw_remove (&cx_cdevsw);
3127#endif
3128#if __FreeBSD_version >= 500000 && defined NETGRAPH
3129			ng_rmtype (&typestruct);
3130#endif
3131		}
3132		if (timeout_handle.callout)
3133			untimeout (cx_timeout, 0, timeout_handle);
3134#if __FreeBSD_version >= 500000
3135		ithread_remove_handler (cx_fast_ih);
3136		ithread_remove_handler (cx_slow_ih);
3137#else
3138		unregister_swi (SWI_TTY, cx_softintr);
3139#endif
3140		--load_count;
3141		break;
3142	case MOD_SHUTDOWN:
3143		break;
3144	}
3145	return 0;
3146}
3147#endif  /* __FreeBSD_version >= 400000 */
3148
3149#ifdef NETGRAPH
3150static struct ng_type typestruct = {
3151#if __FreeBSD_version >= 500000
3152	NG_ABI_VERSION,
3153#else
3154	NG_VERSION,
3155#endif
3156	NG_CX_NODE_TYPE,
3157#if __FreeBSD_version < 500000 && defined KLD_MODULE
3158	cx_modevent,
3159#else
3160	NULL,
3161#endif
3162	ng_cx_constructor,
3163	ng_cx_rcvmsg,
3164	ng_cx_rmnode,
3165	ng_cx_newhook,
3166	NULL,
3167	ng_cx_connect,
3168	ng_cx_rcvdata,
3169#if __FreeBSD_version < 500000
3170	NULL,
3171#endif
3172	ng_cx_disconnect
3173};
3174
3175#if __FreeBSD_version < 400000
3176NETGRAPH_INIT_ORDERED (cx, &typestruct, SI_SUB_DRIVERS,\
3177	SI_ORDER_MIDDLE + CDEV_MAJOR);
3178#endif
3179#endif /*NETGRAPH*/
3180
3181#if __FreeBSD_version >= 500000
3182#ifdef NETGRAPH
3183MODULE_DEPEND (ng_cx, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
3184#else
3185MODULE_DEPEND (isa_cx, sppp, 1, 1, 1);
3186#endif
3187#ifdef KLD_MODULE
3188DRIVER_MODULE (cxmod, isa, cx_isa_driver, cx_devclass, cx_modevent, NULL);
3189#else
3190DRIVER_MODULE (cx, isa, cx_isa_driver, cx_devclass, cx_modevent, NULL);
3191#endif
3192#elif __FreeBSD_version >= 400000
3193#ifdef NETGRAPH
3194DRIVER_MODULE(cx, isa, cx_isa_driver, cx_devclass, ng_mod_event, &typestruct);
3195#else
3196DRIVER_MODULE(cx, isa, cx_isa_driver, cx_devclass, cx_modevent, 0);
3197#endif
3198#else /* __FreeBSD_version < 400000 */
3199#ifdef KLD_MODULE
3200#ifndef NETGRAPH
3201static moduledata_t cxmod = { "cx", cx_modevent, NULL};
3202DECLARE_MODULE (cx, cxmod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE + CDEV_MAJOR);
3203#endif
3204#else /* KLD_MODULE */
3205
3206/*
3207 * Now for some driver initialisation.
3208 * Occurs ONCE during boot (very early).
3209 * This is if we are NOT a loadable module.
3210 */
3211static void cx_drvinit (void *unused)
3212{
3213#if __FreeBSD_version < 400000
3214        dev_t dev;
3215
3216	dev = makedev (CDEV_MAJOR, 0);
3217	cdevsw_add (&dev, &cx_cdevsw, NULL);
3218#else
3219	cdevsw_add (&cx_cdevsw);
3220#endif
3221
3222	/* Activate the timeout routine. */
3223	timeout_handle = timeout (cx_timeout, 0, hz*5);
3224
3225	/* Software interrupt. */
3226	register_swi (SWI_TTY, cx_softintr);
3227#ifdef NETGRAPH
3228#if 0
3229	/* Register our node type in netgraph */
3230	if (ng_newtype (&typestruct))
3231		printf ("Failed to register ng_cx\n");
3232#endif
3233#endif
3234}
3235
3236SYSINIT (cxdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE+CDEV_MAJOR, cx_drvinit, 0)
3237
3238#endif /* KLD_MODULE */
3239#endif /*  __FreeBSD_version < 400000 */
3240#endif /* NCX */
3241