]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - sys/dev/lmc/if_lmc.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / sys / dev / lmc / if_lmc.c
1 /*
2  * $FreeBSD$
3  *
4  * Copyright (c) 2002-2004 David Boggs. <boggs@boggs.palo-alto.ca.us>
5  * All rights reserved.
6  *
7  * BSD License:
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * GNU General Public License:
31  *
32  * This program is free software; you can redistribute it and/or modify it 
33  * under the terms of the GNU General Public License as published by the Free 
34  * Software Foundation; either version 2 of the License, or (at your option) 
35  * any later version.
36  * 
37  * This program is distributed in the hope that it will be useful, but WITHOUT 
38  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
39  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for 
40  * more details.
41  *
42  * You should have received a copy of the GNU General Public License along with
43  * this program; if not, write to the Free Software Foundation, Inc., 59 
44  * Temple Place - Suite 330, Boston, MA  02111-1307, USA.
45  *
46  * Description:
47  *
48  * This is an open-source Unix device driver for PCI-bus WAN interface cards.
49  * It sends and receives packets in HDLC frames over synchronous links.
50  * A generic PC plus Unix plus some SBE/LMC cards makes an OPEN router.
51  * This driver works with FreeBSD, NetBSD, OpenBSD, BSD/OS and Linux.
52  * It has been tested on i386 (32-bit little-end), Sparc (64-bit big-end),
53  * and Alpha (64-bit little-end) architectures.
54  *
55  * History and Authors:
56  *
57  * Ron Crane had the neat idea to use a Fast Ethernet chip as a PCI
58  * interface and add an Ethernet-to-HDLC gate array to make a WAN card.
59  * David Boggs designed the Ethernet-to-HDLC gate arrays and PC cards.
60  * We did this at our company, LAN Media Corporation (LMC).
61  * SBE Corp acquired LMC and continues to make the cards.
62  *
63  * Since the cards use Tulip Ethernet chips, we started with Matt Thomas'
64  * ubiquitous "de" driver.  Michael Graff stripped out the Ethernet stuff
65  * and added HSSI stuff.  Basil Gunn ported it to Solaris (lost) and
66  * Rob Braun ported it to Linux.  Andrew Stanley-Jones added support
67  * for three more cards and wrote the first version of lmcconfig.
68  * During 2002-5 David Boggs rewrote it and now feels responsible for it.
69  *
70  * Responsible Individual:
71  *
72  * Send bug reports and improvements to <boggs@boggs.palo-alto.ca.us>.
73  */
74 #ifdef __FreeBSD__
75 # include <sys/param.h> /* OS version */
76 # define  IFNET 1
77 # include "opt_inet.h"  /* INET */
78 # include "opt_inet6.h" /* INET6 */
79 # include "opt_netgraph.h" /* NETGRAPH */
80 # ifdef HAVE_KERNEL_OPTION_HEADERS
81 # include "opt_device_polling.h" /* DEVICE_POLLING */
82 # endif
83 # ifndef INET
84 #  define INET 0
85 # endif
86 # ifndef INET6
87 #  define INET6 0
88 # endif
89 # ifndef NETGRAPH
90 #  define NETGRAPH 0
91 # endif
92 # define  P2P 0         /* not in FreeBSD */
93 # if (__FreeBSD_version >= 500000)
94 #  define NSPPP 1       /* No count devices in FreeBSD 5 */
95 #  include "opt_bpf.h"  /* DEV_BPF */
96 #  define NBPFILTER DEV_BPF
97 # else  /* FreeBSD-4 */
98 # include "sppp.h"      /* NSPPP */
99 #  include "bpf.h"      /* NBPF */
100 #  define NBPFILTER NBPF
101 # endif
102 # define  GEN_HDLC 0    /* not in FreeBSD */
103 #
104 # include <sys/systm.h>
105 # include <sys/kernel.h>
106 # include <sys/malloc.h>
107 # include <sys/mbuf.h>
108 # include <sys/socket.h>
109 # include <sys/sockio.h>
110 # include <sys/module.h>
111 # include <sys/bus.h>
112 # include <sys/lock.h>
113 # include <net/if.h>
114 # include <net/if_types.h>
115 # include <net/if_media.h>
116 # include <net/netisr.h>
117 # include <net/route.h>
118 # include <machine/bus.h>
119 # include <machine/resource.h>
120 # include <sys/rman.h>
121 # include <vm/vm.h>
122 # include <vm/pmap.h>
123 # if (__FreeBSD_version >= 700000)
124 #  include <sys/priv.h>
125 # endif
126 # if (__FreeBSD_version >= 500000)
127 #  include <sys/mutex.h>
128 #  include <dev/pci/pcivar.h>
129 # else /* FreeBSD-4 */
130 #  include <sys/proc.h>
131 #  include <pci/pcivar.h>
132 # endif
133 # if NETGRAPH
134 #  include <netgraph/ng_message.h>
135 #  include <netgraph/netgraph.h>
136 # endif
137 # if (INET || INET6)
138 #  include <netinet/in.h>
139 #  include <netinet/in_var.h>
140 # endif
141 # if NSPPP
142 #  include <net/if_sppp.h>
143 # endif
144 # if NBPFILTER
145 #  include <net/bpf.h>
146 # endif
147 /* and finally... */
148 # include <dev/lmc/if_lmc.h>
149 #endif /*__FreeBSD__*/
150
151 #ifdef __NetBSD__
152 # include <sys/param.h> /* OS version */
153 # define  IFNET 1
154 # include "opt_inet.h"  /* INET6, INET */
155 # define  NETGRAPH 0    /* not in NetBSD */
156 # include "sppp.h"      /* NSPPP */
157 # define  P2P 0         /* not in NetBSD */
158 # include "opt_altq_enabled.h" /* ALTQ */
159 # include "bpfilter.h"  /* NBPFILTER */
160 # define  GEN_HDLC 0    /* not in NetBSD */
161 #
162 # include <sys/systm.h>
163 # include <sys/kernel.h>
164 # include <sys/lkm.h>
165 # include <sys/mbuf.h>
166 # include <sys/socket.h>
167 # include <sys/sockio.h>
168 # include <sys/device.h>
169 # include <sys/lock.h>
170 # include <net/if.h>
171 # include <net/if_types.h>
172 # include <net/if_media.h>
173 # include <net/netisr.h>
174 # include <machine/bus.h>
175 # include <machine/intr.h>
176 # include <dev/pci/pcivar.h>
177 # if (__NetBSD_Version__ >= 106000000)
178 #  include <uvm/uvm_extern.h>
179 # else
180 #  include <vm/vm.h>
181 # endif
182 # if (INET || INET6)
183 #  include <netinet/in.h>
184 #  include <netinet/in_var.h>
185 # endif
186 # if NSPPP
187 #  if (__NetBSD_Version__ >= 106000000)
188 #   include <net/if_spppvar.h>
189 #  else
190 #   include <net/if_sppp.h>
191 #  endif
192 # endif
193 # if NBPFILTER
194 #  include <net/bpf.h>
195 # endif
196 /* and finally... */
197 # include "if_lmc.h"
198 #endif /*__NetBSD__*/
199
200 #ifdef __OpenBSD__
201 # include <sys/param.h> /* OS version */
202 # define  IFNET 1
203 /* -DINET  is passed on the compiler command line */
204 /* -DINET6 is passed on the compiler command line */
205 # define  NETGRAPH 0    /* not in OpenBSD */
206 # include "sppp.h"      /* NSPPP */
207 # define  P2P 0         /* not in OpenBSD */
208 /* -DALTQ  is passed on the compiler command line */
209 # include "bpfilter.h"  /* NBPFILTER */
210 # define  GEN_HDLC 0    /* not in OpenBSD */
211 #
212 # include <sys/systm.h>
213 # include <sys/kernel.h>
214 # include <sys/conf.h>
215 # include <sys/exec.h>
216 # include <sys/lkm.h>
217 # include <sys/mbuf.h>
218 # include <sys/socket.h>
219 # include <sys/sockio.h>
220 # include <sys/device.h>
221 # include <sys/lock.h>
222 # include <net/if.h>
223 # include <net/if_types.h>
224 # include <net/if_media.h>
225 # include <net/netisr.h>
226 # include <machine/bus.h>
227 # include <machine/intr.h>
228 # include <dev/pci/pcivar.h>
229 # if (OpenBSD >= 200206)
230 #  include <uvm/uvm_extern.h>
231 # else
232 #  include <vm/vm.h>
233 # endif
234 # if (INET || INET6)
235 #  include <netinet/in.h>
236 #  include <netinet/in_var.h>
237 # endif
238 # if NSPPP
239 #  include <net/if_sppp.h>
240 # endif
241 # if NBPFILTER
242 #  include <net/bpf.h>
243 # endif
244 /* and finally... */
245 # include "if_lmc.h"
246 #endif /*__OpenBSD__*/
247
248 #ifdef __bsdi__
249 # include <sys/param.h> /* OS version */
250 # define  IFNET 1
251 /* -DINET  is passed on the compiler command line */
252 /* -DINET6 is passed on the compiler command line */
253 # define  NETGRAPH 0    /* not in BSD/OS */
254 # define  NSPPP 0       /* not in BSD/OS */
255 /* -DPPP   is passed on the compiler command line */
256 /* -DCISCO_HDLC is passed on the compiler command line */
257 /* -DFR    is passed on the compiler command line */
258 # if (PPP || CISCO_HDLC || FR)
259 #  define P2P 1
260 # else
261 #  define P2P 0
262 # endif
263 # define  ALTQ 0        /* not in BSD/OS */
264 # include "bpfilter.h"  /* NBPFILTER */
265 # define  GEN_HDLC 0    /* not in BSD/OS */
266 #
267 # include <sys/kernel.h>
268 # include <sys/malloc.h>
269 # include <sys/mbuf.h>
270 # include <sys/socket.h>
271 # include <sys/sockio.h>
272 # include <sys/device.h>
273 # include <sys/lock.h>
274 # include <net/if.h>
275 # include <net/if_types.h>
276 # include <net/if_media.h>
277 # include <net/netisr.h>
278 # include <vm/vm.h>
279 # include <i386/isa/dma.h>
280 # include <i386/isa/isavar.h>
281 # include <i386/include/cpu.h>
282 # include <i386/pci/pci.h>
283 # if (INET || INET6)
284 #  include <netinet/in.h>
285 #  include <netinet/in_var.h>
286 # endif
287 # if P2P
288 #  include <net/if_p2p.h>
289 #  include <sys/ttycom.h>
290 # endif
291 # if NBPFILTER
292 #  include <net/bpf.h>
293 # endif
294 /* and finally... */
295 # include "if_lmc.h"
296 #endif /*__bsdi__*/
297
298 #ifdef __linux__
299 # include <linux/config.h>
300 # if (CONFIG_HDLC || CONFIG_HDLC_MODULE)
301 #  define GEN_HDLC 1
302 # else
303 #  define GEN_HDLC 0
304 # endif
305 # define IFNET 0        /* different in Linux */
306 # define NETGRAPH 0     /* not in Linux */
307 # define NSPPP 0        /* different in Linux */
308 # define P2P 0          /* not in Linux */
309 # define ALTQ 0         /* different in Linux */
310 # define NBPFILTER 0    /* different in Linux */
311 #
312 # include <linux/pci.h>
313 # include <linux/delay.h>
314 # include <linux/netdevice.h>
315 # include <linux/if_arp.h>
316 # if GEN_HDLC
317 #  include <linux/hdlc.h>
318 # endif
319 /* and finally... */
320 # include "if_lmc.h"
321 #endif /* __linux__ */
322
323 /* The SROM is a generic 93C46 serial EEPROM (64 words by 16 bits). */
324 /* Data is set up before the RISING edge of CLK; CLK is parked low. */
325 static void
326 shift_srom_bits(softc_t *sc, u_int32_t data, u_int32_t len)
327   {
328   u_int32_t csr = READ_CSR(TLP_SROM_MII);
329   for (; len>0; len--)
330     {  /* MSB first */
331     if (data & (1<<(len-1)))
332       csr |=  TLP_SROM_DIN;     /* DIN setup */
333     else
334       csr &= ~TLP_SROM_DIN;     /* DIN setup */
335     WRITE_CSR(TLP_SROM_MII, csr);
336     csr |=  TLP_SROM_CLK;       /* CLK rising edge */
337     WRITE_CSR(TLP_SROM_MII, csr);
338     csr &= ~TLP_SROM_CLK;       /* CLK falling edge */
339     WRITE_CSR(TLP_SROM_MII, csr);
340     }
341   }
342
343 /* Data is sampled on the RISING edge of CLK; CLK is parked low. */
344 static u_int16_t
345 read_srom(softc_t *sc, u_int8_t addr)
346   {
347   int i;
348   u_int32_t csr;
349   u_int16_t data;
350
351   /* Enable SROM access. */
352   csr = (TLP_SROM_SEL | TLP_SROM_RD | TLP_MII_MDOE);
353   WRITE_CSR(TLP_SROM_MII, csr);
354   /* CS rising edge prepares SROM for a new cycle. */
355   csr |= TLP_SROM_CS;
356   WRITE_CSR(TLP_SROM_MII, csr); /* assert CS */
357   shift_srom_bits(sc,  6,   4);         /* issue read cmd */
358   shift_srom_bits(sc, addr, 6);         /* issue address */
359   for (data=0, i=16; i>=0; i--)         /* read ->17<- bits of data */
360     {  /* MSB first */
361     csr = READ_CSR(TLP_SROM_MII);       /* DOUT sampled */
362     data = (data<<1) | ((csr & TLP_SROM_DOUT) ? 1:0);
363     csr |=  TLP_SROM_CLK;               /* CLK rising edge */
364     WRITE_CSR(TLP_SROM_MII, csr);
365     csr &= ~TLP_SROM_CLK;               /* CLK falling edge */
366     WRITE_CSR(TLP_SROM_MII, csr);
367     }
368   /* Disable SROM access. */
369   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
370
371   return data;
372   }
373
374 /* The SROM is formatted by the mfgr and should NOT be written! */
375 /* But lmcconfig can rewrite it in case it gets overwritten somehow. */
376 /* IOCTL SYSCALL: can sleep. */
377 static void
378 write_srom(softc_t *sc, u_int8_t addr, u_int16_t data)
379   {
380   u_int32_t csr;
381   int i;
382
383   /* Enable SROM access. */
384   csr = (TLP_SROM_SEL | TLP_SROM_RD | TLP_MII_MDOE);
385   WRITE_CSR(TLP_SROM_MII, csr);
386
387   /* Issue write-enable command. */
388   csr |= TLP_SROM_CS;
389   WRITE_CSR(TLP_SROM_MII, csr); /* assert CS */
390   shift_srom_bits(sc,  4, 4);           /* issue write enable cmd */
391   shift_srom_bits(sc, 63, 6);           /* issue address */
392   csr &= ~TLP_SROM_CS;
393   WRITE_CSR(TLP_SROM_MII, csr); /* deassert CS */
394
395   /* Issue erase command. */
396   csr |= TLP_SROM_CS;
397   WRITE_CSR(TLP_SROM_MII, csr); /* assert CS */
398   shift_srom_bits(sc, 7, 4);            /* issue erase cmd */
399   shift_srom_bits(sc, addr, 6);         /* issue address */
400   csr &= ~TLP_SROM_CS;
401   WRITE_CSR(TLP_SROM_MII, csr); /* deassert CS */
402
403   /* Issue write command. */
404   csr |= TLP_SROM_CS;
405   WRITE_CSR(TLP_SROM_MII, csr); /* assert CS */
406   for (i=0; i<10; i++)  /* 100 ms max wait */
407     if ((READ_CSR(TLP_SROM_MII) & TLP_SROM_DOUT)==0) SLEEP(10000);
408   shift_srom_bits(sc, 5, 4);            /* issue write cmd */
409   shift_srom_bits(sc, addr, 6);         /* issue address */
410   shift_srom_bits(sc, data, 16);        /* issue data */
411   csr &= ~TLP_SROM_CS;
412   WRITE_CSR(TLP_SROM_MII, csr); /* deassert CS */
413
414   /* Issue write-disable command. */
415   csr |= TLP_SROM_CS;
416   WRITE_CSR(TLP_SROM_MII, csr); /* assert CS */
417   for (i=0; i<10; i++)  /* 100 ms max wait */
418     if ((READ_CSR(TLP_SROM_MII) & TLP_SROM_DOUT)==0) SLEEP(10000);
419   shift_srom_bits(sc, 4, 4);            /* issue write disable cmd */
420   shift_srom_bits(sc, 0, 6);            /* issue address */
421   csr &= ~TLP_SROM_CS;
422   WRITE_CSR(TLP_SROM_MII, csr); /* deassert CS */
423
424   /* Disable SROM access. */
425   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
426   }
427
428 /* Not all boards have BIOS roms. */
429 /* The BIOS ROM is an AMD 29F010 1Mbit (128K by 8) EEPROM. */
430 static u_int8_t
431 read_bios(softc_t *sc, u_int32_t addr)
432   {
433   u_int32_t srom_mii;
434
435   /* Load the BIOS rom address register. */
436   WRITE_CSR(TLP_BIOS_ROM, addr);
437
438   /* Enable the BIOS rom. */
439   srom_mii = TLP_BIOS_SEL | TLP_BIOS_RD | TLP_MII_MDOE;
440   WRITE_CSR(TLP_SROM_MII, srom_mii);
441
442   /* Wait at least 20 PCI cycles. */
443   DELAY(20);
444
445   /* Read the BIOS rom data. */
446   srom_mii = READ_CSR(TLP_SROM_MII);
447
448   /* Disable the BIOS rom. */
449   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
450
451   return (u_int8_t)srom_mii & 0xFF;
452   }
453
454 static void
455 write_bios_phys(softc_t *sc, u_int32_t addr, u_int8_t data)
456   {
457   u_int32_t srom_mii;
458
459   /* Load the BIOS rom address register. */
460   WRITE_CSR(TLP_BIOS_ROM, addr);
461
462   /* Enable the BIOS rom. */
463   srom_mii = TLP_BIOS_SEL | TLP_BIOS_WR | TLP_MII_MDOE;
464
465   /* Load the data into the data register. */
466   srom_mii = (srom_mii & 0xFFFFFF00) | (data & 0xFF);
467   WRITE_CSR(TLP_SROM_MII, srom_mii);
468
469   /* Wait at least 20 PCI cycles. */
470   DELAY(20);
471
472   /* Disable the BIOS rom. */
473   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
474   }
475
476 /* IOCTL SYSCALL: can sleep. */
477 static void
478 write_bios(softc_t *sc, u_int32_t addr, u_int8_t data)
479   {
480   u_int8_t read_data;
481
482   /* this sequence enables writing */
483   write_bios_phys(sc, 0x5555, 0xAA);
484   write_bios_phys(sc, 0x2AAA, 0x55);
485   write_bios_phys(sc, 0x5555, 0xA0);
486   write_bios_phys(sc, addr,   data);
487
488   /* Wait for the write operation to complete. */
489   for (;;)  /* interruptable syscall */
490     {
491     for (;;)
492       {
493       read_data = read_bios(sc, addr);
494       if ((read_data & 0x80) == (data & 0x80)) break;
495       if  (read_data & 0x20)
496         {  /* Data sheet says read it again. */
497         read_data = read_bios(sc, addr);
498         if ((read_data & 0x80) == (data & 0x80)) break;
499         if (DRIVER_DEBUG)
500           printf("%s: write_bios() failed; rom addr=0x%x\n",
501            NAME_UNIT, addr);
502         return;
503         }
504       }
505     read_data = read_bios(sc, addr);
506     if (read_data == data) break;
507     }
508   }
509
510 /* IOCTL SYSCALL: can sleep. */
511 static void
512 erase_bios(softc_t *sc)
513   {
514   unsigned char read_data;
515
516   /* This sequence enables erasing: */
517   write_bios_phys(sc, 0x5555, 0xAA);
518   write_bios_phys(sc, 0x2AAA, 0x55);
519   write_bios_phys(sc, 0x5555, 0x80);
520   write_bios_phys(sc, 0x5555, 0xAA);
521   write_bios_phys(sc, 0x2AAA, 0x55);
522   write_bios_phys(sc, 0x5555, 0x10);
523
524   /* Wait for the erase operation to complete. */
525   for (;;) /* interruptable syscall */
526     {
527     for (;;)
528       {
529       read_data = read_bios(sc, 0);
530       if (read_data & 0x80) break;
531       if (read_data & 0x20)
532         {  /* Data sheet says read it again. */
533         read_data = read_bios(sc, 0);
534         if (read_data & 0x80) break;
535         if (DRIVER_DEBUG)
536           printf("%s: erase_bios() failed\n", NAME_UNIT);
537         return;
538         }
539       }
540     read_data = read_bios(sc, 0);
541     if (read_data == 0xFF) break;
542     }
543   }
544
545 /* MDIO is 3-stated between tranactions. */
546 /* MDIO is set up before the RISING edge of MDC; MDC is parked low. */
547 static void
548 shift_mii_bits(softc_t *sc, u_int32_t data, u_int32_t len)
549   {
550   u_int32_t csr = READ_CSR(TLP_SROM_MII);
551   for (; len>0; len--)
552     {  /* MSB first */
553     if (data & (1<<(len-1)))
554       csr |=  TLP_MII_MDOUT; /* MDOUT setup */
555     else
556       csr &= ~TLP_MII_MDOUT; /* MDOUT setup */
557     WRITE_CSR(TLP_SROM_MII, csr);
558     csr |=  TLP_MII_MDC;     /* MDC rising edge */
559     WRITE_CSR(TLP_SROM_MII, csr);
560     csr &= ~TLP_MII_MDC;     /* MDC falling edge */
561     WRITE_CSR(TLP_SROM_MII, csr);
562     }
563   }
564
565 /* The specification for the MII is IEEE Std 802.3 clause 22. */
566 /* MDIO is sampled on the RISING edge of MDC; MDC is parked low. */
567 static u_int16_t
568 read_mii(softc_t *sc, u_int8_t regad)
569   {
570   int i;
571   u_int32_t csr;
572   u_int16_t data = 0;
573  
574   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOUT);
575
576   shift_mii_bits(sc, 0xFFFFF, 20);      /* preamble */
577   shift_mii_bits(sc, 0xFFFFF, 20);      /* preamble */
578   shift_mii_bits(sc, 1, 2);             /* start symbol */
579   shift_mii_bits(sc, 2, 2);             /* read op */
580   shift_mii_bits(sc, 0, 5);             /* phyad=0 */
581   shift_mii_bits(sc, regad, 5);         /* regad */
582   csr = READ_CSR(TLP_SROM_MII);
583   csr |= TLP_MII_MDOE;
584   WRITE_CSR(TLP_SROM_MII, csr);
585   shift_mii_bits(sc, 0, 2);             /* turn-around */
586   for (i=15; i>=0; i--)                 /* data */
587     {  /* MSB first */
588     csr = READ_CSR(TLP_SROM_MII);       /* MDIN sampled */
589     data = (data<<1) | ((csr & TLP_MII_MDIN) ? 1:0);
590     csr |=  TLP_MII_MDC;                /* MDC rising edge */
591     WRITE_CSR(TLP_SROM_MII, csr);
592     csr &= ~TLP_MII_MDC;                /* MDC falling edge */
593     WRITE_CSR(TLP_SROM_MII, csr);
594     }
595   return data;
596   }
597
598 static void
599 write_mii(softc_t *sc, u_int8_t regad, u_int16_t data)
600   {
601   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOUT);
602   shift_mii_bits(sc, 0xFFFFF, 20);      /* preamble */
603   shift_mii_bits(sc, 0xFFFFF, 20);      /* preamble */
604   shift_mii_bits(sc, 1, 2);             /* start symbol */
605   shift_mii_bits(sc, 1, 2);             /* write op */
606   shift_mii_bits(sc, 0, 5);             /* phyad=0 */
607   shift_mii_bits(sc, regad, 5);         /* regad */
608   shift_mii_bits(sc, 2, 2);             /* turn-around */
609   shift_mii_bits(sc, data, 16);         /* data */
610   WRITE_CSR(TLP_SROM_MII, TLP_MII_MDOE);
611   if (regad == 16) sc->led_state = data; /* a small optimization */
612   }
613
614 static void
615 set_mii16_bits(softc_t *sc, u_int16_t bits)
616   {
617   u_int16_t mii16 = read_mii(sc, 16);
618   mii16 |= bits;
619   write_mii(sc, 16, mii16);
620   }
621
622 static void
623 clr_mii16_bits(softc_t *sc, u_int16_t bits)
624   {
625   u_int16_t mii16 = read_mii(sc, 16);
626   mii16 &= ~bits;
627   write_mii(sc, 16, mii16);
628   }
629
630 static void
631 set_mii17_bits(softc_t *sc, u_int16_t bits)
632   {
633   u_int16_t mii17 = read_mii(sc, 17);
634   mii17 |= bits;
635   write_mii(sc, 17, mii17);
636   }
637
638 static void
639 clr_mii17_bits(softc_t *sc, u_int16_t bits)
640   {
641   u_int16_t mii17 = read_mii(sc, 17);
642   mii17 &= ~bits;
643   write_mii(sc, 17, mii17);
644   }
645
646 /*
647  * Watchdog code is more readable if it refreshes LEDs
648  *  once a second whether they need it or not.
649  * But MII refs take 150 uSecs each, so remember the last value
650  *  written to MII16 and avoid LED writes that do nothing.
651  */
652
653 static void
654 led_off(softc_t *sc, u_int16_t led)
655   {
656   if ((led & sc->led_state) == led) return;
657   set_mii16_bits(sc, led);
658   }
659
660 static void
661 led_on(softc_t *sc, u_int16_t led)
662   {
663   if ((led & sc->led_state) == 0) return;
664   clr_mii16_bits(sc, led);
665   }
666
667 static void
668 led_inv(softc_t *sc, u_int16_t led)
669   {
670   u_int16_t mii16 = read_mii(sc, 16);
671   mii16 ^= led;
672   write_mii(sc, 16, mii16);
673   }
674
675 /*
676  * T1 & T3 framer registers are accessed through MII regs 17 & 18.
677  * Write the address to MII reg 17 then R/W data through MII reg 18.
678  * The hardware interface is an Intel-style 8-bit muxed A/D bus.
679  */
680 static void
681 write_framer(softc_t *sc, u_int16_t addr, u_int8_t data)
682   {
683   write_mii(sc, 17, addr);
684   write_mii(sc, 18, data);
685   }
686
687 static u_int8_t
688 read_framer(softc_t *sc, u_int16_t addr)
689   {
690   write_mii(sc, 17, addr);
691   return (u_int8_t)read_mii(sc, 18);
692   }
693
694 /* Tulip's hardware implementation of General Purpose IO
695  *   (GPIO) pins makes life difficult for software.
696  * Bits 7-0 in the Tulip GPIO CSR are used for two purposes
697  *   depending on the state of bit 8.
698  * If bit 8 is 0 then bits 7-0 are "data" bits.
699  * If bit 8 is 1 then bits 7-0 are "direction" bits.
700  * If a direction bit is one, the data bit is an output.
701  * The problem is that the direction bits are WRITE-ONLY.
702  * Software must remember the direction bits in a shadow copy.
703  * (sc->gpio_dir) in order to change some but not all of the bits.
704  * All accesses to the Tulip GPIO register use these five procedures.
705  */
706
707 static void
708 make_gpio_input(softc_t *sc, u_int32_t bits)
709   {
710   sc->gpio_dir &= ~bits;
711   WRITE_CSR(TLP_GPIO, TLP_GPIO_DIR | (sc->gpio_dir));
712   }
713
714 static void
715 make_gpio_output(softc_t *sc, u_int32_t bits)
716   {
717   sc->gpio_dir |= bits;
718   WRITE_CSR(TLP_GPIO, TLP_GPIO_DIR | (sc->gpio_dir));
719   }
720
721 static u_int32_t
722 read_gpio(softc_t *sc)
723   {
724   return READ_CSR(TLP_GPIO);
725   }
726
727 static void
728 set_gpio_bits(softc_t *sc, u_int32_t bits)
729   {
730   WRITE_CSR(TLP_GPIO, (read_gpio(sc) |  bits) & 0xFF);
731   }
732
733 static void
734 clr_gpio_bits(softc_t *sc, u_int32_t bits)
735   {
736   WRITE_CSR(TLP_GPIO, (read_gpio(sc) & ~bits) & 0xFF);
737   }
738
739 /* Reset ALL of the flip-flops in the gate array to zero. */
740 /* This does NOT change the gate array programming. */
741 /* Called during initialization so it must not sleep. */
742 static void
743 reset_xilinx(softc_t *sc)
744   {
745   /* Drive RESET low to force initialization. */
746   clr_gpio_bits(sc, GPIO_RESET);
747   make_gpio_output(sc, GPIO_RESET);
748
749   /* Hold RESET low for more than 10 uSec. */
750   DELAY(50);
751
752   /* Done with RESET; make it an input. */
753   make_gpio_input(sc,  GPIO_RESET);
754   }
755
756 /* Load Xilinx gate array program from on-board rom. */
757 /* This changes the gate array programming. */
758 /* IOCTL SYSCALL: can sleep. */
759 static void
760 load_xilinx_from_rom(softc_t *sc)
761   {
762   int i;
763
764   /* Drive MODE low to load from ROM rather than GPIO. */
765   clr_gpio_bits(sc, GPIO_MODE);
766   make_gpio_output(sc, GPIO_MODE);
767
768   /* Drive DP & RESET low to force configuration. */
769   clr_gpio_bits(sc, GPIO_RESET | GPIO_DP);
770   make_gpio_output(sc, GPIO_RESET | GPIO_DP);
771
772   /* Hold RESET & DP low for more than 10 uSec. */
773   DELAY(50);
774
775   /* Done with RESET & DP; make them inputs. */
776   make_gpio_input(sc, GPIO_DP | GPIO_RESET);
777
778   /* BUSY-WAIT for Xilinx chip to configure itself from ROM bits. */
779   for (i=0; i<100; i++) /* 1 sec max delay */
780     if ((read_gpio(sc) & GPIO_DP) == 0) SLEEP(10000);
781
782   /* Done with MODE; make it an input. */
783   make_gpio_input(sc, GPIO_MODE);
784   }
785
786 /* Load the Xilinx gate array program from userland bits. */
787 /* This changes the gate array programming. */
788 /* IOCTL SYSCALL: can sleep. */
789 static int
790 load_xilinx_from_file(softc_t *sc, char *addr, u_int32_t len)
791   {
792   char *data;
793   int i, j, error;
794
795   /* Get some pages to hold the Xilinx bits; biggest file is < 6 KB. */
796   if (len > 8192) return EFBIG;  /* too big */
797   data = malloc(len, M_DEVBUF, M_WAITOK);
798   if (data == NULL) return ENOMEM;
799
800   /* Copy the Xilinx bits from userland. */
801   if ((error = copyin(addr, data, len)))
802     {
803     free(data, M_DEVBUF);
804     return error;
805     }
806
807   /* Drive MODE high to load from GPIO rather than ROM. */
808   set_gpio_bits(sc, GPIO_MODE);
809   make_gpio_output(sc, GPIO_MODE);
810
811   /* Drive DP & RESET low to force configuration. */
812   clr_gpio_bits(sc, GPIO_RESET | GPIO_DP);
813   make_gpio_output(sc, GPIO_RESET | GPIO_DP);
814
815   /* Hold RESET & DP low for more than 10 uSec. */
816   DELAY(50);
817   
818   /* Done with RESET & DP; make them inputs. */
819   make_gpio_input(sc, GPIO_RESET | GPIO_DP);
820
821   /* BUSY-WAIT for Xilinx chip to clear its config memory. */
822   make_gpio_input(sc, GPIO_INIT);
823   for (i=0; i<10000; i++) /* 1 sec max delay */
824     if ((read_gpio(sc) & GPIO_INIT)==0) SLEEP(10000);
825
826   /* Configure CLK and DATA as outputs. */
827   set_gpio_bits(sc, GPIO_CLK);  /* park CLK high */
828   make_gpio_output(sc, GPIO_CLK | GPIO_DATA);
829
830   /* Write bits to Xilinx; CLK is parked HIGH. */
831   /* DATA is set up before the RISING edge of CLK. */
832   for (i=0; i<len; i++)
833     for (j=0; j<8; j++)
834       {  /* LSB first */
835       if ((data[i] & (1<<j)) != 0)
836         set_gpio_bits(sc, GPIO_DATA); /* DATA setup */
837       else
838         clr_gpio_bits(sc, GPIO_DATA); /* DATA setup */
839       clr_gpio_bits(sc, GPIO_CLK); /* CLK falling edge */
840       set_gpio_bits(sc, GPIO_CLK); /* CLK rising edge */
841       }
842
843   /* Stop driving all Xilinx-related signals. */
844   /* Pullup and pulldown resistors take over. */
845   make_gpio_input(sc, GPIO_CLK | GPIO_DATA | GPIO_MODE);
846
847   free(data, M_DEVBUF);
848   return 0;
849   }
850
851 /* Write fragments of a command into the synthesized oscillator. */
852 /* DATA is set up before the RISING edge of CLK.  CLK is parked low. */
853 static void
854 shift_synth_bits(softc_t *sc, u_int32_t data, u_int32_t len)
855   {
856   int i;
857
858   for (i=0; i<len; i++)
859     { /* LSB first */
860     if ((data & (1<<i)) != 0)
861       set_gpio_bits(sc, GPIO_DATA); /* DATA setup */
862     else
863       clr_gpio_bits(sc, GPIO_DATA); /* DATA setup */
864     set_gpio_bits(sc, GPIO_CLK);    /* CLK rising edge */
865     clr_gpio_bits(sc, GPIO_CLK);    /* CLK falling edge */
866     }
867   }
868
869 /* Write a command to the synthesized oscillator on SSI and HSSIc. */
870 static void
871 write_synth(softc_t *sc, struct synth *synth)
872   {
873   /* SSI cards have a programmable prescaler */
874   if (sc->status.card_type == TLP_CSID_SSI)
875     {
876     if (synth->prescale == 9) /* divide by 512 */
877       set_mii17_bits(sc, MII17_SSI_PRESCALE);
878     else                      /* divide by  32 */
879       clr_mii17_bits(sc, MII17_SSI_PRESCALE);
880     }
881
882   clr_gpio_bits(sc,    GPIO_DATA | GPIO_CLK);
883   make_gpio_output(sc, GPIO_DATA | GPIO_CLK);
884
885   /* SYNTH is a low-true chip enable for the AV9110 chip. */
886   set_gpio_bits(sc,    GPIO_SSI_SYNTH);
887   make_gpio_output(sc, GPIO_SSI_SYNTH);
888   clr_gpio_bits(sc,    GPIO_SSI_SYNTH);
889
890   /* Serially shift the command into the AV9110 chip. */
891   shift_synth_bits(sc, synth->n, 7);
892   shift_synth_bits(sc, synth->m, 7);
893   shift_synth_bits(sc, synth->v, 1);
894   shift_synth_bits(sc, synth->x, 2);
895   shift_synth_bits(sc, synth->r, 2);
896   shift_synth_bits(sc, 0x16, 5); /* enable clk/x output */
897
898   /* SYNTH (chip enable) going high ends the command. */
899   set_gpio_bits(sc,   GPIO_SSI_SYNTH);
900   make_gpio_input(sc, GPIO_SSI_SYNTH);
901
902   /* Stop driving serial-related signals; pullups/pulldowns take over. */
903   make_gpio_input(sc, GPIO_DATA | GPIO_CLK);
904
905   /* remember the new synthesizer parameters */
906   if (&sc->config.synth != synth) sc->config.synth = *synth;
907   }
908
909 /* Write a command to the DAC controlling the VCXO on some T3 adapters. */
910 /* The DAC is a TI-TLV5636: 12-bit resolution and a serial interface. */
911 /* DATA is set up before the FALLING edge of CLK.  CLK is parked HIGH. */
912 static void
913 write_dac(softc_t *sc, u_int16_t data)
914   {
915   int i;
916
917   /* Prepare to use DATA and CLK. */
918   set_gpio_bits(sc,    GPIO_DATA | GPIO_CLK);
919   make_gpio_output(sc, GPIO_DATA | GPIO_CLK);
920
921   /* High-to-low transition prepares DAC for new value. */
922   set_gpio_bits(sc,    GPIO_T3_DAC);
923   make_gpio_output(sc, GPIO_T3_DAC);
924   clr_gpio_bits(sc,    GPIO_T3_DAC);
925
926   /* Serially shift command bits into DAC. */
927   for (i=0; i<16; i++)
928     { /* MSB first */
929     if ((data & (1<<(15-i))) != 0)
930       set_gpio_bits(sc, GPIO_DATA); /* DATA setup */
931     else
932       clr_gpio_bits(sc, GPIO_DATA); /* DATA setup */
933     clr_gpio_bits(sc, GPIO_CLK);    /* CLK falling edge */
934     set_gpio_bits(sc, GPIO_CLK);    /* CLK rising edge */
935     }
936
937   /* Done with DAC; make it an input; loads new value into DAC. */
938   set_gpio_bits(sc,   GPIO_T3_DAC);
939   make_gpio_input(sc, GPIO_T3_DAC);
940
941   /* Stop driving serial-related signals; pullups/pulldowns take over. */
942   make_gpio_input(sc, GPIO_DATA | GPIO_CLK);
943   }
944
945 /* begin HSSI card code */
946
947 /* Must not sleep. */
948 static void
949 hssi_config(softc_t *sc)
950   {
951   if (sc->status.card_type == 0)
952     { /* defaults */
953     sc->status.card_type  = READ_PCI_CFG(sc, TLP_CSID);
954     sc->config.crc_len    = CFG_CRC_16;
955     sc->config.loop_back  = CFG_LOOP_NONE;
956     sc->config.tx_clk_src = CFG_CLKMUX_ST;
957     sc->config.dte_dce    = CFG_DTE;
958     sc->config.synth.n    = 52; /* 52.000 Mbs */
959     sc->config.synth.m    = 5;
960     sc->config.synth.v    = 0;
961     sc->config.synth.x    = 0;
962     sc->config.synth.r    = 0;
963     sc->config.synth.prescale = 2;
964     }
965
966   /* set CRC length */
967   if (sc->config.crc_len == CFG_CRC_32)
968     set_mii16_bits(sc, MII16_HSSI_CRC32);
969   else
970     clr_mii16_bits(sc, MII16_HSSI_CRC32);
971
972   /* Assert pin LA in HSSI conn: ask modem for local loop. */
973   if (sc->config.loop_back == CFG_LOOP_LL)
974     set_mii16_bits(sc, MII16_HSSI_LA);
975   else
976     clr_mii16_bits(sc, MII16_HSSI_LA);
977
978   /* Assert pin LB in HSSI conn: ask modem for remote loop. */
979   if (sc->config.loop_back == CFG_LOOP_RL)
980     set_mii16_bits(sc, MII16_HSSI_LB);
981   else
982     clr_mii16_bits(sc, MII16_HSSI_LB);
983
984   if (sc->status.card_type == TLP_CSID_HSSI)
985     {
986     /* set TXCLK src */
987     if (sc->config.tx_clk_src == CFG_CLKMUX_ST)
988       set_gpio_bits(sc, GPIO_HSSI_TXCLK);
989     else
990       clr_gpio_bits(sc, GPIO_HSSI_TXCLK);
991     make_gpio_output(sc, GPIO_HSSI_TXCLK);
992     }
993   else if (sc->status.card_type == TLP_CSID_HSSIc)
994     {  /* cPCI HSSI rev C has extra features */
995     /* Set TXCLK source. */
996     u_int16_t mii16 = read_mii(sc, 16);
997     mii16 &= ~MII16_HSSI_CLKMUX;
998     mii16 |= (sc->config.tx_clk_src&3)<<13;
999     write_mii(sc, 16, mii16);
1000
1001     /* cPCI HSSI implements loopback towards the net. */
1002     if (sc->config.loop_back == CFG_LOOP_LINE)
1003       set_mii16_bits(sc, MII16_HSSI_LOOP);
1004     else
1005       clr_mii16_bits(sc, MII16_HSSI_LOOP);
1006
1007     /* Set DTE/DCE mode. */
1008     if (sc->config.dte_dce == CFG_DCE)
1009       set_gpio_bits(sc, GPIO_HSSI_DCE);
1010     else
1011       clr_gpio_bits(sc, GPIO_HSSI_DCE);
1012     make_gpio_output(sc, GPIO_HSSI_DCE);
1013
1014     /* Program the synthesized oscillator. */
1015     write_synth(sc, &sc->config.synth);
1016     }
1017   }
1018
1019 static void
1020 hssi_ident(softc_t *sc)
1021   {
1022   }
1023
1024 /* Called once a second; must not sleep. */
1025 static int
1026 hssi_watchdog(softc_t *sc)
1027   {
1028   u_int16_t mii16 = read_mii(sc, 16) & MII16_HSSI_MODEM;
1029   int link_status = STATUS_UP;
1030
1031   led_inv(sc, MII16_HSSI_LED_UL);  /* Software is alive. */
1032   led_on(sc, MII16_HSSI_LED_LL);  /* always on (SSI cable) */
1033
1034   /* Check the transmit clock. */
1035   if (sc->status.tx_speed == 0)
1036     {
1037     led_on(sc, MII16_HSSI_LED_UR);
1038     link_status = STATUS_DOWN;
1039     }
1040   else
1041     led_off(sc, MII16_HSSI_LED_UR);
1042
1043   /* Is the modem ready? */
1044   if ((mii16 & MII16_HSSI_CA) == 0)
1045     {
1046     led_off(sc, MII16_HSSI_LED_LR);
1047     link_status = STATUS_DOWN;
1048     }
1049   else
1050     led_on(sc, MII16_HSSI_LED_LR);
1051
1052   /* Print the modem control signals if they changed. */
1053   if ((DRIVER_DEBUG) && (mii16 != sc->last_mii16))
1054     {
1055     char *on = "ON ", *off = "OFF";
1056     printf("%s: TA=%s CA=%s LA=%s LB=%s LC=%s TM=%s\n", NAME_UNIT,
1057      (mii16 & MII16_HSSI_TA) ? on : off,
1058      (mii16 & MII16_HSSI_CA) ? on : off,
1059      (mii16 & MII16_HSSI_LA) ? on : off,
1060      (mii16 & MII16_HSSI_LB) ? on : off,
1061      (mii16 & MII16_HSSI_LC) ? on : off,
1062      (mii16 & MII16_HSSI_TM) ? on : off);
1063     }
1064
1065   /* SNMP one-second-report */
1066   sc->status.snmp.hssi.sigs = mii16 & MII16_HSSI_MODEM;
1067
1068   /* Remember this state until next time. */
1069   sc->last_mii16 = mii16;
1070
1071   /* If a loop back is in effect, link status is UP */
1072   if (sc->config.loop_back != CFG_LOOP_NONE)
1073     link_status = STATUS_UP;
1074
1075   return link_status;
1076   }
1077
1078 /* IOCTL SYSCALL: can sleep (but doesn't). */
1079 static int
1080 hssi_ioctl(softc_t *sc, struct ioctl *ioctl)
1081   {
1082   int error = 0;
1083
1084   if (ioctl->cmd == IOCTL_SNMP_SIGS)
1085     {
1086     u_int16_t mii16 = read_mii(sc, 16);
1087     mii16 &= ~MII16_HSSI_MODEM;
1088     mii16 |= (MII16_HSSI_MODEM & ioctl->data);
1089     write_mii(sc, 16, mii16);
1090     }
1091   else if (ioctl->cmd == IOCTL_SET_STATUS)
1092     {
1093     if (ioctl->data != 0)
1094       set_mii16_bits(sc, MII16_HSSI_TA);
1095     else
1096       clr_mii16_bits(sc, MII16_HSSI_TA);
1097     }
1098   else
1099     error = EINVAL;
1100
1101   return error;
1102   }
1103
1104 /* begin DS3 card code */
1105
1106 /* Must not sleep. */
1107 static void
1108 t3_config(softc_t *sc)
1109   {
1110   int i;
1111   u_int8_t ctl1;
1112
1113   if (sc->status.card_type == 0)
1114     { /* defaults */
1115     sc->status.card_type  = TLP_CSID_T3;
1116     sc->config.crc_len    = CFG_CRC_16;
1117     sc->config.loop_back  = CFG_LOOP_NONE;
1118     sc->config.format     = CFG_FORMAT_T3CPAR;
1119     sc->config.cable_len  = 10; /* meters */
1120     sc->config.scrambler  = CFG_SCRAM_DL_KEN;
1121     sc->config.tx_clk_src = CFG_CLKMUX_INT;
1122
1123     /* Center the VCXO -- get within 20 PPM of 44736000. */
1124     write_dac(sc, 0x9002); /* set Vref = 2.048 volts */
1125     write_dac(sc, 2048); /* range is 0..4095 */
1126     }
1127
1128   /* Set cable length. */
1129   if (sc->config.cable_len > 30)
1130     clr_mii16_bits(sc, MII16_DS3_ZERO);
1131   else
1132     set_mii16_bits(sc, MII16_DS3_ZERO);
1133
1134   /* Set payload scrambler polynomial. */
1135   if (sc->config.scrambler == CFG_SCRAM_LARS)
1136     set_mii16_bits(sc, MII16_DS3_POLY);
1137   else
1138     clr_mii16_bits(sc, MII16_DS3_POLY);
1139
1140   /* Set payload scrambler on/off. */
1141   if (sc->config.scrambler == CFG_SCRAM_OFF)
1142     clr_mii16_bits(sc, MII16_DS3_SCRAM);
1143   else
1144     set_mii16_bits(sc, MII16_DS3_SCRAM);
1145
1146   /* Set CRC length. */
1147   if (sc->config.crc_len == CFG_CRC_32)
1148     set_mii16_bits(sc, MII16_DS3_CRC32);
1149   else
1150     clr_mii16_bits(sc, MII16_DS3_CRC32);
1151
1152   /* Loopback towards host thru the line interface. */
1153   if (sc->config.loop_back == CFG_LOOP_OTHER)
1154     set_mii16_bits(sc, MII16_DS3_TRLBK);
1155   else
1156     clr_mii16_bits(sc, MII16_DS3_TRLBK);
1157
1158   /* Loopback towards network thru the line interface. */
1159   if (sc->config.loop_back == CFG_LOOP_LINE)
1160     set_mii16_bits(sc, MII16_DS3_LNLBK);
1161   else if (sc->config.loop_back == CFG_LOOP_DUAL)
1162     set_mii16_bits(sc, MII16_DS3_LNLBK);
1163   else
1164     clr_mii16_bits(sc, MII16_DS3_LNLBK);
1165
1166   /* Configure T3 framer chip; write EVERY writeable register. */
1167   ctl1 = CTL1_SER | CTL1_XTX;
1168   if (sc->config.loop_back == CFG_LOOP_INWARD) ctl1 |= CTL1_3LOOP;
1169   if (sc->config.loop_back == CFG_LOOP_DUAL)   ctl1 |= CTL1_3LOOP;
1170   if (sc->config.format == CFG_FORMAT_T3M13)   ctl1 |= CTL1_M13MODE;
1171   write_framer(sc, T3CSR_CTL1,     ctl1);
1172   write_framer(sc, T3CSR_TX_FEAC,  CTL5_EMODE);
1173   write_framer(sc, T3CSR_CTL8,     CTL8_FBEC);
1174   write_framer(sc, T3CSR_CTL12,    CTL12_DLCB1 | CTL12_C21 | CTL12_MCB1);
1175   write_framer(sc, T3CSR_DBL_FEAC, 0);
1176   write_framer(sc, T3CSR_CTL14,    CTL14_RGCEN | CTL14_TGCEN);
1177   write_framer(sc, T3CSR_INTEN,    0);
1178   write_framer(sc, T3CSR_CTL20,    CTL20_CVEN);
1179
1180   /* Clear error counters and latched error bits */
1181   /*  that may have happened while initializing. */
1182   for (i=0; i<21; i++) read_framer(sc, i);
1183   }
1184
1185 static void
1186 t3_ident(softc_t *sc)
1187   {
1188   printf(", TXC03401 rev B");
1189   }
1190
1191 /* Called once a second; must not sleep. */
1192 static int
1193 t3_watchdog(softc_t *sc)
1194   {
1195   u_int16_t CV;
1196   u_int8_t CERR, PERR, MERR, FERR, FEBE;
1197   u_int8_t ctl1, stat16, feac;
1198   int link_status = STATUS_UP;
1199   u_int16_t mii16;
1200
1201   /* Read the alarm registers. */
1202   ctl1   = read_framer(sc, T3CSR_CTL1);
1203   stat16 = read_framer(sc, T3CSR_STAT16);
1204   mii16  = read_mii(sc, 16);
1205
1206   /* Always ignore the RTLOC alarm bit. */
1207   stat16 &= ~STAT16_RTLOC;
1208
1209   /* Software is alive. */
1210   led_inv(sc, MII16_DS3_LED_GRN);
1211
1212   /* Receiving Alarm Indication Signal (AIS). */
1213   if ((stat16 & STAT16_RAIS) != 0) /* receiving ais */
1214     led_on(sc, MII16_DS3_LED_BLU);
1215   else if (ctl1 & CTL1_TXAIS) /* sending ais */
1216     led_inv(sc, MII16_DS3_LED_BLU);
1217   else
1218     led_off(sc, MII16_DS3_LED_BLU);
1219
1220   /* Receiving Remote Alarm Indication (RAI). */
1221   if ((stat16 & STAT16_XERR) != 0) /* receiving rai */
1222     led_on(sc, MII16_DS3_LED_YEL);
1223   else if ((ctl1 & CTL1_XTX) == 0) /* sending rai */
1224     led_inv(sc, MII16_DS3_LED_YEL);
1225   else
1226     led_off(sc, MII16_DS3_LED_YEL);
1227
1228   /* If certain status bits are set then the link is 'down'. */
1229   /* The bad bits are: rxlos rxoof rxais rxidl xerr. */
1230   if ((stat16 & ~(STAT16_FEAC | STAT16_SEF)) != 0)
1231     link_status = STATUS_DOWN;
1232
1233   /* Declare local Red Alarm if the link is down. */
1234   if (link_status == STATUS_DOWN)
1235     led_on(sc, MII16_DS3_LED_RED);
1236   else if (sc->loop_timer != 0) /* loopback is active */
1237     led_inv(sc, MII16_DS3_LED_RED);
1238   else
1239     led_off(sc, MII16_DS3_LED_RED);
1240
1241   /* Print latched error bits if they changed. */
1242   if ((DRIVER_DEBUG) && ((stat16 & ~STAT16_FEAC) != sc->last_stat16))
1243     {
1244     char *on = "ON ", *off = "OFF";
1245     printf("%s: RLOS=%s ROOF=%s RAIS=%s RIDL=%s SEF=%s XERR=%s\n",
1246      NAME_UNIT,
1247      (stat16 & STAT16_RLOS) ? on : off,
1248      (stat16 & STAT16_ROOF) ? on : off,
1249      (stat16 & STAT16_RAIS) ? on : off,
1250      (stat16 & STAT16_RIDL) ? on : off,
1251      (stat16 & STAT16_SEF)  ? on : off,
1252      (stat16 & STAT16_XERR) ? on : off);
1253     }
1254
1255   /* Check and print error counters if non-zero. */
1256   CV   = read_framer(sc, T3CSR_CVHI)<<8;
1257   CV  += read_framer(sc, T3CSR_CVLO);
1258   PERR = read_framer(sc, T3CSR_PERR);
1259   CERR = read_framer(sc, T3CSR_CERR);
1260   FERR = read_framer(sc, T3CSR_FERR);
1261   MERR = read_framer(sc, T3CSR_MERR);
1262   FEBE = read_framer(sc, T3CSR_FEBE);
1263
1264   /* CV is invalid during LOS. */
1265   if ((stat16 & STAT16_RLOS)!=0) CV = 0;
1266   /* CERR & FEBE are invalid in M13 mode */
1267   if (sc->config.format == CFG_FORMAT_T3M13) CERR = FEBE = 0;
1268   /* FEBE is invalid during AIS. */
1269   if ((stat16 & STAT16_RAIS)!=0) FEBE = 0;
1270   if (DRIVER_DEBUG && (CV || PERR || CERR || FERR || MERR || FEBE))
1271     printf("%s: CV=%u PERR=%u CERR=%u FERR=%u MERR=%u FEBE=%u\n",
1272      NAME_UNIT, CV,   PERR,   CERR,   FERR,   MERR,   FEBE);
1273
1274   /* Driver keeps crude link-level error counters (SNMP is better). */
1275   sc->status.cntrs.lcv_errs  += CV;
1276   sc->status.cntrs.par_errs  += PERR;
1277   sc->status.cntrs.cpar_errs += CERR;
1278   sc->status.cntrs.frm_errs  += FERR;
1279   sc->status.cntrs.mfrm_errs += MERR;
1280   sc->status.cntrs.febe_errs += FEBE;
1281
1282   /* Check for FEAC messages (FEAC not defined in M13 mode). */
1283   if (FORMAT_T3CPAR && (stat16 & STAT16_FEAC)) do
1284     {
1285     feac = read_framer(sc, T3CSR_FEAC_STK);
1286     if ((feac & FEAC_STK_VALID)==0) break;
1287     /* Ignore RxFEACs while a far end loopback has been requested. */
1288     if ((sc->status.snmp.t3.line & TLOOP_FAR_LINE)!=0) continue;
1289     switch (feac & FEAC_STK_FEAC)
1290       {
1291       case T3BOP_LINE_UP:   break;
1292       case T3BOP_LINE_DOWN: break;
1293       case T3BOP_LOOP_DS3:
1294         {
1295         if (sc->last_FEAC == T3BOP_LINE_DOWN)
1296           {
1297           if (DRIVER_DEBUG)
1298             printf("%s: Received a 'line loopback deactivate' FEAC msg\n", NAME_UNIT);
1299           clr_mii16_bits(sc, MII16_DS3_LNLBK);
1300           sc->loop_timer = 0;
1301           }
1302         if (sc->last_FEAC == T3BOP_LINE_UP)
1303           {
1304           if (DRIVER_DEBUG)
1305             printf("%s: Received a 'line loopback activate' FEAC msg\n", NAME_UNIT);
1306           set_mii16_bits(sc, MII16_DS3_LNLBK);
1307           sc->loop_timer = 300;
1308           }
1309         break;
1310         }
1311       case T3BOP_OOF:
1312         {
1313         if (DRIVER_DEBUG)
1314           printf("%s: Received a 'far end LOF' FEAC msg\n", NAME_UNIT);
1315         break;
1316         }
1317       case T3BOP_IDLE:
1318         {
1319         if (DRIVER_DEBUG)
1320           printf("%s: Received a 'far end IDL' FEAC msg\n", NAME_UNIT);
1321         break;
1322         }
1323       case T3BOP_AIS:
1324         {
1325         if (DRIVER_DEBUG)
1326           printf("%s: Received a 'far end AIS' FEAC msg\n", NAME_UNIT);
1327         break;
1328         }
1329       case T3BOP_LOS:
1330         {
1331         if (DRIVER_DEBUG)
1332           printf("%s: Received a 'far end LOS' FEAC msg\n", NAME_UNIT);
1333         break;
1334         }
1335       default:
1336         {
1337         if (DRIVER_DEBUG)
1338           printf("%s: Received a 'type 0x%02X' FEAC msg\n", NAME_UNIT, feac & FEAC_STK_FEAC);
1339         break;
1340         }
1341       }
1342     sc->last_FEAC = feac & FEAC_STK_FEAC;
1343     } while ((feac & FEAC_STK_MORE) != 0);
1344   stat16 &= ~STAT16_FEAC;
1345
1346   /* Send Service-Affecting priority FEAC messages */
1347   if (((sc->last_stat16 ^ stat16) & 0xF0) && (FORMAT_T3CPAR))
1348     {
1349     /* Transmit continuous FEACs */
1350     write_framer(sc, T3CSR_CTL14,
1351      read_framer(sc, T3CSR_CTL14) & ~CTL14_FEAC10);
1352     if      ((stat16 & STAT16_RLOS)!=0)
1353       write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_LOS);
1354     else if ((stat16 & STAT16_ROOF)!=0)
1355       write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_OOF);
1356     else if ((stat16 & STAT16_RAIS)!=0)
1357       write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_AIS);
1358     else if ((stat16 & STAT16_RIDL)!=0)
1359       write_framer(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_IDLE);
1360     else
1361       write_framer(sc, T3CSR_TX_FEAC, CTL5_EMODE);
1362     }
1363
1364   /* Start sending RAI, Remote Alarm Indication. */
1365   if (((stat16 & STAT16_ROOF)!=0) && ((stat16 & STAT16_RLOS)==0) &&
1366    ((sc->last_stat16 & STAT16_ROOF)==0))
1367     write_framer(sc, T3CSR_CTL1, ctl1 &= ~CTL1_XTX);
1368   /* Stop sending RAI, Remote Alarm Indication. */
1369   else if (((stat16 & STAT16_ROOF)==0) && ((sc->last_stat16 & STAT16_ROOF)!=0))
1370     write_framer(sc, T3CSR_CTL1, ctl1 |=  CTL1_XTX);
1371
1372   /* Start sending AIS, Alarm Indication Signal */
1373   if (((stat16 & STAT16_RLOS)!=0) && ((sc->last_stat16 & STAT16_RLOS)==0))
1374     {
1375     set_mii16_bits(sc, MII16_DS3_FRAME);
1376     write_framer(sc, T3CSR_CTL1, ctl1 |  CTL1_TXAIS);
1377     }
1378   /* Stop sending AIS, Alarm Indication Signal */
1379   else if (((stat16 & STAT16_RLOS)==0) && ((sc->last_stat16 & STAT16_RLOS)!=0))
1380     {
1381     clr_mii16_bits(sc, MII16_DS3_FRAME);
1382     write_framer(sc, T3CSR_CTL1, ctl1 & ~CTL1_TXAIS);
1383     }
1384
1385   /* Time out loopback requests. */
1386   if (sc->loop_timer != 0)
1387     if (--sc->loop_timer == 0)
1388       if ((mii16 & MII16_DS3_LNLBK)!=0)
1389         {
1390         if (DRIVER_DEBUG)
1391           printf("%s: Timeout: Loop Down after 300 seconds\n", NAME_UNIT);
1392         clr_mii16_bits(sc, MII16_DS3_LNLBK); /* line loopback off */
1393         }
1394
1395   /* SNMP error counters */
1396   sc->status.snmp.t3.lcv  = CV;
1397   sc->status.snmp.t3.pcv  = PERR;
1398   sc->status.snmp.t3.ccv  = CERR;
1399   sc->status.snmp.t3.febe = FEBE;
1400
1401   /* SNMP Line Status */
1402   sc->status.snmp.t3.line = 0;
1403   if ((ctl1  & CTL1_XTX)==0)   sc->status.snmp.t3.line |= TLINE_TX_RAI;
1404   if (stat16 & STAT16_XERR)    sc->status.snmp.t3.line |= TLINE_RX_RAI;
1405   if (ctl1   & CTL1_TXAIS)     sc->status.snmp.t3.line |= TLINE_TX_AIS;
1406   if (stat16 & STAT16_RAIS)    sc->status.snmp.t3.line |= TLINE_RX_AIS;
1407   if (stat16 & STAT16_ROOF)    sc->status.snmp.t3.line |= TLINE_LOF;
1408   if (stat16 & STAT16_RLOS)    sc->status.snmp.t3.line |= TLINE_LOS;
1409   if (stat16 & STAT16_SEF)     sc->status.snmp.t3.line |= T3LINE_SEF;
1410
1411   /* SNMP Loopback Status */
1412   sc->status.snmp.t3.loop &= ~TLOOP_FAR_LINE;
1413   if (sc->config.loop_back == CFG_LOOP_TULIP)
1414                                sc->status.snmp.t3.loop |= TLOOP_NEAR_OTHER;
1415   if (ctl1  & CTL1_3LOOP)      sc->status.snmp.t3.loop |= TLOOP_NEAR_INWARD;
1416   if (mii16 & MII16_DS3_TRLBK) sc->status.snmp.t3.loop |= TLOOP_NEAR_OTHER;
1417   if (mii16 & MII16_DS3_LNLBK) sc->status.snmp.t3.loop |= TLOOP_NEAR_LINE;
1418 /*if (ctl12 & CTL12_RTPLOOP)   sc->status.snmp.t3.loop |= TLOOP_NEAR_PAYLOAD; */
1419
1420   /* Remember this state until next time. */
1421   sc->last_stat16 = stat16;
1422
1423   /* If an INWARD loopback is in effect, link status is UP */
1424   if (sc->config.loop_back != CFG_LOOP_NONE) /* XXX INWARD ONLY */
1425     link_status = STATUS_UP;
1426
1427   return link_status;
1428   }
1429
1430 /* IOCTL SYSCALL: can sleep. */
1431 static void
1432 t3_send_dbl_feac(softc_t *sc, int feac1, int feac2)
1433   {
1434   u_int8_t tx_feac;
1435   int i;
1436
1437   /* The FEAC transmitter could be sending a continuous */
1438   /*  FEAC msg when told to send a double FEAC message. */
1439   /* So save the current state of the FEAC transmitter. */
1440   tx_feac = read_framer(sc, T3CSR_TX_FEAC);
1441   /* Load second FEAC code and stop FEAC transmitter. */
1442   write_framer(sc, T3CSR_TX_FEAC,  CTL5_EMODE + feac2);
1443   /* FEAC transmitter sends 10 more FEACs and then stops. */
1444   SLEEP(20000); /* sending one FEAC takes 1700 uSecs */
1445   /* Load first FEAC code and start FEAC transmitter. */
1446   write_framer(sc, T3CSR_DBL_FEAC, CTL13_DFEXEC + feac1);
1447   /* Wait for double FEAC sequence to complete -- about 70 ms. */
1448   for (i=0; i<10; i++) /* max delay 100 ms */
1449     if (read_framer(sc, T3CSR_DBL_FEAC) & CTL13_DFEXEC) SLEEP(10000);
1450   /* Flush received FEACS; don't respond to our own loop cmd! */
1451   while (read_framer(sc, T3CSR_FEAC_STK) & FEAC_STK_VALID) DELAY(1); /* XXX HANG */
1452   /* Restore previous state of the FEAC transmitter. */
1453   /* If it was sending a continous FEAC, it will resume. */
1454   write_framer(sc, T3CSR_TX_FEAC, tx_feac);
1455   }
1456
1457 /* IOCTL SYSCALL: can sleep. */
1458 static int
1459 t3_ioctl(softc_t *sc, struct ioctl *ioctl)
1460   {
1461   int error = 0;
1462
1463   switch (ioctl->cmd)
1464     {
1465     case IOCTL_SNMP_SEND:  /* set opstatus? */
1466       {
1467       if (sc->config.format != CFG_FORMAT_T3CPAR)
1468         error = EINVAL;
1469       else if (ioctl->data == TSEND_LINE)
1470         {
1471         sc->status.snmp.t3.loop |= TLOOP_FAR_LINE;
1472         t3_send_dbl_feac(sc, T3BOP_LINE_UP, T3BOP_LOOP_DS3);
1473         }
1474       else if (ioctl->data == TSEND_RESET)
1475         {
1476         t3_send_dbl_feac(sc, T3BOP_LINE_DOWN, T3BOP_LOOP_DS3);
1477         sc->status.snmp.t3.loop &= ~TLOOP_FAR_LINE;
1478         }
1479       else
1480         error = EINVAL;
1481       break;
1482       }
1483     case IOCTL_SNMP_LOOP:  /* set opstatus = test? */
1484       {
1485       if (ioctl->data == CFG_LOOP_NONE)
1486         {
1487         clr_mii16_bits(sc, MII16_DS3_FRAME);
1488         clr_mii16_bits(sc, MII16_DS3_TRLBK);
1489         clr_mii16_bits(sc, MII16_DS3_LNLBK);
1490         write_framer(sc, T3CSR_CTL1,
1491          read_framer(sc, T3CSR_CTL1) & ~CTL1_3LOOP);
1492         write_framer(sc, T3CSR_CTL12,
1493          read_framer(sc, T3CSR_CTL12) & ~(CTL12_RTPLOOP | CTL12_RTPLLEN));
1494         }
1495       else if (ioctl->data == CFG_LOOP_LINE)
1496         set_mii16_bits(sc, MII16_DS3_LNLBK);
1497       else if (ioctl->data == CFG_LOOP_OTHER)
1498         set_mii16_bits(sc, MII16_DS3_TRLBK);
1499       else if (ioctl->data == CFG_LOOP_INWARD)
1500         write_framer(sc, T3CSR_CTL1,
1501          read_framer(sc, T3CSR_CTL1) | CTL1_3LOOP);
1502       else if (ioctl->data == CFG_LOOP_DUAL)
1503         {
1504         set_mii16_bits(sc, MII16_DS3_LNLBK);
1505         write_framer(sc, T3CSR_CTL1,
1506          read_framer(sc, T3CSR_CTL1) | CTL1_3LOOP);
1507         }
1508       else if (ioctl->data == CFG_LOOP_PAYLOAD)
1509         {
1510         set_mii16_bits(sc, MII16_DS3_FRAME);
1511         write_framer(sc, T3CSR_CTL12,
1512          read_framer(sc, T3CSR_CTL12) |  CTL12_RTPLOOP);
1513         write_framer(sc, T3CSR_CTL12,
1514          read_framer(sc, T3CSR_CTL12) |  CTL12_RTPLLEN);
1515         DELAY(25); /* at least two frames (22 uS) */
1516         write_framer(sc, T3CSR_CTL12,
1517          read_framer(sc, T3CSR_CTL12) & ~CTL12_RTPLLEN);
1518         }
1519       else
1520         error = EINVAL;
1521       break;
1522       }
1523     default:
1524       error = EINVAL;
1525       break;
1526     }
1527
1528   return error;
1529   }
1530
1531 /* begin SSI card code */
1532
1533 /* Must not sleep. */
1534 static void
1535 ssi_config(softc_t *sc)
1536   {
1537   if (sc->status.card_type == 0)
1538     { /* defaults */
1539     sc->status.card_type  = TLP_CSID_SSI;
1540     sc->config.crc_len    = CFG_CRC_16;
1541     sc->config.loop_back  = CFG_LOOP_NONE;
1542     sc->config.tx_clk_src = CFG_CLKMUX_ST;
1543     sc->config.dte_dce    = CFG_DTE;
1544     sc->config.synth.n    = 51; /* 1.536 MHz */
1545     sc->config.synth.m    = 83;
1546     sc->config.synth.v    =  1;
1547     sc->config.synth.x    =  1;
1548     sc->config.synth.r    =  1;
1549     sc->config.synth.prescale = 4;
1550     }
1551
1552   /* Disable the TX clock driver while programming the oscillator. */
1553   clr_gpio_bits(sc, GPIO_SSI_DCE);
1554   make_gpio_output(sc, GPIO_SSI_DCE);
1555
1556   /* Program the synthesized oscillator. */
1557   write_synth(sc, &sc->config.synth);
1558
1559   /* Set DTE/DCE mode. */
1560   /* If DTE mode then DCD & TXC are received. */
1561   /* If DCE mode then DCD & TXC are driven. */
1562   /* Boards with MII rev=4.0 don't drive DCD. */
1563   if (sc->config.dte_dce == CFG_DCE)
1564     set_gpio_bits(sc, GPIO_SSI_DCE);
1565   else
1566     clr_gpio_bits(sc, GPIO_SSI_DCE);
1567   make_gpio_output(sc, GPIO_SSI_DCE);
1568
1569   /* Set CRC length. */
1570   if (sc->config.crc_len == CFG_CRC_32)
1571     set_mii16_bits(sc, MII16_SSI_CRC32);
1572   else
1573     clr_mii16_bits(sc, MII16_SSI_CRC32);
1574
1575   /* Loop towards host thru cable drivers and receivers. */
1576   /* Asserts DCD at the far end of a null modem cable. */
1577   if (sc->config.loop_back == CFG_LOOP_PINS)
1578     set_mii16_bits(sc, MII16_SSI_LOOP);
1579   else
1580     clr_mii16_bits(sc, MII16_SSI_LOOP);
1581
1582   /* Assert pin LL in modem conn: ask modem for local loop. */
1583   /* Asserts TM at the far end of a null modem cable. */
1584   if (sc->config.loop_back == CFG_LOOP_LL)
1585     set_mii16_bits(sc, MII16_SSI_LL);
1586   else
1587     clr_mii16_bits(sc, MII16_SSI_LL);
1588
1589   /* Assert pin RL in modem conn: ask modem for remote loop. */
1590   if (sc->config.loop_back == CFG_LOOP_RL)
1591     set_mii16_bits(sc, MII16_SSI_RL);
1592   else
1593     clr_mii16_bits(sc, MII16_SSI_RL);
1594   }
1595
1596 static void
1597 ssi_ident(softc_t *sc)
1598   {
1599   printf(", LTC1343/44");
1600   }
1601
1602 /* Called once a second; must not sleep. */
1603 static int
1604 ssi_watchdog(softc_t *sc)
1605   {
1606   u_int16_t cable;
1607   u_int16_t mii16 = read_mii(sc, 16) & MII16_SSI_MODEM;
1608   int link_status = STATUS_UP;
1609
1610   /* Software is alive. */
1611   led_inv(sc, MII16_SSI_LED_UL);
1612
1613   /* Check the transmit clock. */
1614   if (sc->status.tx_speed == 0)
1615     {
1616     led_on(sc, MII16_SSI_LED_UR);
1617     link_status = STATUS_DOWN;
1618     }
1619   else
1620     led_off(sc, MII16_SSI_LED_UR);
1621
1622   /* Check the external cable. */
1623   cable = read_mii(sc, 17);
1624   cable = cable &  MII17_SSI_CABLE_MASK;
1625   cable = cable >> MII17_SSI_CABLE_SHIFT;
1626   if (cable == 7)
1627     {
1628     led_off(sc, MII16_SSI_LED_LL); /* no cable */
1629     link_status = STATUS_DOWN;
1630     }
1631   else
1632     led_on(sc, MII16_SSI_LED_LL);
1633
1634   /* The unit at the other end of the cable is ready if: */
1635   /*  DTE mode and DCD pin is asserted */
1636   /*  DCE mode and DSR pin is asserted */
1637   if (((sc->config.dte_dce == CFG_DTE) && ((mii16 & MII16_SSI_DCD)==0)) ||
1638       ((sc->config.dte_dce == CFG_DCE) && ((mii16 & MII16_SSI_DSR)==0)))
1639     {
1640     led_off(sc, MII16_SSI_LED_LR);
1641     link_status = STATUS_DOWN;
1642     }
1643   else
1644     led_on(sc, MII16_SSI_LED_LR);
1645
1646   if (DRIVER_DEBUG && (cable != sc->status.cable_type))
1647     printf("%s: SSI cable type changed to '%s'\n",
1648      NAME_UNIT, ssi_cables[cable]);
1649   sc->status.cable_type = cable;
1650
1651   /* Print the modem control signals if they changed. */
1652   if ((DRIVER_DEBUG) && (mii16 != sc->last_mii16))
1653     {
1654     char *on = "ON ", *off = "OFF";
1655     printf("%s: DTR=%s DSR=%s RTS=%s CTS=%s DCD=%s RI=%s LL=%s RL=%s TM=%s\n",
1656      NAME_UNIT,
1657      (mii16 & MII16_SSI_DTR) ? on : off,
1658      (mii16 & MII16_SSI_DSR) ? on : off,
1659      (mii16 & MII16_SSI_RTS) ? on : off,
1660      (mii16 & MII16_SSI_CTS) ? on : off,
1661      (mii16 & MII16_SSI_DCD) ? on : off,
1662      (mii16 & MII16_SSI_RI)  ? on : off,
1663      (mii16 & MII16_SSI_LL)  ? on : off,
1664      (mii16 & MII16_SSI_RL)  ? on : off,
1665      (mii16 & MII16_SSI_TM)  ? on : off);
1666     }
1667
1668   /* SNMP one-second report */
1669   sc->status.snmp.ssi.sigs = mii16 & MII16_SSI_MODEM;
1670
1671   /* Remember this state until next time. */
1672   sc->last_mii16 = mii16;
1673
1674   /* If a loop back is in effect, link status is UP */
1675   if (sc->config.loop_back != CFG_LOOP_NONE)
1676     link_status = STATUS_UP;
1677
1678   return link_status;
1679   }
1680
1681 /* IOCTL SYSCALL: can sleep (but doesn't). */
1682 static int
1683 ssi_ioctl(softc_t *sc, struct ioctl *ioctl)
1684   {
1685   int error = 0;
1686
1687   if (ioctl->cmd == IOCTL_SNMP_SIGS)
1688     {
1689     u_int16_t mii16 = read_mii(sc, 16);
1690     mii16 &= ~MII16_SSI_MODEM;
1691     mii16 |= (MII16_SSI_MODEM & ioctl->data);
1692     write_mii(sc, 16, mii16);
1693     }
1694   else if (ioctl->cmd == IOCTL_SET_STATUS)
1695     {
1696     if (ioctl->data != 0)
1697       set_mii16_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
1698     else
1699       clr_mii16_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
1700     }
1701   else
1702     error = EINVAL;
1703
1704   return error;
1705   }
1706
1707 /* begin T1E1 card code */
1708
1709 /* Must not sleep. */
1710 static void
1711 t1_config(softc_t *sc)
1712   {
1713   int i;
1714   u_int8_t pulse, lbo, gain;
1715
1716   if (sc->status.card_type == 0)
1717     {  /* defaults */
1718     sc->status.card_type   = TLP_CSID_T1E1;
1719     sc->config.crc_len     = CFG_CRC_16;
1720     sc->config.loop_back   = CFG_LOOP_NONE;
1721     sc->config.tx_clk_src  = CFG_CLKMUX_INT;
1722     sc->config.format      = CFG_FORMAT_T1ESF;
1723     sc->config.cable_len   = 10;
1724     sc->config.time_slots  = 0x01FFFFFE;
1725     sc->config.tx_pulse    = CFG_PULSE_AUTO;
1726     sc->config.rx_gain     = CFG_GAIN_AUTO;
1727     sc->config.tx_lbo      = CFG_LBO_AUTO;
1728
1729     /* Bt8370 occasionally powers up in a loopback mode. */
1730     /* Data sheet says zero LOOP reg and do a s/w reset. */
1731     write_framer(sc, Bt8370_LOOP, 0x00); /* no loopback */
1732     write_framer(sc, Bt8370_CR0,  0x80); /* s/w reset */
1733     for (i=0; i<10; i++) /* max delay 10 ms */
1734       if (read_framer(sc, Bt8370_CR0) & 0x80) DELAY(1000);
1735     }
1736
1737   /* Set CRC length. */
1738   if (sc->config.crc_len == CFG_CRC_32)
1739     set_mii16_bits(sc, MII16_T1_CRC32);
1740   else
1741     clr_mii16_bits(sc, MII16_T1_CRC32);
1742
1743   /* Invert HDLC payload data in SF/AMI mode. */
1744   /* HDLC stuff bits satisfy T1 pulse density. */
1745   if (FORMAT_T1SF)
1746     set_mii16_bits(sc, MII16_T1_INVERT);
1747   else
1748     clr_mii16_bits(sc, MII16_T1_INVERT);
1749
1750   /* Set the transmitter output impedance. */
1751   if (FORMAT_E1ANY) set_mii16_bits(sc, MII16_T1_Z);
1752
1753   /* 001:CR0 -- Control Register 0 - T1/E1 and frame format */
1754   write_framer(sc, Bt8370_CR0, sc->config.format);
1755
1756   /* 002:JAT_CR -- Jitter Attenuator Control Register */
1757   if (sc->config.tx_clk_src == CFG_CLKMUX_RT) /* loop timing */
1758     write_framer(sc, Bt8370_JAT_CR, 0xA3); /* JAT in RX path */
1759   else
1760     { /* 64-bit elastic store; free-running JCLK and CLADO */
1761     write_framer(sc, Bt8370_JAT_CR, 0x4B); /* assert jcenter */
1762     write_framer(sc, Bt8370_JAT_CR, 0x43); /* release jcenter */
1763     }
1764
1765   /* 00C-013:IERn -- Interrupt Enable Registers */
1766   for (i=Bt8370_IER7; i<=Bt8370_IER0; i++)
1767     write_framer(sc, i, 0); /* no interrupts; polled */
1768
1769   /* 014:LOOP -- loopbacks */
1770   if      (sc->config.loop_back == CFG_LOOP_PAYLOAD)
1771     write_framer(sc, Bt8370_LOOP, LOOP_PAYLOAD);
1772   else if (sc->config.loop_back == CFG_LOOP_LINE)
1773     write_framer(sc, Bt8370_LOOP, LOOP_LINE);
1774   else if (sc->config.loop_back == CFG_LOOP_OTHER)
1775     write_framer(sc, Bt8370_LOOP, LOOP_ANALOG);
1776   else if (sc->config.loop_back == CFG_LOOP_INWARD)
1777     write_framer(sc, Bt8370_LOOP, LOOP_FRAMER);
1778   else if (sc->config.loop_back == CFG_LOOP_DUAL)
1779     write_framer(sc, Bt8370_LOOP, LOOP_DUAL);
1780   else
1781     write_framer(sc, Bt8370_LOOP, 0x00); /* no loopback */
1782
1783   /* 015:DL3_TS -- Data Link 3 */
1784   write_framer(sc, Bt8370_DL3_TS, 0x00); /* disabled */
1785
1786   /* 018:PIO -- Programmable I/O */
1787   write_framer(sc, Bt8370_PIO, 0xFF); /* all pins are outputs */
1788
1789   /* 019:POE -- Programmable Output Enable */
1790   write_framer(sc, Bt8370_POE, 0x00); /* all outputs are enabled */
1791
1792   /* 01A;CMUX -- Clock Input Mux */
1793   if (sc->config.tx_clk_src == CFG_CLKMUX_EXT)
1794     write_framer(sc, Bt8370_CMUX, 0x0C); /* external timing */
1795   else
1796     write_framer(sc, Bt8370_CMUX, 0x0F); /* internal timing */
1797
1798   /* 020:LIU_CR -- Line Interface Unit Config Register */
1799   write_framer(sc, Bt8370_LIU_CR, 0xC1); /* reset LIU, squelch */
1800
1801   /* 022:RLIU_CR -- RX Line Interface Unit Config Reg */
1802   /* Errata sheet says don't use freeze-short, but we do anyway! */
1803   write_framer(sc, Bt8370_RLIU_CR, 0xB1); /* AGC=2048, Long Eye */
1804
1805   /* Select Rx sensitivity based on cable length. */
1806   if ((gain = sc->config.rx_gain) == CFG_GAIN_AUTO)
1807     {
1808     if      (sc->config.cable_len > 2000)
1809       gain = CFG_GAIN_EXTEND;
1810     else if (sc->config.cable_len > 1000)
1811       gain = CFG_GAIN_LONG;
1812     else if (sc->config.cable_len > 100)
1813       gain = CFG_GAIN_MEDIUM;
1814     else
1815       gain = CFG_GAIN_SHORT;
1816     }
1817
1818   /* 024:VGA_MAX -- Variable Gain Amplifier Max gain */
1819   write_framer(sc, Bt8370_VGA_MAX, gain);
1820
1821   /* 028:PRE_EQ -- Pre Equalizer */
1822   if (gain == CFG_GAIN_EXTEND)
1823     write_framer(sc, Bt8370_PRE_EQ, 0xE6);  /* ON; thresh 6 */
1824   else
1825     write_framer(sc, Bt8370_PRE_EQ, 0xA6);  /* OFF; thresh 6 */
1826
1827   /* 038-03C:GAINn -- RX Equalizer gain thresholds */
1828   write_framer(sc, Bt8370_GAIN0, 0x24);
1829   write_framer(sc, Bt8370_GAIN1, 0x28);
1830   write_framer(sc, Bt8370_GAIN2, 0x2C);
1831   write_framer(sc, Bt8370_GAIN3, 0x30);
1832   write_framer(sc, Bt8370_GAIN4, 0x34);
1833
1834   /* 040:RCR0 -- Receiver Control Register 0 */
1835   if      (FORMAT_T1ESF)
1836     write_framer(sc, Bt8370_RCR0, 0x05); /* B8ZS, 2/5 FErrs */
1837   else if (FORMAT_T1SF)
1838     write_framer(sc, Bt8370_RCR0, 0x84); /* AMI,  2/5 FErrs */
1839   else if (FORMAT_E1NONE)
1840     write_framer(sc, Bt8370_RCR0, 0x41); /* HDB3, rabort */
1841   else if (FORMAT_E1CRC)
1842     write_framer(sc, Bt8370_RCR0, 0x09); /* HDB3, 3 FErrs or 915 CErrs */
1843   else  /* E1 no CRC */
1844     write_framer(sc, Bt8370_RCR0, 0x19); /* HDB3, 3 FErrs */
1845
1846   /* 041:RPATT -- Receive Test Pattern configuration */
1847   write_framer(sc, Bt8370_RPATT, 0x3E); /* looking for framed QRSS */
1848
1849   /* 042:RLB -- Receive Loop Back code detector config */
1850   write_framer(sc, Bt8370_RLB, 0x09); /* 6 bits down; 5 bits up */
1851
1852   /* 043:LBA -- Loop Back Activate code */
1853   write_framer(sc, Bt8370_LBA, 0x08); /* 10000 10000 10000 ... */
1854
1855   /* 044:LBD -- Loop Back Deactivate code */
1856   write_framer(sc, Bt8370_LBD, 0x24); /* 100100 100100 100100 ... */
1857
1858   /* 045:RALM -- Receive Alarm signal configuration */
1859   write_framer(sc, Bt8370_RALM, 0x0C); /* yel_intg rlof_intg */
1860
1861   /* 046:LATCH -- Alarm/Error/Counter Latch register */
1862   write_framer(sc, Bt8370_LATCH, 0x1F); /* stop_cnt latch_{cnt,err,alm} */
1863
1864   /* Select Pulse Shape based on cable length (T1 only). */
1865   if ((pulse = sc->config.tx_pulse) == CFG_PULSE_AUTO)
1866     {
1867     if (FORMAT_T1ANY)
1868       {
1869       if      (sc->config.cable_len > 200)
1870         pulse = CFG_PULSE_T1CSU;
1871       else if (sc->config.cable_len > 160)
1872         pulse = CFG_PULSE_T1DSX4;
1873       else if (sc->config.cable_len > 120)
1874         pulse = CFG_PULSE_T1DSX3;
1875       else if (sc->config.cable_len > 80)
1876         pulse = CFG_PULSE_T1DSX2;
1877       else if (sc->config.cable_len > 40)
1878         pulse = CFG_PULSE_T1DSX1;
1879       else
1880         pulse = CFG_PULSE_T1DSX0;
1881       }
1882     else
1883       pulse = CFG_PULSE_E1TWIST;
1884     }
1885
1886   /* Select Line Build Out based on cable length (T1CSU only). */
1887   if ((lbo = sc->config.tx_lbo) == CFG_LBO_AUTO)
1888     {
1889     if (pulse == CFG_PULSE_T1CSU)
1890       {
1891       if      (sc->config.cable_len > 1500)
1892         lbo = CFG_LBO_0DB;
1893       else if (sc->config.cable_len > 1000)
1894         lbo = CFG_LBO_7DB;
1895       else if (sc->config.cable_len >  500)
1896         lbo = CFG_LBO_15DB;
1897       else
1898         lbo = CFG_LBO_22DB;
1899       }
1900     else
1901       lbo = 0;
1902     }
1903
1904   /* 068:TLIU_CR -- Transmit LIU Control Register */
1905   write_framer(sc, Bt8370_TLIU_CR, (0x40 | (lbo & 0x30) | (pulse & 0x0E)));
1906
1907   /* 070:TCR0 -- Transmit Framer Configuration */
1908   write_framer(sc, Bt8370_TCR0, sc->config.format>>1);
1909
1910   /* 071:TCR1 -- Transmitter Configuration */
1911   if (FORMAT_T1SF)
1912     write_framer(sc, Bt8370_TCR1, 0x43); /* tabort, AMI PDV enforced */
1913   else
1914     write_framer(sc, Bt8370_TCR1, 0x41); /* tabort, B8ZS or HDB3 */
1915
1916   /* 072:TFRM -- Transmit Frame format       MYEL YEL MF FE CRC FBIT */
1917   if      (sc->config.format == CFG_FORMAT_T1ESF)
1918     write_framer(sc, Bt8370_TFRM, 0x0B); /*  -   YEL MF -  CRC FBIT */
1919   else if (sc->config.format == CFG_FORMAT_T1SF)
1920     write_framer(sc, Bt8370_TFRM, 0x19); /*  -   YEL MF -   -  FBIT */
1921   else if (sc->config.format == CFG_FORMAT_E1FAS)
1922     write_framer(sc, Bt8370_TFRM, 0x11); /*  -   YEL -  -   -  FBIT */
1923   else if (sc->config.format == CFG_FORMAT_E1FASCRC)
1924     write_framer(sc, Bt8370_TFRM, 0x1F); /*  -   YEL MF FE CRC FBIT */
1925   else if (sc->config.format == CFG_FORMAT_E1FASCAS)
1926     write_framer(sc, Bt8370_TFRM, 0x31); /* MYEL YEL -  -   -  FBIT */
1927   else if (sc->config.format == CFG_FORMAT_E1FASCRCCAS)
1928     write_framer(sc, Bt8370_TFRM, 0x3F); /* MYEL YEL MF FE CRC FBIT */
1929   else if (sc->config.format == CFG_FORMAT_E1NONE)
1930     write_framer(sc, Bt8370_TFRM, 0x00); /* NO FRAMING BITS AT ALL! */
1931
1932   /* 073:TERROR -- Transmit Error Insert */
1933   write_framer(sc, Bt8370_TERROR, 0x00); /* no errors, please! */
1934
1935   /* 074:TMAN -- Transmit Manual Sa-byte/FEBE configuration */
1936   write_framer(sc, Bt8370_TMAN, 0x00); /* none */
1937
1938   /* 075:TALM -- Transmit Alarm Signal Configuration */
1939   if (FORMAT_E1ANY)
1940     write_framer(sc, Bt8370_TALM, 0x38); /* auto_myel auto_yel auto_ais */
1941   else if (FORMAT_T1ANY)
1942     write_framer(sc, Bt8370_TALM, 0x18); /* auto_yel auto_ais */
1943
1944   /* 076:TPATT -- Transmit Test Pattern Configuration */
1945   write_framer(sc, Bt8370_TPATT, 0x00); /* disabled */
1946
1947   /* 077:TLB -- Transmit Inband Loopback Code Configuration */
1948   write_framer(sc, Bt8370_TLB, 0x00); /* disabled */
1949
1950   /* 090:CLAD_CR -- Clack Rate Adapter Configuration */
1951   if (FORMAT_T1ANY)
1952     write_framer(sc, Bt8370_CLAD_CR, 0x06); /* loop filter gain 1/2^6 */
1953   else
1954     write_framer(sc, Bt8370_CLAD_CR, 0x08); /* loop filter gain 1/2^8 */
1955
1956   /* 091:CSEL -- CLAD frequency Select */
1957   if (FORMAT_T1ANY)
1958     write_framer(sc, Bt8370_CSEL, 0x55); /* 1544 kHz */
1959   else
1960     write_framer(sc, Bt8370_CSEL, 0x11); /* 2048 kHz */
1961
1962   /* 092:CPHASE -- CLAD Phase detector */
1963   if (FORMAT_T1ANY)
1964     write_framer(sc, Bt8370_CPHASE, 0x22); /* phase compare @  386 kHz */
1965   else
1966     write_framer(sc, Bt8370_CPHASE, 0x00); /* phase compare @ 2048 kHz */
1967
1968   if (FORMAT_T1ESF) /* BOP & PRM are enabled in T1ESF mode only. */
1969     {
1970     /* 0A0:BOP -- Bit Oriented Protocol messages */
1971     write_framer(sc, Bt8370_BOP, RBOP_25 | TBOP_OFF);
1972     /* 0A4:DL1_TS -- Data Link 1 Time Slot Enable */
1973     write_framer(sc, Bt8370_DL1_TS, 0x40); /* FDL bits in odd frames */
1974     /* 0A6:DL1_CTL -- Data Link 1 Control */
1975     write_framer(sc, Bt8370_DL1_CTL, 0x03); /* FCS mode, TX on, RX on */
1976     /* 0A7:RDL1_FFC -- Rx Data Link 1 Fifo Fill Control */
1977     write_framer(sc, Bt8370_RDL1_FFC, 0x30); /* assert "near full" at 48 */
1978     /* 0AA:PRM -- Performance Report Messages */
1979     write_framer(sc, Bt8370_PRM, 0x80);
1980     }
1981
1982   /* 0D0:SBI_CR -- System Bus Interface Configuration Register */
1983   if (FORMAT_T1ANY)
1984     write_framer(sc, Bt8370_SBI_CR, 0x47); /* 1.544 with 24 TS +Fbits */
1985   else
1986     write_framer(sc, Bt8370_SBI_CR, 0x46); /* 2.048 with 32 TS */
1987
1988   /* 0D1:RSB_CR -- Receive System Bus Configuration Register */
1989   /* Change RINDO & RFSYNC on falling edge of RSBCLKI. */
1990   write_framer(sc, Bt8370_RSB_CR, 0x70);
1991
1992   /* 0D2,0D3:RSYNC_{TS,BIT} -- Receive frame Sync offset */
1993   write_framer(sc, Bt8370_RSYNC_BIT, 0x00);
1994   write_framer(sc, Bt8370_RSYNC_TS,  0x00);
1995
1996   /* 0D4:TSB_CR -- Transmit System Bus Configuration Register */
1997   /* Change TINDO & TFSYNC on falling edge of TSBCLKI. */
1998   write_framer(sc, Bt8370_TSB_CR, 0x30);
1999
2000   /* 0D5,0D6:TSYNC_{TS,BIT} -- Transmit frame Sync offset */
2001   write_framer(sc, Bt8370_TSYNC_BIT, 0x00);
2002   write_framer(sc, Bt8370_TSYNC_TS,  0x00);
2003
2004   /* 0D7:RSIG_CR -- Receive SIGnalling Configuratin Register */
2005   write_framer(sc, Bt8370_RSIG_CR, 0x00);
2006
2007   /* Assign and configure 64Kb TIME SLOTS. */
2008   /* TS24..TS1 must be assigned for T1, TS31..TS0 for E1. */
2009   /* Timeslots with no user data have RINDO and TINDO off. */
2010   for (i=0; i<32; i++)
2011     {
2012     /* 0E0-0FF:SBCn -- System Bus Per-Channel Control */
2013     if      (FORMAT_T1ANY && (i==0 || i>24))
2014       write_framer(sc, Bt8370_SBCn +i, 0x00); /* not assigned in T1 mode */
2015     else if (FORMAT_E1ANY && (i==0)  && !FORMAT_E1NONE)
2016       write_framer(sc, Bt8370_SBCn +i, 0x01); /* assigned, TS0  o/h bits */
2017     else if (FORMAT_E1CAS && (i==16) && !FORMAT_E1NONE)
2018       write_framer(sc, Bt8370_SBCn +i, 0x01); /* assigned, TS16 o/h bits */
2019     else if ((sc->config.time_slots & (1<<i)) != 0)
2020       write_framer(sc, Bt8370_SBCn +i, 0x0D); /* assigned, RINDO, TINDO */
2021     else
2022       write_framer(sc, Bt8370_SBCn +i, 0x01); /* assigned, idle */
2023
2024     /* 100-11F:TPCn -- Transmit Per-Channel Control */
2025     if      (FORMAT_E1CAS && (i==0))
2026       write_framer(sc, Bt8370_TPCn +i, 0x30); /* tidle, sig=0000 (MAS) */
2027     else if (FORMAT_E1CAS && (i==16))
2028       write_framer(sc, Bt8370_TPCn +i, 0x3B); /* tidle, sig=1011 (XYXX) */
2029     else if ((sc->config.time_slots & (1<<i)) == 0)
2030       write_framer(sc, Bt8370_TPCn +i, 0x20); /* tidle: use TSLIP_LOn */
2031     else
2032       write_framer(sc, Bt8370_TPCn +i, 0x00); /* nothing special */
2033
2034     /* 140-15F:TSLIP_LOn -- Transmit PCM Slip Buffer */
2035     write_framer(sc, Bt8370_TSLIP_LOn +i, 0x7F); /* idle chan data */
2036     /* 180-19F:RPCn -- Receive Per-Channel Control */
2037     write_framer(sc, Bt8370_RPCn +i, 0x00);   /* nothing special */
2038     }
2039
2040   /* Enable transmitter output drivers. */
2041   set_mii16_bits(sc, MII16_T1_XOE);
2042   }
2043
2044 static void
2045 t1_ident(softc_t *sc)
2046   {
2047   printf(", Bt837%x rev %x",
2048    read_framer(sc, Bt8370_DID)>>4,
2049    read_framer(sc, Bt8370_DID)&0x0F);
2050   }
2051
2052 /* Called once a second; must not sleep. */
2053 static int
2054 t1_watchdog(softc_t *sc)
2055   {
2056   u_int16_t LCV = 0, FERR = 0, CRC = 0, FEBE = 0;
2057   u_int8_t alm1, alm3, loop, isr0;
2058   int link_status = STATUS_UP;
2059   int i;
2060
2061   /* Read the alarm registers */
2062   alm1 = read_framer(sc, Bt8370_ALM1);
2063   alm3 = read_framer(sc, Bt8370_ALM3);
2064   loop = read_framer(sc, Bt8370_LOOP);
2065   isr0 = read_framer(sc, Bt8370_ISR0);
2066
2067   /* Always ignore the SIGFRZ alarm bit, */
2068   alm1 &= ~ALM1_SIGFRZ;
2069   if (FORMAT_T1ANY)  /* ignore RYEL in T1 modes */
2070     alm1 &= ~ALM1_RYEL;
2071   else if (FORMAT_E1NONE) /* ignore all alarms except LOS */
2072     alm1 &= ALM1_RLOS;
2073
2074   /* Software is alive. */
2075   led_inv(sc, MII16_T1_LED_GRN);
2076
2077   /* Receiving Alarm Indication Signal (AIS). */
2078   if ((alm1 & ALM1_RAIS)!=0) /* receiving ais */
2079     led_on(sc, MII16_T1_LED_BLU);
2080   else if ((alm1 & ALM1_RLOS)!=0) /* sending ais */
2081     led_inv(sc, MII16_T1_LED_BLU);
2082   else
2083     led_off(sc, MII16_T1_LED_BLU);
2084
2085   /* Receiving Remote Alarm Indication (RAI). */
2086   if ((alm1 & (ALM1_RMYEL | ALM1_RYEL))!=0) /* receiving rai */
2087     led_on(sc, MII16_T1_LED_YEL);
2088   else if ((alm1 & ALM1_RLOF)!=0) /* sending rai */
2089     led_inv(sc, MII16_T1_LED_YEL);
2090   else
2091     led_off(sc, MII16_T1_LED_YEL);
2092
2093   /* If any alarm bits are set then the link is 'down'. */
2094   /* The bad bits are: rmyel ryel rais ralos rlos rlof. */
2095   /* Some alarm bits have been masked by this point. */
2096   if (alm1 != 0) link_status = STATUS_DOWN;
2097
2098   /* Declare local Red Alarm if the link is down. */
2099   if (link_status == STATUS_DOWN)
2100     led_on(sc, MII16_T1_LED_RED);
2101   else if (sc->loop_timer != 0) /* loopback is active */
2102     led_inv(sc, MII16_T1_LED_RED);
2103   else
2104     led_off(sc, MII16_T1_LED_RED);
2105
2106   /* Print latched error bits if they changed. */
2107   if ((DRIVER_DEBUG) && (alm1 != sc->last_alm1))
2108     {
2109     char *on = "ON ", *off = "OFF";
2110     printf("%s: RLOF=%s RLOS=%s RALOS=%s RAIS=%s RYEL=%s RMYEL=%s\n",
2111      NAME_UNIT,
2112      (alm1 & ALM1_RLOF)  ? on : off,
2113      (alm1 & ALM1_RLOS)  ? on : off,
2114      (alm1 & ALM1_RALOS) ? on : off,
2115      (alm1 & ALM1_RAIS)  ? on : off,
2116      (alm1 & ALM1_RYEL)  ? on : off,
2117      (alm1 & ALM1_RMYEL) ? on : off);
2118     }
2119
2120   /* Check and print error counters if non-zero. */
2121   LCV = read_framer(sc, Bt8370_LCV_LO)  +
2122         (read_framer(sc, Bt8370_LCV_HI)<<8);
2123   if (!FORMAT_E1NONE)
2124     FERR = read_framer(sc, Bt8370_FERR_LO) +
2125           (read_framer(sc, Bt8370_FERR_HI)<<8);
2126   if (FORMAT_E1CRC || FORMAT_T1ESF)
2127     CRC  = read_framer(sc, Bt8370_CRC_LO)  +
2128           (read_framer(sc, Bt8370_CRC_HI)<<8);
2129   if (FORMAT_E1CRC)
2130     FEBE = read_framer(sc, Bt8370_FEBE_LO) +
2131           (read_framer(sc, Bt8370_FEBE_HI)<<8);
2132   /* Only LCV is valid if Out-Of-Frame */
2133   if (FORMAT_E1NONE) FERR = CRC = FEBE = 0;
2134   if ((DRIVER_DEBUG) && (LCV || FERR || CRC || FEBE))
2135     printf("%s: LCV=%u FERR=%u CRC=%u FEBE=%u\n",
2136      NAME_UNIT, LCV,   FERR,   CRC,   FEBE);
2137
2138   /* Driver keeps crude link-level error counters (SNMP is better). */
2139   sc->status.cntrs.lcv_errs  += LCV;
2140   sc->status.cntrs.frm_errs  += FERR;
2141   sc->status.cntrs.crc_errs  += CRC;
2142   sc->status.cntrs.febe_errs += FEBE;
2143
2144   /* Check for BOP messages in the ESF Facility Data Link. */
2145   if ((FORMAT_T1ESF) && (read_framer(sc, Bt8370_ISR1) & 0x80))
2146     {
2147     u_int8_t bop_code = read_framer(sc, Bt8370_RBOP) & 0x3F;
2148
2149     switch (bop_code)
2150       {
2151       case T1BOP_OOF:
2152         {
2153         if ((DRIVER_DEBUG) && ((sc->last_alm1 & ALM1_RMYEL)==0))
2154           printf("%s: Receiving a 'yellow alarm' BOP msg\n", NAME_UNIT);
2155         break;
2156         }
2157       case T1BOP_LINE_UP:
2158         {
2159         if (DRIVER_DEBUG)
2160           printf("%s: Received a 'line loopback activate' BOP msg\n", NAME_UNIT);
2161         write_framer(sc, Bt8370_LOOP, LOOP_LINE);
2162         sc->loop_timer = 305;
2163         break;
2164         }
2165       case T1BOP_LINE_DOWN:
2166         {
2167         if (DRIVER_DEBUG)
2168           printf("%s: Received a 'line loopback deactivate' BOP msg\n", NAME_UNIT);
2169         write_framer(sc, Bt8370_LOOP,
2170          read_framer(sc, Bt8370_LOOP) & ~LOOP_LINE);
2171         sc->loop_timer = 0;
2172         break;
2173         }
2174       case T1BOP_PAY_UP:
2175         {
2176         if (DRIVER_DEBUG)
2177           printf("%s: Received a 'payload loopback activate' BOP msg\n", NAME_UNIT);
2178         write_framer(sc, Bt8370_LOOP, LOOP_PAYLOAD);
2179         sc->loop_timer = 305;
2180         break;
2181         }
2182       case T1BOP_PAY_DOWN:
2183         {
2184         if (DRIVER_DEBUG)
2185           printf("%s: Received a 'payload loopback deactivate' BOP msg\n", NAME_UNIT);
2186         write_framer(sc, Bt8370_LOOP,
2187          read_framer(sc, Bt8370_LOOP) & ~LOOP_PAYLOAD);
2188         sc->loop_timer = 0;
2189         break;
2190         }
2191       default:
2192         {
2193         if (DRIVER_DEBUG)
2194           printf("%s: Received a type 0x%02X BOP msg\n", NAME_UNIT, bop_code);
2195         break;
2196         }
2197       }
2198     }
2199
2200   /* Check for HDLC pkts in the ESF Facility Data Link. */
2201   if ((FORMAT_T1ESF) && (read_framer(sc, Bt8370_ISR2) & 0x70))
2202     {
2203     /* while (not fifo-empty && not start-of-msg) flush fifo */
2204     while ((read_framer(sc, Bt8370_RDL1_STAT) & 0x0C) == 0)
2205       read_framer(sc, Bt8370_RDL1);
2206     /* If (not fifo-empty), then begin processing fifo contents. */
2207     if ((read_framer(sc, Bt8370_RDL1_STAT) & 0x0C) == 0x08)
2208       {
2209       u_int8_t msg[64];
2210       u_int8_t stat = read_framer(sc, Bt8370_RDL1);
2211       sc->status.cntrs.fdl_pkts++;
2212       for (i=0; i<(stat & 0x3F); i++)
2213         msg[i] = read_framer(sc, Bt8370_RDL1);
2214       /* Is this FDL message a T1.403 performance report? */
2215       if (((stat & 0x3F)==11) &&
2216           ((msg[0]==0x38) || (msg[0]==0x3A)) &&
2217            (msg[1]==1)   &&  (msg[2]==3))
2218         /* Copy 4 PRs from FDL pkt to SNMP struct. */
2219         memcpy(sc->status.snmp.t1.prm, msg+3, 8);
2220       }
2221     }
2222
2223   /* Check for inband loop up/down commands. */
2224   if (FORMAT_T1ANY)
2225     {
2226     u_int8_t isr6   = read_framer(sc, Bt8370_ISR6);
2227     u_int8_t alarm2 = read_framer(sc, Bt8370_ALM2);
2228     u_int8_t tlb    = read_framer(sc, Bt8370_TLB);
2229
2230     /* Inband Code == Loop Up && On Transition && Inband Tx Inactive */
2231     if ((isr6 & 0x40) && (alarm2 & 0x40) && ((tlb & 1)==0))
2232       { /* CSU loop up is 10000 10000 ... */
2233       if (DRIVER_DEBUG)
2234         printf("%s: Received a 'CSU Loop Up' inband msg\n", NAME_UNIT);
2235       write_framer(sc, Bt8370_LOOP, LOOP_LINE); /* Loop up */
2236       sc->loop_timer = 305;
2237       }
2238     /* Inband Code == Loop Down && On Transition && Inband Tx Inactive */
2239     if ((isr6 & 0x80) && (alarm2 & 0x80) && ((tlb & 1)==0))
2240       { /* CSU loop down is 100 100 100 ... */
2241       if (DRIVER_DEBUG)
2242         printf("%s: Received a 'CSU Loop Down' inband msg\n", NAME_UNIT);
2243       write_framer(sc, Bt8370_LOOP,
2244        read_framer(sc, Bt8370_LOOP) & ~LOOP_LINE); /* loop down */
2245       sc->loop_timer = 0;
2246       }
2247     }
2248
2249   /* Manually send Yellow Alarm BOP msgs. */
2250   if (FORMAT_T1ESF)
2251     {
2252     u_int8_t isr7 = read_framer(sc, Bt8370_ISR7);
2253
2254     if ((isr7 & 0x02) && (alm1 & 0x02)) /* RLOF on-transition */
2255       { /* Start sending continuous Yellow Alarm BOP messages. */
2256       write_framer(sc, Bt8370_BOP,  RBOP_25 | TBOP_CONT);
2257       write_framer(sc, Bt8370_TBOP, 0x00); /* send BOP; order matters */
2258       }
2259     else if ((isr7 & 0x02) && ((alm1 & 0x02)==0)) /* RLOF off-transition */
2260       { /* Stop sending continuous Yellow Alarm BOP messages. */
2261       write_framer(sc, Bt8370_BOP,  RBOP_25 | TBOP_OFF);
2262       }
2263     }
2264
2265   /* Time out loopback requests. */
2266   if (sc->loop_timer != 0)
2267     if (--sc->loop_timer == 0)
2268       if (loop != 0)
2269         {
2270         if (DRIVER_DEBUG)
2271           printf("%s: Timeout: Loop Down after 300 seconds\n", NAME_UNIT);
2272         write_framer(sc, Bt8370_LOOP, loop & ~(LOOP_PAYLOAD | LOOP_LINE));
2273         }
2274
2275   /* RX Test Pattern status */
2276   if ((DRIVER_DEBUG) && (isr0 & 0x10))
2277     printf("%s: RX Test Pattern Sync\n", NAME_UNIT);
2278
2279   /* SNMP Error Counters */
2280   sc->status.snmp.t1.lcv  = LCV;
2281   sc->status.snmp.t1.fe   = FERR;
2282   sc->status.snmp.t1.crc  = CRC;
2283   sc->status.snmp.t1.febe = FEBE;
2284
2285   /* SNMP Line Status */
2286   sc->status.snmp.t1.line = 0;
2287   if  (alm1 & ALM1_RMYEL)  sc->status.snmp.t1.line |= TLINE_RX_RAI;
2288   if  (alm1 & ALM1_RYEL)   sc->status.snmp.t1.line |= TLINE_RX_RAI;
2289   if  (alm1 & ALM1_RLOF)   sc->status.snmp.t1.line |= TLINE_TX_RAI;
2290   if  (alm1 & ALM1_RAIS)   sc->status.snmp.t1.line |= TLINE_RX_AIS;
2291   if  (alm1 & ALM1_RLOS)   sc->status.snmp.t1.line |= TLINE_TX_AIS;
2292   if  (alm1 & ALM1_RLOF)   sc->status.snmp.t1.line |= TLINE_LOF;
2293   if  (alm1 & ALM1_RLOS)   sc->status.snmp.t1.line |= TLINE_LOS;
2294   if  (alm3 & ALM3_RMAIS)  sc->status.snmp.t1.line |= T1LINE_RX_TS16_AIS;
2295   if  (alm3 & ALM3_SRED)   sc->status.snmp.t1.line |= T1LINE_TX_TS16_LOMF;
2296   if  (alm3 & ALM3_SEF)    sc->status.snmp.t1.line |= T1LINE_SEF;
2297   if  (isr0 & 0x10)        sc->status.snmp.t1.line |= T1LINE_RX_TEST;
2298   if ((alm1 & ALM1_RMYEL) && (FORMAT_E1CAS))
2299                            sc->status.snmp.t1.line |= T1LINE_RX_TS16_LOMF;
2300
2301   /* SNMP Loopback Status */
2302   sc->status.snmp.t1.loop &= ~(TLOOP_FAR_LINE | TLOOP_FAR_PAYLOAD);
2303   if (sc->config.loop_back == CFG_LOOP_TULIP)
2304                            sc->status.snmp.t1.loop |= TLOOP_NEAR_OTHER;
2305   if (loop & LOOP_PAYLOAD) sc->status.snmp.t1.loop |= TLOOP_NEAR_PAYLOAD;
2306   if (loop & LOOP_LINE)    sc->status.snmp.t1.loop |= TLOOP_NEAR_LINE;
2307   if (loop & LOOP_ANALOG)  sc->status.snmp.t1.loop |= TLOOP_NEAR_OTHER;
2308   if (loop & LOOP_FRAMER)  sc->status.snmp.t1.loop |= TLOOP_NEAR_INWARD;
2309
2310   /* Remember this state until next time. */
2311   sc->last_alm1 = alm1;
2312
2313   /* If an INWARD loopback is in effect, link status is UP */
2314   if (sc->config.loop_back != CFG_LOOP_NONE) /* XXX INWARD ONLY */
2315     link_status = STATUS_UP;
2316
2317   return link_status;
2318   }
2319
2320 /* IOCTL SYSCALL: can sleep. */
2321 static void
2322 t1_send_bop(softc_t *sc, int bop_code)
2323   {
2324   u_int8_t bop;
2325   int i;
2326
2327   /* The BOP transmitter could be sending a continuous */
2328   /*  BOP msg when told to send this BOP_25 message. */
2329   /* So save and restore the state of the BOP machine. */
2330   bop = read_framer(sc, Bt8370_BOP);
2331   write_framer(sc, Bt8370_BOP, RBOP_OFF | TBOP_OFF);
2332   for (i=0; i<40; i++) /* max delay 400 ms. */
2333     if (read_framer(sc, Bt8370_BOP_STAT) & 0x80) SLEEP(10000);
2334   /* send 25 repetitions of bop_code */
2335   write_framer(sc, Bt8370_BOP, RBOP_OFF | TBOP_25);
2336   write_framer(sc, Bt8370_TBOP, bop_code); /* order matters */
2337   /* wait for tx to stop */
2338   for (i=0; i<40; i++) /* max delay 400 ms. */
2339     if (read_framer(sc, Bt8370_BOP_STAT) & 0x80) SLEEP(10000);
2340   /* Restore previous state of the BOP machine. */
2341   write_framer(sc, Bt8370_BOP, bop);
2342   }
2343
2344 /* IOCTL SYSCALL: can sleep. */
2345 static int
2346 t1_ioctl(softc_t *sc, struct ioctl *ioctl)
2347   {
2348   int error = 0;
2349
2350   switch (ioctl->cmd)
2351     {
2352     case IOCTL_SNMP_SEND:  /* set opstatus? */
2353       {
2354       switch (ioctl->data)
2355         {
2356         case TSEND_NORMAL:
2357           {
2358           write_framer(sc, Bt8370_TPATT, 0x00); /* tx pattern generator off */
2359           write_framer(sc, Bt8370_RPATT, 0x00); /* rx pattern detector off */
2360           write_framer(sc, Bt8370_TLB,   0x00); /* tx inband generator off */
2361           break;
2362           }
2363         case TSEND_LINE:
2364           {
2365           if (FORMAT_T1ESF)
2366             t1_send_bop(sc, T1BOP_LINE_UP);
2367           else if (FORMAT_T1SF)
2368             {
2369             write_framer(sc, Bt8370_LBP, 0x08); /* 10000 10000 ... */
2370             write_framer(sc, Bt8370_TLB, 0x05); /* 5 bits, framed, start */
2371             }
2372           sc->status.snmp.t1.loop |= TLOOP_FAR_LINE;
2373           break;
2374           }
2375         case TSEND_PAYLOAD:
2376           {
2377           t1_send_bop(sc, T1BOP_PAY_UP);
2378           sc->status.snmp.t1.loop |= TLOOP_FAR_PAYLOAD;
2379           break;
2380           }
2381         case TSEND_RESET:
2382           {
2383           if (sc->status.snmp.t1.loop == TLOOP_FAR_LINE)
2384             {
2385             if (FORMAT_T1ESF)
2386               t1_send_bop(sc, T1BOP_LINE_DOWN);
2387             else if (FORMAT_T1SF)
2388               {
2389               write_framer(sc, Bt8370_LBP, 0x24); /* 100100 100100 ... */
2390               write_framer(sc, Bt8370_TLB, 0x09); /* 6 bits, framed, start */
2391               }
2392             sc->status.snmp.t1.loop &= ~TLOOP_FAR_LINE;
2393             }
2394           if (sc->status.snmp.t1.loop == TLOOP_FAR_PAYLOAD)
2395             {
2396             t1_send_bop(sc, T1BOP_PAY_DOWN);
2397             sc->status.snmp.t1.loop &= ~TLOOP_FAR_PAYLOAD;
2398             }
2399           break;
2400           }
2401         case TSEND_QRS:
2402           {
2403           write_framer(sc, Bt8370_TPATT, 0x1E); /* framed QRSS */
2404           break;
2405           }
2406         default:
2407           {
2408           error = EINVAL;
2409           break;
2410           }
2411         }
2412       break;
2413       }
2414     case IOCTL_SNMP_LOOP:  /* set opstatus = test? */
2415       {
2416       u_int8_t new_loop = 0;
2417
2418       if (ioctl->data == CFG_LOOP_NONE)
2419         new_loop = 0;
2420       else if (ioctl->data == CFG_LOOP_PAYLOAD)
2421         new_loop = LOOP_PAYLOAD;
2422       else if (ioctl->data == CFG_LOOP_LINE)
2423         new_loop = LOOP_LINE;
2424       else if (ioctl->data == CFG_LOOP_OTHER)
2425         new_loop = LOOP_ANALOG;
2426       else if (ioctl->data == CFG_LOOP_INWARD)
2427         new_loop = LOOP_FRAMER;
2428       else if (ioctl->data == CFG_LOOP_DUAL)
2429         new_loop = LOOP_DUAL;
2430       else
2431         error = EINVAL;
2432       if (error == 0)
2433         {
2434         write_framer(sc, Bt8370_LOOP, new_loop);
2435         sc->config.loop_back = ioctl->data;
2436         }
2437       break;
2438       }
2439     default:
2440       error = EINVAL;
2441       break;
2442     }
2443
2444   return error;
2445   }
2446
2447 static
2448 struct card hssi_card =
2449   {
2450   .config   = hssi_config,
2451   .ident    = hssi_ident,
2452   .watchdog = hssi_watchdog,
2453   .ioctl    = hssi_ioctl,
2454   };
2455
2456 static
2457 struct card t3_card =
2458   {
2459   .config   = t3_config,
2460   .ident    = t3_ident,
2461   .watchdog = t3_watchdog,
2462   .ioctl    = t3_ioctl,
2463   };
2464
2465 static
2466 struct card ssi_card =
2467   {
2468   .config   = ssi_config,
2469   .ident    = ssi_ident,
2470   .watchdog = ssi_watchdog,
2471   .ioctl    = ssi_ioctl,
2472   };
2473
2474 static
2475 struct card t1_card =
2476   {
2477   .config   = t1_config,
2478   .ident    = t1_ident,
2479   .watchdog = t1_watchdog,
2480   .ioctl    = t1_ioctl,
2481   };
2482
2483 /* RAWIP is raw IP packets (v4 or v6) in HDLC frames with NO HEADERS. */
2484 /* No HDLC Address/Control fields!  No line control protocol at all!  */
2485 /* This code is BSD/ifnet-specific; Linux and Netgraph also do RAWIP. */
2486
2487 #if IFNET
2488
2489 # if ((defined(__FreeBSD__) && (__FreeBSD_version < 500000)) ||\
2490         defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__))
2491 static void
2492 netisr_dispatch(int isr, struct mbuf *mbuf)
2493   {
2494   struct ifqueue *intrq = NULL;
2495   int qfull = 0;
2496
2497 #if INET
2498   if (isr == NETISR_IP)   intrq = &ipintrq;
2499 #endif
2500 #if INET6
2501   if (isr == NETISR_IPV6) intrq = &ip6intrq;
2502 #endif
2503
2504   if ((intrq != NULL) && ((qfull = IF_QFULL(intrq)) == 0))
2505     {
2506     /* rxintr_cleanup() ENQUEUES in a hard interrupt. */
2507     /* networking code DEQUEUES in a soft interrupt. */
2508     /* Some BSD QUEUE routines are not interrupt-safe. */
2509     DISABLE_INTR; /* noop in FreeBSD */
2510     IF_ENQUEUE(intrq, mbuf);
2511     ENABLE_INTR;
2512     schednetisr(isr); /* schedule a soft interrupt */
2513     }
2514   else
2515     {
2516     m_freem(mbuf);
2517     if ((intrq != NULL) && (qfull != 0))
2518       IF_DROP(intrq);
2519     }
2520   }
2521 # endif /* ((__FreeBSD__ && (__FreeBSD_version < 500000)) || */
2522            /* __NetBSD__ || __OpenBSD__ || __bsdi__) */
2523
2524 /* rxintr_cleanup calls this to give a newly arrived pkt to higher levels. */
2525 static void
2526 lmc_raw_input(struct ifnet *ifp, struct mbuf *mbuf)
2527   {
2528   softc_t *sc = IFP2SC(ifp);
2529
2530   M_SETFIB(mbuf, ifp->if_fib);
2531 # if INET
2532   if (mbuf->m_data[0]>>4 == 4)
2533     netisr_dispatch(NETISR_IP,   mbuf);
2534   else
2535 # endif
2536 # if INET6
2537   if (mbuf->m_data[0]>>4 == 6)
2538     netisr_dispatch(NETISR_IPV6, mbuf);
2539   else
2540 # endif
2541     {
2542     m_freem(mbuf);
2543     sc->status.cntrs.idiscards++;
2544     if (DRIVER_DEBUG)
2545       printf("%s: lmc_raw_input: rx pkt discarded: not IPv4 or IPv6\n",
2546         NAME_UNIT);
2547     }
2548   }
2549
2550 #endif /* IFNET */
2551
2552 /* There are TWO VERSIONS of interrupt/DMA code: Linux & BSD.
2553  * Handling Linux and the BSDs with CPP directives would
2554  *  make the code unreadable, so there are two versions.
2555  * Conceptually, the two versions do the same thing and
2556  *  core_interrupt() doesn't know they are different.
2557  *
2558  * We are "standing on the head of a pin" in these routines.
2559  * Tulip CSRs can be accessed, but nothing else is interrupt-safe!
2560  * Do NOT access: MII, GPIO, SROM, BIOSROM, XILINX, SYNTH, or DAC.
2561  */
2562
2563 #if BSD /* BSD version of interrupt/DMA code */
2564
2565 /* Singly-linked tail-queues hold mbufs with active DMA.
2566  * For RX, single mbuf clusters; for TX, mbuf chains are queued.
2567  * NB: mbufs are linked through their m_nextpkt field.
2568  * Callers must hold sc->bottom_lock; not otherwise locked.
2569  */
2570
2571 /* Put an mbuf (chain) on the tail of the descriptor ring queue. */
2572 static void  /* BSD version */
2573 mbuf_enqueue(struct desc_ring *ring, struct mbuf *m)
2574   {
2575   m->m_nextpkt = NULL;
2576   if (ring->tail == NULL)
2577     ring->head = m;
2578   else
2579     ring->tail->m_nextpkt = m;
2580   ring->tail = m;
2581   }
2582
2583 /* Get an mbuf (chain) from the head of the descriptor ring queue. */
2584 static struct mbuf*  /* BSD version */
2585 mbuf_dequeue(struct desc_ring *ring)
2586   {
2587   struct mbuf *m = ring->head;
2588   if (m != NULL)
2589     if ((ring->head = m->m_nextpkt) == NULL)
2590       ring->tail = NULL;
2591   return m;
2592   }
2593
2594 # ifdef __FreeBSD__
2595 static void /* *** FreeBSD ONLY *** Callout from bus_dmamap_load() */
2596 fbsd_dmamap_load(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2597   {
2598   struct desc_ring *ring = arg;
2599   ring->nsegs = error ? 0 : nsegs;
2600   ring->segs[0] = segs[0];
2601   ring->segs[1] = segs[1];
2602   }
2603 # endif
2604
2605 /* Initialize a DMA descriptor ring. */
2606 static int  /* BSD version */
2607 create_ring(softc_t *sc, struct desc_ring *ring, int num_descs)
2608   {
2609   struct dma_desc *descs;
2610   int size_descs = sizeof(struct dma_desc)*num_descs;
2611   int i, error = 0;
2612
2613   /* The DMA descriptor array must not cross a page boundary. */
2614   if (size_descs > PAGE_SIZE)
2615     {
2616     printf("%s: DMA descriptor array > PAGE_SIZE (%d)\n", NAME_UNIT, 
2617      (u_int)PAGE_SIZE);
2618     return EINVAL;
2619     }
2620
2621 #ifdef __FreeBSD__
2622
2623   /* Create a DMA tag for descriptors and buffers. */
2624   if ((error = bus_dma_tag_create(bus_get_dma_tag(sc->dev),
2625    4, 0, BUS_SPACE_MAXADDR_32BIT,
2626    BUS_SPACE_MAXADDR, NULL, NULL, PAGE_SIZE, 2, PAGE_SIZE, BUS_DMA_ALLOCNOW,
2627 # if (__FreeBSD_version >= 502000)
2628    NULL, NULL,
2629 # endif
2630    &ring->tag)))
2631     {
2632     printf("%s: bus_dma_tag_create() failed: error %d\n", NAME_UNIT, error);
2633     return error;
2634     }
2635
2636   /* Allocate wired physical memory for DMA descriptor array */
2637   /*  and map physical address to kernel virtual address. */
2638   if ((error = bus_dmamem_alloc(ring->tag, (void**)&ring->first,
2639    BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &ring->map)))
2640     {
2641     printf("%s: bus_dmamem_alloc() failed; error %d\n", NAME_UNIT, error);
2642     return error;
2643     }
2644   descs = ring->first;
2645
2646   /* Map kernel virtual address to PCI address for DMA descriptor array. */
2647   if ((error = bus_dmamap_load(ring->tag, ring->map, descs, size_descs,
2648    fbsd_dmamap_load, ring, 0)))
2649     {
2650     printf("%s: bus_dmamap_load() failed; error %d\n", NAME_UNIT, error);
2651     return error;
2652     }
2653   ring->dma_addr = ring->segs[0].ds_addr;
2654
2655   /* Allocate dmamaps for each DMA descriptor. */
2656   for (i=0; i<num_descs; i++)
2657     if ((error = bus_dmamap_create(ring->tag, 0, &descs[i].map)))
2658       {
2659       printf("%s: bus_dmamap_create() failed; error %d\n", NAME_UNIT, error);
2660       return error;
2661       }
2662
2663 #elif (defined(__NetBSD__) || defined(__OpenBSD__))
2664
2665   /* Use the DMA tag passed to attach() for descriptors and buffers. */
2666   ring->tag = sc->pa_dmat;
2667
2668   /* Allocate wired physical memory for DMA descriptor array. */
2669   if ((error = bus_dmamem_alloc(ring->tag, size_descs, PAGE_SIZE, 0,
2670    ring->segs, 1, &ring->nsegs, BUS_DMA_NOWAIT)))
2671     {
2672     printf("%s: bus_dmamem_alloc() failed; error %d\n", NAME_UNIT, error);
2673     return error;
2674     }
2675
2676   /* Map physical address to kernel virtual address. */
2677   if ((error = bus_dmamem_map(ring->tag, ring->segs, ring->nsegs,
2678    size_descs, (caddr_t *)&ring->first, BUS_DMA_NOWAIT | BUS_DMA_COHERENT)))
2679     {
2680     printf("%s: bus_dmamem_map() failed; error %d\n", NAME_UNIT, error);
2681     return error;
2682     }
2683   descs = ring->first; /* suppress compiler warning about aliasing */
2684   memset(descs, 0, size_descs);
2685
2686   /* Allocate dmamap for PCI access to DMA descriptor array. */
2687   if ((error = bus_dmamap_create(ring->tag, size_descs, 1,
2688    size_descs, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &ring->map)))
2689     {
2690     printf("%s: bus_dmamap_create() failed; error %d\n", NAME_UNIT, error);
2691     return error;
2692     }
2693
2694   /* Map kernel virtual address to PCI address for DMA descriptor array. */
2695   if ((error = bus_dmamap_load(ring->tag, ring->map, descs, size_descs,
2696    0, BUS_DMA_NOWAIT)))
2697     {
2698     printf("%s: bus_dmamap_load() failed; error %d\n", NAME_UNIT, error);
2699     return error;
2700     }
2701   ring->dma_addr = ring->map->dm_segs[0].ds_addr;
2702
2703   /* Allocate dmamaps for each DMA descriptor. */
2704   for (i=0; i<num_descs; i++)
2705     if ((error = bus_dmamap_create(ring->tag, MAX_DESC_LEN, 2,
2706      MAX_CHUNK_LEN, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &descs[i].map)))
2707       {
2708       printf("%s: bus_dmamap_create() failed; error %d\n", NAME_UNIT, error);
2709       return error;
2710       }
2711
2712 #elif defined(__bsdi__)
2713
2714   /* Allocate wired physical memory for DMA descriptor array. */
2715   if ((ring->first = malloc(size_descs, M_DEVBUF, M_NOWAIT)) == NULL)
2716     {
2717     printf("%s: malloc() failed for DMA descriptor array\n", NAME_UNIT);
2718     return ENOMEM;
2719     }
2720   descs = ring->first;
2721   memset(descs, 0, size_descs);
2722
2723   /* Map kernel virtual address to PCI address for DMA descriptor array. */
2724   ring->dma_addr = vtophys(descs); /* Relax! BSD/OS only. */
2725
2726 #endif
2727
2728   ring->read  = descs;
2729   ring->write = descs;
2730   ring->first = descs;
2731   ring->last  = descs + num_descs -1;
2732   ring->last->control = TLP_DCTL_END_RING;
2733   ring->num_descs = num_descs;
2734   ring->size_descs = size_descs;
2735   ring->head = NULL;
2736   ring->tail = NULL;
2737
2738   return 0;
2739   }
2740
2741 /* Destroy a DMA descriptor ring */
2742 static void  /* BSD version */
2743 destroy_ring(softc_t *sc, struct desc_ring *ring)
2744   {
2745   struct dma_desc *desc;
2746   struct mbuf *m;
2747
2748   /* Free queued mbufs. */
2749   while ((m = mbuf_dequeue(ring)) != NULL)
2750     m_freem(m);
2751
2752   /* TX may have one pkt that is not on any queue. */
2753   if (sc->tx_mbuf != NULL)
2754     {
2755     m_freem(sc->tx_mbuf);
2756     sc->tx_mbuf = NULL;
2757     }
2758
2759   /* Unmap active DMA descriptors. */
2760   while (ring->read != ring->write)
2761     {
2762     bus_dmamap_unload(ring->tag, ring->read->map);
2763     if (ring->read++ == ring->last) ring->read = ring->first;
2764     }
2765
2766 #ifdef __FreeBSD__
2767
2768   /* Free the dmamaps of all DMA descriptors. */
2769   for (desc=ring->first; desc!=ring->last+1; desc++)
2770     if (desc->map != NULL)
2771       bus_dmamap_destroy(ring->tag, desc->map);
2772
2773   /* Unmap PCI address for DMA descriptor array. */
2774   if (ring->dma_addr != 0)
2775     bus_dmamap_unload(ring->tag, ring->map);
2776   /* Free kernel memory for DMA descriptor array. */
2777   if (ring->first != NULL)
2778     bus_dmamem_free(ring->tag, ring->first, ring->map);
2779   /* Free the DMA tag created for this ring. */
2780   if (ring->tag != NULL)
2781     bus_dma_tag_destroy(ring->tag);
2782
2783 #elif (defined(__NetBSD__) || defined(__OpenBSD__))
2784
2785   /* Free the dmamaps of all DMA descriptors. */
2786   for (desc=ring->first; desc!=ring->last+1; desc++)
2787     if (desc->map != NULL)
2788       bus_dmamap_destroy(ring->tag, desc->map);
2789
2790   /* Unmap PCI address for DMA descriptor array. */
2791   if (ring->dma_addr != 0)
2792     bus_dmamap_unload(ring->tag, ring->map);
2793   /* Free dmamap for DMA descriptor array. */
2794   if (ring->map != NULL)
2795     bus_dmamap_destroy(ring->tag, ring->map);
2796   /* Unmap kernel address for DMA descriptor array. */
2797   if (ring->first != NULL)
2798     bus_dmamem_unmap(ring->tag, (caddr_t)ring->first, ring->size_descs);
2799   /* Free kernel memory for DMA descriptor array. */
2800   if (ring->segs[0].ds_addr != 0)
2801     bus_dmamem_free(ring->tag, ring->segs, ring->nsegs);
2802
2803 #elif defined(__bsdi__)
2804
2805   /* Free kernel memory for DMA descriptor array. */
2806   if (ring->first != NULL)
2807     free(ring->first, M_DEVBUF);
2808
2809 #endif
2810   }
2811
2812 /* Clean up after a packet has been received. */
2813 static int  /* BSD version */
2814 rxintr_cleanup(softc_t *sc)
2815   {
2816   struct desc_ring *ring = &sc->rxring;
2817   struct dma_desc *first_desc, *last_desc;
2818   struct mbuf *first_mbuf=NULL, *last_mbuf=NULL;
2819   struct mbuf *new_mbuf;
2820   int pkt_len, desc_len;
2821
2822 #if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
2823   /* Input packet flow control (livelock prevention): */
2824   /* Give pkts to higher levels only if quota is > 0. */
2825   if (sc->quota <= 0) return 0;
2826 #endif
2827
2828   /* This looks complicated, but remember: typically packets up */
2829   /*  to 2048 bytes long fit in one mbuf and use one descriptor. */
2830
2831   first_desc = last_desc = ring->read;
2832
2833   /* ASSERTION: If there is a descriptor in the ring and the hardware has */
2834   /*  finished with it, then that descriptor will have RX_FIRST_DESC set. */
2835   if ((ring->read != ring->write) && /* descriptor ring not empty */
2836      ((ring->read->status & TLP_DSTS_OWNER) == 0) && /* hardware done */
2837      ((ring->read->status & TLP_DSTS_RX_FIRST_DESC) == 0)) /* should be set */
2838     panic("%s: rxintr_cleanup: rx-first-descriptor not set.\n", NAME_UNIT);
2839
2840   /* First decide if a complete packet has arrived. */
2841   /* Run down DMA descriptors looking for one marked "last". */
2842   /* Bail out if an active descriptor is encountered. */
2843   /* Accumulate most significant bits of packet length. */
2844   pkt_len = 0;
2845   for (;;)
2846     {
2847     if (last_desc == ring->write) return 0;  /* no more descs */
2848     if (last_desc->status & TLP_DSTS_OWNER) return 0; /* still active */
2849     if (last_desc->status & TLP_DSTS_RX_LAST_DESC) break; /* end of packet */
2850     pkt_len += last_desc->length1 + last_desc->length2; /* entire desc filled */
2851     if (last_desc++->control & TLP_DCTL_END_RING) last_desc = ring->first; /* ring wrap */
2852     }
2853
2854   /* A complete packet has arrived; how long is it? */
2855   /* H/w ref man shows RX pkt length as a 14-bit field. */
2856   /* An experiment found that only the 12 LSBs work. */
2857   if (((last_desc->status>>16)&0xFFF) == 0) pkt_len += 4096; /* carry-bit */
2858   pkt_len = (pkt_len & 0xF000) + ((last_desc->status>>16) & 0x0FFF);
2859   /* Subtract the CRC length unless doing so would underflow. */
2860   if (pkt_len >= sc->config.crc_len) pkt_len -= sc->config.crc_len;
2861
2862   /* Run down DMA descriptors again doing the following:
2863    *  1) put pkt info in pkthdr of first mbuf,
2864    *  2) link mbufs,
2865    *  3) set mbuf lengths.
2866    */
2867   first_desc = ring->read;
2868   do
2869     {
2870     /* Read a DMA descriptor from the ring. */
2871     last_desc = ring->read;
2872     /* Advance the ring read pointer. */
2873     if (ring->read++ == ring->last) ring->read = ring->first;
2874
2875     /* Dequeue the corresponding cluster mbuf. */
2876     new_mbuf = mbuf_dequeue(ring);
2877     if (new_mbuf == NULL)
2878       panic("%s: rxintr_cleanup: expected an mbuf\n", NAME_UNIT);
2879
2880     desc_len = last_desc->length1 + last_desc->length2;
2881     /* If bouncing, copy bounce buf to mbuf. */
2882     DMA_SYNC(last_desc->map, desc_len, BUS_DMASYNC_POSTREAD);
2883     /* Unmap kernel virtual address to PCI address. */
2884     bus_dmamap_unload(ring->tag, last_desc->map);
2885
2886     /* 1) Put pkt info in pkthdr of first mbuf. */
2887     if (last_desc == first_desc)
2888       {
2889       first_mbuf = new_mbuf;
2890       first_mbuf->m_pkthdr.len   = pkt_len; /* total pkt length */
2891 #if IFNET
2892       first_mbuf->m_pkthdr.rcvif = sc->ifp; /* how it got here */
2893 #else
2894       first_mbuf->m_pkthdr.rcvif = NULL;
2895 #endif
2896       }
2897     else /* 2) link mbufs. */
2898       {
2899       last_mbuf->m_next = new_mbuf;
2900       /* M_PKTHDR should be set in the first mbuf only. */
2901       new_mbuf->m_flags &= ~M_PKTHDR;
2902       }
2903     last_mbuf = new_mbuf;
2904
2905     /* 3) Set mbuf lengths. */
2906     new_mbuf->m_len = (pkt_len >= desc_len) ? desc_len : pkt_len;
2907     pkt_len -= new_mbuf->m_len;
2908     } while ((last_desc->status & TLP_DSTS_RX_LAST_DESC) == 0);
2909
2910   /* Decide whether to accept or to discard this packet. */
2911   /* RxHDLC sets MIIERR for bad CRC, abort and partial byte at pkt end. */
2912   if (((last_desc->status & TLP_DSTS_RX_BAD) == 0) &&
2913    (sc->status.oper_status == STATUS_UP) &&
2914    (first_mbuf->m_pkthdr.len > 0))
2915     {
2916     /* Optimization: copy a small pkt into a small mbuf. */
2917     if (first_mbuf->m_pkthdr.len <= COPY_BREAK)
2918       {
2919       MGETHDR(new_mbuf, M_NOWAIT, MT_DATA);
2920       if (new_mbuf != NULL)
2921         {
2922         new_mbuf->m_pkthdr.rcvif = first_mbuf->m_pkthdr.rcvif;
2923         new_mbuf->m_pkthdr.len   = first_mbuf->m_pkthdr.len;
2924         new_mbuf->m_len          = first_mbuf->m_len;
2925         memcpy(new_mbuf->m_data,   first_mbuf->m_data,
2926          first_mbuf->m_pkthdr.len);
2927         m_freem(first_mbuf);
2928         first_mbuf = new_mbuf;
2929         }
2930       }
2931     /* Include CRC and one flag byte in input byte count. */
2932     sc->status.cntrs.ibytes += first_mbuf->m_pkthdr.len + sc->config.crc_len +1;
2933     sc->status.cntrs.ipackets++;
2934 #if IFNET
2935     sc->ifp->if_ipackets++;
2936     LMC_BPF_MTAP(first_mbuf);
2937 #endif
2938 #if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
2939     sc->quota--;
2940 #endif
2941
2942     /* Give this good packet to the network stacks. */
2943 #if NETGRAPH
2944     if (sc->ng_hook != NULL) /* is hook connected? */
2945       {
2946 # if (__FreeBSD_version >= 500000)
2947       int error;  /* ignore error */
2948       NG_SEND_DATA_ONLY(error, sc->ng_hook, first_mbuf);
2949 # else /* FreeBSD-4 */
2950       ng_queue_data(sc->ng_hook, first_mbuf, NULL);
2951 # endif
2952       return 1;  /* did something */
2953       }
2954 #endif /* NETGRAPH */
2955     if (sc->config.line_pkg == PKG_RAWIP)
2956       lmc_raw_input(sc->ifp, first_mbuf);
2957     else
2958       {
2959 #if NSPPP
2960       sppp_input(sc->ifp, first_mbuf);
2961 #elif P2P
2962       new_mbuf = first_mbuf;
2963       while (new_mbuf != NULL)
2964         {
2965         sc->p2p->p2p_hdrinput(sc->p2p, new_mbuf->m_data, new_mbuf->m_len);
2966         new_mbuf = new_mbuf->m_next;
2967         }
2968       sc->p2p->p2p_input(sc->p2p, NULL);
2969       m_freem(first_mbuf);
2970 #else
2971       m_freem(first_mbuf);
2972       sc->status.cntrs.idiscards++;
2973 #endif
2974       }
2975     }
2976   else if (sc->status.oper_status != STATUS_UP)
2977     {
2978     /* If the link is down, this packet is probably noise. */
2979     m_freem(first_mbuf);
2980     sc->status.cntrs.idiscards++;
2981     if (DRIVER_DEBUG)
2982       printf("%s: rxintr_cleanup: rx pkt discarded: link down\n", NAME_UNIT);
2983     }
2984   else /* Log and discard this bad packet. */
2985     {
2986     if (DRIVER_DEBUG)
2987       printf("%s: RX bad pkt; len=%d %s%s%s%s\n",
2988        NAME_UNIT, first_mbuf->m_pkthdr.len,
2989        (last_desc->status & TLP_DSTS_RX_MII_ERR)  ? " miierr"  : "",
2990        (last_desc->status & TLP_DSTS_RX_DRIBBLE)  ? " dribble" : "",
2991        (last_desc->status & TLP_DSTS_RX_DESC_ERR) ? " descerr" : "",
2992        (last_desc->status & TLP_DSTS_RX_OVERRUN)  ? " overrun" : "");
2993     if (last_desc->status & TLP_DSTS_RX_OVERRUN)
2994       sc->status.cntrs.fifo_over++;
2995     else
2996       sc->status.cntrs.ierrors++;
2997     m_freem(first_mbuf);
2998     }
2999
3000   return 1; /* did something */
3001   }
3002
3003 /* Setup (prepare) to receive a packet. */
3004 /* Try to keep the RX descriptor ring full of empty buffers. */
3005 static int  /* BSD version */
3006 rxintr_setup(softc_t *sc)
3007   {
3008   struct desc_ring *ring = &sc->rxring;
3009   struct dma_desc *desc;
3010   struct mbuf *m;
3011   int desc_len;
3012   int error;
3013
3014   /* Ring is full if (wrap(write+1)==read) */
3015   if (((ring->write == ring->last) ? ring->first : ring->write+1) == ring->read)
3016     return 0;  /* ring is full; nothing to do */
3017
3018   /* Allocate a small mbuf and attach an mbuf cluster. */
3019   MGETHDR(m, M_NOWAIT, MT_DATA);
3020   if (m == NULL)
3021     {
3022     sc->status.cntrs.rxdma++;
3023     if (DRIVER_DEBUG)
3024       printf("%s: rxintr_setup: MGETHDR() failed\n", NAME_UNIT);
3025     return 0;
3026     }
3027   MCLGET(m, M_NOWAIT);
3028   if ((m->m_flags & M_EXT) == 0)
3029     {
3030     m_freem(m);
3031     sc->status.cntrs.rxdma++;
3032     if (DRIVER_DEBUG)
3033       printf("%s: rxintr_setup: MCLGET() failed\n", NAME_UNIT);
3034     return 0;
3035     }
3036
3037   /* Queue the mbuf for later processing by rxintr_cleanup. */
3038   mbuf_enqueue(ring, m);
3039
3040   /* Write a DMA descriptor into the ring. */
3041   /* Hardware won't see it until the OWNER bit is set. */
3042   desc = ring->write;
3043   /* Advance the ring write pointer. */
3044   if (ring->write++ == ring->last) ring->write = ring->first;
3045
3046   desc_len = (MCLBYTES < MAX_DESC_LEN) ? MCLBYTES : MAX_DESC_LEN;
3047   /* Map kernel virtual address to PCI address. */
3048   if ((error = DMA_LOAD(desc->map, m->m_data, desc_len)))
3049     printf("%s: bus_dmamap_load(rx) failed; error %d\n", NAME_UNIT, error);
3050   /* Invalidate the cache for this mbuf. */
3051   DMA_SYNC(desc->map, desc_len, BUS_DMASYNC_PREREAD);
3052
3053   /* Set up the DMA descriptor. */
3054 #ifdef __FreeBSD__
3055   desc->address1 = ring->segs[0].ds_addr;
3056 #elif (defined(__NetBSD__) || defined(__OpenBSD__))
3057   desc->address1 = desc->map->dm_segs[0].ds_addr;
3058 #elif defined(__bsdi__)
3059   desc->address1 = vtophys(m->m_data); /* Relax! BSD/OS only. */
3060 #endif
3061   desc->length1  = desc_len>>1;
3062   desc->address2 = desc->address1 + desc->length1;
3063   desc->length2  = desc_len>>1;
3064
3065   /* Before setting the OWNER bit, flush the cache (memory barrier). */
3066   DMA_SYNC(ring->map, ring->size_descs, BUS_DMASYNC_PREWRITE);
3067
3068   /* Commit the DMA descriptor to the hardware. */
3069   desc->status = TLP_DSTS_OWNER;
3070
3071   /* Notify the receiver that there is another buffer available. */
3072   WRITE_CSR(TLP_RX_POLL, 1);
3073
3074   return 1; /* did something */
3075   }
3076
3077 /* Clean up after a packet has been transmitted. */
3078 /* Free the mbuf chain and update the DMA descriptor ring. */
3079 static int  /* BSD version */
3080 txintr_cleanup(softc_t *sc)
3081   {
3082   struct desc_ring *ring = &sc->txring;
3083   struct dma_desc *desc;
3084
3085   while ((ring->read != ring->write) && /* while ring is not empty */
3086         ((ring->read->status & TLP_DSTS_OWNER) == 0))
3087     {
3088     /* Read a DMA descriptor from the ring. */
3089     desc = ring->read;
3090     /* Advance the ring read pointer. */
3091     if (ring->read++ == ring->last) ring->read = ring->first;
3092
3093     /* This is a no-op on most architectures. */
3094     DMA_SYNC(desc->map, desc->length1 + desc->length2, BUS_DMASYNC_POSTWRITE);
3095     /* Unmap kernel virtual address to PCI address. */
3096     bus_dmamap_unload(ring->tag, desc->map);
3097
3098     /* If this descriptor is the last segment of a packet, */
3099     /*  then dequeue and free the corresponding mbuf chain. */
3100     if ((desc->control & TLP_DCTL_TX_LAST_SEG) != 0)
3101       {
3102       struct mbuf *m;
3103       if ((m = mbuf_dequeue(ring)) == NULL)
3104         panic("%s: txintr_cleanup: expected an mbuf\n", NAME_UNIT);
3105
3106       /* Include CRC and one flag byte in output byte count. */
3107       sc->status.cntrs.obytes += m->m_pkthdr.len + sc->config.crc_len +1;
3108       sc->status.cntrs.opackets++;
3109 #if IFNET
3110       sc->ifp->if_opackets++;
3111       LMC_BPF_MTAP(m);
3112 #endif
3113       /* The only bad TX status is fifo underrun. */
3114       if ((desc->status & TLP_DSTS_TX_UNDERRUN) != 0)
3115         sc->status.cntrs.fifo_under++;
3116
3117       m_freem(m);
3118       return 1;  /* did something */
3119       }
3120     }
3121
3122   return 0;
3123   }
3124
3125 /* Build DMA descriptors for a transmit packet mbuf chain. */
3126 static int /* 0=success; 1=error */ /* BSD version */
3127 txintr_setup_mbuf(softc_t *sc, struct mbuf *m)
3128   {
3129   struct desc_ring *ring = &sc->txring;
3130   struct dma_desc *desc;
3131   unsigned int desc_len;
3132
3133   /* build DMA descriptors for a chain of mbufs. */
3134   while (m != NULL)
3135     {
3136     char *data = m->m_data;
3137     int length = m->m_len; /* zero length mbufs happen! */
3138
3139     /* Build DMA descriptors for one mbuf. */
3140     while (length > 0)
3141       {
3142       int error;
3143
3144       /* Ring is full if (wrap(write+1)==read) */
3145       if (((ring->temp==ring->last) ? ring->first : ring->temp+1) == ring->read)
3146         { /* Not enough DMA descriptors; try later. */
3147         for (; ring->temp!=ring->write;
3148          ring->temp = (ring->temp==ring->first)? ring->last : ring->temp-1)
3149           bus_dmamap_unload(ring->tag, ring->temp->map);
3150         sc->status.cntrs.txdma++;
3151         return 1;
3152         }
3153
3154       /* Provisionally, write a descriptor into the ring. */
3155       /* But don't change the REAL ring write pointer. */
3156       /* Hardware won't see it until the OWNER bit is set. */
3157       desc = ring->temp;
3158       /* Advance the temporary ring write pointer. */
3159       if (ring->temp++ == ring->last) ring->temp = ring->first;
3160
3161       /* Clear all control bits except the END_RING bit. */
3162       desc->control &= TLP_DCTL_END_RING;
3163       /* Don't pad short packets up to 64 bytes. */
3164       desc->control |= TLP_DCTL_TX_NO_PAD;
3165       /* Use Tulip's CRC-32 generator, if appropriate. */
3166       if (sc->config.crc_len != CFG_CRC_32)
3167         desc->control |= TLP_DCTL_TX_NO_CRC;
3168       /* Set the OWNER bit, except in the first descriptor. */
3169       if (desc != ring->write)
3170         desc->status = TLP_DSTS_OWNER;
3171
3172       desc_len = (length > MAX_CHUNK_LEN) ? MAX_CHUNK_LEN : length;
3173       /* Map kernel virtual address to PCI address. */
3174       if ((error = DMA_LOAD(desc->map, data, desc_len)))
3175         printf("%s: bus_dmamap_load(tx) failed; error %d\n", NAME_UNIT, error);
3176       /* Flush the cache and if bouncing, copy mbuf to bounce buf. */
3177       DMA_SYNC(desc->map, desc_len, BUS_DMASYNC_PREWRITE);
3178
3179       /* Prevent wild fetches if mapping fails (nsegs==0). */
3180       desc->length1  = desc->length2  = 0;
3181       desc->address1 = desc->address2 = 0;
3182 #if (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__))
3183         {
3184 # ifdef __FreeBSD__
3185         bus_dma_segment_t *segs = ring->segs;
3186         int nsegs = ring->nsegs;
3187 # elif (defined(__NetBSD__) || defined(__OpenBSD__))
3188         bus_dma_segment_t *segs = desc->map->dm_segs;
3189         int nsegs = desc->map->dm_nsegs;
3190 # endif
3191         if (nsegs >= 1)
3192           {
3193           desc->address1 = segs[0].ds_addr;
3194           desc->length1  = segs[0].ds_len;
3195           }
3196         if (nsegs == 2)
3197           {
3198           desc->address2 = segs[1].ds_addr;
3199           desc->length2  = segs[1].ds_len;
3200           }
3201         }
3202 #elif defined(__bsdi__)
3203       desc->address1 = vtophys(data); /* Relax! BSD/OS only. */
3204       desc->length1  = desc_len;
3205 #endif
3206
3207       data   += desc_len;
3208       length -= desc_len;
3209       } /* while (length > 0) */
3210
3211     m = m->m_next;
3212     } /* while (m != NULL) */
3213
3214   return 0; /* success */
3215   }
3216
3217 /* Setup (prepare) to transmit a packet. */
3218 /* Select a packet, build DMA descriptors and give packet to hardware. */
3219 /* If DMA descriptors run out, abandon the attempt and return 0. */
3220 static int  /* BSD version */
3221 txintr_setup(softc_t *sc)
3222   {
3223   struct desc_ring *ring = &sc->txring;
3224   struct dma_desc *first_desc, *last_desc;
3225
3226   /* Protect against half-up links: Don't transmit */
3227   /*  if the receiver can't hear the far end. */
3228   if (sc->status.oper_status != STATUS_UP) return 0;
3229
3230   /* Pick a packet to transmit. */
3231 #if NETGRAPH
3232   if ((sc->ng_hook != NULL) && (sc->tx_mbuf == NULL))
3233     {
3234     if (!IFQ_IS_EMPTY(&sc->ng_fastq))
3235       IFQ_DEQUEUE(&sc->ng_fastq, sc->tx_mbuf);
3236     else
3237       IFQ_DEQUEUE(&sc->ng_sndq,  sc->tx_mbuf);
3238     }
3239   else
3240 #endif
3241   if (sc->tx_mbuf == NULL)
3242     {
3243     if (sc->config.line_pkg == PKG_RAWIP)
3244       IFQ_DEQUEUE(&sc->ifp->if_snd, sc->tx_mbuf);
3245     else
3246       {
3247 #if NSPPP
3248       sc->tx_mbuf = sppp_dequeue(sc->ifp);
3249 #elif P2P
3250       if (!IFQ_IS_EMPTY(&sc->p2p->p2p_isnd))
3251         IFQ_DEQUEUE(&sc->p2p->p2p_isnd, sc->tx_mbuf);
3252       else
3253         IFQ_DEQUEUE(&sc->ifp->if_snd, sc->tx_mbuf);
3254 #endif
3255       }
3256     }
3257   if (sc->tx_mbuf == NULL) return 0;  /* no pkt to transmit */
3258
3259   /* Build DMA descriptors for an outgoing mbuf chain. */
3260   ring->temp = ring->write; /* temporary ring write pointer */
3261   if (txintr_setup_mbuf(sc, sc->tx_mbuf) != 0) return 0;
3262
3263   /* Enqueue the mbuf; txintr_cleanup will free it. */
3264   mbuf_enqueue(ring, sc->tx_mbuf);
3265
3266   /* The transmitter has room for another packet. */
3267   sc->tx_mbuf = NULL;
3268
3269   /* Set first & last segment bits. */
3270   /* last_desc is the desc BEFORE the one pointed to by ring->temp. */
3271   first_desc = ring->write;
3272   first_desc->control |= TLP_DCTL_TX_FIRST_SEG;
3273   last_desc = (ring->temp==ring->first)? ring->last : ring->temp-1;
3274    last_desc->control |= TLP_DCTL_TX_LAST_SEG;
3275   /* Interrupt at end-of-transmission?  Why bother the poor computer! */
3276 /* last_desc->control |= TLP_DCTL_TX_INTERRUPT; */
3277
3278   /* Make sure the OWNER bit is not set in the next descriptor. */
3279   /* The OWNER bit may have been set if a previous call aborted. */
3280   ring->temp->status = 0;
3281
3282   /* Commit the DMA descriptors to the software. */
3283   ring->write = ring->temp;
3284
3285   /* Before setting the OWNER bit, flush the cache (memory barrier). */
3286   DMA_SYNC(ring->map, ring->size_descs, BUS_DMASYNC_PREWRITE);
3287
3288   /* Commit the DMA descriptors to the hardware. */
3289   first_desc->status = TLP_DSTS_OWNER;
3290
3291   /* Notify the transmitter that there is another packet to send. */
3292   WRITE_CSR(TLP_TX_POLL, 1);
3293
3294   return 1; /* did something */
3295   }
3296
3297 #endif /* BSD */
3298
3299 #ifdef __linux__
3300 /* NOTE: this is the LINUX version of the interrupt/DMA code, */
3301
3302 /* Singly-linked tail-queues hold sk_buffs with active DMA.
3303  * skbuffs are linked through their sk_buff.next field.
3304  * Callers must hold sc->bottom_lock; not otherwise locked.
3305  */
3306
3307 /* Put an skbuff on the tail of the descriptor ring queue. */
3308 static void  /* Linux version */
3309 skbuff_enqueue(struct desc_ring *ring, struct sk_buff *skb)
3310   {
3311   skb->next = NULL;
3312   if (ring->tail == NULL)
3313     ring->head = skb;
3314   else
3315     ring->tail->next = skb;
3316   ring->tail = skb;
3317   }
3318
3319 /* Get an skbuff from the head of the descriptor ring queue. */
3320 static struct sk_buff*  /* Linux version */
3321 skbuff_dequeue(struct desc_ring *ring)
3322   {
3323   struct sk_buff *skb = ring->head;
3324   if (skb != NULL)
3325     if ((ring->head = skb->next) == NULL)
3326       ring->tail = NULL;
3327   return skb;
3328   }
3329
3330 /* Initialize a DMA descriptor ring. */
3331 static int  /* Linux version */
3332 create_ring(softc_t *sc, struct desc_ring *ring, int num_descs)
3333   {
3334   struct dma_desc *descs;
3335   int size_descs = sizeof(struct dma_desc)*num_descs;
3336
3337   /* Allocate and map memory for DMA descriptor array. */
3338   if ((descs = pci_alloc_consistent(sc->pci_dev, size_descs,
3339    &ring->dma_addr)) == NULL)
3340     {
3341     printk("%s: pci_alloc_consistent() failed\n", NAME_UNIT);
3342     return ENOMEM;
3343     }
3344   memset(descs, 0, size_descs);
3345
3346   ring->read  = descs;
3347   ring->write = descs;
3348   ring->first = descs;
3349   ring->last  = descs + num_descs -1;
3350   ring->last->control = TLP_DCTL_END_RING;
3351   ring->num_descs = num_descs;
3352   ring->size_descs = size_descs;
3353   ring->head = NULL;
3354   ring->tail = NULL;
3355
3356   return 0;
3357   }
3358
3359 /* Destroy a DMA descriptor ring */
3360 static void  /* Linux version */
3361 destroy_ring(softc_t *sc, struct desc_ring *ring)
3362   {
3363   struct sk_buff *skb;
3364
3365   /* Free queued skbuffs. */
3366   while ((skb = skbuff_dequeue(ring)) != NULL)
3367     dev_kfree_skb(skb);
3368
3369   /* TX may have one pkt that is not on any queue. */
3370   if (sc->tx_skb != NULL)
3371     {
3372     dev_kfree_skb(sc->tx_skb);
3373     sc->tx_skb = NULL;
3374     }
3375
3376   if (ring->first != NULL)
3377     {
3378     /* Unmap active DMA descriptors. */
3379     while (ring->read != ring->write)
3380       {
3381       pci_unmap_single(sc->pci_dev, ring->read->address1,
3382        ring->read->length1 + ring->read->length2, PCI_DMA_BIDIRECTIONAL);
3383       if (ring->read++ == ring->last) ring->read = ring->first;
3384       }
3385
3386     /* Unmap and free memory for DMA descriptor array. */
3387     pci_free_consistent(sc->pci_dev, ring->size_descs, ring->first,
3388      ring->dma_addr);
3389     }
3390   }
3391
3392 static int  /* Linux version */
3393 rxintr_cleanup(softc_t *sc)
3394   {
3395   struct desc_ring *ring = &sc->rxring;
3396   struct dma_desc *first_desc, *last_desc;
3397   struct sk_buff *first_skb=NULL, *last_skb=NULL;
3398   struct sk_buff *new_skb;
3399   int pkt_len, desc_len;
3400
3401   /* Input packet flow control (livelock prevention): */
3402   /* Give pkts to higher levels only if quota is > 0. */
3403   if (sc->quota <= 0) return 0;
3404
3405   /* This looks complicated, but remember: packets up to 4032 */
3406   /*  bytes long fit in one skbuff and use one DMA descriptor. */
3407
3408   first_desc = last_desc = ring->read;
3409
3410   /* ASSERTION: If there is a descriptor in the ring and the hardware has */
3411   /*  finished with it, then that descriptor will have RX_FIRST_DESC set. */
3412   if ((ring->read != ring->write) && /* descriptor ring not empty */
3413      ((ring->read->status & TLP_DSTS_OWNER) == 0) && /* hardware done */
3414      ((ring->read->status & TLP_DSTS_RX_FIRST_DESC) == 0)) /* should be set */
3415     panic("%s: rxintr_cleanup: rx-first-descriptor not set.\n", NAME_UNIT);
3416
3417   /* First decide if a complete packet has arrived. */
3418   /* Run down DMA descriptors looking for one marked "last". */
3419   /* Bail out if an active descriptor is encountered. */
3420   /* Accumulate most significant bits of packet length. */
3421   pkt_len = 0;
3422   for (;;)
3423     {
3424     if (last_desc == ring->write) return 0;  /* no more descs */
3425     if (last_desc->status & TLP_DSTS_OWNER) return 0; /* still active */
3426     if (last_desc->status & TLP_DSTS_RX_LAST_DESC) break; /* end of packet */
3427     pkt_len += last_desc->length1 + last_desc->length2; /* entire desc filled */
3428     if (last_desc++->control & TLP_DCTL_END_RING) last_desc = ring->first; /* ring wrap */
3429     }
3430
3431   /* A complete packet has arrived; how long is it? */
3432   /* H/w ref man shows RX pkt length as a 14-bit field. */
3433   /* An experiment found that only the 12 LSBs work. */
3434   if (((last_desc->status>>16)&0xFFF) == 0) pkt_len += 4096; /* carry-bit */
3435   pkt_len = (pkt_len & 0xF000) + ((last_desc->status>>16) & 0x0FFF);
3436   /* Subtract the CRC length unless doing so would underflow. */
3437   if (pkt_len >= sc->config.crc_len) pkt_len -= sc->config.crc_len;
3438
3439   /* Run down DMA descriptors again doing the following:
3440    *  1) put pkt info in hdr of first skbuff.
3441    *  2) put additional skbuffs on frag_list.
3442    *  3) set skbuff lengths.
3443    */
3444   first_desc = ring->read;
3445   do
3446     {
3447     /* Read a DMA descriptor from the ring. */
3448     last_desc = ring->read;
3449     /* Advance the ring read pointer. */
3450     if (ring->read++ == ring->last) ring->read = ring->first;
3451
3452     /* Dequeue the corresponding skbuff. */
3453     new_skb = skbuff_dequeue(ring);
3454     if (new_skb == NULL)
3455       panic("%s: rxintr_cleanup: expected an skbuff\n", NAME_UNIT);
3456
3457     desc_len = last_desc->length1 + last_desc->length2;
3458     /* Unmap kernel virtual addresss to PCI address. */
3459     pci_unmap_single(sc->pci_dev, last_desc->address1,
3460      desc_len, PCI_DMA_FROMDEVICE);
3461
3462     /* Set skbuff length. */
3463     skb_put(new_skb, (pkt_len >= desc_len) ? desc_len : pkt_len);
3464     pkt_len -= new_skb->len;
3465
3466     /* 1) Put pkt info in hdr of first skbuff. */
3467     if (last_desc == first_desc)
3468       {
3469       first_skb = new_skb;
3470       if (sc->config.line_pkg == PKG_RAWIP)
3471         {
3472         if      (first_skb->data[0]>>4 == 4)
3473           first_skb->protocol = htons(ETH_P_IP);
3474         else if (first_skb->data[0]>>4 == 6)
3475           first_skb->protocol = htons(ETH_P_IPV6);
3476         }
3477       else
3478 #if GEN_HDLC
3479         first_skb->protocol = hdlc_type_trans(first_skb, sc->net_dev);
3480 #else
3481         first_skb->protocol = htons(ETH_P_HDLC);
3482 #endif
3483       first_skb->mac.raw = first_skb->data;
3484       first_skb->dev = sc->net_dev;
3485       do_gettimeofday(&first_skb->stamp);
3486       sc->net_dev->last_rx = jiffies;
3487       }
3488     else /* 2) link skbuffs. */
3489       {
3490       /* Put this skbuff on the frag_list of the first skbuff. */
3491       new_skb->next = NULL;
3492       if (skb_shinfo(first_skb)->frag_list == NULL)
3493         skb_shinfo(first_skb)->frag_list = new_skb;
3494       else
3495         last_skb->next = new_skb;
3496       /* 3) set skbuff lengths. */
3497       first_skb->len      += new_skb->len;
3498       first_skb->data_len += new_skb->len;
3499       }
3500     last_skb = new_skb;
3501     } while ((last_desc->status & TLP_DSTS_RX_LAST_DESC) == 0);
3502
3503   /* Decide whether to accept or to discard this packet. */
3504   /* RxHDLC sets MIIERR for bad CRC, abort and partial byte at pkt end. */
3505   if (((last_desc->status & TLP_DSTS_RX_BAD) == 0) &&
3506    (sc->status.oper_status == STATUS_UP) &&
3507    (first_skb->len > 0))
3508     {
3509     /* Optimization: copy a small pkt into a small skbuff. */
3510     if (first_skb->len <= COPY_BREAK)
3511       if ((new_skb = skb_copy(first_skb, GFP_ATOMIC)) != NULL)
3512         {
3513         dev_kfree_skb_any(first_skb);
3514         first_skb = new_skb;
3515         }
3516
3517     /* Include CRC and one flag byte in input byte count. */
3518     sc->status.cntrs.ibytes += first_skb->len + sc->config.crc_len +1;
3519     sc->status.cntrs.ipackets++;
3520
3521     /* Give this good packet to the network stacks. */
3522     netif_receive_skb(first_skb);  /* NAPI */
3523     sc->quota--;
3524     }
3525   else if (sc->status.oper_status != STATUS_UP)
3526     {
3527     /* If the link is down, this packet is probably noise. */
3528     sc->status.cntrs.idiscards++;
3529     dev_kfree_skb_any(first_skb);
3530     if (DRIVER_DEBUG)
3531       printk("%s: rxintr_cleanup: rx pkt discarded: link down\n", NAME_UNIT);
3532     }
3533   else /* Log and discard this bad packet. */
3534     {
3535     if (DRIVER_DEBUG)
3536       printk("%s: RX bad pkt; len=%d %s%s%s%s\n",
3537        NAME_UNIT, first_skb->len,
3538        (last_desc->status & TLP_DSTS_RX_MII_ERR)  ? " miierr"  : "",
3539        (last_desc->status & TLP_DSTS_RX_DRIBBLE)  ? " dribble" : "",
3540        (last_desc->status & TLP_DSTS_RX_DESC_ERR) ? " descerr" : "",
3541        (last_desc->status & TLP_DSTS_RX_OVERRUN)  ? " overrun" : "");
3542     if (last_desc->status & TLP_DSTS_RX_OVERRUN)
3543       sc->status.cntrs.fifo_over++;
3544     else
3545       sc->status.cntrs.ierrors++;
3546     dev_kfree_skb_any(first_skb);
3547     }
3548
3549   return 1; /* did something */
3550   }
3551
3552 /* Setup (prepare) to receive a packet. */
3553 /* Try to keep the RX descriptor ring full of empty buffers. */
3554 static int  /* Linux version */
3555 rxintr_setup(softc_t *sc)
3556   {
3557   struct desc_ring *ring = &sc->rxring;
3558   struct dma_desc *desc;
3559   struct sk_buff *skb;
3560   u_int32_t dma_addr;
3561
3562   /* Ring is full if (wrap(write+1)==read) */
3563   if (((ring->write == ring->last) ? ring->first : ring->write+1) == ring->read)
3564     return 0;  /* ring is full; nothing to do */
3565
3566   /* Allocate an skbuff. */
3567   if ((skb = dev_alloc_skb(MAX_DESC_LEN)) == NULL)
3568     {
3569     sc->status.cntrs.rxdma++;
3570     if (DRIVER_DEBUG)
3571       printk("%s: rxintr_setup: dev_alloc_skb() failed\n", NAME_UNIT);
3572     return 0;
3573     }
3574   skb->dev = sc->net_dev;
3575
3576   /* Queue the skbuff for later processing by rxintr_cleanup. */
3577   skbuff_enqueue(ring, skb);
3578
3579   /* Write a DMA descriptor into the ring. */
3580   /* Hardware won't see it until the OWNER bit is set. */
3581   desc = ring->write;
3582   /* Advance the ring write pointer. */
3583   if (ring->write++ == ring->last) ring->write = ring->first;
3584
3585   /* Map kernel virtual addresses to PCI addresses. */
3586   dma_addr = pci_map_single(sc->pci_dev, skb->data,
3587    MAX_DESC_LEN, PCI_DMA_FROMDEVICE);
3588   /* Set up the DMA descriptor. */
3589   desc->address1 = dma_addr;
3590   desc->length1  = MAX_CHUNK_LEN;
3591   desc->address2 = desc->address1 + desc->length1;
3592   desc->length2  = MAX_CHUNK_LEN;
3593
3594   /* Before setting the OWNER bit, flush the cache (memory barrier). */
3595   wmb(); /* write memory barrier */
3596
3597   /* Commit the DMA descriptor to the hardware. */
3598   desc->status = TLP_DSTS_OWNER;
3599
3600   /* Notify the receiver that there is another buffer available. */
3601   WRITE_CSR(TLP_RX_POLL, 1);
3602
3603   return 1; /* did something */
3604   }
3605
3606 /* Clean up after a packet has been transmitted. */
3607 /* Free the sk_buff and update the DMA descriptor ring. */
3608 static int  /* Linux version */
3609 txintr_cleanup(softc_t *sc)
3610   {
3611   struct desc_ring *ring = &sc->txring;
3612   struct dma_desc *desc;
3613
3614   while ((ring->read != ring->write) && /* ring is not empty */
3615         ((ring->read->status & TLP_DSTS_OWNER) == 0))
3616     {
3617     /* Read a DMA descriptor from the ring. */
3618     desc = ring->read;
3619     /* Advance the ring read pointer. */
3620     if (ring->read++ == ring->last) ring->read = ring->first;
3621     /* Unmap kernel virtual address to PCI address. */
3622     pci_unmap_single(sc->pci_dev, desc->address1,
3623      desc->length1 + desc->length2, PCI_DMA_TODEVICE);
3624
3625     /* If this descriptor is the last segment of a packet, */
3626     /*  then dequeue and free the corresponding skbuff. */
3627     if ((desc->control & TLP_DCTL_TX_LAST_SEG) != 0)
3628       {
3629       struct sk_buff *skb;
3630       if ((skb = skbuff_dequeue(ring)) == NULL)
3631         panic("%s: txintr_cleanup: expected an sk_buff\n", NAME_UNIT);
3632
3633       /* Include CRC and one flag byte in output byte count. */
3634       sc->status.cntrs.obytes += skb->len + sc->config.crc_len +1;
3635       sc->status.cntrs.opackets++;
3636
3637       /* The only bad TX status is fifo underrun. */
3638       if ((desc->status & TLP_DSTS_TX_UNDERRUN) != 0)
3639         {
3640         sc->status.cntrs.fifo_under++; /* also increment oerrors? */
3641         if (DRIVER_DEBUG)
3642           printk("%s: txintr_cleanup: tx fifo underrun\n", NAME_UNIT);
3643         }
3644
3645       dev_kfree_skb_any(skb);
3646       return 1;  /* did something */
3647       }
3648     }
3649
3650   return 0;
3651   }
3652
3653 /* Build DMA descriptors for a tranmit packet fragment, */
3654 /* Assertion: fragment is contiguous in physical memory. */
3655 static int /* 0=success; 1=error */ /* linux version */
3656 txintr_setup_frag(softc_t *sc, char *data, int length)
3657   {
3658   struct desc_ring *ring = &sc->txring;
3659   struct dma_desc *desc;
3660   unsigned int desc_len;
3661   u_int32_t dma_addr;
3662
3663   while (length > 0)
3664     {
3665     /* Ring is full if (wrap(write+1)==read) */
3666     if (((ring->temp==ring->last) ? ring->first : ring->temp+1) == ring->read)
3667       { /* Not enough DMA descriptors; try later. */
3668       for (; ring->temp!=ring->write;
3669        ring->temp = (ring->temp==ring->first)? ring->last : ring->temp-1)
3670         pci_unmap_single(sc->pci_dev, ring->temp->address1,
3671          ring->temp->length1 + ring->temp->length2, PCI_DMA_FROMDEVICE);
3672       sc->status.cntrs.txdma++;
3673       return 1;
3674       }
3675
3676     /* Provisionally, write a DMA descriptor into the ring. */
3677     /* But don't change the REAL ring write pointer. */
3678     /* Hardware won't see it until the OWNER bit is set. */
3679     desc = ring->temp;
3680     /* Advance the temporary ring write pointer. */
3681     if (ring->temp++ == ring->last) ring->temp = ring->first;
3682
3683     /* Clear all control bits except the END_RING bit. */
3684     desc->control &= TLP_DCTL_END_RING;
3685     /* Don't pad short packets up to 64 bytes */
3686     desc->control |= TLP_DCTL_TX_NO_PAD;
3687     /* Use Tulip's CRC-32 generator, if appropriate. */
3688     if (sc->config.crc_len != CFG_CRC_32)
3689       desc->control |= TLP_DCTL_TX_NO_CRC;
3690     /* Set the OWNER bit, except in the first descriptor. */
3691     if (desc != ring->write)
3692       desc->status = TLP_DSTS_OWNER;
3693
3694     desc_len = (length >= MAX_DESC_LEN) ? MAX_DESC_LEN : length;
3695     /* Map kernel virtual address to PCI address. */
3696     dma_addr = pci_map_single(sc->pci_dev, data, desc_len, PCI_DMA_TODEVICE);
3697     /* If it will fit in one chunk, do so, otherwise split it. */
3698     if (desc_len <= MAX_CHUNK_LEN)
3699       {
3700       desc->address1 = dma_addr;
3701       desc->length1  = desc_len;
3702       desc->address2 = 0;
3703       desc->length2  = 0;
3704       }
3705     else
3706       {
3707       desc->address1 = dma_addr;
3708       desc->length1  = desc_len>>1;
3709       desc->address2 = desc->address1 + desc->length1;
3710       desc->length2  = desc_len>>1;
3711       if (desc_len & 1) desc->length2++;
3712       }
3713
3714     data   += desc_len;
3715     length -= desc_len;
3716     } /* while (length > 0) */
3717
3718   return 0; /* success */
3719   }
3720
3721 /* NB: this procedure is recursive! */
3722 static int /* 0=success; 1=error */
3723 txintr_setup_skb(softc_t *sc, struct sk_buff *skb)
3724   {
3725   struct sk_buff *list;
3726   int i;
3727
3728   /* First, handle the data in the skbuff itself. */
3729   if (txintr_setup_frag(sc, skb->data, skb_headlen(skb)))
3730     return 1;
3731
3732   /* Next, handle the VM pages in the Scatter/Gather list. */
3733   if (skb_shinfo(skb)->nr_frags != 0)
3734     for (i=0; i<skb_shinfo(skb)->nr_frags; i++)
3735       {
3736       skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3737       if (txintr_setup_frag(sc, page_address(frag->page) +
3738        frag->page_offset, frag->size))
3739         return 1;
3740       }
3741
3742   /* Finally, handle the skbuffs in the frag_list. */
3743   if ((list = skb_shinfo(skb)->frag_list) != NULL)
3744     for (; list; list=list->next)
3745       if (txintr_setup_skb(sc, list)) /* recursive! */
3746         return 1;
3747
3748   return 0;
3749   }
3750
3751 /* Setup (prepare) to transmit a packet. */
3752 /* Select a packet, build DMA descriptors and give packet to hardware. */
3753 /* If DMA descriptors run out, abandon the attempt and return 0. */
3754 static int  /* Linux version */
3755 txintr_setup(softc_t *sc)
3756   {
3757   struct desc_ring *ring = &sc->txring;
3758   struct dma_desc *first_desc, *last_desc;
3759
3760   /* Protect against half-up links: Don't transmit */
3761   /*  if the receiver can't hear the far end. */
3762   if (sc->status.oper_status != STATUS_UP) return 0;
3763
3764   /* Pick a packet to transmit. */
3765   /* linux_start() puts packets in sc->tx_skb. */
3766   if (sc->tx_skb == NULL)
3767     {
3768     if (netif_queue_stopped(sc->net_dev) != 0)
3769       netif_wake_queue(sc->net_dev);
3770     return 0; /* no pkt to transmit */
3771     }
3772
3773   /* Build DMA descriptors for an outgoing skbuff. */
3774   ring->temp = ring->write; /* temporary ring write pointer */
3775   if (txintr_setup_skb(sc, sc->tx_skb) != 0) return 0;
3776
3777   /* Enqueue the skbuff; txintr_cleanup will free it. */
3778   skbuff_enqueue(ring, sc->tx_skb);
3779
3780   /* The transmitter has room for another packet. */
3781   sc->tx_skb = NULL;
3782
3783   /* Set first & last segment bits. */
3784   /* last_desc is the desc BEFORE the one pointed to by ring->temp. */
3785   first_desc = ring->write;
3786   first_desc->control |= TLP_DCTL_TX_FIRST_SEG;
3787   last_desc = (ring->temp==ring->first)? ring->last : ring->temp-1;
3788    last_desc->control |= TLP_DCTL_TX_LAST_SEG;
3789   /* Interrupt at end-of-transmission?  Why bother the poor computer! */
3790 /* last_desc->control |= TLP_DCTL_TX_INTERRUPT; */
3791
3792   /* Make sure the OWNER bit is not set in the next descriptor. */
3793   /* The OWNER bit may have been set if a previous call aborted. */
3794   ring->temp->status = 0;
3795
3796   /* Commit the DMA descriptors to the software. */
3797   ring->write = ring->temp;
3798
3799   /* Before setting the OWNER bit, flush the cache (memory barrier). */
3800   wmb(); /* write memory barrier */
3801
3802   /* Commit the DMA descriptors to the hardware. */
3803   first_desc->status = TLP_DSTS_OWNER;
3804
3805   /* Notify the transmitter that there is another packet to send. */
3806   WRITE_CSR(TLP_TX_POLL, 1);
3807
3808   sc->net_dev->trans_start = jiffies;
3809
3810   return 1; /* did something */
3811   }
3812
3813 #endif /* __linux__ */
3814
3815 static void
3816 check_intr_status(softc_t *sc)
3817   {
3818   u_int32_t status, cfcs, op_mode;
3819   u_int32_t missed, overruns;
3820
3821   /* Check for four unusual events:
3822    *  1) fatal PCI bus errors       - some are recoverable
3823    *  2) transmitter FIFO underruns - increase fifo threshold
3824    *  3) receiver FIFO overruns     - clear potential hangup
3825    *  4) no receive descs or bufs   - count missed packets
3826    */
3827
3828   /* 1) A fatal bus error causes a Tulip to stop initiating bus cycles. */
3829   /* Module unload/load or boot are the only fixes for Parity Errors. */
3830   /* Master and Target Aborts can be cleared and life may continue. */
3831   status = READ_CSR(TLP_STATUS);
3832   if ((status & TLP_STAT_FATAL_ERROR) != 0)
3833     {
3834     u_int32_t fatal = (status & TLP_STAT_FATAL_BITS)>>TLP_STAT_FATAL_SHIFT;
3835     printf("%s: FATAL PCI BUS ERROR: %s%s%s%s\n", NAME_UNIT,
3836      (fatal == 0) ? "PARITY ERROR" : "",
3837      (fatal == 1) ? "MASTER ABORT" : "",
3838      (fatal == 2) ? "TARGET ABORT" : "",
3839      (fatal >= 3) ? "RESERVED (?)" : "");
3840     cfcs = READ_PCI_CFG(sc, TLP_CFCS);  /* try to clear it */
3841     cfcs &= ~(TLP_CFCS_MSTR_ABORT | TLP_CFCS_TARG_ABORT);
3842     WRITE_PCI_CFG(sc, TLP_CFCS, cfcs);
3843     }
3844
3845   /* 2) If the transmitter fifo underruns, increase the transmit fifo */
3846   /*  threshold: the number of bytes required to be in the fifo */
3847   /*  before starting the transmitter (cost: increased tx delay). */
3848   /* The TX_FSM must be stopped to change this parameter. */
3849   if ((status & TLP_STAT_TX_UNDERRUN) != 0)
3850     {
3851     op_mode = READ_CSR(TLP_OP_MODE);
3852     /* enable store-and-forward mode if tx_threshold tops out? */
3853     if ((op_mode & TLP_OP_TX_THRESH) < TLP_OP_TX_THRESH)
3854       {
3855       op_mode += 0x4000;  /* increment TX_THRESH field; can't overflow */
3856       WRITE_CSR(TLP_OP_MODE, op_mode & ~TLP_OP_TX_RUN);
3857       /* Wait for the TX FSM to stop; it might be processing a pkt. */
3858       while (READ_CSR(TLP_STATUS) & TLP_STAT_TX_FSM); /* XXX HANG */
3859       WRITE_CSR(TLP_OP_MODE, op_mode); /* restart tx */
3860       if (DRIVER_DEBUG)
3861         printf("%s: tx underrun; tx fifo threshold now %d bytes\n",
3862          NAME_UNIT, 128<<((op_mode>>TLP_OP_TR_SHIFT)&3));
3863       }
3864     }
3865
3866   /* 3) Errata memo from Digital Equipment Corp warns that 21140A */
3867   /* receivers through rev 2.2 can hang if the fifo overruns. */
3868   /* Recommended fix: stop and start the RX FSM after an overrun. */
3869   missed = READ_CSR(TLP_MISSED);
3870   if ((overruns = ((missed & TLP_MISS_OVERRUN)>>TLP_OVERRUN_SHIFT)) != 0)
3871     {
3872     if (DRIVER_DEBUG)
3873       printf("%s: rx overrun cntr=%d\n", NAME_UNIT, overruns);
3874     sc->status.cntrs.overruns += overruns;
3875     if ((READ_PCI_CFG(sc, TLP_CFRV) & 0xFF) <= 0x22)
3876       {
3877       op_mode = READ_CSR(TLP_OP_MODE);
3878       WRITE_CSR(TLP_OP_MODE, op_mode & ~TLP_OP_RX_RUN);
3879       /* Wait for the RX FSM to stop; it might be processing a pkt. */
3880       while (READ_CSR(TLP_STATUS) & TLP_STAT_RX_FSM); /* XXX HANG */
3881       WRITE_CSR(TLP_OP_MODE, op_mode);  /* restart rx */
3882       }
3883     }
3884
3885   /* 4) When the receiver is enabled and a packet arrives, but no DMA */
3886   /*  descriptor is available, the packet is counted as 'missed'. */
3887   /* The receiver should never miss packets; warn if it happens. */
3888   if ((missed = (missed & TLP_MISS_MISSED)) != 0)
3889     {
3890     if (DRIVER_DEBUG)
3891       printf("%s: rx missed %d pkts\n", NAME_UNIT, missed);
3892     sc->status.cntrs.missed += missed;
3893     }
3894   }
3895
3896 static void /* This is where the work gets done. */
3897 core_interrupt(void *arg, int check_status)
3898   {
3899   softc_t *sc = arg;
3900   int activity;
3901
3902   /* If any CPU is inside this critical section, then */
3903   /* other CPUs should go away without doing anything. */
3904   if (BOTTOM_TRYLOCK == 0)
3905     {
3906     sc->status.cntrs.lck_intr++;
3907     return;
3908     }
3909
3910   /* Clear pending card interrupts. */
3911   WRITE_CSR(TLP_STATUS, READ_CSR(TLP_STATUS));
3912
3913   /* In Linux, pci_alloc_consistent() means DMA descriptors */
3914   /*  don't need explicit syncing. */
3915 #if BSD
3916   {
3917   struct desc_ring *ring = &sc->txring;
3918   DMA_SYNC(sc->txring.map, sc->txring.size_descs,
3919    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
3920   ring = &sc->rxring;
3921   DMA_SYNC(sc->rxring.map, sc->rxring.size_descs,
3922    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
3923   }
3924 #endif
3925
3926   do  /* This is the main loop for interrupt processing. */
3927     {
3928     activity  = txintr_cleanup(sc);
3929     activity += txintr_setup(sc);
3930     activity += rxintr_cleanup(sc);
3931     activity += rxintr_setup(sc);
3932     } while (activity);
3933
3934 #if BSD
3935   {
3936   struct desc_ring *ring = &sc->txring;
3937   DMA_SYNC(sc->txring.map, sc->txring.size_descs,
3938    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3939   ring = &sc->rxring;
3940   DMA_SYNC(sc->rxring.map, sc->rxring.size_descs,
3941    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3942   }
3943 #endif
3944
3945   /* As the interrupt is dismissed, check for four unusual events. */
3946   if (check_status) check_intr_status(sc);
3947
3948   BOTTOM_UNLOCK;
3949   }
3950
3951 /* user_interrupt() may be called from a syscall or a softirq */
3952 static void
3953 user_interrupt(softc_t *sc, int check_status)
3954   {
3955   DISABLE_INTR; /* noop on FreeBSD-5 and Linux */
3956   core_interrupt(sc, check_status);
3957   ENABLE_INTR;  /* noop on FreeBSD-5 and Linux */
3958   }
3959
3960 #if BSD
3961
3962 # if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
3963
3964 /* Service the card from the kernel idle loop without interrupts. */
3965 static int
3966 fbsd_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
3967   {
3968   softc_t *sc = IFP2SC(ifp);
3969
3970 #if (__FreeBSD_version < 700000)
3971   if ((ifp->if_capenable & IFCAP_POLLING) == 0)
3972     {
3973     ether_poll_deregister(ifp);
3974     cmd = POLL_DEREGISTER;
3975     }
3976
3977   if (cmd == POLL_DEREGISTER)
3978     {
3979     /* Last call -- reenable card interrupts. */
3980     WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);
3981     return 0;
3982     }
3983 #endif
3984
3985   sc->quota = count;
3986   core_interrupt(sc, (cmd==POLL_AND_CHECK_STATUS));
3987   return 0;
3988   }
3989
3990 # endif  /* (__FreeBSD__ && DEVICE_POLLING) */
3991
3992 /* BSD kernels call this procedure when an interrupt happens. */
3993 static intr_return_t
3994 bsd_interrupt(void *arg)
3995   {
3996   softc_t *sc = arg;
3997
3998   /* Cut losses early if this is not our interrupt. */
3999   if ((READ_CSR(TLP_STATUS) & TLP_INT_TXRX) == 0)
4000     return IRQ_NONE;
4001
4002 # if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
4003   if (sc->ifp->if_capenable & IFCAP_POLLING)
4004     return IRQ_NONE;
4005
4006   if ((sc->ifp->if_capabilities & IFCAP_POLLING) &&
4007    (ether_poll_register(fbsd_poll, sc->ifp)))
4008     {
4009     WRITE_CSR(TLP_INT_ENBL, TLP_INT_DISABLE);
4010     return IRQ_NONE;
4011     }
4012   else
4013     sc->quota = sc->rxring.num_descs; /* input flow control */
4014 # endif  /* (__FreeBSD__ && DEVICE_POLLING) */
4015
4016   /* Disable card interrupts. */
4017   WRITE_CSR(TLP_INT_ENBL, TLP_INT_DISABLE);
4018
4019   core_interrupt(sc, 0);
4020
4021   /* Enable card interrupts. */
4022   WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);
4023
4024   return IRQ_HANDLED;
4025   }
4026
4027 #endif /* BSD */
4028
4029 /* Administrative status of the driver (UP or DOWN) has changed. */
4030 /* A card-specific action may be required: T1 and T3 cards: no-op. */
4031 /* HSSI and SSI cards change the state of modem ready signals. */
4032 static void
4033 set_status(softc_t *sc, int status)
4034   {
4035   struct ioctl ioctl;
4036
4037   ioctl.cmd = IOCTL_SET_STATUS;
4038   ioctl.data = status;
4039
4040   sc->card->ioctl(sc, &ioctl);
4041   }
4042
4043 #if P2P
4044
4045 /* Callout from P2P: */
4046 /* Get the state of DCD (Data Carrier Detect). */
4047 static int
4048 p2p_getmdm(struct p2pcom *p2p, caddr_t result)
4049   {
4050   softc_t *sc = IFP2SC(&p2p->p2p_if);
4051
4052   /* Non-zero isn't good enough; TIOCM_CAR is 0x40. */
4053   *(int *)result = (sc->status.oper_status==STATUS_UP) ? TIOCM_CAR : 0;
4054
4055   return 0;
4056   }
4057
4058 /* Callout from P2P: */
4059 /* Set the state of DTR (Data Terminal Ready). */
4060 static int
4061 p2p_mdmctl(struct p2pcom *p2p, int flag)
4062   {
4063   softc_t *sc = IFP2SC(&p2p->p2p_if);
4064
4065   set_status(sc, flag);
4066
4067   return 0;
4068   }
4069
4070 #endif /* P2P */
4071
4072 #if NSPPP
4073
4074 # ifndef PP_FR
4075 #  define PP_FR 0
4076 # endif
4077
4078 /* Callout from SPPP: */
4079 static void
4080 sppp_tls(struct sppp *sppp)
4081   {
4082 # ifdef __FreeBSD__
4083   if (!(sppp->pp_mode  & IFF_LINK2) &&
4084       !(sppp->pp_flags & PP_FR))
4085 # elif defined(__NetBSD__) || defined(__OpenBSD__)
4086   if (!(sppp->pp_flags & PP_CISCO))
4087 # endif
4088     sppp->pp_up(sppp);
4089   }
4090
4091 /* Callout from SPPP: */
4092 static void
4093 sppp_tlf(struct sppp *sppp)
4094   {
4095 # ifdef __FreeBSD__
4096   if (!(sppp->pp_mode  & IFF_LINK2) &&
4097       !(sppp->pp_flags & PP_FR))
4098 # elif defined(__NetBSD__) || defined(__OpenBSD__)
4099   if (!(sppp->pp_flags & PP_CISCO))
4100 # endif
4101     sppp->pp_down(sppp);
4102   }
4103
4104 #endif /* NSPPP */
4105
4106 /* Configure line protocol stuff.
4107  * Called by attach_card() during module init.
4108  * Called by core_ioctl()  when lmcconfig writes sc->config.
4109  * Called by detach_card() during module shutdown.
4110  */
4111 static void
4112 config_proto(softc_t *sc, struct config *config)
4113   {
4114   /* Use line protocol stack instead of RAWIP mode. */
4115   if ((sc->config.line_pkg == PKG_RAWIP) &&
4116          (config->line_pkg != PKG_RAWIP))
4117     {
4118 #if NSPPP
4119     LMC_BPF_DETACH;
4120     sppp_attach(sc->ifp);
4121     LMC_BPF_ATTACH(DLT_PPP, 4);
4122     sc->sppp->pp_tls = sppp_tls;
4123     sc->sppp->pp_tlf = sppp_tlf;
4124     /* Force reconfiguration of SPPP params. */
4125     sc->config.line_prot = 0;
4126     sc->config.keep_alive = config->keep_alive ? 0:1;
4127 #elif P2P
4128     int error = 0;
4129     sc->p2p->p2p_proto = 0; /* force p2p_attach */
4130     if ((error = p2p_attach(sc->p2p))) /* calls bpfattach() */
4131       {
4132       printf("%s: p2p_attach() failed; error %d\n", NAME_UNIT, error);
4133       config->line_pkg = PKG_RAWIP;  /* still in RAWIP mode */
4134       }
4135     else
4136       {
4137       sc->p2p->p2p_mdmctl = p2p_mdmctl; /* set DTR */
4138       sc->p2p->p2p_getmdm = p2p_getmdm; /* get DCD */
4139       }
4140 #elif GEN_HDLC
4141     int error = 0;
4142     sc->net_dev->mtu = HDLC_MAX_MTU;
4143     if ((error = hdlc_open(sc->net_dev)))
4144       {
4145       printf("%s: hdlc_open() failed; error %d\n", NAME_UNIT, error);
4146       printf("%s: Try 'sethdlc %s ppp'\n", NAME_UNIT, NAME_UNIT);
4147       config->line_pkg = PKG_RAWIP;  /* still in RAWIP mode */
4148       }
4149 #else /* no line protocol stack was configured */
4150     config->line_pkg = PKG_RAWIP;  /* still in RAWIP mode */
4151 #endif
4152     }
4153
4154   /* Bypass line protocol stack and return to RAWIP mode. */
4155   if ((sc->config.line_pkg != PKG_RAWIP) &&
4156          (config->line_pkg == PKG_RAWIP))
4157     {
4158 #if NSPPP
4159     LMC_BPF_DETACH;
4160     sppp_flush(sc->ifp);
4161     sppp_detach(sc->ifp);
4162     setup_ifnet(sc->ifp);
4163     LMC_BPF_ATTACH(DLT_RAW, 0);
4164 #elif P2P
4165     int error = 0;
4166     if_qflush(&sc->p2p->p2p_isnd);
4167     if ((error = p2p_detach(sc->p2p)))
4168       {
4169       printf("%s: p2p_detach() failed; error %d\n",  NAME_UNIT, error);
4170       printf("%s: Try 'ifconfig %s down -remove'\n", NAME_UNIT, NAME_UNIT);
4171       config->line_pkg = PKG_P2P; /* not in RAWIP mode; still attached to P2P */
4172       }
4173     else
4174       {
4175       setup_ifnet(sc->ifp);
4176       LMC_BPF_ATTACH(DLT_RAW, 0);
4177       }
4178 #elif GEN_HDLC
4179     hdlc_proto_detach(sc->hdlc_dev);
4180     hdlc_close(sc->net_dev);
4181     setup_netdev(sc->net_dev);
4182 #endif
4183     }
4184
4185 #if NSPPP
4186
4187   if (config->line_pkg != PKG_RAWIP)
4188     {
4189     /* Check for change to PPP protocol. */
4190     if ((sc->config.line_prot != PROT_PPP) &&
4191            (config->line_prot == PROT_PPP))
4192       {
4193       LMC_BPF_DETACH;
4194 # if (defined(__NetBSD__) || defined(__OpenBSD__))
4195       sc->sppp->pp_flags &= ~PP_CISCO;
4196 # elif defined(__FreeBSD__)
4197       sc->ifp->if_flags  &= ~IFF_LINK2;
4198       sc->sppp->pp_flags &= ~PP_FR;
4199 # endif
4200       LMC_BPF_ATTACH(DLT_PPP, 4);
4201       sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
4202       }
4203
4204 # ifndef DLT_C_HDLC
4205 #  define DLT_C_HDLC DLT_PPP
4206 # endif
4207
4208     /* Check for change to C_HDLC protocol. */
4209     if ((sc->config.line_prot != PROT_C_HDLC) &&
4210            (config->line_prot == PROT_C_HDLC))
4211       {
4212       LMC_BPF_DETACH;
4213 # if (defined(__NetBSD__) || defined(__OpenBSD__))
4214       sc->sppp->pp_flags |=  PP_CISCO;
4215 # elif defined(__FreeBSD__)
4216       sc->ifp->if_flags  |=  IFF_LINK2;
4217       sc->sppp->pp_flags &= ~PP_FR;
4218 # endif
4219       LMC_BPF_ATTACH(DLT_C_HDLC, 4);
4220       sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
4221       }
4222
4223     /* Check for change to Frame Relay protocol. */
4224     if ((sc->config.line_prot != PROT_FRM_RLY) &&
4225            (config->line_prot == PROT_FRM_RLY))
4226       {
4227       LMC_BPF_DETACH;
4228 # if (defined(__NetBSD__) || defined(__OpenBSD__))
4229       sc->sppp->pp_flags &= ~PP_CISCO;
4230 # elif defined(__FreeBSD__)
4231       sc->ifp->if_flags  &= ~IFF_LINK2;
4232       sc->sppp->pp_flags |= PP_FR;
4233 # endif
4234       LMC_BPF_ATTACH(DLT_FRELAY, 4);
4235       sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
4236       }
4237
4238     /* Check for disabling keep-alives. */
4239     if ((sc->config.keep_alive != 0) &&
4240            (config->keep_alive == 0))
4241       sc->sppp->pp_flags &= ~PP_KEEPALIVE;
4242
4243     /* Check for enabling keep-alives. */
4244     if ((sc->config.keep_alive == 0) &&
4245            (config->keep_alive != 0))
4246       sc->sppp->pp_flags |=  PP_KEEPALIVE;      
4247     }
4248
4249 #endif /* NSPPP */
4250
4251   /* Loop back through the TULIP Ethernet chip; (no CRC). */
4252   /* Data sheet says stop DMA before changing OPMODE register. */
4253   /* But that's not as simple as it sounds; works anyway. */
4254   /* Check for enabling loopback thru Tulip chip. */
4255   if ((sc->config.loop_back != CFG_LOOP_TULIP) &&
4256          (config->loop_back == CFG_LOOP_TULIP))
4257     {
4258     u_int32_t op_mode = READ_CSR(TLP_OP_MODE);
4259     op_mode |= TLP_OP_INT_LOOP;
4260     WRITE_CSR(TLP_OP_MODE, op_mode);
4261     config->crc_len = CFG_CRC_0;
4262     }
4263
4264   /* Check for disabling loopback thru Tulip chip. */
4265   if ((sc->config.loop_back == CFG_LOOP_TULIP) &&
4266          (config->loop_back != CFG_LOOP_TULIP))
4267     {
4268     u_int32_t op_mode = READ_CSR(TLP_OP_MODE);
4269     op_mode &= ~TLP_OP_LOOP_MODE;
4270     WRITE_CSR(TLP_OP_MODE, op_mode);
4271     config->crc_len = CFG_CRC_16;
4272     }
4273   }
4274
4275 /* This is the core ioctl procedure. */
4276 /* It handles IOCTLs from lmcconfig(8). */
4277 /* It must not run when card watchdogs run. */
4278 /* Called from a syscall (user context; no spinlocks). */
4279 /* This procedure can SLEEP. */
4280 static int
4281 core_ioctl(softc_t *sc, u_long cmd, caddr_t data)
4282   {
4283   struct iohdr  *iohdr  = (struct iohdr  *) data;
4284   struct ioctl  *ioctl  = (struct ioctl  *) data;
4285   struct status *status = (struct status *) data;
4286   struct config *config = (struct config *) data;
4287   int error = 0;
4288
4289   /* All structs start with a string and a cookie. */
4290   if (((struct iohdr *)data)->cookie != NGM_LMC_COOKIE)
4291     return EINVAL;
4292
4293   while (TOP_TRYLOCK == 0)
4294     {
4295     sc->status.cntrs.lck_ioctl++;
4296     SLEEP(10000); /* yield? */
4297     }
4298   switch (cmd)
4299     {
4300     case LMCIOCGSTAT:
4301       {
4302       *status = sc->status;
4303       iohdr->cookie = NGM_LMC_COOKIE;
4304       break;
4305       }
4306     case LMCIOCGCFG:
4307       {
4308       *config = sc->config;
4309       iohdr->cookie = NGM_LMC_COOKIE;
4310       break;
4311       }
4312     case LMCIOCSCFG:
4313       {
4314       if ((error = CHECK_CAP)) break;
4315       config_proto(sc, config);
4316       sc->config = *config;
4317       sc->card->config(sc);
4318       break;
4319       }
4320     case LMCIOCREAD:
4321       {
4322       if (ioctl->cmd == IOCTL_RW_PCI)
4323         {
4324         if (ioctl->address > 252) { error = EFAULT; break; }
4325         ioctl->data = READ_PCI_CFG(sc, ioctl->address);
4326         }
4327       else if (ioctl->cmd == IOCTL_RW_CSR)
4328         {
4329         if (ioctl->address > 15) { error = EFAULT; break; }
4330         ioctl->data = READ_CSR(ioctl->address*TLP_CSR_STRIDE);
4331         }
4332       else if (ioctl->cmd == IOCTL_RW_SROM)
4333         {
4334         if (ioctl->address > 63)  { error = EFAULT; break; }
4335         ioctl->data = read_srom(sc, ioctl->address);
4336         }
4337       else if (ioctl->cmd == IOCTL_RW_BIOS)
4338         ioctl->data = read_bios(sc, ioctl->address);
4339       else if (ioctl->cmd == IOCTL_RW_MII)
4340         ioctl->data = read_mii(sc, ioctl->address);
4341       else if (ioctl->cmd == IOCTL_RW_FRAME)
4342         ioctl->data = read_framer(sc, ioctl->address);
4343       else
4344         error = EINVAL;
4345       break;
4346       }
4347     case LMCIOCWRITE:
4348       {
4349       if ((error = CHECK_CAP)) break;
4350       if (ioctl->cmd == IOCTL_RW_PCI)
4351         {
4352         if (ioctl->address > 252) { error = EFAULT; break; }
4353         WRITE_PCI_CFG(sc, ioctl->address, ioctl->data);
4354         }
4355       else if (ioctl->cmd == IOCTL_RW_CSR)
4356         {
4357         if (ioctl->address > 15) { error = EFAULT; break; }
4358         WRITE_CSR(ioctl->address*TLP_CSR_STRIDE, ioctl->data);
4359         }
4360       else if (ioctl->cmd == IOCTL_RW_SROM)
4361         {
4362         if (ioctl->address > 63)  { error = EFAULT; break; }
4363         write_srom(sc, ioctl->address, ioctl->data); /* can sleep */
4364         }
4365       else if (ioctl->cmd == IOCTL_RW_BIOS)
4366         {
4367         if (ioctl->address == 0) erase_bios(sc);
4368         write_bios(sc, ioctl->address, ioctl->data); /* can sleep */
4369         }
4370       else if (ioctl->cmd == IOCTL_RW_MII)
4371         write_mii(sc, ioctl->address, ioctl->data);
4372       else if (ioctl->cmd == IOCTL_RW_FRAME)
4373         write_framer(sc, ioctl->address, ioctl->data);
4374       else if (ioctl->cmd == IOCTL_WO_SYNTH)
4375         write_synth(sc, (struct synth *)&ioctl->data);
4376       else if (ioctl->cmd == IOCTL_WO_DAC)
4377         {
4378         write_dac(sc, 0x9002); /* set Vref = 2.048 volts */
4379         write_dac(sc, ioctl->data & 0xFFF);
4380         }
4381       else
4382         error = EINVAL;
4383       break;
4384       }
4385     case LMCIOCTL:
4386       {
4387       if ((error = CHECK_CAP)) break;
4388       if (ioctl->cmd == IOCTL_XILINX_RESET)
4389         {
4390         reset_xilinx(sc);
4391         sc->card->config(sc);
4392         }
4393       else if (ioctl->cmd == IOCTL_XILINX_ROM)
4394         {
4395         load_xilinx_from_rom(sc); /* can sleep */
4396         sc->card->config(sc);
4397         }
4398       else if (ioctl->cmd == IOCTL_XILINX_FILE)
4399         {
4400         /* load_xilinx_from_file() can sleep. */
4401         error = load_xilinx_from_file(sc, ioctl->ucode, ioctl->data);
4402         if (error != 0) load_xilinx_from_rom(sc); /* try the rom */
4403         sc->card->config(sc);
4404         set_status(sc, (error==0));  /* XXX */
4405         }
4406       else if (ioctl->cmd == IOCTL_RESET_CNTRS)
4407         {
4408         memset(&sc->status.cntrs, 0, sizeof(struct event_cntrs));
4409         microtime(&sc->status.cntrs.reset_time);
4410         }
4411       else
4412         error = sc->card->ioctl(sc, ioctl); /* can sleep */
4413       break;
4414       }
4415     default:
4416       error = EINVAL;
4417       break;
4418     }
4419   TOP_UNLOCK;
4420
4421   return error;
4422   }
4423
4424 /* This is the core watchdog procedure. */
4425 /* It calculates link speed, and calls the card-specific watchdog code. */
4426 /* Calls interrupt() in case one got lost; also kick-starts the device. */
4427 /* ioctl syscalls and card watchdog routines must be interlocked.       */
4428 /* This procedure must not sleep. */
4429 static void
4430 core_watchdog(softc_t *sc)
4431   {
4432   /* Read and restart the Tulip timer. */
4433   u_int32_t tx_speed = READ_CSR(TLP_TIMER);
4434   WRITE_CSR(TLP_TIMER, 0xFFFF);
4435
4436   /* Measure MII clock using a timer in the Tulip chip.
4437    * This timer counts transmitter bits divided by 4096.
4438    * Since this is called once a second the math is easy.
4439    * This is only correct when the link is NOT sending pkts.
4440    * On a fully-loaded link, answer will be HALF actual rate.
4441    * Clock rate during pkt is HALF clk rate between pkts.
4442    * Measuring clock rate really measures link utilization!
4443    */
4444   sc->status.tx_speed = (0xFFFF - (tx_speed & 0xFFFF)) << 12;
4445
4446   /* The first status reset time is when the calendar clock is set. */
4447   if (sc->status.cntrs.reset_time.tv_sec < 1000)
4448     microtime(&sc->status.cntrs.reset_time);
4449
4450   /* Update hardware (operational) status. */
4451   /* Call the card-specific watchdog routines. */
4452   if (TOP_TRYLOCK != 0)
4453     {
4454     sc->status.oper_status = sc->card->watchdog(sc);
4455
4456     /* Increment a counter which tells user-land */
4457     /*  observers that SNMP state has been updated. */
4458     sc->status.ticks++;
4459
4460     TOP_UNLOCK;
4461     }
4462   else
4463     sc->status.cntrs.lck_watch++;
4464
4465   /* In case an interrupt gets lost... */
4466   user_interrupt(sc, 1);
4467   }
4468
4469 #if IFNET
4470
4471 /* Called from a syscall (user context; no spinlocks). */
4472 static int
4473 lmc_raw_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4474   {
4475   struct ifreq *ifr = (struct ifreq *) data;
4476   int error = 0;
4477
4478   switch (cmd)
4479     {
4480 # if (defined(__FreeBSD__) && defined(DEVICE_POLLING))  /* XXX necessary? */
4481     case SIOCSIFCAP:
4482 # endif
4483     case SIOCAIFADDR:
4484     case SIOCSIFFLAGS:
4485 #if 0
4486     case SIOCADDMULTI:
4487     case SIOCDELMULTI:
4488       break;
4489 #endif
4490     case SIOCSIFADDR:
4491       ifp->if_flags |= IFF_UP;  /* a Unix tradition */
4492       break;
4493     case SIOCSIFMTU:
4494       ifp->if_mtu = ifr->ifr_mtu;
4495       break;
4496     default:
4497       error = EINVAL;
4498       break;
4499     }
4500   return error;
4501   }
4502
4503 /* Called from a syscall (user context; no spinlocks). */
4504 static int
4505 lmc_ifnet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4506   {
4507   softc_t *sc = IFP2SC(ifp);
4508 # ifdef __OpenBSD__
4509   struct ifreq *ifr = (struct ifreq *) data;
4510 # endif
4511   int error = 0;
4512
4513   switch (cmd)
4514     {
4515     /* Catch the IOCTLs used by lmcconfig. */
4516     case LMCIOCGSTAT:
4517     case LMCIOCGCFG:
4518     case LMCIOCSCFG:
4519     case LMCIOCREAD:
4520     case LMCIOCWRITE:
4521     case LMCIOCTL:
4522       error = core_ioctl(sc, cmd, data);
4523       break;
4524 # ifdef __OpenBSD__
4525     /* Catch the IOCTLs used by ifconfig. */
4526     case SIOCSIFMEDIA:
4527       if ((error = CHECK_CAP)) break;
4528     case SIOCGIFMEDIA:
4529       error = ifmedia_ioctl(ifp, ifr, &sc->ifm, cmd);
4530       break;
4531     case SIOCSIFTIMESLOT:
4532       if ((error = CHECK_CAP)) break;
4533       if (sc->status.card_type == TLP_CSID_T1E1)
4534         {
4535         struct config config = sc->config;
4536         if ((error = copyin(ifr->ifr_data, &config.time_slots,
4537          sizeof config.time_slots))) break;
4538         config.iohdr.cookie = NGM_LMC_COOKIE;
4539         error = core_ioctl(sc, LMCIOCSCFG, (caddr_t)&config);
4540         }
4541       else
4542         error = EINVAL;
4543       break;
4544     case SIOCGIFTIMESLOT:
4545       if (sc->status.card_type == TLP_CSID_T1E1)
4546         error = copyout(&sc->config.time_slots, ifr->ifr_data,
4547          sizeof sc->config.time_slots);
4548       else
4549         error = EINVAL;
4550       break;
4551 # endif
4552     /* Pass the rest to the line protocol. */
4553     default:
4554       if (sc->config.line_pkg == PKG_RAWIP)
4555         error =  lmc_raw_ioctl(ifp, cmd, data);
4556       else
4557 # if NSPPP
4558         error = sppp_ioctl(ifp, cmd, data);
4559 # elif P2P
4560         error =  p2p_ioctl(ifp, cmd, data);
4561 # else
4562         error = EINVAL;
4563 # endif
4564       break;
4565     }
4566
4567   if (DRIVER_DEBUG && (error!=0))
4568     printf("%s: lmc_ifnet_ioctl; cmd=0x%08lx error=%d\n",
4569      NAME_UNIT, cmd, error);
4570
4571   return error;
4572   }
4573
4574 /* Called from a syscall (user context; no spinlocks). */
4575 static void
4576 lmc_ifnet_start(struct ifnet *ifp)
4577   {
4578   softc_t *sc = IFP2SC(ifp);
4579
4580   /* Start the transmitter; incoming pkts are NOT processed. */
4581   user_interrupt(sc, 0);
4582   }
4583
4584 /* sppp and p2p replace this with their own proc. */
4585 /* RAWIP mode is the only time this is used. */
4586 /* Called from a syscall (user context; no spinlocks). */
4587 static int
4588 lmc_raw_output(struct ifnet *ifp, struct mbuf *m,
4589  const struct sockaddr *dst, struct route *ro)
4590   {
4591   softc_t *sc = IFP2SC(ifp);
4592   int error = 0;
4593
4594   /* Fail if the link is down. */
4595   if (sc->status.oper_status != STATUS_UP)
4596     {
4597     m_freem(m);
4598     sc->status.cntrs.odiscards++;
4599     if (DRIVER_DEBUG)
4600       printf("%s: lmc_raw_output: tx pkt discarded: link down\n", NAME_UNIT);
4601     return ENETDOWN;
4602     }
4603
4604 # if NETGRAPH
4605   /* Netgraph has priority over the ifnet kernel interface. */
4606   if (sc->ng_hook != NULL)
4607     {
4608     m_freem(m);
4609     sc->status.cntrs.odiscards++;
4610     if (DRIVER_DEBUG)
4611       printf("%s: lmc_raw_output: tx pkt discarded: netgraph active\n",
4612         NAME_UNIT);
4613     return EBUSY;
4614     }
4615 # endif
4616
4617   /* lmc_raw_output() ENQUEUEs in a syscall or softirq. */
4618   /* txintr_setup() DEQUEUEs in a hard interrupt. */
4619   /* Some BSD QUEUE routines are not interrupt-safe. */
4620   {
4621   DISABLE_INTR;
4622 # if (__FreeBSD_version >= 503000)
4623   IFQ_ENQUEUE(&ifp->if_snd, m, error);
4624 # else
4625   IFQ_ENQUEUE(&ifp->if_snd, m, NULL, error);
4626 # endif
4627   ENABLE_INTR;
4628   }
4629
4630   if (error==0)
4631     user_interrupt(sc, 0); /* start the transmitter */
4632   else
4633     {
4634     m_freem(m);
4635     sc->status.cntrs.odiscards++;
4636     if (DRIVER_DEBUG)
4637       printf("%s: lmc_raw_output: IFQ_ENQUEUE() failed; error %d\n",
4638        NAME_UNIT, error);
4639     }
4640
4641   return error;
4642   }
4643
4644 /* Called from a softirq once a second. */
4645 static void
4646 lmc_watchdog(void *arg)
4647   {
4648   struct ifnet *ifp = arg;
4649   softc_t *sc = IFP2SC(ifp);
4650   u_int8_t old_oper_status = sc->status.oper_status;
4651   struct event_cntrs *cntrs = &sc->status.cntrs;
4652
4653   core_watchdog(sc); /* updates oper_status */
4654
4655 #if NETGRAPH
4656   if (sc->ng_hook != NULL)
4657     {
4658     sc->status.line_pkg  = PKG_NG;
4659     sc->status.line_prot = 0;
4660     }
4661   else
4662 #endif
4663   if (sc->config.line_pkg == PKG_RAWIP)
4664     {
4665     sc->status.line_pkg  = PKG_RAWIP;
4666     sc->status.line_prot = PROT_IP_HDLC;
4667     }
4668   else
4669     {
4670 # if P2P
4671     /* Notice change in link status. */
4672     if ((old_oper_status != sc->status.oper_status) && (sc->p2p->p2p_modem))
4673       (*sc->p2p->p2p_modem)(sc->p2p, sc->status.oper_status==STATUS_UP);
4674
4675     /* Notice change in line protocol. */
4676     sc->status.line_pkg = PKG_P2P;
4677     switch (sc->ifp->if_type)
4678       {
4679       case IFT_PPP:
4680         sc->status.line_prot = PROT_PPP;
4681         break;
4682       case IFT_PTPSERIAL:
4683         sc->status.line_prot = PROT_C_HDLC;
4684         break;
4685       case IFT_FRELAY:
4686         sc->status.line_prot = PROT_FRM_RLY;
4687         break;
4688       default:
4689         sc->status.line_prot = 0;
4690         break;
4691       }
4692
4693 # elif NSPPP
4694     /* Notice change in link status. */
4695     if     ((old_oper_status != STATUS_UP) &&
4696      (sc->status.oper_status == STATUS_UP))  /* link came up */
4697       sppp_tls(sc->sppp);
4698     if     ((old_oper_status == STATUS_UP) &&
4699      (sc->status.oper_status != STATUS_UP))  /* link went down */
4700       sppp_tlf(sc->sppp);
4701
4702     /* Notice change in line protocol. */
4703     sc->status.line_pkg = PKG_SPPP;
4704 #  ifdef __FreeBSD__
4705     if (sc->sppp->pp_flags & PP_FR)
4706       sc->status.line_prot = PROT_FRM_RLY;
4707     else if (sc->ifp->if_flags  & IFF_LINK2)
4708 #  elif (defined(__NetBSD__) || defined(__OpenBSD__))
4709     if (sc->sppp->pp_flags & PP_CISCO)
4710 #  endif
4711       sc->status.line_prot = PROT_C_HDLC;
4712     else
4713       sc->status.line_prot = PROT_PPP;
4714
4715 # else
4716     /* Suppress compiler warning. */
4717     if (old_oper_status == STATUS_UP);
4718 # endif
4719     }
4720
4721   /* Copy statistics from sc to ifp. */
4722   ifp->if_baudrate = sc->status.tx_speed;
4723   ifp->if_ipackets = cntrs->ipackets;
4724   ifp->if_opackets = cntrs->opackets;
4725   ifp->if_ibytes   = cntrs->ibytes;
4726   ifp->if_obytes   = cntrs->obytes;
4727   ifp->if_ierrors  = cntrs->ierrors;
4728   ifp->if_oerrors  = cntrs->oerrors;
4729   ifp->if_iqdrops  = cntrs->idiscards;
4730
4731 # if ((__FreeBSD_version >= 500000) || defined(__OpenBSD__) || defined(__NetBSD__))
4732   if (sc->status.oper_status == STATUS_UP)
4733     ifp->if_link_state = LINK_STATE_UP;
4734   else
4735     ifp->if_link_state = LINK_STATE_DOWN;
4736 # endif
4737
4738   /* Call this procedure again after one second. */
4739   callout_reset(&sc->callout, hz, lmc_watchdog, ifp);
4740   }
4741
4742 # ifdef __OpenBSD__
4743
4744 /* Callback from ifmedia. */
4745 static int
4746 ifmedia_change(struct ifnet *ifp)
4747   {
4748   softc_t *sc = IFP2SC(ifp);
4749   struct config config = sc->config;
4750   int media = sc->ifm.ifm_media;
4751   int error;
4752
4753   /* ifconfig lmc0 media t1 */
4754   if      (sc->status.card_type == TLP_CSID_T3)
4755     {
4756     if      ((media & IFM_TMASK) == IFM_TDM_T3)
4757       config.format = CFG_FORMAT_T3CPAR;
4758     else if ((media & IFM_TMASK) == IFM_TDM_T3_M13)
4759       config.format = CFG_FORMAT_T3M13;
4760     }
4761   else if (sc->status.card_type == TLP_CSID_T1E1)
4762     {
4763     if      ((media & IFM_TMASK) == IFM_TDM_T1)
4764       config.format = CFG_FORMAT_T1ESF;
4765     else if ((media & IFM_TMASK) == IFM_TDM_T1_AMI)
4766       config.format = CFG_FORMAT_T1SF;
4767     else if ((media & IFM_TMASK) == IFM_TDM_E1)
4768       config.format = CFG_FORMAT_E1NONE;
4769     else if ((media & IFM_TMASK) == IFM_TDM_E1_G704)
4770       config.format = CFG_FORMAT_E1FASCRC;
4771     }
4772
4773   /* ifconfig lmc0 mediaopt loopback */
4774   if (media & IFM_LOOP)
4775     config.loop_back = CFG_LOOP_TULIP;
4776   else
4777     config.loop_back = CFG_LOOP_NONE;
4778
4779   /* ifconfig lmc0 mediaopt crc16 */
4780   if (media & IFM_TDM_HDLC_CRC16)
4781     config.crc_len = CFG_CRC_16;
4782   else
4783     config.crc_len = CFG_CRC_32;
4784
4785   /* Set ConFiGuration. */
4786   config.iohdr.cookie = NGM_LMC_COOKIE;
4787   error = core_ioctl(sc, LMCIOCSCFG, (caddr_t)&config);
4788
4789   return error;
4790   }
4791
4792 /* Callback from ifmedia. */
4793 static void
4794 ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4795   {
4796   softc_t *sc = IFP2SC(ifp);
4797
4798   /* ifconfig wants to know if the hardware link is up. */
4799   ifmr->ifm_status = IFM_AVALID;
4800   if (sc->status.oper_status == STATUS_UP)
4801     ifmr->ifm_status |= IFM_ACTIVE;
4802
4803   ifmr->ifm_active = sc->ifm.ifm_cur->ifm_media;
4804
4805   if (sc->config.loop_back != CFG_LOOP_NONE)
4806     ifmr->ifm_active |= IFM_LOOP;
4807
4808   if (sc->config.crc_len == CFG_CRC_16)
4809     ifmr->ifm_active |= IFM_TDM_HDLC_CRC16;
4810   }
4811
4812 # endif  /* __OpenBSD__ */
4813
4814 static void
4815 setup_ifnet(struct ifnet *ifp)
4816   {
4817   softc_t *sc = ifp->if_softc;
4818
4819   /* Initialize the generic network interface. */
4820   /* Note similarity to linux's setup_netdev(). */
4821   ifp->if_flags    = IFF_POINTOPOINT;
4822   ifp->if_flags   |= IFF_RUNNING;
4823   ifp->if_ioctl    = lmc_ifnet_ioctl;
4824   ifp->if_start    = lmc_ifnet_start;   /* sppp changes this */
4825   ifp->if_output   = lmc_raw_output;    /* sppp & p2p change this */
4826   ifp->if_input    = lmc_raw_input;
4827   ifp->if_mtu      = MAX_DESC_LEN;      /* sppp & p2p change this */
4828   ifp->if_type     = IFT_PTPSERIAL;     /* p2p changes this */
4829
4830 # if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
4831   ifp->if_capabilities |= IFCAP_POLLING;
4832   ifp->if_capenable    |= IFCAP_POLLING_NOCOUNT;
4833 # if (__FreeBSD_version < 500000)
4834   ifp->if_capenable    |= IFCAP_POLLING;
4835 # endif
4836 # endif
4837
4838   /* Every OS does it differently! */
4839 # if (defined(__FreeBSD__) && (__FreeBSD_version < 502000))
4840   (const char *)ifp->if_name = device_get_name(sc->dev);
4841   ifp->if_unit  = device_get_unit(sc->dev);
4842 # elif (__FreeBSD_version >= 502000)
4843   if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
4844 # elif defined(__NetBSD__)
4845   strcpy(ifp->if_xname, sc->dev.dv_xname);
4846 # elif defined(__OpenBSD__)
4847   bcopy(sc->dev.dv_xname, ifp->if_xname, IFNAMSIZ);
4848 # elif defined(__bsdi__)
4849   ifp->if_name  = sc->dev.dv_cfdata->cf_driver->cd_name;
4850   ifp->if_unit  = sc->dev.dv_unit;
4851 # endif
4852   }
4853
4854 static int
4855 lmc_ifnet_attach(softc_t *sc)
4856   {
4857 # if (__FreeBSD_version >= 600000)
4858   sc->ifp  = if_alloc(NSPPP ? IFT_PPP : IFT_OTHER);
4859   if (sc->ifp == NULL) return ENOMEM;
4860 # endif
4861 # if NSPPP
4862 #  if (__FreeBSD_version >= 600000)
4863   sc->sppp = sc->ifp->if_l2com;
4864 #  else
4865   sc->ifp  = &sc->spppcom.pp_if;
4866   sc->sppp = &sc->spppcom;
4867 #  endif
4868 # elif P2P
4869   sc->ifp  = &sc->p2pcom.p2p_if;
4870   sc->p2p  = &sc->p2pcom;
4871 # elif (__FreeBSD_version < 600000)
4872   sc->ifp  = &sc->ifnet;
4873 # endif
4874
4875   /* Initialize the network interface struct. */
4876   sc->ifp->if_softc = sc;
4877   setup_ifnet(sc->ifp);
4878
4879   /* ALTQ output queue initialization. */
4880   IFQ_SET_MAXLEN(&sc->ifp->if_snd, SNDQ_MAXLEN);
4881   IFQ_SET_READY(&sc->ifp->if_snd);
4882
4883   /* Attach to the ifnet kernel interface. */
4884   if_attach(sc->ifp);
4885
4886 # if ((defined(__NetBSD__) && __NetBSD_Version__ >= 106000000) || \
4887      (defined(__OpenBSD__) && OpenBSD >= 200211))
4888   if_alloc_sadl(sc->ifp);
4889 # endif
4890
4891   /* Attach Berkeley Packet Filter. */
4892   LMC_BPF_ATTACH(DLT_RAW, 0);
4893
4894 # ifdef __OpenBSD__
4895   /* Initialize ifmedia mechanism. */
4896   ifmedia_init(&sc->ifm, IFM_OMASK | IFM_GMASK | IFM_IMASK,
4897    ifmedia_change, ifmedia_status);
4898   if       (sc->status.card_type == TLP_CSID_T3)
4899     {
4900     ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T3, 0, NULL);
4901     ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T3_M13, 0, NULL);
4902     ifmedia_set(&sc->ifm, IFM_TDM | IFM_TDM_T3);
4903     }
4904   else if  (sc->status.card_type == TLP_CSID_T1E1)
4905     {
4906     ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T1, 0, NULL);
4907     ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_T1_AMI, 0, NULL);
4908     ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_E1, 0, NULL);
4909     ifmedia_add(&sc->ifm, IFM_TDM | IFM_TDM_E1_G704, 0, NULL);
4910     ifmedia_set(&sc->ifm, IFM_TDM | IFM_TDM_T1);
4911     }
4912   else if ((sc->status.card_type == TLP_CSID_HSSI) ||
4913            (sc->status.card_type == TLP_CSID_SSI))
4914     {
4915     ifmedia_add(&sc->ifm, IFM_TDM | IFM_NONE, 0, NULL);
4916     ifmedia_set(&sc->ifm, IFM_TDM | IFM_NONE);
4917     }
4918 # endif  /* __OpenBSD__ */
4919
4920   callout_reset(&sc->callout, hz, lmc_watchdog, sc);
4921
4922   return 0;
4923   }
4924
4925 static void
4926 lmc_ifnet_detach(softc_t *sc)
4927   {
4928 # ifdef __OpenBSD__
4929   ifmedia_delete_instance(&sc->ifm, IFM_INST_ANY);
4930 # endif
4931
4932 # if (defined(__FreeBSD__) && defined(DEVICE_POLLING))
4933   if (sc->ifp->if_capenable & IFCAP_POLLING)
4934     ether_poll_deregister(sc->ifp);
4935 # endif
4936
4937   /* Detach Berkeley Packet Filter. */
4938   LMC_BPF_DETACH;
4939
4940 # if ((defined(__NetBSD__) && __NetBSD_Version__ >= 106000000) || \
4941      (defined(__OpenBSD__) && OpenBSD >= 200211))
4942   if_free_sadl(sc->ifp);
4943 # endif
4944
4945   /* Detach from the ifnet kernel interface. */
4946   if_detach(sc->ifp);
4947
4948 # if (defined(__FreeBSD__) && __FreeBSD_version >= 800082)
4949   if_free(sc->ifp);
4950 # elif (defined(__FreeBSD__) && __FreeBSD_version >= 600000)
4951   if_free_type(sc->ifp, NSPPP ? IFT_PPP : IFT_OTHER);
4952 # endif
4953   }
4954
4955 #endif  /* IFNET */
4956
4957 #if NETGRAPH
4958
4959 /* Netgraph changed significantly between FreeBSD-4 and -5. */
4960 /* These are backward compatibility hacks for FreeBSD-4. */
4961 # if (__FreeBSD_version >= 500000)
4962 /* These next two macros should be added to netgraph */
4963 #  define NG_TYPE_REF(type) atomic_add_int(&(type)->refs, 1)
4964 #  define NG_TYPE_UNREF(type)   \
4965 do {                            \
4966   if ((type)->refs == 1)        \
4967     ng_rmtype(type);            \
4968   else                          \
4969     atomic_subtract_int(&(type)->refs, 1); \
4970    } while (0)
4971 # else /* FreeBSD-4 */
4972 #  define NGI_GET_MSG(item, msg)        /* nothing */
4973 #  define NG_HOOK_FORCE_QUEUE(hook)     /* nothing */
4974 #  define NG_TYPE_REF(type) atomic_add_int(&(type)->refs, 1)
4975 #  define NG_TYPE_UNREF(type)   \
4976 do {                            \
4977   if ((type)->refs == 1)        \
4978     LIST_REMOVE(type, types);   \
4979   else                          \
4980     atomic_subtract_int(&(type)->refs, 1); \
4981    } while (0)
4982 # endif
4983
4984 /* It is an error to construct new copies of this Netgraph node. */
4985 /* All instances are constructed by ng_attach and are persistent. */
4986 # if (__FreeBSD_version >= 500000)
4987 static int ng_constructor(node_p  node) { return EINVAL; }
4988 # else /* FreeBSD-4 */
4989 static int ng_constructor(node_p *node) { return EINVAL; }
4990 # endif
4991
4992 /* Incoming Netgraph control message. */
4993 # if (__FreeBSD_version >= 500000)
4994 static int
4995 ng_rcvmsg(node_p node, item_p item, hook_p lasthook)
4996   {
4997   struct ng_mesg *msg;
4998 # else /* FreeBSD-4 */
4999 static int
5000 ng_rcvmsg(node_p node, struct ng_mesg *msg,
5001  const char *retaddr,  struct ng_mesg **rptr)
5002   {
5003 # endif
5004   struct ng_mesg *resp = NULL;
5005   softc_t *sc = NG_NODE_PRIVATE(node);
5006   int error = 0;
5007
5008   NGI_GET_MSG(item, msg);
5009   if (msg->header.typecookie == NGM_LMC_COOKIE)
5010     {
5011     switch (msg->header.cmd)
5012       {
5013       case LMCIOCGSTAT:
5014       case LMCIOCGCFG:
5015       case LMCIOCSCFG:
5016       case LMCIOCREAD:
5017       case LMCIOCWRITE:
5018       case LMCIOCTL:
5019         {
5020         /* Call the core ioctl procedure. */
5021         error = core_ioctl(sc, msg->header.cmd, msg->data);
5022         if ((msg->header.cmd & IOC_OUT) != 0)
5023           { /* synchronous response */
5024           NG_MKRESPONSE(resp, msg, sizeof(struct ng_mesg) +
5025            IOCPARM_LEN(msg->header.cmd), M_NOWAIT);
5026           if (resp == NULL)
5027             error = ENOMEM;
5028           else
5029             memcpy(resp->data, msg->data, IOCPARM_LEN(msg->header.cmd));
5030           }
5031         break;
5032         }
5033       default:
5034         error = EINVAL;
5035         break;
5036       }
5037     }
5038   else if ((msg->header.typecookie == NGM_GENERIC_COOKIE) &&
5039            (msg->header.cmd == NGM_TEXT_STATUS))
5040     {  /* synchronous response */
5041     NG_MKRESPONSE(resp, msg, sizeof(struct ng_mesg) +
5042      NG_TEXTRESPONSE, M_NOWAIT);
5043     if (resp == NULL)
5044       error = ENOMEM;
5045     else
5046       {
5047       char *s = resp->data;
5048       sprintf(s, "Card type = <%s>\n"
5049        "This driver considers the link to be %s.\n"
5050        "Use lmcconfig to configure this interface.\n",
5051        sc->dev_desc, (sc->status.oper_status==STATUS_UP) ? "UP" : "DOWN");
5052       resp->header.arglen = strlen(s) +1;
5053       }
5054     }
5055   else
5056 /* Netgraph should be able to read and write these
5057  *  parameters with text-format control messages:
5058  *  SSI      HSSI     T1E1     T3
5059  *  crc      crc      crc      crc      
5060  *  loop     loop     loop     loop
5061  *           clksrc   clksrc
5062  *  dte      dte      format   format
5063  *  synth    synth    cablen   cablen
5064  *  cable             timeslot scram
5065  *                    gain
5066  *                    pulse
5067  *                    lbo
5068  * Someday I'll implement this...
5069  */
5070     error = EINVAL;
5071
5072   /* Handle synchronous response. */
5073 # if (__FreeBSD_version >= 500000)
5074   NG_RESPOND_MSG(error, node, item, resp);
5075   NG_FREE_MSG(msg);
5076 # else /* FreeBSD-4 */
5077   if (rptr != NULL)
5078     *rptr = resp;
5079   else if (resp != NULL)
5080     free(resp, M_NETGRAPH);
5081   free(msg, M_NETGRAPH);
5082 # endif
5083
5084   return error;
5085   }
5086
5087 /* This is a persistent netgraph node. */
5088 static int
5089 ng_shutdown(node_p node)
5090   {
5091 # if (__FreeBSD_version >= 500000)
5092   /* unless told to really die, bounce back to life */
5093   if ((node->nd_flags & NG_REALLY_DIE)==0)
5094     node->nd_flags &= ~NG_INVALID; /* bounce back to life */
5095 # else /* FreeBSD-4 */
5096   ng_cutlinks(node);
5097   node->flags &= ~NG_INVALID;  /* bounce back to life */
5098 # endif
5099
5100   return 0;
5101   }
5102
5103 /* ng_disconnect is the opposite of this procedure. */
5104 static int
5105 ng_newhook(node_p node, hook_p hook, const char *name)
5106   {
5107   softc_t *sc = NG_NODE_PRIVATE(node);
5108
5109   /* Hook name must be 'rawdata'. */
5110   if (strncmp(name, "rawdata", 7) != 0) return EINVAL;
5111
5112   /* Is our hook connected? */
5113   if (sc->ng_hook != NULL) return EBUSY;
5114
5115   /* Accept the hook. */
5116   sc->ng_hook = hook;
5117
5118   return 0;
5119   }
5120
5121 /* Both ends have accepted their hooks and the links have been made. */
5122 /* This is the last chance to reject the connection request. */
5123 static int
5124 ng_connect(hook_p hook)
5125   {
5126   /* Probably not at splnet, force outward queueing. (huh?) */
5127   NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
5128   return 0; /* always accept */
5129   }
5130
5131 /* Receive data in mbufs from another Netgraph node. */
5132 /* Transmit an mbuf-chain on the communication link. */
5133 /* This procedure is very similar to lmc_raw_output(). */
5134 /* Called from a syscall (user context; no spinlocks). */
5135 # if (__FreeBSD_version >= 500000)
5136 static int
5137 ng_rcvdata(hook_p hook, item_p item)
5138   {
5139   softc_t *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
5140   int error = 0;
5141   struct mbuf *m;
5142   meta_p meta = NULL;
5143
5144   NGI_GET_M(item, m);
5145   NGI_GET_META(item, meta);
5146   NG_FREE_ITEM(item);
5147 # else /* FreeBSD-4 */
5148 static int
5149 ng_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
5150   {
5151   softc_t *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
5152   int error = 0;
5153 # endif
5154
5155   /* This macro must not store into meta! */
5156   NG_FREE_META(meta);
5157
5158   /* Fail if the link is down. */
5159   if (sc->status.oper_status  != STATUS_UP)
5160     {
5161     m_freem(m);
5162     sc->status.cntrs.odiscards++;
5163     if (DRIVER_DEBUG)
5164       printf("%s: ng_rcvdata: tx pkt discarded: link down\n", NAME_UNIT);
5165     return ENETDOWN;
5166     }
5167
5168   /* ng_rcvdata() ENQUEUEs in a syscall or softirq. */
5169   /* txintr_setup() DEQUEUEs in a hard interrupt. */
5170   /* Some BSD QUEUE routines are not interrupt-safe. */
5171   {
5172   DISABLE_INTR;
5173 # if (__FreeBSD_version >= 503000)
5174   if (meta==NULL)
5175     IFQ_ENQUEUE(&sc->ng_sndq, m, error);
5176   else
5177     IFQ_ENQUEUE(&sc->ng_fastq, m, error);
5178 # else
5179   if (meta==NULL)
5180     IFQ_ENQUEUE(&sc->ng_sndq, m, NULL, error);
5181   else
5182     IFQ_ENQUEUE(&sc->ng_fastq, m, NULL, error);
5183 # endif
5184   ENABLE_INTR;
5185   }
5186
5187   if (error==0)
5188     user_interrupt(sc, 0); /* start the transmitter */
5189   else
5190     {
5191     m_freem(m);
5192     sc->status.cntrs.odiscards++;
5193     if (DRIVER_DEBUG)
5194       printf("%s: ng_rcvdata: IFQ_ENQUEUE() failed; error %d\n",
5195        NAME_UNIT, error);
5196     }
5197
5198   return error;
5199   }
5200
5201 /* ng_newhook is the opposite of this procedure, not */
5202 /*  ng_connect, as you might expect from the names. */
5203 static int
5204 ng_disconnect(hook_p hook)
5205   {
5206   softc_t *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
5207
5208   /* Disconnect the hook. */
5209   sc->ng_hook = NULL;
5210
5211   return 0;
5212   }
5213
5214 static
5215 struct ng_type ng_type =
5216   {
5217   .version      = NG_ABI_VERSION,
5218   .name         = NG_LMC_NODE_TYPE,
5219   .mod_event    = NULL,
5220   .constructor  = ng_constructor,
5221   .rcvmsg       = ng_rcvmsg,
5222 # if (__FreeBSD_version >=503000)
5223   .close        = NULL,
5224 # endif
5225   .shutdown     = ng_shutdown,
5226   .newhook      = ng_newhook,
5227   .findhook     = NULL,
5228   .connect      = ng_connect,
5229   .rcvdata      = ng_rcvdata,
5230 # if (defined(__FreeBSD__) && (__FreeBSD_version < 500000))
5231   .rcvdataq     = ng_rcvdata,
5232 # endif
5233   .disconnect   = ng_disconnect,
5234   };
5235
5236 # if (IFNET == 0)
5237 /* Called from a softirq once a second. */
5238 static void
5239 ng_watchdog(void *arg)
5240   {
5241   softc_t *sc = arg;
5242
5243   /* Call the core watchdog procedure. */
5244   core_watchdog(sc);
5245
5246   /* Set line protocol and package status. */
5247   sc->status.line_pkg  = PKG_NG;
5248   sc->status.line_prot = 0;
5249
5250   /* Call this procedure again after one second. */
5251   callout_reset(&sc->callout, hz, ng_watchdog, sc);
5252   }
5253 # endif
5254
5255 /* Attach to the Netgraph kernel interface (/sys/netgraph).
5256  * It is called once for each physical card during device attach.
5257  * This is effectively ng_constructor.
5258  */
5259 static int
5260 ng_attach(softc_t *sc)
5261   {
5262   int error;
5263
5264   /* If this node type is not known to Netgraph then register it. */
5265   if (ng_type.refs == 0) /* or: if (ng_findtype(&ng_type) == NULL) */
5266     {
5267     if ((error = ng_newtype(&ng_type)))
5268       {
5269       printf("%s: ng_newtype() failed; error %d\n", NAME_UNIT, error);
5270       return error;
5271       }
5272     }
5273   else
5274     NG_TYPE_REF(&ng_type);
5275
5276   /* Call the superclass node constructor. */
5277   if ((error = ng_make_node_common(&ng_type, &sc->ng_node)))
5278     {
5279     NG_TYPE_UNREF(&ng_type);
5280     printf("%s: ng_make_node_common() failed; error %d\n", NAME_UNIT, error);
5281     return error;
5282     }
5283
5284   /* Associate a name with this netgraph node. */
5285   if ((error = ng_name_node(sc->ng_node, NAME_UNIT)))
5286     {
5287     NG_NODE_UNREF(sc->ng_node);
5288     NG_TYPE_UNREF(&ng_type);
5289     printf("%s: ng_name_node() failed; error %d\n", NAME_UNIT, error);
5290     return error;
5291     }
5292
5293 # if (__FreeBSD_version >= 500000)
5294   /* Initialize the send queue mutexes. */
5295   mtx_init(&sc->ng_sndq.ifq_mtx,  NAME_UNIT, "sndq",  MTX_DEF);
5296   mtx_init(&sc->ng_fastq.ifq_mtx, NAME_UNIT, "fastq", MTX_DEF);
5297 # endif
5298
5299   /* Put a backpointer to the softc in the netgraph node. */
5300   NG_NODE_SET_PRIVATE(sc->ng_node, sc);
5301
5302   /* ALTQ output queue initialization. */
5303   IFQ_SET_MAXLEN(&sc->ng_fastq, SNDQ_MAXLEN);
5304   IFQ_SET_READY(&sc->ng_fastq);
5305   IFQ_SET_MAXLEN(&sc->ng_sndq,  SNDQ_MAXLEN);
5306   IFQ_SET_READY(&sc->ng_sndq);
5307
5308 # if (IFNET == 0)
5309   /* Arrange to call ng_watchdog() once a second. */
5310   callout_reset(&sc->callout, hz, ng_watchdog, sc);
5311 # endif
5312
5313   return 0;
5314   }
5315
5316 static void
5317 ng_detach(softc_t *sc)
5318   {
5319   callout_drain(&sc->callout);
5320 # if (__FreeBSD_version >= 500000)
5321   mtx_destroy(&sc->ng_sndq.ifq_mtx);
5322   mtx_destroy(&sc->ng_fastq.ifq_mtx);
5323   ng_rmnode_self(sc->ng_node); /* free hook */
5324   NG_NODE_UNREF(sc->ng_node);  /* free node */
5325   NG_TYPE_UNREF(&ng_type);
5326 # else /* FreeBSD-4 */
5327   ng_unname(sc->ng_node);      /* free name */
5328   ng_cutlinks(sc->ng_node);    /* free hook */
5329   NG_NODE_UNREF(sc->ng_node);  /* free node */
5330   NG_TYPE_UNREF(&ng_type);
5331 # endif
5332   }
5333
5334 #endif /* NETGRAPH */
5335
5336 /* The next few procedures initialize the card. */
5337
5338 /* Returns 0 on success; error code on failure. */
5339 static int
5340 startup_card(softc_t *sc)
5341   {
5342   int num_rx_descs, error = 0;
5343   u_int32_t tlp_bus_pbl, tlp_bus_cal, tlp_op_tr;
5344   u_int32_t tlp_cfdd, tlp_cfcs;
5345   u_int32_t tlp_cflt, tlp_csid, tlp_cfit;
5346
5347   /* Make sure the COMMAND bits are reasonable. */
5348   tlp_cfcs = READ_PCI_CFG(sc, TLP_CFCS);
5349   tlp_cfcs &= ~TLP_CFCS_MWI_ENABLE;
5350   tlp_cfcs |=  TLP_CFCS_BUS_MASTER;
5351   tlp_cfcs |=  TLP_CFCS_MEM_ENABLE;
5352   tlp_cfcs |=  TLP_CFCS_IO_ENABLE;
5353   tlp_cfcs |=  TLP_CFCS_PAR_ERROR;
5354   tlp_cfcs |=  TLP_CFCS_SYS_ERROR;
5355   WRITE_PCI_CFG(sc, TLP_CFCS, tlp_cfcs);
5356
5357   /* Set the LATENCY TIMER to the recommended value, */
5358   /*  and make sure the CACHE LINE SIZE is reasonable. */
5359   tlp_cfit = READ_PCI_CFG(sc, TLP_CFIT);
5360   tlp_cflt = READ_PCI_CFG(sc, TLP_CFLT);
5361   tlp_cflt &= ~TLP_CFLT_LATENCY;
5362   tlp_cflt |= (tlp_cfit & TLP_CFIT_MAX_LAT)>>16;
5363   /* "prgmbl burst length" and "cache alignment" used below. */
5364   switch(tlp_cflt & TLP_CFLT_CACHE)
5365     {
5366     case 8: /* 8 bytes per cache line */
5367       { tlp_bus_pbl = 32; tlp_bus_cal = 1; break; }
5368     case 16:
5369       { tlp_bus_pbl = 32; tlp_bus_cal = 2; break; }
5370     case 32:
5371       { tlp_bus_pbl = 32; tlp_bus_cal = 3; break; }
5372     default:
5373       {
5374       tlp_bus_pbl = 32; tlp_bus_cal = 1;
5375       tlp_cflt &= ~TLP_CFLT_CACHE;
5376       tlp_cflt |= 8;
5377       break;
5378       }
5379     }
5380   WRITE_PCI_CFG(sc, TLP_CFLT, tlp_cflt);
5381
5382   /* Make sure SNOOZE and SLEEP modes are disabled. */
5383   tlp_cfdd = READ_PCI_CFG(sc, TLP_CFDD);
5384   tlp_cfdd &= ~TLP_CFDD_SLEEP;
5385   tlp_cfdd &= ~TLP_CFDD_SNOOZE;
5386   WRITE_PCI_CFG(sc, TLP_CFDD, tlp_cfdd);
5387   DELAY(11*1000); /* Tulip wakes up in 10 ms max */
5388
5389   /* Software Reset the Tulip chip; stops DMA and Interrupts. */
5390   /* This does not change the PCI config regs just set above. */
5391   WRITE_CSR(TLP_BUS_MODE, TLP_BUS_RESET); /* self-clearing */
5392   DELAY(5);  /* Tulip is dead for 50 PCI cycles after reset. */
5393
5394   /* Reset the Xilinx Field Programmable Gate Array. */
5395   reset_xilinx(sc); /* side effect: turns on all four LEDs */
5396
5397   /* Configure card-specific stuff (framers, line interfaces, etc.). */
5398   sc->card->config(sc);
5399
5400   /* Initializing cards can glitch clocks and upset fifos. */
5401   /* Reset the FIFOs between the Tulip and Xilinx chips. */
5402   set_mii16_bits(sc, MII16_FIFO);
5403   clr_mii16_bits(sc, MII16_FIFO);
5404
5405   /* Initialize the PCI busmode register. */
5406   /* The PCI bus cycle type "Memory Write and Invalidate" does NOT */
5407   /*  work cleanly in any version of the 21140A, so don't enable it! */
5408   WRITE_CSR(TLP_BUS_MODE,
5409         (tlp_bus_cal ? TLP_BUS_READ_LINE : 0) |
5410         (tlp_bus_cal ? TLP_BUS_READ_MULT : 0) |
5411         (tlp_bus_pbl<<TLP_BUS_PBL_SHIFT) |
5412         (tlp_bus_cal<<TLP_BUS_CAL_SHIFT) |
5413    ((BYTE_ORDER == BIG_ENDIAN) ? TLP_BUS_DESC_BIGEND : 0) |
5414    ((BYTE_ORDER == BIG_ENDIAN) ? TLP_BUS_DATA_BIGEND : 0) |
5415                 TLP_BUS_DSL_VAL |
5416                 TLP_BUS_ARB);
5417
5418   /* Pick number of RX descriptors and TX fifo threshold. */
5419   /* tx_threshold in bytes: 0=128, 1=256, 2=512, 3=1024 */
5420   tlp_csid = READ_PCI_CFG(sc, TLP_CSID);
5421   switch(tlp_csid)
5422     {
5423     case TLP_CSID_HSSI:         /* 52 Mb/s */
5424     case TLP_CSID_HSSIc:        /* 52 Mb/s */
5425     case TLP_CSID_T3:           /* 45 Mb/s */
5426       { num_rx_descs = 48; tlp_op_tr = 2; break; }
5427     case TLP_CSID_SSI:          /* 10 Mb/s */
5428       { num_rx_descs = 32; tlp_op_tr = 1; break; }
5429     case TLP_CSID_T1E1:         /*  2 Mb/s */
5430       { num_rx_descs = 16; tlp_op_tr = 0; break; }
5431     default:
5432       { num_rx_descs = 16; tlp_op_tr = 0; break; }
5433     }
5434
5435   /* Create DMA descriptors and initialize list head registers. */
5436   if ((error = create_ring(sc, &sc->txring, NUM_TX_DESCS))) return error;
5437   WRITE_CSR(TLP_TX_LIST, sc->txring.dma_addr);
5438   if ((error = create_ring(sc, &sc->rxring, num_rx_descs))) return error;
5439   WRITE_CSR(TLP_RX_LIST, sc->rxring.dma_addr);
5440
5441   /* Initialize the operating mode register. */
5442   WRITE_CSR(TLP_OP_MODE, TLP_OP_INIT | (tlp_op_tr<<TLP_OP_TR_SHIFT));
5443
5444   /* Read the missed frame register (result ignored) to zero it. */
5445   error = READ_CSR( TLP_MISSED); /* error is used as a bit-dump */
5446
5447   /* Disable rx watchdog and tx jabber features. */
5448   WRITE_CSR(TLP_WDOG, TLP_WDOG_INIT);
5449
5450   /* Enable card interrupts. */
5451   WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);
5452
5453   return 0;
5454   }
5455
5456 /* Stop DMA and Interrupts; free descriptors and buffers. */
5457 static void
5458 shutdown_card(void *arg)
5459   {
5460   softc_t *sc = arg;
5461
5462   /* Leave the LEDs in the state they were in after power-on. */
5463   led_on(sc, MII16_LED_ALL);
5464
5465   /* Software reset the Tulip chip; stops DMA and Interrupts */
5466   WRITE_CSR(TLP_BUS_MODE, TLP_BUS_RESET); /* self-clearing */
5467   DELAY(5);  /* Tulip is dead for 50 PCI cycles after reset. */
5468
5469   /* Disconnect from the PCI bus except for config cycles. */
5470   /* Hmmm; Linux syslogs a warning that IO and MEM are disabled. */
5471   WRITE_PCI_CFG(sc, TLP_CFCS, TLP_CFCS_MEM_ENABLE | TLP_CFCS_IO_ENABLE);
5472
5473   /* Free the DMA descriptor rings. */
5474   destroy_ring(sc, &sc->txring);
5475   destroy_ring(sc, &sc->rxring);
5476   }
5477
5478 /* Start the card and attach a kernel interface and line protocol. */
5479 static int
5480 attach_card(softc_t *sc, const char *intrstr)
5481   {
5482   struct config config;
5483   u_int32_t tlp_cfrv;
5484   u_int16_t mii3;
5485   u_int8_t *ieee;
5486   int i, error = 0;
5487
5488   /* Start the card. */
5489   if ((error = startup_card(sc))) return error;
5490
5491 #  if (__FreeBSD_version >= 500000)
5492   callout_init(&sc->callout, 0);
5493 #  else  /* FreeBSD-4 */
5494   callout_init(&sc->callout);
5495 #  endif
5496
5497   /* Attach a kernel interface. */
5498 #if NETGRAPH
5499   if ((error = ng_attach(sc))) return error;
5500   sc->flags |= FLAG_NETGRAPH;
5501 #endif
5502 #if IFNET
5503   if ((error = lmc_ifnet_attach(sc))) return error;
5504   sc->flags |= FLAG_IFNET;
5505 #endif
5506
5507   /* Attach a line protocol stack. */
5508   sc->config.line_pkg = PKG_RAWIP;
5509   config = sc->config;  /* get current config */
5510   config.line_pkg = 0;  /* select external stack */
5511   config.line_prot = PROT_C_HDLC;
5512   config.keep_alive = 1;
5513   config_proto(sc, &config); /* reconfigure */
5514   sc->config = config;  /* save new configuration */
5515
5516   /* Print interesting hardware-related things. */
5517   mii3 = read_mii(sc, 3);
5518   tlp_cfrv = READ_PCI_CFG(sc, TLP_CFRV);
5519   printf("%s: PCI rev %d.%d, MII rev %d.%d", NAME_UNIT,
5520    (tlp_cfrv>>4) & 0xF, tlp_cfrv & 0xF, (mii3>>4) & 0xF, mii3 & 0xF);
5521   ieee = (u_int8_t *)sc->status.ieee;
5522   for (i=0; i<3; i++) sc->status.ieee[i] = read_srom(sc, 10+i);
5523   printf(", IEEE addr %02x:%02x:%02x:%02x:%02x:%02x",
5524    ieee[0], ieee[1], ieee[2], ieee[3], ieee[4], ieee[5]);
5525   sc->card->ident(sc);
5526   printf(" %s\n", intrstr);
5527
5528   /* Print interesting software-related things. */
5529   printf("%s: Driver rev %d.%d.%d", NAME_UNIT,
5530    DRIVER_MAJOR_VERSION, DRIVER_MINOR_VERSION, DRIVER_SUB_VERSION);
5531   printf(", Options %s%s%s%s%s%s%s%s%s\n",
5532    NETGRAPH ? "NETGRAPH " : "", GEN_HDLC ? "GEN_HDLC " : "",
5533    NSPPP ? "SPPP " : "", P2P ? "P2P " : "",
5534    ALTQ_PRESENT ? "ALTQ " : "", NBPFILTER ? "BPF " : "",
5535    DEV_POLL ? "POLL " : "", IOREF_CSR ? "IO_CSR " : "MEM_CSR ",
5536    (BYTE_ORDER == BIG_ENDIAN) ? "BIG_END " : "LITTLE_END ");
5537
5538   /* Make the local hardware ready. */
5539   set_status(sc, 1);
5540
5541   return 0;
5542   }
5543
5544 /* Detach from the kernel in all ways. */
5545 static void
5546 detach_card(softc_t *sc)
5547   {
5548   struct config config;
5549
5550   /* Make the local hardware NOT ready. */
5551   set_status(sc, 0);
5552
5553   /* Detach external line protocol stack. */
5554   if (sc->config.line_pkg != PKG_RAWIP)
5555     {
5556     config = sc->config;
5557     config.line_pkg = PKG_RAWIP;
5558     config_proto(sc, &config);
5559     sc->config = config;
5560     }
5561
5562   /* Detach kernel interfaces. */
5563 #if NETGRAPH
5564   if (sc->flags & FLAG_NETGRAPH)
5565     {
5566     IFQ_PURGE(&sc->ng_fastq);
5567     IFQ_PURGE(&sc->ng_sndq);
5568     ng_detach(sc);
5569     sc->flags &= ~FLAG_NETGRAPH;
5570     }
5571 #endif
5572 #if IFNET
5573   if (sc->flags & FLAG_IFNET)
5574     {
5575     IFQ_PURGE(&sc->ifp->if_snd);
5576     lmc_ifnet_detach(sc);
5577     sc->flags &= ~FLAG_IFNET;
5578     }
5579 #endif
5580
5581   /* Reset the Tulip chip; stops DMA and Interrupts. */
5582   shutdown_card(sc);
5583   }
5584
5585 /* This is the I/O configuration interface for FreeBSD */
5586
5587 #ifdef __FreeBSD__
5588
5589 static int
5590 fbsd_probe(device_t dev)
5591   {
5592   u_int32_t cfid = pci_read_config(dev, TLP_CFID, 4);
5593   u_int32_t csid = pci_read_config(dev, TLP_CSID, 4);
5594
5595   /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
5596   if (cfid != TLP_CFID_TULIP) return ENXIO;
5597   switch (csid)
5598     {
5599     case TLP_CSID_HSSI:
5600     case TLP_CSID_HSSIc:
5601       device_set_desc(dev, HSSI_DESC);
5602       break;
5603     case TLP_CSID_T3:
5604       device_set_desc(dev,   T3_DESC);
5605       break;
5606     case TLP_CSID_SSI:
5607       device_set_desc(dev,  SSI_DESC);
5608       break;
5609     case TLP_CSID_T1E1:
5610       device_set_desc(dev, T1E1_DESC);
5611       break;
5612     default:
5613       return ENXIO;
5614     }
5615   return 0;
5616   }
5617
5618 static int
5619 fbsd_detach(device_t dev)
5620   {
5621   softc_t *sc = device_get_softc(dev);
5622
5623   /* Stop the card and detach from the kernel. */
5624   detach_card(sc);
5625
5626   /* Release resources. */
5627   if (sc->irq_cookie != NULL)
5628     {
5629     bus_teardown_intr(dev, sc->irq_res, sc->irq_cookie);
5630     sc->irq_cookie = NULL;
5631     }
5632   if (sc->irq_res != NULL)
5633     {
5634     bus_release_resource(dev, SYS_RES_IRQ, sc->irq_res_id, sc->irq_res);
5635     sc->irq_res = NULL;
5636     }
5637   if (sc->csr_res != NULL)
5638     {
5639     bus_release_resource(dev, sc->csr_res_type, sc->csr_res_id, sc->csr_res);
5640     sc->csr_res = NULL;
5641     }
5642
5643 # if (__FreeBSD_version >= 500000)
5644   mtx_destroy(&sc->top_mtx);
5645   mtx_destroy(&sc->bottom_mtx);
5646 # endif
5647   return 0; /* no error */
5648   }
5649
5650 static int
5651 fbsd_shutdown(device_t dev)
5652   {
5653   shutdown_card(device_get_softc(dev));
5654   return 0;
5655   }
5656
5657 static int
5658 fbsd_attach(device_t dev)
5659   {
5660   softc_t *sc = device_get_softc(dev);
5661   int error;
5662
5663   /* READ/WRITE_PCI_CFG need this. */
5664   sc->dev = dev;
5665
5666   /* What kind of card are we driving? */
5667   switch (READ_PCI_CFG(sc, TLP_CSID))
5668     {
5669     case TLP_CSID_HSSI:
5670     case TLP_CSID_HSSIc:
5671       sc->card = &hssi_card;
5672       break;
5673     case TLP_CSID_T3:
5674       sc->card =   &t3_card;
5675       break;
5676     case TLP_CSID_SSI:
5677       sc->card =  &ssi_card;
5678       break;
5679     case TLP_CSID_T1E1:
5680       sc->card =   &t1_card;
5681       break;
5682     default:
5683       return ENXIO;
5684     }
5685   sc->dev_desc = device_get_desc(dev);
5686
5687   /* Allocate PCI memory or IO resources to access the Tulip chip CSRs. */
5688 # if IOREF_CSR
5689   sc->csr_res_id   = TLP_CBIO;
5690   sc->csr_res_type = SYS_RES_IOPORT;
5691 # else
5692   sc->csr_res_id   = TLP_CBMA;
5693   sc->csr_res_type = SYS_RES_MEMORY;
5694 # endif
5695   sc->csr_res = bus_alloc_resource(dev, sc->csr_res_type, &sc->csr_res_id,
5696    0, ~0, 1, RF_ACTIVE);
5697   if (sc->csr_res == NULL)
5698     {
5699     printf("%s: bus_alloc_resource(csr) failed.\n", NAME_UNIT);
5700     return ENXIO;
5701     }
5702   sc->csr_tag    = rman_get_bustag(sc->csr_res);
5703   sc->csr_handle = rman_get_bushandle(sc->csr_res); 
5704
5705   /* Allocate PCI interrupt resources for the card. */
5706   sc->irq_res_id = 0;
5707   sc->irq_res = bus_alloc_resource(dev, SYS_RES_IRQ, &sc->irq_res_id,
5708    0, ~0, 1, RF_ACTIVE | RF_SHAREABLE);
5709   if (sc->irq_res == NULL)
5710     {
5711     printf("%s: bus_alloc_resource(irq) failed.\n", NAME_UNIT);
5712     fbsd_detach(dev);
5713     return ENXIO;
5714     }
5715   if ((error = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET | INTR_MPSAFE,
5716    NULL, bsd_interrupt, sc, &sc->irq_cookie)))
5717     {
5718     printf("%s: bus_setup_intr() failed; error %d\n", NAME_UNIT, error);
5719     fbsd_detach(dev);
5720     return error;
5721     }
5722
5723 # if (__FreeBSD_version >= 500000)
5724   /* Initialize the top-half and bottom-half locks. */
5725   mtx_init(&sc->top_mtx,    NAME_UNIT, "top half lock",    MTX_DEF);
5726   mtx_init(&sc->bottom_mtx, NAME_UNIT, "bottom half lock", MTX_DEF);
5727 # endif
5728
5729   /* Start the card and attach a kernel interface and line protocol. */
5730   if ((error = attach_card(sc, ""))) detach_card(sc);
5731   return error;
5732   }
5733
5734 static device_method_t methods[] =
5735   {
5736   DEVMETHOD(device_probe,    fbsd_probe),
5737   DEVMETHOD(device_attach,   fbsd_attach),
5738   DEVMETHOD(device_detach,   fbsd_detach),
5739   DEVMETHOD(device_shutdown, fbsd_shutdown),
5740   /* This driver does not suspend and resume. */
5741   { 0, 0 }
5742   };
5743
5744 static driver_t driver =
5745   {
5746   .name    = DEVICE_NAME,
5747   .methods = methods,
5748 # if (__FreeBSD_version >= 500000)
5749   .size    = sizeof(softc_t),
5750 # else /* FreeBSD-4 */
5751   .softc   = sizeof(softc_t),
5752 # endif
5753   };
5754
5755 static devclass_t devclass;
5756
5757 DRIVER_MODULE(lmc, pci, driver, devclass, 0, 0);
5758 MODULE_VERSION(lmc, 2);
5759 MODULE_DEPEND(lmc, pci, 1, 1, 1);
5760 # if NETGRAPH
5761 MODULE_DEPEND(lmc, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
5762 # endif
5763 # if NSPPP
5764 MODULE_DEPEND(lmc, sppp, 1, 1, 1);
5765 # endif
5766
5767 #endif  /* __FreeBSD__ */
5768
5769 /* This is the I/O configuration interface for NetBSD. */
5770
5771 #ifdef __NetBSD__
5772
5773 static int
5774 nbsd_match(struct device *parent, struct cfdata *match, void *aux)
5775   {
5776   struct pci_attach_args *pa = aux;
5777   u_int32_t cfid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CFID);
5778   u_int32_t csid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CSID);      
5779
5780   /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
5781   if (cfid != TLP_CFID_TULIP) return 0;
5782   switch (csid)
5783     {
5784     case TLP_CSID_HSSI:
5785     case TLP_CSID_HSSIc:
5786     case TLP_CSID_T3:
5787     case TLP_CSID_SSI:
5788     case TLP_CSID_T1E1:
5789       return 100;
5790     default:
5791       return 0;
5792     }
5793   }
5794
5795 static int
5796 nbsd_detach(struct device *self, int flags)
5797   {
5798   softc_t *sc = (softc_t *)self; /* device is first in softc */
5799
5800   /* Stop the card and detach from the kernel. */
5801   detach_card(sc);
5802
5803   /* Release resources. */
5804   if (sc->sdh_cookie != NULL)
5805     {
5806     shutdownhook_disestablish(sc->sdh_cookie);
5807     sc->sdh_cookie = NULL;
5808     }
5809   if (sc->irq_cookie != NULL)
5810     {
5811     pci_intr_disestablish(sc->pa_pc, sc->irq_cookie);
5812     sc->irq_cookie = NULL;
5813     }
5814   if (sc->csr_handle)
5815     {
5816     bus_space_unmap(sc->csr_tag, sc->csr_handle, TLP_CSR_SIZE);
5817     sc->csr_handle = 0;
5818     }
5819
5820   return 0; /* no error */
5821   }
5822
5823 static void
5824 nbsd_attach(struct device *parent, struct device *self, void *aux)
5825   {
5826   softc_t *sc = (softc_t *)self; /* device is first in softc */
5827   struct pci_attach_args *pa = aux;
5828   const char *intrstr;
5829   bus_addr_t csr_addr;
5830   int error;
5831
5832   /* READ/WRITE_PCI_CFG need these. */
5833   sc->pa_pc   = pa->pa_pc;
5834   sc->pa_tag  = pa->pa_tag;
5835   /* bus_dma needs this. */
5836   sc->pa_dmat = pa->pa_dmat;
5837
5838   /* What kind of card are we driving? */
5839   switch (READ_PCI_CFG(sc, TLP_CSID))
5840     {
5841     case TLP_CSID_HSSI:
5842     case TLP_CSID_HSSIc:
5843       sc->dev_desc =  HSSI_DESC;
5844       sc->card     = &hssi_card;
5845       break;
5846     case TLP_CSID_T3:
5847       sc->dev_desc =    T3_DESC;
5848       sc->card     =   &t3_card;
5849       break;
5850     case TLP_CSID_SSI:
5851       sc->dev_desc =   SSI_DESC;
5852       sc->card     =  &ssi_card;
5853       break;
5854     case TLP_CSID_T1E1:
5855       sc->dev_desc =  T1E1_DESC;
5856       sc->card     =   &t1_card;
5857       break;
5858     default:
5859       return;
5860     }
5861   printf(": %s\n", sc->dev_desc);
5862
5863   /* Allocate PCI resources to access the Tulip chip CSRs. */
5864 # if IOREF_CSR
5865   csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBIO) & -2;
5866   sc->csr_tag = pa->pa_iot;     /* bus_space tag for IO refs */
5867 # else
5868   csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBMA);
5869   sc->csr_tag = pa->pa_memt;    /* bus_space tag for MEM refs */
5870 # endif
5871   if ((error = bus_space_map(sc->csr_tag, csr_addr,
5872    TLP_CSR_SIZE, 0, &sc->csr_handle)))
5873     {
5874     printf("%s: bus_space_map() failed; error %d\n", NAME_UNIT, error);
5875     return;
5876     }
5877
5878   /* Allocate PCI interrupt resources. */
5879   if ((error = pci_intr_map(pa, &sc->intr_handle)))
5880     {
5881     printf("%s: pci_intr_map() failed; error %d\n", NAME_UNIT, error);
5882     nbsd_detach(self, 0);
5883     return;
5884     }
5885   sc->irq_cookie = pci_intr_establish(pa->pa_pc, sc->intr_handle,
5886    IPL_NET, bsd_interrupt, sc);
5887   if (sc->irq_cookie == NULL)
5888     {
5889     printf("%s: pci_intr_establish() failed\n", NAME_UNIT);
5890     nbsd_detach(self, 0);
5891     return;
5892     }
5893   intrstr = pci_intr_string(pa->pa_pc, sc->intr_handle);
5894
5895   /* Install a shutdown hook. */
5896   sc->sdh_cookie = shutdownhook_establish(shutdown_card, sc);
5897   if (sc->sdh_cookie == NULL)
5898     {
5899     printf("%s: shutdown_hook_establish() failed\n", NAME_UNIT);
5900     nbsd_detach(self, 0);
5901     return;
5902     }
5903
5904   /* Initialize the top-half and bottom-half locks. */
5905   simple_lock_init(&sc->top_lock);
5906   simple_lock_init(&sc->bottom_lock);
5907
5908   /* Start the card and attach a kernel interface and line protocol. */
5909   if ((error = attach_card(sc, intrstr))) detach_card(sc);
5910   }
5911
5912 # if (__NetBSD_Version__ >= 106080000) /* 1.6H */
5913 CFATTACH_DECL(lmc, sizeof(softc_t),
5914  nbsd_match, nbsd_attach, nbsd_detach, NULL);
5915 # else
5916 struct cfattach lmc_ca =
5917   {
5918 /*.ca_name      = DEVICE_NAME, */
5919   .ca_devsize   = sizeof(softc_t),
5920   .ca_match     = nbsd_match,
5921   .ca_attach    = nbsd_attach,
5922   .ca_detach    = nbsd_detach,
5923   .ca_activate  = NULL,
5924   };
5925 # endif
5926
5927 # if (__NetBSD_Version__ >= 106080000)
5928 CFDRIVER_DECL(lmc, DV_IFNET, NULL);
5929 # else
5930 static struct cfdriver lmc_cd =
5931   {
5932   .cd_name      = DEVICE_NAME,
5933   .cd_class     = DV_IFNET,
5934   .cd_ndevs     = 0,
5935   .cd_devs      = NULL,
5936   };
5937 # endif
5938
5939 /* cfdata is declared static, unseen outside this module. */
5940 /* It is used for LKM; config builds its own in ioconf.c. */
5941 static struct cfdata lmc_cf =
5942   {
5943 # if (__NetBSD_Version__ >= 106080000)
5944   .cf_name      = DEVICE_NAME,
5945   .cf_atname    = DEVICE_NAME,
5946 # else
5947   .cf_driver    = &lmc_cd,
5948   .cf_attach    = &lmc_ca,
5949 # endif
5950   .cf_unit      = 0,
5951   .cf_fstate    = FSTATE_STAR,
5952   };
5953
5954 # if (__NetBSD_Version__ >= 106080000)
5955 MOD_MISC(DEVICE_NAME)
5956 # else
5957 static struct lkm_misc _module =
5958   {
5959   .lkm_name     = DEVICE_NAME,
5960   .lkm_type     = LM_MISC,
5961   .lkm_offset   = 0,
5962   .lkm_ver      = LKM_VERSION,
5963   };
5964 # endif
5965
5966 /* From /sys/dev/pci/pci.c (no public prototype). */
5967 int pciprint(void *, const char *);
5968
5969 static int lkm_nbsd_match(struct pci_attach_args *pa)
5970   { return nbsd_match(0, 0, pa); }
5971
5972 /* LKM loader finds this by appending "_lkmentry" to filename "if_lmc". */
5973 int if_lmc_lkmentry(struct lkm_table *lkmtp, int cmd, int ver)
5974   {
5975   int i, error = 0;
5976
5977   if (ver != LKM_VERSION) return EINVAL;
5978   switch (cmd)
5979     {
5980     case LKM_E_LOAD:
5981       {
5982       struct cfdriver* pcicd;
5983
5984       lkmtp->private.lkm_misc = &_module;
5985       if ((pcicd = config_cfdriver_lookup("pci")) == NULL)
5986         {
5987         printf("%s: config_cfdriver_lookup(pci) failed; error %d\n",
5988          lmc_cd.cd_name, error);
5989         return error;
5990         }
5991 # if (__NetBSD_Version__ >= 106080000)
5992       if ((error = config_cfdriver_attach(&lmc_cd)))
5993         {
5994         printf("%s: config_cfdriver_attach() failed; error %d\n",
5995          lmc_cd.cd_name, error);
5996         return error;
5997         }
5998       if ((error = config_cfattach_attach(lmc_cd.cd_name, &lmc_ca)))
5999         {
6000         printf("%s: config_cfattach_attach() failed; error %d\n",
6001          lmc_cd.cd_name, error);
6002         config_cfdriver_detach(&lmc_cd);
6003         return error;
6004         }
6005 # endif
6006       for (i=0; i<pcicd->cd_ndevs; i++)
6007         {
6008         int dev;
6009         /* A pointer to a device is a pointer to its softc. */
6010         struct pci_softc *sc = pcicd->cd_devs[i];
6011         if (sc == NULL) continue;
6012         for (dev=0; dev<sc->sc_maxndevs; dev++)
6013           {
6014           struct pci_attach_args pa;
6015           pcitag_t tag = pci_make_tag(sc->sc_pc, sc->sc_bus, dev, 0);
6016           if (pci_probe_device(sc, tag, lkm_nbsd_match, &pa) != 0)
6017             config_attach(pcicd->cd_devs[i], &lmc_cf, &pa, pciprint);
6018             /* config_attach doesn't return on failure; it calls panic. */
6019           }
6020         }
6021       break;
6022       }
6023     case LKM_E_UNLOAD:
6024       {
6025       for (i=lmc_cd.cd_ndevs-1; i>=0; i--)
6026         {
6027         struct device *dev = lmc_cd.cd_devs[i];
6028         if (dev == NULL) continue;
6029         if ((error = config_detach(dev, 0)))
6030           {
6031           printf("%s: config_detach() failed; error %d\n",
6032            dev->dv_xname, error);
6033           return error;
6034           }
6035         }
6036 # if (__NetBSD_Version__ >= 106080000)
6037       if ((error = config_cfattach_detach(lmc_cd.cd_name, &lmc_ca)))
6038         {
6039         printf("%s: config_cfattach_detach() failed; error %d\n",
6040          lmc_cd.cd_name, error);
6041         return error;
6042         }
6043       if ((error = config_cfdriver_detach(&lmc_cd)))
6044         {
6045         printf("%s: config_cfdriver_detach() failed; error %d\n",
6046          lmc_cd.cd_name, error);
6047         return error;
6048         }
6049 # endif
6050       break;
6051       }
6052     case LKM_E_STAT:
6053       break;
6054     }
6055
6056   return error;
6057   }
6058
6059 #endif  /* __NetBSD__ */
6060
6061 /* This is the I/O configuration interface for OpenBSD. */
6062
6063 #ifdef __OpenBSD__
6064
6065 static int
6066 obsd_match(struct device *parent, void *match, void *aux)
6067   {
6068   struct pci_attach_args *pa = aux;
6069   u_int32_t cfid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CFID);
6070   u_int32_t csid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CSID);      
6071
6072   /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
6073   if (cfid != TLP_CFID_TULIP) return 0;
6074   switch (csid)
6075     {
6076     case TLP_CSID_HSSI:
6077     case TLP_CSID_HSSIc:
6078     case TLP_CSID_T3:
6079     case TLP_CSID_SSI:
6080     case TLP_CSID_T1E1:
6081       return 100; /* match better than other 21140 drivers */
6082     default:
6083       return 0;
6084     }
6085   }
6086
6087 static int
6088 obsd_detach(struct device *self, int flags)
6089   {
6090   softc_t *sc = (softc_t *)self; /* device is first in softc */
6091
6092   /* Stop the card and detach from the kernel. */
6093   detach_card(sc);
6094
6095   /* Release resources. */
6096   if (sc->sdh_cookie != NULL)
6097     {
6098     shutdownhook_disestablish(sc->sdh_cookie);
6099     sc->sdh_cookie = NULL;
6100     }
6101   if (sc->irq_cookie != NULL)
6102     {
6103     pci_intr_disestablish(sc->pa_pc, sc->irq_cookie);
6104     sc->irq_cookie = NULL;
6105     }
6106   if (sc->csr_handle)
6107     {
6108     bus_space_unmap(sc->csr_tag, sc->csr_handle, TLP_CSR_SIZE);
6109     sc->csr_handle = 0;
6110     }
6111
6112   return 0; /* no error */
6113   }
6114
6115 static void
6116 obsd_attach(struct device *parent, struct device *self, void *aux)
6117   {
6118   softc_t *sc = (softc_t *)self; /* device is first in softc */
6119   struct pci_attach_args *pa = aux;
6120   const char *intrstr;
6121   bus_addr_t csr_addr;
6122   int error;
6123
6124   /* READ/WRITE_PCI_CFG need these. */
6125   sc->pa_pc   = pa->pa_pc;
6126   sc->pa_tag  = pa->pa_tag;
6127   /* bus_dma needs this. */
6128   sc->pa_dmat = pa->pa_dmat;
6129
6130   /* What kind of card are we driving? */
6131   switch (READ_PCI_CFG(sc, TLP_CSID))
6132     {
6133     case TLP_CSID_HSSI:
6134     case TLP_CSID_HSSIc:
6135       sc->dev_desc =  HSSI_DESC;
6136       sc->card     = &hssi_card;
6137       break;
6138     case TLP_CSID_T3:
6139       sc->dev_desc =    T3_DESC;
6140       sc->card     =   &t3_card;
6141       break;
6142     case TLP_CSID_SSI:
6143       sc->dev_desc =   SSI_DESC;
6144       sc->card     =  &ssi_card;
6145       break;
6146     case TLP_CSID_T1E1:
6147       sc->dev_desc =  T1E1_DESC;
6148       sc->card     =   &t1_card;
6149       break;
6150     default:
6151       return;
6152     }
6153   printf(": %s\n", sc->dev_desc);
6154
6155   /* Allocate PCI resources to access the Tulip chip CSRs. */
6156 # if IOREF_CSR
6157   csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBIO) & -2;
6158   sc->csr_tag = pa->pa_iot;     /* bus_space tag for IO refs */
6159 # else
6160   csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBMA);
6161   sc->csr_tag = pa->pa_memt;    /* bus_space tag for MEM refs */
6162 # endif
6163   if ((error = bus_space_map(sc->csr_tag, csr_addr,
6164    TLP_CSR_SIZE, 0, &sc->csr_handle)))
6165     {
6166     printf("%s: bus_space_map() failed; error %d\n", NAME_UNIT, error);
6167     return;
6168     }
6169
6170   /* Allocate PCI interrupt resources. */
6171   if ((error = pci_intr_map(pa, &sc->intr_handle)))
6172     {
6173     printf("%s: pci_intr_map() failed; error %d\n", NAME_UNIT, error);
6174     obsd_detach(self, 0);
6175     return;
6176     }
6177   sc->irq_cookie = pci_intr_establish(pa->pa_pc, sc->intr_handle,
6178    IPL_NET, bsd_interrupt, sc, self->dv_xname);
6179   if (sc->irq_cookie == NULL)
6180     {
6181     printf("%s: pci_intr_establish() failed\n", NAME_UNIT);
6182     obsd_detach(self, 0);
6183     return;
6184     }
6185   intrstr = pci_intr_string(pa->pa_pc, sc->intr_handle);
6186
6187   /* Install a shutdown hook. */
6188   sc->sdh_cookie = shutdownhook_establish(shutdown_card, sc);
6189   if (sc->sdh_cookie == NULL)
6190     {
6191     printf("%s: shutdown_hook_establish() failed\n", NAME_UNIT);
6192     obsd_detach(self, 0);
6193     return;
6194     }
6195
6196   /* Initialize the top-half and bottom-half locks. */
6197   simple_lock_init(&sc->top_lock);
6198   simple_lock_init(&sc->bottom_lock);
6199
6200   /* Start the card and attach a kernel interface and line protocol. */
6201   if ((error = attach_card(sc, intrstr))) detach_card(sc);
6202   }
6203
6204 struct cfattach lmc_ca =
6205   {
6206   .ca_devsize   = sizeof(softc_t),
6207   .ca_match     = obsd_match,
6208   .ca_attach    = obsd_attach,
6209   .ca_detach    = obsd_detach,
6210   .ca_activate  = NULL,
6211   };
6212
6213 struct cfdriver lmc_cd =
6214   {
6215   .cd_name      = DEVICE_NAME,
6216   .cd_devs      = NULL,
6217   .cd_class     = DV_IFNET,
6218   .cd_indirect  = 0,
6219   .cd_ndevs     = 0,
6220   };
6221
6222 /* cfdata is declared static, unseen outside this module. */
6223 /* It is used for LKM; config builds its own in ioconf.c. */
6224 static struct cfdata lmc_cfdata =
6225   {
6226   .cf_attach    = &lmc_ca,
6227   .cf_driver    = &lmc_cd,
6228   .cf_unit      = 0,
6229   .cf_fstate    = FSTATE_STAR,
6230   };
6231
6232 static struct lkm_any _module =
6233   {
6234   .lkm_name     = DEVICE_NAME,
6235   .lkm_type     = LM_MISC,
6236   .lkm_offset   = 0,
6237   .lkm_ver      = LKM_VERSION,
6238   };
6239
6240 /* From /sys/dev/pci/pci.c (no public prototype). */
6241 int pciprint(void *, const char *);
6242
6243 extern struct cfdriver pci_cd;
6244
6245 /* LKM loader finds this by appending "_lkmentry" to filename "if_lmc". */
6246 int if_lmc_lkmentry(struct lkm_table *lkmtp, int cmd, int ver)
6247   {
6248   int i, error = 0;
6249
6250   if (ver != LKM_VERSION) return EINVAL;
6251   switch (cmd)
6252     {
6253     case LKM_E_LOAD:
6254       {  /* XXX This works for ONE card on pci0 of a i386 machine! XXX */
6255       lkmtp->private.lkm_any = &_module;
6256       for (i=0; i<pci_cd.cd_ndevs; i++)
6257         {
6258         struct pci_attach_args pa;
6259         struct device *parent = pci_cd.cd_devs[i];
6260         if (parent == NULL) continue; /* dead clone? */
6261         if ((parent->dv_unit)!=0) continue; /* only bus zero */
6262         /* XXX For machine independence, need: pcibus_attach_args. XXX */
6263         /* XXX See NetBSD's sys/dev/pci/pci.c/pci_probe_device.    XXX */
6264         /* XXX Why isn't there an LKM network interface module?    XXX */
6265         pa.pa_pc    = NULL;                                     /* XXX */
6266         pa.pa_bus   = 0;                                        /* XXX */
6267         pa.pa_iot   = X86_BUS_SPACE_IO;                         /* XXX */
6268         pa.pa_memt  = X86_BUS_SPACE_MEM;                        /* XXX */
6269         pa.pa_dmat  = &pci_bus_dma_tag;                         /* XXX */
6270         for (pa.pa_device=0; pa.pa_device<32; pa.pa_device++)   /* XXX */
6271           {
6272           int intr;
6273           pa.pa_function = 0; /* DEC-21140A has function 0 only    XXX */
6274           pa.pa_tag = pci_make_tag(pa.pa_pc, pa.pa_bus, pa.pa_device, 0);
6275           pa.pa_id = pci_conf_read(pa.pa_pc, pa.pa_tag, PCI_ID_REG);
6276           if ((pa.pa_id & 0xFFFF) == 0xFFFF) continue;
6277           if ((pa.pa_id & 0xFFFF) == 0) continue;
6278           /* XXX this only works for pci0 -- no swizzelling        XXX */
6279           pa.pa_intrswiz = 0;
6280           pa.pa_intrtag = pa.pa_tag;
6281           intr = pci_conf_read(pa.pa_pc, pa.pa_tag, PCI_INTERRUPT_REG);
6282           pa.pa_intrline = PCI_INTERRUPT_LINE(intr);
6283           pa.pa_intrpin = ((PCI_INTERRUPT_PIN(intr) -1) % 4) +1;
6284           if (obsd_match(parent, &lmc_cfdata, &pa))
6285             config_attach(parent, &lmc_cfdata, &pa, pciprint);
6286           /* config_attach doesn't return on failure; it calls panic. */
6287           }
6288         }
6289       break;
6290       }
6291     case LKM_E_UNLOAD:
6292       {
6293       for (i=lmc_cd.cd_ndevs-1; i>=0; i--)
6294         {
6295         struct device *dev = lmc_cd.cd_devs[i];
6296         if (dev == NULL) continue;
6297         if ((error = config_detach(dev, 0)))
6298           printf("%s: config_detach() failed; error %d\n", dev->dv_xname, error);
6299         }
6300       break;
6301       }
6302     case LKM_E_STAT:
6303       break;
6304     }
6305
6306   return error;
6307   }
6308
6309 #endif  /* __OpenBSD__ */
6310
6311 /* This is the I/O configuration interface for BSD/OS. */
6312
6313 #ifdef __bsdi__
6314
6315 static int
6316 bsdi_match(pci_devaddr_t *pa)
6317   {
6318   u_int32_t cfid = pci_inl(pa, TLP_CFID);
6319   u_int32_t csid = pci_inl(pa, TLP_CSID);
6320
6321   /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
6322   if (cfid != TLP_CFID_TULIP) return 0;
6323   switch (csid)
6324     {
6325     case TLP_CSID_HSSI:
6326     case TLP_CSID_HSSIc:
6327     case TLP_CSID_T3:
6328     case TLP_CSID_SSI:
6329     case TLP_CSID_T1E1:
6330       return 1;
6331     default:
6332       return 0;
6333     }
6334   }
6335
6336 static int
6337 bsdi_probe(struct device *parent, struct cfdata *cf, void *aux)
6338   {
6339   struct isa_attach_args *ia = aux;
6340   pci_devaddr_t *pa = NULL;
6341   pci_devres_t res;
6342
6343   /* This must be a PCI bus. */
6344   if (ia->ia_bustype != BUS_PCI) return 0;
6345
6346   /* Scan PCI bus for our boards. */
6347   if ((pa = pci_scan(bsdi_match)) == 0) return 0;
6348
6349   /* Scan config space for IO and MEM base registers and IRQ info. */
6350   pci_getres(pa, &res, 1, ia);
6351
6352   /* Crucial: pass pci_devaddr to bsdi_attach in ia_aux. */
6353   ia->ia_aux = (void *)pa;
6354
6355   return 1;
6356   }
6357
6358 static void
6359 bsdi_attach(struct device *parent, struct device *self, void *aux)
6360   {
6361   softc_t *sc = (softc_t *)self; /* device is first in softc */
6362   struct isa_attach_args *ia = aux;
6363   pci_devaddr_t *pa = ia->ia_aux; /* this is crucial! */
6364   int error;
6365
6366   /* READ/WRITE_PCI_CFG need this. */
6367   sc->cfgbase = *pa;
6368
6369   /* What kind of card are we driving? */
6370   switch (READ_PCI_CFG(sc, TLP_CSID))
6371     {
6372     case TLP_CSID_HSSI:
6373     case TLP_CSID_HSSIc:
6374       sc->dev_desc =  HSSI_DESC;
6375       sc->card     = &hssi_card;
6376       break;
6377     case TLP_CSID_T3:
6378       sc->dev_desc =    T3_DESC;
6379       sc->card     =   &t3_card;
6380       break;
6381     case TLP_CSID_SSI:
6382       sc->dev_desc =   SSI_DESC;
6383       sc->card     =  &ssi_card;
6384       break;
6385     case TLP_CSID_T1E1:
6386       sc->dev_desc =  T1E1_DESC;
6387       sc->card     =   &t1_card;
6388       break;
6389     default:
6390       return;
6391     }
6392   printf(": %s\n", sc->dev_desc);
6393
6394   /* Allocate PCI memory or IO resources to access the Tulip chip CSRs. */
6395   sc->csr_iobase  = ia->ia_iobase;
6396   sc->csr_membase = (u_int32_t *)mapphys((vm_offset_t)ia->ia_maddr, TLP_CSR_SIZE);
6397
6398   /* Attach to the PCI bus. */
6399   isa_establish(&sc->id, &sc->dev);
6400
6401   /* Allocate PCI interrupt resources for the card. */
6402   sc->ih.ih_fun = bsd_interrupt;
6403   sc->ih.ih_arg = sc;
6404   intr_establish(ia->ia_irq, &sc->ih, DV_NET);
6405
6406   /* Install a shutdown hook. */
6407   sc->ats.func = shutdown_card;
6408   sc->ats.arg = sc;
6409   atshutdown(&sc->ats, ATSH_ADD);
6410
6411   /* Initialize the top-half and bottom-half locks. */
6412   simple_lock_init(&sc->top_lock);
6413   simple_lock_init(&sc->bottom_lock);
6414
6415   /* Start the card and attach a kernel interface and line protocol. */
6416   if ((error = attach_card(sc, ""))) detach_card(sc);
6417   }
6418
6419 struct cfdriver lmccd =
6420   {
6421   .cd_devs      = NULL,
6422   .cd_name      = DEVICE_NAME,
6423   .cd_match     = bsdi_probe,
6424   .cd_attach    = bsdi_attach,
6425   .cd_class     = DV_IFNET,
6426   .cd_devsize   = sizeof(softc_t),
6427   };
6428 #endif  /* __bsdi__ */
6429
6430 #ifdef __linux__
6431
6432 /* The kernel calls this procedure when an interrupt happens. */
6433 static irqreturn_t
6434 linux_interrupt(int irq, void *dev, struct pt_regs *regs)
6435   {
6436   struct net_device *net_dev = dev;
6437   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6438
6439   /* Cut losses early if this is not our interrupt. */
6440   if ((READ_CSR(TLP_STATUS) & TLP_INT_TXRX) == 0)
6441     return IRQ_NONE;
6442
6443   /* Disable card interrupts. */
6444   WRITE_CSR(TLP_INT_ENBL, TLP_INT_DISABLE);
6445
6446   /* Handle the card interrupt with the dev->poll method. */
6447   if (netif_rx_schedule_prep(net_dev))
6448     __netif_rx_schedule(net_dev);  /* NAPI - add to poll list */
6449   else
6450     printk("%s: interrupt while on poll list\n", NAME_UNIT);
6451
6452   return IRQ_HANDLED;
6453   }
6454
6455 /* This net_device method services interrupts in a softirq. */
6456 /* With rxintr_cleanup(), it implements input flow control. */
6457 static int
6458 linux_poll(struct net_device *net_dev, int *budget)
6459   {
6460   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6461   int received;
6462
6463   /* Yes, we do NAPI. */
6464   /* Allow processing up to net_dev->quota incoming packets. */
6465   /* This is the ONLY time core_interrupt() may process rx pkts. */
6466   /* Otherwise (sc->quota == 0) and rxintr_cleanup() is a NOOP. */
6467   sc->quota = net_dev->quota;
6468
6469   /* Handle the card interrupt with kernel ints enabled. */
6470   /* Process rx pkts (and tx pkts, too). */
6471   /* Card interrupts are disabled. */
6472   core_interrupt(sc, 0);
6473
6474   /* Report number of rx packets processed. */
6475   received = net_dev->quota - sc->quota;
6476   net_dev->quota -= received;
6477   *budget        -= received;
6478
6479   /* if quota prevented processing all rx pkts, leave rx ints disabled */
6480   if (sc->quota == 0)  /* this is off by one...but harmless */
6481     {
6482     WRITE_CSR(TLP_INT_ENBL, TLP_INT_TX);
6483     return 1; /* more pkts to handle -- reschedule */
6484     }
6485
6486   sc->quota = 0;  /* disable rx pkt processing by rxintr_cleanup() */
6487   netif_rx_complete(net_dev); /* NAPI - remove from poll list */
6488
6489   /* Enable card interrupts. */
6490   WRITE_CSR(TLP_INT_ENBL, TLP_INT_TXRX);
6491   return 0;
6492   }
6493
6494 /* These next routines are similar to BSD's ifnet kernel/driver interface. */
6495
6496 /* This net_device method hands outgoing packets to the transmitter. */
6497 /* With txintr_setup(), it implements output flow control. */
6498 /* Called from a syscall (user context; no spinlocks). */
6499 static int
6500 linux_start(struct sk_buff *skb, struct net_device *net_dev)
6501   {
6502   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6503
6504   if (sc->tx_skb == NULL)
6505     {
6506     /* Put this skb where the transmitter will see it. */
6507     sc->tx_skb = skb;
6508
6509     /* Start the transmitter; incoming pkts are NOT processed. */
6510     user_interrupt(sc, 0);
6511
6512     /* If the tx didn't take the skb then stop the queue. */
6513     /* This can happen if another CPU is in core_interrupt(). */
6514     if (sc->tx_skb != NULL) netif_stop_queue(net_dev);
6515
6516     return 0;
6517     }
6518
6519   /* This shouldn't happen; skb is NOT consumed. */
6520   if (netif_queue_stopped(net_dev))
6521     printk("%s: dev->start() called with queue stopped\n", NAME_UNIT);
6522   else
6523     netif_stop_queue(net_dev);
6524
6525   return 1;
6526   }
6527
6528 /* This net_device method restarts the transmitter if it hangs. */
6529 /* Called from a softirq. */
6530 static void
6531 linux_timeout(struct net_device *net_dev)
6532   {
6533   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6534
6535   /* Start the transmitter; incoming packets are NOT processed. */
6536   user_interrupt(sc, 1);
6537   }
6538
6539 /* This net_device method handles IOCTL syscalls. */
6540 /* Called from a syscall (user context; no spinlocks; can sleep). */
6541 static int
6542 linux_ioctl(struct net_device *net_dev, struct ifreq *ifr, int cmd)
6543   {
6544   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6545   int error = 0;
6546
6547   if ((cmd >= SIOCDEVPRIVATE) && (cmd <= SIOCDEVPRIVATE+15))
6548     {
6549     struct iohdr *iohdr = (struct iohdr *)ifr;
6550     u_int16_t direction = iohdr->direction;
6551     u_int16_t length = iohdr->length;
6552     char *user_addr = (char *)iohdr->iohdr;
6553     char *kern_addr;
6554
6555     if (iohdr->cookie != NGM_LMC_COOKIE) return -EINVAL;
6556
6557     /* Emulate a BSD-style IOCTL syscall. */
6558     kern_addr = kmalloc(length, GFP_KERNEL);
6559     if (kern_addr == NULL)
6560       error = -ENOMEM;
6561     if ((error == 0) && ((direction & DIR_IOW) != 0))
6562       error = copy_from_user(kern_addr, user_addr, length);
6563     if (error == 0)
6564       error = -core_ioctl(sc, (unsigned long)cmd, kern_addr);
6565     if ((error == 0) && ((direction & DIR_IOR) != 0))
6566       error = copy_to_user(user_addr, kern_addr, length);
6567     kfree(kern_addr);
6568     }
6569 # if GEN_HDLC
6570   else if (cmd == SIOCWANDEV)
6571     {
6572     const size_t size = sizeof(sync_serial_settings);
6573
6574     switch (ifr->ifr_settings.type)
6575       {
6576       case IF_GET_IFACE: /* get interface config */
6577         {
6578         ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
6579         if (ifr->ifr_settings.size < size)
6580           {
6581           ifr->ifr_settings.size = size;
6582           error = -ENOBUFS;
6583           }
6584         else
6585           {
6586           if (sc->config.tx_clk_src == CFG_CLKMUX_ST)
6587             sc->hdlc_settings.clock_type = CLOCK_EXT;
6588           if (sc->config.tx_clk_src == CFG_CLKMUX_INT)
6589             sc->hdlc_settings.clock_type = CLOCK_TXINT;
6590           if (sc->config.tx_clk_src == CFG_CLKMUX_RT)
6591             sc->hdlc_settings.clock_type = CLOCK_TXFROMRX;
6592           sc->hdlc_settings.loopback = (sc->config.loop_back != CFG_LOOP_NONE) ? 1:0;
6593           sc->hdlc_settings.clock_rate = sc->status.tx_speed;
6594           error = copy_to_user(ifr->ifr_settings.ifs_ifsu.sync,
6595            &sc->hdlc_settings, size);
6596           }
6597         break;
6598         }
6599       case IF_IFACE_SYNC_SERIAL: /* set interface config */
6600         {
6601         if (!capable(CAP_NET_ADMIN))
6602           error = -EPERM;
6603         if (error == 0) 
6604           error = copy_from_user(&sc->hdlc_settings,
6605           ifr->ifr_settings.ifs_ifsu.sync, size);
6606         /* hdlc_settings are currently ignored. */
6607         break;
6608         }
6609       default:  /* Pass the rest to the line protocol code. */
6610         {
6611         error = hdlc_ioctl(net_dev, ifr, cmd);
6612         break;
6613         }
6614       }
6615     }
6616 # endif /* GEN_HDLC */
6617   else /* unknown IOCTL command */
6618     error = -EINVAL;
6619
6620   if (DRIVER_DEBUG)
6621     printk("%s: linux_ioctl; cmd=0x%08x error=%d\n",
6622      NAME_UNIT, cmd, error);
6623
6624   return error;
6625   }
6626
6627 /* This net_device method returns a pointer to device statistics. */
6628 static struct net_device_stats *
6629 linux_stats(struct net_device *net_dev)
6630   {
6631 # if GEN_HDLC
6632   return &dev_to_hdlc(net_dev)->stats;
6633 # else
6634   softc_t *sc = net_dev->priv;
6635   return &sc->net_stats;
6636 # endif
6637   }
6638
6639 /* Called from a softirq once a second. */
6640 static void
6641 linux_watchdog(unsigned long softc)
6642   {
6643   softc_t *sc = (softc_t *)softc;
6644   u_int8_t old_oper_status = sc->status.oper_status;
6645   struct event_cntrs *cntrs = &sc->status.cntrs;
6646   struct net_device_stats *stats = linux_stats(sc->net_dev);
6647
6648   core_watchdog(sc); /* updates oper_status */
6649
6650   /* Notice change in link status. */
6651   if     ((old_oper_status != STATUS_UP) &&
6652    (sc->status.oper_status == STATUS_UP))  /* link came up */
6653     {
6654     hdlc_set_carrier(1, sc->net_dev);
6655     netif_wake_queue(sc->net_dev);
6656     }
6657   if     ((old_oper_status == STATUS_UP) &&
6658    (sc->status.oper_status != STATUS_UP))  /* link went down */
6659     {
6660     hdlc_set_carrier(0, sc->net_dev);
6661     netif_stop_queue(sc->net_dev);
6662     }
6663
6664   /* Notice change in line protocol. */
6665   if (sc->config.line_pkg == PKG_RAWIP)
6666     {
6667     sc->status.line_pkg  = PKG_RAWIP;
6668     sc->status.line_prot = PROT_IP_HDLC;
6669     }
6670 # if GEN_HDLC
6671   else
6672     {
6673     sc->status.line_pkg  = PKG_GEN_HDLC;
6674     switch (sc->hdlc_dev->proto.id)
6675       {
6676       case IF_PROTO_PPP:
6677         sc->status.line_prot = PROT_PPP;
6678         break;
6679       case IF_PROTO_CISCO:
6680         sc->status.line_prot = PROT_C_HDLC;
6681         break;
6682       case IF_PROTO_FR:
6683         sc->status.line_prot = PROT_FRM_RLY;
6684         break;
6685       case IF_PROTO_HDLC:
6686         sc->status.line_prot = PROT_IP_HDLC;
6687         break;
6688       case IF_PROTO_X25:
6689         sc->status.line_prot = PROT_X25;
6690         break;
6691       case IF_PROTO_HDLC_ETH:
6692         sc->status.line_prot = PROT_ETH_HDLC;
6693         break;
6694       default:
6695         sc->status.line_prot = 0;
6696         break;
6697       }
6698     }
6699 # endif /* GEN_HDLC */
6700
6701   /* Copy statistics from sc to net_dev for get_stats(). */
6702   stats->rx_packets       = cntrs->ipackets;
6703   stats->tx_packets       = cntrs->opackets;
6704   stats->rx_bytes         = cntrs->ibytes;
6705   stats->tx_bytes         = cntrs->obytes;
6706   stats->rx_errors        = cntrs->ierrors;
6707   stats->tx_errors        = cntrs->oerrors;
6708   stats->rx_dropped       = cntrs->idiscards;
6709   stats->tx_dropped       = cntrs->odiscards;
6710   stats->rx_fifo_errors   = cntrs->fifo_over;
6711   stats->tx_fifo_errors   = cntrs->fifo_under;
6712   stats->rx_missed_errors = cntrs->missed;
6713   stats->rx_over_errors   = cntrs->overruns;
6714
6715   /* Call this procedure again after one second. */
6716   sc->wd_timer.expires = jiffies + HZ; /* now plus one second */
6717   add_timer(&sc->wd_timer);
6718   }
6719
6720 /* This is the I/O configuration interface for Linux. */
6721
6722 /* This net_device method is called when IFF_UP goes false. */
6723 static int
6724 linux_stop(struct net_device *net_dev)
6725   {
6726   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6727
6728   /* Stop the card and detach from the kernel. */
6729   detach_card(sc);  /* doesn't fail */
6730
6731   free_irq(net_dev->irq, net_dev); /* doesn't fail */
6732
6733   del_timer(&sc->wd_timer); /* return value ignored */
6734
6735   return 0;
6736   }
6737
6738 /* This net_device method is called when IFF_UP goes true. */
6739 static int
6740 linux_open(struct net_device *net_dev)
6741   {
6742   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6743   int error;
6744
6745   /* Allocate PCI interrupt resources for the card. */
6746   if ((error = request_irq(net_dev->irq, &linux_interrupt, SA_SHIRQ,
6747    NAME_UNIT, net_dev)))
6748     {
6749     printk("%s: request_irq() failed; error %d\n", NAME_UNIT, error);
6750     return error;
6751     }
6752
6753   /* Arrange to call linux_watchdog() once a second. */
6754   init_timer(&sc->wd_timer);
6755   sc->wd_timer.expires  = jiffies + HZ; /* now plus one second */
6756   sc->wd_timer.function = &linux_watchdog;
6757   sc->wd_timer.data     = (unsigned long) sc;
6758   add_timer(&sc->wd_timer);
6759
6760   /* Start the card and attach a kernel interface and line protocol. */
6761   if ((error = -attach_card(sc, "")))
6762     linux_stop(net_dev);
6763   else
6764     {
6765     net_dev->weight = sc->rxring.num_descs; /* input flow control */
6766     netif_start_queue(net_dev);            /* output flow control */
6767     }
6768
6769   return error;
6770   }
6771
6772 # if GEN_HDLC
6773 static int
6774 hdlc_attach(struct net_device *net_dev,
6775  unsigned short encoding, unsigned short parity)
6776   { return 0; }
6777 # endif
6778
6779 /* This pci_driver method is called during shutdown or module-unload. */
6780 /* This is called from user context; can sleep; no spinlocks! */
6781 static void __exit
6782 linux_remove(struct pci_dev *pci_dev)
6783   {
6784   struct net_device *net_dev = (struct net_device *)pci_get_drvdata(pci_dev);
6785   softc_t *sc = dev_to_hdlc(net_dev)->priv;
6786
6787   if (net_dev == NULL) return;
6788
6789   /* Assume that linux_stop() has already been called. */
6790   if (sc->flags & FLAG_NETDEV)
6791 # if GEN_HDLC
6792     unregister_hdlc_device(net_dev);
6793 # else
6794     unregister_netdev(net_dev);
6795 # endif
6796
6797 # if (IOREF_CSR == 0)
6798   if (sc->csr_membase != NULL)
6799     iounmap(sc->csr_membase);
6800 # endif
6801
6802   pci_disable_device(pci_dev);
6803
6804   if (sc->csr_iobase != 0)
6805     pci_release_regions(pci_dev);
6806
6807   pci_set_drvdata(pci_dev, NULL);
6808
6809   kfree(sc);
6810   free_netdev(net_dev);
6811   }
6812
6813 static void
6814 setup_netdev(struct net_device *net_dev)
6815   {
6816   /* Initialize the generic network device. */
6817   /* Note similarity to BSD's lmc_ifnet_attach(). */
6818   net_dev->flags           = IFF_POINTOPOINT;
6819   net_dev->flags          |= IFF_RUNNING;
6820   net_dev->open            = linux_open;
6821   net_dev->stop            = linux_stop;
6822   net_dev->hard_start_xmit = linux_start;
6823   net_dev->do_ioctl        = linux_ioctl;
6824   net_dev->get_stats       = linux_stats;
6825   net_dev->tx_timeout      = linux_timeout;
6826   net_dev->poll            = linux_poll;
6827   net_dev->watchdog_timeo  = 1 * HZ;
6828   net_dev->tx_queue_len    = SNDQ_MAXLEN;
6829   net_dev->mtu             = MAX_DESC_LEN;
6830   net_dev->type            = ARPHRD_RAWHDLC;
6831 /* The receiver generates frag-lists for packets >4032 bytes.   */
6832 /* The transmitter accepts scatter/gather lists and frag-lists. */
6833 /* However Linux linearizes outgoing packets since our hardware */
6834 /*  doesn't compute soft checksums.  All that work for nothing! */
6835 /*net_dev->features       |= NETIF_F_SG; */
6836 /*net_dev->features       |= NETIF_F_FRAGLIST; */
6837   }
6838
6839 /* This pci_driver method is called during boot or module-load. */
6840 /* This is called from user context; can sleep; no spinlocks! */
6841 static int __init
6842 linux_probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
6843   {
6844   u_int32_t cfid, csid;
6845   struct net_device *net_dev;
6846   softc_t *sc;
6847   int error;
6848
6849   /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
6850   pci_read_config_dword(pci_dev, TLP_CFID, &cfid);
6851   if (cfid != TLP_CFID_TULIP) return -ENXIO;
6852   pci_read_config_dword(pci_dev, TLP_CSID, &csid);
6853   switch (csid)
6854     {
6855     case TLP_CSID_HSSI:
6856     case TLP_CSID_HSSIc:
6857     case TLP_CSID_T3:
6858     case TLP_CSID_SSI:
6859     case TLP_CSID_T1E1:
6860       break;
6861     default:
6862       return -ENXIO;
6863     }
6864
6865   /* Declare that these cards use 32-bit single-address PCI cycles. */
6866   if ((error = pci_set_dma_mask(pci_dev, DMA_32BIT_MASK)))
6867     {
6868     printk("%s: pci_set_dma_mask() failed; error %d\n", DEVICE_NAME, error);
6869     return error;
6870     }
6871   pci_set_consistent_dma_mask(pci_dev, DMA_32BIT_MASK); /* can't fail */
6872
6873 # if GEN_HDLC /* generic-hdlc line protocols */
6874
6875   /* device driver instance data, aka Soft Context or sc */
6876   if ((sc = kmalloc(sizeof(softc_t), GFP_KERNEL)) == NULL)
6877     {
6878     printk("%s: kmalloc() failed\n", DEVICE_NAME);
6879     return -ENOMEM;
6880     }
6881   memset(sc, 0, sizeof(softc_t));
6882
6883   /* Allocate space for the HDLC network device struct. */
6884   if ((net_dev = alloc_hdlcdev(sc)) == NULL)
6885     {
6886     printk("%s: alloc_hdlcdev() failed\n", DEVICE_NAME);
6887     kfree(sc);
6888     return -ENOMEM;
6889     }
6890
6891   /* Initialize the network device struct. */
6892   setup_netdev(net_dev);
6893
6894   /* Initialize the HDLC extension to the network device. */
6895   sc->hdlc_dev         = dev_to_hdlc(net_dev);
6896   sc->hdlc_dev->attach = hdlc_attach; /* noop for this driver */
6897   sc->hdlc_dev->xmit   = linux_start; /* the REAL hard_start_xmit() */
6898
6899 # else /* GEN_HDLC */ /* no line protocol. */
6900
6901   /* Allocate space for the bare network device struct. */
6902   net_dev = alloc_netdev(sizeof(softc_t), DEVICE_NAME"%d", setup_netdev);
6903   if (net_dev == NULL)
6904     {
6905     printk("%s: alloc_netdev() failed\n", DEVICE_NAME);
6906     return -ENOMEM;
6907     }
6908   /* device driver instance data, aka Soft Context or sc */
6909   sc = net_dev->priv;
6910
6911 # endif /* GEN_HDLC */
6912
6913   sc->net_dev = net_dev;  /* NAME_UNIT macro needs this */
6914   sc->pci_dev = pci_dev;  /* READ/WRITE_PCI_CFG macros need this */
6915
6916   /* Cross-link pci_dev and net_dev. */
6917   pci_set_drvdata(pci_dev, net_dev);      /* pci_dev->driver_data = net_dev */
6918   SET_NETDEV_DEV(net_dev, &pci_dev->dev); /* net_dev->class_dev.dev = &pci_dev->dev */
6919   SET_MODULE_OWNER(net_dev);              /* ??? NOOP in linux-2.6.3. ??? */
6920
6921   /* Sets cfcs.io and cfcs.mem; sets pci_dev->irq based on cfit.int */
6922   if ((error = pci_enable_device(pci_dev)))
6923     {
6924     printk("%s: pci_enable_device() failed; error %d\n", DEVICE_NAME, error);
6925     linux_remove(pci_dev);
6926     return error;
6927     }
6928   net_dev->irq = pci_dev->irq; /* linux_open/stop need this */
6929
6930   /* Allocate PCI memory and IO resources to access the Tulip chip CSRs. */
6931   if ((error = pci_request_regions(pci_dev, DEVICE_NAME)))
6932     {
6933     printk("%s: pci_request_regions() failed; error %d\n", DEVICE_NAME, error);
6934     linux_remove(pci_dev);
6935     return error;
6936     }
6937   net_dev->base_addr = pci_resource_start(pci_dev, 0);
6938   net_dev->mem_start = pci_resource_start(pci_dev, 1);
6939   net_dev->mem_end   = pci_resource_end(pci_dev, 1);
6940   sc->csr_iobase     = net_dev->base_addr;
6941
6942 # if (IOREF_CSR == 0)
6943   sc->csr_membase = ioremap_nocache(net_dev->mem_start, TLP_CSR_SIZE);
6944   if (sc->csr_membase == NULL)
6945     {
6946     printk("%s: ioremap_nocache() failed\n", DEVICE_NAME);
6947     linux_remove(pci_dev);
6948     return -EFAULT;
6949     }
6950 # endif
6951
6952   /* Sets cfcs.master, enabling PCI DMA; checks latency timer value. */
6953   pci_set_master(pci_dev); /* Later, attach_card() does this too. */
6954
6955   /* Initialize the top-half and bottom-half locks. */
6956   /* Top_lock must be initialized before net_dev is registered. */
6957   init_MUTEX(&sc->top_lock);
6958   spin_lock_init(&sc->bottom_lock);
6959
6960 # if GEN_HDLC
6961   if ((error = register_hdlc_device(net_dev)))
6962     {
6963     printk("%s: register_hdlc_device() failed; error %d\n", DEVICE_NAME, error);
6964     linux_remove(pci_dev);
6965     return error;
6966     }
6967 # else
6968   if ((error = register_netdev(net_dev)))
6969     {
6970     printk("%s: register_netdev() failed; error %d\n", DEVICE_NAME, error);
6971     linux_remove(pci_dev);
6972     return error;
6973     }
6974 # endif
6975   /* The NAME_UNIT macro now works.  Use DEVICE_NAME before this. */
6976   sc->flags |= FLAG_NETDEV;
6977
6978   /* What kind of card are we driving? */
6979   switch (READ_PCI_CFG(sc, TLP_CSID))
6980     {
6981     case TLP_CSID_HSSI:
6982     case TLP_CSID_HSSIc:
6983       sc->dev_desc =  HSSI_DESC;
6984       sc->card     = &hssi_card;
6985       break;
6986     case TLP_CSID_T3:
6987       sc->dev_desc =    T3_DESC;
6988       sc->card     =   &t3_card;
6989       break;
6990     case TLP_CSID_SSI:
6991       sc->dev_desc =   SSI_DESC;
6992       sc->card     =  &ssi_card;
6993       break;
6994     case TLP_CSID_T1E1:
6995       sc->dev_desc =  T1E1_DESC;
6996       sc->card     =   &t1_card;
6997       break;
6998     default: /* shouldn't happen! */
6999       linux_remove(pci_dev);
7000       return -ENXIO;
7001     }
7002
7003   /* Announce the hardware on the console. */
7004   printk("%s: <%s> io 0x%04lx/9 mem 0x%08lx/25 rom 0x%08lx/14 irq %d pci %s\n",
7005    NAME_UNIT, sc->dev_desc, pci_resource_start(pci_dev, 0),
7006    pci_resource_start(pci_dev, 1), pci_resource_start(pci_dev, 6),
7007    pci_dev->irq, pci_name(pci_dev));
7008
7009   return 0;
7010   }
7011
7012 /* This pci driver knows how to drive these devices: */
7013 static __initdata struct pci_device_id pci_device_id_tbl[] =
7014   {
7015   /* Looking for a DEC 21140A chip on any Lan Media Corp card. */
7016     { 0x1011, 0x0009, 0x1376, PCI_ANY_ID, 0, 0, 0 },
7017     {      0,      0,      0,          0, 0, 0, 0 }
7018   };
7019 MODULE_DEVICE_TABLE(pci, pci_device_id_tbl);
7020
7021 static struct pci_driver pci_driver =
7022   {
7023   .name     = DEVICE_NAME,
7024   .id_table = pci_device_id_tbl,
7025   .probe    = linux_probe,
7026   .remove   = __devexit_p(linux_remove),
7027   /* This driver does not suspend and resume. */
7028   };
7029
7030 /* This ultimately calls our pci_driver.probe() method. */
7031 static int  __init linux_modload(void)
7032   { return pci_module_init(&pci_driver); }
7033 module_init(linux_modload);
7034
7035 /* This ultimately calls our pci_driver.remove() method. */
7036 static void __exit linux_modunload(void)
7037   { pci_unregister_driver(&pci_driver); }
7038 module_exit(linux_modunload);
7039
7040 MODULE_LICENSE("Dual BSD/GPL");
7041 MODULE_DESCRIPTION("Device driver for SBE/LMC Wide-Area Network cards");
7042 MODULE_AUTHOR("David Boggs <boggs@boggs.palo-alto.ca.us>");
7043
7044 #endif /* __linux__ */