- Set hardware timer according to bus clock. Adjust hardware timer to 8000HZ
[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.66 2008/10/05 07:57:45 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
1332         if (sc->re_type == RE_8139CPLUS) {
1333                 sc->re_bus_speed = 33; /* XXX */
1334         } else if (sc->re_flags & RE_F_PCIE) {
1335                 uint16_t val;
1336                 uint8_t expr_ptr;
1337
1338                 expr_ptr = pci_get_pciecap_ptr(dev);
1339                 if (expr_ptr != 0) {
1340                         /*
1341                          * We will set TX DMA burst to "unlimited" in
1342                          * re_init(), so push "max read request size"
1343                          * to the limit.
1344                          */
1345                         val = pci_read_config(dev, expr_ptr + PCIER_DEVCTRL, 2);
1346                         if ((val & PCIEM_DEVCTL_MAX_READRQ_MASK) !=
1347                             PCIEM_DEVCTL_MAX_READRQ_4096) {
1348                                 device_printf(dev, "adjust device control "
1349                                               "0x%04x ", val);
1350
1351                                 val &= ~PCIEM_DEVCTL_MAX_READRQ_MASK;
1352                                 val |= PCIEM_DEVCTL_MAX_READRQ_4096;
1353                                 pci_write_config(dev, expr_ptr + PCIER_DEVCTRL,
1354                                                  val, 2);
1355
1356                                 kprintf("-> 0x%04x\n", val);
1357                         }
1358                 } else {
1359                         device_printf(dev, "not PCI-E device\n");
1360                         /* XXX clear RE_F_PCIE and read RE_CFG2? */
1361                 }
1362                 sc->re_bus_speed = 125;
1363         } else {
1364                 uint8_t cfg2;
1365
1366                 cfg2 = CSR_READ_1(sc, RE_CFG2);
1367                 switch (cfg2 & RE_CFG2_PCICLK_MASK) {
1368                 case RE_CFG2_PCICLK_33MHZ:
1369                         sc->re_bus_speed = 33;
1370                         break;
1371                 case RE_CFG2_PCICLK_66MHZ:
1372                         sc->re_bus_speed = 66;
1373                         break;
1374                 default:
1375                         device_printf(dev, "unknown bus speed, assume 33MHz\n");
1376                         sc->re_bus_speed = 33;
1377                         break;
1378                 }
1379                 if (cfg2 & RE_CFG2_PCI64)
1380                         sc->re_flags |= RE_F_PCI64;
1381         }
1382         device_printf(dev, "Hardware rev. 0x%08x; PCI%s %dMHz\n",
1383                       sc->re_hwrev,
1384                       (sc->re_flags & RE_F_PCIE) ?
1385                       "-E" : ((sc->re_flags & RE_F_PCI64) ? "64" : "32"),
1386                       sc->re_bus_speed);
1387
1388         sc->re_eewidth = 6;
1389         re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
1390         if (re_did != 0x8129)
1391                 sc->re_eewidth = 8;
1392
1393         /*
1394          * Get station address from the EEPROM.
1395          */
1396         re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
1397         for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
1398                 as[i] = le16toh(as[i]);
1399         bcopy(as, eaddr, sizeof(eaddr));
1400
1401         if (sc->re_type == RE_8169) {
1402                 /* Set RX length mask */
1403                 sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1404                 sc->re_txstart = RE_GTXSTART;
1405         } else {
1406                 /* Set RX length mask */
1407                 sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1408                 sc->re_txstart = RE_TXSTART;
1409         }
1410
1411         /* Allocate DMA stuffs */
1412         error = re_allocmem(dev);
1413         if (error)
1414                 goto fail;
1415
1416         /* Do MII setup */
1417         if (mii_phy_probe(dev, &sc->re_miibus,
1418             re_ifmedia_upd, re_ifmedia_sts)) {
1419                 device_printf(dev, "MII without any phy!\n");
1420                 error = ENXIO;
1421                 goto fail;
1422         }
1423
1424         ifp = &sc->arpcom.ac_if;
1425         ifp->if_softc = sc;
1426         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1427         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1428         ifp->if_ioctl = re_ioctl;
1429         ifp->if_start = re_start;
1430         ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1431
1432         switch (hwrev) {
1433         case RE_HWREV_8168C:
1434         case RE_HWREV_8102EL:
1435                 /*
1436                  * XXX Hardware checksum does not work yet on 8168C
1437                  * and 8102EL. Disble it.
1438                  */
1439                 ifp->if_capabilities &= ~IFCAP_HWCSUM;
1440                 break;
1441         default:
1442                 ifp->if_capabilities |= IFCAP_HWCSUM;
1443                 break;
1444         }
1445 #ifdef DEVICE_POLLING
1446         ifp->if_poll = re_poll;
1447 #endif
1448         ifp->if_watchdog = re_watchdog;
1449         ifp->if_init = re_init;
1450         if (sc->re_type == RE_8169)
1451                 ifp->if_baudrate = 1000000000;
1452         else
1453                 ifp->if_baudrate = 100000000;
1454         ifq_set_maxlen(&ifp->if_snd, qlen);
1455         ifq_set_ready(&ifp->if_snd);
1456
1457 #ifdef RE_DISABLE_HWCSUM
1458         ifp->if_capenable = ifp->if_capabilities & ~IFCAP_HWCSUM;
1459         ifp->if_hwassist = 0;
1460 #else
1461         ifp->if_capenable = ifp->if_capabilities;
1462         if (ifp->if_capabilities & IFCAP_HWCSUM)
1463                 ifp->if_hwassist = RE_CSUM_FEATURES;
1464         else
1465                 ifp->if_hwassist = 0;
1466 #endif  /* RE_DISABLE_HWCSUM */
1467
1468         /*
1469          * Call MI attach routine.
1470          */
1471         ether_ifattach(ifp, eaddr, NULL);
1472
1473 #ifdef RE_DIAG
1474         /*
1475          * Perform hardware diagnostic on the original RTL8169.
1476          * Some 32-bit cards were incorrectly wired and would
1477          * malfunction if plugged into a 64-bit slot.
1478          */
1479         if (hwrev == RE_HWREV_8169) {
1480                 lwkt_serialize_enter(ifp->if_serializer);
1481                 error = re_diag(sc);
1482                 lwkt_serialize_exit(ifp->if_serializer);
1483
1484                 if (error) {
1485                         device_printf(dev, "hardware diagnostic failure\n");
1486                         ether_ifdetach(ifp);
1487                         goto fail;
1488                 }
1489         }
1490 #endif  /* RE_DIAG */
1491
1492         /* Hook interrupt last to avoid having to lock softc */
1493         error = bus_setup_intr(dev, sc->re_irq, INTR_MPSAFE, re_intr, sc,
1494                                &sc->re_intrhand, ifp->if_serializer);
1495
1496         if (error) {
1497                 device_printf(dev, "couldn't set up irq\n");
1498                 ether_ifdetach(ifp);
1499                 goto fail;
1500         }
1501
1502         ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1503         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1504
1505 fail:
1506         if (error)
1507                 re_detach(dev);
1508
1509         return (error);
1510 }
1511
1512 /*
1513  * Shutdown hardware and free up resources. This can be called any
1514  * time after the mutex has been initialized. It is called in both
1515  * the error case in attach and the normal detach case so it needs
1516  * to be careful about only freeing resources that have actually been
1517  * allocated.
1518  */
1519 static int
1520 re_detach(device_t dev)
1521 {
1522         struct re_softc *sc = device_get_softc(dev);
1523         struct ifnet *ifp = &sc->arpcom.ac_if;
1524
1525         /* These should only be active if attach succeeded */
1526         if (device_is_attached(dev)) {
1527                 lwkt_serialize_enter(ifp->if_serializer);
1528                 re_stop(sc);
1529                 bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1530                 lwkt_serialize_exit(ifp->if_serializer);
1531
1532                 ether_ifdetach(ifp);
1533         }
1534         if (sc->re_miibus)
1535                 device_delete_child(dev, sc->re_miibus);
1536         bus_generic_detach(dev);
1537
1538         if (sc->re_sysctl_tree != NULL)
1539                 sysctl_ctx_free(&sc->re_sysctl_ctx);
1540
1541         if (sc->re_irq)
1542                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1543         if (sc->re_res) {
1544                 bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1545                                      sc->re_res);
1546         }
1547
1548         /* Free DMA stuffs */
1549         re_freemem(dev);
1550
1551         return(0);
1552 }
1553
1554 static void
1555 re_setup_rxdesc(struct re_softc *sc, int idx)
1556 {
1557         bus_addr_t paddr;
1558         uint32_t cmdstat;
1559         struct re_desc *d;
1560
1561         paddr = sc->re_ldata.re_rx_paddr[idx];
1562         d = &sc->re_ldata.re_rx_list[idx];
1563
1564         d->re_bufaddr_lo = htole32(RE_ADDR_LO(paddr));
1565         d->re_bufaddr_hi = htole32(RE_ADDR_HI(paddr));
1566
1567         cmdstat = MCLBYTES | RE_RDESC_CMD_OWN;
1568         if (idx == (sc->re_rx_desc_cnt - 1))
1569                 cmdstat |= RE_TDESC_CMD_EOR;
1570         d->re_cmdstat = htole32(cmdstat);
1571 }
1572
1573 static int
1574 re_newbuf(struct re_softc *sc, int idx, int init)
1575 {
1576         struct re_dmaload_arg arg;
1577         bus_dma_segment_t seg;
1578         bus_dmamap_t map;
1579         struct mbuf *m;
1580         int error;
1581
1582         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
1583         if (m == NULL) {
1584                 error = ENOBUFS;
1585
1586                 if (init) {
1587                         if_printf(&sc->arpcom.ac_if, "m_getcl failed\n");
1588                         return error;
1589                 } else {
1590                         goto back;
1591                 }
1592         }
1593         m->m_len = m->m_pkthdr.len = MCLBYTES;
1594
1595         /*
1596          * NOTE:
1597          * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1598          * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1599          */
1600
1601         arg.re_nsegs = 1;
1602         arg.re_segs = &seg;
1603         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag,
1604                                      sc->re_ldata.re_rx_spare, m,
1605                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1606         if (error || arg.re_nsegs == 0) {
1607                 if (!error) {
1608                         if_printf(&sc->arpcom.ac_if, "too many segments?!\n");
1609                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1610                                           sc->re_ldata.re_rx_spare);
1611                         error = EFBIG;
1612                 }
1613                 m_freem(m);
1614
1615                 if (init) {
1616                         if_printf(&sc->arpcom.ac_if, "can't load RX mbuf\n");
1617                         return error;
1618                 } else {
1619                         goto back;
1620                 }
1621         }
1622
1623         if (!init) {
1624                 bus_dmamap_sync(sc->re_ldata.re_mtag,
1625                                 sc->re_ldata.re_rx_dmamap[idx],
1626                                 BUS_DMASYNC_POSTREAD);
1627                 bus_dmamap_unload(sc->re_ldata.re_mtag,
1628                                   sc->re_ldata.re_rx_dmamap[idx]);
1629         }
1630         sc->re_ldata.re_rx_mbuf[idx] = m;
1631         sc->re_ldata.re_rx_paddr[idx] = seg.ds_addr;
1632
1633         map = sc->re_ldata.re_rx_dmamap[idx];
1634         sc->re_ldata.re_rx_dmamap[idx] = sc->re_ldata.re_rx_spare;
1635         sc->re_ldata.re_rx_spare = map;
1636 back:
1637         re_setup_rxdesc(sc, idx);
1638         return error;
1639 }
1640
1641 static int
1642 re_tx_list_init(struct re_softc *sc)
1643 {
1644         bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ(sc));
1645
1646         /* Flush the TX descriptors */
1647         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1648                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1649
1650         sc->re_ldata.re_tx_prodidx = 0;
1651         sc->re_ldata.re_tx_considx = 0;
1652         sc->re_ldata.re_tx_free = sc->re_tx_desc_cnt;
1653
1654         return(0);
1655 }
1656
1657 static int
1658 re_rx_list_init(struct re_softc *sc)
1659 {
1660         int i, error;
1661
1662         bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ(sc));
1663
1664         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
1665                 error = re_newbuf(sc, i, 1);
1666                 if (error)
1667                         return(error);
1668         }
1669
1670         /* Flush the RX descriptors */
1671         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1672                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1673
1674         sc->re_ldata.re_rx_prodidx = 0;
1675         sc->re_head = sc->re_tail = NULL;
1676
1677         return(0);
1678 }
1679
1680 /*
1681  * RX handler for C+ and 8169. For the gigE chips, we support
1682  * the reception of jumbo frames that have been fragmented
1683  * across multiple 2K mbuf cluster buffers.
1684  */
1685 static void
1686 re_rxeof(struct re_softc *sc)
1687 {
1688         struct ifnet *ifp = &sc->arpcom.ac_if;
1689         struct mbuf *m;
1690         struct re_desc  *cur_rx;
1691         uint32_t rxstat, rxvlan;
1692         int i, total_len;
1693         struct mbuf_chain chain[MAXCPU];
1694
1695         /* Invalidate the descriptor memory */
1696
1697         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1698                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1699
1700         ether_input_chain_init(chain);
1701
1702         for (i = sc->re_ldata.re_rx_prodidx;
1703              RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0; RE_RXDESC_INC(sc, i)) {
1704                 cur_rx = &sc->re_ldata.re_rx_list[i];
1705                 m = sc->re_ldata.re_rx_mbuf[i];
1706                 total_len = RE_RXBYTES(cur_rx);
1707                 rxstat = le32toh(cur_rx->re_cmdstat);
1708                 rxvlan = le32toh(cur_rx->re_vlanctl);
1709
1710                 if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1711                         if (sc->re_drop_rxfrag) {
1712                                 re_setup_rxdesc(sc, i);
1713                                 continue;
1714                         }
1715
1716                         if (re_newbuf(sc, i, 0)) {
1717                                 /* Drop upcoming fragments */
1718                                 sc->re_drop_rxfrag = 1;
1719                                 continue;
1720                         }
1721
1722                         m->m_len = MCLBYTES;
1723                         if (sc->re_head == NULL) {
1724                                 sc->re_head = sc->re_tail = m;
1725                         } else {
1726                                 sc->re_tail->m_next = m;
1727                                 sc->re_tail = m;
1728                         }
1729                         continue;
1730                 } else if (sc->re_drop_rxfrag) {
1731                         /*
1732                          * Last fragment of a multi-fragment packet.
1733                          *
1734                          * Since error already happened, this fragment
1735                          * must be dropped as well as the fragment chain.
1736                          */
1737                         re_setup_rxdesc(sc, i);
1738                         re_free_rxchain(sc);
1739                         sc->re_drop_rxfrag = 0;
1740                         continue;
1741                 }
1742
1743                 /*
1744                  * NOTE: for the 8139C+, the frame length field
1745                  * is always 12 bits in size, but for the gigE chips,
1746                  * it is 13 bits (since the max RX frame length is 16K).
1747                  * Unfortunately, all 32 bits in the status word
1748                  * were already used, so to make room for the extra
1749                  * length bit, RealTek took out the 'frame alignment
1750                  * error' bit and shifted the other status bits
1751                  * over one slot. The OWN, EOR, FS and LS bits are
1752                  * still in the same places. We have already extracted
1753                  * the frame length and checked the OWN bit, so rather
1754                  * than using an alternate bit mapping, we shift the
1755                  * status bits one space to the right so we can evaluate
1756                  * them using the 8169 status as though it was in the
1757                  * same format as that of the 8139C+.
1758                  */
1759                 if (sc->re_type == RE_8169)
1760                         rxstat >>= 1;
1761
1762                 if (rxstat & RE_RDESC_STAT_RXERRSUM) {
1763                         ifp->if_ierrors++;
1764                         /*
1765                          * If this is part of a multi-fragment packet,
1766                          * discard all the pieces.
1767                          */
1768                         re_free_rxchain(sc);
1769                         re_setup_rxdesc(sc, i);
1770                         continue;
1771                 }
1772
1773                 /*
1774                  * If allocating a replacement mbuf fails,
1775                  * reload the current one.
1776                  */
1777
1778                 if (re_newbuf(sc, i, 0)) {
1779                         ifp->if_ierrors++;
1780                         re_free_rxchain(sc);
1781                         continue;
1782                 }
1783
1784                 if (sc->re_head != NULL) {
1785                         m->m_len = total_len % MCLBYTES;
1786                         /* 
1787                          * Special case: if there's 4 bytes or less
1788                          * in this buffer, the mbuf can be discarded:
1789                          * the last 4 bytes is the CRC, which we don't
1790                          * care about anyway.
1791                          */
1792                         if (m->m_len <= ETHER_CRC_LEN) {
1793                                 sc->re_tail->m_len -=
1794                                     (ETHER_CRC_LEN - m->m_len);
1795                                 m_freem(m);
1796                         } else {
1797                                 m->m_len -= ETHER_CRC_LEN;
1798                                 sc->re_tail->m_next = m;
1799                         }
1800                         m = sc->re_head;
1801                         sc->re_head = sc->re_tail = NULL;
1802                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
1803                 } else {
1804                         m->m_pkthdr.len = m->m_len =
1805                             (total_len - ETHER_CRC_LEN);
1806                 }
1807
1808                 ifp->if_ipackets++;
1809                 m->m_pkthdr.rcvif = ifp;
1810
1811                 /* Do RX checksumming if enabled */
1812
1813                 if (ifp->if_capenable & IFCAP_RXCSUM) {
1814                         /* Check IP header checksum */
1815                         if (rxstat & RE_RDESC_STAT_PROTOID)
1816                                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
1817                         if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
1818                                 m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1819
1820                         /* Check TCP/UDP checksum */
1821                         if ((RE_TCPPKT(rxstat) &&
1822                             (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
1823                             (RE_UDPPKT(rxstat) &&
1824                             (rxstat & RE_RDESC_STAT_UDPSUMBAD)) == 0) {
1825                                 m->m_pkthdr.csum_flags |=
1826                                     CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
1827                                     CSUM_FRAG_NOT_CHECKED;
1828                                 m->m_pkthdr.csum_data = 0xffff;
1829                         }
1830                 }
1831
1832                 if (rxvlan & RE_RDESC_VLANCTL_TAG) {
1833                         m->m_flags |= M_VLANTAG;
1834                         m->m_pkthdr.ether_vlantag =
1835                                 be16toh((rxvlan & RE_RDESC_VLANCTL_DATA));
1836                 }
1837                 ether_input_chain(ifp, m, chain);
1838         }
1839
1840         ether_input_dispatch(chain);
1841
1842         /* Flush the RX DMA ring */
1843
1844         bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1845                         sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1846
1847         sc->re_ldata.re_rx_prodidx = i;
1848 }
1849
1850 static void
1851 re_txeof(struct re_softc *sc)
1852 {
1853         struct ifnet *ifp = &sc->arpcom.ac_if;
1854         uint32_t txstat;
1855         int idx;
1856
1857         /* Invalidate the TX descriptor list */
1858
1859         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1860                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
1861
1862         for (idx = sc->re_ldata.re_tx_considx;
1863              sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt;
1864              RE_TXDESC_INC(sc, idx)) {
1865                 txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
1866                 if (txstat & RE_TDESC_CMD_OWN)
1867                         break;
1868
1869                 sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
1870
1871                 /*
1872                  * We only stash mbufs in the last descriptor
1873                  * in a fragment chain, which also happens to
1874                  * be the only place where the TX status bits
1875                  * are valid.
1876                  */
1877                 if (txstat & RE_TDESC_CMD_EOF) {
1878                         m_freem(sc->re_ldata.re_tx_mbuf[idx]);
1879                         sc->re_ldata.re_tx_mbuf[idx] = NULL;
1880                         bus_dmamap_unload(sc->re_ldata.re_mtag,
1881                             sc->re_ldata.re_tx_dmamap[idx]);
1882                         if (txstat & (RE_TDESC_STAT_EXCESSCOL|
1883                             RE_TDESC_STAT_COLCNT))
1884                                 ifp->if_collisions++;
1885                         if (txstat & RE_TDESC_STAT_TXERRSUM)
1886                                 ifp->if_oerrors++;
1887                         else
1888                                 ifp->if_opackets++;
1889                 }
1890                 sc->re_ldata.re_tx_free++;
1891         }
1892         sc->re_ldata.re_tx_considx = idx;
1893
1894         /* There is enough free TX descs */
1895         if (sc->re_ldata.re_tx_free > RE_TXDESC_SPARE)
1896                 ifp->if_flags &= ~IFF_OACTIVE;
1897
1898         /*
1899          * Some chips will ignore a second TX request issued while an
1900          * existing transmission is in progress. If the transmitter goes
1901          * idle but there are still packets waiting to be sent, we need
1902          * to restart the channel here to flush them out. This only seems
1903          * to be required with the PCIe devices.
1904          */
1905         if (sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt)
1906                 CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
1907         else
1908                 ifp->if_timer = 0;
1909
1910         /*
1911          * If not all descriptors have been released reaped yet,
1912          * reload the timer so that we will eventually get another
1913          * interrupt that will cause us to re-enter this routine.
1914          * This is done in case the transmitter has gone idle.
1915          */
1916         if (RE_TX_MODERATION_IS_ENABLED(sc) &&
1917             sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt)
1918                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
1919 }
1920
1921 static void
1922 re_tick(void *xsc)
1923 {
1924         struct re_softc *sc = xsc;
1925
1926         lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
1927         re_tick_serialized(xsc);
1928         lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
1929 }
1930
1931 static void
1932 re_tick_serialized(void *xsc)
1933 {
1934         struct re_softc *sc = xsc;
1935         struct ifnet *ifp = &sc->arpcom.ac_if;
1936         struct mii_data *mii;
1937
1938         ASSERT_SERIALIZED(ifp->if_serializer);
1939
1940         mii = device_get_softc(sc->re_miibus);
1941         mii_tick(mii);
1942         if (sc->re_link) {
1943                 if (!(mii->mii_media_status & IFM_ACTIVE))
1944                         sc->re_link = 0;
1945         } else {
1946                 if (mii->mii_media_status & IFM_ACTIVE &&
1947                     IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
1948                         sc->re_link = 1;
1949                         if (!ifq_is_empty(&ifp->if_snd))
1950                                 if_devstart(ifp);
1951                 }
1952         }
1953
1954         callout_reset(&sc->re_timer, hz, re_tick, sc);
1955 }
1956
1957 #ifdef DEVICE_POLLING
1958
1959 static void
1960 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1961 {
1962         struct re_softc *sc = ifp->if_softc;
1963
1964         ASSERT_SERIALIZED(ifp->if_serializer);
1965
1966         switch(cmd) {
1967         case POLL_REGISTER:
1968                 /* disable interrupts */
1969                 CSR_WRITE_2(sc, RE_IMR, 0x0000);
1970                 break;
1971         case POLL_DEREGISTER:
1972                 /* enable interrupts */
1973                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
1974                 break;
1975         default:
1976                 sc->rxcycles = count;
1977                 re_rxeof(sc);
1978                 re_txeof(sc);
1979
1980                 if (!ifq_is_empty(&ifp->if_snd))
1981                         if_devstart(ifp);
1982
1983                 if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
1984                         uint16_t       status;
1985
1986                         status = CSR_READ_2(sc, RE_ISR);
1987                         if (status == 0xffff)
1988                                 return;
1989                         if (status)
1990                                 CSR_WRITE_2(sc, RE_ISR, status);
1991
1992                         /*
1993                          * XXX check behaviour on receiver stalls.
1994                          */
1995
1996                         if (status & RE_ISR_SYSTEM_ERR) {
1997                                 re_reset(sc);
1998                                 re_init(sc);
1999                         }
2000                 }
2001                 break;
2002         }
2003 }
2004 #endif /* DEVICE_POLLING */
2005
2006 static void
2007 re_intr(void *arg)
2008 {
2009         struct re_softc *sc = arg;
2010         struct ifnet *ifp = &sc->arpcom.ac_if;
2011         uint16_t status;
2012
2013         ASSERT_SERIALIZED(ifp->if_serializer);
2014
2015         if (sc->suspended || (ifp->if_flags & IFF_UP) == 0)
2016                 return;
2017
2018         for (;;) {
2019                 status = CSR_READ_2(sc, RE_ISR);
2020                 /* If the card has gone away the read returns 0xffff. */
2021                 if (status == 0xffff)
2022                         break;
2023                 if (status)
2024                         CSR_WRITE_2(sc, RE_ISR, status);
2025
2026                 if ((status & sc->re_intrs) == 0)
2027                         break;
2028
2029                 if (status & (RE_ISR_RX_OK | RE_ISR_RX_ERR | RE_ISR_FIFO_OFLOW))
2030                         re_rxeof(sc);
2031
2032                 if ((status & sc->re_tx_ack) ||
2033                     (status & RE_ISR_TX_ERR) ||
2034                     (status & RE_ISR_TX_DESC_UNAVAIL))
2035                         re_txeof(sc);
2036
2037                 if (status & RE_ISR_SYSTEM_ERR) {
2038                         re_reset(sc);
2039                         re_init(sc);
2040                 }
2041
2042                 if (status & RE_ISR_LINKCHG) {
2043                         callout_stop(&sc->re_timer);
2044                         re_tick_serialized(sc);
2045                 }
2046         }
2047
2048         if (!ifq_is_empty(&ifp->if_snd))
2049                 if_devstart(ifp);
2050 }
2051
2052 static int
2053 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx0)
2054 {
2055         struct ifnet *ifp = &sc->arpcom.ac_if;
2056         struct mbuf *m;
2057         struct re_dmaload_arg arg;
2058         bus_dma_segment_t segs[RE_MAXSEGS];
2059         bus_dmamap_t map;
2060         int error, maxsegs, idx, i;
2061         struct re_desc *d, *tx_ring;
2062         uint32_t csum_flags;
2063
2064         KASSERT(sc->re_ldata.re_tx_free > RE_TXDESC_SPARE,
2065                 ("not enough free TX desc\n"));
2066
2067         m = *m_head;
2068         map = sc->re_ldata.re_tx_dmamap[*idx0];
2069
2070         /*
2071          * Set up checksum offload. Note: checksum offload bits must
2072          * appear in all descriptors of a multi-descriptor transmit
2073          * attempt. (This is according to testing done with an 8169
2074          * chip. I'm not sure if this is a requirement or a bug.)
2075          */
2076         csum_flags = 0;
2077         if (m->m_pkthdr.csum_flags & CSUM_IP)
2078                 csum_flags |= RE_TDESC_CMD_IPCSUM;
2079         if (m->m_pkthdr.csum_flags & CSUM_TCP)
2080                 csum_flags |= RE_TDESC_CMD_TCPCSUM;
2081         if (m->m_pkthdr.csum_flags & CSUM_UDP)
2082                 csum_flags |= RE_TDESC_CMD_UDPCSUM;
2083
2084         if (m->m_pkthdr.len > sc->re_swcsum_lim &&
2085             (m->m_pkthdr.csum_flags & (CSUM_DELAY_IP | CSUM_DELAY_DATA))) {
2086                 struct ether_header *eh;
2087                 struct ip *ip;
2088                 u_short offset;
2089
2090                 m = m_pullup(m, sizeof(struct ether_header *));
2091                 if (m == NULL) {
2092                         *m_head = NULL;
2093                         return ENOBUFS;
2094                 }
2095                 eh = mtod(m, struct ether_header *);
2096
2097                 /* XXX */
2098                 if (eh->ether_type == ETHERTYPE_VLAN)
2099                         offset = sizeof(struct ether_vlan_header);
2100                 else
2101                         offset = sizeof(struct ether_header);
2102
2103                 m = m_pullup(m, offset + sizeof(struct ip *));
2104                 if (m == NULL) {
2105                         *m_head = NULL;
2106                         return ENOBUFS;
2107                 }
2108                 ip = (struct ip *)(mtod(m, uint8_t *) + offset);
2109
2110                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2111                         u_short csum;
2112
2113                         offset += IP_VHL_HL(ip->ip_vhl) << 2;
2114                         csum = in_cksum_skip(m, ntohs(ip->ip_len), offset);
2115                         if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
2116                                 csum = 0xffff;
2117                         offset += m->m_pkthdr.csum_data;        /* checksum offset */
2118                         *(u_short *)(m->m_data + offset) = csum;
2119
2120                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2121                 }
2122                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_IP) {
2123                         ip->ip_sum = 0;
2124                         if (ip->ip_vhl == IP_VHL_BORING) {
2125                                 ip->ip_sum = in_cksum_hdr(ip);
2126                         } else {
2127                                 ip->ip_sum =
2128                                 in_cksum(m, IP_VHL_HL(ip->ip_vhl) << 2);
2129                         }
2130                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_IP;
2131                 }
2132                 *m_head = m; /* 'm' may be changed by above two m_pullup() */
2133         }
2134
2135         /*
2136          * With some of the RealTek chips, using the checksum offload
2137          * support in conjunction with the autopadding feature results
2138          * in the transmission of corrupt frames. For example, if we
2139          * need to send a really small IP fragment that's less than 60
2140          * bytes in size, and IP header checksumming is enabled, the
2141          * resulting ethernet frame that appears on the wire will
2142          * have garbled payload. To work around this, if TX checksum
2143          * offload is enabled, we always manually pad short frames out
2144          * to the minimum ethernet frame size. We do this by pretending
2145          * the mbuf chain has too many fragments so the coalescing code
2146          * below can assemble the packet into a single buffer that's
2147          * padded out to the mininum frame size.
2148          *
2149          * Note: this appears unnecessary for TCP, and doing it for TCP
2150          * with PCIe adapters seems to result in bad checksums.
2151          */
2152         if (csum_flags && !(csum_flags & RE_TDESC_CMD_TCPCSUM) &&
2153             m->m_pkthdr.len < RE_MIN_FRAMELEN) {
2154                 error = re_pad_frame(m);
2155                 if (error)
2156                         goto back;
2157         }
2158
2159         maxsegs = sc->re_ldata.re_tx_free;
2160         if (maxsegs > RE_MAXSEGS)
2161                 maxsegs = RE_MAXSEGS;
2162
2163         arg.re_nsegs = maxsegs;
2164         arg.re_segs = segs;
2165         error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2166                                      re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
2167         if (error && error != EFBIG) {
2168                 if_printf(ifp, "can't map mbuf (error %d)\n", error);
2169                 goto back;
2170         }
2171
2172         /*
2173          * Too many segments to map, coalesce into a single mbuf
2174          */
2175         if (!error && arg.re_nsegs == 0) {
2176                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2177                 error = EFBIG;
2178         }
2179         if (error) {
2180                 struct mbuf *m_new;
2181
2182                 m_new = m_defrag(m, MB_DONTWAIT);
2183                 if (m_new == NULL) {
2184                         if_printf(ifp, "can't defrag TX mbuf\n");
2185                         error = ENOBUFS;
2186                         goto back;
2187                 } else {
2188                         *m_head = m = m_new;
2189                 }
2190
2191                 arg.re_nsegs = maxsegs;
2192                 arg.re_segs = segs;
2193                 error = bus_dmamap_load_mbuf(sc->re_ldata.re_mtag, map, m,
2194                                              re_dma_map_desc, &arg,
2195                                              BUS_DMA_NOWAIT);
2196                 if (error || arg.re_nsegs == 0) {
2197                         if (!error) {
2198                                 bus_dmamap_unload(sc->re_ldata.re_mtag, map);
2199                                 error = EFBIG;
2200                         }
2201                         if_printf(ifp, "can't map mbuf (error %d)\n", error);
2202                         goto back;
2203                 }
2204         }
2205         bus_dmamap_sync(sc->re_ldata.re_mtag, map, BUS_DMASYNC_PREWRITE);
2206
2207         /*
2208          * Map the segment array into descriptors.  We also keep track
2209          * of the end of the ring and set the end-of-ring bits as needed,
2210          * and we set the ownership bits in all except the very first
2211          * descriptor, whose ownership bits will be turned on later.
2212          */
2213         tx_ring = sc->re_ldata.re_tx_list;
2214         idx = *idx0;
2215         i = 0;
2216         for (;;) {
2217                 uint32_t cmdstat;
2218
2219                 d = &tx_ring[idx];
2220
2221                 cmdstat = segs[i].ds_len;
2222                 d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
2223                 d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
2224                 if (i == 0)
2225                         cmdstat |= RE_TDESC_CMD_SOF;
2226                 else
2227                         cmdstat |= RE_TDESC_CMD_OWN;
2228                 if (idx == (sc->re_tx_desc_cnt - 1))
2229                         cmdstat |= RE_TDESC_CMD_EOR;
2230                 d->re_cmdstat = htole32(cmdstat | csum_flags);
2231
2232                 i++;
2233                 if (i == arg.re_nsegs)
2234                         break;
2235                 RE_TXDESC_INC(sc, idx);
2236         }
2237         d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
2238
2239         /*
2240          * Set up hardware VLAN tagging. Note: vlan tag info must
2241          * appear in the first descriptor of a multi-descriptor
2242          * transmission attempt.
2243          */
2244         if (m->m_flags & M_VLANTAG) {
2245                 tx_ring[*idx0].re_vlanctl =
2246                     htole32(htobe16(m->m_pkthdr.ether_vlantag) |
2247                             RE_TDESC_VLANCTL_TAG);
2248         }
2249
2250         /* Transfer ownership of packet to the chip. */
2251         d->re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2252         if (*idx0 != idx)
2253                 tx_ring[*idx0].re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2254
2255         /*
2256          * Insure that the map for this transmission
2257          * is placed at the array index of the last descriptor
2258          * in this chain.
2259          */
2260         sc->re_ldata.re_tx_dmamap[*idx0] = sc->re_ldata.re_tx_dmamap[idx];
2261         sc->re_ldata.re_tx_dmamap[idx] = map;
2262
2263         sc->re_ldata.re_tx_mbuf[idx] = m;
2264         sc->re_ldata.re_tx_free -= arg.re_nsegs;
2265
2266         RE_TXDESC_INC(sc, idx);
2267         *idx0 = idx;
2268 back:
2269         if (error) {
2270                 m_freem(m);
2271                 *m_head = NULL;
2272         }
2273         return error;
2274 }
2275
2276 /*
2277  * Main transmit routine for C+ and gigE NICs.
2278  */
2279
2280 static void
2281 re_start(struct ifnet *ifp)
2282 {
2283         struct re_softc *sc = ifp->if_softc;
2284         struct mbuf *m_head;
2285         int idx, need_trans;
2286
2287         ASSERT_SERIALIZED(ifp->if_serializer);
2288
2289         if (!sc->re_link) {
2290                 ifq_purge(&ifp->if_snd);
2291                 return;
2292         }
2293
2294         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2295                 return;
2296
2297         idx = sc->re_ldata.re_tx_prodidx;
2298
2299         need_trans = 0;
2300         while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2301                 if (sc->re_ldata.re_tx_free <= RE_TXDESC_SPARE) {
2302                         ifp->if_flags |= IFF_OACTIVE;
2303                         break;
2304                 }
2305
2306                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
2307                 if (m_head == NULL)
2308                         break;
2309
2310                 if (re_encap(sc, &m_head, &idx)) {
2311                         /* m_head is freed by re_encap(), if we reach here */
2312                         ifp->if_oerrors++;
2313                         ifp->if_flags |= IFF_OACTIVE;
2314                         break;
2315                 }
2316
2317                 need_trans = 1;
2318
2319                 /*
2320                  * If there's a BPF listener, bounce a copy of this frame
2321                  * to him.
2322                  */
2323                 ETHER_BPF_MTAP(ifp, m_head);
2324         }
2325
2326         if (!need_trans) {
2327                 if (RE_TX_MODERATION_IS_ENABLED(sc) &&
2328                     sc->re_ldata.re_tx_free != sc->re_tx_desc_cnt)
2329                         CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2330                 return;
2331         }
2332
2333         /* Flush the TX descriptors */
2334         bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2335                         sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2336
2337         sc->re_ldata.re_tx_prodidx = idx;
2338
2339         /*
2340          * RealTek put the TX poll request register in a different
2341          * location on the 8169 gigE chip. I don't know why.
2342          */
2343         CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2344
2345         if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2346                 /*
2347                  * Use the countdown timer for interrupt moderation.
2348                  * 'TX done' interrupts are disabled. Instead, we reset the
2349                  * countdown timer, which will begin counting until it hits
2350                  * the value in the TIMERINT register, and then trigger an
2351                  * interrupt. Each time we write to the TIMERCNT register,
2352                  * the timer count is reset to 0.
2353                  */
2354                 CSR_WRITE_4(sc, RE_TIMERCNT, 1);
2355         }
2356
2357         /*
2358          * Set a timeout in case the chip goes out to lunch.
2359          */
2360         ifp->if_timer = 5;
2361 }
2362
2363 static void
2364 re_init(void *xsc)
2365 {
2366         struct re_softc *sc = xsc;
2367         struct ifnet *ifp = &sc->arpcom.ac_if;
2368         struct mii_data *mii;
2369         uint32_t rxcfg = 0;
2370         int error, framelen;
2371
2372         ASSERT_SERIALIZED(ifp->if_serializer);
2373
2374         mii = device_get_softc(sc->re_miibus);
2375
2376         /*
2377          * Cancel pending I/O and free all RX/TX buffers.
2378          */
2379         re_stop(sc);
2380
2381         /*
2382          * Enable C+ RX and TX mode, as well as VLAN stripping and
2383          * RX checksum offload. We must configure the C+ register
2384          * before all others.
2385          */
2386         CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2387                     RE_CPLUSCMD_PCI_MRW | RE_CPLUSCMD_VLANSTRIP |
2388                     (ifp->if_capenable & IFCAP_RXCSUM ?
2389                      RE_CPLUSCMD_RXCSUM_ENB : 0));
2390
2391         /*
2392          * Init our MAC address.  Even though the chipset
2393          * documentation doesn't mention it, we need to enter "Config
2394          * register write enable" mode to modify the ID registers.
2395          */
2396         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2397         CSR_WRITE_4(sc, RE_IDR0,
2398             htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2399         CSR_WRITE_2(sc, RE_IDR4,
2400             htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2401         CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2402
2403         /*
2404          * For C+ mode, initialize the RX descriptors and mbufs.
2405          */
2406         error = re_rx_list_init(sc);
2407         if (error) {
2408                 re_stop(sc);
2409                 return;
2410         }
2411         error = re_tx_list_init(sc);
2412         if (error) {
2413                 re_stop(sc);
2414                 return;
2415         }
2416
2417         /*
2418          * Load the addresses of the RX and TX lists into the chip.
2419          */
2420         CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2421             RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2422         CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2423             RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2424
2425         CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2426             RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2427         CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2428             RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2429
2430         /*
2431          * Enable transmit and receive.
2432          */
2433         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2434
2435         /*
2436          * Set the initial TX and RX configuration.
2437          */
2438         if (sc->re_testmode) {
2439                 if (sc->re_type == RE_8169)
2440                         CSR_WRITE_4(sc, RE_TXCFG,
2441                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2442                 else
2443                         CSR_WRITE_4(sc, RE_TXCFG,
2444                                     RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2445         } else
2446                 CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2447
2448         framelen = RE_FRAMELEN(ifp->if_mtu);
2449         if (framelen < RE_FRAMELEN_2K) {
2450                 CSR_WRITE_1(sc, RE_EARLY_TX_THRESH,
2451                             howmany(RE_FRAMELEN_2K, 128));
2452         } else {
2453                 CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, howmany(framelen, 128));
2454         }
2455
2456         CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2457
2458         /* Set the individual bit to receive frames for this host only. */
2459         rxcfg = CSR_READ_4(sc, RE_RXCFG);
2460         rxcfg |= RE_RXCFG_RX_INDIV;
2461
2462         /* If we want promiscuous mode, set the allframes bit. */
2463         if (ifp->if_flags & IFF_PROMISC) {
2464                 rxcfg |= RE_RXCFG_RX_ALLPHYS;
2465                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2466         } else {
2467                 rxcfg &= ~RE_RXCFG_RX_ALLPHYS;
2468                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2469         }
2470
2471         /*
2472          * Set capture broadcast bit to capture broadcast frames.
2473          */
2474         if (ifp->if_flags & IFF_BROADCAST) {
2475                 rxcfg |= RE_RXCFG_RX_BROAD;
2476                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2477         } else {
2478                 rxcfg &= ~RE_RXCFG_RX_BROAD;
2479                 CSR_WRITE_4(sc, RE_RXCFG, rxcfg);
2480         }
2481
2482         /*
2483          * Program the multicast filter, if necessary.
2484          */
2485         re_setmulti(sc);
2486
2487 #ifdef DEVICE_POLLING
2488         /*
2489          * Disable interrupts if we are polling.
2490          */
2491         if (ifp->if_flags & IFF_POLLING)
2492                 CSR_WRITE_2(sc, RE_IMR, 0);
2493         else    /* otherwise ... */
2494 #endif /* DEVICE_POLLING */
2495         /*
2496          * Enable interrupts.
2497          */
2498         if (sc->re_testmode)
2499                 CSR_WRITE_2(sc, RE_IMR, 0);
2500         else
2501                 CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
2502         CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2503
2504         /* Set initial TX threshold */
2505         sc->re_txthresh = RE_TX_THRESH_INIT;
2506
2507         /* Start RX/TX process. */
2508         if (sc->re_flags & RE_F_HASMPC)
2509                 CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2510 #ifdef notdef
2511         /* Enable receiver and transmitter. */
2512         CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2513 #endif
2514
2515         if (RE_TX_MODERATION_IS_ENABLED(sc)) {
2516                 /*
2517                  * Initialize the timer interrupt register so that
2518                  * a timer interrupt will be generated once the timer
2519                  * reaches a certain number of ticks. The timer is
2520                  * reloaded on each transmit. This gives us TX interrupt
2521                  * moderation, which dramatically improves TX frame rate.
2522                  */
2523                 if (sc->re_type == RE_8169) {
2524                         /*
2525                          * Set hardare timer to 125us
2526                          * XXX measurement showed me the actual value is ~76us,
2527                          * which is ~2/3 of the desired value
2528                          *
2529                          * TODO: sysctl variable.
2530                          */
2531                         CSR_WRITE_4(sc, RE_TIMERINT_8169,
2532                                     125 * sc->re_bus_speed);
2533                 } else {
2534                         CSR_WRITE_4(sc, RE_TIMERINT, 0x400);
2535                 }
2536         }
2537
2538         /*
2539          * For 8169 gigE NICs, set the max allowed RX packet
2540          * size so we can receive jumbo frames.
2541          */
2542         if (sc->re_type == RE_8169)
2543                 CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2544
2545         if (sc->re_testmode) {
2546                 return;
2547         }
2548
2549         mii_mediachg(mii);
2550
2551         CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2552
2553         ifp->if_flags |= IFF_RUNNING;
2554         ifp->if_flags &= ~IFF_OACTIVE;
2555
2556         sc->re_link = 0;
2557         callout_reset(&sc->re_timer, hz, re_tick, sc);
2558 }
2559
2560 /*
2561  * Set media options.
2562  */
2563 static int
2564 re_ifmedia_upd(struct ifnet *ifp)
2565 {
2566         struct re_softc *sc = ifp->if_softc;
2567         struct mii_data *mii;
2568
2569         ASSERT_SERIALIZED(ifp->if_serializer);
2570
2571         mii = device_get_softc(sc->re_miibus);
2572         mii_mediachg(mii);
2573
2574         return(0);
2575 }
2576
2577 /*
2578  * Report current media status.
2579  */
2580 static void
2581 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2582 {
2583         struct re_softc *sc = ifp->if_softc;
2584         struct mii_data *mii;
2585
2586         ASSERT_SERIALIZED(ifp->if_serializer);
2587
2588         mii = device_get_softc(sc->re_miibus);
2589
2590         mii_pollstat(mii);
2591         ifmr->ifm_active = mii->mii_media_active;
2592         ifmr->ifm_status = mii->mii_media_status;
2593 }
2594
2595 static int
2596 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2597 {
2598         struct re_softc *sc = ifp->if_softc;
2599         struct ifreq *ifr = (struct ifreq *) data;
2600         struct mii_data *mii;
2601         int error = 0;
2602
2603         ASSERT_SERIALIZED(ifp->if_serializer);
2604
2605         switch(command) {
2606         case SIOCSIFMTU:
2607                 if (ifr->ifr_mtu > sc->re_maxmtu) {
2608                         error = EINVAL;
2609                 } else if (ifp->if_mtu != ifr->ifr_mtu) {
2610                         ifp->if_mtu = ifr->ifr_mtu;
2611                         if (ifp->if_flags & IFF_RUNNING)
2612                                 ifp->if_init(sc);
2613                 }
2614                 break;
2615
2616         case SIOCSIFFLAGS:
2617                 if (ifp->if_flags & IFF_UP)
2618                         re_init(sc);
2619                 else if (ifp->if_flags & IFF_RUNNING)
2620                         re_stop(sc);
2621                 break;
2622         case SIOCADDMULTI:
2623         case SIOCDELMULTI:
2624                 re_setmulti(sc);
2625                 error = 0;
2626                 break;
2627         case SIOCGIFMEDIA:
2628         case SIOCSIFMEDIA:
2629                 mii = device_get_softc(sc->re_miibus);
2630                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2631                 break;
2632         case SIOCSIFCAP:
2633                 ifp->if_capenable &= ~(IFCAP_HWCSUM);
2634                 ifp->if_capenable |=
2635                     ifr->ifr_reqcap & (IFCAP_HWCSUM);
2636                 if (ifp->if_capenable & IFCAP_TXCSUM)
2637                         ifp->if_hwassist = RE_CSUM_FEATURES;
2638                 else
2639                         ifp->if_hwassist = 0;
2640                 if (ifp->if_flags & IFF_RUNNING)
2641                         re_init(sc);
2642                 break;
2643         default:
2644                 error = ether_ioctl(ifp, command, data);
2645                 break;
2646         }
2647         return(error);
2648 }
2649
2650 static void
2651 re_watchdog(struct ifnet *ifp)
2652 {
2653         struct re_softc *sc = ifp->if_softc;
2654
2655         ASSERT_SERIALIZED(ifp->if_serializer);
2656
2657         if_printf(ifp, "watchdog timeout\n");
2658
2659         ifp->if_oerrors++;
2660
2661         re_txeof(sc);
2662         re_rxeof(sc);
2663
2664         re_init(sc);
2665
2666         if (!ifq_is_empty(&ifp->if_snd))
2667                 if_devstart(ifp);
2668 }
2669
2670 /*
2671  * Stop the adapter and free any mbufs allocated to the
2672  * RX and TX lists.
2673  */
2674 static void
2675 re_stop(struct re_softc *sc)
2676 {
2677         struct ifnet *ifp = &sc->arpcom.ac_if;
2678         int i;
2679
2680         ASSERT_SERIALIZED(ifp->if_serializer);
2681
2682         ifp->if_timer = 0;
2683         callout_stop(&sc->re_timer);
2684
2685         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2686
2687         CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2688         CSR_WRITE_2(sc, RE_IMR, 0x0000);
2689         CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2690
2691         re_free_rxchain(sc);
2692         sc->re_drop_rxfrag = 0;
2693
2694         /* Free the TX list buffers. */
2695         for (i = 0; i < sc->re_tx_desc_cnt; i++) {
2696                 if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2697                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2698                                           sc->re_ldata.re_tx_dmamap[i]);
2699                         m_freem(sc->re_ldata.re_tx_mbuf[i]);
2700                         sc->re_ldata.re_tx_mbuf[i] = NULL;
2701                 }
2702         }
2703
2704         /* Free the RX list buffers. */
2705         for (i = 0; i < sc->re_rx_desc_cnt; i++) {
2706                 if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2707                         bus_dmamap_unload(sc->re_ldata.re_mtag,
2708                                           sc->re_ldata.re_rx_dmamap[i]);
2709                         m_freem(sc->re_ldata.re_rx_mbuf[i]);
2710                         sc->re_ldata.re_rx_mbuf[i] = NULL;
2711                 }
2712         }
2713 }
2714
2715 /*
2716  * Device suspend routine.  Stop the interface and save some PCI
2717  * settings in case the BIOS doesn't restore them properly on
2718  * resume.
2719  */
2720 static int
2721 re_suspend(device_t dev)
2722 {
2723 #ifndef BURN_BRIDGES
2724         int i;
2725 #endif
2726         struct re_softc *sc = device_get_softc(dev);
2727         struct ifnet *ifp = &sc->arpcom.ac_if;
2728
2729         lwkt_serialize_enter(ifp->if_serializer);
2730
2731         re_stop(sc);
2732
2733 #ifndef BURN_BRIDGES
2734         for (i = 0; i < 5; i++)
2735                 sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
2736         sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
2737         sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
2738         sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
2739         sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
2740 #endif
2741
2742         sc->suspended = 1;
2743
2744         lwkt_serialize_exit(ifp->if_serializer);
2745
2746         return (0);
2747 }
2748
2749 /*
2750  * Device resume routine.  Restore some PCI settings in case the BIOS
2751  * doesn't, re-enable busmastering, and restart the interface if
2752  * appropriate.
2753  */
2754 static int
2755 re_resume(device_t dev)
2756 {
2757         struct re_softc *sc = device_get_softc(dev);
2758         struct ifnet *ifp = &sc->arpcom.ac_if;
2759 #ifndef BURN_BRIDGES
2760         int i;
2761 #endif
2762
2763         lwkt_serialize_enter(ifp->if_serializer);
2764
2765 #ifndef BURN_BRIDGES
2766         /* better way to do this? */
2767         for (i = 0; i < 5; i++)
2768                 pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
2769         pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
2770         pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
2771         pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
2772         pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
2773
2774         /* reenable busmastering */
2775         pci_enable_busmaster(dev);
2776         pci_enable_io(dev, SYS_RES_IOPORT);
2777 #endif
2778
2779         /* reinitialize interface if necessary */
2780         if (ifp->if_flags & IFF_UP)
2781                 re_init(sc);
2782
2783         sc->suspended = 0;
2784
2785         lwkt_serialize_exit(ifp->if_serializer);
2786
2787         return (0);
2788 }
2789
2790 /*
2791  * Stop all chip I/O so that the kernel's probe routines don't
2792  * get confused by errant DMAs when rebooting.
2793  */
2794 static void
2795 re_shutdown(device_t dev)
2796 {
2797         struct re_softc *sc = device_get_softc(dev);
2798         struct ifnet *ifp = &sc->arpcom.ac_if;
2799
2800         lwkt_serialize_enter(ifp->if_serializer);
2801         re_stop(sc);
2802         lwkt_serialize_exit(ifp->if_serializer);
2803 }
2804
2805 static int
2806 re_sysctl_tx_moderation(SYSCTL_HANDLER_ARGS)
2807 {
2808         struct re_softc *sc = arg1;
2809         struct ifnet *ifp = &sc->arpcom.ac_if;
2810         int error = 0, mod, mod_old;
2811
2812         lwkt_serialize_enter(ifp->if_serializer);
2813
2814         mod_old = mod = RE_TX_MODERATION_IS_ENABLED(sc);
2815
2816         error = sysctl_handle_int(oidp, &mod, 0, req);
2817         if (error || req->newptr == NULL || mod == mod_old)
2818                 goto back;
2819         if (mod != 0 && mod != 1) {
2820                 error = EINVAL;
2821                 goto back;
2822         }
2823
2824         if (mod)
2825                 RE_ENABLE_TX_MODERATION(sc);
2826         else
2827                 RE_DISABLE_TX_MODERATION(sc);
2828
2829         if ((ifp->if_flags & (IFF_RUNNING | IFF_UP)) == (IFF_RUNNING | IFF_UP))
2830                 re_init(sc);
2831 back:
2832         lwkt_serialize_exit(ifp->if_serializer);
2833         return error;
2834 }
2835
2836 static int
2837 re_pad_frame(struct mbuf *pkt)
2838 {
2839         struct mbuf *last = NULL;
2840         int padlen;
2841
2842         padlen = RE_MIN_FRAMELEN - pkt->m_pkthdr.len;
2843
2844         /* if there's only the packet-header and we can pad there, use it. */
2845         if (pkt->m_pkthdr.len == pkt->m_len &&
2846             M_TRAILINGSPACE(pkt) >= padlen) {
2847                 last = pkt;
2848         } else {
2849                 /*
2850                  * Walk packet chain to find last mbuf. We will either
2851                  * pad there, or append a new mbuf and pad it
2852                  */
2853                 for (last = pkt; last->m_next != NULL; last = last->m_next)
2854                         ; /* EMPTY */
2855
2856                 /* `last' now points to last in chain. */
2857                 if (M_TRAILINGSPACE(last) < padlen) {
2858                         struct mbuf *n;
2859
2860                         /* Allocate new empty mbuf, pad it.  Compact later. */
2861                         MGET(n, MB_DONTWAIT, MT_DATA);
2862                         if (n == NULL)
2863                                 return ENOBUFS;
2864                         n->m_len = 0;
2865                         last->m_next = n;
2866                         last = n;
2867                 }
2868         }
2869         KKASSERT(M_TRAILINGSPACE(last) >= padlen);
2870         KKASSERT(M_WRITABLE(last));
2871
2872         /* Now zero the pad area, to avoid the re cksum-assist bug */
2873         bzero(mtod(last, char *) + last->m_len, padlen);
2874         last->m_len += padlen;
2875         pkt->m_pkthdr.len += padlen;
2876         return 0;
2877 }