xref: /dflybsd-src/sys/dev/netif/re/if_re.c (revision b77f5f80d15dc7078037f892777955cc2e8286d2)
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.99 2008/10/30 11:27:40 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 
160 /*
161  * Various supported device vendors/types and their names.
162  */
163 static const struct re_type {
164 	uint16_t	re_vid;
165 	uint16_t	re_did;
166 	const char	*re_name;
167 } re_devs[] = {
168 	{ PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DGE528T,
169 	  "D-Link DGE-528(T) Gigabit Ethernet Adapter" },
170 
171 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139,
172 	  "RealTek 8139C+ 10/100BaseTX" },
173 
174 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8101E,
175 	  "RealTek 810x PCIe 10/100baseTX" },
176 
177 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8168,
178 	  "RealTek 8111/8168 PCIe Gigabit Ethernet" },
179 
180 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169,
181 	  "RealTek 8110/8169 Gigabit Ethernet" },
182 
183 	{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8169SC,
184 	  "RealTek 8169SC/8110SC Single-chip Gigabit Ethernet" },
185 
186 	{ PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CG_LAPCIGT,
187 	  "Corega CG-LAPCIGT Gigabit Ethernet" },
188 
189 	{ PCI_VENDOR_LINKSYS, PCI_PRODUCT_LINKSYS_EG1032,
190 	  "Linksys EG1032 Gigabit Ethernet" },
191 
192 	{ PCI_VENDOR_USR2, PCI_PRODUCT_USR2_997902,
193 	  "US Robotics 997902 Gigabit Ethernet" },
194 
195 	{ PCI_VENDOR_TTTECH, PCI_PRODUCT_TTTECH_MC322,
196 	  "TTTech MC322 Gigabit Ethernet" },
197 
198 	{ 0, 0, NULL }
199 };
200 
201 static const struct re_hwrev re_hwrevs[] = {
202 	{ RE_HWREV_8139CPLUS,	RE_MACVER_UNKN,		ETHERMTU,
203 	  RE_C_HWCSUM | RE_C_8139CP | RE_C_FASTE },
204 
205 	{ RE_HWREV_8169,	RE_MACVER_UNKN,		ETHERMTU,
206 	  RE_C_HWCSUM | RE_C_8169 },
207 
208 	{ RE_HWREV_8110S,	RE_MACVER_03,		RE_MTU_6K,
209 	  RE_C_HWCSUM | RE_C_8169 },
210 
211 	{ RE_HWREV_8169S,	RE_MACVER_03,		RE_MTU_6K,
212 	  RE_C_HWCSUM | RE_C_8169 },
213 
214 	{ RE_HWREV_8169SB,	RE_MACVER_04,		RE_MTU_6K,
215 	  RE_C_HWCSUM | RE_C_PHYPMGT | RE_C_8169 },
216 
217 	{ RE_HWREV_8169SC1,	RE_MACVER_05,		RE_MTU_6K,
218 	  RE_C_HWCSUM | RE_C_PHYPMGT | RE_C_8169 },
219 
220 	{ RE_HWREV_8169SC2,	RE_MACVER_06,		RE_MTU_6K,
221 	  RE_C_HWCSUM | RE_C_PHYPMGT | RE_C_8169 },
222 
223 	{ RE_HWREV_8168B1,	RE_MACVER_21,		RE_MTU_6K,
224 	  RE_C_HWIM | RE_C_HWCSUM | RE_C_PHYPMGT },
225 
226 	{ RE_HWREV_8168B2,	RE_MACVER_23,		RE_MTU_6K,
227 	  RE_C_HWIM | RE_C_HWCSUM | RE_C_PHYPMGT | RE_C_AUTOPAD },
228 
229 	{ RE_HWREV_8168B3,	RE_MACVER_23,		RE_MTU_6K,
230 	  RE_C_HWIM | RE_C_HWCSUM | RE_C_PHYPMGT | RE_C_AUTOPAD },
231 
232 	{ RE_HWREV_8168C,	RE_MACVER_29,		RE_MTU_6K,
233 	  RE_C_HWIM | RE_C_HWCSUM | RE_C_MAC2 | RE_C_PHYPMGT |
234 	  RE_C_AUTOPAD | RE_C_CONTIGRX | RE_C_STOP_RXTX },
235 
236 	{ RE_HWREV_8168CP,	RE_MACVER_2B,		RE_MTU_6K,
237 	  RE_C_HWIM | RE_C_HWCSUM | RE_C_MAC2 | RE_C_PHYPMGT |
238 	  RE_C_AUTOPAD | RE_C_CONTIGRX | RE_C_STOP_RXTX },
239 
240 	{ RE_HWREV_8168D,	RE_MACVER_2A,		RE_MTU_9K,
241 	  RE_C_HWIM | RE_C_HWCSUM | RE_C_MAC2 | RE_C_PHYPMGT |
242 	  RE_C_AUTOPAD | RE_C_CONTIGRX | RE_C_STOP_RXTX },
243 
244 	{ RE_HWREV_8100E,	RE_MACVER_UNKN,		ETHERMTU,
245 	  RE_C_HWCSUM | RE_C_FASTE },
246 
247 	{ RE_HWREV_8101E1,	RE_MACVER_16,		ETHERMTU,
248 	  RE_C_HWCSUM | RE_C_FASTE },
249 
250 	{ RE_HWREV_8101E2,	RE_MACVER_16,		ETHERMTU,
251 	  RE_C_HWCSUM | RE_C_FASTE },
252 
253 	{ RE_HWREV_8102E,	RE_MACVER_15,		ETHERMTU,
254 	  RE_C_HWCSUM | RE_C_MAC2 | RE_C_AUTOPAD | RE_C_STOP_RXTX |
255 	  RE_C_FASTE },
256 
257 	{ RE_HWREV_8102EL,	RE_MACVER_15,		ETHERMTU,
258 	  RE_C_HWCSUM | RE_C_MAC2 | RE_C_AUTOPAD | RE_C_STOP_RXTX |
259 	  RE_C_FASTE },
260 
261 	{ RE_HWREV_NULL, 0, 0, 0 }
262 };
263 
264 static int	re_probe(device_t);
265 static int	re_attach(device_t);
266 static int	re_detach(device_t);
267 static int	re_suspend(device_t);
268 static int	re_resume(device_t);
269 static void	re_shutdown(device_t);
270 
271 static void	re_dma_map_addr(void *, bus_dma_segment_t *, int, int);
272 static void	re_dma_map_desc(void *, bus_dma_segment_t *, int,
273 				bus_size_t, int);
274 static int	re_allocmem(device_t);
275 static void	re_freemem(device_t);
276 static void	re_freebufmem(struct re_softc *, int, int);
277 static int	re_encap(struct re_softc *, struct mbuf **, int *);
278 static int	re_newbuf_std(struct re_softc *, int, int);
279 static int	re_newbuf_jumbo(struct re_softc *, int, int);
280 static void	re_setup_rxdesc(struct re_softc *, int);
281 static int	re_rx_list_init(struct re_softc *);
282 static int	re_tx_list_init(struct re_softc *);
283 static int	re_rxeof(struct re_softc *);
284 static int	re_txeof(struct re_softc *);
285 static int	re_tx_collect(struct re_softc *);
286 static void	re_intr(void *);
287 static void	re_tick(void *);
288 static void	re_tick_serialized(void *);
289 
290 static void	re_start(struct ifnet *);
291 static int	re_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
292 static void	re_init(void *);
293 static void	re_stop(struct re_softc *);
294 static void	re_watchdog(struct ifnet *);
295 static int	re_ifmedia_upd(struct ifnet *);
296 static void	re_ifmedia_sts(struct ifnet *, struct ifmediareq *);
297 
298 static void	re_eeprom_putbyte(struct re_softc *, int);
299 static void	re_eeprom_getword(struct re_softc *, int, u_int16_t *);
300 static void	re_read_eeprom(struct re_softc *, caddr_t, int, int);
301 static void	re_get_eewidth(struct re_softc *);
302 
303 static int	re_gmii_readreg(device_t, int, int);
304 static int	re_gmii_writereg(device_t, int, int, int);
305 
306 static int	re_miibus_readreg(device_t, int, int);
307 static int	re_miibus_writereg(device_t, int, int, int);
308 static void	re_miibus_statchg(device_t);
309 
310 static void	re_setmulti(struct re_softc *);
311 static void	re_reset(struct re_softc *, int);
312 static void	re_get_eaddr(struct re_softc *, uint8_t *);
313 
314 static void	re_setup_hw_im(struct re_softc *);
315 static void	re_setup_sim_im(struct re_softc *);
316 static void	re_disable_hw_im(struct re_softc *);
317 static void	re_disable_sim_im(struct re_softc *);
318 static void	re_config_imtype(struct re_softc *, int);
319 static void	re_setup_intr(struct re_softc *, int, int);
320 
321 static int	re_sysctl_hwtime(SYSCTL_HANDLER_ARGS, int *);
322 static int	re_sysctl_rxtime(SYSCTL_HANDLER_ARGS);
323 static int	re_sysctl_txtime(SYSCTL_HANDLER_ARGS);
324 static int	re_sysctl_simtime(SYSCTL_HANDLER_ARGS);
325 static int	re_sysctl_imtype(SYSCTL_HANDLER_ARGS);
326 
327 static int	re_jpool_alloc(struct re_softc *);
328 static void	re_jpool_free(struct re_softc *);
329 static struct re_jbuf *re_jbuf_alloc(struct re_softc *);
330 static void	re_jbuf_free(void *);
331 static void	re_jbuf_ref(void *);
332 
333 #ifdef RE_DIAG
334 static int	re_diag(struct re_softc *);
335 #endif
336 
337 #ifdef DEVICE_POLLING
338 static void	re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
339 #endif
340 
341 static device_method_t re_methods[] = {
342 	/* Device interface */
343 	DEVMETHOD(device_probe,		re_probe),
344 	DEVMETHOD(device_attach,	re_attach),
345 	DEVMETHOD(device_detach,	re_detach),
346 	DEVMETHOD(device_suspend,	re_suspend),
347 	DEVMETHOD(device_resume,	re_resume),
348 	DEVMETHOD(device_shutdown,	re_shutdown),
349 
350 	/* bus interface */
351 	DEVMETHOD(bus_print_child,	bus_generic_print_child),
352 	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
353 
354 	/* MII interface */
355 	DEVMETHOD(miibus_readreg,	re_miibus_readreg),
356 	DEVMETHOD(miibus_writereg,	re_miibus_writereg),
357 	DEVMETHOD(miibus_statchg,	re_miibus_statchg),
358 
359 	{ 0, 0 }
360 };
361 
362 static driver_t re_driver = {
363 	"re",
364 	re_methods,
365 	sizeof(struct re_softc)
366 };
367 
368 static devclass_t re_devclass;
369 
370 DECLARE_DUMMY_MODULE(if_re);
371 MODULE_DEPEND(if_re, miibus, 1, 1, 1);
372 DRIVER_MODULE(if_re, pci, re_driver, re_devclass, 0, 0);
373 DRIVER_MODULE(if_re, cardbus, re_driver, re_devclass, 0, 0);
374 DRIVER_MODULE(miibus, re, miibus_driver, miibus_devclass, 0, 0);
375 
376 static int	re_rx_desc_count = RE_RX_DESC_CNT_DEF;
377 static int	re_tx_desc_count = RE_TX_DESC_CNT_DEF;
378 
379 TUNABLE_INT("hw.re.rx_desc_count", &re_rx_desc_count);
380 TUNABLE_INT("hw.re.tx_desc_count", &re_tx_desc_count);
381 
382 #define EE_SET(x)	\
383 	CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) | (x))
384 
385 #define EE_CLR(x)	\
386 	CSR_WRITE_1(sc, RE_EECMD, CSR_READ_1(sc, RE_EECMD) & ~(x))
387 
388 static __inline void
389 re_free_rxchain(struct re_softc *sc)
390 {
391 	if (sc->re_head != NULL) {
392 		m_freem(sc->re_head);
393 		sc->re_head = sc->re_tail = NULL;
394 	}
395 }
396 
397 /*
398  * Send a read command and address to the EEPROM, check for ACK.
399  */
400 static void
401 re_eeprom_putbyte(struct re_softc *sc, int addr)
402 {
403 	int d, i;
404 
405 	d = addr | (RE_9346_READ << sc->re_eewidth);
406 
407 	/*
408 	 * Feed in each bit and strobe the clock.
409 	 */
410 	for (i = 1 << (sc->re_eewidth + 3); i; i >>= 1) {
411 		if (d & i)
412 			EE_SET(RE_EE_DATAIN);
413 		else
414 			EE_CLR(RE_EE_DATAIN);
415 		DELAY(100);
416 		EE_SET(RE_EE_CLK);
417 		DELAY(150);
418 		EE_CLR(RE_EE_CLK);
419 		DELAY(100);
420 	}
421 }
422 
423 /*
424  * Read a word of data stored in the EEPROM at address 'addr.'
425  */
426 static void
427 re_eeprom_getword(struct re_softc *sc, int addr, uint16_t *dest)
428 {
429 	int i;
430 	uint16_t word = 0;
431 
432 	/*
433 	 * Send address of word we want to read.
434 	 */
435 	re_eeprom_putbyte(sc, addr);
436 
437 	/*
438 	 * Start reading bits from EEPROM.
439 	 */
440 	for (i = 0x8000; i != 0; i >>= 1) {
441 		EE_SET(RE_EE_CLK);
442 		DELAY(100);
443 		if (CSR_READ_1(sc, RE_EECMD) & RE_EE_DATAOUT)
444 			word |= i;
445 		EE_CLR(RE_EE_CLK);
446 		DELAY(100);
447 	}
448 
449 	*dest = word;
450 }
451 
452 /*
453  * Read a sequence of words from the EEPROM.
454  */
455 static void
456 re_read_eeprom(struct re_softc *sc, caddr_t dest, int off, int cnt)
457 {
458 	int i;
459 	uint16_t word = 0, *ptr;
460 
461 	CSR_SETBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
462 	DELAY(100);
463 
464 	for (i = 0; i < cnt; i++) {
465 		CSR_SETBIT_1(sc, RE_EECMD, RE_EE_SEL);
466 		re_eeprom_getword(sc, off + i, &word);
467 		CSR_CLRBIT_1(sc, RE_EECMD, RE_EE_SEL);
468 		ptr = (uint16_t *)(dest + (i * 2));
469 		*ptr = word;
470 	}
471 
472 	CSR_CLRBIT_1(sc, RE_EECMD, RE_EEMODE_PROGRAM);
473 }
474 
475 static void
476 re_get_eewidth(struct re_softc *sc)
477 {
478 	uint16_t re_did = 0;
479 
480 	sc->re_eewidth = 6;
481 	re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
482 	if (re_did != 0x8129)
483 		sc->re_eewidth = 8;
484 }
485 
486 static int
487 re_gmii_readreg(device_t dev, int phy, int reg)
488 {
489 	struct re_softc *sc = device_get_softc(dev);
490 	u_int32_t rval;
491 	int i;
492 
493 	if (phy != 1)
494 		return(0);
495 
496 	/* Let the rgephy driver read the GMEDIASTAT register */
497 
498 	if (reg == RE_GMEDIASTAT)
499 		return(CSR_READ_1(sc, RE_GMEDIASTAT));
500 
501 	CSR_WRITE_4(sc, RE_PHYAR, reg << 16);
502 	DELAY(1000);
503 
504 	for (i = 0; i < RE_TIMEOUT; i++) {
505 		rval = CSR_READ_4(sc, RE_PHYAR);
506 		if (rval & RE_PHYAR_BUSY)
507 			break;
508 		DELAY(100);
509 	}
510 
511 	if (i == RE_TIMEOUT) {
512 		device_printf(dev, "PHY read failed\n");
513 		return(0);
514 	}
515 
516 	return(rval & RE_PHYAR_PHYDATA);
517 }
518 
519 static int
520 re_gmii_writereg(device_t dev, int phy, int reg, int data)
521 {
522 	struct re_softc *sc = device_get_softc(dev);
523 	uint32_t rval;
524 	int i;
525 
526 	CSR_WRITE_4(sc, RE_PHYAR,
527 		    (reg << 16) | (data & RE_PHYAR_PHYDATA) | RE_PHYAR_BUSY);
528 	DELAY(1000);
529 
530 	for (i = 0; i < RE_TIMEOUT; i++) {
531 		rval = CSR_READ_4(sc, RE_PHYAR);
532 		if ((rval & RE_PHYAR_BUSY) == 0)
533 			break;
534 		DELAY(100);
535 	}
536 
537 	if (i == RE_TIMEOUT)
538 		device_printf(dev, "PHY write failed\n");
539 
540 	return(0);
541 }
542 
543 static int
544 re_miibus_readreg(device_t dev, int phy, int reg)
545 {
546 	struct re_softc	*sc = device_get_softc(dev);
547 	uint16_t rval = 0;
548 	uint16_t re8139_reg = 0;
549 
550 	if (!RE_IS_8139CP(sc)) {
551 		rval = re_gmii_readreg(dev, phy, reg);
552 		return(rval);
553 	}
554 
555 	/* Pretend the internal PHY is only at address 0 */
556 	if (phy)
557 		return(0);
558 
559 	switch(reg) {
560 	case MII_BMCR:
561 		re8139_reg = RE_BMCR;
562 		break;
563 	case MII_BMSR:
564 		re8139_reg = RE_BMSR;
565 		break;
566 	case MII_ANAR:
567 		re8139_reg = RE_ANAR;
568 		break;
569 	case MII_ANER:
570 		re8139_reg = RE_ANER;
571 		break;
572 	case MII_ANLPAR:
573 		re8139_reg = RE_LPAR;
574 		break;
575 	case MII_PHYIDR1:
576 	case MII_PHYIDR2:
577 		return(0);
578 	/*
579 	 * Allow the rlphy driver to read the media status
580 	 * register. If we have a link partner which does not
581 	 * support NWAY, this is the register which will tell
582 	 * us the results of parallel detection.
583 	 */
584 	case RE_MEDIASTAT:
585 		return(CSR_READ_1(sc, RE_MEDIASTAT));
586 	default:
587 		device_printf(dev, "bad phy register\n");
588 		return(0);
589 	}
590 	rval = CSR_READ_2(sc, re8139_reg);
591 	if (re8139_reg == RE_BMCR) {
592 		/* 8139C+ has different bit layout. */
593 		rval &= ~(BMCR_LOOP | BMCR_ISO);
594 	}
595 	return(rval);
596 }
597 
598 static int
599 re_miibus_writereg(device_t dev, int phy, int reg, int data)
600 {
601 	struct re_softc *sc= device_get_softc(dev);
602 	u_int16_t re8139_reg = 0;
603 
604 	if (!RE_IS_8139CP(sc))
605 		return(re_gmii_writereg(dev, phy, reg, data));
606 
607 	/* Pretend the internal PHY is only at address 0 */
608 	if (phy)
609 		return(0);
610 
611 	switch(reg) {
612 	case MII_BMCR:
613 		re8139_reg = RE_BMCR;
614 		/* 8139C+ has different bit layout. */
615 		data &= ~(BMCR_LOOP | BMCR_ISO);
616 		break;
617 	case MII_BMSR:
618 		re8139_reg = RE_BMSR;
619 		break;
620 	case MII_ANAR:
621 		re8139_reg = RE_ANAR;
622 		break;
623 	case MII_ANER:
624 		re8139_reg = RE_ANER;
625 		break;
626 	case MII_ANLPAR:
627 		re8139_reg = RE_LPAR;
628 		break;
629 	case MII_PHYIDR1:
630 	case MII_PHYIDR2:
631 		return(0);
632 	default:
633 		device_printf(dev, "bad phy register\n");
634 		return(0);
635 	}
636 	CSR_WRITE_2(sc, re8139_reg, data);
637 	return(0);
638 }
639 
640 static void
641 re_miibus_statchg(device_t dev)
642 {
643 }
644 
645 /*
646  * Program the 64-bit multicast hash filter.
647  */
648 static void
649 re_setmulti(struct re_softc *sc)
650 {
651 	struct ifnet *ifp = &sc->arpcom.ac_if;
652 	int h = 0;
653 	uint32_t hashes[2] = { 0, 0 };
654 	struct ifmultiaddr *ifma;
655 	uint32_t rxfilt;
656 	int mcnt = 0;
657 
658 	rxfilt = CSR_READ_4(sc, RE_RXCFG);
659 
660 	/* Set the individual bit to receive frames for this host only. */
661 	rxfilt |= RE_RXCFG_RX_INDIV;
662 	/* Set capture broadcast bit to capture broadcast frames. */
663 	rxfilt |= RE_RXCFG_RX_BROAD;
664 
665 	rxfilt &= ~(RE_RXCFG_RX_ALLPHYS | RE_RXCFG_RX_MULTI);
666 	if ((ifp->if_flags & IFF_ALLMULTI) || (ifp->if_flags & IFF_PROMISC)) {
667 		rxfilt |= RE_RXCFG_RX_MULTI;
668 
669 		/* If we want promiscuous mode, set the allframes bit. */
670 		if (ifp->if_flags & IFF_PROMISC)
671 			rxfilt |= RE_RXCFG_RX_ALLPHYS;
672 
673 		CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
674 		CSR_WRITE_4(sc, RE_MAR0, 0xFFFFFFFF);
675 		CSR_WRITE_4(sc, RE_MAR4, 0xFFFFFFFF);
676 		return;
677 	}
678 
679 	/* first, zot all the existing hash bits */
680 	CSR_WRITE_4(sc, RE_MAR0, 0);
681 	CSR_WRITE_4(sc, RE_MAR4, 0);
682 
683 	/* now program new ones */
684 	LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
685 		if (ifma->ifma_addr->sa_family != AF_LINK)
686 			continue;
687 		h = ether_crc32_be(LLADDR((struct sockaddr_dl *)
688 		    ifma->ifma_addr), ETHER_ADDR_LEN) >> 26;
689 		if (h < 32)
690 			hashes[0] |= (1 << h);
691 		else
692 			hashes[1] |= (1 << (h - 32));
693 		mcnt++;
694 	}
695 
696 	if (mcnt)
697 		rxfilt |= RE_RXCFG_RX_MULTI;
698 	else
699 		rxfilt &= ~RE_RXCFG_RX_MULTI;
700 
701 	CSR_WRITE_4(sc, RE_RXCFG, rxfilt);
702 
703 	/*
704 	 * For some unfathomable reason, RealTek decided to reverse
705 	 * the order of the multicast hash registers in the PCI Express
706 	 * parts. This means we have to write the hash pattern in reverse
707 	 * order for those devices.
708 	 */
709 	if (sc->re_caps & RE_C_PCIE) {
710 		CSR_WRITE_4(sc, RE_MAR0, bswap32(hashes[0]));
711 		CSR_WRITE_4(sc, RE_MAR4, bswap32(hashes[1]));
712 	} else {
713 		CSR_WRITE_4(sc, RE_MAR0, hashes[0]);
714 		CSR_WRITE_4(sc, RE_MAR4, hashes[1]);
715 	}
716 }
717 
718 static void
719 re_reset(struct re_softc *sc, int running)
720 {
721 	int i;
722 
723 	if ((sc->re_caps & RE_C_STOP_RXTX) && running) {
724 		CSR_WRITE_1(sc, RE_COMMAND,
725 			    RE_CMD_STOPREQ | RE_CMD_TX_ENB | RE_CMD_RX_ENB);
726 		DELAY(100);
727 	}
728 
729 	CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_RESET);
730 
731 	for (i = 0; i < RE_TIMEOUT; i++) {
732 		DELAY(10);
733 		if ((CSR_READ_1(sc, RE_COMMAND) & RE_CMD_RESET) == 0)
734 			break;
735 	}
736 	if (i == RE_TIMEOUT)
737 		if_printf(&sc->arpcom.ac_if, "reset never completed!\n");
738 }
739 
740 #ifdef RE_DIAG
741 /*
742  * The following routine is designed to test for a defect on some
743  * 32-bit 8169 cards. Some of these NICs have the REQ64# and ACK64#
744  * lines connected to the bus, however for a 32-bit only card, they
745  * should be pulled high. The result of this defect is that the
746  * NIC will not work right if you plug it into a 64-bit slot: DMA
747  * operations will be done with 64-bit transfers, which will fail
748  * because the 64-bit data lines aren't connected.
749  *
750  * There's no way to work around this (short of talking a soldering
751  * iron to the board), however we can detect it. The method we use
752  * here is to put the NIC into digital loopback mode, set the receiver
753  * to promiscuous mode, and then try to send a frame. We then compare
754  * the frame data we sent to what was received. If the data matches,
755  * then the NIC is working correctly, otherwise we know the user has
756  * a defective NIC which has been mistakenly plugged into a 64-bit PCI
757  * slot. In the latter case, there's no way the NIC can work correctly,
758  * so we print out a message on the console and abort the device attach.
759  */
760 
761 static int
762 re_diag(struct re_softc *sc)
763 {
764 	struct ifnet *ifp = &sc->arpcom.ac_if;
765 	struct mbuf *m0;
766 	struct ether_header *eh;
767 	struct re_desc *cur_rx;
768 	uint16_t status;
769 	uint32_t rxstat;
770 	int total_len, i, error = 0, phyaddr;
771 	uint8_t dst[ETHER_ADDR_LEN] = { 0x00, 'h', 'e', 'l', 'l', 'o' };
772 	uint8_t src[ETHER_ADDR_LEN] = { 0x00, 'w', 'o', 'r', 'l', 'd' };
773 
774 	/* Allocate a single mbuf */
775 
776 	MGETHDR(m0, MB_DONTWAIT, MT_DATA);
777 	if (m0 == NULL)
778 		return(ENOBUFS);
779 
780 	/*
781 	 * Initialize the NIC in test mode. This sets the chip up
782 	 * so that it can send and receive frames, but performs the
783 	 * following special functions:
784 	 * - Puts receiver in promiscuous mode
785 	 * - Enables digital loopback mode
786 	 * - Leaves interrupts turned off
787 	 */
788 
789 	ifp->if_flags |= IFF_PROMISC;
790 	sc->re_flags |= RE_F_TESTMODE;
791 	re_init(sc);
792 	sc->re_flags |= RE_F_LINKED;
793 	if (!RE_IS_8139CP(sc))
794 		phyaddr = 1;
795 	else
796 		phyaddr = 0;
797 
798 	re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_RESET);
799 	for (i = 0; i < RE_TIMEOUT; i++) {
800 		status = re_miibus_readreg(sc->re_dev, phyaddr, MII_BMCR);
801 		if (!(status & BMCR_RESET))
802 			break;
803 	}
804 
805 	re_miibus_writereg(sc->re_dev, phyaddr, MII_BMCR, BMCR_LOOP);
806 	CSR_WRITE_2(sc, RE_ISR, RE_INTRS_DIAG);
807 
808 	DELAY(100000);
809 
810 	/* Put some data in the mbuf */
811 
812 	eh = mtod(m0, struct ether_header *);
813 	bcopy (dst, eh->ether_dhost, ETHER_ADDR_LEN);
814 	bcopy (src, eh->ether_shost, ETHER_ADDR_LEN);
815 	eh->ether_type = htons(ETHERTYPE_IP);
816 	m0->m_pkthdr.len = m0->m_len = ETHER_MIN_LEN - ETHER_CRC_LEN;
817 
818 	/*
819 	 * Queue the packet, start transmission.
820 	 * Note: ifq_handoff() ultimately calls re_start() for us.
821 	 */
822 
823 	CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
824 	error = ifq_handoff(ifp, m0, NULL);
825 	if (error) {
826 		m0 = NULL;
827 		goto done;
828 	}
829 	m0 = NULL;
830 
831 	/* Wait for it to propagate through the chip */
832 
833 	DELAY(100000);
834 	for (i = 0; i < RE_TIMEOUT; i++) {
835 		status = CSR_READ_2(sc, RE_ISR);
836 		CSR_WRITE_2(sc, RE_ISR, status);
837 		if ((status & (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK)) ==
838 		    (RE_ISR_TIMEOUT_EXPIRED|RE_ISR_RX_OK))
839 			break;
840 		DELAY(10);
841 	}
842 
843 	if (i == RE_TIMEOUT) {
844 		if_printf(ifp, "diagnostic failed to receive packet "
845 			  "in loopback mode\n");
846 		error = EIO;
847 		goto done;
848 	}
849 
850 	/*
851 	 * The packet should have been dumped into the first
852 	 * entry in the RX DMA ring. Grab it from there.
853 	 */
854 
855 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
856 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
857 	bus_dmamap_sync(sc->re_ldata.re_rx_mtag, sc->re_ldata.re_rx_dmamap[0],
858 			BUS_DMASYNC_POSTREAD);
859 	bus_dmamap_unload(sc->re_ldata.re_rx_mtag,
860 			  sc->re_ldata.re_rx_dmamap[0]);
861 
862 	m0 = sc->re_ldata.re_rx_mbuf[0];
863 	sc->re_ldata.re_rx_mbuf[0] = NULL;
864 	eh = mtod(m0, struct ether_header *);
865 
866 	cur_rx = &sc->re_ldata.re_rx_list[0];
867 	total_len = RE_RXBYTES(cur_rx);
868 	rxstat = le32toh(cur_rx->re_cmdstat);
869 
870 	if (total_len != ETHER_MIN_LEN) {
871 		if_printf(ifp, "diagnostic failed, received short packet\n");
872 		error = EIO;
873 		goto done;
874 	}
875 
876 	/* Test that the received packet data matches what we sent. */
877 
878 	if (bcmp(eh->ether_dhost, dst, ETHER_ADDR_LEN) ||
879 	    bcmp(eh->ether_shost, &src, ETHER_ADDR_LEN) ||
880 	    be16toh(eh->ether_type) != ETHERTYPE_IP) {
881 		if_printf(ifp, "WARNING, DMA FAILURE!\n");
882 		if_printf(ifp, "expected TX data: %6D/%6D/0x%x\n",
883 		    dst, ":", src, ":", ETHERTYPE_IP);
884 		if_printf(ifp, "received RX data: %6D/%6D/0x%x\n",
885 		    eh->ether_dhost, ":",  eh->ether_shost, ":",
886 		    ntohs(eh->ether_type));
887 		if_printf(ifp, "You may have a defective 32-bit NIC plugged "
888 		    "into a 64-bit PCI slot.\n");
889 		if_printf(ifp, "Please re-install the NIC in a 32-bit slot "
890 		    "for proper operation.\n");
891 		if_printf(ifp, "Read the re(4) man page for more details.\n");
892 		error = EIO;
893 	}
894 
895 done:
896 	/* Turn interface off, release resources */
897 
898 	sc->re_flags &= ~(RE_F_LINKED | RE_F_TESTMODE);
899 	ifp->if_flags &= ~IFF_PROMISC;
900 	re_stop(sc);
901 	if (m0 != NULL)
902 		m_freem(m0);
903 
904 	return (error);
905 }
906 #endif	/* RE_DIAG */
907 
908 /*
909  * Probe for a RealTek 8139C+/8169/8110 chip. Check the PCI vendor and device
910  * IDs against our list and return a device name if we find a match.
911  */
912 static int
913 re_probe(device_t dev)
914 {
915 	const struct re_type *t;
916 	const struct re_hwrev *hw_rev;
917 	struct re_softc *sc;
918 	int rid;
919 	uint32_t hwrev, macmode, txcfg;
920 	uint16_t vendor, product;
921 
922 	vendor = pci_get_vendor(dev);
923 	product = pci_get_device(dev);
924 
925 	/*
926 	 * Only attach to rev.3 of the Linksys EG1032 adapter.
927 	 * Rev.2 is supported by sk(4).
928 	 */
929 	if (vendor == PCI_VENDOR_LINKSYS &&
930 	    product == PCI_PRODUCT_LINKSYS_EG1032 &&
931 	    pci_get_subdevice(dev) != PCI_SUBDEVICE_LINKSYS_EG1032_REV3)
932 		return ENXIO;
933 
934 	if (vendor == PCI_VENDOR_REALTEK &&
935 	    product == PCI_PRODUCT_REALTEK_RT8139 &&
936 	    pci_get_revid(dev) != PCI_REVID_REALTEK_RT8139CP) {
937 		/* Poor 8139 */
938 		return ENXIO;
939 	}
940 
941 	for (t = re_devs; t->re_name != NULL; t++) {
942 		if (product == t->re_did && vendor == t->re_vid)
943 			break;
944 	}
945 
946 	/*
947 	 * Check if we found a RealTek device.
948 	 */
949 	if (t->re_name == NULL)
950 		return ENXIO;
951 
952 	/*
953 	 * Temporarily map the I/O space so we can read the chip ID register.
954 	 */
955 	sc = kmalloc(sizeof(*sc), M_TEMP, M_WAITOK | M_ZERO);
956 	rid = RE_PCI_LOIO;
957 	sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
958 					    RF_ACTIVE);
959 	if (sc->re_res == NULL) {
960 		device_printf(dev, "couldn't map ports/memory\n");
961 		kfree(sc, M_TEMP);
962 		return ENXIO;
963 	}
964 
965 	sc->re_btag = rman_get_bustag(sc->re_res);
966 	sc->re_bhandle = rman_get_bushandle(sc->re_res);
967 
968 	txcfg = CSR_READ_4(sc, RE_TXCFG);
969 	hwrev = txcfg & RE_TXCFG_HWREV;
970 	macmode = txcfg & RE_TXCFG_MACMODE;
971 	bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO, sc->re_res);
972 	kfree(sc, M_TEMP);
973 
974 	/*
975 	 * and continue matching for the specific chip...
976 	 */
977 	for (hw_rev = re_hwrevs; hw_rev->re_hwrev != RE_HWREV_NULL; hw_rev++) {
978 		if (hw_rev->re_hwrev == hwrev) {
979 			sc = device_get_softc(dev);
980 
981 			sc->re_hwrev = hw_rev->re_hwrev;
982 			sc->re_macver = hw_rev->re_macver;
983 			sc->re_caps = hw_rev->re_caps;
984 			sc->re_maxmtu = hw_rev->re_maxmtu;
985 
986 			/*
987 			 * Apply chip property fixup
988 			 */
989 			switch (sc->re_hwrev) {
990 			case RE_HWREV_8101E1:
991 			case RE_HWREV_8101E2:
992 				if (macmode == 0)
993 					sc->re_macver = RE_MACVER_11;
994 				else if (macmode == 0x200000)
995 					sc->re_macver = RE_MACVER_12;
996 				break;
997 			case RE_HWREV_8102E:
998 			case RE_HWREV_8102EL:
999 				if (macmode == 0)
1000 					sc->re_macver = RE_MACVER_13;
1001 				else if (macmode == 0x100000)
1002 					sc->re_macver = RE_MACVER_14;
1003 				break;
1004 			case RE_HWREV_8168B2:
1005 			case RE_HWREV_8168B3:
1006 				if (macmode == 0)
1007 					sc->re_macver = RE_MACVER_22;
1008 				break;
1009 			case RE_HWREV_8168C:
1010 				if (macmode == 0)
1011 					sc->re_macver = RE_MACVER_24;
1012 				else if (macmode == 0x200000)
1013 					sc->re_macver = RE_MACVER_25;
1014 				else if (macmode == 0x300000)
1015 					sc->re_macver = RE_MACVER_27;
1016 				break;
1017 			case RE_HWREV_8168CP:
1018 				if (macmode == 0)
1019 					sc->re_macver = RE_MACVER_26;
1020 				else if (macmode == 0x100000)
1021 					sc->re_macver = RE_MACVER_28;
1022 				break;
1023 			}
1024 			if (pci_is_pcie(dev))
1025 				sc->re_caps |= RE_C_PCIE;
1026 
1027 			device_set_desc(dev, t->re_name);
1028 			return 0;
1029 		}
1030 	}
1031 
1032 	if (bootverbose) {
1033 		device_printf(dev, "unknown hwrev 0x%08x, macmode 0x%08x\n",
1034 			      hwrev, macmode);
1035 	}
1036 	return ENXIO;
1037 }
1038 
1039 static void
1040 re_dma_map_desc(void *xarg, bus_dma_segment_t *segs, int nsegs,
1041 		bus_size_t mapsize, int error)
1042 {
1043 	struct re_dmaload_arg *arg = xarg;
1044 	int i;
1045 
1046 	if (error)
1047 		return;
1048 
1049 	if (nsegs > arg->re_nsegs) {
1050 		arg->re_nsegs = 0;
1051 		return;
1052 	}
1053 
1054 	arg->re_nsegs = nsegs;
1055 	for (i = 0; i < nsegs; ++i)
1056 		arg->re_segs[i] = segs[i];
1057 }
1058 
1059 /*
1060  * Map a single buffer address.
1061  */
1062 
1063 static void
1064 re_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1065 {
1066 	uint32_t *addr;
1067 
1068 	if (error)
1069 		return;
1070 
1071 	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
1072 	addr = arg;
1073 	*addr = segs->ds_addr;
1074 }
1075 
1076 static int
1077 re_allocmem(device_t dev)
1078 {
1079 	struct re_softc *sc = device_get_softc(dev);
1080 	int error, i;
1081 
1082 	/*
1083 	 * Allocate list data
1084 	 */
1085 	sc->re_ldata.re_tx_mbuf =
1086 	kmalloc(sc->re_tx_desc_cnt * sizeof(struct mbuf *),
1087 		M_DEVBUF, M_ZERO | M_WAITOK);
1088 
1089 	sc->re_ldata.re_rx_mbuf =
1090 	kmalloc(sc->re_rx_desc_cnt * sizeof(struct mbuf *),
1091 		M_DEVBUF, M_ZERO | M_WAITOK);
1092 
1093 	sc->re_ldata.re_rx_paddr =
1094 	kmalloc(sc->re_rx_desc_cnt * sizeof(bus_addr_t),
1095 		M_DEVBUF, M_ZERO | M_WAITOK);
1096 
1097 	sc->re_ldata.re_tx_dmamap =
1098 	kmalloc(sc->re_tx_desc_cnt * sizeof(bus_dmamap_t),
1099 		M_DEVBUF, M_ZERO | M_WAITOK);
1100 
1101 	sc->re_ldata.re_rx_dmamap =
1102 	kmalloc(sc->re_rx_desc_cnt * sizeof(bus_dmamap_t),
1103 		M_DEVBUF, M_ZERO | M_WAITOK);
1104 
1105 	/*
1106 	 * Allocate the parent bus DMA tag appropriate for PCI.
1107 	 */
1108 	error = bus_dma_tag_create(NULL,	/* parent */
1109 			1, 0,			/* alignment, boundary */
1110 			BUS_SPACE_MAXADDR,	/* lowaddr */
1111 			BUS_SPACE_MAXADDR,	/* highaddr */
1112 			NULL, NULL,		/* filter, filterarg */
1113 			BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1114 			0,			/* nsegments */
1115 			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1116 			0,			/* flags */
1117 			&sc->re_parent_tag);
1118 	if (error) {
1119 		device_printf(dev, "could not allocate parent dma tag\n");
1120 		return error;
1121 	}
1122 
1123 	/* Allocate tag for TX descriptor list. */
1124 	error = bus_dma_tag_create(sc->re_parent_tag,
1125 			RE_RING_ALIGN, 0,
1126 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1127 			NULL, NULL,
1128 			RE_TX_LIST_SZ(sc), 1, RE_TX_LIST_SZ(sc),
1129 			0, &sc->re_ldata.re_tx_list_tag);
1130 	if (error) {
1131 		device_printf(dev, "could not allocate TX ring dma tag\n");
1132 		return(error);
1133 	}
1134 
1135 	/* Allocate DMA'able memory for the TX ring */
1136         error = bus_dmamem_alloc(sc->re_ldata.re_tx_list_tag,
1137 			(void **)&sc->re_ldata.re_tx_list,
1138 			BUS_DMA_WAITOK | BUS_DMA_ZERO,
1139 			&sc->re_ldata.re_tx_list_map);
1140         if (error) {
1141 		device_printf(dev, "could not allocate TX ring\n");
1142 		bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1143 		sc->re_ldata.re_tx_list_tag = NULL;
1144                 return(error);
1145 	}
1146 
1147 	/* Load the map for the TX ring. */
1148 	error = bus_dmamap_load(sc->re_ldata.re_tx_list_tag,
1149 			sc->re_ldata.re_tx_list_map,
1150 			sc->re_ldata.re_tx_list, RE_TX_LIST_SZ(sc),
1151 			re_dma_map_addr, &sc->re_ldata.re_tx_list_addr,
1152 			BUS_DMA_NOWAIT);
1153 	if (error) {
1154 		device_printf(dev, "could not get address of TX ring\n");
1155 		bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1156 				sc->re_ldata.re_tx_list,
1157 				sc->re_ldata.re_tx_list_map);
1158 		bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1159 		sc->re_ldata.re_tx_list_tag = NULL;
1160 		return(error);
1161 	}
1162 
1163 	/* Allocate tag for RX descriptor list. */
1164 	error = bus_dma_tag_create(sc->re_parent_tag,
1165 			RE_RING_ALIGN, 0,
1166 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1167 			NULL, NULL,
1168 			RE_RX_LIST_SZ(sc), 1, RE_RX_LIST_SZ(sc),
1169 			0, &sc->re_ldata.re_rx_list_tag);
1170 	if (error) {
1171 		device_printf(dev, "could not allocate RX ring dma tag\n");
1172 		return(error);
1173 	}
1174 
1175 	/* Allocate DMA'able memory for the RX ring */
1176         error = bus_dmamem_alloc(sc->re_ldata.re_rx_list_tag,
1177 			(void **)&sc->re_ldata.re_rx_list,
1178 			BUS_DMA_WAITOK | BUS_DMA_ZERO,
1179 			&sc->re_ldata.re_rx_list_map);
1180         if (error) {
1181 		device_printf(dev, "could not allocate RX ring\n");
1182 		bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1183 		sc->re_ldata.re_rx_list_tag = NULL;
1184                 return(error);
1185 	}
1186 
1187 	/* Load the map for the RX ring. */
1188 	error = bus_dmamap_load(sc->re_ldata.re_rx_list_tag,
1189 			sc->re_ldata.re_rx_list_map,
1190 			sc->re_ldata.re_rx_list, RE_RX_LIST_SZ(sc),
1191 			re_dma_map_addr, &sc->re_ldata.re_rx_list_addr,
1192 			BUS_DMA_NOWAIT);
1193 	if (error) {
1194 		device_printf(dev, "could not get address of RX ring\n");
1195 		bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1196 				sc->re_ldata.re_rx_list,
1197 				sc->re_ldata.re_rx_list_map);
1198 		bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1199 		sc->re_ldata.re_rx_list_tag = NULL;
1200 		return(error);
1201 	}
1202 
1203 	/* Allocate maps for TX mbufs. */
1204 	error = bus_dma_tag_create(sc->re_parent_tag,
1205 			1, 0,
1206 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1207 			NULL, NULL,
1208 			RE_FRAMELEN_MAX, RE_MAXSEGS, MCLBYTES,
1209 			BUS_DMA_ALLOCNOW | BUS_DMA_WAITOK | BUS_DMA_ONEPAGE,
1210 			&sc->re_ldata.re_tx_mtag);
1211 	if (error) {
1212 		device_printf(dev, "could not allocate TX buf dma tag\n");
1213 		return(error);
1214 	}
1215 
1216 	/* Create DMA maps for TX buffers */
1217 	for (i = 0; i < sc->re_tx_desc_cnt; i++) {
1218 		error = bus_dmamap_create(sc->re_ldata.re_tx_mtag,
1219 				BUS_DMA_WAITOK | BUS_DMA_ONEPAGE,
1220 				&sc->re_ldata.re_tx_dmamap[i]);
1221 		if (error) {
1222 			device_printf(dev, "can't create DMA map for TX buf\n");
1223 			re_freebufmem(sc, i, 0);
1224 			return(error);
1225 		}
1226 	}
1227 
1228 	/* Allocate maps for RX mbufs. */
1229 	error = bus_dma_tag_create(sc->re_parent_tag,
1230 			RE_RXBUF_ALIGN, 0,
1231 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1232 			NULL, NULL,
1233 			MCLBYTES, 1, MCLBYTES,
1234 			BUS_DMA_ALLOCNOW | BUS_DMA_WAITOK,
1235 			&sc->re_ldata.re_rx_mtag);
1236 	if (error) {
1237 		device_printf(dev, "could not allocate RX buf dma tag\n");
1238 		return(error);
1239 	}
1240 
1241 	/* Create spare DMA map for RX */
1242 	error = bus_dmamap_create(sc->re_ldata.re_rx_mtag, 0,
1243 			&sc->re_ldata.re_rx_spare);
1244 	if (error) {
1245 		device_printf(dev, "can't create spare DMA map for RX\n");
1246 		bus_dma_tag_destroy(sc->re_ldata.re_rx_mtag);
1247 		sc->re_ldata.re_rx_mtag = NULL;
1248 		return error;
1249 	}
1250 
1251 	/* Create DMA maps for RX buffers */
1252 	for (i = 0; i < sc->re_rx_desc_cnt; i++) {
1253 		error = bus_dmamap_create(sc->re_ldata.re_rx_mtag,
1254 				BUS_DMA_WAITOK, &sc->re_ldata.re_rx_dmamap[i]);
1255 		if (error) {
1256 			device_printf(dev, "can't create DMA map for RX buf\n");
1257 			re_freebufmem(sc, sc->re_tx_desc_cnt, i);
1258 			return(error);
1259 		}
1260 	}
1261 
1262 	/* Create jumbo buffer pool for RX if required */
1263 	if (sc->re_caps & RE_C_CONTIGRX) {
1264 		error = re_jpool_alloc(sc);
1265 		if (error) {
1266 			re_jpool_free(sc);
1267 			/* Disable jumbo frame support */
1268 			sc->re_maxmtu = ETHERMTU;
1269 		}
1270 	}
1271 	return(0);
1272 }
1273 
1274 static void
1275 re_freebufmem(struct re_softc *sc, int tx_cnt, int rx_cnt)
1276 {
1277 	int i;
1278 
1279 	/* Destroy all the RX and TX buffer maps */
1280 	if (sc->re_ldata.re_tx_mtag) {
1281 		for (i = 0; i < tx_cnt; i++) {
1282 			bus_dmamap_destroy(sc->re_ldata.re_tx_mtag,
1283 					   sc->re_ldata.re_tx_dmamap[i]);
1284 		}
1285 		bus_dma_tag_destroy(sc->re_ldata.re_tx_mtag);
1286 		sc->re_ldata.re_tx_mtag = NULL;
1287 	}
1288 
1289 	if (sc->re_ldata.re_rx_mtag) {
1290 		for (i = 0; i < rx_cnt; i++) {
1291 			bus_dmamap_destroy(sc->re_ldata.re_rx_mtag,
1292 					   sc->re_ldata.re_rx_dmamap[i]);
1293 		}
1294 		bus_dmamap_destroy(sc->re_ldata.re_rx_mtag,
1295 				   sc->re_ldata.re_rx_spare);
1296 		bus_dma_tag_destroy(sc->re_ldata.re_rx_mtag);
1297 		sc->re_ldata.re_rx_mtag = NULL;
1298 	}
1299 }
1300 
1301 static void
1302 re_freemem(device_t dev)
1303 {
1304 	struct re_softc *sc = device_get_softc(dev);
1305 
1306 	/* Unload and free the RX DMA ring memory and map */
1307 	if (sc->re_ldata.re_rx_list_tag) {
1308 		bus_dmamap_unload(sc->re_ldata.re_rx_list_tag,
1309 				  sc->re_ldata.re_rx_list_map);
1310 		bus_dmamem_free(sc->re_ldata.re_rx_list_tag,
1311 				sc->re_ldata.re_rx_list,
1312 				sc->re_ldata.re_rx_list_map);
1313 		bus_dma_tag_destroy(sc->re_ldata.re_rx_list_tag);
1314 	}
1315 
1316 	/* Unload and free the TX DMA ring memory and map */
1317 	if (sc->re_ldata.re_tx_list_tag) {
1318 		bus_dmamap_unload(sc->re_ldata.re_tx_list_tag,
1319 				  sc->re_ldata.re_tx_list_map);
1320 		bus_dmamem_free(sc->re_ldata.re_tx_list_tag,
1321 				sc->re_ldata.re_tx_list,
1322 				sc->re_ldata.re_tx_list_map);
1323 		bus_dma_tag_destroy(sc->re_ldata.re_tx_list_tag);
1324 	}
1325 
1326 	/* Free RX/TX buf DMA stuffs */
1327 	re_freebufmem(sc, sc->re_tx_desc_cnt, sc->re_rx_desc_cnt);
1328 
1329 	/* Unload and free the stats buffer and map */
1330 	if (sc->re_ldata.re_stag) {
1331 		bus_dmamap_unload(sc->re_ldata.re_stag,
1332 				  sc->re_ldata.re_rx_list_map);
1333 		bus_dmamem_free(sc->re_ldata.re_stag,
1334 				sc->re_ldata.re_stats,
1335 				sc->re_ldata.re_smap);
1336 		bus_dma_tag_destroy(sc->re_ldata.re_stag);
1337 	}
1338 
1339 	if (sc->re_caps & RE_C_CONTIGRX)
1340 		re_jpool_free(sc);
1341 
1342 	if (sc->re_parent_tag)
1343 		bus_dma_tag_destroy(sc->re_parent_tag);
1344 
1345 	if (sc->re_ldata.re_tx_mbuf != NULL)
1346 		kfree(sc->re_ldata.re_tx_mbuf, M_DEVBUF);
1347 	if (sc->re_ldata.re_rx_mbuf != NULL)
1348 		kfree(sc->re_ldata.re_rx_mbuf, M_DEVBUF);
1349 	if (sc->re_ldata.re_rx_paddr != NULL)
1350 		kfree(sc->re_ldata.re_rx_paddr, M_DEVBUF);
1351 	if (sc->re_ldata.re_tx_dmamap != NULL)
1352 		kfree(sc->re_ldata.re_tx_dmamap, M_DEVBUF);
1353 	if (sc->re_ldata.re_rx_dmamap != NULL)
1354 		kfree(sc->re_ldata.re_rx_dmamap, M_DEVBUF);
1355 }
1356 
1357 /*
1358  * Attach the interface. Allocate softc structures, do ifmedia
1359  * setup and ethernet/BPF attach.
1360  */
1361 static int
1362 re_attach(device_t dev)
1363 {
1364 	struct re_softc	*sc = device_get_softc(dev);
1365 	struct ifnet *ifp;
1366 	uint8_t eaddr[ETHER_ADDR_LEN];
1367 	int error = 0, rid, qlen;
1368 
1369 	callout_init(&sc->re_timer);
1370 	sc->re_dev = dev;
1371 
1372 	if (RE_IS_8139CP(sc)) {
1373 		sc->re_rx_desc_cnt = RE_RX_DESC_CNT_8139CP;
1374 		sc->re_tx_desc_cnt = RE_TX_DESC_CNT_8139CP;
1375 	} else {
1376 		sc->re_rx_desc_cnt = re_rx_desc_count;
1377 		if (sc->re_rx_desc_cnt > RE_RX_DESC_CNT_MAX)
1378 			sc->re_rx_desc_cnt = RE_RX_DESC_CNT_MAX;
1379 
1380 		sc->re_tx_desc_cnt = re_tx_desc_count;
1381 		if (sc->re_tx_desc_cnt > RE_TX_DESC_CNT_MAX)
1382 			sc->re_tx_desc_cnt = RE_TX_DESC_CNT_MAX;
1383 	}
1384 
1385 	qlen = RE_IFQ_MAXLEN;
1386 	if (sc->re_tx_desc_cnt > qlen)
1387 		qlen = sc->re_tx_desc_cnt;
1388 
1389 	sc->re_rxbuf_size = MCLBYTES;
1390 	sc->re_newbuf = re_newbuf_std;
1391 
1392 	sc->re_tx_time = 5;		/* 125us */
1393 	sc->re_rx_time = 2;		/* 50us */
1394 	if (sc->re_caps & RE_C_PCIE)
1395 		sc->re_sim_time = 75;	/* 75us */
1396 	else
1397 		sc->re_sim_time = 125;	/* 125us */
1398 	if (!RE_IS_8139CP(sc)) {
1399 		/* simulated interrupt moderation */
1400 		sc->re_imtype = RE_IMTYPE_SIM;
1401 	} else {
1402 		sc->re_imtype = RE_IMTYPE_NONE;
1403 	}
1404 	re_config_imtype(sc, sc->re_imtype);
1405 
1406 	sysctl_ctx_init(&sc->re_sysctl_ctx);
1407 	sc->re_sysctl_tree = SYSCTL_ADD_NODE(&sc->re_sysctl_ctx,
1408 					     SYSCTL_STATIC_CHILDREN(_hw),
1409 					     OID_AUTO,
1410 					     device_get_nameunit(dev),
1411 					     CTLFLAG_RD, 0, "");
1412 	if (sc->re_sysctl_tree == NULL) {
1413 		device_printf(dev, "can't add sysctl node\n");
1414 		error = ENXIO;
1415 		goto fail;
1416 	}
1417 	SYSCTL_ADD_INT(&sc->re_sysctl_ctx,
1418 		       SYSCTL_CHILDREN(sc->re_sysctl_tree), OID_AUTO,
1419 		       "rx_desc_count", CTLFLAG_RD, &sc->re_rx_desc_cnt,
1420 		       0, "RX desc count");
1421 	SYSCTL_ADD_INT(&sc->re_sysctl_ctx,
1422 		       SYSCTL_CHILDREN(sc->re_sysctl_tree), OID_AUTO,
1423 		       "tx_desc_count", CTLFLAG_RD, &sc->re_tx_desc_cnt,
1424 		       0, "TX desc count");
1425 	SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1426 			SYSCTL_CHILDREN(sc->re_sysctl_tree),
1427 			OID_AUTO, "sim_time",
1428 			CTLTYPE_INT | CTLFLAG_RW,
1429 			sc, 0, re_sysctl_simtime, "I",
1430 			"Simulated interrupt moderation time (usec).");
1431 	SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1432 			SYSCTL_CHILDREN(sc->re_sysctl_tree),
1433 			OID_AUTO, "imtype",
1434 			CTLTYPE_INT | CTLFLAG_RW,
1435 			sc, 0, re_sysctl_imtype, "I",
1436 			"Interrupt moderation type -- "
1437 			"0:disable, 1:simulated, "
1438 			"2:hardware(if supported)");
1439 	if (sc->re_caps & RE_C_HWIM) {
1440 		SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1441 				SYSCTL_CHILDREN(sc->re_sysctl_tree),
1442 				OID_AUTO, "hw_rxtime",
1443 				CTLTYPE_INT | CTLFLAG_RW,
1444 				sc, 0, re_sysctl_rxtime, "I",
1445 				"Hardware interrupt moderation time "
1446 				"(unit: 25usec).");
1447 		SYSCTL_ADD_PROC(&sc->re_sysctl_ctx,
1448 				SYSCTL_CHILDREN(sc->re_sysctl_tree),
1449 				OID_AUTO, "hw_txtime",
1450 				CTLTYPE_INT | CTLFLAG_RW,
1451 				sc, 0, re_sysctl_txtime, "I",
1452 				"Hardware interrupt moderation time "
1453 				"(unit: 25usec).");
1454 	}
1455 
1456 #ifndef BURN_BRIDGES
1457 	/*
1458 	 * Handle power management nonsense.
1459 	 */
1460 
1461 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1462 		uint32_t membase, irq;
1463 
1464 		/* Save important PCI config data. */
1465 		membase = pci_read_config(dev, RE_PCI_LOMEM, 4);
1466 		irq = pci_read_config(dev, PCIR_INTLINE, 4);
1467 
1468 		/* Reset the power state. */
1469 		device_printf(dev, "chip is in D%d power mode "
1470 		    "-- setting to D0\n", pci_get_powerstate(dev));
1471 
1472 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1473 
1474 		/* Restore PCI config data. */
1475 		pci_write_config(dev, RE_PCI_LOMEM, membase, 4);
1476 		pci_write_config(dev, PCIR_INTLINE, irq, 4);
1477 	}
1478 #endif
1479 	/*
1480 	 * Map control/status registers.
1481 	 */
1482 	pci_enable_busmaster(dev);
1483 
1484 	rid = RE_PCI_LOIO;
1485 	sc->re_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1486 					    RF_ACTIVE);
1487 
1488 	if (sc->re_res == NULL) {
1489 		device_printf(dev, "couldn't map ports\n");
1490 		error = ENXIO;
1491 		goto fail;
1492 	}
1493 
1494 	sc->re_btag = rman_get_bustag(sc->re_res);
1495 	sc->re_bhandle = rman_get_bushandle(sc->re_res);
1496 
1497 	/* Allocate interrupt */
1498 	rid = 0;
1499 	sc->re_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1500 					    RF_SHAREABLE | RF_ACTIVE);
1501 
1502 	if (sc->re_irq == NULL) {
1503 		device_printf(dev, "couldn't map interrupt\n");
1504 		error = ENXIO;
1505 		goto fail;
1506 	}
1507 
1508 	/* Reset the adapter. */
1509 	re_reset(sc, 0);
1510 
1511 	if (RE_IS_8139CP(sc)) {
1512 		sc->re_bus_speed = 33; /* XXX */
1513 	} else if (sc->re_caps & RE_C_PCIE) {
1514 		sc->re_bus_speed = 125;
1515 	} else {
1516 		uint8_t cfg2;
1517 
1518 		cfg2 = CSR_READ_1(sc, RE_CFG2);
1519 		switch (cfg2 & RE_CFG2_PCICLK_MASK) {
1520 		case RE_CFG2_PCICLK_33MHZ:
1521 			sc->re_bus_speed = 33;
1522 			break;
1523 		case RE_CFG2_PCICLK_66MHZ:
1524 			sc->re_bus_speed = 66;
1525 			break;
1526 		default:
1527 			device_printf(dev, "unknown bus speed, assume 33MHz\n");
1528 			sc->re_bus_speed = 33;
1529 			break;
1530 		}
1531 		if (cfg2 & RE_CFG2_PCI64)
1532 			sc->re_caps |= RE_C_PCI64;
1533 	}
1534 	device_printf(dev, "Hardware rev. 0x%08x; MAC ver. 0x%02x; "
1535 		      "PCI%s %dMHz\n",
1536 		      sc->re_hwrev, sc->re_macver,
1537 		      (sc->re_caps & RE_C_PCIE) ?
1538 		      "-E" : ((sc->re_caps & RE_C_PCI64) ? "64" : "32"),
1539 		      sc->re_bus_speed);
1540 
1541 	/*
1542 	 * NOTE:
1543 	 * DO NOT try to adjust config1 and config5 which was spotted in
1544 	 * Realtek's Linux drivers.  It will _permanently_ damage certain
1545 	 * cards EEPROM, e.g. one of my 8168B (0x38000000) card ...
1546 	 */
1547 
1548 	re_get_eaddr(sc, eaddr);
1549 
1550 	if (!RE_IS_8139CP(sc)) {
1551 		/* Set RX length mask */
1552 		sc->re_rxlenmask = RE_RDESC_STAT_GFRAGLEN;
1553 		sc->re_txstart = RE_GTXSTART;
1554 	} else {
1555 		/* Set RX length mask */
1556 		sc->re_rxlenmask = RE_RDESC_STAT_FRAGLEN;
1557 		sc->re_txstart = RE_TXSTART;
1558 	}
1559 
1560 	/* Allocate DMA stuffs */
1561 	error = re_allocmem(dev);
1562 	if (error)
1563 		goto fail;
1564 
1565 	/*
1566 	 * Apply some magic PCI settings from Realtek ...
1567 	 */
1568 	if (RE_IS_8169(sc)) {
1569 		CSR_WRITE_1(sc, 0x82, 1);
1570 		pci_write_config(dev, PCIR_CACHELNSZ, 0x8, 1);
1571 	}
1572 	pci_write_config(dev, PCIR_LATTIMER, 0x40, 1);
1573 
1574 	if (sc->re_caps & RE_C_MAC2) {
1575 		/*
1576 		 * Following part is extracted from Realtek BSD driver v176.
1577 		 * However, this does _not_ make much/any sense:
1578 		 * 8168C's PCI Express device control is located at 0x78,
1579 		 * so the reading from 0x79 (higher part of 0x78) and setting
1580 		 * the 4~6bits intend to enlarge the "max read request size"
1581 		 * (we will do it).  The content of the rest part of this
1582 		 * register is not meaningful to other PCI registers, so
1583 		 * writing the value to 0x54 could be completely wrong.
1584 		 * 0x80 is the lower part of PCI Express device status, non-
1585 		 * reserved bits are RW1C, writing 0 to them will not have
1586 		 * any effect at all.
1587 		 */
1588 #ifdef foo
1589 		uint8_t val;
1590 
1591 		val = pci_read_config(dev, 0x79, 1);
1592 		val = (val & ~0x70) | 0x50;
1593 		pci_write_config(dev, 0x54, val, 1);
1594 		pci_write_config(dev, 0x80, 0, 1);
1595 #endif
1596 	}
1597 
1598 	/*
1599 	 * Apply some PHY fixup from Realtek ...
1600 	 */
1601 	if (sc->re_hwrev == RE_HWREV_8110S) {
1602 		CSR_WRITE_1(sc, 0x82, 1);
1603 		re_miibus_writereg(dev, 1, 0xb, 0);
1604 	}
1605 	if (sc->re_caps & RE_C_PHYPMGT) {
1606 		/* Power up PHY */
1607 		re_miibus_writereg(dev, 1, 0x1f, 0);
1608 		re_miibus_writereg(dev, 1, 0xe, 0);
1609 	}
1610 
1611 	/* Do MII setup */
1612 	if (mii_phy_probe(dev, &sc->re_miibus,
1613 	    re_ifmedia_upd, re_ifmedia_sts)) {
1614 		device_printf(dev, "MII without any phy!\n");
1615 		error = ENXIO;
1616 		goto fail;
1617 	}
1618 
1619 	ifp = &sc->arpcom.ac_if;
1620 	ifp->if_softc = sc;
1621 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1622 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1623 	ifp->if_ioctl = re_ioctl;
1624 	ifp->if_start = re_start;
1625 #ifdef DEVICE_POLLING
1626 	ifp->if_poll = re_poll;
1627 #endif
1628 	ifp->if_watchdog = re_watchdog;
1629 	ifp->if_init = re_init;
1630 	if (!RE_IS_8139CP(sc)) /* XXX */
1631 		ifp->if_baudrate = 1000000000;
1632 	else
1633 		ifp->if_baudrate = 100000000;
1634 	ifq_set_maxlen(&ifp->if_snd, qlen);
1635 	ifq_set_ready(&ifp->if_snd);
1636 
1637 	ifp->if_capabilities = IFCAP_VLAN_MTU | IFCAP_VLAN_HWTAGGING;
1638 	if (sc->re_caps & RE_C_HWCSUM)
1639 		ifp->if_capabilities |= IFCAP_HWCSUM;
1640 
1641 	ifp->if_capenable = ifp->if_capabilities;
1642 	if (ifp->if_capabilities & IFCAP_HWCSUM)
1643 		ifp->if_hwassist = RE_CSUM_FEATURES;
1644 	else
1645 		ifp->if_hwassist = 0;
1646 
1647 	/*
1648 	 * Call MI attach routine.
1649 	 */
1650 	ether_ifattach(ifp, eaddr, NULL);
1651 
1652 #ifdef RE_DIAG
1653 	/*
1654 	 * Perform hardware diagnostic on the original RTL8169.
1655 	 * Some 32-bit cards were incorrectly wired and would
1656 	 * malfunction if plugged into a 64-bit slot.
1657 	 */
1658 	if (sc->re_hwrev == RE_HWREV_8169) {
1659 		lwkt_serialize_enter(ifp->if_serializer);
1660 		error = re_diag(sc);
1661 		lwkt_serialize_exit(ifp->if_serializer);
1662 
1663 		if (error) {
1664 			device_printf(dev, "hardware diagnostic failure\n");
1665 			ether_ifdetach(ifp);
1666 			goto fail;
1667 		}
1668 	}
1669 #endif	/* RE_DIAG */
1670 
1671 	/* Hook interrupt last to avoid having to lock softc */
1672 	error = bus_setup_intr(dev, sc->re_irq, INTR_MPSAFE, re_intr, sc,
1673 			       &sc->re_intrhand, ifp->if_serializer);
1674 
1675 	if (error) {
1676 		device_printf(dev, "couldn't set up irq\n");
1677 		ether_ifdetach(ifp);
1678 		goto fail;
1679 	}
1680 
1681 	ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->re_irq));
1682 	KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
1683 
1684 fail:
1685 	if (error)
1686 		re_detach(dev);
1687 
1688 	return (error);
1689 }
1690 
1691 /*
1692  * Shutdown hardware and free up resources. This can be called any
1693  * time after the mutex has been initialized. It is called in both
1694  * the error case in attach and the normal detach case so it needs
1695  * to be careful about only freeing resources that have actually been
1696  * allocated.
1697  */
1698 static int
1699 re_detach(device_t dev)
1700 {
1701 	struct re_softc *sc = device_get_softc(dev);
1702 	struct ifnet *ifp = &sc->arpcom.ac_if;
1703 
1704 	/* These should only be active if attach succeeded */
1705 	if (device_is_attached(dev)) {
1706 		lwkt_serialize_enter(ifp->if_serializer);
1707 		re_stop(sc);
1708 		bus_teardown_intr(dev, sc->re_irq, sc->re_intrhand);
1709 		lwkt_serialize_exit(ifp->if_serializer);
1710 
1711 		ether_ifdetach(ifp);
1712 	}
1713 	if (sc->re_miibus)
1714 		device_delete_child(dev, sc->re_miibus);
1715 	bus_generic_detach(dev);
1716 
1717 	if (sc->re_sysctl_tree != NULL)
1718 		sysctl_ctx_free(&sc->re_sysctl_ctx);
1719 
1720 	if (sc->re_irq)
1721 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->re_irq);
1722 	if (sc->re_res) {
1723 		bus_release_resource(dev, SYS_RES_IOPORT, RE_PCI_LOIO,
1724 				     sc->re_res);
1725 	}
1726 
1727 	/* Free DMA stuffs */
1728 	re_freemem(dev);
1729 
1730 	return(0);
1731 }
1732 
1733 static void
1734 re_setup_rxdesc(struct re_softc *sc, int idx)
1735 {
1736 	bus_addr_t paddr;
1737 	uint32_t cmdstat;
1738 	struct re_desc *d;
1739 
1740 	paddr = sc->re_ldata.re_rx_paddr[idx];
1741 	d = &sc->re_ldata.re_rx_list[idx];
1742 
1743 	d->re_bufaddr_lo = htole32(RE_ADDR_LO(paddr));
1744 	d->re_bufaddr_hi = htole32(RE_ADDR_HI(paddr));
1745 
1746 	cmdstat = sc->re_rxbuf_size | RE_RDESC_CMD_OWN;
1747 	if (idx == (sc->re_rx_desc_cnt - 1))
1748 		cmdstat |= RE_RDESC_CMD_EOR;
1749 	d->re_cmdstat = htole32(cmdstat);
1750 }
1751 
1752 static int
1753 re_newbuf_std(struct re_softc *sc, int idx, int init)
1754 {
1755 	struct re_dmaload_arg arg;
1756 	bus_dma_segment_t seg;
1757 	bus_dmamap_t map;
1758 	struct mbuf *m;
1759 	int error;
1760 
1761 	m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
1762 	if (m == NULL) {
1763 		error = ENOBUFS;
1764 
1765 		if (init) {
1766 			if_printf(&sc->arpcom.ac_if, "m_getcl failed\n");
1767 			return error;
1768 		} else {
1769 			goto back;
1770 		}
1771 	}
1772 	m->m_len = m->m_pkthdr.len = MCLBYTES;
1773 
1774 	/*
1775 	 * NOTE:
1776 	 * re(4) chips need address of the receive buffer to be 8-byte
1777 	 * aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1778 	 */
1779 
1780 	arg.re_nsegs = 1;
1781 	arg.re_segs = &seg;
1782 	error = bus_dmamap_load_mbuf(sc->re_ldata.re_rx_mtag,
1783 				     sc->re_ldata.re_rx_spare, m,
1784 				     re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
1785 	if (error || arg.re_nsegs == 0) {
1786 		if (!error) {
1787 			if_printf(&sc->arpcom.ac_if, "too many segments?!\n");
1788 			bus_dmamap_unload(sc->re_ldata.re_rx_mtag,
1789 					  sc->re_ldata.re_rx_spare);
1790 			error = EFBIG;
1791 		}
1792 		m_freem(m);
1793 
1794 		if (init) {
1795 			if_printf(&sc->arpcom.ac_if, "can't load RX mbuf\n");
1796 			return error;
1797 		} else {
1798 			goto back;
1799 		}
1800 	}
1801 
1802 	if (!init) {
1803 		bus_dmamap_sync(sc->re_ldata.re_rx_mtag,
1804 				sc->re_ldata.re_rx_dmamap[idx],
1805 				BUS_DMASYNC_POSTREAD);
1806 		bus_dmamap_unload(sc->re_ldata.re_rx_mtag,
1807 				  sc->re_ldata.re_rx_dmamap[idx]);
1808 	}
1809 	sc->re_ldata.re_rx_mbuf[idx] = m;
1810 	sc->re_ldata.re_rx_paddr[idx] = seg.ds_addr;
1811 
1812 	map = sc->re_ldata.re_rx_dmamap[idx];
1813 	sc->re_ldata.re_rx_dmamap[idx] = sc->re_ldata.re_rx_spare;
1814 	sc->re_ldata.re_rx_spare = map;
1815 back:
1816 	re_setup_rxdesc(sc, idx);
1817 	return error;
1818 }
1819 
1820 static int
1821 re_newbuf_jumbo(struct re_softc *sc, int idx, int init)
1822 {
1823 	struct mbuf *m;
1824 	struct re_jbuf *jbuf;
1825 	int error = 0;
1826 
1827 	MGETHDR(m, init ? MB_WAIT : MB_DONTWAIT, MT_DATA);
1828 	if (m == NULL) {
1829 		error = ENOBUFS;
1830 		if (init) {
1831 			if_printf(&sc->arpcom.ac_if, "MGETHDR failed\n");
1832 			return error;
1833 		} else {
1834 			goto back;
1835 		}
1836 	}
1837 
1838 	jbuf = re_jbuf_alloc(sc);
1839 	if (jbuf == NULL) {
1840 		m_freem(m);
1841 
1842 		error = ENOBUFS;
1843 		if (init) {
1844 			if_printf(&sc->arpcom.ac_if, "jpool is empty\n");
1845 			return error;
1846 		} else {
1847 			goto back;
1848 		}
1849 	}
1850 
1851 	m->m_ext.ext_arg = jbuf;
1852 	m->m_ext.ext_buf = jbuf->re_buf;
1853 	m->m_ext.ext_free = re_jbuf_free;
1854 	m->m_ext.ext_ref = re_jbuf_ref;
1855 	m->m_ext.ext_size = sc->re_rxbuf_size;
1856 
1857 	m->m_data = m->m_ext.ext_buf;
1858 	m->m_flags |= M_EXT;
1859 	m->m_len = m->m_pkthdr.len = m->m_ext.ext_size;
1860 
1861 	/*
1862 	 * NOTE:
1863 	 * Some re(4) chips(e.g. RTL8101E) need address of the receive buffer
1864 	 * to be 8-byte aligned, so don't call m_adj(m, ETHER_ALIGN) here.
1865 	 */
1866 
1867 	sc->re_ldata.re_rx_mbuf[idx] = m;
1868 	sc->re_ldata.re_rx_paddr[idx] = jbuf->re_paddr;
1869 back:
1870 	re_setup_rxdesc(sc, idx);
1871 	return error;
1872 }
1873 
1874 static int
1875 re_tx_list_init(struct re_softc *sc)
1876 {
1877 	bzero(sc->re_ldata.re_tx_list, RE_TX_LIST_SZ(sc));
1878 
1879 	/* Flush the TX descriptors */
1880 	bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
1881 			sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
1882 
1883 	sc->re_ldata.re_tx_prodidx = 0;
1884 	sc->re_ldata.re_tx_considx = 0;
1885 	sc->re_ldata.re_tx_free = sc->re_tx_desc_cnt;
1886 
1887 	return(0);
1888 }
1889 
1890 static int
1891 re_rx_list_init(struct re_softc *sc)
1892 {
1893 	int i, error;
1894 
1895 	bzero(sc->re_ldata.re_rx_list, RE_RX_LIST_SZ(sc));
1896 
1897 	for (i = 0; i < sc->re_rx_desc_cnt; i++) {
1898 		error = sc->re_newbuf(sc, i, 1);
1899 		if (error)
1900 			return(error);
1901 	}
1902 
1903 	/* Flush the RX descriptors */
1904 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1905 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
1906 
1907 	sc->re_ldata.re_rx_prodidx = 0;
1908 	sc->re_head = sc->re_tail = NULL;
1909 
1910 	return(0);
1911 }
1912 
1913 #define RE_IP4_PACKET	0x1
1914 #define RE_TCP_PACKET	0x2
1915 #define RE_UDP_PACKET	0x4
1916 
1917 static __inline uint8_t
1918 re_packet_type(struct re_softc *sc, uint32_t rxstat, uint32_t rxctrl)
1919 {
1920 	uint8_t packet_type = 0;
1921 
1922 	if (sc->re_caps & RE_C_MAC2) {
1923 		if (rxctrl & RE_RDESC_CTL_PROTOIP4)
1924 			packet_type |= RE_IP4_PACKET;
1925 	} else {
1926 		if (rxstat & RE_RDESC_STAT_PROTOID)
1927 			packet_type |= RE_IP4_PACKET;
1928 	}
1929 	if (RE_TCPPKT(rxstat))
1930 		packet_type |= RE_TCP_PACKET;
1931 	else if (RE_UDPPKT(rxstat))
1932 		packet_type |= RE_UDP_PACKET;
1933 	return packet_type;
1934 }
1935 
1936 /*
1937  * RX handler for C+ and 8169. For the gigE chips, we support
1938  * the reception of jumbo frames that have been fragmented
1939  * across multiple 2K mbuf cluster buffers.
1940  */
1941 static int
1942 re_rxeof(struct re_softc *sc)
1943 {
1944 	struct ifnet *ifp = &sc->arpcom.ac_if;
1945 	struct mbuf *m;
1946 	struct re_desc 	*cur_rx;
1947 	uint32_t rxstat, rxctrl;
1948 	int i, total_len, rx = 0;
1949 	struct mbuf_chain chain[MAXCPU];
1950 
1951 	/* Invalidate the descriptor memory */
1952 
1953 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
1954 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_POSTREAD);
1955 
1956 	ether_input_chain_init(chain);
1957 
1958 	for (i = sc->re_ldata.re_rx_prodidx;
1959 	     RE_OWN(&sc->re_ldata.re_rx_list[i]) == 0; RE_RXDESC_INC(sc, i)) {
1960 		cur_rx = &sc->re_ldata.re_rx_list[i];
1961 		m = sc->re_ldata.re_rx_mbuf[i];
1962 		total_len = RE_RXBYTES(cur_rx);
1963 		rxstat = le32toh(cur_rx->re_cmdstat);
1964 		rxctrl = le32toh(cur_rx->re_control);
1965 
1966 		rx = 1;
1967 
1968 #ifdef INVARIANTS
1969 		if (sc->re_flags & RE_F_USE_JPOOL)
1970 			KKASSERT(rxstat & RE_RDESC_STAT_EOF);
1971 #endif
1972 
1973 		if ((rxstat & RE_RDESC_STAT_EOF) == 0) {
1974 			if (sc->re_flags & RE_F_DROP_RXFRAG) {
1975 				re_setup_rxdesc(sc, i);
1976 				continue;
1977 			}
1978 
1979 			if (sc->re_newbuf(sc, i, 0)) {
1980 				/* Drop upcoming fragments */
1981 				sc->re_flags |= RE_F_DROP_RXFRAG;
1982 				continue;
1983 			}
1984 
1985 			m->m_len = MCLBYTES;
1986 			if (sc->re_head == NULL) {
1987 				sc->re_head = sc->re_tail = m;
1988 			} else {
1989 				sc->re_tail->m_next = m;
1990 				sc->re_tail = m;
1991 			}
1992 			continue;
1993 		} else if (sc->re_flags & RE_F_DROP_RXFRAG) {
1994 			/*
1995 			 * Last fragment of a multi-fragment packet.
1996 			 *
1997 			 * Since error already happened, this fragment
1998 			 * must be dropped as well as the fragment chain.
1999 			 */
2000 			re_setup_rxdesc(sc, i);
2001 			re_free_rxchain(sc);
2002 			sc->re_flags &= ~RE_F_DROP_RXFRAG;
2003 			continue;
2004 		}
2005 
2006 		/*
2007 		 * NOTE: for the 8139C+, the frame length field
2008 		 * is always 12 bits in size, but for the gigE chips,
2009 		 * it is 13 bits (since the max RX frame length is 16K).
2010 		 * Unfortunately, all 32 bits in the status word
2011 		 * were already used, so to make room for the extra
2012 		 * length bit, RealTek took out the 'frame alignment
2013 		 * error' bit and shifted the other status bits
2014 		 * over one slot. The OWN, EOR, FS and LS bits are
2015 		 * still in the same places. We have already extracted
2016 		 * the frame length and checked the OWN bit, so rather
2017 		 * than using an alternate bit mapping, we shift the
2018 		 * status bits one space to the right so we can evaluate
2019 		 * them using the 8169 status as though it was in the
2020 		 * same format as that of the 8139C+.
2021 		 */
2022 		if (!RE_IS_8139CP(sc))
2023 			rxstat >>= 1;
2024 
2025 		if (rxstat & RE_RDESC_STAT_RXERRSUM) {
2026 			ifp->if_ierrors++;
2027 			/*
2028 			 * If this is part of a multi-fragment packet,
2029 			 * discard all the pieces.
2030 			 */
2031 			re_free_rxchain(sc);
2032 			re_setup_rxdesc(sc, i);
2033 			continue;
2034 		}
2035 
2036 		/*
2037 		 * If allocating a replacement mbuf fails,
2038 		 * reload the current one.
2039 		 */
2040 
2041 		if (sc->re_newbuf(sc, i, 0)) {
2042 			ifp->if_ierrors++;
2043 			continue;
2044 		}
2045 
2046 		if (sc->re_head != NULL) {
2047 			m->m_len = total_len % MCLBYTES;
2048 			/*
2049 			 * Special case: if there's 4 bytes or less
2050 			 * in this buffer, the mbuf can be discarded:
2051 			 * the last 4 bytes is the CRC, which we don't
2052 			 * care about anyway.
2053 			 */
2054 			if (m->m_len <= ETHER_CRC_LEN) {
2055 				sc->re_tail->m_len -=
2056 				    (ETHER_CRC_LEN - m->m_len);
2057 				m_freem(m);
2058 			} else {
2059 				m->m_len -= ETHER_CRC_LEN;
2060 				sc->re_tail->m_next = m;
2061 			}
2062 			m = sc->re_head;
2063 			sc->re_head = sc->re_tail = NULL;
2064 			m->m_pkthdr.len = total_len - ETHER_CRC_LEN;
2065 		} else {
2066 			m->m_pkthdr.len = m->m_len =
2067 			    (total_len - ETHER_CRC_LEN);
2068 		}
2069 
2070 		ifp->if_ipackets++;
2071 		m->m_pkthdr.rcvif = ifp;
2072 
2073 		/* Do RX checksumming if enabled */
2074 
2075 		if (ifp->if_capenable & IFCAP_RXCSUM) {
2076 			uint8_t packet_type;
2077 
2078 			packet_type = re_packet_type(sc, rxstat, rxctrl);
2079 
2080 			/* Check IP header checksum */
2081 			if (packet_type & RE_IP4_PACKET) {
2082 				m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
2083 				if ((rxstat & RE_RDESC_STAT_IPSUMBAD) == 0)
2084 					m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
2085 			}
2086 
2087 			/* Check TCP/UDP checksum */
2088 			if (((packet_type & RE_TCP_PACKET) &&
2089 			     (rxstat & RE_RDESC_STAT_TCPSUMBAD) == 0) ||
2090 			    ((packet_type & RE_UDP_PACKET) &&
2091 			     (rxstat & RE_RDESC_STAT_UDPSUMBAD) == 0)) {
2092 				m->m_pkthdr.csum_flags |=
2093 				    CSUM_DATA_VALID|CSUM_PSEUDO_HDR|
2094 				    CSUM_FRAG_NOT_CHECKED;
2095 				m->m_pkthdr.csum_data = 0xffff;
2096 			}
2097 		}
2098 
2099 		if (rxctrl & RE_RDESC_CTL_HASTAG) {
2100 			m->m_flags |= M_VLANTAG;
2101 			m->m_pkthdr.ether_vlantag =
2102 				be16toh((rxctrl & RE_RDESC_CTL_TAGDATA));
2103 		}
2104 		ether_input_chain(ifp, m, chain);
2105 	}
2106 
2107 	ether_input_dispatch(chain);
2108 
2109 	/* Flush the RX DMA ring */
2110 
2111 	bus_dmamap_sync(sc->re_ldata.re_rx_list_tag,
2112 			sc->re_ldata.re_rx_list_map, BUS_DMASYNC_PREWRITE);
2113 
2114 	sc->re_ldata.re_rx_prodidx = i;
2115 
2116 	return rx;
2117 }
2118 
2119 #undef RE_IP4_PACKET
2120 #undef RE_TCP_PACKET
2121 #undef RE_UDP_PACKET
2122 
2123 static int
2124 re_tx_collect(struct re_softc *sc)
2125 {
2126 	struct ifnet *ifp = &sc->arpcom.ac_if;
2127 	uint32_t txstat;
2128 	int idx, tx = 0;
2129 
2130 	/* Invalidate the TX descriptor list */
2131 	bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2132 			sc->re_ldata.re_tx_list_map, BUS_DMASYNC_POSTREAD);
2133 
2134 	for (idx = sc->re_ldata.re_tx_considx;
2135 	     sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt;
2136 	     RE_TXDESC_INC(sc, idx)) {
2137 		txstat = le32toh(sc->re_ldata.re_tx_list[idx].re_cmdstat);
2138 		if (txstat & RE_TDESC_CMD_OWN)
2139 			break;
2140 
2141 		tx = 1;
2142 
2143 		sc->re_ldata.re_tx_list[idx].re_bufaddr_lo = 0;
2144 
2145 		/*
2146 		 * We only stash mbufs in the last descriptor
2147 		 * in a fragment chain, which also happens to
2148 		 * be the only place where the TX status bits
2149 		 * are valid.
2150 		 */
2151 		if (txstat & RE_TDESC_CMD_EOF) {
2152 			bus_dmamap_unload(sc->re_ldata.re_tx_mtag,
2153 			    sc->re_ldata.re_tx_dmamap[idx]);
2154 			m_freem(sc->re_ldata.re_tx_mbuf[idx]);
2155 			sc->re_ldata.re_tx_mbuf[idx] = NULL;
2156 			if (txstat & (RE_TDESC_STAT_EXCESSCOL|
2157 			    RE_TDESC_STAT_COLCNT))
2158 				ifp->if_collisions++;
2159 			if (txstat & RE_TDESC_STAT_TXERRSUM)
2160 				ifp->if_oerrors++;
2161 			else
2162 				ifp->if_opackets++;
2163 		}
2164 		sc->re_ldata.re_tx_free++;
2165 	}
2166 	sc->re_ldata.re_tx_considx = idx;
2167 
2168 	return tx;
2169 }
2170 
2171 static int
2172 re_txeof(struct re_softc *sc)
2173 {
2174 	struct ifnet *ifp = &sc->arpcom.ac_if;
2175 	int tx;
2176 
2177 	tx = re_tx_collect(sc);
2178 
2179 	/* There is enough free TX descs */
2180 	if (sc->re_ldata.re_tx_free > RE_TXDESC_SPARE)
2181 		ifp->if_flags &= ~IFF_OACTIVE;
2182 
2183 	/*
2184 	 * Some chips will ignore a second TX request issued while an
2185 	 * existing transmission is in progress. If the transmitter goes
2186 	 * idle but there are still packets waiting to be sent, we need
2187 	 * to restart the channel here to flush them out. This only seems
2188 	 * to be required with the PCIe devices.
2189 	 */
2190 	if (sc->re_ldata.re_tx_free < sc->re_tx_desc_cnt)
2191 		CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2192 	else
2193 		ifp->if_timer = 0;
2194 
2195 	return tx;
2196 }
2197 
2198 static void
2199 re_tick(void *xsc)
2200 {
2201 	struct re_softc *sc = xsc;
2202 
2203 	lwkt_serialize_enter(sc->arpcom.ac_if.if_serializer);
2204 	re_tick_serialized(xsc);
2205 	lwkt_serialize_exit(sc->arpcom.ac_if.if_serializer);
2206 }
2207 
2208 static void
2209 re_tick_serialized(void *xsc)
2210 {
2211 	struct re_softc *sc = xsc;
2212 	struct ifnet *ifp = &sc->arpcom.ac_if;
2213 	struct mii_data *mii;
2214 
2215 	ASSERT_SERIALIZED(ifp->if_serializer);
2216 
2217 	mii = device_get_softc(sc->re_miibus);
2218 	mii_tick(mii);
2219 	if (sc->re_flags & RE_F_LINKED) {
2220 		if (!(mii->mii_media_status & IFM_ACTIVE))
2221 			sc->re_flags &= ~RE_F_LINKED;
2222 	} else {
2223 		if (mii->mii_media_status & IFM_ACTIVE &&
2224 		    IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
2225 			sc->re_flags |= RE_F_LINKED;
2226 			if (!ifq_is_empty(&ifp->if_snd))
2227 				if_devstart(ifp);
2228 		}
2229 	}
2230 
2231 	callout_reset(&sc->re_timer, hz, re_tick, sc);
2232 }
2233 
2234 #ifdef DEVICE_POLLING
2235 
2236 static void
2237 re_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
2238 {
2239 	struct re_softc *sc = ifp->if_softc;
2240 
2241 	ASSERT_SERIALIZED(ifp->if_serializer);
2242 
2243 	switch(cmd) {
2244 	case POLL_REGISTER:
2245 		/* disable interrupts */
2246 		re_setup_intr(sc, 0, RE_IMTYPE_NONE);
2247 		break;
2248 
2249 	case POLL_DEREGISTER:
2250 		/* enable interrupts */
2251 		re_setup_intr(sc, 1, sc->re_imtype);
2252 		break;
2253 
2254 	default:
2255 		sc->rxcycles = count;
2256 		re_rxeof(sc);
2257 		re_txeof(sc);
2258 
2259 		if (!ifq_is_empty(&ifp->if_snd))
2260 			if_devstart(ifp);
2261 
2262 		if (cmd == POLL_AND_CHECK_STATUS) { /* also check status register */
2263 			uint16_t       status;
2264 
2265 			status = CSR_READ_2(sc, RE_ISR);
2266 			if (status == 0xffff)
2267 				return;
2268 			if (status)
2269 				CSR_WRITE_2(sc, RE_ISR, status);
2270 
2271 			/*
2272 			 * XXX check behaviour on receiver stalls.
2273 			 */
2274 
2275 			if (status & RE_ISR_SYSTEM_ERR)
2276 				re_init(sc);
2277 		}
2278 		break;
2279 	}
2280 }
2281 #endif /* DEVICE_POLLING */
2282 
2283 static void
2284 re_intr(void *arg)
2285 {
2286 	struct re_softc	*sc = arg;
2287 	struct ifnet *ifp = &sc->arpcom.ac_if;
2288 	uint16_t status;
2289 	int rx, tx;
2290 
2291 	ASSERT_SERIALIZED(ifp->if_serializer);
2292 
2293 	if ((sc->re_flags & RE_F_SUSPENDED) ||
2294 	    (ifp->if_flags & IFF_RUNNING) == 0)
2295 		return;
2296 
2297 	rx = tx = 0;
2298 	for (;;) {
2299 		status = CSR_READ_2(sc, RE_ISR);
2300 		/* If the card has gone away the read returns 0xffff. */
2301 		if (status == 0xffff)
2302 			break;
2303 		if (status)
2304 			CSR_WRITE_2(sc, RE_ISR, status);
2305 
2306 		if ((status & sc->re_intrs) == 0)
2307 			break;
2308 
2309 		if (status & (sc->re_rx_ack | RE_ISR_RX_ERR))
2310 			rx |= re_rxeof(sc);
2311 
2312 		if (status & (sc->re_tx_ack | RE_ISR_TX_ERR))
2313 			tx |= re_txeof(sc);
2314 
2315 		if (status & RE_ISR_SYSTEM_ERR)
2316 			re_init(sc);
2317 
2318 		if (status & RE_ISR_LINKCHG) {
2319 			callout_stop(&sc->re_timer);
2320 			re_tick_serialized(sc);
2321 		}
2322 	}
2323 
2324 	if (sc->re_imtype == RE_IMTYPE_SIM) {
2325 		if ((sc->re_flags & RE_F_TIMER_INTR)) {
2326 			if ((tx | rx) == 0) {
2327 				/*
2328 				 * Nothing needs to be processed, fallback
2329 				 * to use TX/RX interrupts.
2330 				 */
2331 				re_setup_intr(sc, 1, RE_IMTYPE_NONE);
2332 
2333 				/*
2334 				 * Recollect, mainly to avoid the possible
2335 				 * race introduced by changing interrupt
2336 				 * masks.
2337 				 */
2338 				re_rxeof(sc);
2339 				tx = re_txeof(sc);
2340 			} else {
2341 				CSR_WRITE_4(sc, RE_TIMERCNT, 1); /* reload */
2342 			}
2343 		} else if (tx | rx) {
2344 			/*
2345 			 * Assume that using simulated interrupt moderation
2346 			 * (hardware timer based) could reduce the interript
2347 			 * rate.
2348 			 */
2349 			re_setup_intr(sc, 1, RE_IMTYPE_SIM);
2350 		}
2351 	}
2352 
2353 	if (tx && !ifq_is_empty(&ifp->if_snd))
2354 		if_devstart(ifp);
2355 }
2356 
2357 static int
2358 re_encap(struct re_softc *sc, struct mbuf **m_head, int *idx0)
2359 {
2360 	struct ifnet *ifp = &sc->arpcom.ac_if;
2361 	struct mbuf *m;
2362 	struct re_dmaload_arg arg;
2363 	bus_dma_segment_t segs[RE_MAXSEGS];
2364 	bus_dmamap_t map;
2365 	int error, maxsegs, idx, i;
2366 	struct re_desc *d, *tx_ring;
2367 	uint32_t cmd_csum, ctl_csum, vlantag;
2368 
2369 	KASSERT(sc->re_ldata.re_tx_free > RE_TXDESC_SPARE,
2370 		("not enough free TX desc\n"));
2371 
2372 	m = *m_head;
2373 	map = sc->re_ldata.re_tx_dmamap[*idx0];
2374 
2375 	/*
2376 	 * Set up checksum offload. Note: checksum offload bits must
2377 	 * appear in all descriptors of a multi-descriptor transmit
2378 	 * attempt. (This is according to testing done with an 8169
2379 	 * chip. I'm not sure if this is a requirement or a bug.)
2380 	 */
2381 	cmd_csum = ctl_csum = 0;
2382 	if (m->m_pkthdr.csum_flags & CSUM_IP) {
2383 		cmd_csum |= RE_TDESC_CMD_IPCSUM;
2384 		ctl_csum |= RE_TDESC_CTL_IPCSUM;
2385 	}
2386 	if (m->m_pkthdr.csum_flags & CSUM_TCP) {
2387 		cmd_csum |= RE_TDESC_CMD_TCPCSUM;
2388 		ctl_csum |= RE_TDESC_CTL_TCPCSUM;
2389 	}
2390 	if (m->m_pkthdr.csum_flags & CSUM_UDP) {
2391 		cmd_csum |= RE_TDESC_CMD_UDPCSUM;
2392 		ctl_csum |= RE_TDESC_CTL_UDPCSUM;
2393 	}
2394 
2395 	/* For MAC2 chips, csum flags are set on re_control */
2396 	if (sc->re_caps & RE_C_MAC2)
2397 		cmd_csum = 0;
2398 	else
2399 		ctl_csum = 0;
2400 
2401 	if ((sc->re_caps & RE_C_AUTOPAD) == 0) {
2402 		/*
2403 		 * With some of the RealTek chips, using the checksum offload
2404 		 * support in conjunction with the autopadding feature results
2405 		 * in the transmission of corrupt frames. For example, if we
2406 		 * need to send a really small IP fragment that's less than 60
2407 		 * bytes in size, and IP header checksumming is enabled, the
2408 		 * resulting ethernet frame that appears on the wire will
2409 		 * have garbled payload. To work around this, if TX checksum
2410 		 * offload is enabled, we always manually pad short frames out
2411 		 * to the minimum ethernet frame size.
2412 		 *
2413 		 * Note: this appears unnecessary for TCP, and doing it for TCP
2414 		 * with PCIe adapters seems to result in bad checksums.
2415 		 */
2416 		if ((m->m_pkthdr.csum_flags &
2417 		     (CSUM_DELAY_IP | CSUM_DELAY_DATA)) &&
2418 		    (m->m_pkthdr.csum_flags & CSUM_TCP) == 0 &&
2419 		    m->m_pkthdr.len < RE_MIN_FRAMELEN) {
2420 			error = m_devpad(m, RE_MIN_FRAMELEN);
2421 			if (error)
2422 				goto back;
2423 		}
2424 	}
2425 
2426 	vlantag = 0;
2427 	if (m->m_flags & M_VLANTAG) {
2428 		vlantag = htobe16(m->m_pkthdr.ether_vlantag) |
2429 			  RE_TDESC_CTL_INSTAG;
2430 	}
2431 
2432 	maxsegs = sc->re_ldata.re_tx_free;
2433 	if (maxsegs > RE_MAXSEGS)
2434 		maxsegs = RE_MAXSEGS;
2435 
2436 	arg.re_nsegs = maxsegs;
2437 	arg.re_segs = segs;
2438 	error = bus_dmamap_load_mbuf(sc->re_ldata.re_tx_mtag, map, m,
2439 				     re_dma_map_desc, &arg, BUS_DMA_NOWAIT);
2440 	if (error && error != EFBIG) {
2441 		if_printf(ifp, "can't map mbuf (error %d)\n", error);
2442 		goto back;
2443 	}
2444 
2445 	/*
2446 	 * Too many segments to map, coalesce into a single mbuf
2447 	 */
2448 	if (!error && arg.re_nsegs == 0) {
2449 		bus_dmamap_unload(sc->re_ldata.re_tx_mtag, map);
2450 		error = EFBIG;
2451 	}
2452 	if (error) {
2453 		struct mbuf *m_new;
2454 
2455 		m_new = m_defrag(m, MB_DONTWAIT);
2456 		if (m_new == NULL) {
2457 			if_printf(ifp, "can't defrag TX mbuf\n");
2458 			error = ENOBUFS;
2459 			goto back;
2460 		} else {
2461 			*m_head = m = m_new;
2462 		}
2463 
2464 		arg.re_nsegs = maxsegs;
2465 		arg.re_segs = segs;
2466 		error = bus_dmamap_load_mbuf(sc->re_ldata.re_tx_mtag, map, m,
2467 					     re_dma_map_desc, &arg,
2468 					     BUS_DMA_NOWAIT);
2469 		if (error || arg.re_nsegs == 0) {
2470 			if (!error) {
2471 				bus_dmamap_unload(sc->re_ldata.re_tx_mtag, map);
2472 				error = EFBIG;
2473 			}
2474 			if_printf(ifp, "can't map mbuf (error %d)\n", error);
2475 			goto back;
2476 		}
2477 	}
2478 	bus_dmamap_sync(sc->re_ldata.re_tx_mtag, map, BUS_DMASYNC_PREWRITE);
2479 
2480 	/*
2481 	 * Map the segment array into descriptors.  We also keep track
2482 	 * of the end of the ring and set the end-of-ring bits as needed,
2483 	 * and we set the ownership bits in all except the very first
2484 	 * descriptor, whose ownership bits will be turned on later.
2485 	 */
2486 	tx_ring = sc->re_ldata.re_tx_list;
2487 	idx = *idx0;
2488 	i = 0;
2489 	for (;;) {
2490 		uint32_t cmdstat;
2491 
2492 		d = &tx_ring[idx];
2493 
2494 		cmdstat = segs[i].ds_len;
2495 		d->re_bufaddr_lo = htole32(RE_ADDR_LO(segs[i].ds_addr));
2496 		d->re_bufaddr_hi = htole32(RE_ADDR_HI(segs[i].ds_addr));
2497 		if (i == 0)
2498 			cmdstat |= RE_TDESC_CMD_SOF;
2499 		else
2500 			cmdstat |= RE_TDESC_CMD_OWN;
2501 		if (idx == (sc->re_tx_desc_cnt - 1))
2502 			cmdstat |= RE_TDESC_CMD_EOR;
2503 		d->re_cmdstat = htole32(cmdstat | cmd_csum);
2504 		d->re_control = htole32(ctl_csum | vlantag);
2505 
2506 		i++;
2507 		if (i == arg.re_nsegs)
2508 			break;
2509 		RE_TXDESC_INC(sc, idx);
2510 	}
2511 	d->re_cmdstat |= htole32(RE_TDESC_CMD_EOF);
2512 
2513 	/* Transfer ownership of packet to the chip. */
2514 	d->re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2515 	if (*idx0 != idx)
2516 		tx_ring[*idx0].re_cmdstat |= htole32(RE_TDESC_CMD_OWN);
2517 
2518 	/*
2519 	 * Insure that the map for this transmission
2520 	 * is placed at the array index of the last descriptor
2521 	 * in this chain.
2522 	 */
2523 	sc->re_ldata.re_tx_dmamap[*idx0] = sc->re_ldata.re_tx_dmamap[idx];
2524 	sc->re_ldata.re_tx_dmamap[idx] = map;
2525 
2526 	sc->re_ldata.re_tx_mbuf[idx] = m;
2527 	sc->re_ldata.re_tx_free -= arg.re_nsegs;
2528 
2529 	RE_TXDESC_INC(sc, idx);
2530 	*idx0 = idx;
2531 back:
2532 	if (error) {
2533 		m_freem(m);
2534 		*m_head = NULL;
2535 	}
2536 	return error;
2537 }
2538 
2539 /*
2540  * Main transmit routine for C+ and gigE NICs.
2541  */
2542 
2543 static void
2544 re_start(struct ifnet *ifp)
2545 {
2546 	struct re_softc	*sc = ifp->if_softc;
2547 	struct mbuf *m_head;
2548 	int idx, need_trans, oactive, error;
2549 
2550 	ASSERT_SERIALIZED(ifp->if_serializer);
2551 
2552 	if ((sc->re_flags & RE_F_LINKED) == 0) {
2553 		ifq_purge(&ifp->if_snd);
2554 		return;
2555 	}
2556 
2557 	if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING)
2558 		return;
2559 
2560 	idx = sc->re_ldata.re_tx_prodidx;
2561 
2562 	need_trans = 0;
2563 	oactive = 0;
2564 	while (sc->re_ldata.re_tx_mbuf[idx] == NULL) {
2565 		if (sc->re_ldata.re_tx_free <= RE_TXDESC_SPARE) {
2566 			if (!oactive) {
2567 				if (re_tx_collect(sc)) {
2568 					oactive = 1;
2569 					continue;
2570 				}
2571 			}
2572 			ifp->if_flags |= IFF_OACTIVE;
2573 			break;
2574 		}
2575 
2576 		m_head = ifq_dequeue(&ifp->if_snd, NULL);
2577 		if (m_head == NULL)
2578 			break;
2579 
2580 		error = re_encap(sc, &m_head, &idx);
2581 		if (error) {
2582 			/* m_head is freed by re_encap(), if we reach here */
2583 			ifp->if_oerrors++;
2584 
2585 			if (error == EFBIG && !oactive) {
2586 				if (re_tx_collect(sc)) {
2587 					oactive = 1;
2588 					continue;
2589 				}
2590 			}
2591 			ifp->if_flags |= IFF_OACTIVE;
2592 			break;
2593 		}
2594 
2595 		oactive = 0;
2596 		need_trans = 1;
2597 
2598 		/*
2599 		 * If there's a BPF listener, bounce a copy of this frame
2600 		 * to him.
2601 		 */
2602 		ETHER_BPF_MTAP(ifp, m_head);
2603 	}
2604 
2605 	if (!need_trans)
2606 		return;
2607 
2608 	/* Flush the TX descriptors */
2609 	bus_dmamap_sync(sc->re_ldata.re_tx_list_tag,
2610 			sc->re_ldata.re_tx_list_map, BUS_DMASYNC_PREWRITE);
2611 
2612 	sc->re_ldata.re_tx_prodidx = idx;
2613 
2614 	/*
2615 	 * RealTek put the TX poll request register in a different
2616 	 * location on the 8169 gigE chip. I don't know why.
2617 	 */
2618 	CSR_WRITE_1(sc, sc->re_txstart, RE_TXSTART_START);
2619 
2620 	/*
2621 	 * Set a timeout in case the chip goes out to lunch.
2622 	 */
2623 	ifp->if_timer = 5;
2624 }
2625 
2626 static void
2627 re_init(void *xsc)
2628 {
2629 	struct re_softc *sc = xsc;
2630 	struct ifnet *ifp = &sc->arpcom.ac_if;
2631 	struct mii_data *mii;
2632 	int error, framelen;
2633 
2634 	ASSERT_SERIALIZED(ifp->if_serializer);
2635 
2636 	mii = device_get_softc(sc->re_miibus);
2637 
2638 	/*
2639 	 * Cancel pending I/O and free all RX/TX buffers.
2640 	 */
2641 	re_stop(sc);
2642 
2643 	if (sc->re_caps & RE_C_CONTIGRX) {
2644 		if (ifp->if_mtu > ETHERMTU) {
2645 			KKASSERT(sc->re_ldata.re_jbuf != NULL);
2646 			sc->re_flags |= RE_F_USE_JPOOL;
2647 			sc->re_rxbuf_size = RE_FRAMELEN_MAX;
2648 			sc->re_newbuf = re_newbuf_jumbo;
2649 		} else {
2650 			sc->re_flags &= ~RE_F_USE_JPOOL;
2651 			sc->re_rxbuf_size = MCLBYTES;
2652 			sc->re_newbuf = re_newbuf_std;
2653 		}
2654 	}
2655 
2656 	/*
2657 	 * Adjust max read request size according to MTU; mainly to
2658 	 * improve TX performance for common case (ETHERMTU) on GigE
2659 	 * NICs.  However, this could _not_ be done on 10/100 only
2660 	 * NICs; their DMA engines will malfunction using non-default
2661 	 * max read request size.
2662 	 */
2663 	if ((sc->re_caps & (RE_C_PCIE | RE_C_FASTE)) == RE_C_PCIE) {
2664 		if (ifp->if_mtu > ETHERMTU) {
2665 			/*
2666 			 * 512 seems to be the only value that works
2667 			 * reliably with jumbo frame
2668 			 */
2669 			pcie_set_max_readrq(sc->re_dev,
2670 				PCIEM_DEVCTL_MAX_READRQ_512);
2671 		} else {
2672 			pcie_set_max_readrq(sc->re_dev,
2673 				PCIEM_DEVCTL_MAX_READRQ_4096);
2674 		}
2675 	}
2676 
2677 	/*
2678 	 * Enable C+ RX and TX mode, as well as VLAN stripping and
2679 	 * RX checksum offload. We must configure the C+ register
2680 	 * before all others.
2681 	 */
2682 	CSR_WRITE_2(sc, RE_CPLUS_CMD, RE_CPLUSCMD_RXENB | RE_CPLUSCMD_TXENB |
2683 		    RE_CPLUSCMD_PCI_MRW |
2684 		    (ifp->if_capenable & IFCAP_VLAN_HWTAGGING ?
2685 		     RE_CPLUSCMD_VLANSTRIP : 0) |
2686 		    (ifp->if_capenable & IFCAP_RXCSUM ?
2687 		     RE_CPLUSCMD_RXCSUM_ENB : 0));
2688 
2689 	/*
2690 	 * Init our MAC address.  Even though the chipset
2691 	 * documentation doesn't mention it, we need to enter "Config
2692 	 * register write enable" mode to modify the ID registers.
2693 	 */
2694 	CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_WRITECFG);
2695 	CSR_WRITE_4(sc, RE_IDR0,
2696 	    htole32(*(uint32_t *)(&sc->arpcom.ac_enaddr[0])));
2697 	CSR_WRITE_2(sc, RE_IDR4,
2698 	    htole16(*(uint16_t *)(&sc->arpcom.ac_enaddr[4])));
2699 	CSR_WRITE_1(sc, RE_EECMD, RE_EEMODE_OFF);
2700 
2701 	/*
2702 	 * For C+ mode, initialize the RX descriptors and mbufs.
2703 	 */
2704 	error = re_rx_list_init(sc);
2705 	if (error) {
2706 		re_stop(sc);
2707 		return;
2708 	}
2709 	error = re_tx_list_init(sc);
2710 	if (error) {
2711 		re_stop(sc);
2712 		return;
2713 	}
2714 
2715 	/*
2716 	 * Load the addresses of the RX and TX lists into the chip.
2717 	 */
2718 	CSR_WRITE_4(sc, RE_RXLIST_ADDR_HI,
2719 	    RE_ADDR_HI(sc->re_ldata.re_rx_list_addr));
2720 	CSR_WRITE_4(sc, RE_RXLIST_ADDR_LO,
2721 	    RE_ADDR_LO(sc->re_ldata.re_rx_list_addr));
2722 
2723 	CSR_WRITE_4(sc, RE_TXLIST_ADDR_HI,
2724 	    RE_ADDR_HI(sc->re_ldata.re_tx_list_addr));
2725 	CSR_WRITE_4(sc, RE_TXLIST_ADDR_LO,
2726 	    RE_ADDR_LO(sc->re_ldata.re_tx_list_addr));
2727 
2728 	/*
2729 	 * Enable transmit and receive.
2730 	 */
2731 	CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2732 
2733 	/*
2734 	 * Set the initial TX and RX configuration.
2735 	 */
2736 	if (sc->re_flags & RE_F_TESTMODE) {
2737 		if (!RE_IS_8139CP(sc))
2738 			CSR_WRITE_4(sc, RE_TXCFG,
2739 				    RE_TXCFG_CONFIG | RE_LOOPTEST_ON);
2740 		else
2741 			CSR_WRITE_4(sc, RE_TXCFG,
2742 				    RE_TXCFG_CONFIG | RE_LOOPTEST_ON_CPLUS);
2743 	} else
2744 		CSR_WRITE_4(sc, RE_TXCFG, RE_TXCFG_CONFIG);
2745 
2746 	framelen = RE_FRAMELEN(ifp->if_mtu);
2747 	if (framelen < MCLBYTES)
2748 		CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, howmany(MCLBYTES, 128));
2749 	else
2750 		CSR_WRITE_1(sc, RE_EARLY_TX_THRESH, howmany(framelen, 128));
2751 
2752 	CSR_WRITE_4(sc, RE_RXCFG, RE_RXCFG_CONFIG);
2753 
2754 	/*
2755 	 * Program the multicast filter, if necessary.
2756 	 */
2757 	re_setmulti(sc);
2758 
2759 #ifdef DEVICE_POLLING
2760 	/*
2761 	 * Disable interrupts if we are polling.
2762 	 */
2763 	if (ifp->if_flags & IFF_POLLING)
2764 		re_setup_intr(sc, 0, RE_IMTYPE_NONE);
2765 	else	/* otherwise ... */
2766 #endif /* DEVICE_POLLING */
2767 	/*
2768 	 * Enable interrupts.
2769 	 */
2770 	if (sc->re_flags & RE_F_TESTMODE)
2771 		CSR_WRITE_2(sc, RE_IMR, 0);
2772 	else
2773 		re_setup_intr(sc, 1, sc->re_imtype);
2774 	CSR_WRITE_2(sc, RE_ISR, sc->re_intrs);
2775 
2776 	/* Start RX/TX process. */
2777 	CSR_WRITE_4(sc, RE_MISSEDPKT, 0);
2778 
2779 #ifdef notdef
2780 	/* Enable receiver and transmitter. */
2781 	CSR_WRITE_1(sc, RE_COMMAND, RE_CMD_TX_ENB|RE_CMD_RX_ENB);
2782 #endif
2783 
2784 	/*
2785 	 * For 8169 gigE NICs, set the max allowed RX packet
2786 	 * size so we can receive jumbo frames.
2787 	 */
2788 	if (!RE_IS_8139CP(sc)) {
2789 		if (sc->re_caps & RE_C_CONTIGRX)
2790 			CSR_WRITE_2(sc, RE_MAXRXPKTLEN, sc->re_rxbuf_size);
2791 		else
2792 			CSR_WRITE_2(sc, RE_MAXRXPKTLEN, 16383);
2793 	}
2794 
2795 	if (sc->re_flags & RE_F_TESTMODE)
2796 		return;
2797 
2798 	mii_mediachg(mii);
2799 
2800 	CSR_WRITE_1(sc, RE_CFG1, RE_CFG1_DRVLOAD|RE_CFG1_FULLDUPLEX);
2801 
2802 	ifp->if_flags |= IFF_RUNNING;
2803 	ifp->if_flags &= ~IFF_OACTIVE;
2804 
2805 	callout_reset(&sc->re_timer, hz, re_tick, sc);
2806 }
2807 
2808 /*
2809  * Set media options.
2810  */
2811 static int
2812 re_ifmedia_upd(struct ifnet *ifp)
2813 {
2814 	struct re_softc *sc = ifp->if_softc;
2815 	struct mii_data *mii;
2816 
2817 	ASSERT_SERIALIZED(ifp->if_serializer);
2818 
2819 	mii = device_get_softc(sc->re_miibus);
2820 	mii_mediachg(mii);
2821 
2822 	return(0);
2823 }
2824 
2825 /*
2826  * Report current media status.
2827  */
2828 static void
2829 re_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2830 {
2831 	struct re_softc *sc = ifp->if_softc;
2832 	struct mii_data *mii;
2833 
2834 	ASSERT_SERIALIZED(ifp->if_serializer);
2835 
2836 	mii = device_get_softc(sc->re_miibus);
2837 
2838 	mii_pollstat(mii);
2839 	ifmr->ifm_active = mii->mii_media_active;
2840 	ifmr->ifm_status = mii->mii_media_status;
2841 }
2842 
2843 static int
2844 re_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2845 {
2846 	struct re_softc *sc = ifp->if_softc;
2847 	struct ifreq *ifr = (struct ifreq *) data;
2848 	struct mii_data *mii;
2849 	int error = 0, mask;
2850 
2851 	ASSERT_SERIALIZED(ifp->if_serializer);
2852 
2853 	switch(command) {
2854 	case SIOCSIFMTU:
2855 		if (ifr->ifr_mtu > sc->re_maxmtu) {
2856 			error = EINVAL;
2857 		} else if (ifp->if_mtu != ifr->ifr_mtu) {
2858 			ifp->if_mtu = ifr->ifr_mtu;
2859 			if (ifp->if_flags & IFF_RUNNING)
2860 				ifp->if_init(sc);
2861 		}
2862 		break;
2863 
2864 	case SIOCSIFFLAGS:
2865 		if (ifp->if_flags & IFF_UP) {
2866 			if (ifp->if_flags & IFF_RUNNING) {
2867 				if ((ifp->if_flags ^ sc->re_if_flags) &
2868 				    (IFF_PROMISC | IFF_ALLMULTI))
2869 					re_setmulti(sc);
2870 			} else {
2871 				re_init(sc);
2872 			}
2873 		} else if (ifp->if_flags & IFF_RUNNING) {
2874 			re_stop(sc);
2875 		}
2876 		sc->re_if_flags = ifp->if_flags;
2877 		break;
2878 
2879 	case SIOCADDMULTI:
2880 	case SIOCDELMULTI:
2881 		re_setmulti(sc);
2882 		break;
2883 
2884 	case SIOCGIFMEDIA:
2885 	case SIOCSIFMEDIA:
2886 		mii = device_get_softc(sc->re_miibus);
2887 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
2888 		break;
2889 
2890 	case SIOCSIFCAP:
2891 		mask = (ifr->ifr_reqcap ^ ifp->if_capenable) &
2892 		       ifp->if_capabilities;
2893 		ifp->if_capenable ^= mask;
2894 
2895 		if (mask & IFCAP_HWCSUM) {
2896 			if (ifp->if_capenable & IFCAP_TXCSUM)
2897 				ifp->if_hwassist = RE_CSUM_FEATURES;
2898 			else
2899 				ifp->if_hwassist = 0;
2900 		}
2901 		if (mask && (ifp->if_flags & IFF_RUNNING))
2902 			re_init(sc);
2903 		break;
2904 
2905 	default:
2906 		error = ether_ioctl(ifp, command, data);
2907 		break;
2908 	}
2909 	return(error);
2910 }
2911 
2912 static void
2913 re_watchdog(struct ifnet *ifp)
2914 {
2915 	struct re_softc *sc = ifp->if_softc;
2916 
2917 	ASSERT_SERIALIZED(ifp->if_serializer);
2918 
2919 	if_printf(ifp, "watchdog timeout\n");
2920 
2921 	ifp->if_oerrors++;
2922 
2923 	re_txeof(sc);
2924 	re_rxeof(sc);
2925 
2926 	re_init(sc);
2927 
2928 	if (!ifq_is_empty(&ifp->if_snd))
2929 		if_devstart(ifp);
2930 }
2931 
2932 /*
2933  * Stop the adapter and free any mbufs allocated to the
2934  * RX and TX lists.
2935  */
2936 static void
2937 re_stop(struct re_softc *sc)
2938 {
2939 	struct ifnet *ifp = &sc->arpcom.ac_if;
2940 	int i;
2941 
2942 	ASSERT_SERIALIZED(ifp->if_serializer);
2943 
2944 	/* Reset the adapter. */
2945 	re_reset(sc, ifp->if_flags & IFF_RUNNING);
2946 
2947 	ifp->if_timer = 0;
2948 	callout_stop(&sc->re_timer);
2949 
2950 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2951 	sc->re_flags &= ~(RE_F_TIMER_INTR | RE_F_DROP_RXFRAG | RE_F_LINKED);
2952 
2953 	CSR_WRITE_1(sc, RE_COMMAND, 0x00);
2954 	CSR_WRITE_2(sc, RE_IMR, 0x0000);
2955 	CSR_WRITE_2(sc, RE_ISR, 0xFFFF);
2956 
2957 	re_free_rxchain(sc);
2958 
2959 	/* Free the TX list buffers. */
2960 	for (i = 0; i < sc->re_tx_desc_cnt; i++) {
2961 		if (sc->re_ldata.re_tx_mbuf[i] != NULL) {
2962 			bus_dmamap_unload(sc->re_ldata.re_tx_mtag,
2963 					  sc->re_ldata.re_tx_dmamap[i]);
2964 			m_freem(sc->re_ldata.re_tx_mbuf[i]);
2965 			sc->re_ldata.re_tx_mbuf[i] = NULL;
2966 		}
2967 	}
2968 
2969 	/* Free the RX list buffers. */
2970 	for (i = 0; i < sc->re_rx_desc_cnt; i++) {
2971 		if (sc->re_ldata.re_rx_mbuf[i] != NULL) {
2972 			if ((sc->re_flags & RE_F_USE_JPOOL) == 0) {
2973 				bus_dmamap_unload(sc->re_ldata.re_rx_mtag,
2974 						  sc->re_ldata.re_rx_dmamap[i]);
2975 			}
2976 			m_freem(sc->re_ldata.re_rx_mbuf[i]);
2977 			sc->re_ldata.re_rx_mbuf[i] = NULL;
2978 		}
2979 	}
2980 }
2981 
2982 /*
2983  * Device suspend routine.  Stop the interface and save some PCI
2984  * settings in case the BIOS doesn't restore them properly on
2985  * resume.
2986  */
2987 static int
2988 re_suspend(device_t dev)
2989 {
2990 #ifndef BURN_BRIDGES
2991 	int i;
2992 #endif
2993 	struct re_softc *sc = device_get_softc(dev);
2994 	struct ifnet *ifp = &sc->arpcom.ac_if;
2995 
2996 	lwkt_serialize_enter(ifp->if_serializer);
2997 
2998 	re_stop(sc);
2999 
3000 #ifndef BURN_BRIDGES
3001 	for (i = 0; i < 5; i++)
3002 		sc->saved_maps[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
3003 	sc->saved_biosaddr = pci_read_config(dev, PCIR_BIOS, 4);
3004 	sc->saved_intline = pci_read_config(dev, PCIR_INTLINE, 1);
3005 	sc->saved_cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
3006 	sc->saved_lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
3007 #endif
3008 
3009 	sc->re_flags |= RE_F_SUSPENDED;
3010 
3011 	lwkt_serialize_exit(ifp->if_serializer);
3012 
3013 	return (0);
3014 }
3015 
3016 /*
3017  * Device resume routine.  Restore some PCI settings in case the BIOS
3018  * doesn't, re-enable busmastering, and restart the interface if
3019  * appropriate.
3020  */
3021 static int
3022 re_resume(device_t dev)
3023 {
3024 	struct re_softc *sc = device_get_softc(dev);
3025 	struct ifnet *ifp = &sc->arpcom.ac_if;
3026 #ifndef BURN_BRIDGES
3027 	int i;
3028 #endif
3029 
3030 	lwkt_serialize_enter(ifp->if_serializer);
3031 
3032 #ifndef BURN_BRIDGES
3033 	/* better way to do this? */
3034 	for (i = 0; i < 5; i++)
3035 		pci_write_config(dev, PCIR_MAPS + i * 4, sc->saved_maps[i], 4);
3036 	pci_write_config(dev, PCIR_BIOS, sc->saved_biosaddr, 4);
3037 	pci_write_config(dev, PCIR_INTLINE, sc->saved_intline, 1);
3038 	pci_write_config(dev, PCIR_CACHELNSZ, sc->saved_cachelnsz, 1);
3039 	pci_write_config(dev, PCIR_LATTIMER, sc->saved_lattimer, 1);
3040 
3041 	/* reenable busmastering */
3042 	pci_enable_busmaster(dev);
3043 	pci_enable_io(dev, SYS_RES_IOPORT);
3044 #endif
3045 
3046 	/* reinitialize interface if necessary */
3047 	if (ifp->if_flags & IFF_UP)
3048 		re_init(sc);
3049 
3050 	sc->re_flags &= ~RE_F_SUSPENDED;
3051 
3052 	lwkt_serialize_exit(ifp->if_serializer);
3053 
3054 	return (0);
3055 }
3056 
3057 /*
3058  * Stop all chip I/O so that the kernel's probe routines don't
3059  * get confused by errant DMAs when rebooting.
3060  */
3061 static void
3062 re_shutdown(device_t dev)
3063 {
3064 	struct re_softc *sc = device_get_softc(dev);
3065 	struct ifnet *ifp = &sc->arpcom.ac_if;
3066 
3067 	lwkt_serialize_enter(ifp->if_serializer);
3068 	re_stop(sc);
3069 	lwkt_serialize_exit(ifp->if_serializer);
3070 }
3071 
3072 static int
3073 re_sysctl_rxtime(SYSCTL_HANDLER_ARGS)
3074 {
3075 	struct re_softc *sc = arg1;
3076 
3077 	return re_sysctl_hwtime(oidp, arg1, arg2, req, &sc->re_rx_time);
3078 }
3079 
3080 static int
3081 re_sysctl_txtime(SYSCTL_HANDLER_ARGS)
3082 {
3083 	struct re_softc *sc = arg1;
3084 
3085 	return re_sysctl_hwtime(oidp, arg1, arg2, req, &sc->re_tx_time);
3086 }
3087 
3088 static int
3089 re_sysctl_hwtime(SYSCTL_HANDLER_ARGS, int *hwtime)
3090 {
3091 	struct re_softc *sc = arg1;
3092 	struct ifnet *ifp = &sc->arpcom.ac_if;
3093 	int error, v;
3094 
3095 	lwkt_serialize_enter(ifp->if_serializer);
3096 
3097 	v = *hwtime;
3098 	error = sysctl_handle_int(oidp, &v, 0, req);
3099 	if (error || req->newptr == NULL)
3100 		goto back;
3101 
3102 	if (v <= 0) {
3103 		error = EINVAL;
3104 		goto back;
3105 	}
3106 
3107 	if (v != *hwtime) {
3108 		*hwtime = v;
3109 
3110 		if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3111 		    IFF_RUNNING && sc->re_imtype == RE_IMTYPE_HW)
3112 			re_setup_hw_im(sc);
3113 	}
3114 back:
3115 	lwkt_serialize_exit(ifp->if_serializer);
3116 	return error;
3117 }
3118 
3119 static int
3120 re_sysctl_simtime(SYSCTL_HANDLER_ARGS)
3121 {
3122 	struct re_softc *sc = arg1;
3123 	struct ifnet *ifp = &sc->arpcom.ac_if;
3124 	int error, v;
3125 
3126 	lwkt_serialize_enter(ifp->if_serializer);
3127 
3128 	v = sc->re_sim_time;
3129 	error = sysctl_handle_int(oidp, &v, 0, req);
3130 	if (error || req->newptr == NULL)
3131 		goto back;
3132 
3133 	if (v <= 0) {
3134 		error = EINVAL;
3135 		goto back;
3136 	}
3137 
3138 	if (v != sc->re_sim_time) {
3139 		sc->re_sim_time = v;
3140 
3141 		if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3142 		    IFF_RUNNING && sc->re_imtype == RE_IMTYPE_SIM) {
3143 #ifdef foo
3144 			int reg;
3145 
3146 			/*
3147 			 * Following code causes various strange
3148 			 * performance problems.  Hmm ...
3149 			 */
3150 			CSR_WRITE_2(sc, RE_IMR, 0);
3151 			if (!RE_IS_8139CP(sc))
3152 				reg = RE_TIMERINT_8169;
3153 			else
3154 				reg = RE_TIMERINT;
3155 			CSR_WRITE_4(sc, reg, 0);
3156 			CSR_READ_4(sc, reg); /* flush */
3157 
3158 			CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
3159 			re_setup_sim_im(sc);
3160 #else
3161 			re_setup_intr(sc, 0, RE_IMTYPE_NONE);
3162 			DELAY(10);
3163 			re_setup_intr(sc, 1, RE_IMTYPE_SIM);
3164 #endif
3165 		}
3166 	}
3167 back:
3168 	lwkt_serialize_exit(ifp->if_serializer);
3169 	return error;
3170 }
3171 
3172 static int
3173 re_sysctl_imtype(SYSCTL_HANDLER_ARGS)
3174 {
3175 	struct re_softc *sc = arg1;
3176 	struct ifnet *ifp = &sc->arpcom.ac_if;
3177 	int error, v;
3178 
3179 	lwkt_serialize_enter(ifp->if_serializer);
3180 
3181 	v = sc->re_imtype;
3182 	error = sysctl_handle_int(oidp, &v, 0, req);
3183 	if (error || req->newptr == NULL)
3184 		goto back;
3185 
3186 	if (v != RE_IMTYPE_HW && v != RE_IMTYPE_SIM && v != RE_IMTYPE_NONE) {
3187 		error = EINVAL;
3188 		goto back;
3189 	}
3190 	if (v == RE_IMTYPE_HW && (sc->re_caps & RE_C_HWIM) == 0) {
3191 		/* Can't do hardware interrupt moderation */
3192 		error = EOPNOTSUPP;
3193 		goto back;
3194 	}
3195 
3196 	if (v != sc->re_imtype) {
3197 		sc->re_imtype = v;
3198 		if ((ifp->if_flags & (IFF_RUNNING | IFF_POLLING)) ==
3199 		    IFF_RUNNING)
3200 			re_setup_intr(sc, 1, sc->re_imtype);
3201 	}
3202 back:
3203 	lwkt_serialize_exit(ifp->if_serializer);
3204 	return error;
3205 }
3206 
3207 static void
3208 re_setup_hw_im(struct re_softc *sc)
3209 {
3210 	KKASSERT(sc->re_caps & RE_C_HWIM);
3211 
3212 	/*
3213 	 * Interrupt moderation
3214 	 *
3215 	 * 0xABCD
3216 	 * A - unknown (maybe TX related)
3217 	 * B - TX timer (unit: 25us)
3218 	 * C - unknown (maybe RX related)
3219 	 * D - RX timer (unit: 25us)
3220 	 *
3221 	 *
3222 	 * re(4)'s interrupt moderation is actually controlled by
3223 	 * two variables, like most other NICs (bge, bce etc.)
3224 	 * o  timer
3225 	 * o  number of packets [P]
3226 	 *
3227 	 * The logic relationship between these two variables is
3228 	 * similar to other NICs too:
3229 	 * if (timer expire || packets > [P])
3230 	 *     Interrupt is delivered
3231 	 *
3232 	 * Currently we only know how to set 'timer', but not
3233 	 * 'number of packets', which should be ~30, as far as I
3234 	 * tested (sink ~900Kpps, interrupt rate is 30KHz)
3235 	 */
3236 	CSR_WRITE_2(sc, RE_IM,
3237 		    RE_IM_RXTIME(sc->re_rx_time) |
3238 		    RE_IM_TXTIME(sc->re_tx_time) |
3239 		    RE_IM_MAGIC);
3240 }
3241 
3242 static void
3243 re_disable_hw_im(struct re_softc *sc)
3244 {
3245 	if (sc->re_caps & RE_C_HWIM)
3246 		CSR_WRITE_2(sc, RE_IM, 0);
3247 }
3248 
3249 static void
3250 re_setup_sim_im(struct re_softc *sc)
3251 {
3252 	if (!RE_IS_8139CP(sc)) {
3253 		uint32_t ticks;
3254 
3255 		/*
3256 		 * Datasheet says tick decreases at bus speed,
3257 		 * but it seems the clock runs a little bit
3258 		 * faster, so we do some compensation here.
3259 		 */
3260 		ticks = (sc->re_sim_time * sc->re_bus_speed * 8) / 5;
3261 		CSR_WRITE_4(sc, RE_TIMERINT_8169, ticks);
3262 	} else {
3263 		CSR_WRITE_4(sc, RE_TIMERINT, 0x400); /* XXX */
3264 	}
3265 	CSR_WRITE_4(sc, RE_TIMERCNT, 1); /* reload */
3266 	sc->re_flags |= RE_F_TIMER_INTR;
3267 }
3268 
3269 static void
3270 re_disable_sim_im(struct re_softc *sc)
3271 {
3272 	if (!RE_IS_8139CP(sc))
3273 		CSR_WRITE_4(sc, RE_TIMERINT_8169, 0);
3274 	else
3275 		CSR_WRITE_4(sc, RE_TIMERINT, 0);
3276 	sc->re_flags &= ~RE_F_TIMER_INTR;
3277 }
3278 
3279 static void
3280 re_config_imtype(struct re_softc *sc, int imtype)
3281 {
3282 	switch (imtype) {
3283 	case RE_IMTYPE_HW:
3284 		KKASSERT(sc->re_caps & RE_C_HWIM);
3285 		/* FALL THROUGH */
3286 	case RE_IMTYPE_NONE:
3287 		sc->re_intrs = RE_INTRS;
3288 		sc->re_rx_ack = RE_ISR_RX_OK | RE_ISR_FIFO_OFLOW |
3289 				RE_ISR_RX_OVERRUN;
3290 		sc->re_tx_ack = RE_ISR_TX_OK;
3291 		break;
3292 
3293 	case RE_IMTYPE_SIM:
3294 		sc->re_intrs = RE_INTRS_TIMER;
3295 		sc->re_rx_ack = RE_ISR_TIMEOUT_EXPIRED;
3296 		sc->re_tx_ack = RE_ISR_TIMEOUT_EXPIRED;
3297 		break;
3298 
3299 	default:
3300 		panic("%s: unknown imtype %d\n",
3301 		      sc->arpcom.ac_if.if_xname, imtype);
3302 	}
3303 }
3304 
3305 static void
3306 re_setup_intr(struct re_softc *sc, int enable_intrs, int imtype)
3307 {
3308 	re_config_imtype(sc, imtype);
3309 
3310 	if (enable_intrs)
3311 		CSR_WRITE_2(sc, RE_IMR, sc->re_intrs);
3312 	else
3313 		CSR_WRITE_2(sc, RE_IMR, 0);
3314 
3315 	switch (imtype) {
3316 	case RE_IMTYPE_NONE:
3317 		re_disable_sim_im(sc);
3318 		re_disable_hw_im(sc);
3319 		break;
3320 
3321 	case RE_IMTYPE_HW:
3322 		KKASSERT(sc->re_caps & RE_C_HWIM);
3323 		re_disable_sim_im(sc);
3324 		re_setup_hw_im(sc);
3325 		break;
3326 
3327 	case RE_IMTYPE_SIM:
3328 		re_disable_hw_im(sc);
3329 		re_setup_sim_im(sc);
3330 		break;
3331 
3332 	default:
3333 		panic("%s: unknown imtype %d\n",
3334 		      sc->arpcom.ac_if.if_xname, imtype);
3335 	}
3336 }
3337 
3338 static void
3339 re_get_eaddr(struct re_softc *sc, uint8_t *eaddr)
3340 {
3341 	int i;
3342 
3343 	if (sc->re_macver == RE_MACVER_11 || sc->re_macver == RE_MACVER_12) {
3344 		uint16_t re_did;
3345 
3346 		re_get_eewidth(sc);
3347 		re_read_eeprom(sc, (caddr_t)&re_did, 0, 1);
3348 		if (re_did == 0x8128) {
3349 			uint16_t as[ETHER_ADDR_LEN / 2];
3350 
3351 			/*
3352 			 * Get station address from the EEPROM.
3353 			 */
3354 			re_read_eeprom(sc, (caddr_t)as, RE_EE_EADDR, 3);
3355 			for (i = 0; i < ETHER_ADDR_LEN / 2; i++)
3356 				as[i] = le16toh(as[i]);
3357 			bcopy(as, eaddr, sizeof(eaddr));
3358 			return;
3359 		}
3360 	}
3361 
3362 	/*
3363 	 * Get station address from IDRx.
3364 	 */
3365 	for (i = 0; i < ETHER_ADDR_LEN; ++i)
3366 		eaddr[i] = CSR_READ_1(sc, RE_IDR0 + i);
3367 }
3368 
3369 static int
3370 re_jpool_alloc(struct re_softc *sc)
3371 {
3372 	struct re_list_data *ldata = &sc->re_ldata;
3373 	struct re_jbuf *jbuf;
3374 	bus_addr_t paddr;
3375 	bus_size_t jpool_size;
3376 	caddr_t buf;
3377 	int i, error;
3378 
3379 	lwkt_serialize_init(&ldata->re_jbuf_serializer);
3380 
3381 	ldata->re_jbuf = kmalloc(sizeof(struct re_jbuf) * RE_JBUF_COUNT(sc),
3382 				 M_DEVBUF, M_WAITOK | M_ZERO);
3383 
3384 	jpool_size = RE_JBUF_COUNT(sc) * RE_JBUF_SIZE;
3385 
3386 	error = bus_dma_tag_create(sc->re_parent_tag,
3387 			RE_RXBUF_ALIGN, 0,	/* alignment, boundary */
3388 			BUS_SPACE_MAXADDR,	/* lowaddr */
3389 			BUS_SPACE_MAXADDR,	/* highaddr */
3390 			NULL, NULL,		/* filter, filterarg */
3391 			jpool_size, 1,		/* maxsize, nsegments */
3392 			jpool_size,		/* maxsegsize */
3393 			0,			/* flags */
3394 			&ldata->re_jpool_tag);
3395 	if (error) {
3396 		device_printf(sc->re_dev, "could not allocate jumbo dma tag\n");
3397 		return error;
3398 	}
3399 
3400 	error = bus_dmamem_alloc(ldata->re_jpool_tag, (void **)&ldata->re_jpool,
3401 				 BUS_DMA_WAITOK, &ldata->re_jpool_map);
3402 	if (error) {
3403 		device_printf(sc->re_dev,
3404 			      "could not allocate jumbo dma memory\n");
3405 		bus_dma_tag_destroy(ldata->re_jpool_tag);
3406 		ldata->re_jpool_tag = NULL;
3407 		return error;
3408 	}
3409 
3410 	error = bus_dmamap_load(ldata->re_jpool_tag, ldata->re_jpool_map,
3411 				ldata->re_jpool, jpool_size,
3412 				re_dma_map_addr, &paddr, BUS_DMA_WAITOK);
3413 	if (error) {
3414 		device_printf(sc->re_dev, "could not load jumbo dma map\n");
3415 		bus_dmamem_free(ldata->re_jpool_tag, ldata->re_jpool,
3416 				ldata->re_jpool_map);
3417 		bus_dma_tag_destroy(ldata->re_jpool_tag);
3418 		ldata->re_jpool_tag = NULL;
3419 		return error;
3420 	}
3421 
3422 	/* ..and split it into 9KB chunks */
3423 	SLIST_INIT(&ldata->re_jbuf_free);
3424 
3425 	buf = ldata->re_jpool;
3426 	for (i = 0; i < RE_JBUF_COUNT(sc); i++) {
3427 		jbuf = &ldata->re_jbuf[i];
3428 
3429 		jbuf->re_sc = sc;
3430 		jbuf->re_inuse = 0;
3431 		jbuf->re_slot = i;
3432 		jbuf->re_buf = buf;
3433 		jbuf->re_paddr = paddr;
3434 
3435 		SLIST_INSERT_HEAD(&ldata->re_jbuf_free, jbuf, re_link);
3436 
3437 		buf += RE_JBUF_SIZE;
3438 		paddr += RE_JBUF_SIZE;
3439 	}
3440 	return 0;
3441 }
3442 
3443 static void
3444 re_jpool_free(struct re_softc *sc)
3445 {
3446 	struct re_list_data *ldata = &sc->re_ldata;
3447 
3448 	if (ldata->re_jpool_tag != NULL) {
3449 		bus_dmamap_unload(ldata->re_jpool_tag, ldata->re_jpool_map);
3450 		bus_dmamem_free(ldata->re_jpool_tag, ldata->re_jpool,
3451 				ldata->re_jpool_map);
3452 		bus_dma_tag_destroy(ldata->re_jpool_tag);
3453 		ldata->re_jpool_tag = NULL;
3454 	}
3455 
3456 	if (ldata->re_jbuf != NULL) {
3457 		kfree(ldata->re_jbuf, M_DEVBUF);
3458 		ldata->re_jbuf = NULL;
3459 	}
3460 }
3461 
3462 static struct re_jbuf *
3463 re_jbuf_alloc(struct re_softc *sc)
3464 {
3465 	struct re_list_data *ldata = &sc->re_ldata;
3466 	struct re_jbuf *jbuf;
3467 
3468 	lwkt_serialize_enter(&ldata->re_jbuf_serializer);
3469 
3470 	jbuf = SLIST_FIRST(&ldata->re_jbuf_free);
3471 	if (jbuf != NULL) {
3472 		SLIST_REMOVE_HEAD(&ldata->re_jbuf_free, re_link);
3473 		jbuf->re_inuse = 1;
3474 	}
3475 
3476 	lwkt_serialize_exit(&ldata->re_jbuf_serializer);
3477 
3478 	return jbuf;
3479 }
3480 
3481 static void
3482 re_jbuf_free(void *arg)
3483 {
3484 	struct re_jbuf *jbuf = arg;
3485 	struct re_softc *sc = jbuf->re_sc;
3486 	struct re_list_data *ldata = &sc->re_ldata;
3487 
3488 	if (&ldata->re_jbuf[jbuf->re_slot] != jbuf) {
3489 		panic("%s: free wrong jumbo buffer\n",
3490 		      sc->arpcom.ac_if.if_xname);
3491 	} else if (jbuf->re_inuse == 0) {
3492 		panic("%s: jumbo buffer already freed\n",
3493 		      sc->arpcom.ac_if.if_xname);
3494 	}
3495 
3496 	lwkt_serialize_enter(&ldata->re_jbuf_serializer);
3497 	atomic_subtract_int(&jbuf->re_inuse, 1);
3498 	if (jbuf->re_inuse == 0)
3499 		SLIST_INSERT_HEAD(&ldata->re_jbuf_free, jbuf, re_link);
3500 	lwkt_serialize_exit(&ldata->re_jbuf_serializer);
3501 }
3502 
3503 static void
3504 re_jbuf_ref(void *arg)
3505 {
3506 	struct re_jbuf *jbuf = arg;
3507 	struct re_softc *sc = jbuf->re_sc;
3508 	struct re_list_data *ldata = &sc->re_ldata;
3509 
3510 	if (&ldata->re_jbuf[jbuf->re_slot] != jbuf) {
3511 		panic("%s: ref wrong jumbo buffer\n",
3512 		      sc->arpcom.ac_if.if_xname);
3513 	} else if (jbuf->re_inuse == 0) {
3514 		panic("%s: jumbo buffer already freed\n",
3515 		      sc->arpcom.ac_if.if_xname);
3516 	}
3517 	atomic_add_int(&jbuf->re_inuse, 1);
3518 }
3519