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