xref: /dragonfly/sys/dev/netif/em/if_em.c (revision 7d3e9a5b)
1 /*
2  * Copyright (c) 2004 Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
3  *
4  * Copyright (c) 2001-2015, 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 /*
68  * SERIALIZATION API RULES:
69  *
70  * - We must call lwkt_serialize_handler_enable() prior to enabling the
71  *   hardware interrupt and lwkt_serialize_handler_disable() after disabling
72  *   the hardware interrupt in order to avoid handler execution races from
73  *   scheduled interrupt threads.
74  */
75 
76 #include "opt_ifpoll.h"
77 
78 #include <sys/param.h>
79 #include <sys/bus.h>
80 #include <sys/endian.h>
81 #include <sys/interrupt.h>
82 #include <sys/kernel.h>
83 #include <sys/ktr.h>
84 #include <sys/malloc.h>
85 #include <sys/mbuf.h>
86 #include <sys/proc.h>
87 #include <sys/rman.h>
88 #include <sys/serialize.h>
89 #include <sys/socket.h>
90 #include <sys/sockio.h>
91 #include <sys/sysctl.h>
92 #include <sys/systm.h>
93 
94 #include <net/bpf.h>
95 #include <net/ethernet.h>
96 #include <net/if.h>
97 #include <net/if_arp.h>
98 #include <net/if_dl.h>
99 #include <net/if_media.h>
100 #include <net/if_poll.h>
101 #include <net/ifq_var.h>
102 #include <net/vlan/if_vlan_var.h>
103 #include <net/vlan/if_vlan_ether.h>
104 
105 #include <netinet/ip.h>
106 #include <netinet/tcp.h>
107 #include <netinet/udp.h>
108 
109 #include <bus/pci/pcivar.h>
110 #include <bus/pci/pcireg.h>
111 
112 #include <dev/netif/ig_hal/e1000_api.h>
113 #include <dev/netif/ig_hal/e1000_82571.h>
114 #include <dev/netif/ig_hal/e1000_dragonfly.h>
115 #include <dev/netif/em/if_em.h>
116 
117 #define DEBUG_HW 0
118 
119 #define EM_NAME	"Intel(R) PRO/1000 Network Connection "
120 #define EM_VER	" 7.6.2"
121 
122 #define _EM_DEVICE(id, ret)	\
123 	{ EM_VENDOR_ID, E1000_DEV_ID_##id, ret, EM_NAME #id EM_VER }
124 #define EM_EMX_DEVICE(id)	_EM_DEVICE(id, -100)
125 #define EM_DEVICE(id)		_EM_DEVICE(id, 0)
126 #define EM_DEVICE_NULL	{ 0, 0, 0, NULL }
127 
128 static const struct em_vendor_info em_vendor_info_array[] = {
129 	EM_DEVICE(82540EM),
130 	EM_DEVICE(82540EM_LOM),
131 	EM_DEVICE(82540EP),
132 	EM_DEVICE(82540EP_LOM),
133 	EM_DEVICE(82540EP_LP),
134 
135 	EM_DEVICE(82541EI),
136 	EM_DEVICE(82541ER),
137 	EM_DEVICE(82541ER_LOM),
138 	EM_DEVICE(82541EI_MOBILE),
139 	EM_DEVICE(82541GI),
140 	EM_DEVICE(82541GI_LF),
141 	EM_DEVICE(82541GI_MOBILE),
142 
143 	EM_DEVICE(82542),
144 
145 	EM_DEVICE(82543GC_FIBER),
146 	EM_DEVICE(82543GC_COPPER),
147 
148 	EM_DEVICE(82544EI_COPPER),
149 	EM_DEVICE(82544EI_FIBER),
150 	EM_DEVICE(82544GC_COPPER),
151 	EM_DEVICE(82544GC_LOM),
152 
153 	EM_DEVICE(82545EM_COPPER),
154 	EM_DEVICE(82545EM_FIBER),
155 	EM_DEVICE(82545GM_COPPER),
156 	EM_DEVICE(82545GM_FIBER),
157 	EM_DEVICE(82545GM_SERDES),
158 
159 	EM_DEVICE(82546EB_COPPER),
160 	EM_DEVICE(82546EB_FIBER),
161 	EM_DEVICE(82546EB_QUAD_COPPER),
162 	EM_DEVICE(82546GB_COPPER),
163 	EM_DEVICE(82546GB_FIBER),
164 	EM_DEVICE(82546GB_SERDES),
165 	EM_DEVICE(82546GB_PCIE),
166 	EM_DEVICE(82546GB_QUAD_COPPER),
167 	EM_DEVICE(82546GB_QUAD_COPPER_KSP3),
168 
169 	EM_DEVICE(82547EI),
170 	EM_DEVICE(82547EI_MOBILE),
171 	EM_DEVICE(82547GI),
172 
173 	EM_EMX_DEVICE(82571EB_COPPER),
174 	EM_EMX_DEVICE(82571EB_FIBER),
175 	EM_EMX_DEVICE(82571EB_SERDES),
176 	EM_EMX_DEVICE(82571EB_SERDES_DUAL),
177 	EM_EMX_DEVICE(82571EB_SERDES_QUAD),
178 	EM_EMX_DEVICE(82571EB_QUAD_COPPER),
179 	EM_EMX_DEVICE(82571EB_QUAD_COPPER_BP),
180 	EM_EMX_DEVICE(82571EB_QUAD_COPPER_LP),
181 	EM_EMX_DEVICE(82571EB_QUAD_FIBER),
182 	EM_EMX_DEVICE(82571PT_QUAD_COPPER),
183 
184 	EM_EMX_DEVICE(82572EI_COPPER),
185 	EM_EMX_DEVICE(82572EI_FIBER),
186 	EM_EMX_DEVICE(82572EI_SERDES),
187 	EM_EMX_DEVICE(82572EI),
188 
189 	EM_EMX_DEVICE(82573E),
190 	EM_EMX_DEVICE(82573E_IAMT),
191 	EM_EMX_DEVICE(82573L),
192 
193 	EM_DEVICE(82583V),
194 
195 	EM_EMX_DEVICE(80003ES2LAN_COPPER_SPT),
196 	EM_EMX_DEVICE(80003ES2LAN_SERDES_SPT),
197 	EM_EMX_DEVICE(80003ES2LAN_COPPER_DPT),
198 	EM_EMX_DEVICE(80003ES2LAN_SERDES_DPT),
199 
200 	EM_DEVICE(ICH8_IGP_M_AMT),
201 	EM_DEVICE(ICH8_IGP_AMT),
202 	EM_DEVICE(ICH8_IGP_C),
203 	EM_DEVICE(ICH8_IFE),
204 	EM_DEVICE(ICH8_IFE_GT),
205 	EM_DEVICE(ICH8_IFE_G),
206 	EM_DEVICE(ICH8_IGP_M),
207 	EM_DEVICE(ICH8_82567V_3),
208 
209 	EM_DEVICE(ICH9_IGP_M_AMT),
210 	EM_DEVICE(ICH9_IGP_AMT),
211 	EM_DEVICE(ICH9_IGP_C),
212 	EM_DEVICE(ICH9_IGP_M),
213 	EM_DEVICE(ICH9_IGP_M_V),
214 	EM_DEVICE(ICH9_IFE),
215 	EM_DEVICE(ICH9_IFE_GT),
216 	EM_DEVICE(ICH9_IFE_G),
217 	EM_DEVICE(ICH9_BM),
218 
219 	EM_EMX_DEVICE(82574L),
220 	EM_EMX_DEVICE(82574LA),
221 
222 	EM_DEVICE(ICH10_R_BM_LM),
223 	EM_DEVICE(ICH10_R_BM_LF),
224 	EM_DEVICE(ICH10_R_BM_V),
225 	EM_DEVICE(ICH10_D_BM_LM),
226 	EM_DEVICE(ICH10_D_BM_LF),
227 	EM_DEVICE(ICH10_D_BM_V),
228 
229 	EM_DEVICE(PCH_M_HV_LM),
230 	EM_DEVICE(PCH_M_HV_LC),
231 	EM_DEVICE(PCH_D_HV_DM),
232 	EM_DEVICE(PCH_D_HV_DC),
233 
234 	EM_DEVICE(PCH2_LV_LM),
235 	EM_DEVICE(PCH2_LV_V),
236 
237 	EM_EMX_DEVICE(PCH_LPT_I217_LM),
238 	EM_EMX_DEVICE(PCH_LPT_I217_V),
239 	EM_EMX_DEVICE(PCH_LPTLP_I218_LM),
240 	EM_EMX_DEVICE(PCH_LPTLP_I218_V),
241 	EM_EMX_DEVICE(PCH_I218_LM2),
242 	EM_EMX_DEVICE(PCH_I218_V2),
243 	EM_EMX_DEVICE(PCH_I218_LM3),
244 	EM_EMX_DEVICE(PCH_I218_V3),
245 	EM_EMX_DEVICE(PCH_SPT_I219_LM),
246 	EM_EMX_DEVICE(PCH_SPT_I219_V),
247 	EM_EMX_DEVICE(PCH_SPT_I219_LM2),
248 	EM_EMX_DEVICE(PCH_SPT_I219_V2),
249 	EM_EMX_DEVICE(PCH_LBG_I219_LM3),
250 	EM_EMX_DEVICE(PCH_SPT_I219_LM4),
251 	EM_EMX_DEVICE(PCH_SPT_I219_V4),
252 	EM_EMX_DEVICE(PCH_SPT_I219_LM5),
253 	EM_EMX_DEVICE(PCH_SPT_I219_V5),
254 	EM_EMX_DEVICE(PCH_CNP_I219_LM6),
255 	EM_EMX_DEVICE(PCH_CNP_I219_V6),
256 	EM_EMX_DEVICE(PCH_CNP_I219_LM7),
257 	EM_EMX_DEVICE(PCH_CNP_I219_V7),
258 	EM_EMX_DEVICE(PCH_ICP_I219_LM8),
259 	EM_EMX_DEVICE(PCH_ICP_I219_V8),
260 	EM_EMX_DEVICE(PCH_ICP_I219_LM9),
261 	EM_EMX_DEVICE(PCH_ICP_I219_V9),
262 	EM_EMX_DEVICE(PCH_CMP_I219_LM10),
263 	EM_EMX_DEVICE(PCH_CMP_I219_V10),
264 	EM_EMX_DEVICE(PCH_CMP_I219_LM11),
265 	EM_EMX_DEVICE(PCH_CMP_I219_V11),
266 	EM_EMX_DEVICE(PCH_CMP_I219_LM12),
267 	EM_EMX_DEVICE(PCH_CMP_I219_V12),
268 	EM_EMX_DEVICE(PCH_TGP_I219_LM13),
269 	EM_EMX_DEVICE(PCH_TGP_I219_V13),
270 	EM_EMX_DEVICE(PCH_TGP_I219_LM14),
271 	EM_EMX_DEVICE(PCH_TGP_I219_V14),
272 	EM_EMX_DEVICE(PCH_TGP_I219_LM15),
273 	EM_EMX_DEVICE(PCH_TGP_I219_V15),
274 	EM_EMX_DEVICE(PCH_ADP_I219_LM16),
275 	EM_EMX_DEVICE(PCH_ADP_I219_V16),
276 	EM_EMX_DEVICE(PCH_ADP_I219_LM17),
277 	EM_EMX_DEVICE(PCH_ADP_I219_V17),
278 	EM_EMX_DEVICE(PCH_MTP_I219_LM18),
279 	EM_EMX_DEVICE(PCH_MTP_I219_V18),
280 	EM_EMX_DEVICE(PCH_MTP_I219_LM19),
281 	EM_EMX_DEVICE(PCH_MTP_I219_V19),
282 
283 	/* required last entry */
284 	EM_DEVICE_NULL
285 };
286 
287 static int	em_probe(device_t);
288 static int	em_attach(device_t);
289 static int	em_detach(device_t);
290 static int	em_shutdown(device_t);
291 static int	em_suspend(device_t);
292 static int	em_resume(device_t);
293 
294 static void	em_init(void *);
295 static void	em_stop(struct adapter *);
296 static int	em_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
297 static void	em_start(struct ifnet *, struct ifaltq_subque *);
298 #ifdef IFPOLL_ENABLE
299 static void	em_npoll(struct ifnet *, struct ifpoll_info *);
300 static void	em_npoll_compat(struct ifnet *, void *, int);
301 #endif
302 static void	em_watchdog(struct ifnet *);
303 static void	em_media_status(struct ifnet *, struct ifmediareq *);
304 static int	em_media_change(struct ifnet *);
305 static void	em_timer(void *);
306 
307 static void	em_intr(void *);
308 static void	em_intr_mask(void *);
309 static void	em_intr_body(struct adapter *, boolean_t);
310 static void	em_rxeof(struct adapter *, int);
311 static void	em_txeof(struct adapter *);
312 static void	em_tx_collect(struct adapter *, boolean_t);
313 static void	em_tx_purge(struct adapter *);
314 static void	em_txgc_timer(void *);
315 static void	em_enable_intr(struct adapter *);
316 static void	em_disable_intr(struct adapter *);
317 
318 static int	em_dma_malloc(struct adapter *, bus_size_t,
319 		    struct em_dma_alloc *);
320 static void	em_dma_free(struct adapter *, struct em_dma_alloc *);
321 static void	em_init_tx_ring(struct adapter *);
322 static int	em_init_rx_ring(struct adapter *);
323 static int	em_create_tx_ring(struct adapter *);
324 static int	em_create_rx_ring(struct adapter *);
325 static void	em_destroy_tx_ring(struct adapter *, int);
326 static void	em_destroy_rx_ring(struct adapter *, int);
327 static int	em_newbuf(struct adapter *, int, int);
328 static int	em_encap(struct adapter *, struct mbuf **, int *, int *);
329 static void	em_rxcsum(struct adapter *, struct e1000_rx_desc *,
330 		    struct mbuf *);
331 static int	em_txcsum(struct adapter *, struct mbuf *,
332 		    uint32_t *, uint32_t *);
333 static int	em_tso_pullup(struct adapter *, struct mbuf **);
334 static int	em_tso_setup(struct adapter *, struct mbuf *,
335 		    uint32_t *, uint32_t *);
336 
337 static int	em_get_hw_info(struct adapter *);
338 static int 	em_is_valid_eaddr(const uint8_t *);
339 static int	em_alloc_pci_res(struct adapter *);
340 static void	em_free_pci_res(struct adapter *);
341 static int	em_reset(struct adapter *);
342 static void	em_setup_ifp(struct adapter *);
343 static void	em_init_tx_unit(struct adapter *);
344 static void	em_init_rx_unit(struct adapter *);
345 static void	em_update_stats(struct adapter *);
346 static void	em_set_promisc(struct adapter *);
347 static void	em_disable_promisc(struct adapter *);
348 static void	em_set_multi(struct adapter *);
349 static void	em_update_link_status(struct adapter *);
350 static void	em_smartspeed(struct adapter *);
351 static void	em_set_itr(struct adapter *, uint32_t);
352 static void	em_disable_aspm(struct adapter *);
353 static void	em_flush_tx_ring(struct adapter *);
354 static void	em_flush_rx_ring(struct adapter *);
355 static void	em_flush_txrx_ring(struct adapter *);
356 
357 /* Hardware workarounds */
358 static int	em_82547_fifo_workaround(struct adapter *, int);
359 static void	em_82547_update_fifo_head(struct adapter *, int);
360 static int	em_82547_tx_fifo_reset(struct adapter *);
361 static void	em_82547_move_tail(void *);
362 static void	em_82547_move_tail_serialized(struct adapter *);
363 static uint32_t	em_82544_fill_desc(bus_addr_t, uint32_t, PDESC_ARRAY);
364 
365 static void	em_print_debug_info(struct adapter *);
366 static void	em_print_nvm_info(struct adapter *);
367 static void	em_print_hw_stats(struct adapter *);
368 
369 static int	em_sysctl_stats(SYSCTL_HANDLER_ARGS);
370 static int	em_sysctl_debug_info(SYSCTL_HANDLER_ARGS);
371 static int	em_sysctl_int_throttle(SYSCTL_HANDLER_ARGS);
372 static int	em_sysctl_int_tx_nsegs(SYSCTL_HANDLER_ARGS);
373 static void	em_add_sysctl(struct adapter *adapter);
374 
375 /* Management and WOL Support */
376 static void	em_get_mgmt(struct adapter *);
377 static void	em_rel_mgmt(struct adapter *);
378 static void	em_get_hw_control(struct adapter *);
379 static void	em_rel_hw_control(struct adapter *);
380 static void	em_enable_wol(device_t);
381 
382 static device_method_t em_methods[] = {
383 	/* Device interface */
384 	DEVMETHOD(device_probe,		em_probe),
385 	DEVMETHOD(device_attach,	em_attach),
386 	DEVMETHOD(device_detach,	em_detach),
387 	DEVMETHOD(device_shutdown,	em_shutdown),
388 	DEVMETHOD(device_suspend,	em_suspend),
389 	DEVMETHOD(device_resume,	em_resume),
390 	DEVMETHOD_END
391 };
392 
393 static driver_t em_driver = {
394 	"em",
395 	em_methods,
396 	sizeof(struct adapter),
397 };
398 
399 static devclass_t em_devclass;
400 
401 DECLARE_DUMMY_MODULE(if_em);
402 MODULE_DEPEND(em, ig_hal, 1, 1, 1);
403 DRIVER_MODULE(if_em, pci, em_driver, em_devclass, NULL, NULL);
404 
405 /*
406  * Tunables
407  */
408 static int	em_int_throttle_ceil = EM_DEFAULT_ITR;
409 static int	em_rxd = EM_DEFAULT_RXD;
410 static int	em_txd = EM_DEFAULT_TXD;
411 static int	em_smart_pwr_down = 0;
412 
413 /* Controls whether promiscuous also shows bad packets */
414 static int	em_debug_sbp = FALSE;
415 
416 static int	em_82573_workaround = 1;
417 static int	em_msi_enable = 1;
418 
419 static char	em_flowctrl[IFM_ETH_FC_STRLEN] = IFM_ETH_FC_NONE;
420 
421 TUNABLE_INT("hw.em.int_throttle_ceil", &em_int_throttle_ceil);
422 TUNABLE_INT("hw.em.rxd", &em_rxd);
423 TUNABLE_INT("hw.em.txd", &em_txd);
424 TUNABLE_INT("hw.em.smart_pwr_down", &em_smart_pwr_down);
425 TUNABLE_INT("hw.em.sbp", &em_debug_sbp);
426 TUNABLE_INT("hw.em.82573_workaround", &em_82573_workaround);
427 TUNABLE_INT("hw.em.msi.enable", &em_msi_enable);
428 TUNABLE_STR("hw.em.flow_ctrl", em_flowctrl, sizeof(em_flowctrl));
429 
430 /* Global used in WOL setup with multiport cards */
431 static int	em_global_quad_port_a = 0;
432 
433 /* Set this to one to display debug statistics */
434 static int	em_display_debug_stats = 0;
435 
436 #if !defined(KTR_IF_EM)
437 #define KTR_IF_EM	KTR_ALL
438 #endif
439 KTR_INFO_MASTER(if_em);
440 KTR_INFO(KTR_IF_EM, if_em, intr_beg, 0, "intr begin");
441 KTR_INFO(KTR_IF_EM, if_em, intr_end, 1, "intr end");
442 KTR_INFO(KTR_IF_EM, if_em, pkt_receive, 4, "rx packet");
443 KTR_INFO(KTR_IF_EM, if_em, pkt_txqueue, 5, "tx packet");
444 KTR_INFO(KTR_IF_EM, if_em, pkt_txclean, 6, "tx clean");
445 #define logif(name)	KTR_LOG(if_em_ ## name)
446 
447 static __inline void
448 em_tx_intr(struct adapter *adapter)
449 {
450 	struct ifnet *ifp = &adapter->arpcom.ac_if;
451 
452 	em_txeof(adapter);
453 	if (!ifq_is_empty(&ifp->if_snd))
454 		if_devstart(ifp);
455 }
456 
457 static __inline void
458 em_free_txbuffer(struct adapter *adapter, struct em_buffer *tx_buffer)
459 {
460 
461 	KKASSERT(tx_buffer->m_head != NULL);
462 	KKASSERT(adapter->tx_nmbuf > 0);
463 	adapter->tx_nmbuf--;
464 
465 	bus_dmamap_unload(adapter->txtag, tx_buffer->map);
466 	m_freem(tx_buffer->m_head);
467 	tx_buffer->m_head = NULL;
468 }
469 
470 static __inline void
471 em_try_txgc(struct adapter *adapter, int dec)
472 {
473 
474 	if (adapter->tx_running > 0) {
475 		adapter->tx_running -= dec;
476 		if (adapter->tx_running <= 0 && adapter->tx_nmbuf &&
477 		    adapter->num_tx_desc_avail < adapter->num_tx_desc &&
478 		    adapter->num_tx_desc_avail + adapter->tx_int_nsegs >
479 		    adapter->num_tx_desc)
480 			em_tx_collect(adapter, TRUE);
481 	}
482 }
483 
484 static void
485 em_txgc_timer(void *xadapter)
486 {
487 	struct adapter *adapter = xadapter;
488 	struct ifnet *ifp = &adapter->arpcom.ac_if;
489 
490 	if ((ifp->if_flags & (IFF_RUNNING | IFF_UP | IFF_NPOLLING)) !=
491 	    (IFF_RUNNING | IFF_UP))
492 		return;
493 
494 	if (!lwkt_serialize_try(ifp->if_serializer))
495 		goto done;
496 
497 	if ((ifp->if_flags & (IFF_RUNNING | IFF_UP | IFF_NPOLLING)) !=
498 	    (IFF_RUNNING | IFF_UP)) {
499 		lwkt_serialize_exit(ifp->if_serializer);
500 		return;
501 	}
502 	em_try_txgc(adapter, EM_TX_RUNNING_DEC);
503 
504 	lwkt_serialize_exit(ifp->if_serializer);
505 done:
506 	callout_reset(&adapter->tx_gc_timer, 1, em_txgc_timer, adapter);
507 }
508 
509 static int
510 em_probe(device_t dev)
511 {
512 	const struct em_vendor_info *ent;
513 	uint16_t vid, did;
514 
515 	vid = pci_get_vendor(dev);
516 	did = pci_get_device(dev);
517 
518 	for (ent = em_vendor_info_array; ent->desc != NULL; ++ent) {
519 		if (vid == ent->vendor_id && did == ent->device_id) {
520 			device_set_desc(dev, ent->desc);
521 			device_set_async_attach(dev, TRUE);
522 			return (ent->ret);
523 		}
524 	}
525 	return (ENXIO);
526 }
527 
528 static int
529 em_attach(device_t dev)
530 {
531 	struct adapter *adapter = device_get_softc(dev);
532 	struct ifnet *ifp = &adapter->arpcom.ac_if;
533 	int tsize, rsize;
534 	int error = 0;
535 	int cap;
536 	uint16_t eeprom_data, device_id, apme_mask;
537 	driver_intr_t *intr_func;
538 	char flowctrl[IFM_ETH_FC_STRLEN];
539 
540 	adapter->dev = adapter->osdep.dev = dev;
541 
542 	/*
543 	 * Some versions of I219 only have PCI AF.
544 	 */
545 	if (pci_is_pcie(dev) || pci_find_extcap(dev, PCIY_PCIAF, &cap) == 0)
546 		adapter->flags |= EM_FLAG_GEN2;
547 
548 	callout_init_mp(&adapter->timer);
549 	callout_init_mp(&adapter->tx_fifo_timer);
550 	callout_init_mp(&adapter->tx_gc_timer);
551 
552 	ifmedia_init(&adapter->media, IFM_IMASK | IFM_ETH_FCMASK,
553 	    em_media_change, em_media_status);
554 
555 	/* Determine hardware and mac info */
556 	error = em_get_hw_info(adapter);
557 	if (error) {
558 		device_printf(dev, "Identify hardware failed\n");
559 		goto fail;
560 	}
561 
562 	/* Setup PCI resources */
563 	error = em_alloc_pci_res(adapter);
564 	if (error) {
565 		device_printf(dev, "Allocation of PCI resources failed\n");
566 		goto fail;
567 	}
568 
569 	/*
570 	 * For ICH8 and family we need to map the flash memory,
571 	 * and this must happen after the MAC is identified.
572 	 *
573 	 * (SPT does not map the flash with a separate BAR)
574 	 */
575 	if (adapter->hw.mac.type == e1000_ich8lan ||
576 	    adapter->hw.mac.type == e1000_ich9lan ||
577 	    adapter->hw.mac.type == e1000_ich10lan ||
578 	    adapter->hw.mac.type == e1000_pchlan ||
579 	    adapter->hw.mac.type == e1000_pch2lan ||
580 	    adapter->hw.mac.type == e1000_pch_lpt) {
581 		adapter->flash_rid = EM_BAR_FLASH;
582 
583 		adapter->flash = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
584 					&adapter->flash_rid, RF_ACTIVE);
585 		if (adapter->flash == NULL) {
586 			device_printf(dev, "Mapping of Flash failed\n");
587 			error = ENXIO;
588 			goto fail;
589 		}
590 		adapter->osdep.flash_bus_space_tag =
591 		    rman_get_bustag(adapter->flash);
592 		adapter->osdep.flash_bus_space_handle =
593 		    rman_get_bushandle(adapter->flash);
594 
595 		/*
596 		 * This is used in the shared code
597 		 * XXX this goof is actually not used.
598 		 */
599 		adapter->hw.flash_address = (uint8_t *)adapter->flash;
600 	} else if (adapter->hw.mac.type >= e1000_pch_spt) {
601 		/*
602 		 * In the new SPT device flash is not a seperate BAR,
603 		 * rather it is also in BAR0, so use the same tag and
604 		 * an offset handle for the FLASH read/write macros
605 		 * in the shared code.
606 		 */
607 		adapter->osdep.flash_bus_space_tag =
608 		    adapter->osdep.mem_bus_space_tag;
609 		adapter->osdep.flash_bus_space_handle =
610 		    adapter->osdep.mem_bus_space_handle + E1000_FLASH_BASE_ADDR;
611 	}
612 
613 	switch (adapter->hw.mac.type) {
614 	case e1000_82571:
615 	case e1000_82572:
616 	case e1000_pch_lpt:
617 	case e1000_pch_spt:
618 	case e1000_pch_cnp:
619 		/*
620 		 * Pullup extra 4bytes into the first data segment for
621 		 * TSO, see:
622 		 * 82571/82572 specification update errata #7
623 		 *
624 		 * Same applies to I217 (and maybe I218 and I219).
625 		 *
626 		 * NOTE:
627 		 * 4bytes instead of 2bytes, which are mentioned in the
628 		 * errata, are pulled; mainly to keep rest of the data
629 		 * properly aligned.
630 		 */
631 		adapter->flags |= EM_FLAG_TSO_PULLEX;
632 		/* FALL THROUGH */
633 
634 	default:
635 		if (adapter->flags & EM_FLAG_GEN2)
636 			adapter->flags |= EM_FLAG_TSO;
637 		break;
638 	}
639 
640 	/* Do Shared Code initialization */
641 	if (e1000_setup_init_funcs(&adapter->hw, TRUE)) {
642 		device_printf(dev, "Setup of Shared code failed\n");
643 		error = ENXIO;
644 		goto fail;
645 	}
646 
647 	e1000_get_bus_info(&adapter->hw);
648 
649 	/*
650 	 * Validate number of transmit and receive descriptors.  It
651 	 * must not exceed hardware maximum, and must be multiple
652 	 * of E1000_DBA_ALIGN.
653 	 */
654 	if ((em_txd * sizeof(struct e1000_tx_desc)) % EM_DBA_ALIGN != 0 ||
655 	    (adapter->hw.mac.type >= e1000_82544 && em_txd > EM_MAX_TXD) ||
656 	    (adapter->hw.mac.type < e1000_82544 && em_txd > EM_MAX_TXD_82543) ||
657 	    em_txd < EM_MIN_TXD) {
658 		if (adapter->hw.mac.type < e1000_82544)
659 			adapter->num_tx_desc = EM_MAX_TXD_82543;
660 		else
661 			adapter->num_tx_desc = EM_DEFAULT_TXD;
662 		device_printf(dev, "Using %d TX descriptors instead of %d!\n",
663 		    adapter->num_tx_desc, em_txd);
664 	} else {
665 		adapter->num_tx_desc = em_txd;
666 	}
667 	if ((em_rxd * sizeof(struct e1000_rx_desc)) % EM_DBA_ALIGN != 0 ||
668 	    (adapter->hw.mac.type >= e1000_82544 && em_rxd > EM_MAX_RXD) ||
669 	    (adapter->hw.mac.type < e1000_82544 && em_rxd > EM_MAX_RXD_82543) ||
670 	    em_rxd < EM_MIN_RXD) {
671 		if (adapter->hw.mac.type < e1000_82544)
672 			adapter->num_rx_desc = EM_MAX_RXD_82543;
673 		else
674 			adapter->num_rx_desc = EM_DEFAULT_RXD;
675 		device_printf(dev, "Using %d RX descriptors instead of %d!\n",
676 		    adapter->num_rx_desc, em_rxd);
677 	} else {
678 		adapter->num_rx_desc = em_rxd;
679 	}
680 
681 	adapter->hw.mac.autoneg = DO_AUTO_NEG;
682 	adapter->hw.phy.autoneg_wait_to_complete = FALSE;
683 	adapter->hw.phy.autoneg_advertised = AUTONEG_ADV_DEFAULT;
684 	adapter->rx_buffer_len = MCLBYTES;
685 
686 	/*
687 	 * Interrupt throttle rate
688 	 */
689 	if (em_int_throttle_ceil == 0) {
690 		adapter->int_throttle_ceil = 0;
691 	} else {
692 		int throttle = em_int_throttle_ceil;
693 
694 		if (throttle < 0)
695 			throttle = EM_DEFAULT_ITR;
696 
697 		/* Recalculate the tunable value to get the exact frequency. */
698 		throttle = 1000000000 / 256 / throttle;
699 
700 		/* Upper 16bits of ITR is reserved and should be zero */
701 		if (throttle & 0xffff0000)
702 			throttle = 1000000000 / 256 / EM_DEFAULT_ITR;
703 
704 		adapter->int_throttle_ceil = 1000000000 / 256 / throttle;
705 	}
706 
707 	e1000_init_script_state_82541(&adapter->hw, TRUE);
708 	e1000_set_tbi_compatibility_82543(&adapter->hw, TRUE);
709 
710 	/* Copper options */
711 	if (adapter->hw.phy.media_type == e1000_media_type_copper) {
712 		adapter->hw.phy.mdix = AUTO_ALL_MODES;
713 		adapter->hw.phy.disable_polarity_correction = FALSE;
714 		adapter->hw.phy.ms_type = EM_MASTER_SLAVE;
715 	}
716 
717 	/* Set the frame limits assuming standard ethernet sized frames. */
718 	adapter->hw.mac.max_frame_size =
719 	    ETHERMTU + ETHER_HDR_LEN + ETHER_CRC_LEN;
720 	adapter->min_frame_size = ETH_ZLEN + ETHER_CRC_LEN;
721 
722 	/* This controls when hardware reports transmit completion status. */
723 	adapter->hw.mac.report_tx_early = 1;
724 
725 	/*
726 	 * Create top level busdma tag
727 	 */
728 	error = bus_dma_tag_create(NULL, 1, 0,
729 			BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
730 			NULL, NULL,
731 			BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
732 			0, &adapter->parent_dtag);
733 	if (error) {
734 		device_printf(dev, "could not create top level DMA tag\n");
735 		goto fail;
736 	}
737 
738 	/*
739 	 * Allocate Transmit Descriptor ring
740 	 */
741 	tsize = roundup2(adapter->num_tx_desc * sizeof(struct e1000_tx_desc),
742 			 EM_DBA_ALIGN);
743 	error = em_dma_malloc(adapter, tsize, &adapter->txdma);
744 	if (error) {
745 		device_printf(dev, "Unable to allocate tx_desc memory\n");
746 		goto fail;
747 	}
748 	adapter->tx_desc_base = adapter->txdma.dma_vaddr;
749 
750 	/*
751 	 * Allocate Receive Descriptor ring
752 	 */
753 	rsize = roundup2(adapter->num_rx_desc * sizeof(struct e1000_rx_desc),
754 			 EM_DBA_ALIGN);
755 	error = em_dma_malloc(adapter, rsize, &adapter->rxdma);
756 	if (error) {
757 		device_printf(dev, "Unable to allocate rx_desc memory\n");
758 		goto fail;
759 	}
760 	adapter->rx_desc_base = adapter->rxdma.dma_vaddr;
761 
762 	/* Allocate multicast array memory. */
763 	adapter->mta = kmalloc(ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES,
764 	    M_DEVBUF, M_WAITOK);
765 
766 	/* Indicate SOL/IDER usage */
767 	if (e1000_check_reset_block(&adapter->hw)) {
768 		device_printf(dev,
769 		    "PHY reset is blocked due to SOL/IDER session.\n");
770 	}
771 
772 	/* Disable EEE */
773 	adapter->hw.dev_spec.ich8lan.eee_disable = 1;
774 
775 	/*
776 	 * Start from a known state, this is important in reading the
777 	 * nvm and mac from that.
778 	 */
779 	e1000_reset_hw(&adapter->hw);
780 
781 	/* Make sure we have a good EEPROM before we read from it */
782 	if (e1000_validate_nvm_checksum(&adapter->hw) < 0) {
783 		/*
784 		 * Some PCI-E parts fail the first check due to
785 		 * the link being in sleep state, call it again,
786 		 * if it fails a second time its a real issue.
787 		 */
788 		if (e1000_validate_nvm_checksum(&adapter->hw) < 0) {
789 			device_printf(dev,
790 			    "The EEPROM Checksum Is Not Valid\n");
791 			error = EIO;
792 			goto fail;
793 		}
794 	}
795 
796 	/* Copy the permanent MAC address out of the EEPROM */
797 	if (e1000_read_mac_addr(&adapter->hw) < 0) {
798 		device_printf(dev, "EEPROM read error while reading MAC"
799 		    " address\n");
800 		error = EIO;
801 		goto fail;
802 	}
803 	if (!em_is_valid_eaddr(adapter->hw.mac.addr)) {
804 		device_printf(dev, "Invalid MAC address\n");
805 		error = EIO;
806 		goto fail;
807 	}
808 
809 	/* Disable ULP support */
810 	e1000_disable_ulp_lpt_lp(&adapter->hw, TRUE);
811 
812 	/* Allocate transmit descriptors and buffers */
813 	error = em_create_tx_ring(adapter);
814 	if (error) {
815 		device_printf(dev, "Could not setup transmit structures\n");
816 		goto fail;
817 	}
818 
819 	/* Allocate receive descriptors and buffers */
820 	error = em_create_rx_ring(adapter);
821 	if (error) {
822 		device_printf(dev, "Could not setup receive structures\n");
823 		goto fail;
824 	}
825 
826 	/* Manually turn off all interrupts */
827 	E1000_WRITE_REG(&adapter->hw, E1000_IMC, 0xffffffff);
828 
829 	/* Determine if we have to control management hardware */
830 	if (e1000_enable_mng_pass_thru(&adapter->hw))
831 		adapter->flags |= EM_FLAG_HAS_MGMT;
832 
833 	/*
834 	 * Setup Wake-on-Lan
835 	 */
836 	apme_mask = EM_EEPROM_APME;
837 	eeprom_data = 0;
838 	switch (adapter->hw.mac.type) {
839 	case e1000_82542:
840 	case e1000_82543:
841 		break;
842 
843 	case e1000_82573:
844 	case e1000_82583:
845 		adapter->flags |= EM_FLAG_HAS_AMT;
846 		/* FALL THROUGH */
847 
848 	case e1000_82546:
849 	case e1000_82546_rev_3:
850 	case e1000_82571:
851 	case e1000_82572:
852 	case e1000_80003es2lan:
853 		if (adapter->hw.bus.func == 1) {
854 			e1000_read_nvm(&adapter->hw,
855 			    NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
856 		} else {
857 			e1000_read_nvm(&adapter->hw,
858 			    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
859 		}
860 		break;
861 
862 	case e1000_ich8lan:
863 	case e1000_ich9lan:
864 	case e1000_ich10lan:
865 	case e1000_pchlan:
866 	case e1000_pch2lan:
867 	case e1000_pch_lpt:
868 	case e1000_pch_spt:
869 	case e1000_pch_cnp:
870 		apme_mask = E1000_WUC_APME;
871 		adapter->flags |= EM_FLAG_HAS_AMT;
872 		eeprom_data = E1000_READ_REG(&adapter->hw, E1000_WUC);
873 		break;
874 
875 	default:
876 		e1000_read_nvm(&adapter->hw,
877 		    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
878 		break;
879 	}
880 	if (eeprom_data & apme_mask)
881 		adapter->wol = E1000_WUFC_MAG | E1000_WUFC_MC;
882 
883 	/*
884          * We have the eeprom settings, now apply the special cases
885          * where the eeprom may be wrong or the board won't support
886          * wake on lan on a particular port
887 	 */
888 	device_id = pci_get_device(dev);
889         switch (device_id) {
890 	case E1000_DEV_ID_82546GB_PCIE:
891 		adapter->wol = 0;
892 		break;
893 
894 	case E1000_DEV_ID_82546EB_FIBER:
895 	case E1000_DEV_ID_82546GB_FIBER:
896 	case E1000_DEV_ID_82571EB_FIBER:
897 		/*
898 		 * Wake events only supported on port A for dual fiber
899 		 * regardless of eeprom setting
900 		 */
901 		if (E1000_READ_REG(&adapter->hw, E1000_STATUS) &
902 		    E1000_STATUS_FUNC_1)
903 			adapter->wol = 0;
904 		break;
905 
906 	case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3:
907 	case E1000_DEV_ID_82571EB_QUAD_COPPER:
908 	case E1000_DEV_ID_82571EB_QUAD_FIBER:
909 	case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
910                 /* if quad port adapter, disable WoL on all but port A */
911 		if (em_global_quad_port_a != 0)
912 			adapter->wol = 0;
913 		/* Reset for multiple quad port adapters */
914 		if (++em_global_quad_port_a == 4)
915 			em_global_quad_port_a = 0;
916                 break;
917 	}
918 
919 	/* XXX disable wol */
920 	adapter->wol = 0;
921 
922 	/* Setup flow control. */
923 	device_getenv_string(dev, "flow_ctrl", flowctrl, sizeof(flowctrl),
924 	    em_flowctrl);
925 	adapter->ifm_flowctrl = ifmedia_str2ethfc(flowctrl);
926 	if (adapter->hw.mac.type == e1000_pchlan) {
927 		/* Only PAUSE reception is supported on PCH */
928 		adapter->ifm_flowctrl &= ~IFM_ETH_TXPAUSE;
929 	}
930 
931 	/* Setup OS specific network interface */
932 	em_setup_ifp(adapter);
933 
934 	/* Add sysctl tree, must after em_setup_ifp() */
935 	em_add_sysctl(adapter);
936 
937 #ifdef IFPOLL_ENABLE
938 	/* Polling setup */
939 	ifpoll_compat_setup(&adapter->npoll,
940 	    device_get_sysctl_ctx(dev), device_get_sysctl_tree(dev),
941 	    device_get_unit(dev), ifp->if_serializer);
942 #endif
943 
944 	/* Reset the hardware */
945 	error = em_reset(adapter);
946 	if (error) {
947 		/*
948 		 * Some 82573 parts fail the first reset, call it again,
949 		 * if it fails a second time its a real issue.
950 		 */
951 		error = em_reset(adapter);
952 		if (error) {
953 			device_printf(dev, "Unable to reset the hardware\n");
954 			ether_ifdetach(ifp);
955 			goto fail;
956 		}
957 	}
958 
959 	/* Initialize statistics */
960 	em_update_stats(adapter);
961 
962 	adapter->hw.mac.get_link_status = 1;
963 	em_update_link_status(adapter);
964 
965 	/* Do we need workaround for 82544 PCI-X adapter? */
966 	if (adapter->hw.bus.type == e1000_bus_type_pcix &&
967 	    adapter->hw.mac.type == e1000_82544)
968 		adapter->pcix_82544 = TRUE;
969 	else
970 		adapter->pcix_82544 = FALSE;
971 
972 	if (adapter->pcix_82544) {
973 		/*
974 		 * 82544 on PCI-X may split one TX segment
975 		 * into two TX descs, so we double its number
976 		 * of spare TX desc here.
977 		 */
978 		adapter->spare_tx_desc = 2 * EM_TX_SPARE;
979 	} else {
980 		adapter->spare_tx_desc = EM_TX_SPARE;
981 	}
982 	if (adapter->flags & EM_FLAG_TSO)
983 		adapter->spare_tx_desc = EM_TX_SPARE_TSO;
984 	adapter->tx_wreg_nsegs = EM_DEFAULT_TXWREG;
985 
986 	/*
987 	 * Keep following relationship between spare_tx_desc, oact_tx_desc
988 	 * and tx_int_nsegs:
989 	 * (spare_tx_desc + EM_TX_RESERVED) <=
990 	 * oact_tx_desc <= EM_TX_OACTIVE_MAX <= tx_int_nsegs
991 	 */
992 	adapter->oact_tx_desc = adapter->num_tx_desc / 8;
993 	if (adapter->oact_tx_desc > EM_TX_OACTIVE_MAX)
994 		adapter->oact_tx_desc = EM_TX_OACTIVE_MAX;
995 	if (adapter->oact_tx_desc < adapter->spare_tx_desc + EM_TX_RESERVED)
996 		adapter->oact_tx_desc = adapter->spare_tx_desc + EM_TX_RESERVED;
997 
998 	adapter->tx_int_nsegs = adapter->num_tx_desc / 16;
999 	if (adapter->tx_int_nsegs < adapter->oact_tx_desc)
1000 		adapter->tx_int_nsegs = adapter->oact_tx_desc;
1001 
1002 	/* Non-AMT based hardware can now take control from firmware */
1003 	if ((adapter->flags & (EM_FLAG_HAS_MGMT | EM_FLAG_HAS_AMT)) ==
1004 	    EM_FLAG_HAS_MGMT && adapter->hw.mac.type >= e1000_82571)
1005 		em_get_hw_control(adapter);
1006 
1007 	ifq_set_cpuid(&ifp->if_snd, rman_get_cpuid(adapter->intr_res));
1008 
1009 	/*
1010 	 * Missing Interrupt Following ICR read:
1011 	 *
1012 	 * 82571/82572 specification update errata #76
1013 	 * 82573 specification update errata #31
1014 	 * 82574 specification update errata #12
1015 	 * 82583 specification update errata #4
1016 	 */
1017 	intr_func = em_intr;
1018 	if ((adapter->flags & EM_FLAG_SHARED_INTR) &&
1019 	    (adapter->hw.mac.type == e1000_82571 ||
1020 	     adapter->hw.mac.type == e1000_82572 ||
1021 	     adapter->hw.mac.type == e1000_82573 ||
1022 	     adapter->hw.mac.type == e1000_82574 ||
1023 	     adapter->hw.mac.type == e1000_82583))
1024 		intr_func = em_intr_mask;
1025 
1026 	error = bus_setup_intr(dev, adapter->intr_res, INTR_MPSAFE,
1027 			       intr_func, adapter, &adapter->intr_tag,
1028 			       ifp->if_serializer);
1029 	if (error) {
1030 		device_printf(dev, "Failed to register interrupt handler");
1031 		ether_ifdetach(ifp);
1032 		goto fail;
1033 	}
1034 	return (0);
1035 fail:
1036 	em_detach(dev);
1037 	return (error);
1038 }
1039 
1040 static int
1041 em_detach(device_t dev)
1042 {
1043 	struct adapter *adapter = device_get_softc(dev);
1044 
1045 	if (device_is_attached(dev)) {
1046 		struct ifnet *ifp = &adapter->arpcom.ac_if;
1047 
1048 		lwkt_serialize_enter(ifp->if_serializer);
1049 
1050 		em_stop(adapter);
1051 
1052 		e1000_phy_hw_reset(&adapter->hw);
1053 
1054 		em_rel_mgmt(adapter);
1055 		em_rel_hw_control(adapter);
1056 
1057 		if (adapter->wol) {
1058 			E1000_WRITE_REG(&adapter->hw, E1000_WUC,
1059 					E1000_WUC_PME_EN);
1060 			E1000_WRITE_REG(&adapter->hw, E1000_WUFC, adapter->wol);
1061 			em_enable_wol(dev);
1062 		}
1063 
1064 		bus_teardown_intr(dev, adapter->intr_res, adapter->intr_tag);
1065 
1066 		lwkt_serialize_exit(ifp->if_serializer);
1067 
1068 		ether_ifdetach(ifp);
1069 	} else if (adapter->memory != NULL) {
1070 		em_rel_hw_control(adapter);
1071 	}
1072 
1073 	ifmedia_removeall(&adapter->media);
1074 	bus_generic_detach(dev);
1075 
1076 	em_free_pci_res(adapter);
1077 
1078 	em_destroy_tx_ring(adapter, adapter->num_tx_desc);
1079 	em_destroy_rx_ring(adapter, adapter->num_rx_desc);
1080 
1081 	/* Free Transmit Descriptor ring */
1082 	if (adapter->tx_desc_base)
1083 		em_dma_free(adapter, &adapter->txdma);
1084 
1085 	/* Free Receive Descriptor ring */
1086 	if (adapter->rx_desc_base)
1087 		em_dma_free(adapter, &adapter->rxdma);
1088 
1089 	/* Free top level busdma tag */
1090 	if (adapter->parent_dtag != NULL)
1091 		bus_dma_tag_destroy(adapter->parent_dtag);
1092 
1093 	if (adapter->mta != NULL)
1094 		kfree(adapter->mta, M_DEVBUF);
1095 
1096 	return (0);
1097 }
1098 
1099 static int
1100 em_shutdown(device_t dev)
1101 {
1102 	return em_suspend(dev);
1103 }
1104 
1105 static int
1106 em_suspend(device_t dev)
1107 {
1108 	struct adapter *adapter = device_get_softc(dev);
1109 	struct ifnet *ifp = &adapter->arpcom.ac_if;
1110 
1111 	lwkt_serialize_enter(ifp->if_serializer);
1112 
1113 	em_stop(adapter);
1114 
1115 	em_rel_mgmt(adapter);
1116 	em_rel_hw_control(adapter);
1117 
1118 	if (adapter->wol) {
1119 		E1000_WRITE_REG(&adapter->hw, E1000_WUC, E1000_WUC_PME_EN);
1120 		E1000_WRITE_REG(&adapter->hw, E1000_WUFC, adapter->wol);
1121 		em_enable_wol(dev);
1122 	}
1123 
1124 	lwkt_serialize_exit(ifp->if_serializer);
1125 
1126 	return bus_generic_suspend(dev);
1127 }
1128 
1129 static int
1130 em_resume(device_t dev)
1131 {
1132 	struct adapter *adapter = device_get_softc(dev);
1133 	struct ifnet *ifp = &adapter->arpcom.ac_if;
1134 
1135 	lwkt_serialize_enter(ifp->if_serializer);
1136 
1137 	if (adapter->hw.mac.type == e1000_pch2lan)
1138 		e1000_resume_workarounds_pchlan(&adapter->hw);
1139 
1140 	em_init(adapter);
1141 	em_get_mgmt(adapter);
1142 	if_devstart(ifp);
1143 
1144 	lwkt_serialize_exit(ifp->if_serializer);
1145 
1146 	return bus_generic_resume(dev);
1147 }
1148 
1149 static void
1150 em_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
1151 {
1152 	struct adapter *adapter = ifp->if_softc;
1153 	struct mbuf *m_head;
1154 	int idx = -1, nsegs = 0;
1155 
1156 	ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
1157 	ASSERT_SERIALIZED(ifp->if_serializer);
1158 
1159 	if ((ifp->if_flags & IFF_RUNNING) == 0 || ifq_is_oactive(&ifp->if_snd))
1160 		return;
1161 
1162 	if (!adapter->link_active) {
1163 		ifq_purge(&ifp->if_snd);
1164 		return;
1165 	}
1166 
1167 	while (!ifq_is_empty(&ifp->if_snd)) {
1168 		/* Now do we at least have a minimal? */
1169 		if (EM_IS_OACTIVE(adapter)) {
1170 			em_tx_collect(adapter, FALSE);
1171 			if (EM_IS_OACTIVE(adapter)) {
1172 				ifq_set_oactive(&ifp->if_snd);
1173 				adapter->no_tx_desc_avail1++;
1174 				break;
1175 			}
1176 		}
1177 
1178 		logif(pkt_txqueue);
1179 		m_head = ifq_dequeue(&ifp->if_snd);
1180 		if (m_head == NULL)
1181 			break;
1182 
1183 		if (em_encap(adapter, &m_head, &nsegs, &idx)) {
1184 			IFNET_STAT_INC(ifp, oerrors, 1);
1185 			em_tx_collect(adapter, FALSE);
1186 			continue;
1187 		}
1188 
1189 		/*
1190 		 * TX interrupt are aggressively aggregated, so increasing
1191 		 * opackets at TX interrupt time will make the opackets
1192 		 * statistics vastly inaccurate; we do the opackets increment
1193 		 * now.
1194 		 */
1195 		IFNET_STAT_INC(ifp, opackets, 1);
1196 
1197 		if (nsegs >= adapter->tx_wreg_nsegs && idx >= 0) {
1198 			E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), idx);
1199 			nsegs = 0;
1200 			idx = -1;
1201 		}
1202 
1203 		/* Send a copy of the frame to the BPF listener */
1204 		ETHER_BPF_MTAP(ifp, m_head);
1205 
1206 		/* Set timeout in case hardware has problems transmitting. */
1207 		ifp->if_timer = EM_TX_TIMEOUT;
1208 	}
1209 	if (idx >= 0)
1210 		E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), idx);
1211 	adapter->tx_running = EM_TX_RUNNING;
1212 }
1213 
1214 static int
1215 em_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
1216 {
1217 	struct adapter *adapter = ifp->if_softc;
1218 	struct ifreq *ifr = (struct ifreq *)data;
1219 	uint16_t eeprom_data = 0;
1220 	int max_frame_size, mask, reinit;
1221 	int error = 0;
1222 
1223 	ASSERT_SERIALIZED(ifp->if_serializer);
1224 
1225 	switch (command) {
1226 	case SIOCSIFMTU:
1227 		switch (adapter->hw.mac.type) {
1228 		case e1000_82573:
1229 			/*
1230 			 * 82573 only supports jumbo frames
1231 			 * if ASPM is disabled.
1232 			 */
1233 			e1000_read_nvm(&adapter->hw,
1234 			    NVM_INIT_3GIO_3, 1, &eeprom_data);
1235 			if (eeprom_data & NVM_WORD1A_ASPM_MASK) {
1236 				max_frame_size = ETHER_MAX_LEN;
1237 				break;
1238 			}
1239 			/* FALL THROUGH */
1240 
1241 		/* Limit Jumbo Frame size */
1242 		case e1000_82571:
1243 		case e1000_82572:
1244 		case e1000_ich9lan:
1245 		case e1000_ich10lan:
1246 		case e1000_pch2lan:
1247 		case e1000_pch_lpt:
1248 		case e1000_pch_spt:
1249 		case e1000_pch_cnp:
1250 		case e1000_82574:
1251 		case e1000_82583:
1252 		case e1000_80003es2lan:
1253 			max_frame_size = 9234;
1254 			break;
1255 
1256 		case e1000_pchlan:
1257 			max_frame_size = 4096;
1258 			break;
1259 
1260 		/* Adapters that do not support jumbo frames */
1261 		case e1000_82542:
1262 		case e1000_ich8lan:
1263 			max_frame_size = ETHER_MAX_LEN;
1264 			break;
1265 
1266 		default:
1267 			max_frame_size = MAX_JUMBO_FRAME_SIZE;
1268 			break;
1269 		}
1270 		if (ifr->ifr_mtu > max_frame_size - ETHER_HDR_LEN -
1271 		    ETHER_CRC_LEN) {
1272 			error = EINVAL;
1273 			break;
1274 		}
1275 
1276 		ifp->if_mtu = ifr->ifr_mtu;
1277 		adapter->hw.mac.max_frame_size =
1278 		    ifp->if_mtu + ETHER_HDR_LEN + ETHER_CRC_LEN;
1279 
1280 		if (ifp->if_flags & IFF_RUNNING)
1281 			em_init(adapter);
1282 		break;
1283 
1284 	case SIOCSIFFLAGS:
1285 		if (ifp->if_flags & IFF_UP) {
1286 			if ((ifp->if_flags & IFF_RUNNING)) {
1287 				if ((ifp->if_flags ^ adapter->if_flags) &
1288 				    (IFF_PROMISC | IFF_ALLMULTI)) {
1289 					em_disable_promisc(adapter);
1290 					em_set_promisc(adapter);
1291 				}
1292 			} else {
1293 				em_init(adapter);
1294 			}
1295 		} else if (ifp->if_flags & IFF_RUNNING) {
1296 			em_stop(adapter);
1297 		}
1298 		adapter->if_flags = ifp->if_flags;
1299 		break;
1300 
1301 	case SIOCADDMULTI:
1302 	case SIOCDELMULTI:
1303 		if (ifp->if_flags & IFF_RUNNING) {
1304 			em_disable_intr(adapter);
1305 			em_set_multi(adapter);
1306 			if (adapter->hw.mac.type == e1000_82542 &&
1307 			    adapter->hw.revision_id == E1000_REVISION_2)
1308 				em_init_rx_unit(adapter);
1309 #ifdef IFPOLL_ENABLE
1310 			if (!(ifp->if_flags & IFF_NPOLLING))
1311 #endif
1312 				em_enable_intr(adapter);
1313 		}
1314 		break;
1315 
1316 	case SIOCSIFMEDIA:
1317 		/* Check SOL/IDER usage */
1318 		if (e1000_check_reset_block(&adapter->hw)) {
1319 			device_printf(adapter->dev, "Media change is"
1320 			    " blocked due to SOL/IDER session.\n");
1321 			break;
1322 		}
1323 		/* FALL THROUGH */
1324 
1325 	case SIOCGIFMEDIA:
1326 		error = ifmedia_ioctl(ifp, ifr, &adapter->media, command);
1327 		break;
1328 
1329 	case SIOCSIFCAP:
1330 		reinit = 0;
1331 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1332 		if (mask & IFCAP_RXCSUM) {
1333 			ifp->if_capenable ^= IFCAP_RXCSUM;
1334 			reinit = 1;
1335 		}
1336 		if (mask & IFCAP_TXCSUM) {
1337 			ifp->if_capenable ^= IFCAP_TXCSUM;
1338 			if (ifp->if_capenable & IFCAP_TXCSUM)
1339 				ifp->if_hwassist |= EM_CSUM_FEATURES;
1340 			else
1341 				ifp->if_hwassist &= ~EM_CSUM_FEATURES;
1342 		}
1343 		if (mask & IFCAP_TSO) {
1344 			ifp->if_capenable ^= IFCAP_TSO;
1345 			if (ifp->if_capenable & IFCAP_TSO)
1346 				ifp->if_hwassist |= CSUM_TSO;
1347 			else
1348 				ifp->if_hwassist &= ~CSUM_TSO;
1349 		}
1350 		if (mask & IFCAP_VLAN_HWTAGGING) {
1351 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1352 			reinit = 1;
1353 		}
1354 		if (reinit && (ifp->if_flags & IFF_RUNNING))
1355 			em_init(adapter);
1356 		break;
1357 
1358 	default:
1359 		error = ether_ioctl(ifp, command, data);
1360 		break;
1361 	}
1362 	return (error);
1363 }
1364 
1365 static void
1366 em_watchdog(struct ifnet *ifp)
1367 {
1368 	struct adapter *adapter = ifp->if_softc;
1369 
1370 	ASSERT_SERIALIZED(ifp->if_serializer);
1371 
1372 	/*
1373 	 * The timer is set to 5 every time start queues a packet.
1374 	 * Then txeof keeps resetting it as long as it cleans at
1375 	 * least one descriptor.
1376 	 * Finally, anytime all descriptors are clean the timer is
1377 	 * set to 0.
1378 	 */
1379 
1380 	if (E1000_READ_REG(&adapter->hw, E1000_TDT(0)) ==
1381 	    E1000_READ_REG(&adapter->hw, E1000_TDH(0))) {
1382 		/*
1383 		 * If we reach here, all TX jobs are completed and
1384 		 * the TX engine should have been idled for some time.
1385 		 * We don't need to call if_devstart() here.
1386 		 */
1387 		ifq_clr_oactive(&ifp->if_snd);
1388 		ifp->if_timer = 0;
1389 		return;
1390 	}
1391 
1392 	/*
1393 	 * If we are in this routine because of pause frames, then
1394 	 * don't reset the hardware.
1395 	 */
1396 	if (E1000_READ_REG(&adapter->hw, E1000_STATUS) &
1397 	    E1000_STATUS_TXOFF) {
1398 		ifp->if_timer = EM_TX_TIMEOUT;
1399 		return;
1400 	}
1401 
1402 	if (e1000_check_for_link(&adapter->hw) == 0)
1403 		if_printf(ifp, "watchdog timeout -- resetting\n");
1404 
1405 	IFNET_STAT_INC(ifp, oerrors, 1);
1406 	adapter->watchdog_events++;
1407 
1408 	em_init(adapter);
1409 
1410 	if (!ifq_is_empty(&ifp->if_snd))
1411 		if_devstart(ifp);
1412 }
1413 
1414 static void
1415 em_init(void *xsc)
1416 {
1417 	struct adapter *adapter = xsc;
1418 	struct ifnet *ifp = &adapter->arpcom.ac_if;
1419 	device_t dev = adapter->dev;
1420 
1421 	ASSERT_SERIALIZED(ifp->if_serializer);
1422 
1423 	em_stop(adapter);
1424 
1425 	/* Get the latest mac address, User can use a LAA */
1426         bcopy(IF_LLADDR(ifp), adapter->hw.mac.addr, ETHER_ADDR_LEN);
1427 
1428 	/* Put the address into the Receive Address Array */
1429 	e1000_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
1430 
1431 	/*
1432 	 * With the 82571 adapter, RAR[0] may be overwritten
1433 	 * when the other port is reset, we make a duplicate
1434 	 * in RAR[14] for that eventuality, this assures
1435 	 * the interface continues to function.
1436 	 */
1437 	if (adapter->hw.mac.type == e1000_82571) {
1438 		e1000_set_laa_state_82571(&adapter->hw, TRUE);
1439 		e1000_rar_set(&adapter->hw, adapter->hw.mac.addr,
1440 		    E1000_RAR_ENTRIES - 1);
1441 	}
1442 
1443 	/* Reset the hardware */
1444 	if (em_reset(adapter)) {
1445 		device_printf(dev, "Unable to reset the hardware\n");
1446 		/* XXX em_stop()? */
1447 		return;
1448 	}
1449 	em_update_link_status(adapter);
1450 
1451 	/* Setup VLAN support, basic and offload if available */
1452 	E1000_WRITE_REG(&adapter->hw, E1000_VET, ETHERTYPE_VLAN);
1453 
1454 	if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1455 		uint32_t ctrl;
1456 
1457 		ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
1458 		ctrl |= E1000_CTRL_VME;
1459 		E1000_WRITE_REG(&adapter->hw, E1000_CTRL, ctrl);
1460 	}
1461 
1462 	/* Configure for OS presence */
1463 	em_get_mgmt(adapter);
1464 
1465 	/* Prepare transmit descriptors and buffers */
1466 	em_init_tx_ring(adapter);
1467 	em_init_tx_unit(adapter);
1468 
1469 	/* Setup Multicast table */
1470 	em_set_multi(adapter);
1471 
1472 	/* Prepare receive descriptors and buffers */
1473 	if (em_init_rx_ring(adapter)) {
1474 		device_printf(dev, "Could not setup receive structures\n");
1475 		em_stop(adapter);
1476 		return;
1477 	}
1478 	em_init_rx_unit(adapter);
1479 
1480 	/* Don't lose promiscuous settings */
1481 	em_set_promisc(adapter);
1482 
1483 	/* Reset hardware counters */
1484 	e1000_clear_hw_cntrs_base_generic(&adapter->hw);
1485 
1486 	/* MSI/X configuration for 82574 */
1487 	if (adapter->hw.mac.type == e1000_82574) {
1488 		int tmp;
1489 
1490 		tmp = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
1491 		tmp |= E1000_CTRL_EXT_PBA_CLR;
1492 		E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT, tmp);
1493 		/*
1494 		 * XXX MSIX
1495 		 * Set the IVAR - interrupt vector routing.
1496 		 * Each nibble represents a vector, high bit
1497 		 * is enable, other 3 bits are the MSIX table
1498 		 * entry, we map RXQ0 to 0, TXQ0 to 1, and
1499 		 * Link (other) to 2, hence the magic number.
1500 		 */
1501 		E1000_WRITE_REG(&adapter->hw, E1000_IVAR, 0x800A0908);
1502 	}
1503 
1504 #ifdef IFPOLL_ENABLE
1505 	/*
1506 	 * Only enable interrupts if we are not polling, make sure
1507 	 * they are off otherwise.
1508 	 */
1509 	if (ifp->if_flags & IFF_NPOLLING)
1510 		em_disable_intr(adapter);
1511 	else
1512 #endif /* IFPOLL_ENABLE */
1513 		em_enable_intr(adapter);
1514 
1515 	/* AMT based hardware can now take control from firmware */
1516 	if ((adapter->flags & (EM_FLAG_HAS_MGMT | EM_FLAG_HAS_AMT)) ==
1517 	    (EM_FLAG_HAS_MGMT | EM_FLAG_HAS_AMT) &&
1518 	    adapter->hw.mac.type >= e1000_82571)
1519 		em_get_hw_control(adapter);
1520 
1521 	ifp->if_flags |= IFF_RUNNING;
1522 	ifq_clr_oactive(&ifp->if_snd);
1523 
1524 #ifdef IFPOLL_ENABLE
1525 	if ((ifp->if_flags & IFF_NPOLLING) == 0)
1526 #endif
1527 	{
1528 		callout_reset_bycpu(&adapter->tx_gc_timer, 1,
1529 		    em_txgc_timer, adapter,
1530 		    rman_get_cpuid(adapter->intr_res));
1531 	}
1532 	callout_reset(&adapter->timer, hz, em_timer, adapter);
1533 }
1534 
1535 #ifdef IFPOLL_ENABLE
1536 
1537 static void
1538 em_npoll_compat(struct ifnet *ifp, void *arg __unused, int count)
1539 {
1540 	struct adapter *adapter = ifp->if_softc;
1541 
1542 	ASSERT_SERIALIZED(ifp->if_serializer);
1543 
1544 	if (adapter->npoll.ifpc_stcount-- == 0) {
1545 		uint32_t reg_icr;
1546 
1547 		adapter->npoll.ifpc_stcount = adapter->npoll.ifpc_stfrac;
1548 
1549 		reg_icr = E1000_READ_REG(&adapter->hw, E1000_ICR);
1550 		if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1551 			callout_stop(&adapter->timer);
1552 			adapter->hw.mac.get_link_status = 1;
1553 			em_update_link_status(adapter);
1554 			callout_reset(&adapter->timer, hz, em_timer, adapter);
1555 		}
1556 	}
1557 
1558 	em_rxeof(adapter, count);
1559 
1560 	em_tx_intr(adapter);
1561 	em_try_txgc(adapter, 1);
1562 }
1563 
1564 static void
1565 em_npoll(struct ifnet *ifp, struct ifpoll_info *info)
1566 {
1567 	struct adapter *adapter = ifp->if_softc;
1568 
1569 	ASSERT_SERIALIZED(ifp->if_serializer);
1570 
1571 	if (info != NULL) {
1572 		int cpuid = adapter->npoll.ifpc_cpuid;
1573 
1574                 info->ifpi_rx[cpuid].poll_func = em_npoll_compat;
1575 		info->ifpi_rx[cpuid].arg = NULL;
1576 		info->ifpi_rx[cpuid].serializer = ifp->if_serializer;
1577 
1578 		ifq_set_cpuid(&ifp->if_snd, cpuid);
1579 	} else {
1580 		ifq_set_cpuid(&ifp->if_snd, rman_get_cpuid(adapter->intr_res));
1581 	}
1582 	if (ifp->if_flags & IFF_RUNNING)
1583 		em_init(adapter);
1584 }
1585 
1586 #endif /* IFPOLL_ENABLE */
1587 
1588 static void
1589 em_intr(void *xsc)
1590 {
1591 	em_intr_body(xsc, TRUE);
1592 }
1593 
1594 static void
1595 em_intr_body(struct adapter *adapter, boolean_t chk_asserted)
1596 {
1597 	struct ifnet *ifp = &adapter->arpcom.ac_if;
1598 	uint32_t reg_icr;
1599 
1600 	logif(intr_beg);
1601 	ASSERT_SERIALIZED(ifp->if_serializer);
1602 
1603 	reg_icr = E1000_READ_REG(&adapter->hw, E1000_ICR);
1604 
1605 	if (chk_asserted &&
1606 	    ((adapter->hw.mac.type >= e1000_82571 &&
1607 	      (reg_icr & E1000_ICR_INT_ASSERTED) == 0) ||
1608 	     reg_icr == 0)) {
1609 		logif(intr_end);
1610 		return;
1611 	}
1612 
1613 	/*
1614 	 * XXX: some laptops trigger several spurious interrupts
1615 	 * on em(4) when in the resume cycle. The ICR register
1616 	 * reports all-ones value in this case. Processing such
1617 	 * interrupts would lead to a freeze. I don't know why.
1618 	 */
1619 	if (reg_icr == 0xffffffff) {
1620 		logif(intr_end);
1621 		return;
1622 	}
1623 
1624 	if (ifp->if_flags & IFF_RUNNING) {
1625 		if (reg_icr &
1626 		    (E1000_ICR_RXT0 | E1000_ICR_RXDMT0 | E1000_ICR_RXO))
1627 			em_rxeof(adapter, -1);
1628 		if (reg_icr & E1000_ICR_TXDW)
1629 			em_tx_intr(adapter);
1630 	}
1631 
1632 	/* Link status change */
1633 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1634 		callout_stop(&adapter->timer);
1635 		adapter->hw.mac.get_link_status = 1;
1636 		em_update_link_status(adapter);
1637 
1638 		/* Deal with TX cruft when link lost */
1639 		em_tx_purge(adapter);
1640 
1641 		callout_reset(&adapter->timer, hz, em_timer, adapter);
1642 	}
1643 
1644 	if (reg_icr & E1000_ICR_RXO)
1645 		adapter->rx_overruns++;
1646 
1647 	logif(intr_end);
1648 }
1649 
1650 static void
1651 em_intr_mask(void *xsc)
1652 {
1653 	struct adapter *adapter = xsc;
1654 
1655 	E1000_WRITE_REG(&adapter->hw, E1000_IMC, 0xffffffff);
1656 	/*
1657 	 * NOTE:
1658 	 * ICR.INT_ASSERTED bit will never be set if IMS is 0,
1659 	 * so don't check it.
1660 	 */
1661 	em_intr_body(adapter, FALSE);
1662 	E1000_WRITE_REG(&adapter->hw, E1000_IMS, IMS_ENABLE_MASK);
1663 }
1664 
1665 static void
1666 em_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1667 {
1668 	struct adapter *adapter = ifp->if_softc;
1669 
1670 	ASSERT_SERIALIZED(ifp->if_serializer);
1671 
1672 	em_update_link_status(adapter);
1673 
1674 	ifmr->ifm_status = IFM_AVALID;
1675 	ifmr->ifm_active = IFM_ETHER;
1676 
1677 	if (!adapter->link_active) {
1678 		if (adapter->hw.mac.autoneg)
1679 			ifmr->ifm_active |= IFM_NONE;
1680 		else
1681 			ifmr->ifm_active = adapter->media.ifm_media;
1682 		return;
1683 	}
1684 
1685 	ifmr->ifm_status |= IFM_ACTIVE;
1686 	if (adapter->ifm_flowctrl & IFM_ETH_FORCEPAUSE)
1687 		ifmr->ifm_active |= adapter->ifm_flowctrl;
1688 
1689 	if (adapter->hw.phy.media_type == e1000_media_type_fiber ||
1690 	    adapter->hw.phy.media_type == e1000_media_type_internal_serdes) {
1691 		u_char fiber_type = IFM_1000_SX;
1692 
1693 		if (adapter->hw.mac.type == e1000_82545)
1694 			fiber_type = IFM_1000_LX;
1695 		ifmr->ifm_active |= fiber_type | IFM_FDX;
1696 	} else {
1697 		switch (adapter->link_speed) {
1698 		case 10:
1699 			ifmr->ifm_active |= IFM_10_T;
1700 			break;
1701 		case 100:
1702 			ifmr->ifm_active |= IFM_100_TX;
1703 			break;
1704 
1705 		case 1000:
1706 			ifmr->ifm_active |= IFM_1000_T;
1707 			break;
1708 		}
1709 		if (adapter->link_duplex == FULL_DUPLEX)
1710 			ifmr->ifm_active |= IFM_FDX;
1711 		else
1712 			ifmr->ifm_active |= IFM_HDX;
1713 	}
1714 	if (ifmr->ifm_active & IFM_FDX) {
1715 		ifmr->ifm_active |=
1716 		    e1000_fc2ifmedia(adapter->hw.fc.current_mode);
1717 	}
1718 }
1719 
1720 static int
1721 em_media_change(struct ifnet *ifp)
1722 {
1723 	struct adapter *adapter = ifp->if_softc;
1724 	struct ifmedia *ifm = &adapter->media;
1725 
1726 	ASSERT_SERIALIZED(ifp->if_serializer);
1727 
1728 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1729 		return (EINVAL);
1730 
1731 	if (adapter->hw.mac.type == e1000_pchlan &&
1732 	    (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)) {
1733 		if (bootverbose)
1734 			if_printf(ifp, "TX PAUSE is not supported on PCH\n");
1735 		return EINVAL;
1736 	}
1737 
1738 	switch (IFM_SUBTYPE(ifm->ifm_media)) {
1739 	case IFM_AUTO:
1740 		adapter->hw.mac.autoneg = DO_AUTO_NEG;
1741 		adapter->hw.phy.autoneg_advertised = AUTONEG_ADV_DEFAULT;
1742 		break;
1743 
1744 	case IFM_1000_LX:
1745 	case IFM_1000_SX:
1746 	case IFM_1000_T:
1747 		adapter->hw.mac.autoneg = DO_AUTO_NEG;
1748 		adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1749 		break;
1750 
1751 	case IFM_100_TX:
1752 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_FDX) {
1753 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1754 		} else {
1755 			if (IFM_OPTIONS(ifm->ifm_media) &
1756 			    (IFM_ETH_RXPAUSE | IFM_ETH_TXPAUSE)) {
1757 				if (bootverbose) {
1758 					if_printf(ifp, "Flow control is not "
1759 					    "allowed for half-duplex\n");
1760 				}
1761 				return EINVAL;
1762 			}
1763 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1764 		}
1765 		adapter->hw.mac.autoneg = FALSE;
1766 		adapter->hw.phy.autoneg_advertised = 0;
1767 		break;
1768 
1769 	case IFM_10_T:
1770 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_FDX) {
1771 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1772 		} else {
1773 			if (IFM_OPTIONS(ifm->ifm_media) &
1774 			    (IFM_ETH_RXPAUSE | IFM_ETH_TXPAUSE)) {
1775 				if (bootverbose) {
1776 					if_printf(ifp, "Flow control is not "
1777 					    "allowed for half-duplex\n");
1778 				}
1779 				return EINVAL;
1780 			}
1781 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1782 		}
1783 		adapter->hw.mac.autoneg = FALSE;
1784 		adapter->hw.phy.autoneg_advertised = 0;
1785 		break;
1786 
1787 	default:
1788 		if (bootverbose) {
1789 			if_printf(ifp, "Unsupported media type %d\n",
1790 			    IFM_SUBTYPE(ifm->ifm_media));
1791 		}
1792 		return EINVAL;
1793 	}
1794 	adapter->ifm_flowctrl = ifm->ifm_media & IFM_ETH_FCMASK;
1795 
1796 	if (ifp->if_flags & IFF_RUNNING)
1797 		em_init(adapter);
1798 
1799 	return (0);
1800 }
1801 
1802 static int
1803 em_encap(struct adapter *adapter, struct mbuf **m_headp,
1804     int *segs_used, int *idx)
1805 {
1806 	bus_dma_segment_t segs[EM_MAX_SCATTER];
1807 	bus_dmamap_t map;
1808 	struct em_buffer *tx_buffer, *tx_buffer_mapped;
1809 	struct e1000_tx_desc *ctxd = NULL;
1810 	struct mbuf *m_head = *m_headp;
1811 	uint32_t txd_upper, txd_lower, txd_used, cmd = 0;
1812 	int maxsegs, nsegs, i, j, first, last = 0, error;
1813 
1814 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1815 		error = em_tso_pullup(adapter, m_headp);
1816 		if (error)
1817 			return error;
1818 		m_head = *m_headp;
1819 	}
1820 
1821 	txd_upper = txd_lower = 0;
1822 	txd_used = 0;
1823 
1824 	/*
1825 	 * Capture the first descriptor index, this descriptor
1826 	 * will have the index of the EOP which is the only one
1827 	 * that now gets a DONE bit writeback.
1828 	 */
1829 	first = adapter->next_avail_tx_desc;
1830 	tx_buffer = &adapter->tx_buffer_area[first];
1831 	tx_buffer_mapped = tx_buffer;
1832 	map = tx_buffer->map;
1833 
1834 	maxsegs = adapter->num_tx_desc_avail - EM_TX_RESERVED;
1835 	KASSERT(maxsegs >= adapter->spare_tx_desc,
1836 		("not enough spare TX desc"));
1837 	if (adapter->pcix_82544) {
1838 		/* Half it; see the comment in em_attach() */
1839 		maxsegs >>= 1;
1840 	}
1841 	if (maxsegs > EM_MAX_SCATTER)
1842 		maxsegs = EM_MAX_SCATTER;
1843 
1844 	error = bus_dmamap_load_mbuf_defrag(adapter->txtag, map, m_headp,
1845 			segs, maxsegs, &nsegs, BUS_DMA_NOWAIT);
1846 	if (error) {
1847 		if (error == ENOBUFS)
1848 			adapter->mbuf_alloc_failed++;
1849 		else
1850 			adapter->no_tx_dma_setup++;
1851 
1852 		m_freem(*m_headp);
1853 		*m_headp = NULL;
1854 		return error;
1855 	}
1856         bus_dmamap_sync(adapter->txtag, map, BUS_DMASYNC_PREWRITE);
1857 
1858 	m_head = *m_headp;
1859 	adapter->tx_nsegs += nsegs;
1860 	*segs_used += nsegs;
1861 
1862 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1863 		/* TSO will consume one TX desc */
1864 		i = em_tso_setup(adapter, m_head, &txd_upper, &txd_lower);
1865 		adapter->tx_nsegs += i;
1866 		*segs_used += i;
1867 	} else if (m_head->m_pkthdr.csum_flags & EM_CSUM_FEATURES) {
1868 		/* TX csum offloading will consume one TX desc */
1869 		i = em_txcsum(adapter, m_head, &txd_upper, &txd_lower);
1870 		adapter->tx_nsegs += i;
1871 		*segs_used += i;
1872 	}
1873 
1874         /* Handle VLAN tag */
1875 	if (m_head->m_flags & M_VLANTAG) {
1876 		/* Set the vlan id. */
1877 		txd_upper |= (htole16(m_head->m_pkthdr.ether_vlantag) << 16);
1878 		/* Tell hardware to add tag */
1879 		txd_lower |= htole32(E1000_TXD_CMD_VLE);
1880 	}
1881 
1882 	i = adapter->next_avail_tx_desc;
1883 
1884 	/* Set up our transmit descriptors */
1885 	for (j = 0; j < nsegs; j++) {
1886 		/* If adapter is 82544 and on PCIX bus */
1887 		if(adapter->pcix_82544) {
1888 			DESC_ARRAY desc_array;
1889 			uint32_t array_elements, counter;
1890 
1891 			/*
1892 			 * Check the Address and Length combination and
1893 			 * split the data accordingly
1894 			 */
1895 			array_elements = em_82544_fill_desc(segs[j].ds_addr,
1896 						segs[j].ds_len, &desc_array);
1897 			for (counter = 0; counter < array_elements; counter++) {
1898 				KKASSERT(txd_used < adapter->num_tx_desc_avail);
1899 
1900 				tx_buffer = &adapter->tx_buffer_area[i];
1901 				ctxd = &adapter->tx_desc_base[i];
1902 
1903 				ctxd->buffer_addr = htole64(
1904 				    desc_array.descriptor[counter].address);
1905 				ctxd->lower.data = htole32(
1906 				    E1000_TXD_CMD_IFCS | txd_lower |
1907 				    desc_array.descriptor[counter].length);
1908 				ctxd->upper.data = htole32(txd_upper);
1909 
1910 				last = i;
1911 				if (++i == adapter->num_tx_desc)
1912 					i = 0;
1913 
1914 				txd_used++;
1915                         }
1916 		} else {
1917 			tx_buffer = &adapter->tx_buffer_area[i];
1918 			ctxd = &adapter->tx_desc_base[i];
1919 
1920 			ctxd->buffer_addr = htole64(segs[j].ds_addr);
1921 			ctxd->lower.data = htole32(E1000_TXD_CMD_IFCS |
1922 						   txd_lower | segs[j].ds_len);
1923 			ctxd->upper.data = htole32(txd_upper);
1924 
1925 			last = i;
1926 			if (++i == adapter->num_tx_desc)
1927 				i = 0;
1928 		}
1929 	}
1930 
1931 	adapter->next_avail_tx_desc = i;
1932 	if (adapter->pcix_82544) {
1933 		KKASSERT(adapter->num_tx_desc_avail > txd_used);
1934 		adapter->num_tx_desc_avail -= txd_used;
1935 	} else {
1936 		KKASSERT(adapter->num_tx_desc_avail > nsegs);
1937 		adapter->num_tx_desc_avail -= nsegs;
1938 	}
1939 	adapter->tx_nmbuf++;
1940 
1941 	tx_buffer->m_head = m_head;
1942 	tx_buffer_mapped->map = tx_buffer->map;
1943 	tx_buffer->map = map;
1944 
1945 	if (adapter->tx_nsegs >= adapter->tx_int_nsegs) {
1946 		adapter->tx_nsegs = 0;
1947 
1948 		/*
1949 		 * Report Status (RS) is turned on
1950 		 * every tx_int_nsegs descriptors.
1951 		 */
1952 		cmd = E1000_TXD_CMD_RS;
1953 
1954 		/*
1955 		 * Keep track of the descriptor, which will
1956 		 * be written back by hardware.
1957 		 */
1958 		adapter->tx_dd[adapter->tx_dd_tail] = last;
1959 		EM_INC_TXDD_IDX(adapter->tx_dd_tail);
1960 		KKASSERT(adapter->tx_dd_tail != adapter->tx_dd_head);
1961 	}
1962 
1963 	/*
1964 	 * Last Descriptor of Packet needs End Of Packet (EOP)
1965 	 */
1966 	ctxd->lower.data |= htole32(E1000_TXD_CMD_EOP | cmd);
1967 
1968 	if (adapter->hw.mac.type == e1000_82547) {
1969 		/*
1970 		 * Advance the Transmit Descriptor Tail (TDT), this tells the
1971 		 * E1000 that this frame is available to transmit.
1972 		 */
1973 		if (adapter->link_duplex == HALF_DUPLEX) {
1974 			em_82547_move_tail_serialized(adapter);
1975 		} else {
1976 			E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), i);
1977 			em_82547_update_fifo_head(adapter,
1978 			    m_head->m_pkthdr.len);
1979 		}
1980 	} else {
1981 		/*
1982 		 * Defer TDT updating, until enough descriptors are setup
1983 		 */
1984 		*idx = i;
1985 	}
1986 	return (0);
1987 }
1988 
1989 /*
1990  * 82547 workaround to avoid controller hang in half-duplex environment.
1991  * The workaround is to avoid queuing a large packet that would span
1992  * the internal Tx FIFO ring boundary.  We need to reset the FIFO pointers
1993  * in this case.  We do that only when FIFO is quiescent.
1994  */
1995 static void
1996 em_82547_move_tail_serialized(struct adapter *adapter)
1997 {
1998 	struct e1000_tx_desc *tx_desc;
1999 	uint16_t hw_tdt, sw_tdt, length = 0;
2000 	bool eop = 0;
2001 
2002 	ASSERT_SERIALIZED(adapter->arpcom.ac_if.if_serializer);
2003 
2004 	hw_tdt = E1000_READ_REG(&adapter->hw, E1000_TDT(0));
2005 	sw_tdt = adapter->next_avail_tx_desc;
2006 
2007 	while (hw_tdt != sw_tdt) {
2008 		tx_desc = &adapter->tx_desc_base[hw_tdt];
2009 		length += tx_desc->lower.flags.length;
2010 		eop = tx_desc->lower.data & E1000_TXD_CMD_EOP;
2011 		if (++hw_tdt == adapter->num_tx_desc)
2012 			hw_tdt = 0;
2013 
2014 		if (eop) {
2015 			if (em_82547_fifo_workaround(adapter, length)) {
2016 				adapter->tx_fifo_wrk_cnt++;
2017 				callout_reset(&adapter->tx_fifo_timer, 1,
2018 					em_82547_move_tail, adapter);
2019 				break;
2020 			}
2021 			E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), hw_tdt);
2022 			em_82547_update_fifo_head(adapter, length);
2023 			length = 0;
2024 		}
2025 	}
2026 }
2027 
2028 static void
2029 em_82547_move_tail(void *xsc)
2030 {
2031 	struct adapter *adapter = xsc;
2032 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2033 
2034 	lwkt_serialize_enter(ifp->if_serializer);
2035 	em_82547_move_tail_serialized(adapter);
2036 	lwkt_serialize_exit(ifp->if_serializer);
2037 }
2038 
2039 static int
2040 em_82547_fifo_workaround(struct adapter *adapter, int len)
2041 {
2042 	int fifo_space, fifo_pkt_len;
2043 
2044 	fifo_pkt_len = roundup2(len + EM_FIFO_HDR, EM_FIFO_HDR);
2045 
2046 	if (adapter->link_duplex == HALF_DUPLEX) {
2047 		fifo_space = adapter->tx_fifo_size - adapter->tx_fifo_head;
2048 
2049 		if (fifo_pkt_len >= (EM_82547_PKT_THRESH + fifo_space)) {
2050 			if (em_82547_tx_fifo_reset(adapter))
2051 				return (0);
2052 			else
2053 				return (1);
2054 		}
2055 	}
2056 	return (0);
2057 }
2058 
2059 static void
2060 em_82547_update_fifo_head(struct adapter *adapter, int len)
2061 {
2062 	int fifo_pkt_len = roundup2(len + EM_FIFO_HDR, EM_FIFO_HDR);
2063 
2064 	/* tx_fifo_head is always 16 byte aligned */
2065 	adapter->tx_fifo_head += fifo_pkt_len;
2066 	if (adapter->tx_fifo_head >= adapter->tx_fifo_size)
2067 		adapter->tx_fifo_head -= adapter->tx_fifo_size;
2068 }
2069 
2070 static int
2071 em_82547_tx_fifo_reset(struct adapter *adapter)
2072 {
2073 	uint32_t tctl;
2074 
2075 	if ((E1000_READ_REG(&adapter->hw, E1000_TDT(0)) ==
2076 	     E1000_READ_REG(&adapter->hw, E1000_TDH(0))) &&
2077 	    (E1000_READ_REG(&adapter->hw, E1000_TDFT) ==
2078 	     E1000_READ_REG(&adapter->hw, E1000_TDFH)) &&
2079 	    (E1000_READ_REG(&adapter->hw, E1000_TDFTS) ==
2080 	     E1000_READ_REG(&adapter->hw, E1000_TDFHS)) &&
2081 	    (E1000_READ_REG(&adapter->hw, E1000_TDFPC) == 0)) {
2082 		/* Disable TX unit */
2083 		tctl = E1000_READ_REG(&adapter->hw, E1000_TCTL);
2084 		E1000_WRITE_REG(&adapter->hw, E1000_TCTL,
2085 		    tctl & ~E1000_TCTL_EN);
2086 
2087 		/* Reset FIFO pointers */
2088 		E1000_WRITE_REG(&adapter->hw, E1000_TDFT,
2089 		    adapter->tx_head_addr);
2090 		E1000_WRITE_REG(&adapter->hw, E1000_TDFH,
2091 		    adapter->tx_head_addr);
2092 		E1000_WRITE_REG(&adapter->hw, E1000_TDFTS,
2093 		    adapter->tx_head_addr);
2094 		E1000_WRITE_REG(&adapter->hw, E1000_TDFHS,
2095 		    adapter->tx_head_addr);
2096 
2097 		/* Re-enable TX unit */
2098 		E1000_WRITE_REG(&adapter->hw, E1000_TCTL, tctl);
2099 		E1000_WRITE_FLUSH(&adapter->hw);
2100 
2101 		adapter->tx_fifo_head = 0;
2102 		adapter->tx_fifo_reset_cnt++;
2103 
2104 		return (TRUE);
2105 	} else {
2106 		return (FALSE);
2107 	}
2108 }
2109 
2110 static void
2111 em_set_promisc(struct adapter *adapter)
2112 {
2113 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2114 	uint32_t reg_rctl;
2115 
2116 	reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2117 
2118 	if (ifp->if_flags & IFF_PROMISC) {
2119 		reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
2120 		/* Turn this on if you want to see bad packets */
2121 		if (em_debug_sbp)
2122 			reg_rctl |= E1000_RCTL_SBP;
2123 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2124 	} else if (ifp->if_flags & IFF_ALLMULTI) {
2125 		reg_rctl |= E1000_RCTL_MPE;
2126 		reg_rctl &= ~E1000_RCTL_UPE;
2127 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2128 	}
2129 }
2130 
2131 static void
2132 em_disable_promisc(struct adapter *adapter)
2133 {
2134 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2135 	uint32_t reg_rctl;
2136 	int mcnt = 0;
2137 
2138 	reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2139 	reg_rctl &= ~(E1000_RCTL_UPE | E1000_RCTL_SBP);
2140 
2141 	if (ifp->if_flags & IFF_ALLMULTI) {
2142 		mcnt = MAX_NUM_MULTICAST_ADDRESSES;
2143 	} else {
2144 		const struct ifmultiaddr *ifma;
2145 
2146 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2147 			if (ifma->ifma_addr->sa_family != AF_LINK)
2148 				continue;
2149 			if (mcnt == MAX_NUM_MULTICAST_ADDRESSES)
2150 				break;
2151 			mcnt++;
2152 		}
2153 	}
2154 	/* Don't disable if in MAX groups */
2155 	if (mcnt < MAX_NUM_MULTICAST_ADDRESSES)
2156 		reg_rctl &= ~E1000_RCTL_MPE;
2157 
2158 	E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2159 }
2160 
2161 static void
2162 em_set_multi(struct adapter *adapter)
2163 {
2164 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2165 	struct ifmultiaddr *ifma;
2166 	uint32_t reg_rctl = 0;
2167 	uint8_t *mta;
2168 	int mcnt = 0;
2169 
2170 	mta = adapter->mta;
2171 	bzero(mta, ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES);
2172 
2173 	if (adapter->hw.mac.type == e1000_82542 &&
2174 	    adapter->hw.revision_id == E1000_REVISION_2) {
2175 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2176 		if (adapter->hw.bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
2177 			e1000_pci_clear_mwi(&adapter->hw);
2178 		reg_rctl |= E1000_RCTL_RST;
2179 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2180 		msec_delay(5);
2181 	}
2182 
2183 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2184 		if (ifma->ifma_addr->sa_family != AF_LINK)
2185 			continue;
2186 
2187 		if (mcnt == MAX_NUM_MULTICAST_ADDRESSES)
2188 			break;
2189 
2190 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
2191 		    &mta[mcnt * ETHER_ADDR_LEN], ETHER_ADDR_LEN);
2192 		mcnt++;
2193 	}
2194 
2195 	if (mcnt >= MAX_NUM_MULTICAST_ADDRESSES) {
2196 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2197 		reg_rctl |= E1000_RCTL_MPE;
2198 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2199 	} else {
2200 		e1000_update_mc_addr_list(&adapter->hw, mta, mcnt);
2201 	}
2202 
2203 	if (adapter->hw.mac.type == e1000_82542 &&
2204 	    adapter->hw.revision_id == E1000_REVISION_2) {
2205 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2206 		reg_rctl &= ~E1000_RCTL_RST;
2207 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2208 		msec_delay(5);
2209 		if (adapter->hw.bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
2210 			e1000_pci_set_mwi(&adapter->hw);
2211 	}
2212 }
2213 
2214 /*
2215  * This routine checks for link status and updates statistics.
2216  */
2217 static void
2218 em_timer(void *xsc)
2219 {
2220 	struct adapter *adapter = xsc;
2221 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2222 
2223 	lwkt_serialize_enter(ifp->if_serializer);
2224 
2225 	em_update_link_status(adapter);
2226 	em_update_stats(adapter);
2227 
2228 	/* Reset LAA into RAR[0] on 82571 */
2229 	if (e1000_get_laa_state_82571(&adapter->hw) == TRUE)
2230 		e1000_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
2231 
2232 	if (em_display_debug_stats && (ifp->if_flags & IFF_RUNNING))
2233 		em_print_hw_stats(adapter);
2234 
2235 	em_smartspeed(adapter);
2236 
2237 	callout_reset(&adapter->timer, hz, em_timer, adapter);
2238 
2239 	lwkt_serialize_exit(ifp->if_serializer);
2240 }
2241 
2242 static void
2243 em_update_link_status(struct adapter *adapter)
2244 {
2245 	struct e1000_hw *hw = &adapter->hw;
2246 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2247 	device_t dev = adapter->dev;
2248 	uint32_t link_check = 0;
2249 
2250 	/* Get the cached link value or read phy for real */
2251 	switch (hw->phy.media_type) {
2252 	case e1000_media_type_copper:
2253 		if (hw->mac.get_link_status) {
2254 			if (hw->mac.type >= e1000_pch_spt)
2255 				msec_delay(50);
2256 			/* Do the work to read phy */
2257 			e1000_check_for_link(hw);
2258 			link_check = !hw->mac.get_link_status;
2259 			if (link_check) /* ESB2 fix */
2260 				e1000_cfg_on_link_up(hw);
2261 		} else {
2262 			link_check = TRUE;
2263 		}
2264 		break;
2265 
2266 	case e1000_media_type_fiber:
2267 		e1000_check_for_link(hw);
2268 		link_check =
2269 			E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU;
2270 		break;
2271 
2272 	case e1000_media_type_internal_serdes:
2273 		e1000_check_for_link(hw);
2274 		link_check = adapter->hw.mac.serdes_has_link;
2275 		break;
2276 
2277 	case e1000_media_type_unknown:
2278 	default:
2279 		break;
2280 	}
2281 
2282 	/* Now check for a transition */
2283 	if (link_check && adapter->link_active == 0) {
2284 		e1000_get_speed_and_duplex(hw, &adapter->link_speed,
2285 		    &adapter->link_duplex);
2286 
2287 		/*
2288 		 * Check if we should enable/disable SPEED_MODE bit on
2289 		 * 82571/82572
2290 		 */
2291 		if (adapter->link_speed != SPEED_1000 &&
2292 		    (hw->mac.type == e1000_82571 ||
2293 		     hw->mac.type == e1000_82572)) {
2294 			int tarc0;
2295 
2296 			tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
2297 			tarc0 &= ~TARC_SPEED_MODE_BIT;
2298 			E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
2299 		}
2300 		if (bootverbose) {
2301 			char flowctrl[IFM_ETH_FC_STRLEN];
2302 
2303 			e1000_fc2str(hw->fc.current_mode, flowctrl,
2304 			    sizeof(flowctrl));
2305 			device_printf(dev, "Link is up %d Mbps %s, "
2306 			    "Flow control: %s\n",
2307 			    adapter->link_speed,
2308 			    (adapter->link_duplex == FULL_DUPLEX) ?
2309 			    "Full Duplex" : "Half Duplex",
2310 			    flowctrl);
2311 		}
2312 		if (adapter->ifm_flowctrl & IFM_ETH_FORCEPAUSE)
2313 			e1000_force_flowctrl(hw, adapter->ifm_flowctrl);
2314 		adapter->link_active = 1;
2315 		adapter->smartspeed = 0;
2316 		ifp->if_baudrate = adapter->link_speed * 1000000;
2317 		ifp->if_link_state = LINK_STATE_UP;
2318 		if_link_state_change(ifp);
2319 	} else if (!link_check && adapter->link_active == 1) {
2320 		ifp->if_baudrate = adapter->link_speed = 0;
2321 		adapter->link_duplex = 0;
2322 		if (bootverbose)
2323 			device_printf(dev, "Link is Down\n");
2324 		adapter->link_active = 0;
2325 #if 0
2326 		/* Link down, disable watchdog */
2327 		if->if_timer = 0;
2328 #endif
2329 		ifp->if_link_state = LINK_STATE_DOWN;
2330 		if_link_state_change(ifp);
2331 	}
2332 }
2333 
2334 static void
2335 em_stop(struct adapter *adapter)
2336 {
2337 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2338 	int i;
2339 
2340 	ASSERT_SERIALIZED(ifp->if_serializer);
2341 
2342 	em_disable_intr(adapter);
2343 
2344 	callout_stop(&adapter->timer);
2345 	callout_stop(&adapter->tx_fifo_timer);
2346 
2347 	ifp->if_flags &= ~IFF_RUNNING;
2348 	ifq_clr_oactive(&ifp->if_snd);
2349 	ifp->if_timer = 0;
2350 	adapter->tx_running = 0;
2351 	callout_stop(&adapter->tx_gc_timer);
2352 
2353 	/* I219 needs some special flushing to avoid hangs */
2354 	if (adapter->hw.mac.type >= e1000_pch_spt)
2355 		em_flush_txrx_ring(adapter);
2356 
2357 	e1000_reset_hw(&adapter->hw);
2358 	if (adapter->hw.mac.type >= e1000_82544)
2359 		E1000_WRITE_REG(&adapter->hw, E1000_WUC, 0);
2360 
2361 	for (i = 0; i < adapter->num_tx_desc; i++) {
2362 		struct em_buffer *tx_buffer = &adapter->tx_buffer_area[i];
2363 
2364 		if (tx_buffer->m_head != NULL)
2365 			em_free_txbuffer(adapter, tx_buffer);
2366 	}
2367 
2368 	for (i = 0; i < adapter->num_rx_desc; i++) {
2369 		struct em_buffer *rx_buffer = &adapter->rx_buffer_area[i];
2370 
2371 		if (rx_buffer->m_head != NULL) {
2372 			bus_dmamap_unload(adapter->rxtag, rx_buffer->map);
2373 			m_freem(rx_buffer->m_head);
2374 			rx_buffer->m_head = NULL;
2375 		}
2376 	}
2377 
2378 	if (adapter->fmp != NULL)
2379 		m_freem(adapter->fmp);
2380 	adapter->fmp = NULL;
2381 	adapter->lmp = NULL;
2382 
2383 	adapter->csum_flags = 0;
2384 	adapter->csum_lhlen = 0;
2385 	adapter->csum_iphlen = 0;
2386 	adapter->csum_thlen = 0;
2387 	adapter->csum_mss = 0;
2388 	adapter->csum_pktlen = 0;
2389 
2390 	adapter->tx_dd_head = 0;
2391 	adapter->tx_dd_tail = 0;
2392 	adapter->tx_nsegs = 0;
2393 }
2394 
2395 static int
2396 em_get_hw_info(struct adapter *adapter)
2397 {
2398 	device_t dev = adapter->dev;
2399 
2400 	/* Save off the information about this board */
2401 	adapter->hw.vendor_id = pci_get_vendor(dev);
2402 	adapter->hw.device_id = pci_get_device(dev);
2403 	adapter->hw.revision_id = pci_get_revid(dev);
2404 	adapter->hw.subsystem_vendor_id = pci_get_subvendor(dev);
2405 	adapter->hw.subsystem_device_id = pci_get_subdevice(dev);
2406 
2407 	/* Do Shared Code Init and Setup */
2408 	if (e1000_set_mac_type(&adapter->hw))
2409 		return ENXIO;
2410 	return 0;
2411 }
2412 
2413 static int
2414 em_alloc_pci_res(struct adapter *adapter)
2415 {
2416 	device_t dev = adapter->dev;
2417 	u_int intr_flags;
2418 	int val, rid, msi_enable;
2419 
2420 	/* Enable bus mastering */
2421 	pci_enable_busmaster(dev);
2422 
2423 	adapter->memory_rid = EM_BAR_MEM;
2424 	adapter->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
2425 				&adapter->memory_rid, RF_ACTIVE);
2426 	if (adapter->memory == NULL) {
2427 		device_printf(dev, "Unable to allocate bus resource: memory\n");
2428 		return (ENXIO);
2429 	}
2430 	adapter->osdep.mem_bus_space_tag =
2431 	    rman_get_bustag(adapter->memory);
2432 	adapter->osdep.mem_bus_space_handle =
2433 	    rman_get_bushandle(adapter->memory);
2434 
2435 	/* XXX This is quite goofy, it is not actually used */
2436 	adapter->hw.hw_addr = (uint8_t *)&adapter->osdep.mem_bus_space_handle;
2437 
2438 	/* Only older adapters use IO mapping */
2439 	if (adapter->hw.mac.type > e1000_82543 &&
2440 	    adapter->hw.mac.type < e1000_82571) {
2441 		/* Figure our where our IO BAR is ? */
2442 		for (rid = PCIR_BAR(0); rid < PCIR_CARDBUSCIS;) {
2443 			val = pci_read_config(dev, rid, 4);
2444 			if (EM_BAR_TYPE(val) == EM_BAR_TYPE_IO) {
2445 				adapter->io_rid = rid;
2446 				break;
2447 			}
2448 			rid += 4;
2449 			/* check for 64bit BAR */
2450 			if (EM_BAR_MEM_TYPE(val) == EM_BAR_MEM_TYPE_64BIT)
2451 				rid += 4;
2452 		}
2453 		if (rid >= PCIR_CARDBUSCIS) {
2454 			device_printf(dev, "Unable to locate IO BAR\n");
2455 			return (ENXIO);
2456 		}
2457 		adapter->ioport = bus_alloc_resource_any(dev, SYS_RES_IOPORT,
2458 					&adapter->io_rid, RF_ACTIVE);
2459 		if (adapter->ioport == NULL) {
2460 			device_printf(dev, "Unable to allocate bus resource: "
2461 			    "ioport\n");
2462 			return (ENXIO);
2463 		}
2464 		adapter->hw.io_base = 0;
2465 		adapter->osdep.io_bus_space_tag =
2466 		    rman_get_bustag(adapter->ioport);
2467 		adapter->osdep.io_bus_space_handle =
2468 		    rman_get_bushandle(adapter->ioport);
2469 	}
2470 
2471 	/*
2472 	 * Don't enable MSI-X on 82574, see:
2473 	 * 82574 specification update errata #15
2474 	 *
2475 	 * Don't enable MSI on PCI/PCI-X chips, see:
2476 	 * 82540 specification update errata #6
2477 	 * 82545 specification update errata #4
2478 	 *
2479 	 * Don't enable MSI on 82571/82572, see:
2480 	 * 82571/82572 specification update errata #63
2481 	 */
2482 	msi_enable = em_msi_enable;
2483 	if (msi_enable &&
2484 	    ((adapter->flags & EM_FLAG_GEN2) == 0 ||
2485 	     adapter->hw.mac.type == e1000_82571 ||
2486 	     adapter->hw.mac.type == e1000_82572))
2487 		msi_enable = 0;
2488 again:
2489 	adapter->intr_type = pci_alloc_1intr(dev, msi_enable,
2490 	    &adapter->intr_rid, &intr_flags);
2491 
2492 	if (adapter->intr_type == PCI_INTR_TYPE_LEGACY) {
2493 		int unshared;
2494 
2495 		unshared = device_getenv_int(dev, "irq.unshared", 0);
2496 		if (!unshared) {
2497 			adapter->flags |= EM_FLAG_SHARED_INTR;
2498 			if (bootverbose)
2499 				device_printf(dev, "IRQ shared\n");
2500 		} else {
2501 			intr_flags &= ~RF_SHAREABLE;
2502 			if (bootverbose)
2503 				device_printf(dev, "IRQ unshared\n");
2504 		}
2505 	}
2506 
2507 	adapter->intr_res = bus_alloc_resource_any(dev, SYS_RES_IRQ,
2508 	    &adapter->intr_rid, intr_flags);
2509 	if (adapter->intr_res == NULL) {
2510 		device_printf(dev, "Unable to allocate bus resource: %s\n",
2511 		    adapter->intr_type == PCI_INTR_TYPE_MSI ?
2512 		    "MSI" : "legacy intr");
2513 		if (!msi_enable) {
2514 			/* Retry with MSI. */
2515 			msi_enable = 1;
2516 			adapter->flags &= ~EM_FLAG_SHARED_INTR;
2517 			goto again;
2518 		}
2519 		return (ENXIO);
2520 	}
2521 
2522 	adapter->hw.bus.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
2523 	adapter->hw.back = &adapter->osdep;
2524 	return (0);
2525 }
2526 
2527 static void
2528 em_free_pci_res(struct adapter *adapter)
2529 {
2530 	device_t dev = adapter->dev;
2531 
2532 	if (adapter->intr_res != NULL) {
2533 		bus_release_resource(dev, SYS_RES_IRQ,
2534 		    adapter->intr_rid, adapter->intr_res);
2535 	}
2536 
2537 	if (adapter->intr_type == PCI_INTR_TYPE_MSI)
2538 		pci_release_msi(dev);
2539 
2540 	if (adapter->memory != NULL) {
2541 		bus_release_resource(dev, SYS_RES_MEMORY,
2542 		    adapter->memory_rid, adapter->memory);
2543 	}
2544 
2545 	if (adapter->flash != NULL) {
2546 		bus_release_resource(dev, SYS_RES_MEMORY,
2547 		    adapter->flash_rid, adapter->flash);
2548 	}
2549 
2550 	if (adapter->ioport != NULL) {
2551 		bus_release_resource(dev, SYS_RES_IOPORT,
2552 		    adapter->io_rid, adapter->ioport);
2553 	}
2554 }
2555 
2556 static int
2557 em_reset(struct adapter *adapter)
2558 {
2559 	device_t dev = adapter->dev;
2560 	uint16_t rx_buffer_size;
2561 	uint32_t pba;
2562 
2563 	/* When hardware is reset, fifo_head is also reset */
2564 	adapter->tx_fifo_head = 0;
2565 
2566 	/* Set up smart power down as default off on newer adapters. */
2567 	if (!em_smart_pwr_down &&
2568 	    (adapter->hw.mac.type == e1000_82571 ||
2569 	     adapter->hw.mac.type == e1000_82572)) {
2570 		uint16_t phy_tmp = 0;
2571 
2572 		/* Speed up time to link by disabling smart power down. */
2573 		e1000_read_phy_reg(&adapter->hw,
2574 		    IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
2575 		phy_tmp &= ~IGP02E1000_PM_SPD;
2576 		e1000_write_phy_reg(&adapter->hw,
2577 		    IGP02E1000_PHY_POWER_MGMT, phy_tmp);
2578 	}
2579 
2580 	/*
2581 	 * Packet Buffer Allocation (PBA)
2582 	 * Writing PBA sets the receive portion of the buffer
2583 	 * the remainder is used for the transmit buffer.
2584 	 *
2585 	 * Devices before the 82547 had a Packet Buffer of 64K.
2586 	 *   Default allocation: PBA=48K for Rx, leaving 16K for Tx.
2587 	 * After the 82547 the buffer was reduced to 40K.
2588 	 *   Default allocation: PBA=30K for Rx, leaving 10K for Tx.
2589 	 *   Note: default does not leave enough room for Jumbo Frame >10k.
2590 	 */
2591 	switch (adapter->hw.mac.type) {
2592 	case e1000_82547:
2593 	case e1000_82547_rev_2: /* 82547: Total Packet Buffer is 40K */
2594 		if (adapter->hw.mac.max_frame_size > 8192)
2595 			pba = E1000_PBA_22K; /* 22K for Rx, 18K for Tx */
2596 		else
2597 			pba = E1000_PBA_30K; /* 30K for Rx, 10K for Tx */
2598 		adapter->tx_fifo_head = 0;
2599 		adapter->tx_head_addr = pba << EM_TX_HEAD_ADDR_SHIFT;
2600 		adapter->tx_fifo_size =
2601 		    (E1000_PBA_40K - pba) << EM_PBA_BYTES_SHIFT;
2602 		break;
2603 
2604 	/* Total Packet Buffer on these is 48K */
2605 	case e1000_82571:
2606 	case e1000_82572:
2607 	case e1000_80003es2lan:
2608 		pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
2609 		break;
2610 
2611 	case e1000_82573: /* 82573: Total Packet Buffer is 32K */
2612 		pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
2613 		break;
2614 
2615 	case e1000_82574:
2616 	case e1000_82583:
2617 		pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
2618 		break;
2619 
2620 	case e1000_ich8lan:
2621 		pba = E1000_PBA_8K;
2622 		break;
2623 
2624 	case e1000_ich9lan:
2625 	case e1000_ich10lan:
2626 #define E1000_PBA_10K	0x000A
2627 		pba = E1000_PBA_10K;
2628 		break;
2629 
2630 	case e1000_pchlan:
2631 	case e1000_pch2lan:
2632 	case e1000_pch_lpt:
2633 	case e1000_pch_spt:
2634 	case e1000_pch_cnp:
2635 		pba = E1000_PBA_26K;
2636 		break;
2637 
2638 	default:
2639 		/* Devices before 82547 had a Packet Buffer of 64K.   */
2640 		if (adapter->hw.mac.max_frame_size > 8192)
2641 			pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
2642 		else
2643 			pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
2644 	}
2645 	E1000_WRITE_REG(&adapter->hw, E1000_PBA, pba);
2646 
2647 	/*
2648 	 * These parameters control the automatic generation (Tx) and
2649 	 * response (Rx) to Ethernet PAUSE frames.
2650 	 * - High water mark should allow for at least two frames to be
2651 	 *   received after sending an XOFF.
2652 	 * - Low water mark works best when it is very near the high water mark.
2653 	 *   This allows the receiver to restart by sending XON when it has
2654 	 *   drained a bit. Here we use an arbitary value of 1500 which will
2655 	 *   restart after one full frame is pulled from the buffer. There
2656 	 *   could be several smaller frames in the buffer and if so they will
2657 	 *   not trigger the XON until their total number reduces the buffer
2658 	 *   by 1500.
2659 	 * - The pause time is fairly large at 1000 x 512ns = 512 usec.
2660 	 */
2661 	rx_buffer_size =
2662 		(E1000_READ_REG(&adapter->hw, E1000_PBA) & 0xffff) << 10;
2663 
2664 	adapter->hw.fc.high_water = rx_buffer_size -
2665 	    roundup2(adapter->hw.mac.max_frame_size, 1024);
2666 	adapter->hw.fc.low_water = adapter->hw.fc.high_water - 1500;
2667 
2668 	if (adapter->hw.mac.type == e1000_80003es2lan)
2669 		adapter->hw.fc.pause_time = 0xFFFF;
2670 	else
2671 		adapter->hw.fc.pause_time = EM_FC_PAUSE_TIME;
2672 
2673 	adapter->hw.fc.send_xon = TRUE;
2674 
2675 	adapter->hw.fc.requested_mode = e1000_ifmedia2fc(adapter->ifm_flowctrl);
2676 
2677 	/*
2678 	 * Device specific overrides/settings
2679 	 */
2680 	switch (adapter->hw.mac.type) {
2681 	case e1000_pchlan:
2682 		KASSERT(adapter->hw.fc.requested_mode == e1000_fc_rx_pause ||
2683 		    adapter->hw.fc.requested_mode == e1000_fc_none,
2684 		    ("unsupported flow control on PCH %d",
2685 		     adapter->hw.fc.requested_mode));
2686 		adapter->hw.fc.pause_time = 0xFFFF; /* override */
2687 		if (adapter->arpcom.ac_if.if_mtu > ETHERMTU) {
2688 			adapter->hw.fc.high_water = 0x3500;
2689 			adapter->hw.fc.low_water = 0x1500;
2690 		} else {
2691 			adapter->hw.fc.high_water = 0x5000;
2692 			adapter->hw.fc.low_water = 0x3000;
2693 		}
2694 		adapter->hw.fc.refresh_time = 0x1000;
2695 		break;
2696 
2697 	case e1000_pch2lan:
2698 	case e1000_pch_lpt:
2699 	case e1000_pch_spt:
2700 	case e1000_pch_cnp:
2701 		adapter->hw.fc.high_water = 0x5C20;
2702 		adapter->hw.fc.low_water = 0x5048;
2703 		adapter->hw.fc.pause_time = 0x0650;
2704 		adapter->hw.fc.refresh_time = 0x0400;
2705 		/* Jumbos need adjusted PBA */
2706 		if (adapter->arpcom.ac_if.if_mtu > ETHERMTU)
2707 			E1000_WRITE_REG(&adapter->hw, E1000_PBA, 12);
2708 		else
2709 			E1000_WRITE_REG(&adapter->hw, E1000_PBA, 26);
2710 		break;
2711 
2712 	case e1000_ich9lan:
2713 	case e1000_ich10lan:
2714 		if (adapter->arpcom.ac_if.if_mtu > ETHERMTU) {
2715 			adapter->hw.fc.high_water = 0x2800;
2716 			adapter->hw.fc.low_water =
2717 			    adapter->hw.fc.high_water - 8;
2718 			break;
2719 		}
2720 		/* FALL THROUGH */
2721 	default:
2722 		if (adapter->hw.mac.type == e1000_80003es2lan)
2723 			adapter->hw.fc.pause_time = 0xFFFF;
2724 		break;
2725 	}
2726 
2727 	/* I219 needs some special flushing to avoid hangs */
2728 	if (adapter->hw.mac.type >= e1000_pch_spt)
2729 		em_flush_txrx_ring(adapter);
2730 
2731 	/* Issue a global reset */
2732 	e1000_reset_hw(&adapter->hw);
2733 	if (adapter->hw.mac.type >= e1000_82544)
2734 		E1000_WRITE_REG(&adapter->hw, E1000_WUC, 0);
2735 	em_disable_aspm(adapter);
2736 
2737 	if (e1000_init_hw(&adapter->hw) < 0) {
2738 		device_printf(dev, "Hardware Initialization Failed\n");
2739 		return (EIO);
2740 	}
2741 
2742 	E1000_WRITE_REG(&adapter->hw, E1000_VET, ETHERTYPE_VLAN);
2743 	e1000_get_phy_info(&adapter->hw);
2744 	e1000_check_for_link(&adapter->hw);
2745 
2746 	return (0);
2747 }
2748 
2749 static void
2750 em_setup_ifp(struct adapter *adapter)
2751 {
2752 	struct ifnet *ifp = &adapter->arpcom.ac_if;
2753 
2754 	if_initname(ifp, device_get_name(adapter->dev),
2755 		    device_get_unit(adapter->dev));
2756 	ifp->if_softc = adapter;
2757 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2758 	ifp->if_init =  em_init;
2759 	ifp->if_ioctl = em_ioctl;
2760 	ifp->if_start = em_start;
2761 #ifdef IFPOLL_ENABLE
2762 	ifp->if_npoll = em_npoll;
2763 #endif
2764 	ifp->if_watchdog = em_watchdog;
2765 	ifp->if_nmbclusters = adapter->num_rx_desc;
2766 	ifq_set_maxlen(&ifp->if_snd, adapter->num_tx_desc - 1);
2767 	ifq_set_ready(&ifp->if_snd);
2768 
2769 	ether_ifattach(ifp, adapter->hw.mac.addr, NULL);
2770 
2771 	ifp->if_capabilities = IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU;
2772 	if (adapter->hw.mac.type >= e1000_82543)
2773 		ifp->if_capabilities |= IFCAP_HWCSUM;
2774 	if (adapter->flags & EM_FLAG_TSO)
2775 		ifp->if_capabilities |= IFCAP_TSO;
2776 	ifp->if_capenable = ifp->if_capabilities;
2777 
2778 	if (ifp->if_capenable & IFCAP_TXCSUM)
2779 		ifp->if_hwassist |= EM_CSUM_FEATURES;
2780 	if (ifp->if_capenable & IFCAP_TSO)
2781 		ifp->if_hwassist |= CSUM_TSO;
2782 
2783 	/*
2784 	 * Tell the upper layer(s) we support long frames.
2785 	 */
2786 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
2787 
2788 	/*
2789 	 * Specify the media types supported by this adapter and register
2790 	 * callbacks to update media and link information
2791 	 */
2792 	if (adapter->hw.phy.media_type == e1000_media_type_fiber ||
2793 	    adapter->hw.phy.media_type == e1000_media_type_internal_serdes) {
2794 		u_char fiber_type = IFM_1000_SX; /* default type */
2795 
2796 		if (adapter->hw.mac.type == e1000_82545)
2797 			fiber_type = IFM_1000_LX;
2798 		ifmedia_add(&adapter->media, IFM_ETHER | fiber_type | IFM_FDX,
2799 			    0, NULL);
2800 	} else {
2801 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_10_T, 0, NULL);
2802 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_10_T | IFM_FDX,
2803 			    0, NULL);
2804 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_100_TX,
2805 			    0, NULL);
2806 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_100_TX | IFM_FDX,
2807 			    0, NULL);
2808 		if (adapter->hw.phy.type != e1000_phy_ife) {
2809 			ifmedia_add(&adapter->media,
2810 				IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL);
2811 		}
2812 	}
2813 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2814 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO |
2815 	    adapter->ifm_flowctrl);
2816 }
2817 
2818 
2819 /*
2820  * Workaround for SmartSpeed on 82541 and 82547 controllers
2821  */
2822 static void
2823 em_smartspeed(struct adapter *adapter)
2824 {
2825 	uint16_t phy_tmp;
2826 
2827 	if (adapter->link_active || adapter->hw.phy.type != e1000_phy_igp ||
2828 	    adapter->hw.mac.autoneg == 0 ||
2829 	    (adapter->hw.phy.autoneg_advertised & ADVERTISE_1000_FULL) == 0)
2830 		return;
2831 
2832 	if (adapter->smartspeed == 0) {
2833 		/*
2834 		 * If Master/Slave config fault is asserted twice,
2835 		 * we assume back-to-back
2836 		 */
2837 		e1000_read_phy_reg(&adapter->hw, PHY_1000T_STATUS, &phy_tmp);
2838 		if (!(phy_tmp & SR_1000T_MS_CONFIG_FAULT))
2839 			return;
2840 		e1000_read_phy_reg(&adapter->hw, PHY_1000T_STATUS, &phy_tmp);
2841 		if (phy_tmp & SR_1000T_MS_CONFIG_FAULT) {
2842 			e1000_read_phy_reg(&adapter->hw,
2843 			    PHY_1000T_CTRL, &phy_tmp);
2844 			if (phy_tmp & CR_1000T_MS_ENABLE) {
2845 				phy_tmp &= ~CR_1000T_MS_ENABLE;
2846 				e1000_write_phy_reg(&adapter->hw,
2847 				    PHY_1000T_CTRL, phy_tmp);
2848 				adapter->smartspeed++;
2849 				if (adapter->hw.mac.autoneg &&
2850 				    !e1000_phy_setup_autoneg(&adapter->hw) &&
2851 				    !e1000_read_phy_reg(&adapter->hw,
2852 				     PHY_CONTROL, &phy_tmp)) {
2853 					phy_tmp |= MII_CR_AUTO_NEG_EN |
2854 						   MII_CR_RESTART_AUTO_NEG;
2855 					e1000_write_phy_reg(&adapter->hw,
2856 					    PHY_CONTROL, phy_tmp);
2857 				}
2858 			}
2859 		}
2860 		return;
2861 	} else if (adapter->smartspeed == EM_SMARTSPEED_DOWNSHIFT) {
2862 		/* If still no link, perhaps using 2/3 pair cable */
2863 		e1000_read_phy_reg(&adapter->hw, PHY_1000T_CTRL, &phy_tmp);
2864 		phy_tmp |= CR_1000T_MS_ENABLE;
2865 		e1000_write_phy_reg(&adapter->hw, PHY_1000T_CTRL, phy_tmp);
2866 		if (adapter->hw.mac.autoneg &&
2867 		    !e1000_phy_setup_autoneg(&adapter->hw) &&
2868 		    !e1000_read_phy_reg(&adapter->hw, PHY_CONTROL, &phy_tmp)) {
2869 			phy_tmp |= MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
2870 			e1000_write_phy_reg(&adapter->hw, PHY_CONTROL, phy_tmp);
2871 		}
2872 	}
2873 
2874 	/* Restart process after EM_SMARTSPEED_MAX iterations */
2875 	if (adapter->smartspeed++ == EM_SMARTSPEED_MAX)
2876 		adapter->smartspeed = 0;
2877 }
2878 
2879 static int
2880 em_dma_malloc(struct adapter *adapter, bus_size_t size,
2881 	      struct em_dma_alloc *dma)
2882 {
2883 	dma->dma_vaddr = bus_dmamem_coherent_any(adapter->parent_dtag,
2884 				EM_DBA_ALIGN, size, BUS_DMA_WAITOK,
2885 				&dma->dma_tag, &dma->dma_map,
2886 				&dma->dma_paddr);
2887 	if (dma->dma_vaddr == NULL)
2888 		return ENOMEM;
2889 	else
2890 		return 0;
2891 }
2892 
2893 static void
2894 em_dma_free(struct adapter *adapter, struct em_dma_alloc *dma)
2895 {
2896 	if (dma->dma_tag == NULL)
2897 		return;
2898 	bus_dmamap_unload(dma->dma_tag, dma->dma_map);
2899 	bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
2900 	bus_dma_tag_destroy(dma->dma_tag);
2901 }
2902 
2903 static int
2904 em_create_tx_ring(struct adapter *adapter)
2905 {
2906 	device_t dev = adapter->dev;
2907 	struct em_buffer *tx_buffer;
2908 	int error, i;
2909 
2910 	adapter->tx_buffer_area =
2911 		kmalloc(sizeof(struct em_buffer) * adapter->num_tx_desc,
2912 			M_DEVBUF, M_WAITOK | M_ZERO);
2913 
2914 	/*
2915 	 * Create DMA tags for tx buffers
2916 	 */
2917 	error = bus_dma_tag_create(adapter->parent_dtag, /* parent */
2918 			1, 0,			/* alignment, bounds */
2919 			BUS_SPACE_MAXADDR,	/* lowaddr */
2920 			BUS_SPACE_MAXADDR,	/* highaddr */
2921 			NULL, NULL,		/* filter, filterarg */
2922 			EM_TSO_SIZE,		/* maxsize */
2923 			EM_MAX_SCATTER,		/* nsegments */
2924 			PAGE_SIZE,		/* maxsegsize */
2925 			BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW |
2926 			BUS_DMA_ONEBPAGE,	/* flags */
2927 			&adapter->txtag);
2928 	if (error) {
2929 		device_printf(dev, "Unable to allocate TX DMA tag\n");
2930 		kfree(adapter->tx_buffer_area, M_DEVBUF);
2931 		adapter->tx_buffer_area = NULL;
2932 		return error;
2933 	}
2934 
2935 	/*
2936 	 * Create DMA maps for tx buffers
2937 	 */
2938 	for (i = 0; i < adapter->num_tx_desc; i++) {
2939 		tx_buffer = &adapter->tx_buffer_area[i];
2940 
2941 		error = bus_dmamap_create(adapter->txtag,
2942 					  BUS_DMA_WAITOK | BUS_DMA_ONEBPAGE,
2943 					  &tx_buffer->map);
2944 		if (error) {
2945 			device_printf(dev, "Unable to create TX DMA map\n");
2946 			em_destroy_tx_ring(adapter, i);
2947 			return error;
2948 		}
2949 	}
2950 	return (0);
2951 }
2952 
2953 static void
2954 em_init_tx_ring(struct adapter *adapter)
2955 {
2956 	/* Clear the old ring contents */
2957 	bzero(adapter->tx_desc_base,
2958 	    (sizeof(struct e1000_tx_desc)) * adapter->num_tx_desc);
2959 
2960 	/* Reset state */
2961 	adapter->next_avail_tx_desc = 0;
2962 	adapter->next_tx_to_clean = 0;
2963 	adapter->num_tx_desc_avail = adapter->num_tx_desc;
2964 	adapter->tx_nmbuf = 0;
2965 	adapter->tx_running = 0;
2966 }
2967 
2968 static void
2969 em_init_tx_unit(struct adapter *adapter)
2970 {
2971 	uint32_t tctl, tarc, tipg = 0;
2972 	uint64_t bus_addr;
2973 
2974 	/* Setup the Base and Length of the Tx Descriptor Ring */
2975 	bus_addr = adapter->txdma.dma_paddr;
2976 	E1000_WRITE_REG(&adapter->hw, E1000_TDLEN(0),
2977 	    adapter->num_tx_desc * sizeof(struct e1000_tx_desc));
2978 	E1000_WRITE_REG(&adapter->hw, E1000_TDBAH(0),
2979 	    (uint32_t)(bus_addr >> 32));
2980 	E1000_WRITE_REG(&adapter->hw, E1000_TDBAL(0),
2981 	    (uint32_t)bus_addr);
2982 	/* Setup the HW Tx Head and Tail descriptor pointers */
2983 	E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), 0);
2984 	E1000_WRITE_REG(&adapter->hw, E1000_TDH(0), 0);
2985 	if (adapter->flags & EM_FLAG_GEN2) {
2986 		uint32_t txdctl = 0;
2987 
2988 		txdctl |= 0x1f;		/* PTHRESH */
2989 		txdctl |= 1 << 8;	/* HTHRESH */
2990 		txdctl |= 1 << 16;	/* WTHRESH */
2991 		txdctl |= 1 << 22;	/* Reserved bit 22 must always be 1 */
2992 		txdctl |= E1000_TXDCTL_GRAN;
2993 		txdctl |= 1 << 25;	/* LWTHRESH */
2994 
2995 		E1000_WRITE_REG(&adapter->hw, E1000_TXDCTL(0), txdctl);
2996 	}
2997 
2998 	/* Set the default values for the Tx Inter Packet Gap timer */
2999 	switch (adapter->hw.mac.type) {
3000 	case e1000_82542:
3001 		tipg = DEFAULT_82542_TIPG_IPGT;
3002 		tipg |= DEFAULT_82542_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
3003 		tipg |= DEFAULT_82542_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
3004 		break;
3005 
3006 	case e1000_80003es2lan:
3007 		tipg = DEFAULT_82543_TIPG_IPGR1;
3008 		tipg |= DEFAULT_80003ES2LAN_TIPG_IPGR2 <<
3009 		    E1000_TIPG_IPGR2_SHIFT;
3010 		break;
3011 
3012 	default:
3013 		if (adapter->hw.phy.media_type == e1000_media_type_fiber ||
3014 		    adapter->hw.phy.media_type ==
3015 		    e1000_media_type_internal_serdes)
3016 			tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
3017 		else
3018 			tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
3019 		tipg |= DEFAULT_82543_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
3020 		tipg |= DEFAULT_82543_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
3021 		break;
3022 	}
3023 
3024 	E1000_WRITE_REG(&adapter->hw, E1000_TIPG, tipg);
3025 
3026 	/* NOTE: 0 is not allowed for TIDV */
3027 	E1000_WRITE_REG(&adapter->hw, E1000_TIDV, 1);
3028 	if(adapter->hw.mac.type >= e1000_82540)
3029 		E1000_WRITE_REG(&adapter->hw, E1000_TADV, 0);
3030 
3031 	if (adapter->hw.mac.type == e1000_82571 ||
3032 	    adapter->hw.mac.type == e1000_82572) {
3033 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
3034 		tarc |= TARC_SPEED_MODE_BIT;
3035 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), tarc);
3036 	} else if (adapter->hw.mac.type == e1000_80003es2lan) {
3037 		/* errata: program both queues to unweighted RR */
3038 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
3039 		tarc |= 1;
3040 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), tarc);
3041 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(1));
3042 		tarc |= 1;
3043 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(1), tarc);
3044 	} else if (adapter->hw.mac.type == e1000_82574) {
3045 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
3046 		tarc |= TARC_ERRATA_BIT;
3047 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), tarc);
3048 	}
3049 
3050 	/* Program the Transmit Control Register */
3051 	tctl = E1000_READ_REG(&adapter->hw, E1000_TCTL);
3052 	tctl &= ~E1000_TCTL_CT;
3053 	tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC | E1000_TCTL_EN |
3054 		(E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
3055 
3056 	if (adapter->hw.mac.type >= e1000_82571)
3057 		tctl |= E1000_TCTL_MULR;
3058 
3059 	/* This write will effectively turn on the transmit unit. */
3060 	E1000_WRITE_REG(&adapter->hw, E1000_TCTL, tctl);
3061 
3062 	if (adapter->hw.mac.type == e1000_82571 ||
3063 	    adapter->hw.mac.type == e1000_82572 ||
3064 	    adapter->hw.mac.type == e1000_80003es2lan) {
3065 		/* Bit 28 of TARC1 must be cleared when MULR is enabled */
3066 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(1));
3067 		tarc &= ~(1 << 28);
3068 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(1), tarc);
3069 	} else if (adapter->hw.mac.type >= e1000_pch_spt) {
3070 		uint32_t reg;
3071 
3072 		reg = E1000_READ_REG(&adapter->hw, E1000_IOSFPC);
3073 		reg |= E1000_RCTL_RDMTS_HEX;
3074 		E1000_WRITE_REG(&adapter->hw, E1000_IOSFPC, reg);
3075 		reg = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
3076 		reg |= E1000_TARC0_CB_MULTIQ_3_REQ;
3077 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), reg);
3078 	}
3079 }
3080 
3081 static void
3082 em_destroy_tx_ring(struct adapter *adapter, int ndesc)
3083 {
3084 	struct em_buffer *tx_buffer;
3085 	int i;
3086 
3087 	if (adapter->tx_buffer_area == NULL)
3088 		return;
3089 
3090 	for (i = 0; i < ndesc; i++) {
3091 		tx_buffer = &adapter->tx_buffer_area[i];
3092 
3093 		KKASSERT(tx_buffer->m_head == NULL);
3094 		bus_dmamap_destroy(adapter->txtag, tx_buffer->map);
3095 	}
3096 	bus_dma_tag_destroy(adapter->txtag);
3097 
3098 	kfree(adapter->tx_buffer_area, M_DEVBUF);
3099 	adapter->tx_buffer_area = NULL;
3100 }
3101 
3102 /*
3103  * The offload context needs to be set when we transfer the first
3104  * packet of a particular protocol (TCP/UDP).  This routine has been
3105  * enhanced to deal with inserted VLAN headers.
3106  *
3107  * If the new packet's ether header length, ip header length and
3108  * csum offloading type are same as the previous packet, we should
3109  * avoid allocating a new csum context descriptor; mainly to take
3110  * advantage of the pipeline effect of the TX data read request.
3111  *
3112  * This function returns number of TX descrptors allocated for
3113  * csum context.
3114  */
3115 static int
3116 em_txcsum(struct adapter *adapter, struct mbuf *mp,
3117 	  uint32_t *txd_upper, uint32_t *txd_lower)
3118 {
3119 	struct e1000_context_desc *TXD;
3120 	int curr_txd, ehdrlen, csum_flags;
3121 	uint32_t cmd, hdr_len, ip_hlen;
3122 
3123 	csum_flags = mp->m_pkthdr.csum_flags & EM_CSUM_FEATURES;
3124 	ip_hlen = mp->m_pkthdr.csum_iphlen;
3125 	ehdrlen = mp->m_pkthdr.csum_lhlen;
3126 
3127 	if (adapter->csum_lhlen == ehdrlen &&
3128 	    adapter->csum_iphlen == ip_hlen &&
3129 	    adapter->csum_flags == csum_flags) {
3130 		/*
3131 		 * Same csum offload context as the previous packets;
3132 		 * just return.
3133 		 */
3134 		*txd_upper = adapter->csum_txd_upper;
3135 		*txd_lower = adapter->csum_txd_lower;
3136 		return 0;
3137 	}
3138 
3139 	/*
3140 	 * Setup a new csum offload context.
3141 	 */
3142 
3143 	curr_txd = adapter->next_avail_tx_desc;
3144 	TXD = (struct e1000_context_desc *)&adapter->tx_desc_base[curr_txd];
3145 
3146 	cmd = 0;
3147 
3148 	/* Setup of IP header checksum. */
3149 	if (csum_flags & CSUM_IP) {
3150 		/*
3151 		 * Start offset for header checksum calculation.
3152 		 * End offset for header checksum calculation.
3153 		 * Offset of place to put the checksum.
3154 		 */
3155 		TXD->lower_setup.ip_fields.ipcss = ehdrlen;
3156 		TXD->lower_setup.ip_fields.ipcse =
3157 		    htole16(ehdrlen + ip_hlen - 1);
3158 		TXD->lower_setup.ip_fields.ipcso =
3159 		    ehdrlen + offsetof(struct ip, ip_sum);
3160 		cmd |= E1000_TXD_CMD_IP;
3161 		*txd_upper |= E1000_TXD_POPTS_IXSM << 8;
3162 	}
3163 	hdr_len = ehdrlen + ip_hlen;
3164 
3165 	if (csum_flags & CSUM_TCP) {
3166 		/*
3167 		 * Start offset for payload checksum calculation.
3168 		 * End offset for payload checksum calculation.
3169 		 * Offset of place to put the checksum.
3170 		 */
3171 		TXD->upper_setup.tcp_fields.tucss = hdr_len;
3172 		TXD->upper_setup.tcp_fields.tucse = htole16(0);
3173 		TXD->upper_setup.tcp_fields.tucso =
3174 		    hdr_len + offsetof(struct tcphdr, th_sum);
3175 		cmd |= E1000_TXD_CMD_TCP;
3176 		*txd_upper |= E1000_TXD_POPTS_TXSM << 8;
3177 	} else if (csum_flags & CSUM_UDP) {
3178 		/*
3179 		 * Start offset for header checksum calculation.
3180 		 * End offset for header checksum calculation.
3181 		 * Offset of place to put the checksum.
3182 		 */
3183 		TXD->upper_setup.tcp_fields.tucss = hdr_len;
3184 		TXD->upper_setup.tcp_fields.tucse = htole16(0);
3185 		TXD->upper_setup.tcp_fields.tucso =
3186 		    hdr_len + offsetof(struct udphdr, uh_sum);
3187 		*txd_upper |= E1000_TXD_POPTS_TXSM << 8;
3188 	}
3189 
3190 	*txd_lower = E1000_TXD_CMD_DEXT |	/* Extended descr type */
3191 		     E1000_TXD_DTYP_D;		/* Data descr */
3192 
3193 	/* Save the information for this csum offloading context */
3194 	adapter->csum_lhlen = ehdrlen;
3195 	adapter->csum_iphlen = ip_hlen;
3196 	adapter->csum_flags = csum_flags;
3197 	adapter->csum_txd_upper = *txd_upper;
3198 	adapter->csum_txd_lower = *txd_lower;
3199 
3200 	TXD->tcp_seg_setup.data = htole32(0);
3201 	TXD->cmd_and_length =
3202 	    htole32(E1000_TXD_CMD_IFCS | E1000_TXD_CMD_DEXT | cmd);
3203 
3204 	if (++curr_txd == adapter->num_tx_desc)
3205 		curr_txd = 0;
3206 
3207 	KKASSERT(adapter->num_tx_desc_avail > 0);
3208 	adapter->num_tx_desc_avail--;
3209 
3210 	adapter->next_avail_tx_desc = curr_txd;
3211 	return 1;
3212 }
3213 
3214 static void
3215 em_txeof(struct adapter *adapter)
3216 {
3217 	struct ifnet *ifp = &adapter->arpcom.ac_if;
3218 	struct em_buffer *tx_buffer;
3219 	int first, num_avail;
3220 
3221 	if (adapter->tx_dd_head == adapter->tx_dd_tail)
3222 		return;
3223 
3224 	if (adapter->num_tx_desc_avail == adapter->num_tx_desc)
3225 		return;
3226 
3227 	num_avail = adapter->num_tx_desc_avail;
3228 	first = adapter->next_tx_to_clean;
3229 
3230 	while (adapter->tx_dd_head != adapter->tx_dd_tail) {
3231 		struct e1000_tx_desc *tx_desc;
3232 		int dd_idx = adapter->tx_dd[adapter->tx_dd_head];
3233 
3234 		tx_desc = &adapter->tx_desc_base[dd_idx];
3235 		if (tx_desc->upper.fields.status & E1000_TXD_STAT_DD) {
3236 			EM_INC_TXDD_IDX(adapter->tx_dd_head);
3237 
3238 			if (++dd_idx == adapter->num_tx_desc)
3239 				dd_idx = 0;
3240 
3241 			while (first != dd_idx) {
3242 				logif(pkt_txclean);
3243 
3244 				KKASSERT(num_avail < adapter->num_tx_desc);
3245 				num_avail++;
3246 
3247 				tx_buffer = &adapter->tx_buffer_area[first];
3248 				if (tx_buffer->m_head != NULL)
3249 					em_free_txbuffer(adapter, tx_buffer);
3250 
3251 				if (++first == adapter->num_tx_desc)
3252 					first = 0;
3253 			}
3254 		} else {
3255 			break;
3256 		}
3257 	}
3258 	adapter->next_tx_to_clean = first;
3259 	adapter->num_tx_desc_avail = num_avail;
3260 
3261 	if (adapter->tx_dd_head == adapter->tx_dd_tail) {
3262 		adapter->tx_dd_head = 0;
3263 		adapter->tx_dd_tail = 0;
3264 	}
3265 
3266 	if (!EM_IS_OACTIVE(adapter)) {
3267 		ifq_clr_oactive(&ifp->if_snd);
3268 
3269 		/* All clean, turn off the timer */
3270 		if (adapter->num_tx_desc_avail == adapter->num_tx_desc)
3271 			ifp->if_timer = 0;
3272 	}
3273 	adapter->tx_running = EM_TX_RUNNING;
3274 }
3275 
3276 static void
3277 em_tx_collect(struct adapter *adapter, boolean_t gc)
3278 {
3279 	struct ifnet *ifp = &adapter->arpcom.ac_if;
3280 	struct em_buffer *tx_buffer;
3281 	int tdh, first, num_avail, dd_idx = -1;
3282 
3283 	if (adapter->num_tx_desc_avail == adapter->num_tx_desc)
3284 		return;
3285 
3286 	tdh = E1000_READ_REG(&adapter->hw, E1000_TDH(0));
3287 	if (tdh == adapter->next_tx_to_clean) {
3288 		if (gc && adapter->tx_nmbuf > 0)
3289 			adapter->tx_running = EM_TX_RUNNING;
3290 		return;
3291 	}
3292 	if (gc)
3293 		adapter->tx_gc++;
3294 
3295 	if (adapter->tx_dd_head != adapter->tx_dd_tail)
3296 		dd_idx = adapter->tx_dd[adapter->tx_dd_head];
3297 
3298 	num_avail = adapter->num_tx_desc_avail;
3299 	first = adapter->next_tx_to_clean;
3300 
3301 	while (first != tdh) {
3302 		logif(pkt_txclean);
3303 
3304 		KKASSERT(num_avail < adapter->num_tx_desc);
3305 		num_avail++;
3306 
3307 		tx_buffer = &adapter->tx_buffer_area[first];
3308 		if (tx_buffer->m_head != NULL)
3309 			em_free_txbuffer(adapter, tx_buffer);
3310 
3311 		if (first == dd_idx) {
3312 			EM_INC_TXDD_IDX(adapter->tx_dd_head);
3313 			if (adapter->tx_dd_head == adapter->tx_dd_tail) {
3314 				adapter->tx_dd_head = 0;
3315 				adapter->tx_dd_tail = 0;
3316 				dd_idx = -1;
3317 			} else {
3318 				dd_idx = adapter->tx_dd[adapter->tx_dd_head];
3319 			}
3320 		}
3321 
3322 		if (++first == adapter->num_tx_desc)
3323 			first = 0;
3324 	}
3325 	adapter->next_tx_to_clean = first;
3326 	adapter->num_tx_desc_avail = num_avail;
3327 
3328 	if (!EM_IS_OACTIVE(adapter)) {
3329 		ifq_clr_oactive(&ifp->if_snd);
3330 
3331 		/* All clean, turn off the timer */
3332 		if (adapter->num_tx_desc_avail == adapter->num_tx_desc)
3333 			ifp->if_timer = 0;
3334 	}
3335 	if (!gc || adapter->tx_nmbuf > 0)
3336 		adapter->tx_running = EM_TX_RUNNING;
3337 }
3338 
3339 /*
3340  * When Link is lost sometimes there is work still in the TX ring
3341  * which will result in a watchdog, rather than allow that do an
3342  * attempted cleanup and then reinit here.  Note that this has been
3343  * seens mostly with fiber adapters.
3344  */
3345 static void
3346 em_tx_purge(struct adapter *adapter)
3347 {
3348 	struct ifnet *ifp = &adapter->arpcom.ac_if;
3349 
3350 	if (!adapter->link_active && ifp->if_timer) {
3351 		em_tx_collect(adapter, FALSE);
3352 		if (ifp->if_timer) {
3353 			if_printf(ifp, "Link lost, TX pending, reinit\n");
3354 			ifp->if_timer = 0;
3355 			em_init(adapter);
3356 		}
3357 	}
3358 }
3359 
3360 static int
3361 em_newbuf(struct adapter *adapter, int i, int init)
3362 {
3363 	struct mbuf *m;
3364 	bus_dma_segment_t seg;
3365 	bus_dmamap_t map;
3366 	struct em_buffer *rx_buffer;
3367 	int error, nseg;
3368 
3369 	m = m_getcl(init ? M_WAITOK : M_NOWAIT, MT_DATA, M_PKTHDR);
3370 	if (m == NULL) {
3371 		adapter->mbuf_cluster_failed++;
3372 		if (init) {
3373 			if_printf(&adapter->arpcom.ac_if,
3374 				  "Unable to allocate RX mbuf\n");
3375 		}
3376 		return (ENOBUFS);
3377 	}
3378 	m->m_len = m->m_pkthdr.len = MCLBYTES;
3379 
3380 	if (adapter->hw.mac.max_frame_size <= MCLBYTES - ETHER_ALIGN)
3381 		m_adj(m, ETHER_ALIGN);
3382 
3383 	error = bus_dmamap_load_mbuf_segment(adapter->rxtag,
3384 			adapter->rx_sparemap, m,
3385 			&seg, 1, &nseg, BUS_DMA_NOWAIT);
3386 	if (error) {
3387 		m_freem(m);
3388 		if (init) {
3389 			if_printf(&adapter->arpcom.ac_if,
3390 				  "Unable to load RX mbuf\n");
3391 		}
3392 		return (error);
3393 	}
3394 
3395 	rx_buffer = &adapter->rx_buffer_area[i];
3396 	if (rx_buffer->m_head != NULL)
3397 		bus_dmamap_unload(adapter->rxtag, rx_buffer->map);
3398 
3399 	map = rx_buffer->map;
3400 	rx_buffer->map = adapter->rx_sparemap;
3401 	adapter->rx_sparemap = map;
3402 
3403 	rx_buffer->m_head = m;
3404 
3405 	adapter->rx_desc_base[i].buffer_addr = htole64(seg.ds_addr);
3406 	return (0);
3407 }
3408 
3409 static int
3410 em_create_rx_ring(struct adapter *adapter)
3411 {
3412 	device_t dev = adapter->dev;
3413 	struct em_buffer *rx_buffer;
3414 	int i, error;
3415 
3416 	adapter->rx_buffer_area =
3417 		kmalloc(sizeof(struct em_buffer) * adapter->num_rx_desc,
3418 			M_DEVBUF, M_WAITOK | M_ZERO);
3419 
3420 	/*
3421 	 * Create DMA tag for rx buffers
3422 	 */
3423 	error = bus_dma_tag_create(adapter->parent_dtag, /* parent */
3424 			1, 0,			/* alignment, bounds */
3425 			BUS_SPACE_MAXADDR,	/* lowaddr */
3426 			BUS_SPACE_MAXADDR,	/* highaddr */
3427 			NULL, NULL,		/* filter, filterarg */
3428 			MCLBYTES,		/* maxsize */
3429 			1,			/* nsegments */
3430 			MCLBYTES,		/* maxsegsize */
3431 			BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, /* flags */
3432 			&adapter->rxtag);
3433 	if (error) {
3434 		device_printf(dev, "Unable to allocate RX DMA tag\n");
3435 		kfree(adapter->rx_buffer_area, M_DEVBUF);
3436 		adapter->rx_buffer_area = NULL;
3437 		return error;
3438 	}
3439 
3440 	/*
3441 	 * Create spare DMA map for rx buffers
3442 	 */
3443 	error = bus_dmamap_create(adapter->rxtag, BUS_DMA_WAITOK,
3444 				  &adapter->rx_sparemap);
3445 	if (error) {
3446 		device_printf(dev, "Unable to create spare RX DMA map\n");
3447 		bus_dma_tag_destroy(adapter->rxtag);
3448 		kfree(adapter->rx_buffer_area, M_DEVBUF);
3449 		adapter->rx_buffer_area = NULL;
3450 		return error;
3451 	}
3452 
3453 	/*
3454 	 * Create DMA maps for rx buffers
3455 	 */
3456 	for (i = 0; i < adapter->num_rx_desc; i++) {
3457 		rx_buffer = &adapter->rx_buffer_area[i];
3458 
3459 		error = bus_dmamap_create(adapter->rxtag, BUS_DMA_WAITOK,
3460 					  &rx_buffer->map);
3461 		if (error) {
3462 			device_printf(dev, "Unable to create RX DMA map\n");
3463 			em_destroy_rx_ring(adapter, i);
3464 			return error;
3465 		}
3466 	}
3467 	return (0);
3468 }
3469 
3470 static int
3471 em_init_rx_ring(struct adapter *adapter)
3472 {
3473 	int i, error;
3474 
3475 	/* Reset descriptor ring */
3476 	bzero(adapter->rx_desc_base,
3477 	    (sizeof(struct e1000_rx_desc)) * adapter->num_rx_desc);
3478 
3479 	/* Allocate new ones. */
3480 	for (i = 0; i < adapter->num_rx_desc; i++) {
3481 		error = em_newbuf(adapter, i, 1);
3482 		if (error)
3483 			return (error);
3484 	}
3485 
3486 	/* Setup our descriptor pointers */
3487 	adapter->next_rx_desc_to_check = 0;
3488 
3489 	return (0);
3490 }
3491 
3492 static void
3493 em_init_rx_unit(struct adapter *adapter)
3494 {
3495 	struct ifnet *ifp = &adapter->arpcom.ac_if;
3496 	uint64_t bus_addr;
3497 	uint32_t rctl, rxcsum;
3498 
3499 	/*
3500 	 * Make sure receives are disabled while setting
3501 	 * up the descriptor ring
3502 	 */
3503 	rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
3504 	/* Do not disable if ever enabled on this hardware */
3505 	if (adapter->hw.mac.type != e1000_82574 &&
3506 	    adapter->hw.mac.type != e1000_82583)
3507 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
3508 
3509 	if (adapter->hw.mac.type >= e1000_82540) {
3510 		uint32_t itr;
3511 
3512 		/*
3513 		 * Set the interrupt throttling rate. Value is calculated
3514 		 * as ITR = 1 / (INT_THROTTLE_CEIL * 256ns)
3515 		 */
3516 		if (adapter->int_throttle_ceil)
3517 			itr = 1000000000 / 256 / adapter->int_throttle_ceil;
3518 		else
3519 			itr = 0;
3520 		em_set_itr(adapter, itr);
3521 	}
3522 
3523 	/* Disable accelerated ackknowledge */
3524 	if (adapter->hw.mac.type == e1000_82574) {
3525 		uint32_t rfctl;
3526 
3527 		rfctl = E1000_READ_REG(&adapter->hw, E1000_RFCTL);
3528 		rfctl |= E1000_RFCTL_ACK_DIS;
3529 		E1000_WRITE_REG(&adapter->hw, E1000_RFCTL, rfctl);
3530 	}
3531 
3532 	/* Receive Checksum Offload for IP and TCP/UDP */
3533 	rxcsum = E1000_READ_REG(&adapter->hw, E1000_RXCSUM);
3534 	if (ifp->if_capenable & IFCAP_RXCSUM)
3535 		rxcsum |= (E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL);
3536 	else
3537 		rxcsum &= ~(E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL);
3538 	E1000_WRITE_REG(&adapter->hw, E1000_RXCSUM, rxcsum);
3539 
3540 	/*
3541 	 * XXX TEMPORARY WORKAROUND: on some systems with 82573
3542 	 * long latencies are observed, like Lenovo X60. This
3543 	 * change eliminates the problem, but since having positive
3544 	 * values in RDTR is a known source of problems on other
3545 	 * platforms another solution is being sought.
3546 	 */
3547 	if (em_82573_workaround && adapter->hw.mac.type == e1000_82573) {
3548 		E1000_WRITE_REG(&adapter->hw, E1000_RADV, EM_RADV_82573);
3549 		E1000_WRITE_REG(&adapter->hw, E1000_RDTR, EM_RDTR_82573);
3550 	}
3551 
3552 	/*
3553 	 * Setup the Base and Length of the Rx Descriptor Ring
3554 	 */
3555 	bus_addr = adapter->rxdma.dma_paddr;
3556 	E1000_WRITE_REG(&adapter->hw, E1000_RDLEN(0),
3557 	    adapter->num_rx_desc * sizeof(struct e1000_rx_desc));
3558 	E1000_WRITE_REG(&adapter->hw, E1000_RDBAH(0),
3559 	    (uint32_t)(bus_addr >> 32));
3560 	E1000_WRITE_REG(&adapter->hw, E1000_RDBAL(0),
3561 	    (uint32_t)bus_addr);
3562 
3563 	/*
3564 	 * Setup the HW Rx Head and Tail Descriptor Pointers
3565 	 */
3566 	E1000_WRITE_REG(&adapter->hw, E1000_RDH(0), 0);
3567 	E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), adapter->num_rx_desc - 1);
3568 
3569 	/* Set PTHRESH for improved jumbo performance */
3570 	if (ifp->if_mtu > ETHERMTU) {
3571 		uint32_t rxdctl;
3572 
3573 		if (adapter->hw.mac.type == e1000_ich9lan ||
3574 		    adapter->hw.mac.type == e1000_pch2lan ||
3575 		    adapter->hw.mac.type == e1000_ich10lan) {
3576 			rxdctl = E1000_READ_REG(&adapter->hw, E1000_RXDCTL(0));
3577 			E1000_WRITE_REG(&adapter->hw, E1000_RXDCTL(0),
3578 			    rxdctl | 3);
3579 		} else if (adapter->hw.mac.type == e1000_82574) {
3580 			rxdctl = E1000_READ_REG(&adapter->hw, E1000_RXDCTL(0));
3581                 	rxdctl |= 0x20;		/* PTHRESH */
3582                 	rxdctl |= 4 << 8;	/* HTHRESH */
3583                 	rxdctl |= 4 << 16;	/* WTHRESH */
3584 			rxdctl |= 1 << 24;	/* Switch to granularity */
3585 			E1000_WRITE_REG(&adapter->hw, E1000_RXDCTL(0), rxdctl);
3586 		}
3587 	}
3588 
3589 	if (adapter->hw.mac.type >= e1000_pch2lan) {
3590 		if (ifp->if_mtu > ETHERMTU)
3591 			e1000_lv_jumbo_workaround_ich8lan(&adapter->hw, TRUE);
3592 		else
3593 			e1000_lv_jumbo_workaround_ich8lan(&adapter->hw, FALSE);
3594 	}
3595 
3596 	/* Setup the Receive Control Register */
3597 	rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
3598 	rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO |
3599 		E1000_RCTL_RDMTS_HALF |
3600 		(adapter->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
3601 
3602 	/* Make sure VLAN Filters are off */
3603 	rctl &= ~E1000_RCTL_VFE;
3604 
3605 	if (e1000_tbi_sbp_enabled_82543(&adapter->hw))
3606 		rctl |= E1000_RCTL_SBP;
3607 	else
3608 		rctl &= ~E1000_RCTL_SBP;
3609 
3610 	switch (adapter->rx_buffer_len) {
3611 	default:
3612 	case 2048:
3613 		rctl |= E1000_RCTL_SZ_2048;
3614 		break;
3615 
3616 	case 4096:
3617 		rctl |= E1000_RCTL_SZ_4096 |
3618 		    E1000_RCTL_BSEX | E1000_RCTL_LPE;
3619 		break;
3620 
3621 	case 8192:
3622 		rctl |= E1000_RCTL_SZ_8192 |
3623 		    E1000_RCTL_BSEX | E1000_RCTL_LPE;
3624 		break;
3625 
3626 	case 16384:
3627 		rctl |= E1000_RCTL_SZ_16384 |
3628 		    E1000_RCTL_BSEX | E1000_RCTL_LPE;
3629 		break;
3630 	}
3631 
3632 	if (ifp->if_mtu > ETHERMTU)
3633 		rctl |= E1000_RCTL_LPE;
3634 	else
3635 		rctl &= ~E1000_RCTL_LPE;
3636 
3637 	/* Enable Receives */
3638 	E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
3639 }
3640 
3641 static void
3642 em_destroy_rx_ring(struct adapter *adapter, int ndesc)
3643 {
3644 	struct em_buffer *rx_buffer;
3645 	int i;
3646 
3647 	if (adapter->rx_buffer_area == NULL)
3648 		return;
3649 
3650 	for (i = 0; i < ndesc; i++) {
3651 		rx_buffer = &adapter->rx_buffer_area[i];
3652 
3653 		KKASSERT(rx_buffer->m_head == NULL);
3654 		bus_dmamap_destroy(adapter->rxtag, rx_buffer->map);
3655 	}
3656 	bus_dmamap_destroy(adapter->rxtag, adapter->rx_sparemap);
3657 	bus_dma_tag_destroy(adapter->rxtag);
3658 
3659 	kfree(adapter->rx_buffer_area, M_DEVBUF);
3660 	adapter->rx_buffer_area = NULL;
3661 }
3662 
3663 static void
3664 em_rxeof(struct adapter *adapter, int count)
3665 {
3666 	struct ifnet *ifp = &adapter->arpcom.ac_if;
3667 	uint8_t status, accept_frame = 0, eop = 0;
3668 	uint16_t len, desc_len, prev_len_adj;
3669 	struct e1000_rx_desc *current_desc;
3670 	struct mbuf *mp;
3671 	int i;
3672 
3673 	i = adapter->next_rx_desc_to_check;
3674 	current_desc = &adapter->rx_desc_base[i];
3675 
3676 	if (!(current_desc->status & E1000_RXD_STAT_DD))
3677 		return;
3678 
3679 	while ((current_desc->status & E1000_RXD_STAT_DD) && count != 0) {
3680 		struct mbuf *m = NULL;
3681 
3682 		logif(pkt_receive);
3683 
3684 		mp = adapter->rx_buffer_area[i].m_head;
3685 
3686 		/*
3687 		 * Can't defer bus_dmamap_sync(9) because TBI_ACCEPT
3688 		 * needs to access the last received byte in the mbuf.
3689 		 */
3690 		bus_dmamap_sync(adapter->rxtag, adapter->rx_buffer_area[i].map,
3691 				BUS_DMASYNC_POSTREAD);
3692 
3693 		accept_frame = 1;
3694 		prev_len_adj = 0;
3695 		desc_len = le16toh(current_desc->length);
3696 		status = current_desc->status;
3697 		if (status & E1000_RXD_STAT_EOP) {
3698 			count--;
3699 			eop = 1;
3700 			if (desc_len < ETHER_CRC_LEN) {
3701 				len = 0;
3702 				prev_len_adj = ETHER_CRC_LEN - desc_len;
3703 			} else {
3704 				len = desc_len - ETHER_CRC_LEN;
3705 			}
3706 		} else {
3707 			eop = 0;
3708 			len = desc_len;
3709 		}
3710 
3711 		if (current_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK) {
3712 			uint8_t	last_byte;
3713 			uint32_t pkt_len = desc_len;
3714 
3715 			if (adapter->fmp != NULL)
3716 				pkt_len += adapter->fmp->m_pkthdr.len;
3717 
3718 			last_byte = *(mtod(mp, caddr_t) + desc_len - 1);
3719 			if (TBI_ACCEPT(&adapter->hw, status,
3720 			    current_desc->errors, pkt_len, last_byte,
3721 			    adapter->min_frame_size,
3722 			    adapter->hw.mac.max_frame_size)) {
3723 				e1000_tbi_adjust_stats_82543(&adapter->hw,
3724 				    &adapter->stats, pkt_len,
3725 				    adapter->hw.mac.addr,
3726 				    adapter->hw.mac.max_frame_size);
3727 				if (len > 0)
3728 					len--;
3729 			} else {
3730 				accept_frame = 0;
3731 			}
3732 		}
3733 
3734 		if (accept_frame) {
3735 			if (em_newbuf(adapter, i, 0) != 0) {
3736 				IFNET_STAT_INC(ifp, iqdrops, 1);
3737 				goto discard;
3738 			}
3739 
3740 			/* Assign correct length to the current fragment */
3741 			mp->m_len = len;
3742 
3743 			if (adapter->fmp == NULL) {
3744 				mp->m_pkthdr.len = len;
3745 				adapter->fmp = mp; /* Store the first mbuf */
3746 				adapter->lmp = mp;
3747 			} else {
3748 				/*
3749 				 * Chain mbuf's together
3750 				 */
3751 
3752 				/*
3753 				 * Adjust length of previous mbuf in chain if
3754 				 * we received less than 4 bytes in the last
3755 				 * descriptor.
3756 				 */
3757 				if (prev_len_adj > 0) {
3758 					adapter->lmp->m_len -= prev_len_adj;
3759 					adapter->fmp->m_pkthdr.len -=
3760 					    prev_len_adj;
3761 				}
3762 				adapter->lmp->m_next = mp;
3763 				adapter->lmp = adapter->lmp->m_next;
3764 				adapter->fmp->m_pkthdr.len += len;
3765 			}
3766 
3767 			if (eop) {
3768 				adapter->fmp->m_pkthdr.rcvif = ifp;
3769 				IFNET_STAT_INC(ifp, ipackets, 1);
3770 
3771 				if (ifp->if_capenable & IFCAP_RXCSUM) {
3772 					em_rxcsum(adapter, current_desc,
3773 						  adapter->fmp);
3774 				}
3775 
3776 				if (status & E1000_RXD_STAT_VP) {
3777 					adapter->fmp->m_pkthdr.ether_vlantag =
3778 					    (le16toh(current_desc->special) &
3779 					    E1000_RXD_SPC_VLAN_MASK);
3780 					adapter->fmp->m_flags |= M_VLANTAG;
3781 				}
3782 				m = adapter->fmp;
3783 				adapter->fmp = NULL;
3784 				adapter->lmp = NULL;
3785 			}
3786 		} else {
3787 			IFNET_STAT_INC(ifp, ierrors, 1);
3788 discard:
3789 #ifdef foo
3790 			/* Reuse loaded DMA map and just update mbuf chain */
3791 			mp = adapter->rx_buffer_area[i].m_head;
3792 			mp->m_len = mp->m_pkthdr.len = MCLBYTES;
3793 			mp->m_data = mp->m_ext.ext_buf;
3794 			mp->m_next = NULL;
3795 			if (adapter->hw.mac.max_frame_size <=
3796 			    (MCLBYTES - ETHER_ALIGN))
3797 				m_adj(mp, ETHER_ALIGN);
3798 #endif
3799 			if (adapter->fmp != NULL) {
3800 				m_freem(adapter->fmp);
3801 				adapter->fmp = NULL;
3802 				adapter->lmp = NULL;
3803 			}
3804 			m = NULL;
3805 		}
3806 
3807 		/* Zero out the receive descriptors status. */
3808 		current_desc->status = 0;
3809 
3810 		if (m != NULL)
3811 			ifp->if_input(ifp, m, NULL, -1);
3812 
3813 		/* Advance our pointers to the next descriptor. */
3814 		if (++i == adapter->num_rx_desc)
3815 			i = 0;
3816 		current_desc = &adapter->rx_desc_base[i];
3817 	}
3818 	adapter->next_rx_desc_to_check = i;
3819 
3820 	/* Advance the E1000's Receive Queue #0  "Tail Pointer". */
3821 	if (--i < 0)
3822 		i = adapter->num_rx_desc - 1;
3823 	E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), i);
3824 }
3825 
3826 static void
3827 em_rxcsum(struct adapter *adapter, struct e1000_rx_desc *rx_desc,
3828 	  struct mbuf *mp)
3829 {
3830 	/* 82543 or newer only */
3831 	if (adapter->hw.mac.type < e1000_82543 ||
3832 	    /* Ignore Checksum bit is set */
3833 	    (rx_desc->status & E1000_RXD_STAT_IXSM))
3834 		return;
3835 
3836 	if ((rx_desc->status & E1000_RXD_STAT_IPCS) &&
3837 	    !(rx_desc->errors & E1000_RXD_ERR_IPE)) {
3838 		/* IP Checksum Good */
3839 		mp->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
3840 	}
3841 
3842 	if ((rx_desc->status & E1000_RXD_STAT_TCPCS) &&
3843 	    !(rx_desc->errors & E1000_RXD_ERR_TCPE)) {
3844 		mp->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
3845 					   CSUM_PSEUDO_HDR |
3846 					   CSUM_FRAG_NOT_CHECKED;
3847 		mp->m_pkthdr.csum_data = htons(0xffff);
3848 	}
3849 }
3850 
3851 static void
3852 em_enable_intr(struct adapter *adapter)
3853 {
3854 	uint32_t ims_mask = IMS_ENABLE_MASK;
3855 
3856 	lwkt_serialize_handler_enable(adapter->arpcom.ac_if.if_serializer);
3857 
3858 #if 0
3859 	/* XXX MSIX */
3860 	if (adapter->hw.mac.type == e1000_82574) {
3861 		E1000_WRITE_REG(&adapter->hw, EM_EIAC, EM_MSIX_MASK);
3862 		ims_mask |= EM_MSIX_MASK;
3863         }
3864 #endif
3865 	E1000_WRITE_REG(&adapter->hw, E1000_IMS, ims_mask);
3866 }
3867 
3868 static void
3869 em_disable_intr(struct adapter *adapter)
3870 {
3871 	uint32_t clear = 0xffffffff;
3872 
3873 	/*
3874 	 * The first version of 82542 had an errata where when link was forced
3875 	 * it would stay up even up even if the cable was disconnected.
3876 	 * Sequence errors were used to detect the disconnect and then the
3877 	 * driver would unforce the link.  This code in the in the ISR.  For
3878 	 * this to work correctly the Sequence error interrupt had to be
3879 	 * enabled all the time.
3880 	 */
3881 	if (adapter->hw.mac.type == e1000_82542 &&
3882 	    adapter->hw.revision_id == E1000_REVISION_2)
3883 		clear &= ~E1000_ICR_RXSEQ;
3884 	else if (adapter->hw.mac.type == e1000_82574)
3885 		E1000_WRITE_REG(&adapter->hw, EM_EIAC, 0);
3886 
3887 	E1000_WRITE_REG(&adapter->hw, E1000_IMC, clear);
3888 
3889 	adapter->npoll.ifpc_stcount = 0;
3890 
3891 	lwkt_serialize_handler_disable(adapter->arpcom.ac_if.if_serializer);
3892 }
3893 
3894 /*
3895  * Bit of a misnomer, what this really means is
3896  * to enable OS management of the system... aka
3897  * to disable special hardware management features
3898  */
3899 static void
3900 em_get_mgmt(struct adapter *adapter)
3901 {
3902 	/* A shared code workaround */
3903 #define E1000_82542_MANC2H E1000_MANC2H
3904 	if (adapter->flags & EM_FLAG_HAS_MGMT) {
3905 		int manc2h = E1000_READ_REG(&adapter->hw, E1000_MANC2H);
3906 		int manc = E1000_READ_REG(&adapter->hw, E1000_MANC);
3907 
3908 		/* disable hardware interception of ARP */
3909 		manc &= ~(E1000_MANC_ARP_EN);
3910 
3911                 /* enable receiving management packets to the host */
3912                 if (adapter->hw.mac.type >= e1000_82571) {
3913 			manc |= E1000_MANC_EN_MNG2HOST;
3914 #define E1000_MNG2HOST_PORT_623 (1 << 5)
3915 #define E1000_MNG2HOST_PORT_664 (1 << 6)
3916 			manc2h |= E1000_MNG2HOST_PORT_623;
3917 			manc2h |= E1000_MNG2HOST_PORT_664;
3918 			E1000_WRITE_REG(&adapter->hw, E1000_MANC2H, manc2h);
3919 		}
3920 
3921 		E1000_WRITE_REG(&adapter->hw, E1000_MANC, manc);
3922 	}
3923 }
3924 
3925 /*
3926  * Give control back to hardware management
3927  * controller if there is one.
3928  */
3929 static void
3930 em_rel_mgmt(struct adapter *adapter)
3931 {
3932 	if (adapter->flags & EM_FLAG_HAS_MGMT) {
3933 		int manc = E1000_READ_REG(&adapter->hw, E1000_MANC);
3934 
3935 		/* re-enable hardware interception of ARP */
3936 		manc |= E1000_MANC_ARP_EN;
3937 
3938 		if (adapter->hw.mac.type >= e1000_82571)
3939 			manc &= ~E1000_MANC_EN_MNG2HOST;
3940 
3941 		E1000_WRITE_REG(&adapter->hw, E1000_MANC, manc);
3942 	}
3943 }
3944 
3945 /*
3946  * em_get_hw_control() sets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3947  * For ASF and Pass Through versions of f/w this means that
3948  * the driver is loaded.  For AMT version (only with 82573)
3949  * of the f/w this means that the network i/f is open.
3950  */
3951 static void
3952 em_get_hw_control(struct adapter *adapter)
3953 {
3954 	/* Let firmware know the driver has taken over */
3955 	if (adapter->hw.mac.type == e1000_82573) {
3956 		uint32_t swsm;
3957 
3958 		swsm = E1000_READ_REG(&adapter->hw, E1000_SWSM);
3959 		E1000_WRITE_REG(&adapter->hw, E1000_SWSM,
3960 		    swsm | E1000_SWSM_DRV_LOAD);
3961 	} else {
3962 		uint32_t ctrl_ext;
3963 
3964 		ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
3965 		E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT,
3966 		    ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
3967 	}
3968 	adapter->flags |= EM_FLAG_HW_CTRL;
3969 }
3970 
3971 /*
3972  * em_rel_hw_control() resets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3973  * For ASF and Pass Through versions of f/w this means that the
3974  * driver is no longer loaded.  For AMT version (only with 82573)
3975  * of the f/w this means that the network i/f is closed.
3976  */
3977 static void
3978 em_rel_hw_control(struct adapter *adapter)
3979 {
3980 	if ((adapter->flags & EM_FLAG_HW_CTRL) == 0)
3981 		return;
3982 	adapter->flags &= ~EM_FLAG_HW_CTRL;
3983 
3984 	/* Let firmware taken over control of h/w */
3985 	if (adapter->hw.mac.type == e1000_82573) {
3986 		uint32_t swsm;
3987 
3988 		swsm = E1000_READ_REG(&adapter->hw, E1000_SWSM);
3989 		E1000_WRITE_REG(&adapter->hw, E1000_SWSM,
3990 		    swsm & ~E1000_SWSM_DRV_LOAD);
3991 	} else {
3992 		uint32_t ctrl_ext;
3993 
3994 		ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
3995 		E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT,
3996 		    ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
3997 	}
3998 }
3999 
4000 static int
4001 em_is_valid_eaddr(const uint8_t *addr)
4002 {
4003 	char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
4004 
4005 	if ((addr[0] & 1) || !bcmp(addr, zero_addr, ETHER_ADDR_LEN))
4006 		return (FALSE);
4007 
4008 	return (TRUE);
4009 }
4010 
4011 /*
4012  * Enable PCI Wake On Lan capability
4013  */
4014 static void
4015 em_enable_wol(device_t dev)
4016 {
4017 	uint16_t cap, status;
4018 	uint8_t id;
4019 
4020 	/* First find the capabilities pointer*/
4021 	cap = pci_read_config(dev, PCIR_CAP_PTR, 2);
4022 
4023 	/* Read the PM Capabilities */
4024 	id = pci_read_config(dev, cap, 1);
4025 	if (id != PCIY_PMG)     /* Something wrong */
4026 		return;
4027 
4028 	/*
4029 	 * OK, we have the power capabilities,
4030 	 * so now get the status register
4031 	 */
4032 	cap += PCIR_POWER_STATUS;
4033 	status = pci_read_config(dev, cap, 2);
4034 	status |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
4035 	pci_write_config(dev, cap, status, 2);
4036 }
4037 
4038 
4039 /*
4040  * 82544 Coexistence issue workaround.
4041  *    There are 2 issues.
4042  *       1. Transmit Hang issue.
4043  *    To detect this issue, following equation can be used...
4044  *	  SIZE[3:0] + ADDR[2:0] = SUM[3:0].
4045  *	  If SUM[3:0] is in between 1 to 4, we will have this issue.
4046  *
4047  *       2. DAC issue.
4048  *    To detect this issue, following equation can be used...
4049  *	  SIZE[3:0] + ADDR[2:0] = SUM[3:0].
4050  *	  If SUM[3:0] is in between 9 to c, we will have this issue.
4051  *
4052  *    WORKAROUND:
4053  *	  Make sure we do not have ending address
4054  *	  as 1,2,3,4(Hang) or 9,a,b,c (DAC)
4055  */
4056 static uint32_t
4057 em_82544_fill_desc(bus_addr_t address, uint32_t length, PDESC_ARRAY desc_array)
4058 {
4059 	uint32_t safe_terminator;
4060 
4061 	/*
4062 	 * Since issue is sensitive to length and address.
4063 	 * Let us first check the address...
4064 	 */
4065 	if (length <= 4) {
4066 		desc_array->descriptor[0].address = address;
4067 		desc_array->descriptor[0].length = length;
4068 		desc_array->elements = 1;
4069 		return (desc_array->elements);
4070 	}
4071 
4072 	safe_terminator =
4073 	(uint32_t)((((uint32_t)address & 0x7) + (length & 0xF)) & 0xF);
4074 
4075 	/* If it does not fall between 0x1 to 0x4 and 0x9 to 0xC then return */
4076 	if (safe_terminator == 0 ||
4077 	    (safe_terminator > 4 && safe_terminator < 9) ||
4078 	    (safe_terminator > 0xC && safe_terminator <= 0xF)) {
4079 		desc_array->descriptor[0].address = address;
4080 		desc_array->descriptor[0].length = length;
4081 		desc_array->elements = 1;
4082 		return (desc_array->elements);
4083 	}
4084 
4085 	desc_array->descriptor[0].address = address;
4086 	desc_array->descriptor[0].length = length - 4;
4087 	desc_array->descriptor[1].address = address + (length - 4);
4088 	desc_array->descriptor[1].length = 4;
4089 	desc_array->elements = 2;
4090 	return (desc_array->elements);
4091 }
4092 
4093 static void
4094 em_update_stats(struct adapter *adapter)
4095 {
4096 	struct ifnet *ifp = &adapter->arpcom.ac_if;
4097 
4098 	if (adapter->hw.phy.media_type == e1000_media_type_copper ||
4099 	    (E1000_READ_REG(&adapter->hw, E1000_STATUS) & E1000_STATUS_LU)) {
4100 		adapter->stats.symerrs +=
4101 			E1000_READ_REG(&adapter->hw, E1000_SYMERRS);
4102 		adapter->stats.sec += E1000_READ_REG(&adapter->hw, E1000_SEC);
4103 	}
4104 	adapter->stats.crcerrs += E1000_READ_REG(&adapter->hw, E1000_CRCERRS);
4105 	adapter->stats.mpc += E1000_READ_REG(&adapter->hw, E1000_MPC);
4106 	adapter->stats.scc += E1000_READ_REG(&adapter->hw, E1000_SCC);
4107 	adapter->stats.ecol += E1000_READ_REG(&adapter->hw, E1000_ECOL);
4108 
4109 	adapter->stats.mcc += E1000_READ_REG(&adapter->hw, E1000_MCC);
4110 	adapter->stats.latecol += E1000_READ_REG(&adapter->hw, E1000_LATECOL);
4111 	adapter->stats.colc += E1000_READ_REG(&adapter->hw, E1000_COLC);
4112 	adapter->stats.dc += E1000_READ_REG(&adapter->hw, E1000_DC);
4113 	adapter->stats.rlec += E1000_READ_REG(&adapter->hw, E1000_RLEC);
4114 	adapter->stats.xonrxc += E1000_READ_REG(&adapter->hw, E1000_XONRXC);
4115 	adapter->stats.xontxc += E1000_READ_REG(&adapter->hw, E1000_XONTXC);
4116 	adapter->stats.xoffrxc += E1000_READ_REG(&adapter->hw, E1000_XOFFRXC);
4117 	adapter->stats.xofftxc += E1000_READ_REG(&adapter->hw, E1000_XOFFTXC);
4118 	adapter->stats.fcruc += E1000_READ_REG(&adapter->hw, E1000_FCRUC);
4119 	adapter->stats.prc64 += E1000_READ_REG(&adapter->hw, E1000_PRC64);
4120 	adapter->stats.prc127 += E1000_READ_REG(&adapter->hw, E1000_PRC127);
4121 	adapter->stats.prc255 += E1000_READ_REG(&adapter->hw, E1000_PRC255);
4122 	adapter->stats.prc511 += E1000_READ_REG(&adapter->hw, E1000_PRC511);
4123 	adapter->stats.prc1023 += E1000_READ_REG(&adapter->hw, E1000_PRC1023);
4124 	adapter->stats.prc1522 += E1000_READ_REG(&adapter->hw, E1000_PRC1522);
4125 	adapter->stats.gprc += E1000_READ_REG(&adapter->hw, E1000_GPRC);
4126 	adapter->stats.bprc += E1000_READ_REG(&adapter->hw, E1000_BPRC);
4127 	adapter->stats.mprc += E1000_READ_REG(&adapter->hw, E1000_MPRC);
4128 	adapter->stats.gptc += E1000_READ_REG(&adapter->hw, E1000_GPTC);
4129 
4130 	/* For the 64-bit byte counters the low dword must be read first. */
4131 	/* Both registers clear on the read of the high dword */
4132 
4133 	adapter->stats.gorc += E1000_READ_REG(&adapter->hw, E1000_GORCH);
4134 	adapter->stats.gotc += E1000_READ_REG(&adapter->hw, E1000_GOTCH);
4135 
4136 	adapter->stats.rnbc += E1000_READ_REG(&adapter->hw, E1000_RNBC);
4137 	adapter->stats.ruc += E1000_READ_REG(&adapter->hw, E1000_RUC);
4138 	adapter->stats.rfc += E1000_READ_REG(&adapter->hw, E1000_RFC);
4139 	adapter->stats.roc += E1000_READ_REG(&adapter->hw, E1000_ROC);
4140 	adapter->stats.rjc += E1000_READ_REG(&adapter->hw, E1000_RJC);
4141 
4142 	adapter->stats.tor += E1000_READ_REG(&adapter->hw, E1000_TORH);
4143 	adapter->stats.tot += E1000_READ_REG(&adapter->hw, E1000_TOTH);
4144 
4145 	adapter->stats.tpr += E1000_READ_REG(&adapter->hw, E1000_TPR);
4146 	adapter->stats.tpt += E1000_READ_REG(&adapter->hw, E1000_TPT);
4147 	adapter->stats.ptc64 += E1000_READ_REG(&adapter->hw, E1000_PTC64);
4148 	adapter->stats.ptc127 += E1000_READ_REG(&adapter->hw, E1000_PTC127);
4149 	adapter->stats.ptc255 += E1000_READ_REG(&adapter->hw, E1000_PTC255);
4150 	adapter->stats.ptc511 += E1000_READ_REG(&adapter->hw, E1000_PTC511);
4151 	adapter->stats.ptc1023 += E1000_READ_REG(&adapter->hw, E1000_PTC1023);
4152 	adapter->stats.ptc1522 += E1000_READ_REG(&adapter->hw, E1000_PTC1522);
4153 	adapter->stats.mptc += E1000_READ_REG(&adapter->hw, E1000_MPTC);
4154 	adapter->stats.bptc += E1000_READ_REG(&adapter->hw, E1000_BPTC);
4155 
4156 	if (adapter->hw.mac.type >= e1000_82543) {
4157 		adapter->stats.algnerrc +=
4158 		E1000_READ_REG(&adapter->hw, E1000_ALGNERRC);
4159 		adapter->stats.rxerrc +=
4160 		E1000_READ_REG(&adapter->hw, E1000_RXERRC);
4161 		adapter->stats.tncrs +=
4162 		E1000_READ_REG(&adapter->hw, E1000_TNCRS);
4163 		adapter->stats.cexterr +=
4164 		E1000_READ_REG(&adapter->hw, E1000_CEXTERR);
4165 		adapter->stats.tsctc +=
4166 		E1000_READ_REG(&adapter->hw, E1000_TSCTC);
4167 		adapter->stats.tsctfc +=
4168 		E1000_READ_REG(&adapter->hw, E1000_TSCTFC);
4169 	}
4170 
4171 	IFNET_STAT_SET(ifp, collisions, adapter->stats.colc);
4172 
4173 	/* Rx Errors */
4174 	IFNET_STAT_SET(ifp, ierrors,
4175 	    adapter->dropped_pkts + adapter->stats.rxerrc +
4176 	    adapter->stats.crcerrs + adapter->stats.algnerrc +
4177 	    adapter->stats.ruc + adapter->stats.roc +
4178 	    adapter->stats.mpc + adapter->stats.cexterr);
4179 
4180 	/* Tx Errors */
4181 	IFNET_STAT_SET(ifp, oerrors,
4182 	    adapter->stats.ecol + adapter->stats.latecol +
4183 	    adapter->watchdog_events);
4184 }
4185 
4186 static void
4187 em_print_debug_info(struct adapter *adapter)
4188 {
4189 	device_t dev = adapter->dev;
4190 	uint8_t *hw_addr = adapter->hw.hw_addr;
4191 
4192 	device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
4193 	device_printf(dev, "CTRL = 0x%x RCTL = 0x%x \n",
4194 	    E1000_READ_REG(&adapter->hw, E1000_CTRL),
4195 	    E1000_READ_REG(&adapter->hw, E1000_RCTL));
4196 	device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk \n",
4197 	    ((E1000_READ_REG(&adapter->hw, E1000_PBA) & 0xffff0000) >> 16),\
4198 	    (E1000_READ_REG(&adapter->hw, E1000_PBA) & 0xffff) );
4199 	device_printf(dev, "Flow control watermarks high = %d low = %d\n",
4200 	    adapter->hw.fc.high_water,
4201 	    adapter->hw.fc.low_water);
4202 	device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
4203 	    E1000_READ_REG(&adapter->hw, E1000_TIDV),
4204 	    E1000_READ_REG(&adapter->hw, E1000_TADV));
4205 	device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
4206 	    E1000_READ_REG(&adapter->hw, E1000_RDTR),
4207 	    E1000_READ_REG(&adapter->hw, E1000_RADV));
4208 	device_printf(dev, "fifo workaround = %lld, fifo_reset_count = %lld\n",
4209 	    (long long)adapter->tx_fifo_wrk_cnt,
4210 	    (long long)adapter->tx_fifo_reset_cnt);
4211 	device_printf(dev, "hw tdh = %d, hw tdt = %d\n",
4212 	    E1000_READ_REG(&adapter->hw, E1000_TDH(0)),
4213 	    E1000_READ_REG(&adapter->hw, E1000_TDT(0)));
4214 	device_printf(dev, "hw rdh = %d, hw rdt = %d\n",
4215 	    E1000_READ_REG(&adapter->hw, E1000_RDH(0)),
4216 	    E1000_READ_REG(&adapter->hw, E1000_RDT(0)));
4217 	device_printf(dev, "Num Tx descriptors avail = %d\n",
4218 	    adapter->num_tx_desc_avail);
4219 	device_printf(dev, "Tx Descriptors not avail1 = %ld\n",
4220 	    adapter->no_tx_desc_avail1);
4221 	device_printf(dev, "Tx Descriptors not avail2 = %ld\n",
4222 	    adapter->no_tx_desc_avail2);
4223 	device_printf(dev, "Std mbuf failed = %ld\n",
4224 	    adapter->mbuf_alloc_failed);
4225 	device_printf(dev, "Std mbuf cluster failed = %ld\n",
4226 	    adapter->mbuf_cluster_failed);
4227 	device_printf(dev, "Driver dropped packets = %ld\n",
4228 	    adapter->dropped_pkts);
4229 	device_printf(dev, "Driver tx dma failure in encap = %ld\n",
4230 	    adapter->no_tx_dma_setup);
4231 }
4232 
4233 static void
4234 em_print_hw_stats(struct adapter *adapter)
4235 {
4236 	device_t dev = adapter->dev;
4237 
4238 	device_printf(dev, "Excessive collisions = %lld\n",
4239 	    (long long)adapter->stats.ecol);
4240 #if (DEBUG_HW > 0)  /* Dont output these errors normally */
4241 	device_printf(dev, "Symbol errors = %lld\n",
4242 	    (long long)adapter->stats.symerrs);
4243 #endif
4244 	device_printf(dev, "Sequence errors = %lld\n",
4245 	    (long long)adapter->stats.sec);
4246 	device_printf(dev, "Defer count = %lld\n",
4247 	    (long long)adapter->stats.dc);
4248 	device_printf(dev, "Missed Packets = %lld\n",
4249 	    (long long)adapter->stats.mpc);
4250 	device_printf(dev, "Receive No Buffers = %lld\n",
4251 	    (long long)adapter->stats.rnbc);
4252 	/* RLEC is inaccurate on some hardware, calculate our own. */
4253 	device_printf(dev, "Receive Length Errors = %lld\n",
4254 	    ((long long)adapter->stats.roc + (long long)adapter->stats.ruc));
4255 	device_printf(dev, "Receive errors = %lld\n",
4256 	    (long long)adapter->stats.rxerrc);
4257 	device_printf(dev, "Crc errors = %lld\n",
4258 	    (long long)adapter->stats.crcerrs);
4259 	device_printf(dev, "Alignment errors = %lld\n",
4260 	    (long long)adapter->stats.algnerrc);
4261 	device_printf(dev, "Collision/Carrier extension errors = %lld\n",
4262 	    (long long)adapter->stats.cexterr);
4263 	device_printf(dev, "RX overruns = %ld\n", adapter->rx_overruns);
4264 	device_printf(dev, "watchdog timeouts = %ld\n",
4265 	    adapter->watchdog_events);
4266 	device_printf(dev, "XON Rcvd = %lld\n",
4267 	    (long long)adapter->stats.xonrxc);
4268 	device_printf(dev, "XON Xmtd = %lld\n",
4269 	    (long long)adapter->stats.xontxc);
4270 	device_printf(dev, "XOFF Rcvd = %lld\n",
4271 	    (long long)adapter->stats.xoffrxc);
4272 	device_printf(dev, "XOFF Xmtd = %lld\n",
4273 	    (long long)adapter->stats.xofftxc);
4274 	device_printf(dev, "Good Packets Rcvd = %lld\n",
4275 	    (long long)adapter->stats.gprc);
4276 	device_printf(dev, "Good Packets Xmtd = %lld\n",
4277 	    (long long)adapter->stats.gptc);
4278 }
4279 
4280 static void
4281 em_print_nvm_info(struct adapter *adapter)
4282 {
4283 	uint16_t eeprom_data;
4284 	int i, j, row = 0;
4285 
4286 	/* Its a bit crude, but it gets the job done */
4287 	kprintf("\nInterface EEPROM Dump:\n");
4288 	kprintf("Offset\n0x0000  ");
4289 	for (i = 0, j = 0; i < 32; i++, j++) {
4290 		if (j == 8) { /* Make the offset block */
4291 			j = 0; ++row;
4292 			kprintf("\n0x00%x0  ",row);
4293 		}
4294 		e1000_read_nvm(&adapter->hw, i, 1, &eeprom_data);
4295 		kprintf("%04x ", eeprom_data);
4296 	}
4297 	kprintf("\n");
4298 }
4299 
4300 static int
4301 em_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
4302 {
4303 	struct adapter *adapter;
4304 	struct ifnet *ifp;
4305 	int error, result;
4306 
4307 	result = -1;
4308 	error = sysctl_handle_int(oidp, &result, 0, req);
4309 	if (error || !req->newptr)
4310 		return (error);
4311 
4312 	adapter = (struct adapter *)arg1;
4313 	ifp = &adapter->arpcom.ac_if;
4314 
4315 	lwkt_serialize_enter(ifp->if_serializer);
4316 
4317 	if (result == 1)
4318 		em_print_debug_info(adapter);
4319 
4320 	/*
4321 	 * This value will cause a hex dump of the
4322 	 * first 32 16-bit words of the EEPROM to
4323 	 * the screen.
4324 	 */
4325 	if (result == 2)
4326 		em_print_nvm_info(adapter);
4327 
4328 	lwkt_serialize_exit(ifp->if_serializer);
4329 
4330 	return (error);
4331 }
4332 
4333 static int
4334 em_sysctl_stats(SYSCTL_HANDLER_ARGS)
4335 {
4336 	int error, result;
4337 
4338 	result = -1;
4339 	error = sysctl_handle_int(oidp, &result, 0, req);
4340 	if (error || !req->newptr)
4341 		return (error);
4342 
4343 	if (result == 1) {
4344 		struct adapter *adapter = (struct adapter *)arg1;
4345 		struct ifnet *ifp = &adapter->arpcom.ac_if;
4346 
4347 		lwkt_serialize_enter(ifp->if_serializer);
4348 		em_print_hw_stats(adapter);
4349 		lwkt_serialize_exit(ifp->if_serializer);
4350 	}
4351 	return (error);
4352 }
4353 
4354 static void
4355 em_add_sysctl(struct adapter *adapter)
4356 {
4357 	struct sysctl_ctx_list *ctx;
4358 	struct sysctl_oid *tree;
4359 
4360 	ctx = device_get_sysctl_ctx(adapter->dev);
4361 	tree = device_get_sysctl_tree(adapter->dev);
4362 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
4363 	    OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
4364 	    em_sysctl_debug_info, "I", "Debug Information");
4365 
4366 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
4367 	    OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
4368 	    em_sysctl_stats, "I", "Statistics");
4369 
4370 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
4371 	    OID_AUTO, "rxd", CTLFLAG_RD,
4372 	    &adapter->num_rx_desc, 0, NULL);
4373 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
4374 	    OID_AUTO, "txd", CTLFLAG_RD,
4375 	    &adapter->num_tx_desc, 0, NULL);
4376 
4377 	if (adapter->hw.mac.type >= e1000_82540) {
4378 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
4379 		    OID_AUTO, "int_throttle_ceil",
4380 		    CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
4381 		    em_sysctl_int_throttle, "I",
4382 		    "interrupt throttling rate");
4383 	}
4384 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
4385 	    OID_AUTO, "int_tx_nsegs",
4386 	    CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
4387 	    em_sysctl_int_tx_nsegs, "I",
4388 	    "# segments per TX interrupt");
4389 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
4390 	    OID_AUTO, "wreg_tx_nsegs", CTLFLAG_RW,
4391 	    &adapter->tx_wreg_nsegs, 0,
4392 	    "# segments before write to hardware register");
4393 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "tx_nmbuf",
4394 	    CTLFLAG_RD, &adapter->tx_nmbuf, 0, "# of pending TX mbufs");
4395 	SYSCTL_ADD_ULONG(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "tx_gc",
4396 	    CTLFLAG_RW, &adapter->tx_gc, "# of TX GC");
4397 }
4398 
4399 static int
4400 em_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
4401 {
4402 	struct adapter *adapter = (void *)arg1;
4403 	struct ifnet *ifp = &adapter->arpcom.ac_if;
4404 	int error, throttle;
4405 
4406 	throttle = adapter->int_throttle_ceil;
4407 	error = sysctl_handle_int(oidp, &throttle, 0, req);
4408 	if (error || req->newptr == NULL)
4409 		return error;
4410 	if (throttle < 0 || throttle > 1000000000 / 256)
4411 		return EINVAL;
4412 
4413 	if (throttle) {
4414 		/*
4415 		 * Set the interrupt throttling rate in 256ns increments,
4416 		 * recalculate sysctl value assignment to get exact frequency.
4417 		 */
4418 		throttle = 1000000000 / 256 / throttle;
4419 
4420 		/* Upper 16bits of ITR is reserved and should be zero */
4421 		if (throttle & 0xffff0000)
4422 			return EINVAL;
4423 	}
4424 
4425 	lwkt_serialize_enter(ifp->if_serializer);
4426 
4427 	if (throttle)
4428 		adapter->int_throttle_ceil = 1000000000 / 256 / throttle;
4429 	else
4430 		adapter->int_throttle_ceil = 0;
4431 
4432 	if (ifp->if_flags & IFF_RUNNING)
4433 		em_set_itr(adapter, throttle);
4434 
4435 	lwkt_serialize_exit(ifp->if_serializer);
4436 
4437 	if (bootverbose) {
4438 		if_printf(ifp, "Interrupt moderation set to %d/sec\n",
4439 			  adapter->int_throttle_ceil);
4440 	}
4441 	return 0;
4442 }
4443 
4444 static int
4445 em_sysctl_int_tx_nsegs(SYSCTL_HANDLER_ARGS)
4446 {
4447 	struct adapter *adapter = (void *)arg1;
4448 	struct ifnet *ifp = &adapter->arpcom.ac_if;
4449 	int error, segs;
4450 
4451 	segs = adapter->tx_int_nsegs;
4452 	error = sysctl_handle_int(oidp, &segs, 0, req);
4453 	if (error || req->newptr == NULL)
4454 		return error;
4455 	if (segs <= 0)
4456 		return EINVAL;
4457 
4458 	lwkt_serialize_enter(ifp->if_serializer);
4459 
4460 	/*
4461 	 * Don't allow int_tx_nsegs to become:
4462 	 * o  Less the oact_tx_desc
4463 	 * o  Too large that no TX desc will cause TX interrupt to
4464 	 *    be generated (OACTIVE will never recover)
4465 	 * o  Too small that will cause tx_dd[] overflow
4466 	 */
4467 	if (segs < adapter->oact_tx_desc ||
4468 	    segs >= adapter->num_tx_desc - adapter->oact_tx_desc ||
4469 	    segs < adapter->num_tx_desc / EM_TXDD_SAFE) {
4470 		error = EINVAL;
4471 	} else {
4472 		error = 0;
4473 		adapter->tx_int_nsegs = segs;
4474 	}
4475 
4476 	lwkt_serialize_exit(ifp->if_serializer);
4477 
4478 	return error;
4479 }
4480 
4481 static void
4482 em_set_itr(struct adapter *adapter, uint32_t itr)
4483 {
4484 	E1000_WRITE_REG(&adapter->hw, E1000_ITR, itr);
4485 	if (adapter->hw.mac.type == e1000_82574) {
4486 		int i;
4487 
4488 		/*
4489 		 * When using MSIX interrupts we need to
4490 		 * throttle using the EITR register
4491 		 */
4492 		for (i = 0; i < 4; ++i) {
4493 			E1000_WRITE_REG(&adapter->hw,
4494 			    E1000_EITR_82574(i), itr);
4495 		}
4496 	}
4497 }
4498 
4499 static void
4500 em_disable_aspm(struct adapter *adapter)
4501 {
4502 	uint16_t link_cap, link_ctrl, disable;
4503 	uint8_t pcie_ptr, reg;
4504 	device_t dev = adapter->dev;
4505 
4506 	switch (adapter->hw.mac.type) {
4507 	case e1000_82571:
4508 	case e1000_82572:
4509 	case e1000_82573:
4510 		/*
4511 		 * 82573 specification update
4512 		 * errata #8 disable L0s
4513 		 * errata #41 disable L1
4514 		 *
4515 		 * 82571/82572 specification update
4516 		 # errata #13 disable L1
4517 		 * errata #68 disable L0s
4518 		 */
4519 		disable = PCIEM_LNKCTL_ASPM_L0S | PCIEM_LNKCTL_ASPM_L1;
4520 		break;
4521 
4522 	case e1000_82574:
4523 	case e1000_82583:
4524 		/*
4525 		 * 82574 specification update errata #20
4526 		 * 82583 specification update errata #9
4527 		 *
4528 		 * There is no need to disable L1
4529 		 */
4530 		disable = PCIEM_LNKCTL_ASPM_L0S;
4531 		break;
4532 
4533 	default:
4534 		return;
4535 	}
4536 
4537 	pcie_ptr = pci_get_pciecap_ptr(dev);
4538 	if (pcie_ptr == 0)
4539 		return;
4540 
4541 	link_cap = pci_read_config(dev, pcie_ptr + PCIER_LINKCAP, 2);
4542 	if ((link_cap & PCIEM_LNKCAP_ASPM_MASK) == 0)
4543 		return;
4544 
4545 	if (bootverbose) {
4546 		if_printf(&adapter->arpcom.ac_if,
4547 		    "disable ASPM %#02x\n", disable);
4548 	}
4549 
4550 	reg = pcie_ptr + PCIER_LINKCTRL;
4551 	link_ctrl = pci_read_config(dev, reg, 2);
4552 	link_ctrl &= ~disable;
4553 	pci_write_config(dev, reg, link_ctrl, 2);
4554 }
4555 
4556 static int
4557 em_tso_pullup(struct adapter *adapter, struct mbuf **mp)
4558 {
4559 	int iphlen, hoff, thoff, ex = 0;
4560 	struct mbuf *m;
4561 	struct ip *ip;
4562 
4563 	m = *mp;
4564 	KASSERT(M_WRITABLE(m), ("TSO mbuf not writable"));
4565 
4566 	iphlen = m->m_pkthdr.csum_iphlen;
4567 	thoff = m->m_pkthdr.csum_thlen;
4568 	hoff = m->m_pkthdr.csum_lhlen;
4569 
4570 	KASSERT(iphlen > 0, ("invalid ip hlen"));
4571 	KASSERT(thoff > 0, ("invalid tcp hlen"));
4572 	KASSERT(hoff > 0, ("invalid ether hlen"));
4573 
4574 	if (adapter->flags & EM_FLAG_TSO_PULLEX)
4575 		ex = 4;
4576 
4577 	if (m->m_len < hoff + iphlen + thoff + ex) {
4578 		m = m_pullup(m, hoff + iphlen + thoff + ex);
4579 		if (m == NULL) {
4580 			*mp = NULL;
4581 			return ENOBUFS;
4582 		}
4583 		*mp = m;
4584 	}
4585 	ip = mtodoff(m, struct ip *, hoff);
4586 	ip->ip_len = 0;
4587 
4588 	return 0;
4589 }
4590 
4591 static int
4592 em_tso_setup(struct adapter *adapter, struct mbuf *mp,
4593     uint32_t *txd_upper, uint32_t *txd_lower)
4594 {
4595 	struct e1000_context_desc *TXD;
4596 	int hoff, iphlen, thoff, hlen;
4597 	int mss, pktlen, curr_txd;
4598 
4599 	iphlen = mp->m_pkthdr.csum_iphlen;
4600 	thoff = mp->m_pkthdr.csum_thlen;
4601 	hoff = mp->m_pkthdr.csum_lhlen;
4602 	mss = mp->m_pkthdr.tso_segsz;
4603 	pktlen = mp->m_pkthdr.len;
4604 
4605 	if (adapter->csum_flags == CSUM_TSO &&
4606 	    adapter->csum_iphlen == iphlen &&
4607 	    adapter->csum_lhlen == hoff &&
4608 	    adapter->csum_thlen == thoff &&
4609 	    adapter->csum_mss == mss &&
4610 	    adapter->csum_pktlen == pktlen) {
4611 		*txd_upper = adapter->csum_txd_upper;
4612 		*txd_lower = adapter->csum_txd_lower;
4613 		return 0;
4614 	}
4615 	hlen = hoff + iphlen + thoff;
4616 
4617 	/*
4618 	 * Setup a new TSO context.
4619 	 */
4620 
4621 	curr_txd = adapter->next_avail_tx_desc;
4622 	TXD = (struct e1000_context_desc *)&adapter->tx_desc_base[curr_txd];
4623 
4624 	*txd_lower = E1000_TXD_CMD_DEXT |	/* Extended descr type */
4625 		     E1000_TXD_DTYP_D |		/* Data descr type */
4626 		     E1000_TXD_CMD_TSE;		/* Do TSE on this packet */
4627 
4628 	/* IP and/or TCP header checksum calculation and insertion. */
4629 	*txd_upper = (E1000_TXD_POPTS_IXSM | E1000_TXD_POPTS_TXSM) << 8;
4630 
4631 	/*
4632 	 * Start offset for header checksum calculation.
4633 	 * End offset for header checksum calculation.
4634 	 * Offset of place put the checksum.
4635 	 */
4636 	TXD->lower_setup.ip_fields.ipcss = hoff;
4637 	TXD->lower_setup.ip_fields.ipcse = htole16(hoff + iphlen - 1);
4638 	TXD->lower_setup.ip_fields.ipcso = hoff + offsetof(struct ip, ip_sum);
4639 
4640 	/*
4641 	 * Start offset for payload checksum calculation.
4642 	 * End offset for payload checksum calculation.
4643 	 * Offset of place to put the checksum.
4644 	 */
4645 	TXD->upper_setup.tcp_fields.tucss = hoff + iphlen;
4646 	TXD->upper_setup.tcp_fields.tucse = 0;
4647 	TXD->upper_setup.tcp_fields.tucso =
4648 	    hoff + iphlen + offsetof(struct tcphdr, th_sum);
4649 
4650 	/*
4651 	 * Payload size per packet w/o any headers.
4652 	 * Length of all headers up to payload.
4653 	 */
4654 	TXD->tcp_seg_setup.fields.mss = htole16(mss);
4655 	TXD->tcp_seg_setup.fields.hdr_len = hlen;
4656 	TXD->cmd_and_length = htole32(E1000_TXD_CMD_IFCS |
4657 				E1000_TXD_CMD_DEXT |	/* Extended descr */
4658 				E1000_TXD_CMD_TSE |	/* TSE context */
4659 				E1000_TXD_CMD_IP |	/* Do IP csum */
4660 				E1000_TXD_CMD_TCP |	/* Do TCP checksum */
4661 				(pktlen - hlen));	/* Total len */
4662 
4663 	/* Save the information for this TSO context */
4664 	adapter->csum_flags = CSUM_TSO;
4665 	adapter->csum_lhlen = hoff;
4666 	adapter->csum_iphlen = iphlen;
4667 	adapter->csum_thlen = thoff;
4668 	adapter->csum_mss = mss;
4669 	adapter->csum_pktlen = pktlen;
4670 	adapter->csum_txd_upper = *txd_upper;
4671 	adapter->csum_txd_lower = *txd_lower;
4672 
4673 	if (++curr_txd == adapter->num_tx_desc)
4674 		curr_txd = 0;
4675 
4676 	KKASSERT(adapter->num_tx_desc_avail > 0);
4677 	adapter->num_tx_desc_avail--;
4678 
4679 	adapter->next_avail_tx_desc = curr_txd;
4680 	return 1;
4681 }
4682 
4683 /*
4684  * Remove all descriptors from the TX ring.
4685  *
4686  * We want to clear all pending descriptors from the TX ring.  Zeroing
4687  * happens when the HW reads the regs.  We assign the ring itself as
4688  * the data of the next descriptor.  We don't care about the data we
4689  * are about to reset the HW.
4690  */
4691 static void
4692 em_flush_tx_ring(struct adapter *adapter)
4693 {
4694 	struct e1000_hw *hw = &adapter->hw;
4695 	struct e1000_tx_desc *txd;
4696 	uint32_t tctl;
4697 
4698 	tctl = E1000_READ_REG(hw, E1000_TCTL);
4699 	E1000_WRITE_REG(hw, E1000_TCTL, tctl | E1000_TCTL_EN);
4700 
4701 	txd = &adapter->tx_desc_base[adapter->next_avail_tx_desc++];
4702 	if (adapter->next_avail_tx_desc == adapter->num_tx_desc)
4703 		adapter->next_avail_tx_desc = 0;
4704 
4705 	/* Just use the ring as a dummy buffer addr */
4706 	txd->buffer_addr = adapter->txdma.dma_paddr;
4707 	txd->lower.data = htole32(E1000_TXD_CMD_IFCS | 512);
4708 	txd->upper.data = 0;
4709 
4710 	E1000_WRITE_REG(hw, E1000_TDT(0), adapter->next_avail_tx_desc);
4711 	usec_delay(250);
4712 }
4713 
4714 /*
4715  * Remove all descriptors from the RX ring.
4716  *
4717  * Mark all descriptors in the RX ring as consumed and disable the RX ring.
4718  */
4719 static void
4720 em_flush_rx_ring(struct adapter *adapter)
4721 {
4722 	struct e1000_hw	*hw = &adapter->hw;
4723 	uint32_t rctl, rxdctl;
4724 
4725 	rctl = E1000_READ_REG(hw, E1000_RCTL);
4726 	E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
4727 	E1000_WRITE_FLUSH(hw);
4728 	usec_delay(150);
4729 
4730 	rxdctl = E1000_READ_REG(hw, E1000_RXDCTL(0));
4731 	/* Zero the lower 14 bits (prefetch and host thresholds) */
4732 	rxdctl &= 0xffffc000;
4733 	/*
4734 	 * Update thresholds: prefetch threshold to 31, host threshold to 1
4735 	 * and make sure the granularity is "descriptors" and not "cache
4736 	 * lines".
4737 	 */
4738 	rxdctl |= (0x1F | (1 << 8) | E1000_RXDCTL_THRESH_UNIT_DESC);
4739 	E1000_WRITE_REG(hw, E1000_RXDCTL(0), rxdctl);
4740 
4741 	/* Momentarily enable the RX ring for the changes to take effect */
4742 	E1000_WRITE_REG(hw, E1000_RCTL, rctl | E1000_RCTL_EN);
4743 	E1000_WRITE_FLUSH(hw);
4744 	usec_delay(150);
4745 	E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
4746 }
4747 
4748 /*
4749  * Remove all descriptors from the descriptor rings.
4750  *
4751  * In i219, the descriptor rings must be emptied before resetting the HW
4752  * or before changing the device state to D3 during runtime (runtime PM).
4753  *
4754  * Failure to do this will cause the HW to enter a unit hang state which
4755  * can only be released by PCI reset on the device.
4756  */
4757 static void
4758 em_flush_txrx_ring(struct adapter *adapter)
4759 {
4760 	struct e1000_hw *hw = &adapter->hw;
4761 	device_t dev = adapter->dev;
4762 	uint16_t hang_state;
4763 	uint32_t fext_nvm11;
4764 
4765 	/*
4766 	 * First, disable MULR fix in FEXTNVM11.
4767 	 */
4768 	fext_nvm11 = E1000_READ_REG(hw, E1000_FEXTNVM11);
4769 	fext_nvm11 |= E1000_FEXTNVM11_DISABLE_MULR_FIX;
4770 	E1000_WRITE_REG(hw, E1000_FEXTNVM11, fext_nvm11);
4771 
4772 	/*
4773 	 * Do nothing if we're not in faulty state, or if the queue is
4774 	 * empty.
4775 	 */
4776 	hang_state = pci_read_config(dev, PCICFG_DESC_RING_STATUS, 2);
4777 	if ((hang_state & FLUSH_DESC_REQUIRED) &&
4778 	    E1000_READ_REG(hw, E1000_TDLEN(0)))
4779 		em_flush_tx_ring(adapter);
4780 
4781 	/*
4782 	 * Recheck, maybe the fault is caused by the RX ring.
4783 	 */
4784 	hang_state = pci_read_config(dev, PCICFG_DESC_RING_STATUS, 2);
4785 	if (hang_state & FLUSH_DESC_REQUIRED)
4786 		em_flush_rx_ring(adapter);
4787 }
4788