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