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