if_ct.c revision 134412
1105665Srwatson/*
2126256Srwatson * Cronyx-Tau adapter driver for FreeBSD.
3126256Srwatson * Supports PPP/HDLC and Cisco/HDLC protocol in synchronous mode,
4105665Srwatson * and asyncronous channels with full modem control.
5105665Srwatson * Keepalive protocol implemented in both Cisco and PPP modes.
6105665Srwatson *
7105665Srwatson * Copyright (C) 1994-2002 Cronyx Engineering.
8105665Srwatson * Author: Serge Vakulenko, <vak@cronyx.ru>
9105665Srwatson *
10105665Srwatson * Copyright (C) 1999-2004 Cronyx Engineering.
11105665Srwatson * Author: Roman Kurakin, <rik@cronyx.ru>
12105665Srwatson *
13105665Srwatson * This software is distributed with NO WARRANTIES, not even the implied
14105665Srwatson * warranties for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15105665Srwatson *
16105665Srwatson * Authors grant any other persons or organisations a permission to use,
17105665Srwatson * modify and redistribute this software in source and binary forms,
18105665Srwatson * as long as this message is kept with the software, all derivative
19105665Srwatson * works or modified versions.
20105665Srwatson *
21105665Srwatson * Cronyx Id: if_ct.c,v 1.1.2.31 2004/06/23 17:09:13 rik Exp $
22105665Srwatson */
23105665Srwatson
24105665Srwatson#include <sys/cdefs.h>
25105665Srwatson__FBSDID("$FreeBSD: head/sys/dev/ctau/if_ct.c 134412 2004-08-27 22:14:26Z rik $");
26105665Srwatson
27105665Srwatson#include <sys/param.h>
28105665Srwatson
29105665Srwatson#if __FreeBSD_version >= 500000
30105665Srwatson#   define NCTAU 1
31105665Srwatson#else
32105665Srwatson#   include "ctau.h"
33105665Srwatson#endif
34105665Srwatson
35105665Srwatson#if NCTAU > 0
36285873Strasz#include <sys/proc.h>
37107780Sru#include <sys/systm.h>
38105665Srwatson#include <sys/kernel.h>
39105665Srwatson#include <sys/module.h>
40105665Srwatson#include <sys/mbuf.h>
41105665Srwatson#include <sys/sockio.h>
42105665Srwatson#include <sys/malloc.h>
43105665Srwatson#include <sys/socket.h>
44105665Srwatson#include <sys/conf.h>
45105665Srwatson#include <sys/errno.h>
46105665Srwatson#include <sys/tty.h>
47105665Srwatson#include <sys/bus.h>
48105665Srwatson#include <machine/bus.h>
49105665Srwatson#include <sys/rman.h>
50105665Srwatson#include <isa/isavar.h>
51107780Sru#include <sys/interrupt.h>
52107780Sru#include <vm/vm.h>
53107780Sru#include <vm/pmap.h>
54105665Srwatson#include <net/if.h>
55105665Srwatson#include <machine/cpufunc.h>
56105665Srwatson#include <machine/cserial.h>
57105665Srwatson#include <machine/clock.h>
58105665Srwatson#if __FreeBSD_version < 500000
59105665Srwatson#   include <i386/isa/isa_device.h>
60105665Srwatson#endif
61105665Srwatson#include <machine/resource.h>
62105665Srwatson#if __FreeBSD_version <= 501000
63105665Srwatson#   include <i386/isa/intr_machdep.h>
64105665Srwatson#endif
65107780Sru#include <dev/cx/machdep.h>
66105665Srwatson#include <dev/ctau/ctddk.h>
67105665Srwatson#include <dev/cx/cronyxfw.h>
68107780Sru#include "opt_ng_cronyx.h"
69105665Srwatson#ifdef NETGRAPH_CRONYX
70107780Sru#   include "opt_netgraph.h"
71107780Sru#   include <netgraph/ng_message.h>
72107780Sru#   include <netgraph/netgraph.h>
73105665Srwatson#   include <dev/ctau/ng_ct.h>
74105665Srwatson#else
75105665Srwatson#   include <net/if_types.h>
76105665Srwatson#   if __FreeBSD_version < 500000
77105665Srwatson#   include "sppp.h"
78105665Srwatson#   if NSPPP <= 0
79105665Srwatson#	error The device ctau requires sppp or netgraph.
80105665Srwatson#   endif
81105665Srwatson#   endif
82105665Srwatson#   include <net/if_sppp.h>
83105665Srwatson#   define PP_CISCO IFF_LINK2
84105665Srwatson#   if __FreeBSD_version < 500000
85105665Srwatson#	include <bpf.h>
86105665Srwatson#   endif
87105665Srwatson#   include <net/bpf.h>
88105665Srwatson#   define NBPFILTER NBPF
89105665Srwatson#endif
90105665Srwatson
91105665Srwatson/* If we don't have Cronyx's sppp version, we don't have fr support via sppp */
92105665Srwatson#ifndef PP_FR
93105665Srwatson#define PP_FR 0
94105665Srwatson#endif
95105665Srwatson
96105665Srwatson#define CT_DEBUG(d,s)	({if (d->chan->debug) {\
97105665Srwatson				printf ("%s: ", d->name); printf s;}})
98105665Srwatson#define CT_DEBUG2(d,s)	({if (d->chan->debug>1) {\
99105665Srwatson				printf ("%s: ", d->name); printf s;}})
100105665Srwatson#define CDEV_MAJOR	99
101105665Srwatson
102107780Srustatic void ct_identify		__P((driver_t *, device_t));
103107780Srustatic int ct_probe		__P((device_t));
104105665Srwatsonstatic int ct_attach		__P((device_t));
105105665Srwatsonstatic int ct_detach		__P((device_t));
106105665Srwatson
107105665Srwatsonstatic device_method_t ct_isa_methods [] = {
108105665Srwatson	DEVMETHOD(device_identify,	ct_identify),
109105665Srwatson	DEVMETHOD(device_probe,		ct_probe),
110105665Srwatson	DEVMETHOD(device_attach,	ct_attach),
111105665Srwatson	DEVMETHOD(device_detach,	ct_detach),
112105665Srwatson	{0, 0}
113105665Srwatson};
114105665Srwatson
115105665Srwatsontypedef struct _ct_dma_mem_t {
116105665Srwatson	unsigned long	phys;
117105665Srwatson	void		*virt;
118105665Srwatson	size_t		size;
119105665Srwatson#if __FreeBSD_version >= 500000
120105665Srwatson	bus_dma_tag_t	dmat;
121105665Srwatson	bus_dmamap_t	mapp;
122105665Srwatson#endif
123105665Srwatson} ct_dma_mem_t;
124105665Srwatson
125105665Srwatsontypedef struct _drv_t {
126105665Srwatson	char name [8];
127105665Srwatson	ct_chan_t *chan;
128105665Srwatson	ct_board_t *board;
129105665Srwatson	ct_dma_mem_t dmamem;
130105665Srwatson	int running;
131105665Srwatson#ifdef NETGRAPH
132105665Srwatson	char	nodename [NG_NODELEN+1];
133105665Srwatson	hook_p	hook;
134105665Srwatson	hook_p	debug_hook;
135105665Srwatson	node_p	node;
136105665Srwatson	struct	ifqueue queue;
137105665Srwatson	struct	ifqueue hi_queue;
138105665Srwatson	short	timeout;
139105665Srwatson	struct	callout_handle timeout_handle;
140105665Srwatson#else
141105665Srwatson	struct sppp pp;
142105665Srwatson#endif
143105665Srwatson	struct cdev *devt;
144105665Srwatson} drv_t;
145105665Srwatson
146107780Srutypedef struct _bdrv_t {
147160261Sjoel	ct_board_t	*board;
148107780Sru	struct resource	*base_res;
149105665Srwatson	struct resource	*drq_res;
150105665Srwatson	struct resource	*irq_res;
151105665Srwatson	int		base_rid;
152107780Sru	int		drq_rid;
153107795Schris	int		irq_rid;
154107795Schris	void		*intrhand;
155107795Schris	drv_t		channel [NCHAN];
156141355Sbrueffer} bdrv_t;
157107795Schris
158107795Schrisstatic driver_t ct_isa_driver = {
159107795Schris	"ct",
160107795Schris	ct_isa_methods,
161107795Schris	sizeof (bdrv_t),
162105665Srwatson};
163105665Srwatson
164105665Srwatsonstatic devclass_t ct_devclass;
165107780Sru
166108936Schrisstatic void ct_receive (ct_chan_t *c, char *data, int len);
167160247Sjoelstatic void ct_transmit (ct_chan_t *c, void *attachment, int len);
168202386Srustatic void ct_error (ct_chan_t *c, int data);
169108936Schrisstatic void ct_up (drv_t *d);
170140561Srustatic void ct_start (drv_t *d);
171140561Srustatic void ct_down (drv_t *d);
172140561Srustatic void ct_watchdog (drv_t *d);
173140561Sru#ifdef NETGRAPH
174140561Sruextern struct ng_type typestruct;
175105665Srwatson#else
176147647Shmpstatic void ct_ifstart (struct ifnet *ifp);
177105665Srwatsonstatic void ct_tlf (struct sppp *sp);
178105665Srwatsonstatic void ct_tls (struct sppp *sp);
179105665Srwatsonstatic void ct_ifwatchdog (struct ifnet *ifp);
180105665Srwatsonstatic int ct_sioctl (struct ifnet *ifp, u_long cmd, caddr_t data);
181131530Srustatic void ct_initialize (void *softc);
182107780Sru#endif
183107780Sru
184107780Srustatic ct_board_t *adapter [NCTAU];
185105665Srwatsonstatic drv_t *channel [NCTAU*NCHAN];
186105665Srwatsonstatic struct callout_handle led_timo [NCTAU];
187107780Srustatic struct callout_handle timeout_handle;
188107780Sru
189107780Sru/*
190105665Srwatson * Print the mbuf chain, for debug purposes only.
191105665Srwatson */
192108317Sschweikhstatic void printmbuf (struct mbuf *m)
193105665Srwatson{
194105665Srwatson	printf ("mbuf:");
195105665Srwatson	for (; m; m=m->m_next) {
196105665Srwatson		if (m->m_flags & M_PKTHDR)
197105665Srwatson			printf (" HDR %d:", m->m_pkthdr.len);
198126256Srwatson		if (m->m_flags & M_EXT)
199105665Srwatson			printf (" EXT:");
200105665Srwatson		printf (" %d", m->m_len);
201105665Srwatson	}
202105665Srwatson	printf ("\n");
203105665Srwatson}
204126256Srwatson
205105665Srwatson/*
206105665Srwatson * Make an mbuf from data.
207105665Srwatson */
208105665Srwatsonstatic struct mbuf *makembuf (void *buf, u_int len)
209105665Srwatson{
210105665Srwatson	struct mbuf *m;
211105665Srwatson
212105665Srwatson	MGETHDR (m, M_DONTWAIT, MT_DATA);
213105665Srwatson	if (! m)
214124963Sdes		return 0;
215105665Srwatson	MCLGET (m, M_DONTWAIT);
216105665Srwatson	if (! (m->m_flags & M_EXT)) {
217130582Sru		m_freem (m);
218105665Srwatson		return 0;
219105665Srwatson	}
220126256Srwatson	m->m_pkthdr.len = m->m_len = len;
221126256Srwatson	bcopy (buf, mtod (m, caddr_t), len);
222105665Srwatson	return m;
223126256Srwatson}
224105665Srwatson
225126256Srwatsonstatic void ct_timeout (void *arg)
226106419Srwatson{
227106419Srwatson	drv_t *d;
228107478Schris	int s, i;
229106419Srwatson
230106419Srwatson	for (i=0; i<NCTAU*NCHAN; ++i) {
231106419Srwatson		d = channel[i];
232		if (! d)
233			continue;
234		if (d->chan->mode != M_G703)
235			continue;
236		s = splimp ();
237		ct_g703_timer (d->chan);
238		splx (s);
239	}
240	timeout_handle = timeout (ct_timeout, 0, hz);
241}
242
243static void ct_led_off (void *arg)
244{
245	ct_board_t *b = arg;
246	int s = splimp ();
247
248	ct_led (b, 0);
249	led_timo[b->num].callout = 0;
250	splx (s);
251}
252
253/*
254 * Activate interupt handler from DDK.
255 */
256static void ct_intr (void *arg)
257{
258	bdrv_t *bd = arg;
259	ct_board_t *b = bd->board;
260	int s = splimp ();
261
262	/* Turn LED on. */
263	ct_led (b, 1);
264
265	ct_int_handler (b);
266
267	/* Turn LED off 50 msec later. */
268	if (! led_timo[b->num].callout)
269		led_timo[b->num] = timeout (ct_led_off, b, hz/20);
270	splx (s);
271}
272
273static int probe_irq (ct_board_t *b, int irq)
274{
275	int mask, busy, cnt;
276
277	/* Clear pending irq, if any. */
278	ct_probe_irq (b, -irq);
279	DELAY (100);
280	for (cnt=0; cnt<5; ++cnt) {
281		/* Get the mask of pending irqs, assuming they are busy.
282		 * Activate the adapter on given irq. */
283		busy = ct_probe_irq (b, irq);
284		DELAY (1000);
285
286		/* Get the mask of active irqs.
287		 * Deactivate our irq. */
288		mask = ct_probe_irq (b, -irq);
289		DELAY (100);
290		if ((mask & ~busy) == 1 << irq) {
291			ct_probe_irq (b, 0);
292			/* printf ("ct%d: irq %d ok, mask=0x%04x, busy=0x%04x\n",
293				b->num, irq, mask, busy); */
294			return 1;
295		}
296	}
297	/* printf ("ct%d: irq %d not functional, mask=0x%04x, busy=0x%04x\n",
298		b->num, irq, mask, busy); */
299	ct_probe_irq (b, 0);
300	return 0;
301}
302
303static	short porttab [] = {
304		0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0,
305		0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3c0, 0x3e0, 0
306	};
307static	char dmatab [] = { 7, 6, 5, 0 };
308static	char irqtab [] = { 5, 10, 11, 7, 3, 15, 12, 0 };
309
310static int ct_is_free_res (device_t dev, int rid, int type, u_long start,
311	u_long end, u_long count)
312{
313	struct resource *res;
314
315	if (!(res = bus_alloc_resource (dev, type, &rid, start, end, count,
316	    RF_ALLOCATED)))
317		return 0;
318
319	bus_release_resource (dev, type, rid, res);
320
321	return 1;
322}
323
324static void ct_identify (driver_t *driver, device_t dev)
325{
326	u_long iobase, rescount;
327	int devcount;
328	device_t *devices;
329	device_t child;
330	devclass_t my_devclass;
331	int i, k;
332
333	if ((my_devclass = devclass_find ("ct")) == NULL)
334		return;
335
336	devclass_get_devices (my_devclass, &devices, &devcount);
337
338	if (devcount == 0) {
339		/* We should find all devices by our self. We could alter other
340		 * devices, but we don't have a choise
341		 */
342		for (i = 0; (iobase = porttab [i]) != 0; i++) {
343			if (!ct_is_free_res (dev, 0, SYS_RES_IOPORT,
344			    iobase, iobase + NPORT, NPORT))
345				continue;
346			if (ct_probe_board (iobase, -1, -1) == 0)
347				continue;
348
349			devcount++;
350			child = BUS_ADD_CHILD (dev, ISA_ORDER_SPECULATIVE, "ct",
351			    -1);
352
353			if (child == NULL)
354				return;
355
356			device_set_desc_copy (child, "Cronyx Tau-ISA");
357			device_set_driver (child, driver);
358			bus_set_resource (child, SYS_RES_IOPORT, 0,
359			    iobase, NPORT);
360
361			if (devcount >= NCTAU)
362				break;
363		}
364	} else {
365		static	short porttab [] = {
366			0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0,
367			0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3c0, 0x3e0, 0
368		};
369		/* Lets check user choise.
370		 */
371		for (k = 0; k < devcount; k++) {
372			if (bus_get_resource (devices[k], SYS_RES_IOPORT, 0,
373			    &iobase, &rescount) != 0)
374				continue;
375
376			for (i = 0; porttab [i] != 0; i++) {
377				if (porttab [i] != iobase)
378					continue;
379
380				if (!ct_is_free_res (devices[k], 0, SYS_RES_IOPORT,
381				    iobase, iobase + NPORT, NPORT))
382					continue;
383
384				if (ct_probe_board (iobase, -1, -1) == 0)
385					continue;
386				porttab [i] = -1;
387				device_set_desc_copy (devices[k], "Cronyx Tau-ISA");
388				break;
389			}
390			if (porttab [i] == 0) {
391				device_delete_child (
392				    device_get_parent (devices[k]),
393				    devices [k]);
394				devices[k] = 0;
395				continue;
396			}
397		}
398		for (k = 0; k < devcount; k++) {
399			if (devices[k] == 0)
400				continue;
401			if (bus_get_resource (devices[k], SYS_RES_IOPORT, 0,
402			    &iobase, &rescount) == 0)
403				continue;
404			for (i = 0; (iobase = porttab [i]) != 0; i++) {
405				if (porttab [i] == -1)
406					continue;
407				if (!ct_is_free_res (devices[k], 0, SYS_RES_IOPORT,
408				    iobase, iobase + NPORT, NPORT))
409					continue;
410				if (ct_probe_board (iobase, -1, -1) == 0)
411					continue;
412
413				bus_set_resource (devices[k], SYS_RES_IOPORT, 0,
414				    iobase, NPORT);
415				porttab [i] = -1;
416				device_set_desc_copy (devices[k], "Cronyx Tau-ISA");
417				break;
418			}
419			if (porttab [i] == 0) {
420				device_delete_child (
421				    device_get_parent (devices[k]),
422				    devices [k]);
423			}
424		}
425		free (devices, M_TEMP);
426	}
427
428	return;
429}
430
431static int ct_probe (device_t dev)
432{
433	int unit = device_get_unit (dev);
434	u_long iobase, rescount;
435
436	if (!device_get_desc (dev) ||
437	    strcmp (device_get_desc (dev), "Cronyx Tau-ISA"))
438		return ENXIO;
439
440/*	KASSERT ((bd != NULL), ("ct%d: NULL device softc\n", unit));*/
441	if (bus_get_resource (dev, SYS_RES_IOPORT, 0, &iobase, &rescount) != 0) {
442		printf ("ct%d: Couldn't get IOPORT\n", unit);
443		return ENXIO;
444	}
445
446	if (!ct_is_free_res (dev, 0, SYS_RES_IOPORT,
447	    iobase, iobase + NPORT, NPORT)) {
448		printf ("ct%d: Resource IOPORT isn't free\n", unit);
449		return ENXIO;
450	}
451
452	if (!ct_probe_board (iobase, -1, -1)) {
453		printf ("ct%d: probing for Tau-ISA at %lx faild\n", unit, iobase);
454		return ENXIO;
455	}
456
457	return 0;
458}
459
460extern struct cdevsw ct_cdevsw;
461
462#if __FreeBSD_version >= 500000
463static void
464ct_bus_dmamap_addr (void *arg, bus_dma_segment_t *segs, int nseg, int error)
465{
466	unsigned long *addr;
467
468	if (error)
469		return;
470
471	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
472	addr = arg;
473	*addr = segs->ds_addr;
474}
475
476static int
477ct_bus_dma_mem_alloc (int bnum, int cnum, ct_dma_mem_t *dmem)
478{
479	int error;
480
481	error = bus_dma_tag_create (NULL, 16, 0, BUS_SPACE_MAXADDR_24BIT,
482		BUS_SPACE_MAXADDR, NULL, NULL, dmem->size, 1,
483		dmem->size, 0, NULL, NULL, &dmem->dmat);
484	if (error) {
485		if (cnum >= 0)	printf ("ct%d-%d: ", bnum, cnum);
486		else		printf ("ct%d: ", bnum);
487		printf ("couldn't allocate tag for dma memory\n");
488 		return 0;
489	}
490	error = bus_dmamem_alloc (dmem->dmat, (void **)&dmem->virt,
491		BUS_DMA_NOWAIT | BUS_DMA_ZERO, &dmem->mapp);
492	if (error) {
493		if (cnum >= 0)	printf ("ct%d-%d: ", bnum, cnum);
494		else		printf ("ct%d: ", bnum);
495		printf ("couldn't allocate mem for dma memory\n");
496		bus_dma_tag_destroy (dmem->dmat);
497 		return 0;
498	}
499	error = bus_dmamap_load (dmem->dmat, dmem->mapp, dmem->virt,
500		dmem->size, ct_bus_dmamap_addr, &dmem->phys, 0);
501	if (error) {
502		if (cnum >= 0)	printf ("ct%d-%d: ", bnum, cnum);
503		else		printf ("ct%d: ", bnum);
504		printf ("couldn't load mem map for dma memory\n");
505		bus_dmamem_free (dmem->dmat, dmem->virt, dmem->mapp);
506		bus_dma_tag_destroy (dmem->dmat);
507 		return 0;
508	}
509	return 1;
510}
511
512static void
513ct_bus_dma_mem_free (ct_dma_mem_t *dmem)
514{
515	bus_dmamap_unload (dmem->dmat, dmem->mapp);
516	bus_dmamem_free (dmem->dmat, dmem->virt, dmem->mapp);
517	bus_dma_tag_destroy (dmem->dmat);
518}
519#else
520static int
521ct_bus_dma_mem_alloc (int bnum, int cnum, ct_dma_mem_t *dmem)
522{
523	dmem->virt = contigmalloc (dmem->size, M_DEVBUF, M_WAITOK,
524				   0x100000, 0x1000000, 16, 0);
525	if (dmem->virt == NULL) {
526		if (cnum >= 0)	printf ("ct%d-%d: ", bnum, cnum);
527		else		printf ("ct%d: ", bnum);
528		printf ("couldn't allocate memory for dma memory\n", unit);
529 		return 0;
530	}
531	dmem->phys = vtophys (dmem->virt);
532	return 1;
533}
534
535static void
536ct_bus_dma_mem_free (ct_dma_mem_t *dmem)
537{
538	contigfree (dmem->virt, dmem->size, M_DEVBUF);
539}
540#endif
541
542/*
543 * The adapter is present, initialize the driver structures.
544 */
545static int ct_attach (device_t dev)
546{
547	bdrv_t *bd = device_get_softc (dev);
548	u_long iobase, drq, irq, rescount;
549	int unit = device_get_unit (dev);
550	ct_board_t *b;
551	ct_chan_t *c;
552	drv_t *d;
553	int i;
554	int s;
555
556	KASSERT ((bd != NULL), ("ct%d: NULL device softc\n", unit));
557
558	bus_get_resource (dev, SYS_RES_IOPORT, 0, &iobase, &rescount);
559	bd->base_rid = 0;
560	bd->base_res = bus_alloc_resource (dev, SYS_RES_IOPORT, &bd->base_rid,
561		iobase, iobase + NPORT, NPORT, RF_ACTIVE);
562	if (! bd->base_res) {
563		printf ("ct%d: cannot alloc base address\n", unit);
564		return ENXIO;
565	}
566
567	if (bus_get_resource (dev, SYS_RES_DRQ, 0, &drq, &rescount) != 0) {
568		for (i = 0; (drq = dmatab [i]) != 0; i++) {
569			if (!ct_is_free_res (dev, 0, SYS_RES_DRQ,
570			    drq, drq + 1, 1))
571				continue;
572			bus_set_resource (dev, SYS_RES_DRQ, 0, drq, 1);
573			break;
574		}
575
576		if (dmatab[i] == 0) {
577			bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
578				bd->base_res);
579			printf ("ct%d: Couldn't get DRQ\n", unit);
580			return ENXIO;
581		}
582	}
583
584	bd->drq_rid = 0;
585	bd->drq_res = bus_alloc_resource (dev, SYS_RES_DRQ, &bd->drq_rid,
586		drq, drq + 1, 1, RF_ACTIVE);
587	if (! bd->drq_res) {
588		printf ("ct%d: cannot allocate drq\n", unit);
589		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
590			bd->base_res);
591		return ENXIO;
592	}
593
594	if (bus_get_resource (dev, SYS_RES_IRQ, 0, &irq, &rescount) != 0) {
595		for (i = 0; (irq = irqtab [i]) != 0; i++) {
596			if (!ct_is_free_res (dev, 0, SYS_RES_IRQ,
597			    irq, irq + 1, 1))
598				continue;
599			bus_set_resource (dev, SYS_RES_IRQ, 0, irq, 1);
600			break;
601		}
602
603		if (irqtab[i] == 0) {
604			bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
605				bd->drq_res);
606			bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
607				bd->base_res);
608			printf ("ct%d: Couldn't get IRQ\n", unit);
609			return ENXIO;
610		}
611	}
612
613	bd->irq_rid = 0;
614	bd->irq_res = bus_alloc_resource (dev, SYS_RES_IRQ, &bd->irq_rid,
615		irq, irq + 1, 1, RF_ACTIVE);
616	if (! bd->irq_res) {
617		printf ("ct%d: Couldn't allocate irq\n", unit);
618		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
619			bd->drq_res);
620		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
621			bd->base_res);
622		return ENXIO;
623	}
624
625	b = malloc (sizeof (ct_board_t), M_DEVBUF, M_WAITOK);
626	if (!b) {
627		printf ("ct:%d: Couldn't allocate memory\n", unit);
628		return (ENXIO);
629	}
630	adapter[unit] = b;
631	bzero (b, sizeof(ct_board_t));
632
633	if (! ct_open_board (b, unit, iobase, irq, drq)) {
634		printf ("ct%d: error loading firmware\n", unit);
635		free (b, M_DEVBUF);
636		bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid,
637			bd->irq_res);
638		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
639			bd->drq_res);
640		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
641			bd->base_res);
642 		return ENXIO;
643	}
644
645	bd->board = b;
646
647	if (! probe_irq (b, irq)) {
648		printf ("ct%d: irq %ld not functional\n", unit, irq);
649		bd->board = 0;
650		adapter [unit] = 0;
651		free (b, M_DEVBUF);
652		bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid,
653			bd->irq_res);
654		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
655			bd->drq_res);
656		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
657			bd->base_res);
658 		return ENXIO;
659	}
660
661	s = splimp ();
662	if (bus_setup_intr (dev, bd->irq_res, INTR_TYPE_NET, ct_intr, bd,
663	    &bd->intrhand)) {
664		printf ("ct%d: Can't setup irq %ld\n", unit, irq);
665		bd->board = 0;
666		adapter [unit] = 0;
667		free (b, M_DEVBUF);
668		bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid,
669			bd->irq_res);
670		bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid,
671			bd->drq_res);
672		bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid,
673			bd->base_res);
674		splx (s);
675 		return ENXIO;
676	}
677
678	ct_init_board (b, b->num, b->port, irq, drq, b->type, b->osc);
679	ct_setup_board (b, 0, 0, 0);
680
681	printf ("ct%d: <Cronyx-%s>, clock %s MHz\n", b->num, b->name,
682		b->osc == 20000000 ? "20" : "16.384");
683
684	for (c=b->chan; c<b->chan+NCHAN; ++c) {
685		d = &bd->channel[c->num];
686		d->dmamem.size = sizeof(ct_buf_t);
687		if (! ct_bus_dma_mem_alloc (unit, c->num, &d->dmamem))
688			continue;
689		channel [b->num*NCHAN + c->num] = d;
690		sprintf (d->name, "ct%d.%d", b->num, c->num);
691		d->board = b;
692		d->chan = c;
693		c->sys = d;
694
695#ifdef NETGRAPH
696		if (ng_make_node_common (&typestruct, &d->node) != 0) {
697			printf ("%s: cannot make common node\n", d->name);
698			channel [b->num*NCHAN + c->num] = 0;
699			c->sys = 0;
700			ct_bus_dma_mem_free (&d->dmamem);
701			continue;
702		}
703#if __FreeBSD_version >= 500000
704		NG_NODE_SET_PRIVATE (d->node, d);
705#else
706		d->node->private = d;
707#endif
708		sprintf (d->nodename, "%s%d", NG_CT_NODE_TYPE,
709			 c->board->num*NCHAN + c->num);
710		if (ng_name_node (d->node, d->nodename)) {
711			printf ("%s: cannot name node\n", d->nodename);
712#if __FreeBSD_version >= 500000
713			NG_NODE_UNREF (d->node);
714#else
715			ng_rmnode (d->node);
716			ng_unref (d->node);
717#endif
718			channel [b->num*NCHAN + c->num] = 0;
719			c->sys = 0;
720			ct_bus_dma_mem_free (&d->dmamem);
721			continue;
722		}
723		d->queue.ifq_maxlen = IFQ_MAXLEN;
724		d->hi_queue.ifq_maxlen = IFQ_MAXLEN;
725#if __FreeBSD_version >= 500000
726		mtx_init (&d->queue.ifq_mtx, "ct_queue", NULL, MTX_DEF);
727		mtx_init (&d->hi_queue.ifq_mtx, "ct_queue_hi", NULL, MTX_DEF);
728#endif
729#else /*NETGRAPH*/
730		d->pp.pp_if.if_softc    = d;
731#if __FreeBSD_version > 501000
732		if_initname (&d->pp.pp_if, "ct", b->num * NCHAN + c->num);
733#else
734		d->pp.pp_if.if_unit	= b->num * NCHAN + c->num;
735		d->pp.pp_if.if_name	= "ct";
736#endif
737		d->pp.pp_if.if_mtu	= PP_MTU;
738		d->pp.pp_if.if_flags	= IFF_POINTOPOINT | IFF_MULTICAST |
739					  IFF_NEEDSGIANT;
740		d->pp.pp_if.if_ioctl	= ct_sioctl;
741		d->pp.pp_if.if_start	= ct_ifstart;
742		d->pp.pp_if.if_watchdog	= ct_ifwatchdog;
743		d->pp.pp_if.if_init	= ct_initialize;
744		sppp_attach (&d->pp.pp_if);
745		if_attach (&d->pp.pp_if);
746		d->pp.pp_tlf		= ct_tlf;
747		d->pp.pp_tls		= ct_tls;
748		/* If BPF is in the kernel, call the attach for it.
749		 * Header size is 4 bytes. */
750		bpfattach (&d->pp.pp_if, DLT_PPP, 4);
751#endif /*NETGRAPH*/
752		ct_start_chan (c, d->dmamem.virt, d->dmamem.phys);
753		ct_register_receive (c, &ct_receive);
754		ct_register_transmit (c, &ct_transmit);
755		ct_register_error (c, &ct_error);
756		d->devt = make_dev (&ct_cdevsw, b->num*NCHAN+c->num, UID_ROOT,
757				GID_WHEEL, 0600, "ct%d", b->num*NCHAN+c->num);
758	}
759	splx (s);
760
761	return 0;
762}
763
764static int ct_detach (device_t dev)
765{
766	bdrv_t *bd = device_get_softc (dev);
767	ct_board_t *b = bd->board;
768	ct_chan_t *c;
769	int s = splimp ();
770
771	/* Check if the device is busy (open). */
772	for (c = b->chan; c < b->chan + NCHAN; ++c) {
773		drv_t *d = (drv_t*) c->sys;
774
775		if (!d || !d->chan->type)
776			continue;
777
778		if (d->running) {
779			splx (s);
780			return EBUSY;
781		}
782	}
783
784	/* Deactivate the timeout routine. */
785	if (led_timo[b->num].callout)
786		untimeout (ct_led_off, b, led_timo[b->num]);
787
788	bus_teardown_intr (dev, bd->irq_res, bd->intrhand);
789	bus_deactivate_resource (dev, SYS_RES_IRQ, bd->irq_rid, bd->irq_res);
790	bus_release_resource (dev, SYS_RES_IRQ, bd->irq_rid, bd->irq_res);
791
792	bus_deactivate_resource (dev, SYS_RES_DRQ, bd->drq_rid, bd->drq_res);
793	bus_release_resource (dev, SYS_RES_DRQ, bd->drq_rid, bd->drq_res);
794
795	bus_deactivate_resource (dev, SYS_RES_IOPORT, bd->base_rid, bd->irq_res);
796	bus_release_resource (dev, SYS_RES_IOPORT, bd->base_rid, bd->base_res);
797
798	ct_close_board (b);
799
800	/* Detach the interfaces, free buffer memory. */
801	for (c = b->chan; c < b->chan + NCHAN; ++c) {
802		drv_t *d = (drv_t*) c->sys;
803
804		if (!d || !d->chan->type)
805			continue;
806
807#ifdef NETGRAPH
808#if __FreeBSD_version >= 500000
809		if (d->node) {
810			ng_rmnode_self (d->node);
811			NG_NODE_UNREF (d->node);
812			d->node = NULL;
813		}
814		mtx_destroy (&d->queue.ifq_mtx);
815		mtx_destroy (&d->hi_queue.ifq_mtx);
816#else
817		ng_rmnode (d->node);
818		d->node = 0;
819#endif
820#else
821#if __FreeBSD_version >= 410000 && NBPFILTER > 0
822		/* Detach from the packet filter list of interfaces. */
823		bpfdetach (&d->pp.pp_if);
824#endif
825		/* Detach from the sync PPP list. */
826		sppp_detach (&d->pp.pp_if);
827
828		if_detach (&d->pp.pp_if);
829#endif
830		destroy_dev (d->devt);
831	}
832
833	ct_led_off (b);
834	if (led_timo[b->num].callout)
835		untimeout (ct_led_off, b, led_timo[b->num]);
836	splx (s);
837
838	s = splimp ();
839	for (c = b->chan; c < b->chan + NCHAN; ++c) {
840		drv_t *d = (drv_t*) c->sys;
841
842		if (!d || !d->chan->type)
843			continue;
844
845		/* Deallocate buffers. */
846		ct_bus_dma_mem_free (&d->dmamem);
847	}
848	bd->board = 0;
849	adapter [b->num] = 0;
850	free (b, M_DEVBUF);
851	splx (s);
852
853	return 0;
854}
855
856#ifndef NETGRAPH
857static void ct_ifstart (struct ifnet *ifp)
858{
859	drv_t *d = ifp->if_softc;
860
861	ct_start (d);
862}
863
864static void ct_ifwatchdog (struct ifnet *ifp)
865{
866	drv_t *d = ifp->if_softc;
867
868	ct_watchdog (d);
869}
870
871static void ct_tlf (struct sppp *sp)
872{
873	drv_t *d = sp->pp_if.if_softc;
874
875	CT_DEBUG (d, ("ct_tlf\n"));
876/*	ct_set_dtr (d->chan, 0);*/
877/*	ct_set_rts (d->chan, 0);*/
878	sp->pp_down (sp);
879}
880
881static void ct_tls (struct sppp *sp)
882{
883	drv_t *d = sp->pp_if.if_softc;
884
885	CT_DEBUG (d, ("ct_tls\n"));
886	sp->pp_up (sp);
887}
888
889/*
890 * Initialization of interface.
891 * Ii seems to be never called by upper level.
892 */
893static void ct_initialize (void *softc)
894{
895	drv_t *d = softc;
896
897	CT_DEBUG (d, ("ct_initialize\n"));
898}
899
900/*
901 * Process an ioctl request.
902 */
903static int ct_sioctl (struct ifnet *ifp, u_long cmd, caddr_t data)
904{
905	drv_t *d = ifp->if_softc;
906	int error, s, was_up, should_be_up;
907
908	was_up = (ifp->if_flags & IFF_RUNNING) != 0;
909	error = sppp_ioctl (ifp, cmd, data);
910	if (error)
911		return error;
912
913	if (! (ifp->if_flags & IFF_DEBUG))
914		d->chan->debug = 0;
915	else if (! d->chan->debug)
916		d->chan->debug = 1;
917
918	switch (cmd) {
919	default:	   CT_DEBUG2 (d, ("ioctl 0x%lx\n", cmd)); return 0;
920	case SIOCADDMULTI: CT_DEBUG2 (d, ("SIOCADDMULTI\n"));     return 0;
921	case SIOCDELMULTI: CT_DEBUG2 (d, ("SIOCDELMULTI\n"));     return 0;
922	case SIOCSIFFLAGS: CT_DEBUG2 (d, ("SIOCSIFFLAGS\n"));     break;
923	case SIOCSIFADDR:  CT_DEBUG2 (d, ("SIOCSIFADDR\n"));      break;
924	}
925
926	/* We get here only in case of SIFFLAGS or SIFADDR. */
927	s = splimp ();
928	should_be_up = (ifp->if_flags & IFF_RUNNING) != 0;
929	if (! was_up && should_be_up) {
930		/* Interface goes up -- start it. */
931		ct_up (d);
932		ct_start (d);
933	} else if (was_up && ! should_be_up) {
934		/* Interface is going down -- stop it. */
935		/* if ((d->pp.pp_flags & PP_FR) || (ifp->if_flags & PP_CISCO))*/
936		ct_down (d);
937	}
938	splx (s);
939	return 0;
940}
941#endif /*NETGRAPH*/
942
943/*
944 * Stop the interface.  Called on splimp().
945 */
946static void ct_down (drv_t *d)
947{
948	int s = splimp ();
949	CT_DEBUG (d, ("ct_down\n"));
950	ct_set_dtr (d->chan, 0);
951	ct_set_rts (d->chan, 0);
952	d->running = 0;
953	splx (s);
954}
955
956/*
957 * Start the interface.  Called on splimp().
958 */
959static void ct_up (drv_t *d)
960{
961	int s = splimp ();
962	CT_DEBUG (d, ("ct_up\n"));
963	ct_set_dtr (d->chan, 1);
964	ct_set_rts (d->chan, 1);
965	d->running = 1;
966	splx (s);
967}
968
969/*
970 * Start output on the (slave) interface.  Get another datagram to send
971 * off of the interface queue, and copy it to the interface
972 * before starting the output.
973 */
974static void ct_send (drv_t *d)
975{
976	struct mbuf *m;
977	u_short len;
978
979	CT_DEBUG2 (d, ("ct_send, tn=%d\n", d->chan->tn));
980
981	/* No output if the interface is down. */
982	if (! d->running)
983		return;
984
985	/* No output if the modem is off. */
986	if (! ct_get_dsr (d->chan) && !ct_get_loop (d->chan))
987		return;
988
989	while (ct_buf_free (d->chan)) {
990		/* Get the packet to send. */
991#ifdef NETGRAPH
992		IF_DEQUEUE (&d->hi_queue, m);
993		if (! m)
994			IF_DEQUEUE (&d->queue, m);
995#else
996		m = sppp_dequeue (&d->pp.pp_if);
997#endif
998		if (! m)
999			return;
1000#ifndef NETGRAPH
1001		if (d->pp.pp_if.if_bpf)
1002#if __FreeBSD_version >= 500000
1003			BPF_MTAP (&d->pp.pp_if, m);
1004#else
1005			bpf_mtap (&d->pp.pp_if, m);
1006#endif
1007#endif
1008		len = m->m_pkthdr.len;
1009		if (! m->m_next)
1010			ct_send_packet (d->chan, (u_char*)mtod (m, caddr_t),
1011				len, 0);
1012		else {
1013			m_copydata (m, 0, len, d->chan->tbuf[d->chan->te]);
1014			ct_send_packet (d->chan, d->chan->tbuf[d->chan->te],
1015				len, 0);
1016		}
1017		m_freem (m);
1018
1019		/* Set up transmit timeout, if the transmit ring is not empty.
1020		 * Transmit timeout is 10 seconds. */
1021#ifdef NETGRAPH
1022		d->timeout = 10;
1023#else
1024		d->pp.pp_if.if_timer = 10;
1025#endif
1026	}
1027#ifndef NETGRAPH
1028	d->pp.pp_if.if_flags |= IFF_OACTIVE;
1029#endif
1030}
1031
1032/*
1033 * Start output on the interface.
1034 * Always called on splimp().
1035 */
1036static void ct_start (drv_t *d)
1037{
1038	int s = splimp ();
1039
1040	if (d->running) {
1041		if (! d->chan->dtr)
1042			ct_set_dtr (d->chan, 1);
1043		if (! d->chan->rts)
1044			ct_set_rts (d->chan, 1);
1045		ct_send (d);
1046	}
1047
1048	splx (s);
1049}
1050
1051/*
1052 * Handle transmit timeouts.
1053 * Recover after lost transmit interrupts.
1054 * Always called on splimp().
1055 */
1056static void ct_watchdog (drv_t *d)
1057{
1058	int s = splimp ();
1059
1060	CT_DEBUG (d, ("device timeout\n"));
1061	if (d->running) {
1062		ct_setup_chan (d->chan);
1063		ct_start_chan (d->chan, 0, 0);
1064		ct_set_dtr (d->chan, 1);
1065		ct_set_rts (d->chan, 1);
1066		ct_start (d);
1067	}
1068
1069	splx (s);
1070}
1071
1072/*
1073 * Transmit callback function.
1074 */
1075static void ct_transmit (ct_chan_t *c, void *attachment, int len)
1076{
1077	drv_t *d = c->sys;
1078
1079	if (!d)
1080		return;
1081#ifdef NETGRAPH
1082	d->timeout = 0;
1083#else
1084	++d->pp.pp_if.if_opackets;
1085	d->pp.pp_if.if_flags &= ~IFF_OACTIVE;
1086	d->pp.pp_if.if_timer = 0;
1087#endif
1088	ct_start (d);
1089}
1090
1091/*
1092 * Process the received packet.
1093 */
1094static void ct_receive (ct_chan_t *c, char *data, int len)
1095{
1096	drv_t *d = c->sys;
1097	struct mbuf *m;
1098#if __FreeBSD_version >= 500000 && defined NETGRAPH
1099	int error;
1100#endif
1101
1102	if (!d || !d->running)
1103		return;
1104
1105	m = makembuf (data, len);
1106	if (! m) {
1107		CT_DEBUG (d, ("no memory for packet\n"));
1108#ifndef NETGRAPH
1109		++d->pp.pp_if.if_iqdrops;
1110#endif
1111		return;
1112	}
1113	if (c->debug > 1)
1114		printmbuf (m);
1115#ifdef NETGRAPH
1116	m->m_pkthdr.rcvif = 0;
1117#if __FreeBSD_version >= 500000
1118	NG_SEND_DATA_ONLY (error, d->hook, m);
1119#else
1120	ng_queue_data (d->hook, m, 0);
1121#endif
1122#else
1123	++d->pp.pp_if.if_ipackets;
1124	m->m_pkthdr.rcvif = &d->pp.pp_if;
1125	/* Check if there's a BPF listener on this interface.
1126	 * If so, hand off the raw packet to bpf. */
1127	if (d->pp.pp_if.if_bpf)
1128#if __FreeBSD_version >= 500000
1129		BPF_TAP (&d->pp.pp_if, data, len);
1130#else
1131		bpf_tap (&d->pp.pp_if, data, len);
1132#endif
1133	sppp_input (&d->pp.pp_if, m);
1134#endif
1135}
1136
1137/*
1138 * Error callback function.
1139 */
1140static void ct_error (ct_chan_t *c, int data)
1141{
1142	drv_t *d = c->sys;
1143
1144	if (!d)
1145		return;
1146
1147	switch (data) {
1148	case CT_FRAME:
1149		CT_DEBUG (d, ("frame error\n"));
1150#ifndef NETGRAPH
1151		++d->pp.pp_if.if_ierrors;
1152#endif
1153		break;
1154	case CT_CRC:
1155		CT_DEBUG (d, ("crc error\n"));
1156#ifndef NETGRAPH
1157		++d->pp.pp_if.if_ierrors;
1158#endif
1159		break;
1160	case CT_OVERRUN:
1161		CT_DEBUG (d, ("overrun error\n"));
1162#ifndef NETGRAPH
1163		++d->pp.pp_if.if_collisions;
1164		++d->pp.pp_if.if_ierrors;
1165#endif
1166		break;
1167	case CT_OVERFLOW:
1168		CT_DEBUG (d, ("overflow error\n"));
1169#ifndef NETGRAPH
1170		++d->pp.pp_if.if_ierrors;
1171#endif
1172		break;
1173	case CT_UNDERRUN:
1174		CT_DEBUG (d, ("underrun error\n"));
1175#ifdef NETGRAPH
1176		d->timeout = 0;
1177#else
1178		++d->pp.pp_if.if_oerrors;
1179		d->pp.pp_if.if_flags &= ~IFF_OACTIVE;
1180		d->pp.pp_if.if_timer = 0;
1181#endif
1182		ct_start (d);
1183		break;
1184	default:
1185		CT_DEBUG (d, ("error #%d\n", data));
1186	}
1187}
1188
1189#if __FreeBSD_version < 500000
1190static int ct_open (dev_t dev, int oflags, int devtype, struct proc *p)
1191#else
1192static int ct_open (struct cdev *dev, int oflags, int devtype, struct thread *td)
1193#endif
1194{
1195	drv_t *d;
1196
1197	if (minor(dev) >= NCTAU*NCHAN || ! (d = channel[minor(dev)]))
1198		return ENXIO;
1199
1200	CT_DEBUG2 (d, ("ct_open\n"));
1201	return 0;
1202}
1203
1204#if __FreeBSD_version < 500000
1205static int ct_close (dev_t dev, int fflag, int devtype, struct proc *p)
1206#else
1207static int ct_close (struct cdev *dev, int fflag, int devtype, struct thread *td)
1208#endif
1209{
1210	drv_t *d = channel [minor(dev)];
1211
1212	if (!d)
1213		return 0;
1214
1215	CT_DEBUG2 (d, ("ct_close\n"));
1216	return 0;
1217}
1218
1219static int ct_modem_status (ct_chan_t *c)
1220{
1221	drv_t *d = c->sys;
1222	int status, s;
1223
1224	if (!d)
1225		return 0;
1226
1227	status = d->running ? TIOCM_LE : 0;
1228	s = splimp ();
1229	if (ct_get_cd  (c)) status |= TIOCM_CD;
1230	if (ct_get_cts (c)) status |= TIOCM_CTS;
1231	if (ct_get_dsr (c)) status |= TIOCM_DSR;
1232	if (c->dtr)	    status |= TIOCM_DTR;
1233	if (c->rts)	    status |= TIOCM_RTS;
1234	splx (s);
1235	return status;
1236}
1237
1238/*
1239 * Process an ioctl request on /dev/cronyx/ctauN.
1240 */
1241#if __FreeBSD_version < 500000
1242static int ct_ioctl (dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
1243#else
1244static int ct_ioctl (struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
1245#endif
1246{
1247	drv_t *d = channel [minor (dev)];
1248	ct_chan_t *c;
1249	struct serial_statistics *st;
1250	struct e1_statistics *opte1;
1251	int error, s;
1252	char mask[16];
1253
1254	if (!d || !d->chan)
1255		return 0;
1256
1257	c = d->chan;
1258
1259	switch (cmd) {
1260	case SERIAL_GETREGISTERED:
1261		bzero (mask, sizeof(mask));
1262		for (s=0; s<NCTAU*NCHAN; ++s)
1263			if (channel [s])
1264				mask [s/8] |= 1 << (s & 7);
1265		bcopy (mask, data, sizeof (mask));
1266		return 0;
1267
1268#ifndef NETGRAPH
1269	case SERIAL_GETPROTO:
1270		strcpy ((char*)data, (d->pp.pp_flags & PP_FR) ? "fr" :
1271			(d->pp.pp_if.if_flags & PP_CISCO) ? "cisco" : "ppp");
1272		return 0;
1273
1274	case SERIAL_SETPROTO:
1275		/* Only for superuser! */
1276#if __FreeBSD_version < 500000
1277		error = suser (p);
1278#else /* __FreeBSD_version >= 500000 */
1279		error = suser (td);
1280#endif /* __FreeBSD_version >= 500000 */
1281		if (error)
1282			return error;
1283		if (d->pp.pp_if.if_flags & IFF_RUNNING)
1284			return EBUSY;
1285		if (! strcmp ("cisco", (char*)data)) {
1286			d->pp.pp_flags &= ~(PP_FR);
1287			d->pp.pp_flags |= PP_KEEPALIVE;
1288			d->pp.pp_if.if_flags |= PP_CISCO;
1289		} else if (! strcmp ("fr", (char*)data)) {
1290			d->pp.pp_if.if_flags &= ~(PP_CISCO);
1291			d->pp.pp_flags |= PP_FR | PP_KEEPALIVE;
1292		} else if (! strcmp ("ppp", (char*)data)) {
1293			d->pp.pp_flags &= ~(PP_FR | PP_KEEPALIVE);
1294			d->pp.pp_if.if_flags &= ~(PP_CISCO);
1295		} else
1296			return EINVAL;
1297		return 0;
1298
1299	case SERIAL_GETKEEPALIVE:
1300		if ((d->pp.pp_flags & PP_FR) ||
1301			(d->pp.pp_if.if_flags & PP_CISCO))
1302			return EINVAL;
1303		*(int*)data = (d->pp.pp_flags & PP_KEEPALIVE) ? 1 : 0;
1304		return 0;
1305
1306	case SERIAL_SETKEEPALIVE:
1307		/* Only for superuser! */
1308#if __FreeBSD_version < 500000
1309		error = suser (p);
1310#else /* __FreeBSD_version >= 500000 */
1311		error = suser (td);
1312#endif /* __FreeBSD_version >= 500000 */
1313		if (error)
1314			return error;
1315		if ((d->pp.pp_flags & PP_FR) ||
1316			(d->pp.pp_if.if_flags & PP_CISCO))
1317			return EINVAL;
1318		if (*(int*)data)
1319			d->pp.pp_flags |= PP_KEEPALIVE;
1320		else
1321			d->pp.pp_flags &= ~PP_KEEPALIVE;
1322		return 0;
1323#endif /*NETGRAPH*/
1324
1325	case SERIAL_GETMODE:
1326		*(int*)data = SERIAL_HDLC;
1327		return 0;
1328
1329	case SERIAL_GETCFG:
1330		if (c->mode == M_HDLC)
1331			return EINVAL;
1332		switch (ct_get_config (c->board)) {
1333		default:    *(char*)data = 'a'; break;
1334		case CFG_B: *(char*)data = 'b'; break;
1335		case CFG_C: *(char*)data = 'c'; break;
1336		}
1337		return 0;
1338
1339	case SERIAL_SETCFG:
1340		/* Only for superuser! */
1341#if __FreeBSD_version < 500000
1342		error = suser (p);
1343#else /* __FreeBSD_version >= 500000 */
1344		error = suser (td);
1345#endif /* __FreeBSD_version >= 500000 */
1346		if (error)
1347			return error;
1348		if (c->mode == M_HDLC)
1349			return EINVAL;
1350		s = splimp ();
1351		switch (*(char*)data) {
1352		case 'a': ct_set_config (c->board, CFG_A); break;
1353		case 'b': ct_set_config (c->board, CFG_B); break;
1354		case 'c': ct_set_config (c->board, CFG_C); break;
1355		}
1356		splx (s);
1357		return 0;
1358
1359	case SERIAL_GETSTAT:
1360		st = (struct serial_statistics*) data;
1361		st->rintr  = c->rintr;
1362		st->tintr  = c->tintr;
1363		st->mintr  = c->mintr;
1364		st->ibytes = c->ibytes;
1365		st->ipkts  = c->ipkts;
1366		st->ierrs  = c->ierrs;
1367		st->obytes = c->obytes;
1368		st->opkts  = c->opkts;
1369		st->oerrs  = c->oerrs;
1370		return 0;
1371
1372	case SERIAL_GETESTAT:
1373		opte1 = (struct e1_statistics*)data;
1374		opte1->status	   = c->status;
1375		opte1->cursec	   = c->cursec;
1376		opte1->totsec	   = c->totsec + c->cursec;
1377
1378		opte1->currnt.bpv   = c->currnt.bpv;
1379		opte1->currnt.fse   = c->currnt.fse;
1380		opte1->currnt.crce  = c->currnt.crce;
1381		opte1->currnt.rcrce = c->currnt.rcrce;
1382		opte1->currnt.uas   = c->currnt.uas;
1383		opte1->currnt.les   = c->currnt.les;
1384		opte1->currnt.es    = c->currnt.es;
1385		opte1->currnt.bes   = c->currnt.bes;
1386		opte1->currnt.ses   = c->currnt.ses;
1387		opte1->currnt.oofs  = c->currnt.oofs;
1388		opte1->currnt.css   = c->currnt.css;
1389		opte1->currnt.dm    = c->currnt.dm;
1390
1391		opte1->total.bpv   = c->total.bpv   + c->currnt.bpv;
1392		opte1->total.fse   = c->total.fse   + c->currnt.fse;
1393		opte1->total.crce  = c->total.crce  + c->currnt.crce;
1394		opte1->total.rcrce = c->total.rcrce + c->currnt.rcrce;
1395		opte1->total.uas   = c->total.uas   + c->currnt.uas;
1396		opte1->total.les   = c->total.les   + c->currnt.les;
1397		opte1->total.es	   = c->total.es    + c->currnt.es;
1398		opte1->total.bes   = c->total.bes   + c->currnt.bes;
1399		opte1->total.ses   = c->total.ses   + c->currnt.ses;
1400		opte1->total.oofs  = c->total.oofs  + c->currnt.oofs;
1401		opte1->total.css   = c->total.css   + c->currnt.css;
1402		opte1->total.dm	   = c->total.dm    + c->currnt.dm;
1403		for (s=0; s<48; ++s) {
1404			opte1->interval[s].bpv   = c->interval[s].bpv;
1405			opte1->interval[s].fse   = c->interval[s].fse;
1406			opte1->interval[s].crce  = c->interval[s].crce;
1407			opte1->interval[s].rcrce = c->interval[s].rcrce;
1408			opte1->interval[s].uas   = c->interval[s].uas;
1409			opte1->interval[s].les   = c->interval[s].les;
1410			opte1->interval[s].es	 = c->interval[s].es;
1411			opte1->interval[s].bes   = c->interval[s].bes;
1412			opte1->interval[s].ses   = c->interval[s].ses;
1413			opte1->interval[s].oofs  = c->interval[s].oofs;
1414			opte1->interval[s].css   = c->interval[s].css;
1415			opte1->interval[s].dm	 = c->interval[s].dm;
1416		}
1417		return 0;
1418
1419	case SERIAL_CLRSTAT:
1420		/* Only for superuser! */
1421#if __FreeBSD_version < 500000
1422		error = suser (p);
1423#else /* __FreeBSD_version >= 500000 */
1424		error = suser (td);
1425#endif /* __FreeBSD_version >= 500000 */
1426		if (error)
1427			return error;
1428		c->rintr = 0;
1429		c->tintr = 0;
1430		c->mintr = 0;
1431		c->ibytes = 0;
1432		c->ipkts = 0;
1433		c->ierrs = 0;
1434		c->obytes = 0;
1435		c->opkts = 0;
1436		c->oerrs = 0;
1437		bzero (&c->currnt, sizeof (c->currnt));
1438		bzero (&c->total, sizeof (c->total));
1439		bzero (c->interval, sizeof (c->interval));
1440		return 0;
1441
1442	case SERIAL_GETBAUD:
1443		*(long*)data = ct_get_baud(c);
1444		return 0;
1445
1446	case SERIAL_SETBAUD:
1447		/* Only for superuser! */
1448#if __FreeBSD_version < 500000
1449		error = suser (p);
1450#else /* __FreeBSD_version >= 500000 */
1451		error = suser (td);
1452#endif /* __FreeBSD_version >= 500000 */
1453		if (error)
1454			return error;
1455		s = splimp ();
1456		ct_set_baud (c, *(long*)data);
1457		splx (s);
1458		return 0;
1459
1460	case SERIAL_GETLOOP:
1461		*(int*)data = ct_get_loop (c);
1462		return 0;
1463
1464	case SERIAL_SETLOOP:
1465		/* Only for superuser! */
1466#if __FreeBSD_version < 500000
1467		error = suser (p);
1468#else /* __FreeBSD_version >= 500000 */
1469		error = suser (td);
1470#endif /* __FreeBSD_version >= 500000 */
1471		if (error)
1472			return error;
1473		s = splimp ();
1474		ct_set_loop (c, *(int*)data);
1475		splx (s);
1476		return 0;
1477
1478	case SERIAL_GETDPLL:
1479		if (c->mode == M_E1 || c->mode == M_G703)
1480			return EINVAL;
1481		*(int*)data = ct_get_dpll (c);
1482		return 0;
1483
1484	case SERIAL_SETDPLL:
1485		/* Only for superuser! */
1486#if __FreeBSD_version < 500000
1487		error = suser (p);
1488#else /* __FreeBSD_version >= 500000 */
1489		error = suser (td);
1490#endif /* __FreeBSD_version >= 500000 */
1491		if (error)
1492			return error;
1493		if (c->mode == M_E1 || c->mode == M_G703)
1494			return EINVAL;
1495		s = splimp ();
1496		ct_set_dpll (c, *(int*)data);
1497		splx (s);
1498		return 0;
1499
1500	case SERIAL_GETNRZI:
1501		if (c->mode == M_E1 || c->mode == M_G703)
1502			return EINVAL;
1503		*(int*)data = ct_get_nrzi (c);
1504		return 0;
1505
1506	case SERIAL_SETNRZI:
1507		/* Only for superuser! */
1508#if __FreeBSD_version < 500000
1509		error = suser (p);
1510#else /* __FreeBSD_version >= 500000 */
1511		error = suser (td);
1512#endif /* __FreeBSD_version >= 500000 */
1513		if (error)
1514			return error;
1515		if (c->mode == M_E1 || c->mode == M_G703)
1516			return EINVAL;
1517		s = splimp ();
1518		ct_set_nrzi (c, *(int*)data);
1519		splx (s);
1520		return 0;
1521
1522	case SERIAL_GETDEBUG:
1523		*(int*)data = c->debug;
1524		return 0;
1525
1526	case SERIAL_SETDEBUG:
1527		/* Only for superuser! */
1528#if __FreeBSD_version < 500000
1529		error = suser (p);
1530#else /* __FreeBSD_version >= 500000 */
1531		error = suser (td);
1532#endif /* __FreeBSD_version >= 500000 */
1533		if (error)
1534			return error;
1535		c->debug = *(int*)data;
1536#ifndef	NETGRAPH
1537		if (d->chan->debug)
1538			d->pp.pp_if.if_flags |= IFF_DEBUG;
1539		else
1540			d->pp.pp_if.if_flags &= (~IFF_DEBUG);
1541#endif
1542		return 0;
1543
1544	case SERIAL_GETHIGAIN:
1545		if (c->mode != M_E1)
1546			return EINVAL;
1547		*(int*)data = ct_get_higain (c);
1548		return 0;
1549
1550	case SERIAL_SETHIGAIN:
1551		/* Only for superuser! */
1552#if __FreeBSD_version < 500000
1553		error = suser (p);
1554#else /* __FreeBSD_version >= 500000 */
1555		error = suser (td);
1556#endif /* __FreeBSD_version >= 500000 */
1557		if (error)
1558			return error;
1559		s = splimp ();
1560		ct_set_higain (c, *(int*)data);
1561		splx (s);
1562		return 0;
1563
1564	case SERIAL_GETPHONY:
1565		CT_DEBUG2 (d, ("ioctl: getphony\n"));
1566		if (c->mode != M_E1)
1567			return EINVAL;
1568		*(int*)data = c->gopt.phony;
1569		return 0;
1570
1571	case SERIAL_SETPHONY:
1572		CT_DEBUG2 (d, ("ioctl: setphony\n"));
1573		if (c->mode != M_E1)
1574			return EINVAL;
1575		/* Only for superuser! */
1576#if __FreeBSD_version < 500000
1577		error = suser (p);
1578#else /* __FreeBSD_version >= 500000 */
1579		error = suser (td);
1580#endif /* __FreeBSD_version >= 500000 */
1581		if (error)
1582			return error;
1583		s = splimp ();
1584		ct_set_phony (c, *(int*)data);
1585		splx (s);
1586		return 0;
1587
1588	case SERIAL_GETCLK:
1589		if (c->mode != M_E1 && c->mode != M_G703)
1590			return EINVAL;
1591		switch (ct_get_clk(c)) {
1592		default:	 *(int*)data = E1CLK_INTERNAL;		break;
1593		case GCLK_RCV:   *(int*)data = E1CLK_RECEIVE;		break;
1594		case GCLK_RCLKO: *(int*)data = c->num ?
1595			E1CLK_RECEIVE_CHAN0 : E1CLK_RECEIVE_CHAN1;	break;
1596		}
1597		return 0;
1598
1599	case SERIAL_SETCLK:
1600		/* Only for superuser! */
1601#if __FreeBSD_version < 500000
1602		error = suser (p);
1603#else /* __FreeBSD_version >= 500000 */
1604		error = suser (td);
1605#endif /* __FreeBSD_version >= 500000 */
1606		if (error)
1607			return error;
1608		s = splimp ();
1609		switch (*(int*)data) {
1610		default:		    ct_set_clk (c, GCLK_INT);   break;
1611		case E1CLK_RECEIVE:	    ct_set_clk (c, GCLK_RCV);   break;
1612		case E1CLK_RECEIVE_CHAN0:
1613		case E1CLK_RECEIVE_CHAN1:
1614					    ct_set_clk (c, GCLK_RCLKO); break;
1615		}
1616		splx (s);
1617		return 0;
1618
1619	case SERIAL_GETTIMESLOTS:
1620		if (c->mode != M_E1)
1621			return EINVAL;
1622		*(long*)data = ct_get_ts (c);
1623		return 0;
1624
1625	case SERIAL_SETTIMESLOTS:
1626		/* Only for superuser! */
1627#if __FreeBSD_version < 500000
1628		error = suser (p);
1629#else /* __FreeBSD_version >= 500000 */
1630		error = suser (td);
1631#endif /* __FreeBSD_version >= 500000 */
1632		if (error)
1633			return error;
1634		s = splimp ();
1635		ct_set_ts (c, *(long*)data);
1636		splx (s);
1637		return 0;
1638
1639	case SERIAL_GETSUBCHAN:
1640		if (c->mode != M_E1)
1641			return EINVAL;
1642		*(long*)data = ct_get_subchan (c->board);
1643		return 0;
1644
1645	case SERIAL_SETSUBCHAN:
1646		/* Only for superuser! */
1647#if __FreeBSD_version < 500000
1648		error = suser (p);
1649#else /* __FreeBSD_version >= 500000 */
1650		error = suser (td);
1651#endif /* __FreeBSD_version >= 500000 */
1652		if (error)
1653			return error;
1654		s = splimp ();
1655		ct_set_subchan (c->board, *(long*)data);
1656		splx (s);
1657		return 0;
1658
1659	case SERIAL_GETINVCLK:
1660	case SERIAL_GETINVTCLK:
1661		if (c->mode == M_E1 || c->mode == M_G703)
1662			return EINVAL;
1663		*(int*)data = ct_get_invtxc (c);
1664		return 0;
1665
1666	case SERIAL_GETINVRCLK:
1667		if (c->mode == M_E1 || c->mode == M_G703)
1668			return EINVAL;
1669		*(int*)data = ct_get_invrxc (c);
1670		return 0;
1671
1672	case SERIAL_SETINVCLK:
1673	case SERIAL_SETINVTCLK:
1674		/* Only for superuser! */
1675#if __FreeBSD_version < 500000
1676		error = suser (p);
1677#else /* __FreeBSD_version >= 500000 */
1678		error = suser (td);
1679#endif /* __FreeBSD_version >= 500000 */
1680		if (error)
1681			return error;
1682		if (c->mode == M_E1 || c->mode == M_G703)
1683			return EINVAL;
1684		s = splimp ();
1685		ct_set_invtxc (c, *(int*)data);
1686		splx (s);
1687		return 0;
1688
1689	case SERIAL_SETINVRCLK:
1690		/* Only for superuser! */
1691#if __FreeBSD_version < 500000
1692		error = suser (p);
1693#else /* __FreeBSD_version >= 500000 */
1694		error = suser (td);
1695#endif /* __FreeBSD_version >= 500000 */
1696		if (error)
1697			return error;
1698		if (c->mode == M_E1 || c->mode == M_G703)
1699			return EINVAL;
1700		s = splimp ();
1701		ct_set_invrxc (c, *(int*)data);
1702		splx (s);
1703		return 0;
1704
1705	case SERIAL_GETLEVEL:
1706		if (c->mode != M_G703)
1707			return EINVAL;
1708		s = splimp ();
1709		*(int*)data = ct_get_lq (c);
1710		splx (s);
1711		return 0;
1712
1713	case TIOCSDTR:	/* Set DTR */
1714		s = splimp ();
1715		ct_set_dtr (c, 1);
1716		splx (s);
1717		return 0;
1718
1719	case TIOCCDTR:	/* Clear DTR */
1720		s = splimp ();
1721		ct_set_dtr (c, 0);
1722		splx (s);
1723		return 0;
1724
1725	case TIOCMSET:	/* Set DTR/RTS */
1726		s = splimp ();
1727		ct_set_dtr (c, (*(int*)data & TIOCM_DTR) ? 1 : 0);
1728		ct_set_rts (c, (*(int*)data & TIOCM_RTS) ? 1 : 0);
1729		splx (s);
1730		return 0;
1731
1732	case TIOCMBIS:	/* Add DTR/RTS */
1733		s = splimp ();
1734		if (*(int*)data & TIOCM_DTR) ct_set_dtr (c, 1);
1735		if (*(int*)data & TIOCM_RTS) ct_set_rts (c, 1);
1736		splx (s);
1737		return 0;
1738
1739	case TIOCMBIC:	/* Clear DTR/RTS */
1740		s = splimp ();
1741		if (*(int*)data & TIOCM_DTR) ct_set_dtr (c, 0);
1742		if (*(int*)data & TIOCM_RTS) ct_set_rts (c, 0);
1743		splx (s);
1744		return 0;
1745
1746	case TIOCMGET:	/* Get modem status */
1747		*(int*)data = ct_modem_status (c);
1748		return 0;
1749	}
1750	return ENOTTY;
1751}
1752
1753#if __FreeBSD_version < 500000
1754static struct cdevsw ct_cdevsw = {
1755	ct_open,	ct_close,	noread,		nowrite,
1756	ct_ioctl,	nopoll,		nommap,		nostrategy,
1757	"ct",		CDEV_MAJOR,	nodump,		nopsize,
1758	D_NAGGED,	-1
1759};
1760#elif __FreeBSD_version == 500000
1761static struct cdevsw ct_cdevsw = {
1762	ct_open,	ct_close,	noread,		nowrite,
1763	ct_ioctl,	nopoll,		nommap,		nostrategy,
1764	"ct",		CDEV_MAJOR,	nodump,		nopsize,
1765	D_NAGGED,
1766	};
1767#elif __FreeBSD_version <= 501000
1768static struct cdevsw ct_cdevsw = {
1769	.d_open     = ct_open,
1770	.d_close    = ct_close,
1771	.d_read     = noread,
1772	.d_write    = nowrite,
1773	.d_ioctl    = ct_ioctl,
1774	.d_poll     = nopoll,
1775	.d_mmap	    = nommap,
1776	.d_strategy = nostrategy,
1777	.d_name     = "ct",
1778	.d_maj      = CDEV_MAJOR,
1779	.d_dump     = nodump,
1780	.d_flags    = D_NAGGED,
1781};
1782#elif __FreeBSD_version < 502103
1783static struct cdevsw ct_cdevsw = {
1784	.d_open     = ct_open,
1785	.d_close    = ct_close,
1786	.d_ioctl    = ct_ioctl,
1787	.d_name     = "ct",
1788	.d_maj      = CDEV_MAJOR,
1789	.d_flags    = D_NAGGED,
1790};
1791#else /* __FreeBSD_version >= 502103 */
1792static struct cdevsw ct_cdevsw = {
1793	.d_version  = D_VERSION,
1794	.d_open     = ct_open,
1795	.d_close    = ct_close,
1796	.d_ioctl    = ct_ioctl,
1797	.d_name     = "ct",
1798	.d_maj      = CDEV_MAJOR,
1799	.d_flags    = D_NEEDGIANT,
1800};
1801#endif /* __FreeBSD_version > 501000 */
1802
1803#ifdef NETGRAPH
1804#if __FreeBSD_version >= 500000
1805static int ng_ct_constructor (node_p node)
1806{
1807	drv_t *d = NG_NODE_PRIVATE (node);
1808#else
1809static int ng_ct_constructor (node_p *node)
1810{
1811	drv_t *d = (*node)->private;
1812#endif
1813	CT_DEBUG (d, ("Constructor\n"));
1814	return EINVAL;
1815}
1816
1817static int ng_ct_newhook (node_p node, hook_p hook, const char *name)
1818{
1819	int s;
1820#if __FreeBSD_version >= 500000
1821	drv_t *d = NG_NODE_PRIVATE (node);
1822#else
1823	drv_t *d = node->private;
1824#endif
1825
1826	if (!d)
1827		return EINVAL;
1828
1829	/* Attach debug hook */
1830	if (strcmp (name, NG_CT_HOOK_DEBUG) == 0) {
1831#if __FreeBSD_version >= 500000
1832		NG_HOOK_SET_PRIVATE (hook, NULL);
1833#else
1834		hook->private = 0;
1835#endif
1836		d->debug_hook = hook;
1837		return 0;
1838	}
1839
1840	/* Check for raw hook */
1841	if (strcmp (name, NG_CT_HOOK_RAW) != 0)
1842		return EINVAL;
1843
1844#if __FreeBSD_version >= 500000
1845	NG_HOOK_SET_PRIVATE (hook, d);
1846#else
1847	hook->private = d;
1848#endif
1849	d->hook = hook;
1850	s = splimp ();
1851	ct_up (d);
1852	splx (s);
1853	return 0;
1854}
1855
1856static char *format_timeslots (u_long s)
1857{
1858	static char buf [100];
1859	char *p = buf;
1860	int i;
1861
1862	for (i=1; i<32; ++i)
1863		if ((s >> i) & 1) {
1864			int prev = (i > 1)  & (s >> (i-1));
1865			int next = (i < 31) & (s >> (i+1));
1866
1867			if (prev) {
1868				if (next)
1869					continue;
1870				*p++ = '-';
1871			} else if (p > buf)
1872				*p++ = ',';
1873
1874			if (i >= 10)
1875				*p++ = '0' + i / 10;
1876			*p++ = '0' + i % 10;
1877		}
1878	*p = 0;
1879	return buf;
1880}
1881
1882static int print_modems (char *s, ct_chan_t *c, int need_header)
1883{
1884	int status = ct_modem_status (c);
1885	int length = 0;
1886
1887	if (need_header)
1888		length += sprintf (s + length, "  LE   DTR  DSR  RTS  CTS  CD\n");
1889	length += sprintf (s + length, "%4s %4s %4s %4s %4s %4s\n",
1890		status & TIOCM_LE  ? "On" : "-",
1891		status & TIOCM_DTR ? "On" : "-",
1892		status & TIOCM_DSR ? "On" : "-",
1893		status & TIOCM_RTS ? "On" : "-",
1894		status & TIOCM_CTS ? "On" : "-",
1895		status & TIOCM_CD  ? "On" : "-");
1896	return length;
1897}
1898
1899static int print_stats (char *s, ct_chan_t *c, int need_header)
1900{
1901	struct serial_statistics st;
1902	int length = 0;
1903
1904	st.rintr  = c->rintr;
1905	st.tintr  = c->tintr;
1906	st.mintr  = c->mintr;
1907	st.ibytes = c->ibytes;
1908	st.ipkts  = c->ipkts;
1909	st.ierrs  = c->ierrs;
1910	st.obytes = c->obytes;
1911	st.opkts  = c->opkts;
1912	st.oerrs  = c->oerrs;
1913	if (need_header)
1914		length += sprintf (s + length, "  Rintr   Tintr   Mintr   Ibytes   Ipkts   Ierrs   Obytes   Opkts   Oerrs\n");
1915	length += sprintf (s + length, "%7ld %7ld %7ld %8ld %7ld %7ld %8ld %7ld %7ld\n",
1916		st.rintr, st.tintr, st.mintr, st.ibytes, st.ipkts,
1917		st.ierrs, st.obytes, st.opkts, st.oerrs);
1918	return length;
1919}
1920
1921static char *format_e1_status (u_char status)
1922{
1923	static char buf [80];
1924
1925	if (status & E1_NOALARM)
1926		return "Ok";
1927	buf[0] = 0;
1928	if (status & E1_LOS)     strcat (buf, ",LOS");
1929	if (status & E1_AIS)     strcat (buf, ",AIS");
1930	if (status & E1_LOF)     strcat (buf, ",LOF");
1931	if (status & E1_LOMF)    strcat (buf, ",LOMF");
1932	if (status & E1_FARLOF)  strcat (buf, ",FARLOF");
1933	if (status & E1_AIS16)   strcat (buf, ",AIS16");
1934	if (status & E1_FARLOMF) strcat (buf, ",FARLOMF");
1935	if (status & E1_TSTREQ)  strcat (buf, ",TSTREQ");
1936	if (status & E1_TSTERR)  strcat (buf, ",TSTERR");
1937	if (buf[0] == ',')
1938		return buf+1;
1939	return "Unknown";
1940}
1941
1942static int print_frac (char *s, int leftalign, u_long numerator, u_long divider)
1943{
1944	int n, length = 0;
1945
1946	if (numerator < 1 || divider < 1) {
1947		length += sprintf (s+length, leftalign ? "/-   " : "    -");
1948		return length;
1949	}
1950	n = (int) (0.5 + 1000.0 * numerator / divider);
1951	if (n < 1000) {
1952		length += sprintf (s+length, leftalign ? "/.%-3d" : " .%03d", n);
1953		return length;
1954	}
1955	*(s + length) = leftalign ? '/' : ' ';
1956	length ++;
1957
1958	if     (n >= 1000000) n = (n+500) / 1000 * 1000;
1959	else if (n >= 100000)  n = (n+50)  / 100 * 100;
1960	else if (n >= 10000)   n = (n+5)   / 10 * 10;
1961
1962	switch (n) {
1963	case 1000:    length += printf (s+length, ".999"); return length;
1964	case 10000:   n = 9990;   break;
1965	case 100000:  n = 99900;  break;
1966	case 1000000: n = 999000; break;
1967	}
1968	if (n < 10000)	      length += sprintf (s+length, "%d.%d", n/1000, n/10%100);
1969	else if (n < 100000)  length += sprintf (s+length, "%d.%d", n/1000, n/100%10);
1970	else if (n < 1000000) length += sprintf (s+length, "%d.", n/1000);
1971	else		      length += sprintf (s+length, "%d", n/1000);
1972
1973	return length;
1974}
1975
1976static int print_e1_stats (char *s, ct_chan_t *c)
1977{
1978	struct e1_counters total;
1979	u_long totsec;
1980	int length = 0;
1981
1982	totsec		= c->totsec + c->cursec;
1983	total.bpv	= c->total.bpv   + c->currnt.bpv;
1984	total.fse	= c->total.fse   + c->currnt.fse;
1985	total.crce	= c->total.crce  + c->currnt.crce;
1986	total.rcrce	= c->total.rcrce + c->currnt.rcrce;
1987	total.uas	= c->total.uas   + c->currnt.uas;
1988	total.les	= c->total.les   + c->currnt.les;
1989	total.es	= c->total.es    + c->currnt.es;
1990	total.bes	= c->total.bes   + c->currnt.bes;
1991	total.ses	= c->total.ses   + c->currnt.ses;
1992	total.oofs	= c->total.oofs  + c->currnt.oofs;
1993	total.css	= c->total.css   + c->currnt.css;
1994	total.dm	= c->total.dm    + c->currnt.dm;
1995
1996	length += sprintf (s + length, " Unav/Degr  Bpv/Fsyn  CRC/RCRC  Err/Lerr  Sev/Bur   Oof/Slp  Status\n");
1997
1998	/* Unavailable seconds, degraded minutes */
1999	length += print_frac (s + length, 0, c->currnt.uas, c->cursec);
2000	length += print_frac (s + length, 1, 60 * c->currnt.dm, c->cursec);
2001
2002	/* Bipolar violations, frame sync errors */
2003	length += print_frac (s + length, 0, c->currnt.bpv, c->cursec);
2004	length += print_frac (s + length, 1, c->currnt.fse, c->cursec);
2005
2006	/* CRC errors, remote CRC errors (E-bit) */
2007	length += print_frac (s + length, 0, c->currnt.crce, c->cursec);
2008	length += print_frac (s + length, 1, c->currnt.rcrce, c->cursec);
2009
2010	/* Errored seconds, line errored seconds */
2011	length += print_frac (s + length, 0, c->currnt.es, c->cursec);
2012	length += print_frac (s + length, 1, c->currnt.les, c->cursec);
2013
2014	/* Severely errored seconds, burst errored seconds */
2015	length += print_frac (s + length, 0, c->currnt.ses, c->cursec);
2016	length += print_frac (s + length, 1, c->currnt.bes, c->cursec);
2017
2018	/* Out of frame seconds, controlled slip seconds */
2019	length += print_frac (s + length, 0, c->currnt.oofs, c->cursec);
2020	length += print_frac (s + length, 1, c->currnt.css, c->cursec);
2021
2022	length += sprintf (s + length, " %s\n", format_e1_status (c->status));
2023
2024	/* Print total statistics. */
2025	length += print_frac (s + length, 0, total.uas, totsec);
2026	length += print_frac (s + length, 1, 60 * total.dm, totsec);
2027
2028	length += print_frac (s + length, 0, total.bpv, totsec);
2029	length += print_frac (s + length, 1, total.fse, totsec);
2030
2031	length += print_frac (s + length, 0, total.crce, totsec);
2032	length += print_frac (s + length, 1, total.rcrce, totsec);
2033
2034	length += print_frac (s + length, 0, total.es, totsec);
2035	length += print_frac (s + length, 1, total.les, totsec);
2036
2037	length += print_frac (s + length, 0, total.ses, totsec);
2038	length += print_frac (s + length, 1, total.bes, totsec);
2039
2040	length += print_frac (s + length, 0, total.oofs, totsec);
2041	length += print_frac (s + length, 1, total.css, totsec);
2042
2043	length += sprintf (s + length, " -- Total\n");
2044	return length;
2045}
2046
2047static int print_chan (char *s, ct_chan_t *c)
2048{
2049	drv_t *d = c->sys;
2050	int length = 0;
2051
2052	length += sprintf (s + length, "ct%d", c->board->num * NCHAN + c->num);
2053	if (d->chan->debug)
2054		length += sprintf (s + length, " debug=%d", d->chan->debug);
2055
2056	switch (ct_get_config (c->board)) {
2057	case CFG_A:	length += sprintf (s + length, " cfg=A");	break;
2058	case CFG_B:	length += sprintf (s + length, " cfg=B");	break;
2059	case CFG_C:	length += sprintf (s + length, " cfg=C");	break;
2060	default:	length += sprintf (s + length, " cfg=unknown"); break;
2061	}
2062
2063	if (ct_get_baud (c))
2064		length += sprintf (s + length, " %ld", ct_get_baud (c));
2065	else
2066		length += sprintf (s + length, " extclock");
2067
2068	if (c->mode == M_E1 || c->mode == M_G703)
2069		switch (ct_get_clk(c)) {
2070		case GCLK_INT   : length += sprintf (s + length, " syn=int");     break;
2071		case GCLK_RCV   : length += sprintf (s + length, " syn=rcv");     break;
2072		case GCLK_RCLKO  : length += sprintf (s + length, " syn=xrcv");    break;
2073		}
2074	if (c->mode == M_HDLC) {
2075		length += sprintf (s + length, " dpll=%s",   ct_get_dpll (c)   ? "on" : "off");
2076		length += sprintf (s + length, " nrzi=%s",   ct_get_nrzi (c)   ? "on" : "off");
2077		length += sprintf (s + length, " invtclk=%s", ct_get_invtxc (c) ? "on" : "off");
2078		length += sprintf (s + length, " invrclk=%s", ct_get_invrxc (c) ? "on" : "off");
2079	}
2080	if (c->mode == M_E1)
2081		length += sprintf (s + length, " higain=%s", ct_get_higain (c)? "on" : "off");
2082
2083	length += sprintf (s + length, " loop=%s", ct_get_loop (c) ? "on" : "off");
2084
2085	if (c->mode == M_E1)
2086		length += sprintf (s + length, " ts=%s", format_timeslots (ct_get_ts(c)));
2087	if (c->mode == M_E1 && ct_get_config (c->board) != CFG_A)
2088		length += sprintf (s + length, " pass=%s", format_timeslots (ct_get_subchan(c->board)));
2089	if (c->mode == M_G703) {
2090		int lq, x;
2091
2092		x = splimp ();
2093		lq = ct_get_lq (c);
2094		splx (x);
2095		length += sprintf (s + length, " (level=-%.1fdB)", lq / 10.0);
2096	}
2097	length += sprintf (s + length, "\n");
2098	return length;
2099}
2100
2101#if __FreeBSD_version >= 500000
2102static int ng_ct_rcvmsg (node_p node, item_p item, hook_p lasthook)
2103{
2104	drv_t *d = NG_NODE_PRIVATE (node);
2105	struct ng_mesg *msg;
2106#else
2107static int ng_ct_rcvmsg (node_p node, struct ng_mesg *msg,
2108	const char *retaddr, struct ng_mesg **rptr)
2109{
2110	drv_t *d = node->private;
2111#endif
2112	struct ng_mesg *resp = NULL;
2113	int error = 0;
2114
2115	if (!d)
2116		return EINVAL;
2117
2118	CT_DEBUG (d, ("Rcvmsg\n"));
2119#if __FreeBSD_version >= 500000
2120	NGI_GET_MSG (item, msg);
2121#endif
2122	switch (msg->header.typecookie) {
2123	default:
2124		error = EINVAL;
2125		break;
2126
2127	case NGM_CT_COOKIE:
2128		printf ("Don't forget to implement\n");
2129		error = EINVAL;
2130		break;
2131
2132	case NGM_GENERIC_COOKIE:
2133		switch (msg->header.cmd) {
2134		default:
2135			error = EINVAL;
2136			break;
2137
2138		case NGM_TEXT_STATUS: {
2139			char *s;
2140			int l = 0;
2141			int dl = sizeof (struct ng_mesg) + 730;
2142
2143#if __FreeBSD_version >= 500000
2144			NG_MKRESPONSE (resp, msg, dl, M_NOWAIT);
2145			if (! resp) {
2146				error = ENOMEM;
2147				break;
2148			}
2149#else
2150			MALLOC (resp, struct ng_mesg *, dl,
2151				M_NETGRAPH, M_NOWAIT);
2152			if (! resp) {
2153				error = ENOMEM;
2154				break;
2155			}
2156			bzero (resp, dl);
2157#endif
2158			s = (resp)->data;
2159			l += print_chan (s + l, d->chan);
2160			l += print_stats (s + l, d->chan, 1);
2161			l += print_modems (s + l, d->chan, 1);
2162			l += print_e1_stats (s + l, d->chan);
2163#if __FreeBSD_version < 500000
2164			(resp)->header.version = NG_VERSION;
2165			(resp)->header.arglen = strlen (s) + 1;
2166			(resp)->header.token = msg->header.token;
2167			(resp)->header.typecookie = NGM_CT_COOKIE;
2168			(resp)->header.cmd = msg->header.cmd;
2169#endif
2170			strncpy ((resp)->header.cmdstr, "status", NG_CMDSTRLEN);
2171			}
2172			break;
2173		}
2174		break;
2175	}
2176#if __FreeBSD_version >= 500000
2177	NG_RESPOND_MSG (error, node, item, resp);
2178	NG_FREE_MSG (msg);
2179#else
2180	*rptr = resp;
2181	FREE (msg, M_NETGRAPH);
2182#endif
2183	return error;
2184}
2185
2186#if __FreeBSD_version >= 500000
2187static int ng_ct_rcvdata (hook_p hook, item_p item)
2188{
2189	drv_t *d = NG_NODE_PRIVATE (NG_HOOK_NODE(hook));
2190	struct mbuf *m;
2191	struct ng_tag_prio *ptag;
2192#else
2193static int ng_ct_rcvdata (hook_p hook, struct mbuf *m, meta_p meta)
2194{
2195	drv_t *d = hook->node->private;
2196#endif
2197	struct ifqueue *q;
2198	int s;
2199
2200	if (!d)
2201		return ENETDOWN;
2202
2203#if __FreeBSD_version >= 500000
2204	NGI_GET_M (item, m);
2205	NG_FREE_ITEM (item);
2206	if (! NG_HOOK_PRIVATE (hook) || ! d) {
2207		NG_FREE_M (m);
2208#else
2209	if (! hook->private || ! d) {
2210		NG_FREE_DATA (m,meta);
2211#endif
2212		return ENETDOWN;
2213	}
2214
2215	/* Check for high priority data */
2216	if ((ptag = (struct ng_tag_prio *)m_tag_locate(m, NGM_GENERIC_COOKIE,
2217	    NG_TAG_PRIO, NULL)) != NULL && (ptag->priority > NG_PRIO_CUTOFF) )
2218		q = &d->hi_queue;
2219	else
2220		q = &d->queue;
2221
2222	s = splimp ();
2223#if __FreeBSD_version >= 500000
2224	IF_LOCK (q);
2225	if (_IF_QFULL (q)) {
2226		_IF_DROP (q);
2227		IF_UNLOCK (q);
2228		splx (s);
2229		NG_FREE_M (m);
2230		return ENOBUFS;
2231	}
2232	_IF_ENQUEUE (q, m);
2233	IF_UNLOCK (q);
2234#else
2235	if (IF_QFULL (q)) {
2236		IF_DROP (q);
2237		splx (s);
2238		NG_FREE_DATA (m, meta);
2239		return ENOBUFS;
2240	}
2241	IF_ENQUEUE (q, m);
2242#endif
2243	ct_start (d);
2244	splx (s);
2245	return 0;
2246}
2247
2248static int ng_ct_rmnode (node_p node)
2249{
2250#if __FreeBSD_version >= 500000
2251	drv_t *d = NG_NODE_PRIVATE (node);
2252
2253	CT_DEBUG (d, ("Rmnode\n"));
2254	if (d && d->running) {
2255		int s = splimp ();
2256		ct_down (d);
2257		splx (s);
2258	}
2259#ifdef	KLD_MODULE
2260	if (node->nd_flags & NGF_REALLY_DIE) {
2261		NG_NODE_SET_PRIVATE (node, NULL);
2262		NG_NODE_UNREF (node);
2263	}
2264	NG_NODE_REVIVE(node);		/* Persistant node */
2265#endif
2266#else /* __FreeBSD_version < 500000 */
2267	drv_t *d = node->private;
2268	int s;
2269
2270	if (!d)
2271		return 0;
2272
2273	s = splimp ();
2274	ct_down (d);
2275	splx (s);
2276	node->flags |= NG_INVALID;
2277	ng_cutlinks (node);
2278#ifdef	KLD_MODULE
2279	ng_unname (node);
2280	ng_unref (node);
2281#else
2282	node->flags &= ~NG_INVALID;
2283#endif
2284#endif
2285	return 0;
2286}
2287
2288static void ng_ct_watchdog (void *arg)
2289{
2290	drv_t *d = arg;
2291
2292	if (!d)
2293		return;
2294
2295	if (d->timeout == 1)
2296		ct_watchdog (d);
2297	if (d->timeout)
2298		d->timeout--;
2299	d->timeout_handle = timeout (ng_ct_watchdog, d, hz);
2300}
2301
2302static int ng_ct_connect (hook_p hook)
2303{
2304#if __FreeBSD_version >= 500000
2305	drv_t *d = NG_NODE_PRIVATE (NG_HOOK_NODE (hook));
2306#else
2307	drv_t *d = hook->node->private;
2308#endif
2309
2310	if (!d)
2311		return 0;
2312
2313	d->timeout_handle = timeout (ng_ct_watchdog, d, hz);
2314	return 0;
2315}
2316
2317static int ng_ct_disconnect (hook_p hook)
2318{
2319#if __FreeBSD_version >= 500000
2320	drv_t *d = NG_NODE_PRIVATE (NG_HOOK_NODE (hook));
2321#else
2322	drv_t *d = hook->node->private;
2323#endif
2324
2325	if (!d)
2326		return 0;
2327
2328#if __FreeBSD_version >= 500000
2329	if (NG_HOOK_PRIVATE (hook))
2330#else
2331	if (hook->private)
2332#endif
2333		ct_down (d);
2334	untimeout (ng_ct_watchdog, d, d->timeout_handle);
2335	return 0;
2336}
2337#endif
2338
2339static int ct_modevent (module_t mod, int type, void *unused)
2340{
2341	struct cdev *dev;
2342	static int load_count = 0;
2343	struct cdevsw *cdsw;
2344
2345#if __FreeBSD_version >= 502103
2346	dev = findcdev (makedev(CDEV_MAJOR, 0));
2347#else
2348	dev = makedev (CDEV_MAJOR, 0);
2349#endif
2350	switch (type) {
2351	case MOD_LOAD:
2352		if (dev != NULL &&
2353		    (cdsw = devsw (dev)) &&
2354		    cdsw->d_maj == CDEV_MAJOR) {
2355			printf ("Tau-ISA driver is already in system\n");
2356			return (ENXIO);
2357		}
2358#if __FreeBSD_version >= 500000 && defined NETGRAPH
2359		if (ng_newtype (&typestruct))
2360			printf ("Failed to register ng_ct\n");
2361#endif
2362		++load_count;
2363#if __FreeBSD_version <= 500000
2364		cdevsw_add (&ct_cdevsw);
2365#endif
2366		timeout_handle = timeout (ct_timeout, 0, hz*5);
2367		break;
2368	case MOD_UNLOAD:
2369		if (load_count == 1) {
2370			printf ("Removing device entry for Tau-ISA\n");
2371#if __FreeBSD_version <= 500000
2372			cdevsw_remove (&ct_cdevsw);
2373#endif
2374#if __FreeBSD_version >= 500000 && defined NETGRAPH
2375			ng_rmtype (&typestruct);
2376#endif
2377		}
2378		if (timeout_handle.callout)
2379			untimeout (ct_timeout, 0, timeout_handle);
2380		--load_count;
2381		break;
2382	case MOD_SHUTDOWN:
2383		break;
2384	}
2385	return 0;
2386}
2387
2388#ifdef NETGRAPH
2389static struct ng_type typestruct = {
2390	.version	= NG_ABI_VERSION,
2391	.name		= NG_CT_NODE_TYPE,
2392	.constructor	= ng_ct_constructor,
2393	.rcvmsg		= ng_ct_rcvmsg,
2394	.shutdown	= ng_ct_rmnode,
2395	.newhook	= ng_ct_newhook,
2396	.connect	= ng_ct_connect,
2397	.rcvdata	= ng_ct_rcvdata,
2398	.disconnect	= ng_ct_disconnect,
2399};
2400#endif /*NETGRAPH*/
2401
2402#if __FreeBSD_version >= 500000
2403#ifdef NETGRAPH
2404MODULE_DEPEND (ng_ct, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
2405#else
2406MODULE_DEPEND (ct, sppp, 1, 1, 1);
2407#endif
2408#ifdef KLD_MODULE
2409DRIVER_MODULE (ctmod, isa, ct_isa_driver, ct_devclass, ct_modevent, NULL);
2410#else
2411DRIVER_MODULE (ct, isa, ct_isa_driver, ct_devclass, ct_modevent, NULL);
2412#endif
2413#elif __FreeBSD_version >= 400000
2414#ifdef NETGRAPH
2415DRIVER_MODULE(ct, isa, ct_isa_driver, ct_devclass, ng_mod_event, &typestruct);
2416#else
2417DRIVER_MODULE(ct, isa, ct_isa_driver, ct_devclass, ct_modevent, 0);
2418#endif
2419#endif /* __FreeBSD_version >= 400000 */
2420#endif /* NCTAU */
2421