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