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