Rework DMA stuffs' allocation/free
[dragonfly.git] / sys / dev / netif / re / if_re.c
1 /*
2  * Copyright (c) 2004
3  *      Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
4  *
5  * Copyright (c) 1997, 1998-2003
6  *      Bill Paul <wpaul@windriver.com>.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Bill Paul.
19  * 4. Neither the name of the author nor the names of any co-contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
33  * THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  * $FreeBSD: src/sys/dev/re/if_re.c,v 1.25 2004/06/09 14:34:01 naddy Exp $
36  * $DragonFly: src/sys/dev/netif/re/if_re.c,v 1.55 2008/10/03 07:52:26 sephe Exp $
37  */
38
39 /*
40  * RealTek 8139C+/8169/8169S/8110S/8168/8111/8101E PCI NIC driver
41  *
42  * Written by Bill Paul <wpaul@windriver.com>
43  * Senior Networking Software Engineer
44  * Wind River Systems
45  */
46
47 /*
48  * This driver is designed to support RealTek's next generation of
49  * 10/100 and 10/100/1000 PCI ethernet controllers. There are currently
50  * seven devices in this family: the RTL8139C+, the RTL8169, the RTL8169S,
51  * RTL8110S, the RTL8168, the RTL8111 and the RTL8101E.
52  *
53  * The 8139C+ is a 10/100 ethernet chip. It is backwards compatible
54  * with the older 8139 family, however it also supports a special
55  * C+ mode of operation that provides several new performance enhancing
56  * features. These include:
57  *
58  *      o Descriptor based DMA mechanism. Each descriptor represents
59  *        a single packet fragment. Data buffers may be aligned on
60  *        any byte boundary.
61  *
62  *      o 64-bit DMA
63  *
64  *      o TCP/IP checksum offload for both RX and TX
65  *
66  *      o High and normal priority transmit DMA rings
67  *
68  *      o VLAN tag insertion and extraction
69  *
70  *      o TCP large send (segmentation offload)
71  *
72  * Like the 8139, the 8139C+ also has a built-in 10/100 PHY. The C+
73  * programming API is fairly straightforward. The RX filtering, EEPROM
74  * access and PHY access is the same as it is on the older 8139 series
75  * chips.
76  *
77  * The 8169 is a 64-bit 10/100/1000 gigabit ethernet MAC. It has almost the
78  * same programming API and feature set as the 8139C+ with the following
79  * differences and additions:
80  *
81  *      o 1000Mbps mode
82  *
83  *      o Jumbo frames
84  *
85  *      o GMII and TBI ports/registers for interfacing with copper
86  *        or fiber PHYs
87  *
88  *      o RX and TX DMA rings can have up to 1024 descriptors
89  *        (the 8139C+ allows a maximum of 64)
90  *
91  *      o Slight differences in register layout from the 8139C+
92  *
93  * The TX start and timer interrupt registers are at different locations
94  * on the 8169 than they are on the 8139C+. Also, the status word in the
95  * RX descriptor has a slightly different bit layout. The 8169 does not
96  * have a built-in PHY. Most reference boards use a Marvell 88E1000 'Alaska'
97  * copper gigE PHY.
98  *
99  * The 8169S/8110S 10/100/1000 devices have built-in copper gigE PHYs
100  * (the 'S' stands for 'single-chip'). These devices have the same
101  * programming API as the older 8169, but also have some vendor-specific
102  * registers for the on-board PHY. The 8110S is a LAN-on-motherboard
103  * part designed to be pin-compatible with the RealTek 8100 10/100 chip.
104  * 
105  * This driver takes advantage of the RX and TX checksum offload and
106  * VLAN tag insertion/extraction features. It also implements TX
107  * interrupt moderation using the timer interrupt registers, which
108  * significantly reduces TX interrupt load. There is also support
109  * for jumbo frames, however the 8169/8169S/8110S can not transmit
110  * jumbo frames larger than 7440, so the max MTU possible with this
111  * driver is 7422 bytes.
112  */
113
114 #include "opt_polling.h"
115
116 #include <sys/param.h>
117 #include <sys/bus.h>
118 #include <sys/endian.h>
119 #include <sys/kernel.h>
120 #include <sys/interrupt.h>
121 #include <sys/malloc.h>
122 #include <sys/mbuf.h>
123 #include <sys/rman.h>
124 #include <sys/serialize.h>
125 #include <sys/socket.h>
126 #include <sys/sockio.h>
127 #include <sys/sysctl.h>
128
129 #include <net/bpf.h>
130 #include <net/ethernet.h>
131 #include <net/if.h>
132 #include <net/ifq_var.h>
133 #include <net/if_arp.h>
134 #include <net/if_dl.h>
135 #include <net/if_media.h>
136 #include <net/if_types.h>
137 #include <net/vlan/if_vlan_var.h>
138 #include <net/vlan/if_vlan_ether.h>
139
140 #include <dev/netif/mii_layer/mii.h>
141 #include <dev/netif/mii_layer/miivar.h>
142
143 #include <bus/pci/pcidevs.h>
144 #include <bus/pci/pcireg.h>
145 #include <bus/pci/pcivar.h>
146
147 /* "device miibus" required.  See GENERIC if you get errors here. */
148 #include "miibus_if.h"
149
150 #include <dev/netif/re/if_rereg.h>
151 #include <dev/netif/re/if_revar.h>
152
153 #define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
154 #if 0
155 #define RE_DISABLE_HWCSUM
156 #endif
157
158 /*
159  * Various supported device vendors/types and their names.
160  */
161 static const struct re_type re_devs[] = {
162         { PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DGE528T, RE_HWREV_8169S,
163                 "D-Link DGE-528(T) Gigabit Ethernet Adapter" },
164         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139, RE_HWREV_8139CPLUS,
165                 "RealTek 8139C+ 10/100BaseTX" },
166         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E, RE_HWREV_8101E,
167                 "RealTek 8101E PCIe 10/100baseTX" },
168         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E, RE_HWREV_8102EL,
169                 "RealTek 8102EL PCIe 10/100baseTX" },
170         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN1,
171                 "RealTek 8168/8111B PCIe Gigabit Ethernet" },
172         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN2,
173                 "RealTek 8168/8111B PCIe Gigabit Ethernet" },
174         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168_SPIN3,
175                 "RealTek 8168B/8111B PCIe Gigabit Ethernet" },
176         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168, RE_HWREV_8168C,
177                 "RealTek 8168C/8111C PCIe Gigabit Ethernet" },
178         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169,
179                 "RealTek 8169 Gigabit Ethernet" },
180         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169S,
181                 "RealTek 8169S Single-chip Gigabit Ethernet" },
182         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169_8110SB,
183                 "RealTek 8169SB/8110SB Single-chip Gigabit Ethernet" },
184         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8169_8110SC,
185                 "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
186         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169SC, RE_HWREV_8169_8110SC,
187                 "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
188         { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169, RE_HWREV_8110S,
189                 "RealTek 8110S Single-chip Gigabit Ethernet" },
190         { PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CG_LAPCIGT, RE_HWREV_8169S,
191                 "Corega CG-LAPCIGT Gigabit Ethernet" },
192         { PCI_VENDOR_LINKSYS, PCI_PRODUCT_LINKSYS_EG1032, RE_HWREV_8169S,
193                 "Linksys EG1032 Gigabit Ethernet" },
194         { PCI_VENDOR_USR2, PCI_PRODUCT_USR2_997902, RE_HWREV_8169S,
195                 "US Robotics 997902 Gigabit Ethernet" },
196         { 0, 0, 0, NULL }
197 };
198
199 static const struct re_hwrev re_hwrevs[] = {
200         { RE_HWREV_8139CPLUS,   RE_8139CPLUS,   RE_F_HASMPC,    "C+" },
201         { RE_HWREV_8168_SPIN1,  RE_8169,        RE_F_PCIE,      "8168" },
202         { RE_HWREV_8168_SPIN2,  RE_8169,        RE_F_PCIE,      "8168" },
203         { RE_HWREV_8168_SPIN3,  RE_8169,        RE_F_PCIE,      "8168" },
204         { RE_HWREV_8168C,       RE_8169,        RE_F_PCIE,      "8168C" },
205         { RE_HWREV_8169,        RE_8169,        RE_F_HASMPC,    "8169" },
206         { RE_HWREV_8169S,       RE_8169,        RE_F_HASMPC,    "8169S" },
207         { RE_HWREV_8110S,       RE_8169,        RE_F_HASMPC,    "8110S" },
208         { RE_HWREV_8169_8110SB, RE_8169,        RE_F_HASMPC,    "8169SB" },
209         { RE_HWREV_8169_8110SC, RE_8169,        0,              "8169SC" },
210         { RE_HWREV_8100E,       RE_8169,        RE_F_HASMPC,    "8100E" },
211         { RE_HWREV_8101E,       RE_8169,        RE_F_PCIE,      "8101E" },
212         { RE_HWREV_8102EL,      RE_8169,        RE_F_PCIE,      "8102EL" },
213         { 0, 0, 0, NULL }
214 };
215
216 static int      re_probe(device_t);
217 static int      re_attach(device_t);
218 static int      re_detach(device_t);
219 static int      re_suspend(device_t);
220 static int      re_resume(device_t);
221 static void     re_shutdown(device_t);
222
223 static void     re_dma_map_addr(void *, bus_dma_segment_t *, int, int);
224 static void     re_dma_map_desc(void *, bus_dma_segment_t *, int,
225                                 bus_size_t, int);
226 static int      re_allocmem(device_t);
227 static void     re_freemem(device_t);
228 static void     re_freebufmem(struct re_softc *, int, int);
229 static int      re_encap(struct re_softc *, struct mbuf **, int *);
230 static int      re_newbuf(struct re_softc *, int, int);
231 static void     re_setup_rxdesc(struct re_softc *, int);
232 static int      re_rx_list_init(struct re_softc *);
233 static int      re_tx_list_init(struct re_softc *);
234 static void     re_rxeof(struct re_softc *);
235 static void     re_txeof(struct re_softc *);
236 static void     re_intr(void *);
237 static void     re_tick(void *);
238 static void     re_tick_serialized(void *);
239
240 static void     re_start(struct ifnet *);
241 static int      re_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
242 static void     re_init(void *);
243 static void     re_stop(struct re_softc *);
244 static void     re_watchdog(struct ifnet *);
245 static int      re_ifmedia_upd(struct ifnet *);
246 static void     re_ifmedia_sts(struct ifnet *, struct ifmediareq *);
247
248 static void     re_eeprom_putbyte(struct re_softc *, int);
249 static void     re_eeprom_getword(struct re_softc *, int, u_int16_t *);
250 static void     re_read_eeprom(struct re_softc *, caddr_t, int, int);
251 static int      re_gmii_readreg(device_t, int, int);
252 static int      re_gmii_writereg(device_t, int, int, int);
253
254 static int      re_miibus_readreg(device_t, int, int);
255 static int      re_miibus_writereg(device_t, int, int, int);
256 static void     re_miibus_statchg(device_t);
257
258 static void     re_setmulti(struct re_softc *);
259 static void     re_reset(struct re_softc *);
260 static int      re_pad_frame(struct mbuf *);
261
262 #ifdef RE_DIAG
263 static int      re_diag(struct re_softc *);
264 #endif
265
266 #ifdef DEVICE_POLLING
267 static void     re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
268 #endif
269
270 static int      re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS);
271
272 static device_method_t re_methods[] = {
273         /* Device interface */
274         DEVMETHOD(device_probe,         re_probe),
275         DEVMETHOD(device_attach,        re_attach),
276         DEVMETHOD(device_detach,        re_detach),
277         DEVMETHOD(device_suspend,       re_suspend),
278         DEVMETHOD(device_resume,        re_resume),
279         DEVMETHOD(device_shutdown,      re_shutdown),
280
281         /* bus interface */
282         DEVMETHOD(bus_print_child,      bus_generic_print_child),
283         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
284
285         /* MII interface */
286         DEVMETHOD(miibus_readreg,       re_miibus_readreg),
287         DEVMETHOD(miibus_writereg,      re_miibus_writereg),
288         DEVMETHOD(miibus_statchg,       re_miibus_statchg),
289
290         { 0, 0 }
291 };
292
293 static driver_t re_driver = {
294         "re",
295         re_methods,
296         sizeof(struct re_softc)
297 };
298
299 static devclass_t re_devclass;
300
301 DECLARE_DUMMY_MODULE(if_re);
302 DRIVER_MODULE(if_re, pci, re_driver, re_devclass, 0, 0);
303 DRIVER_MODULE(if_re, cardbus, re_driver, re_devclass, 0, 0);
304 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
305
306 #define EE_SET(x)       \
307         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) | (x))
308
309 #define EE_CLR(x)       \
310         CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) & ~(x))
311
312 /*
313  * Send a read command and address to the EEPROM, check for ACK.
314  */
315 static void
316 re_eeprom_putbyte(struct re_softc *sc, int addr)
317 {
318         int d, i;
319
320         d = addr | (RE_9346_READ << sc->re_eewidth);
321
322         /*
323          * Feed in each bit and strobe the clock.
324          */
325         for (i = 1 << (sc->re_eewidth + 3); i; i >>= 1) {
326                 if (d & i)
327                         EE_SET(RE_EE_DATAIN);
328                 else
329                         EE_CLR(RE_EE_DATAIN);
330                 DELAY(100);
331                 EE_SET(RE_EE_CLK);
332                 DELAY(150);
333                 EE_CLR(RE_EE_CLK);
334                 DELAY(100);
335         }
336 }
337
338 /*
339  * Read a word of data stored in the EEPROM at address 'addr.'
340  */
341 static void
342 re_eeprom_getword(struct re_softc *sc, int addr, uint16_t *dest)
343 {
344         int i;
345         uint16_t word = 0;
346
347         /*
348          * Send address of word we want to read.
349          */
350         re_eeprom_putbyte(sc, addr);
351
352         /*
353          * Start reading bits from EEPROM.
354          */
355         for (i = 0x8000; i != 0; i >>= 1) {
356                 EE_SET(RE_EE_CLK);
357                 DELAY(100);
358                 if (CSR_READ_1(sc, RE_EECMD) & RE_EE_DATAOUT)
359                         word |= i;
360                 EE_CLR(RE_EE_CLK);
361                 DELAY(100);
362         }
363
364         *dest = word;
365 }
366
367 /*
368  * Read a sequence of words from the EEPROM.
369  */
370 static void
371 re_read_eeprom(struct re_softc *sc, caddr_t dest, int off, int cnt)
372 {
373         int i;
374         uint16_t word = 0, *ptr;
375
376         CSR_SETBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
377         DELAY(100);
378
379         for (i = 0; i < cnt; i++) {
380                 CSR_SETBIT_1(sc, RE_EECMD, RE_EE_SEL);
381                 re_eeprom_getword(sc, off + i, &word);
382                 CSR_CLRBIT_1(sc, RE_EECMD, RE_EE_SEL);
383                 ptr = (uint16_t *)(dest + (i * 2));
384                 *ptr = word;
385         }
386
387         CSR_CLRBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
388 }
389
390 static int
391 re_gmii_readreg(device_t dev, int phy, int reg)
392 {
393         struct re_softc *sc = device_get_softc(dev);
394         u_int32_t rval;
395         int i;
396
397         if (phy != 1)
398                 return(0);
399
400         /* Let the rgephy driver read the GMEDIASTAT register */
401
402         if (reg == RE_GMEDIASTAT)
403                 return(CSR_READ_1(sc, RE_GMEDIASTAT));
404
405         CSR_WRITE_4(sc, RE_PHYAR, reg << 16);
406         DELAY(1000);
407
408         for (i = 0; i < RE_TIMEOUT; i++) {
409                 rval = CSR_READ_4(sc, RE_PHYAR);
410                 if (rval & RE_PHYAR_BUSY)
411                         break;
412                 DELAY(100);
413         }
414
415         if (i == RE_TIMEOUT) {
416                 device_printf(dev, "PHY read failed\n");
417                 return(0);
418         }
419
420         return(rval & RE_PHYAR_PHYDATA);
421 }
422
423 static int
424 re_gmii_writereg(device_t dev, int phy, int reg, int data)
425 {
426         struct re_softc *sc = device_get_softc(dev);
427         uint32_t rval;
428         int i;
429
430         CSR_WRITE_4(sc, RE_PHYAR,
431                     (reg << 16) | (data & RE_PHYAR_PHYDATA) | RE_PHYAR_BUSY);
432         DELAY(1000);
433
434         for (i = 0; i < RE_TIMEOUT; i++) {
435                 rval = CSR_READ_4(sc, RE_PHYAR);
436                 if ((rval & RE_PHYAR_BUSY) == 0)
437                         break;
438                 DELAY(100);
439         }
440
441         if (i == RE_TIMEOUT)
442                 device_printf(dev, "PHY write failed\n");
443
444         return(0);
445 }
446
447 static int
448 re_miibus_readreg(device_t dev, int phy, int reg)
449 {
450         struct re_softc *sc = device_get_softc(dev);
451         uint16_t rval = 0;
452         uint16_t re8139_reg = 0;
453
454         if (sc->re_type == RE_8169) {
455                 rval = re_gmii_readreg(dev, phy, reg);
456                 return(rval);
457         }
458
459         /* Pretend the internal PHY is only at address 0 */
460         if (phy)
461                 return(0);
462
463         switch(reg) {
464         case MII_BMCR:
465                 re8139_reg = RE_BMCR;
466                 break;
467         case MII_BMSR:
468                 re8139_reg = RE_BMSR;
469                 break;
470         case MII_ANAR:
471                 re8139_reg = RE_ANAR;
472                 break;
473         case MII_ANER:
474                 re8139_reg = RE_ANER;
475                 break;
476         case MII_ANLPAR:
477                 re8139_reg = RE_LPAR;
478                 break;
479         case MII_PHYIDR1:
480         case MII_PHYIDR2:
481                 return(0);
482         /*
483          * Allow the rlphy driver to read the media status
484          * register. If we have a link partner which does not
485          * support NWAY, this is the register which will tell
486          * us the results of parallel detection.
487          */
488         case RE_MEDIASTAT:
489                 return(CSR_READ_1(sc, RE_MEDIASTAT));
490         default:
491                 device_printf(dev, "bad phy register\n");
492                 return(0);
493         }
494         rval = CSR_READ_2(sc, re8139_reg);
495         if (sc->re_type == RE_8139CPLUS && re8139_reg == RE_BMCR) {
496                 /* 8139C+ has different bit layout. */
497                 rval &= ~(BMCR_LOOP | BMCR_ISO);
498         }
499         return(rval);
500 }
501
502 static int
503 re_miibus_writereg(device_t dev, int phy, int reg, int data)
504 {
505         struct re_softc *sc= device_get_softc(dev);
506         u_int16_t re8139_reg = 0;
507
508         if (sc->re_type == RE_8169)
509                 return(re_gmii_writereg(dev, phy, reg, data));
510
511         /* Pretend the internal PHY is only at address 0 */
512         if (phy)
513                 return(0);
514
515         switch(reg) {
516         case MII_BMCR:
517                 re8139_reg = RE_BMCR;
518                 if (sc->re_type == RE_8139CPLUS) {
519                         /* 8139C+ has different bit layout. */
520                         data &= ~(BMCR_LOOP | BMCR_ISO);
521                 }
522                 break;
523         case MII_BMSR:
524                 re8139_reg = RE_BMSR;
525                 break;
526         case MII_ANAR:
527                 re8139_reg = RE_ANAR;
528                 break;
529         case MII_ANER:
530                 re8139_reg = RE_ANER;
531                 break;
532         case MII_ANLPAR:
533                 re8139_reg = RE_LPAR;
534                 break;
535         case MII_PHYIDR1:
536         case MII_PHYIDR2:
537                 return(0);
538         default:
539                 device_printf(dev, "bad phy register\n");
540                 return(0);
541         }
542         CSR_WRITE_2(sc, re8139_reg, data);
543         return(0);
544 }
545
546 static void
547 re_miibus_statchg(device_t dev)
548 {
549 }
550
551 /*
552  * Program the 64-bit multicast hash filter.
553  */
554 static void
555 re_setmulti(struct re_softc *sc)
556 {
557         struct ifnet *ifp = &sc->arpcom.ac_if;
558         int h = 0;
559         uint32_t hashes[2] = { 0, 0 };
560         struct ifmultiaddr *ifma;
561         uint32_t rxfilt;
562         int mcnt = 0;
563
564         rxfilt = CSR_READ_4(sc, RE_RXCFG);
565
566         if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) {
567                 rxfilt |= RE_RXCFG_RX_MULTI;
568                 CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
569                 CSR_WRITE_4(sc, RE_MAR0, 0xFFFFFFFF);
570                 CSR_WRITE_4(sc, RE_MAR4, 0xFFFFFFFF);
571                 return;
572         }
573
574         /* first, zot all the existing hash bits */
575         CSR_WRITE_4(sc, RE_MAR0, 0);
576         CSR_WRITE_4(sc, RE_MAR4, 0);
577
578         /* now program new ones */
579         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
580                 if (ifma->ifma_addr->sa_family != AF_LINK)
581                         continue;
582                 h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
583                     ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
584                 if (h < 32)
585                         hashes[0] |= (1 << h);
586                 else
587                         hashes[1] |= (1 << (h - 32));
588                 mcnt++;
589         }
590
591         if (mcnt)
592                 rxfilt |= RE_RXCFG_RX_MULTI;
593         else
594                 rxfilt &= ~RE_RXCFG_RX_MULTI;
595
596         CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
597
598         /*
599          * For some unfathomable reason, RealTek decided to reverse
600          * the order of the multicast hash registers in the PCI Express
601          * parts. This means we have to write the hash pattern in reverse
602          * order for those devices.
603          */
604         if (sc->re_flags & RE_F_PCIE) {
605                 CSR_WRITE_4(sc, RE_MAR0, bswap32(hashes[0]));
606                 CSR_WRITE_4(sc, RE_MAR4, bswap32(hashes[1]));
607         } else {
608                 CSR_WRITE_4(sc, RE_MAR0, hashes[0]);
609                 CSR_WRITE_4(sc, RE_MAR4, hashes[1]);
610         }
611 }
612
613 static void
614 re_reset(struct re_softc *sc)
615 {
616         int i;
617
618         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_RESET);
619
620         for (i = 0; i < RE_TIMEOUT; i++) {
621                 DELAY(10);
622                 if ((CSR_READ_1(sc, RE_COMMAND) & RE_CMD_RESET) == 0)
623                         break;
624         }
625         if (i == RE_TIMEOUT)
626                 if_printf(&sc->arpcom.ac_if, "reset never completed!\n");
627
628         CSR_WRITE_1(sc, 0x82, 1);
629 }
630
631 #ifdef RE_DIAG
632 /*
633  * The following routine is designed to test for a defect on some
634  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
635  * lines connected to the bus, however for a 32-bit only card, they
636  * should be pulled high. The result of this defect is that the
637  * NIC will not work right if you plug it into a 64-bit slot: DMA
638  * operations will be done with 64-bit transfers, which will fail
639  * because the 64-bit data lines aren't connected.
640  *
641  * There's no way to work around this (short of talking a soldering
642  * iron to the board), however we can detect it. The method we use
643  * here is to put the NIC into digital loopback mode, set the receiver
644  * to promiscuous mode, and then try to send a frame. We then compare
645  * the frame data we sent to what was received. If the data matches,
646  * then the NIC is working correctly, otherwise we know the user has
647  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
648  * slot. In the latter case, there's no way the NIC can work correctly,
649  * so we print out a message on the console and abort the device attach.
650  */
651
652 static int
653 re_diag(struct re_softc *sc)
654 {
655         struct ifnet *ifp = &sc->arpcom.ac_if;
656         struct mbuf *m0;
657         struct ether_header *eh;
658         struct re_desc *cur_rx;
659         uint16_t status;
660         uint32_t rxstat;
661         int total_len, i, error = 0, phyaddr;
662         uint8_t dst[ETHER_ADDR_LEN] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
663         uint8_t src[ETHER_ADDR_LEN] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
664
665         /* Allocate a single mbuf */
666
667         MGETHDR(m0, MB_DONTWAIT, MT_DATA);
668         if (m0 == NULL)
669                 return(ENOBUFS);
670
671         /*
672          * Initialize the NIC in test mode. This sets the chip up
673          * so that it can send and receive frames, but performs the
674          * following special functions:
675          * - Puts receiver in promiscuous mode
676          * - Enables digital loopback mode
677          * - Leaves interrupts turned off
678          */
679
680         ifp->if_flags |= IFF_PROMISC;
681         sc->re_testmode = 1;
682         re_reset(sc);
683         re_init(sc);
684         sc->re_link = 1;
685         if (sc->re_type == RE_8169)
686                 phyaddr = 1;
687         else
688                 phyaddr = 0;
689
690         re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_RESET);
691         for (i = 0; i < RE_TIMEOUT; i++) {
692                 status = re_miibus_readreg(sc->re_dev, phyaddr, MII_BMCR);
693                 if (!(status & BMCR_RESET))
694                         break;
695         }
696
697         re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_LOOP);
698         CSR_WRITE_2(sc, RE_ISR, RE_INTRS_DIAG);
699
700         DELAY(100000);
701
702         /* Put some data in the mbuf */
703
704         eh = mtod(m0, struct ether_header *);
705         bcopy (dst, eh->ether_dhost, ETHER_ADDR_LEN);
706         bcopy (src, eh->ether_shost, ETHER_ADDR_LEN);
707         eh->ether_type = htons(ETHERTYPE_IP);
708         m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
709
710         /*
711          * Queue the packet, start transmission.
712          * Note: ifq_handoff() ultimately calls re_start() for us.
713          */
714
715         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
716         error = ifq_handoff(ifp, m0, NULL);
717         if (error) {
718                 m0 = NULL;
719                 goto done;
720         }
721         m0 = NULL;
722
723         /* Wait for it to propagate through the chip */
724
725         DELAY(100000);
726         for (i = 0; i < RE_TIMEOUT; i++) {
727                 status = CSR_READ_2(sc, RE_ISR);
728                 CSR_WRITE_2(sc, RE_ISR, status);
729                 if ((status & (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK)) ==
730                     (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK))
731                         break;
732                 DELAY(10);
733         }
734
735         if (i == RE_TIMEOUT) {
736                 if_printf(ifp, "diagnostic failed to receive packet "
737                           "in loopback mode\n");
738                 error = EIO;
739                 goto done;
740         }
741
742         /*
743          * The packet should have been dumped into the first
744          * entry in the RX DMA ring. Grab it from there.
745          */
746
747         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
748                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
749         bus_dmamap_sync(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0],
750                         BUS_DMASYNC_POSTWRITE);
751         bus_dmamap_unload(sc->re_ldata.re_mtag, sc->re_ldata.re_rx_dmamap[0]);
752
753         m0 = sc->re_ldata.re_rx_mbuf[0];
754         sc->re_ldata.re_rx_mbuf[0] = NULL;
755         eh = mtod(m0, struct ether_header *);
756
757         cur_rx = &sc->re_ldata.re_rx_list[0];
758         total_len = RE_RXBYTES(cur_rx);
759         rxstat = le32toh(cur_rx->re_cmdstat);
760
761         if (total_len != ETHER_MIN_LEN) {
762                 if_printf(ifp, "diagnostic failed, received short packet\n");
763                 error = EIO;
764                 goto done;
765         }
766
767         /* Test that the received packet data matches what we sent. */
768
769         if (bcmp(eh->ether_dhost, dst, ETHER_ADDR_LEN) ||
770             bcmp(eh->ether_shost, &src, ETHER_ADDR_LEN) ||
771             be16toh(eh->ether_type) != ETHERTYPE_IP) {
772                 if_printf(ifp, "WARNING, DMA FAILURE!\n");
773                 if_printf(ifp, "expected TX data: %6D/%6D/0x%x\n",
774                     dst, ":", src, ":", ETHERTYPE_IP);
775                 if_printf(ifp, "received RX data: %6D/%6D/0x%x\n",
776                     eh->ether_dhost, ":",  eh->ether_shost, ":",
777                     ntohs(eh->ether_type));
778                 if_printf(ifp, "You may have a defective 32-bit NIC plugged "
779                     "into a 64-bit PCI slot.\n");
780                 if_printf(ifp, "Please re-install the NIC in a 32-bit slot "
781                     "for proper operation.\n");
782                 if_printf(ifp, "Read the re(4) man page for more details.\n");
783                 error = EIO;
784         }
785
786 done:
787         /* Turn interface off, release resources */
788
789         sc->re_testmode = 0;
790         sc->re_link = 0;
791         ifp->if_flags &= ~IFF_PROMISC;
792         re_stop(sc);
793         if (m0 != NULL)
794                 m_freem(m0);
795
796         return (error);
797 }
798 #endif  /* RE_DIAG */
799
800 /*
801  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
802  * IDs against our list and return a device name if we find a match.
803  */
804 static int
805 re_probe(device_t dev)
806 {
807         const struct re_type *t;
808         struct re_softc *sc;
809         int rid;
810         uint32_t hwrev;
811         uint16_t vendor, product;
812
813         vendor = pci_get_vendor(dev);
814         product = pci_get_device(dev);
815
816         /*
817          * Only attach to rev.3 of the Linksys EG1032 adapter.
818          * Rev.2 is supported by sk(4).
819          */
820         if (vendor == PCI_VENDOR_LINKSYS &&
821             product == PCI_PRODUCT_LINKSYS_EG1032 &&
822             pci_get_subdevice(dev) != PCI_SUBDEVICE_LINKSYS_EG1032_REV3)
823                         return ENXIO;
824
825         for (t = re_devs; t->re_name != NULL; t++) {
826                 if (product == t->re_did && vendor == t->re_vid)
827                         break;
828         }
829
830         /*
831          * Check if we found a RealTek device.
832          */
833         if (t->re_name == NULL)
834                 return(ENXIO);
835
836         /*
837          * Temporarily map the I/O space so we can read the chip ID register.
838          */
839         sc = kmalloc(sizeof(*sc), M_TEMP, M_WAITOK | M_ZERO);
840         rid = RE_PCI_LOIO;
841         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
842                                             RF_ACTIVE);
843         if (sc->re_res == NULL) {
844                 device_printf(dev, "couldn't map ports/memory\n");
845                 kfree(sc, M_TEMP);
846                 return(ENXIO);
847         }
848
849         sc->re_btag = rman_get_bustag(sc->re_res);
850         sc->re_bhandle = rman_get_bushandle(sc->re_res);
851
852         hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
853         bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO, sc->re_res);
854         kfree(sc, M_TEMP);
855
856         /*
857          * and continue matching for the specific chip...
858          */
859         for (; t->re_name != NULL; t++) {
860                 if (product == t->re_did && vendor == t->re_vid &&
861                     t->re_basetype == hwrev) {
862                         device_set_desc(dev, t->re_name);
863                         return(0);
864                 }
865         }
866
867         if (bootverbose)
868                 kprintf("re: unknown hwrev %#x\n", hwrev);
869         return(ENXIO);
870 }
871
872 static void
873 re_dma_map_desc(void *xarg, bus_dma_segment_t *segs, int nsegs,
874                 bus_size_t mapsize, int error)
875 {
876         struct re_dmaload_arg *arg = xarg;
877         int i;
878
879         if (error)
880                 return;
881
882         if (nsegs > arg->re_nsegs) {
883                 arg->re_nsegs = 0;
884                 return;
885         }
886
887         arg->re_nsegs = nsegs;
888         for (i = 0; i < nsegs; ++i)
889                 arg->re_segs[i] = segs[i];
890 }
891
892 /*
893  * Map a single buffer address.
894  */
895
896 static void
897 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
898 {
899         uint32_t *addr;
900
901         if (error)
902                 return;
903
904         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
905         addr = arg;
906         *addr = segs->ds_addr;
907 }
908
909 static int
910 re_allocmem(device_t dev)
911 {
912         struct re_softc *sc = device_get_softc(dev);
913         int error, i;
914
915         /*
916          * Allocate the parent bus DMA tag appropriate for PCI.
917          */
918         error = bus_dma_tag_create(NULL,        /* parent */
919                         1, 0,                   /* alignment, boundary */
920                         BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
921                         BUS_SPACE_MAXADDR,      /* highaddr */
922                         NULL, NULL,             /* filter, filterarg */
923                         MAXBSIZE, RE_MAXSEGS,   /* maxsize, nsegments */
924                         BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
925                         BUS_DMA_ALLOCNOW,       /* flags */
926                         &sc->re_parent_tag);
927         if (error) {
928                 device_printf(dev, "could not allocate parent dma tag\n");
929                 return error;
930         }
931
932         /* Allocate tag for TX descriptor list. */
933         error = bus_dma_tag_create(sc->re_parent_tag,
934                         RE_RING_ALIGN, 0,
935                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
936                         NULL, NULL,
937                         RE_TX_LIST_SZ, 1, RE_TX_LIST_SZ,
938                         BUS_DMA_ALLOCNOW,
939                         &sc->re_ldata.re_tx_list_tag);
940         if (error) {
941                 device_printf(dev, "could not allocate TX ring dma tag\n");
942                 return(error);
943         }
944
945         /* Allocate DMA'able memory for the TX ring */
946         error = bus_dmamem_alloc(sc->re_ldata.re_tx_list_tag,
947                         (void **)&sc->re_ldata.re_tx_list,
948                         BUS_DMA_WAITOK | BUS_DMA_ZERO,
949                         &sc->re_ldata.re_tx_list_map);
950         if (error) {
951                 device_printf(dev, "could not allocate TX ring\n");
952                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
953                 sc->re_ldata.re_tx_list_tag = NULL;
954                 return(error);
955         }
956
957         /* Load the map for the TX ring. */
958         error = bus_dmamap_load(sc->re_ldata.re_tx_list_tag,
959                         sc->re_ldata.re_tx_list_map,
960                         sc->re_ldata.re_tx_list, RE_TX_LIST_SZ,
961                         re_dma_map_addr, &sc->re_ldata.re_tx_list_addr,
962                         BUS_DMA_NOWAIT);
963         if (error) {
964                 device_printf(dev, "could not get address of TX ring\n");
965                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
966                                 sc->re_ldata.re_tx_list,
967                                 sc->re_ldata.re_tx_list_map);
968                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
969                 sc->re_ldata.re_tx_list_tag = NULL;
970                 return(error);
971         }
972
973         /* Allocate tag for RX descriptor list. */
974         error = bus_dma_tag_create(sc->re_parent_tag,
975                         RE_RING_ALIGN, 0,
976                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
977                         NULL, NULL,
978                         RE_RX_LIST_SZ, 1, RE_RX_LIST_SZ,
979                         BUS_DMA_ALLOCNOW,
980                         &sc->re_ldata.re_rx_list_tag);
981         if (error) {
982                 device_printf(dev, "could not allocate RX ring dma tag\n");
983                 return(error);
984         }
985
986         /* Allocate DMA'able memory for the RX ring */
987         error = bus_dmamem_alloc(sc->re_ldata.re_rx_list_tag,
988                         (void **)&sc->re_ldata.re_rx_list,
989                         BUS_DMA_WAITOK | BUS_DMA_ZERO,
990                         &sc->re_ldata.re_rx_list_map);
991         if (error) {
992                 device_printf(dev, "could not allocate RX ring\n");
993                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
994                 sc->re_ldata.re_rx_list_tag = NULL;
995                 return(error);
996         }
997
998         /* Load the map for the RX ring. */
999         error = bus_dmamap_load(sc->re_ldata.re_rx_list_tag,
1000                         sc->re_ldata.re_rx_list_map,
1001                         sc->re_ldata.re_rx_list, RE_RX_LIST_SZ,
1002                         re_dma_map_addr, &sc->re_ldata.re_rx_list_addr,
1003                         BUS_DMA_NOWAIT);
1004         if (error) {
1005                 device_printf(dev, "could not get address of RX ring\n");
1006                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1007                                 sc->re_ldata.re_rx_list,
1008                                 sc->re_ldata.re_rx_list_map);
1009                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1010                 sc->re_ldata.re_rx_list_tag = NULL;
1011                 return(error);
1012         }
1013
1014         /* Allocate map for RX/TX mbufs. */
1015         error = bus_dma_tag_create(sc->re_parent_tag,
1016                         ETHER_ALIGN, 0,
1017                         BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
1018                         NULL, NULL,
1019                         RE_JUMBO_FRAMELEN, RE_MAXSEGS, MCLBYTES,
1020                         BUS_DMA_ALLOCNOW,
1021                         &sc->re_ldata.re_mtag);
1022         if (error) {
1023                 device_printf(dev, "could not allocate buf dma tag\n");
1024                 return(error);
1025         }
1026
1027         /* Create spare DMA map for RX */
1028         error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1029                         &sc->re_ldata.re_rx_spare);
1030         if (error) {
1031                 device_printf(dev, "can't create spare DMA map for RX\n");
1032                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1033                 sc->re_ldata.re_mtag = NULL;
1034                 return error;
1035         }
1036
1037         /* Create DMA maps for TX buffers */
1038         for (i = 0; i < RE_TX_DESC_CNT; i++) {
1039                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1040                                 &sc->re_ldata.re_tx_dmamap[i]);
1041                 if (error) {
1042                         device_printf(dev, "can't create DMA map for TX buf\n");
1043                         re_freebufmem(sc, i, 0);
1044                         return(error);
1045                 }
1046         }
1047
1048         /* Create DMA maps for RX buffers */
1049         for (i = 0; i < RE_RX_DESC_CNT; i++) {
1050                 error = bus_dmamap_create(sc->re_ldata.re_mtag, 0,
1051                                 &sc->re_ldata.re_rx_dmamap[i]);
1052                 if (error) {
1053                         device_printf(dev, "can't create DMA map for RX buf\n");
1054                         re_freebufmem(sc, RE_TX_DESC_CNT, i);
1055                         return(error);
1056                 }
1057         }
1058         return(0);
1059 }
1060
1061 static void
1062 re_freebufmem(struct re_softc *sc, int tx_cnt, int rx_cnt)
1063 {
1064         int i;
1065
1066         /* Destroy all the RX and TX buffer maps */
1067         if (sc->re_ldata.re_mtag) {
1068                 for (i = 0; i < tx_cnt; i++) {
1069                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1070                                            sc->re_ldata.re_tx_dmamap[i]);
1071                 }
1072                 for (i = 0; i < rx_cnt; i++) {
1073                         bus_dmamap_destroy(sc->re_ldata.re_mtag,
1074                                            sc->re_ldata.re_rx_dmamap[i]);
1075                 }
1076                 bus_dmamap_destroy(sc->re_ldata.re_mtag,
1077                                    sc->re_ldata.re_rx_spare);
1078                 bus_dma_tag_destroy(sc->re_ldata.re_mtag);
1079         }
1080 }
1081
1082 static void
1083 re_freemem(device_t dev)
1084 {
1085         struct re_softc *sc = device_get_softc(dev);
1086
1087         /* Unload and free the RX DMA ring memory and map */
1088         if (sc->re_ldata.re_rx_list_tag) {
1089                 bus_dmamap_unload(sc->re_ldata.re_rx_list_tag,
1090                                   sc->re_ldata.re_rx_list_map);
1091                 bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1092                                 sc->re_ldata.re_rx_list,
1093                                 sc->re_ldata.re_rx_list_map);
1094                 bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1095         }
1096
1097         /* Unload and free the TX DMA ring memory and map */
1098         if (sc->re_ldata.re_tx_list_tag) {
1099                 bus_dmamap_unload(sc->re_ldata.re_tx_list_tag,
1100                                   sc->re_ldata.re_tx_list_map);
1101                 bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1102                                 sc->re_ldata.re_tx_list,
1103                                 sc->re_ldata.re_tx_list_map);
1104                 bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1105         }
1106
1107         /* Free RX/TX buf DMA stuffs */
1108         re_freebufmem(sc, RE_TX_DESC_CNT, RE_RX_DESC_CNT);
1109
1110         /* Unload and free the stats buffer and map */
1111         if (sc->re_ldata.re_stag) {
1112                 bus_dmamap_unload(sc->re_ldata.re_stag,
1113                                   sc->re_ldata.re_rx_list_map);
1114                 bus_dmamem_free(sc->re_ldata.re_stag,
1115                                 sc->re_ldata.re_stats,
1116                                 sc->re_ldata.re_smap);
1117                 bus_dma_tag_destroy(sc->re_ldata.re_stag);
1118         }
1119
1120         if (sc->re_parent_tag)
1121                 bus_dma_tag_destroy(sc->re_parent_tag);
1122 }
1123
1124 /*
1125  * Attach the interface. Allocate softc structures, do ifmedia
1126  * setup and ethernet/BPF attach.
1127  */
1128 static int
1129 re_attach(device_t dev)
1130 {
1131         struct re_softc *sc = device_get_softc(dev);
1132         struct ifnet *ifp;
1133         const struct re_hwrev *hw_rev;
1134         uint8_t eaddr[ETHER_ADDR_LEN];
1135         uint16_t as[ETHER_ADDR_LEN / 2];
1136         uint16_t re_did = 0;
1137         uint32_t hwrev;
1138         int error = 0, rid, i;
1139
1140         callout_init(&sc->re_timer);
1141 #ifdef RE_DIAG
1142         sc->re_dev = dev;
1143 #endif
1144
1145         RE_ENABLE_TX_MODERATION(sc);
1146
1147         sysctl_ctx_init(&sc->re_sysctl_ctx);
1148         sc->re_sysctl_tree = SYSCTL_ADD_NODE(&sc->re_sysctl_ctx,
1149                                              SYSCTL_STATIC_CHILDREN(_hw),
1150                                              OID_AUTO,
1151                                              device_get_nameunit(dev),
1152                                              CTLFLAG_RD, 0, "");
1153         if (sc->re_sysctl_tree == NULL) {
1154                 device_printf(dev, "can't add sysctl node\n");
1155                 error = ENXIO;
1156                 goto fail;
1157         }
1158         SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1159                         SYSCTL_CHILDREN(sc->re_sysctl_tree),
1160                         OID_AUTO, "tx_moderation",
1161                         CTLTYPE_INT | CTLFLAG_RW,
1162                         sc, 0, re_sysctl_tx_moderation, "I",
1163                         "Enable/Disable TX moderation");
1164
1165 #ifndef BURN_BRIDGES
1166         /*
1167          * Handle power management nonsense.
1168          */
1169
1170         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1171                 uint32_t membase, irq;
1172
1173                 /* Save important PCI config data. */
1174                 membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1175                 irq = pci_read_config(dev, PCIR_INTLINE, 4);
1176
1177                 /* Reset the power state. */
1178                 device_printf(dev, "chip is in D%d power mode "
1179                     "-- setting to D0\n", pci_get_powerstate(dev));
1180
1181                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1182
1183                 /* Restore PCI config data. */
1184                 pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1185                 pci_write_config(dev, PCIR_INTLINE, irq, 4);
1186         }
1187 #endif
1188         /*
1189          * Map control/status registers.
1190          */
1191         pci_enable_busmaster(dev);
1192
1193         rid = RE_PCI_LOIO;
1194         sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1195                                             RF_ACTIVE);
1196
1197         if (sc->re_res == NULL) {
1198                 device_printf(dev, "couldn't map ports\n");
1199                 error = ENXIO;
1200                 goto fail;
1201         }
1202
1203         sc->re_btag = rman_get_bustag(sc->re_res);
1204         sc->re_bhandle = rman_get_bushandle(sc->re_res);
1205
1206         /* Allocate interrupt */
1207         rid = 0;
1208         sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1209                                             RF_SHAREABLE | RF_ACTIVE);
1210
1211         if (sc->re_irq == NULL) {
1212                 device_printf(dev, "couldn't map interrupt\n");
1213                 error = ENXIO;
1214                 goto fail;
1215         }
1216
1217         /* Reset the adapter. */
1218         re_reset(sc);
1219
1220         hwrev = CSR_READ_4(sc, RE_TXCFG) & RE_TXCFG_HWREV;
1221         for (hw_rev = re_hwrevs; hw_rev->re_desc != NULL; hw_rev++) {
1222                 if (hw_rev->re_rev == hwrev) {
1223                         sc->re_type = hw_rev->re_type;
1224                         sc->re_flags = hw_rev->re_flags;
1225                         break;
1226                 }
1227         }
1228
1229         sc->re_eewidth = 6;
1230         re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
1231         if (re_did != 0x8129)
1232                 sc->re_eewidth = 8;
1233
1234         /*
1235          * Get station address from the EEPROM.
1236          */
1237         re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
1238         for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
1239                 as[i] = le16toh(as[i]);
1240         bcopy(as, eaddr, sizeof(eaddr));
1241
1242         if (sc->re_type == RE_8169) {
1243                 /* Set RX length mask */
1244                 sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1245                 sc->re_txstart = RE_GTXSTART;
1246         } else {
1247                 /* Set RX length mask */
1248                 sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1249                 sc->re_txstart = RE_TXSTART;
1250         }
1251
1252         /* Allocate DMA stuffs */
1253         error = re_allocmem(dev);
1254         if (error)
1255                 goto fail;
1256
1257         /* Do MII setup */
1258         if (mii_phy_probe(dev, &sc->re_miibus,
1259             re_ifmedia_upd, re_ifmedia_sts)) {
1260                 device_printf(dev, "MII without any phy!\n");
1261                 error = ENXIO;
1262                 goto fail;
1263         }
1264
1265         ifp = &sc->arpcom.ac_if;
1266         ifp->if_softc = sc;
1267         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1268         ifp->if_mtu = ETHERMTU;
1269         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1270         ifp->if_ioctl = re_ioctl;
1271         ifp->if_start = re_start;
1272         ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1273
1274         switch (hwrev) {
1275         case RE_HWREV_8168C:
1276         case RE_HWREV_8102EL:
1277                 /*
1278                  * XXX Hardware checksum does not work yet on 8168C
1279                  * and 8102EL. Disble it.
1280                  */
1281                 ifp->if_capabilities &= ~IFCAP_HWCSUM;
1282                 break;
1283         default:
1284                 ifp->if_capabilities |= IFCAP_HWCSUM;
1285                 break;
1286         }
1287 #ifdef DEVICE_POLLING
1288         ifp->if_poll = re_poll;
1289 #endif
1290         ifp->if_watchdog = re_watchdog;
1291         ifp->if_init = re_init;
1292         if (sc->re_type == RE_8169)
1293                 ifp->if_baudrate = 1000000000;
1294         else
1295                 ifp->if_baudrate = 100000000;
1296         ifq_set_maxlen(&ifp->if_snd, RE_IFQ_MAXLEN);
1297         ifq_set_ready(&ifp->if_snd);
1298
1299 #ifdef RE_DISABLE_HWCSUM
1300         ifp->if_capenable = ifp->if_capabilities & ~IFCAP_HWCSUM;
1301         ifp->if_hwassist = 0;
1302 #else
1303         ifp->if_capenable = ifp->if_capabilities;
1304         if (ifp->if_capabilities & IFCAP_HWCSUM)
1305                 ifp->if_hwassist = RE_CSUM_FEATURES;
1306         else
1307                 ifp->if_hwassist = 0;
1308 #endif  /* RE_DISABLE_HWCSUM */
1309
1310         /*
1311          * Call MI attach routine.
1312          */
1313         ether_ifattach(ifp, eaddr, NULL);
1314
1315 #ifdef RE_DIAG
1316         /*
1317          * Perform hardware diagnostic on the original RTL8169.
1318          * Some 32-bit cards were incorrectly wired and would
1319          * malfunction if plugged into a 64-bit slot.
1320          */
1321         if (hwrev == RE_HWREV_8169) {
1322                 lwkt_serialize_enter(ifp->if_serializer);
1323                 error = re_diag(sc);
1324                 lwkt_serialize_exit(ifp->if_serializer);
1325
1326                 if (error) {
1327                         device_printf(dev, "hardware diagnostic failure\n");
1328                         ether_ifdetach(ifp);
1329                         goto fail;
1330                 }
1331         }
1332 #endif  /* RE_DIAG */
1333
1334         /* Hook interrupt last to avoid having to lock softc */
1335         error = bus_setup_intr(dev, sc->re_irq, INTR_MPSAFE, re_intr, sc,
1336                                &sc->re_intrhand, ifp->if_serializer);
1337
1338         if (error) {
1339                 device_printf(dev, "couldn't set up irq\n");
1340                 ether_ifdetach(ifp);
1341                 goto fail;
1342         }
1343
1344         ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1345         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1346
1347 fail:
1348         if (error)
1349                 re_detach(dev);
1350
1351         return (error);
1352 }
1353
1354 /*
1355  * Shutdown hardware and free up resources. This can be called any
1356  * time after the mutex has been initialized. It is called in both
1357  * the error case in attach and the normal detach case so it needs
1358  * to be careful about only freeing resources that have actually been
1359  * allocated.
1360  */
1361 static int
1362 re_detach(device_t dev)
1363 {
1364         struct re_softc *sc = device_get_softc(dev);
1365         struct ifnet *ifp = &sc->arpcom.ac_if;
1366
1367         /* These should only be active if attach succeeded */
1368         if (device_is_attached(dev)) {
1369                 lwkt_serialize_enter(ifp->if_serializer);
1370                 re_stop(sc);
1371                 bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1372                 lwkt_serialize_exit(ifp->if_serializer);
1373
1374                 ether_ifdetach(ifp);
1375         }
1376         if (sc->re_miibus)
1377                 device_delete_child(dev, sc->re_miibus);
1378         bus_generic_detach(dev);
1379
1380         if (sc->re_irq)
1381                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1382         if (sc->re_res) {
1383                 bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1384                                      sc->re_res);
1385         }
1386
1387         /* Free DMA stuffs */
1388         re_freemem(dev);
1389
1390         return(0);
1391 }
1392
1393 static void
1394 re_setup_rxdesc(struct re_softc *sc, int idx)
1395 {
1396         bus_addr_t paddr;
1397         uint32_t cmdstat;
1398         struct re_desc *d;
1399
1400         paddr = sc->re_ldata.re_rx_paddr[idx];
1401         d = &sc->re_ldata.re_rx_list[idx];
1402
1403         d->re_bufaddr_lo = htole32(RE_ADDR_LO(paddr));
1404         d->re_bufaddr_hi = htole32(RE_ADDR_HI(paddr));
1405
1406         cmdstat = MCLBYTES | RE_RDESC_CMD_OWN;
1407         if (idx == (RE_RX_DESC_CNT - 1))
1408                 cmdstat |= RE_TDESC_CMD_EOR;
1409         d->re_cmdstat = htole32(cmdstat);
1410 }
1411
1412 static int
1413 re_newbuf(struct re_softc *sc, int idx, int init)
1414 {
1415         struct re_dmaload_arg arg;
1416         bus_dma_segment_t seg;
1417         bus_dmamap_t map;
1418         struct mbuf *m;
1419         int error;
1420
1421         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
1422         if (m == NULL) {
1423                 error = ENOBUFS;
1424
1425                 if (init) {
1426                         if_printf(&sc->arpcom.ac_if, "m_getcl failed\n");
1427                         return error;
1428                 } else {
1429                         goto back;
1430                 }
1431         }
1432         m->m_len = m->m_pkthdr.len = MCLBYTES;
1433
1434         /*
1435          * NOTE:
1436          * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1437          * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1438          */
1439
1440         arg.re_nsegs = 1;
1441         arg.re_segs = &seg;
1442         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1443                                      sc->re_ldata.re_rx_spare, m,
1444                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1445         if (error || arg.re_nsegs == 0) {
1446                 if (!error) {
1447                         if_printf(&sc->arpcom.ac_if, "too many segments?!\n");
1448                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1449                                           sc->re_ldata.re_rx_spare);
1450                         error = EFBIG;
1451                 }
1452                 m_freem(m);
1453
1454                 if (init) {
1455                         if_printf(&sc->arpcom.ac_if, "can't load RX mbuf\n");
1456                         return error;
1457                 } else {
1458                         goto back;
1459                 }
1460         }
1461
1462         if (!init) {
1463                 bus_dmamap_sync(sc->re_ldata.re_mtag,
1464                                 sc->re_ldata.re_rx_dmamap[idx],
1465                                 BUS_DMASYNC_POSTREAD);
1466                 bus_dmamap_unload(sc->re_ldata.re_mtag,
1467                                   sc->re_ldata.re_rx_dmamap[idx]);
1468         }
1469         sc->re_ldata.re_rx_mbuf[idx] = m;
1470         sc->re_ldata.re_rx_paddr[idx] = seg.ds_addr;
1471
1472         map = sc->re_ldata.re_rx_dmamap[idx];
1473         sc->re_ldata.re_rx_dmamap[idx] = sc->re_ldata.re_rx_spare;
1474         sc->re_ldata.re_rx_spare = map;
1475 back:
1476         re_setup_rxdesc(sc, idx);
1477         return error;
1478 }
1479
1480 static int
1481 re_tx_list_init(struct re_softc *sc)
1482 {
1483         bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ);
1484         bzero(&sc->re_ldata.re_tx_mbuf, RE_TX_DESC_CNT * sizeof(struct mbuf *));
1485
1486         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1487                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1488         sc->re_ldata.re_tx_prodidx = 0;
1489         sc->re_ldata.re_tx_considx = 0;
1490         sc->re_ldata.re_tx_free = RE_TX_DESC_CNT;
1491
1492         return(0);
1493 }
1494
1495 static int
1496 re_rx_list_init(struct re_softc *sc)
1497 {
1498         int i, error;
1499
1500         bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ);
1501         bzero(&sc->re_ldata.re_rx_mbuf, RE_RX_DESC_CNT * sizeof(struct mbuf *));
1502
1503         for (i = 0; i < RE_RX_DESC_CNT; i++) {
1504                 error = re_newbuf(sc, i, 1);
1505                 if (error)
1506                         return(error);
1507         }
1508
1509         /* Flush the RX descriptors */
1510
1511         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1512                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1513
1514         sc->re_ldata.re_rx_prodidx = 0;
1515         sc->re_head = sc->re_tail = NULL;
1516
1517         return(0);
1518 }
1519
1520 /*
1521  * RX handler for C+ and 8169. For the gigE chips, we support
1522  * the reception of jumbo frames that have been fragmented
1523  * across multiple 2K mbuf cluster buffers.
1524  */
1525 static void
1526 re_rxeof(struct re_softc *sc)
1527 {
1528         struct ifnet *ifp = &sc->arpcom.ac_if;
1529         struct mbuf *m;
1530         struct re_desc  *cur_rx;
1531         uint32_t rxstat, rxvlan;
1532         int i, total_len;
1533         struct mbuf_chain chain[MAXCPU];
1534
1535         /* Invalidate the descriptor memory */
1536
1537         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1538                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1539
1540         ether_input_chain_init(chain);
1541
1542         for (i = sc->re_ldata.re_rx_prodidx;
1543              RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0; RE_DESC_INC(i)) {
1544                 cur_rx = &sc->re_ldata.re_rx_list[i];
1545                 m = sc->re_ldata.re_rx_mbuf[i];
1546                 total_len = RE_RXBYTES(cur_rx);
1547                 rxstat = le32toh(cur_rx->re_cmdstat);
1548                 rxvlan = le32toh(cur_rx->re_vlanctl);
1549
1550                 if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1551                         if (re_newbuf(sc, i, 0)) {
1552                                 /* TODO: Drop upcoming fragments */
1553                                 continue;
1554                         }
1555
1556                         m->m_len = MCLBYTES - ETHER_ALIGN;
1557                         if (sc->re_head == NULL) {
1558                                 sc->re_head = sc->re_tail = m;
1559                         } else {
1560                                 sc->re_tail->m_next = m;
1561                                 sc->re_tail = m;
1562                         }
1563                         continue;
1564                 }
1565
1566                 /*
1567                  * NOTE: for the 8139C+, the frame length field
1568                  * is always 12 bits in size, but for the gigE chips,
1569                  * it is 13 bits (since the max RX frame length is 16K).
1570                  * Unfortunately, all 32 bits in the status word
1571                  * were already used, so to make room for the extra
1572                  * length bit, RealTek took out the 'frame alignment
1573                  * error' bit and shifted the other status bits
1574                  * over one slot. The OWN, EOR, FS and LS bits are
1575                  * still in the same places. We have already extracted
1576                  * the frame length and checked the OWN bit, so rather
1577                  * than using an alternate bit mapping, we shift the
1578                  * status bits one space to the right so we can evaluate
1579                  * them using the 8169 status as though it was in the
1580                  * same format as that of the 8139C+.
1581                  */
1582                 if (sc->re_type == RE_8169)
1583                         rxstat >>= 1;
1584
1585                 if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1586                         ifp->if_ierrors++;
1587                         /*
1588                          * If this is part of a multi-fragment packet,
1589                          * discard all the pieces.
1590                          */
1591                         if (sc->re_head != NULL) {
1592                                 m_freem(sc->re_head);
1593                                 sc->re_head = sc->re_tail = NULL;
1594                         }
1595                         re_setup_rxdesc(sc, i);
1596                         continue;
1597                 }
1598
1599                 /*
1600                  * If allocating a replacement mbuf fails,
1601                  * reload the current one.
1602                  */
1603
1604                 if (re_newbuf(sc, i, 0)) {
1605                         ifp->if_ierrors++;
1606                         if (sc->re_head != NULL) {
1607                                 m_freem(sc->re_head);
1608                                 sc->re_head = sc->re_tail = NULL;
1609                         }
1610                         continue;
1611                 }
1612
1613                 if (sc->re_head != NULL) {
1614                         m->m_len = total_len % (MCLBYTES - ETHER_ALIGN);
1615                         /* 
1616                          * Special case: if there's 4 bytes or less
1617                          * in this buffer, the mbuf can be discarded:
1618                          * the last 4 bytes is the CRC, which we don't
1619                          * care about anyway.
1620                          */
1621                         if (m->m_len <= ETHER_CRC_LEN) {
1622                                 sc->re_tail->m_len -=
1623                                     (ETHER_CRC_LEN - m->m_len);
1624                                 m_freem(m);
1625                         } else {
1626                                 m->m_len -= ETHER_CRC_LEN;
1627                                 sc->re_tail->m_next = m;
1628                         }
1629                         m = sc->re_head;
1630                         sc->re_head = sc->re_tail = NULL;
1631                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1632                 } else {
1633                         m->m_pkthdr.len = m->m_len =
1634                             (total_len - ETHER_CRC_LEN);
1635                 }
1636
1637                 ifp->if_ipackets++;
1638                 m->m_pkthdr.rcvif = ifp;
1639
1640                 /* Do RX checksumming if enabled */
1641
1642                 if (ifp->if_capenable & IFCAP_RXCSUM) {
1643                         /* Check IP header checksum */
1644                         if (rxstat & RE_RDESC_STAT_PROTOID)
1645                                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1646                         if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1647                                 m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1648
1649                         /* Check TCP/UDP checksum */
1650                         if ((RE_TCPPKT(rxstat) &&
1651                             (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1652                             (RE_UDPPKT(rxstat) &&
1653                             (rxstat & RE_RDESC_STAT_UDPSUMBAD)) == 0) {
1654                                 m->m_pkthdr.csum_flags |=
1655                                     CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
1656                                     CSUM_FRAG_NOT_CHECKED;
1657                                 m->m_pkthdr.csum_data = 0xffff;
1658                         }
1659                 }
1660
1661                 if (rxvlan & RE_RDESC_VLANCTL_TAG) {
1662                         m->m_flags |= M_VLANTAG;
1663                         m->m_pkthdr.ether_vlantag =
1664                                 be16toh((rxvlan & RE_RDESC_VLANCTL_DATA));
1665                 }
1666                 ether_input_chain(ifp, m, chain);
1667         }
1668
1669         ether_input_dispatch(chain);
1670
1671         /* Flush the RX DMA ring */
1672
1673         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1674                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1675
1676         sc->re_ldata.re_rx_prodidx = i;
1677 }
1678
1679 static void
1680 re_txeof(struct re_softc *sc)
1681 {
1682         struct ifnet *ifp = &sc->arpcom.ac_if;
1683         uint32_t txstat;
1684         int idx;
1685
1686         /* Invalidate the TX descriptor list */
1687
1688         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1689                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
1690
1691         for (idx = sc->re_ldata.re_tx_considx;
1692              sc->re_ldata.re_tx_free < RE_TX_DESC_CNT; RE_DESC_INC(idx)) {
1693                 txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
1694                 if (txstat & RE_TDESC_CMD_OWN)
1695                         break;
1696
1697                 sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
1698
1699                 /*
1700                  * We only stash mbufs in the last descriptor
1701                  * in a fragment chain, which also happens to
1702                  * be the only place where the TX status bits
1703                  * are valid.
1704                  */
1705                 if (txstat & RE_TDESC_CMD_EOF) {
1706                         m_freem(sc->re_ldata.re_tx_mbuf[idx]);
1707                         sc->re_ldata.re_tx_mbuf[idx] = NULL;
1708                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1709                             sc->re_ldata.re_tx_dmamap[idx]);
1710                         if (txstat & (RE_TDESC_STAT_EXCESSCOL|
1711                             RE_TDESC_STAT_COLCNT))
1712                                 ifp->if_collisions++;
1713                         if (txstat & RE_TDESC_STAT_TXERRSUM)
1714                                 ifp->if_oerrors++;
1715                         else
1716                                 ifp->if_opackets++;
1717                 }
1718                 sc->re_ldata.re_tx_free++;
1719         }
1720         sc->re_ldata.re_tx_considx = idx;
1721
1722         /* There is enough free TX descs */
1723         if (sc->re_ldata.re_tx_free > RE_TXDESC_SPARE)
1724                 ifp->if_flags &= ~IFF_OACTIVE;
1725
1726         /*
1727          * Some chips will ignore a second TX request issued while an
1728          * existing transmission is in progress. If the transmitter goes
1729          * idle but there are still packets waiting to be sent, we need
1730          * to restart the channel here to flush them out. This only seems
1731          * to be required with the PCIe devices.
1732          */
1733         if (sc->re_ldata.re_tx_free < RE_TX_DESC_CNT)
1734                 CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
1735         else
1736                 ifp->if_timer = 0;
1737
1738         /*
1739          * If not all descriptors have been released reaped yet,
1740          * reload the timer so that we will eventually get another
1741          * interrupt that will cause us to re-enter this routine.
1742          * This is done in case the transmitter has gone idle.
1743          */
1744         if (RE_TX_MODERATION_IS_ENABLED(sc) &&
1745             sc->re_ldata.re_tx_free < RE_TX_DESC_CNT)
1746                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
1747 }
1748
1749 static void
1750 re_tick(void *xsc)
1751 {
1752         struct re_softc *sc = xsc;
1753
1754         lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
1755         re_tick_serialized(xsc);
1756         lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
1757 }
1758
1759 static void
1760 re_tick_serialized(void *xsc)
1761 {
1762         struct re_softc *sc = xsc;
1763         struct ifnet *ifp = &sc->arpcom.ac_if;
1764         struct mii_data *mii;
1765
1766         ASSERT_SERIALIZED(ifp->if_serializer);
1767
1768         mii = device_get_softc(sc->re_miibus);
1769         mii_tick(mii);
1770         if (sc->re_link) {
1771                 if (!(mii->mii_media_status & IFM_ACTIVE))
1772                         sc->re_link = 0;
1773         } else {
1774                 if (mii->mii_media_status & IFM_ACTIVE &&
1775                     IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1776                         sc->re_link = 1;
1777                         if (!ifq_is_empty(&ifp->if_snd))
1778                                 if_devstart(ifp);
1779                 }
1780         }
1781
1782         callout_reset(&sc->re_timer, hz, re_tick, sc);
1783 }
1784
1785 #ifdef DEVICE_POLLING
1786
1787 static void
1788 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1789 {
1790         struct re_softc *sc = ifp->if_softc;
1791
1792         ASSERT_SERIALIZED(ifp->if_serializer);
1793
1794         switch(cmd) {
1795         case POLL_REGISTER:
1796                 /* disable interrupts */
1797                 CSR_WRITE_2(sc, RE_IMR, 0x0000);
1798                 break;
1799         case POLL_DEREGISTER:
1800                 /* enable interrupts */
1801                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
1802                 break;
1803         default:
1804                 sc->rxcycles = count;
1805                 re_rxeof(sc);
1806                 re_txeof(sc);
1807
1808                 if (!ifq_is_empty(&ifp->if_snd))
1809                         if_devstart(ifp);
1810
1811                 if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1812                         uint16_t       status;
1813
1814                         status = CSR_READ_2(sc, RE_ISR);
1815                         if (status == 0xffff)
1816                                 return;
1817                         if (status)
1818                                 CSR_WRITE_2(sc, RE_ISR, status);
1819
1820                         /*
1821                          * XXX check behaviour on receiver stalls.
1822                          */
1823
1824                         if (status & RE_ISR_SYSTEM_ERR) {
1825                                 re_reset(sc);
1826                                 re_init(sc);
1827                         }
1828                 }
1829                 break;
1830         }
1831 }
1832 #endif /* DEVICE_POLLING */
1833
1834 static void
1835 re_intr(void *arg)
1836 {
1837         struct re_softc *sc = arg;
1838         struct ifnet *ifp = &sc->arpcom.ac_if;
1839         uint16_t status;
1840
1841         ASSERT_SERIALIZED(ifp->if_serializer);
1842
1843         if (sc->suspended || (ifp->if_flags & IFF_UP) == 0)
1844                 return;
1845
1846         for (;;) {
1847                 status = CSR_READ_2(sc, RE_ISR);
1848                 /* If the card has gone away the read returns 0xffff. */
1849                 if (status == 0xffff)
1850                         break;
1851                 if (status)
1852                         CSR_WRITE_2(sc, RE_ISR, status);
1853
1854                 if ((status & sc->re_intrs) == 0)
1855                         break;
1856
1857                 if (status & (RE_ISR_RX_OK | RE_ISR_RX_ERR | RE_ISR_FIFO_OFLOW))
1858                         re_rxeof(sc);
1859
1860                 if ((status & sc->re_tx_ack) ||
1861                     (status & RE_ISR_TX_ERR) ||
1862                     (status & RE_ISR_TX_DESC_UNAVAIL))
1863                         re_txeof(sc);
1864
1865                 if (status & RE_ISR_SYSTEM_ERR) {
1866                         re_reset(sc);
1867                         re_init(sc);
1868                 }
1869
1870                 if (status & RE_ISR_LINKCHG) {
1871                         callout_stop(&sc->re_timer);
1872                         re_tick_serialized(sc);
1873                 }
1874         }
1875
1876         if (!ifq_is_empty(&ifp->if_snd))
1877                 if_devstart(ifp);
1878 }
1879
1880 static int
1881 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx0)
1882 {
1883         struct ifnet *ifp = &sc->arpcom.ac_if;
1884         struct mbuf *m;
1885         struct re_dmaload_arg arg;
1886         bus_dma_segment_t segs[RE_MAXSEGS];
1887         bus_dmamap_t map;
1888         int error, maxsegs, idx, i;
1889         struct re_desc *d, *tx_ring;
1890         uint32_t csum_flags;
1891
1892         KASSERT(sc->re_ldata.re_tx_free > RE_TXDESC_SPARE,
1893                 ("not enough free TX desc\n"));
1894
1895         m = *m_head;
1896         map = sc->re_ldata.re_tx_dmamap[*idx0];
1897
1898         /*
1899          * Set up checksum offload. Note: checksum offload bits must
1900          * appear in all descriptors of a multi-descriptor transmit
1901          * attempt. (This is according to testing done with an 8169
1902          * chip. I'm not sure if this is a requirement or a bug.)
1903          */
1904         csum_flags = 0;
1905         if (m->m_pkthdr.csum_flags & CSUM_IP)
1906                 csum_flags |= RE_TDESC_CMD_IPCSUM;
1907         if (m->m_pkthdr.csum_flags & CSUM_TCP)
1908                 csum_flags |= RE_TDESC_CMD_TCPCSUM;
1909         if (m->m_pkthdr.csum_flags & CSUM_UDP)
1910                 csum_flags |= RE_TDESC_CMD_UDPCSUM;
1911
1912         /*
1913          * With some of the RealTek chips, using the checksum offload
1914          * support in conjunction with the autopadding feature results
1915          * in the transmission of corrupt frames. For example, if we
1916          * need to send a really small IP fragment that's less than 60
1917          * bytes in size, and IP header checksumming is enabled, the
1918          * resulting ethernet frame that appears on the wire will
1919          * have garbled payload. To work around this, if TX checksum
1920          * offload is enabled, we always manually pad short frames out
1921          * to the minimum ethernet frame size. We do this by pretending
1922          * the mbuf chain has too many fragments so the coalescing code
1923          * below can assemble the packet into a single buffer that's
1924          * padded out to the mininum frame size.
1925          *
1926          * Note: this appears unnecessary for TCP, and doing it for TCP
1927          * with PCIe adapters seems to result in bad checksums.
1928          */
1929         if (csum_flags && !(csum_flags & RE_TDESC_CMD_TCPCSUM) &&
1930             m->m_pkthdr.len < RE_MIN_FRAMELEN) {
1931                 error = re_pad_frame(m);
1932                 if (error)
1933                         goto back;
1934         }
1935
1936         maxsegs = sc->re_ldata.re_tx_free - RE_TXDESC_SPARE;
1937         if (maxsegs > RE_MAXSEGS)
1938                 maxsegs = RE_MAXSEGS;
1939
1940         arg.re_nsegs = maxsegs;
1941         arg.re_segs = segs;
1942         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
1943                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1944         if (error && error != EFBIG) {
1945                 if_printf(ifp, "can't map mbuf (error %d)\n", error);
1946                 goto back;
1947         }
1948
1949         /*
1950          * Too many segments to map, coalesce into a single mbuf
1951          */
1952         if (!error && arg.re_nsegs == 0) {
1953                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
1954                 error = EFBIG;
1955         }
1956         if (error) {
1957                 struct mbuf *m_new;
1958
1959                 m_new = m_defrag(m, MB_DONTWAIT);
1960                 if (m_new == NULL) {
1961                         if_printf(ifp, "can't defrag TX mbuf\n");
1962                         error = ENOBUFS;
1963                         goto back;
1964                 } else {
1965                         *m_head = m = m_new;
1966                 }
1967
1968                 arg.re_nsegs = maxsegs;
1969                 arg.re_segs = segs;
1970                 error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
1971                                              re_dma_map_desc, &arg,
1972                                              BUS_DMA_NOWAIT);
1973                 if (error || arg.re_nsegs == 0) {
1974                         if (!error) {
1975                                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
1976                                 error = EFBIG;
1977                         }
1978                         if_printf(ifp, "can't map mbuf (error %d)\n", error);
1979                         goto back;
1980                 }
1981         }
1982         bus_dmamap_sync(sc->re_ldata.re_mtag, map, BUS_DMASYNC_PREWRITE);
1983
1984         /*
1985          * Map the segment array into descriptors.  We also keep track
1986          * of the end of the ring and set the end-of-ring bits as needed,
1987          * and we set the ownership bits in all except the very first
1988          * descriptor, whose ownership bits will be turned on later.
1989          */
1990         tx_ring = sc->re_ldata.re_tx_list;
1991         idx = *idx0;
1992         i = 0;
1993         for (;;) {
1994                 uint32_t cmdstat;
1995
1996                 d = &tx_ring[idx];
1997
1998                 cmdstat = segs[i].ds_len;
1999                 d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
2000                 d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
2001                 if (i == 0)
2002                         cmdstat |= RE_TDESC_CMD_SOF;
2003                 else
2004                         cmdstat |= RE_TDESC_CMD_OWN;
2005                 if (idx == (RE_TX_DESC_CNT - 1))
2006                         cmdstat |= RE_TDESC_CMD_EOR;
2007                 d->re_cmdstat = htole32(cmdstat | csum_flags);
2008
2009                 i++;
2010                 if (i == arg.re_nsegs)
2011                         break;
2012                 RE_DESC_INC(idx);
2013         }
2014         d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
2015
2016         /*
2017          * Set up hardware VLAN tagging. Note: vlan tag info must
2018          * appear in the first descriptor of a multi-descriptor
2019          * transmission attempt.
2020          */
2021         if (m->m_flags & M_VLANTAG) {
2022                 tx_ring[*idx0].re_vlanctl =
2023                     htole32(htobe16(m->m_pkthdr.ether_vlantag) |
2024                             RE_TDESC_VLANCTL_TAG);
2025         }
2026
2027         /* Transfer ownership of packet to the chip. */
2028         d->re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2029         if (*idx0 != idx)
2030                 tx_ring[*idx0].re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2031
2032         /*
2033          * Insure that the map for this transmission
2034          * is placed at the array index of the last descriptor
2035          * in this chain.
2036          */
2037         sc->re_ldata.re_tx_dmamap[*idx0] = sc->re_ldata.re_tx_dmamap[idx];
2038         sc->re_ldata.re_tx_dmamap[idx] = map;
2039
2040         sc->re_ldata.re_tx_mbuf[idx] = m;
2041         sc->re_ldata.re_tx_free -= arg.re_nsegs;
2042
2043         RE_DESC_INC(idx);
2044         *idx0 = idx;
2045 back:
2046         if (error) {
2047                 m_freem(m);
2048                 *m_head = NULL;
2049         }
2050         return error;
2051 }
2052
2053 /*
2054  * Main transmit routine for C+ and gigE NICs.
2055  */
2056
2057 static void
2058 re_start(struct ifnet *ifp)
2059 {
2060         struct re_softc *sc = ifp->if_softc;
2061         struct mbuf *m_head;
2062         int idx, need_trans;
2063
2064         ASSERT_SERIALIZED(ifp->if_serializer);
2065
2066         if (!sc->re_link) {
2067                 ifq_purge(&ifp->if_snd);
2068                 return;
2069         }
2070
2071         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2072                 return;
2073
2074         idx = sc->re_ldata.re_tx_prodidx;
2075
2076         need_trans = 0;
2077         while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2078                 if (sc->re_ldata.re_tx_free <= RE_TXDESC_SPARE) {
2079                         ifp->if_flags |= IFF_OACTIVE;
2080                         break;
2081                 }
2082
2083                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
2084                 if (m_head == NULL)
2085                         break;
2086
2087                 if (re_encap(sc, &m_head, &idx)) {
2088                         /* m_head is freed by re_encap(), if we reach here */
2089                         ifp->if_oerrors++;
2090                         ifp->if_flags |= IFF_OACTIVE;
2091                         break;
2092                 }
2093
2094                 need_trans = 1;
2095
2096                 /*
2097                  * If there's a BPF listener, bounce a copy of this frame
2098                  * to him.
2099                  */
2100                 ETHER_BPF_MTAP(ifp, m_head);
2101         }
2102
2103         if (!need_trans) {
2104                 if (RE_TX_MODERATION_IS_ENABLED(sc) &&
2105                     sc->re_ldata.re_tx_free != RE_TX_DESC_CNT)
2106                         CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2107                 return;
2108         }
2109
2110         /* Flush the TX descriptors */
2111         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2112                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2113
2114         sc->re_ldata.re_tx_prodidx = idx;
2115
2116         /*
2117          * RealTek put the TX poll request register in a different
2118          * location on the 8169 gigE chip. I don't know why.
2119          */
2120         CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2121
2122         if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2123                 /*
2124                  * Use the countdown timer for interrupt moderation.
2125                  * 'TX done' interrupts are disabled. Instead, we reset the
2126                  * countdown timer, which will begin counting until it hits
2127                  * the value in the TIMERINT register, and then trigger an
2128                  * interrupt. Each time we write to the TIMERCNT register,
2129                  * the timer count is reset to 0.
2130                  */
2131                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2132         }
2133
2134         /*
2135          * Set a timeout in case the chip goes out to lunch.
2136          */
2137         ifp->if_timer = 5;
2138 }
2139
2140 static void
2141 re_init(void *xsc)
2142 {
2143         struct re_softc *sc = xsc;
2144         struct ifnet *ifp = &sc->arpcom.ac_if;
2145         struct mii_data *mii;
2146         uint32_t rxcfg = 0;
2147         int error;
2148
2149         ASSERT_SERIALIZED(ifp->if_serializer);
2150
2151         mii = device_get_softc(sc->re_miibus);
2152
2153         /*
2154          * Cancel pending I/O and free all RX/TX buffers.
2155          */
2156         re_stop(sc);
2157
2158         /*
2159          * Enable C+ RX and TX mode, as well as VLAN stripping and
2160          * RX checksum offload. We must configure the C+ register
2161          * before all others.
2162          */
2163         CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2164                     RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
2165                     (ifp->if_capenable & IFCAP_RXCSUM ?
2166                      RE_CPLUSCMD_RXCSUM_ENB : 0));
2167
2168         /*
2169          * Init our MAC address.  Even though the chipset
2170          * documentation doesn't mention it, we need to enter "Config
2171          * register write enable" mode to modify the ID registers.
2172          */
2173         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2174         CSR_WRITE_4(sc, RE_IDR0,
2175             htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2176         CSR_WRITE_2(sc, RE_IDR4,
2177             htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2178         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2179
2180         /*
2181          * For C+ mode, initialize the RX descriptors and mbufs.
2182          */
2183         error = re_rx_list_init(sc);
2184         if (error) {
2185                 re_stop(sc);
2186                 return;
2187         }
2188         error = re_tx_list_init(sc);
2189         if (error) {
2190                 re_stop(sc);
2191                 return;
2192         }
2193
2194         /*
2195          * Load the addresses of the RX and TX lists into the chip.
2196          */
2197         CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2198             RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2199         CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2200             RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2201
2202         CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2203             RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2204         CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2205             RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2206
2207         /*
2208          * Enable transmit and receive.
2209          */
2210         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2211
2212         /*
2213          * Set the initial TX and RX configuration.
2214          */
2215         if (sc->re_testmode) {
2216                 if (sc->re_type == RE_8169)
2217                         CSR_WRITE_4(sc, RE_TXCFG,
2218                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2219                 else
2220                         CSR_WRITE_4(sc, RE_TXCFG,
2221                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2222         } else
2223                 CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2224
2225         CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, 16);
2226
2227         CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2228
2229         /* Set the individual bit to receive frames for this host only. */
2230         rxcfg = CSR_READ_4(sc, RE_RXCFG);
2231         rxcfg |= RE_RXCFG_RX_INDIV;
2232
2233         /* If we want promiscuous mode, set the allframes bit. */
2234         if (ifp->if_flags & IFF_PROMISC) {
2235                 rxcfg |= RE_RXCFG_RX_ALLPHYS;
2236                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2237         } else {
2238                 rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
2239                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2240         }
2241
2242         /*
2243          * Set capture broadcast bit to capture broadcast frames.
2244          */
2245         if (ifp->if_flags & IFF_BROADCAST) {
2246                 rxcfg |= RE_RXCFG_RX_BROAD;
2247                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2248         } else {
2249                 rxcfg &= ~RE_RXCFG_RX_BROAD;
2250                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2251         }
2252
2253         /*
2254          * Program the multicast filter, if necessary.
2255          */
2256         re_setmulti(sc);
2257
2258 #ifdef DEVICE_POLLING
2259         /*
2260          * Disable interrupts if we are polling.
2261          */
2262         if (ifp->if_flags & IFF_POLLING)
2263                 CSR_WRITE_2(sc, RE_IMR, 0);
2264         else    /* otherwise ... */
2265 #endif /* DEVICE_POLLING */
2266         /*
2267          * Enable interrupts.
2268          */
2269         if (sc->re_testmode)
2270                 CSR_WRITE_2(sc, RE_IMR, 0);
2271         else
2272                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
2273         CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2274
2275         /* Set initial TX threshold */
2276         sc->re_txthresh = RE_TX_THRESH_INIT;
2277
2278         /* Start RX/TX process. */
2279         if (sc->re_flags & RE_F_HASMPC)
2280                 CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2281 #ifdef notdef
2282         /* Enable receiver and transmitter. */
2283         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2284 #endif
2285
2286         if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2287                 /*
2288                  * Initialize the timer interrupt register so that
2289                  * a timer interrupt will be generated once the timer
2290                  * reaches a certain number of ticks. The timer is
2291                  * reloaded on each transmit. This gives us TX interrupt
2292                  * moderation, which dramatically improves TX frame rate.
2293                  */
2294                 if (sc->re_type == RE_8169)
2295                         CSR_WRITE_4(sc, RE_TIMERINT_8169, 0x800);
2296                 else
2297                         CSR_WRITE_4(sc, RE_TIMERINT, 0x400);
2298         }
2299
2300         /*
2301          * For 8169 gigE NICs, set the max allowed RX packet
2302          * size so we can receive jumbo frames.
2303          */
2304         if (sc->re_type == RE_8169)
2305                 CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2306
2307         if (sc->re_testmode) {
2308                 return;
2309         }
2310
2311         mii_mediachg(mii);
2312
2313         CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2314
2315         ifp->if_flags |= IFF_RUNNING;
2316         ifp->if_flags &= ~IFF_OACTIVE;
2317
2318         sc->re_link = 0;
2319         callout_reset(&sc->re_timer, hz, re_tick, sc);
2320 }
2321
2322 /*
2323  * Set media options.
2324  */
2325 static int
2326 re_ifmedia_upd(struct ifnet *ifp)
2327 {
2328         struct re_softc *sc = ifp->if_softc;
2329         struct mii_data *mii;
2330
2331         ASSERT_SERIALIZED(ifp->if_serializer);
2332
2333         mii = device_get_softc(sc->re_miibus);
2334         mii_mediachg(mii);
2335
2336         return(0);
2337 }
2338
2339 /*
2340  * Report current media status.
2341  */
2342 static void
2343 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2344 {
2345         struct re_softc *sc = ifp->if_softc;
2346         struct mii_data *mii;
2347
2348         ASSERT_SERIALIZED(ifp->if_serializer);
2349
2350         mii = device_get_softc(sc->re_miibus);
2351
2352         mii_pollstat(mii);
2353         ifmr->ifm_active = mii->mii_media_active;
2354         ifmr->ifm_status = mii->mii_media_status;
2355 }
2356
2357 static int
2358 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2359 {
2360         struct re_softc *sc = ifp->if_softc;
2361         struct ifreq *ifr = (struct ifreq *) data;
2362         struct mii_data *mii;
2363         int error = 0;
2364
2365         ASSERT_SERIALIZED(ifp->if_serializer);
2366
2367         switch(command) {
2368         case SIOCSIFMTU:
2369                 if (ifr->ifr_mtu > RE_JUMBO_MTU)
2370                         error = EINVAL;
2371                 ifp->if_mtu = ifr->ifr_mtu;
2372                 break;
2373         case SIOCSIFFLAGS:
2374                 if (ifp->if_flags & IFF_UP)
2375                         re_init(sc);
2376                 else if (ifp->if_flags & IFF_RUNNING)
2377                         re_stop(sc);
2378                 break;
2379         case SIOCADDMULTI:
2380         case SIOCDELMULTI:
2381                 re_setmulti(sc);
2382                 error = 0;
2383                 break;
2384         case SIOCGIFMEDIA:
2385         case SIOCSIFMEDIA:
2386                 mii = device_get_softc(sc->re_miibus);
2387                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2388                 break;
2389         case SIOCSIFCAP:
2390                 ifp->if_capenable &= ~(IFCAP_HWCSUM);
2391                 ifp->if_capenable |=
2392                     ifr->ifr_reqcap & (IFCAP_HWCSUM);
2393                 if (ifp->if_capenable & IFCAP_TXCSUM)
2394                         ifp->if_hwassist = RE_CSUM_FEATURES;
2395                 else
2396                         ifp->if_hwassist = 0;
2397                 if (ifp->if_flags & IFF_RUNNING)
2398                         re_init(sc);
2399                 break;
2400         default:
2401                 error = ether_ioctl(ifp, command, data);
2402                 break;
2403         }
2404         return(error);
2405 }
2406
2407 static void
2408 re_watchdog(struct ifnet *ifp)
2409 {
2410         struct re_softc *sc = ifp->if_softc;
2411
2412         ASSERT_SERIALIZED(ifp->if_serializer);
2413
2414         if_printf(ifp, "watchdog timeout\n");
2415
2416         ifp->if_oerrors++;
2417
2418         re_txeof(sc);
2419         re_rxeof(sc);
2420
2421         re_init(sc);
2422
2423         if (!ifq_is_empty(&ifp->if_snd))
2424                 if_devstart(ifp);
2425 }
2426
2427 /*
2428  * Stop the adapter and free any mbufs allocated to the
2429  * RX and TX lists.
2430  */
2431 static void
2432 re_stop(struct re_softc *sc)
2433 {
2434         struct ifnet *ifp = &sc->arpcom.ac_if;
2435         int i;
2436
2437         ASSERT_SERIALIZED(ifp->if_serializer);
2438
2439         ifp->if_timer = 0;
2440         callout_stop(&sc->re_timer);
2441
2442         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2443
2444         CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2445         CSR_WRITE_2(sc, RE_IMR, 0x0000);
2446         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2447
2448         if (sc->re_head != NULL) {
2449                 m_freem(sc->re_head);
2450                 sc->re_head = sc->re_tail = NULL;
2451         }
2452
2453         /* Free the TX list buffers. */
2454         for (i = 0; i < RE_TX_DESC_CNT; i++) {
2455                 if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2456                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2457                                           sc->re_ldata.re_tx_dmamap[i]);
2458                         m_freem(sc->re_ldata.re_tx_mbuf[i]);
2459                         sc->re_ldata.re_tx_mbuf[i] = NULL;
2460                 }
2461         }
2462
2463         /* Free the RX list buffers. */
2464         for (i = 0; i < RE_RX_DESC_CNT; i++) {
2465                 if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2466                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2467                                           sc->re_ldata.re_rx_dmamap[i]);
2468                         m_freem(sc->re_ldata.re_rx_mbuf[i]);
2469                         sc->re_ldata.re_rx_mbuf[i] = NULL;
2470                 }
2471         }
2472 }
2473
2474 /*
2475  * Device suspend routine.  Stop the interface and save some PCI
2476  * settings in case the BIOS doesn't restore them properly on
2477  * resume.
2478  */
2479 static int
2480 re_suspend(device_t dev)
2481 {
2482 #ifndef BURN_BRIDGES
2483         int i;
2484 #endif
2485         struct re_softc *sc = device_get_softc(dev);
2486         struct ifnet *ifp = &sc->arpcom.ac_if;
2487
2488         lwkt_serialize_enter(ifp->if_serializer);
2489
2490         re_stop(sc);
2491
2492 #ifndef BURN_BRIDGES
2493         for (i = 0; i < 5; i++)
2494                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2495         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2496         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2497         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2498         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2499 #endif
2500
2501         sc->suspended = 1;
2502
2503         lwkt_serialize_exit(ifp->if_serializer);
2504
2505         return (0);
2506 }
2507
2508 /*
2509  * Device resume routine.  Restore some PCI settings in case the BIOS
2510  * doesn't, re-enable busmastering, and restart the interface if
2511  * appropriate.
2512  */
2513 static int
2514 re_resume(device_t dev)
2515 {
2516         struct re_softc *sc = device_get_softc(dev);
2517         struct ifnet *ifp = &sc->arpcom.ac_if;
2518 #ifndef BURN_BRIDGES
2519         int i;
2520 #endif
2521
2522         lwkt_serialize_enter(ifp->if_serializer);
2523
2524 #ifndef BURN_BRIDGES
2525         /* better way to do this? */
2526         for (i = 0; i < 5; i++)
2527                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2528         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2529         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2530         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2531         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2532
2533         /* reenable busmastering */
2534         pci_enable_busmaster(dev);
2535         pci_enable_io(dev, SYS_RES_IOPORT);
2536 #endif
2537
2538         /* reinitialize interface if necessary */
2539         if (ifp->if_flags & IFF_UP)
2540                 re_init(sc);
2541
2542         sc->suspended = 0;
2543
2544         lwkt_serialize_exit(ifp->if_serializer);
2545
2546         return (0);
2547 }
2548
2549 /*
2550  * Stop all chip I/O so that the kernel's probe routines don't
2551  * get confused by errant DMAs when rebooting.
2552  */
2553 static void
2554 re_shutdown(device_t dev)
2555 {
2556         struct re_softc *sc = device_get_softc(dev);
2557         struct ifnet *ifp = &sc->arpcom.ac_if;
2558
2559         lwkt_serialize_enter(ifp->if_serializer);
2560         re_stop(sc);
2561         lwkt_serialize_exit(ifp->if_serializer);
2562 }
2563
2564 static int
2565 re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS)
2566 {
2567         struct re_softc *sc = arg1;
2568         struct ifnet *ifp = &sc->arpcom.ac_if;
2569         int error = 0, mod, mod_old;
2570
2571         lwkt_serialize_enter(ifp->if_serializer);
2572
2573         mod_old = mod = RE_TX_MODERATION_IS_ENABLED(sc);
2574
2575         error = sysctl_handle_int(oidp, &mod, 0, req);
2576         if (error || req->newptr == NULL || mod == mod_old)
2577                 goto back;
2578         if (mod != 0 && mod != 1) {
2579                 error = EINVAL;
2580                 goto back;
2581         }
2582
2583         if (mod)
2584                 RE_ENABLE_TX_MODERATION(sc);
2585         else
2586                 RE_DISABLE_TX_MODERATION(sc);
2587
2588         if ((ifp->if_flags & (IFF_RUNNING | IFF_UP)) == (IFF_RUNNING | IFF_UP))
2589                 re_init(sc);
2590 back:
2591         lwkt_serialize_exit(ifp->if_serializer);
2592         return error;
2593 }
2594
2595 static int
2596 re_pad_frame(struct mbuf *pkt)
2597 {
2598         struct mbuf *last = NULL;
2599         int padlen;
2600
2601         padlen = RE_MIN_FRAMELEN - pkt->m_pkthdr.len;
2602
2603         /* if there's only the packet-header and we can pad there, use it. */
2604         if (pkt->m_pkthdr.len == pkt->m_len &&
2605             M_TRAILINGSPACE(pkt) >= padlen) {
2606                 last = pkt;
2607         } else {
2608                 /*
2609                  * Walk packet chain to find last mbuf. We will either
2610                  * pad there, or append a new mbuf and pad it
2611                  */
2612                 for (last = pkt; last->m_next != NULL; last = last->m_next)
2613                         ; /* EMPTY */
2614
2615                 /* `last' now points to last in chain. */
2616                 if (M_TRAILINGSPACE(last) < padlen) {
2617                         struct mbuf *n;
2618
2619                         /* Allocate new empty mbuf, pad it.  Compact later. */
2620                         MGET(n, MB_DONTWAIT, MT_DATA);
2621                         if (n == NULL)
2622                                 return ENOBUFS;
2623                         n->m_len = 0;
2624                         last->m_next = n;
2625                         last = n;
2626                 }
2627         }
2628         KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2629         KKASSERT(M_WRITABLE(last));
2630
2631         /* Now zero the pad area, to avoid the re cksum-assist bug */
2632         bzero(mtod(last, char *) + last->m_len, padlen);
2633         last->m_len += padlen;
2634         pkt->m_pkthdr.len += padlen;
2635         return 0;
2636 }