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