]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/re/if_re.c
sys/{x86,amd64}: remove one of doubled ;s
[FreeBSD/FreeBSD.git] / sys / dev / re / if_re.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1997, 1998-2003
5  *      Bill Paul <wpaul@windriver.com>.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by Bill Paul.
18  * 4. Neither the name of the author nor the names of any co-contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
32  * THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 /*
39  * RealTek 8139C+/8169/8169S/8110S/8168/8111/8101E PCI NIC driver
40  *
41  * Written by Bill Paul <wpaul@windriver.com>
42  * Senior Networking Software Engineer
43  * Wind River Systems
44  */
45
46 /*
47  * This driver is designed to support RealTek's next generation of
48  * 10/100 and 10/100/1000 PCI ethernet controllers. There are currently
49  * seven devices in this family: the RTL8139C+, the RTL8169, the RTL8169S,
50  * RTL8110S, the RTL8168, the RTL8111 and the RTL8101E.
51  *
52  * The 8139C+ is a 10/100 ethernet chip. It is backwards compatible
53  * with the older 8139 family, however it also supports a special
54  * C+ mode of operation that provides several new performance enhancing
55  * features. These include:
56  *
57  *      o Descriptor based DMA mechanism. Each descriptor represents
58  *        a single packet fragment. Data buffers may be aligned on
59  *        any byte boundary.
60  *
61  *      o 64-bit DMA
62  *
63  *      o TCP/IP checksum offload for both RX and TX
64  *
65  *      o High and normal priority transmit DMA rings
66  *
67  *      o VLAN tag insertion and extraction
68  *
69  *      o TCP large send (segmentation offload)
70  *
71  * Like the 8139, the 8139C+ also has a built-in 10/100 PHY. The C+
72  * programming API is fairly straightforward. The RX filtering, EEPROM
73  * access and PHY access is the same as it is on the older 8139 series
74  * chips.
75  *
76  * The 8169 is a 64-bit 10/100/1000 gigabit ethernet MAC. It has almost the
77  * same programming API and feature set as the 8139C+ with the following
78  * differences and additions:
79  *
80  *      o 1000Mbps mode
81  *
82  *      o Jumbo frames
83  *
84  *      o GMII and TBI ports/registers for interfacing with copper
85  *        or fiber PHYs
86  *
87  *      o RX and TX DMA rings can have up to 1024 descriptors
88  *        (the 8139C+ allows a maximum of 64)
89  *
90  *      o Slight differences in register layout from the 8139C+
91  *
92  * The TX start and timer interrupt registers are at different locations
93  * on the 8169 than they are on the 8139C+. Also, the status word in the
94  * RX descriptor has a slightly different bit layout. The 8169 does not
95  * have a built-in PHY. Most reference boards use a Marvell 88E1000 'Alaska'
96  * copper gigE PHY.
97  *
98  * The 8169S/8110S 10/100/1000 devices have built-in copper gigE PHYs
99  * (the 'S' stands for 'single-chip'). These devices have the same
100  * programming API as the older 8169, but also have some vendor-specific
101  * registers for the on-board PHY. The 8110S is a LAN-on-motherboard
102  * part designed to be pin-compatible with the RealTek 8100 10/100 chip.
103  *
104  * This driver takes advantage of the RX and TX checksum offload and
105  * VLAN tag insertion/extraction features. It also implements TX
106  * interrupt moderation using the timer interrupt registers, which
107  * significantly reduces TX interrupt load. There is also support
108  * for jumbo frames, however the 8169/8169S/8110S can not transmit
109  * jumbo frames larger than 7440, so the max MTU possible with this
110  * driver is 7422 bytes.
111  */
112
113 #ifdef HAVE_KERNEL_OPTION_HEADERS
114 #include "opt_device_polling.h"
115 #endif
116
117 #include <sys/param.h>
118 #include <sys/endian.h>
119 #include <sys/systm.h>
120 #include <sys/sockio.h>
121 #include <sys/mbuf.h>
122 #include <sys/malloc.h>
123 #include <sys/module.h>
124 #include <sys/kernel.h>
125 #include <sys/socket.h>
126 #include <sys/lock.h>
127 #include <sys/mutex.h>
128 #include <sys/sysctl.h>
129 #include <sys/taskqueue.h>
130
131 #include <net/if.h>
132 #include <net/if_var.h>
133 #include <net/if_arp.h>
134 #include <net/ethernet.h>
135 #include <net/if_dl.h>
136 #include <net/if_media.h>
137 #include <net/if_types.h>
138 #include <net/if_vlan_var.h>
139
140 #include <net/bpf.h>
141
142 #include <netinet/netdump/netdump.h>
143
144 #include <machine/bus.h>
145 #include <machine/resource.h>
146 #include <sys/bus.h>
147 #include <sys/rman.h>
148
149 #include <dev/mii/mii.h>
150 #include <dev/mii/miivar.h>
151
152 #include <dev/pci/pcireg.h>
153 #include <dev/pci/pcivar.h>
154
155 #include <dev/rl/if_rlreg.h>
156
157 MODULE_DEPEND(re, pci, 1, 1, 1);
158 MODULE_DEPEND(re, ether, 1, 1, 1);
159 MODULE_DEPEND(re, miibus, 1, 1, 1);
160
161 /* "device miibus" required.  See GENERIC if you get errors here. */
162 #include "miibus_if.h"
163
164 /* Tunables. */
165 static int intr_filter = 0;
166 TUNABLE_INT("hw.re.intr_filter", &intr_filter);
167 static int msi_disable = 0;
168 TUNABLE_INT("hw.re.msi_disable", &msi_disable);
169 static int msix_disable = 0;
170 TUNABLE_INT("hw.re.msix_disable", &msix_disable);
171 static int prefer_iomap = 0;
172 TUNABLE_INT("hw.re.prefer_iomap", &prefer_iomap);
173
174 #define RE_CSUM_FEATURES    (CSUM_IP | CSUM_TCP | CSUM_UDP)
175
176 /*
177  * Various supported device vendors/types and their names.
178  */
179 static const struct rl_type re_devs[] = {
180         { DLINK_VENDORID, DLINK_DEVICEID_528T, 0,
181             "D-Link DGE-528(T) Gigabit Ethernet Adapter" },
182         { DLINK_VENDORID, DLINK_DEVICEID_530T_REVC, 0,
183             "D-Link DGE-530(T) Gigabit Ethernet Adapter" },
184         { RT_VENDORID, RT_DEVICEID_8139, 0,
185             "RealTek 8139C+ 10/100BaseTX" },
186         { RT_VENDORID, RT_DEVICEID_8101E, 0,
187             "RealTek 810xE PCIe 10/100baseTX" },
188         { RT_VENDORID, RT_DEVICEID_8168, 0,
189             "RealTek 8168/8111 B/C/CP/D/DP/E/F/G PCIe Gigabit Ethernet" },
190         { NCUBE_VENDORID, RT_DEVICEID_8168, 0,
191             "TP-Link TG-3468 v2 (RTL8168) Gigabit Ethernet" },
192         { RT_VENDORID, RT_DEVICEID_8169, 0,
193             "RealTek 8169/8169S/8169SB(L)/8110S/8110SB(L) Gigabit Ethernet" },
194         { RT_VENDORID, RT_DEVICEID_8169SC, 0,
195             "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
196         { COREGA_VENDORID, COREGA_DEVICEID_CGLAPCIGT, 0,
197             "Corega CG-LAPCIGT (RTL8169S) Gigabit Ethernet" },
198         { LINKSYS_VENDORID, LINKSYS_DEVICEID_EG1032, 0,
199             "Linksys EG1032 (RTL8169S) Gigabit Ethernet" },
200         { USR_VENDORID, USR_DEVICEID_997902, 0,
201             "US Robotics 997902 (RTL8169S) Gigabit Ethernet" }
202 };
203
204 static const struct rl_hwrev re_hwrevs[] = {
205         { RL_HWREV_8139, RL_8139, "", RL_MTU },
206         { RL_HWREV_8139A, RL_8139, "A", RL_MTU },
207         { RL_HWREV_8139AG, RL_8139, "A-G", RL_MTU },
208         { RL_HWREV_8139B, RL_8139, "B", RL_MTU },
209         { RL_HWREV_8130, RL_8139, "8130", RL_MTU },
210         { RL_HWREV_8139C, RL_8139, "C", RL_MTU },
211         { RL_HWREV_8139D, RL_8139, "8139D/8100B/8100C", RL_MTU },
212         { RL_HWREV_8139CPLUS, RL_8139CPLUS, "C+", RL_MTU },
213         { RL_HWREV_8168B_SPIN1, RL_8169, "8168", RL_JUMBO_MTU },
214         { RL_HWREV_8169, RL_8169, "8169", RL_JUMBO_MTU },
215         { RL_HWREV_8169S, RL_8169, "8169S", RL_JUMBO_MTU },
216         { RL_HWREV_8110S, RL_8169, "8110S", RL_JUMBO_MTU },
217         { RL_HWREV_8169_8110SB, RL_8169, "8169SB/8110SB", RL_JUMBO_MTU },
218         { RL_HWREV_8169_8110SC, RL_8169, "8169SC/8110SC", RL_JUMBO_MTU },
219         { RL_HWREV_8169_8110SBL, RL_8169, "8169SBL/8110SBL", RL_JUMBO_MTU },
220         { RL_HWREV_8169_8110SCE, RL_8169, "8169SC/8110SC", RL_JUMBO_MTU },
221         { RL_HWREV_8100, RL_8139, "8100", RL_MTU },
222         { RL_HWREV_8101, RL_8139, "8101", RL_MTU },
223         { RL_HWREV_8100E, RL_8169, "8100E", RL_MTU },
224         { RL_HWREV_8101E, RL_8169, "8101E", RL_MTU },
225         { RL_HWREV_8102E, RL_8169, "8102E", RL_MTU },
226         { RL_HWREV_8102EL, RL_8169, "8102EL", RL_MTU },
227         { RL_HWREV_8102EL_SPIN1, RL_8169, "8102EL", RL_MTU },
228         { RL_HWREV_8103E, RL_8169, "8103E", RL_MTU },
229         { RL_HWREV_8401E, RL_8169, "8401E", RL_MTU },
230         { RL_HWREV_8402, RL_8169, "8402", RL_MTU },
231         { RL_HWREV_8105E, RL_8169, "8105E", RL_MTU },
232         { RL_HWREV_8105E_SPIN1, RL_8169, "8105E", RL_MTU },
233         { RL_HWREV_8106E, RL_8169, "8106E", RL_MTU },
234         { RL_HWREV_8168B_SPIN2, RL_8169, "8168", RL_JUMBO_MTU },
235         { RL_HWREV_8168B_SPIN3, RL_8169, "8168", RL_JUMBO_MTU },
236         { RL_HWREV_8168C, RL_8169, "8168C/8111C", RL_JUMBO_MTU_6K },
237         { RL_HWREV_8168C_SPIN2, RL_8169, "8168C/8111C", RL_JUMBO_MTU_6K },
238         { RL_HWREV_8168CP, RL_8169, "8168CP/8111CP", RL_JUMBO_MTU_6K },
239         { RL_HWREV_8168D, RL_8169, "8168D/8111D", RL_JUMBO_MTU_9K },
240         { RL_HWREV_8168DP, RL_8169, "8168DP/8111DP", RL_JUMBO_MTU_9K },
241         { RL_HWREV_8168E, RL_8169, "8168E/8111E", RL_JUMBO_MTU_9K},
242         { RL_HWREV_8168E_VL, RL_8169, "8168E/8111E-VL", RL_JUMBO_MTU_6K},
243         { RL_HWREV_8168EP, RL_8169, "8168EP/8111EP", RL_JUMBO_MTU_9K},
244         { RL_HWREV_8168F, RL_8169, "8168F/8111F", RL_JUMBO_MTU_9K},
245         { RL_HWREV_8168G, RL_8169, "8168G/8111G", RL_JUMBO_MTU_9K},
246         { RL_HWREV_8168GU, RL_8169, "8168GU/8111GU", RL_JUMBO_MTU_9K},
247         { RL_HWREV_8168H, RL_8169, "8168H/8111H", RL_JUMBO_MTU_9K},
248         { RL_HWREV_8411, RL_8169, "8411", RL_JUMBO_MTU_9K},
249         { RL_HWREV_8411B, RL_8169, "8411B", RL_JUMBO_MTU_9K},
250         { 0, 0, NULL, 0 }
251 };
252
253 static int re_probe             (device_t);
254 static int re_attach            (device_t);
255 static int re_detach            (device_t);
256
257 static int re_encap             (struct rl_softc *, struct mbuf **);
258
259 static void re_dma_map_addr     (void *, bus_dma_segment_t *, int, int);
260 static int re_allocmem          (device_t, struct rl_softc *);
261 static __inline void re_discard_rxbuf
262                                 (struct rl_softc *, int);
263 static int re_newbuf            (struct rl_softc *, int);
264 static int re_jumbo_newbuf      (struct rl_softc *, int);
265 static int re_rx_list_init      (struct rl_softc *);
266 static int re_jrx_list_init     (struct rl_softc *);
267 static int re_tx_list_init      (struct rl_softc *);
268 #ifdef RE_FIXUP_RX
269 static __inline void re_fixup_rx
270                                 (struct mbuf *);
271 #endif
272 static int re_rxeof             (struct rl_softc *, int *);
273 static void re_txeof            (struct rl_softc *);
274 #ifdef DEVICE_POLLING
275 static int re_poll              (struct ifnet *, enum poll_cmd, int);
276 static int re_poll_locked       (struct ifnet *, enum poll_cmd, int);
277 #endif
278 static int re_intr              (void *);
279 static void re_intr_msi         (void *);
280 static void re_tick             (void *);
281 static void re_int_task         (void *, int);
282 static void re_start            (struct ifnet *);
283 static void re_start_locked     (struct ifnet *);
284 static void re_start_tx         (struct rl_softc *);
285 static int re_ioctl             (struct ifnet *, u_long, caddr_t);
286 static void re_init             (void *);
287 static void re_init_locked      (struct rl_softc *);
288 static void re_stop             (struct rl_softc *);
289 static void re_watchdog         (struct rl_softc *);
290 static int re_suspend           (device_t);
291 static int re_resume            (device_t);
292 static int re_shutdown          (device_t);
293 static int re_ifmedia_upd       (struct ifnet *);
294 static void re_ifmedia_sts      (struct ifnet *, struct ifmediareq *);
295
296 static void re_eeprom_putbyte   (struct rl_softc *, int);
297 static void re_eeprom_getword   (struct rl_softc *, int, u_int16_t *);
298 static void re_read_eeprom      (struct rl_softc *, caddr_t, int, int);
299 static int re_gmii_readreg      (device_t, int, int);
300 static int re_gmii_writereg     (device_t, int, int, int);
301
302 static int re_miibus_readreg    (device_t, int, int);
303 static int re_miibus_writereg   (device_t, int, int, int);
304 static void re_miibus_statchg   (device_t);
305
306 static void re_set_jumbo        (struct rl_softc *, int);
307 static void re_set_rxmode               (struct rl_softc *);
308 static void re_reset            (struct rl_softc *);
309 static void re_setwol           (struct rl_softc *);
310 static void re_clrwol           (struct rl_softc *);
311 static void re_set_linkspeed    (struct rl_softc *);
312
313 NETDUMP_DEFINE(re);
314
315 #ifdef DEV_NETMAP       /* see ixgbe.c for details */
316 #include <dev/netmap/if_re_netmap.h>
317 MODULE_DEPEND(re, netmap, 1, 1, 1);
318 #endif /* !DEV_NETMAP */
319
320 #ifdef RE_DIAG
321 static int re_diag              (struct rl_softc *);
322 #endif
323
324 static void re_add_sysctls      (struct rl_softc *);
325 static int re_sysctl_stats      (SYSCTL_HANDLER_ARGS);
326 static int sysctl_int_range     (SYSCTL_HANDLER_ARGS, int, int);
327 static int sysctl_hw_re_int_mod (SYSCTL_HANDLER_ARGS);
328
329 static device_method_t re_methods[] = {
330         /* Device interface */
331         DEVMETHOD(device_probe,         re_probe),
332         DEVMETHOD(device_attach,        re_attach),
333         DEVMETHOD(device_detach,        re_detach),
334         DEVMETHOD(device_suspend,       re_suspend),
335         DEVMETHOD(device_resume,        re_resume),
336         DEVMETHOD(device_shutdown,      re_shutdown),
337
338         /* MII interface */
339         DEVMETHOD(miibus_readreg,       re_miibus_readreg),
340         DEVMETHOD(miibus_writereg,      re_miibus_writereg),
341         DEVMETHOD(miibus_statchg,       re_miibus_statchg),
342
343         DEVMETHOD_END
344 };
345
346 static driver_t re_driver = {
347         "re",
348         re_methods,
349         sizeof(struct rl_softc)
350 };
351
352 static devclass_t re_devclass;
353
354 DRIVER_MODULE(re, pci, re_driver, re_devclass, 0, 0);
355 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
356
357 #define EE_SET(x)                                       \
358         CSR_WRITE_1(sc, RL_EECMD,                       \
359                 CSR_READ_1(sc, RL_EECMD) | x)
360
361 #define EE_CLR(x)                                       \
362         CSR_WRITE_1(sc, RL_EECMD,                       \
363                 CSR_READ_1(sc, RL_EECMD) & ~x)
364
365 /*
366  * Send a read command and address to the EEPROM, check for ACK.
367  */
368 static void
369 re_eeprom_putbyte(struct rl_softc *sc, int addr)
370 {
371         int                     d, i;
372
373         d = addr | (RL_9346_READ << sc->rl_eewidth);
374
375         /*
376          * Feed in each bit and strobe the clock.
377          */
378
379         for (i = 1 << (sc->rl_eewidth + 3); i; i >>= 1) {
380                 if (d & i) {
381                         EE_SET(RL_EE_DATAIN);
382                 } else {
383                         EE_CLR(RL_EE_DATAIN);
384                 }
385                 DELAY(100);
386                 EE_SET(RL_EE_CLK);
387                 DELAY(150);
388                 EE_CLR(RL_EE_CLK);
389                 DELAY(100);
390         }
391 }
392
393 /*
394  * Read a word of data stored in the EEPROM at address 'addr.'
395  */
396 static void
397 re_eeprom_getword(struct rl_softc *sc, int addr, u_int16_t *dest)
398 {
399         int                     i;
400         u_int16_t               word = 0;
401
402         /*
403          * Send address of word we want to read.
404          */
405         re_eeprom_putbyte(sc, addr);
406
407         /*
408          * Start reading bits from EEPROM.
409          */
410         for (i = 0x8000; i; i >>= 1) {
411                 EE_SET(RL_EE_CLK);
412                 DELAY(100);
413                 if (CSR_READ_1(sc, RL_EECMD) & RL_EE_DATAOUT)
414                         word |= i;
415                 EE_CLR(RL_EE_CLK);
416                 DELAY(100);
417         }
418
419         *dest = word;
420 }
421
422 /*
423  * Read a sequence of words from the EEPROM.
424  */
425 static void
426 re_read_eeprom(struct rl_softc *sc, caddr_t dest, int off, int cnt)
427 {
428         int                     i;
429         u_int16_t               word = 0, *ptr;
430
431         CSR_SETBIT_1(sc, RL_EECMD, RL_EEMODE_PROGRAM);
432
433         DELAY(100);
434
435         for (i = 0; i < cnt; i++) {
436                 CSR_SETBIT_1(sc, RL_EECMD, RL_EE_SEL);
437                 re_eeprom_getword(sc, off + i, &word);
438                 CSR_CLRBIT_1(sc, RL_EECMD, RL_EE_SEL);
439                 ptr = (u_int16_t *)(dest + (i * 2));
440                 *ptr = word;
441         }
442
443         CSR_CLRBIT_1(sc, RL_EECMD, RL_EEMODE_PROGRAM);
444 }
445
446 static int
447 re_gmii_readreg(device_t dev, int phy, int reg)
448 {
449         struct rl_softc         *sc;
450         u_int32_t               rval;
451         int                     i;
452
453         sc = device_get_softc(dev);
454
455         /* Let the rgephy driver read the GMEDIASTAT register */
456
457         if (reg == RL_GMEDIASTAT) {
458                 rval = CSR_READ_1(sc, RL_GMEDIASTAT);
459                 return (rval);
460         }
461
462         CSR_WRITE_4(sc, RL_PHYAR, reg << 16);
463
464         for (i = 0; i < RL_PHY_TIMEOUT; i++) {
465                 rval = CSR_READ_4(sc, RL_PHYAR);
466                 if (rval & RL_PHYAR_BUSY)
467                         break;
468                 DELAY(25);
469         }
470
471         if (i == RL_PHY_TIMEOUT) {
472                 device_printf(sc->rl_dev, "PHY read failed\n");
473                 return (0);
474         }
475
476         /*
477          * Controller requires a 20us delay to process next MDIO request.
478          */
479         DELAY(20);
480
481         return (rval & RL_PHYAR_PHYDATA);
482 }
483
484 static int
485 re_gmii_writereg(device_t dev, int phy, int reg, int data)
486 {
487         struct rl_softc         *sc;
488         u_int32_t               rval;
489         int                     i;
490
491         sc = device_get_softc(dev);
492
493         CSR_WRITE_4(sc, RL_PHYAR, (reg << 16) |
494             (data & RL_PHYAR_PHYDATA) | RL_PHYAR_BUSY);
495
496         for (i = 0; i < RL_PHY_TIMEOUT; i++) {
497                 rval = CSR_READ_4(sc, RL_PHYAR);
498                 if (!(rval & RL_PHYAR_BUSY))
499                         break;
500                 DELAY(25);
501         }
502
503         if (i == RL_PHY_TIMEOUT) {
504                 device_printf(sc->rl_dev, "PHY write failed\n");
505                 return (0);
506         }
507
508         /*
509          * Controller requires a 20us delay to process next MDIO request.
510          */
511         DELAY(20);
512
513         return (0);
514 }
515
516 static int
517 re_miibus_readreg(device_t dev, int phy, int reg)
518 {
519         struct rl_softc         *sc;
520         u_int16_t               rval = 0;
521         u_int16_t               re8139_reg = 0;
522
523         sc = device_get_softc(dev);
524
525         if (sc->rl_type == RL_8169) {
526                 rval = re_gmii_readreg(dev, phy, reg);
527                 return (rval);
528         }
529
530         switch (reg) {
531         case MII_BMCR:
532                 re8139_reg = RL_BMCR;
533                 break;
534         case MII_BMSR:
535                 re8139_reg = RL_BMSR;
536                 break;
537         case MII_ANAR:
538                 re8139_reg = RL_ANAR;
539                 break;
540         case MII_ANER:
541                 re8139_reg = RL_ANER;
542                 break;
543         case MII_ANLPAR:
544                 re8139_reg = RL_LPAR;
545                 break;
546         case MII_PHYIDR1:
547         case MII_PHYIDR2:
548                 return (0);
549         /*
550          * Allow the rlphy driver to read the media status
551          * register. If we have a link partner which does not
552          * support NWAY, this is the register which will tell
553          * us the results of parallel detection.
554          */
555         case RL_MEDIASTAT:
556                 rval = CSR_READ_1(sc, RL_MEDIASTAT);
557                 return (rval);
558         default:
559                 device_printf(sc->rl_dev, "bad phy register\n");
560                 return (0);
561         }
562         rval = CSR_READ_2(sc, re8139_reg);
563         if (sc->rl_type == RL_8139CPLUS && re8139_reg == RL_BMCR) {
564                 /* 8139C+ has different bit layout. */
565                 rval &= ~(BMCR_LOOP | BMCR_ISO);
566         }
567         return (rval);
568 }
569
570 static int
571 re_miibus_writereg(device_t dev, int phy, int reg, int data)
572 {
573         struct rl_softc         *sc;
574         u_int16_t               re8139_reg = 0;
575         int                     rval = 0;
576
577         sc = device_get_softc(dev);
578
579         if (sc->rl_type == RL_8169) {
580                 rval = re_gmii_writereg(dev, phy, reg, data);
581                 return (rval);
582         }
583
584         switch (reg) {
585         case MII_BMCR:
586                 re8139_reg = RL_BMCR;
587                 if (sc->rl_type == RL_8139CPLUS) {
588                         /* 8139C+ has different bit layout. */
589                         data &= ~(BMCR_LOOP | BMCR_ISO);
590                 }
591                 break;
592         case MII_BMSR:
593                 re8139_reg = RL_BMSR;
594                 break;
595         case MII_ANAR:
596                 re8139_reg = RL_ANAR;
597                 break;
598         case MII_ANER:
599                 re8139_reg = RL_ANER;
600                 break;
601         case MII_ANLPAR:
602                 re8139_reg = RL_LPAR;
603                 break;
604         case MII_PHYIDR1:
605         case MII_PHYIDR2:
606                 return (0);
607                 break;
608         default:
609                 device_printf(sc->rl_dev, "bad phy register\n");
610                 return (0);
611         }
612         CSR_WRITE_2(sc, re8139_reg, data);
613         return (0);
614 }
615
616 static void
617 re_miibus_statchg(device_t dev)
618 {
619         struct rl_softc         *sc;
620         struct ifnet            *ifp;
621         struct mii_data         *mii;
622
623         sc = device_get_softc(dev);
624         mii = device_get_softc(sc->rl_miibus);
625         ifp = sc->rl_ifp;
626         if (mii == NULL || ifp == NULL ||
627             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
628                 return;
629
630         sc->rl_flags &= ~RL_FLAG_LINK;
631         if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
632             (IFM_ACTIVE | IFM_AVALID)) {
633                 switch (IFM_SUBTYPE(mii->mii_media_active)) {
634                 case IFM_10_T:
635                 case IFM_100_TX:
636                         sc->rl_flags |= RL_FLAG_LINK;
637                         break;
638                 case IFM_1000_T:
639                         if ((sc->rl_flags & RL_FLAG_FASTETHER) != 0)
640                                 break;
641                         sc->rl_flags |= RL_FLAG_LINK;
642                         break;
643                 default:
644                         break;
645                 }
646         }
647         /*
648          * RealTek controllers do not provide any interface to the RX/TX
649          * MACs for resolved speed, duplex and flow-control parameters.
650          */
651 }
652
653 /*
654  * Set the RX configuration and 64-bit multicast hash filter.
655  */
656 static void
657 re_set_rxmode(struct rl_softc *sc)
658 {
659         struct ifnet            *ifp;
660         struct ifmultiaddr      *ifma;
661         uint32_t                hashes[2] = { 0, 0 };
662         uint32_t                h, rxfilt;
663
664         RL_LOCK_ASSERT(sc);
665
666         ifp = sc->rl_ifp;
667
668         rxfilt = RL_RXCFG_CONFIG | RL_RXCFG_RX_INDIV | RL_RXCFG_RX_BROAD;
669         if ((sc->rl_flags & RL_FLAG_EARLYOFF) != 0)
670                 rxfilt |= RL_RXCFG_EARLYOFF;
671         else if ((sc->rl_flags & RL_FLAG_8168G_PLUS) != 0)
672                 rxfilt |= RL_RXCFG_EARLYOFFV2;
673
674         if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) {
675                 if (ifp->if_flags & IFF_PROMISC)
676                         rxfilt |= RL_RXCFG_RX_ALLPHYS;
677                 /*
678                  * Unlike other hardwares, we have to explicitly set
679                  * RL_RXCFG_RX_MULTI to receive multicast frames in
680                  * promiscuous mode.
681                  */
682                 rxfilt |= RL_RXCFG_RX_MULTI;
683                 hashes[0] = hashes[1] = 0xffffffff;
684                 goto done;
685         }
686
687         if_maddr_rlock(ifp);
688         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
689                 if (ifma->ifma_addr->sa_family != AF_LINK)
690                         continue;
691                 h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
692                     ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
693                 if (h < 32)
694                         hashes[0] |= (1 << h);
695                 else
696                         hashes[1] |= (1 << (h - 32));
697         }
698         if_maddr_runlock(ifp);
699
700         if (hashes[0] != 0 || hashes[1] != 0) {
701                 /*
702                  * For some unfathomable reason, RealTek decided to
703                  * reverse the order of the multicast hash registers
704                  * in the PCI Express parts.  This means we have to
705                  * write the hash pattern in reverse order for those
706                  * devices.
707                  */
708                 if ((sc->rl_flags & RL_FLAG_PCIE) != 0) {
709                         h = bswap32(hashes[0]);
710                         hashes[0] = bswap32(hashes[1]);
711                         hashes[1] = h;
712                 }
713                 rxfilt |= RL_RXCFG_RX_MULTI;
714         }
715
716         if  (sc->rl_hwrev->rl_rev == RL_HWREV_8168F) {
717                 /* Disable multicast filtering due to silicon bug. */
718                 hashes[0] = 0xffffffff;
719                 hashes[1] = 0xffffffff;
720         }
721
722 done:
723         CSR_WRITE_4(sc, RL_MAR0, hashes[0]);
724         CSR_WRITE_4(sc, RL_MAR4, hashes[1]);
725         CSR_WRITE_4(sc, RL_RXCFG, rxfilt);
726 }
727
728 static void
729 re_reset(struct rl_softc *sc)
730 {
731         int                     i;
732
733         RL_LOCK_ASSERT(sc);
734
735         CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RESET);
736
737         for (i = 0; i < RL_TIMEOUT; i++) {
738                 DELAY(10);
739                 if (!(CSR_READ_1(sc, RL_COMMAND) & RL_CMD_RESET))
740                         break;
741         }
742         if (i == RL_TIMEOUT)
743                 device_printf(sc->rl_dev, "reset never completed!\n");
744
745         if ((sc->rl_flags & RL_FLAG_MACRESET) != 0)
746                 CSR_WRITE_1(sc, 0x82, 1);
747         if (sc->rl_hwrev->rl_rev == RL_HWREV_8169S)
748                 re_gmii_writereg(sc->rl_dev, 1, 0x0b, 0);
749 }
750
751 #ifdef RE_DIAG
752
753 /*
754  * The following routine is designed to test for a defect on some
755  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
756  * lines connected to the bus, however for a 32-bit only card, they
757  * should be pulled high. The result of this defect is that the
758  * NIC will not work right if you plug it into a 64-bit slot: DMA
759  * operations will be done with 64-bit transfers, which will fail
760  * because the 64-bit data lines aren't connected.
761  *
762  * There's no way to work around this (short of talking a soldering
763  * iron to the board), however we can detect it. The method we use
764  * here is to put the NIC into digital loopback mode, set the receiver
765  * to promiscuous mode, and then try to send a frame. We then compare
766  * the frame data we sent to what was received. If the data matches,
767  * then the NIC is working correctly, otherwise we know the user has
768  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
769  * slot. In the latter case, there's no way the NIC can work correctly,
770  * so we print out a message on the console and abort the device attach.
771  */
772
773 static int
774 re_diag(struct rl_softc *sc)
775 {
776         struct ifnet            *ifp = sc->rl_ifp;
777         struct mbuf             *m0;
778         struct ether_header     *eh;
779         struct rl_desc          *cur_rx;
780         u_int16_t               status;
781         u_int32_t               rxstat;
782         int                     total_len, i, error = 0, phyaddr;
783         u_int8_t                dst[] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
784         u_int8_t                src[] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
785
786         /* Allocate a single mbuf */
787         MGETHDR(m0, M_NOWAIT, MT_DATA);
788         if (m0 == NULL)
789                 return (ENOBUFS);
790
791         RL_LOCK(sc);
792
793         /*
794          * Initialize the NIC in test mode. This sets the chip up
795          * so that it can send and receive frames, but performs the
796          * following special functions:
797          * - Puts receiver in promiscuous mode
798          * - Enables digital loopback mode
799          * - Leaves interrupts turned off
800          */
801
802         ifp->if_flags |= IFF_PROMISC;
803         sc->rl_testmode = 1;
804         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
805         re_init_locked(sc);
806         sc->rl_flags |= RL_FLAG_LINK;
807         if (sc->rl_type == RL_8169)
808                 phyaddr = 1;
809         else
810                 phyaddr = 0;
811
812         re_miibus_writereg(sc->rl_dev, phyaddr, MII_BMCR, BMCR_RESET);
813         for (i = 0; i < RL_TIMEOUT; i++) {
814                 status = re_miibus_readreg(sc->rl_dev, phyaddr, MII_BMCR);
815                 if (!(status & BMCR_RESET))
816                         break;
817         }
818
819         re_miibus_writereg(sc->rl_dev, phyaddr, MII_BMCR, BMCR_LOOP);
820         CSR_WRITE_2(sc, RL_ISR, RL_INTRS);
821
822         DELAY(100000);
823
824         /* Put some data in the mbuf */
825
826         eh = mtod(m0, struct ether_header *);
827         bcopy ((char *)&dst, eh->ether_dhost, ETHER_ADDR_LEN);
828         bcopy ((char *)&src, eh->ether_shost, ETHER_ADDR_LEN);
829         eh->ether_type = htons(ETHERTYPE_IP);
830         m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
831
832         /*
833          * Queue the packet, start transmission.
834          * Note: IF_HANDOFF() ultimately calls re_start() for us.
835          */
836
837         CSR_WRITE_2(sc, RL_ISR, 0xFFFF);
838         RL_UNLOCK(sc);
839         /* XXX: re_diag must not be called when in ALTQ mode */
840         IF_HANDOFF(&ifp->if_snd, m0, ifp);
841         RL_LOCK(sc);
842         m0 = NULL;
843
844         /* Wait for it to propagate through the chip */
845
846         DELAY(100000);
847         for (i = 0; i < RL_TIMEOUT; i++) {
848                 status = CSR_READ_2(sc, RL_ISR);
849                 CSR_WRITE_2(sc, RL_ISR, status);
850                 if ((status & (RL_ISR_TIMEOUT_EXPIRED|RL_ISR_RX_OK)) ==
851                     (RL_ISR_TIMEOUT_EXPIRED|RL_ISR_RX_OK))
852                         break;
853                 DELAY(10);
854         }
855
856         if (i == RL_TIMEOUT) {
857                 device_printf(sc->rl_dev,
858                     "diagnostic failed, failed to receive packet in"
859                     " loopback mode\n");
860                 error = EIO;
861                 goto done;
862         }
863
864         /*
865          * The packet should have been dumped into the first
866          * entry in the RX DMA ring. Grab it from there.
867          */
868
869         bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
870             sc->rl_ldata.rl_rx_list_map,
871             BUS_DMASYNC_POSTREAD);
872         bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
873             sc->rl_ldata.rl_rx_desc[0].rx_dmamap,
874             BUS_DMASYNC_POSTREAD);
875         bus_dmamap_unload(sc->rl_ldata.rl_rx_mtag,
876             sc->rl_ldata.rl_rx_desc[0].rx_dmamap);
877
878         m0 = sc->rl_ldata.rl_rx_desc[0].rx_m;
879         sc->rl_ldata.rl_rx_desc[0].rx_m = NULL;
880         eh = mtod(m0, struct ether_header *);
881
882         cur_rx = &sc->rl_ldata.rl_rx_list[0];
883         total_len = RL_RXBYTES(cur_rx);
884         rxstat = le32toh(cur_rx->rl_cmdstat);
885
886         if (total_len != ETHER_MIN_LEN) {
887                 device_printf(sc->rl_dev,
888                     "diagnostic failed, received short packet\n");
889                 error = EIO;
890                 goto done;
891         }
892
893         /* Test that the received packet data matches what we sent. */
894
895         if (bcmp((char *)&eh->ether_dhost, (char *)&dst, ETHER_ADDR_LEN) ||
896             bcmp((char *)&eh->ether_shost, (char *)&src, ETHER_ADDR_LEN) ||
897             ntohs(eh->ether_type) != ETHERTYPE_IP) {
898                 device_printf(sc->rl_dev, "WARNING, DMA FAILURE!\n");
899                 device_printf(sc->rl_dev, "expected TX data: %6D/%6D/0x%x\n",
900                     dst, ":", src, ":", ETHERTYPE_IP);
901                 device_printf(sc->rl_dev, "received RX data: %6D/%6D/0x%x\n",
902                     eh->ether_dhost, ":", eh->ether_shost, ":",
903                     ntohs(eh->ether_type));
904                 device_printf(sc->rl_dev, "You may have a defective 32-bit "
905                     "NIC plugged into a 64-bit PCI slot.\n");
906                 device_printf(sc->rl_dev, "Please re-install the NIC in a "
907                     "32-bit slot for proper operation.\n");
908                 device_printf(sc->rl_dev, "Read the re(4) man page for more "
909                     "details.\n");
910                 error = EIO;
911         }
912
913 done:
914         /* Turn interface off, release resources */
915
916         sc->rl_testmode = 0;
917         sc->rl_flags &= ~RL_FLAG_LINK;
918         ifp->if_flags &= ~IFF_PROMISC;
919         re_stop(sc);
920         if (m0 != NULL)
921                 m_freem(m0);
922
923         RL_UNLOCK(sc);
924
925         return (error);
926 }
927
928 #endif
929
930 /*
931  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
932  * IDs against our list and return a device name if we find a match.
933  */
934 static int
935 re_probe(device_t dev)
936 {
937         const struct rl_type    *t;
938         uint16_t                devid, vendor;
939         uint16_t                revid, sdevid;
940         int                     i;
941
942         vendor = pci_get_vendor(dev);
943         devid = pci_get_device(dev);
944         revid = pci_get_revid(dev);
945         sdevid = pci_get_subdevice(dev);
946
947         if (vendor == LINKSYS_VENDORID && devid == LINKSYS_DEVICEID_EG1032) {
948                 if (sdevid != LINKSYS_SUBDEVICE_EG1032_REV3) {
949                         /*
950                          * Only attach to rev. 3 of the Linksys EG1032 adapter.
951                          * Rev. 2 is supported by sk(4).
952                          */
953                         return (ENXIO);
954                 }
955         }
956
957         if (vendor == RT_VENDORID && devid == RT_DEVICEID_8139) {
958                 if (revid != 0x20) {
959                         /* 8139, let rl(4) take care of this device. */
960                         return (ENXIO);
961                 }
962         }
963
964         t = re_devs;
965         for (i = 0; i < nitems(re_devs); i++, t++) {
966                 if (vendor == t->rl_vid && devid == t->rl_did) {
967                         device_set_desc(dev, t->rl_name);
968                         return (BUS_PROBE_DEFAULT);
969                 }
970         }
971
972         return (ENXIO);
973 }
974
975 /*
976  * Map a single buffer address.
977  */
978
979 static void
980 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
981 {
982         bus_addr_t              *addr;
983
984         if (error)
985                 return;
986
987         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
988         addr = arg;
989         *addr = segs->ds_addr;
990 }
991
992 static int
993 re_allocmem(device_t dev, struct rl_softc *sc)
994 {
995         bus_addr_t              lowaddr;
996         bus_size_t              rx_list_size, tx_list_size;
997         int                     error;
998         int                     i;
999
1000         rx_list_size = sc->rl_ldata.rl_rx_desc_cnt * sizeof(struct rl_desc);
1001         tx_list_size = sc->rl_ldata.rl_tx_desc_cnt * sizeof(struct rl_desc);
1002
1003         /*
1004          * Allocate the parent bus DMA tag appropriate for PCI.
1005          * In order to use DAC, RL_CPLUSCMD_PCI_DAC bit of RL_CPLUS_CMD
1006          * register should be set. However some RealTek chips are known
1007          * to be buggy on DAC handling, therefore disable DAC by limiting
1008          * DMA address space to 32bit. PCIe variants of RealTek chips
1009          * may not have the limitation.
1010          */
1011         lowaddr = BUS_SPACE_MAXADDR;
1012         if ((sc->rl_flags & RL_FLAG_PCIE) == 0)
1013                 lowaddr = BUS_SPACE_MAXADDR_32BIT;
1014         error = bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
1015             lowaddr, BUS_SPACE_MAXADDR, NULL, NULL,
1016             BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT, 0,
1017             NULL, NULL, &sc->rl_parent_tag);
1018         if (error) {
1019                 device_printf(dev, "could not allocate parent DMA tag\n");
1020                 return (error);
1021         }
1022
1023         /*
1024          * Allocate map for TX mbufs.
1025          */
1026         error = bus_dma_tag_create(sc->rl_parent_tag, 1, 0,
1027             BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
1028             NULL, MCLBYTES * RL_NTXSEGS, RL_NTXSEGS, 4096, 0,
1029             NULL, NULL, &sc->rl_ldata.rl_tx_mtag);
1030         if (error) {
1031                 device_printf(dev, "could not allocate TX DMA tag\n");
1032                 return (error);
1033         }
1034
1035         /*
1036          * Allocate map for RX mbufs.
1037          */
1038
1039         if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0) {
1040                 error = bus_dma_tag_create(sc->rl_parent_tag, sizeof(uint64_t),
1041                     0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1042                     MJUM9BYTES, 1, MJUM9BYTES, 0, NULL, NULL,
1043                     &sc->rl_ldata.rl_jrx_mtag);
1044                 if (error) {
1045                         device_printf(dev,
1046                             "could not allocate jumbo RX DMA tag\n");
1047                         return (error);
1048                 }
1049         }
1050         error = bus_dma_tag_create(sc->rl_parent_tag, sizeof(uint64_t), 0,
1051             BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1052             MCLBYTES, 1, MCLBYTES, 0, NULL, NULL, &sc->rl_ldata.rl_rx_mtag);
1053         if (error) {
1054                 device_printf(dev, "could not allocate RX DMA tag\n");
1055                 return (error);
1056         }
1057
1058         /*
1059          * Allocate map for TX descriptor list.
1060          */
1061         error = bus_dma_tag_create(sc->rl_parent_tag, RL_RING_ALIGN,
1062             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1063             NULL, tx_list_size, 1, tx_list_size, 0,
1064             NULL, NULL, &sc->rl_ldata.rl_tx_list_tag);
1065         if (error) {
1066                 device_printf(dev, "could not allocate TX DMA ring tag\n");
1067                 return (error);
1068         }
1069
1070         /* Allocate DMA'able memory for the TX ring */
1071
1072         error = bus_dmamem_alloc(sc->rl_ldata.rl_tx_list_tag,
1073             (void **)&sc->rl_ldata.rl_tx_list,
1074             BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO,
1075             &sc->rl_ldata.rl_tx_list_map);
1076         if (error) {
1077                 device_printf(dev, "could not allocate TX DMA ring\n");
1078                 return (error);
1079         }
1080
1081         /* Load the map for the TX ring. */
1082
1083         sc->rl_ldata.rl_tx_list_addr = 0;
1084         error = bus_dmamap_load(sc->rl_ldata.rl_tx_list_tag,
1085              sc->rl_ldata.rl_tx_list_map, sc->rl_ldata.rl_tx_list,
1086              tx_list_size, re_dma_map_addr,
1087              &sc->rl_ldata.rl_tx_list_addr, BUS_DMA_NOWAIT);
1088         if (error != 0 || sc->rl_ldata.rl_tx_list_addr == 0) {
1089                 device_printf(dev, "could not load TX DMA ring\n");
1090                 return (ENOMEM);
1091         }
1092
1093         /* Create DMA maps for TX buffers */
1094
1095         for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++) {
1096                 error = bus_dmamap_create(sc->rl_ldata.rl_tx_mtag, 0,
1097                     &sc->rl_ldata.rl_tx_desc[i].tx_dmamap);
1098                 if (error) {
1099                         device_printf(dev, "could not create DMA map for TX\n");
1100                         return (error);
1101                 }
1102         }
1103
1104         /*
1105          * Allocate map for RX descriptor list.
1106          */
1107         error = bus_dma_tag_create(sc->rl_parent_tag, RL_RING_ALIGN,
1108             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
1109             NULL, rx_list_size, 1, rx_list_size, 0,
1110             NULL, NULL, &sc->rl_ldata.rl_rx_list_tag);
1111         if (error) {
1112                 device_printf(dev, "could not create RX DMA ring tag\n");
1113                 return (error);
1114         }
1115
1116         /* Allocate DMA'able memory for the RX ring */
1117
1118         error = bus_dmamem_alloc(sc->rl_ldata.rl_rx_list_tag,
1119             (void **)&sc->rl_ldata.rl_rx_list,
1120             BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO,
1121             &sc->rl_ldata.rl_rx_list_map);
1122         if (error) {
1123                 device_printf(dev, "could not allocate RX DMA ring\n");
1124                 return (error);
1125         }
1126
1127         /* Load the map for the RX ring. */
1128
1129         sc->rl_ldata.rl_rx_list_addr = 0;
1130         error = bus_dmamap_load(sc->rl_ldata.rl_rx_list_tag,
1131              sc->rl_ldata.rl_rx_list_map, sc->rl_ldata.rl_rx_list,
1132              rx_list_size, re_dma_map_addr,
1133              &sc->rl_ldata.rl_rx_list_addr, BUS_DMA_NOWAIT);
1134         if (error != 0 || sc->rl_ldata.rl_rx_list_addr == 0) {
1135                 device_printf(dev, "could not load RX DMA ring\n");
1136                 return (ENOMEM);
1137         }
1138
1139         /* Create DMA maps for RX buffers */
1140
1141         if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0) {
1142                 error = bus_dmamap_create(sc->rl_ldata.rl_jrx_mtag, 0,
1143                     &sc->rl_ldata.rl_jrx_sparemap);
1144                 if (error) {
1145                         device_printf(dev,
1146                             "could not create spare DMA map for jumbo RX\n");
1147                         return (error);
1148                 }
1149                 for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
1150                         error = bus_dmamap_create(sc->rl_ldata.rl_jrx_mtag, 0,
1151                             &sc->rl_ldata.rl_jrx_desc[i].rx_dmamap);
1152                         if (error) {
1153                                 device_printf(dev,
1154                                     "could not create DMA map for jumbo RX\n");
1155                                 return (error);
1156                         }
1157                 }
1158         }
1159         error = bus_dmamap_create(sc->rl_ldata.rl_rx_mtag, 0,
1160             &sc->rl_ldata.rl_rx_sparemap);
1161         if (error) {
1162                 device_printf(dev, "could not create spare DMA map for RX\n");
1163                 return (error);
1164         }
1165         for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
1166                 error = bus_dmamap_create(sc->rl_ldata.rl_rx_mtag, 0,
1167                     &sc->rl_ldata.rl_rx_desc[i].rx_dmamap);
1168                 if (error) {
1169                         device_printf(dev, "could not create DMA map for RX\n");
1170                         return (error);
1171                 }
1172         }
1173
1174         /* Create DMA map for statistics. */
1175         error = bus_dma_tag_create(sc->rl_parent_tag, RL_DUMP_ALIGN, 0,
1176             BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1177             sizeof(struct rl_stats), 1, sizeof(struct rl_stats), 0, NULL, NULL,
1178             &sc->rl_ldata.rl_stag);
1179         if (error) {
1180                 device_printf(dev, "could not create statistics DMA tag\n");
1181                 return (error);
1182         }
1183         /* Allocate DMA'able memory for statistics. */
1184         error = bus_dmamem_alloc(sc->rl_ldata.rl_stag,
1185             (void **)&sc->rl_ldata.rl_stats,
1186             BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO,
1187             &sc->rl_ldata.rl_smap);
1188         if (error) {
1189                 device_printf(dev,
1190                     "could not allocate statistics DMA memory\n");
1191                 return (error);
1192         }
1193         /* Load the map for statistics. */
1194         sc->rl_ldata.rl_stats_addr = 0;
1195         error = bus_dmamap_load(sc->rl_ldata.rl_stag, sc->rl_ldata.rl_smap,
1196             sc->rl_ldata.rl_stats, sizeof(struct rl_stats), re_dma_map_addr,
1197              &sc->rl_ldata.rl_stats_addr, BUS_DMA_NOWAIT);
1198         if (error != 0 || sc->rl_ldata.rl_stats_addr == 0) {
1199                 device_printf(dev, "could not load statistics DMA memory\n");
1200                 return (ENOMEM);
1201         }
1202
1203         return (0);
1204 }
1205
1206 /*
1207  * Attach the interface. Allocate softc structures, do ifmedia
1208  * setup and ethernet/BPF attach.
1209  */
1210 static int
1211 re_attach(device_t dev)
1212 {
1213         u_char                  eaddr[ETHER_ADDR_LEN];
1214         u_int16_t               as[ETHER_ADDR_LEN / 2];
1215         struct rl_softc         *sc;
1216         struct ifnet            *ifp;
1217         const struct rl_hwrev   *hw_rev;
1218         int                     capmask, error = 0, hwrev, i, msic, msixc,
1219                                 phy, reg, rid;
1220         u_int32_t               cap, ctl;
1221         u_int16_t               devid, re_did = 0;
1222         uint8_t                 cfg;
1223
1224         sc = device_get_softc(dev);
1225         sc->rl_dev = dev;
1226
1227         mtx_init(&sc->rl_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
1228             MTX_DEF);
1229         callout_init_mtx(&sc->rl_stat_callout, &sc->rl_mtx, 0);
1230
1231         /*
1232          * Map control/status registers.
1233          */
1234         pci_enable_busmaster(dev);
1235
1236         devid = pci_get_device(dev);
1237         /*
1238          * Prefer memory space register mapping over IO space.
1239          * Because RTL8169SC does not seem to work when memory mapping
1240          * is used always activate io mapping.
1241          */
1242         if (devid == RT_DEVICEID_8169SC)
1243                 prefer_iomap = 1;
1244         if (prefer_iomap == 0) {
1245                 sc->rl_res_id = PCIR_BAR(1);
1246                 sc->rl_res_type = SYS_RES_MEMORY;
1247                 /* RTL8168/8101E seems to use different BARs. */
1248                 if (devid == RT_DEVICEID_8168 || devid == RT_DEVICEID_8101E)
1249                         sc->rl_res_id = PCIR_BAR(2);
1250         } else {
1251                 sc->rl_res_id = PCIR_BAR(0);
1252                 sc->rl_res_type = SYS_RES_IOPORT;
1253         }
1254         sc->rl_res = bus_alloc_resource_any(dev, sc->rl_res_type,
1255             &sc->rl_res_id, RF_ACTIVE);
1256         if (sc->rl_res == NULL && prefer_iomap == 0) {
1257                 sc->rl_res_id = PCIR_BAR(0);
1258                 sc->rl_res_type = SYS_RES_IOPORT;
1259                 sc->rl_res = bus_alloc_resource_any(dev, sc->rl_res_type,
1260                     &sc->rl_res_id, RF_ACTIVE);
1261         }
1262         if (sc->rl_res == NULL) {
1263                 device_printf(dev, "couldn't map ports/memory\n");
1264                 error = ENXIO;
1265                 goto fail;
1266         }
1267
1268         sc->rl_btag = rman_get_bustag(sc->rl_res);
1269         sc->rl_bhandle = rman_get_bushandle(sc->rl_res);
1270
1271         msic = pci_msi_count(dev);
1272         msixc = pci_msix_count(dev);
1273         if (pci_find_cap(dev, PCIY_EXPRESS, &reg) == 0) {
1274                 sc->rl_flags |= RL_FLAG_PCIE;
1275                 sc->rl_expcap = reg;
1276         }
1277         if (bootverbose) {
1278                 device_printf(dev, "MSI count : %d\n", msic);
1279                 device_printf(dev, "MSI-X count : %d\n", msixc);
1280         }
1281         if (msix_disable > 0)
1282                 msixc = 0;
1283         if (msi_disable > 0)
1284                 msic = 0;
1285         /* Prefer MSI-X to MSI. */
1286         if (msixc > 0) {
1287                 msixc = RL_MSI_MESSAGES;
1288                 rid = PCIR_BAR(4);
1289                 sc->rl_res_pba = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
1290                     &rid, RF_ACTIVE);
1291                 if (sc->rl_res_pba == NULL) {
1292                         device_printf(sc->rl_dev,
1293                             "could not allocate MSI-X PBA resource\n");
1294                 }
1295                 if (sc->rl_res_pba != NULL &&
1296                     pci_alloc_msix(dev, &msixc) == 0) {
1297                         if (msixc == RL_MSI_MESSAGES) {
1298                                 device_printf(dev, "Using %d MSI-X message\n",
1299                                     msixc);
1300                                 sc->rl_flags |= RL_FLAG_MSIX;
1301                         } else
1302                                 pci_release_msi(dev);
1303                 }
1304                 if ((sc->rl_flags & RL_FLAG_MSIX) == 0) {
1305                         if (sc->rl_res_pba != NULL)
1306                                 bus_release_resource(dev, SYS_RES_MEMORY, rid,
1307                                     sc->rl_res_pba);
1308                         sc->rl_res_pba = NULL;
1309                         msixc = 0;
1310                 }
1311         }
1312         /* Prefer MSI to INTx. */
1313         if (msixc == 0 && msic > 0) {
1314                 msic = RL_MSI_MESSAGES;
1315                 if (pci_alloc_msi(dev, &msic) == 0) {
1316                         if (msic == RL_MSI_MESSAGES) {
1317                                 device_printf(dev, "Using %d MSI message\n",
1318                                     msic);
1319                                 sc->rl_flags |= RL_FLAG_MSI;
1320                                 /* Explicitly set MSI enable bit. */
1321                                 CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
1322                                 cfg = CSR_READ_1(sc, RL_CFG2);
1323                                 cfg |= RL_CFG2_MSI;
1324                                 CSR_WRITE_1(sc, RL_CFG2, cfg);
1325                                 CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1326                         } else
1327                                 pci_release_msi(dev);
1328                 }
1329                 if ((sc->rl_flags & RL_FLAG_MSI) == 0)
1330                         msic = 0;
1331         }
1332
1333         /* Allocate interrupt */
1334         if ((sc->rl_flags & (RL_FLAG_MSI | RL_FLAG_MSIX)) == 0) {
1335                 rid = 0;
1336                 sc->rl_irq[0] = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1337                     RF_SHAREABLE | RF_ACTIVE);
1338                 if (sc->rl_irq[0] == NULL) {
1339                         device_printf(dev, "couldn't allocate IRQ resources\n");
1340                         error = ENXIO;
1341                         goto fail;
1342                 }
1343         } else {
1344                 for (i = 0, rid = 1; i < RL_MSI_MESSAGES; i++, rid++) {
1345                         sc->rl_irq[i] = bus_alloc_resource_any(dev,
1346                             SYS_RES_IRQ, &rid, RF_ACTIVE);
1347                         if (sc->rl_irq[i] == NULL) {
1348                                 device_printf(dev,
1349                                     "couldn't allocate IRQ resources for "
1350                                     "message %d\n", rid);
1351                                 error = ENXIO;
1352                                 goto fail;
1353                         }
1354                 }
1355         }
1356
1357         if ((sc->rl_flags & RL_FLAG_MSI) == 0) {
1358                 CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
1359                 cfg = CSR_READ_1(sc, RL_CFG2);
1360                 if ((cfg & RL_CFG2_MSI) != 0) {
1361                         device_printf(dev, "turning off MSI enable bit.\n");
1362                         cfg &= ~RL_CFG2_MSI;
1363                         CSR_WRITE_1(sc, RL_CFG2, cfg);
1364                 }
1365                 CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1366         }
1367
1368         /* Disable ASPM L0S/L1 and CLKREQ. */
1369         if (sc->rl_expcap != 0) {
1370                 cap = pci_read_config(dev, sc->rl_expcap +
1371                     PCIER_LINK_CAP, 2);
1372                 if ((cap & PCIEM_LINK_CAP_ASPM) != 0) {
1373                         ctl = pci_read_config(dev, sc->rl_expcap +
1374                             PCIER_LINK_CTL, 2);
1375                         if ((ctl & (PCIEM_LINK_CTL_ECPM |
1376                             PCIEM_LINK_CTL_ASPMC))!= 0) {
1377                                 ctl &= ~(PCIEM_LINK_CTL_ECPM |
1378                                     PCIEM_LINK_CTL_ASPMC);
1379                                 pci_write_config(dev, sc->rl_expcap +
1380                                     PCIER_LINK_CTL, ctl, 2);
1381                                 device_printf(dev, "ASPM disabled\n");
1382                         }
1383                 } else
1384                         device_printf(dev, "no ASPM capability\n");
1385         }
1386
1387         hw_rev = re_hwrevs;
1388         hwrev = CSR_READ_4(sc, RL_TXCFG);
1389         switch (hwrev & 0x70000000) {
1390         case 0x00000000:
1391         case 0x10000000:
1392                 device_printf(dev, "Chip rev. 0x%08x\n", hwrev & 0xfc800000);
1393                 hwrev &= (RL_TXCFG_HWREV | 0x80000000);
1394                 break;
1395         default:
1396                 device_printf(dev, "Chip rev. 0x%08x\n", hwrev & 0x7c800000);
1397                 sc->rl_macrev = hwrev & 0x00700000;
1398                 hwrev &= RL_TXCFG_HWREV;
1399                 break;
1400         }
1401         device_printf(dev, "MAC rev. 0x%08x\n", sc->rl_macrev);
1402         while (hw_rev->rl_desc != NULL) {
1403                 if (hw_rev->rl_rev == hwrev) {
1404                         sc->rl_type = hw_rev->rl_type;
1405                         sc->rl_hwrev = hw_rev;
1406                         break;
1407                 }
1408                 hw_rev++;
1409         }
1410         if (hw_rev->rl_desc == NULL) {
1411                 device_printf(dev, "Unknown H/W revision: 0x%08x\n", hwrev);
1412                 error = ENXIO;
1413                 goto fail;
1414         }
1415
1416         switch (hw_rev->rl_rev) {
1417         case RL_HWREV_8139CPLUS:
1418                 sc->rl_flags |= RL_FLAG_FASTETHER | RL_FLAG_AUTOPAD;
1419                 break;
1420         case RL_HWREV_8100E:
1421         case RL_HWREV_8101E:
1422                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_FASTETHER;
1423                 break;
1424         case RL_HWREV_8102E:
1425         case RL_HWREV_8102EL:
1426         case RL_HWREV_8102EL_SPIN1:
1427                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR | RL_FLAG_DESCV2 |
1428                     RL_FLAG_MACSTAT | RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP |
1429                     RL_FLAG_AUTOPAD;
1430                 break;
1431         case RL_HWREV_8103E:
1432                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR | RL_FLAG_DESCV2 |
1433                     RL_FLAG_MACSTAT | RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP |
1434                     RL_FLAG_AUTOPAD | RL_FLAG_MACSLEEP;
1435                 break;
1436         case RL_HWREV_8401E:
1437         case RL_HWREV_8105E:
1438         case RL_HWREV_8105E_SPIN1:
1439         case RL_HWREV_8106E:
1440                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
1441                     RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
1442                     RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD;
1443                 break;
1444         case RL_HWREV_8402:
1445                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
1446                     RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
1447                     RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD |
1448                     RL_FLAG_CMDSTOP_WAIT_TXQ;
1449                 break;
1450         case RL_HWREV_8168B_SPIN1:
1451         case RL_HWREV_8168B_SPIN2:
1452                 sc->rl_flags |= RL_FLAG_WOLRXENB;
1453                 /* FALLTHROUGH */
1454         case RL_HWREV_8168B_SPIN3:
1455                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_MACSTAT;
1456                 break;
1457         case RL_HWREV_8168C_SPIN2:
1458                 sc->rl_flags |= RL_FLAG_MACSLEEP;
1459                 /* FALLTHROUGH */
1460         case RL_HWREV_8168C:
1461                 if (sc->rl_macrev == 0x00200000)
1462                         sc->rl_flags |= RL_FLAG_MACSLEEP;
1463                 /* FALLTHROUGH */
1464         case RL_HWREV_8168CP:
1465                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
1466                     RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
1467                     RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 | RL_FLAG_WOL_MANLINK;
1468                 break;
1469         case RL_HWREV_8168D:
1470                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
1471                     RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
1472                     RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 |
1473                     RL_FLAG_WOL_MANLINK;
1474                 break;
1475         case RL_HWREV_8168DP:
1476                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
1477                     RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_AUTOPAD |
1478                     RL_FLAG_JUMBOV2 | RL_FLAG_WAIT_TXPOLL | RL_FLAG_WOL_MANLINK;
1479                 break;
1480         case RL_HWREV_8168E:
1481                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
1482                     RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
1483                     RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 |
1484                     RL_FLAG_WOL_MANLINK;
1485                 break;
1486         case RL_HWREV_8168E_VL:
1487         case RL_HWREV_8168F:
1488                 sc->rl_flags |= RL_FLAG_EARLYOFF;
1489                 /* FALLTHROUGH */
1490         case RL_HWREV_8411:
1491                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
1492                     RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
1493                     RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 |
1494                     RL_FLAG_CMDSTOP_WAIT_TXQ | RL_FLAG_WOL_MANLINK;
1495                 break;
1496         case RL_HWREV_8168EP:
1497         case RL_HWREV_8168G:
1498         case RL_HWREV_8411B:
1499                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
1500                     RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
1501                     RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 |
1502                     RL_FLAG_CMDSTOP_WAIT_TXQ | RL_FLAG_WOL_MANLINK |
1503                     RL_FLAG_8168G_PLUS;
1504                 break;
1505         case RL_HWREV_8168GU:
1506         case RL_HWREV_8168H:
1507                 if (pci_get_device(dev) == RT_DEVICEID_8101E) {
1508                         /* RTL8106E(US), RTL8107E */
1509                         sc->rl_flags |= RL_FLAG_FASTETHER;
1510                 } else
1511                         sc->rl_flags |= RL_FLAG_JUMBOV2 | RL_FLAG_WOL_MANLINK;
1512
1513                 sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
1514                     RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
1515                     RL_FLAG_AUTOPAD | RL_FLAG_CMDSTOP_WAIT_TXQ |
1516                     RL_FLAG_8168G_PLUS;
1517                 break;
1518         case RL_HWREV_8169_8110SB:
1519         case RL_HWREV_8169_8110SBL:
1520         case RL_HWREV_8169_8110SC:
1521         case RL_HWREV_8169_8110SCE:
1522                 sc->rl_flags |= RL_FLAG_PHYWAKE;
1523                 /* FALLTHROUGH */
1524         case RL_HWREV_8169:
1525         case RL_HWREV_8169S:
1526         case RL_HWREV_8110S:
1527                 sc->rl_flags |= RL_FLAG_MACRESET;
1528                 break;
1529         default:
1530                 break;
1531         }
1532
1533         if (sc->rl_hwrev->rl_rev == RL_HWREV_8139CPLUS) {
1534                 sc->rl_cfg0 = RL_8139_CFG0;
1535                 sc->rl_cfg1 = RL_8139_CFG1;
1536                 sc->rl_cfg2 = 0;
1537                 sc->rl_cfg3 = RL_8139_CFG3;
1538                 sc->rl_cfg4 = RL_8139_CFG4;
1539                 sc->rl_cfg5 = RL_8139_CFG5;
1540         } else {
1541                 sc->rl_cfg0 = RL_CFG0;
1542                 sc->rl_cfg1 = RL_CFG1;
1543                 sc->rl_cfg2 = RL_CFG2;
1544                 sc->rl_cfg3 = RL_CFG3;
1545                 sc->rl_cfg4 = RL_CFG4;
1546                 sc->rl_cfg5 = RL_CFG5;
1547         }
1548
1549         /* Reset the adapter. */
1550         RL_LOCK(sc);
1551         re_reset(sc);
1552         RL_UNLOCK(sc);
1553
1554         /* Enable PME. */
1555         CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
1556         cfg = CSR_READ_1(sc, sc->rl_cfg1);
1557         cfg |= RL_CFG1_PME;
1558         CSR_WRITE_1(sc, sc->rl_cfg1, cfg);
1559         cfg = CSR_READ_1(sc, sc->rl_cfg5);
1560         cfg &= RL_CFG5_PME_STS;
1561         CSR_WRITE_1(sc, sc->rl_cfg5, cfg);
1562         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
1563
1564         if ((sc->rl_flags & RL_FLAG_PAR) != 0) {
1565                 /*
1566                  * XXX Should have a better way to extract station
1567                  * address from EEPROM.
1568                  */
1569                 for (i = 0; i < ETHER_ADDR_LEN; i++)
1570                         eaddr[i] = CSR_READ_1(sc, RL_IDR0 + i);
1571         } else {
1572                 sc->rl_eewidth = RL_9356_ADDR_LEN;
1573                 re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
1574                 if (re_did != 0x8129)
1575                         sc->rl_eewidth = RL_9346_ADDR_LEN;
1576
1577                 /*
1578                  * Get station address from the EEPROM.
1579                  */
1580                 re_read_eeprom(sc, (caddr_t)as, RL_EE_EADDR, 3);
1581                 for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
1582                         as[i] = le16toh(as[i]);
1583                 bcopy(as, eaddr, ETHER_ADDR_LEN);
1584         }
1585
1586         if (sc->rl_type == RL_8169) {
1587                 /* Set RX length mask and number of descriptors. */
1588                 sc->rl_rxlenmask = RL_RDESC_STAT_GFRAGLEN;
1589                 sc->rl_txstart = RL_GTXSTART;
1590                 sc->rl_ldata.rl_tx_desc_cnt = RL_8169_TX_DESC_CNT;
1591                 sc->rl_ldata.rl_rx_desc_cnt = RL_8169_RX_DESC_CNT;
1592         } else {
1593                 /* Set RX length mask and number of descriptors. */
1594                 sc->rl_rxlenmask = RL_RDESC_STAT_FRAGLEN;
1595                 sc->rl_txstart = RL_TXSTART;
1596                 sc->rl_ldata.rl_tx_desc_cnt = RL_8139_TX_DESC_CNT;
1597                 sc->rl_ldata.rl_rx_desc_cnt = RL_8139_RX_DESC_CNT;
1598         }
1599
1600         error = re_allocmem(dev, sc);
1601         if (error)
1602                 goto fail;
1603         re_add_sysctls(sc);
1604
1605         ifp = sc->rl_ifp = if_alloc(IFT_ETHER);
1606         if (ifp == NULL) {
1607                 device_printf(dev, "can not if_alloc()\n");
1608                 error = ENOSPC;
1609                 goto fail;
1610         }
1611
1612         /* Take controller out of deep sleep mode. */
1613         if ((sc->rl_flags & RL_FLAG_MACSLEEP) != 0) {
1614                 if ((CSR_READ_1(sc, RL_MACDBG) & 0x80) == 0x80)
1615                         CSR_WRITE_1(sc, RL_GPIO,
1616                             CSR_READ_1(sc, RL_GPIO) | 0x01);
1617                 else
1618                         CSR_WRITE_1(sc, RL_GPIO,
1619                             CSR_READ_1(sc, RL_GPIO) & ~0x01);
1620         }
1621
1622         /* Take PHY out of power down mode. */
1623         if ((sc->rl_flags & RL_FLAG_PHYWAKE_PM) != 0) {
1624                 CSR_WRITE_1(sc, RL_PMCH, CSR_READ_1(sc, RL_PMCH) | 0x80);
1625                 if (hw_rev->rl_rev == RL_HWREV_8401E)
1626                         CSR_WRITE_1(sc, 0xD1, CSR_READ_1(sc, 0xD1) & ~0x08);
1627         }
1628         if ((sc->rl_flags & RL_FLAG_PHYWAKE) != 0) {
1629                 re_gmii_writereg(dev, 1, 0x1f, 0);
1630                 re_gmii_writereg(dev, 1, 0x0e, 0);
1631         }
1632
1633         ifp->if_softc = sc;
1634         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1635         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1636         ifp->if_ioctl = re_ioctl;
1637         ifp->if_start = re_start;
1638         /*
1639          * RTL8168/8111C generates wrong IP checksummed frame if the
1640          * packet has IP options so disable TX checksum offloading.
1641          */
1642         if (sc->rl_hwrev->rl_rev == RL_HWREV_8168C ||
1643             sc->rl_hwrev->rl_rev == RL_HWREV_8168C_SPIN2 ||
1644             sc->rl_hwrev->rl_rev == RL_HWREV_8168CP) {
1645                 ifp->if_hwassist = 0;
1646                 ifp->if_capabilities = IFCAP_RXCSUM | IFCAP_TSO4;
1647         } else {
1648                 ifp->if_hwassist = CSUM_IP | CSUM_TCP | CSUM_UDP;
1649                 ifp->if_capabilities = IFCAP_HWCSUM | IFCAP_TSO4;
1650         }
1651         ifp->if_hwassist |= CSUM_TSO;
1652         ifp->if_capenable = ifp->if_capabilities;
1653         ifp->if_init = re_init;
1654         IFQ_SET_MAXLEN(&ifp->if_snd, RL_IFQ_MAXLEN);
1655         ifp->if_snd.ifq_drv_maxlen = RL_IFQ_MAXLEN;
1656         IFQ_SET_READY(&ifp->if_snd);
1657
1658         TASK_INIT(&sc->rl_inttask, 0, re_int_task, sc);
1659
1660 #define RE_PHYAD_INTERNAL        0
1661
1662         /* Do MII setup. */
1663         phy = RE_PHYAD_INTERNAL;
1664         if (sc->rl_type == RL_8169)
1665                 phy = 1;
1666         capmask = BMSR_DEFCAPMASK;
1667         if ((sc->rl_flags & RL_FLAG_FASTETHER) != 0)
1668                  capmask &= ~BMSR_EXTSTAT;
1669         error = mii_attach(dev, &sc->rl_miibus, ifp, re_ifmedia_upd,
1670             re_ifmedia_sts, capmask, phy, MII_OFFSET_ANY, MIIF_DOPAUSE);
1671         if (error != 0) {
1672                 device_printf(dev, "attaching PHYs failed\n");
1673                 goto fail;
1674         }
1675
1676         /*
1677          * Call MI attach routine.
1678          */
1679         ether_ifattach(ifp, eaddr);
1680
1681         /* VLAN capability setup */
1682         ifp->if_capabilities |= IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1683         if (ifp->if_capabilities & IFCAP_HWCSUM)
1684                 ifp->if_capabilities |= IFCAP_VLAN_HWCSUM;
1685         /* Enable WOL if PM is supported. */
1686         if (pci_find_cap(sc->rl_dev, PCIY_PMG, &reg) == 0)
1687                 ifp->if_capabilities |= IFCAP_WOL;
1688         ifp->if_capenable = ifp->if_capabilities;
1689         ifp->if_capenable &= ~(IFCAP_WOL_UCAST | IFCAP_WOL_MCAST);
1690         /*
1691          * Don't enable TSO by default.  It is known to generate
1692          * corrupted TCP segments(bad TCP options) under certain
1693          * circumstances.
1694          */
1695         ifp->if_hwassist &= ~CSUM_TSO;
1696         ifp->if_capenable &= ~(IFCAP_TSO4 | IFCAP_VLAN_HWTSO);
1697 #ifdef DEVICE_POLLING
1698         ifp->if_capabilities |= IFCAP_POLLING;
1699 #endif
1700         /*
1701          * Tell the upper layer(s) we support long frames.
1702          * Must appear after the call to ether_ifattach() because
1703          * ether_ifattach() sets ifi_hdrlen to the default value.
1704          */
1705         ifp->if_hdrlen = sizeof(struct ether_vlan_header);
1706
1707 #ifdef DEV_NETMAP
1708         re_netmap_attach(sc);
1709 #endif /* DEV_NETMAP */
1710
1711 #ifdef RE_DIAG
1712         /*
1713          * Perform hardware diagnostic on the original RTL8169.
1714          * Some 32-bit cards were incorrectly wired and would
1715          * malfunction if plugged into a 64-bit slot.
1716          */
1717         if (hwrev == RL_HWREV_8169) {
1718                 error = re_diag(sc);
1719                 if (error) {
1720                         device_printf(dev,
1721                         "attach aborted due to hardware diag failure\n");
1722                         ether_ifdetach(ifp);
1723                         goto fail;
1724                 }
1725         }
1726 #endif
1727
1728 #ifdef RE_TX_MODERATION
1729         intr_filter = 1;
1730 #endif
1731         /* Hook interrupt last to avoid having to lock softc */
1732         if ((sc->rl_flags & (RL_FLAG_MSI | RL_FLAG_MSIX)) != 0 &&
1733             intr_filter == 0) {
1734                 error = bus_setup_intr(dev, sc->rl_irq[0],
1735                     INTR_TYPE_NET | INTR_MPSAFE, NULL, re_intr_msi, sc,
1736                     &sc->rl_intrhand[0]);
1737         } else {
1738                 error = bus_setup_intr(dev, sc->rl_irq[0],
1739                     INTR_TYPE_NET | INTR_MPSAFE, re_intr, NULL, sc,
1740                     &sc->rl_intrhand[0]);
1741         }
1742         if (error) {
1743                 device_printf(dev, "couldn't set up irq\n");
1744                 ether_ifdetach(ifp);
1745                 goto fail;
1746         }
1747
1748         NETDUMP_SET(ifp, re);
1749
1750 fail:
1751         if (error)
1752                 re_detach(dev);
1753
1754         return (error);
1755 }
1756
1757 /*
1758  * Shutdown hardware and free up resources. This can be called any
1759  * time after the mutex has been initialized. It is called in both
1760  * the error case in attach and the normal detach case so it needs
1761  * to be careful about only freeing resources that have actually been
1762  * allocated.
1763  */
1764 static int
1765 re_detach(device_t dev)
1766 {
1767         struct rl_softc         *sc;
1768         struct ifnet            *ifp;
1769         int                     i, rid;
1770
1771         sc = device_get_softc(dev);
1772         ifp = sc->rl_ifp;
1773         KASSERT(mtx_initialized(&sc->rl_mtx), ("re mutex not initialized"));
1774
1775         /* These should only be active if attach succeeded */
1776         if (device_is_attached(dev)) {
1777 #ifdef DEVICE_POLLING
1778                 if (ifp->if_capenable & IFCAP_POLLING)
1779                         ether_poll_deregister(ifp);
1780 #endif
1781                 RL_LOCK(sc);
1782 #if 0
1783                 sc->suspended = 1;
1784 #endif
1785                 re_stop(sc);
1786                 RL_UNLOCK(sc);
1787                 callout_drain(&sc->rl_stat_callout);
1788                 taskqueue_drain(taskqueue_fast, &sc->rl_inttask);
1789                 /*
1790                  * Force off the IFF_UP flag here, in case someone
1791                  * still had a BPF descriptor attached to this
1792                  * interface. If they do, ether_ifdetach() will cause
1793                  * the BPF code to try and clear the promisc mode
1794                  * flag, which will bubble down to re_ioctl(),
1795                  * which will try to call re_init() again. This will
1796                  * turn the NIC back on and restart the MII ticker,
1797                  * which will panic the system when the kernel tries
1798                  * to invoke the re_tick() function that isn't there
1799                  * anymore.
1800                  */
1801                 ifp->if_flags &= ~IFF_UP;
1802                 ether_ifdetach(ifp);
1803         }
1804         if (sc->rl_miibus)
1805                 device_delete_child(dev, sc->rl_miibus);
1806         bus_generic_detach(dev);
1807
1808         /*
1809          * The rest is resource deallocation, so we should already be
1810          * stopped here.
1811          */
1812
1813         if (sc->rl_intrhand[0] != NULL) {
1814                 bus_teardown_intr(dev, sc->rl_irq[0], sc->rl_intrhand[0]);
1815                 sc->rl_intrhand[0] = NULL;
1816         }
1817         if (ifp != NULL) {
1818 #ifdef DEV_NETMAP
1819                 netmap_detach(ifp);
1820 #endif /* DEV_NETMAP */
1821                 if_free(ifp);
1822         }
1823         if ((sc->rl_flags & (RL_FLAG_MSI | RL_FLAG_MSIX)) == 0)
1824                 rid = 0;
1825         else
1826                 rid = 1;
1827         if (sc->rl_irq[0] != NULL) {
1828                 bus_release_resource(dev, SYS_RES_IRQ, rid, sc->rl_irq[0]);
1829                 sc->rl_irq[0] = NULL;
1830         }
1831         if ((sc->rl_flags & (RL_FLAG_MSI | RL_FLAG_MSIX)) != 0)
1832                 pci_release_msi(dev);
1833         if (sc->rl_res_pba) {
1834                 rid = PCIR_BAR(4);
1835                 bus_release_resource(dev, SYS_RES_MEMORY, rid, sc->rl_res_pba);
1836         }
1837         if (sc->rl_res)
1838                 bus_release_resource(dev, sc->rl_res_type, sc->rl_res_id,
1839                     sc->rl_res);
1840
1841         /* Unload and free the RX DMA ring memory and map */
1842
1843         if (sc->rl_ldata.rl_rx_list_tag) {
1844                 if (sc->rl_ldata.rl_rx_list_addr)
1845                         bus_dmamap_unload(sc->rl_ldata.rl_rx_list_tag,
1846                             sc->rl_ldata.rl_rx_list_map);
1847                 if (sc->rl_ldata.rl_rx_list)
1848                         bus_dmamem_free(sc->rl_ldata.rl_rx_list_tag,
1849                             sc->rl_ldata.rl_rx_list,
1850                             sc->rl_ldata.rl_rx_list_map);
1851                 bus_dma_tag_destroy(sc->rl_ldata.rl_rx_list_tag);
1852         }
1853
1854         /* Unload and free the TX DMA ring memory and map */
1855
1856         if (sc->rl_ldata.rl_tx_list_tag) {
1857                 if (sc->rl_ldata.rl_tx_list_addr)
1858                         bus_dmamap_unload(sc->rl_ldata.rl_tx_list_tag,
1859                             sc->rl_ldata.rl_tx_list_map);
1860                 if (sc->rl_ldata.rl_tx_list)
1861                         bus_dmamem_free(sc->rl_ldata.rl_tx_list_tag,
1862                             sc->rl_ldata.rl_tx_list,
1863                             sc->rl_ldata.rl_tx_list_map);
1864                 bus_dma_tag_destroy(sc->rl_ldata.rl_tx_list_tag);
1865         }
1866
1867         /* Destroy all the RX and TX buffer maps */
1868
1869         if (sc->rl_ldata.rl_tx_mtag) {
1870                 for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++) {
1871                         if (sc->rl_ldata.rl_tx_desc[i].tx_dmamap)
1872                                 bus_dmamap_destroy(sc->rl_ldata.rl_tx_mtag,
1873                                     sc->rl_ldata.rl_tx_desc[i].tx_dmamap);
1874                 }
1875                 bus_dma_tag_destroy(sc->rl_ldata.rl_tx_mtag);
1876         }
1877         if (sc->rl_ldata.rl_rx_mtag) {
1878                 for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
1879                         if (sc->rl_ldata.rl_rx_desc[i].rx_dmamap)
1880                                 bus_dmamap_destroy(sc->rl_ldata.rl_rx_mtag,
1881                                     sc->rl_ldata.rl_rx_desc[i].rx_dmamap);
1882                 }
1883                 if (sc->rl_ldata.rl_rx_sparemap)
1884                         bus_dmamap_destroy(sc->rl_ldata.rl_rx_mtag,
1885                             sc->rl_ldata.rl_rx_sparemap);
1886                 bus_dma_tag_destroy(sc->rl_ldata.rl_rx_mtag);
1887         }
1888         if (sc->rl_ldata.rl_jrx_mtag) {
1889                 for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
1890                         if (sc->rl_ldata.rl_jrx_desc[i].rx_dmamap)
1891                                 bus_dmamap_destroy(sc->rl_ldata.rl_jrx_mtag,
1892                                     sc->rl_ldata.rl_jrx_desc[i].rx_dmamap);
1893                 }
1894                 if (sc->rl_ldata.rl_jrx_sparemap)
1895                         bus_dmamap_destroy(sc->rl_ldata.rl_jrx_mtag,
1896                             sc->rl_ldata.rl_jrx_sparemap);
1897                 bus_dma_tag_destroy(sc->rl_ldata.rl_jrx_mtag);
1898         }
1899         /* Unload and free the stats buffer and map */
1900
1901         if (sc->rl_ldata.rl_stag) {
1902                 if (sc->rl_ldata.rl_stats_addr)
1903                         bus_dmamap_unload(sc->rl_ldata.rl_stag,
1904                             sc->rl_ldata.rl_smap);
1905                 if (sc->rl_ldata.rl_stats)
1906                         bus_dmamem_free(sc->rl_ldata.rl_stag,
1907                             sc->rl_ldata.rl_stats, sc->rl_ldata.rl_smap);
1908                 bus_dma_tag_destroy(sc->rl_ldata.rl_stag);
1909         }
1910
1911         if (sc->rl_parent_tag)
1912                 bus_dma_tag_destroy(sc->rl_parent_tag);
1913
1914         mtx_destroy(&sc->rl_mtx);
1915
1916         return (0);
1917 }
1918
1919 static __inline void
1920 re_discard_rxbuf(struct rl_softc *sc, int idx)
1921 {
1922         struct rl_desc          *desc;
1923         struct rl_rxdesc        *rxd;
1924         uint32_t                cmdstat;
1925
1926         if (sc->rl_ifp->if_mtu > RL_MTU &&
1927             (sc->rl_flags & RL_FLAG_JUMBOV2) != 0)
1928                 rxd = &sc->rl_ldata.rl_jrx_desc[idx];
1929         else
1930                 rxd = &sc->rl_ldata.rl_rx_desc[idx];
1931         desc = &sc->rl_ldata.rl_rx_list[idx];
1932         desc->rl_vlanctl = 0;
1933         cmdstat = rxd->rx_size;
1934         if (idx == sc->rl_ldata.rl_rx_desc_cnt - 1)
1935                 cmdstat |= RL_RDESC_CMD_EOR;
1936         desc->rl_cmdstat = htole32(cmdstat | RL_RDESC_CMD_OWN);
1937 }
1938
1939 static int
1940 re_newbuf(struct rl_softc *sc, int idx)
1941 {
1942         struct mbuf             *m;
1943         struct rl_rxdesc        *rxd;
1944         bus_dma_segment_t       segs[1];
1945         bus_dmamap_t            map;
1946         struct rl_desc          *desc;
1947         uint32_t                cmdstat;
1948         int                     error, nsegs;
1949
1950         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1951         if (m == NULL)
1952                 return (ENOBUFS);
1953
1954         m->m_len = m->m_pkthdr.len = MCLBYTES;
1955 #ifdef RE_FIXUP_RX
1956         /*
1957          * This is part of an evil trick to deal with non-x86 platforms.
1958          * The RealTek chip requires RX buffers to be aligned on 64-bit
1959          * boundaries, but that will hose non-x86 machines. To get around
1960          * this, we leave some empty space at the start of each buffer
1961          * and for non-x86 hosts, we copy the buffer back six bytes
1962          * to achieve word alignment. This is slightly more efficient
1963          * than allocating a new buffer, copying the contents, and
1964          * discarding the old buffer.
1965          */
1966         m_adj(m, RE_ETHER_ALIGN);
1967 #endif
1968         error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_rx_mtag,
1969             sc->rl_ldata.rl_rx_sparemap, m, segs, &nsegs, BUS_DMA_NOWAIT);
1970         if (error != 0) {
1971                 m_freem(m);
1972                 return (ENOBUFS);
1973         }
1974         KASSERT(nsegs == 1, ("%s: %d segment returned!", __func__, nsegs));
1975
1976         rxd = &sc->rl_ldata.rl_rx_desc[idx];
1977         if (rxd->rx_m != NULL) {
1978                 bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, rxd->rx_dmamap,
1979                     BUS_DMASYNC_POSTREAD);
1980                 bus_dmamap_unload(sc->rl_ldata.rl_rx_mtag, rxd->rx_dmamap);
1981         }
1982
1983         rxd->rx_m = m;
1984         map = rxd->rx_dmamap;
1985         rxd->rx_dmamap = sc->rl_ldata.rl_rx_sparemap;
1986         rxd->rx_size = segs[0].ds_len;
1987         sc->rl_ldata.rl_rx_sparemap = map;
1988         bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, rxd->rx_dmamap,
1989             BUS_DMASYNC_PREREAD);
1990
1991         desc = &sc->rl_ldata.rl_rx_list[idx];
1992         desc->rl_vlanctl = 0;
1993         desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(segs[0].ds_addr));
1994         desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(segs[0].ds_addr));
1995         cmdstat = segs[0].ds_len;
1996         if (idx == sc->rl_ldata.rl_rx_desc_cnt - 1)
1997                 cmdstat |= RL_RDESC_CMD_EOR;
1998         desc->rl_cmdstat = htole32(cmdstat | RL_RDESC_CMD_OWN);
1999
2000         return (0);
2001 }
2002
2003 static int
2004 re_jumbo_newbuf(struct rl_softc *sc, int idx)
2005 {
2006         struct mbuf             *m;
2007         struct rl_rxdesc        *rxd;
2008         bus_dma_segment_t       segs[1];
2009         bus_dmamap_t            map;
2010         struct rl_desc          *desc;
2011         uint32_t                cmdstat;
2012         int                     error, nsegs;
2013
2014         m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUM9BYTES);
2015         if (m == NULL)
2016                 return (ENOBUFS);
2017         m->m_len = m->m_pkthdr.len = MJUM9BYTES;
2018 #ifdef RE_FIXUP_RX
2019         m_adj(m, RE_ETHER_ALIGN);
2020 #endif
2021         error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_jrx_mtag,
2022             sc->rl_ldata.rl_jrx_sparemap, m, segs, &nsegs, BUS_DMA_NOWAIT);
2023         if (error != 0) {
2024                 m_freem(m);
2025                 return (ENOBUFS);
2026         }
2027         KASSERT(nsegs == 1, ("%s: %d segment returned!", __func__, nsegs));
2028
2029         rxd = &sc->rl_ldata.rl_jrx_desc[idx];
2030         if (rxd->rx_m != NULL) {
2031                 bus_dmamap_sync(sc->rl_ldata.rl_jrx_mtag, rxd->rx_dmamap,
2032                     BUS_DMASYNC_POSTREAD);
2033                 bus_dmamap_unload(sc->rl_ldata.rl_jrx_mtag, rxd->rx_dmamap);
2034         }
2035
2036         rxd->rx_m = m;
2037         map = rxd->rx_dmamap;
2038         rxd->rx_dmamap = sc->rl_ldata.rl_jrx_sparemap;
2039         rxd->rx_size = segs[0].ds_len;
2040         sc->rl_ldata.rl_jrx_sparemap = map;
2041         bus_dmamap_sync(sc->rl_ldata.rl_jrx_mtag, rxd->rx_dmamap,
2042             BUS_DMASYNC_PREREAD);
2043
2044         desc = &sc->rl_ldata.rl_rx_list[idx];
2045         desc->rl_vlanctl = 0;
2046         desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(segs[0].ds_addr));
2047         desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(segs[0].ds_addr));
2048         cmdstat = segs[0].ds_len;
2049         if (idx == sc->rl_ldata.rl_rx_desc_cnt - 1)
2050                 cmdstat |= RL_RDESC_CMD_EOR;
2051         desc->rl_cmdstat = htole32(cmdstat | RL_RDESC_CMD_OWN);
2052
2053         return (0);
2054 }
2055
2056 #ifdef RE_FIXUP_RX
2057 static __inline void
2058 re_fixup_rx(struct mbuf *m)
2059 {
2060         int                     i;
2061         uint16_t                *src, *dst;
2062
2063         src = mtod(m, uint16_t *);
2064         dst = src - (RE_ETHER_ALIGN - ETHER_ALIGN) / sizeof *src;
2065
2066         for (i = 0; i < (m->m_len / sizeof(uint16_t) + 1); i++)
2067                 *dst++ = *src++;
2068
2069         m->m_data -= RE_ETHER_ALIGN - ETHER_ALIGN;
2070 }
2071 #endif
2072
2073 static int
2074 re_tx_list_init(struct rl_softc *sc)
2075 {
2076         struct rl_desc          *desc;
2077         int                     i;
2078
2079         RL_LOCK_ASSERT(sc);
2080
2081         bzero(sc->rl_ldata.rl_tx_list,
2082             sc->rl_ldata.rl_tx_desc_cnt * sizeof(struct rl_desc));
2083         for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++)
2084                 sc->rl_ldata.rl_tx_desc[i].tx_m = NULL;
2085 #ifdef DEV_NETMAP
2086         re_netmap_tx_init(sc);
2087 #endif /* DEV_NETMAP */
2088         /* Set EOR. */
2089         desc = &sc->rl_ldata.rl_tx_list[sc->rl_ldata.rl_tx_desc_cnt - 1];
2090         desc->rl_cmdstat |= htole32(RL_TDESC_CMD_EOR);
2091
2092         bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
2093             sc->rl_ldata.rl_tx_list_map,
2094             BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2095
2096         sc->rl_ldata.rl_tx_prodidx = 0;
2097         sc->rl_ldata.rl_tx_considx = 0;
2098         sc->rl_ldata.rl_tx_free = sc->rl_ldata.rl_tx_desc_cnt;
2099
2100         return (0);
2101 }
2102
2103 static int
2104 re_rx_list_init(struct rl_softc *sc)
2105 {
2106         int                     error, i;
2107
2108         bzero(sc->rl_ldata.rl_rx_list,
2109             sc->rl_ldata.rl_rx_desc_cnt * sizeof(struct rl_desc));
2110         for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
2111                 sc->rl_ldata.rl_rx_desc[i].rx_m = NULL;
2112                 if ((error = re_newbuf(sc, i)) != 0)
2113                         return (error);
2114         }
2115 #ifdef DEV_NETMAP
2116         re_netmap_rx_init(sc);
2117 #endif /* DEV_NETMAP */
2118
2119         /* Flush the RX descriptors */
2120
2121         bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
2122             sc->rl_ldata.rl_rx_list_map,
2123             BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
2124
2125         sc->rl_ldata.rl_rx_prodidx = 0;
2126         sc->rl_head = sc->rl_tail = NULL;
2127         sc->rl_int_rx_act = 0;
2128
2129         return (0);
2130 }
2131
2132 static int
2133 re_jrx_list_init(struct rl_softc *sc)
2134 {
2135         int                     error, i;
2136
2137         bzero(sc->rl_ldata.rl_rx_list,
2138             sc->rl_ldata.rl_rx_desc_cnt * sizeof(struct rl_desc));
2139         for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
2140                 sc->rl_ldata.rl_jrx_desc[i].rx_m = NULL;
2141                 if ((error = re_jumbo_newbuf(sc, i)) != 0)
2142                         return (error);
2143         }
2144
2145         bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
2146             sc->rl_ldata.rl_rx_list_map,
2147             BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2148
2149         sc->rl_ldata.rl_rx_prodidx = 0;
2150         sc->rl_head = sc->rl_tail = NULL;
2151         sc->rl_int_rx_act = 0;
2152
2153         return (0);
2154 }
2155
2156 /*
2157  * RX handler for C+ and 8169. For the gigE chips, we support
2158  * the reception of jumbo frames that have been fragmented
2159  * across multiple 2K mbuf cluster buffers.
2160  */
2161 static int
2162 re_rxeof(struct rl_softc *sc, int *rx_npktsp)
2163 {
2164         struct mbuf             *m;
2165         struct ifnet            *ifp;
2166         int                     i, rxerr, total_len;
2167         struct rl_desc          *cur_rx;
2168         u_int32_t               rxstat, rxvlan;
2169         int                     jumbo, maxpkt = 16, rx_npkts = 0;
2170
2171         RL_LOCK_ASSERT(sc);
2172
2173         ifp = sc->rl_ifp;
2174 #ifdef DEV_NETMAP
2175         if (netmap_rx_irq(ifp, 0, &rx_npkts))
2176                 return 0;
2177 #endif /* DEV_NETMAP */
2178         if (ifp->if_mtu > RL_MTU && (sc->rl_flags & RL_FLAG_JUMBOV2) != 0)
2179                 jumbo = 1;
2180         else
2181                 jumbo = 0;
2182
2183         /* Invalidate the descriptor memory */
2184
2185         bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
2186             sc->rl_ldata.rl_rx_list_map,
2187             BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2188
2189         for (i = sc->rl_ldata.rl_rx_prodidx; maxpkt > 0;
2190             i = RL_RX_DESC_NXT(sc, i)) {
2191                 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
2192                         break;
2193                 cur_rx = &sc->rl_ldata.rl_rx_list[i];
2194                 rxstat = le32toh(cur_rx->rl_cmdstat);
2195                 if ((rxstat & RL_RDESC_STAT_OWN) != 0)
2196                         break;
2197                 total_len = rxstat & sc->rl_rxlenmask;
2198                 rxvlan = le32toh(cur_rx->rl_vlanctl);
2199                 if (jumbo != 0)
2200                         m = sc->rl_ldata.rl_jrx_desc[i].rx_m;
2201                 else
2202                         m = sc->rl_ldata.rl_rx_desc[i].rx_m;
2203
2204                 if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0 &&
2205                     (rxstat & (RL_RDESC_STAT_SOF | RL_RDESC_STAT_EOF)) !=
2206                     (RL_RDESC_STAT_SOF | RL_RDESC_STAT_EOF)) {
2207                         /*
2208                          * RTL8168C or later controllers do not
2209                          * support multi-fragment packet.
2210                          */
2211                         re_discard_rxbuf(sc, i);
2212                         continue;
2213                 } else if ((rxstat & RL_RDESC_STAT_EOF) == 0) {
2214                         if (re_newbuf(sc, i) != 0) {
2215                                 /*
2216                                  * If this is part of a multi-fragment packet,
2217                                  * discard all the pieces.
2218                                  */
2219                                 if (sc->rl_head != NULL) {
2220                                         m_freem(sc->rl_head);
2221                                         sc->rl_head = sc->rl_tail = NULL;
2222                                 }
2223                                 re_discard_rxbuf(sc, i);
2224                                 continue;
2225                         }
2226                         m->m_len = RE_RX_DESC_BUFLEN;
2227                         if (sc->rl_head == NULL)
2228                                 sc->rl_head = sc->rl_tail = m;
2229                         else {
2230                                 m->m_flags &= ~M_PKTHDR;
2231                                 sc->rl_tail->m_next = m;
2232                                 sc->rl_tail = m;
2233                         }
2234                         continue;
2235                 }
2236
2237                 /*
2238                  * NOTE: for the 8139C+, the frame length field
2239                  * is always 12 bits in size, but for the gigE chips,
2240                  * it is 13 bits (since the max RX frame length is 16K).
2241                  * Unfortunately, all 32 bits in the status word
2242                  * were already used, so to make room for the extra
2243                  * length bit, RealTek took out the 'frame alignment
2244                  * error' bit and shifted the other status bits
2245                  * over one slot. The OWN, EOR, FS and LS bits are
2246                  * still in the same places. We have already extracted
2247                  * the frame length and checked the OWN bit, so rather
2248                  * than using an alternate bit mapping, we shift the
2249                  * status bits one space to the right so we can evaluate
2250                  * them using the 8169 status as though it was in the
2251                  * same format as that of the 8139C+.
2252                  */
2253                 if (sc->rl_type == RL_8169)
2254                         rxstat >>= 1;
2255
2256                 /*
2257                  * if total_len > 2^13-1, both _RXERRSUM and _GIANT will be
2258                  * set, but if CRC is clear, it will still be a valid frame.
2259                  */
2260                 if ((rxstat & RL_RDESC_STAT_RXERRSUM) != 0) {
2261                         rxerr = 1;
2262                         if ((sc->rl_flags & RL_FLAG_JUMBOV2) == 0 &&
2263                             total_len > 8191 &&
2264                             (rxstat & RL_RDESC_STAT_ERRS) == RL_RDESC_STAT_GIANT)
2265                                 rxerr = 0;
2266                         if (rxerr != 0) {
2267                                 if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2268                                 /*
2269                                  * If this is part of a multi-fragment packet,
2270                                  * discard all the pieces.
2271                                  */
2272                                 if (sc->rl_head != NULL) {
2273                                         m_freem(sc->rl_head);
2274                                         sc->rl_head = sc->rl_tail = NULL;
2275                                 }
2276                                 re_discard_rxbuf(sc, i);
2277                                 continue;
2278                         }
2279                 }
2280
2281                 /*
2282                  * If allocating a replacement mbuf fails,
2283                  * reload the current one.
2284                  */
2285                 if (jumbo != 0)
2286                         rxerr = re_jumbo_newbuf(sc, i);
2287                 else
2288                         rxerr = re_newbuf(sc, i);
2289                 if (rxerr != 0) {
2290                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
2291                         if (sc->rl_head != NULL) {
2292                                 m_freem(sc->rl_head);
2293                                 sc->rl_head = sc->rl_tail = NULL;
2294                         }
2295                         re_discard_rxbuf(sc, i);
2296                         continue;
2297                 }
2298
2299                 if (sc->rl_head != NULL) {
2300                         if (jumbo != 0)
2301                                 m->m_len = total_len;
2302                         else {
2303                                 m->m_len = total_len % RE_RX_DESC_BUFLEN;
2304                                 if (m->m_len == 0)
2305                                         m->m_len = RE_RX_DESC_BUFLEN;
2306                         }
2307                         /*
2308                          * Special case: if there's 4 bytes or less
2309                          * in this buffer, the mbuf can be discarded:
2310                          * the last 4 bytes is the CRC, which we don't
2311                          * care about anyway.
2312                          */
2313                         if (m->m_len <= ETHER_CRC_LEN) {
2314                                 sc->rl_tail->m_len -=
2315                                     (ETHER_CRC_LEN - m->m_len);
2316                                 m_freem(m);
2317                         } else {
2318                                 m->m_len -= ETHER_CRC_LEN;
2319                                 m->m_flags &= ~M_PKTHDR;
2320                                 sc->rl_tail->m_next = m;
2321                         }
2322                         m = sc->rl_head;
2323                         sc->rl_head = sc->rl_tail = NULL;
2324                         m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
2325                 } else
2326                         m->m_pkthdr.len = m->m_len =
2327                             (total_len - ETHER_CRC_LEN);
2328
2329 #ifdef RE_FIXUP_RX
2330                 re_fixup_rx(m);
2331 #endif
2332                 if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
2333                 m->m_pkthdr.rcvif = ifp;
2334
2335                 /* Do RX checksumming if enabled */
2336
2337                 if (ifp->if_capenable & IFCAP_RXCSUM) {
2338                         if ((sc->rl_flags & RL_FLAG_DESCV2) == 0) {
2339                                 /* Check IP header checksum */
2340                                 if (rxstat & RL_RDESC_STAT_PROTOID)
2341                                         m->m_pkthdr.csum_flags |=
2342                                             CSUM_IP_CHECKED;
2343                                 if (!(rxstat & RL_RDESC_STAT_IPSUMBAD))
2344                                         m->m_pkthdr.csum_flags |=
2345                                             CSUM_IP_VALID;
2346
2347                                 /* Check TCP/UDP checksum */
2348                                 if ((RL_TCPPKT(rxstat) &&
2349                                     !(rxstat & RL_RDESC_STAT_TCPSUMBAD)) ||
2350                                     (RL_UDPPKT(rxstat) &&
2351                                      !(rxstat & RL_RDESC_STAT_UDPSUMBAD))) {
2352                                         m->m_pkthdr.csum_flags |=
2353                                                 CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
2354                                         m->m_pkthdr.csum_data = 0xffff;
2355                                 }
2356                         } else {
2357                                 /*
2358                                  * RTL8168C/RTL816CP/RTL8111C/RTL8111CP
2359                                  */
2360                                 if ((rxstat & RL_RDESC_STAT_PROTOID) &&
2361                                     (rxvlan & RL_RDESC_IPV4))
2362                                         m->m_pkthdr.csum_flags |=
2363                                             CSUM_IP_CHECKED;
2364                                 if (!(rxstat & RL_RDESC_STAT_IPSUMBAD) &&
2365                                     (rxvlan & RL_RDESC_IPV4))
2366                                         m->m_pkthdr.csum_flags |=
2367                                             CSUM_IP_VALID;
2368                                 if (((rxstat & RL_RDESC_STAT_TCP) &&
2369                                     !(rxstat & RL_RDESC_STAT_TCPSUMBAD)) ||
2370                                     ((rxstat & RL_RDESC_STAT_UDP) &&
2371                                     !(rxstat & RL_RDESC_STAT_UDPSUMBAD))) {
2372                                         m->m_pkthdr.csum_flags |=
2373                                                 CSUM_DATA_VALID|CSUM_PSEUDO_HDR;
2374                                         m->m_pkthdr.csum_data = 0xffff;
2375                                 }
2376                         }
2377                 }
2378                 maxpkt--;
2379                 if (rxvlan & RL_RDESC_VLANCTL_TAG) {
2380                         m->m_pkthdr.ether_vtag =
2381                             bswap16((rxvlan & RL_RDESC_VLANCTL_DATA));
2382                         m->m_flags |= M_VLANTAG;
2383                 }
2384                 RL_UNLOCK(sc);
2385                 (*ifp->if_input)(ifp, m);
2386                 RL_LOCK(sc);
2387                 rx_npkts++;
2388         }
2389
2390         /* Flush the RX DMA ring */
2391
2392         bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
2393             sc->rl_ldata.rl_rx_list_map,
2394             BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
2395
2396         sc->rl_ldata.rl_rx_prodidx = i;
2397
2398         if (rx_npktsp != NULL)
2399                 *rx_npktsp = rx_npkts;
2400         if (maxpkt)
2401                 return (EAGAIN);
2402
2403         return (0);
2404 }
2405
2406 static void
2407 re_txeof(struct rl_softc *sc)
2408 {
2409         struct ifnet            *ifp;
2410         struct rl_txdesc        *txd;
2411         u_int32_t               txstat;
2412         int                     cons;
2413
2414         cons = sc->rl_ldata.rl_tx_considx;
2415         if (cons == sc->rl_ldata.rl_tx_prodidx)
2416                 return;
2417
2418         ifp = sc->rl_ifp;
2419 #ifdef DEV_NETMAP
2420         if (netmap_tx_irq(ifp, 0))
2421                 return;
2422 #endif /* DEV_NETMAP */
2423         /* Invalidate the TX descriptor list */
2424         bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
2425             sc->rl_ldata.rl_tx_list_map,
2426             BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2427
2428         for (; cons != sc->rl_ldata.rl_tx_prodidx;
2429             cons = RL_TX_DESC_NXT(sc, cons)) {
2430                 txstat = le32toh(sc->rl_ldata.rl_tx_list[cons].rl_cmdstat);
2431                 if (txstat & RL_TDESC_STAT_OWN)
2432                         break;
2433                 /*
2434                  * We only stash mbufs in the last descriptor
2435                  * in a fragment chain, which also happens to
2436                  * be the only place where the TX status bits
2437                  * are valid.
2438                  */
2439                 if (txstat & RL_TDESC_CMD_EOF) {
2440                         txd = &sc->rl_ldata.rl_tx_desc[cons];
2441                         bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
2442                             txd->tx_dmamap, BUS_DMASYNC_POSTWRITE);
2443                         bus_dmamap_unload(sc->rl_ldata.rl_tx_mtag,
2444                             txd->tx_dmamap);
2445                         KASSERT(txd->tx_m != NULL,
2446                             ("%s: freeing NULL mbufs!", __func__));
2447                         m_freem(txd->tx_m);
2448                         txd->tx_m = NULL;
2449                         if (txstat & (RL_TDESC_STAT_EXCESSCOL|
2450                             RL_TDESC_STAT_COLCNT))
2451                                 if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1);
2452                         if (txstat & RL_TDESC_STAT_TXERRSUM)
2453                                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2454                         else
2455                                 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
2456                 }
2457                 sc->rl_ldata.rl_tx_free++;
2458                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2459         }
2460         sc->rl_ldata.rl_tx_considx = cons;
2461
2462         /* No changes made to the TX ring, so no flush needed */
2463
2464         if (sc->rl_ldata.rl_tx_free != sc->rl_ldata.rl_tx_desc_cnt) {
2465 #ifdef RE_TX_MODERATION
2466                 /*
2467                  * If not all descriptors have been reaped yet, reload
2468                  * the timer so that we will eventually get another
2469                  * interrupt that will cause us to re-enter this routine.
2470                  * This is done in case the transmitter has gone idle.
2471                  */
2472                 CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2473 #endif
2474         } else
2475                 sc->rl_watchdog_timer = 0;
2476 }
2477
2478 static void
2479 re_tick(void *xsc)
2480 {
2481         struct rl_softc         *sc;
2482         struct mii_data         *mii;
2483
2484         sc = xsc;
2485
2486         RL_LOCK_ASSERT(sc);
2487
2488         mii = device_get_softc(sc->rl_miibus);
2489         mii_tick(mii);
2490         if ((sc->rl_flags & RL_FLAG_LINK) == 0)
2491                 re_miibus_statchg(sc->rl_dev);
2492         /*
2493          * Reclaim transmitted frames here. Technically it is not
2494          * necessary to do here but it ensures periodic reclamation
2495          * regardless of Tx completion interrupt which seems to be
2496          * lost on PCIe based controllers under certain situations.
2497          */
2498         re_txeof(sc);
2499         re_watchdog(sc);
2500         callout_reset(&sc->rl_stat_callout, hz, re_tick, sc);
2501 }
2502
2503 #ifdef DEVICE_POLLING
2504 static int
2505 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
2506 {
2507         struct rl_softc *sc = ifp->if_softc;
2508         int rx_npkts = 0;
2509
2510         RL_LOCK(sc);
2511         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2512                 rx_npkts = re_poll_locked(ifp, cmd, count);
2513         RL_UNLOCK(sc);
2514         return (rx_npkts);
2515 }
2516
2517 static int
2518 re_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
2519 {
2520         struct rl_softc *sc = ifp->if_softc;
2521         int rx_npkts;
2522
2523         RL_LOCK_ASSERT(sc);
2524
2525         sc->rxcycles = count;
2526         re_rxeof(sc, &rx_npkts);
2527         re_txeof(sc);
2528
2529         if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2530                 re_start_locked(ifp);
2531
2532         if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
2533                 u_int16_t       status;
2534
2535                 status = CSR_READ_2(sc, RL_ISR);
2536                 if (status == 0xffff)
2537                         return (rx_npkts);
2538                 if (status)
2539                         CSR_WRITE_2(sc, RL_ISR, status);
2540                 if ((status & (RL_ISR_TX_OK | RL_ISR_TX_DESC_UNAVAIL)) &&
2541                     (sc->rl_flags & RL_FLAG_PCIE))
2542                         CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2543
2544                 /*
2545                  * XXX check behaviour on receiver stalls.
2546                  */
2547
2548                 if (status & RL_ISR_SYSTEM_ERR) {
2549                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2550                         re_init_locked(sc);
2551                 }
2552         }
2553         return (rx_npkts);
2554 }
2555 #endif /* DEVICE_POLLING */
2556
2557 static int
2558 re_intr(void *arg)
2559 {
2560         struct rl_softc         *sc;
2561         uint16_t                status;
2562
2563         sc = arg;
2564
2565         status = CSR_READ_2(sc, RL_ISR);
2566         if (status == 0xFFFF || (status & RL_INTRS_CPLUS) == 0)
2567                 return (FILTER_STRAY);
2568         CSR_WRITE_2(sc, RL_IMR, 0);
2569
2570         taskqueue_enqueue(taskqueue_fast, &sc->rl_inttask);
2571
2572         return (FILTER_HANDLED);
2573 }
2574
2575 static void
2576 re_int_task(void *arg, int npending)
2577 {
2578         struct rl_softc         *sc;
2579         struct ifnet            *ifp;
2580         u_int16_t               status;
2581         int                     rval = 0;
2582
2583         sc = arg;
2584         ifp = sc->rl_ifp;
2585
2586         RL_LOCK(sc);
2587
2588         status = CSR_READ_2(sc, RL_ISR);
2589         CSR_WRITE_2(sc, RL_ISR, status);
2590
2591         if (sc->suspended ||
2592             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2593                 RL_UNLOCK(sc);
2594                 return;
2595         }
2596
2597 #ifdef DEVICE_POLLING
2598         if  (ifp->if_capenable & IFCAP_POLLING) {
2599                 RL_UNLOCK(sc);
2600                 return;
2601         }
2602 #endif
2603
2604         if (status & (RL_ISR_RX_OK|RL_ISR_RX_ERR|RL_ISR_FIFO_OFLOW))
2605                 rval = re_rxeof(sc, NULL);
2606
2607         /*
2608          * Some chips will ignore a second TX request issued
2609          * while an existing transmission is in progress. If
2610          * the transmitter goes idle but there are still
2611          * packets waiting to be sent, we need to restart the
2612          * channel here to flush them out. This only seems to
2613          * be required with the PCIe devices.
2614          */
2615         if ((status & (RL_ISR_TX_OK | RL_ISR_TX_DESC_UNAVAIL)) &&
2616             (sc->rl_flags & RL_FLAG_PCIE))
2617                 CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2618         if (status & (
2619 #ifdef RE_TX_MODERATION
2620             RL_ISR_TIMEOUT_EXPIRED|
2621 #else
2622             RL_ISR_TX_OK|
2623 #endif
2624             RL_ISR_TX_ERR|RL_ISR_TX_DESC_UNAVAIL))
2625                 re_txeof(sc);
2626
2627         if (status & RL_ISR_SYSTEM_ERR) {
2628                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2629                 re_init_locked(sc);
2630         }
2631
2632         if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2633                 re_start_locked(ifp);
2634
2635         RL_UNLOCK(sc);
2636
2637         if ((CSR_READ_2(sc, RL_ISR) & RL_INTRS_CPLUS) || rval) {
2638                 taskqueue_enqueue(taskqueue_fast, &sc->rl_inttask);
2639                 return;
2640         }
2641
2642         CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
2643 }
2644
2645 static void
2646 re_intr_msi(void *xsc)
2647 {
2648         struct rl_softc         *sc;
2649         struct ifnet            *ifp;
2650         uint16_t                intrs, status;
2651
2652         sc = xsc;
2653         RL_LOCK(sc);
2654
2655         ifp = sc->rl_ifp;
2656 #ifdef DEVICE_POLLING
2657         if (ifp->if_capenable & IFCAP_POLLING) {
2658                 RL_UNLOCK(sc);
2659                 return;
2660         }
2661 #endif
2662         /* Disable interrupts. */
2663         CSR_WRITE_2(sc, RL_IMR, 0);
2664         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2665                 RL_UNLOCK(sc);
2666                 return;
2667         }
2668
2669         intrs = RL_INTRS_CPLUS;
2670         status = CSR_READ_2(sc, RL_ISR);
2671         CSR_WRITE_2(sc, RL_ISR, status);
2672         if (sc->rl_int_rx_act > 0) {
2673                 intrs &= ~(RL_ISR_RX_OK | RL_ISR_RX_ERR | RL_ISR_FIFO_OFLOW |
2674                     RL_ISR_RX_OVERRUN);
2675                 status &= ~(RL_ISR_RX_OK | RL_ISR_RX_ERR | RL_ISR_FIFO_OFLOW |
2676                     RL_ISR_RX_OVERRUN);
2677         }
2678
2679         if (status & (RL_ISR_TIMEOUT_EXPIRED | RL_ISR_RX_OK | RL_ISR_RX_ERR |
2680             RL_ISR_FIFO_OFLOW | RL_ISR_RX_OVERRUN)) {
2681                 re_rxeof(sc, NULL);
2682                 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
2683                         if (sc->rl_int_rx_mod != 0 &&
2684                             (status & (RL_ISR_RX_OK | RL_ISR_RX_ERR |
2685                             RL_ISR_FIFO_OFLOW | RL_ISR_RX_OVERRUN)) != 0) {
2686                                 /* Rearm one-shot timer. */
2687                                 CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2688                                 intrs &= ~(RL_ISR_RX_OK | RL_ISR_RX_ERR |
2689                                     RL_ISR_FIFO_OFLOW | RL_ISR_RX_OVERRUN);
2690                                 sc->rl_int_rx_act = 1;
2691                         } else {
2692                                 intrs |= RL_ISR_RX_OK | RL_ISR_RX_ERR |
2693                                     RL_ISR_FIFO_OFLOW | RL_ISR_RX_OVERRUN;
2694                                 sc->rl_int_rx_act = 0;
2695                         }
2696                 }
2697         }
2698
2699         /*
2700          * Some chips will ignore a second TX request issued
2701          * while an existing transmission is in progress. If
2702          * the transmitter goes idle but there are still
2703          * packets waiting to be sent, we need to restart the
2704          * channel here to flush them out. This only seems to
2705          * be required with the PCIe devices.
2706          */
2707         if ((status & (RL_ISR_TX_OK | RL_ISR_TX_DESC_UNAVAIL)) &&
2708             (sc->rl_flags & RL_FLAG_PCIE))
2709                 CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2710         if (status & (RL_ISR_TX_OK | RL_ISR_TX_ERR | RL_ISR_TX_DESC_UNAVAIL))
2711                 re_txeof(sc);
2712
2713         if (status & RL_ISR_SYSTEM_ERR) {
2714                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2715                 re_init_locked(sc);
2716         }
2717
2718         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
2719                 if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
2720                         re_start_locked(ifp);
2721                 CSR_WRITE_2(sc, RL_IMR, intrs);
2722         }
2723         RL_UNLOCK(sc);
2724 }
2725
2726 static int
2727 re_encap(struct rl_softc *sc, struct mbuf **m_head)
2728 {
2729         struct rl_txdesc        *txd, *txd_last;
2730         bus_dma_segment_t       segs[RL_NTXSEGS];
2731         bus_dmamap_t            map;
2732         struct mbuf             *m_new;
2733         struct rl_desc          *desc;
2734         int                     nsegs, prod;
2735         int                     i, error, ei, si;
2736         int                     padlen;
2737         uint32_t                cmdstat, csum_flags, vlanctl;
2738
2739         RL_LOCK_ASSERT(sc);
2740         M_ASSERTPKTHDR((*m_head));
2741
2742         /*
2743          * With some of the RealTek chips, using the checksum offload
2744          * support in conjunction with the autopadding feature results
2745          * in the transmission of corrupt frames. For example, if we
2746          * need to send a really small IP fragment that's less than 60
2747          * bytes in size, and IP header checksumming is enabled, the
2748          * resulting ethernet frame that appears on the wire will
2749          * have garbled payload. To work around this, if TX IP checksum
2750          * offload is enabled, we always manually pad short frames out
2751          * to the minimum ethernet frame size.
2752          */
2753         if ((sc->rl_flags & RL_FLAG_AUTOPAD) == 0 &&
2754             (*m_head)->m_pkthdr.len < RL_IP4CSUMTX_PADLEN &&
2755             ((*m_head)->m_pkthdr.csum_flags & CSUM_IP) != 0) {
2756                 padlen = RL_MIN_FRAMELEN - (*m_head)->m_pkthdr.len;
2757                 if (M_WRITABLE(*m_head) == 0) {
2758                         /* Get a writable copy. */
2759                         m_new = m_dup(*m_head, M_NOWAIT);
2760                         m_freem(*m_head);
2761                         if (m_new == NULL) {
2762                                 *m_head = NULL;
2763                                 return (ENOBUFS);
2764                         }
2765                         *m_head = m_new;
2766                 }
2767                 if ((*m_head)->m_next != NULL ||
2768                     M_TRAILINGSPACE(*m_head) < padlen) {
2769                         m_new = m_defrag(*m_head, M_NOWAIT);
2770                         if (m_new == NULL) {
2771                                 m_freem(*m_head);
2772                                 *m_head = NULL;
2773                                 return (ENOBUFS);
2774                         }
2775                 } else
2776                         m_new = *m_head;
2777
2778                 /*
2779                  * Manually pad short frames, and zero the pad space
2780                  * to avoid leaking data.
2781                  */
2782                 bzero(mtod(m_new, char *) + m_new->m_pkthdr.len, padlen);
2783                 m_new->m_pkthdr.len += padlen;
2784                 m_new->m_len = m_new->m_pkthdr.len;
2785                 *m_head = m_new;
2786         }
2787
2788         prod = sc->rl_ldata.rl_tx_prodidx;
2789         txd = &sc->rl_ldata.rl_tx_desc[prod];
2790         error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_tx_mtag, txd->tx_dmamap,
2791             *m_head, segs, &nsegs, BUS_DMA_NOWAIT);
2792         if (error == EFBIG) {
2793                 m_new = m_collapse(*m_head, M_NOWAIT, RL_NTXSEGS);
2794                 if (m_new == NULL) {
2795                         m_freem(*m_head);
2796                         *m_head = NULL;
2797                         return (ENOBUFS);
2798                 }
2799                 *m_head = m_new;
2800                 error = bus_dmamap_load_mbuf_sg(sc->rl_ldata.rl_tx_mtag,
2801                     txd->tx_dmamap, *m_head, segs, &nsegs, BUS_DMA_NOWAIT);
2802                 if (error != 0) {
2803                         m_freem(*m_head);
2804                         *m_head = NULL;
2805                         return (error);
2806                 }
2807         } else if (error != 0)
2808                 return (error);
2809         if (nsegs == 0) {
2810                 m_freem(*m_head);
2811                 *m_head = NULL;
2812                 return (EIO);
2813         }
2814
2815         /* Check for number of available descriptors. */
2816         if (sc->rl_ldata.rl_tx_free - nsegs <= 1) {
2817                 bus_dmamap_unload(sc->rl_ldata.rl_tx_mtag, txd->tx_dmamap);
2818                 return (ENOBUFS);
2819         }
2820
2821         bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag, txd->tx_dmamap,
2822             BUS_DMASYNC_PREWRITE);
2823
2824         /*
2825          * Set up checksum offload. Note: checksum offload bits must
2826          * appear in all descriptors of a multi-descriptor transmit
2827          * attempt. This is according to testing done with an 8169
2828          * chip. This is a requirement.
2829          */
2830         vlanctl = 0;
2831         csum_flags = 0;
2832         if (((*m_head)->m_pkthdr.csum_flags & CSUM_TSO) != 0) {
2833                 if ((sc->rl_flags & RL_FLAG_DESCV2) != 0) {
2834                         csum_flags |= RL_TDESC_CMD_LGSEND;
2835                         vlanctl |= ((uint32_t)(*m_head)->m_pkthdr.tso_segsz <<
2836                             RL_TDESC_CMD_MSSVALV2_SHIFT);
2837                 } else {
2838                         csum_flags |= RL_TDESC_CMD_LGSEND |
2839                             ((uint32_t)(*m_head)->m_pkthdr.tso_segsz <<
2840                             RL_TDESC_CMD_MSSVAL_SHIFT);
2841                 }
2842         } else {
2843                 /*
2844                  * Unconditionally enable IP checksum if TCP or UDP
2845                  * checksum is required. Otherwise, TCP/UDP checksum
2846                  * doesn't make effects.
2847                  */
2848                 if (((*m_head)->m_pkthdr.csum_flags & RE_CSUM_FEATURES) != 0) {
2849                         if ((sc->rl_flags & RL_FLAG_DESCV2) == 0) {
2850                                 csum_flags |= RL_TDESC_CMD_IPCSUM;
2851                                 if (((*m_head)->m_pkthdr.csum_flags &
2852                                     CSUM_TCP) != 0)
2853                                         csum_flags |= RL_TDESC_CMD_TCPCSUM;
2854                                 if (((*m_head)->m_pkthdr.csum_flags &
2855                                     CSUM_UDP) != 0)
2856                                         csum_flags |= RL_TDESC_CMD_UDPCSUM;
2857                         } else {
2858                                 vlanctl |= RL_TDESC_CMD_IPCSUMV2;
2859                                 if (((*m_head)->m_pkthdr.csum_flags &
2860                                     CSUM_TCP) != 0)
2861                                         vlanctl |= RL_TDESC_CMD_TCPCSUMV2;
2862                                 if (((*m_head)->m_pkthdr.csum_flags &
2863                                     CSUM_UDP) != 0)
2864                                         vlanctl |= RL_TDESC_CMD_UDPCSUMV2;
2865                         }
2866                 }
2867         }
2868
2869         /*
2870          * Set up hardware VLAN tagging. Note: vlan tag info must
2871          * appear in all descriptors of a multi-descriptor
2872          * transmission attempt.
2873          */
2874         if ((*m_head)->m_flags & M_VLANTAG)
2875                 vlanctl |= bswap16((*m_head)->m_pkthdr.ether_vtag) |
2876                     RL_TDESC_VLANCTL_TAG;
2877
2878         si = prod;
2879         for (i = 0; i < nsegs; i++, prod = RL_TX_DESC_NXT(sc, prod)) {
2880                 desc = &sc->rl_ldata.rl_tx_list[prod];
2881                 desc->rl_vlanctl = htole32(vlanctl);
2882                 desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(segs[i].ds_addr));
2883                 desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(segs[i].ds_addr));
2884                 cmdstat = segs[i].ds_len;
2885                 if (i != 0)
2886                         cmdstat |= RL_TDESC_CMD_OWN;
2887                 if (prod == sc->rl_ldata.rl_tx_desc_cnt - 1)
2888                         cmdstat |= RL_TDESC_CMD_EOR;
2889                 desc->rl_cmdstat = htole32(cmdstat | csum_flags);
2890                 sc->rl_ldata.rl_tx_free--;
2891         }
2892         /* Update producer index. */
2893         sc->rl_ldata.rl_tx_prodidx = prod;
2894
2895         /* Set EOF on the last descriptor. */
2896         ei = RL_TX_DESC_PRV(sc, prod);
2897         desc = &sc->rl_ldata.rl_tx_list[ei];
2898         desc->rl_cmdstat |= htole32(RL_TDESC_CMD_EOF);
2899
2900         desc = &sc->rl_ldata.rl_tx_list[si];
2901         /* Set SOF and transfer ownership of packet to the chip. */
2902         desc->rl_cmdstat |= htole32(RL_TDESC_CMD_OWN | RL_TDESC_CMD_SOF);
2903
2904         /*
2905          * Insure that the map for this transmission
2906          * is placed at the array index of the last descriptor
2907          * in this chain.  (Swap last and first dmamaps.)
2908          */
2909         txd_last = &sc->rl_ldata.rl_tx_desc[ei];
2910         map = txd->tx_dmamap;
2911         txd->tx_dmamap = txd_last->tx_dmamap;
2912         txd_last->tx_dmamap = map;
2913         txd_last->tx_m = *m_head;
2914
2915         return (0);
2916 }
2917
2918 static void
2919 re_start(struct ifnet *ifp)
2920 {
2921         struct rl_softc         *sc;
2922
2923         sc = ifp->if_softc;
2924         RL_LOCK(sc);
2925         re_start_locked(ifp);
2926         RL_UNLOCK(sc);
2927 }
2928
2929 /*
2930  * Main transmit routine for C+ and gigE NICs.
2931  */
2932 static void
2933 re_start_locked(struct ifnet *ifp)
2934 {
2935         struct rl_softc         *sc;
2936         struct mbuf             *m_head;
2937         int                     queued;
2938
2939         sc = ifp->if_softc;
2940
2941 #ifdef DEV_NETMAP
2942         /* XXX is this necessary ? */
2943         if (ifp->if_capenable & IFCAP_NETMAP) {
2944                 struct netmap_kring *kring = NA(ifp)->tx_rings[0];
2945                 if (sc->rl_ldata.rl_tx_prodidx != kring->nr_hwcur) {
2946                         /* kick the tx unit */
2947                         CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
2948 #ifdef RE_TX_MODERATION
2949                         CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2950 #endif
2951                         sc->rl_watchdog_timer = 5;
2952                 }
2953                 return;
2954         }
2955 #endif /* DEV_NETMAP */
2956
2957         if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
2958             IFF_DRV_RUNNING || (sc->rl_flags & RL_FLAG_LINK) == 0)
2959                 return;
2960
2961         for (queued = 0; !IFQ_DRV_IS_EMPTY(&ifp->if_snd) &&
2962             sc->rl_ldata.rl_tx_free > 1;) {
2963                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
2964                 if (m_head == NULL)
2965                         break;
2966
2967                 if (re_encap(sc, &m_head) != 0) {
2968                         if (m_head == NULL)
2969                                 break;
2970                         IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
2971                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2972                         break;
2973                 }
2974
2975                 /*
2976                  * If there's a BPF listener, bounce a copy of this frame
2977                  * to him.
2978                  */
2979                 ETHER_BPF_MTAP(ifp, m_head);
2980
2981                 queued++;
2982         }
2983
2984         if (queued == 0) {
2985 #ifdef RE_TX_MODERATION
2986                 if (sc->rl_ldata.rl_tx_free != sc->rl_ldata.rl_tx_desc_cnt)
2987                         CSR_WRITE_4(sc, RL_TIMERCNT, 1);
2988 #endif
2989                 return;
2990         }
2991
2992         re_start_tx(sc);
2993 }
2994
2995 static void
2996 re_start_tx(struct rl_softc *sc)
2997 {
2998
2999         /* Flush the TX descriptors */
3000         bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
3001             sc->rl_ldata.rl_tx_list_map,
3002             BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
3003
3004         CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
3005
3006 #ifdef RE_TX_MODERATION
3007         /*
3008          * Use the countdown timer for interrupt moderation.
3009          * 'TX done' interrupts are disabled. Instead, we reset the
3010          * countdown timer, which will begin counting until it hits
3011          * the value in the TIMERINT register, and then trigger an
3012          * interrupt. Each time we write to the TIMERCNT register,
3013          * the timer count is reset to 0.
3014          */
3015         CSR_WRITE_4(sc, RL_TIMERCNT, 1);
3016 #endif
3017
3018         /*
3019          * Set a timeout in case the chip goes out to lunch.
3020          */
3021         sc->rl_watchdog_timer = 5;
3022 }
3023
3024 static void
3025 re_set_jumbo(struct rl_softc *sc, int jumbo)
3026 {
3027
3028         if (sc->rl_hwrev->rl_rev == RL_HWREV_8168E_VL) {
3029                 pci_set_max_read_req(sc->rl_dev, 4096);
3030                 return;
3031         }
3032
3033         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_WRITECFG);
3034         if (jumbo != 0) {
3035                 CSR_WRITE_1(sc, sc->rl_cfg3, CSR_READ_1(sc, sc->rl_cfg3) |
3036                     RL_CFG3_JUMBO_EN0);
3037                 switch (sc->rl_hwrev->rl_rev) {
3038                 case RL_HWREV_8168DP:
3039                         break;
3040                 case RL_HWREV_8168E:
3041                         CSR_WRITE_1(sc, sc->rl_cfg4,
3042                             CSR_READ_1(sc, sc->rl_cfg4) | 0x01);
3043                         break;
3044                 default:
3045                         CSR_WRITE_1(sc, sc->rl_cfg4,
3046                             CSR_READ_1(sc, sc->rl_cfg4) | RL_CFG4_JUMBO_EN1);
3047                 }
3048         } else {
3049                 CSR_WRITE_1(sc, sc->rl_cfg3, CSR_READ_1(sc, sc->rl_cfg3) &
3050                     ~RL_CFG3_JUMBO_EN0);
3051                 switch (sc->rl_hwrev->rl_rev) {
3052                 case RL_HWREV_8168DP:
3053                         break;
3054                 case RL_HWREV_8168E:
3055                         CSR_WRITE_1(sc, sc->rl_cfg4,
3056                             CSR_READ_1(sc, sc->rl_cfg4) & ~0x01);
3057                         break;
3058                 default:
3059                         CSR_WRITE_1(sc, sc->rl_cfg4,
3060                             CSR_READ_1(sc, sc->rl_cfg4) & ~RL_CFG4_JUMBO_EN1);
3061                 }
3062         }
3063         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
3064
3065         switch (sc->rl_hwrev->rl_rev) {
3066         case RL_HWREV_8168DP:
3067                 pci_set_max_read_req(sc->rl_dev, 4096);
3068                 break;
3069         default:
3070                 if (jumbo != 0)
3071                         pci_set_max_read_req(sc->rl_dev, 512);
3072                 else
3073                         pci_set_max_read_req(sc->rl_dev, 4096);
3074         }
3075 }
3076
3077 static void
3078 re_init(void *xsc)
3079 {
3080         struct rl_softc         *sc = xsc;
3081
3082         RL_LOCK(sc);
3083         re_init_locked(sc);
3084         RL_UNLOCK(sc);
3085 }
3086
3087 static void
3088 re_init_locked(struct rl_softc *sc)
3089 {
3090         struct ifnet            *ifp = sc->rl_ifp;
3091         struct mii_data         *mii;
3092         uint32_t                reg;
3093         uint16_t                cfg;
3094         union {
3095                 uint32_t align_dummy;
3096                 u_char eaddr[ETHER_ADDR_LEN];
3097         } eaddr;
3098
3099         RL_LOCK_ASSERT(sc);
3100
3101         mii = device_get_softc(sc->rl_miibus);
3102
3103         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
3104                 return;
3105
3106         /*
3107          * Cancel pending I/O and free all RX/TX buffers.
3108          */
3109         re_stop(sc);
3110
3111         /* Put controller into known state. */
3112         re_reset(sc);
3113
3114         /*
3115          * For C+ mode, initialize the RX descriptors and mbufs.
3116          */
3117         if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0) {
3118                 if (ifp->if_mtu > RL_MTU) {
3119                         if (re_jrx_list_init(sc) != 0) {
3120                                 device_printf(sc->rl_dev,
3121                                     "no memory for jumbo RX buffers\n");
3122                                 re_stop(sc);
3123                                 return;
3124                         }
3125                         /* Disable checksum offloading for jumbo frames. */
3126                         ifp->if_capenable &= ~(IFCAP_HWCSUM | IFCAP_TSO4);
3127                         ifp->if_hwassist &= ~(RE_CSUM_FEATURES | CSUM_TSO);
3128                 } else {
3129                         if (re_rx_list_init(sc) != 0) {
3130                                 device_printf(sc->rl_dev,
3131                                     "no memory for RX buffers\n");
3132                                 re_stop(sc);
3133                                 return;
3134                         }
3135                 }
3136                 re_set_jumbo(sc, ifp->if_mtu > RL_MTU);
3137         } else {
3138                 if (re_rx_list_init(sc) != 0) {
3139                         device_printf(sc->rl_dev, "no memory for RX buffers\n");
3140                         re_stop(sc);
3141                         return;
3142                 }
3143                 if ((sc->rl_flags & RL_FLAG_PCIE) != 0 &&
3144                     pci_get_device(sc->rl_dev) != RT_DEVICEID_8101E) {
3145                         if (ifp->if_mtu > RL_MTU)
3146                                 pci_set_max_read_req(sc->rl_dev, 512);
3147                         else
3148                                 pci_set_max_read_req(sc->rl_dev, 4096);
3149                 }
3150         }
3151         re_tx_list_init(sc);
3152
3153         /*
3154          * Enable C+ RX and TX mode, as well as VLAN stripping and
3155          * RX checksum offload. We must configure the C+ register
3156          * before all others.
3157          */
3158         cfg = RL_CPLUSCMD_PCI_MRW;
3159         if ((ifp->if_capenable & IFCAP_RXCSUM) != 0)
3160                 cfg |= RL_CPLUSCMD_RXCSUM_ENB;
3161         if ((ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0)
3162                 cfg |= RL_CPLUSCMD_VLANSTRIP;
3163         if ((sc->rl_flags & RL_FLAG_MACSTAT) != 0) {
3164                 cfg |= RL_CPLUSCMD_MACSTAT_DIS;
3165                 /* XXX magic. */
3166                 cfg |= 0x0001;
3167         } else
3168                 cfg |= RL_CPLUSCMD_RXENB | RL_CPLUSCMD_TXENB;
3169         CSR_WRITE_2(sc, RL_CPLUS_CMD, cfg);
3170         if (sc->rl_hwrev->rl_rev == RL_HWREV_8169_8110SC ||
3171             sc->rl_hwrev->rl_rev == RL_HWREV_8169_8110SCE) {
3172                 reg = 0x000fff00;
3173                 if ((CSR_READ_1(sc, sc->rl_cfg2) & RL_CFG2_PCI66MHZ) != 0)
3174                         reg |= 0x000000ff;
3175                 if (sc->rl_hwrev->rl_rev == RL_HWREV_8169_8110SCE)
3176                         reg |= 0x00f00000;
3177                 CSR_WRITE_4(sc, 0x7c, reg);
3178                 /* Disable interrupt mitigation. */
3179                 CSR_WRITE_2(sc, 0xe2, 0);
3180         }
3181         /*
3182          * Disable TSO if interface MTU size is greater than MSS
3183          * allowed in controller.
3184          */
3185         if (ifp->if_mtu > RL_TSO_MTU && (ifp->if_capenable & IFCAP_TSO4) != 0) {
3186                 ifp->if_capenable &= ~IFCAP_TSO4;
3187                 ifp->if_hwassist &= ~CSUM_TSO;
3188         }
3189
3190         /*
3191          * Init our MAC address.  Even though the chipset
3192          * documentation doesn't mention it, we need to enter "Config
3193          * register write enable" mode to modify the ID registers.
3194          */
3195         /* Copy MAC address on stack to align. */
3196         bcopy(IF_LLADDR(ifp), eaddr.eaddr, ETHER_ADDR_LEN);
3197         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_WRITECFG);
3198         CSR_WRITE_4(sc, RL_IDR0,
3199             htole32(*(u_int32_t *)(&eaddr.eaddr[0])));
3200         CSR_WRITE_4(sc, RL_IDR4,
3201             htole32(*(u_int32_t *)(&eaddr.eaddr[4])));
3202         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
3203
3204         /*
3205          * Load the addresses of the RX and TX lists into the chip.
3206          */
3207
3208         CSR_WRITE_4(sc, RL_RXLIST_ADDR_HI,
3209             RL_ADDR_HI(sc->rl_ldata.rl_rx_list_addr));
3210         CSR_WRITE_4(sc, RL_RXLIST_ADDR_LO,
3211             RL_ADDR_LO(sc->rl_ldata.rl_rx_list_addr));
3212
3213         CSR_WRITE_4(sc, RL_TXLIST_ADDR_HI,
3214             RL_ADDR_HI(sc->rl_ldata.rl_tx_list_addr));
3215         CSR_WRITE_4(sc, RL_TXLIST_ADDR_LO,
3216             RL_ADDR_LO(sc->rl_ldata.rl_tx_list_addr));
3217
3218         if ((sc->rl_flags & RL_FLAG_8168G_PLUS) != 0) {
3219                 /* Disable RXDV gate. */
3220                 CSR_WRITE_4(sc, RL_MISC, CSR_READ_4(sc, RL_MISC) &
3221                     ~0x00080000);
3222         }
3223
3224         /*
3225          * Enable transmit and receive for pre-RTL8168G controllers.
3226          * RX/TX MACs should be enabled before RX/TX configuration.
3227          */
3228         if ((sc->rl_flags & RL_FLAG_8168G_PLUS) == 0)
3229                 CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB | RL_CMD_RX_ENB);
3230
3231         /*
3232          * Set the initial TX configuration.
3233          */
3234         if (sc->rl_testmode) {
3235                 if (sc->rl_type == RL_8169)
3236                         CSR_WRITE_4(sc, RL_TXCFG,
3237                             RL_TXCFG_CONFIG|RL_LOOPTEST_ON);
3238                 else
3239                         CSR_WRITE_4(sc, RL_TXCFG,
3240                             RL_TXCFG_CONFIG|RL_LOOPTEST_ON_CPLUS);
3241         } else
3242                 CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
3243
3244         CSR_WRITE_1(sc, RL_EARLY_TX_THRESH, 16);
3245
3246         /*
3247          * Set the initial RX configuration.
3248          */
3249         re_set_rxmode(sc);
3250
3251         /* Configure interrupt moderation. */
3252         if (sc->rl_type == RL_8169) {
3253                 /* Magic from vendor. */
3254                 CSR_WRITE_2(sc, RL_INTRMOD, 0x5100);
3255         }
3256
3257         /*
3258          * Enable transmit and receive for RTL8168G and later controllers.
3259          * RX/TX MACs should be enabled after RX/TX configuration.
3260          */
3261         if ((sc->rl_flags & RL_FLAG_8168G_PLUS) != 0)
3262                 CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_TX_ENB | RL_CMD_RX_ENB);
3263
3264 #ifdef DEVICE_POLLING
3265         /*
3266          * Disable interrupts if we are polling.
3267          */
3268         if (ifp->if_capenable & IFCAP_POLLING)
3269                 CSR_WRITE_2(sc, RL_IMR, 0);
3270         else    /* otherwise ... */
3271 #endif
3272
3273         /*
3274          * Enable interrupts.
3275          */
3276         if (sc->rl_testmode)
3277                 CSR_WRITE_2(sc, RL_IMR, 0);
3278         else
3279                 CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
3280         CSR_WRITE_2(sc, RL_ISR, RL_INTRS_CPLUS);
3281
3282         /* Set initial TX threshold */
3283         sc->rl_txthresh = RL_TX_THRESH_INIT;
3284
3285         /* Start RX/TX process. */
3286         CSR_WRITE_4(sc, RL_MISSEDPKT, 0);
3287
3288         /*
3289          * Initialize the timer interrupt register so that
3290          * a timer interrupt will be generated once the timer
3291          * reaches a certain number of ticks. The timer is
3292          * reloaded on each transmit.
3293          */
3294 #ifdef RE_TX_MODERATION
3295         /*
3296          * Use timer interrupt register to moderate TX interrupt
3297          * moderation, which dramatically improves TX frame rate.
3298          */
3299         if (sc->rl_type == RL_8169)
3300                 CSR_WRITE_4(sc, RL_TIMERINT_8169, 0x800);
3301         else
3302                 CSR_WRITE_4(sc, RL_TIMERINT, 0x400);
3303 #else
3304         /*
3305          * Use timer interrupt register to moderate RX interrupt
3306          * moderation.
3307          */
3308         if ((sc->rl_flags & (RL_FLAG_MSI | RL_FLAG_MSIX)) != 0 &&
3309             intr_filter == 0) {
3310                 if (sc->rl_type == RL_8169)
3311                         CSR_WRITE_4(sc, RL_TIMERINT_8169,
3312                             RL_USECS(sc->rl_int_rx_mod));
3313         } else {
3314                 if (sc->rl_type == RL_8169)
3315                         CSR_WRITE_4(sc, RL_TIMERINT_8169, RL_USECS(0));
3316         }
3317 #endif
3318
3319         /*
3320          * For 8169 gigE NICs, set the max allowed RX packet
3321          * size so we can receive jumbo frames.
3322          */
3323         if (sc->rl_type == RL_8169) {
3324                 if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0) {
3325                         /*
3326                          * For controllers that use new jumbo frame scheme,
3327                          * set maximum size of jumbo frame depending on
3328                          * controller revisions.
3329                          */
3330                         if (ifp->if_mtu > RL_MTU)
3331                                 CSR_WRITE_2(sc, RL_MAXRXPKTLEN,
3332                                     sc->rl_hwrev->rl_max_mtu +
3333                                     ETHER_VLAN_ENCAP_LEN + ETHER_HDR_LEN +
3334                                     ETHER_CRC_LEN);
3335                         else
3336                                 CSR_WRITE_2(sc, RL_MAXRXPKTLEN,
3337                                     RE_RX_DESC_BUFLEN);
3338                 } else if ((sc->rl_flags & RL_FLAG_PCIE) != 0 &&
3339                     sc->rl_hwrev->rl_max_mtu == RL_MTU) {
3340                         /* RTL810x has no jumbo frame support. */
3341                         CSR_WRITE_2(sc, RL_MAXRXPKTLEN, RE_RX_DESC_BUFLEN);
3342                 } else
3343                         CSR_WRITE_2(sc, RL_MAXRXPKTLEN, 16383);
3344         }
3345
3346         if (sc->rl_testmode)
3347                 return;
3348
3349         CSR_WRITE_1(sc, sc->rl_cfg1, CSR_READ_1(sc, sc->rl_cfg1) |
3350             RL_CFG1_DRVLOAD);
3351
3352         ifp->if_drv_flags |= IFF_DRV_RUNNING;
3353         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3354
3355         sc->rl_flags &= ~RL_FLAG_LINK;
3356         mii_mediachg(mii);
3357
3358         sc->rl_watchdog_timer = 0;
3359         callout_reset(&sc->rl_stat_callout, hz, re_tick, sc);
3360 }
3361
3362 /*
3363  * Set media options.
3364  */
3365 static int
3366 re_ifmedia_upd(struct ifnet *ifp)
3367 {
3368         struct rl_softc         *sc;
3369         struct mii_data         *mii;
3370         int                     error;
3371
3372         sc = ifp->if_softc;
3373         mii = device_get_softc(sc->rl_miibus);
3374         RL_LOCK(sc);
3375         error = mii_mediachg(mii);
3376         RL_UNLOCK(sc);
3377
3378         return (error);
3379 }
3380
3381 /*
3382  * Report current media status.
3383  */
3384 static void
3385 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
3386 {
3387         struct rl_softc         *sc;
3388         struct mii_data         *mii;
3389
3390         sc = ifp->if_softc;
3391         mii = device_get_softc(sc->rl_miibus);
3392
3393         RL_LOCK(sc);
3394         mii_pollstat(mii);
3395         ifmr->ifm_active = mii->mii_media_active;
3396         ifmr->ifm_status = mii->mii_media_status;
3397         RL_UNLOCK(sc);
3398 }
3399
3400 static int
3401 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
3402 {
3403         struct rl_softc         *sc = ifp->if_softc;
3404         struct ifreq            *ifr = (struct ifreq *) data;
3405         struct mii_data         *mii;
3406         int                     error = 0;
3407
3408         switch (command) {
3409         case SIOCSIFMTU:
3410                 if (ifr->ifr_mtu < ETHERMIN ||
3411                     ifr->ifr_mtu > sc->rl_hwrev->rl_max_mtu ||
3412                     ((sc->rl_flags & RL_FLAG_FASTETHER) != 0 &&
3413                     ifr->ifr_mtu > RL_MTU)) {
3414                         error = EINVAL;
3415                         break;
3416                 }
3417                 RL_LOCK(sc);
3418                 if (ifp->if_mtu != ifr->ifr_mtu) {
3419                         ifp->if_mtu = ifr->ifr_mtu;
3420                         if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0 &&
3421                             (ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
3422                                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
3423                                 re_init_locked(sc);
3424                         }
3425                         if (ifp->if_mtu > RL_TSO_MTU &&
3426                             (ifp->if_capenable & IFCAP_TSO4) != 0) {
3427                                 ifp->if_capenable &= ~(IFCAP_TSO4 |
3428                                     IFCAP_VLAN_HWTSO);
3429                                 ifp->if_hwassist &= ~CSUM_TSO;
3430                         }
3431                         VLAN_CAPABILITIES(ifp);
3432                 }
3433                 RL_UNLOCK(sc);
3434                 break;
3435         case SIOCSIFFLAGS:
3436                 RL_LOCK(sc);
3437                 if ((ifp->if_flags & IFF_UP) != 0) {
3438                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
3439                                 if (((ifp->if_flags ^ sc->rl_if_flags)
3440                                     & (IFF_PROMISC | IFF_ALLMULTI)) != 0)
3441                                         re_set_rxmode(sc);
3442                         } else
3443                                 re_init_locked(sc);
3444                 } else {
3445                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
3446                                 re_stop(sc);
3447                 }
3448                 sc->rl_if_flags = ifp->if_flags;
3449                 RL_UNLOCK(sc);
3450                 break;
3451         case SIOCADDMULTI:
3452         case SIOCDELMULTI:
3453                 RL_LOCK(sc);
3454                 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
3455                         re_set_rxmode(sc);
3456                 RL_UNLOCK(sc);
3457                 break;
3458         case SIOCGIFMEDIA:
3459         case SIOCSIFMEDIA:
3460                 mii = device_get_softc(sc->rl_miibus);
3461                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
3462                 break;
3463         case SIOCSIFCAP:
3464             {
3465                 int mask, reinit;
3466
3467                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
3468                 reinit = 0;
3469 #ifdef DEVICE_POLLING
3470                 if (mask & IFCAP_POLLING) {
3471                         if (ifr->ifr_reqcap & IFCAP_POLLING) {
3472                                 error = ether_poll_register(re_poll, ifp);
3473                                 if (error)
3474                                         return (error);
3475                                 RL_LOCK(sc);
3476                                 /* Disable interrupts */
3477                                 CSR_WRITE_2(sc, RL_IMR, 0x0000);
3478                                 ifp->if_capenable |= IFCAP_POLLING;
3479                                 RL_UNLOCK(sc);
3480                         } else {
3481                                 error = ether_poll_deregister(ifp);
3482                                 /* Enable interrupts. */
3483                                 RL_LOCK(sc);
3484                                 CSR_WRITE_2(sc, RL_IMR, RL_INTRS_CPLUS);
3485                                 ifp->if_capenable &= ~IFCAP_POLLING;
3486                                 RL_UNLOCK(sc);
3487                         }
3488                 }
3489 #endif /* DEVICE_POLLING */
3490                 RL_LOCK(sc);
3491                 if ((mask & IFCAP_TXCSUM) != 0 &&
3492                     (ifp->if_capabilities & IFCAP_TXCSUM) != 0) {
3493                         ifp->if_capenable ^= IFCAP_TXCSUM;
3494                         if ((ifp->if_capenable & IFCAP_TXCSUM) != 0)
3495                                 ifp->if_hwassist |= RE_CSUM_FEATURES;
3496                         else
3497                                 ifp->if_hwassist &= ~RE_CSUM_FEATURES;
3498                         reinit = 1;
3499                 }
3500                 if ((mask & IFCAP_RXCSUM) != 0 &&
3501                     (ifp->if_capabilities & IFCAP_RXCSUM) != 0) {
3502                         ifp->if_capenable ^= IFCAP_RXCSUM;
3503                         reinit = 1;
3504                 }
3505                 if ((mask & IFCAP_TSO4) != 0 &&
3506                     (ifp->if_capabilities & IFCAP_TSO4) != 0) {
3507                         ifp->if_capenable ^= IFCAP_TSO4;
3508                         if ((IFCAP_TSO4 & ifp->if_capenable) != 0)
3509                                 ifp->if_hwassist |= CSUM_TSO;
3510                         else
3511                                 ifp->if_hwassist &= ~CSUM_TSO;
3512                         if (ifp->if_mtu > RL_TSO_MTU &&
3513                             (ifp->if_capenable & IFCAP_TSO4) != 0) {
3514                                 ifp->if_capenable &= ~IFCAP_TSO4;
3515                                 ifp->if_hwassist &= ~CSUM_TSO;
3516                         }
3517                 }
3518                 if ((mask & IFCAP_VLAN_HWTSO) != 0 &&
3519                     (ifp->if_capabilities & IFCAP_VLAN_HWTSO) != 0)
3520                         ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
3521                 if ((mask & IFCAP_VLAN_HWTAGGING) != 0 &&
3522                     (ifp->if_capabilities & IFCAP_VLAN_HWTAGGING) != 0) {
3523                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
3524                         /* TSO over VLAN requires VLAN hardware tagging. */
3525                         if ((ifp->if_capenable & IFCAP_VLAN_HWTAGGING) == 0)
3526                                 ifp->if_capenable &= ~IFCAP_VLAN_HWTSO;
3527                         reinit = 1;
3528                 }
3529                 if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0 &&
3530                     (mask & (IFCAP_HWCSUM | IFCAP_TSO4 |
3531                     IFCAP_VLAN_HWTSO)) != 0)
3532                                 reinit = 1;
3533                 if ((mask & IFCAP_WOL) != 0 &&
3534                     (ifp->if_capabilities & IFCAP_WOL) != 0) {
3535                         if ((mask & IFCAP_WOL_UCAST) != 0)
3536                                 ifp->if_capenable ^= IFCAP_WOL_UCAST;
3537                         if ((mask & IFCAP_WOL_MCAST) != 0)
3538                                 ifp->if_capenable ^= IFCAP_WOL_MCAST;
3539                         if ((mask & IFCAP_WOL_MAGIC) != 0)
3540                                 ifp->if_capenable ^= IFCAP_WOL_MAGIC;
3541                 }
3542                 if (reinit && ifp->if_drv_flags & IFF_DRV_RUNNING) {
3543                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
3544                         re_init_locked(sc);
3545                 }
3546                 RL_UNLOCK(sc);
3547                 VLAN_CAPABILITIES(ifp);
3548             }
3549                 break;
3550         default:
3551                 error = ether_ioctl(ifp, command, data);
3552                 break;
3553         }
3554
3555         return (error);
3556 }
3557
3558 static void
3559 re_watchdog(struct rl_softc *sc)
3560 {
3561         struct ifnet            *ifp;
3562
3563         RL_LOCK_ASSERT(sc);
3564
3565         if (sc->rl_watchdog_timer == 0 || --sc->rl_watchdog_timer != 0)
3566                 return;
3567
3568         ifp = sc->rl_ifp;
3569         re_txeof(sc);
3570         if (sc->rl_ldata.rl_tx_free == sc->rl_ldata.rl_tx_desc_cnt) {
3571                 if_printf(ifp, "watchdog timeout (missed Tx interrupts) "
3572                     "-- recovering\n");
3573                 if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
3574                         re_start_locked(ifp);
3575                 return;
3576         }
3577
3578         if_printf(ifp, "watchdog timeout\n");
3579         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3580
3581         re_rxeof(sc, NULL);
3582         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
3583         re_init_locked(sc);
3584         if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
3585                 re_start_locked(ifp);
3586 }
3587
3588 /*
3589  * Stop the adapter and free any mbufs allocated to the
3590  * RX and TX lists.
3591  */
3592 static void
3593 re_stop(struct rl_softc *sc)
3594 {
3595         int                     i;
3596         struct ifnet            *ifp;
3597         struct rl_txdesc        *txd;
3598         struct rl_rxdesc        *rxd;
3599
3600         RL_LOCK_ASSERT(sc);
3601
3602         ifp = sc->rl_ifp;
3603
3604         sc->rl_watchdog_timer = 0;
3605         callout_stop(&sc->rl_stat_callout);
3606         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
3607
3608         /*
3609          * Disable accepting frames to put RX MAC into idle state.
3610          * Otherwise it's possible to get frames while stop command
3611          * execution is in progress and controller can DMA the frame
3612          * to already freed RX buffer during that period.
3613          */
3614         CSR_WRITE_4(sc, RL_RXCFG, CSR_READ_4(sc, RL_RXCFG) &
3615             ~(RL_RXCFG_RX_ALLPHYS | RL_RXCFG_RX_INDIV | RL_RXCFG_RX_MULTI |
3616             RL_RXCFG_RX_BROAD));
3617
3618         if ((sc->rl_flags & RL_FLAG_8168G_PLUS) != 0) {
3619                 /* Enable RXDV gate. */
3620                 CSR_WRITE_4(sc, RL_MISC, CSR_READ_4(sc, RL_MISC) |
3621                     0x00080000);
3622         }
3623
3624         if ((sc->rl_flags & RL_FLAG_WAIT_TXPOLL) != 0) {
3625                 for (i = RL_TIMEOUT; i > 0; i--) {
3626                         if ((CSR_READ_1(sc, sc->rl_txstart) &
3627                             RL_TXSTART_START) == 0)
3628                                 break;
3629                         DELAY(20);
3630                 }
3631                 if (i == 0)
3632                         device_printf(sc->rl_dev,
3633                             "stopping TX poll timed out!\n");
3634                 CSR_WRITE_1(sc, RL_COMMAND, 0x00);
3635         } else if ((sc->rl_flags & RL_FLAG_CMDSTOP) != 0) {
3636                 CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_STOPREQ | RL_CMD_TX_ENB |
3637                     RL_CMD_RX_ENB);
3638                 if ((sc->rl_flags & RL_FLAG_CMDSTOP_WAIT_TXQ) != 0) {
3639                         for (i = RL_TIMEOUT; i > 0; i--) {
3640                                 if ((CSR_READ_4(sc, RL_TXCFG) &
3641                                     RL_TXCFG_QUEUE_EMPTY) != 0)
3642                                         break;
3643                                 DELAY(100);
3644                         }
3645                         if (i == 0)
3646                                 device_printf(sc->rl_dev,
3647                                    "stopping TXQ timed out!\n");
3648                 }
3649         } else
3650                 CSR_WRITE_1(sc, RL_COMMAND, 0x00);
3651         DELAY(1000);
3652         CSR_WRITE_2(sc, RL_IMR, 0x0000);
3653         CSR_WRITE_2(sc, RL_ISR, 0xFFFF);
3654
3655         if (sc->rl_head != NULL) {
3656                 m_freem(sc->rl_head);
3657                 sc->rl_head = sc->rl_tail = NULL;
3658         }
3659
3660         /* Free the TX list buffers. */
3661         for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++) {
3662                 txd = &sc->rl_ldata.rl_tx_desc[i];
3663                 if (txd->tx_m != NULL) {
3664                         bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
3665                             txd->tx_dmamap, BUS_DMASYNC_POSTWRITE);
3666                         bus_dmamap_unload(sc->rl_ldata.rl_tx_mtag,
3667                             txd->tx_dmamap);
3668                         m_freem(txd->tx_m);
3669                         txd->tx_m = NULL;
3670                 }
3671         }
3672
3673         /* Free the RX list buffers. */
3674         for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
3675                 rxd = &sc->rl_ldata.rl_rx_desc[i];
3676                 if (rxd->rx_m != NULL) {
3677                         bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
3678                             rxd->rx_dmamap, BUS_DMASYNC_POSTREAD);
3679                         bus_dmamap_unload(sc->rl_ldata.rl_rx_mtag,
3680                             rxd->rx_dmamap);
3681                         m_freem(rxd->rx_m);
3682                         rxd->rx_m = NULL;
3683                 }
3684         }
3685
3686         if ((sc->rl_flags & RL_FLAG_JUMBOV2) != 0) {
3687                 for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
3688                         rxd = &sc->rl_ldata.rl_jrx_desc[i];
3689                         if (rxd->rx_m != NULL) {
3690                                 bus_dmamap_sync(sc->rl_ldata.rl_jrx_mtag,
3691                                     rxd->rx_dmamap, BUS_DMASYNC_POSTREAD);
3692                                 bus_dmamap_unload(sc->rl_ldata.rl_jrx_mtag,
3693                                     rxd->rx_dmamap);
3694                                 m_freem(rxd->rx_m);
3695                                 rxd->rx_m = NULL;
3696                         }
3697                 }
3698         }
3699 }
3700
3701 /*
3702  * Device suspend routine.  Stop the interface and save some PCI
3703  * settings in case the BIOS doesn't restore them properly on
3704  * resume.
3705  */
3706 static int
3707 re_suspend(device_t dev)
3708 {
3709         struct rl_softc         *sc;
3710
3711         sc = device_get_softc(dev);
3712
3713         RL_LOCK(sc);
3714         re_stop(sc);
3715         re_setwol(sc);
3716         sc->suspended = 1;
3717         RL_UNLOCK(sc);
3718
3719         return (0);
3720 }
3721
3722 /*
3723  * Device resume routine.  Restore some PCI settings in case the BIOS
3724  * doesn't, re-enable busmastering, and restart the interface if
3725  * appropriate.
3726  */
3727 static int
3728 re_resume(device_t dev)
3729 {
3730         struct rl_softc         *sc;
3731         struct ifnet            *ifp;
3732
3733         sc = device_get_softc(dev);
3734
3735         RL_LOCK(sc);
3736
3737         ifp = sc->rl_ifp;
3738         /* Take controller out of sleep mode. */
3739         if ((sc->rl_flags & RL_FLAG_MACSLEEP) != 0) {
3740                 if ((CSR_READ_1(sc, RL_MACDBG) & 0x80) == 0x80)
3741                         CSR_WRITE_1(sc, RL_GPIO,
3742                             CSR_READ_1(sc, RL_GPIO) | 0x01);
3743         }
3744
3745         /*
3746          * Clear WOL matching such that normal Rx filtering
3747          * wouldn't interfere with WOL patterns.
3748          */
3749         re_clrwol(sc);
3750
3751         /* reinitialize interface if necessary */
3752         if (ifp->if_flags & IFF_UP)
3753                 re_init_locked(sc);
3754
3755         sc->suspended = 0;
3756         RL_UNLOCK(sc);
3757
3758         return (0);
3759 }
3760
3761 /*
3762  * Stop all chip I/O so that the kernel's probe routines don't
3763  * get confused by errant DMAs when rebooting.
3764  */
3765 static int
3766 re_shutdown(device_t dev)
3767 {
3768         struct rl_softc         *sc;
3769
3770         sc = device_get_softc(dev);
3771
3772         RL_LOCK(sc);
3773         re_stop(sc);
3774         /*
3775          * Mark interface as down since otherwise we will panic if
3776          * interrupt comes in later on, which can happen in some
3777          * cases.
3778          */
3779         sc->rl_ifp->if_flags &= ~IFF_UP;
3780         re_setwol(sc);
3781         RL_UNLOCK(sc);
3782
3783         return (0);
3784 }
3785
3786 static void
3787 re_set_linkspeed(struct rl_softc *sc)
3788 {
3789         struct mii_softc *miisc;
3790         struct mii_data *mii;
3791         int aneg, i, phyno;
3792
3793         RL_LOCK_ASSERT(sc);
3794
3795         mii = device_get_softc(sc->rl_miibus);
3796         mii_pollstat(mii);
3797         aneg = 0;
3798         if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
3799             (IFM_ACTIVE | IFM_AVALID)) {
3800                 switch IFM_SUBTYPE(mii->mii_media_active) {
3801                 case IFM_10_T:
3802                 case IFM_100_TX:
3803                         return;
3804                 case IFM_1000_T:
3805                         aneg++;
3806                         break;
3807                 default:
3808                         break;
3809                 }
3810         }
3811         miisc = LIST_FIRST(&mii->mii_phys);
3812         phyno = miisc->mii_phy;
3813         LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
3814                 PHY_RESET(miisc);
3815         re_miibus_writereg(sc->rl_dev, phyno, MII_100T2CR, 0);
3816         re_miibus_writereg(sc->rl_dev, phyno,
3817             MII_ANAR, ANAR_TX_FD | ANAR_TX | ANAR_10_FD | ANAR_10 | ANAR_CSMA);
3818         re_miibus_writereg(sc->rl_dev, phyno,
3819             MII_BMCR, BMCR_AUTOEN | BMCR_STARTNEG);
3820         DELAY(1000);
3821         if (aneg != 0) {
3822                 /*
3823                  * Poll link state until re(4) get a 10/100Mbps link.
3824                  */
3825                 for (i = 0; i < MII_ANEGTICKS_GIGE; i++) {
3826                         mii_pollstat(mii);
3827                         if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID))
3828                             == (IFM_ACTIVE | IFM_AVALID)) {
3829                                 switch (IFM_SUBTYPE(mii->mii_media_active)) {
3830                                 case IFM_10_T:
3831                                 case IFM_100_TX:
3832                                         return;
3833                                 default:
3834                                         break;
3835                                 }
3836                         }
3837                         RL_UNLOCK(sc);
3838                         pause("relnk", hz);
3839                         RL_LOCK(sc);
3840                 }
3841                 if (i == MII_ANEGTICKS_GIGE)
3842                         device_printf(sc->rl_dev,
3843                             "establishing a link failed, WOL may not work!");
3844         }
3845         /*
3846          * No link, force MAC to have 100Mbps, full-duplex link.
3847          * MAC does not require reprogramming on resolved speed/duplex,
3848          * so this is just for completeness.
3849          */
3850         mii->mii_media_status = IFM_AVALID | IFM_ACTIVE;
3851         mii->mii_media_active = IFM_ETHER | IFM_100_TX | IFM_FDX;
3852 }
3853
3854 static void
3855 re_setwol(struct rl_softc *sc)
3856 {
3857         struct ifnet            *ifp;
3858         int                     pmc;
3859         uint16_t                pmstat;
3860         uint8_t                 v;
3861
3862         RL_LOCK_ASSERT(sc);
3863
3864         if (pci_find_cap(sc->rl_dev, PCIY_PMG, &pmc) != 0)
3865                 return;
3866
3867         ifp = sc->rl_ifp;
3868         /* Put controller into sleep mode. */
3869         if ((sc->rl_flags & RL_FLAG_MACSLEEP) != 0) {
3870                 if ((CSR_READ_1(sc, RL_MACDBG) & 0x80) == 0x80)
3871                         CSR_WRITE_1(sc, RL_GPIO,
3872                             CSR_READ_1(sc, RL_GPIO) & ~0x01);
3873         }
3874         if ((ifp->if_capenable & IFCAP_WOL) != 0) {
3875                 if ((sc->rl_flags & RL_FLAG_8168G_PLUS) != 0) {
3876                         /* Disable RXDV gate. */
3877                         CSR_WRITE_4(sc, RL_MISC, CSR_READ_4(sc, RL_MISC) &
3878                             ~0x00080000);
3879                 }
3880                 re_set_rxmode(sc);
3881                 if ((sc->rl_flags & RL_FLAG_WOL_MANLINK) != 0)
3882                         re_set_linkspeed(sc);
3883                 if ((sc->rl_flags & RL_FLAG_WOLRXENB) != 0)
3884                         CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RX_ENB);
3885         }
3886         /* Enable config register write. */
3887         CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
3888
3889         /* Enable PME. */
3890         v = CSR_READ_1(sc, sc->rl_cfg1);
3891         v &= ~RL_CFG1_PME;
3892         if ((ifp->if_capenable & IFCAP_WOL) != 0)
3893                 v |= RL_CFG1_PME;
3894         CSR_WRITE_1(sc, sc->rl_cfg1, v);
3895
3896         v = CSR_READ_1(sc, sc->rl_cfg3);
3897         v &= ~(RL_CFG3_WOL_LINK | RL_CFG3_WOL_MAGIC);
3898         if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
3899                 v |= RL_CFG3_WOL_MAGIC;
3900         CSR_WRITE_1(sc, sc->rl_cfg3, v);
3901
3902         v = CSR_READ_1(sc, sc->rl_cfg5);
3903         v &= ~(RL_CFG5_WOL_BCAST | RL_CFG5_WOL_MCAST | RL_CFG5_WOL_UCAST |
3904             RL_CFG5_WOL_LANWAKE);
3905         if ((ifp->if_capenable & IFCAP_WOL_UCAST) != 0)
3906                 v |= RL_CFG5_WOL_UCAST;
3907         if ((ifp->if_capenable & IFCAP_WOL_MCAST) != 0)
3908                 v |= RL_CFG5_WOL_MCAST | RL_CFG5_WOL_BCAST;
3909         if ((ifp->if_capenable & IFCAP_WOL) != 0)
3910                 v |= RL_CFG5_WOL_LANWAKE;
3911         CSR_WRITE_1(sc, sc->rl_cfg5, v);
3912
3913         /* Config register write done. */
3914         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
3915
3916         if ((ifp->if_capenable & IFCAP_WOL) == 0 &&
3917             (sc->rl_flags & RL_FLAG_PHYWAKE_PM) != 0)
3918                 CSR_WRITE_1(sc, RL_PMCH, CSR_READ_1(sc, RL_PMCH) & ~0x80);
3919         /*
3920          * It seems that hardware resets its link speed to 100Mbps in
3921          * power down mode so switching to 100Mbps in driver is not
3922          * needed.
3923          */
3924
3925         /* Request PME if WOL is requested. */
3926         pmstat = pci_read_config(sc->rl_dev, pmc + PCIR_POWER_STATUS, 2);
3927         pmstat &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE);
3928         if ((ifp->if_capenable & IFCAP_WOL) != 0)
3929                 pmstat |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
3930         pci_write_config(sc->rl_dev, pmc + PCIR_POWER_STATUS, pmstat, 2);
3931 }
3932
3933 static void
3934 re_clrwol(struct rl_softc *sc)
3935 {
3936         int                     pmc;
3937         uint8_t                 v;
3938
3939         RL_LOCK_ASSERT(sc);
3940
3941         if (pci_find_cap(sc->rl_dev, PCIY_PMG, &pmc) != 0)
3942                 return;
3943
3944         /* Enable config register write. */
3945         CSR_WRITE_1(sc, RL_EECMD, RL_EE_MODE);
3946
3947         v = CSR_READ_1(sc, sc->rl_cfg3);
3948         v &= ~(RL_CFG3_WOL_LINK | RL_CFG3_WOL_MAGIC);
3949         CSR_WRITE_1(sc, sc->rl_cfg3, v);
3950
3951         /* Config register write done. */
3952         CSR_WRITE_1(sc, RL_EECMD, RL_EEMODE_OFF);
3953
3954         v = CSR_READ_1(sc, sc->rl_cfg5);
3955         v &= ~(RL_CFG5_WOL_BCAST | RL_CFG5_WOL_MCAST | RL_CFG5_WOL_UCAST);
3956         v &= ~RL_CFG5_WOL_LANWAKE;
3957         CSR_WRITE_1(sc, sc->rl_cfg5, v);
3958 }
3959
3960 static void
3961 re_add_sysctls(struct rl_softc *sc)
3962 {
3963         struct sysctl_ctx_list  *ctx;
3964         struct sysctl_oid_list  *children;
3965         int                     error;
3966
3967         ctx = device_get_sysctl_ctx(sc->rl_dev);
3968         children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->rl_dev));
3969
3970         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "stats",
3971             CTLTYPE_INT | CTLFLAG_RW, sc, 0, re_sysctl_stats, "I",
3972             "Statistics Information");
3973         if ((sc->rl_flags & (RL_FLAG_MSI | RL_FLAG_MSIX)) == 0)
3974                 return;
3975
3976         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "int_rx_mod",
3977             CTLTYPE_INT | CTLFLAG_RW, &sc->rl_int_rx_mod, 0,
3978             sysctl_hw_re_int_mod, "I", "re RX interrupt moderation");
3979         /* Pull in device tunables. */
3980         sc->rl_int_rx_mod = RL_TIMER_DEFAULT;
3981         error = resource_int_value(device_get_name(sc->rl_dev),
3982             device_get_unit(sc->rl_dev), "int_rx_mod", &sc->rl_int_rx_mod);
3983         if (error == 0) {
3984                 if (sc->rl_int_rx_mod < RL_TIMER_MIN ||
3985                     sc->rl_int_rx_mod > RL_TIMER_MAX) {
3986                         device_printf(sc->rl_dev, "int_rx_mod value out of "
3987                             "range; using default: %d\n",
3988                             RL_TIMER_DEFAULT);
3989                         sc->rl_int_rx_mod = RL_TIMER_DEFAULT;
3990                 }
3991         }
3992 }
3993
3994 static int
3995 re_sysctl_stats(SYSCTL_HANDLER_ARGS)
3996 {
3997         struct rl_softc         *sc;
3998         struct rl_stats         *stats;
3999         int                     error, i, result;
4000
4001         result = -1;
4002         error = sysctl_handle_int(oidp, &result, 0, req);
4003         if (error || req->newptr == NULL)
4004                 return (error);
4005
4006         if (result == 1) {
4007                 sc = (struct rl_softc *)arg1;
4008                 RL_LOCK(sc);
4009                 if ((sc->rl_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4010                         RL_UNLOCK(sc);
4011                         goto done;
4012                 }
4013                 bus_dmamap_sync(sc->rl_ldata.rl_stag,
4014                     sc->rl_ldata.rl_smap, BUS_DMASYNC_PREREAD);
4015                 CSR_WRITE_4(sc, RL_DUMPSTATS_HI,
4016                     RL_ADDR_HI(sc->rl_ldata.rl_stats_addr));
4017                 CSR_WRITE_4(sc, RL_DUMPSTATS_LO,
4018                     RL_ADDR_LO(sc->rl_ldata.rl_stats_addr));
4019                 CSR_WRITE_4(sc, RL_DUMPSTATS_LO,
4020                     RL_ADDR_LO(sc->rl_ldata.rl_stats_addr |
4021                     RL_DUMPSTATS_START));
4022                 for (i = RL_TIMEOUT; i > 0; i--) {
4023                         if ((CSR_READ_4(sc, RL_DUMPSTATS_LO) &
4024                             RL_DUMPSTATS_START) == 0)
4025                                 break;
4026                         DELAY(1000);
4027                 }
4028                 bus_dmamap_sync(sc->rl_ldata.rl_stag,
4029                     sc->rl_ldata.rl_smap, BUS_DMASYNC_POSTREAD);
4030                 RL_UNLOCK(sc);
4031                 if (i == 0) {
4032                         device_printf(sc->rl_dev,
4033                             "DUMP statistics request timed out\n");
4034                         return (ETIMEDOUT);
4035                 }
4036 done:
4037                 stats = sc->rl_ldata.rl_stats;
4038                 printf("%s statistics:\n", device_get_nameunit(sc->rl_dev));
4039                 printf("Tx frames : %ju\n",
4040                     (uintmax_t)le64toh(stats->rl_tx_pkts));
4041                 printf("Rx frames : %ju\n",
4042                     (uintmax_t)le64toh(stats->rl_rx_pkts));
4043                 printf("Tx errors : %ju\n",
4044                     (uintmax_t)le64toh(stats->rl_tx_errs));
4045                 printf("Rx errors : %u\n",
4046                     le32toh(stats->rl_rx_errs));
4047                 printf("Rx missed frames : %u\n",
4048                     (uint32_t)le16toh(stats->rl_missed_pkts));
4049                 printf("Rx frame alignment errs : %u\n",
4050                     (uint32_t)le16toh(stats->rl_rx_framealign_errs));
4051                 printf("Tx single collisions : %u\n",
4052                     le32toh(stats->rl_tx_onecoll));
4053                 printf("Tx multiple collisions : %u\n",
4054                     le32toh(stats->rl_tx_multicolls));
4055                 printf("Rx unicast frames : %ju\n",
4056                     (uintmax_t)le64toh(stats->rl_rx_ucasts));
4057                 printf("Rx broadcast frames : %ju\n",
4058                     (uintmax_t)le64toh(stats->rl_rx_bcasts));
4059                 printf("Rx multicast frames : %u\n",
4060                     le32toh(stats->rl_rx_mcasts));
4061                 printf("Tx aborts : %u\n",
4062                     (uint32_t)le16toh(stats->rl_tx_aborts));
4063                 printf("Tx underruns : %u\n",
4064                     (uint32_t)le16toh(stats->rl_rx_underruns));
4065         }
4066
4067         return (error);
4068 }
4069
4070 static int
4071 sysctl_int_range(SYSCTL_HANDLER_ARGS, int low, int high)
4072 {
4073         int error, value;
4074
4075         if (arg1 == NULL)
4076                 return (EINVAL);
4077         value = *(int *)arg1;
4078         error = sysctl_handle_int(oidp, &value, 0, req);
4079         if (error || req->newptr == NULL)
4080                 return (error);
4081         if (value < low || value > high)
4082                 return (EINVAL);
4083         *(int *)arg1 = value;
4084
4085         return (0);
4086 }
4087
4088 static int
4089 sysctl_hw_re_int_mod(SYSCTL_HANDLER_ARGS)
4090 {
4091
4092         return (sysctl_int_range(oidp, arg1, arg2, req, RL_TIMER_MIN,
4093             RL_TIMER_MAX));
4094 }
4095
4096 #ifdef NETDUMP
4097 static void
4098 re_netdump_init(struct ifnet *ifp, int *nrxr, int *ncl, int *clsize)
4099 {
4100         struct rl_softc *sc;
4101
4102         sc = if_getsoftc(ifp);
4103         RL_LOCK(sc);
4104         *nrxr = sc->rl_ldata.rl_rx_desc_cnt;
4105         *ncl = NETDUMP_MAX_IN_FLIGHT;
4106         *clsize = (ifp->if_mtu > RL_MTU &&
4107             (sc->rl_flags & RL_FLAG_JUMBOV2) != 0) ? MJUM9BYTES : MCLBYTES;
4108         RL_UNLOCK(sc);
4109 }
4110
4111 static void
4112 re_netdump_event(struct ifnet *ifp __unused, enum netdump_ev event __unused)
4113 {
4114 }
4115
4116 static int
4117 re_netdump_transmit(struct ifnet *ifp, struct mbuf *m)
4118 {
4119         struct rl_softc *sc;
4120         int error;
4121
4122         sc = if_getsoftc(ifp);
4123         if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
4124             IFF_DRV_RUNNING || (sc->rl_flags & RL_FLAG_LINK) == 0)
4125                 return (EBUSY);
4126
4127         error = re_encap(sc, &m);
4128         if (error == 0)
4129                 re_start_tx(sc);
4130         return (error);
4131 }
4132
4133 static int
4134 re_netdump_poll(struct ifnet *ifp, int count)
4135 {
4136         struct rl_softc *sc;
4137         int error;
4138
4139         sc = if_getsoftc(ifp);
4140         if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
4141             (sc->rl_flags & RL_FLAG_LINK) == 0)
4142                 return (EBUSY);
4143
4144         re_txeof(sc);
4145         error = re_rxeof(sc, NULL);
4146         if (error != 0 && error != EAGAIN)
4147                 return (error);
4148         return (0);
4149 }
4150 #endif /* NETDUMP */