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