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