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