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