Merge from vendor branch ZLIB:
[dragonfly.git] / sys / dev / netif / fxp / if_fxp.c
1 /*-
2  * Copyright (c) 1995, David Greenman
3  * Copyright (c) 2001 Jonathan Lemon <jlemon@freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice unmodified, this list of conditions, and the following
11  *    disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/dev/fxp/if_fxp.c,v 1.110.2.30 2003/06/12 16:47:05 mux Exp $
29  * $DragonFly: src/sys/dev/netif/fxp/if_fxp.c,v 1.17 2004/09/17 09:51:12 dillon Exp $
30  */
31
32 /*
33  * Intel EtherExpress Pro/100B PCI Fast Ethernet driver
34  */
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/mbuf.h>
39 #include <sys/malloc.h>
40                 /* #include <sys/mutex.h> */
41 #include <sys/kernel.h>
42 #include <sys/socket.h>
43 #include <sys/sysctl.h>
44
45 #include <net/if.h>
46 #include <net/if_dl.h>
47 #include <net/if_media.h>
48
49 #ifdef NS
50 #include <netns/ns.h>
51 #include <netns/ns_if.h>
52 #endif
53
54 #include <net/bpf.h>
55 #include <sys/sockio.h>
56 #include <sys/bus.h>
57 #include <machine/bus.h>
58 #include <sys/rman.h>
59 #include <machine/resource.h>
60
61 #include <net/ethernet.h>
62 #include <net/if_arp.h>
63
64 #include <vm/vm.h>              /* for vtophys */
65 #include <vm/pmap.h>            /* for vtophys */
66 #include <machine/clock.h>      /* for DELAY */
67
68 #include <net/if_types.h>
69 #include <net/vlan/if_vlan_var.h>
70
71 #include <bus/pci/pcivar.h>
72 #include <bus/pci/pcireg.h>             /* for PCIM_CMD_xxx */
73
74 #include "../mii_layer/mii.h"
75 #include "../mii_layer/miivar.h"
76
77 #include "if_fxpreg.h"
78 #include "if_fxpvar.h"
79 #include "rcvbundl.h"
80
81 #include "miibus_if.h"
82
83 /*
84  * NOTE!  On the Alpha, we have an alignment constraint.  The
85  * card DMAs the packet immediately following the RFA.  However,
86  * the first thing in the packet is a 14-byte Ethernet header.
87  * This means that the packet is misaligned.  To compensate,
88  * we actually offset the RFA 2 bytes into the cluster.  This
89  * alignes the packet after the Ethernet header at a 32-bit
90  * boundary.  HOWEVER!  This means that the RFA is misaligned!
91  */
92 #define RFA_ALIGNMENT_FUDGE     2
93
94 /*
95  * Set initial transmit threshold at 64 (512 bytes). This is
96  * increased by 64 (512 bytes) at a time, to maximum of 192
97  * (1536 bytes), if an underrun occurs.
98  */
99 static int tx_threshold = 64;
100
101 /*
102  * The configuration byte map has several undefined fields which
103  * must be one or must be zero.  Set up a template for these bits
104  * only, (assuming a 82557 chip) leaving the actual configuration
105  * to fxp_init.
106  *
107  * See struct fxp_cb_config for the bit definitions.
108  */
109 static u_char fxp_cb_config_template[] = {
110         0x0, 0x0,               /* cb_status */
111         0x0, 0x0,               /* cb_command */
112         0x0, 0x0, 0x0, 0x0,     /* link_addr */
113         0x0,    /*  0 */
114         0x0,    /*  1 */
115         0x0,    /*  2 */
116         0x0,    /*  3 */
117         0x0,    /*  4 */
118         0x0,    /*  5 */
119         0x32,   /*  6 */
120         0x0,    /*  7 */
121         0x0,    /*  8 */
122         0x0,    /*  9 */
123         0x6,    /* 10 */
124         0x0,    /* 11 */
125         0x0,    /* 12 */
126         0x0,    /* 13 */
127         0xf2,   /* 14 */
128         0x48,   /* 15 */
129         0x0,    /* 16 */
130         0x40,   /* 17 */
131         0xf0,   /* 18 */
132         0x0,    /* 19 */
133         0x3f,   /* 20 */
134         0x5     /* 21 */
135 };
136
137 struct fxp_ident {
138         u_int16_t       devid;
139         int16_t         revid;          /* -1 matches anything */
140         char            *name;
141 };
142
143 /*
144  * Claim various Intel PCI device identifiers for this driver.  The
145  * sub-vendor and sub-device field are extensively used to identify
146  * particular variants, but we don't currently differentiate between
147  * them.
148  */
149 static struct fxp_ident fxp_ident_table[] = {
150      { 0x1029,  -1,     "Intel 82559 PCI/CardBus Pro/100" },
151      { 0x1030,  -1,     "Intel 82559 Pro/100 Ethernet" },
152      { 0x1031,  -1,     "Intel 82801CAM (ICH3) Pro/100 VE Ethernet" },
153      { 0x1032,  -1,     "Intel 82801CAM (ICH3) Pro/100 VE Ethernet" },
154      { 0x1033,  -1,     "Intel 82801CAM (ICH3) Pro/100 VM Ethernet" },
155      { 0x1034,  -1,     "Intel 82801CAM (ICH3) Pro/100 VM Ethernet" },
156      { 0x1035,  -1,     "Intel 82801CAM (ICH3) Pro/100 Ethernet" },
157      { 0x1036,  -1,     "Intel 82801CAM (ICH3) Pro/100 Ethernet" },
158      { 0x1037,  -1,     "Intel 82801CAM (ICH3) Pro/100 Ethernet" },
159      { 0x1038,  -1,     "Intel 82801CAM (ICH3) Pro/100 VM Ethernet" },
160      { 0x1039,  -1,     "Intel 82801DB (ICH4) Pro/100 VE Ethernet" },
161      { 0x103A,  -1,     "Intel 82801DB (ICH4) Pro/100 Ethernet" },
162      { 0x103B,  -1,     "Intel 82801DB (ICH4) Pro/100 VM Ethernet" },
163      { 0x103C,  -1,     "Intel 82801DB (ICH4) Pro/100 Ethernet" },
164      { 0x103D,  -1,     "Intel 82801DB (ICH4) Pro/100 VE Ethernet" },
165      { 0x103E,  -1,     "Intel 82801DB (ICH4) Pro/100 VM Ethernet" },
166      { 0x1050,  -1,     "Intel 82801BA (D865) Pro/100 VE Ethernet" },
167      { 0x1059,  -1,     "Intel 82551QM Pro/100 M Mobile Connection" },
168      { 0x1209,  -1,     "Intel 82559ER Embedded 10/100 Ethernet" },
169      { 0x1229,  0x01,   "Intel 82557 Pro/100 Ethernet" },
170      { 0x1229,  0x02,   "Intel 82557 Pro/100 Ethernet" },
171      { 0x1229,  0x03,   "Intel 82557 Pro/100 Ethernet" },
172      { 0x1229,  0x04,   "Intel 82558 Pro/100 Ethernet" },
173      { 0x1229,  0x05,   "Intel 82558 Pro/100 Ethernet" },
174      { 0x1229,  0x06,   "Intel 82559 Pro/100 Ethernet" },
175      { 0x1229,  0x07,   "Intel 82559 Pro/100 Ethernet" },
176      { 0x1229,  0x08,   "Intel 82559 Pro/100 Ethernet" },
177      { 0x1229,  0x09,   "Intel 82559ER Pro/100 Ethernet" },
178      { 0x1229,  0x0c,   "Intel 82550 Pro/100 Ethernet" },
179      { 0x1229,  0x0d,   "Intel 82550 Pro/100 Ethernet" },
180      { 0x1229,  0x0e,   "Intel 82550 Pro/100 Ethernet" },
181      { 0x1229,  0x0f,   "Intel 82551 Pro/100 Ethernet" },
182      { 0x1229,  0x10,   "Intel 82551 Pro/100 Ethernet" },
183      { 0x1229,  -1,     "Intel 82557/8/9 Pro/100 Ethernet" },
184      { 0x2449,  -1,     "Intel 82801BA/CAM (ICH2/3) Pro/100 Ethernet" },
185      { 0,       -1,     NULL },
186 };
187
188 static int              fxp_probe(device_t dev);
189 static int              fxp_attach(device_t dev);
190 static int              fxp_detach(device_t dev);
191 static int              fxp_shutdown(device_t dev);
192 static int              fxp_suspend(device_t dev);
193 static int              fxp_resume(device_t dev);
194
195 static void             fxp_intr(void *xsc);
196 static void             fxp_intr_body(struct fxp_softc *sc,
197                                 u_int8_t statack, int count);
198
199 static void             fxp_init(void *xsc);
200 static void             fxp_tick(void *xsc);
201 static void             fxp_powerstate_d0(device_t dev);
202 static void             fxp_start(struct ifnet *ifp);
203 static void             fxp_stop(struct fxp_softc *sc);
204 static void             fxp_release(struct fxp_softc *sc);
205 static int              fxp_ioctl(struct ifnet *ifp, u_long command,
206                             caddr_t data, struct ucred *);
207 static void             fxp_watchdog(struct ifnet *ifp);
208 static int              fxp_add_rfabuf(struct fxp_softc *sc, struct mbuf *oldm);
209 static int              fxp_mc_addrs(struct fxp_softc *sc);
210 static void             fxp_mc_setup(struct fxp_softc *sc);
211 static u_int16_t        fxp_eeprom_getword(struct fxp_softc *sc, int offset,
212                             int autosize);
213 static void             fxp_eeprom_putword(struct fxp_softc *sc, int offset,
214                             u_int16_t data);
215 static void             fxp_autosize_eeprom(struct fxp_softc *sc);
216 static void             fxp_read_eeprom(struct fxp_softc *sc, u_short *data,
217                             int offset, int words);
218 static void             fxp_write_eeprom(struct fxp_softc *sc, u_short *data,
219                             int offset, int words);
220 static int              fxp_ifmedia_upd(struct ifnet *ifp);
221 static void             fxp_ifmedia_sts(struct ifnet *ifp,
222                             struct ifmediareq *ifmr);
223 static int              fxp_serial_ifmedia_upd(struct ifnet *ifp);
224 static void             fxp_serial_ifmedia_sts(struct ifnet *ifp,
225                             struct ifmediareq *ifmr);
226 static volatile int     fxp_miibus_readreg(device_t dev, int phy, int reg);
227 static void             fxp_miibus_writereg(device_t dev, int phy, int reg,
228                             int value);
229 static void             fxp_load_ucode(struct fxp_softc *sc);
230 static int              sysctl_int_range(SYSCTL_HANDLER_ARGS,
231                             int low, int high);
232 static int              sysctl_hw_fxp_bundle_max(SYSCTL_HANDLER_ARGS);
233 static int              sysctl_hw_fxp_int_delay(SYSCTL_HANDLER_ARGS);
234 static __inline void    fxp_lwcopy(volatile u_int32_t *src,
235                             volatile u_int32_t *dst);
236 static __inline void    fxp_scb_wait(struct fxp_softc *sc);
237 static __inline void    fxp_scb_cmd(struct fxp_softc *sc, int cmd);
238 static __inline void    fxp_dma_wait(volatile u_int16_t *status,
239                             struct fxp_softc *sc);
240
241 static device_method_t fxp_methods[] = {
242         /* Device interface */
243         DEVMETHOD(device_probe,         fxp_probe),
244         DEVMETHOD(device_attach,        fxp_attach),
245         DEVMETHOD(device_detach,        fxp_detach),
246         DEVMETHOD(device_shutdown,      fxp_shutdown),
247         DEVMETHOD(device_suspend,       fxp_suspend),
248         DEVMETHOD(device_resume,        fxp_resume),
249
250         /* MII interface */
251         DEVMETHOD(miibus_readreg,       fxp_miibus_readreg),
252         DEVMETHOD(miibus_writereg,      fxp_miibus_writereg),
253
254         { 0, 0 }
255 };
256
257 static driver_t fxp_driver = {
258         "fxp",
259         fxp_methods,
260         sizeof(struct fxp_softc),
261 };
262
263 static devclass_t fxp_devclass;
264
265 DECLARE_DUMMY_MODULE(if_fxp);
266 MODULE_DEPEND(if_fxp, miibus, 1, 1, 1);
267 DRIVER_MODULE(if_fxp, pci, fxp_driver, fxp_devclass, 0, 0);
268 DRIVER_MODULE(if_fxp, cardbus, fxp_driver, fxp_devclass, 0, 0);
269 DRIVER_MODULE(miibus, fxp, miibus_driver, miibus_devclass, 0, 0);
270
271 static int fxp_rnr;
272 SYSCTL_INT(_hw, OID_AUTO, fxp_rnr, CTLFLAG_RW, &fxp_rnr, 0, "fxp rnr events");
273
274 /*
275  * Inline function to copy a 16-bit aligned 32-bit quantity.
276  */
277 static __inline void
278 fxp_lwcopy(volatile u_int32_t *src, volatile u_int32_t *dst)
279 {
280 #ifdef __i386__
281         *dst = *src;
282 #else
283         volatile u_int16_t *a = (volatile u_int16_t *)src;
284         volatile u_int16_t *b = (volatile u_int16_t *)dst;
285
286         b[0] = a[0];
287         b[1] = a[1];
288 #endif
289 }
290
291 /*
292  * Wait for the previous command to be accepted (but not necessarily
293  * completed).
294  */
295 static __inline void
296 fxp_scb_wait(struct fxp_softc *sc)
297 {
298         int i = 10000;
299
300         while (CSR_READ_1(sc, FXP_CSR_SCB_COMMAND) && --i)
301                 DELAY(2);
302         if (i == 0)
303                 device_printf(sc->dev, "SCB timeout: 0x%x 0x%x 0x%x 0x%x\n",
304                     CSR_READ_1(sc, FXP_CSR_SCB_COMMAND),
305                     CSR_READ_1(sc, FXP_CSR_SCB_STATACK),
306                     CSR_READ_1(sc, FXP_CSR_SCB_RUSCUS),
307                     CSR_READ_2(sc, FXP_CSR_FLOWCONTROL));
308 }
309
310 static __inline void
311 fxp_scb_cmd(struct fxp_softc *sc, int cmd)
312 {
313
314         if (cmd == FXP_SCB_COMMAND_CU_RESUME && sc->cu_resume_bug) {
315                 CSR_WRITE_1(sc, FXP_CSR_SCB_COMMAND, FXP_CB_COMMAND_NOP);
316                 fxp_scb_wait(sc);
317         }
318         CSR_WRITE_1(sc, FXP_CSR_SCB_COMMAND, cmd);
319 }
320
321 static __inline void
322 fxp_dma_wait(volatile u_int16_t *status, struct fxp_softc *sc)
323 {
324         int i = 10000;
325
326         while (!(*status & FXP_CB_STATUS_C) && --i)
327                 DELAY(2);
328         if (i == 0)
329                 device_printf(sc->dev, "DMA timeout\n");
330 }
331
332 /*
333  * Return identification string if this is device is ours.
334  */
335 static int
336 fxp_probe(device_t dev)
337 {
338         u_int16_t devid;
339         u_int8_t revid;
340         struct fxp_ident *ident;
341
342         if (pci_get_vendor(dev) == FXP_VENDORID_INTEL) {
343                 devid = pci_get_device(dev);
344                 revid = pci_get_revid(dev);
345                 for (ident = fxp_ident_table; ident->name != NULL; ident++) {
346                         if (ident->devid == devid &&
347                             (ident->revid == revid || ident->revid == -1)) {
348                                 device_set_desc(dev, ident->name);
349                                 return (0);
350                         }
351                 }
352         }
353         return (ENXIO);
354 }
355
356 static void
357 fxp_powerstate_d0(device_t dev)
358 {
359 #if defined(__DragonFly__) || __FreeBSD_version >= 430002
360         u_int32_t iobase, membase, irq;
361
362         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
363                 /* Save important PCI config data. */
364                 iobase = pci_read_config(dev, FXP_PCI_IOBA, 4);
365                 membase = pci_read_config(dev, FXP_PCI_MMBA, 4);
366                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
367
368                 /* Reset the power state. */
369                 device_printf(dev, "chip is in D%d power mode "
370                     "-- setting to D0\n", pci_get_powerstate(dev));
371
372                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
373
374                 /* Restore PCI config data. */
375                 pci_write_config(dev, FXP_PCI_IOBA, iobase, 4);
376                 pci_write_config(dev, FXP_PCI_MMBA, membase, 4);
377                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
378         }
379 #endif
380 }
381
382 static int
383 fxp_attach(device_t dev)
384 {
385         int error = 0;
386         struct fxp_softc *sc = device_get_softc(dev);
387         struct ifnet *ifp;
388         u_int32_t val;
389         u_int16_t data;
390         int i, rid, m1, m2, prefer_iomap;
391         int s;
392
393         bzero(sc, sizeof(*sc));
394         sc->dev = dev;
395         callout_init(&sc->fxp_stat_timer);
396         sysctl_ctx_init(&sc->sysctl_ctx);
397         mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_DEF | MTX_RECURSE);
398
399         s = splimp(); 
400
401         /*
402          * Enable bus mastering. Enable memory space too, in case
403          * BIOS/Prom forgot about it.
404          */
405         val = pci_read_config(dev, PCIR_COMMAND, 2);
406         val |= (PCIM_CMD_MEMEN|PCIM_CMD_BUSMASTEREN);
407         pci_write_config(dev, PCIR_COMMAND, val, 2);
408         val = pci_read_config(dev, PCIR_COMMAND, 2);
409
410         fxp_powerstate_d0(dev);
411
412         /*
413          * Figure out which we should try first - memory mapping or i/o mapping?
414          * We default to memory mapping. Then we accept an override from the
415          * command line. Then we check to see which one is enabled.
416          */
417         m1 = PCIM_CMD_MEMEN;
418         m2 = PCIM_CMD_PORTEN;
419         prefer_iomap = 0;
420         if (resource_int_value(device_get_name(dev), device_get_unit(dev),
421             "prefer_iomap", &prefer_iomap) == 0 && prefer_iomap != 0) {
422                 m1 = PCIM_CMD_PORTEN;
423                 m2 = PCIM_CMD_MEMEN;
424         }
425
426         if (val & m1) {
427                 sc->rtp =
428                     (m1 == PCIM_CMD_MEMEN)? SYS_RES_MEMORY : SYS_RES_IOPORT;
429                 sc->rgd = (m1 == PCIM_CMD_MEMEN)? FXP_PCI_MMBA : FXP_PCI_IOBA;
430                 sc->mem = bus_alloc_resource(dev, sc->rtp, &sc->rgd,
431                                              0, ~0, 1, RF_ACTIVE);
432         }
433         if (sc->mem == NULL && (val & m2)) {
434                 sc->rtp =
435                     (m2 == PCIM_CMD_MEMEN)? SYS_RES_MEMORY : SYS_RES_IOPORT;
436                 sc->rgd = (m2 == PCIM_CMD_MEMEN)? FXP_PCI_MMBA : FXP_PCI_IOBA;
437                 sc->mem = bus_alloc_resource(dev, sc->rtp, &sc->rgd,
438                                             0, ~0, 1, RF_ACTIVE);
439         }
440
441         if (!sc->mem) {
442                 device_printf(dev, "could not map device registers\n");
443                 error = ENXIO;
444                 goto fail;
445         }
446         if (bootverbose) {
447                 device_printf(dev, "using %s space register mapping\n",
448                    sc->rtp == SYS_RES_MEMORY? "memory" : "I/O");
449         }
450
451         sc->sc_st = rman_get_bustag(sc->mem);
452         sc->sc_sh = rman_get_bushandle(sc->mem);
453
454         /*
455          * Allocate our interrupt.
456          */
457         rid = 0;
458         sc->irq = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0, ~0, 1,
459                                  RF_SHAREABLE | RF_ACTIVE);
460         if (sc->irq == NULL) {
461                 device_printf(dev, "could not map interrupt\n");
462                 error = ENXIO;
463                 goto fail;
464         }
465
466         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET,
467                                fxp_intr, sc, &sc->ih);
468         if (error) {
469                 device_printf(dev, "could not setup irq\n");
470                 goto fail;
471         }
472
473         /*
474          * Reset to a stable state.
475          */
476         CSR_WRITE_4(sc, FXP_CSR_PORT, FXP_PORT_SELECTIVE_RESET);
477         DELAY(10);
478
479         sc->cbl_base = malloc(sizeof(struct fxp_cb_tx) * FXP_NTXCB,
480             M_DEVBUF, M_WAITOK | M_ZERO);
481
482         sc->fxp_stats = malloc(sizeof(struct fxp_stats), M_DEVBUF,
483             M_WAITOK | M_ZERO);
484
485         sc->mcsp = malloc(sizeof(struct fxp_cb_mcs), M_DEVBUF, M_WAITOK);
486
487         /*
488          * Pre-allocate our receive buffers.
489          */
490         for (i = 0; i < FXP_NRFABUFS; i++) {
491                 if (fxp_add_rfabuf(sc, NULL) != 0) {
492                         goto failmem;
493                 }
494         }
495
496         /*
497          * Find out how large of an SEEPROM we have.
498          */
499         fxp_autosize_eeprom(sc);
500
501         /*
502          * Determine whether we must use the 503 serial interface.
503          */
504         fxp_read_eeprom(sc, &data, 6, 1);
505         if ((data & FXP_PHY_DEVICE_MASK) != 0 &&
506             (data & FXP_PHY_SERIAL_ONLY))
507                 sc->flags |= FXP_FLAG_SERIAL_MEDIA;
508
509         /*
510          * Create the sysctl tree
511          */
512         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
513             SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
514             device_get_nameunit(dev), CTLFLAG_RD, 0, "");
515         if (sc->sysctl_tree == NULL)
516                 goto fail;
517         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
518             OID_AUTO, "int_delay", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_PRISON,
519             &sc->tunable_int_delay, 0, &sysctl_hw_fxp_int_delay, "I",
520             "FXP driver receive interrupt microcode bundling delay");
521         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
522             OID_AUTO, "bundle_max", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_PRISON,
523             &sc->tunable_bundle_max, 0, &sysctl_hw_fxp_bundle_max, "I",
524             "FXP driver receive interrupt microcode bundle size limit");
525
526         /*
527          * Pull in device tunables.
528          */
529         sc->tunable_int_delay = TUNABLE_INT_DELAY;
530         sc->tunable_bundle_max = TUNABLE_BUNDLE_MAX;
531         (void) resource_int_value(device_get_name(dev), device_get_unit(dev),
532             "int_delay", &sc->tunable_int_delay);
533         (void) resource_int_value(device_get_name(dev), device_get_unit(dev),
534             "bundle_max", &sc->tunable_bundle_max);
535
536         /*
537          * Find out the chip revision; lump all 82557 revs together.
538          */
539         fxp_read_eeprom(sc, &data, 5, 1);
540         if ((data >> 8) == 1)
541                 sc->revision = FXP_REV_82557;
542         else
543                 sc->revision = pci_get_revid(dev);
544
545         /*
546          * Enable workarounds for certain chip revision deficiencies.
547          *
548          * Systems based on the ICH2/ICH2-M chip from Intel, and possibly
549          * some systems based a normal 82559 design, have a defect where
550          * the chip can cause a PCI protocol violation if it receives
551          * a CU_RESUME command when it is entering the IDLE state.  The 
552          * workaround is to disable Dynamic Standby Mode, so the chip never
553          * deasserts CLKRUN#, and always remains in an active state.
554          *
555          * See Intel 82801BA/82801BAM Specification Update, Errata #30.
556          */
557         i = pci_get_device(dev);
558         if (i == 0x2449 || (i > 0x1030 && i < 0x1039) ||
559             sc->revision >= FXP_REV_82559_A0) {
560                 fxp_read_eeprom(sc, &data, 10, 1);
561                 if (data & 0x02) {                      /* STB enable */
562                         u_int16_t cksum;
563                         int i;
564
565                         device_printf(dev,
566                             "Disabling dynamic standby mode in EEPROM\n");
567                         data &= ~0x02;
568                         fxp_write_eeprom(sc, &data, 10, 1);
569                         device_printf(dev, "New EEPROM ID: 0x%x\n", data);
570                         cksum = 0;
571                         for (i = 0; i < (1 << sc->eeprom_size) - 1; i++) {
572                                 fxp_read_eeprom(sc, &data, i, 1);
573                                 cksum += data;
574                         }
575                         i = (1 << sc->eeprom_size) - 1;
576                         cksum = 0xBABA - cksum;
577                         fxp_read_eeprom(sc, &data, i, 1);
578                         fxp_write_eeprom(sc, &cksum, i, 1);
579                         device_printf(dev,
580                             "EEPROM checksum @ 0x%x: 0x%x -> 0x%x\n",
581                             i, data, cksum);
582 #if 1
583                         /*
584                          * If the user elects to continue, try the software
585                          * workaround, as it is better than nothing.
586                          */
587                         sc->flags |= FXP_FLAG_CU_RESUME_BUG;
588 #endif
589                 }
590         }
591
592         /*
593          * If we are not a 82557 chip, we can enable extended features.
594          */
595         if (sc->revision != FXP_REV_82557) {
596                 /*
597                  * If MWI is enabled in the PCI configuration, and there
598                  * is a valid cacheline size (8 or 16 dwords), then tell
599                  * the board to turn on MWI.
600                  */
601                 if (val & PCIM_CMD_MWRICEN &&
602                     pci_read_config(dev, PCIR_CACHELNSZ, 1) != 0)
603                         sc->flags |= FXP_FLAG_MWI_ENABLE;
604
605                 /* turn on the extended TxCB feature */
606                 sc->flags |= FXP_FLAG_EXT_TXCB;
607
608                 /* enable reception of long frames for VLAN */
609                 sc->flags |= FXP_FLAG_LONG_PKT_EN;
610         }
611
612         /*
613          * Read MAC address.
614          */
615         fxp_read_eeprom(sc, (u_int16_t *)sc->arpcom.ac_enaddr, 0, 3);
616         if (sc->flags & FXP_FLAG_SERIAL_MEDIA)
617                 device_printf(dev, "10Mbps");
618         if (bootverbose) {
619                 device_printf(dev, "PCI IDs: %04x %04x %04x %04x %04x\n",
620                     pci_get_vendor(dev), pci_get_device(dev),
621                     pci_get_subvendor(dev), pci_get_subdevice(dev),
622                     pci_get_revid(dev));
623                 fxp_read_eeprom(sc, &data, 10, 1);
624                 device_printf(dev, "Dynamic Standby mode is %s\n",
625                     data & 0x02 ? "enabled" : "disabled");
626         }
627
628         /*
629          * If this is only a 10Mbps device, then there is no MII, and
630          * the PHY will use a serial interface instead.
631          *
632          * The Seeq 80c24 AutoDUPLEX(tm) Ethernet Interface Adapter
633          * doesn't have a programming interface of any sort.  The
634          * media is sensed automatically based on how the link partner
635          * is configured.  This is, in essence, manual configuration.
636          */
637         if (sc->flags & FXP_FLAG_SERIAL_MEDIA) {
638                 ifmedia_init(&sc->sc_media, 0, fxp_serial_ifmedia_upd,
639                     fxp_serial_ifmedia_sts);
640                 ifmedia_add(&sc->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
641                 ifmedia_set(&sc->sc_media, IFM_ETHER|IFM_MANUAL);
642         } else {
643                 if (mii_phy_probe(dev, &sc->miibus, fxp_ifmedia_upd,
644                     fxp_ifmedia_sts)) {
645                         device_printf(dev, "MII without any PHY!\n");
646                         error = ENXIO;
647                         goto fail;
648                 }
649         }
650
651         ifp = &sc->arpcom.ac_if;
652         if_initname(ifp, "fxp", device_get_unit(dev));
653         ifp->if_baudrate = 100000000;
654         ifp->if_init = fxp_init;
655         ifp->if_softc = sc;
656         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
657         ifp->if_ioctl = fxp_ioctl;
658         ifp->if_start = fxp_start;
659         ifp->if_watchdog = fxp_watchdog;
660
661         /*
662          * Attach the interface.
663          */
664         ether_ifattach(ifp, sc->arpcom.ac_enaddr);
665
666         /*
667          * Tell the upper layer(s) we support long frames.
668          */
669         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
670
671         /*
672          * Let the system queue as many packets as we have available
673          * TX descriptors.
674          */
675         ifp->if_snd.ifq_maxlen = FXP_NTXCB - 1;
676
677         splx(s);
678         return (0);
679
680 failmem:
681         device_printf(dev, "Failed to malloc memory\n");
682         error = ENOMEM;
683 fail:
684         splx(s);
685         fxp_release(sc);
686         return (error);
687 }
688
689 /*
690  * release all resources
691  */
692 static void
693 fxp_release(struct fxp_softc *sc)
694 {
695
696         bus_generic_detach(sc->dev);
697         if (sc->miibus)
698                 device_delete_child(sc->dev, sc->miibus);
699
700         if (sc->cbl_base)
701                 free(sc->cbl_base, M_DEVBUF);
702         if (sc->fxp_stats)
703                 free(sc->fxp_stats, M_DEVBUF);
704         if (sc->mcsp)
705                 free(sc->mcsp, M_DEVBUF);
706         if (sc->rfa_headm)
707                 m_freem(sc->rfa_headm);
708
709         if (sc->ih)
710                 bus_teardown_intr(sc->dev, sc->irq, sc->ih);
711         if (sc->irq)
712                 bus_release_resource(sc->dev, SYS_RES_IRQ, 0, sc->irq);
713         if (sc->mem)
714                 bus_release_resource(sc->dev, sc->rtp, sc->rgd, sc->mem);
715
716         sysctl_ctx_free(&sc->sysctl_ctx);
717
718         mtx_destroy(&sc->sc_mtx);
719 }
720
721 /*
722  * Detach interface.
723  */
724 static int
725 fxp_detach(device_t dev)
726 {
727         struct fxp_softc *sc = device_get_softc(dev);
728         int s;
729
730         /* disable interrupts */
731         CSR_WRITE_1(sc, FXP_CSR_SCB_INTRCNTL, FXP_SCB_INTR_DISABLE);
732
733         s = splimp();
734
735         /*
736          * Stop DMA and drop transmit queue.
737          */
738         fxp_stop(sc);
739
740         /*
741          * Close down routes etc.
742          */
743         ether_ifdetach(&sc->arpcom.ac_if);
744
745         /*
746          * Free all media structures.
747          */
748         ifmedia_removeall(&sc->sc_media);
749
750         splx(s);
751
752         /* Release our allocated resources. */
753         fxp_release(sc);
754
755         return (0);
756 }
757
758 /*
759  * Device shutdown routine. Called at system shutdown after sync. The
760  * main purpose of this routine is to shut off receiver DMA so that
761  * kernel memory doesn't get clobbered during warmboot.
762  */
763 static int
764 fxp_shutdown(device_t dev)
765 {
766         /*
767          * Make sure that DMA is disabled prior to reboot. Not doing
768          * do could allow DMA to corrupt kernel memory during the
769          * reboot before the driver initializes.
770          */
771         fxp_stop((struct fxp_softc *) device_get_softc(dev));
772         return (0);
773 }
774
775 /*
776  * Device suspend routine.  Stop the interface and save some PCI
777  * settings in case the BIOS doesn't restore them properly on
778  * resume.
779  */
780 static int
781 fxp_suspend(device_t dev)
782 {
783         struct fxp_softc *sc = device_get_softc(dev);
784         int i, s;
785
786         s = splimp();
787
788         fxp_stop(sc);
789         
790         for (i = 0; i < 5; i++)
791                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
792         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
793         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
794         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
795         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
796
797         sc->suspended = 1;
798
799         splx(s);
800         return (0);
801 }
802
803 /*
804  * Device resume routine.  Restore some PCI settings in case the BIOS
805  * doesn't, re-enable busmastering, and restart the interface if
806  * appropriate.
807  */
808 static int
809 fxp_resume(device_t dev)
810 {
811         struct fxp_softc *sc = device_get_softc(dev);
812         struct ifnet *ifp = &sc->sc_if;
813         u_int16_t pci_command;
814         int i, s;
815
816         s = splimp();
817
818         fxp_powerstate_d0(dev);
819
820         /* better way to do this? */
821         for (i = 0; i < 5; i++)
822                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
823         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
824         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
825         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
826         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
827
828         /* reenable busmastering */
829         pci_command = pci_read_config(dev, PCIR_COMMAND, 2);
830         pci_command |= (PCIM_CMD_MEMEN|PCIM_CMD_BUSMASTEREN);
831         pci_write_config(dev, PCIR_COMMAND, pci_command, 2);
832
833         CSR_WRITE_4(sc, FXP_CSR_PORT, FXP_PORT_SELECTIVE_RESET);
834         DELAY(10);
835
836         /* reinitialize interface if necessary */
837         if (ifp->if_flags & IFF_UP)
838                 fxp_init(sc);
839
840         sc->suspended = 0;
841
842         splx(s);
843         return (0);
844 }
845
846 static void 
847 fxp_eeprom_shiftin(struct fxp_softc *sc, int data, int length)
848 {
849         u_int16_t reg;
850         int x;
851
852         /*
853          * Shift in data.
854          */
855         for (x = 1 << (length - 1); x; x >>= 1) {
856                 if (data & x)
857                         reg = FXP_EEPROM_EECS | FXP_EEPROM_EEDI;
858                 else
859                         reg = FXP_EEPROM_EECS;
860                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg);
861                 DELAY(1);
862                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg | FXP_EEPROM_EESK);
863                 DELAY(1);
864                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg);
865                 DELAY(1);
866         }
867 }
868
869 /*
870  * Read from the serial EEPROM. Basically, you manually shift in
871  * the read opcode (one bit at a time) and then shift in the address,
872  * and then you shift out the data (all of this one bit at a time).
873  * The word size is 16 bits, so you have to provide the address for
874  * every 16 bits of data.
875  */
876 static u_int16_t
877 fxp_eeprom_getword(struct fxp_softc *sc, int offset, int autosize)
878 {
879         u_int16_t reg, data;
880         int x;
881
882         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, FXP_EEPROM_EECS);
883         /*
884          * Shift in read opcode.
885          */
886         fxp_eeprom_shiftin(sc, FXP_EEPROM_OPC_READ, 3);
887         /*
888          * Shift in address.
889          */
890         data = 0;
891         for (x = 1 << (sc->eeprom_size - 1); x; x >>= 1) {
892                 if (offset & x)
893                         reg = FXP_EEPROM_EECS | FXP_EEPROM_EEDI;
894                 else
895                         reg = FXP_EEPROM_EECS;
896                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg);
897                 DELAY(1);
898                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg | FXP_EEPROM_EESK);
899                 DELAY(1);
900                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg);
901                 DELAY(1);
902                 reg = CSR_READ_2(sc, FXP_CSR_EEPROMCONTROL) & FXP_EEPROM_EEDO;
903                 data++;
904                 if (autosize && reg == 0) {
905                         sc->eeprom_size = data;
906                         break;
907                 }
908         }
909         /*
910          * Shift out data.
911          */
912         data = 0;
913         reg = FXP_EEPROM_EECS;
914         for (x = 1 << 15; x; x >>= 1) {
915                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg | FXP_EEPROM_EESK);
916                 DELAY(1);
917                 if (CSR_READ_2(sc, FXP_CSR_EEPROMCONTROL) & FXP_EEPROM_EEDO)
918                         data |= x;
919                 CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, reg);
920                 DELAY(1);
921         }
922         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, 0);
923         DELAY(1);
924
925         return (data);
926 }
927
928 static void
929 fxp_eeprom_putword(struct fxp_softc *sc, int offset, u_int16_t data)
930 {
931         int i;
932
933         /*
934          * Erase/write enable.
935          */
936         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, FXP_EEPROM_EECS);
937         fxp_eeprom_shiftin(sc, 0x4, 3);
938         fxp_eeprom_shiftin(sc, 0x03 << (sc->eeprom_size - 2), sc->eeprom_size);
939         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, 0);
940         DELAY(1);
941         /*
942          * Shift in write opcode, address, data.
943          */
944         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, FXP_EEPROM_EECS);
945         fxp_eeprom_shiftin(sc, FXP_EEPROM_OPC_WRITE, 3);
946         fxp_eeprom_shiftin(sc, offset, sc->eeprom_size);
947         fxp_eeprom_shiftin(sc, data, 16);
948         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, 0);
949         DELAY(1);
950         /*
951          * Wait for EEPROM to finish up.
952          */
953         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, FXP_EEPROM_EECS);
954         DELAY(1);
955         for (i = 0; i < 1000; i++) {
956                 if (CSR_READ_2(sc, FXP_CSR_EEPROMCONTROL) & FXP_EEPROM_EEDO)
957                         break;
958                 DELAY(50);
959         }
960         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, 0);
961         DELAY(1);
962         /*
963          * Erase/write disable.
964          */
965         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, FXP_EEPROM_EECS);
966         fxp_eeprom_shiftin(sc, 0x4, 3);
967         fxp_eeprom_shiftin(sc, 0, sc->eeprom_size);
968         CSR_WRITE_2(sc, FXP_CSR_EEPROMCONTROL, 0);
969         DELAY(1);
970 }
971
972 /*
973  * From NetBSD:
974  *
975  * Figure out EEPROM size.
976  *
977  * 559's can have either 64-word or 256-word EEPROMs, the 558
978  * datasheet only talks about 64-word EEPROMs, and the 557 datasheet
979  * talks about the existance of 16 to 256 word EEPROMs.
980  *
981  * The only known sizes are 64 and 256, where the 256 version is used
982  * by CardBus cards to store CIS information.
983  *
984  * The address is shifted in msb-to-lsb, and after the last
985  * address-bit the EEPROM is supposed to output a `dummy zero' bit,
986  * after which follows the actual data. We try to detect this zero, by
987  * probing the data-out bit in the EEPROM control register just after
988  * having shifted in a bit. If the bit is zero, we assume we've
989  * shifted enough address bits. The data-out should be tri-state,
990  * before this, which should translate to a logical one.
991  */
992 static void
993 fxp_autosize_eeprom(struct fxp_softc *sc)
994 {
995
996         /* guess maximum size of 256 words */
997         sc->eeprom_size = 8;
998
999         /* autosize */
1000         (void) fxp_eeprom_getword(sc, 0, 1);
1001 }
1002
1003 static void
1004 fxp_read_eeprom(struct fxp_softc *sc, u_short *data, int offset, int words)
1005 {
1006         int i;
1007
1008         for (i = 0; i < words; i++)
1009                 data[i] = fxp_eeprom_getword(sc, offset + i, 0);
1010 }
1011
1012 static void
1013 fxp_write_eeprom(struct fxp_softc *sc, u_short *data, int offset, int words)
1014 {
1015         int i;
1016
1017         for (i = 0; i < words; i++)
1018                 fxp_eeprom_putword(sc, offset + i, data[i]);
1019 }
1020
1021 /*
1022  * Start packet transmission on the interface.
1023  */
1024 static void
1025 fxp_start(struct ifnet *ifp)
1026 {
1027         struct fxp_softc *sc = ifp->if_softc;
1028         struct fxp_cb_tx *txp;
1029
1030         /*
1031          * See if we need to suspend xmit until the multicast filter
1032          * has been reprogrammed (which can only be done at the head
1033          * of the command chain).
1034          */
1035         if (sc->need_mcsetup) {
1036                 return;
1037         }
1038
1039         txp = NULL;
1040
1041         /*
1042          * We're finished if there is nothing more to add to the list or if
1043          * we're all filled up with buffers to transmit.
1044          * NOTE: One TxCB is reserved to guarantee that fxp_mc_setup() can add
1045          *       a NOP command when needed.
1046          */
1047         while (ifp->if_snd.ifq_head != NULL && sc->tx_queued < FXP_NTXCB - 1) {
1048                 struct mbuf *m, *mb_head;
1049                 int segment;
1050
1051                 /*
1052                  * Grab a packet to transmit.
1053                  */
1054                 IF_DEQUEUE(&ifp->if_snd, mb_head);
1055
1056                 /*
1057                  * Get pointer to next available tx desc.
1058                  */
1059                 txp = sc->cbl_last->next;
1060
1061                 /*
1062                  * Go through each of the mbufs in the chain and initialize
1063                  * the transmit buffer descriptors with the physical address
1064                  * and size of the mbuf.
1065                  */
1066 tbdinit:
1067                 for (m = mb_head, segment = 0; m != NULL; m = m->m_next) {
1068                         if (m->m_len != 0) {
1069                                 if (segment == FXP_NTXSEG)
1070                                         break;
1071                                 txp->tbd[segment].tb_addr =
1072                                     vtophys(mtod(m, vm_offset_t));
1073                                 txp->tbd[segment].tb_size = m->m_len;
1074                                 segment++;
1075                         }
1076                 }
1077                 if (m != NULL) {
1078                         struct mbuf *mn;
1079
1080                         /*
1081                          * We ran out of segments. We have to recopy this
1082                          * mbuf chain first. Bail out if we can't get the
1083                          * new buffers.
1084                          */
1085                         MGETHDR(mn, MB_DONTWAIT, MT_DATA);
1086                         if (mn == NULL) {
1087                                 m_freem(mb_head);
1088                                 break;
1089                         }
1090                         if (mb_head->m_pkthdr.len > MHLEN) {
1091                                 MCLGET(mn, MB_DONTWAIT);
1092                                 if ((mn->m_flags & M_EXT) == 0) {
1093                                         m_freem(mn);
1094                                         m_freem(mb_head);
1095                                         break;
1096                                 }
1097                         }
1098                         m_copydata(mb_head, 0, mb_head->m_pkthdr.len,
1099                             mtod(mn, caddr_t));
1100                         mn->m_pkthdr.len = mn->m_len = mb_head->m_pkthdr.len;
1101                         m_freem(mb_head);
1102                         mb_head = mn;
1103                         goto tbdinit;
1104                 }
1105
1106                 txp->tbd_number = segment;
1107                 txp->mb_head = mb_head;
1108                 txp->cb_status = 0;
1109                 if (sc->tx_queued != FXP_CXINT_THRESH - 1) {
1110                         txp->cb_command =
1111                             FXP_CB_COMMAND_XMIT | FXP_CB_COMMAND_SF |
1112                             FXP_CB_COMMAND_S;
1113                 } else {
1114                         txp->cb_command =
1115                             FXP_CB_COMMAND_XMIT | FXP_CB_COMMAND_SF |
1116                             FXP_CB_COMMAND_S | FXP_CB_COMMAND_I;
1117                         /*
1118                          * Set a 5 second timer just in case we don't hear
1119                          * from the card again.
1120                          */
1121                         ifp->if_timer = 5;
1122                 }
1123                 txp->tx_threshold = tx_threshold;
1124         
1125                 /*
1126                  * Advance the end of list forward.
1127                  */
1128
1129 #ifdef __alpha__
1130                 /*
1131                  * On platforms which can't access memory in 16-bit
1132                  * granularities, we must prevent the card from DMA'ing
1133                  * up the status while we update the command field.
1134                  * This could cause us to overwrite the completion status.
1135                  */
1136                 atomic_clear_short(&sc->cbl_last->cb_command,
1137                     FXP_CB_COMMAND_S);
1138 #else
1139                 sc->cbl_last->cb_command &= ~FXP_CB_COMMAND_S;
1140 #endif /*__alpha__*/
1141                 sc->cbl_last = txp;
1142
1143                 /*
1144                  * Advance the beginning of the list forward if there are
1145                  * no other packets queued (when nothing is queued, cbl_first
1146                  * sits on the last TxCB that was sent out).
1147                  */
1148                 if (sc->tx_queued == 0)
1149                         sc->cbl_first = txp;
1150
1151                 sc->tx_queued++;
1152
1153                 /*
1154                  * Pass packet to bpf if there is a listener.
1155                  */
1156                 if (ifp->if_bpf)
1157                         bpf_mtap(ifp, mb_head);
1158         }
1159
1160         /*
1161          * We're finished. If we added to the list, issue a RESUME to get DMA
1162          * going again if suspended.
1163          */
1164         if (txp != NULL) {
1165                 fxp_scb_wait(sc);
1166                 fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_RESUME);
1167         }
1168 }
1169
1170 #ifdef DEVICE_POLLING
1171 static poll_handler_t fxp_poll;
1172
1173 static void
1174 fxp_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1175 {
1176         struct fxp_softc *sc = ifp->if_softc;
1177         u_int8_t statack;
1178
1179         if (cmd == POLL_DEREGISTER) {   /* final call, enable interrupts */
1180                 CSR_WRITE_1(sc, FXP_CSR_SCB_INTRCNTL, 0);
1181                 return;
1182         }
1183         statack = FXP_SCB_STATACK_CXTNO | FXP_SCB_STATACK_CNA |
1184             FXP_SCB_STATACK_FR;
1185         if (cmd == POLL_AND_CHECK_STATUS) {
1186                 u_int8_t tmp;
1187
1188                 tmp = CSR_READ_1(sc, FXP_CSR_SCB_STATACK);
1189                 if (tmp == 0xff || tmp == 0)
1190                         return; /* nothing to do */
1191                 tmp &= ~statack;
1192                 /* ack what we can */
1193                 if (tmp != 0)
1194                         CSR_WRITE_1(sc, FXP_CSR_SCB_STATACK, tmp);
1195                 statack |= tmp;
1196         }
1197         fxp_intr_body(sc, statack, count);
1198 }
1199 #endif /* DEVICE_POLLING */
1200
1201 /*
1202  * Process interface interrupts.
1203  */
1204 static void
1205 fxp_intr(void *xsc)
1206 {
1207         struct fxp_softc *sc = xsc;
1208         u_int8_t statack;
1209
1210 #ifdef DEVICE_POLLING
1211         struct ifnet *ifp = &sc->sc_if;
1212
1213         if (ifp->if_flags & IFF_POLLING)
1214                 return;
1215         if (ether_poll_register(fxp_poll, ifp)) {
1216                 /* disable interrupts */
1217                 CSR_WRITE_1(sc, FXP_CSR_SCB_INTRCNTL, FXP_SCB_INTR_DISABLE);
1218                 fxp_poll(ifp, 0, 1);
1219                 return;
1220         }
1221 #endif
1222
1223         if (sc->suspended) {
1224                 return;
1225         }
1226
1227         while ((statack = CSR_READ_1(sc, FXP_CSR_SCB_STATACK)) != 0) {
1228                 /*
1229                  * It should not be possible to have all bits set; the
1230                  * FXP_SCB_INTR_SWI bit always returns 0 on a read.  If 
1231                  * all bits are set, this may indicate that the card has
1232                  * been physically ejected, so ignore it.
1233                  */  
1234                 if (statack == 0xff) 
1235                         return;
1236
1237                 /*
1238                  * First ACK all the interrupts in this pass.
1239                  */
1240                 CSR_WRITE_1(sc, FXP_CSR_SCB_STATACK, statack);
1241                 fxp_intr_body(sc, statack, -1);
1242         }
1243 }
1244
1245 static void
1246 fxp_intr_body(struct fxp_softc *sc, u_int8_t statack, int count)
1247 {
1248         struct ifnet *ifp = &sc->sc_if;
1249         struct mbuf *m;
1250         struct fxp_rfa *rfa;
1251         int rnr = (statack & FXP_SCB_STATACK_RNR) ? 1 : 0;
1252
1253         if (rnr)
1254                 fxp_rnr++;
1255 #ifdef DEVICE_POLLING
1256         /* Pick up a deferred RNR condition if `count' ran out last time. */
1257         if (sc->flags & FXP_FLAG_DEFERRED_RNR) {
1258                 sc->flags &= ~FXP_FLAG_DEFERRED_RNR;
1259                 rnr = 1;
1260         }
1261 #endif
1262
1263         /*
1264          * Free any finished transmit mbuf chains.
1265          *
1266          * Handle the CNA event likt a CXTNO event. It used to
1267          * be that this event (control unit not ready) was not
1268          * encountered, but it is now with the SMPng modifications.
1269          * The exact sequence of events that occur when the interface
1270          * is brought up are different now, and if this event
1271          * goes unhandled, the configuration/rxfilter setup sequence
1272          * can stall for several seconds. The result is that no
1273          * packets go out onto the wire for about 5 to 10 seconds
1274          * after the interface is ifconfig'ed for the first time.
1275          */
1276         if (statack & (FXP_SCB_STATACK_CXTNO | FXP_SCB_STATACK_CNA)) {
1277                 struct fxp_cb_tx *txp;
1278
1279                 for (txp = sc->cbl_first; sc->tx_queued &&
1280                     (txp->cb_status & FXP_CB_STATUS_C) != 0;
1281                     txp = txp->next) {
1282                         if ((m = txp->mb_head) != NULL) {
1283                                 txp->mb_head = NULL;
1284                                 sc->tx_queued--;
1285                                 m_freem(m);
1286                         } else {
1287                                 sc->tx_queued--;
1288                         }
1289                 }
1290                 sc->cbl_first = txp;
1291                 ifp->if_timer = 0;
1292                 if (sc->tx_queued == 0) {
1293                         if (sc->need_mcsetup)
1294                                 fxp_mc_setup(sc);
1295                 }
1296                 /*
1297                  * Try to start more packets transmitting.
1298                  */
1299                 if (ifp->if_snd.ifq_head != NULL)
1300                         fxp_start(ifp);
1301         }
1302
1303         /*
1304          * Just return if nothing happened on the receive side.
1305          */
1306         if (!rnr && (statack & FXP_SCB_STATACK_FR) == 0)
1307                 return;
1308
1309         /*
1310          * Process receiver interrupts. If a no-resource (RNR)
1311          * condition exists, get whatever packets we can and
1312          * re-start the receiver.
1313          *
1314          * When using polling, we do not process the list to completion,
1315          * so when we get an RNR interrupt we must defer the restart
1316          * until we hit the last buffer with the C bit set.
1317          * If we run out of cycles and rfa_headm has the C bit set,
1318          * record the pending RNR in the FXP_FLAG_DEFERRED_RNR flag so
1319          * that the info will be used in the subsequent polling cycle.
1320          */
1321         for (;;) {
1322                 m = sc->rfa_headm;
1323                 rfa = (struct fxp_rfa *)(m->m_ext.ext_buf +
1324                     RFA_ALIGNMENT_FUDGE);
1325
1326 #ifdef DEVICE_POLLING /* loop at most count times if count >=0 */
1327                 if (count >= 0 && count-- == 0) {
1328                         if (rnr) {
1329                                 /* Defer RNR processing until the next time. */
1330                                 sc->flags |= FXP_FLAG_DEFERRED_RNR;
1331                                 rnr = 0;
1332                         }
1333                         break;
1334                 }
1335 #endif /* DEVICE_POLLING */
1336
1337                 if ( (rfa->rfa_status & FXP_RFA_STATUS_C) == 0)
1338                         break;
1339
1340                 /*
1341                  * Remove first packet from the chain.
1342                  */
1343                 sc->rfa_headm = m->m_next;
1344                 m->m_next = NULL;
1345
1346                 /*
1347                  * Add a new buffer to the receive chain.
1348                  * If this fails, the old buffer is recycled
1349                  * instead.
1350                  */
1351                 if (fxp_add_rfabuf(sc, m) == 0) {
1352                         int total_len;
1353
1354                         /*
1355                          * Fetch packet length (the top 2 bits of
1356                          * actual_size are flags set by the controller
1357                          * upon completion), and drop the packet in case
1358                          * of bogus length or CRC errors.
1359                          */
1360                         total_len = rfa->actual_size & 0x3fff;
1361                         if (total_len < sizeof(struct ether_header) ||
1362                             total_len > MCLBYTES - RFA_ALIGNMENT_FUDGE -
1363                                 sizeof(struct fxp_rfa) ||
1364                             rfa->rfa_status & FXP_RFA_STATUS_CRC) {
1365                                 m_freem(m);
1366                                 continue;
1367                         }
1368                         m->m_pkthdr.len = m->m_len = total_len;
1369                         (*ifp->if_input)(ifp, m);
1370                 }
1371         }
1372         if (rnr) {
1373                 fxp_scb_wait(sc);
1374                 CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL,
1375                     vtophys(sc->rfa_headm->m_ext.ext_buf) +
1376                     RFA_ALIGNMENT_FUDGE);
1377                 fxp_scb_cmd(sc, FXP_SCB_COMMAND_RU_START);
1378         }
1379 }
1380
1381 /*
1382  * Update packet in/out/collision statistics. The i82557 doesn't
1383  * allow you to access these counters without doing a fairly
1384  * expensive DMA to get _all_ of the statistics it maintains, so
1385  * we do this operation here only once per second. The statistics
1386  * counters in the kernel are updated from the previous dump-stats
1387  * DMA and then a new dump-stats DMA is started. The on-chip
1388  * counters are zeroed when the DMA completes. If we can't start
1389  * the DMA immediately, we don't wait - we just prepare to read
1390  * them again next time.
1391  */
1392 static void
1393 fxp_tick(void *xsc)
1394 {
1395         struct fxp_softc *sc = xsc;
1396         struct ifnet *ifp = &sc->sc_if;
1397         struct fxp_stats *sp = sc->fxp_stats;
1398         struct fxp_cb_tx *txp;
1399         struct mbuf *m;
1400         int s;
1401
1402         ifp->if_opackets += sp->tx_good;
1403         ifp->if_collisions += sp->tx_total_collisions;
1404         if (sp->rx_good) {
1405                 ifp->if_ipackets += sp->rx_good;
1406                 sc->rx_idle_secs = 0;
1407         } else {
1408                 /*
1409                  * Receiver's been idle for another second.
1410                  */
1411                 sc->rx_idle_secs++;
1412         }
1413         ifp->if_ierrors +=
1414             sp->rx_crc_errors +
1415             sp->rx_alignment_errors +
1416             sp->rx_rnr_errors +
1417             sp->rx_overrun_errors;
1418         /*
1419          * If any transmit underruns occured, bump up the transmit
1420          * threshold by another 512 bytes (64 * 8).
1421          */
1422         if (sp->tx_underruns) {
1423                 ifp->if_oerrors += sp->tx_underruns;
1424                 if (tx_threshold < 192)
1425                         tx_threshold += 64;
1426         }
1427         s = splimp();
1428         /*
1429          * Release any xmit buffers that have completed DMA. This isn't
1430          * strictly necessary to do here, but it's advantagous for mbufs
1431          * with external storage to be released in a timely manner rather
1432          * than being defered for a potentially long time. This limits
1433          * the delay to a maximum of one second.
1434          */ 
1435         for (txp = sc->cbl_first; sc->tx_queued &&
1436             (txp->cb_status & FXP_CB_STATUS_C) != 0;
1437             txp = txp->next) {
1438                 if ((m = txp->mb_head) != NULL) {
1439                         txp->mb_head = NULL;
1440                         sc->tx_queued--;
1441                         m_freem(m);
1442                 } else {
1443                         sc->tx_queued--;
1444                 }
1445         }
1446         sc->cbl_first = txp;
1447         /*
1448          * If we haven't received any packets in FXP_MAC_RX_IDLE seconds,
1449          * then assume the receiver has locked up and attempt to clear
1450          * the condition by reprogramming the multicast filter. This is
1451          * a work-around for a bug in the 82557 where the receiver locks
1452          * up if it gets certain types of garbage in the syncronization
1453          * bits prior to the packet header. This bug is supposed to only
1454          * occur in 10Mbps mode, but has been seen to occur in 100Mbps
1455          * mode as well (perhaps due to a 10/100 speed transition).
1456          */
1457         if (sc->rx_idle_secs > FXP_MAX_RX_IDLE) {
1458                 sc->rx_idle_secs = 0;
1459                 fxp_mc_setup(sc);
1460         }
1461         /*
1462          * If there is no pending command, start another stats
1463          * dump. Otherwise punt for now.
1464          */
1465         if (CSR_READ_1(sc, FXP_CSR_SCB_COMMAND) == 0) {
1466                 /*
1467                  * Start another stats dump.
1468                  */
1469                 fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_DUMPRESET);
1470         } else {
1471                 /*
1472                  * A previous command is still waiting to be accepted.
1473                  * Just zero our copy of the stats and wait for the
1474                  * next timer event to update them.
1475                  */
1476                 sp->tx_good = 0;
1477                 sp->tx_underruns = 0;
1478                 sp->tx_total_collisions = 0;
1479
1480                 sp->rx_good = 0;
1481                 sp->rx_crc_errors = 0;
1482                 sp->rx_alignment_errors = 0;
1483                 sp->rx_rnr_errors = 0;
1484                 sp->rx_overrun_errors = 0;
1485         }
1486         if (sc->miibus != NULL)
1487                 mii_tick(device_get_softc(sc->miibus));
1488         splx(s);
1489         /*
1490          * Schedule another timeout one second from now.
1491          */
1492         callout_reset(&sc->fxp_stat_timer, hz, fxp_tick, sc);
1493 }
1494
1495 /*
1496  * Stop the interface. Cancels the statistics updater and resets
1497  * the interface.
1498  */
1499 static void
1500 fxp_stop(struct fxp_softc *sc)
1501 {
1502         struct ifnet *ifp = &sc->sc_if;
1503         struct fxp_cb_tx *txp;
1504         int i;
1505
1506         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1507         ifp->if_timer = 0;
1508
1509 #ifdef DEVICE_POLLING
1510         ether_poll_deregister(ifp);
1511 #endif
1512         /*
1513          * Cancel stats updater.
1514          */
1515         callout_stop(&sc->fxp_stat_timer);
1516
1517         /*
1518          * Issue software reset, which also unloads the microcode.
1519          */
1520         sc->flags &= ~FXP_FLAG_UCODE;
1521         CSR_WRITE_4(sc, FXP_CSR_PORT, FXP_PORT_SOFTWARE_RESET);
1522         DELAY(50);
1523
1524         /*
1525          * Release any xmit buffers.
1526          */
1527         txp = sc->cbl_base;
1528         if (txp != NULL) {
1529                 for (i = 0; i < FXP_NTXCB; i++) {
1530                         if (txp[i].mb_head != NULL) {
1531                                 m_freem(txp[i].mb_head);
1532                                 txp[i].mb_head = NULL;
1533                         }
1534                 }
1535         }
1536         sc->tx_queued = 0;
1537
1538         /*
1539          * Free all the receive buffers then reallocate/reinitialize
1540          */
1541         if (sc->rfa_headm != NULL)
1542                 m_freem(sc->rfa_headm);
1543         sc->rfa_headm = NULL;
1544         sc->rfa_tailm = NULL;
1545         for (i = 0; i < FXP_NRFABUFS; i++) {
1546                 if (fxp_add_rfabuf(sc, NULL) != 0) {
1547                         /*
1548                          * This "can't happen" - we're at splimp()
1549                          * and we just freed all the buffers we need
1550                          * above.
1551                          */
1552                         panic("fxp_stop: no buffers!");
1553                 }
1554         }
1555 }
1556
1557 /*
1558  * Watchdog/transmission transmit timeout handler. Called when a
1559  * transmission is started on the interface, but no interrupt is
1560  * received before the timeout. This usually indicates that the
1561  * card has wedged for some reason.
1562  */
1563 static void
1564 fxp_watchdog(struct ifnet *ifp)
1565 {
1566         struct fxp_softc *sc = ifp->if_softc;
1567
1568         device_printf(sc->dev, "device timeout\n");
1569         ifp->if_oerrors++;
1570
1571         fxp_init(sc);
1572 }
1573
1574 static void
1575 fxp_init(void *xsc)
1576 {
1577         struct fxp_softc *sc = xsc;
1578         struct ifnet *ifp = &sc->sc_if;
1579         struct fxp_cb_config *cbp;
1580         struct fxp_cb_ias *cb_ias;
1581         struct fxp_cb_tx *txp;
1582         struct fxp_cb_mcs *mcsp;
1583         int i, prm, s;
1584
1585         s = splimp();
1586         /*
1587          * Cancel any pending I/O
1588          */
1589         fxp_stop(sc);
1590
1591         prm = (ifp->if_flags & IFF_PROMISC) ? 1 : 0;
1592
1593         /*
1594          * Initialize base of CBL and RFA memory. Loading with zero
1595          * sets it up for regular linear addressing.
1596          */
1597         CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL, 0);
1598         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_BASE);
1599
1600         fxp_scb_wait(sc);
1601         fxp_scb_cmd(sc, FXP_SCB_COMMAND_RU_BASE);
1602
1603         /*
1604          * Initialize base of dump-stats buffer.
1605          */
1606         fxp_scb_wait(sc);
1607         CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL, vtophys(sc->fxp_stats));
1608         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_DUMP_ADR);
1609
1610         /*
1611          * Attempt to load microcode if requested.
1612          */
1613         if (ifp->if_flags & IFF_LINK0 && (sc->flags & FXP_FLAG_UCODE) == 0)
1614                 fxp_load_ucode(sc);
1615
1616         /*
1617          * Initialize the multicast address list.
1618          */
1619         if (fxp_mc_addrs(sc)) {
1620                 mcsp = sc->mcsp;
1621                 mcsp->cb_status = 0;
1622                 mcsp->cb_command = FXP_CB_COMMAND_MCAS | FXP_CB_COMMAND_EL;
1623                 mcsp->link_addr = -1;
1624                 /*
1625                  * Start the multicast setup command.
1626                  */
1627                 fxp_scb_wait(sc);
1628                 CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL, vtophys(&mcsp->cb_status));
1629                 fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_START);
1630                 /* ...and wait for it to complete. */
1631                 fxp_dma_wait(&mcsp->cb_status, sc);
1632         }
1633
1634         /*
1635          * We temporarily use memory that contains the TxCB list to
1636          * construct the config CB. The TxCB list memory is rebuilt
1637          * later.
1638          */
1639         cbp = (struct fxp_cb_config *) sc->cbl_base;
1640
1641         /*
1642          * This bcopy is kind of disgusting, but there are a bunch of must be
1643          * zero and must be one bits in this structure and this is the easiest
1644          * way to initialize them all to proper values.
1645          */
1646         bcopy(fxp_cb_config_template,
1647                 (void *)(uintptr_t)(volatile void *)&cbp->cb_status,
1648                 sizeof(fxp_cb_config_template));
1649
1650         cbp->cb_status =        0;
1651         cbp->cb_command =       FXP_CB_COMMAND_CONFIG | FXP_CB_COMMAND_EL;
1652         cbp->link_addr =        -1;     /* (no) next command */
1653         cbp->byte_count =       22;     /* (22) bytes to config */
1654         cbp->rx_fifo_limit =    8;      /* rx fifo threshold (32 bytes) */
1655         cbp->tx_fifo_limit =    0;      /* tx fifo threshold (0 bytes) */
1656         cbp->adaptive_ifs =     0;      /* (no) adaptive interframe spacing */
1657         cbp->mwi_enable =       sc->flags & FXP_FLAG_MWI_ENABLE ? 1 : 0;
1658         cbp->type_enable =      0;      /* actually reserved */
1659         cbp->read_align_en =    sc->flags & FXP_FLAG_READ_ALIGN ? 1 : 0;
1660         cbp->end_wr_on_cl =     sc->flags & FXP_FLAG_WRITE_ALIGN ? 1 : 0;
1661         cbp->rx_dma_bytecount = 0;      /* (no) rx DMA max */
1662         cbp->tx_dma_bytecount = 0;      /* (no) tx DMA max */
1663         cbp->dma_mbce =         0;      /* (disable) dma max counters */
1664         cbp->late_scb =         0;      /* (don't) defer SCB update */
1665         cbp->direct_dma_dis =   1;      /* disable direct rcv dma mode */
1666         cbp->tno_int_or_tco_en =0;      /* (disable) tx not okay interrupt */
1667         cbp->ci_int =           1;      /* interrupt on CU idle */
1668         cbp->ext_txcb_dis =     sc->flags & FXP_FLAG_EXT_TXCB ? 0 : 1;
1669         cbp->ext_stats_dis =    1;      /* disable extended counters */
1670         cbp->keep_overrun_rx =  0;      /* don't pass overrun frames to host */
1671         cbp->save_bf =          sc->revision == FXP_REV_82557 ? 1 : prm;
1672         cbp->disc_short_rx =    !prm;   /* discard short packets */
1673         cbp->underrun_retry =   1;      /* retry mode (once) on DMA underrun */
1674         cbp->two_frames =       0;      /* do not limit FIFO to 2 frames */
1675         cbp->dyn_tbd =          0;      /* (no) dynamic TBD mode */
1676         cbp->mediatype =        sc->flags & FXP_FLAG_SERIAL_MEDIA ? 0 : 1;
1677         cbp->csma_dis =         0;      /* (don't) disable link */
1678         cbp->tcp_udp_cksum =    0;      /* (don't) enable checksum */
1679         cbp->vlan_tco =         0;      /* (don't) enable vlan wakeup */
1680         cbp->link_wake_en =     0;      /* (don't) assert PME# on link change */
1681         cbp->arp_wake_en =      0;      /* (don't) assert PME# on arp */
1682         cbp->mc_wake_en =       0;      /* (don't) enable PME# on mcmatch */
1683         cbp->nsai =             1;      /* (don't) disable source addr insert */
1684         cbp->preamble_length =  2;      /* (7 byte) preamble */
1685         cbp->loopback =         0;      /* (don't) loopback */
1686         cbp->linear_priority =  0;      /* (normal CSMA/CD operation) */
1687         cbp->linear_pri_mode =  0;      /* (wait after xmit only) */
1688         cbp->interfrm_spacing = 6;      /* (96 bits of) interframe spacing */
1689         cbp->promiscuous =      prm;    /* promiscuous mode */
1690         cbp->bcast_disable =    0;      /* (don't) disable broadcasts */
1691         cbp->wait_after_win =   0;      /* (don't) enable modified backoff alg*/
1692         cbp->ignore_ul =        0;      /* consider U/L bit in IA matching */
1693         cbp->crc16_en =         0;      /* (don't) enable crc-16 algorithm */
1694         cbp->crscdt =           sc->flags & FXP_FLAG_SERIAL_MEDIA ? 1 : 0;
1695
1696         cbp->stripping =        !prm;   /* truncate rx packet to byte count */
1697         cbp->padding =          1;      /* (do) pad short tx packets */
1698         cbp->rcv_crc_xfer =     0;      /* (don't) xfer CRC to host */
1699         cbp->long_rx_en =       sc->flags & FXP_FLAG_LONG_PKT_EN ? 1 : 0;
1700         cbp->ia_wake_en =       0;      /* (don't) wake up on address match */
1701         cbp->magic_pkt_dis =    0;      /* (don't) disable magic packet */
1702                                         /* must set wake_en in PMCSR also */
1703         cbp->force_fdx =        0;      /* (don't) force full duplex */
1704         cbp->fdx_pin_en =       1;      /* (enable) FDX# pin */
1705         cbp->multi_ia =         0;      /* (don't) accept multiple IAs */
1706         cbp->mc_all =           sc->flags & FXP_FLAG_ALL_MCAST ? 1 : 0;
1707
1708         if (sc->revision == FXP_REV_82557) {
1709                 /*
1710                  * The 82557 has no hardware flow control, the values
1711                  * below are the defaults for the chip.
1712                  */
1713                 cbp->fc_delay_lsb =     0;
1714                 cbp->fc_delay_msb =     0x40;
1715                 cbp->pri_fc_thresh =    3;
1716                 cbp->tx_fc_dis =        0;
1717                 cbp->rx_fc_restop =     0;
1718                 cbp->rx_fc_restart =    0;
1719                 cbp->fc_filter =        0;
1720                 cbp->pri_fc_loc =       1;
1721         } else {
1722                 cbp->fc_delay_lsb =     0x1f;
1723                 cbp->fc_delay_msb =     0x01;
1724                 cbp->pri_fc_thresh =    3;
1725                 cbp->tx_fc_dis =        0;      /* enable transmit FC */
1726                 cbp->rx_fc_restop =     1;      /* enable FC restop frames */
1727                 cbp->rx_fc_restart =    1;      /* enable FC restart frames */
1728                 cbp->fc_filter =        !prm;   /* drop FC frames to host */
1729                 cbp->pri_fc_loc =       1;      /* FC pri location (byte31) */
1730         }
1731
1732         /*
1733          * Start the config command/DMA.
1734          */
1735         fxp_scb_wait(sc);
1736         CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL, vtophys(&cbp->cb_status));
1737         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_START);
1738         /* ...and wait for it to complete. */
1739         fxp_dma_wait(&cbp->cb_status, sc);
1740
1741         /*
1742          * Now initialize the station address. Temporarily use the TxCB
1743          * memory area like we did above for the config CB.
1744          */
1745         cb_ias = (struct fxp_cb_ias *) sc->cbl_base;
1746         cb_ias->cb_status = 0;
1747         cb_ias->cb_command = FXP_CB_COMMAND_IAS | FXP_CB_COMMAND_EL;
1748         cb_ias->link_addr = -1;
1749         bcopy(sc->arpcom.ac_enaddr,
1750             (void *)(uintptr_t)(volatile void *)cb_ias->macaddr,
1751             sizeof(sc->arpcom.ac_enaddr));
1752
1753         /*
1754          * Start the IAS (Individual Address Setup) command/DMA.
1755          */
1756         fxp_scb_wait(sc);
1757         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_START);
1758         /* ...and wait for it to complete. */
1759         fxp_dma_wait(&cb_ias->cb_status, sc);
1760
1761         /*
1762          * Initialize transmit control block (TxCB) list.
1763          */
1764
1765         txp = sc->cbl_base;
1766         bzero(txp, sizeof(struct fxp_cb_tx) * FXP_NTXCB);
1767         for (i = 0; i < FXP_NTXCB; i++) {
1768                 txp[i].cb_status = FXP_CB_STATUS_C | FXP_CB_STATUS_OK;
1769                 txp[i].cb_command = FXP_CB_COMMAND_NOP;
1770                 txp[i].link_addr =
1771                     vtophys(&txp[(i + 1) & FXP_TXCB_MASK].cb_status);
1772                 if (sc->flags & FXP_FLAG_EXT_TXCB)
1773                         txp[i].tbd_array_addr = vtophys(&txp[i].tbd[2]);
1774                 else
1775                         txp[i].tbd_array_addr = vtophys(&txp[i].tbd[0]);
1776                 txp[i].next = &txp[(i + 1) & FXP_TXCB_MASK];
1777         }
1778         /*
1779          * Set the suspend flag on the first TxCB and start the control
1780          * unit. It will execute the NOP and then suspend.
1781          */
1782         txp->cb_command = FXP_CB_COMMAND_NOP | FXP_CB_COMMAND_S;
1783         sc->cbl_first = sc->cbl_last = txp;
1784         sc->tx_queued = 1;
1785
1786         fxp_scb_wait(sc);
1787         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_START);
1788
1789         /*
1790          * Initialize receiver buffer area - RFA.
1791          */
1792         fxp_scb_wait(sc);
1793         CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL,
1794             vtophys(sc->rfa_headm->m_ext.ext_buf) + RFA_ALIGNMENT_FUDGE);
1795         fxp_scb_cmd(sc, FXP_SCB_COMMAND_RU_START);
1796
1797         /*
1798          * Set current media.
1799          */
1800         if (sc->miibus != NULL)
1801                 mii_mediachg(device_get_softc(sc->miibus));
1802
1803         ifp->if_flags |= IFF_RUNNING;
1804         ifp->if_flags &= ~IFF_OACTIVE;
1805
1806         /*
1807          * Enable interrupts.
1808          */
1809 #ifdef DEVICE_POLLING
1810         /*
1811          * ... but only do that if we are not polling. And because (presumably)
1812          * the default is interrupts on, we need to disable them explicitly!
1813          */
1814         if ( ifp->if_flags & IFF_POLLING )
1815                 CSR_WRITE_1(sc, FXP_CSR_SCB_INTRCNTL, FXP_SCB_INTR_DISABLE);
1816         else
1817 #endif /* DEVICE_POLLING */
1818         CSR_WRITE_1(sc, FXP_CSR_SCB_INTRCNTL, 0);
1819         splx(s);
1820
1821         /*
1822          * Start stats updater.
1823          */
1824         callout_reset(&sc->fxp_stat_timer, hz, fxp_tick, sc);
1825 }
1826
1827 static int
1828 fxp_serial_ifmedia_upd(struct ifnet *ifp)
1829 {
1830
1831         return (0);
1832 }
1833
1834 static void
1835 fxp_serial_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
1836 {
1837
1838         ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
1839 }
1840
1841 /*
1842  * Change media according to request.
1843  */
1844 static int
1845 fxp_ifmedia_upd(struct ifnet *ifp)
1846 {
1847         struct fxp_softc *sc = ifp->if_softc;
1848         struct mii_data *mii;
1849
1850         mii = device_get_softc(sc->miibus);
1851         mii_mediachg(mii);
1852         return (0);
1853 }
1854
1855 /*
1856  * Notify the world which media we're using.
1857  */
1858 static void
1859 fxp_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
1860 {
1861         struct fxp_softc *sc = ifp->if_softc;
1862         struct mii_data *mii;
1863
1864         mii = device_get_softc(sc->miibus);
1865         mii_pollstat(mii);
1866         ifmr->ifm_active = mii->mii_media_active;
1867         ifmr->ifm_status = mii->mii_media_status;
1868
1869         if (ifmr->ifm_status & IFM_10_T && sc->flags & FXP_FLAG_CU_RESUME_BUG)
1870                 sc->cu_resume_bug = 1;
1871         else
1872                 sc->cu_resume_bug = 0;
1873 }
1874
1875 /*
1876  * Add a buffer to the end of the RFA buffer list.
1877  * Return 0 if successful, 1 for failure. A failure results in
1878  * adding the 'oldm' (if non-NULL) on to the end of the list -
1879  * tossing out its old contents and recycling it.
1880  * The RFA struct is stuck at the beginning of mbuf cluster and the
1881  * data pointer is fixed up to point just past it.
1882  */
1883 static int
1884 fxp_add_rfabuf(struct fxp_softc *sc, struct mbuf *oldm)
1885 {
1886         u_int32_t v;
1887         struct mbuf *m;
1888         struct fxp_rfa *rfa, *p_rfa;
1889
1890         m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1891         if (m == NULL) { /* try to recycle the old mbuf instead */
1892                 if (oldm == NULL)
1893                         return 1;
1894                 m = oldm;
1895                 m->m_data = m->m_ext.ext_buf;
1896         }
1897
1898         /*
1899          * Move the data pointer up so that the incoming data packet
1900          * will be 32-bit aligned.
1901          */
1902         m->m_data += RFA_ALIGNMENT_FUDGE;
1903
1904         /*
1905          * Get a pointer to the base of the mbuf cluster and move
1906          * data start past it.
1907          */
1908         rfa = mtod(m, struct fxp_rfa *);
1909         m->m_data += sizeof(struct fxp_rfa);
1910         rfa->size = (u_int16_t)(MCLBYTES - sizeof(struct fxp_rfa) - RFA_ALIGNMENT_FUDGE);
1911
1912         /*
1913          * Initialize the rest of the RFA.  Note that since the RFA
1914          * is misaligned, we cannot store values directly.  Instead,
1915          * we use an optimized, inline copy.
1916          */
1917
1918         rfa->rfa_status = 0;
1919         rfa->rfa_control = FXP_RFA_CONTROL_EL;
1920         rfa->actual_size = 0;
1921
1922         v = -1;
1923         fxp_lwcopy(&v, (volatile u_int32_t *) rfa->link_addr);
1924         fxp_lwcopy(&v, (volatile u_int32_t *) rfa->rbd_addr);
1925
1926         /*
1927          * If there are other buffers already on the list, attach this
1928          * one to the end by fixing up the tail to point to this one.
1929          */
1930         if (sc->rfa_headm != NULL) {
1931                 p_rfa = (struct fxp_rfa *) (sc->rfa_tailm->m_ext.ext_buf +
1932                     RFA_ALIGNMENT_FUDGE);
1933                 sc->rfa_tailm->m_next = m;
1934                 v = vtophys(rfa);
1935                 fxp_lwcopy(&v, (volatile u_int32_t *) p_rfa->link_addr);
1936                 p_rfa->rfa_control = 0;
1937         } else {
1938                 sc->rfa_headm = m;
1939         }
1940         sc->rfa_tailm = m;
1941
1942         return (m == oldm);
1943 }
1944
1945 static volatile int
1946 fxp_miibus_readreg(device_t dev, int phy, int reg)
1947 {
1948         struct fxp_softc *sc = device_get_softc(dev);
1949         int count = 10000;
1950         int value;
1951
1952         CSR_WRITE_4(sc, FXP_CSR_MDICONTROL,
1953             (FXP_MDI_READ << 26) | (reg << 16) | (phy << 21));
1954
1955         while (((value = CSR_READ_4(sc, FXP_CSR_MDICONTROL)) & 0x10000000) == 0
1956             && count--)
1957                 DELAY(10);
1958
1959         if (count <= 0)
1960                 device_printf(dev, "fxp_miibus_readreg: timed out\n");
1961
1962         return (value & 0xffff);
1963 }
1964
1965 static void
1966 fxp_miibus_writereg(device_t dev, int phy, int reg, int value)
1967 {
1968         struct fxp_softc *sc = device_get_softc(dev);
1969         int count = 10000;
1970
1971         CSR_WRITE_4(sc, FXP_CSR_MDICONTROL,
1972             (FXP_MDI_WRITE << 26) | (reg << 16) | (phy << 21) |
1973             (value & 0xffff));
1974
1975         while ((CSR_READ_4(sc, FXP_CSR_MDICONTROL) & 0x10000000) == 0 &&
1976             count--)
1977                 DELAY(10);
1978
1979         if (count <= 0)
1980                 device_printf(dev, "fxp_miibus_writereg: timed out\n");
1981 }
1982
1983 static int
1984 fxp_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
1985 {
1986         struct fxp_softc *sc = ifp->if_softc;
1987         struct ifreq *ifr = (struct ifreq *)data;
1988         struct mii_data *mii;
1989         int s, error = 0;
1990
1991         s = splimp();
1992
1993         switch (command) {
1994         case SIOCSIFADDR:
1995         case SIOCGIFADDR:
1996         case SIOCSIFMTU:
1997                 error = ether_ioctl(ifp, command, data);
1998                 break;
1999
2000         case SIOCSIFFLAGS:
2001                 if (ifp->if_flags & IFF_ALLMULTI)
2002                         sc->flags |= FXP_FLAG_ALL_MCAST;
2003                 else
2004                         sc->flags &= ~FXP_FLAG_ALL_MCAST;
2005
2006                 /*
2007                  * If interface is marked up and not running, then start it.
2008                  * If it is marked down and running, stop it.
2009                  * XXX If it's up then re-initialize it. This is so flags
2010                  * such as IFF_PROMISC are handled.
2011                  */
2012                 if (ifp->if_flags & IFF_UP) {
2013                         fxp_init(sc);
2014                 } else {
2015                         if (ifp->if_flags & IFF_RUNNING)
2016                                 fxp_stop(sc);
2017                 }
2018                 break;
2019
2020         case SIOCADDMULTI:
2021         case SIOCDELMULTI:
2022                 if (ifp->if_flags & IFF_ALLMULTI)
2023                         sc->flags |= FXP_FLAG_ALL_MCAST;
2024                 else
2025                         sc->flags &= ~FXP_FLAG_ALL_MCAST;
2026                 /*
2027                  * Multicast list has changed; set the hardware filter
2028                  * accordingly.
2029                  */
2030                 if ((sc->flags & FXP_FLAG_ALL_MCAST) == 0)
2031                         fxp_mc_setup(sc);
2032                 /*
2033                  * fxp_mc_setup() can set FXP_FLAG_ALL_MCAST, so check it
2034                  * again rather than else {}.
2035                  */
2036                 if (sc->flags & FXP_FLAG_ALL_MCAST)
2037                         fxp_init(sc);
2038                 error = 0;
2039                 break;
2040
2041         case SIOCSIFMEDIA:
2042         case SIOCGIFMEDIA:
2043                 if (sc->miibus != NULL) {
2044                         mii = device_get_softc(sc->miibus);
2045                         error = ifmedia_ioctl(ifp, ifr,
2046                             &mii->mii_media, command);
2047                 } else {
2048                         error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, command);
2049                 }
2050                 break;
2051
2052         default:
2053                 error = EINVAL;
2054         }
2055         splx(s);
2056         return (error);
2057 }
2058
2059 /*
2060  * Fill in the multicast address list and return number of entries.
2061  */
2062 static int
2063 fxp_mc_addrs(struct fxp_softc *sc)
2064 {
2065         struct fxp_cb_mcs *mcsp = sc->mcsp;
2066         struct ifnet *ifp = &sc->sc_if;
2067         struct ifmultiaddr *ifma;
2068         int nmcasts;
2069
2070         nmcasts = 0;
2071         if ((sc->flags & FXP_FLAG_ALL_MCAST) == 0) {
2072 #if defined(__DragonFly__) || __FreeBSD_version < 500000
2073                 LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2074 #else
2075                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2076 #endif
2077                         if (ifma->ifma_addr->sa_family != AF_LINK)
2078                                 continue;
2079                         if (nmcasts >= MAXMCADDR) {
2080                                 sc->flags |= FXP_FLAG_ALL_MCAST;
2081                                 nmcasts = 0;
2082                                 break;
2083                         }
2084                         bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
2085                             (void *)(uintptr_t)(volatile void *)
2086                                 &sc->mcsp->mc_addr[nmcasts][0], 6);
2087                         nmcasts++;
2088                 }
2089         }
2090         mcsp->mc_cnt = nmcasts * 6;
2091         return (nmcasts);
2092 }
2093
2094 /*
2095  * Program the multicast filter.
2096  *
2097  * We have an artificial restriction that the multicast setup command
2098  * must be the first command in the chain, so we take steps to ensure
2099  * this. By requiring this, it allows us to keep up the performance of
2100  * the pre-initialized command ring (esp. link pointers) by not actually
2101  * inserting the mcsetup command in the ring - i.e. its link pointer
2102  * points to the TxCB ring, but the mcsetup descriptor itself is not part
2103  * of it. We then can do 'CU_START' on the mcsetup descriptor and have it
2104  * lead into the regular TxCB ring when it completes.
2105  *
2106  * This function must be called at splimp.
2107  */
2108 static void
2109 fxp_mc_setup(struct fxp_softc *sc)
2110 {
2111         struct fxp_cb_mcs *mcsp = sc->mcsp;
2112         struct ifnet *ifp = &sc->sc_if;
2113         int count;
2114
2115         /*
2116          * If there are queued commands, we must wait until they are all
2117          * completed. If we are already waiting, then add a NOP command
2118          * with interrupt option so that we're notified when all commands
2119          * have been completed - fxp_start() ensures that no additional
2120          * TX commands will be added when need_mcsetup is true.
2121          */
2122         if (sc->tx_queued) {
2123                 struct fxp_cb_tx *txp;
2124
2125                 /*
2126                  * need_mcsetup will be true if we are already waiting for the
2127                  * NOP command to be completed (see below). In this case, bail.
2128                  */
2129                 if (sc->need_mcsetup)
2130                         return;
2131                 sc->need_mcsetup = 1;
2132
2133                 /*
2134                  * Add a NOP command with interrupt so that we are notified
2135                  * when all TX commands have been processed.
2136                  */
2137                 txp = sc->cbl_last->next;
2138                 txp->mb_head = NULL;
2139                 txp->cb_status = 0;
2140                 txp->cb_command = FXP_CB_COMMAND_NOP |
2141                     FXP_CB_COMMAND_S | FXP_CB_COMMAND_I;
2142                 /*
2143                  * Advance the end of list forward.
2144                  */
2145                 sc->cbl_last->cb_command &= ~FXP_CB_COMMAND_S;
2146                 sc->cbl_last = txp;
2147                 sc->tx_queued++;
2148                 /*
2149                  * Issue a resume in case the CU has just suspended.
2150                  */
2151                 fxp_scb_wait(sc);
2152                 fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_RESUME);
2153                 /*
2154                  * Set a 5 second timer just in case we don't hear from the
2155                  * card again.
2156                  */
2157                 ifp->if_timer = 5;
2158
2159                 return;
2160         }
2161         sc->need_mcsetup = 0;
2162
2163         /*
2164          * Initialize multicast setup descriptor.
2165          */
2166         mcsp->next = sc->cbl_base;
2167         mcsp->mb_head = NULL;
2168         mcsp->cb_status = 0;
2169         mcsp->cb_command = FXP_CB_COMMAND_MCAS |
2170             FXP_CB_COMMAND_S | FXP_CB_COMMAND_I;
2171         mcsp->link_addr = vtophys(&sc->cbl_base->cb_status);
2172         (void) fxp_mc_addrs(sc);
2173         sc->cbl_first = sc->cbl_last = (struct fxp_cb_tx *) mcsp;
2174         sc->tx_queued = 1;
2175
2176         /*
2177          * Wait until command unit is not active. This should never
2178          * be the case when nothing is queued, but make sure anyway.
2179          */
2180         count = 100;
2181         while ((CSR_READ_1(sc, FXP_CSR_SCB_RUSCUS) >> 6) ==
2182             FXP_SCB_CUS_ACTIVE && --count)
2183                 DELAY(10);
2184         if (count == 0) {
2185                 device_printf(sc->dev, "command queue timeout\n");
2186                 return;
2187         }
2188
2189         /*
2190          * Start the multicast setup command.
2191          */
2192         fxp_scb_wait(sc);
2193         CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL, vtophys(&mcsp->cb_status));
2194         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_START);
2195
2196         ifp->if_timer = 2;
2197         return;
2198 }
2199
2200 static u_int32_t fxp_ucode_d101a[] = D101_A_RCVBUNDLE_UCODE;
2201 static u_int32_t fxp_ucode_d101b0[] = D101_B0_RCVBUNDLE_UCODE;
2202 static u_int32_t fxp_ucode_d101ma[] = D101M_B_RCVBUNDLE_UCODE;
2203 static u_int32_t fxp_ucode_d101s[] = D101S_RCVBUNDLE_UCODE;
2204 static u_int32_t fxp_ucode_d102[] = D102_B_RCVBUNDLE_UCODE;
2205 static u_int32_t fxp_ucode_d102c[] = D102_C_RCVBUNDLE_UCODE;
2206
2207 #define UCODE(x)        x, sizeof(x)
2208
2209 struct ucode {
2210         u_int32_t       revision;
2211         u_int32_t       *ucode;
2212         int             length;
2213         u_short         int_delay_offset;
2214         u_short         bundle_max_offset;
2215 } ucode_table[] = {
2216         { FXP_REV_82558_A4, UCODE(fxp_ucode_d101a), D101_CPUSAVER_DWORD, 0 },
2217         { FXP_REV_82558_B0, UCODE(fxp_ucode_d101b0), D101_CPUSAVER_DWORD, 0 },
2218         { FXP_REV_82559_A0, UCODE(fxp_ucode_d101ma),
2219             D101M_CPUSAVER_DWORD, D101M_CPUSAVER_BUNDLE_MAX_DWORD },
2220         { FXP_REV_82559S_A, UCODE(fxp_ucode_d101s),
2221             D101S_CPUSAVER_DWORD, D101S_CPUSAVER_BUNDLE_MAX_DWORD },
2222         { FXP_REV_82550, UCODE(fxp_ucode_d102),
2223             D102_B_CPUSAVER_DWORD, D102_B_CPUSAVER_BUNDLE_MAX_DWORD },
2224         { FXP_REV_82550_C, UCODE(fxp_ucode_d102c),
2225             D102_C_CPUSAVER_DWORD, D102_C_CPUSAVER_BUNDLE_MAX_DWORD },
2226         { 0, NULL, 0, 0, 0 }
2227 };
2228
2229 static void
2230 fxp_load_ucode(struct fxp_softc *sc)
2231 {
2232         struct ucode *uc;
2233         struct fxp_cb_ucode *cbp;
2234
2235         for (uc = ucode_table; uc->ucode != NULL; uc++)
2236                 if (sc->revision == uc->revision)
2237                         break;
2238         if (uc->ucode == NULL)
2239                 return;
2240         cbp = (struct fxp_cb_ucode *)sc->cbl_base;
2241         cbp->cb_status = 0;
2242         cbp->cb_command = FXP_CB_COMMAND_UCODE | FXP_CB_COMMAND_EL;
2243         cbp->link_addr = -1;            /* (no) next command */
2244         memcpy(cbp->ucode, uc->ucode, uc->length);
2245         if (uc->int_delay_offset)
2246                 *(u_short *)&cbp->ucode[uc->int_delay_offset] =
2247                     sc->tunable_int_delay + sc->tunable_int_delay / 2;
2248         if (uc->bundle_max_offset)
2249                 *(u_short *)&cbp->ucode[uc->bundle_max_offset] =
2250                     sc->tunable_bundle_max;
2251         /*
2252          * Download the ucode to the chip.
2253          */
2254         fxp_scb_wait(sc);
2255         CSR_WRITE_4(sc, FXP_CSR_SCB_GENERAL, vtophys(&cbp->cb_status));
2256         fxp_scb_cmd(sc, FXP_SCB_COMMAND_CU_START);
2257         /* ...and wait for it to complete. */
2258         fxp_dma_wait(&cbp->cb_status, sc);
2259         device_printf(sc->dev,
2260             "Microcode loaded, int_delay: %d usec  bundle_max: %d\n",
2261             sc->tunable_int_delay, 
2262             uc->bundle_max_offset == 0 ? 0 : sc->tunable_bundle_max);
2263         sc->flags |= FXP_FLAG_UCODE;
2264 }
2265
2266 static int
2267 sysctl_int_range(SYSCTL_HANDLER_ARGS, int low, int high)
2268 {
2269         int error, value;
2270
2271         value = *(int *)arg1;
2272         error = sysctl_handle_int(oidp, &value, 0, req);
2273         if (error || !req->newptr)
2274                 return (error);
2275         if (value < low || value > high)
2276                 return (EINVAL);
2277         *(int *)arg1 = value;
2278         return (0);
2279 }
2280
2281 /*
2282  * Interrupt delay is expressed in microseconds, a multiplier is used
2283  * to convert this to the appropriate clock ticks before using. 
2284  */
2285 static int
2286 sysctl_hw_fxp_int_delay(SYSCTL_HANDLER_ARGS)
2287 {
2288         return (sysctl_int_range(oidp, arg1, arg2, req, 300, 3000));
2289 }
2290
2291 static int
2292 sysctl_hw_fxp_bundle_max(SYSCTL_HANDLER_ARGS)
2293 {
2294         return (sysctl_int_range(oidp, arg1, arg2, req, 1, 0xffff));
2295 }