xref: /dflybsd-src/sys/dev/netif/emx/if_emx.c (revision 4c77af2da1d56e9bf10a0f03e974dbbf6a967810)
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 	DEVMETHOD_END
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 	int error = 0, i, throttle, msi_enable, tx_ring_max;
423 	u_int intr_flags;
424 	uint16_t eeprom_data, device_id, apme_mask;
425 	driver_intr_t *intr_func;
426 #ifdef IFPOLL_ENABLE
427 	int offset, offset_def;
428 #endif
429 
430 	/*
431 	 * Setup RX rings
432 	 */
433 	for (i = 0; i < EMX_NRX_RING; ++i) {
434 		sc->rx_data[i].sc = sc;
435 		sc->rx_data[i].idx = i;
436 	}
437 
438 	/*
439 	 * Setup TX ring
440 	 */
441 	for (i = 0; i < EMX_NTX_RING; ++i) {
442 		sc->tx_data[i].sc = sc;
443 		sc->tx_data[i].idx = i;
444 	}
445 
446 	/*
447 	 * Initialize serializers
448 	 */
449 	lwkt_serialize_init(&sc->main_serialize);
450 	for (i = 0; i < EMX_NTX_RING; ++i)
451 		lwkt_serialize_init(&sc->tx_data[i].tx_serialize);
452 	for (i = 0; i < EMX_NRX_RING; ++i)
453 		lwkt_serialize_init(&sc->rx_data[i].rx_serialize);
454 
455 	/*
456 	 * Initialize serializer array
457 	 */
458 	i = 0;
459 	sc->serializes[i++] = &sc->main_serialize;
460 
461 	KKASSERT(i == EMX_TX_SERIALIZE);
462 	sc->serializes[i++] = &sc->tx_data[0].tx_serialize;
463 	sc->serializes[i++] = &sc->tx_data[1].tx_serialize;
464 
465 	KKASSERT(i == EMX_RX_SERIALIZE);
466 	sc->serializes[i++] = &sc->rx_data[0].rx_serialize;
467 	sc->serializes[i++] = &sc->rx_data[1].rx_serialize;
468 	KKASSERT(i == EMX_NSERIALIZE);
469 
470 	callout_init_mp(&sc->timer);
471 
472 	sc->dev = sc->osdep.dev = dev;
473 
474 	/*
475 	 * Determine hardware and mac type
476 	 */
477 	sc->hw.vendor_id = pci_get_vendor(dev);
478 	sc->hw.device_id = pci_get_device(dev);
479 	sc->hw.revision_id = pci_get_revid(dev);
480 	sc->hw.subsystem_vendor_id = pci_get_subvendor(dev);
481 	sc->hw.subsystem_device_id = pci_get_subdevice(dev);
482 
483 	if (e1000_set_mac_type(&sc->hw))
484 		return ENXIO;
485 
486 	/* Enable bus mastering */
487 	pci_enable_busmaster(dev);
488 
489 	/*
490 	 * Allocate IO memory
491 	 */
492 	sc->memory_rid = EMX_BAR_MEM;
493 	sc->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
494 					    &sc->memory_rid, RF_ACTIVE);
495 	if (sc->memory == NULL) {
496 		device_printf(dev, "Unable to allocate bus resource: memory\n");
497 		error = ENXIO;
498 		goto fail;
499 	}
500 	sc->osdep.mem_bus_space_tag = rman_get_bustag(sc->memory);
501 	sc->osdep.mem_bus_space_handle = rman_get_bushandle(sc->memory);
502 
503 	/* XXX This is quite goofy, it is not actually used */
504 	sc->hw.hw_addr = (uint8_t *)&sc->osdep.mem_bus_space_handle;
505 
506 	/*
507 	 * Don't enable MSI-X on 82574, see:
508 	 * 82574 specification update errata #15
509 	 *
510 	 * Don't enable MSI on 82571/82572, see:
511 	 * 82571/82572 specification update errata #63
512 	 */
513 	msi_enable = emx_msi_enable;
514 	if (msi_enable &&
515 	    (sc->hw.mac.type == e1000_82571 ||
516 	     sc->hw.mac.type == e1000_82572))
517 		msi_enable = 0;
518 
519 	/*
520 	 * Allocate interrupt
521 	 */
522 	sc->intr_type = pci_alloc_1intr(dev, msi_enable,
523 	    &sc->intr_rid, &intr_flags);
524 
525 	if (sc->intr_type == PCI_INTR_TYPE_LEGACY) {
526 		int unshared;
527 
528 		unshared = device_getenv_int(dev, "irq.unshared", 0);
529 		if (!unshared) {
530 			sc->flags |= EMX_FLAG_SHARED_INTR;
531 			if (bootverbose)
532 				device_printf(dev, "IRQ shared\n");
533 		} else {
534 			intr_flags &= ~RF_SHAREABLE;
535 			if (bootverbose)
536 				device_printf(dev, "IRQ unshared\n");
537 		}
538 	}
539 
540 	sc->intr_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->intr_rid,
541 	    intr_flags);
542 	if (sc->intr_res == NULL) {
543 		device_printf(dev, "Unable to allocate bus resource: "
544 		    "interrupt\n");
545 		error = ENXIO;
546 		goto fail;
547 	}
548 
549 	/* Save PCI command register for Shared Code */
550 	sc->hw.bus.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
551 	sc->hw.back = &sc->osdep;
552 
553 	/* Do Shared Code initialization */
554 	if (e1000_setup_init_funcs(&sc->hw, TRUE)) {
555 		device_printf(dev, "Setup of Shared code failed\n");
556 		error = ENXIO;
557 		goto fail;
558 	}
559 	e1000_get_bus_info(&sc->hw);
560 
561 	sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
562 	sc->hw.phy.autoneg_wait_to_complete = FALSE;
563 	sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
564 
565 	/*
566 	 * Interrupt throttle rate
567 	 */
568 	throttle = device_getenv_int(dev, "int_throttle_ceil",
569 	    emx_int_throttle_ceil);
570 	if (throttle == 0) {
571 		sc->int_throttle_ceil = 0;
572 	} else {
573 		if (throttle < 0)
574 			throttle = EMX_DEFAULT_ITR;
575 
576 		/* Recalculate the tunable value to get the exact frequency. */
577 		throttle = 1000000000 / 256 / throttle;
578 
579 		/* Upper 16bits of ITR is reserved and should be zero */
580 		if (throttle & 0xffff0000)
581 			throttle = 1000000000 / 256 / EMX_DEFAULT_ITR;
582 
583 		sc->int_throttle_ceil = 1000000000 / 256 / throttle;
584 	}
585 
586 	e1000_init_script_state_82541(&sc->hw, TRUE);
587 	e1000_set_tbi_compatibility_82543(&sc->hw, TRUE);
588 
589 	/* Copper options */
590 	if (sc->hw.phy.media_type == e1000_media_type_copper) {
591 		sc->hw.phy.mdix = EMX_AUTO_ALL_MODES;
592 		sc->hw.phy.disable_polarity_correction = FALSE;
593 		sc->hw.phy.ms_type = EMX_MASTER_SLAVE;
594 	}
595 
596 	/* Set the frame limits assuming standard ethernet sized frames. */
597 	sc->max_frame_size = ETHERMTU + ETHER_HDR_LEN + ETHER_CRC_LEN;
598 	sc->min_frame_size = ETHER_MIN_LEN;
599 
600 	/* This controls when hardware reports transmit completion status. */
601 	sc->hw.mac.report_tx_early = 1;
602 
603 	/* Calculate # of RX rings */
604 	sc->rx_ring_cnt = device_getenv_int(dev, "rxr", emx_rxr);
605 	sc->rx_ring_cnt = if_ring_count2(sc->rx_ring_cnt, EMX_NRX_RING);
606 
607 	/*
608 	 * Calculate # of TX rings
609 	 *
610 	 * NOTE:
611 	 * Don't enable multiple TX queues on 82574; it always gives
612 	 * watchdog timeout when multiple TCP streams are received.
613 	 */
614 	tx_ring_max = 1;
615 	if (sc->hw.mac.type == e1000_82571 ||
616 	    sc->hw.mac.type == e1000_82572 ||
617 	    sc->hw.mac.type == e1000_80003es2lan)
618 		tx_ring_max = EMX_NTX_RING;
619 	sc->tx_ring_cnt = device_getenv_int(dev, "txr", emx_txr);
620 	sc->tx_ring_cnt = if_ring_count2(sc->tx_ring_cnt, tx_ring_max);
621 
622 	/* Allocate RX/TX rings' busdma(9) stuffs */
623 	error = emx_dma_alloc(sc);
624 	if (error)
625 		goto fail;
626 
627 	/* Allocate multicast array memory. */
628 	sc->mta = kmalloc(ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX,
629 	    M_DEVBUF, M_WAITOK);
630 
631 	/* Indicate SOL/IDER usage */
632 	if (e1000_check_reset_block(&sc->hw)) {
633 		device_printf(dev,
634 		    "PHY reset is blocked due to SOL/IDER session.\n");
635 	}
636 
637 	/*
638 	 * Start from a known state, this is important in reading the
639 	 * nvm and mac from that.
640 	 */
641 	e1000_reset_hw(&sc->hw);
642 
643 	/* Make sure we have a good EEPROM before we read from it */
644 	if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
645 		/*
646 		 * Some PCI-E parts fail the first check due to
647 		 * the link being in sleep state, call it again,
648 		 * if it fails a second time its a real issue.
649 		 */
650 		if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
651 			device_printf(dev,
652 			    "The EEPROM Checksum Is Not Valid\n");
653 			error = EIO;
654 			goto fail;
655 		}
656 	}
657 
658 	/* Copy the permanent MAC address out of the EEPROM */
659 	if (e1000_read_mac_addr(&sc->hw) < 0) {
660 		device_printf(dev, "EEPROM read error while reading MAC"
661 		    " address\n");
662 		error = EIO;
663 		goto fail;
664 	}
665 	if (!emx_is_valid_eaddr(sc->hw.mac.addr)) {
666 		device_printf(dev, "Invalid MAC address\n");
667 		error = EIO;
668 		goto fail;
669 	}
670 
671 	/* Determine if we have to control management hardware */
672 	if (e1000_enable_mng_pass_thru(&sc->hw))
673 		sc->flags |= EMX_FLAG_HAS_MGMT;
674 
675 	/*
676 	 * Setup Wake-on-Lan
677 	 */
678 	apme_mask = EMX_EEPROM_APME;
679 	eeprom_data = 0;
680 	switch (sc->hw.mac.type) {
681 	case e1000_82573:
682 		sc->flags |= EMX_FLAG_HAS_AMT;
683 		/* FALL THROUGH */
684 
685 	case e1000_82571:
686 	case e1000_82572:
687 	case e1000_80003es2lan:
688 		if (sc->hw.bus.func == 1) {
689 			e1000_read_nvm(&sc->hw,
690 			    NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
691 		} else {
692 			e1000_read_nvm(&sc->hw,
693 			    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
694 		}
695 		break;
696 
697 	default:
698 		e1000_read_nvm(&sc->hw,
699 		    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
700 		break;
701 	}
702 	if (eeprom_data & apme_mask)
703 		sc->wol = E1000_WUFC_MAG | E1000_WUFC_MC;
704 
705 	/*
706          * We have the eeprom settings, now apply the special cases
707          * where the eeprom may be wrong or the board won't support
708          * wake on lan on a particular port
709 	 */
710 	device_id = pci_get_device(dev);
711         switch (device_id) {
712 	case E1000_DEV_ID_82571EB_FIBER:
713 		/*
714 		 * Wake events only supported on port A for dual fiber
715 		 * regardless of eeprom setting
716 		 */
717 		if (E1000_READ_REG(&sc->hw, E1000_STATUS) &
718 		    E1000_STATUS_FUNC_1)
719 			sc->wol = 0;
720 		break;
721 
722 	case E1000_DEV_ID_82571EB_QUAD_COPPER:
723 	case E1000_DEV_ID_82571EB_QUAD_FIBER:
724 	case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
725                 /* if quad port sc, disable WoL on all but port A */
726 		if (emx_global_quad_port_a != 0)
727 			sc->wol = 0;
728 		/* Reset for multiple quad port adapters */
729 		if (++emx_global_quad_port_a == 4)
730 			emx_global_quad_port_a = 0;
731                 break;
732 	}
733 
734 	/* XXX disable wol */
735 	sc->wol = 0;
736 
737 #ifdef IFPOLL_ENABLE
738 	/*
739 	 * NPOLLING RX CPU offset
740 	 */
741 	if (sc->rx_ring_cnt == ncpus2) {
742 		offset = 0;
743 	} else {
744 		offset_def = (sc->rx_ring_cnt * device_get_unit(dev)) % ncpus2;
745 		offset = device_getenv_int(dev, "npoll.rxoff", offset_def);
746 		if (offset >= ncpus2 ||
747 		    offset % sc->rx_ring_cnt != 0) {
748 			device_printf(dev, "invalid npoll.rxoff %d, use %d\n",
749 			    offset, offset_def);
750 			offset = offset_def;
751 		}
752 	}
753 	sc->rx_npoll_off = offset;
754 
755 	/*
756 	 * NPOLLING TX CPU offset
757 	 */
758 	if (sc->tx_ring_cnt == ncpus2) {
759 		offset = 0;
760 	} else {
761 		offset_def = (sc->tx_ring_cnt * device_get_unit(dev)) % ncpus2;
762 		offset = device_getenv_int(dev, "npoll.txoff", offset_def);
763 		if (offset >= ncpus2 ||
764 		    offset % sc->tx_ring_cnt != 0) {
765 			device_printf(dev, "invalid npoll.txoff %d, use %d\n",
766 			    offset, offset_def);
767 			offset = offset_def;
768 		}
769 	}
770 	sc->tx_npoll_off = offset;
771 #endif
772 	sc->tx_ring_inuse = emx_get_txring_inuse(sc, FALSE);
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 	return (0);
821 fail:
822 	emx_detach(dev);
823 	return (error);
824 }
825 
826 static int
827 emx_detach(device_t dev)
828 {
829 	struct emx_softc *sc = device_get_softc(dev);
830 
831 	if (device_is_attached(dev)) {
832 		struct ifnet *ifp = &sc->arpcom.ac_if;
833 
834 		ifnet_serialize_all(ifp);
835 
836 		emx_stop(sc);
837 
838 		e1000_phy_hw_reset(&sc->hw);
839 
840 		emx_rel_mgmt(sc);
841 		emx_rel_hw_control(sc);
842 
843 		if (sc->wol) {
844 			E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
845 			E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
846 			emx_enable_wol(dev);
847 		}
848 
849 		bus_teardown_intr(dev, sc->intr_res, sc->intr_tag);
850 
851 		ifnet_deserialize_all(ifp);
852 
853 		ether_ifdetach(ifp);
854 	} else if (sc->memory != NULL) {
855 		emx_rel_hw_control(sc);
856 	}
857 	bus_generic_detach(dev);
858 
859 	if (sc->intr_res != NULL) {
860 		bus_release_resource(dev, SYS_RES_IRQ, sc->intr_rid,
861 				     sc->intr_res);
862 	}
863 
864 	if (sc->intr_type == PCI_INTR_TYPE_MSI)
865 		pci_release_msi(dev);
866 
867 	if (sc->memory != NULL) {
868 		bus_release_resource(dev, SYS_RES_MEMORY, sc->memory_rid,
869 				     sc->memory);
870 	}
871 
872 	emx_dma_free(sc);
873 
874 	/* Free sysctl tree */
875 	if (sc->sysctl_tree != NULL)
876 		sysctl_ctx_free(&sc->sysctl_ctx);
877 
878 	if (sc->mta != NULL)
879 		kfree(sc->mta, M_DEVBUF);
880 
881 	return (0);
882 }
883 
884 static int
885 emx_shutdown(device_t dev)
886 {
887 	return emx_suspend(dev);
888 }
889 
890 static int
891 emx_suspend(device_t dev)
892 {
893 	struct emx_softc *sc = device_get_softc(dev);
894 	struct ifnet *ifp = &sc->arpcom.ac_if;
895 
896 	ifnet_serialize_all(ifp);
897 
898 	emx_stop(sc);
899 
900 	emx_rel_mgmt(sc);
901 	emx_rel_hw_control(sc);
902 
903 	if (sc->wol) {
904 		E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
905 		E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
906 		emx_enable_wol(dev);
907 	}
908 
909 	ifnet_deserialize_all(ifp);
910 
911 	return bus_generic_suspend(dev);
912 }
913 
914 static int
915 emx_resume(device_t dev)
916 {
917 	struct emx_softc *sc = device_get_softc(dev);
918 	struct ifnet *ifp = &sc->arpcom.ac_if;
919 	int i;
920 
921 	ifnet_serialize_all(ifp);
922 
923 	emx_init(sc);
924 	emx_get_mgmt(sc);
925 	for (i = 0; i < sc->tx_ring_inuse; ++i)
926 		ifsq_devstart_sched(sc->tx_data[i].ifsq);
927 
928 	ifnet_deserialize_all(ifp);
929 
930 	return bus_generic_resume(dev);
931 }
932 
933 static void
934 emx_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
935 {
936 	struct emx_softc *sc = ifp->if_softc;
937 	struct emx_txdata *tdata = ifsq_get_priv(ifsq);
938 	struct mbuf *m_head;
939 	int idx = -1, nsegs = 0;
940 
941 	KKASSERT(tdata->ifsq == ifsq);
942 	ASSERT_SERIALIZED(&tdata->tx_serialize);
943 
944 	if ((ifp->if_flags & IFF_RUNNING) == 0 || ifsq_is_oactive(ifsq))
945 		return;
946 
947 	if (!sc->link_active || (tdata->tx_flags & EMX_TXFLAG_ENABLED) == 0) {
948 		ifsq_purge(ifsq);
949 		return;
950 	}
951 
952 	while (!ifsq_is_empty(ifsq)) {
953 		/* Now do we at least have a minimal? */
954 		if (EMX_IS_OACTIVE(tdata)) {
955 			emx_tx_collect(tdata);
956 			if (EMX_IS_OACTIVE(tdata)) {
957 				ifsq_set_oactive(ifsq);
958 				break;
959 			}
960 		}
961 
962 		logif(pkt_txqueue);
963 		m_head = ifsq_dequeue(ifsq, NULL);
964 		if (m_head == NULL)
965 			break;
966 
967 		if (emx_encap(tdata, &m_head, &nsegs, &idx)) {
968 			IFNET_STAT_INC(ifp, oerrors, 1);
969 			emx_tx_collect(tdata);
970 			continue;
971 		}
972 
973 		if (nsegs >= tdata->tx_wreg_nsegs) {
974 			E1000_WRITE_REG(&sc->hw, E1000_TDT(tdata->idx), idx);
975 			nsegs = 0;
976 			idx = -1;
977 		}
978 
979 		/* Send a copy of the frame to the BPF listener */
980 		ETHER_BPF_MTAP(ifp, m_head);
981 
982 		/* Set timeout in case hardware has problems transmitting. */
983 		tdata->tx_watchdog.wd_timer = EMX_TX_TIMEOUT;
984 	}
985 	if (idx >= 0)
986 		E1000_WRITE_REG(&sc->hw, E1000_TDT(tdata->idx), idx);
987 }
988 
989 static int
990 emx_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
991 {
992 	struct emx_softc *sc = ifp->if_softc;
993 	struct ifreq *ifr = (struct ifreq *)data;
994 	uint16_t eeprom_data = 0;
995 	int max_frame_size, mask, reinit;
996 	int error = 0;
997 
998 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
999 
1000 	switch (command) {
1001 	case SIOCSIFMTU:
1002 		switch (sc->hw.mac.type) {
1003 		case e1000_82573:
1004 			/*
1005 			 * 82573 only supports jumbo frames
1006 			 * if ASPM is disabled.
1007 			 */
1008 			e1000_read_nvm(&sc->hw, NVM_INIT_3GIO_3, 1,
1009 				       &eeprom_data);
1010 			if (eeprom_data & NVM_WORD1A_ASPM_MASK) {
1011 				max_frame_size = ETHER_MAX_LEN;
1012 				break;
1013 			}
1014 			/* FALL THROUGH */
1015 
1016 		/* Limit Jumbo Frame size */
1017 		case e1000_82571:
1018 		case e1000_82572:
1019 		case e1000_82574:
1020 		case e1000_80003es2lan:
1021 			max_frame_size = 9234;
1022 			break;
1023 
1024 		default:
1025 			max_frame_size = MAX_JUMBO_FRAME_SIZE;
1026 			break;
1027 		}
1028 		if (ifr->ifr_mtu > max_frame_size - ETHER_HDR_LEN -
1029 		    ETHER_CRC_LEN) {
1030 			error = EINVAL;
1031 			break;
1032 		}
1033 
1034 		ifp->if_mtu = ifr->ifr_mtu;
1035 		sc->max_frame_size = ifp->if_mtu + ETHER_HDR_LEN +
1036 				     ETHER_CRC_LEN;
1037 
1038 		if (ifp->if_flags & IFF_RUNNING)
1039 			emx_init(sc);
1040 		break;
1041 
1042 	case SIOCSIFFLAGS:
1043 		if (ifp->if_flags & IFF_UP) {
1044 			if ((ifp->if_flags & IFF_RUNNING)) {
1045 				if ((ifp->if_flags ^ sc->if_flags) &
1046 				    (IFF_PROMISC | IFF_ALLMULTI)) {
1047 					emx_disable_promisc(sc);
1048 					emx_set_promisc(sc);
1049 				}
1050 			} else {
1051 				emx_init(sc);
1052 			}
1053 		} else if (ifp->if_flags & IFF_RUNNING) {
1054 			emx_stop(sc);
1055 		}
1056 		sc->if_flags = ifp->if_flags;
1057 		break;
1058 
1059 	case SIOCADDMULTI:
1060 	case SIOCDELMULTI:
1061 		if (ifp->if_flags & IFF_RUNNING) {
1062 			emx_disable_intr(sc);
1063 			emx_set_multi(sc);
1064 #ifdef IFPOLL_ENABLE
1065 			if (!(ifp->if_flags & IFF_NPOLLING))
1066 #endif
1067 				emx_enable_intr(sc);
1068 		}
1069 		break;
1070 
1071 	case SIOCSIFMEDIA:
1072 		/* Check SOL/IDER usage */
1073 		if (e1000_check_reset_block(&sc->hw)) {
1074 			device_printf(sc->dev, "Media change is"
1075 			    " blocked due to SOL/IDER session.\n");
1076 			break;
1077 		}
1078 		/* FALL THROUGH */
1079 
1080 	case SIOCGIFMEDIA:
1081 		error = ifmedia_ioctl(ifp, ifr, &sc->media, command);
1082 		break;
1083 
1084 	case SIOCSIFCAP:
1085 		reinit = 0;
1086 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1087 		if (mask & IFCAP_RXCSUM) {
1088 			ifp->if_capenable ^= IFCAP_RXCSUM;
1089 			reinit = 1;
1090 		}
1091 		if (mask & IFCAP_VLAN_HWTAGGING) {
1092 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1093 			reinit = 1;
1094 		}
1095 		if (mask & IFCAP_TXCSUM) {
1096 			ifp->if_capenable ^= IFCAP_TXCSUM;
1097 			if (ifp->if_capenable & IFCAP_TXCSUM)
1098 				ifp->if_hwassist |= EMX_CSUM_FEATURES;
1099 			else
1100 				ifp->if_hwassist &= ~EMX_CSUM_FEATURES;
1101 		}
1102 		if (mask & IFCAP_TSO) {
1103 			ifp->if_capenable ^= IFCAP_TSO;
1104 			if (ifp->if_capenable & IFCAP_TSO)
1105 				ifp->if_hwassist |= CSUM_TSO;
1106 			else
1107 				ifp->if_hwassist &= ~CSUM_TSO;
1108 		}
1109 		if (mask & IFCAP_RSS)
1110 			ifp->if_capenable ^= IFCAP_RSS;
1111 		if (reinit && (ifp->if_flags & IFF_RUNNING))
1112 			emx_init(sc);
1113 		break;
1114 
1115 	default:
1116 		error = ether_ioctl(ifp, command, data);
1117 		break;
1118 	}
1119 	return (error);
1120 }
1121 
1122 static void
1123 emx_watchdog(struct ifaltq_subque *ifsq)
1124 {
1125 	struct emx_txdata *tdata = ifsq_get_priv(ifsq);
1126 	struct ifnet *ifp = ifsq_get_ifp(ifsq);
1127 	struct emx_softc *sc = ifp->if_softc;
1128 	int i;
1129 
1130 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1131 
1132 	/*
1133 	 * The timer is set to 5 every time start queues a packet.
1134 	 * Then txeof keeps resetting it as long as it cleans at
1135 	 * least one descriptor.
1136 	 * Finally, anytime all descriptors are clean the timer is
1137 	 * set to 0.
1138 	 */
1139 
1140 	if (E1000_READ_REG(&sc->hw, E1000_TDT(tdata->idx)) ==
1141 	    E1000_READ_REG(&sc->hw, E1000_TDH(tdata->idx))) {
1142 		/*
1143 		 * If we reach here, all TX jobs are completed and
1144 		 * the TX engine should have been idled for some time.
1145 		 * We don't need to call ifsq_devstart_sched() here.
1146 		 */
1147 		ifsq_clr_oactive(ifsq);
1148 		tdata->tx_watchdog.wd_timer = 0;
1149 		return;
1150 	}
1151 
1152 	/*
1153 	 * If we are in this routine because of pause frames, then
1154 	 * don't reset the hardware.
1155 	 */
1156 	if (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_TXOFF) {
1157 		tdata->tx_watchdog.wd_timer = EMX_TX_TIMEOUT;
1158 		return;
1159 	}
1160 
1161 	if_printf(ifp, "TX %d watchdog timeout -- resetting\n", tdata->idx);
1162 
1163 	IFNET_STAT_INC(ifp, oerrors, 1);
1164 
1165 	emx_init(sc);
1166 	for (i = 0; i < sc->tx_ring_inuse; ++i)
1167 		ifsq_devstart_sched(sc->tx_data[i].ifsq);
1168 }
1169 
1170 static void
1171 emx_init(void *xsc)
1172 {
1173 	struct emx_softc *sc = xsc;
1174 	struct ifnet *ifp = &sc->arpcom.ac_if;
1175 	device_t dev = sc->dev;
1176 	boolean_t polling;
1177 	int i;
1178 
1179 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1180 
1181 	emx_stop(sc);
1182 
1183 	/* Get the latest mac address, User can use a LAA */
1184         bcopy(IF_LLADDR(ifp), sc->hw.mac.addr, ETHER_ADDR_LEN);
1185 
1186 	/* Put the address into the Receive Address Array */
1187 	e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1188 
1189 	/*
1190 	 * With the 82571 sc, RAR[0] may be overwritten
1191 	 * when the other port is reset, we make a duplicate
1192 	 * in RAR[14] for that eventuality, this assures
1193 	 * the interface continues to function.
1194 	 */
1195 	if (sc->hw.mac.type == e1000_82571) {
1196 		e1000_set_laa_state_82571(&sc->hw, TRUE);
1197 		e1000_rar_set(&sc->hw, sc->hw.mac.addr,
1198 		    E1000_RAR_ENTRIES - 1);
1199 	}
1200 
1201 	/* Initialize the hardware */
1202 	if (emx_reset(sc)) {
1203 		device_printf(dev, "Unable to reset the hardware\n");
1204 		/* XXX emx_stop()? */
1205 		return;
1206 	}
1207 	emx_update_link_status(sc);
1208 
1209 	/* Setup VLAN support, basic and offload if available */
1210 	E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1211 
1212 	if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1213 		uint32_t ctrl;
1214 
1215 		ctrl = E1000_READ_REG(&sc->hw, E1000_CTRL);
1216 		ctrl |= E1000_CTRL_VME;
1217 		E1000_WRITE_REG(&sc->hw, E1000_CTRL, ctrl);
1218 	}
1219 
1220 	/* Configure for OS presence */
1221 	emx_get_mgmt(sc);
1222 
1223 	polling = FALSE;
1224 #ifdef IFPOLL_ENABLE
1225 	if (ifp->if_flags & IFF_NPOLLING)
1226 		polling = TRUE;
1227 #endif
1228 	sc->tx_ring_inuse = emx_get_txring_inuse(sc, polling);
1229 	ifq_set_subq_mask(&ifp->if_snd, sc->tx_ring_inuse - 1);
1230 
1231 	/* Prepare transmit descriptors and buffers */
1232 	for (i = 0; i < sc->tx_ring_inuse; ++i)
1233 		emx_init_tx_ring(&sc->tx_data[i]);
1234 	emx_init_tx_unit(sc);
1235 
1236 	/* Setup Multicast table */
1237 	emx_set_multi(sc);
1238 
1239 	/* Prepare receive descriptors and buffers */
1240 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
1241 		if (emx_init_rx_ring(&sc->rx_data[i])) {
1242 			device_printf(dev,
1243 			    "Could not setup receive structures\n");
1244 			emx_stop(sc);
1245 			return;
1246 		}
1247 	}
1248 	emx_init_rx_unit(sc);
1249 
1250 	/* Don't lose promiscuous settings */
1251 	emx_set_promisc(sc);
1252 
1253 	ifp->if_flags |= IFF_RUNNING;
1254 	for (i = 0; i < sc->tx_ring_inuse; ++i) {
1255 		ifsq_clr_oactive(sc->tx_data[i].ifsq);
1256 		ifsq_watchdog_start(&sc->tx_data[i].tx_watchdog);
1257 	}
1258 
1259 	callout_reset(&sc->timer, hz, emx_timer, sc);
1260 	e1000_clear_hw_cntrs_base_generic(&sc->hw);
1261 
1262 	/* MSI/X configuration for 82574 */
1263 	if (sc->hw.mac.type == e1000_82574) {
1264 		int tmp;
1265 
1266 		tmp = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
1267 		tmp |= E1000_CTRL_EXT_PBA_CLR;
1268 		E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT, tmp);
1269 		/*
1270 		 * XXX MSIX
1271 		 * Set the IVAR - interrupt vector routing.
1272 		 * Each nibble represents a vector, high bit
1273 		 * is enable, other 3 bits are the MSIX table
1274 		 * entry, we map RXQ0 to 0, TXQ0 to 1, and
1275 		 * Link (other) to 2, hence the magic number.
1276 		 */
1277 		E1000_WRITE_REG(&sc->hw, E1000_IVAR, 0x800A0908);
1278 	}
1279 
1280 	/*
1281 	 * Only enable interrupts if we are not polling, make sure
1282 	 * they are off otherwise.
1283 	 */
1284 	if (polling)
1285 		emx_disable_intr(sc);
1286 	else
1287 		emx_enable_intr(sc);
1288 
1289 	/* AMT based hardware can now take control from firmware */
1290 	if ((sc->flags & (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT)) ==
1291 	    (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT))
1292 		emx_get_hw_control(sc);
1293 }
1294 
1295 static void
1296 emx_intr(void *xsc)
1297 {
1298 	emx_intr_body(xsc, TRUE);
1299 }
1300 
1301 static void
1302 emx_intr_body(struct emx_softc *sc, boolean_t chk_asserted)
1303 {
1304 	struct ifnet *ifp = &sc->arpcom.ac_if;
1305 	uint32_t reg_icr;
1306 
1307 	logif(intr_beg);
1308 	ASSERT_SERIALIZED(&sc->main_serialize);
1309 
1310 	reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
1311 
1312 	if (chk_asserted && (reg_icr & E1000_ICR_INT_ASSERTED) == 0) {
1313 		logif(intr_end);
1314 		return;
1315 	}
1316 
1317 	/*
1318 	 * XXX: some laptops trigger several spurious interrupts
1319 	 * on emx(4) when in the resume cycle. The ICR register
1320 	 * reports all-ones value in this case. Processing such
1321 	 * interrupts would lead to a freeze. I don't know why.
1322 	 */
1323 	if (reg_icr == 0xffffffff) {
1324 		logif(intr_end);
1325 		return;
1326 	}
1327 
1328 	if (ifp->if_flags & IFF_RUNNING) {
1329 		if (reg_icr &
1330 		    (E1000_ICR_RXT0 | E1000_ICR_RXDMT0 | E1000_ICR_RXO)) {
1331 			int i;
1332 
1333 			for (i = 0; i < sc->rx_ring_cnt; ++i) {
1334 				lwkt_serialize_enter(
1335 				&sc->rx_data[i].rx_serialize);
1336 				emx_rxeof(&sc->rx_data[i], -1);
1337 				lwkt_serialize_exit(
1338 				&sc->rx_data[i].rx_serialize);
1339 			}
1340 		}
1341 		if (reg_icr & E1000_ICR_TXDW) {
1342 			struct emx_txdata *tdata = &sc->tx_data[0];
1343 
1344 			lwkt_serialize_enter(&tdata->tx_serialize);
1345 			emx_txeof(tdata);
1346 			if (!ifsq_is_empty(tdata->ifsq))
1347 				ifsq_devstart(tdata->ifsq);
1348 			lwkt_serialize_exit(&tdata->tx_serialize);
1349 		}
1350 	}
1351 
1352 	/* Link status change */
1353 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1354 		emx_serialize_skipmain(sc);
1355 
1356 		callout_stop(&sc->timer);
1357 		sc->hw.mac.get_link_status = 1;
1358 		emx_update_link_status(sc);
1359 
1360 		/* Deal with TX cruft when link lost */
1361 		emx_tx_purge(sc);
1362 
1363 		callout_reset(&sc->timer, hz, emx_timer, sc);
1364 
1365 		emx_deserialize_skipmain(sc);
1366 	}
1367 
1368 	if (reg_icr & E1000_ICR_RXO)
1369 		sc->rx_overruns++;
1370 
1371 	logif(intr_end);
1372 }
1373 
1374 static void
1375 emx_intr_mask(void *xsc)
1376 {
1377 	struct emx_softc *sc = xsc;
1378 
1379 	E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
1380 	/*
1381 	 * NOTE:
1382 	 * ICR.INT_ASSERTED bit will never be set if IMS is 0,
1383 	 * so don't check it.
1384 	 */
1385 	emx_intr_body(sc, FALSE);
1386 	E1000_WRITE_REG(&sc->hw, E1000_IMS, IMS_ENABLE_MASK);
1387 }
1388 
1389 static void
1390 emx_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1391 {
1392 	struct emx_softc *sc = ifp->if_softc;
1393 
1394 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1395 
1396 	emx_update_link_status(sc);
1397 
1398 	ifmr->ifm_status = IFM_AVALID;
1399 	ifmr->ifm_active = IFM_ETHER;
1400 
1401 	if (!sc->link_active)
1402 		return;
1403 
1404 	ifmr->ifm_status |= IFM_ACTIVE;
1405 
1406 	if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1407 	    sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1408 		ifmr->ifm_active |= IFM_1000_SX | IFM_FDX;
1409 	} else {
1410 		switch (sc->link_speed) {
1411 		case 10:
1412 			ifmr->ifm_active |= IFM_10_T;
1413 			break;
1414 		case 100:
1415 			ifmr->ifm_active |= IFM_100_TX;
1416 			break;
1417 
1418 		case 1000:
1419 			ifmr->ifm_active |= IFM_1000_T;
1420 			break;
1421 		}
1422 		if (sc->link_duplex == FULL_DUPLEX)
1423 			ifmr->ifm_active |= IFM_FDX;
1424 		else
1425 			ifmr->ifm_active |= IFM_HDX;
1426 	}
1427 }
1428 
1429 static int
1430 emx_media_change(struct ifnet *ifp)
1431 {
1432 	struct emx_softc *sc = ifp->if_softc;
1433 	struct ifmedia *ifm = &sc->media;
1434 
1435 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1436 
1437 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1438 		return (EINVAL);
1439 
1440 	switch (IFM_SUBTYPE(ifm->ifm_media)) {
1441 	case IFM_AUTO:
1442 		sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1443 		sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
1444 		break;
1445 
1446 	case IFM_1000_LX:
1447 	case IFM_1000_SX:
1448 	case IFM_1000_T:
1449 		sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1450 		sc->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1451 		break;
1452 
1453 	case IFM_100_TX:
1454 		sc->hw.mac.autoneg = FALSE;
1455 		sc->hw.phy.autoneg_advertised = 0;
1456 		if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1457 			sc->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1458 		else
1459 			sc->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1460 		break;
1461 
1462 	case IFM_10_T:
1463 		sc->hw.mac.autoneg = FALSE;
1464 		sc->hw.phy.autoneg_advertised = 0;
1465 		if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1466 			sc->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1467 		else
1468 			sc->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1469 		break;
1470 
1471 	default:
1472 		if_printf(ifp, "Unsupported media type\n");
1473 		break;
1474 	}
1475 
1476 	emx_init(sc);
1477 
1478 	return (0);
1479 }
1480 
1481 static int
1482 emx_encap(struct emx_txdata *tdata, struct mbuf **m_headp,
1483     int *segs_used, int *idx)
1484 {
1485 	bus_dma_segment_t segs[EMX_MAX_SCATTER];
1486 	bus_dmamap_t map;
1487 	struct emx_txbuf *tx_buffer, *tx_buffer_mapped;
1488 	struct e1000_tx_desc *ctxd = NULL;
1489 	struct mbuf *m_head = *m_headp;
1490 	uint32_t txd_upper, txd_lower, cmd = 0;
1491 	int maxsegs, nsegs, i, j, first, last = 0, error;
1492 
1493 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1494 		error = emx_tso_pullup(tdata, m_headp);
1495 		if (error)
1496 			return error;
1497 		m_head = *m_headp;
1498 	}
1499 
1500 	txd_upper = txd_lower = 0;
1501 
1502 	/*
1503 	 * Capture the first descriptor index, this descriptor
1504 	 * will have the index of the EOP which is the only one
1505 	 * that now gets a DONE bit writeback.
1506 	 */
1507 	first = tdata->next_avail_tx_desc;
1508 	tx_buffer = &tdata->tx_buf[first];
1509 	tx_buffer_mapped = tx_buffer;
1510 	map = tx_buffer->map;
1511 
1512 	maxsegs = tdata->num_tx_desc_avail - EMX_TX_RESERVED;
1513 	KASSERT(maxsegs >= tdata->spare_tx_desc, ("not enough spare TX desc"));
1514 	if (maxsegs > EMX_MAX_SCATTER)
1515 		maxsegs = EMX_MAX_SCATTER;
1516 
1517 	error = bus_dmamap_load_mbuf_defrag(tdata->txtag, map, m_headp,
1518 			segs, maxsegs, &nsegs, BUS_DMA_NOWAIT);
1519 	if (error) {
1520 		m_freem(*m_headp);
1521 		*m_headp = NULL;
1522 		return error;
1523 	}
1524         bus_dmamap_sync(tdata->txtag, map, BUS_DMASYNC_PREWRITE);
1525 
1526 	m_head = *m_headp;
1527 	tdata->tx_nsegs += nsegs;
1528 	*segs_used += nsegs;
1529 
1530 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1531 		/* TSO will consume one TX desc */
1532 		i = emx_tso_setup(tdata, m_head, &txd_upper, &txd_lower);
1533 		tdata->tx_nsegs += i;
1534 		*segs_used += i;
1535 	} else if (m_head->m_pkthdr.csum_flags & EMX_CSUM_FEATURES) {
1536 		/* TX csum offloading will consume one TX desc */
1537 		i = emx_txcsum(tdata, m_head, &txd_upper, &txd_lower);
1538 		tdata->tx_nsegs += i;
1539 		*segs_used += i;
1540 	}
1541 	i = tdata->next_avail_tx_desc;
1542 
1543 	/* Set up our transmit descriptors */
1544 	for (j = 0; j < nsegs; j++) {
1545 		tx_buffer = &tdata->tx_buf[i];
1546 		ctxd = &tdata->tx_desc_base[i];
1547 
1548 		ctxd->buffer_addr = htole64(segs[j].ds_addr);
1549 		ctxd->lower.data = htole32(E1000_TXD_CMD_IFCS |
1550 					   txd_lower | segs[j].ds_len);
1551 		ctxd->upper.data = htole32(txd_upper);
1552 
1553 		last = i;
1554 		if (++i == tdata->num_tx_desc)
1555 			i = 0;
1556 	}
1557 
1558 	tdata->next_avail_tx_desc = i;
1559 
1560 	KKASSERT(tdata->num_tx_desc_avail > nsegs);
1561 	tdata->num_tx_desc_avail -= nsegs;
1562 
1563         /* Handle VLAN tag */
1564 	if (m_head->m_flags & M_VLANTAG) {
1565 		/* Set the vlan id. */
1566 		ctxd->upper.fields.special =
1567 		    htole16(m_head->m_pkthdr.ether_vlantag);
1568 
1569 		/* Tell hardware to add tag */
1570 		ctxd->lower.data |= htole32(E1000_TXD_CMD_VLE);
1571 	}
1572 
1573 	tx_buffer->m_head = m_head;
1574 	tx_buffer_mapped->map = tx_buffer->map;
1575 	tx_buffer->map = map;
1576 
1577 	if (tdata->tx_nsegs >= tdata->tx_intr_nsegs) {
1578 		tdata->tx_nsegs = 0;
1579 
1580 		/*
1581 		 * Report Status (RS) is turned on
1582 		 * every tx_intr_nsegs descriptors.
1583 		 */
1584 		cmd = E1000_TXD_CMD_RS;
1585 
1586 		/*
1587 		 * Keep track of the descriptor, which will
1588 		 * be written back by hardware.
1589 		 */
1590 		tdata->tx_dd[tdata->tx_dd_tail] = last;
1591 		EMX_INC_TXDD_IDX(tdata->tx_dd_tail);
1592 		KKASSERT(tdata->tx_dd_tail != tdata->tx_dd_head);
1593 	}
1594 
1595 	/*
1596 	 * Last Descriptor of Packet needs End Of Packet (EOP)
1597 	 */
1598 	ctxd->lower.data |= htole32(E1000_TXD_CMD_EOP | cmd);
1599 
1600 	/*
1601 	 * Defer TDT updating, until enough descriptors are setup
1602 	 */
1603 	*idx = i;
1604 
1605 #ifdef EMX_TSS_DEBUG
1606 	tdata->tx_pkts++;
1607 #endif
1608 
1609 	return (0);
1610 }
1611 
1612 static void
1613 emx_set_promisc(struct emx_softc *sc)
1614 {
1615 	struct ifnet *ifp = &sc->arpcom.ac_if;
1616 	uint32_t reg_rctl;
1617 
1618 	reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1619 
1620 	if (ifp->if_flags & IFF_PROMISC) {
1621 		reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
1622 		/* Turn this on if you want to see bad packets */
1623 		if (emx_debug_sbp)
1624 			reg_rctl |= E1000_RCTL_SBP;
1625 		E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1626 	} else if (ifp->if_flags & IFF_ALLMULTI) {
1627 		reg_rctl |= E1000_RCTL_MPE;
1628 		reg_rctl &= ~E1000_RCTL_UPE;
1629 		E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1630 	}
1631 }
1632 
1633 static void
1634 emx_disable_promisc(struct emx_softc *sc)
1635 {
1636 	uint32_t reg_rctl;
1637 
1638 	reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1639 
1640 	reg_rctl &= ~E1000_RCTL_UPE;
1641 	reg_rctl &= ~E1000_RCTL_MPE;
1642 	reg_rctl &= ~E1000_RCTL_SBP;
1643 	E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1644 }
1645 
1646 static void
1647 emx_set_multi(struct emx_softc *sc)
1648 {
1649 	struct ifnet *ifp = &sc->arpcom.ac_if;
1650 	struct ifmultiaddr *ifma;
1651 	uint32_t reg_rctl = 0;
1652 	uint8_t *mta;
1653 	int mcnt = 0;
1654 
1655 	mta = sc->mta;
1656 	bzero(mta, ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX);
1657 
1658 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1659 		if (ifma->ifma_addr->sa_family != AF_LINK)
1660 			continue;
1661 
1662 		if (mcnt == EMX_MCAST_ADDR_MAX)
1663 			break;
1664 
1665 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1666 		      &mta[mcnt * ETHER_ADDR_LEN], ETHER_ADDR_LEN);
1667 		mcnt++;
1668 	}
1669 
1670 	if (mcnt >= EMX_MCAST_ADDR_MAX) {
1671 		reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1672 		reg_rctl |= E1000_RCTL_MPE;
1673 		E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1674 	} else {
1675 		e1000_update_mc_addr_list(&sc->hw, mta, mcnt);
1676 	}
1677 }
1678 
1679 /*
1680  * This routine checks for link status and updates statistics.
1681  */
1682 static void
1683 emx_timer(void *xsc)
1684 {
1685 	struct emx_softc *sc = xsc;
1686 	struct ifnet *ifp = &sc->arpcom.ac_if;
1687 
1688 	lwkt_serialize_enter(&sc->main_serialize);
1689 
1690 	emx_update_link_status(sc);
1691 	emx_update_stats(sc);
1692 
1693 	/* Reset LAA into RAR[0] on 82571 */
1694 	if (e1000_get_laa_state_82571(&sc->hw) == TRUE)
1695 		e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1696 
1697 	if (emx_display_debug_stats && (ifp->if_flags & IFF_RUNNING))
1698 		emx_print_hw_stats(sc);
1699 
1700 	emx_smartspeed(sc);
1701 
1702 	callout_reset(&sc->timer, hz, emx_timer, sc);
1703 
1704 	lwkt_serialize_exit(&sc->main_serialize);
1705 }
1706 
1707 static void
1708 emx_update_link_status(struct emx_softc *sc)
1709 {
1710 	struct e1000_hw *hw = &sc->hw;
1711 	struct ifnet *ifp = &sc->arpcom.ac_if;
1712 	device_t dev = sc->dev;
1713 	uint32_t link_check = 0;
1714 
1715 	/* Get the cached link value or read phy for real */
1716 	switch (hw->phy.media_type) {
1717 	case e1000_media_type_copper:
1718 		if (hw->mac.get_link_status) {
1719 			/* Do the work to read phy */
1720 			e1000_check_for_link(hw);
1721 			link_check = !hw->mac.get_link_status;
1722 			if (link_check) /* ESB2 fix */
1723 				e1000_cfg_on_link_up(hw);
1724 		} else {
1725 			link_check = TRUE;
1726 		}
1727 		break;
1728 
1729 	case e1000_media_type_fiber:
1730 		e1000_check_for_link(hw);
1731 		link_check = E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU;
1732 		break;
1733 
1734 	case e1000_media_type_internal_serdes:
1735 		e1000_check_for_link(hw);
1736 		link_check = sc->hw.mac.serdes_has_link;
1737 		break;
1738 
1739 	case e1000_media_type_unknown:
1740 	default:
1741 		break;
1742 	}
1743 
1744 	/* Now check for a transition */
1745 	if (link_check && sc->link_active == 0) {
1746 		e1000_get_speed_and_duplex(hw, &sc->link_speed,
1747 		    &sc->link_duplex);
1748 
1749 		/*
1750 		 * Check if we should enable/disable SPEED_MODE bit on
1751 		 * 82571EB/82572EI
1752 		 */
1753 		if (sc->link_speed != SPEED_1000 &&
1754 		    (hw->mac.type == e1000_82571 ||
1755 		     hw->mac.type == e1000_82572)) {
1756 			int tarc0;
1757 
1758 			tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
1759 			tarc0 &= ~EMX_TARC_SPEED_MODE;
1760 			E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
1761 		}
1762 		if (bootverbose) {
1763 			device_printf(dev, "Link is up %d Mbps %s\n",
1764 			    sc->link_speed,
1765 			    ((sc->link_duplex == FULL_DUPLEX) ?
1766 			    "Full Duplex" : "Half Duplex"));
1767 		}
1768 		sc->link_active = 1;
1769 		sc->smartspeed = 0;
1770 		ifp->if_baudrate = sc->link_speed * 1000000;
1771 		ifp->if_link_state = LINK_STATE_UP;
1772 		if_link_state_change(ifp);
1773 	} else if (!link_check && sc->link_active == 1) {
1774 		ifp->if_baudrate = sc->link_speed = 0;
1775 		sc->link_duplex = 0;
1776 		if (bootverbose)
1777 			device_printf(dev, "Link is Down\n");
1778 		sc->link_active = 0;
1779 		ifp->if_link_state = LINK_STATE_DOWN;
1780 		if_link_state_change(ifp);
1781 	}
1782 }
1783 
1784 static void
1785 emx_stop(struct emx_softc *sc)
1786 {
1787 	struct ifnet *ifp = &sc->arpcom.ac_if;
1788 	int i;
1789 
1790 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
1791 
1792 	emx_disable_intr(sc);
1793 
1794 	callout_stop(&sc->timer);
1795 
1796 	ifp->if_flags &= ~IFF_RUNNING;
1797 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
1798 		struct emx_txdata *tdata = &sc->tx_data[i];
1799 
1800 		ifsq_clr_oactive(tdata->ifsq);
1801 		ifsq_watchdog_stop(&tdata->tx_watchdog);
1802 		tdata->tx_flags &= ~EMX_TXFLAG_ENABLED;
1803 	}
1804 
1805 	/*
1806 	 * Disable multiple receive queues.
1807 	 *
1808 	 * NOTE:
1809 	 * We should disable multiple receive queues before
1810 	 * resetting the hardware.
1811 	 */
1812 	E1000_WRITE_REG(&sc->hw, E1000_MRQC, 0);
1813 
1814 	e1000_reset_hw(&sc->hw);
1815 	E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1816 
1817 	for (i = 0; i < sc->tx_ring_cnt; ++i)
1818 		emx_free_tx_ring(&sc->tx_data[i]);
1819 	for (i = 0; i < sc->rx_ring_cnt; ++i)
1820 		emx_free_rx_ring(&sc->rx_data[i]);
1821 }
1822 
1823 static int
1824 emx_reset(struct emx_softc *sc)
1825 {
1826 	device_t dev = sc->dev;
1827 	uint16_t rx_buffer_size;
1828 	uint32_t pba;
1829 
1830 	/* Set up smart power down as default off on newer adapters. */
1831 	if (!emx_smart_pwr_down &&
1832 	    (sc->hw.mac.type == e1000_82571 ||
1833 	     sc->hw.mac.type == e1000_82572)) {
1834 		uint16_t phy_tmp = 0;
1835 
1836 		/* Speed up time to link by disabling smart power down. */
1837 		e1000_read_phy_reg(&sc->hw,
1838 		    IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
1839 		phy_tmp &= ~IGP02E1000_PM_SPD;
1840 		e1000_write_phy_reg(&sc->hw,
1841 		    IGP02E1000_PHY_POWER_MGMT, phy_tmp);
1842 	}
1843 
1844 	/*
1845 	 * Packet Buffer Allocation (PBA)
1846 	 * Writing PBA sets the receive portion of the buffer
1847 	 * the remainder is used for the transmit buffer.
1848 	 */
1849 	switch (sc->hw.mac.type) {
1850 	/* Total Packet Buffer on these is 48K */
1851 	case e1000_82571:
1852 	case e1000_82572:
1853 	case e1000_80003es2lan:
1854 		pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
1855 		break;
1856 
1857 	case e1000_82573: /* 82573: Total Packet Buffer is 32K */
1858 		pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
1859 		break;
1860 
1861 	case e1000_82574:
1862 		pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
1863 		break;
1864 
1865 	default:
1866 		/* Devices before 82547 had a Packet Buffer of 64K.   */
1867 		if (sc->max_frame_size > 8192)
1868 			pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
1869 		else
1870 			pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
1871 	}
1872 	E1000_WRITE_REG(&sc->hw, E1000_PBA, pba);
1873 
1874 	/*
1875 	 * These parameters control the automatic generation (Tx) and
1876 	 * response (Rx) to Ethernet PAUSE frames.
1877 	 * - High water mark should allow for at least two frames to be
1878 	 *   received after sending an XOFF.
1879 	 * - Low water mark works best when it is very near the high water mark.
1880 	 *   This allows the receiver to restart by sending XON when it has
1881 	 *   drained a bit. Here we use an arbitary value of 1500 which will
1882 	 *   restart after one full frame is pulled from the buffer. There
1883 	 *   could be several smaller frames in the buffer and if so they will
1884 	 *   not trigger the XON until their total number reduces the buffer
1885 	 *   by 1500.
1886 	 * - The pause time is fairly large at 1000 x 512ns = 512 usec.
1887 	 */
1888 	rx_buffer_size = (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) << 10;
1889 
1890 	sc->hw.fc.high_water = rx_buffer_size -
1891 			       roundup2(sc->max_frame_size, 1024);
1892 	sc->hw.fc.low_water = sc->hw.fc.high_water - 1500;
1893 
1894 	if (sc->hw.mac.type == e1000_80003es2lan)
1895 		sc->hw.fc.pause_time = 0xFFFF;
1896 	else
1897 		sc->hw.fc.pause_time = EMX_FC_PAUSE_TIME;
1898 	sc->hw.fc.send_xon = TRUE;
1899 	sc->hw.fc.requested_mode = e1000_fc_full;
1900 
1901 	/* Issue a global reset */
1902 	e1000_reset_hw(&sc->hw);
1903 	E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1904 	emx_disable_aspm(sc);
1905 
1906 	if (e1000_init_hw(&sc->hw) < 0) {
1907 		device_printf(dev, "Hardware Initialization Failed\n");
1908 		return (EIO);
1909 	}
1910 
1911 	E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1912 	e1000_get_phy_info(&sc->hw);
1913 	e1000_check_for_link(&sc->hw);
1914 
1915 	return (0);
1916 }
1917 
1918 static void
1919 emx_setup_ifp(struct emx_softc *sc)
1920 {
1921 	struct ifnet *ifp = &sc->arpcom.ac_if;
1922 	int i;
1923 
1924 	if_initname(ifp, device_get_name(sc->dev),
1925 		    device_get_unit(sc->dev));
1926 	ifp->if_softc = sc;
1927 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1928 	ifp->if_init =  emx_init;
1929 	ifp->if_ioctl = emx_ioctl;
1930 	ifp->if_start = emx_start;
1931 #ifdef IFPOLL_ENABLE
1932 	ifp->if_npoll = emx_npoll;
1933 #endif
1934 	ifp->if_serialize = emx_serialize;
1935 	ifp->if_deserialize = emx_deserialize;
1936 	ifp->if_tryserialize = emx_tryserialize;
1937 #ifdef INVARIANTS
1938 	ifp->if_serialize_assert = emx_serialize_assert;
1939 #endif
1940 
1941 	ifq_set_maxlen(&ifp->if_snd, sc->tx_data[0].num_tx_desc - 1);
1942 	ifq_set_ready(&ifp->if_snd);
1943 	ifq_set_subq_cnt(&ifp->if_snd, sc->tx_ring_cnt);
1944 
1945 	ifp->if_mapsubq = ifq_mapsubq_mask;
1946 	ifq_set_subq_mask(&ifp->if_snd, 0);
1947 
1948 	ether_ifattach(ifp, sc->hw.mac.addr, NULL);
1949 
1950 	ifp->if_capabilities = IFCAP_HWCSUM |
1951 			       IFCAP_VLAN_HWTAGGING |
1952 			       IFCAP_VLAN_MTU |
1953 			       IFCAP_TSO;
1954 	if (sc->rx_ring_cnt > 1)
1955 		ifp->if_capabilities |= IFCAP_RSS;
1956 	ifp->if_capenable = ifp->if_capabilities;
1957 	ifp->if_hwassist = EMX_CSUM_FEATURES | CSUM_TSO;
1958 
1959 	/*
1960 	 * Tell the upper layer(s) we support long frames.
1961 	 */
1962 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
1963 
1964 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
1965 		struct ifaltq_subque *ifsq = ifq_get_subq(&ifp->if_snd, i);
1966 		struct emx_txdata *tdata = &sc->tx_data[i];
1967 
1968 		ifsq_set_cpuid(ifsq, rman_get_cpuid(sc->intr_res));
1969 		ifsq_set_priv(ifsq, tdata);
1970 		tdata->ifsq = ifsq;
1971 
1972 		ifsq_watchdog_init(&tdata->tx_watchdog, ifsq, emx_watchdog);
1973 	}
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 = EMX_DEFAULT_TXWREG;
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 					IFNET_STAT_INC(ifp, opackets, 1);
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 			IFNET_STAT_INC(ifp, opackets, 1);
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 				IFNET_STAT_INC(ifp, iqdrops, 1);
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 				IFNET_STAT_INC(ifp, ipackets, 1);
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 			IFNET_STAT_INC(ifp, ierrors, 1);
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 	IFNET_STAT_SET(ifp, collisions, sc->stats.colc);
3372 
3373 	/* Rx Errors */
3374 	IFNET_STAT_SET(ifp, ierrors,
3375 	    sc->stats.rxerrc + sc->stats.crcerrs + sc->stats.algnerrc +
3376 	    sc->stats.ruc + sc->stats.roc + sc->stats.mpc + sc->stats.cexterr);
3377 
3378 	/* Tx Errors */
3379 	IFNET_STAT_SET(ifp, oerrors, sc->stats.ecol + sc->stats.latecol);
3380 }
3381 
3382 static void
3383 emx_print_debug_info(struct emx_softc *sc)
3384 {
3385 	device_t dev = sc->dev;
3386 	uint8_t *hw_addr = sc->hw.hw_addr;
3387 	int i;
3388 
3389 	device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
3390 	device_printf(dev, "CTRL = 0x%x RCTL = 0x%x \n",
3391 	    E1000_READ_REG(&sc->hw, E1000_CTRL),
3392 	    E1000_READ_REG(&sc->hw, E1000_RCTL));
3393 	device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk \n",
3394 	    ((E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff0000) >> 16),\
3395 	    (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) );
3396 	device_printf(dev, "Flow control watermarks high = %d low = %d\n",
3397 	    sc->hw.fc.high_water, sc->hw.fc.low_water);
3398 	device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
3399 	    E1000_READ_REG(&sc->hw, E1000_TIDV),
3400 	    E1000_READ_REG(&sc->hw, E1000_TADV));
3401 	device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
3402 	    E1000_READ_REG(&sc->hw, E1000_RDTR),
3403 	    E1000_READ_REG(&sc->hw, E1000_RADV));
3404 
3405 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3406 		device_printf(dev, "hw %d tdh = %d, hw tdt = %d\n", i,
3407 		    E1000_READ_REG(&sc->hw, E1000_TDH(i)),
3408 		    E1000_READ_REG(&sc->hw, E1000_TDT(i)));
3409 	}
3410 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3411 		device_printf(dev, "hw %d rdh = %d, hw rdt = %d\n", i,
3412 		    E1000_READ_REG(&sc->hw, E1000_RDH(i)),
3413 		    E1000_READ_REG(&sc->hw, E1000_RDT(i)));
3414 	}
3415 
3416 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3417 		device_printf(dev, "TX %d Tx descriptors avail = %d\n", i,
3418 		    sc->tx_data[i].num_tx_desc_avail);
3419 		device_printf(dev, "TX %d TSO segments = %lu\n", i,
3420 		    sc->tx_data[i].tso_segments);
3421 		device_printf(dev, "TX %d TSO ctx reused = %lu\n", i,
3422 		    sc->tx_data[i].tso_ctx_reused);
3423 	}
3424 }
3425 
3426 static void
3427 emx_print_hw_stats(struct emx_softc *sc)
3428 {
3429 	device_t dev = sc->dev;
3430 
3431 	device_printf(dev, "Excessive collisions = %lld\n",
3432 	    (long long)sc->stats.ecol);
3433 #if (DEBUG_HW > 0)  /* Dont output these errors normally */
3434 	device_printf(dev, "Symbol errors = %lld\n",
3435 	    (long long)sc->stats.symerrs);
3436 #endif
3437 	device_printf(dev, "Sequence errors = %lld\n",
3438 	    (long long)sc->stats.sec);
3439 	device_printf(dev, "Defer count = %lld\n",
3440 	    (long long)sc->stats.dc);
3441 	device_printf(dev, "Missed Packets = %lld\n",
3442 	    (long long)sc->stats.mpc);
3443 	device_printf(dev, "Receive No Buffers = %lld\n",
3444 	    (long long)sc->stats.rnbc);
3445 	/* RLEC is inaccurate on some hardware, calculate our own. */
3446 	device_printf(dev, "Receive Length Errors = %lld\n",
3447 	    ((long long)sc->stats.roc + (long long)sc->stats.ruc));
3448 	device_printf(dev, "Receive errors = %lld\n",
3449 	    (long long)sc->stats.rxerrc);
3450 	device_printf(dev, "Crc errors = %lld\n",
3451 	    (long long)sc->stats.crcerrs);
3452 	device_printf(dev, "Alignment errors = %lld\n",
3453 	    (long long)sc->stats.algnerrc);
3454 	device_printf(dev, "Collision/Carrier extension errors = %lld\n",
3455 	    (long long)sc->stats.cexterr);
3456 	device_printf(dev, "RX overruns = %ld\n", sc->rx_overruns);
3457 	device_printf(dev, "XON Rcvd = %lld\n",
3458 	    (long long)sc->stats.xonrxc);
3459 	device_printf(dev, "XON Xmtd = %lld\n",
3460 	    (long long)sc->stats.xontxc);
3461 	device_printf(dev, "XOFF Rcvd = %lld\n",
3462 	    (long long)sc->stats.xoffrxc);
3463 	device_printf(dev, "XOFF Xmtd = %lld\n",
3464 	    (long long)sc->stats.xofftxc);
3465 	device_printf(dev, "Good Packets Rcvd = %lld\n",
3466 	    (long long)sc->stats.gprc);
3467 	device_printf(dev, "Good Packets Xmtd = %lld\n",
3468 	    (long long)sc->stats.gptc);
3469 }
3470 
3471 static void
3472 emx_print_nvm_info(struct emx_softc *sc)
3473 {
3474 	uint16_t eeprom_data;
3475 	int i, j, row = 0;
3476 
3477 	/* Its a bit crude, but it gets the job done */
3478 	kprintf("\nInterface EEPROM Dump:\n");
3479 	kprintf("Offset\n0x0000  ");
3480 	for (i = 0, j = 0; i < 32; i++, j++) {
3481 		if (j == 8) { /* Make the offset block */
3482 			j = 0; ++row;
3483 			kprintf("\n0x00%x0  ",row);
3484 		}
3485 		e1000_read_nvm(&sc->hw, i, 1, &eeprom_data);
3486 		kprintf("%04x ", eeprom_data);
3487 	}
3488 	kprintf("\n");
3489 }
3490 
3491 static int
3492 emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
3493 {
3494 	struct emx_softc *sc;
3495 	struct ifnet *ifp;
3496 	int error, result;
3497 
3498 	result = -1;
3499 	error = sysctl_handle_int(oidp, &result, 0, req);
3500 	if (error || !req->newptr)
3501 		return (error);
3502 
3503 	sc = (struct emx_softc *)arg1;
3504 	ifp = &sc->arpcom.ac_if;
3505 
3506 	ifnet_serialize_all(ifp);
3507 
3508 	if (result == 1)
3509 		emx_print_debug_info(sc);
3510 
3511 	/*
3512 	 * This value will cause a hex dump of the
3513 	 * first 32 16-bit words of the EEPROM to
3514 	 * the screen.
3515 	 */
3516 	if (result == 2)
3517 		emx_print_nvm_info(sc);
3518 
3519 	ifnet_deserialize_all(ifp);
3520 
3521 	return (error);
3522 }
3523 
3524 static int
3525 emx_sysctl_stats(SYSCTL_HANDLER_ARGS)
3526 {
3527 	int error, result;
3528 
3529 	result = -1;
3530 	error = sysctl_handle_int(oidp, &result, 0, req);
3531 	if (error || !req->newptr)
3532 		return (error);
3533 
3534 	if (result == 1) {
3535 		struct emx_softc *sc = (struct emx_softc *)arg1;
3536 		struct ifnet *ifp = &sc->arpcom.ac_if;
3537 
3538 		ifnet_serialize_all(ifp);
3539 		emx_print_hw_stats(sc);
3540 		ifnet_deserialize_all(ifp);
3541 	}
3542 	return (error);
3543 }
3544 
3545 static void
3546 emx_add_sysctl(struct emx_softc *sc)
3547 {
3548 #if defined(EMX_RSS_DEBUG) || defined(EMX_TSS_DEBUG)
3549 	char pkt_desc[32];
3550 	int i;
3551 #endif
3552 
3553 	sysctl_ctx_init(&sc->sysctl_ctx);
3554 	sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
3555 				SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
3556 				device_get_nameunit(sc->dev),
3557 				CTLFLAG_RD, 0, "");
3558 	if (sc->sysctl_tree == NULL) {
3559 		device_printf(sc->dev, "can't add sysctl node\n");
3560 		return;
3561 	}
3562 
3563 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3564 			OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3565 			emx_sysctl_debug_info, "I", "Debug Information");
3566 
3567 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3568 			OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3569 			emx_sysctl_stats, "I", "Statistics");
3570 
3571 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3572 	    OID_AUTO, "rxd", CTLFLAG_RD, &sc->rx_data[0].num_rx_desc, 0,
3573 	    "# of RX descs");
3574 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3575 	    OID_AUTO, "txd", CTLFLAG_RD, &sc->tx_data[0].num_tx_desc, 0,
3576 	    "# of TX descs");
3577 
3578 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3579 	    OID_AUTO, "int_throttle_ceil", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3580 	    emx_sysctl_int_throttle, "I", "interrupt throttling rate");
3581 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3582 	    OID_AUTO, "tx_intr_nsegs", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3583 	    emx_sysctl_tx_intr_nsegs, "I", "# segments per TX interrupt");
3584 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3585 	    OID_AUTO, "tx_wreg_nsegs", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3586 	    emx_sysctl_tx_wreg_nsegs, "I",
3587 	    "# segments sent before write to hardware register");
3588 
3589 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3590 	    OID_AUTO, "rx_ring_cnt", CTLFLAG_RD, &sc->rx_ring_cnt, 0,
3591 	    "# of RX rings");
3592 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3593 	    OID_AUTO, "tx_ring_cnt", CTLFLAG_RD, &sc->tx_ring_cnt, 0,
3594 	    "# of TX rings");
3595 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3596 	    OID_AUTO, "tx_ring_inuse", CTLFLAG_RD, &sc->tx_ring_inuse, 0,
3597 	    "# of TX rings used");
3598 
3599 #ifdef IFPOLL_ENABLE
3600 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3601 			OID_AUTO, "npoll_rxoff", CTLTYPE_INT|CTLFLAG_RW,
3602 			sc, 0, emx_sysctl_npoll_rxoff, "I",
3603 			"NPOLLING RX cpu offset");
3604 	SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3605 			OID_AUTO, "npoll_txoff", CTLTYPE_INT|CTLFLAG_RW,
3606 			sc, 0, emx_sysctl_npoll_txoff, "I",
3607 			"NPOLLING TX cpu offset");
3608 #endif
3609 
3610 #ifdef EMX_RSS_DEBUG
3611 	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3612 		       OID_AUTO, "rss_debug", CTLFLAG_RW, &sc->rss_debug,
3613 		       0, "RSS debug level");
3614 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3615 		ksnprintf(pkt_desc, sizeof(pkt_desc), "rx%d_pkt", i);
3616 		SYSCTL_ADD_ULONG(&sc->sysctl_ctx,
3617 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
3618 		    pkt_desc, CTLFLAG_RW, &sc->rx_data[i].rx_pkts,
3619 		    "RXed packets");
3620 	}
3621 #endif
3622 #ifdef EMX_TSS_DEBUG
3623 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3624 		ksnprintf(pkt_desc, sizeof(pkt_desc), "tx%d_pkt", i);
3625 		SYSCTL_ADD_ULONG(&sc->sysctl_ctx,
3626 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
3627 		    pkt_desc, CTLFLAG_RW, &sc->tx_data[i].tx_pkts,
3628 		    "TXed packets");
3629 	}
3630 #endif
3631 }
3632 
3633 static int
3634 emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
3635 {
3636 	struct emx_softc *sc = (void *)arg1;
3637 	struct ifnet *ifp = &sc->arpcom.ac_if;
3638 	int error, throttle;
3639 
3640 	throttle = sc->int_throttle_ceil;
3641 	error = sysctl_handle_int(oidp, &throttle, 0, req);
3642 	if (error || req->newptr == NULL)
3643 		return error;
3644 	if (throttle < 0 || throttle > 1000000000 / 256)
3645 		return EINVAL;
3646 
3647 	if (throttle) {
3648 		/*
3649 		 * Set the interrupt throttling rate in 256ns increments,
3650 		 * recalculate sysctl value assignment to get exact frequency.
3651 		 */
3652 		throttle = 1000000000 / 256 / throttle;
3653 
3654 		/* Upper 16bits of ITR is reserved and should be zero */
3655 		if (throttle & 0xffff0000)
3656 			return EINVAL;
3657 	}
3658 
3659 	ifnet_serialize_all(ifp);
3660 
3661 	if (throttle)
3662 		sc->int_throttle_ceil = 1000000000 / 256 / throttle;
3663 	else
3664 		sc->int_throttle_ceil = 0;
3665 
3666 	if (ifp->if_flags & IFF_RUNNING)
3667 		emx_set_itr(sc, throttle);
3668 
3669 	ifnet_deserialize_all(ifp);
3670 
3671 	if (bootverbose) {
3672 		if_printf(ifp, "Interrupt moderation set to %d/sec\n",
3673 			  sc->int_throttle_ceil);
3674 	}
3675 	return 0;
3676 }
3677 
3678 static int
3679 emx_sysctl_tx_intr_nsegs(SYSCTL_HANDLER_ARGS)
3680 {
3681 	struct emx_softc *sc = (void *)arg1;
3682 	struct ifnet *ifp = &sc->arpcom.ac_if;
3683 	struct emx_txdata *tdata = &sc->tx_data[0];
3684 	int error, segs;
3685 
3686 	segs = tdata->tx_intr_nsegs;
3687 	error = sysctl_handle_int(oidp, &segs, 0, req);
3688 	if (error || req->newptr == NULL)
3689 		return error;
3690 	if (segs <= 0)
3691 		return EINVAL;
3692 
3693 	ifnet_serialize_all(ifp);
3694 
3695 	/*
3696 	 * Don't allow tx_intr_nsegs to become:
3697 	 * o  Less the oact_tx_desc
3698 	 * o  Too large that no TX desc will cause TX interrupt to
3699 	 *    be generated (OACTIVE will never recover)
3700 	 * o  Too small that will cause tx_dd[] overflow
3701 	 */
3702 	if (segs < tdata->oact_tx_desc ||
3703 	    segs >= tdata->num_tx_desc - tdata->oact_tx_desc ||
3704 	    segs < tdata->num_tx_desc / EMX_TXDD_SAFE) {
3705 		error = EINVAL;
3706 	} else {
3707 		int i;
3708 
3709 		error = 0;
3710 		for (i = 0; i < sc->tx_ring_cnt; ++i)
3711 			sc->tx_data[i].tx_intr_nsegs = segs;
3712 	}
3713 
3714 	ifnet_deserialize_all(ifp);
3715 
3716 	return error;
3717 }
3718 
3719 static int
3720 emx_sysctl_tx_wreg_nsegs(SYSCTL_HANDLER_ARGS)
3721 {
3722 	struct emx_softc *sc = (void *)arg1;
3723 	struct ifnet *ifp = &sc->arpcom.ac_if;
3724 	int error, nsegs, i;
3725 
3726 	nsegs = sc->tx_data[0].tx_wreg_nsegs;
3727 	error = sysctl_handle_int(oidp, &nsegs, 0, req);
3728 	if (error || req->newptr == NULL)
3729 		return error;
3730 
3731 	ifnet_serialize_all(ifp);
3732 	for (i = 0; i < sc->tx_ring_cnt; ++i)
3733 		sc->tx_data[i].tx_wreg_nsegs =nsegs;
3734 	ifnet_deserialize_all(ifp);
3735 
3736 	return 0;
3737 }
3738 
3739 #ifdef IFPOLL_ENABLE
3740 
3741 static int
3742 emx_sysctl_npoll_rxoff(SYSCTL_HANDLER_ARGS)
3743 {
3744 	struct emx_softc *sc = (void *)arg1;
3745 	struct ifnet *ifp = &sc->arpcom.ac_if;
3746 	int error, off;
3747 
3748 	off = sc->rx_npoll_off;
3749 	error = sysctl_handle_int(oidp, &off, 0, req);
3750 	if (error || req->newptr == NULL)
3751 		return error;
3752 	if (off < 0)
3753 		return EINVAL;
3754 
3755 	ifnet_serialize_all(ifp);
3756 	if (off >= ncpus2 || off % sc->rx_ring_cnt != 0) {
3757 		error = EINVAL;
3758 	} else {
3759 		error = 0;
3760 		sc->rx_npoll_off = off;
3761 	}
3762 	ifnet_deserialize_all(ifp);
3763 
3764 	return error;
3765 }
3766 
3767 static int
3768 emx_sysctl_npoll_txoff(SYSCTL_HANDLER_ARGS)
3769 {
3770 	struct emx_softc *sc = (void *)arg1;
3771 	struct ifnet *ifp = &sc->arpcom.ac_if;
3772 	int error, off;
3773 
3774 	off = sc->tx_npoll_off;
3775 	error = sysctl_handle_int(oidp, &off, 0, req);
3776 	if (error || req->newptr == NULL)
3777 		return error;
3778 	if (off < 0)
3779 		return EINVAL;
3780 
3781 	ifnet_serialize_all(ifp);
3782 	if (off >= ncpus2 || off % sc->tx_ring_cnt != 0) {
3783 		error = EINVAL;
3784 	} else {
3785 		error = 0;
3786 		sc->tx_npoll_off = off;
3787 	}
3788 	ifnet_deserialize_all(ifp);
3789 
3790 	return error;
3791 }
3792 
3793 #endif	/* IFPOLL_ENABLE */
3794 
3795 static int
3796 emx_dma_alloc(struct emx_softc *sc)
3797 {
3798 	int error, i;
3799 
3800 	/*
3801 	 * Create top level busdma tag
3802 	 */
3803 	error = bus_dma_tag_create(NULL, 1, 0,
3804 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
3805 			NULL, NULL,
3806 			BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
3807 			0, &sc->parent_dtag);
3808 	if (error) {
3809 		device_printf(sc->dev, "could not create top level DMA tag\n");
3810 		return error;
3811 	}
3812 
3813 	/*
3814 	 * Allocate transmit descriptors ring and buffers
3815 	 */
3816 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3817 		error = emx_create_tx_ring(&sc->tx_data[i]);
3818 		if (error) {
3819 			device_printf(sc->dev,
3820 			    "Could not setup transmit structures\n");
3821 			return error;
3822 		}
3823 	}
3824 
3825 	/*
3826 	 * Allocate receive descriptors ring and buffers
3827 	 */
3828 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3829 		error = emx_create_rx_ring(&sc->rx_data[i]);
3830 		if (error) {
3831 			device_printf(sc->dev,
3832 			    "Could not setup receive structures\n");
3833 			return error;
3834 		}
3835 	}
3836 	return 0;
3837 }
3838 
3839 static void
3840 emx_dma_free(struct emx_softc *sc)
3841 {
3842 	int i;
3843 
3844 	for (i = 0; i < sc->tx_ring_cnt; ++i) {
3845 		emx_destroy_tx_ring(&sc->tx_data[i],
3846 		    sc->tx_data[i].num_tx_desc);
3847 	}
3848 
3849 	for (i = 0; i < sc->rx_ring_cnt; ++i) {
3850 		emx_destroy_rx_ring(&sc->rx_data[i],
3851 		    sc->rx_data[i].num_rx_desc);
3852 	}
3853 
3854 	/* Free top level busdma tag */
3855 	if (sc->parent_dtag != NULL)
3856 		bus_dma_tag_destroy(sc->parent_dtag);
3857 }
3858 
3859 static void
3860 emx_serialize(struct ifnet *ifp, enum ifnet_serialize slz)
3861 {
3862 	struct emx_softc *sc = ifp->if_softc;
3863 
3864 	ifnet_serialize_array_enter(sc->serializes, EMX_NSERIALIZE,
3865 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3866 }
3867 
3868 static void
3869 emx_deserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3870 {
3871 	struct emx_softc *sc = ifp->if_softc;
3872 
3873 	ifnet_serialize_array_exit(sc->serializes, EMX_NSERIALIZE,
3874 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3875 }
3876 
3877 static int
3878 emx_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3879 {
3880 	struct emx_softc *sc = ifp->if_softc;
3881 
3882 	return ifnet_serialize_array_try(sc->serializes, EMX_NSERIALIZE,
3883 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3884 }
3885 
3886 static void
3887 emx_serialize_skipmain(struct emx_softc *sc)
3888 {
3889 	lwkt_serialize_array_enter(sc->serializes, EMX_NSERIALIZE, 1);
3890 }
3891 
3892 static void
3893 emx_deserialize_skipmain(struct emx_softc *sc)
3894 {
3895 	lwkt_serialize_array_exit(sc->serializes, EMX_NSERIALIZE, 1);
3896 }
3897 
3898 #ifdef INVARIANTS
3899 
3900 static void
3901 emx_serialize_assert(struct ifnet *ifp, enum ifnet_serialize slz,
3902     boolean_t serialized)
3903 {
3904 	struct emx_softc *sc = ifp->if_softc;
3905 
3906 	ifnet_serialize_array_assert(sc->serializes, EMX_NSERIALIZE,
3907 	    EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz, serialized);
3908 }
3909 
3910 #endif	/* INVARIANTS */
3911 
3912 #ifdef IFPOLL_ENABLE
3913 
3914 static void
3915 emx_npoll_status(struct ifnet *ifp)
3916 {
3917 	struct emx_softc *sc = ifp->if_softc;
3918 	uint32_t reg_icr;
3919 
3920 	ASSERT_SERIALIZED(&sc->main_serialize);
3921 
3922 	reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
3923 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
3924 		callout_stop(&sc->timer);
3925 		sc->hw.mac.get_link_status = 1;
3926 		emx_update_link_status(sc);
3927 		callout_reset(&sc->timer, hz, emx_timer, sc);
3928 	}
3929 }
3930 
3931 static void
3932 emx_npoll_tx(struct ifnet *ifp, void *arg, int cycle __unused)
3933 {
3934 	struct emx_txdata *tdata = arg;
3935 
3936 	ASSERT_SERIALIZED(&tdata->tx_serialize);
3937 
3938 	emx_txeof(tdata);
3939 	if (!ifsq_is_empty(tdata->ifsq))
3940 		ifsq_devstart(tdata->ifsq);
3941 }
3942 
3943 static void
3944 emx_npoll_rx(struct ifnet *ifp __unused, void *arg, int cycle)
3945 {
3946 	struct emx_rxdata *rdata = arg;
3947 
3948 	ASSERT_SERIALIZED(&rdata->rx_serialize);
3949 
3950 	emx_rxeof(rdata, cycle);
3951 }
3952 
3953 static void
3954 emx_npoll(struct ifnet *ifp, struct ifpoll_info *info)
3955 {
3956 	struct emx_softc *sc = ifp->if_softc;
3957 	int i, txr_cnt;
3958 
3959 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
3960 
3961 	if (info) {
3962 		int off;
3963 
3964 		info->ifpi_status.status_func = emx_npoll_status;
3965 		info->ifpi_status.serializer = &sc->main_serialize;
3966 
3967 		txr_cnt = emx_get_txring_inuse(sc, TRUE);
3968 		off = sc->tx_npoll_off;
3969 		for (i = 0; i < txr_cnt; ++i) {
3970 			struct emx_txdata *tdata = &sc->tx_data[i];
3971 			int idx = i + off;
3972 
3973 			KKASSERT(idx < ncpus2);
3974 			info->ifpi_tx[idx].poll_func = emx_npoll_tx;
3975 			info->ifpi_tx[idx].arg = tdata;
3976 			info->ifpi_tx[idx].serializer = &tdata->tx_serialize;
3977 			ifsq_set_cpuid(tdata->ifsq, idx);
3978 		}
3979 
3980 		off = sc->rx_npoll_off;
3981 		for (i = 0; i < sc->rx_ring_cnt; ++i) {
3982 			struct emx_rxdata *rdata = &sc->rx_data[i];
3983 			int idx = i + off;
3984 
3985 			KKASSERT(idx < ncpus2);
3986 			info->ifpi_rx[idx].poll_func = emx_npoll_rx;
3987 			info->ifpi_rx[idx].arg = rdata;
3988 			info->ifpi_rx[idx].serializer = &rdata->rx_serialize;
3989 		}
3990 
3991 		if (ifp->if_flags & IFF_RUNNING) {
3992 			if (txr_cnt == sc->tx_ring_inuse)
3993 				emx_disable_intr(sc);
3994 			else
3995 				emx_init(sc);
3996 		}
3997 	} else {
3998 		for (i = 0; i < sc->tx_ring_cnt; ++i) {
3999 			struct emx_txdata *tdata = &sc->tx_data[i];
4000 
4001 			ifsq_set_cpuid(tdata->ifsq,
4002 			    rman_get_cpuid(sc->intr_res));
4003 		}
4004 
4005 		if (ifp->if_flags & IFF_RUNNING) {
4006 			txr_cnt = emx_get_txring_inuse(sc, FALSE);
4007 			if (txr_cnt == sc->tx_ring_inuse)
4008 				emx_enable_intr(sc);
4009 			else
4010 				emx_init(sc);
4011 		}
4012 	}
4013 }
4014 
4015 #endif	/* IFPOLL_ENABLE */
4016 
4017 static void
4018 emx_set_itr(struct emx_softc *sc, uint32_t itr)
4019 {
4020 	E1000_WRITE_REG(&sc->hw, E1000_ITR, itr);
4021 	if (sc->hw.mac.type == e1000_82574) {
4022 		int i;
4023 
4024 		/*
4025 		 * When using MSIX interrupts we need to
4026 		 * throttle using the EITR register
4027 		 */
4028 		for (i = 0; i < 4; ++i)
4029 			E1000_WRITE_REG(&sc->hw, E1000_EITR_82574(i), itr);
4030 	}
4031 }
4032 
4033 /*
4034  * Disable the L0s, 82574L Errata #20
4035  */
4036 static void
4037 emx_disable_aspm(struct emx_softc *sc)
4038 {
4039 	uint16_t link_cap, link_ctrl, disable;
4040 	uint8_t pcie_ptr, reg;
4041 	device_t dev = sc->dev;
4042 
4043 	switch (sc->hw.mac.type) {
4044 	case e1000_82571:
4045 	case e1000_82572:
4046 	case e1000_82573:
4047 		/*
4048 		 * 82573 specification update
4049 		 * errata #8 disable L0s
4050 		 * errata #41 disable L1
4051 		 *
4052 		 * 82571/82572 specification update
4053 		 # errata #13 disable L1
4054 		 * errata #68 disable L0s
4055 		 */
4056 		disable = PCIEM_LNKCTL_ASPM_L0S | PCIEM_LNKCTL_ASPM_L1;
4057 		break;
4058 
4059 	case e1000_82574:
4060 		/*
4061 		 * 82574 specification update errata #20
4062 		 *
4063 		 * There is no need to disable L1
4064 		 */
4065 		disable = PCIEM_LNKCTL_ASPM_L0S;
4066 		break;
4067 
4068 	default:
4069 		return;
4070 	}
4071 
4072 	pcie_ptr = pci_get_pciecap_ptr(dev);
4073 	if (pcie_ptr == 0)
4074 		return;
4075 
4076 	link_cap = pci_read_config(dev, pcie_ptr + PCIER_LINKCAP, 2);
4077 	if ((link_cap & PCIEM_LNKCAP_ASPM_MASK) == 0)
4078 		return;
4079 
4080 	if (bootverbose)
4081 		if_printf(&sc->arpcom.ac_if, "disable ASPM %#02x\n", disable);
4082 
4083 	reg = pcie_ptr + PCIER_LINKCTRL;
4084 	link_ctrl = pci_read_config(dev, reg, 2);
4085 	link_ctrl &= ~disable;
4086 	pci_write_config(dev, reg, link_ctrl, 2);
4087 }
4088 
4089 static int
4090 emx_tso_pullup(struct emx_txdata *tdata, struct mbuf **mp)
4091 {
4092 	int iphlen, hoff, thoff, ex = 0;
4093 	struct mbuf *m;
4094 	struct ip *ip;
4095 
4096 	m = *mp;
4097 	KASSERT(M_WRITABLE(m), ("TSO mbuf not writable"));
4098 
4099 	iphlen = m->m_pkthdr.csum_iphlen;
4100 	thoff = m->m_pkthdr.csum_thlen;
4101 	hoff = m->m_pkthdr.csum_lhlen;
4102 
4103 	KASSERT(iphlen > 0, ("invalid ip hlen"));
4104 	KASSERT(thoff > 0, ("invalid tcp hlen"));
4105 	KASSERT(hoff > 0, ("invalid ether hlen"));
4106 
4107 	if (tdata->tx_flags & EMX_TXFLAG_TSO_PULLEX)
4108 		ex = 4;
4109 
4110 	if (m->m_len < hoff + iphlen + thoff + ex) {
4111 		m = m_pullup(m, hoff + iphlen + thoff + ex);
4112 		if (m == NULL) {
4113 			*mp = NULL;
4114 			return ENOBUFS;
4115 		}
4116 		*mp = m;
4117 	}
4118 	ip = mtodoff(m, struct ip *, hoff);
4119 	ip->ip_len = 0;
4120 
4121 	return 0;
4122 }
4123 
4124 static int
4125 emx_tso_setup(struct emx_txdata *tdata, struct mbuf *mp,
4126     uint32_t *txd_upper, uint32_t *txd_lower)
4127 {
4128 	struct e1000_context_desc *TXD;
4129 	int hoff, iphlen, thoff, hlen;
4130 	int mss, pktlen, curr_txd;
4131 
4132 #ifdef EMX_TSO_DEBUG
4133 	tdata->tso_segments++;
4134 #endif
4135 
4136 	iphlen = mp->m_pkthdr.csum_iphlen;
4137 	thoff = mp->m_pkthdr.csum_thlen;
4138 	hoff = mp->m_pkthdr.csum_lhlen;
4139 	mss = mp->m_pkthdr.tso_segsz;
4140 	pktlen = mp->m_pkthdr.len;
4141 
4142 	if ((tdata->tx_flags & EMX_TXFLAG_FORCECTX) == 0 &&
4143 	    tdata->csum_flags == CSUM_TSO &&
4144 	    tdata->csum_iphlen == iphlen &&
4145 	    tdata->csum_lhlen == hoff &&
4146 	    tdata->csum_thlen == thoff &&
4147 	    tdata->csum_mss == mss &&
4148 	    tdata->csum_pktlen == pktlen) {
4149 		*txd_upper = tdata->csum_txd_upper;
4150 		*txd_lower = tdata->csum_txd_lower;
4151 #ifdef EMX_TSO_DEBUG
4152 		tdata->tso_ctx_reused++;
4153 #endif
4154 		return 0;
4155 	}
4156 	hlen = hoff + iphlen + thoff;
4157 
4158 	/*
4159 	 * Setup a new TSO context.
4160 	 */
4161 
4162 	curr_txd = tdata->next_avail_tx_desc;
4163 	TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
4164 
4165 	*txd_lower = E1000_TXD_CMD_DEXT |	/* Extended descr type */
4166 		     E1000_TXD_DTYP_D |		/* Data descr type */
4167 		     E1000_TXD_CMD_TSE;		/* Do TSE on this packet */
4168 
4169 	/* IP and/or TCP header checksum calculation and insertion. */
4170 	*txd_upper = (E1000_TXD_POPTS_IXSM | E1000_TXD_POPTS_TXSM) << 8;
4171 
4172 	/*
4173 	 * Start offset for header checksum calculation.
4174 	 * End offset for header checksum calculation.
4175 	 * Offset of place put the checksum.
4176 	 */
4177 	TXD->lower_setup.ip_fields.ipcss = hoff;
4178 	TXD->lower_setup.ip_fields.ipcse = htole16(hoff + iphlen - 1);
4179 	TXD->lower_setup.ip_fields.ipcso = hoff + offsetof(struct ip, ip_sum);
4180 
4181 	/*
4182 	 * Start offset for payload checksum calculation.
4183 	 * End offset for payload checksum calculation.
4184 	 * Offset of place to put the checksum.
4185 	 */
4186 	TXD->upper_setup.tcp_fields.tucss = hoff + iphlen;
4187 	TXD->upper_setup.tcp_fields.tucse = 0;
4188 	TXD->upper_setup.tcp_fields.tucso =
4189 	    hoff + iphlen + offsetof(struct tcphdr, th_sum);
4190 
4191 	/*
4192 	 * Payload size per packet w/o any headers.
4193 	 * Length of all headers up to payload.
4194 	 */
4195 	TXD->tcp_seg_setup.fields.mss = htole16(mss);
4196 	TXD->tcp_seg_setup.fields.hdr_len = hlen;
4197 	TXD->cmd_and_length = htole32(E1000_TXD_CMD_IFCS |
4198 				E1000_TXD_CMD_DEXT |	/* Extended descr */
4199 				E1000_TXD_CMD_TSE |	/* TSE context */
4200 				E1000_TXD_CMD_IP |	/* Do IP csum */
4201 				E1000_TXD_CMD_TCP |	/* Do TCP checksum */
4202 				(pktlen - hlen));	/* Total len */
4203 
4204 	/* Save the information for this TSO context */
4205 	tdata->csum_flags = CSUM_TSO;
4206 	tdata->csum_lhlen = hoff;
4207 	tdata->csum_iphlen = iphlen;
4208 	tdata->csum_thlen = thoff;
4209 	tdata->csum_mss = mss;
4210 	tdata->csum_pktlen = pktlen;
4211 	tdata->csum_txd_upper = *txd_upper;
4212 	tdata->csum_txd_lower = *txd_lower;
4213 
4214 	if (++curr_txd == tdata->num_tx_desc)
4215 		curr_txd = 0;
4216 
4217 	KKASSERT(tdata->num_tx_desc_avail > 0);
4218 	tdata->num_tx_desc_avail--;
4219 
4220 	tdata->next_avail_tx_desc = curr_txd;
4221 	return 1;
4222 }
4223 
4224 static int
4225 emx_get_txring_inuse(const struct emx_softc *sc, boolean_t polling)
4226 {
4227 	if (polling)
4228 		return sc->tx_ring_cnt;
4229 	else
4230 		return 1;
4231 }
4232