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