Merge branch 'vendor/OPENSSL'
[dragonfly.git] / sys / dev / netif / fe / if_fe.c
1 /*
2  * All Rights Reserved, Copyright (C) Fujitsu Limited 1995
3  *
4  * This software may be used, modified, copied, distributed, and sold, in
5  * both source and binary form provided that the above copyright, these
6  * terms and the following disclaimer are retained.  The name of the author
7  * and/or the contributor may not be used to endorse or promote products
8  * derived from this software without specific prior written permission.
9  *
10  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND THE CONTRIBUTOR ``AS IS'' AND
11  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR THE CONTRIBUTOR BE LIABLE
14  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
15  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
16  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION.
17  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
19  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
20  * SUCH DAMAGE.
21  */
22
23 /*
24  * $FreeBSD: src/sys/dev/fe/if_fe.c,v 1.65.2.1 2000/09/22 10:01:47 nyan Exp $
25  *
26  * Device driver for Fujitsu MB86960A/MB86965A based Ethernet cards.
27  * Contributed by M. Sekiguchi. <seki@sysrap.cs.fujitsu.co.jp>
28  *
29  * This version is intended to be a generic template for various
30  * MB86960A/MB86965A based Ethernet cards.  It currently supports
31  * Fujitsu FMV-180 series for ISA and Allied-Telesis AT1700/RE2000
32  * series for ISA, as well as Fujitsu MBH10302 PC card.
33  * There are some currently-
34  * unused hooks embedded, which are primarily intended to support
35  * other types of Ethernet cards, but the author is not sure whether
36  * they are useful.
37  *
38  * This version also includes some alignments to support RE1000,
39  * C-NET(98)P2 and so on. These cards are not for AT-compatibles,
40  * but for NEC PC-98 bus -- a proprietary bus architecture available
41  * only in Japan. Confusingly, it is different from the Microsoft's
42  * PC98 architecture. :-{
43  * Further work for PC-98 version will be available as a part of
44  * FreeBSD(98) project.
45  *
46  * This software is a derivative work of if_ed.c version 1.56 by David
47  * Greenman available as a part of FreeBSD 2.0 RELEASE source distribution.
48  *
49  * The following lines are retained from the original if_ed.c:
50  *
51  * Copyright (C) 1993, David Greenman. This software may be used, modified,
52  *   copied, distributed, and sold, in both source and binary form provided
53  *   that the above copyright and these terms are retained. Under no
54  *   circumstances is the author responsible for the proper functioning
55  *   of this software, nor does the author assume any responsibility
56  *   for damages incurred with its use.
57  */
58
59 /*
60  * TODO:
61  *  o   To support ISA PnP auto configuration for FMV-183/184.
62  *  o   To support REX-9886/87(PC-98 only).
63  *  o   To reconsider mbuf usage.
64  *  o   To reconsider transmission buffer usage, including
65  *      transmission buffer size (currently 4KB x 2) and pros-and-
66  *      cons of multiple frame transmission.
67  *  o   To test new-bus frontend.
68  */
69
70 #include "opt_fe.h"
71 #include "opt_inet.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/socket.h>
76 #include <sys/sockio.h>
77 #include <sys/mbuf.h>
78 #include <sys/interrupt.h>
79 #include <sys/linker_set.h>
80 #include <sys/module.h>
81 #include <sys/bus.h>
82 #include <sys/rman.h>
83 #include <sys/thread2.h>
84
85 #include <net/ethernet.h>
86 #include <net/if.h>
87 #include <net/ifq_var.h>
88 #include <net/if_dl.h>
89 #include <net/if_mib.h>
90 #include <net/if_media.h>
91
92 #include <netinet/in.h>
93 #include <netinet/if_ether.h>
94
95 #include <net/bpf.h>
96
97 #include "mb86960.h"
98 #include "if_fereg.h"
99 #include "if_fevar.h"
100
101 /*
102  * Transmit just one packet per a "send" command to 86960.
103  * This option is intended for performance test.  An EXPERIMENTAL option.
104  */
105 #ifndef FE_SINGLE_TRANSMISSION
106 #define FE_SINGLE_TRANSMISSION 0
107 #endif
108
109 /*
110  * Maximum loops when interrupt.
111  * This option prevents an infinite loop due to hardware failure.
112  * (Some laptops make an infinite loop after PC-Card is ejected.)
113  */
114 #ifndef FE_MAX_LOOP
115 #define FE_MAX_LOOP 0x800
116 #endif
117
118 /*
119  * If you define this option, 8-bit cards are also supported.
120  */
121 /*#define FE_8BIT_SUPPORT*/
122
123 /*
124  * Device configuration flags.
125  */
126
127 /* DLCR6 settings.  */
128 #define FE_FLAGS_DLCR6_VALUE    0x007F
129
130 /* Force DLCR6 override.  */
131 #define FE_FLAGS_OVERRIDE_DLCR6 0x0080
132
133
134 devclass_t fe_devclass;
135
136 /*
137  * Special filter values.
138  */
139 static struct fe_filter const fe_filter_nothing = { FE_FILTER_NOTHING };
140 static struct fe_filter const fe_filter_all     = { FE_FILTER_ALL };
141
142 /* Standard driver entry points.  These can be static.  */
143 static void             fe_init         (void *);
144 static void             fe_intr         (void *);
145 static int              fe_ioctl        (struct ifnet *, u_long, caddr_t,
146                                          struct ucred *);
147 static void             fe_start        (struct ifnet *,
148                                          struct ifaltq_subque *);
149 static void             fe_watchdog     (struct ifnet *);
150 static int              fe_medchange    (struct ifnet *);
151 static void             fe_medstat      (struct ifnet *, struct ifmediareq *);
152
153 /* Local functions.  Order of declaration is confused.  FIXME.  */
154 static int      fe_get_packet   ( struct fe_softc *, u_short );
155 static void     fe_tint         ( struct fe_softc *, u_char );
156 static void     fe_rint         ( struct fe_softc *, u_char );
157 static void     fe_xmit         ( struct fe_softc * );
158 static void     fe_write_mbufs  ( struct fe_softc *, struct mbuf * );
159 static void     fe_setmode      ( struct fe_softc * );
160 static void     fe_loadmar      ( struct fe_softc * );
161
162 #ifdef DIAGNOSTIC
163 static void     fe_emptybuffer  ( struct fe_softc * );
164 #endif
165
166 DECLARE_DUMMY_MODULE(if_fe);
167
168 /*
169  * Fe driver specific constants which relate to 86960/86965.
170  */
171
172 /* Interrupt masks  */
173 #define FE_TMASK ( FE_D2_COLL16 | FE_D2_TXDONE )
174 #define FE_RMASK ( FE_D3_OVRFLO | FE_D3_CRCERR \
175                  | FE_D3_ALGERR | FE_D3_SRTPKT | FE_D3_PKTRDY )
176
177 /* Maximum number of iterations for a receive interrupt.  */
178 #define FE_MAX_RECV_COUNT ( ( 65536 - 2048 * 2 ) / 64 )
179         /*
180          * Maximum size of SRAM is 65536,
181          * minimum size of transmission buffer in fe is 2x2KB,
182          * and minimum amount of received packet including headers
183          * added by the chip is 64 bytes.
184          * Hence FE_MAX_RECV_COUNT is the upper limit for number
185          * of packets in the receive buffer.
186          */
187
188 /*
189  * Miscellaneous definitions not directly related to hardware.
190  */
191
192 /* The following line must be delete when "net/if_media.h" support it.  */
193 #ifndef IFM_10_FL
194 #define IFM_10_FL       /* 13 */ IFM_10_5
195 #endif
196
197 #if 0
198 /* Mapping between media bitmap (in fe_softc.mbitmap) and ifm_media.  */
199 static int const bit2media [] = {
200                         IFM_HDX | IFM_ETHER | IFM_AUTO,
201                         IFM_HDX | IFM_ETHER | IFM_MANUAL,
202                         IFM_HDX | IFM_ETHER | IFM_10_T,
203                         IFM_HDX | IFM_ETHER | IFM_10_2,
204                         IFM_HDX | IFM_ETHER | IFM_10_5,
205                         IFM_HDX | IFM_ETHER | IFM_10_FL,
206                         IFM_FDX | IFM_ETHER | IFM_10_T,
207         /* More can be come here... */
208                         0
209 };
210 #else
211 /* Mapping between media bitmap (in fe_softc.mbitmap) and ifm_media.  */
212 static int const bit2media [] = {
213                         IFM_ETHER | IFM_AUTO,
214                         IFM_ETHER | IFM_MANUAL,
215                         IFM_ETHER | IFM_10_T,
216                         IFM_ETHER | IFM_10_2,
217                         IFM_ETHER | IFM_10_5,
218                         IFM_ETHER | IFM_10_FL,
219                         IFM_ETHER | IFM_10_T,
220         /* More can be come here... */
221                         0
222 };
223 #endif
224
225 /*
226  * Check for specific bits in specific registers have specific values.
227  * A common utility function called from various sub-probe routines.
228  */
229 int
230 fe_simple_probe (struct fe_softc const * sc,
231                  struct fe_simple_probe_struct const * sp)
232 {
233         struct fe_simple_probe_struct const *p;
234
235         for (p  = sp; p->mask != 0; p++) {
236                 if ((fe_inb(sc, p->port) & p->mask) != p->bits)
237                         return 0;
238         }
239         return 1;
240 }
241
242 /* Test if a given 6 byte value is a valid Ethernet station (MAC)
243    address.  "Vendor" is an expected vendor code (first three bytes,)
244    or a zero when nothing expected.  */
245 int
246 valid_Ether_p (u_char const * addr, unsigned vendor)
247 {
248 #ifdef FE_DEBUG
249         char ethstr[ETHER_ADDRSTRLEN + 1];
250         kprintf("fe?: validating %s against %06x\n", kether_ntoa(addr, ethstr),
251             vendor);
252 #endif
253
254         /* All zero is not allowed as a vendor code.  */
255         if (addr[0] == 0 && addr[1] == 0 && addr[2] == 0) return 0;
256
257         switch (vendor) {
258             case 0x000000:
259                 /* Legal Ethernet address (stored in ROM) must have
260                    its Group and Local bits cleared.  */
261                 if ((addr[0] & 0x03) != 0) return 0;
262                 break;
263             case 0x020000:
264                 /* Same as above, but a local address is allowed in
265                    this context.  */
266                 if ((addr[0] & 0x01) != 0) return 0;
267                 break;
268             default:
269                 /* Make sure the vendor part matches if one is given.  */
270                 if (   addr[0] != ((vendor >> 16) & 0xFF)
271                     || addr[1] != ((vendor >>  8) & 0xFF)
272                     || addr[2] != ((vendor      ) & 0xFF)) return 0;
273                 break;
274         }
275
276         /* Host part must not be all-zeros nor all-ones.  */
277         if (addr[3] == 0xFF && addr[4] == 0xFF && addr[5] == 0xFF) return 0;
278         if (addr[3] == 0x00 && addr[4] == 0x00 && addr[5] == 0x00) return 0;
279
280         /* Given addr looks like an Ethernet address.  */
281         return 1;
282 }
283
284 /* Fill our softc struct with default value.  */
285 void
286 fe_softc_defaults (struct fe_softc *sc)
287 {
288         /* Prepare for typical register prototypes.  We assume a
289            "typical" board has <32KB> of <fast> SRAM connected with a
290            <byte-wide> data lines.  */
291         sc->proto_dlcr4 = FE_D4_LBC_DISABLE | FE_D4_CNTRL;
292         sc->proto_dlcr5 = 0;
293         sc->proto_dlcr6 = FE_D6_BUFSIZ_32KB | FE_D6_TXBSIZ_2x4KB
294                 | FE_D6_BBW_BYTE | FE_D6_SBW_WORD | FE_D6_SRAM_100ns;
295         sc->proto_dlcr7 = FE_D7_BYTSWP_LH;
296         sc->proto_bmpr13 = 0;
297
298         /* Assume the probe process (to be done later) is stable.  */
299         sc->stability = 0;
300
301         /* A typical board needs no hooks.  */
302         sc->init = NULL;
303         sc->stop = NULL;
304
305         /* Assume the board has no software-controllable media selection.  */
306         sc->mbitmap = MB_HM;
307         sc->defmedia = MB_HM;
308         sc->msel = NULL;
309 }
310
311 /* Common error reporting routine used in probe routines for
312    "soft configured IRQ"-type boards.  */
313 void
314 fe_irq_failure (char const *name, int unit, int irq, char const *list)
315 {
316         kprintf("fe%d: %s board is detected, but %s IRQ was given\n",
317                unit, name, (irq == NO_IRQ ? "no" : "invalid"));
318         if (list != NULL) {
319                 kprintf("fe%d: specify an IRQ from %s in kernel config\n",
320                        unit, list);
321         }
322 }
323
324 /*
325  * Hardware (vendor) specific hooks.
326  */
327
328 /*
329  * Generic media selection scheme for MB86965 based boards.
330  */
331 void
332 fe_msel_965 (struct fe_softc *sc)
333 {
334         u_char b13;
335
336         /* Find the appropriate bits for BMPR13 tranceiver control.  */
337         switch (IFM_SUBTYPE(sc->media.ifm_media)) {
338             case IFM_AUTO: b13 = FE_B13_PORT_AUTO | FE_B13_TPTYPE_UTP; break;
339             case IFM_10_T: b13 = FE_B13_PORT_TP   | FE_B13_TPTYPE_UTP; break;
340             default:       b13 = FE_B13_PORT_AUI;  break;
341         }
342
343         /* Write it into the register.  It takes effect immediately.  */
344         fe_outb(sc, FE_BMPR13, sc->proto_bmpr13 | b13);
345 }
346
347
348 /*
349  * Fujitsu MB86965 JLI mode support routines.
350  */
351
352 /*
353  * Routines to read all bytes from the config EEPROM through MB86965A.
354  * It is a MicroWire (3-wire) serial EEPROM with 6-bit address.
355  * (93C06 or 93C46.)
356  */
357 static void
358 fe_strobe_eeprom_jli (struct fe_softc *sc, u_short bmpr16)
359 {
360         /*
361          * We must guarantee 1us (or more) interval to access slow
362          * EEPROMs.  The following redundant code provides enough
363          * delay with ISA timing.  (Even if the bus clock is "tuned.")
364          * Some modification will be needed on faster busses.
365          */
366         fe_outb(sc, bmpr16, FE_B16_SELECT);
367         fe_outb(sc, bmpr16, FE_B16_SELECT | FE_B16_CLOCK);
368         fe_outb(sc, bmpr16, FE_B16_SELECT | FE_B16_CLOCK);
369         fe_outb(sc, bmpr16, FE_B16_SELECT);
370 }
371
372 void
373 fe_read_eeprom_jli (struct fe_softc * sc, u_char * data)
374 {
375         u_char n, val, bit;
376         u_char save16, save17;
377         char hexstr[48];
378
379         /* Save the current value of the EEPROM interface registers.  */
380         save16 = fe_inb(sc, FE_BMPR16);
381         save17 = fe_inb(sc, FE_BMPR17);
382
383         /* Read bytes from EEPROM; two bytes per an iteration.  */
384         for (n = 0; n < JLI_EEPROM_SIZE / 2; n++) {
385
386                 /* Reset the EEPROM interface.  */
387                 fe_outb(sc, FE_BMPR16, 0x00);
388                 fe_outb(sc, FE_BMPR17, 0x00);
389
390                 /* Start EEPROM access.  */
391                 fe_outb(sc, FE_BMPR16, FE_B16_SELECT);
392                 fe_outb(sc, FE_BMPR17, FE_B17_DATA);
393                 fe_strobe_eeprom_jli(sc, FE_BMPR16);
394
395                 /* Pass the iteration count as well as a READ command.  */
396                 val = 0x80 | n;
397                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
398                         fe_outb(sc, FE_BMPR17, (val & bit) ? FE_B17_DATA : 0);
399                         fe_strobe_eeprom_jli(sc, FE_BMPR16);
400                 }
401                 fe_outb(sc, FE_BMPR17, 0x00);
402
403                 /* Read a byte.  */
404                 val = 0;
405                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
406                         fe_strobe_eeprom_jli(sc, FE_BMPR16);
407                         if (fe_inb(sc, FE_BMPR17) & FE_B17_DATA)
408                                 val |= bit;
409                 }
410                 *data++ = val;
411
412                 /* Read one more byte.  */
413                 val = 0;
414                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
415                         fe_strobe_eeprom_jli(sc, FE_BMPR16);
416                         if (fe_inb(sc, FE_BMPR17) & FE_B17_DATA)
417                                 val |= bit;
418                 }
419                 *data++ = val;
420         }
421
422 #if 0
423         /* Reset the EEPROM interface, again.  */
424         fe_outb(sc, FE_BMPR16, 0x00);
425         fe_outb(sc, FE_BMPR17, 0x00);
426 #else
427         /* Make sure to restore the original value of EEPROM interface
428            registers, since we are not yet sure we have MB86965A on
429            the address.  */
430         fe_outb(sc, FE_BMPR17, save17);
431         fe_outb(sc, FE_BMPR16, save16);
432 #endif
433
434 #if 1
435         /* Report what we got.  */
436         if (bootverbose) {
437                 int i;
438                 data -= JLI_EEPROM_SIZE;
439                 for (i = 0; i < JLI_EEPROM_SIZE; i += 16) {
440                         hexncpy(data + i, 16, hexstr, 48, " ");
441                         kprintf("fe%d: EEPROM(JLI):%3x: %s\n",
442                             sc->sc_unit, i, hexstr);
443                 }
444         }
445 #endif
446 }
447
448 void
449 fe_init_jli (struct fe_softc * sc)
450 {
451         /* "Reset" by writing into a magic location.  */
452         DELAY(200);
453         fe_outb(sc, 0x1E, fe_inb(sc, 0x1E));
454         DELAY(300);
455 }
456
457
458 /*
459  * SSi 78Q8377A support routines.
460  */
461
462 /*
463  * Routines to read all bytes from the config EEPROM through 78Q8377A.
464  * It is a MicroWire (3-wire) serial EEPROM with 8-bit address.  (I.e.,
465  * 93C56 or 93C66.)
466  *
467  * As I don't have SSi manuals, (hmm, an old song again!) I'm not exactly
468  * sure the following code is correct...  It is just stolen from the
469  * C-NET(98)P2 support routine in FreeBSD(98).
470  */
471
472 void
473 fe_read_eeprom_ssi (struct fe_softc *sc, u_char *data)
474 {
475         u_char val, bit;
476         int n;
477         u_char save6, save7, save12;
478         char hexstr[48];
479
480         /* Save the current value for the DLCR registers we are about
481            to destroy.  */
482         save6 = fe_inb(sc, FE_DLCR6);
483         save7 = fe_inb(sc, FE_DLCR7);
484
485         /* Put the 78Q8377A into a state that we can access the EEPROM.  */
486         fe_outb(sc, FE_DLCR6,
487             FE_D6_BBW_WORD | FE_D6_SBW_WORD | FE_D6_DLC_DISABLE);
488         fe_outb(sc, FE_DLCR7,
489             FE_D7_BYTSWP_LH | FE_D7_RBS_BMPR | FE_D7_RDYPNS | FE_D7_POWER_UP);
490
491         /* Save the current value for the BMPR12 register, too.  */
492         save12 = fe_inb(sc, FE_DLCR12);
493
494         /* Read bytes from EEPROM; two bytes per an iteration.  */
495         for (n = 0; n < SSI_EEPROM_SIZE / 2; n++) {
496
497                 /* Start EEPROM access  */
498                 fe_outb(sc, FE_DLCR12, SSI_EEP);
499                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL);
500
501                 /* Send the following four bits to the EEPROM in the
502                    specified order: a dummy bit, a start bit, and
503                    command bits (10) for READ.  */
504                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL                    );
505                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK          );  /* 0 */
506                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL           | SSI_DAT);
507                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK | SSI_DAT);  /* 1 */
508                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL           | SSI_DAT);
509                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK | SSI_DAT);  /* 1 */
510                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL                    );
511                 fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK          );  /* 0 */
512
513                 /* Pass the iteration count to the chip.  */
514                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
515                     val = ( n & bit ) ? SSI_DAT : 0;
516                     fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL           | val);
517                     fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK | val);
518                 }
519
520                 /* Read a byte.  */
521                 val = 0;
522                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
523                     fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL);
524                     fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK);
525                     if (fe_inb(sc, FE_DLCR12) & SSI_DIN)
526                         val |= bit;
527                 }
528                 *data++ = val;
529
530                 /* Read one more byte.  */
531                 val = 0;
532                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
533                     fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL);
534                     fe_outb(sc, FE_DLCR12, SSI_EEP | SSI_CSL | SSI_CLK);
535                     if (fe_inb(sc, FE_DLCR12) & SSI_DIN)
536                         val |= bit;
537                 }
538                 *data++ = val;
539
540                 fe_outb(sc, FE_DLCR12, SSI_EEP);
541         }
542
543         /* Reset the EEPROM interface.  (For now.)  */
544         fe_outb(sc, FE_DLCR12, 0x00);
545
546         /* Restore the saved register values, for the case that we
547            didn't have 78Q8377A at the given address.  */
548         fe_outb(sc, FE_DLCR12, save12);
549         fe_outb(sc, FE_DLCR7, save7);
550         fe_outb(sc, FE_DLCR6, save6);
551
552 #if 1
553         /* Report what we got.  */
554         if (bootverbose) {
555                 int i;
556                 data -= SSI_EEPROM_SIZE;
557                 for (i = 0; i < SSI_EEPROM_SIZE; i += 16) {
558                         hexncpy(data + i, 16, hexstr, 48, " ");
559                         kprintf("fe%d: EEPROM(SSI):%3x: %s\n",
560                             sc->sc_unit, i, hexstr);
561                 }
562         }
563 #endif
564 }
565
566 /*
567  * TDK/LANX boards support routines.
568  */
569
570 /* It is assumed that the CLK line is low and SDA is high (float) upon entry.  */
571 #define LNX_PH(D,K,N) \
572         ((LNX_SDA_##D | LNX_CLK_##K) << N)
573 #define LNX_CYCLE(D1,D2,D3,D4,K1,K2,K3,K4) \
574         (LNX_PH(D1,K1,0)|LNX_PH(D2,K2,8)|LNX_PH(D3,K3,16)|LNX_PH(D4,K4,24))
575
576 #define LNX_CYCLE_START LNX_CYCLE(HI,LO,LO,HI, HI,HI,LO,LO)
577 #define LNX_CYCLE_STOP  LNX_CYCLE(LO,LO,HI,HI, LO,HI,HI,LO)
578 #define LNX_CYCLE_HI    LNX_CYCLE(HI,HI,HI,HI, LO,HI,LO,LO)
579 #define LNX_CYCLE_LO    LNX_CYCLE(LO,LO,LO,HI, LO,HI,LO,LO)
580 #define LNX_CYCLE_INIT  LNX_CYCLE(LO,HI,HI,HI, LO,LO,LO,LO)
581
582 static void
583 fe_eeprom_cycle_lnx (struct fe_softc *sc, u_short reg20, u_long cycle)
584 {
585         fe_outb(sc, reg20, (cycle      ) & 0xFF);
586         DELAY(15);
587         fe_outb(sc, reg20, (cycle >>  8) & 0xFF);
588         DELAY(15);
589         fe_outb(sc, reg20, (cycle >> 16) & 0xFF);
590         DELAY(15);
591         fe_outb(sc, reg20, (cycle >> 24) & 0xFF);
592         DELAY(15);
593 }
594
595 static u_char
596 fe_eeprom_receive_lnx (struct fe_softc *sc, u_short reg20)
597 {
598         u_char dat;
599
600         fe_outb(sc, reg20, LNX_CLK_HI | LNX_SDA_FL);
601         DELAY(15);
602         dat = fe_inb(sc, reg20);
603         fe_outb(sc, reg20, LNX_CLK_LO | LNX_SDA_FL);
604         DELAY(15);
605         return (dat & LNX_SDA_IN);
606 }
607
608 void
609 fe_read_eeprom_lnx (struct fe_softc *sc, u_char *data)
610 {
611         int i;
612         u_char n, bit, val;
613         u_char save20;
614         u_short reg20 = 0x14;
615         char hexstr[48];
616
617         save20 = fe_inb(sc, reg20);
618
619         /* NOTE: DELAY() timing constants are approximately three
620            times longer (slower) than the required minimum.  This is
621            to guarantee a reliable operation under some tough
622            conditions...  Fortunately, this routine is only called
623            during the boot phase, so the speed is less important than
624            stability.  */
625
626 #if 1
627         /* Reset the X24C01's internal state machine and put it into
628            the IDLE state.  We usually don't need this, but *if*
629            someone (e.g., probe routine of other driver) write some
630            garbage into the register at 0x14, synchronization will be
631            lost, and the normal EEPROM access protocol won't work.
632            Moreover, as there are no easy way to reset, we need a
633            _manoeuvre_ here.  (It even lacks a reset pin, so pushing
634            the RESET button on the PC doesn't help!)  */
635         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_INIT);
636         for (i = 0; i < 10; i++)
637                 fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_START);
638         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_STOP);
639         DELAY(10000);
640 #endif
641
642         /* Issue a start condition.  */
643         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_START);
644
645         /* Send seven bits of the starting address (zero, in this
646            case) and a command bit for READ.  */
647         val = 0x01;
648         for (bit = 0x80; bit != 0x00; bit >>= 1) {
649                 if (val & bit) {
650                         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_HI);
651                 } else {
652                         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_LO);
653                 }
654         }
655
656         /* Receive an ACK bit.  */
657         if (fe_eeprom_receive_lnx(sc, reg20)) {
658                 /* ACK was not received.  EEPROM is not present (i.e.,
659                    this board was not a TDK/LANX) or not working
660                    properly.  */
661                 if (bootverbose) {
662                         kprintf("fe%d: no ACK received from EEPROM(LNX)\n",
663                                sc->sc_unit);
664                 }
665                 /* Clear the given buffer to indicate we could not get
666                    any info. and return.  */
667                 bzero(data, LNX_EEPROM_SIZE);
668                 goto RET;
669         }
670
671         /* Read bytes from EEPROM.  */
672         for (n = 0; n < LNX_EEPROM_SIZE; n++) {
673
674                 /* Read a byte and store it into the buffer.  */
675                 val = 0x00;
676                 for (bit = 0x80; bit != 0x00; bit >>= 1) {
677                         if (fe_eeprom_receive_lnx(sc, reg20))
678                                 val |= bit;
679                 }
680                 *data++ = val;
681
682                 /* Acknowledge if we have to read more.  */
683                 if (n < LNX_EEPROM_SIZE - 1) {
684                         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_LO);
685                 }
686         }
687
688         /* Issue a STOP condition, de-activating the clock line.
689            It will be safer to keep the clock line low than to leave
690            it high.  */
691         fe_eeprom_cycle_lnx(sc, reg20, LNX_CYCLE_STOP);
692
693     RET:
694         fe_outb(sc, reg20, save20);
695         
696 #if 1
697         /* Report what we got.  */
698         if (bootverbose) {
699                 data -= LNX_EEPROM_SIZE;
700                 for (i = 0; i < LNX_EEPROM_SIZE; i += 16) {
701                         hexncpy(data + i, 16, hexstr, 48, " ");
702                         kprintf("fe%d: EEPROM(LNX):%3x: %s\n",
703                             sc->sc_unit, i, hexstr);
704                 }
705         }
706 #endif
707 }
708
709 void
710 fe_init_lnx (struct fe_softc * sc)
711 {
712         /* Reset the 86960.  Do we need this?  FIXME.  */
713         fe_outb(sc, 0x12, 0x06);
714         DELAY(100);
715         fe_outb(sc, 0x12, 0x07);
716         DELAY(100);
717
718         /* Setup IRQ control register on the ASIC.  */
719         fe_outb(sc, 0x14, sc->priv_info);
720 }
721
722
723 /*
724  * Ungermann-Bass boards support routine.
725  */
726 void
727 fe_init_ubn (struct fe_softc * sc)
728 {
729         /* Do we need this?  FIXME.  */
730         fe_outb(sc, FE_DLCR7,
731                 sc->proto_dlcr7 | FE_D7_RBS_BMPR | FE_D7_POWER_UP);
732         fe_outb(sc, 0x18, 0x00);
733         DELAY(200);
734
735         /* Setup IRQ control register on the ASIC.  */
736         fe_outb(sc, 0x14, sc->priv_info);
737 }
738
739
740 /*
741  * Install interface into kernel networking data structures
742  */
743 int
744 fe_attach (device_t dev)
745 {
746         struct fe_softc *sc = device_get_softc(dev);
747         int flags = device_get_flags(dev);
748         int b, error;
749
750         /*
751          * Initialize ifnet structure
752          */
753         sc->sc_if.if_softc    = sc;
754         if_initname(&(sc->sc_if), "fe", sc->sc_unit);
755         sc->sc_if.if_start    = fe_start;
756         sc->sc_if.if_ioctl    = fe_ioctl;
757         sc->sc_if.if_watchdog = fe_watchdog;
758         sc->sc_if.if_init     = fe_init;
759         sc->sc_if.if_linkmib  = &sc->mibdata;
760         sc->sc_if.if_linkmiblen = sizeof (sc->mibdata);
761
762 #if 0 /* I'm not sure... */
763         sc->mibdata.dot3Compliance = DOT3COMPLIANCE_COLLS;
764 #endif
765
766         /*
767          * Set fixed interface flags.
768          */
769         sc->sc_if.if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
770         ifq_set_maxlen(&sc->sc_if.if_snd, IFQ_MAXLEN);
771         ifq_set_ready(&sc->sc_if.if_snd);
772
773 #if FE_SINGLE_TRANSMISSION
774         /* Override txb config to allocate minimum.  */
775         sc->proto_dlcr6 &= ~FE_D6_TXBSIZ
776         sc->proto_dlcr6 |=  FE_D6_TXBSIZ_2x2KB;
777 #endif
778
779         /* Modify hardware config if it is requested.  */
780         if (flags & FE_FLAGS_OVERRIDE_DLCR6)
781                 sc->proto_dlcr6 = flags & FE_FLAGS_DLCR6_VALUE;
782
783         /* Find TX buffer size, based on the hardware dependent proto.  */
784         switch (sc->proto_dlcr6 & FE_D6_TXBSIZ) {
785           case FE_D6_TXBSIZ_2x2KB: sc->txb_size = 2048; break;
786           case FE_D6_TXBSIZ_2x4KB: sc->txb_size = 4096; break;
787           case FE_D6_TXBSIZ_2x8KB: sc->txb_size = 8192; break;
788           default:
789                 /* Oops, we can't work with single buffer configuration.  */
790                 if (bootverbose) {
791                         kprintf("fe%d: strange TXBSIZ config; fixing\n",
792                                sc->sc_unit);
793                 }
794                 sc->proto_dlcr6 &= ~FE_D6_TXBSIZ;
795                 sc->proto_dlcr6 |=  FE_D6_TXBSIZ_2x2KB;
796                 sc->txb_size = 2048;
797                 break;
798         }
799
800         /* Initialize the if_media interface.  */
801         ifmedia_init(&sc->media, 0, fe_medchange, fe_medstat);
802         for (b = 0; bit2media[b] != 0; b++) {
803                 if (sc->mbitmap & (1 << b)) {
804                         ifmedia_add(&sc->media, bit2media[b], 0, NULL);
805                 }
806         }
807         for (b = 0; bit2media[b] != 0; b++) {
808                 if (sc->defmedia & (1 << b)) {
809                         ifmedia_set(&sc->media, bit2media[b]);
810                         break;
811                 }
812         }
813 #if 0   /* Turned off; this is called later, when the interface UPs.  */
814         fe_medchange(sc);
815 #endif
816
817         /* Attach and stop the interface. */
818         ether_ifattach(&sc->sc_if, sc->sc_enaddr, NULL);
819
820         ifq_set_cpuid(&sc->sc_if.if_snd, rman_get_cpuid(sc->irq_res));
821
822         fe_stop(sc);
823
824         error = bus_setup_intr(dev, sc->irq_res, INTR_MPSAFE,
825                                fe_intr, sc, &sc->irq_handle, 
826                                sc->sc_if.if_serializer);
827         if (error) {
828                 if_detach(&sc->sc_if);
829                 fe_release_resource(dev);
830                 return ENXIO;
831         }
832   
833         /* Print additional info when attached.  */
834         device_printf(dev, "type %s%s\n", sc->typestr,
835                       (sc->proto_dlcr4 & FE_D4_DSC) ? ", full duplex" : "");
836         if (bootverbose) {
837                 int buf, txb, bbw, sbw, ram;
838
839                 buf = txb = bbw = sbw = ram = -1;
840                 switch ( sc->proto_dlcr6 & FE_D6_BUFSIZ ) {
841                   case FE_D6_BUFSIZ_8KB:  buf =  8; break;
842                   case FE_D6_BUFSIZ_16KB: buf = 16; break;
843                   case FE_D6_BUFSIZ_32KB: buf = 32; break;
844                   case FE_D6_BUFSIZ_64KB: buf = 64; break;
845                 }
846                 switch ( sc->proto_dlcr6 & FE_D6_TXBSIZ ) {
847                   case FE_D6_TXBSIZ_2x2KB: txb = 2; break;
848                   case FE_D6_TXBSIZ_2x4KB: txb = 4; break;
849                   case FE_D6_TXBSIZ_2x8KB: txb = 8; break;
850                 }
851                 switch ( sc->proto_dlcr6 & FE_D6_BBW ) {
852                   case FE_D6_BBW_BYTE: bbw =  8; break;
853                   case FE_D6_BBW_WORD: bbw = 16; break;
854                 }
855                 switch ( sc->proto_dlcr6 & FE_D6_SBW ) {
856                   case FE_D6_SBW_BYTE: sbw =  8; break;
857                   case FE_D6_SBW_WORD: sbw = 16; break;
858                 }
859                 switch ( sc->proto_dlcr6 & FE_D6_SRAM ) {
860                   case FE_D6_SRAM_100ns: ram = 100; break;
861                   case FE_D6_SRAM_150ns: ram = 150; break;
862                 }
863                 device_printf(dev, "SRAM %dKB %dbit %dns, TXB %dKBx2, %dbit I/O\n",
864                               buf, bbw, ram, txb, sbw);
865         }
866         if (sc->stability & UNSTABLE_IRQ)
867                 device_printf(dev, "warning: IRQ number may be incorrect\n");
868         if (sc->stability & UNSTABLE_MAC)
869                 device_printf(dev, "warning: above MAC address may be incorrect\n");
870         if (sc->stability & UNSTABLE_TYPE)
871                 device_printf(dev, "warning: hardware type was not validated\n");
872
873         return 0;
874 }
875
876 int
877 fe_alloc_port(device_t dev, int size)
878 {
879         struct fe_softc *sc = device_get_softc(dev);
880         struct resource *res;
881         int rid;
882
883         rid = 0;
884         res = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
885                                  0ul, ~0ul, size, RF_ACTIVE);
886         if (res) {
887                 sc->port_used = size;
888                 sc->port_res = res;
889                 sc->iot = rman_get_bustag(res);
890                 sc->ioh = rman_get_bushandle(res);
891                 return (0);
892         }
893
894         return (ENOENT);
895 }
896
897 int
898 fe_alloc_irq(device_t dev, int flags)
899 {
900         struct fe_softc *sc = device_get_softc(dev);
901         struct resource *res;
902         int rid;
903
904         rid = 0;
905         res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE | flags);
906         if (res) {
907                 sc->irq_res = res;
908                 return (0);
909         }
910
911         return (ENOENT);
912 }
913
914 void
915 fe_release_resource(device_t dev)
916 {
917         struct fe_softc *sc = device_get_softc(dev);
918
919         if (sc->port_res) {
920                 bus_release_resource(dev, SYS_RES_IOPORT, 0, sc->port_res);
921                 sc->port_res = NULL;
922         }
923         if (sc->irq_res) {
924                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq_res);
925                 sc->irq_res = NULL;
926         }
927 }
928
929 /*
930  * Reset interface, after some (hardware) trouble is deteced.
931  */
932 static void
933 fe_reset (struct fe_softc *sc)
934 {
935         /* Record how many packets are lost by this accident.  */
936         IFNET_STAT_INC(&sc->sc_if, oerrors, sc->txb_sched + sc->txb_count);
937         sc->mibdata.dot3StatsInternalMacTransmitErrors++;
938
939         /* Put the interface into known initial state.  */
940         fe_stop(sc);
941         if (sc->sc_if.if_flags & IFF_UP)
942                 fe_init(sc);
943 }
944
945 /*
946  * Stop everything on the interface.
947  *
948  * All buffered packets, both transmitting and receiving,
949  * if any, will be lost by stopping the interface.
950  */
951 void
952 fe_stop (struct fe_softc *sc)
953 {
954         /* Disable interrupts.  */
955         fe_outb(sc, FE_DLCR2, 0x00);
956         fe_outb(sc, FE_DLCR3, 0x00);
957
958         /* Stop interface hardware.  */
959         DELAY(200);
960         fe_outb(sc, FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
961         DELAY(200);
962
963         /* Clear all interrupt status.  */
964         fe_outb(sc, FE_DLCR0, 0xFF);
965         fe_outb(sc, FE_DLCR1, 0xFF);
966
967         /* Put the chip in stand-by mode.  */
968         DELAY(200);
969         fe_outb(sc, FE_DLCR7, sc->proto_dlcr7 | FE_D7_POWER_DOWN);
970         DELAY(200);
971
972         /* Reset transmitter variables and interface flags.  */
973         sc->sc_if.if_flags &= ~IFF_RUNNING;
974         ifq_clr_oactive(&sc->sc_if.if_snd);
975         sc->sc_if.if_timer = 0;
976         sc->txb_free = sc->txb_size;
977         sc->txb_count = 0;
978         sc->txb_sched = 0;
979
980         /* MAR loading can be delayed.  */
981         sc->filter_change = 0;
982
983         /* Call a device-specific hook.  */
984         if (sc->stop)
985                 sc->stop(sc);
986 }
987
988 /*
989  * Device timeout/watchdog routine. Entered if the device neglects to
990  * generate an interrupt after a transmit has been started on it.
991  */
992 static void
993 fe_watchdog ( struct ifnet *ifp )
994 {
995         struct fe_softc *sc = (struct fe_softc *)ifp;
996         u_long opkts, ipkts;
997
998         /* A "debug" message.  */
999         kprintf("%s: transmission timeout (%d+%d)%s\n",
1000                ifp->if_xname, sc->txb_sched, sc->txb_count,
1001                (ifp->if_flags & IFF_UP) ? "" : " when down");
1002         IFNET_STAT_GET(&sc->sc_if, opackets, opkts);
1003         IFNET_STAT_GET(&sc->sc_if, ipackets, ipkts);
1004         if (opkts == 0 && ipkts == 0)
1005                 kprintf("%s: wrong IRQ setting in config?\n", ifp->if_xname);
1006         fe_reset(sc);
1007 }
1008
1009 /*
1010  * Initialize device.
1011  */
1012 static void
1013 fe_init (void * xsc)
1014 {
1015         struct fe_softc *sc = xsc;
1016
1017         /* Start initializing 86960.  */
1018         /* Call a hook before we start initializing the chip.  */
1019         if (sc->init)
1020                 sc->init(sc);
1021
1022         /*
1023          * Make sure to disable the chip, also.
1024          * This may also help re-programming the chip after
1025          * hot insertion of PCMCIAs.
1026          */
1027         DELAY(200);
1028         fe_outb(sc, FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
1029         DELAY(200);
1030
1031         /* Power up the chip and select register bank for DLCRs.  */
1032         DELAY(200);
1033         fe_outb(sc, FE_DLCR7,
1034                 sc->proto_dlcr7 | FE_D7_RBS_DLCR | FE_D7_POWER_UP);
1035         DELAY(200);
1036
1037         /* Feed the station address.  */
1038         fe_outblk(sc, FE_DLCR8, sc->sc_enaddr, ETHER_ADDR_LEN);
1039
1040         /* Clear multicast address filter to receive nothing.  */
1041         fe_outb(sc, FE_DLCR7,
1042                 sc->proto_dlcr7 | FE_D7_RBS_MAR | FE_D7_POWER_UP);
1043         fe_outblk(sc, FE_MAR8, fe_filter_nothing.data, FE_FILTER_LEN);
1044
1045         /* Select the BMPR bank for runtime register access.  */
1046         fe_outb(sc, FE_DLCR7,
1047                 sc->proto_dlcr7 | FE_D7_RBS_BMPR | FE_D7_POWER_UP);
1048
1049         /* Initialize registers.  */
1050         fe_outb(sc, FE_DLCR0, 0xFF);    /* Clear all bits.  */
1051         fe_outb(sc, FE_DLCR1, 0xFF);    /* ditto.  */
1052         fe_outb(sc, FE_DLCR2, 0x00);
1053         fe_outb(sc, FE_DLCR3, 0x00);
1054         fe_outb(sc, FE_DLCR4, sc->proto_dlcr4);
1055         fe_outb(sc, FE_DLCR5, sc->proto_dlcr5);
1056         fe_outb(sc, FE_BMPR10, 0x00);
1057         fe_outb(sc, FE_BMPR11, FE_B11_CTRL_SKIP | FE_B11_MODE1);
1058         fe_outb(sc, FE_BMPR12, 0x00);
1059         fe_outb(sc, FE_BMPR13, sc->proto_bmpr13);
1060         fe_outb(sc, FE_BMPR14, 0x00);
1061         fe_outb(sc, FE_BMPR15, 0x00);
1062
1063         /* Enable interrupts.  */
1064         fe_outb(sc, FE_DLCR2, FE_TMASK);
1065         fe_outb(sc, FE_DLCR3, FE_RMASK);
1066
1067         /* Select requested media, just before enabling DLC.  */
1068         if (sc->msel)
1069                 sc->msel(sc);
1070
1071         /* Enable transmitter and receiver.  */
1072         DELAY(200);
1073         fe_outb(sc, FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_ENABLE);
1074         DELAY(200);
1075
1076 #ifdef DIAGNOSTIC
1077         /*
1078          * Make sure to empty the receive buffer.
1079          *
1080          * This may be redundant, but *if* the receive buffer were full
1081          * at this point, then the driver would hang.  I have experienced
1082          * some strange hang-up just after UP.  I hope the following
1083          * code solve the problem.
1084          *
1085          * I have changed the order of hardware initialization.
1086          * I think the receive buffer cannot have any packets at this
1087          * point in this version.  The following code *must* be
1088          * redundant now.  FIXME.
1089          *
1090          * I've heard a rumore that on some PC card implementation of
1091          * 8696x, the receive buffer can have some data at this point.
1092          * The following message helps discovering the fact.  FIXME.
1093          */
1094         if (!(fe_inb(sc, FE_DLCR5) & FE_D5_BUFEMP)) {
1095                 kprintf("fe%d: receive buffer has some data after reset\n",
1096                        sc->sc_unit);
1097                 fe_emptybuffer(sc);
1098         }
1099
1100         /* Do we need this here?  Actually, no.  I must be paranoia.  */
1101         fe_outb(sc, FE_DLCR0, 0xFF);    /* Clear all bits.  */
1102         fe_outb(sc, FE_DLCR1, 0xFF);    /* ditto.  */
1103 #endif
1104
1105         /* Set 'running' flag, because we are now running.   */
1106         sc->sc_if.if_flags |= IFF_RUNNING;
1107
1108         /*
1109          * At this point, the interface is running properly,
1110          * except that it receives *no* packets.  we then call
1111          * fe_setmode() to tell the chip what packets to be
1112          * received, based on the if_flags and multicast group
1113          * list.  It completes the initialization process.
1114          */
1115         fe_setmode(sc);
1116
1117 #if 0
1118         /* ...and attempt to start output queued packets.  */
1119         /* TURNED OFF, because the semi-auto media prober wants to UP
1120            the interface keeping it idle.  The upper layer will soon
1121            start the interface anyway, and there are no significant
1122            delay.  */
1123         if_devstart(&sc->sc_if);
1124 #endif
1125 }
1126
1127 /*
1128  * This routine actually starts the transmission on the interface
1129  */
1130 static void
1131 fe_xmit (struct fe_softc *sc)
1132 {
1133         /*
1134          * Set a timer just in case we never hear from the board again.
1135          * We use longer timeout for multiple packet transmission.
1136          * I'm not sure this timer value is appropriate.  FIXME.
1137          */
1138         sc->sc_if.if_timer = 1 + sc->txb_count;
1139
1140         /* Update txb variables.  */
1141         sc->txb_sched = sc->txb_count;
1142         sc->txb_count = 0;
1143         sc->txb_free = sc->txb_size;
1144         sc->tx_excolls = 0;
1145
1146         /* Start transmitter, passing packets in TX buffer.  */
1147         fe_outb(sc, FE_BMPR10, sc->txb_sched | FE_B10_START);
1148 }
1149
1150 /*
1151  * Start output on interface.
1152  * We make two assumptions here:
1153  *  1) that the current priority is set to splimp _before_ this code
1154  *     is called *and* is returned to the appropriate priority after
1155  *     return
1156  *  2) that the OACTIVE flag is checked before this code is called
1157  *     (i.e. that the output part of the interface is idle)
1158  */
1159 void
1160 fe_start (struct ifnet *ifp, struct ifaltq_subque *ifsq)
1161 {
1162         struct fe_softc *sc = ifp->if_softc;
1163         struct mbuf *m;
1164
1165         ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
1166
1167 #ifdef DIAGNOSTIC
1168         /* Just a sanity check.  */
1169         if ((sc->txb_count == 0) != (sc->txb_free == sc->txb_size)) {
1170                 /*
1171                  * Txb_count and txb_free co-works to manage the
1172                  * transmission buffer.  Txb_count keeps track of the
1173                  * used potion of the buffer, while txb_free does unused
1174                  * potion.  So, as long as the driver runs properly,
1175                  * txb_count is zero if and only if txb_free is same
1176                  * as txb_size (which represents whole buffer.)
1177                  */
1178                 kprintf("fe%d: inconsistent txb variables (%d, %d)\n",
1179                         sc->sc_unit, sc->txb_count, sc->txb_free);
1180                 /*
1181                  * So, what should I do, then?
1182                  *
1183                  * We now know txb_count and txb_free contradicts.  We
1184                  * cannot, however, tell which is wrong.  More
1185                  * over, we cannot peek 86960 transmission buffer or
1186                  * reset the transmission buffer.  (In fact, we can
1187                  * reset the entire interface.  I don't want to do it.)
1188                  *
1189                  * If txb_count is incorrect, leaving it as-is will cause
1190                  * sending of garbage after next interrupt.  We have to
1191                  * avoid it.  Hence, we reset the txb_count here.  If
1192                  * txb_free was incorrect, resetting txb_count just loose
1193                  * some packets.  We can live with it.
1194                  */
1195                 sc->txb_count = 0;
1196         }
1197 #endif
1198
1199         /*
1200          * First, see if there are buffered packets and an idle
1201          * transmitter - should never happen at this point.
1202          */
1203         if ((sc->txb_count > 0) && (sc->txb_sched == 0)) {
1204                 kprintf("fe%d: transmitter idle with %d buffered packets\n",
1205                        sc->sc_unit, sc->txb_count);
1206                 fe_xmit(sc);
1207         }
1208
1209         /*
1210          * Stop accepting more transmission packets temporarily, when
1211          * a filter change request is delayed.  Updating the MARs on
1212          * 86960 flushes the transmission buffer, so it is delayed
1213          * until all buffered transmission packets have been sent
1214          * out.
1215          */
1216         if (sc->filter_change) {
1217                 /*
1218                  * Filter change request is delayed only when the DLC is
1219                  * working.  DLC soon raise an interrupt after finishing
1220                  * the work.
1221                  */
1222                 goto indicate_active;
1223         }
1224
1225         for (;;) {
1226
1227                 /*
1228                  * See if there is room to put another packet in the buffer.
1229                  * We *could* do better job by peeking the send queue to
1230                  * know the length of the next packet.  Current version just
1231                  * tests against the worst case (i.e., longest packet).  FIXME.
1232                  *
1233                  * When adding the packet-peek feature, don't forget adding a
1234                  * test on txb_count against QUEUEING_MAX.
1235                  * There is a little chance the packet count exceeds
1236                  * the limit.  Assume transmission buffer is 8KB (2x8KB
1237                  * configuration) and an application sends a bunch of small
1238                  * (i.e., minimum packet sized) packets rapidly.  An 8KB
1239                  * buffer can hold 130 blocks of 62 bytes long...
1240                  */
1241                 if (sc->txb_free
1242                     < ETHER_MAX_LEN - ETHER_CRC_LEN + FE_DATA_LEN_LEN) {
1243                         /* No room.  */
1244                         goto indicate_active;
1245                 }
1246
1247 #if FE_SINGLE_TRANSMISSION
1248                 if (sc->txb_count > 0) {
1249                         /* Just one packet per a transmission buffer.  */
1250                         goto indicate_active;
1251                 }
1252 #endif
1253
1254                 /*
1255                  * Get the next mbuf chain for a packet to send.
1256                  */
1257                 m = ifq_dequeue(&sc->sc_if.if_snd);
1258                 if (m == NULL) {
1259                         /* No more packets to send.  */
1260                         goto indicate_inactive;
1261                 }
1262
1263                 /*
1264                  * Copy the mbuf chain into the transmission buffer.
1265                  * txb_* variables are updated as necessary.
1266                  */
1267                 fe_write_mbufs(sc, m);
1268
1269                 /* Start transmitter if it's idle.  */
1270                 if ((sc->txb_count > 0) && (sc->txb_sched == 0))
1271                         fe_xmit(sc);
1272
1273                 /*
1274                  * Tap off here if there is a bpf listener,
1275                  * and the device is *not* in promiscuous mode.
1276                  * (86960 receives self-generated packets if 
1277                  * and only if it is in "receive everything"
1278                  * mode.)
1279                  */
1280                 if ((sc->sc_if.if_flags & IFF_PROMISC) == 0)
1281                         BPF_MTAP(&sc->sc_if, m);
1282
1283                 m_freem(m);
1284         }
1285
1286   indicate_inactive:
1287         /*
1288          * We are using the !OACTIVE flag to indicate to
1289          * the outside world that we can accept an
1290          * additional packet rather than that the
1291          * transmitter is _actually_ active.  Indeed, the
1292          * transmitter may be active, but if we haven't
1293          * filled all the buffers with data then we still
1294          * want to accept more.
1295          */
1296         ifq_clr_oactive(&sc->sc_if.if_snd);
1297         return;
1298
1299   indicate_active:
1300         /*
1301          * The transmitter is active, and there are no room for
1302          * more outgoing packets in the transmission buffer.
1303          */
1304         ifq_set_oactive(&sc->sc_if.if_snd);
1305         return;
1306 }
1307
1308 /*
1309  * Drop (skip) a packet from receive buffer in 86960 memory.
1310  */
1311 static void
1312 fe_droppacket (struct fe_softc * sc, int len)
1313 {
1314         int i;
1315
1316         /*
1317          * 86960 manual says that we have to read 8 bytes from the buffer
1318          * before skip the packets and that there must be more than 8 bytes
1319          * remaining in the buffer when issue a skip command.
1320          * Remember, we have already read 4 bytes before come here.
1321          */
1322         if (len > 12) {
1323                 /* Read 4 more bytes, and skip the rest of the packet.  */
1324 #ifdef FE_8BIT_SUPPORT
1325                 if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1326                 {
1327                         fe_inb(sc, FE_BMPR8);
1328                         fe_inb(sc, FE_BMPR8);
1329                         fe_inb(sc, FE_BMPR8);
1330                         fe_inb(sc, FE_BMPR8);
1331                 }
1332                 else
1333 #endif
1334                 {
1335                         fe_inw(sc, FE_BMPR8);
1336                         fe_inw(sc, FE_BMPR8);
1337                 }
1338                 fe_outb(sc, FE_BMPR14, FE_B14_SKIP);
1339         } else {
1340                 /* We should not come here unless receiving RUNTs.  */
1341 #ifdef FE_8BIT_SUPPORT
1342                 if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1343                 {
1344                         for (i = 0; i < len; i++)
1345                                 fe_inb(sc, FE_BMPR8);
1346                 }
1347                 else
1348 #endif
1349                 {
1350                         for (i = 0; i < len; i += 2)
1351                                 fe_inw(sc, FE_BMPR8);
1352                 }
1353         }
1354 }
1355
1356 #ifdef DIAGNOSTIC
1357 /*
1358  * Empty receiving buffer.
1359  */
1360 static void
1361 fe_emptybuffer (struct fe_softc * sc)
1362 {
1363         int i;
1364         u_char saved_dlcr5;
1365
1366 #ifdef FE_DEBUG
1367         kprintf("fe%d: emptying receive buffer\n", sc->sc_unit);
1368 #endif
1369
1370         /*
1371          * Stop receiving packets, temporarily.
1372          */
1373         saved_dlcr5 = fe_inb(sc, FE_DLCR5);
1374         fe_outb(sc, FE_DLCR5, sc->proto_dlcr5);
1375         DELAY(1300);
1376
1377         /*
1378          * When we come here, the receive buffer management may
1379          * have been broken.  So, we cannot use skip operation.
1380          * Just discard everything in the buffer.
1381          */
1382 #ifdef FE_8BIT_SUPPORT
1383         if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1384         {
1385                 for (i = 0; i < 65536; i++) {
1386                         if (fe_inb(sc, FE_DLCR5) & FE_D5_BUFEMP)
1387                                 break;
1388                         fe_inb(sc, FE_BMPR8);
1389                 }
1390         }
1391         else
1392 #endif
1393         {
1394                 for (i = 0; i < 65536; i += 2) {
1395                         if (fe_inb(sc, FE_DLCR5) & FE_D5_BUFEMP)
1396                                 break;
1397                         fe_inw(sc, FE_BMPR8);
1398                 }
1399         }
1400
1401         /*
1402          * Double check.
1403          */
1404         if (fe_inb(sc, FE_DLCR5) & FE_D5_BUFEMP) {
1405                 kprintf("fe%d: could not empty receive buffer\n", sc->sc_unit);
1406                 /* Hmm.  What should I do if this happens?  FIXME.  */
1407         }
1408
1409         /*
1410          * Restart receiving packets.
1411          */
1412         fe_outb(sc, FE_DLCR5, saved_dlcr5);
1413 }
1414 #endif
1415
1416 /*
1417  * Transmission interrupt handler
1418  * The control flow of this function looks silly.  FIXME.
1419  */
1420 static void
1421 fe_tint (struct fe_softc * sc, u_char tstat)
1422 {
1423         int left;
1424         int col;
1425
1426         /*
1427          * Handle "excessive collision" interrupt.
1428          */
1429         if (tstat & FE_D0_COLL16) {
1430
1431                 /*
1432                  * Find how many packets (including this collided one)
1433                  * are left unsent in transmission buffer.
1434                  */
1435                 left = fe_inb(sc, FE_BMPR10);
1436                 kprintf("fe%d: excessive collision (%d/%d)\n",
1437                        sc->sc_unit, left, sc->txb_sched);
1438
1439                 /*
1440                  * Clear the collision flag (in 86960) here
1441                  * to avoid confusing statistics.
1442                  */
1443                 fe_outb(sc, FE_DLCR0, FE_D0_COLLID);
1444
1445                 /*
1446                  * Restart transmitter, skipping the
1447                  * collided packet.
1448                  *
1449                  * We *must* skip the packet to keep network running
1450                  * properly.  Excessive collision error is an
1451                  * indication of the network overload.  If we
1452                  * tried sending the same packet after excessive
1453                  * collision, the network would be filled with
1454                  * out-of-time packets.  Packets belonging
1455                  * to reliable transport (such as TCP) are resent
1456                  * by some upper layer.
1457                  */
1458                 fe_outb(sc, FE_BMPR11, FE_B11_CTRL_SKIP | FE_B11_MODE1);
1459
1460                 /* Update statistics.  */
1461                 sc->tx_excolls++;
1462         }
1463
1464         /*
1465          * Handle "transmission complete" interrupt.
1466          */
1467         if (tstat & FE_D0_TXDONE) {
1468
1469                 /*
1470                  * Add in total number of collisions on last
1471                  * transmission.  We also clear "collision occurred" flag
1472                  * here.
1473                  *
1474                  * 86960 has a design flaw on collision count on multiple
1475                  * packet transmission.  When we send two or more packets
1476                  * with one start command (that's what we do when the
1477                  * transmission queue is crowded), 86960 informs us number
1478                  * of collisions occurred on the last packet on the
1479                  * transmission only.  Number of collisions on previous
1480                  * packets are lost.  I have told that the fact is clearly
1481                  * stated in the Fujitsu document.
1482                  *
1483                  * I considered not to mind it seriously.  Collision
1484                  * count is not so important, anyway.  Any comments?  FIXME.
1485                  */
1486
1487                 if (fe_inb(sc, FE_DLCR0) & FE_D0_COLLID) {
1488
1489                         /* Clear collision flag.  */
1490                         fe_outb(sc, FE_DLCR0, FE_D0_COLLID);
1491
1492                         /* Extract collision count from 86960.  */
1493                         col = fe_inb(sc, FE_DLCR4);
1494                         col = (col & FE_D4_COL) >> FE_D4_COL_SHIFT;
1495                         if (col == 0) {
1496                                 /*
1497                                  * Status register indicates collisions,
1498                                  * while the collision count is zero.
1499                                  * This can happen after multiple packet
1500                                  * transmission, indicating that one or more
1501                                  * previous packet(s) had been collided.
1502                                  *
1503                                  * Since the accurate number of collisions
1504                                  * has been lost, we just guess it as 1;
1505                                  * Am I too optimistic?  FIXME.
1506                                  */
1507                                 col = 1;
1508                         }
1509                         sc->sc_if.if_collisions += col;
1510                         if (col == 1)
1511                                 sc->mibdata.dot3StatsSingleCollisionFrames++;
1512                         else
1513                                 sc->mibdata.dot3StatsMultipleCollisionFrames++;
1514                         sc->mibdata.dot3StatsCollFrequencies[col-1]++;
1515                 }
1516
1517                 /*
1518                  * Update transmission statistics.
1519                  * Be sure to reflect number of excessive collisions.
1520                  */
1521                 col = sc->tx_excolls;
1522                 IFNET_STAT_INC(&sc->sc_if, opackets, sc->txb_sched - col);
1523                 IFNET_STAT_INC(&sc->sc_if, oerrors, col);
1524                 IFNET_STAT_INC(&sc->sc_if, collisions, col * 16);
1525                 sc->mibdata.dot3StatsExcessiveCollisions += col;
1526                 sc->mibdata.dot3StatsCollFrequencies[15] += col;
1527                 sc->txb_sched = 0;
1528
1529                 /*
1530                  * The transmitter is no more active.
1531                  * Reset output active flag and watchdog timer.
1532                  */
1533                 ifq_clr_oactive(&sc->sc_if.if_snd);
1534                 sc->sc_if.if_timer = 0;
1535
1536                 /*
1537                  * If more data is ready to transmit in the buffer, start
1538                  * transmitting them.  Otherwise keep transmitter idle,
1539                  * even if more data is queued.  This gives receive
1540                  * process a slight priority.
1541                  */
1542                 if (sc->txb_count > 0)
1543                         fe_xmit(sc);
1544         }
1545 }
1546
1547 /*
1548  * Ethernet interface receiver interrupt.
1549  */
1550 static void
1551 fe_rint (struct fe_softc * sc, u_char rstat)
1552 {
1553         u_short len;
1554         u_char status;
1555         int i;
1556
1557         /*
1558          * Update statistics if this interrupt is caused by an error.
1559          * Note that, when the system was not sufficiently fast, the
1560          * receive interrupt might not be acknowledged immediately.  If
1561          * one or more errornous frames were received before this routine
1562          * was scheduled, they are ignored, and the following error stats
1563          * give less than real values.
1564          */
1565         if (rstat & (FE_D1_OVRFLO | FE_D1_CRCERR | FE_D1_ALGERR | FE_D1_SRTPKT)) {
1566                 if (rstat & FE_D1_OVRFLO)
1567                         sc->mibdata.dot3StatsInternalMacReceiveErrors++;
1568                 if (rstat & FE_D1_CRCERR)
1569                         sc->mibdata.dot3StatsFCSErrors++;
1570                 if (rstat & FE_D1_ALGERR)
1571                         sc->mibdata.dot3StatsAlignmentErrors++;
1572 #if 0
1573                 /* The reference MAC receiver defined in 802.3
1574                    silently ignores short frames (RUNTs) without
1575                    notifying upper layer.  RFC 1650 (dot3 MIB) is
1576                    based on the 802.3, and it has no stats entry for
1577                    RUNTs...  */
1578                 if (rstat & FE_D1_SRTPKT)
1579                         sc->mibdata.dot3StatsFrameTooShorts++; /* :-) */
1580 #endif
1581                 IFNET_STAT_INC(&sc->sc_if, ierrors, 1);
1582         }
1583
1584         /*
1585          * MB86960 has a flag indicating "receive queue empty."
1586          * We just loop, checking the flag, to pull out all received
1587          * packets.
1588          *
1589          * We limit the number of iterations to avoid infinite-loop.
1590          * The upper bound is set to unrealistic high value.
1591          */
1592         for (i = 0; i < FE_MAX_RECV_COUNT * 2; i++) {
1593
1594                 /* Stop the iteration if 86960 indicates no packets.  */
1595                 if (fe_inb(sc, FE_DLCR5) & FE_D5_BUFEMP)
1596                         return;
1597
1598                 /*
1599                  * Extract a receive status byte.
1600                  * As our 86960 is in 16 bit bus access mode, we have to
1601                  * use inw() to get the status byte.  The significant
1602                  * value is returned in lower 8 bits.
1603                  */
1604 #ifdef FE_8BIT_SUPPORT
1605                 if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1606                 {
1607                         status = fe_inb(sc, FE_BMPR8);
1608                         fe_inb(sc, FE_BMPR8);
1609                 }
1610                 else
1611 #endif
1612                 {
1613                         status = (u_char) fe_inw(sc, FE_BMPR8);
1614                 }       
1615
1616                 /*
1617                  * Extract the packet length.
1618                  * It is a sum of a header (14 bytes) and a payload.
1619                  * CRC has been stripped off by the 86960.
1620                  */
1621 #ifdef FE_8BIT_SUPPORT
1622                 if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1623                 {
1624                         len  =  fe_inb(sc, FE_BMPR8);
1625                         len |= (fe_inb(sc, FE_BMPR8) << 8);
1626                 }
1627                 else
1628 #endif
1629                 {
1630                         len = fe_inw(sc, FE_BMPR8);
1631                 }
1632
1633                 /*
1634                  * AS our 86960 is programed to ignore errored frame,
1635                  * we must not see any error indication in the
1636                  * receive buffer.  So, any error condition is a
1637                  * serious error, e.g., out-of-sync of the receive
1638                  * buffer pointers.
1639                  */
1640                 if ((status & 0xF0) != 0x20 ||
1641                     len > ETHER_MAX_LEN - ETHER_CRC_LEN ||
1642                     len < ETHER_MIN_LEN - ETHER_CRC_LEN) {
1643                         kprintf("fe%d: RX buffer out-of-sync\n", sc->sc_unit);
1644                         IFNET_STAT_INC(&sc->sc_if, ierrors, 1);
1645                         sc->mibdata.dot3StatsInternalMacReceiveErrors++;
1646                         fe_reset(sc);
1647                         return;
1648                 }
1649
1650                 /*
1651                  * Go get a packet.
1652                  */
1653                 if (fe_get_packet(sc, len) < 0) {
1654                         /*
1655                          * Negative return from fe_get_packet()
1656                          * indicates no available mbuf.  We stop
1657                          * receiving packets, even if there are more
1658                          * in the buffer.  We hope we can get more
1659                          * mbuf next time.
1660                          */
1661                         IFNET_STAT_INC(&sc->sc_if, ierrors, 1);
1662                         sc->mibdata.dot3StatsMissedFrames++;
1663                         fe_droppacket(sc, len);
1664                         return;
1665                 }
1666
1667                 /* Successfully received a packet.  Update stat.  */
1668                 IFNET_STAT_INC(&sc->sc_if, ipackets, 1);
1669         }
1670
1671         /* Maximum number of frames has been received.  Something
1672            strange is happening here... */
1673         kprintf("fe%d: unusual receive flood\n", sc->sc_unit);
1674         sc->mibdata.dot3StatsInternalMacReceiveErrors++;
1675         fe_reset(sc);
1676 }
1677
1678 /*
1679  * Ethernet interface interrupt processor
1680  */
1681 static void
1682 fe_intr (void *arg)
1683 {
1684         struct fe_softc *sc = arg;
1685         u_char tstat, rstat;
1686         int loop_count = FE_MAX_LOOP;
1687
1688         /* Loop until there are no more new interrupt conditions.  */
1689         while (loop_count-- > 0) {
1690                 /*
1691                  * Get interrupt conditions, masking unneeded flags.
1692                  */
1693                 tstat = fe_inb(sc, FE_DLCR0) & FE_TMASK;
1694                 rstat = fe_inb(sc, FE_DLCR1) & FE_RMASK;
1695                 if (tstat == 0 && rstat == 0)
1696                         return;
1697
1698                 /*
1699                  * Reset the conditions we are acknowledging.
1700                  */
1701                 fe_outb(sc, FE_DLCR0, tstat);
1702                 fe_outb(sc, FE_DLCR1, rstat);
1703
1704                 /*
1705                  * Handle transmitter interrupts.
1706                  */
1707                 if (tstat)
1708                         fe_tint(sc, tstat);
1709
1710                 /*
1711                  * Handle receiver interrupts
1712                  */
1713                 if (rstat)
1714                         fe_rint(sc, rstat);
1715
1716                 /*
1717                  * Update the multicast address filter if it is
1718                  * needed and possible.  We do it now, because
1719                  * we can make sure the transmission buffer is empty,
1720                  * and there is a good chance that the receive queue
1721                  * is empty.  It will minimize the possibility of
1722                  * packet loss.
1723                  */
1724                 if (sc->filter_change &&
1725                     sc->txb_count == 0 && sc->txb_sched == 0) {
1726                         fe_loadmar(sc);
1727                         ifq_clr_oactive(&sc->sc_if.if_snd);
1728                 }
1729
1730                 /*
1731                  * If it looks like the transmitter can take more data,
1732                  * attempt to start output on the interface. This is done
1733                  * after handling the receiver interrupt to give the
1734                  * receive operation priority.
1735                  *
1736                  * BTW, I'm not sure in what case the OACTIVE is on at
1737                  * this point.  Is the following test redundant?
1738                  *
1739                  * No.  This routine polls for both transmitter and
1740                  * receiver interrupts.  86960 can raise a receiver
1741                  * interrupt when the transmission buffer is full.
1742                  */
1743                 if (!ifq_is_oactive(&sc->sc_if.if_snd))
1744                         if_devstart(&sc->sc_if);
1745         }
1746
1747         kprintf("fe%d: too many loops\n", sc->sc_unit);
1748 }
1749
1750 /*
1751  * Process an ioctl request. This code needs some work - it looks
1752  * pretty ugly.
1753  */
1754 static int
1755 fe_ioctl (struct ifnet * ifp, u_long command, caddr_t data, struct ucred *cr)
1756 {
1757         struct fe_softc *sc = ifp->if_softc;
1758         struct ifreq *ifr = (struct ifreq *)data;
1759         int error = 0;
1760
1761         switch (command) {
1762           case SIOCSIFFLAGS:
1763                 /*
1764                  * Switch interface state between "running" and
1765                  * "stopped", reflecting the UP flag.
1766                  */
1767                 if (sc->sc_if.if_flags & IFF_UP) {
1768                         if ((sc->sc_if.if_flags & IFF_RUNNING) == 0)
1769                                 fe_init(sc);
1770                 } else {
1771                         if ((sc->sc_if.if_flags & IFF_RUNNING) != 0)
1772                                 fe_stop(sc);
1773                 }
1774
1775                 /*
1776                  * Promiscuous and/or multicast flags may have changed,
1777                  * so reprogram the multicast filter and/or receive mode.
1778                  */
1779                 fe_setmode(sc);
1780
1781                 /* Done.  */
1782                 break;
1783
1784           case SIOCADDMULTI:
1785           case SIOCDELMULTI:
1786                 /*
1787                  * Multicast list has changed; set the hardware filter
1788                  * accordingly.
1789                  */
1790                 fe_setmode(sc);
1791                 break;
1792
1793           case SIOCSIFMEDIA:
1794           case SIOCGIFMEDIA:
1795                 /* Let if_media to handle these commands and to call
1796                    us back.  */
1797                 error = ifmedia_ioctl(ifp, ifr, &sc->media, command);
1798                 break;
1799
1800           default:
1801                 error = ether_ioctl(ifp, command, data);
1802                 break;
1803         }
1804         return (error);
1805 }
1806
1807 /*
1808  * Retrieve packet from receive buffer and send to the next level up via
1809  * ether_input().
1810  * Returns 0 if success, -1 if error (i.e., mbuf allocation failure).
1811  */
1812 static int
1813 fe_get_packet (struct fe_softc * sc, u_short len)
1814 {
1815         struct ether_header *eh;
1816         struct mbuf *m;
1817
1818         /*
1819          * NFS wants the data be aligned to the word (4 byte)
1820          * boundary.  Ethernet header has 14 bytes.  There is a
1821          * 2-byte gap.
1822          */
1823 #define NFS_MAGIC_OFFSET 2
1824
1825         /*
1826          * This function assumes that an Ethernet packet fits in an
1827          * mbuf (with a cluster attached when necessary.)  On FreeBSD
1828          * 2.0 for x86, which is the primary target of this driver, an
1829          * mbuf cluster has 4096 bytes, and we are happy.  On ancient
1830          * BSDs, such as vanilla 4.3 for 386, a cluster size was 1024,
1831          * however.  If the following #error message were printed upon
1832          * compile, you need to rewrite this function.
1833          */
1834 #if ( MCLBYTES < ETHER_MAX_LEN - ETHER_CRC_LEN + NFS_MAGIC_OFFSET )
1835 #error "Too small MCLBYTES to use fe driver."
1836 #endif
1837
1838         /*
1839          * Our strategy has one more problem.  There is a policy on
1840          * mbuf cluster allocation.  It says that we must have at
1841          * least MINCLSIZE (208 bytes on FreeBSD 2.0 for x86) to
1842          * allocate a cluster.  For a packet of a size between
1843          * (MHLEN - 2) to (MINCLSIZE - 2), our code violates the rule...
1844          * On the other hand, the current code is short, simple,
1845          * and fast, however.  It does no harmful thing, just waists
1846          * some memory.  Any comments?  FIXME.
1847          */
1848
1849         /* Allocate an mbuf with packet header info.  */
1850         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1851         if (m == NULL)
1852                 return -1;
1853
1854         /* Attach a cluster if this packet doesn't fit in a normal mbuf.  */
1855         if (len > MHLEN - NFS_MAGIC_OFFSET) {
1856                 MCLGET(m, MB_DONTWAIT);
1857                 if (!(m->m_flags & M_EXT)) {
1858                         m_freem(m);
1859                         return -1;
1860                 }
1861         }
1862
1863         /* Initialize packet header info.  */
1864         m->m_pkthdr.rcvif = &sc->sc_if;
1865         m->m_pkthdr.len = len;
1866
1867         /* Set the length of this packet.  */
1868         m->m_len = len;
1869
1870         /* The following silliness is to make NFS happy */
1871         m->m_data += NFS_MAGIC_OFFSET;
1872
1873         /* Get (actually just point to) the header part.  */
1874         eh = mtod(m, struct ether_header *);
1875
1876         /* Get a packet.  */
1877 #ifdef FE_8BIT_SUPPORT
1878         if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1879         {
1880                 fe_insb(sc, FE_BMPR8, (u_int8_t *)eh, len);
1881         }
1882         else
1883 #endif
1884         {
1885                 fe_insw(sc, FE_BMPR8, (u_int16_t *)eh, (len + 1) >> 1);
1886         }
1887
1888         /* Feed the packet to upper layer.  */
1889         sc->sc_if.if_input(&sc->sc_if, m, NULL, -1);
1890         return 0;
1891 }
1892
1893 /*
1894  * Write an mbuf chain to the transmission buffer memory using 16 bit PIO.
1895  * Returns number of bytes actually written, including length word.
1896  *
1897  * If an mbuf chain is too long for an Ethernet frame, it is not sent.
1898  * Packets shorter than Ethernet minimum are legal, and we pad them
1899  * before sending out.  An exception is "partial" packets which are
1900  * shorter than mandatory Ethernet header.
1901  */
1902 static void
1903 fe_write_mbufs (struct fe_softc *sc, struct mbuf *m)
1904 {
1905         u_short length, len;
1906         struct mbuf *mp;
1907         u_char *data;
1908         u_short savebyte;       /* WARNING: Architecture dependent!  */
1909 #define NO_PENDING_BYTE 0xFFFF
1910
1911         static u_char padding [ETHER_MIN_LEN - ETHER_CRC_LEN - ETHER_HDR_LEN];
1912
1913 #ifdef DIAGNOSTIC
1914         /* First, count up the total number of bytes to copy */
1915         length = 0;
1916         for (mp = m; mp != NULL; mp = mp->m_next)
1917                 length += mp->m_len;
1918
1919         /* Check if this matches the one in the packet header.  */
1920         if (length != m->m_pkthdr.len) {
1921                 kprintf("fe%d: packet length mismatch? (%d/%d)\n", sc->sc_unit,
1922                        length, m->m_pkthdr.len);
1923         }
1924 #else
1925         /* Just use the length value in the packet header.  */
1926         length = m->m_pkthdr.len;
1927 #endif
1928
1929 #ifdef DIAGNOSTIC
1930         /*
1931          * Should never send big packets.  If such a packet is passed,
1932          * it should be a bug of upper layer.  We just ignore it.
1933          * ... Partial (too short) packets, neither.
1934          */
1935         if (length < ETHER_HDR_LEN ||
1936             length > ETHER_MAX_LEN - ETHER_CRC_LEN) {
1937                 kprintf("fe%d: got an out-of-spec packet (%u bytes) to send\n",
1938                         sc->sc_unit, length);
1939                 IFNET_STAT_INC(&sc->sc_if, oerrors, 1);
1940                 sc->mibdata.dot3StatsInternalMacTransmitErrors++;
1941                 return;
1942         }
1943 #endif
1944
1945         /*
1946          * Put the length word for this frame.
1947          * Does 86960 accept odd length?  -- Yes.
1948          * Do we need to pad the length to minimum size by ourselves?
1949          * -- Generally yes.  But for (or will be) the last
1950          * packet in the transmission buffer, we can skip the
1951          * padding process.  It may gain performance slightly.  FIXME.
1952          */
1953 #ifdef FE_8BIT_SUPPORT
1954         if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1955         {
1956                 len = max(length, ETHER_MIN_LEN - ETHER_CRC_LEN);
1957                 fe_outb(sc, FE_BMPR8,  len & 0x00ff);
1958                 fe_outb(sc, FE_BMPR8, (len & 0xff00) >> 8);
1959         }
1960         else
1961 #endif
1962         {
1963                 fe_outw(sc, FE_BMPR8,
1964                         max(length, ETHER_MIN_LEN - ETHER_CRC_LEN));
1965         }
1966
1967         /*
1968          * Update buffer status now.
1969          * Truncate the length up to an even number, since we use outw().
1970          */
1971 #ifdef FE_8BIT_SUPPORT
1972         if ((sc->proto_dlcr6 & FE_D6_SBW) != FE_D6_SBW_BYTE)
1973 #endif
1974         {
1975                 length = (length + 1) & ~1;
1976         }
1977         sc->txb_free -= FE_DATA_LEN_LEN +
1978             max(length, ETHER_MIN_LEN - ETHER_CRC_LEN);
1979         sc->txb_count++;
1980
1981         /*
1982          * Transfer the data from mbuf chain to the transmission buffer.
1983          * MB86960 seems to require that data be transferred as words, and
1984          * only words.  So that we require some extra code to patch
1985          * over odd-length mbufs.
1986          */
1987 #ifdef FE_8BIT_SUPPORT
1988         if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
1989         {
1990                 /* 8-bit cards are easy.  */
1991                 for (mp = m; mp != NULL; mp = mp->m_next) {
1992                         if (mp->m_len)
1993                                 fe_outsb(sc, FE_BMPR8, mtod(mp, caddr_t),
1994                                          mp->m_len);
1995                 }
1996         }
1997         else
1998 #endif
1999         {
2000                 /* 16-bit cards are a pain.  */
2001                 savebyte = NO_PENDING_BYTE;
2002                 for (mp = m; mp != NULL; mp = mp->m_next) {
2003
2004                         /* Ignore empty mbuf.  */
2005                         len = mp->m_len;
2006                         if (len == 0)
2007                                 continue;
2008
2009                         /* Find the actual data to send.  */
2010                         data = mtod(mp, caddr_t);
2011
2012                         /* Finish the last byte.  */
2013                         if (savebyte != NO_PENDING_BYTE) {
2014                                 fe_outw(sc, FE_BMPR8, savebyte | (*data << 8));
2015                                 data++;
2016                                 len--;
2017                                 savebyte = NO_PENDING_BYTE;
2018                         }
2019
2020                         /* output contiguous words */
2021                         if (len > 1) {
2022                                 fe_outsw(sc, FE_BMPR8, (u_int16_t *)data,
2023                                          len >> 1);
2024                                 data += len & ~1;
2025                                 len &= 1;
2026                         }
2027
2028                         /* Save a remaining byte, if there is one.  */
2029                         if (len > 0)
2030                                 savebyte = *data;
2031                 }
2032
2033                 /* Spit the last byte, if the length is odd.  */
2034                 if (savebyte != NO_PENDING_BYTE)
2035                         fe_outw(sc, FE_BMPR8, savebyte);
2036         }
2037
2038         /* Pad to the Ethernet minimum length, if the packet is too short.  */
2039         if (length < ETHER_MIN_LEN - ETHER_CRC_LEN) {
2040 #ifdef FE_8BIT_SUPPORT
2041                 if ((sc->proto_dlcr6 & FE_D6_SBW) == FE_D6_SBW_BYTE)
2042                 {
2043                         fe_outsb(sc, FE_BMPR8, padding,
2044                                  ETHER_MIN_LEN - ETHER_CRC_LEN - length);
2045                 }
2046                 else
2047 #endif
2048                 {
2049                         fe_outsw(sc, FE_BMPR8, (u_int16_t *)padding,
2050                                  (ETHER_MIN_LEN - ETHER_CRC_LEN - length) >> 1);
2051                 }
2052         }
2053 }
2054
2055 /*
2056  * Compute hash value for an Ethernet address
2057  */
2058 static int
2059 fe_hash ( u_char * ep )
2060 {
2061 #define FE_HASH_MAGIC_NUMBER 0xEDB88320L
2062
2063         u_long hash = 0xFFFFFFFFL;
2064         int i, j;
2065         u_char b;
2066         u_long m;
2067
2068         for ( i = ETHER_ADDR_LEN; --i >= 0; ) {
2069                 b = *ep++;
2070                 for ( j = 8; --j >= 0; ) {
2071                         m = hash;
2072                         hash >>= 1;
2073                         if ( ( m ^ b ) & 1 ) hash ^= FE_HASH_MAGIC_NUMBER;
2074                         b >>= 1;
2075                 }
2076         }
2077         return ( ( int )( hash >> 26 ) );
2078 }
2079
2080 /*
2081  * Compute the multicast address filter from the
2082  * list of multicast addresses we need to listen to.
2083  */
2084 static struct fe_filter
2085 fe_mcaf ( struct fe_softc *sc )
2086 {
2087         int index;
2088         struct fe_filter filter;
2089         struct ifmultiaddr *ifma;
2090 #ifdef FE_DEBUG
2091         char ethstr[ETHER_ADDRSTRLEN + 1];
2092 #endif
2093         filter = fe_filter_nothing;
2094         TAILQ_FOREACH(ifma, &sc->arpcom.ac_if.if_multiaddrs, ifma_link) {
2095                 if (ifma->ifma_addr->sa_family != AF_LINK)
2096                         continue;
2097                 index = fe_hash(LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
2098 #ifdef FE_DEBUG
2099                 kprintf("fe%d: hash(%s) == %d\n",
2100                     sc->sc_unit, kether_ntoa(enm->enm_addrlo, ethstr), index);
2101 #endif
2102
2103                 filter.data[index >> 3] |= 1 << (index & 7);
2104         }
2105         return ( filter );
2106 }
2107
2108 /*
2109  * Calculate a new "multicast packet filter" and put the 86960
2110  * receiver in appropriate mode.
2111  */
2112 static void
2113 fe_setmode (struct fe_softc *sc)
2114 {
2115         int flags = sc->sc_if.if_flags;
2116
2117         /*
2118          * If the interface is not running, we postpone the update
2119          * process for receive modes and multicast address filter
2120          * until the interface is restarted.  It reduces some
2121          * complicated job on maintaining chip states.  (Earlier versions
2122          * of this driver had a bug on that point...)
2123          *
2124          * To complete the trick, fe_init() calls fe_setmode() after
2125          * restarting the interface.
2126          */
2127         if (!(flags & IFF_RUNNING))
2128                 return;
2129
2130         /*
2131          * Promiscuous mode is handled separately.
2132          */
2133         if (flags & IFF_PROMISC) {
2134                 /*
2135                  * Program 86960 to receive all packets on the segment
2136                  * including those directed to other stations.
2137                  * Multicast filter stored in MARs are ignored
2138                  * under this setting, so we don't need to update it.
2139                  *
2140                  * Promiscuous mode in FreeBSD 2 is used solely by
2141                  * BPF, and BPF only listens to valid (no error) packets.
2142                  * So, we ignore erroneous ones even in this mode.
2143                  * (Older versions of fe driver mistook the point.)
2144                  */
2145                 fe_outb(sc, FE_DLCR5,
2146                         sc->proto_dlcr5 | FE_D5_AFM0 | FE_D5_AFM1);
2147                 sc->filter_change = 0;
2148                 return;
2149         }
2150
2151         /*
2152          * Turn the chip to the normal (non-promiscuous) mode.
2153          */
2154         fe_outb(sc, FE_DLCR5, sc->proto_dlcr5 | FE_D5_AFM1);
2155
2156         /*
2157          * Find the new multicast filter value.
2158          */
2159         if (flags & IFF_ALLMULTI)
2160                 sc->filter = fe_filter_all;
2161         else
2162                 sc->filter = fe_mcaf(sc);
2163         sc->filter_change = 1;
2164
2165         /*
2166          * We have to update the multicast filter in the 86960, A.S.A.P.
2167          *
2168          * Note that the DLC (Data Link Control unit, i.e. transmitter
2169          * and receiver) must be stopped when feeding the filter, and
2170          * DLC trashes all packets in both transmission and receive
2171          * buffers when stopped.
2172          *
2173          * To reduce the packet loss, we delay the filter update
2174          * process until buffers are empty.
2175          */
2176         if (sc->txb_sched == 0 && sc->txb_count == 0 &&
2177             !(fe_inb(sc, FE_DLCR1) & FE_D1_PKTRDY)) {
2178                 /*
2179                  * Buffers are (apparently) empty.  Load
2180                  * the new filter value into MARs now.
2181                  */
2182                 fe_loadmar(sc);
2183         } else {
2184                 /*
2185                  * Buffers are not empty.  Mark that we have to update
2186                  * the MARs.  The new filter will be loaded by feintr()
2187                  * later.
2188                  */
2189         }
2190 }
2191
2192 /*
2193  * Load a new multicast address filter into MARs.
2194  *
2195  * The caller must have splimp'ed before fe_loadmar.
2196  * This function starts the DLC upon return.  So it can be called only
2197  * when the chip is working, i.e., from the driver's point of view, when
2198  * a device is RUNNING.  (I mistook the point in previous versions.)
2199  */
2200 static void
2201 fe_loadmar (struct fe_softc * sc)
2202 {
2203         /* Stop the DLC (transmitter and receiver).  */
2204         DELAY(200);
2205         fe_outb(sc, FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
2206         DELAY(200);
2207
2208         /* Select register bank 1 for MARs.  */
2209         fe_outb(sc, FE_DLCR7, sc->proto_dlcr7 | FE_D7_RBS_MAR | FE_D7_POWER_UP);
2210
2211         /* Copy filter value into the registers.  */
2212         fe_outblk(sc, FE_MAR8, sc->filter.data, FE_FILTER_LEN);
2213
2214         /* Restore the bank selection for BMPRs (i.e., runtime registers).  */
2215         fe_outb(sc, FE_DLCR7,
2216                 sc->proto_dlcr7 | FE_D7_RBS_BMPR | FE_D7_POWER_UP);
2217
2218         /* Restart the DLC.  */
2219         DELAY(200);
2220         fe_outb(sc, FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_ENABLE);
2221         DELAY(200);
2222
2223         /* We have just updated the filter.  */
2224         sc->filter_change = 0;
2225 }
2226
2227 /* Change the media selection.  */
2228 static int
2229 fe_medchange (struct ifnet *ifp)
2230 {
2231         struct fe_softc *sc = (struct fe_softc *)ifp->if_softc;
2232
2233 #ifdef DIAGNOSTIC
2234         /* If_media should not pass any request for a media which this
2235            interface doesn't support.  */
2236         int b;
2237
2238         for (b = 0; bit2media[b] != 0; b++) {
2239                 if (bit2media[b] == sc->media.ifm_media) break;
2240         }
2241         if (((1 << b) & sc->mbitmap) == 0) {
2242                 kprintf("fe%d: got an unsupported media request (0x%x)\n",
2243                        sc->sc_unit, sc->media.ifm_media);
2244                 return EINVAL;
2245         }
2246 #endif
2247
2248         /* We don't actually change media when the interface is down.
2249            fe_init() will do the job, instead.  Should we also wait
2250            until the transmission buffer being empty?  Changing the
2251            media when we are sending a frame will cause two garbages
2252            on wires, one on old media and another on new.  FIXME */
2253         if (sc->sc_if.if_flags & IFF_UP) {
2254                 if (sc->msel) sc->msel(sc);
2255         }
2256
2257         return 0;
2258 }
2259
2260 /* I don't know how I can support media status callback... FIXME.  */
2261 static void
2262 fe_medstat (struct ifnet *ifp __unused, struct ifmediareq *ifmr __unused)
2263 {
2264 }