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