xref: /dflybsd-src/sys/dev/netif/emx/if_emx.c (revision 37cbab4e1d236766bff1f9fd79c7ae9ca6d69ba9)
1 /*
2  * Copyright (c) 2004 Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
3  *
4  * Copyright (c) 2001-2008, Intel Corporation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *
10  *  1. Redistributions of source code must retain the above copyright notice,
11  *     this list of conditions and the following disclaimer.
12  *
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  *
17  *  3. Neither the name of the Intel Corporation nor the names of its
18  *     contributors may be used to endorse or promote products derived from
19  *     this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  *
34  * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
35  *
36  * This code is derived from software contributed to The DragonFly Project
37  * by Matthew Dillon <dillon@backplane.com>
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  *
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in
47  *    the documentation and/or other materials provided with the
48  *    distribution.
49  * 3. Neither the name of The DragonFly Project nor the names of its
50  *    contributors may be used to endorse or promote products derived
51  *    from this software without specific, prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
54  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
55  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
56  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
57  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
58  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
59  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
60  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
61  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
62  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
63  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  */
66 
67 #include "opt_ifpoll.h"
68 #include "opt_emx.h"
69 
70 #include <sys/param.h>
71 #include <sys/bus.h>
72 #include <sys/endian.h>
73 #include <sys/interrupt.h>
74 #include <sys/kernel.h>
75 #include <sys/ktr.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/proc.h>
79 #include <sys/rman.h>
80 #include <sys/serialize.h>
81 #include <sys/serialize2.h>
82 #include <sys/socket.h>
83 #include <sys/sockio.h>
84 #include <sys/sysctl.h>
85 #include <sys/systm.h>
86 
87 #include <net/bpf.h>
88 #include <net/ethernet.h>
89 #include <net/if.h>
90 #include <net/if_arp.h>
91 #include <net/if_dl.h>
92 #include <net/if_media.h>
93 #include <net/ifq_var.h>
94 #include <net/toeplitz.h>
95 #include <net/toeplitz2.h>
96 #include <net/vlan/if_vlan_var.h>
97 #include <net/vlan/if_vlan_ether.h>
98 #include <net/if_poll.h>
99 
100 #include <netinet/in_systm.h>
101 #include <netinet/in.h>
102 #include <netinet/ip.h>
103 #include <netinet/tcp.h>
104 #include <netinet/udp.h>
105 
106 #include <bus/pci/pcivar.h>
107 #include <bus/pci/pcireg.h>
108 
109 #include <dev/netif/ig_hal/e1000_api.h>
110 #include <dev/netif/ig_hal/e1000_82571.h>
111 #include <dev/netif/emx/if_emx.h>
112 
113 #ifdef EMX_RSS_DEBUG
114 #define EMX_RSS_DPRINTF(sc, lvl, fmt, ...) \
115 do { \
116 	if (sc->rss_debug >= lvl) \
117 		if_printf(&sc->arpcom.ac_if, fmt, __VA_ARGS__); \
118 } while (0)
119 #else	/* !EMX_RSS_DEBUG */
120 #define EMX_RSS_DPRINTF(sc, lvl, fmt, ...)	((void)0)
121 #endif	/* EMX_RSS_DEBUG */
122 
123 #define EMX_TX_SERIALIZE	1
124 #define EMX_RX_SERIALIZE	3
125 
126 #define EMX_NAME	"Intel(R) PRO/1000 "
127 
128 #define EMX_DEVICE(id)	\
129 	{ EMX_VENDOR_ID, E1000_DEV_ID_##id, EMX_NAME #id }
130 #define EMX_DEVICE_NULL	{ 0, 0, NULL }
131 
132 static const struct emx_device {
133 	uint16_t	vid;
134 	uint16_t	did;
135 	const char	*desc;
136 } emx_devices[] = {
137 	EMX_DEVICE(82571EB_COPPER),
138 	EMX_DEVICE(82571EB_FIBER),
139 	EMX_DEVICE(82571EB_SERDES),
140 	EMX_DEVICE(82571EB_SERDES_DUAL),
141 	EMX_DEVICE(82571EB_SERDES_QUAD),
142 	EMX_DEVICE(82571EB_QUAD_COPPER),
143 	EMX_DEVICE(82571EB_QUAD_COPPER_BP),
144 	EMX_DEVICE(82571EB_QUAD_COPPER_LP),
145 	EMX_DEVICE(82571EB_QUAD_FIBER),
146 	EMX_DEVICE(82571PT_QUAD_COPPER),
147 
148 	EMX_DEVICE(82572EI_COPPER),
149 	EMX_DEVICE(82572EI_FIBER),
150 	EMX_DEVICE(82572EI_SERDES),
151 	EMX_DEVICE(82572EI),
152 
153 	EMX_DEVICE(82573E),
154 	EMX_DEVICE(82573E_IAMT),
155 	EMX_DEVICE(82573L),
156 
157 	EMX_DEVICE(80003ES2LAN_COPPER_SPT),
158 	EMX_DEVICE(80003ES2LAN_SERDES_SPT),
159 	EMX_DEVICE(80003ES2LAN_COPPER_DPT),
160 	EMX_DEVICE(80003ES2LAN_SERDES_DPT),
161 
162 	EMX_DEVICE(82574L),
163 	EMX_DEVICE(82574LA),
164 
165 	/* required last entry */
166 	EMX_DEVICE_NULL
167 };
168 
169 static int	emx_probe(device_t);
170 static int	emx_attach(device_t);
171 static int	emx_detach(device_t);
172 static int	emx_shutdown(device_t);
173 static int	emx_suspend(device_t);
174 static int	emx_resume(device_t);
175 
176 static void	emx_init(void *);
177 static void	emx_stop(struct emx_softc *);
178 static int	emx_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
179 static void	emx_start(struct ifnet *, struct ifaltq_subque *);
180 #ifdef IFPOLL_ENABLE
181 static void	emx_npoll(struct ifnet *, struct ifpoll_info *);
182 static void	emx_npoll_status(struct ifnet *);
183 static void	emx_npoll_tx(struct ifnet *, void *, int);
184 static void	emx_npoll_rx(struct ifnet *, void *, int);
185 #endif
186 static void	emx_watchdog(struct ifaltq_subque *);
187 static void	emx_media_status(struct ifnet *, struct ifmediareq *);
188 static int	emx_media_change(struct ifnet *);
189 static void	emx_timer(void *);
190 static void	emx_serialize(struct ifnet *, enum ifnet_serialize);
191 static void	emx_deserialize(struct ifnet *, enum ifnet_serialize);
192 static int	emx_tryserialize(struct ifnet *, enum ifnet_serialize);
193 #ifdef INVARIANTS
194 static void	emx_serialize_assert(struct ifnet *, enum ifnet_serialize,
195 		    boolean_t);
196 #endif
197 
198 static void	emx_intr(void *);
199 static void	emx_intr_mask(void *);
200 static void	emx_intr_body(struct emx_softc *, boolean_t);
201 static void	emx_rxeof(struct emx_rxdata *, int);
202 static void	emx_txeof(struct emx_txdata *);
203 static void	emx_tx_collect(struct emx_txdata *);
204 static void	emx_tx_purge(struct emx_softc *);
205 static void	emx_enable_intr(struct emx_softc *);
206 static void	emx_disable_intr(struct emx_softc *);
207 
208 static int	emx_dma_alloc(struct emx_softc *);
209 static void	emx_dma_free(struct emx_softc *);
210 static void	emx_init_tx_ring(struct emx_txdata *);
211 static int	emx_init_rx_ring(struct emx_rxdata *);
212 static void	emx_free_tx_ring(struct emx_txdata *);
213 static void	emx_free_rx_ring(struct emx_rxdata *);
214 static int	emx_create_tx_ring(struct emx_txdata *);
215 static int	emx_create_rx_ring(struct emx_rxdata *);
216 static void	emx_destroy_tx_ring(struct emx_txdata *, int);
217 static void	emx_destroy_rx_ring(struct emx_rxdata *, int);
218 static int	emx_newbuf(struct emx_rxdata *, int, int);
219 static int	emx_encap(struct emx_txdata *, struct mbuf **, int *, int *);
220 static int	emx_txcsum(struct emx_txdata *, struct mbuf *,
221 		    uint32_t *, uint32_t *);
222 static int	emx_tso_pullup(struct emx_txdata *, struct mbuf **);
223 static int	emx_tso_setup(struct emx_txdata *, struct mbuf *,
224 		    uint32_t *, uint32_t *);
225 static int	emx_get_txring_inuse(const struct emx_softc *, boolean_t);
226 
227 static int 	emx_is_valid_eaddr(const uint8_t *);
228 static int	emx_reset(struct emx_softc *);
229 static void	emx_setup_ifp(struct emx_softc *);
230 static void	emx_init_tx_unit(struct emx_softc *);
231 static void	emx_init_rx_unit(struct emx_softc *);
232 static void	emx_update_stats(struct emx_softc *);
233 static void	emx_set_promisc(struct emx_softc *);
234 static void	emx_disable_promisc(struct emx_softc *);
235 static void	emx_set_multi(struct emx_softc *);
236 static void	emx_update_link_status(struct emx_softc *);
237 static void	emx_smartspeed(struct emx_softc *);
238 static void	emx_set_itr(struct emx_softc *, uint32_t);
239 static void	emx_disable_aspm(struct emx_softc *);
240 
241 static void	emx_print_debug_info(struct emx_softc *);
242 static void	emx_print_nvm_info(struct emx_softc *);
243 static void	emx_print_hw_stats(struct emx_softc *);
244 
245 static int	emx_sysctl_stats(SYSCTL_HANDLER_ARGS);
246 static int	emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS);
247 static int	emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS);
248 static int	emx_sysctl_tx_intr_nsegs(SYSCTL_HANDLER_ARGS);
249 static int	emx_sysctl_tx_wreg_nsegs(SYSCTL_HANDLER_ARGS);
250 #ifdef IFPOLL_ENABLE
251 static int	emx_sysctl_npoll_rxoff(SYSCTL_HANDLER_ARGS);
252 static int	emx_sysctl_npoll_txoff(SYSCTL_HANDLER_ARGS);
253 #endif
254 static void	emx_add_sysctl(struct emx_softc *);
255 
256 static void	emx_serialize_skipmain(struct emx_softc *);
257 static void	emx_deserialize_skipmain(struct emx_softc *);
258 
259 /* Management and WOL Support */
260 static void	emx_get_mgmt(struct emx_softc *);
261 static void	emx_rel_mgmt(struct emx_softc *);
262 static void	emx_get_hw_control(struct emx_softc *);
263 static void	emx_rel_hw_control(struct emx_softc *);
264 static void	emx_enable_wol(device_t);
265 
266 static device_method_t emx_methods[] = {
267 	/* Device interface */
268 	DEVMETHOD(device_probe,		emx_probe),
269 	DEVMETHOD(device_attach,	emx_attach),
270 	DEVMETHOD(device_detach,	emx_detach),
271 	DEVMETHOD(device_shutdown,	emx_shutdown),
272 	DEVMETHOD(device_suspend,	emx_suspend),
273 	DEVMETHOD(device_resume,	emx_resume),
274 	{ 0, 0 }
275 };
276 
277 static driver_t emx_driver = {
278 	"emx",
279 	emx_methods,
280 	sizeof(struct emx_softc),
281 };
282 
283 static devclass_t emx_devclass;
284 
285 DECLARE_DUMMY_MODULE(if_emx);
286 MODULE_DEPEND(emx, ig_hal, 1, 1, 1);
287 DRIVER_MODULE(if_emx, pci, emx_driver, emx_devclass, NULL, NULL);
288 
289 /*
290  * Tunables
291  */
292 static int	emx_int_throttle_ceil = EMX_DEFAULT_ITR;
293 static int	emx_rxd = EMX_DEFAULT_RXD;
294 static int	emx_txd = EMX_DEFAULT_TXD;
295 static int	emx_smart_pwr_down = 0;
296 static int	emx_rxr = 0;
297 static int	emx_txr = 1;
298 
299 /* Controls whether promiscuous also shows bad packets */
300 static int	emx_debug_sbp = 0;
301 
302 static int	emx_82573_workaround = 1;
303 static int	emx_msi_enable = 1;
304 
305 TUNABLE_INT("hw.emx.int_throttle_ceil", &emx_int_throttle_ceil);
306 TUNABLE_INT("hw.emx.rxd", &emx_rxd);
307 TUNABLE_INT("hw.emx.rxr", &emx_rxr);
308 TUNABLE_INT("hw.emx.txd", &emx_txd);
309 TUNABLE_INT("hw.emx.txr", &emx_txr);
310 TUNABLE_INT("hw.emx.smart_pwr_down", &emx_smart_pwr_down);
311 TUNABLE_INT("hw.emx.sbp", &emx_debug_sbp);
312 TUNABLE_INT("hw.emx.82573_workaround", &emx_82573_workaround);
313 TUNABLE_INT("hw.emx.msi.enable", &emx_msi_enable);
314 
315 /* Global used in WOL setup with multiport cards */
316 static int	emx_global_quad_port_a = 0;
317 
318 /* Set this to one to display debug statistics */
319 static int	emx_display_debug_stats = 0;
320 
321 #if !defined(KTR_IF_EMX)
322 #define KTR_IF_EMX	KTR_ALL
323 #endif
324 KTR_INFO_MASTER(if_emx);
325 KTR_INFO(KTR_IF_EMX, if_emx, intr_beg, 0, "intr begin");
326 KTR_INFO(KTR_IF_EMX, if_emx, intr_end, 1, "intr end");
327 KTR_INFO(KTR_IF_EMX, if_emx, pkt_receive, 4, "rx packet");
328 KTR_INFO(KTR_IF_EMX, if_emx, pkt_txqueue, 5, "tx packet");
329 KTR_INFO(KTR_IF_EMX, if_emx, pkt_txclean, 6, "tx clean");
330 #define logif(name)	KTR_LOG(if_emx_ ## name)
331 
332 static __inline void
333 emx_setup_rxdesc(emx_rxdesc_t *rxd, const struct emx_rxbuf *rxbuf)
334 {
335 	rxd->rxd_bufaddr = htole64(rxbuf->paddr);
336 	/* DD bit must be cleared */
337 	rxd->rxd_staterr = 0;
338 }
339 
340 static __inline void
341 emx_rxcsum(uint32_t staterr, struct mbuf *mp)
342 {
343 	/* Ignore Checksum bit is set */
344 	if (staterr & E1000_RXD_STAT_IXSM)
345 		return;
346 
347 	if ((staterr & (E1000_RXD_STAT_IPCS | E1000_RXDEXT_STATERR_IPE)) ==
348 	    E1000_RXD_STAT_IPCS)
349 		mp->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
350 
351 	if ((staterr & (E1000_RXD_STAT_TCPCS | E1000_RXDEXT_STATERR_TCPE)) ==
352 	    E1000_RXD_STAT_TCPCS) {
353 		mp->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
354 					   CSUM_PSEUDO_HDR |
355 					   CSUM_FRAG_NOT_CHECKED;
356 		mp->m_pkthdr.csum_data = htons(0xffff);
357 	}
358 }
359 
360 static __inline struct pktinfo *
361 emx_rssinfo(struct mbuf *m, struct pktinfo *pi,
362 	    uint32_t mrq, uint32_t hash, uint32_t staterr)
363 {
364 	switch (mrq & EMX_RXDMRQ_RSSTYPE_MASK) {
365 	case EMX_RXDMRQ_IPV4_TCP:
366 		pi->pi_netisr = NETISR_IP;
367 		pi->pi_flags = 0;
368 		pi->pi_l3proto = IPPROTO_TCP;
369 		break;
370 
371 	case EMX_RXDMRQ_IPV6_TCP:
372 		pi->pi_netisr = NETISR_IPV6;
373 		pi->pi_flags = 0;
374 		pi->pi_l3proto = IPPROTO_TCP;
375 		break;
376 
377 	case EMX_RXDMRQ_IPV4:
378 		if (staterr & E1000_RXD_STAT_IXSM)
379 			return NULL;
380 
381 		if ((staterr &
382 		     (E1000_RXD_STAT_TCPCS | E1000_RXDEXT_STATERR_TCPE)) ==
383 		    E1000_RXD_STAT_TCPCS) {
384 			pi->pi_netisr = NETISR_IP;
385 			pi->pi_flags = 0;
386 			pi->pi_l3proto = IPPROTO_UDP;
387 			break;
388 		}
389 		/* FALL THROUGH */
390 	default:
391 		return NULL;
392 	}
393 
394 	m->m_flags |= M_HASH;
395 	m->m_pkthdr.hash = toeplitz_hash(hash);
396 	return pi;
397 }
398 
399 static int
400 emx_probe(device_t dev)
401 {
402 	const struct emx_device *d;
403 	uint16_t vid, did;
404 
405 	vid = pci_get_vendor(dev);
406 	did = pci_get_device(dev);
407 
408 	for (d = emx_devices; d->desc != NULL; ++d) {
409 		if (vid == d->vid && did == d->did) {
410 			device_set_desc(dev, d->desc);
411 			device_set_async_attach(dev, TRUE);
412 			return 0;
413 		}
414 	}
415 	return ENXIO;
416 }
417 
418 static int
419 emx_attach(device_t dev)
420 {
421 	struct emx_softc *sc = device_get_softc(dev);
422 	struct ifnet *ifp = &sc->arpcom.ac_if;
423 	int error = 0, i, throttle, msi_enable, tx_ring_max;
424 	u_int intr_flags;
425 	uint16_t eeprom_data, device_id, apme_mask;
426 	driver_intr_t *intr_func;
427 #ifdef IFPOLL_ENABLE
428 	int offset, offset_def;
429 #endif
430 
431 	/*
432 	 * Setup RX rings
433 	 */
434 	for (i = 0; i < EMX_NRX_RING; ++i) {
435 		sc->rx_data[i].sc = sc;
436 		sc->rx_data[i].idx = i;
437 	}
438 
439 	/*
440 	 * Setup TX ring
441 	 */
442 	for (i = 0; i < EMX_NTX_RING; ++i) {
443 		sc->tx_data[i].sc = sc;
444 		sc->tx_data[i].idx = i;
445 	}
446 
447 	/*
448 	 * Initialize serializers
449 	 */
450 	lwkt_serialize_init(&sc->main_serialize);
451 	for (i = 0; i < EMX_NTX_RING; ++i)
452 		lwkt_serialize_init(&sc->tx_data[i].tx_serialize);
453 	for (i = 0; i < EMX_NRX_RING; ++i)
454 		lwkt_serialize_init(&sc->rx_data[i].rx_serialize);
455 
456 	/*
457 	 * Initialize serializer array
458 	 */
459 	i = 0;
460 	sc->serializes[i++] = &sc->main_serialize;
461 
462 	KKASSERT(i == EMX_TX_SERIALIZE);
463 	sc->serializes[i++] = &sc->tx_data[0].tx_serialize;
464 	sc->serializes[i++] = &sc->tx_data[1].tx_serialize;
465 
466 	KKASSERT(i == EMX_RX_SERIALIZE);
467 	sc->serializes[i++] = &sc->rx_data[0].rx_serialize;
468 	sc->serializes[i++] = &sc->rx_data[1].rx_serialize;
469 	KKASSERT(i == EMX_NSERIALIZE);
470 
471 	callout_init_mp(&sc->timer);
472 
473 	sc->dev = sc->osdep.dev = dev;
474 
475 	/*
476 	 * Determine hardware and mac type
477 	 */
478 	sc->hw.vendor_id = pci_get_vendor(dev);
479 	sc->hw.device_id = pci_get_device(dev);
480 	sc->hw.revision_id = pci_get_revid(dev);
481 	sc->hw.subsystem_vendor_id = pci_get_subvendor(dev);
482 	sc->hw.subsystem_device_id = pci_get_subdevice(dev);
483 
484 	if (e1000_set_mac_type(&sc->hw))
485 		return ENXIO;
486 
487 	/* Enable bus mastering */
488 	pci_enable_busmaster(dev);
489 
490 	/*
491 	 * Allocate IO memory
492 	 */
493 	sc->memory_rid = EMX_BAR_MEM;
494 	sc->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
495 					    &sc->memory_rid, RF_ACTIVE);
496 	if (sc->memory == NULL) {
497 		device_printf(dev, "Unable to allocate bus resource: memory\n");
498 		error = ENXIO;
499 		goto fail;
500 	}
501 	sc->osdep.mem_bus_space_tag = rman_get_bustag(sc->memory);
502 	sc->osdep.mem_bus_space_handle = rman_get_bushandle(sc->memory);
503 
504 	/* XXX This is quite goofy, it is not actually used */
505 	sc->hw.hw_addr = (uint8_t *)&sc->osdep.mem_bus_space_handle;
506 
507 	/*
508 	 * Don't enable MSI-X on 82574, see:
509 	 * 82574 specification update errata #15
510 	 *
511 	 * Don't enable MSI on 82571/82572, see:
512 	 * 82571/82572 specification update errata #63
513 	 */
514 	msi_enable = emx_msi_enable;
515 	if (msi_enable &&
516 	    (sc->hw.mac.type == e1000_82571 ||
517 	     sc->hw.mac.type == e1000_82572))
518 		msi_enable = 0;
519 
520 	/*
521 	 * Allocate interrupt
522 	 */
523 	sc->intr_type = pci_alloc_1intr(dev, msi_enable,
524 	    &sc->intr_rid, &intr_flags);
525 
526 	if (sc->intr_type == PCI_INTR_TYPE_LEGACY) {
527 		int unshared;
528 
529 		unshared = device_getenv_int(dev, "irq.unshared", 0);
530 		if (!unshared) {
531 			sc->flags |= EMX_FLAG_SHARED_INTR;
532 			if (bootverbose)
533 				device_printf(dev, "IRQ shared\n");
534 		} else {
535 			intr_flags &= ~RF_SHAREABLE;
536 			if (bootverbose)
537 				device_printf(dev, "IRQ unshared\n");
538 		}
539 	}
540 
541 	sc->intr_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->intr_rid,
542 	    intr_flags);
543 	if (sc->intr_res == NULL) {
544 		device_printf(dev, "Unable to allocate bus resource: "
545 		    "interrupt\n");
546 		error = ENXIO;
547 		goto fail;
548 	}
549 
550 	/* Save PCI command register for Shared Code */
551 	sc->hw.bus.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
552 	sc->hw.back = &sc->osdep;
553 
554 	/* Do Shared Code initialization */
555 	if (e1000_setup_init_funcs(&sc->hw, TRUE)) {
556 		device_printf(dev, "Setup of Shared code failed\n");
557 		error = ENXIO;
558 		goto fail;
559 	}
560 	e1000_get_bus_info(&sc->hw);
561 
562 	sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
563 	sc->hw.phy.autoneg_wait_to_complete = FALSE;
564 	sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
565 
566 	/*
567 	 * Interrupt throttle rate
568 	 */
569 	throttle = device_getenv_int(dev, "int_throttle_ceil",
570 	    emx_int_throttle_ceil);
571 	if (throttle == 0) {
572 		sc->int_throttle_ceil = 0;
573 	} else {
574 		if (throttle < 0)
575 			throttle = EMX_DEFAULT_ITR;
576 
577 		/* Recalculate the tunable value to get the exact frequency. */
578 		throttle = 1000000000 / 256 / throttle;
579 
580 		/* Upper 16bits of ITR is reserved and should be zero */
581 		if (throttle & 0xffff0000)
582 			throttle = 1000000000 / 256 / EMX_DEFAULT_ITR;
583 
584 		sc->int_throttle_ceil = 1000000000 / 256 / throttle;
585 	}
586 
587 	e1000_init_script_state_82541(&sc->hw, TRUE);
588 	e1000_set_tbi_compatibility_82543(&sc->hw, TRUE);
589 
590 	/* Copper options */
591 	if (sc->hw.phy.media_type == e1000_media_type_copper) {
592 		sc->hw.phy.mdix = EMX_AUTO_ALL_MODES;
593 		sc->hw.phy.disable_polarity_correction = FALSE;
594 		sc->hw.phy.ms_type = EMX_MASTER_SLAVE;
595 	}
596 
597 	/* Set the frame limits assuming standard ethernet sized frames. */
598 	sc->max_frame_size = ETHERMTU + ETHER_HDR_LEN + ETHER_CRC_LEN;
599 	sc->min_frame_size = ETHER_MIN_LEN;
600 
601 	/* This controls when hardware reports transmit completion status. */
602 	sc->hw.mac.report_tx_early = 1;
603 
604 	/* Calculate # of RX rings */
605 	sc->rx_ring_cnt = device_getenv_int(dev, "rxr", emx_rxr);
606 	sc->rx_ring_cnt = if_ring_count2(sc->rx_ring_cnt, EMX_NRX_RING);
607 
608 	/*
609 	 * Calculate # of TX rings
610 	 *
611 	 * NOTE:
612 	 * Don't enable multiple TX queues on 82574; it always gives
613 	 * watchdog timeout when multiple TCP streams are received.
614 	 */
615 	tx_ring_max = 1;
616 	if (sc->hw.mac.type == e1000_82571 ||
617 	    sc->hw.mac.type == e1000_82572 ||
618 	    sc->hw.mac.type == e1000_80003es2lan)
619 		tx_ring_max = EMX_NTX_RING;
620 	sc->tx_ring_cnt = device_getenv_int(dev, "txr", emx_txr);
621 	sc->tx_ring_cnt = if_ring_count2(sc->tx_ring_cnt, tx_ring_max);
622 
623 	/* Allocate RX/TX rings' busdma(9) stuffs */
624 	error = emx_dma_alloc(sc);
625 	if (error)
626 		goto fail;
627 
628 	/* Allocate multicast array memory. */
629 	sc->mta = kmalloc(ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX,
630 	    M_DEVBUF, M_WAITOK);
631 
632 	/* Indicate SOL/IDER usage */
633 	if (e1000_check_reset_block(&sc->hw)) {
634 		device_printf(dev,
635 		    "PHY reset is blocked due to SOL/IDER session.\n");
636 	}
637 
638 	/*
639 	 * Start from a known state, this is important in reading the
640 	 * nvm and mac from that.
641 	 */
642 	e1000_reset_hw(&sc->hw);
643 
644 	/* Make sure we have a good EEPROM before we read from it */
645 	if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
646 		/*
647 		 * Some PCI-E parts fail the first check due to
648 		 * the link being in sleep state, call it again,
649 		 * if it fails a second time its a real issue.
650 		 */
651 		if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
652 			device_printf(dev,
653 			    "The EEPROM Checksum Is Not Valid\n");
654 			error = EIO;
655 			goto fail;
656 		}
657 	}
658 
659 	/* Copy the permanent MAC address out of the EEPROM */
660 	if (e1000_read_mac_addr(&sc->hw) < 0) {
661 		device_printf(dev, "EEPROM read error while reading MAC"
662 		    " address\n");
663 		error = EIO;
664 		goto fail;
665 	}
666 	if (!emx_is_valid_eaddr(sc->hw.mac.addr)) {
667 		device_printf(dev, "Invalid MAC address\n");
668 		error = EIO;
669 		goto fail;
670 	}
671 
672 	/* Determine if we have to control management hardware */
673 	if (e1000_enable_mng_pass_thru(&sc->hw))
674 		sc->flags |= EMX_FLAG_HAS_MGMT;
675 
676 	/*
677 	 * Setup Wake-on-Lan
678 	 */
679 	apme_mask = EMX_EEPROM_APME;
680 	eeprom_data = 0;
681 	switch (sc->hw.mac.type) {
682 	case e1000_82573:
683 		sc->flags |= EMX_FLAG_HAS_AMT;
684 		/* FALL THROUGH */
685 
686 	case e1000_82571:
687 	case e1000_82572:
688 	case e1000_80003es2lan:
689 		if (sc->hw.bus.func == 1) {
690 			e1000_read_nvm(&sc->hw,
691 			    NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
692 		} else {
693 			e1000_read_nvm(&sc->hw,
694 			    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
695 		}
696 		break;
697 
698 	default:
699 		e1000_read_nvm(&sc->hw,
700 		    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
701 		break;
702 	}
703 	if (eeprom_data & apme_mask)
704 		sc->wol = E1000_WUFC_MAG | E1000_WUFC_MC;
705 
706 	/*
707          * We have the eeprom settings, now apply the special cases
708          * where the eeprom may be wrong or the board won't support
709          * wake on lan on a particular port
710 	 */
711 	device_id = pci_get_device(dev);
712         switch (device_id) {
713 	case E1000_DEV_ID_82571EB_FIBER:
714 		/*
715 		 * Wake events only supported on port A for dual fiber
716 		 * regardless of eeprom setting
717 		 */
718 		if (E1000_READ_REG(&sc->hw, E1000_STATUS) &
719 		    E1000_STATUS_FUNC_1)
720 			sc->wol = 0;
721 		break;
722 
723 	case E1000_DEV_ID_82571EB_QUAD_COPPER:
724 	case E1000_DEV_ID_82571EB_QUAD_FIBER:
725 	case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
726                 /* if quad port sc, disable WoL on all but port A */
727 		if (emx_global_quad_port_a != 0)
728 			sc->wol = 0;
729 		/* Reset for multiple quad port adapters */
730 		if (++emx_global_quad_port_a == 4)
731 			emx_global_quad_port_a = 0;
732                 break;
733 	}
734 
735 	/* XXX disable wol */
736 	sc->wol = 0;
737 
738 #ifdef IFPOLL_ENABLE
739 	/*
740 	 * NPOLLING RX CPU offset
741 	 */
742 	if (sc->rx_ring_cnt == ncpus2) {
743 		offset = 0;
744 	} else {
745 		offset_def = (sc->rx_ring_cnt * device_get_unit(dev)) % ncpus2;
746 		offset = device_getenv_int(dev, "npoll.rxoff", offset_def);
747 		if (offset >= ncpus2 ||
748 		    offset % sc->rx_ring_cnt != 0) {
749 			device_printf(dev, "invalid npoll.rxoff %d, use %d\n",
750 			    offset, offset_def);
751 			offset = offset_def;
752 		}
753 	}
754 	sc->rx_npoll_off = offset;
755 
756 	/*
757 	 * NPOLLING TX CPU offset
758 	 */
759 	if (sc->tx_ring_cnt == ncpus2) {
760 		offset = 0;
761 	} else {
762 		offset_def = (sc->tx_ring_cnt * device_get_unit(dev)) % ncpus2;
763 		offset = device_getenv_int(dev, "npoll.txoff", offset_def);
764 		if (offset >= ncpus2 ||
765 		    offset % sc->tx_ring_cnt != 0) {
766 			device_printf(dev, "invalid npoll.txoff %d, use %d\n",
767 			    offset, offset_def);
768 			offset = offset_def;
769 		}
770 	}
771 	sc->tx_npoll_off = offset;
772 #endif
773 
774 	/* Setup OS specific network interface */
775 	emx_setup_ifp(sc);
776 
777 	/* Add sysctl tree, must after em_setup_ifp() */
778 	emx_add_sysctl(sc);
779 
780 	/* Reset the hardware */
781 	error = emx_reset(sc);
782 	if (error) {
783 		device_printf(dev, "Unable to reset the hardware\n");
784 		goto fail;
785 	}
786 
787 	/* Initialize statistics */
788 	emx_update_stats(sc);
789 
790 	sc->hw.mac.get_link_status = 1;
791 	emx_update_link_status(sc);
792 
793 	/* Non-AMT based hardware can now take control from firmware */
794 	if ((sc->flags & (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT)) ==
795 	    EMX_FLAG_HAS_MGMT)
796 		emx_get_hw_control(sc);
797 
798 	/*
799 	 * Missing Interrupt Following ICR read:
800 	 *
801 	 * 82571/82572 specification update errata #76
802 	 * 82573 specification update errata #31
803 	 * 82574 specification update errata #12
804 	 */
805 	intr_func = emx_intr;
806 	if ((sc->flags & EMX_FLAG_SHARED_INTR) &&
807 	    (sc->hw.mac.type == e1000_82571 ||
808 	     sc->hw.mac.type == e1000_82572 ||
809 	     sc->hw.mac.type == e1000_82573 ||
810 	     sc->hw.mac.type == e1000_82574))
811 		intr_func = emx_intr_mask;
812 
813 	error = bus_setup_intr(dev, sc->intr_res, INTR_MPSAFE, intr_func, sc,
814 			       &sc->intr_tag, &sc->main_serialize);
815 	if (error) {
816 		device_printf(dev, "Failed to register interrupt handler");
817 		ether_ifdetach(&sc->arpcom.ac_if);
818 		goto fail;
819 	}
820 
821 	sc->tx_ring_inuse = emx_get_txring_inuse(sc, FALSE);
822 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
823 		struct ifaltq_subque *ifsq = ifq_get_subq(&ifp->if_snd, i);
824 		struct emx_txdata *tdata = &sc->tx_data[i];
825 
826 		ifsq_set_cpuid(ifsq, rman_get_cpuid(sc->intr_res));
827 		ifsq_set_priv(ifsq, tdata);
828 		tdata->ifsq = ifsq;
829 
830 		ifsq_watchdog_init(&tdata->tx_watchdog, ifsq, emx_watchdog);
831 	}
832 	return (0);
833 fail:
834 	emx_detach(dev);
835 	return (error);
836 }
837 
838 static int
839 emx_detach(device_t dev)
840 {
841 	struct emx_softc *sc = device_get_softc(dev);
842 
843 	if (device_is_attached(dev)) {
844 		struct ifnet *ifp = &sc->arpcom.ac_if;
845 
846 		ifnet_serialize_all(ifp);
847 
848 		emx_stop(sc);
849 
850 		e1000_phy_hw_reset(&sc->hw);
851 
852 		emx_rel_mgmt(sc);
853 		emx_rel_hw_control(sc);
854 
855 		if (sc->wol) {
856 			E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
857 			E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
858 			emx_enable_wol(dev);
859 		}
860 
861 		bus_teardown_intr(dev, sc->intr_res, sc->intr_tag);
862 
863 		ifnet_deserialize_all(ifp);
864 
865 		ether_ifdetach(ifp);
866 	} else if (sc->memory != NULL) {
867 		emx_rel_hw_control(sc);
868 	}
869 	bus_generic_detach(dev);
870 
871 	if (sc->intr_res != NULL) {
872 		bus_release_resource(dev, SYS_RES_IRQ, sc->intr_rid,
873 				     sc->intr_res);
874 	}
875 
876 	if (sc->intr_type == PCI_INTR_TYPE_MSI)
877 		pci_release_msi(dev);
878 
879 	if (sc->memory != NULL) {
880 		bus_release_resource(dev, SYS_RES_MEMORY, sc->memory_rid,
881 				     sc->memory);
882 	}
883 
884 	emx_dma_free(sc);
885 
886 	/* Free sysctl tree */
887 	if (sc->sysctl_tree != NULL)
888 		sysctl_ctx_free(&sc->sysctl_ctx);
889 
890 	if (sc->mta != NULL)
891 		kfree(sc->mta, M_DEVBUF);
892 
893 	return (0);
894 }
895 
896 static int
897 emx_shutdown(device_t dev)
898 {
899 	return emx_suspend(dev);
900 }
901 
902 static int
903 emx_suspend(device_t dev)
904 {
905 	struct emx_softc *sc = device_get_softc(dev);
906 	struct ifnet *ifp = &sc->arpcom.ac_if;
907 
908 	ifnet_serialize_all(ifp);
909 
910 	emx_stop(sc);
911 
912 	emx_rel_mgmt(sc);
913 	emx_rel_hw_control(sc);
914 
915 	if (sc->wol) {
916 		E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
917 		E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
918 		emx_enable_wol(dev);
919 	}
920 
921 	ifnet_deserialize_all(ifp);
922 
923 	return bus_generic_suspend(dev);
924 }
925 
926 static int
927 emx_resume(device_t dev)
928 {
929 	struct emx_softc *sc = device_get_softc(dev);
930 	struct ifnet *ifp = &sc->arpcom.ac_if;
931 	int i;
932 
933 	ifnet_serialize_all(ifp);
934 
935 	emx_init(sc);
936 	emx_get_mgmt(sc);
937 	for (i = 0; i < sc->tx_ring_inuse; ++i)
938 		ifsq_devstart_sched(sc->tx_data[i].ifsq);
939 
940 	ifnet_deserialize_all(ifp);
941 
942 	return bus_generic_resume(dev);
943 }
944 
945 static void
946 emx_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
947 {
948 	struct emx_softc *sc = ifp->if_softc;
949 	struct emx_txdata *tdata = ifsq_get_priv(ifsq);
950 	struct mbuf *m_head;
951 	int idx = -1, nsegs = 0;
952 
953 	KKASSERT(tdata->ifsq == ifsq);
954 	ASSERT_SERIALIZED(&tdata->tx_serialize);
955 
956 	if ((ifp->if_flags & IFF_RUNNING) == 0 || ifsq_is_oactive(ifsq))
957 		return;
958 
959 	if (!sc->link_active || (tdata->tx_flags & EMX_TXFLAG_ENABLED) == 0) {
960 		ifsq_purge(ifsq);
961 		return;
962 	}
963 
964 	while (!ifsq_is_empty(ifsq)) {
965 		/* Now do we at least have a minimal? */
966 		if (EMX_IS_OACTIVE(tdata)) {
967 			emx_tx_collect(tdata);
968 			if (EMX_IS_OACTIVE(tdata)) {
969 				ifsq_set_oactive(ifsq);
970 				break;
971 			}
972 		}
973 
974 		logif(pkt_txqueue);
975 		m_head = ifsq_dequeue(ifsq, NULL);
976 		if (m_head == NULL)
977 			break;
978 
979 		if (emx_encap(tdata, &m_head, &nsegs, &idx)) {
980 			ifp->if_oerrors++;
981 			emx_tx_collect(tdata);
982 			continue;
983 		}
984 
985 		if (nsegs >= tdata->tx_wreg_nsegs) {
986 			E1000_WRITE_REG(&sc->hw, E1000_TDT(tdata->idx), idx);
987 			nsegs = 0;
988 			idx = -1;
989 		}
990 
991 		/* Send a copy of the frame to the BPF listener */
992 		ETHER_BPF_MTAP(ifp, m_head);
993 
994 		/* Set timeout in case hardware has problems transmitting. */
995 		tdata->tx_watchdog.wd_timer = EMX_TX_TIMEOUT;
996 	}
997 	if (idx >= 0)
998 		E1000_WRITE_REG(&sc->hw, E1000_TDT(tdata->idx), idx);
999 }
1000 
1001 static int
1002 emx_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
1003 {
1004 	struct emx_softc *sc = ifp->if_softc;
1005 	struct ifreq *ifr = (struct ifreq *)data;
1006 	uint16_t eeprom_data = 0;
1007 	int max_frame_size, mask, reinit;
1008 	int error = 0;
1009 
1010 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1011 
1012 	switch (command) {
1013 	case SIOCSIFMTU:
1014 		switch (sc->hw.mac.type) {
1015 		case e1000_82573:
1016 			/*
1017 			 * 82573 only supports jumbo frames
1018 			 * if ASPM is disabled.
1019 			 */
1020 			e1000_read_nvm(&sc->hw, NVM_INIT_3GIO_3, 1,
1021 				       &eeprom_data);
1022 			if (eeprom_data & NVM_WORD1A_ASPM_MASK) {
1023 				max_frame_size = ETHER_MAX_LEN;
1024 				break;
1025 			}
1026 			/* FALL THROUGH */
1027 
1028 		/* Limit Jumbo Frame size */
1029 		case e1000_82571:
1030 		case e1000_82572:
1031 		case e1000_82574:
1032 		case e1000_80003es2lan:
1033 			max_frame_size = 9234;
1034 			break;
1035 
1036 		default:
1037 			max_frame_size = MAX_JUMBO_FRAME_SIZE;
1038 			break;
1039 		}
1040 		if (ifr->ifr_mtu > max_frame_size - ETHER_HDR_LEN -
1041 		    ETHER_CRC_LEN) {
1042 			error = EINVAL;
1043 			break;
1044 		}
1045 
1046 		ifp->if_mtu = ifr->ifr_mtu;
1047 		sc->max_frame_size = ifp->if_mtu + ETHER_HDR_LEN +
1048 				     ETHER_CRC_LEN;
1049 
1050 		if (ifp->if_flags & IFF_RUNNING)
1051 			emx_init(sc);
1052 		break;
1053 
1054 	case SIOCSIFFLAGS:
1055 		if (ifp->if_flags & IFF_UP) {
1056 			if ((ifp->if_flags & IFF_RUNNING)) {
1057 				if ((ifp->if_flags ^ sc->if_flags) &
1058 				    (IFF_PROMISC | IFF_ALLMULTI)) {
1059 					emx_disable_promisc(sc);
1060 					emx_set_promisc(sc);
1061 				}
1062 			} else {
1063 				emx_init(sc);
1064 			}
1065 		} else if (ifp->if_flags & IFF_RUNNING) {
1066 			emx_stop(sc);
1067 		}
1068 		sc->if_flags = ifp->if_flags;
1069 		break;
1070 
1071 	case SIOCADDMULTI:
1072 	case SIOCDELMULTI:
1073 		if (ifp->if_flags & IFF_RUNNING) {
1074 			emx_disable_intr(sc);
1075 			emx_set_multi(sc);
1076 #ifdef IFPOLL_ENABLE
1077 			if (!(ifp->if_flags & IFF_NPOLLING))
1078 #endif
1079 				emx_enable_intr(sc);
1080 		}
1081 		break;
1082 
1083 	case SIOCSIFMEDIA:
1084 		/* Check SOL/IDER usage */
1085 		if (e1000_check_reset_block(&sc->hw)) {
1086 			device_printf(sc->dev, "Media change is"
1087 			    " blocked due to SOL/IDER session.\n");
1088 			break;
1089 		}
1090 		/* FALL THROUGH */
1091 
1092 	case SIOCGIFMEDIA:
1093 		error = ifmedia_ioctl(ifp, ifr, &sc->media, command);
1094 		break;
1095 
1096 	case SIOCSIFCAP:
1097 		reinit = 0;
1098 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1099 		if (mask & IFCAP_RXCSUM) {
1100 			ifp->if_capenable ^= IFCAP_RXCSUM;
1101 			reinit = 1;
1102 		}
1103 		if (mask & IFCAP_VLAN_HWTAGGING) {
1104 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1105 			reinit = 1;
1106 		}
1107 		if (mask & IFCAP_TXCSUM) {
1108 			ifp->if_capenable ^= IFCAP_TXCSUM;
1109 			if (ifp->if_capenable & IFCAP_TXCSUM)
1110 				ifp->if_hwassist |= EMX_CSUM_FEATURES;
1111 			else
1112 				ifp->if_hwassist &= ~EMX_CSUM_FEATURES;
1113 		}
1114 		if (mask & IFCAP_TSO) {
1115 			ifp->if_capenable ^= IFCAP_TSO;
1116 			if (ifp->if_capenable & IFCAP_TSO)
1117 				ifp->if_hwassist |= CSUM_TSO;
1118 			else
1119 				ifp->if_hwassist &= ~CSUM_TSO;
1120 		}
1121 		if (mask & IFCAP_RSS)
1122 			ifp->if_capenable ^= IFCAP_RSS;
1123 		if (reinit && (ifp->if_flags & IFF_RUNNING))
1124 			emx_init(sc);
1125 		break;
1126 
1127 	default:
1128 		error = ether_ioctl(ifp, command, data);
1129 		break;
1130 	}
1131 	return (error);
1132 }
1133 
1134 static void
1135 emx_watchdog(struct ifaltq_subque *ifsq)
1136 {
1137 	struct emx_txdata *tdata = ifsq_get_priv(ifsq);
1138 	struct ifnet *ifp = ifsq_get_ifp(ifsq);
1139 	struct emx_softc *sc = ifp->if_softc;
1140 	int i;
1141 
1142 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1143 
1144 	/*
1145 	 * The timer is set to 5 every time start queues a packet.
1146 	 * Then txeof keeps resetting it as long as it cleans at
1147 	 * least one descriptor.
1148 	 * Finally, anytime all descriptors are clean the timer is
1149 	 * set to 0.
1150 	 */
1151 
1152 	if (E1000_READ_REG(&sc->hw, E1000_TDT(tdata->idx)) ==
1153 	    E1000_READ_REG(&sc->hw, E1000_TDH(tdata->idx))) {
1154 		/*
1155 		 * If we reach here, all TX jobs are completed and
1156 		 * the TX engine should have been idled for some time.
1157 		 * We don't need to call ifsq_devstart_sched() here.
1158 		 */
1159 		ifsq_clr_oactive(ifsq);
1160 		tdata->tx_watchdog.wd_timer = 0;
1161 		return;
1162 	}
1163 
1164 	/*
1165 	 * If we are in this routine because of pause frames, then
1166 	 * don't reset the hardware.
1167 	 */
1168 	if (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_TXOFF) {
1169 		tdata->tx_watchdog.wd_timer = EMX_TX_TIMEOUT;
1170 		return;
1171 	}
1172 
1173 	if_printf(ifp, "TX %d watchdog timeout -- resetting\n", tdata->idx);
1174 
1175 	ifp->if_oerrors++;
1176 
1177 	emx_init(sc);
1178 	for (i = 0; i < sc->tx_ring_inuse; ++i)
1179 		ifsq_devstart_sched(sc->tx_data[i].ifsq);
1180 }
1181 
1182 static void
1183 emx_init(void *xsc)
1184 {
1185 	struct emx_softc *sc = xsc;
1186 	struct ifnet *ifp = &sc->arpcom.ac_if;
1187 	device_t dev = sc->dev;
1188 	boolean_t polling;
1189 	int i;
1190 
1191 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1192 
1193 	emx_stop(sc);
1194 
1195 	/* Get the latest mac address, User can use a LAA */
1196         bcopy(IF_LLADDR(ifp), sc->hw.mac.addr, ETHER_ADDR_LEN);
1197 
1198 	/* Put the address into the Receive Address Array */
1199 	e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1200 
1201 	/*
1202 	 * With the 82571 sc, RAR[0] may be overwritten
1203 	 * when the other port is reset, we make a duplicate
1204 	 * in RAR[14] for that eventuality, this assures
1205 	 * the interface continues to function.
1206 	 */
1207 	if (sc->hw.mac.type == e1000_82571) {
1208 		e1000_set_laa_state_82571(&sc->hw, TRUE);
1209 		e1000_rar_set(&sc->hw, sc->hw.mac.addr,
1210 		    E1000_RAR_ENTRIES - 1);
1211 	}
1212 
1213 	/* Initialize the hardware */
1214 	if (emx_reset(sc)) {
1215 		device_printf(dev, "Unable to reset the hardware\n");
1216 		/* XXX emx_stop()? */
1217 		return;
1218 	}
1219 	emx_update_link_status(sc);
1220 
1221 	/* Setup VLAN support, basic and offload if available */
1222 	E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1223 
1224 	if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1225 		uint32_t ctrl;
1226 
1227 		ctrl = E1000_READ_REG(&sc->hw, E1000_CTRL);
1228 		ctrl |= E1000_CTRL_VME;
1229 		E1000_WRITE_REG(&sc->hw, E1000_CTRL, ctrl);
1230 	}
1231 
1232 	/* Configure for OS presence */
1233 	emx_get_mgmt(sc);
1234 
1235 	polling = FALSE;
1236 #ifdef IFPOLL_ENABLE
1237 	if (ifp->if_flags & IFF_NPOLLING)
1238 		polling = TRUE;
1239 #endif
1240 	sc->tx_ring_inuse = emx_get_txring_inuse(sc, polling);
1241 	ifq_set_subq_mask(&ifp->if_snd, sc->tx_ring_inuse - 1);
1242 
1243 	/* Prepare transmit descriptors and buffers */
1244 	for (i = 0; i < sc->tx_ring_inuse; ++i)
1245 		emx_init_tx_ring(&sc->tx_data[i]);
1246 	emx_init_tx_unit(sc);
1247 
1248 	/* Setup Multicast table */
1249 	emx_set_multi(sc);
1250 
1251 	/* Prepare receive descriptors and buffers */
1252 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
1253 		if (emx_init_rx_ring(&sc->rx_data[i])) {
1254 			device_printf(dev,
1255 			    "Could not setup receive structures\n");
1256 			emx_stop(sc);
1257 			return;
1258 		}
1259 	}
1260 	emx_init_rx_unit(sc);
1261 
1262 	/* Don't lose promiscuous settings */
1263 	emx_set_promisc(sc);
1264 
1265 	ifp->if_flags |= IFF_RUNNING;
1266 	for (i = 0; i < sc->tx_ring_inuse; ++i) {
1267 		ifsq_clr_oactive(sc->tx_data[i].ifsq);
1268 		ifsq_watchdog_start(&sc->tx_data[i].tx_watchdog);
1269 	}
1270 
1271 	callout_reset(&sc->timer, hz, emx_timer, sc);
1272 	e1000_clear_hw_cntrs_base_generic(&sc->hw);
1273 
1274 	/* MSI/X configuration for 82574 */
1275 	if (sc->hw.mac.type == e1000_82574) {
1276 		int tmp;
1277 
1278 		tmp = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
1279 		tmp |= E1000_CTRL_EXT_PBA_CLR;
1280 		E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT, tmp);
1281 		/*
1282 		 * XXX MSIX
1283 		 * Set the IVAR - interrupt vector routing.
1284 		 * Each nibble represents a vector, high bit
1285 		 * is enable, other 3 bits are the MSIX table
1286 		 * entry, we map RXQ0 to 0, TXQ0 to 1, and
1287 		 * Link (other) to 2, hence the magic number.
1288 		 */
1289 		E1000_WRITE_REG(&sc->hw, E1000_IVAR, 0x800A0908);
1290 	}
1291 
1292 	/*
1293 	 * Only enable interrupts if we are not polling, make sure
1294 	 * they are off otherwise.
1295 	 */
1296 	if (polling)
1297 		emx_disable_intr(sc);
1298 	else
1299 		emx_enable_intr(sc);
1300 
1301 	/* AMT based hardware can now take control from firmware */
1302 	if ((sc->flags & (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT)) ==
1303 	    (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT))
1304 		emx_get_hw_control(sc);
1305 }
1306 
1307 static void
1308 emx_intr(void *xsc)
1309 {
1310 	emx_intr_body(xsc, TRUE);
1311 }
1312 
1313 static void
1314 emx_intr_body(struct emx_softc *sc, boolean_t chk_asserted)
1315 {
1316 	struct ifnet *ifp = &sc->arpcom.ac_if;
1317 	uint32_t reg_icr;
1318 
1319 	logif(intr_beg);
1320 	ASSERT_SERIALIZED(&sc->main_serialize);
1321 
1322 	reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
1323 
1324 	if (chk_asserted && (reg_icr & E1000_ICR_INT_ASSERTED) == 0) {
1325 		logif(intr_end);
1326 		return;
1327 	}
1328 
1329 	/*
1330 	 * XXX: some laptops trigger several spurious interrupts
1331 	 * on emx(4) when in the resume cycle. The ICR register
1332 	 * reports all-ones value in this case. Processing such
1333 	 * interrupts would lead to a freeze. I don't know why.
1334 	 */
1335 	if (reg_icr == 0xffffffff) {
1336 		logif(intr_end);
1337 		return;
1338 	}
1339 
1340 	if (ifp->if_flags & IFF_RUNNING) {
1341 		if (reg_icr &
1342 		    (E1000_ICR_RXT0 | E1000_ICR_RXDMT0 | E1000_ICR_RXO)) {
1343 			int i;
1344 
1345 			for (i = 0; i < sc->rx_ring_cnt; ++i) {
1346 				lwkt_serialize_enter(
1347 				&sc->rx_data[i].rx_serialize);
1348 				emx_rxeof(&sc->rx_data[i], -1);
1349 				lwkt_serialize_exit(
1350 				&sc->rx_data[i].rx_serialize);
1351 			}
1352 		}
1353 		if (reg_icr & E1000_ICR_TXDW) {
1354 			struct emx_txdata *tdata = &sc->tx_data[0];
1355 
1356 			lwkt_serialize_enter(&tdata->tx_serialize);
1357 			emx_txeof(tdata);
1358 			if (!ifsq_is_empty(tdata->ifsq))
1359 				ifsq_devstart(tdata->ifsq);
1360 			lwkt_serialize_exit(&tdata->tx_serialize);
1361 		}
1362 	}
1363 
1364 	/* Link status change */
1365 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1366 		emx_serialize_skipmain(sc);
1367 
1368 		callout_stop(&sc->timer);
1369 		sc->hw.mac.get_link_status = 1;
1370 		emx_update_link_status(sc);
1371 
1372 		/* Deal with TX cruft when link lost */
1373 		emx_tx_purge(sc);
1374 
1375 		callout_reset(&sc->timer, hz, emx_timer, sc);
1376 
1377 		emx_deserialize_skipmain(sc);
1378 	}
1379 
1380 	if (reg_icr & E1000_ICR_RXO)
1381 		sc->rx_overruns++;
1382 
1383 	logif(intr_end);
1384 }
1385 
1386 static void
1387 emx_intr_mask(void *xsc)
1388 {
1389 	struct emx_softc *sc = xsc;
1390 
1391 	E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
1392 	/*
1393 	 * NOTE:
1394 	 * ICR.INT_ASSERTED bit will never be set if IMS is 0,
1395 	 * so don't check it.
1396 	 */
1397 	emx_intr_body(sc, FALSE);
1398 	E1000_WRITE_REG(&sc->hw, E1000_IMS, IMS_ENABLE_MASK);
1399 }
1400 
1401 static void
1402 emx_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1403 {
1404 	struct emx_softc *sc = ifp->if_softc;
1405 
1406 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1407 
1408 	emx_update_link_status(sc);
1409 
1410 	ifmr->ifm_status = IFM_AVALID;
1411 	ifmr->ifm_active = IFM_ETHER;
1412 
1413 	if (!sc->link_active)
1414 		return;
1415 
1416 	ifmr->ifm_status |= IFM_ACTIVE;
1417 
1418 	if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1419 	    sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1420 		ifmr->ifm_active |= IFM_1000_SX | IFM_FDX;
1421 	} else {
1422 		switch (sc->link_speed) {
1423 		case 10:
1424 			ifmr->ifm_active |= IFM_10_T;
1425 			break;
1426 		case 100:
1427 			ifmr->ifm_active |= IFM_100_TX;
1428 			break;
1429 
1430 		case 1000:
1431 			ifmr->ifm_active |= IFM_1000_T;
1432 			break;
1433 		}
1434 		if (sc->link_duplex == FULL_DUPLEX)
1435 			ifmr->ifm_active |= IFM_FDX;
1436 		else
1437 			ifmr->ifm_active |= IFM_HDX;
1438 	}
1439 }
1440 
1441 static int
1442 emx_media_change(struct ifnet *ifp)
1443 {
1444 	struct emx_softc *sc = ifp->if_softc;
1445 	struct ifmedia *ifm = &sc->media;
1446 
1447 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1448 
1449 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1450 		return (EINVAL);
1451 
1452 	switch (IFM_SUBTYPE(ifm->ifm_media)) {
1453 	case IFM_AUTO:
1454 		sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1455 		sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
1456 		break;
1457 
1458 	case IFM_1000_LX:
1459 	case IFM_1000_SX:
1460 	case IFM_1000_T:
1461 		sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1462 		sc->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1463 		break;
1464 
1465 	case IFM_100_TX:
1466 		sc->hw.mac.autoneg = FALSE;
1467 		sc->hw.phy.autoneg_advertised = 0;
1468 		if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1469 			sc->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1470 		else
1471 			sc->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1472 		break;
1473 
1474 	case IFM_10_T:
1475 		sc->hw.mac.autoneg = FALSE;
1476 		sc->hw.phy.autoneg_advertised = 0;
1477 		if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1478 			sc->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1479 		else
1480 			sc->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1481 		break;
1482 
1483 	default:
1484 		if_printf(ifp, "Unsupported media type\n");
1485 		break;
1486 	}
1487 
1488 	emx_init(sc);
1489 
1490 	return (0);
1491 }
1492 
1493 static int
1494 emx_encap(struct emx_txdata *tdata, struct mbuf **m_headp,
1495     int *segs_used, int *idx)
1496 {
1497 	bus_dma_segment_t segs[EMX_MAX_SCATTER];
1498 	bus_dmamap_t map;
1499 	struct emx_txbuf *tx_buffer, *tx_buffer_mapped;
1500 	struct e1000_tx_desc *ctxd = NULL;
1501 	struct mbuf *m_head = *m_headp;
1502 	uint32_t txd_upper, txd_lower, cmd = 0;
1503 	int maxsegs, nsegs, i, j, first, last = 0, error;
1504 
1505 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1506 		error = emx_tso_pullup(tdata, m_headp);
1507 		if (error)
1508 			return error;
1509 		m_head = *m_headp;
1510 	}
1511 
1512 	txd_upper = txd_lower = 0;
1513 
1514 	/*
1515 	 * Capture the first descriptor index, this descriptor
1516 	 * will have the index of the EOP which is the only one
1517 	 * that now gets a DONE bit writeback.
1518 	 */
1519 	first = tdata->next_avail_tx_desc;
1520 	tx_buffer = &tdata->tx_buf[first];
1521 	tx_buffer_mapped = tx_buffer;
1522 	map = tx_buffer->map;
1523 
1524 	maxsegs = tdata->num_tx_desc_avail - EMX_TX_RESERVED;
1525 	KASSERT(maxsegs >= tdata->spare_tx_desc, ("not enough spare TX desc"));
1526 	if (maxsegs > EMX_MAX_SCATTER)
1527 		maxsegs = EMX_MAX_SCATTER;
1528 
1529 	error = bus_dmamap_load_mbuf_defrag(tdata->txtag, map, m_headp,
1530 			segs, maxsegs, &nsegs, BUS_DMA_NOWAIT);
1531 	if (error) {
1532 		m_freem(*m_headp);
1533 		*m_headp = NULL;
1534 		return error;
1535 	}
1536         bus_dmamap_sync(tdata->txtag, map, BUS_DMASYNC_PREWRITE);
1537 
1538 	m_head = *m_headp;
1539 	tdata->tx_nsegs += nsegs;
1540 	*segs_used += nsegs;
1541 
1542 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1543 		/* TSO will consume one TX desc */
1544 		i = emx_tso_setup(tdata, m_head, &txd_upper, &txd_lower);
1545 		tdata->tx_nsegs += i;
1546 		*segs_used += i;
1547 	} else if (m_head->m_pkthdr.csum_flags & EMX_CSUM_FEATURES) {
1548 		/* TX csum offloading will consume one TX desc */
1549 		i = emx_txcsum(tdata, m_head, &txd_upper, &txd_lower);
1550 		tdata->tx_nsegs += i;
1551 		*segs_used += i;
1552 	}
1553 	i = tdata->next_avail_tx_desc;
1554 
1555 	/* Set up our transmit descriptors */
1556 	for (j = 0; j < nsegs; j++) {
1557 		tx_buffer = &tdata->tx_buf[i];
1558 		ctxd = &tdata->tx_desc_base[i];
1559 
1560 		ctxd->buffer_addr = htole64(segs[j].ds_addr);
1561 		ctxd->lower.data = htole32(E1000_TXD_CMD_IFCS |
1562 					   txd_lower | segs[j].ds_len);
1563 		ctxd->upper.data = htole32(txd_upper);
1564 
1565 		last = i;
1566 		if (++i == tdata->num_tx_desc)
1567 			i = 0;
1568 	}
1569 
1570 	tdata->next_avail_tx_desc = i;
1571 
1572 	KKASSERT(tdata->num_tx_desc_avail > nsegs);
1573 	tdata->num_tx_desc_avail -= nsegs;
1574 
1575         /* Handle VLAN tag */
1576 	if (m_head->m_flags & M_VLANTAG) {
1577 		/* Set the vlan id. */
1578 		ctxd->upper.fields.special =
1579 		    htole16(m_head->m_pkthdr.ether_vlantag);
1580 
1581 		/* Tell hardware to add tag */
1582 		ctxd->lower.data |= htole32(E1000_TXD_CMD_VLE);
1583 	}
1584 
1585 	tx_buffer->m_head = m_head;
1586 	tx_buffer_mapped->map = tx_buffer->map;
1587 	tx_buffer->map = map;
1588 
1589 	if (tdata->tx_nsegs >= tdata->tx_intr_nsegs) {
1590 		tdata->tx_nsegs = 0;
1591 
1592 		/*
1593 		 * Report Status (RS) is turned on
1594 		 * every tx_intr_nsegs descriptors.
1595 		 */
1596 		cmd = E1000_TXD_CMD_RS;
1597 
1598 		/*
1599 		 * Keep track of the descriptor, which will
1600 		 * be written back by hardware.
1601 		 */
1602 		tdata->tx_dd[tdata->tx_dd_tail] = last;
1603 		EMX_INC_TXDD_IDX(tdata->tx_dd_tail);
1604 		KKASSERT(tdata->tx_dd_tail != tdata->tx_dd_head);
1605 	}
1606 
1607 	/*
1608 	 * Last Descriptor of Packet needs End Of Packet (EOP)
1609 	 */
1610 	ctxd->lower.data |= htole32(E1000_TXD_CMD_EOP | cmd);
1611 
1612 	/*
1613 	 * Defer TDT updating, until enough descriptors are setup
1614 	 */
1615 	*idx = i;
1616 
1617 #ifdef EMX_TSS_DEBUG
1618 	tdata->tx_pkts++;
1619 #endif
1620 
1621 	return (0);
1622 }
1623 
1624 static void
1625 emx_set_promisc(struct emx_softc *sc)
1626 {
1627 	struct ifnet *ifp = &sc->arpcom.ac_if;
1628 	uint32_t reg_rctl;
1629 
1630 	reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1631 
1632 	if (ifp->if_flags & IFF_PROMISC) {
1633 		reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
1634 		/* Turn this on if you want to see bad packets */
1635 		if (emx_debug_sbp)
1636 			reg_rctl |= E1000_RCTL_SBP;
1637 		E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1638 	} else if (ifp->if_flags & IFF_ALLMULTI) {
1639 		reg_rctl |= E1000_RCTL_MPE;
1640 		reg_rctl &= ~E1000_RCTL_UPE;
1641 		E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1642 	}
1643 }
1644 
1645 static void
1646 emx_disable_promisc(struct emx_softc *sc)
1647 {
1648 	uint32_t reg_rctl;
1649 
1650 	reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1651 
1652 	reg_rctl &= ~E1000_RCTL_UPE;
1653 	reg_rctl &= ~E1000_RCTL_MPE;
1654 	reg_rctl &= ~E1000_RCTL_SBP;
1655 	E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1656 }
1657 
1658 static void
1659 emx_set_multi(struct emx_softc *sc)
1660 {
1661 	struct ifnet *ifp = &sc->arpcom.ac_if;
1662 	struct ifmultiaddr *ifma;
1663 	uint32_t reg_rctl = 0;
1664 	uint8_t *mta;
1665 	int mcnt = 0;
1666 
1667 	mta = sc->mta;
1668 	bzero(mta, ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX);
1669 
1670 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1671 		if (ifma->ifma_addr->sa_family != AF_LINK)
1672 			continue;
1673 
1674 		if (mcnt == EMX_MCAST_ADDR_MAX)
1675 			break;
1676 
1677 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1678 		      &mta[mcnt * ETHER_ADDR_LEN], ETHER_ADDR_LEN);
1679 		mcnt++;
1680 	}
1681 
1682 	if (mcnt >= EMX_MCAST_ADDR_MAX) {
1683 		reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1684 		reg_rctl |= E1000_RCTL_MPE;
1685 		E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1686 	} else {
1687 		e1000_update_mc_addr_list(&sc->hw, mta, mcnt);
1688 	}
1689 }
1690 
1691 /*
1692  * This routine checks for link status and updates statistics.
1693  */
1694 static void
1695 emx_timer(void *xsc)
1696 {
1697 	struct emx_softc *sc = xsc;
1698 	struct ifnet *ifp = &sc->arpcom.ac_if;
1699 
1700 	lwkt_serialize_enter(&sc->main_serialize);
1701 
1702 	emx_update_link_status(sc);
1703 	emx_update_stats(sc);
1704 
1705 	/* Reset LAA into RAR[0] on 82571 */
1706 	if (e1000_get_laa_state_82571(&sc->hw) == TRUE)
1707 		e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1708 
1709 	if (emx_display_debug_stats && (ifp->if_flags & IFF_RUNNING))
1710 		emx_print_hw_stats(sc);
1711 
1712 	emx_smartspeed(sc);
1713 
1714 	callout_reset(&sc->timer, hz, emx_timer, sc);
1715 
1716 	lwkt_serialize_exit(&sc->main_serialize);
1717 }
1718 
1719 static void
1720 emx_update_link_status(struct emx_softc *sc)
1721 {
1722 	struct e1000_hw *hw = &sc->hw;
1723 	struct ifnet *ifp = &sc->arpcom.ac_if;
1724 	device_t dev = sc->dev;
1725 	uint32_t link_check = 0;
1726 
1727 	/* Get the cached link value or read phy for real */
1728 	switch (hw->phy.media_type) {
1729 	case e1000_media_type_copper:
1730 		if (hw->mac.get_link_status) {
1731 			/* Do the work to read phy */
1732 			e1000_check_for_link(hw);
1733 			link_check = !hw->mac.get_link_status;
1734 			if (link_check) /* ESB2 fix */
1735 				e1000_cfg_on_link_up(hw);
1736 		} else {
1737 			link_check = TRUE;
1738 		}
1739 		break;
1740 
1741 	case e1000_media_type_fiber:
1742 		e1000_check_for_link(hw);
1743 		link_check = E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU;
1744 		break;
1745 
1746 	case e1000_media_type_internal_serdes:
1747 		e1000_check_for_link(hw);
1748 		link_check = sc->hw.mac.serdes_has_link;
1749 		break;
1750 
1751 	case e1000_media_type_unknown:
1752 	default:
1753 		break;
1754 	}
1755 
1756 	/* Now check for a transition */
1757 	if (link_check && sc->link_active == 0) {
1758 		e1000_get_speed_and_duplex(hw, &sc->link_speed,
1759 		    &sc->link_duplex);
1760 
1761 		/*
1762 		 * Check if we should enable/disable SPEED_MODE bit on
1763 		 * 82571EB/82572EI
1764 		 */
1765 		if (sc->link_speed != SPEED_1000 &&
1766 		    (hw->mac.type == e1000_82571 ||
1767 		     hw->mac.type == e1000_82572)) {
1768 			int tarc0;
1769 
1770 			tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
1771 			tarc0 &= ~EMX_TARC_SPEED_MODE;
1772 			E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
1773 		}
1774 		if (bootverbose) {
1775 			device_printf(dev, "Link is up %d Mbps %s\n",
1776 			    sc->link_speed,
1777 			    ((sc->link_duplex == FULL_DUPLEX) ?
1778 			    "Full Duplex" : "Half Duplex"));
1779 		}
1780 		sc->link_active = 1;
1781 		sc->smartspeed = 0;
1782 		ifp->if_baudrate = sc->link_speed * 1000000;
1783 		ifp->if_link_state = LINK_STATE_UP;
1784 		if_link_state_change(ifp);
1785 	} else if (!link_check && sc->link_active == 1) {
1786 		ifp->if_baudrate = sc->link_speed = 0;
1787 		sc->link_duplex = 0;
1788 		if (bootverbose)
1789 			device_printf(dev, "Link is Down\n");
1790 		sc->link_active = 0;
1791 		ifp->if_link_state = LINK_STATE_DOWN;
1792 		if_link_state_change(ifp);
1793 	}
1794 }
1795 
1796 static void
1797 emx_stop(struct emx_softc *sc)
1798 {
1799 	struct ifnet *ifp = &sc->arpcom.ac_if;
1800 	int i;
1801 
1802 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1803 
1804 	emx_disable_intr(sc);
1805 
1806 	callout_stop(&sc->timer);
1807 
1808 	ifp->if_flags &= ~IFF_RUNNING;
1809 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
1810 		struct emx_txdata *tdata = &sc->tx_data[i];
1811 
1812 		ifsq_clr_oactive(tdata->ifsq);
1813 		ifsq_watchdog_stop(&tdata->tx_watchdog);
1814 		tdata->tx_flags &= ~EMX_TXFLAG_ENABLED;
1815 	}
1816 
1817 	/*
1818 	 * Disable multiple receive queues.
1819 	 *
1820 	 * NOTE:
1821 	 * We should disable multiple receive queues before
1822 	 * resetting the hardware.
1823 	 */
1824 	E1000_WRITE_REG(&sc->hw, E1000_MRQC, 0);
1825 
1826 	e1000_reset_hw(&sc->hw);
1827 	E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1828 
1829 	for (i = 0; i < sc->tx_ring_cnt; ++i)
1830 		emx_free_tx_ring(&sc->tx_data[i]);
1831 	for (i = 0; i < sc->rx_ring_cnt; ++i)
1832 		emx_free_rx_ring(&sc->rx_data[i]);
1833 }
1834 
1835 static int
1836 emx_reset(struct emx_softc *sc)
1837 {
1838 	device_t dev = sc->dev;
1839 	uint16_t rx_buffer_size;
1840 	uint32_t pba;
1841 
1842 	/* Set up smart power down as default off on newer adapters. */
1843 	if (!emx_smart_pwr_down &&
1844 	    (sc->hw.mac.type == e1000_82571 ||
1845 	     sc->hw.mac.type == e1000_82572)) {
1846 		uint16_t phy_tmp = 0;
1847 
1848 		/* Speed up time to link by disabling smart power down. */
1849 		e1000_read_phy_reg(&sc->hw,
1850 		    IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
1851 		phy_tmp &= ~IGP02E1000_PM_SPD;
1852 		e1000_write_phy_reg(&sc->hw,
1853 		    IGP02E1000_PHY_POWER_MGMT, phy_tmp);
1854 	}
1855 
1856 	/*
1857 	 * Packet Buffer Allocation (PBA)
1858 	 * Writing PBA sets the receive portion of the buffer
1859 	 * the remainder is used for the transmit buffer.
1860 	 */
1861 	switch (sc->hw.mac.type) {
1862 	/* Total Packet Buffer on these is 48K */
1863 	case e1000_82571:
1864 	case e1000_82572:
1865 	case e1000_80003es2lan:
1866 		pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
1867 		break;
1868 
1869 	case e1000_82573: /* 82573: Total Packet Buffer is 32K */
1870 		pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
1871 		break;
1872 
1873 	case e1000_82574:
1874 		pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
1875 		break;
1876 
1877 	default:
1878 		/* Devices before 82547 had a Packet Buffer of 64K.   */
1879 		if (sc->max_frame_size > 8192)
1880 			pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
1881 		else
1882 			pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
1883 	}
1884 	E1000_WRITE_REG(&sc->hw, E1000_PBA, pba);
1885 
1886 	/*
1887 	 * These parameters control the automatic generation (Tx) and
1888 	 * response (Rx) to Ethernet PAUSE frames.
1889 	 * - High water mark should allow for at least two frames to be
1890 	 *   received after sending an XOFF.
1891 	 * - Low water mark works best when it is very near the high water mark.
1892 	 *   This allows the receiver to restart by sending XON when it has
1893 	 *   drained a bit. Here we use an arbitary value of 1500 which will
1894 	 *   restart after one full frame is pulled from the buffer. There
1895 	 *   could be several smaller frames in the buffer and if so they will
1896 	 *   not trigger the XON until their total number reduces the buffer
1897 	 *   by 1500.
1898 	 * - The pause time is fairly large at 1000 x 512ns = 512 usec.
1899 	 */
1900 	rx_buffer_size = (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) << 10;
1901 
1902 	sc->hw.fc.high_water = rx_buffer_size -
1903 			       roundup2(sc->max_frame_size, 1024);
1904 	sc->hw.fc.low_water = sc->hw.fc.high_water - 1500;
1905 
1906 	if (sc->hw.mac.type == e1000_80003es2lan)
1907 		sc->hw.fc.pause_time = 0xFFFF;
1908 	else
1909 		sc->hw.fc.pause_time = EMX_FC_PAUSE_TIME;
1910 	sc->hw.fc.send_xon = TRUE;
1911 	sc->hw.fc.requested_mode = e1000_fc_full;
1912 
1913 	/* Issue a global reset */
1914 	e1000_reset_hw(&sc->hw);
1915 	E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1916 	emx_disable_aspm(sc);
1917 
1918 	if (e1000_init_hw(&sc->hw) < 0) {
1919 		device_printf(dev, "Hardware Initialization Failed\n");
1920 		return (EIO);
1921 	}
1922 
1923 	E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1924 	e1000_get_phy_info(&sc->hw);
1925 	e1000_check_for_link(&sc->hw);
1926 
1927 	return (0);
1928 }
1929 
1930 static void
1931 emx_setup_ifp(struct emx_softc *sc)
1932 {
1933 	struct ifnet *ifp = &sc->arpcom.ac_if;
1934 
1935 	if_initname(ifp, device_get_name(sc->dev),
1936 		    device_get_unit(sc->dev));
1937 	ifp->if_softc = sc;
1938 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1939 	ifp->if_init =  emx_init;
1940 	ifp->if_ioctl = emx_ioctl;
1941 	ifp->if_start = emx_start;
1942 #ifdef IFPOLL_ENABLE
1943 	ifp->if_npoll = emx_npoll;
1944 #endif
1945 	ifp->if_serialize = emx_serialize;
1946 	ifp->if_deserialize = emx_deserialize;
1947 	ifp->if_tryserialize = emx_tryserialize;
1948 #ifdef INVARIANTS
1949 	ifp->if_serialize_assert = emx_serialize_assert;
1950 #endif
1951 
1952 	ifq_set_maxlen(&ifp->if_snd, sc->tx_data[0].num_tx_desc - 1);
1953 	ifq_set_ready(&ifp->if_snd);
1954 	ifq_set_subq_cnt(&ifp->if_snd, sc->tx_ring_cnt);
1955 
1956 	ifp->if_mapsubq = ifq_mapsubq_mask;
1957 	ifq_set_subq_mask(&ifp->if_snd, 0);
1958 
1959 	ether_ifattach(ifp, sc->hw.mac.addr, NULL);
1960 
1961 	ifp->if_capabilities = IFCAP_HWCSUM |
1962 			       IFCAP_VLAN_HWTAGGING |
1963 			       IFCAP_VLAN_MTU |
1964 			       IFCAP_TSO;
1965 	if (sc->rx_ring_cnt > 1)
1966 		ifp->if_capabilities |= IFCAP_RSS;
1967 	ifp->if_capenable = ifp->if_capabilities;
1968 	ifp->if_hwassist = EMX_CSUM_FEATURES | CSUM_TSO;
1969 
1970 	/*
1971 	 * Tell the upper layer(s) we support long frames.
1972 	 */
1973 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
1974 
1975 	/*
1976 	 * Specify the media types supported by this sc and register
1977 	 * callbacks to update media and link information
1978 	 */
1979 	ifmedia_init(&sc->media, IFM_IMASK,
1980 		     emx_media_change, emx_media_status);
1981 	if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1982 	    sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1983 		ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_SX | IFM_FDX,
1984 			    0, NULL);
1985 		ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_SX, 0, NULL);
1986 	} else {
1987 		ifmedia_add(&sc->media, IFM_ETHER | IFM_10_T, 0, NULL);
1988 		ifmedia_add(&sc->media, IFM_ETHER | IFM_10_T | IFM_FDX,
1989 			    0, NULL);
1990 		ifmedia_add(&sc->media, IFM_ETHER | IFM_100_TX, 0, NULL);
1991 		ifmedia_add(&sc->media, IFM_ETHER | IFM_100_TX | IFM_FDX,
1992 			    0, NULL);
1993 		if (sc->hw.phy.type != e1000_phy_ife) {
1994 			ifmedia_add(&sc->media,
1995 				IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL);
1996 			ifmedia_add(&sc->media,
1997 				IFM_ETHER | IFM_1000_T, 0, NULL);
1998 		}
1999 	}
2000 	ifmedia_add(&sc->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2001 	ifmedia_set(&sc->media, IFM_ETHER | IFM_AUTO);
2002 }
2003 
2004 /*
2005  * Workaround for SmartSpeed on 82541 and 82547 controllers
2006  */
2007 static void
2008 emx_smartspeed(struct emx_softc *sc)
2009 {
2010 	uint16_t phy_tmp;
2011 
2012 	if (sc->link_active || sc->hw.phy.type != e1000_phy_igp ||
2013 	    sc->hw.mac.autoneg == 0 ||
2014 	    (sc->hw.phy.autoneg_advertised & ADVERTISE_1000_FULL) == 0)
2015 		return;
2016 
2017 	if (sc->smartspeed == 0) {
2018 		/*
2019 		 * If Master/Slave config fault is asserted twice,
2020 		 * we assume back-to-back
2021 		 */
2022 		e1000_read_phy_reg(&sc->hw, PHY_1000T_STATUS, &phy_tmp);
2023 		if (!(phy_tmp & SR_1000T_MS_CONFIG_FAULT))
2024 			return;
2025 		e1000_read_phy_reg(&sc->hw, PHY_1000T_STATUS, &phy_tmp);
2026 		if (phy_tmp & SR_1000T_MS_CONFIG_FAULT) {
2027 			e1000_read_phy_reg(&sc->hw,
2028 			    PHY_1000T_CTRL, &phy_tmp);
2029 			if (phy_tmp & CR_1000T_MS_ENABLE) {
2030 				phy_tmp &= ~CR_1000T_MS_ENABLE;
2031 				e1000_write_phy_reg(&sc->hw,
2032 				    PHY_1000T_CTRL, phy_tmp);
2033 				sc->smartspeed++;
2034 				if (sc->hw.mac.autoneg &&
2035 				    !e1000_phy_setup_autoneg(&sc->hw) &&
2036 				    !e1000_read_phy_reg(&sc->hw,
2037 				     PHY_CONTROL, &phy_tmp)) {
2038 					phy_tmp |= MII_CR_AUTO_NEG_EN |
2039 						   MII_CR_RESTART_AUTO_NEG;
2040 					e1000_write_phy_reg(&sc->hw,
2041 					    PHY_CONTROL, phy_tmp);
2042 				}
2043 			}
2044 		}
2045 		return;
2046 	} else if (sc->smartspeed == EMX_SMARTSPEED_DOWNSHIFT) {
2047 		/* If still no link, perhaps using 2/3 pair cable */
2048 		e1000_read_phy_reg(&sc->hw, PHY_1000T_CTRL, &phy_tmp);
2049 		phy_tmp |= CR_1000T_MS_ENABLE;
2050 		e1000_write_phy_reg(&sc->hw, PHY_1000T_CTRL, phy_tmp);
2051 		if (sc->hw.mac.autoneg &&
2052 		    !e1000_phy_setup_autoneg(&sc->hw) &&
2053 		    !e1000_read_phy_reg(&sc->hw, PHY_CONTROL, &phy_tmp)) {
2054 			phy_tmp |= MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
2055 			e1000_write_phy_reg(&sc->hw, PHY_CONTROL, phy_tmp);
2056 		}
2057 	}
2058 
2059 	/* Restart process after EMX_SMARTSPEED_MAX iterations */
2060 	if (sc->smartspeed++ == EMX_SMARTSPEED_MAX)
2061 		sc->smartspeed = 0;
2062 }
2063 
2064 static int
2065 emx_create_tx_ring(struct emx_txdata *tdata)
2066 {
2067 	device_t dev = tdata->sc->dev;
2068 	struct emx_txbuf *tx_buffer;
2069 	int error, i, tsize, ntxd;
2070 
2071 	/*
2072 	 * Validate number of transmit descriptors.  It must not exceed
2073 	 * hardware maximum, and must be multiple of E1000_DBA_ALIGN.
2074 	 */
2075 	ntxd = device_getenv_int(dev, "txd", emx_txd);
2076 	if ((ntxd * sizeof(struct e1000_tx_desc)) % EMX_DBA_ALIGN != 0 ||
2077 	    ntxd > EMX_MAX_TXD || ntxd < EMX_MIN_TXD) {
2078 		device_printf(dev, "Using %d TX descriptors instead of %d!\n",
2079 		    EMX_DEFAULT_TXD, ntxd);
2080 		tdata->num_tx_desc = EMX_DEFAULT_TXD;
2081 	} else {
2082 		tdata->num_tx_desc = ntxd;
2083 	}
2084 
2085 	/*
2086 	 * Allocate Transmit Descriptor ring
2087 	 */
2088 	tsize = roundup2(tdata->num_tx_desc * sizeof(struct e1000_tx_desc),
2089 			 EMX_DBA_ALIGN);
2090 	tdata->tx_desc_base = bus_dmamem_coherent_any(tdata->sc->parent_dtag,
2091 				EMX_DBA_ALIGN, tsize, BUS_DMA_WAITOK,
2092 				&tdata->tx_desc_dtag, &tdata->tx_desc_dmap,
2093 				&tdata->tx_desc_paddr);
2094 	if (tdata->tx_desc_base == NULL) {
2095 		device_printf(dev, "Unable to allocate tx_desc memory\n");
2096 		return ENOMEM;
2097 	}
2098 
2099 	tsize = __VM_CACHELINE_ALIGN(
2100 	    sizeof(struct emx_txbuf) * tdata->num_tx_desc);
2101 	tdata->tx_buf = kmalloc_cachealign(tsize, M_DEVBUF, M_WAITOK | M_ZERO);
2102 
2103 	/*
2104 	 * Create DMA tags for tx buffers
2105 	 */
2106 	error = bus_dma_tag_create(tdata->sc->parent_dtag, /* parent */
2107 			1, 0,			/* alignment, bounds */
2108 			BUS_SPACE_MAXADDR,	/* lowaddr */
2109 			BUS_SPACE_MAXADDR,	/* highaddr */
2110 			NULL, NULL,		/* filter, filterarg */
2111 			EMX_TSO_SIZE,		/* maxsize */
2112 			EMX_MAX_SCATTER,	/* nsegments */
2113 			EMX_MAX_SEGSIZE,	/* maxsegsize */
2114 			BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW |
2115 			BUS_DMA_ONEBPAGE,	/* flags */
2116 			&tdata->txtag);
2117 	if (error) {
2118 		device_printf(dev, "Unable to allocate TX DMA tag\n");
2119 		kfree(tdata->tx_buf, M_DEVBUF);
2120 		tdata->tx_buf = NULL;
2121 		return error;
2122 	}
2123 
2124 	/*
2125 	 * Create DMA maps for tx buffers
2126 	 */
2127 	for (i = 0; i < tdata->num_tx_desc; i++) {
2128 		tx_buffer = &tdata->tx_buf[i];
2129 
2130 		error = bus_dmamap_create(tdata->txtag,
2131 					  BUS_DMA_WAITOK | BUS_DMA_ONEBPAGE,
2132 					  &tx_buffer->map);
2133 		if (error) {
2134 			device_printf(dev, "Unable to create TX DMA map\n");
2135 			emx_destroy_tx_ring(tdata, i);
2136 			return error;
2137 		}
2138 	}
2139 
2140 	/*
2141 	 * Setup TX parameters
2142 	 */
2143 	tdata->spare_tx_desc = EMX_TX_SPARE;
2144 	tdata->tx_wreg_nsegs = 8;
2145 
2146 	/*
2147 	 * Keep following relationship between spare_tx_desc, oact_tx_desc
2148 	 * and tx_intr_nsegs:
2149 	 * (spare_tx_desc + EMX_TX_RESERVED) <=
2150 	 * oact_tx_desc <= EMX_TX_OACTIVE_MAX <= tx_intr_nsegs
2151 	 */
2152 	tdata->oact_tx_desc = tdata->num_tx_desc / 8;
2153 	if (tdata->oact_tx_desc > EMX_TX_OACTIVE_MAX)
2154 		tdata->oact_tx_desc = EMX_TX_OACTIVE_MAX;
2155 	if (tdata->oact_tx_desc < tdata->spare_tx_desc + EMX_TX_RESERVED)
2156 		tdata->oact_tx_desc = tdata->spare_tx_desc + EMX_TX_RESERVED;
2157 
2158 	tdata->tx_intr_nsegs = tdata->num_tx_desc / 16;
2159 	if (tdata->tx_intr_nsegs < tdata->oact_tx_desc)
2160 		tdata->tx_intr_nsegs = tdata->oact_tx_desc;
2161 
2162 	/*
2163 	 * Pullup extra 4bytes into the first data segment, see:
2164 	 * 82571/82572 specification update errata #7
2165 	 *
2166 	 * NOTE:
2167 	 * 4bytes instead of 2bytes, which are mentioned in the errata,
2168 	 * are pulled; mainly to keep rest of the data properly aligned.
2169 	 */
2170 	if (tdata->sc->hw.mac.type == e1000_82571 ||
2171 	    tdata->sc->hw.mac.type == e1000_82572)
2172 		tdata->tx_flags |= EMX_TXFLAG_TSO_PULLEX;
2173 
2174 	return (0);
2175 }
2176 
2177 static void
2178 emx_init_tx_ring(struct emx_txdata *tdata)
2179 {
2180 	/* Clear the old ring contents */
2181 	bzero(tdata->tx_desc_base,
2182 	      sizeof(struct e1000_tx_desc) * tdata->num_tx_desc);
2183 
2184 	/* Reset state */
2185 	tdata->next_avail_tx_desc = 0;
2186 	tdata->next_tx_to_clean = 0;
2187 	tdata->num_tx_desc_avail = tdata->num_tx_desc;
2188 
2189 	tdata->tx_flags |= EMX_TXFLAG_ENABLED;
2190 	if (tdata->sc->tx_ring_inuse > 1) {
2191 		tdata->tx_flags |= EMX_TXFLAG_FORCECTX;
2192 		if (bootverbose) {
2193 			if_printf(&tdata->sc->arpcom.ac_if,
2194 			    "TX %d force ctx setup\n", tdata->idx);
2195 		}
2196 	}
2197 }
2198 
2199 static void
2200 emx_init_tx_unit(struct emx_softc *sc)
2201 {
2202 	uint32_t tctl, tarc, tipg = 0;
2203 	int i;
2204 
2205 	for (i = 0; i < sc->tx_ring_inuse; ++i) {
2206 		struct emx_txdata *tdata = &sc->tx_data[i];
2207 		uint64_t bus_addr;
2208 
2209 		/* Setup the Base and Length of the Tx Descriptor Ring */
2210 		bus_addr = tdata->tx_desc_paddr;
2211 		E1000_WRITE_REG(&sc->hw, E1000_TDLEN(i),
2212 		    tdata->num_tx_desc * sizeof(struct e1000_tx_desc));
2213 		E1000_WRITE_REG(&sc->hw, E1000_TDBAH(i),
2214 		    (uint32_t)(bus_addr >> 32));
2215 		E1000_WRITE_REG(&sc->hw, E1000_TDBAL(i),
2216 		    (uint32_t)bus_addr);
2217 		/* Setup the HW Tx Head and Tail descriptor pointers */
2218 		E1000_WRITE_REG(&sc->hw, E1000_TDT(i), 0);
2219 		E1000_WRITE_REG(&sc->hw, E1000_TDH(i), 0);
2220 	}
2221 
2222 	/* Set the default values for the Tx Inter Packet Gap timer */
2223 	switch (sc->hw.mac.type) {
2224 	case e1000_80003es2lan:
2225 		tipg = DEFAULT_82543_TIPG_IPGR1;
2226 		tipg |= DEFAULT_80003ES2LAN_TIPG_IPGR2 <<
2227 		    E1000_TIPG_IPGR2_SHIFT;
2228 		break;
2229 
2230 	default:
2231 		if (sc->hw.phy.media_type == e1000_media_type_fiber ||
2232 		    sc->hw.phy.media_type == e1000_media_type_internal_serdes)
2233 			tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
2234 		else
2235 			tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
2236 		tipg |= DEFAULT_82543_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
2237 		tipg |= DEFAULT_82543_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
2238 		break;
2239 	}
2240 
2241 	E1000_WRITE_REG(&sc->hw, E1000_TIPG, tipg);
2242 
2243 	/* NOTE: 0 is not allowed for TIDV */
2244 	E1000_WRITE_REG(&sc->hw, E1000_TIDV, 1);
2245 	E1000_WRITE_REG(&sc->hw, E1000_TADV, 0);
2246 
2247 	if (sc->hw.mac.type == e1000_82571 ||
2248 	    sc->hw.mac.type == e1000_82572) {
2249 		tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
2250 		tarc |= EMX_TARC_SPEED_MODE;
2251 		E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
2252 	} else if (sc->hw.mac.type == e1000_80003es2lan) {
2253 		tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
2254 		tarc |= 1;
2255 		E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
2256 		tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
2257 		tarc |= 1;
2258 		E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
2259 	}
2260 
2261 	/* Program the Transmit Control Register */
2262 	tctl = E1000_READ_REG(&sc->hw, E1000_TCTL);
2263 	tctl &= ~E1000_TCTL_CT;
2264 	tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC | E1000_TCTL_EN |
2265 		(E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
2266 	tctl |= E1000_TCTL_MULR;
2267 
2268 	/* This write will effectively turn on the transmit unit. */
2269 	E1000_WRITE_REG(&sc->hw, E1000_TCTL, tctl);
2270 
2271 	if (sc->hw.mac.type == e1000_82571 ||
2272 	    sc->hw.mac.type == e1000_82572 ||
2273 	    sc->hw.mac.type == e1000_80003es2lan) {
2274 		/* Bit 28 of TARC1 must be cleared when MULR is enabled */
2275 		tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
2276 		tarc &= ~(1 << 28);
2277 		E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
2278 	}
2279 
2280 	if (sc->tx_ring_inuse > 1) {
2281 		tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
2282 		tarc &= ~EMX_TARC_COUNT_MASK;
2283 		tarc |= 1;
2284 		E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
2285 
2286 		tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
2287 		tarc &= ~EMX_TARC_COUNT_MASK;
2288 		tarc |= 1;
2289 		E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
2290 	}
2291 }
2292 
2293 static void
2294 emx_destroy_tx_ring(struct emx_txdata *tdata, int ndesc)
2295 {
2296 	struct emx_txbuf *tx_buffer;
2297 	int i;
2298 
2299 	/* Free Transmit Descriptor ring */
2300 	if (tdata->tx_desc_base) {
2301 		bus_dmamap_unload(tdata->tx_desc_dtag, tdata->tx_desc_dmap);
2302 		bus_dmamem_free(tdata->tx_desc_dtag, tdata->tx_desc_base,
2303 				tdata->tx_desc_dmap);
2304 		bus_dma_tag_destroy(tdata->tx_desc_dtag);
2305 
2306 		tdata->tx_desc_base = NULL;
2307 	}
2308 
2309 	if (tdata->tx_buf == NULL)
2310 		return;
2311 
2312 	for (i = 0; i < ndesc; i++) {
2313 		tx_buffer = &tdata->tx_buf[i];
2314 
2315 		KKASSERT(tx_buffer->m_head == NULL);
2316 		bus_dmamap_destroy(tdata->txtag, tx_buffer->map);
2317 	}
2318 	bus_dma_tag_destroy(tdata->txtag);
2319 
2320 	kfree(tdata->tx_buf, M_DEVBUF);
2321 	tdata->tx_buf = NULL;
2322 }
2323 
2324 /*
2325  * The offload context needs to be set when we transfer the first
2326  * packet of a particular protocol (TCP/UDP).  This routine has been
2327  * enhanced to deal with inserted VLAN headers.
2328  *
2329  * If the new packet's ether header length, ip header length and
2330  * csum offloading type are same as the previous packet, we should
2331  * avoid allocating a new csum context descriptor; mainly to take
2332  * advantage of the pipeline effect of the TX data read request.
2333  *
2334  * This function returns number of TX descrptors allocated for
2335  * csum context.
2336  */
2337 static int
2338 emx_txcsum(struct emx_txdata *tdata, struct mbuf *mp,
2339 	   uint32_t *txd_upper, uint32_t *txd_lower)
2340 {
2341 	struct e1000_context_desc *TXD;
2342 	int curr_txd, ehdrlen, csum_flags;
2343 	uint32_t cmd, hdr_len, ip_hlen;
2344 
2345 	csum_flags = mp->m_pkthdr.csum_flags & EMX_CSUM_FEATURES;
2346 	ip_hlen = mp->m_pkthdr.csum_iphlen;
2347 	ehdrlen = mp->m_pkthdr.csum_lhlen;
2348 
2349 	if ((tdata->tx_flags & EMX_TXFLAG_FORCECTX) == 0 &&
2350 	    tdata->csum_lhlen == ehdrlen && tdata->csum_iphlen == ip_hlen &&
2351 	    tdata->csum_flags == csum_flags) {
2352 		/*
2353 		 * Same csum offload context as the previous packets;
2354 		 * just return.
2355 		 */
2356 		*txd_upper = tdata->csum_txd_upper;
2357 		*txd_lower = tdata->csum_txd_lower;
2358 		return 0;
2359 	}
2360 
2361 	/*
2362 	 * Setup a new csum offload context.
2363 	 */
2364 
2365 	curr_txd = tdata->next_avail_tx_desc;
2366 	TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
2367 
2368 	cmd = 0;
2369 
2370 	/* Setup of IP header checksum. */
2371 	if (csum_flags & CSUM_IP) {
2372 		/*
2373 		 * Start offset for header checksum calculation.
2374 		 * End offset for header checksum calculation.
2375 		 * Offset of place to put the checksum.
2376 		 */
2377 		TXD->lower_setup.ip_fields.ipcss = ehdrlen;
2378 		TXD->lower_setup.ip_fields.ipcse =
2379 		    htole16(ehdrlen + ip_hlen - 1);
2380 		TXD->lower_setup.ip_fields.ipcso =
2381 		    ehdrlen + offsetof(struct ip, ip_sum);
2382 		cmd |= E1000_TXD_CMD_IP;
2383 		*txd_upper |= E1000_TXD_POPTS_IXSM << 8;
2384 	}
2385 	hdr_len = ehdrlen + ip_hlen;
2386 
2387 	if (csum_flags & CSUM_TCP) {
2388 		/*
2389 		 * Start offset for payload checksum calculation.
2390 		 * End offset for payload checksum calculation.
2391 		 * Offset of place to put the checksum.
2392 		 */
2393 		TXD->upper_setup.tcp_fields.tucss = hdr_len;
2394 		TXD->upper_setup.tcp_fields.tucse = htole16(0);
2395 		TXD->upper_setup.tcp_fields.tucso =
2396 		    hdr_len + offsetof(struct tcphdr, th_sum);
2397 		cmd |= E1000_TXD_CMD_TCP;
2398 		*txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2399 	} else if (csum_flags & CSUM_UDP) {
2400 		/*
2401 		 * Start offset for header checksum calculation.
2402 		 * End offset for header checksum calculation.
2403 		 * Offset of place to put the checksum.
2404 		 */
2405 		TXD->upper_setup.tcp_fields.tucss = hdr_len;
2406 		TXD->upper_setup.tcp_fields.tucse = htole16(0);
2407 		TXD->upper_setup.tcp_fields.tucso =
2408 		    hdr_len + offsetof(struct udphdr, uh_sum);
2409 		*txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2410 	}
2411 
2412 	*txd_lower = E1000_TXD_CMD_DEXT |	/* Extended descr type */
2413 		     E1000_TXD_DTYP_D;		/* Data descr */
2414 
2415 	/* Save the information for this csum offloading context */
2416 	tdata->csum_lhlen = ehdrlen;
2417 	tdata->csum_iphlen = ip_hlen;
2418 	tdata->csum_flags = csum_flags;
2419 	tdata->csum_txd_upper = *txd_upper;
2420 	tdata->csum_txd_lower = *txd_lower;
2421 
2422 	TXD->tcp_seg_setup.data = htole32(0);
2423 	TXD->cmd_and_length =
2424 	    htole32(E1000_TXD_CMD_IFCS | E1000_TXD_CMD_DEXT | cmd);
2425 
2426 	if (++curr_txd == tdata->num_tx_desc)
2427 		curr_txd = 0;
2428 
2429 	KKASSERT(tdata->num_tx_desc_avail > 0);
2430 	tdata->num_tx_desc_avail--;
2431 
2432 	tdata->next_avail_tx_desc = curr_txd;
2433 	return 1;
2434 }
2435 
2436 static void
2437 emx_txeof(struct emx_txdata *tdata)
2438 {
2439 	struct ifnet *ifp = &tdata->sc->arpcom.ac_if;
2440 	struct emx_txbuf *tx_buffer;
2441 	int first, num_avail;
2442 
2443 	if (tdata->tx_dd_head == tdata->tx_dd_tail)
2444 		return;
2445 
2446 	if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2447 		return;
2448 
2449 	num_avail = tdata->num_tx_desc_avail;
2450 	first = tdata->next_tx_to_clean;
2451 
2452 	while (tdata->tx_dd_head != tdata->tx_dd_tail) {
2453 		int dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2454 		struct e1000_tx_desc *tx_desc;
2455 
2456 		tx_desc = &tdata->tx_desc_base[dd_idx];
2457 		if (tx_desc->upper.fields.status & E1000_TXD_STAT_DD) {
2458 			EMX_INC_TXDD_IDX(tdata->tx_dd_head);
2459 
2460 			if (++dd_idx == tdata->num_tx_desc)
2461 				dd_idx = 0;
2462 
2463 			while (first != dd_idx) {
2464 				logif(pkt_txclean);
2465 
2466 				num_avail++;
2467 
2468 				tx_buffer = &tdata->tx_buf[first];
2469 				if (tx_buffer->m_head) {
2470 					ifp->if_opackets++;
2471 					bus_dmamap_unload(tdata->txtag,
2472 							  tx_buffer->map);
2473 					m_freem(tx_buffer->m_head);
2474 					tx_buffer->m_head = NULL;
2475 				}
2476 
2477 				if (++first == tdata->num_tx_desc)
2478 					first = 0;
2479 			}
2480 		} else {
2481 			break;
2482 		}
2483 	}
2484 	tdata->next_tx_to_clean = first;
2485 	tdata->num_tx_desc_avail = num_avail;
2486 
2487 	if (tdata->tx_dd_head == tdata->tx_dd_tail) {
2488 		tdata->tx_dd_head = 0;
2489 		tdata->tx_dd_tail = 0;
2490 	}
2491 
2492 	if (!EMX_IS_OACTIVE(tdata)) {
2493 		ifsq_clr_oactive(tdata->ifsq);
2494 
2495 		/* All clean, turn off the timer */
2496 		if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2497 			tdata->tx_watchdog.wd_timer = 0;
2498 	}
2499 }
2500 
2501 static void
2502 emx_tx_collect(struct emx_txdata *tdata)
2503 {
2504 	struct ifnet *ifp = &tdata->sc->arpcom.ac_if;
2505 	struct emx_txbuf *tx_buffer;
2506 	int tdh, first, num_avail, dd_idx = -1;
2507 
2508 	if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2509 		return;
2510 
2511 	tdh = E1000_READ_REG(&tdata->sc->hw, E1000_TDH(tdata->idx));
2512 	if (tdh == tdata->next_tx_to_clean)
2513 		return;
2514 
2515 	if (tdata->tx_dd_head != tdata->tx_dd_tail)
2516 		dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2517 
2518 	num_avail = tdata->num_tx_desc_avail;
2519 	first = tdata->next_tx_to_clean;
2520 
2521 	while (first != tdh) {
2522 		logif(pkt_txclean);
2523 
2524 		num_avail++;
2525 
2526 		tx_buffer = &tdata->tx_buf[first];
2527 		if (tx_buffer->m_head) {
2528 			ifp->if_opackets++;
2529 			bus_dmamap_unload(tdata->txtag,
2530 					  tx_buffer->map);
2531 			m_freem(tx_buffer->m_head);
2532 			tx_buffer->m_head = NULL;
2533 		}
2534 
2535 		if (first == dd_idx) {
2536 			EMX_INC_TXDD_IDX(tdata->tx_dd_head);
2537 			if (tdata->tx_dd_head == tdata->tx_dd_tail) {
2538 				tdata->tx_dd_head = 0;
2539 				tdata->tx_dd_tail = 0;
2540 				dd_idx = -1;
2541 			} else {
2542 				dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2543 			}
2544 		}
2545 
2546 		if (++first == tdata->num_tx_desc)
2547 			first = 0;
2548 	}
2549 	tdata->next_tx_to_clean = first;
2550 	tdata->num_tx_desc_avail = num_avail;
2551 
2552 	if (!EMX_IS_OACTIVE(tdata)) {
2553 		ifsq_clr_oactive(tdata->ifsq);
2554 
2555 		/* All clean, turn off the timer */
2556 		if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2557 			tdata->tx_watchdog.wd_timer = 0;
2558 	}
2559 }
2560 
2561 /*
2562  * When Link is lost sometimes there is work still in the TX ring
2563  * which will result in a watchdog, rather than allow that do an
2564  * attempted cleanup and then reinit here.  Note that this has been
2565  * seens mostly with fiber adapters.
2566  */
2567 static void
2568 emx_tx_purge(struct emx_softc *sc)
2569 {
2570 	int i;
2571 
2572 	if (sc->link_active)
2573 		return;
2574 
2575 	for (i = 0; i < sc->tx_ring_inuse; ++i) {
2576 		struct emx_txdata *tdata = &sc->tx_data[i];
2577 
2578 		if (tdata->tx_watchdog.wd_timer) {
2579 			emx_tx_collect(tdata);
2580 			if (tdata->tx_watchdog.wd_timer) {
2581 				if_printf(&sc->arpcom.ac_if,
2582 				    "Link lost, TX pending, reinit\n");
2583 				emx_init(sc);
2584 				return;
2585 			}
2586 		}
2587 	}
2588 }
2589 
2590 static int
2591 emx_newbuf(struct emx_rxdata *rdata, int i, int init)
2592 {
2593 	struct mbuf *m;
2594 	bus_dma_segment_t seg;
2595 	bus_dmamap_t map;
2596 	struct emx_rxbuf *rx_buffer;
2597 	int error, nseg;
2598 
2599 	m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
2600 	if (m == NULL) {
2601 		if (init) {
2602 			if_printf(&rdata->sc->arpcom.ac_if,
2603 				  "Unable to allocate RX mbuf\n");
2604 		}
2605 		return (ENOBUFS);
2606 	}
2607 	m->m_len = m->m_pkthdr.len = MCLBYTES;
2608 
2609 	if (rdata->sc->max_frame_size <= MCLBYTES - ETHER_ALIGN)
2610 		m_adj(m, ETHER_ALIGN);
2611 
2612 	error = bus_dmamap_load_mbuf_segment(rdata->rxtag,
2613 			rdata->rx_sparemap, m,
2614 			&seg, 1, &nseg, BUS_DMA_NOWAIT);
2615 	if (error) {
2616 		m_freem(m);
2617 		if (init) {
2618 			if_printf(&rdata->sc->arpcom.ac_if,
2619 				  "Unable to load RX mbuf\n");
2620 		}
2621 		return (error);
2622 	}
2623 
2624 	rx_buffer = &rdata->rx_buf[i];
2625 	if (rx_buffer->m_head != NULL)
2626 		bus_dmamap_unload(rdata->rxtag, rx_buffer->map);
2627 
2628 	map = rx_buffer->map;
2629 	rx_buffer->map = rdata->rx_sparemap;
2630 	rdata->rx_sparemap = map;
2631 
2632 	rx_buffer->m_head = m;
2633 	rx_buffer->paddr = seg.ds_addr;
2634 
2635 	emx_setup_rxdesc(&rdata->rx_desc[i], rx_buffer);
2636 	return (0);
2637 }
2638 
2639 static int
2640 emx_create_rx_ring(struct emx_rxdata *rdata)
2641 {
2642 	device_t dev = rdata->sc->dev;
2643 	struct emx_rxbuf *rx_buffer;
2644 	int i, error, rsize, nrxd;
2645 
2646 	/*
2647 	 * Validate number of receive descriptors.  It must not exceed
2648 	 * hardware maximum, and must be multiple of E1000_DBA_ALIGN.
2649 	 */
2650 	nrxd = device_getenv_int(dev, "rxd", emx_rxd);
2651 	if ((nrxd * sizeof(emx_rxdesc_t)) % EMX_DBA_ALIGN != 0 ||
2652 	    nrxd > EMX_MAX_RXD || nrxd < EMX_MIN_RXD) {
2653 		device_printf(dev, "Using %d RX descriptors instead of %d!\n",
2654 		    EMX_DEFAULT_RXD, nrxd);
2655 		rdata->num_rx_desc = EMX_DEFAULT_RXD;
2656 	} else {
2657 		rdata->num_rx_desc = nrxd;
2658 	}
2659 
2660 	/*
2661 	 * Allocate Receive Descriptor ring
2662 	 */
2663 	rsize = roundup2(rdata->num_rx_desc * sizeof(emx_rxdesc_t),
2664 			 EMX_DBA_ALIGN);
2665 	rdata->rx_desc = bus_dmamem_coherent_any(rdata->sc->parent_dtag,
2666 				EMX_DBA_ALIGN, rsize, BUS_DMA_WAITOK,
2667 				&rdata->rx_desc_dtag, &rdata->rx_desc_dmap,
2668 				&rdata->rx_desc_paddr);
2669 	if (rdata->rx_desc == NULL) {
2670 		device_printf(dev, "Unable to allocate rx_desc memory\n");
2671 		return ENOMEM;
2672 	}
2673 
2674 	rsize = __VM_CACHELINE_ALIGN(
2675 	    sizeof(struct emx_rxbuf) * rdata->num_rx_desc);
2676 	rdata->rx_buf = kmalloc_cachealign(rsize, M_DEVBUF, M_WAITOK | M_ZERO);
2677 
2678 	/*
2679 	 * Create DMA tag for rx buffers
2680 	 */
2681 	error = bus_dma_tag_create(rdata->sc->parent_dtag, /* parent */
2682 			1, 0,			/* alignment, bounds */
2683 			BUS_SPACE_MAXADDR,	/* lowaddr */
2684 			BUS_SPACE_MAXADDR,	/* highaddr */
2685 			NULL, NULL,		/* filter, filterarg */
2686 			MCLBYTES,		/* maxsize */
2687 			1,			/* nsegments */
2688 			MCLBYTES,		/* maxsegsize */
2689 			BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, /* flags */
2690 			&rdata->rxtag);
2691 	if (error) {
2692 		device_printf(dev, "Unable to allocate RX DMA tag\n");
2693 		kfree(rdata->rx_buf, M_DEVBUF);
2694 		rdata->rx_buf = NULL;
2695 		return error;
2696 	}
2697 
2698 	/*
2699 	 * Create spare DMA map for rx buffers
2700 	 */
2701 	error = bus_dmamap_create(rdata->rxtag, BUS_DMA_WAITOK,
2702 				  &rdata->rx_sparemap);
2703 	if (error) {
2704 		device_printf(dev, "Unable to create spare RX DMA map\n");
2705 		bus_dma_tag_destroy(rdata->rxtag);
2706 		kfree(rdata->rx_buf, M_DEVBUF);
2707 		rdata->rx_buf = NULL;
2708 		return error;
2709 	}
2710 
2711 	/*
2712 	 * Create DMA maps for rx buffers
2713 	 */
2714 	for (i = 0; i < rdata->num_rx_desc; i++) {
2715 		rx_buffer = &rdata->rx_buf[i];
2716 
2717 		error = bus_dmamap_create(rdata->rxtag, BUS_DMA_WAITOK,
2718 					  &rx_buffer->map);
2719 		if (error) {
2720 			device_printf(dev, "Unable to create RX DMA map\n");
2721 			emx_destroy_rx_ring(rdata, i);
2722 			return error;
2723 		}
2724 	}
2725 	return (0);
2726 }
2727 
2728 static void
2729 emx_free_rx_ring(struct emx_rxdata *rdata)
2730 {
2731 	int i;
2732 
2733 	for (i = 0; i < rdata->num_rx_desc; i++) {
2734 		struct emx_rxbuf *rx_buffer = &rdata->rx_buf[i];
2735 
2736 		if (rx_buffer->m_head != NULL) {
2737 			bus_dmamap_unload(rdata->rxtag, rx_buffer->map);
2738 			m_freem(rx_buffer->m_head);
2739 			rx_buffer->m_head = NULL;
2740 		}
2741 	}
2742 
2743 	if (rdata->fmp != NULL)
2744 		m_freem(rdata->fmp);
2745 	rdata->fmp = NULL;
2746 	rdata->lmp = NULL;
2747 }
2748 
2749 static void
2750 emx_free_tx_ring(struct emx_txdata *tdata)
2751 {
2752 	int i;
2753 
2754 	for (i = 0; i < tdata->num_tx_desc; i++) {
2755 		struct emx_txbuf *tx_buffer = &tdata->tx_buf[i];
2756 
2757 		if (tx_buffer->m_head != NULL) {
2758 			bus_dmamap_unload(tdata->txtag, tx_buffer->map);
2759 			m_freem(tx_buffer->m_head);
2760 			tx_buffer->m_head = NULL;
2761 		}
2762 	}
2763 
2764 	tdata->tx_flags &= ~EMX_TXFLAG_FORCECTX;
2765 
2766 	tdata->csum_flags = 0;
2767 	tdata->csum_lhlen = 0;
2768 	tdata->csum_iphlen = 0;
2769 	tdata->csum_thlen = 0;
2770 	tdata->csum_mss = 0;
2771 	tdata->csum_pktlen = 0;
2772 
2773 	tdata->tx_dd_head = 0;
2774 	tdata->tx_dd_tail = 0;
2775 	tdata->tx_nsegs = 0;
2776 }
2777 
2778 static int
2779 emx_init_rx_ring(struct emx_rxdata *rdata)
2780 {
2781 	int i, error;
2782 
2783 	/* Reset descriptor ring */
2784 	bzero(rdata->rx_desc, sizeof(emx_rxdesc_t) * rdata->num_rx_desc);
2785 
2786 	/* Allocate new ones. */
2787 	for (i = 0; i < rdata->num_rx_desc; i++) {
2788 		error = emx_newbuf(rdata, i, 1);
2789 		if (error)
2790 			return (error);
2791 	}
2792 
2793 	/* Setup our descriptor pointers */
2794 	rdata->next_rx_desc_to_check = 0;
2795 
2796 	return (0);
2797 }
2798 
2799 static void
2800 emx_init_rx_unit(struct emx_softc *sc)
2801 {
2802 	struct ifnet *ifp = &sc->arpcom.ac_if;
2803 	uint64_t bus_addr;
2804 	uint32_t rctl, itr, rfctl;
2805 	int i;
2806 
2807 	/*
2808 	 * Make sure receives are disabled while setting
2809 	 * up the descriptor ring
2810 	 */
2811 	rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
2812 	E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
2813 
2814 	/*
2815 	 * Set the interrupt throttling rate. Value is calculated
2816 	 * as ITR = 1 / (INT_THROTTLE_CEIL * 256ns)
2817 	 */
2818 	if (sc->int_throttle_ceil)
2819 		itr = 1000000000 / 256 / sc->int_throttle_ceil;
2820 	else
2821 		itr = 0;
2822 	emx_set_itr(sc, itr);
2823 
2824 	/* Use extended RX descriptor */
2825 	rfctl = E1000_RFCTL_EXTEN;
2826 
2827 	/* Disable accelerated ackknowledge */
2828 	if (sc->hw.mac.type == e1000_82574)
2829 		rfctl |= E1000_RFCTL_ACK_DIS;
2830 
2831 	E1000_WRITE_REG(&sc->hw, E1000_RFCTL, rfctl);
2832 
2833 	/*
2834 	 * Receive Checksum Offload for TCP and UDP
2835 	 *
2836 	 * Checksum offloading is also enabled if multiple receive
2837 	 * queue is to be supported, since we need it to figure out
2838 	 * packet type.
2839 	 */
2840 	if ((ifp->if_capenable & IFCAP_RXCSUM) ||
2841 	    sc->rx_ring_cnt > 1) {
2842 		uint32_t rxcsum;
2843 
2844 		rxcsum = E1000_READ_REG(&sc->hw, E1000_RXCSUM);
2845 
2846 		/*
2847 		 * NOTE:
2848 		 * PCSD must be enabled to enable multiple
2849 		 * receive queues.
2850 		 */
2851 		rxcsum |= E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL |
2852 			  E1000_RXCSUM_PCSD;
2853 		E1000_WRITE_REG(&sc->hw, E1000_RXCSUM, rxcsum);
2854 	}
2855 
2856 	/*
2857 	 * Configure multiple receive queue (RSS)
2858 	 */
2859 	if (sc->rx_ring_cnt > 1) {
2860 		uint8_t key[EMX_NRSSRK * EMX_RSSRK_SIZE];
2861 		uint32_t reta;
2862 
2863 		KASSERT(sc->rx_ring_cnt == EMX_NRX_RING,
2864 		    ("invalid number of RX ring (%d)", sc->rx_ring_cnt));
2865 
2866 		/*
2867 		 * NOTE:
2868 		 * When we reach here, RSS has already been disabled
2869 		 * in emx_stop(), so we could safely configure RSS key
2870 		 * and redirect table.
2871 		 */
2872 
2873 		/*
2874 		 * Configure RSS key
2875 		 */
2876 		toeplitz_get_key(key, sizeof(key));
2877 		for (i = 0; i < EMX_NRSSRK; ++i) {
2878 			uint32_t rssrk;
2879 
2880 			rssrk = EMX_RSSRK_VAL(key, i);
2881 			EMX_RSS_DPRINTF(sc, 1, "rssrk%d 0x%08x\n", i, rssrk);
2882 
2883 			E1000_WRITE_REG(&sc->hw, E1000_RSSRK(i), rssrk);
2884 		}
2885 
2886 		/*
2887 		 * Configure RSS redirect table in following fashion:
2888 	 	 * (hash & ring_cnt_mask) == rdr_table[(hash & rdr_table_mask)]
2889 		 */
2890 		reta = 0;
2891 		for (i = 0; i < EMX_RETA_SIZE; ++i) {
2892 			uint32_t q;
2893 
2894 			q = (i % sc->rx_ring_cnt) << EMX_RETA_RINGIDX_SHIFT;
2895 			reta |= q << (8 * i);
2896 		}
2897 		EMX_RSS_DPRINTF(sc, 1, "reta 0x%08x\n", reta);
2898 
2899 		for (i = 0; i < EMX_NRETA; ++i)
2900 			E1000_WRITE_REG(&sc->hw, E1000_RETA(i), reta);
2901 
2902 		/*
2903 		 * Enable multiple receive queues.
2904 		 * Enable IPv4 RSS standard hash functions.
2905 		 * Disable RSS interrupt.
2906 		 */
2907 		E1000_WRITE_REG(&sc->hw, E1000_MRQC,
2908 				E1000_MRQC_ENABLE_RSS_2Q |
2909 				E1000_MRQC_RSS_FIELD_IPV4_TCP |
2910 				E1000_MRQC_RSS_FIELD_IPV4);
2911 	}
2912 
2913 	/*
2914 	 * XXX TEMPORARY WORKAROUND: on some systems with 82573
2915 	 * long latencies are observed, like Lenovo X60. This
2916 	 * change eliminates the problem, but since having positive
2917 	 * values in RDTR is a known source of problems on other
2918 	 * platforms another solution is being sought.
2919 	 */
2920 	if (emx_82573_workaround && sc->hw.mac.type == e1000_82573) {
2921 		E1000_WRITE_REG(&sc->hw, E1000_RADV, EMX_RADV_82573);
2922 		E1000_WRITE_REG(&sc->hw, E1000_RDTR, EMX_RDTR_82573);
2923 	}
2924 
2925 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
2926 		struct emx_rxdata *rdata = &sc->rx_data[i];
2927 
2928 		/*
2929 		 * Setup the Base and Length of the Rx Descriptor Ring
2930 		 */
2931 		bus_addr = rdata->rx_desc_paddr;
2932 		E1000_WRITE_REG(&sc->hw, E1000_RDLEN(i),
2933 		    rdata->num_rx_desc * sizeof(emx_rxdesc_t));
2934 		E1000_WRITE_REG(&sc->hw, E1000_RDBAH(i),
2935 		    (uint32_t)(bus_addr >> 32));
2936 		E1000_WRITE_REG(&sc->hw, E1000_RDBAL(i),
2937 		    (uint32_t)bus_addr);
2938 
2939 		/*
2940 		 * Setup the HW Rx Head and Tail Descriptor Pointers
2941 		 */
2942 		E1000_WRITE_REG(&sc->hw, E1000_RDH(i), 0);
2943 		E1000_WRITE_REG(&sc->hw, E1000_RDT(i),
2944 		    sc->rx_data[i].num_rx_desc - 1);
2945 	}
2946 
2947 	/* Setup the Receive Control Register */
2948 	rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
2949 	rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO |
2950 		E1000_RCTL_RDMTS_HALF | E1000_RCTL_SECRC |
2951 		(sc->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
2952 
2953 	/* Make sure VLAN Filters are off */
2954 	rctl &= ~E1000_RCTL_VFE;
2955 
2956 	/* Don't store bad paket */
2957 	rctl &= ~E1000_RCTL_SBP;
2958 
2959 	/* MCLBYTES */
2960 	rctl |= E1000_RCTL_SZ_2048;
2961 
2962 	if (ifp->if_mtu > ETHERMTU)
2963 		rctl |= E1000_RCTL_LPE;
2964 	else
2965 		rctl &= ~E1000_RCTL_LPE;
2966 
2967 	/* Enable Receives */
2968 	E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl);
2969 }
2970 
2971 static void
2972 emx_destroy_rx_ring(struct emx_rxdata *rdata, int ndesc)
2973 {
2974 	struct emx_rxbuf *rx_buffer;
2975 	int i;
2976 
2977 	/* Free Receive Descriptor ring */
2978 	if (rdata->rx_desc) {
2979 		bus_dmamap_unload(rdata->rx_desc_dtag, rdata->rx_desc_dmap);
2980 		bus_dmamem_free(rdata->rx_desc_dtag, rdata->rx_desc,
2981 				rdata->rx_desc_dmap);
2982 		bus_dma_tag_destroy(rdata->rx_desc_dtag);
2983 
2984 		rdata->rx_desc = NULL;
2985 	}
2986 
2987 	if (rdata->rx_buf == NULL)
2988 		return;
2989 
2990 	for (i = 0; i < ndesc; i++) {
2991 		rx_buffer = &rdata->rx_buf[i];
2992 
2993 		KKASSERT(rx_buffer->m_head == NULL);
2994 		bus_dmamap_destroy(rdata->rxtag, rx_buffer->map);
2995 	}
2996 	bus_dmamap_destroy(rdata->rxtag, rdata->rx_sparemap);
2997 	bus_dma_tag_destroy(rdata->rxtag);
2998 
2999 	kfree(rdata->rx_buf, M_DEVBUF);
3000 	rdata->rx_buf = NULL;
3001 }
3002 
3003 static void
3004 emx_rxeof(struct emx_rxdata *rdata, int count)
3005 {
3006 	struct ifnet *ifp = &rdata->sc->arpcom.ac_if;
3007 	uint32_t staterr;
3008 	emx_rxdesc_t *current_desc;
3009 	struct mbuf *mp;
3010 	int i;
3011 
3012 	i = rdata->next_rx_desc_to_check;
3013 	current_desc = &rdata->rx_desc[i];
3014 	staterr = le32toh(current_desc->rxd_staterr);
3015 
3016 	if (!(staterr & E1000_RXD_STAT_DD))
3017 		return;
3018 
3019 	while ((staterr & E1000_RXD_STAT_DD) && count != 0) {
3020 		struct pktinfo *pi = NULL, pi0;
3021 		struct emx_rxbuf *rx_buf = &rdata->rx_buf[i];
3022 		struct mbuf *m = NULL;
3023 		int eop, len;
3024 
3025 		logif(pkt_receive);
3026 
3027 		mp = rx_buf->m_head;
3028 
3029 		/*
3030 		 * Can't defer bus_dmamap_sync(9) because TBI_ACCEPT
3031 		 * needs to access the last received byte in the mbuf.
3032 		 */
3033 		bus_dmamap_sync(rdata->rxtag, rx_buf->map,
3034 				BUS_DMASYNC_POSTREAD);
3035 
3036 		len = le16toh(current_desc->rxd_length);
3037 		if (staterr & E1000_RXD_STAT_EOP) {
3038 			count--;
3039 			eop = 1;
3040 		} else {
3041 			eop = 0;
3042 		}
3043 
3044 		if (!(staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK)) {
3045 			uint16_t vlan = 0;
3046 			uint32_t mrq, rss_hash;
3047 
3048 			/*
3049 			 * Save several necessary information,
3050 			 * before emx_newbuf() destroy it.
3051 			 */
3052 			if ((staterr & E1000_RXD_STAT_VP) && eop)
3053 				vlan = le16toh(current_desc->rxd_vlan);
3054 
3055 			mrq = le32toh(current_desc->rxd_mrq);
3056 			rss_hash = le32toh(current_desc->rxd_rss);
3057 
3058 			EMX_RSS_DPRINTF(rdata->sc, 10,
3059 			    "ring%d, mrq 0x%08x, rss_hash 0x%08x\n",
3060 			    rdata->idx, mrq, rss_hash);
3061 
3062 			if (emx_newbuf(rdata, i, 0) != 0) {
3063 				ifp->if_iqdrops++;
3064 				goto discard;
3065 			}
3066 
3067 			/* Assign correct length to the current fragment */
3068 			mp->m_len = len;
3069 
3070 			if (rdata->fmp == NULL) {
3071 				mp->m_pkthdr.len = len;
3072 				rdata->fmp = mp; /* Store the first mbuf */
3073 				rdata->lmp = mp;
3074 			} else {
3075 				/*
3076 				 * Chain mbuf's together
3077 				 */
3078 				rdata->lmp->m_next = mp;
3079 				rdata->lmp = rdata->lmp->m_next;
3080 				rdata->fmp->m_pkthdr.len += len;
3081 			}
3082 
3083 			if (eop) {
3084 				rdata->fmp->m_pkthdr.rcvif = ifp;
3085 				ifp->if_ipackets++;
3086 
3087 				if (ifp->if_capenable & IFCAP_RXCSUM)
3088 					emx_rxcsum(staterr, rdata->fmp);
3089 
3090 				if (staterr & E1000_RXD_STAT_VP) {
3091 					rdata->fmp->m_pkthdr.ether_vlantag =
3092 					    vlan;
3093 					rdata->fmp->m_flags |= M_VLANTAG;
3094 				}
3095 				m = rdata->fmp;
3096 				rdata->fmp = NULL;
3097 				rdata->lmp = NULL;
3098 
3099 				if (ifp->if_capenable & IFCAP_RSS) {
3100 					pi = emx_rssinfo(m, &pi0, mrq,
3101 							 rss_hash, staterr);
3102 				}
3103 #ifdef EMX_RSS_DEBUG
3104 				rdata->rx_pkts++;
3105 #endif
3106 			}
3107 		} else {
3108 			ifp->if_ierrors++;
3109 discard:
3110 			emx_setup_rxdesc(current_desc, rx_buf);
3111 			if (rdata->fmp != NULL) {
3112 				m_freem(rdata->fmp);
3113 				rdata->fmp = NULL;
3114 				rdata->lmp = NULL;
3115 			}
3116 			m = NULL;
3117 		}
3118 
3119 		if (m != NULL)
3120 			ether_input_pkt(ifp, m, pi);
3121 
3122 		/* Advance our pointers to the next descriptor. */
3123 		if (++i == rdata->num_rx_desc)
3124 			i = 0;
3125 
3126 		current_desc = &rdata->rx_desc[i];
3127 		staterr = le32toh(current_desc->rxd_staterr);
3128 	}
3129 	rdata->next_rx_desc_to_check = i;
3130 
3131 	/* Advance the E1000's Receive Queue "Tail Pointer". */
3132 	if (--i < 0)
3133 		i = rdata->num_rx_desc - 1;
3134 	E1000_WRITE_REG(&rdata->sc->hw, E1000_RDT(rdata->idx), i);
3135 }
3136 
3137 static void
3138 emx_enable_intr(struct emx_softc *sc)
3139 {
3140 	uint32_t ims_mask = IMS_ENABLE_MASK;
3141 
3142 	lwkt_serialize_handler_enable(&sc->main_serialize);
3143 
3144 #if 0
3145 	if (sc->hw.mac.type == e1000_82574) {
3146 		E1000_WRITE_REG(hw, EMX_EIAC, EM_MSIX_MASK);
3147 		ims_mask |= EM_MSIX_MASK;
3148 	}
3149 #endif
3150 	E1000_WRITE_REG(&sc->hw, E1000_IMS, ims_mask);
3151 }
3152 
3153 static void
3154 emx_disable_intr(struct emx_softc *sc)
3155 {
3156 	if (sc->hw.mac.type == e1000_82574)
3157 		E1000_WRITE_REG(&sc->hw, EMX_EIAC, 0);
3158 	E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
3159 
3160 	lwkt_serialize_handler_disable(&sc->main_serialize);
3161 }
3162 
3163 /*
3164  * Bit of a misnomer, what this really means is
3165  * to enable OS management of the system... aka
3166  * to disable special hardware management features
3167  */
3168 static void
3169 emx_get_mgmt(struct emx_softc *sc)
3170 {
3171 	/* A shared code workaround */
3172 	if (sc->flags & EMX_FLAG_HAS_MGMT) {
3173 		int manc2h = E1000_READ_REG(&sc->hw, E1000_MANC2H);
3174 		int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
3175 
3176 		/* disable hardware interception of ARP */
3177 		manc &= ~(E1000_MANC_ARP_EN);
3178 
3179                 /* enable receiving management packets to the host */
3180 		manc |= E1000_MANC_EN_MNG2HOST;
3181 #define E1000_MNG2HOST_PORT_623 (1 << 5)
3182 #define E1000_MNG2HOST_PORT_664 (1 << 6)
3183 		manc2h |= E1000_MNG2HOST_PORT_623;
3184 		manc2h |= E1000_MNG2HOST_PORT_664;
3185 		E1000_WRITE_REG(&sc->hw, E1000_MANC2H, manc2h);
3186 
3187 		E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
3188 	}
3189 }
3190 
3191 /*
3192  * Give control back to hardware management
3193  * controller if there is one.
3194  */
3195 static void
3196 emx_rel_mgmt(struct emx_softc *sc)
3197 {
3198 	if (sc->flags & EMX_FLAG_HAS_MGMT) {
3199 		int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
3200 
3201 		/* re-enable hardware interception of ARP */
3202 		manc |= E1000_MANC_ARP_EN;
3203 		manc &= ~E1000_MANC_EN_MNG2HOST;
3204 
3205 		E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
3206 	}
3207 }
3208 
3209 /*
3210  * emx_get_hw_control() sets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3211  * For ASF and Pass Through versions of f/w this means that
3212  * the driver is loaded.  For AMT version (only with 82573)
3213  * of the f/w this means that the network i/f is open.
3214  */
3215 static void
3216 emx_get_hw_control(struct emx_softc *sc)
3217 {
3218 	/* Let firmware know the driver has taken over */
3219 	if (sc->hw.mac.type == e1000_82573) {
3220 		uint32_t swsm;
3221 
3222 		swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
3223 		E1000_WRITE_REG(&sc->hw, E1000_SWSM,
3224 		    swsm | E1000_SWSM_DRV_LOAD);
3225 	} else {
3226 		uint32_t ctrl_ext;
3227 
3228 		ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
3229 		E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
3230 		    ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
3231 	}
3232 	sc->flags |= EMX_FLAG_HW_CTRL;
3233 }
3234 
3235 /*
3236  * emx_rel_hw_control() resets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3237  * For ASF and Pass Through versions of f/w this means that the
3238  * driver is no longer loaded.  For AMT version (only with 82573)
3239  * of the f/w this means that the network i/f is closed.
3240  */
3241 static void
3242 emx_rel_hw_control(struct emx_softc *sc)
3243 {
3244 	if ((sc->flags & EMX_FLAG_HW_CTRL) == 0)
3245 		return;
3246 	sc->flags &= ~EMX_FLAG_HW_CTRL;
3247 
3248 	/* Let firmware taken over control of h/w */
3249 	if (sc->hw.mac.type == e1000_82573) {
3250 		uint32_t swsm;
3251 
3252 		swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
3253 		E1000_WRITE_REG(&sc->hw, E1000_SWSM,
3254 		    swsm & ~E1000_SWSM_DRV_LOAD);
3255 	} else {
3256 		uint32_t ctrl_ext;
3257 
3258 		ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
3259 		E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
3260 		    ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
3261 	}
3262 }
3263 
3264 static int
3265 emx_is_valid_eaddr(const uint8_t *addr)
3266 {
3267 	char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
3268 
3269 	if ((addr[0] & 1) || !bcmp(addr, zero_addr, ETHER_ADDR_LEN))
3270 		return (FALSE);
3271 
3272 	return (TRUE);
3273 }
3274 
3275 /*
3276  * Enable PCI Wake On Lan capability
3277  */
3278 void
3279 emx_enable_wol(device_t dev)
3280 {
3281 	uint16_t cap, status;
3282 	uint8_t id;
3283 
3284 	/* First find the capabilities pointer*/
3285 	cap = pci_read_config(dev, PCIR_CAP_PTR, 2);
3286 
3287 	/* Read the PM Capabilities */
3288 	id = pci_read_config(dev, cap, 1);
3289 	if (id != PCIY_PMG)     /* Something wrong */
3290 		return;
3291 
3292 	/*
3293 	 * OK, we have the power capabilities,
3294 	 * so now get the status register
3295 	 */
3296 	cap += PCIR_POWER_STATUS;
3297 	status = pci_read_config(dev, cap, 2);
3298 	status |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
3299 	pci_write_config(dev, cap, status, 2);
3300 }
3301 
3302 static void
3303 emx_update_stats(struct emx_softc *sc)
3304 {
3305 	struct ifnet *ifp = &sc->arpcom.ac_if;
3306 
3307 	if (sc->hw.phy.media_type == e1000_media_type_copper ||
3308 	    (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_LU)) {
3309 		sc->stats.symerrs += E1000_READ_REG(&sc->hw, E1000_SYMERRS);
3310 		sc->stats.sec += E1000_READ_REG(&sc->hw, E1000_SEC);
3311 	}
3312 	sc->stats.crcerrs += E1000_READ_REG(&sc->hw, E1000_CRCERRS);
3313 	sc->stats.mpc += E1000_READ_REG(&sc->hw, E1000_MPC);
3314 	sc->stats.scc += E1000_READ_REG(&sc->hw, E1000_SCC);
3315 	sc->stats.ecol += E1000_READ_REG(&sc->hw, E1000_ECOL);
3316 
3317 	sc->stats.mcc += E1000_READ_REG(&sc->hw, E1000_MCC);
3318 	sc->stats.latecol += E1000_READ_REG(&sc->hw, E1000_LATECOL);
3319 	sc->stats.colc += E1000_READ_REG(&sc->hw, E1000_COLC);
3320 	sc->stats.dc += E1000_READ_REG(&sc->hw, E1000_DC);
3321 	sc->stats.rlec += E1000_READ_REG(&sc->hw, E1000_RLEC);
3322 	sc->stats.xonrxc += E1000_READ_REG(&sc->hw, E1000_XONRXC);
3323 	sc->stats.xontxc += E1000_READ_REG(&sc->hw, E1000_XONTXC);
3324 	sc->stats.xoffrxc += E1000_READ_REG(&sc->hw, E1000_XOFFRXC);
3325 	sc->stats.xofftxc += E1000_READ_REG(&sc->hw, E1000_XOFFTXC);
3326 	sc->stats.fcruc += E1000_READ_REG(&sc->hw, E1000_FCRUC);
3327 	sc->stats.prc64 += E1000_READ_REG(&sc->hw, E1000_PRC64);
3328 	sc->stats.prc127 += E1000_READ_REG(&sc->hw, E1000_PRC127);
3329 	sc->stats.prc255 += E1000_READ_REG(&sc->hw, E1000_PRC255);
3330 	sc->stats.prc511 += E1000_READ_REG(&sc->hw, E1000_PRC511);
3331 	sc->stats.prc1023 += E1000_READ_REG(&sc->hw, E1000_PRC1023);
3332 	sc->stats.prc1522 += E1000_READ_REG(&sc->hw, E1000_PRC1522);
3333 	sc->stats.gprc += E1000_READ_REG(&sc->hw, E1000_GPRC);
3334 	sc->stats.bprc += E1000_READ_REG(&sc->hw, E1000_BPRC);
3335 	sc->stats.mprc += E1000_READ_REG(&sc->hw, E1000_MPRC);
3336 	sc->stats.gptc += E1000_READ_REG(&sc->hw, E1000_GPTC);
3337 
3338 	/* For the 64-bit byte counters the low dword must be read first. */
3339 	/* Both registers clear on the read of the high dword */
3340 
3341 	sc->stats.gorc += E1000_READ_REG(&sc->hw, E1000_GORCH);
3342 	sc->stats.gotc += E1000_READ_REG(&sc->hw, E1000_GOTCH);
3343 
3344 	sc->stats.rnbc += E1000_READ_REG(&sc->hw, E1000_RNBC);
3345 	sc->stats.ruc += E1000_READ_REG(&sc->hw, E1000_RUC);
3346 	sc->stats.rfc += E1000_READ_REG(&sc->hw, E1000_RFC);
3347 	sc->stats.roc += E1000_READ_REG(&sc->hw, E1000_ROC);
3348 	sc->stats.rjc += E1000_READ_REG(&sc->hw, E1000_RJC);
3349 
3350 	sc->stats.tor += E1000_READ_REG(&sc->hw, E1000_TORH);
3351 	sc->stats.tot += E1000_READ_REG(&sc->hw, E1000_TOTH);
3352 
3353 	sc->stats.tpr += E1000_READ_REG(&sc->hw, E1000_TPR);
3354 	sc->stats.tpt += E1000_READ_REG(&sc->hw, E1000_TPT);
3355 	sc->stats.ptc64 += E1000_READ_REG(&sc->hw, E1000_PTC64);
3356 	sc->stats.ptc127 += E1000_READ_REG(&sc->hw, E1000_PTC127);
3357 	sc->stats.ptc255 += E1000_READ_REG(&sc->hw, E1000_PTC255);
3358 	sc->stats.ptc511 += E1000_READ_REG(&sc->hw, E1000_PTC511);
3359 	sc->stats.ptc1023 += E1000_READ_REG(&sc->hw, E1000_PTC1023);
3360 	sc->stats.ptc1522 += E1000_READ_REG(&sc->hw, E1000_PTC1522);
3361 	sc->stats.mptc += E1000_READ_REG(&sc->hw, E1000_MPTC);
3362 	sc->stats.bptc += E1000_READ_REG(&sc->hw, E1000_BPTC);
3363 
3364 	sc->stats.algnerrc += E1000_READ_REG(&sc->hw, E1000_ALGNERRC);
3365 	sc->stats.rxerrc += E1000_READ_REG(&sc->hw, E1000_RXERRC);
3366 	sc->stats.tncrs += E1000_READ_REG(&sc->hw, E1000_TNCRS);
3367 	sc->stats.cexterr += E1000_READ_REG(&sc->hw, E1000_CEXTERR);
3368 	sc->stats.tsctc += E1000_READ_REG(&sc->hw, E1000_TSCTC);
3369 	sc->stats.tsctfc += E1000_READ_REG(&sc->hw, E1000_TSCTFC);
3370 
3371 	ifp->if_collisions = sc->stats.colc;
3372 
3373 	/* Rx Errors */
3374 	ifp->if_ierrors = sc->stats.rxerrc +
3375 			  sc->stats.crcerrs + sc->stats.algnerrc +
3376 			  sc->stats.ruc + sc->stats.roc +
3377 			  sc->stats.mpc + sc->stats.cexterr;
3378 
3379 	/* Tx Errors */
3380 	ifp->if_oerrors = sc->stats.ecol + sc->stats.latecol;
3381 }
3382 
3383 static void
3384 emx_print_debug_info(struct emx_softc *sc)
3385 {
3386 	device_t dev = sc->dev;
3387 	uint8_t *hw_addr = sc->hw.hw_addr;
3388 	int i;
3389 
3390 	device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
3391 	device_printf(dev, "CTRL = 0x%x RCTL = 0x%x \n",
3392 	    E1000_READ_REG(&sc->hw, E1000_CTRL),
3393 	    E1000_READ_REG(&sc->hw, E1000_RCTL));
3394 	device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk \n",
3395 	    ((E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff0000) >> 16),\
3396 	    (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) );
3397 	device_printf(dev, "Flow control watermarks high = %d low = %d\n",
3398 	    sc->hw.fc.high_water, sc->hw.fc.low_water);
3399 	device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
3400 	    E1000_READ_REG(&sc->hw, E1000_TIDV),
3401 	    E1000_READ_REG(&sc->hw, E1000_TADV));
3402 	device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
3403 	    E1000_READ_REG(&sc->hw, E1000_RDTR),
3404 	    E1000_READ_REG(&sc->hw, E1000_RADV));
3405 
3406 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3407 		device_printf(dev, "hw %d tdh = %d, hw tdt = %d\n", i,
3408 		    E1000_READ_REG(&sc->hw, E1000_TDH(i)),
3409 		    E1000_READ_REG(&sc->hw, E1000_TDT(i)));
3410 	}
3411 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3412 		device_printf(dev, "hw %d rdh = %d, hw rdt = %d\n", i,
3413 		    E1000_READ_REG(&sc->hw, E1000_RDH(i)),
3414 		    E1000_READ_REG(&sc->hw, E1000_RDT(i)));
3415 	}
3416 
3417 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3418 		device_printf(dev, "TX %d Tx descriptors avail = %d\n", i,
3419 		    sc->tx_data[i].num_tx_desc_avail);
3420 		device_printf(dev, "TX %d TSO segments = %lu\n", i,
3421 		    sc->tx_data[i].tso_segments);
3422 		device_printf(dev, "TX %d TSO ctx reused = %lu\n", i,
3423 		    sc->tx_data[i].tso_ctx_reused);
3424 	}
3425 }
3426 
3427 static void
3428 emx_print_hw_stats(struct emx_softc *sc)
3429 {
3430 	device_t dev = sc->dev;
3431 
3432 	device_printf(dev, "Excessive collisions = %lld\n",
3433 	    (long long)sc->stats.ecol);
3434 #if (DEBUG_HW > 0)  /* Dont output these errors normally */
3435 	device_printf(dev, "Symbol errors = %lld\n",
3436 	    (long long)sc->stats.symerrs);
3437 #endif
3438 	device_printf(dev, "Sequence errors = %lld\n",
3439 	    (long long)sc->stats.sec);
3440 	device_printf(dev, "Defer count = %lld\n",
3441 	    (long long)sc->stats.dc);
3442 	device_printf(dev, "Missed Packets = %lld\n",
3443 	    (long long)sc->stats.mpc);
3444 	device_printf(dev, "Receive No Buffers = %lld\n",
3445 	    (long long)sc->stats.rnbc);
3446 	/* RLEC is inaccurate on some hardware, calculate our own. */
3447 	device_printf(dev, "Receive Length Errors = %lld\n",
3448 	    ((long long)sc->stats.roc + (long long)sc->stats.ruc));
3449 	device_printf(dev, "Receive errors = %lld\n",
3450 	    (long long)sc->stats.rxerrc);
3451 	device_printf(dev, "Crc errors = %lld\n",
3452 	    (long long)sc->stats.crcerrs);
3453 	device_printf(dev, "Alignment errors = %lld\n",
3454 	    (long long)sc->stats.algnerrc);
3455 	device_printf(dev, "Collision/Carrier extension errors = %lld\n",
3456 	    (long long)sc->stats.cexterr);
3457 	device_printf(dev, "RX overruns = %ld\n", sc->rx_overruns);
3458 	device_printf(dev, "XON Rcvd = %lld\n",
3459 	    (long long)sc->stats.xonrxc);
3460 	device_printf(dev, "XON Xmtd = %lld\n",
3461 	    (long long)sc->stats.xontxc);
3462 	device_printf(dev, "XOFF Rcvd = %lld\n",
3463 	    (long long)sc->stats.xoffrxc);
3464 	device_printf(dev, "XOFF Xmtd = %lld\n",
3465 	    (long long)sc->stats.xofftxc);
3466 	device_printf(dev, "Good Packets Rcvd = %lld\n",
3467 	    (long long)sc->stats.gprc);
3468 	device_printf(dev, "Good Packets Xmtd = %lld\n",
3469 	    (long long)sc->stats.gptc);
3470 }
3471 
3472 static void
3473 emx_print_nvm_info(struct emx_softc *sc)
3474 {
3475 	uint16_t eeprom_data;
3476 	int i, j, row = 0;
3477 
3478 	/* Its a bit crude, but it gets the job done */
3479 	kprintf("\nInterface EEPROM Dump:\n");
3480 	kprintf("Offset\n0x0000  ");
3481 	for (i = 0, j = 0; i < 32; i++, j++) {
3482 		if (j == 8) { /* Make the offset block */
3483 			j = 0; ++row;
3484 			kprintf("\n0x00%x0  ",row);
3485 		}
3486 		e1000_read_nvm(&sc->hw, i, 1, &eeprom_data);
3487 		kprintf("%04x ", eeprom_data);
3488 	}
3489 	kprintf("\n");
3490 }
3491 
3492 static int
3493 emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
3494 {
3495 	struct emx_softc *sc;
3496 	struct ifnet *ifp;
3497 	int error, result;
3498 
3499 	result = -1;
3500 	error = sysctl_handle_int(oidp, &result, 0, req);
3501 	if (error || !req->newptr)
3502 		return (error);
3503 
3504 	sc = (struct emx_softc *)arg1;
3505 	ifp = &sc->arpcom.ac_if;
3506 
3507 	ifnet_serialize_all(ifp);
3508 
3509 	if (result == 1)
3510 		emx_print_debug_info(sc);
3511 
3512 	/*
3513 	 * This value will cause a hex dump of the
3514 	 * first 32 16-bit words of the EEPROM to
3515 	 * the screen.
3516 	 */
3517 	if (result == 2)
3518 		emx_print_nvm_info(sc);
3519 
3520 	ifnet_deserialize_all(ifp);
3521 
3522 	return (error);
3523 }
3524 
3525 static int
3526 emx_sysctl_stats(SYSCTL_HANDLER_ARGS)
3527 {
3528 	int error, result;
3529 
3530 	result = -1;
3531 	error = sysctl_handle_int(oidp, &result, 0, req);
3532 	if (error || !req->newptr)
3533 		return (error);
3534 
3535 	if (result == 1) {
3536 		struct emx_softc *sc = (struct emx_softc *)arg1;
3537 		struct ifnet *ifp = &sc->arpcom.ac_if;
3538 
3539 		ifnet_serialize_all(ifp);
3540 		emx_print_hw_stats(sc);
3541 		ifnet_deserialize_all(ifp);
3542 	}
3543 	return (error);
3544 }
3545 
3546 static void
3547 emx_add_sysctl(struct emx_softc *sc)
3548 {
3549 #if defined(EMX_RSS_DEBUG) || defined(EMX_TSS_DEBUG)
3550 	char pkt_desc[32];
3551 	int i;
3552 #endif
3553 
3554 	sysctl_ctx_init(&sc->sysctl_ctx);
3555 	sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
3556 				SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
3557 				device_get_nameunit(sc->dev),
3558 				CTLFLAG_RD, 0, "");
3559 	if (sc->sysctl_tree == NULL) {
3560 		device_printf(sc->dev, "can't add sysctl node\n");
3561 		return;
3562 	}
3563 
3564 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3565 			OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3566 			emx_sysctl_debug_info, "I", "Debug Information");
3567 
3568 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3569 			OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3570 			emx_sysctl_stats, "I", "Statistics");
3571 
3572 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3573 	    OID_AUTO, "rxd", CTLFLAG_RD, &sc->rx_data[0].num_rx_desc, 0,
3574 	    "# of RX descs");
3575 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3576 	    OID_AUTO, "txd", CTLFLAG_RD, &sc->tx_data[0].num_tx_desc, 0,
3577 	    "# of TX descs");
3578 
3579 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3580 	    OID_AUTO, "int_throttle_ceil", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3581 	    emx_sysctl_int_throttle, "I", "interrupt throttling rate");
3582 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3583 	    OID_AUTO, "tx_intr_nsegs", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3584 	    emx_sysctl_tx_intr_nsegs, "I", "# segments per TX interrupt");
3585 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3586 	    OID_AUTO, "tx_wreg_nsegs", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3587 	    emx_sysctl_tx_wreg_nsegs, "I",
3588 	    "# segments sent before write to hardware register");
3589 
3590 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3591 	    OID_AUTO, "rx_ring_cnt", CTLFLAG_RD, &sc->rx_ring_cnt, 0,
3592 	    "# of RX rings");
3593 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3594 	    OID_AUTO, "tx_ring_cnt", CTLFLAG_RD, &sc->tx_ring_cnt, 0,
3595 	    "# of TX rings");
3596 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3597 	    OID_AUTO, "tx_ring_inuse", CTLFLAG_RD, &sc->tx_ring_inuse, 0,
3598 	    "# of TX rings used");
3599 
3600 #ifdef IFPOLL_ENABLE
3601 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3602 			OID_AUTO, "npoll_rxoff", CTLTYPE_INT|CTLFLAG_RW,
3603 			sc, 0, emx_sysctl_npoll_rxoff, "I",
3604 			"NPOLLING RX cpu offset");
3605 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3606 			OID_AUTO, "npoll_txoff", CTLTYPE_INT|CTLFLAG_RW,
3607 			sc, 0, emx_sysctl_npoll_txoff, "I",
3608 			"NPOLLING TX cpu offset");
3609 #endif
3610 
3611 #ifdef EMX_RSS_DEBUG
3612 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3613 		       OID_AUTO, "rss_debug", CTLFLAG_RW, &sc->rss_debug,
3614 		       0, "RSS debug level");
3615 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3616 		ksnprintf(pkt_desc, sizeof(pkt_desc), "rx%d_pkt", i);
3617 		SYSCTL_ADD_ULONG(&sc->sysctl_ctx,
3618 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
3619 		    pkt_desc, CTLFLAG_RW, &sc->rx_data[i].rx_pkts,
3620 		    "RXed packets");
3621 	}
3622 #endif
3623 #ifdef EMX_TSS_DEBUG
3624 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3625 		ksnprintf(pkt_desc, sizeof(pkt_desc), "tx%d_pkt", i);
3626 		SYSCTL_ADD_ULONG(&sc->sysctl_ctx,
3627 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
3628 		    pkt_desc, CTLFLAG_RW, &sc->tx_data[i].tx_pkts,
3629 		    "TXed packets");
3630 	}
3631 #endif
3632 }
3633 
3634 static int
3635 emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
3636 {
3637 	struct emx_softc *sc = (void *)arg1;
3638 	struct ifnet *ifp = &sc->arpcom.ac_if;
3639 	int error, throttle;
3640 
3641 	throttle = sc->int_throttle_ceil;
3642 	error = sysctl_handle_int(oidp, &throttle, 0, req);
3643 	if (error || req->newptr == NULL)
3644 		return error;
3645 	if (throttle < 0 || throttle > 1000000000 / 256)
3646 		return EINVAL;
3647 
3648 	if (throttle) {
3649 		/*
3650 		 * Set the interrupt throttling rate in 256ns increments,
3651 		 * recalculate sysctl value assignment to get exact frequency.
3652 		 */
3653 		throttle = 1000000000 / 256 / throttle;
3654 
3655 		/* Upper 16bits of ITR is reserved and should be zero */
3656 		if (throttle & 0xffff0000)
3657 			return EINVAL;
3658 	}
3659 
3660 	ifnet_serialize_all(ifp);
3661 
3662 	if (throttle)
3663 		sc->int_throttle_ceil = 1000000000 / 256 / throttle;
3664 	else
3665 		sc->int_throttle_ceil = 0;
3666 
3667 	if (ifp->if_flags & IFF_RUNNING)
3668 		emx_set_itr(sc, throttle);
3669 
3670 	ifnet_deserialize_all(ifp);
3671 
3672 	if (bootverbose) {
3673 		if_printf(ifp, "Interrupt moderation set to %d/sec\n",
3674 			  sc->int_throttle_ceil);
3675 	}
3676 	return 0;
3677 }
3678 
3679 static int
3680 emx_sysctl_tx_intr_nsegs(SYSCTL_HANDLER_ARGS)
3681 {
3682 	struct emx_softc *sc = (void *)arg1;
3683 	struct ifnet *ifp = &sc->arpcom.ac_if;
3684 	struct emx_txdata *tdata = &sc->tx_data[0];
3685 	int error, segs;
3686 
3687 	segs = tdata->tx_intr_nsegs;
3688 	error = sysctl_handle_int(oidp, &segs, 0, req);
3689 	if (error || req->newptr == NULL)
3690 		return error;
3691 	if (segs <= 0)
3692 		return EINVAL;
3693 
3694 	ifnet_serialize_all(ifp);
3695 
3696 	/*
3697 	 * Don't allow tx_intr_nsegs to become:
3698 	 * o  Less the oact_tx_desc
3699 	 * o  Too large that no TX desc will cause TX interrupt to
3700 	 *    be generated (OACTIVE will never recover)
3701 	 * o  Too small that will cause tx_dd[] overflow
3702 	 */
3703 	if (segs < tdata->oact_tx_desc ||
3704 	    segs >= tdata->num_tx_desc - tdata->oact_tx_desc ||
3705 	    segs < tdata->num_tx_desc / EMX_TXDD_SAFE) {
3706 		error = EINVAL;
3707 	} else {
3708 		int i;
3709 
3710 		error = 0;
3711 		for (i = 0; i < sc->tx_ring_cnt; ++i)
3712 			sc->tx_data[i].tx_intr_nsegs = segs;
3713 	}
3714 
3715 	ifnet_deserialize_all(ifp);
3716 
3717 	return error;
3718 }
3719 
3720 static int
3721 emx_sysctl_tx_wreg_nsegs(SYSCTL_HANDLER_ARGS)
3722 {
3723 	struct emx_softc *sc = (void *)arg1;
3724 	struct ifnet *ifp = &sc->arpcom.ac_if;
3725 	int error, nsegs, i;
3726 
3727 	nsegs = sc->tx_data[0].tx_wreg_nsegs;
3728 	error = sysctl_handle_int(oidp, &nsegs, 0, req);
3729 	if (error || req->newptr == NULL)
3730 		return error;
3731 
3732 	ifnet_serialize_all(ifp);
3733 	for (i = 0; i < sc->tx_ring_cnt; ++i)
3734 		sc->tx_data[i].tx_wreg_nsegs =nsegs;
3735 	ifnet_deserialize_all(ifp);
3736 
3737 	return 0;
3738 }
3739 
3740 #ifdef IFPOLL_ENABLE
3741 
3742 static int
3743 emx_sysctl_npoll_rxoff(SYSCTL_HANDLER_ARGS)
3744 {
3745 	struct emx_softc *sc = (void *)arg1;
3746 	struct ifnet *ifp = &sc->arpcom.ac_if;
3747 	int error, off;
3748 
3749 	off = sc->rx_npoll_off;
3750 	error = sysctl_handle_int(oidp, &off, 0, req);
3751 	if (error || req->newptr == NULL)
3752 		return error;
3753 	if (off < 0)
3754 		return EINVAL;
3755 
3756 	ifnet_serialize_all(ifp);
3757 	if (off >= ncpus2 || off % sc->rx_ring_cnt != 0) {
3758 		error = EINVAL;
3759 	} else {
3760 		error = 0;
3761 		sc->rx_npoll_off = off;
3762 	}
3763 	ifnet_deserialize_all(ifp);
3764 
3765 	return error;
3766 }
3767 
3768 static int
3769 emx_sysctl_npoll_txoff(SYSCTL_HANDLER_ARGS)
3770 {
3771 	struct emx_softc *sc = (void *)arg1;
3772 	struct ifnet *ifp = &sc->arpcom.ac_if;
3773 	int error, off;
3774 
3775 	off = sc->tx_npoll_off;
3776 	error = sysctl_handle_int(oidp, &off, 0, req);
3777 	if (error || req->newptr == NULL)
3778 		return error;
3779 	if (off < 0)
3780 		return EINVAL;
3781 
3782 	ifnet_serialize_all(ifp);
3783 	if (off >= ncpus2 || off % sc->tx_ring_cnt != 0) {
3784 		error = EINVAL;
3785 	} else {
3786 		error = 0;
3787 		sc->tx_npoll_off = off;
3788 	}
3789 	ifnet_deserialize_all(ifp);
3790 
3791 	return error;
3792 }
3793 
3794 #endif	/* IFPOLL_ENABLE */
3795 
3796 static int
3797 emx_dma_alloc(struct emx_softc *sc)
3798 {
3799 	int error, i;
3800 
3801 	/*
3802 	 * Create top level busdma tag
3803 	 */
3804 	error = bus_dma_tag_create(NULL, 1, 0,
3805 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
3806 			NULL, NULL,
3807 			BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
3808 			0, &sc->parent_dtag);
3809 	if (error) {
3810 		device_printf(sc->dev, "could not create top level DMA tag\n");
3811 		return error;
3812 	}
3813 
3814 	/*
3815 	 * Allocate transmit descriptors ring and buffers
3816 	 */
3817 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3818 		error = emx_create_tx_ring(&sc->tx_data[i]);
3819 		if (error) {
3820 			device_printf(sc->dev,
3821 			    "Could not setup transmit structures\n");
3822 			return error;
3823 		}
3824 	}
3825 
3826 	/*
3827 	 * Allocate receive descriptors ring and buffers
3828 	 */
3829 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3830 		error = emx_create_rx_ring(&sc->rx_data[i]);
3831 		if (error) {
3832 			device_printf(sc->dev,
3833 			    "Could not setup receive structures\n");
3834 			return error;
3835 		}
3836 	}
3837 	return 0;
3838 }
3839 
3840 static void
3841 emx_dma_free(struct emx_softc *sc)
3842 {
3843 	int i;
3844 
3845 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3846 		emx_destroy_tx_ring(&sc->tx_data[i],
3847 		    sc->tx_data[i].num_tx_desc);
3848 	}
3849 
3850 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3851 		emx_destroy_rx_ring(&sc->rx_data[i],
3852 		    sc->rx_data[i].num_rx_desc);
3853 	}
3854 
3855 	/* Free top level busdma tag */
3856 	if (sc->parent_dtag != NULL)
3857 		bus_dma_tag_destroy(sc->parent_dtag);
3858 }
3859 
3860 static void
3861 emx_serialize(struct ifnet *ifp, enum ifnet_serialize slz)
3862 {
3863 	struct emx_softc *sc = ifp->if_softc;
3864 
3865 	ifnet_serialize_array_enter(sc->serializes, EMX_NSERIALIZE,
3866 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3867 }
3868 
3869 static void
3870 emx_deserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3871 {
3872 	struct emx_softc *sc = ifp->if_softc;
3873 
3874 	ifnet_serialize_array_exit(sc->serializes, EMX_NSERIALIZE,
3875 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3876 }
3877 
3878 static int
3879 emx_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3880 {
3881 	struct emx_softc *sc = ifp->if_softc;
3882 
3883 	return ifnet_serialize_array_try(sc->serializes, EMX_NSERIALIZE,
3884 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3885 }
3886 
3887 static void
3888 emx_serialize_skipmain(struct emx_softc *sc)
3889 {
3890 	lwkt_serialize_array_enter(sc->serializes, EMX_NSERIALIZE, 1);
3891 }
3892 
3893 static void
3894 emx_deserialize_skipmain(struct emx_softc *sc)
3895 {
3896 	lwkt_serialize_array_exit(sc->serializes, EMX_NSERIALIZE, 1);
3897 }
3898 
3899 #ifdef INVARIANTS
3900 
3901 static void
3902 emx_serialize_assert(struct ifnet *ifp, enum ifnet_serialize slz,
3903     boolean_t serialized)
3904 {
3905 	struct emx_softc *sc = ifp->if_softc;
3906 
3907 	ifnet_serialize_array_assert(sc->serializes, EMX_NSERIALIZE,
3908 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz, serialized);
3909 }
3910 
3911 #endif	/* INVARIANTS */
3912 
3913 #ifdef IFPOLL_ENABLE
3914 
3915 static void
3916 emx_npoll_status(struct ifnet *ifp)
3917 {
3918 	struct emx_softc *sc = ifp->if_softc;
3919 	uint32_t reg_icr;
3920 
3921 	ASSERT_SERIALIZED(&sc->main_serialize);
3922 
3923 	reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
3924 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
3925 		callout_stop(&sc->timer);
3926 		sc->hw.mac.get_link_status = 1;
3927 		emx_update_link_status(sc);
3928 		callout_reset(&sc->timer, hz, emx_timer, sc);
3929 	}
3930 }
3931 
3932 static void
3933 emx_npoll_tx(struct ifnet *ifp, void *arg, int cycle __unused)
3934 {
3935 	struct emx_txdata *tdata = arg;
3936 
3937 	ASSERT_SERIALIZED(&tdata->tx_serialize);
3938 
3939 	emx_txeof(tdata);
3940 	if (!ifsq_is_empty(tdata->ifsq))
3941 		ifsq_devstart(tdata->ifsq);
3942 }
3943 
3944 static void
3945 emx_npoll_rx(struct ifnet *ifp __unused, void *arg, int cycle)
3946 {
3947 	struct emx_rxdata *rdata = arg;
3948 
3949 	ASSERT_SERIALIZED(&rdata->rx_serialize);
3950 
3951 	emx_rxeof(rdata, cycle);
3952 }
3953 
3954 static void
3955 emx_npoll(struct ifnet *ifp, struct ifpoll_info *info)
3956 {
3957 	struct emx_softc *sc = ifp->if_softc;
3958 	int i, txr_cnt;
3959 
3960 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
3961 
3962 	if (info) {
3963 		int off;
3964 
3965 		info->ifpi_status.status_func = emx_npoll_status;
3966 		info->ifpi_status.serializer = &sc->main_serialize;
3967 
3968 		txr_cnt = emx_get_txring_inuse(sc, TRUE);
3969 		off = sc->tx_npoll_off;
3970 		for (i = 0; i < txr_cnt; ++i) {
3971 			struct emx_txdata *tdata = &sc->tx_data[i];
3972 			int idx = i + off;
3973 
3974 			KKASSERT(idx < ncpus2);
3975 			info->ifpi_tx[idx].poll_func = emx_npoll_tx;
3976 			info->ifpi_tx[idx].arg = tdata;
3977 			info->ifpi_tx[idx].serializer = &tdata->tx_serialize;
3978 			ifsq_set_cpuid(tdata->ifsq, idx);
3979 		}
3980 
3981 		off = sc->rx_npoll_off;
3982 		for (i = 0; i < sc->rx_ring_cnt; ++i) {
3983 			struct emx_rxdata *rdata = &sc->rx_data[i];
3984 			int idx = i + off;
3985 
3986 			KKASSERT(idx < ncpus2);
3987 			info->ifpi_rx[idx].poll_func = emx_npoll_rx;
3988 			info->ifpi_rx[idx].arg = rdata;
3989 			info->ifpi_rx[idx].serializer = &rdata->rx_serialize;
3990 		}
3991 
3992 		if (ifp->if_flags & IFF_RUNNING) {
3993 			if (txr_cnt == sc->tx_ring_inuse)
3994 				emx_disable_intr(sc);
3995 			else
3996 				emx_init(sc);
3997 		}
3998 	} else {
3999 		for (i = 0; i < sc->tx_ring_cnt; ++i) {
4000 			struct emx_txdata *tdata = &sc->tx_data[i];
4001 
4002 			ifsq_set_cpuid(tdata->ifsq,
4003 			    rman_get_cpuid(sc->intr_res));
4004 		}
4005 
4006 		if (ifp->if_flags & IFF_RUNNING) {
4007 			txr_cnt = emx_get_txring_inuse(sc, FALSE);
4008 			if (txr_cnt == sc->tx_ring_inuse)
4009 				emx_enable_intr(sc);
4010 			else
4011 				emx_init(sc);
4012 		}
4013 	}
4014 }
4015 
4016 #endif	/* IFPOLL_ENABLE */
4017 
4018 static void
4019 emx_set_itr(struct emx_softc *sc, uint32_t itr)
4020 {
4021 	E1000_WRITE_REG(&sc->hw, E1000_ITR, itr);
4022 	if (sc->hw.mac.type == e1000_82574) {
4023 		int i;
4024 
4025 		/*
4026 		 * When using MSIX interrupts we need to
4027 		 * throttle using the EITR register
4028 		 */
4029 		for (i = 0; i < 4; ++i)
4030 			E1000_WRITE_REG(&sc->hw, E1000_EITR_82574(i), itr);
4031 	}
4032 }
4033 
4034 /*
4035  * Disable the L0s, 82574L Errata #20
4036  */
4037 static void
4038 emx_disable_aspm(struct emx_softc *sc)
4039 {
4040 	uint16_t link_cap, link_ctrl, disable;
4041 	uint8_t pcie_ptr, reg;
4042 	device_t dev = sc->dev;
4043 
4044 	switch (sc->hw.mac.type) {
4045 	case e1000_82571:
4046 	case e1000_82572:
4047 	case e1000_82573:
4048 		/*
4049 		 * 82573 specification update
4050 		 * errata #8 disable L0s
4051 		 * errata #41 disable L1
4052 		 *
4053 		 * 82571/82572 specification update
4054 		 # errata #13 disable L1
4055 		 * errata #68 disable L0s
4056 		 */
4057 		disable = PCIEM_LNKCTL_ASPM_L0S | PCIEM_LNKCTL_ASPM_L1;
4058 		break;
4059 
4060 	case e1000_82574:
4061 		/*
4062 		 * 82574 specification update errata #20
4063 		 *
4064 		 * There is no need to disable L1
4065 		 */
4066 		disable = PCIEM_LNKCTL_ASPM_L0S;
4067 		break;
4068 
4069 	default:
4070 		return;
4071 	}
4072 
4073 	pcie_ptr = pci_get_pciecap_ptr(dev);
4074 	if (pcie_ptr == 0)
4075 		return;
4076 
4077 	link_cap = pci_read_config(dev, pcie_ptr + PCIER_LINKCAP, 2);
4078 	if ((link_cap & PCIEM_LNKCAP_ASPM_MASK) == 0)
4079 		return;
4080 
4081 	if (bootverbose)
4082 		if_printf(&sc->arpcom.ac_if, "disable ASPM %#02x\n", disable);
4083 
4084 	reg = pcie_ptr + PCIER_LINKCTRL;
4085 	link_ctrl = pci_read_config(dev, reg, 2);
4086 	link_ctrl &= ~disable;
4087 	pci_write_config(dev, reg, link_ctrl, 2);
4088 }
4089 
4090 static int
4091 emx_tso_pullup(struct emx_txdata *tdata, struct mbuf **mp)
4092 {
4093 	int iphlen, hoff, thoff, ex = 0;
4094 	struct mbuf *m;
4095 	struct ip *ip;
4096 
4097 	m = *mp;
4098 	KASSERT(M_WRITABLE(m), ("TSO mbuf not writable"));
4099 
4100 	iphlen = m->m_pkthdr.csum_iphlen;
4101 	thoff = m->m_pkthdr.csum_thlen;
4102 	hoff = m->m_pkthdr.csum_lhlen;
4103 
4104 	KASSERT(iphlen > 0, ("invalid ip hlen"));
4105 	KASSERT(thoff > 0, ("invalid tcp hlen"));
4106 	KASSERT(hoff > 0, ("invalid ether hlen"));
4107 
4108 	if (tdata->tx_flags & EMX_TXFLAG_TSO_PULLEX)
4109 		ex = 4;
4110 
4111 	if (m->m_len < hoff + iphlen + thoff + ex) {
4112 		m = m_pullup(m, hoff + iphlen + thoff + ex);
4113 		if (m == NULL) {
4114 			*mp = NULL;
4115 			return ENOBUFS;
4116 		}
4117 		*mp = m;
4118 	}
4119 	ip = mtodoff(m, struct ip *, hoff);
4120 	ip->ip_len = 0;
4121 
4122 	return 0;
4123 }
4124 
4125 static int
4126 emx_tso_setup(struct emx_txdata *tdata, struct mbuf *mp,
4127     uint32_t *txd_upper, uint32_t *txd_lower)
4128 {
4129 	struct e1000_context_desc *TXD;
4130 	int hoff, iphlen, thoff, hlen;
4131 	int mss, pktlen, curr_txd;
4132 
4133 #ifdef EMX_TSO_DEBUG
4134 	tdata->tso_segments++;
4135 #endif
4136 
4137 	iphlen = mp->m_pkthdr.csum_iphlen;
4138 	thoff = mp->m_pkthdr.csum_thlen;
4139 	hoff = mp->m_pkthdr.csum_lhlen;
4140 	mss = mp->m_pkthdr.tso_segsz;
4141 	pktlen = mp->m_pkthdr.len;
4142 
4143 	if ((tdata->tx_flags & EMX_TXFLAG_FORCECTX) == 0 &&
4144 	    tdata->csum_flags == CSUM_TSO &&
4145 	    tdata->csum_iphlen == iphlen &&
4146 	    tdata->csum_lhlen == hoff &&
4147 	    tdata->csum_thlen == thoff &&
4148 	    tdata->csum_mss == mss &&
4149 	    tdata->csum_pktlen == pktlen) {
4150 		*txd_upper = tdata->csum_txd_upper;
4151 		*txd_lower = tdata->csum_txd_lower;
4152 #ifdef EMX_TSO_DEBUG
4153 		tdata->tso_ctx_reused++;
4154 #endif
4155 		return 0;
4156 	}
4157 	hlen = hoff + iphlen + thoff;
4158 
4159 	/*
4160 	 * Setup a new TSO context.
4161 	 */
4162 
4163 	curr_txd = tdata->next_avail_tx_desc;
4164 	TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
4165 
4166 	*txd_lower = E1000_TXD_CMD_DEXT |	/* Extended descr type */
4167 		     E1000_TXD_DTYP_D |		/* Data descr type */
4168 		     E1000_TXD_CMD_TSE;		/* Do TSE on this packet */
4169 
4170 	/* IP and/or TCP header checksum calculation and insertion. */
4171 	*txd_upper = (E1000_TXD_POPTS_IXSM | E1000_TXD_POPTS_TXSM) << 8;
4172 
4173 	/*
4174 	 * Start offset for header checksum calculation.
4175 	 * End offset for header checksum calculation.
4176 	 * Offset of place put the checksum.
4177 	 */
4178 	TXD->lower_setup.ip_fields.ipcss = hoff;
4179 	TXD->lower_setup.ip_fields.ipcse = htole16(hoff + iphlen - 1);
4180 	TXD->lower_setup.ip_fields.ipcso = hoff + offsetof(struct ip, ip_sum);
4181 
4182 	/*
4183 	 * Start offset for payload checksum calculation.
4184 	 * End offset for payload checksum calculation.
4185 	 * Offset of place to put the checksum.
4186 	 */
4187 	TXD->upper_setup.tcp_fields.tucss = hoff + iphlen;
4188 	TXD->upper_setup.tcp_fields.tucse = 0;
4189 	TXD->upper_setup.tcp_fields.tucso =
4190 	    hoff + iphlen + offsetof(struct tcphdr, th_sum);
4191 
4192 	/*
4193 	 * Payload size per packet w/o any headers.
4194 	 * Length of all headers up to payload.
4195 	 */
4196 	TXD->tcp_seg_setup.fields.mss = htole16(mss);
4197 	TXD->tcp_seg_setup.fields.hdr_len = hlen;
4198 	TXD->cmd_and_length = htole32(E1000_TXD_CMD_IFCS |
4199 				E1000_TXD_CMD_DEXT |	/* Extended descr */
4200 				E1000_TXD_CMD_TSE |	/* TSE context */
4201 				E1000_TXD_CMD_IP |	/* Do IP csum */
4202 				E1000_TXD_CMD_TCP |	/* Do TCP checksum */
4203 				(pktlen - hlen));	/* Total len */
4204 
4205 	/* Save the information for this TSO context */
4206 	tdata->csum_flags = CSUM_TSO;
4207 	tdata->csum_lhlen = hoff;
4208 	tdata->csum_iphlen = iphlen;
4209 	tdata->csum_thlen = thoff;
4210 	tdata->csum_mss = mss;
4211 	tdata->csum_pktlen = pktlen;
4212 	tdata->csum_txd_upper = *txd_upper;
4213 	tdata->csum_txd_lower = *txd_lower;
4214 
4215 	if (++curr_txd == tdata->num_tx_desc)
4216 		curr_txd = 0;
4217 
4218 	KKASSERT(tdata->num_tx_desc_avail > 0);
4219 	tdata->num_tx_desc_avail--;
4220 
4221 	tdata->next_avail_tx_desc = curr_txd;
4222 	return 1;
4223 }
4224 
4225 static int
4226 emx_get_txring_inuse(const struct emx_softc *sc, boolean_t polling)
4227 {
4228 	if (polling)
4229 		return sc->tx_ring_cnt;
4230 	else
4231 		return 1;
4232 }
4233