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