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