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