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