xref: /freebsd/sys/dev/e1000/if_em.c (revision 675be9115aae86ad6b3d877155d4fd7822892105)
1 /******************************************************************************
2 
3   Copyright (c) 2001-2011, Intel Corporation
4   All rights reserved.
5 
6   Redistribution and use in source and binary forms, with or without
7   modification, are permitted provided that the following conditions are met:
8 
9    1. Redistributions of source code must retain the above copyright notice,
10       this list of conditions and the following disclaimer.
11 
12    2. Redistributions in binary form must reproduce the above copyright
13       notice, this list of conditions and the following disclaimer in the
14       documentation and/or other materials provided with the distribution.
15 
16    3. Neither the name of the Intel Corporation nor the names of its
17       contributors may be used to endorse or promote products derived from
18       this software without specific prior written permission.
19 
20   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   POSSIBILITY OF SUCH DAMAGE.
31 
32 ******************************************************************************/
33 /*$FreeBSD$*/
34 
35 #ifdef HAVE_KERNEL_OPTION_HEADERS
36 #include "opt_device_polling.h"
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #endif
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #if __FreeBSD_version >= 800000
44 #include <sys/buf_ring.h>
45 #endif
46 #include <sys/bus.h>
47 #include <sys/endian.h>
48 #include <sys/kernel.h>
49 #include <sys/kthread.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/module.h>
53 #include <sys/rman.h>
54 #include <sys/socket.h>
55 #include <sys/sockio.h>
56 #include <sys/sysctl.h>
57 #include <sys/taskqueue.h>
58 #include <sys/eventhandler.h>
59 #include <machine/bus.h>
60 #include <machine/resource.h>
61 
62 #include <net/bpf.h>
63 #include <net/ethernet.h>
64 #include <net/if.h>
65 #include <net/if_arp.h>
66 #include <net/if_dl.h>
67 #include <net/if_media.h>
68 
69 #include <net/if_types.h>
70 #include <net/if_vlan_var.h>
71 
72 #include <netinet/in_systm.h>
73 #include <netinet/in.h>
74 #include <netinet/if_ether.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip6.h>
77 #include <netinet/tcp.h>
78 #include <netinet/udp.h>
79 
80 #include <machine/in_cksum.h>
81 #include <dev/led/led.h>
82 #include <dev/pci/pcivar.h>
83 #include <dev/pci/pcireg.h>
84 
85 #include "e1000_api.h"
86 #include "e1000_82571.h"
87 #include "if_em.h"
88 
89 /*********************************************************************
90  *  Set this to one to display debug statistics
91  *********************************************************************/
92 int	em_display_debug_stats = 0;
93 
94 /*********************************************************************
95  *  Driver version:
96  *********************************************************************/
97 char em_driver_version[] = "7.3.2";
98 
99 /*********************************************************************
100  *  PCI Device ID Table
101  *
102  *  Used by probe to select devices to load on
103  *  Last field stores an index into e1000_strings
104  *  Last entry must be all 0s
105  *
106  *  { Vendor ID, Device ID, SubVendor ID, SubDevice ID, String Index }
107  *********************************************************************/
108 
109 static em_vendor_info_t em_vendor_info_array[] =
110 {
111 	/* Intel(R) PRO/1000 Network Connection */
112 	{ 0x8086, E1000_DEV_ID_82571EB_COPPER,	PCI_ANY_ID, PCI_ANY_ID, 0},
113 	{ 0x8086, E1000_DEV_ID_82571EB_FIBER,	PCI_ANY_ID, PCI_ANY_ID, 0},
114 	{ 0x8086, E1000_DEV_ID_82571EB_SERDES,	PCI_ANY_ID, PCI_ANY_ID, 0},
115 	{ 0x8086, E1000_DEV_ID_82571EB_SERDES_DUAL,
116 						PCI_ANY_ID, PCI_ANY_ID, 0},
117 	{ 0x8086, E1000_DEV_ID_82571EB_SERDES_QUAD,
118 						PCI_ANY_ID, PCI_ANY_ID, 0},
119 	{ 0x8086, E1000_DEV_ID_82571EB_QUAD_COPPER,
120 						PCI_ANY_ID, PCI_ANY_ID, 0},
121 	{ 0x8086, E1000_DEV_ID_82571EB_QUAD_COPPER_LP,
122 						PCI_ANY_ID, PCI_ANY_ID, 0},
123 	{ 0x8086, E1000_DEV_ID_82571EB_QUAD_FIBER,
124 						PCI_ANY_ID, PCI_ANY_ID, 0},
125 	{ 0x8086, E1000_DEV_ID_82571PT_QUAD_COPPER,
126 						PCI_ANY_ID, PCI_ANY_ID, 0},
127 	{ 0x8086, E1000_DEV_ID_82572EI_COPPER,	PCI_ANY_ID, PCI_ANY_ID, 0},
128 	{ 0x8086, E1000_DEV_ID_82572EI_FIBER,	PCI_ANY_ID, PCI_ANY_ID, 0},
129 	{ 0x8086, E1000_DEV_ID_82572EI_SERDES,	PCI_ANY_ID, PCI_ANY_ID, 0},
130 	{ 0x8086, E1000_DEV_ID_82572EI,		PCI_ANY_ID, PCI_ANY_ID, 0},
131 
132 	{ 0x8086, E1000_DEV_ID_82573E,		PCI_ANY_ID, PCI_ANY_ID, 0},
133 	{ 0x8086, E1000_DEV_ID_82573E_IAMT,	PCI_ANY_ID, PCI_ANY_ID, 0},
134 	{ 0x8086, E1000_DEV_ID_82573L,		PCI_ANY_ID, PCI_ANY_ID, 0},
135 	{ 0x8086, E1000_DEV_ID_82583V,		PCI_ANY_ID, PCI_ANY_ID, 0},
136 	{ 0x8086, E1000_DEV_ID_80003ES2LAN_COPPER_SPT,
137 						PCI_ANY_ID, PCI_ANY_ID, 0},
138 	{ 0x8086, E1000_DEV_ID_80003ES2LAN_SERDES_SPT,
139 						PCI_ANY_ID, PCI_ANY_ID, 0},
140 	{ 0x8086, E1000_DEV_ID_80003ES2LAN_COPPER_DPT,
141 						PCI_ANY_ID, PCI_ANY_ID, 0},
142 	{ 0x8086, E1000_DEV_ID_80003ES2LAN_SERDES_DPT,
143 						PCI_ANY_ID, PCI_ANY_ID, 0},
144 	{ 0x8086, E1000_DEV_ID_ICH8_IGP_M_AMT,	PCI_ANY_ID, PCI_ANY_ID, 0},
145 	{ 0x8086, E1000_DEV_ID_ICH8_IGP_AMT,	PCI_ANY_ID, PCI_ANY_ID, 0},
146 	{ 0x8086, E1000_DEV_ID_ICH8_IGP_C,	PCI_ANY_ID, PCI_ANY_ID, 0},
147 	{ 0x8086, E1000_DEV_ID_ICH8_IFE,	PCI_ANY_ID, PCI_ANY_ID, 0},
148 	{ 0x8086, E1000_DEV_ID_ICH8_IFE_GT,	PCI_ANY_ID, PCI_ANY_ID, 0},
149 	{ 0x8086, E1000_DEV_ID_ICH8_IFE_G,	PCI_ANY_ID, PCI_ANY_ID, 0},
150 	{ 0x8086, E1000_DEV_ID_ICH8_IGP_M,	PCI_ANY_ID, PCI_ANY_ID, 0},
151 	{ 0x8086, E1000_DEV_ID_ICH8_82567V_3,	PCI_ANY_ID, PCI_ANY_ID, 0},
152 	{ 0x8086, E1000_DEV_ID_ICH9_IGP_M_AMT,	PCI_ANY_ID, PCI_ANY_ID, 0},
153 	{ 0x8086, E1000_DEV_ID_ICH9_IGP_AMT,	PCI_ANY_ID, PCI_ANY_ID, 0},
154 	{ 0x8086, E1000_DEV_ID_ICH9_IGP_C,	PCI_ANY_ID, PCI_ANY_ID, 0},
155 	{ 0x8086, E1000_DEV_ID_ICH9_IGP_M,	PCI_ANY_ID, PCI_ANY_ID, 0},
156 	{ 0x8086, E1000_DEV_ID_ICH9_IGP_M_V,	PCI_ANY_ID, PCI_ANY_ID, 0},
157 	{ 0x8086, E1000_DEV_ID_ICH9_IFE,	PCI_ANY_ID, PCI_ANY_ID, 0},
158 	{ 0x8086, E1000_DEV_ID_ICH9_IFE_GT,	PCI_ANY_ID, PCI_ANY_ID, 0},
159 	{ 0x8086, E1000_DEV_ID_ICH9_IFE_G,	PCI_ANY_ID, PCI_ANY_ID, 0},
160 	{ 0x8086, E1000_DEV_ID_ICH9_BM,		PCI_ANY_ID, PCI_ANY_ID, 0},
161 	{ 0x8086, E1000_DEV_ID_82574L,		PCI_ANY_ID, PCI_ANY_ID, 0},
162 	{ 0x8086, E1000_DEV_ID_82574LA,		PCI_ANY_ID, PCI_ANY_ID, 0},
163 	{ 0x8086, E1000_DEV_ID_ICH10_R_BM_LM,	PCI_ANY_ID, PCI_ANY_ID, 0},
164 	{ 0x8086, E1000_DEV_ID_ICH10_R_BM_LF,	PCI_ANY_ID, PCI_ANY_ID, 0},
165 	{ 0x8086, E1000_DEV_ID_ICH10_R_BM_V,	PCI_ANY_ID, PCI_ANY_ID, 0},
166 	{ 0x8086, E1000_DEV_ID_ICH10_D_BM_LM,	PCI_ANY_ID, PCI_ANY_ID, 0},
167 	{ 0x8086, E1000_DEV_ID_ICH10_D_BM_LF,	PCI_ANY_ID, PCI_ANY_ID, 0},
168 	{ 0x8086, E1000_DEV_ID_ICH10_D_BM_V,	PCI_ANY_ID, PCI_ANY_ID, 0},
169 	{ 0x8086, E1000_DEV_ID_PCH_M_HV_LM,	PCI_ANY_ID, PCI_ANY_ID, 0},
170 	{ 0x8086, E1000_DEV_ID_PCH_M_HV_LC,	PCI_ANY_ID, PCI_ANY_ID, 0},
171 	{ 0x8086, E1000_DEV_ID_PCH_D_HV_DM,	PCI_ANY_ID, PCI_ANY_ID, 0},
172 	{ 0x8086, E1000_DEV_ID_PCH_D_HV_DC,	PCI_ANY_ID, PCI_ANY_ID, 0},
173 	{ 0x8086, E1000_DEV_ID_PCH2_LV_LM,	PCI_ANY_ID, PCI_ANY_ID, 0},
174 	{ 0x8086, E1000_DEV_ID_PCH2_LV_V,	PCI_ANY_ID, PCI_ANY_ID, 0},
175 	/* required last entry */
176 	{ 0, 0, 0, 0, 0}
177 };
178 
179 /*********************************************************************
180  *  Table of branding strings for all supported NICs.
181  *********************************************************************/
182 
183 static char *em_strings[] = {
184 	"Intel(R) PRO/1000 Network Connection"
185 };
186 
187 /*********************************************************************
188  *  Function prototypes
189  *********************************************************************/
190 static int	em_probe(device_t);
191 static int	em_attach(device_t);
192 static int	em_detach(device_t);
193 static int	em_shutdown(device_t);
194 static int	em_suspend(device_t);
195 static int	em_resume(device_t);
196 static void	em_start(struct ifnet *);
197 static void	em_start_locked(struct ifnet *, struct tx_ring *);
198 #ifdef EM_MULTIQUEUE
199 static int	em_mq_start(struct ifnet *, struct mbuf *);
200 static int	em_mq_start_locked(struct ifnet *,
201 		    struct tx_ring *, struct mbuf *);
202 static void	em_qflush(struct ifnet *);
203 #endif
204 static int	em_ioctl(struct ifnet *, u_long, caddr_t);
205 static void	em_init(void *);
206 static void	em_init_locked(struct adapter *);
207 static void	em_stop(void *);
208 static void	em_media_status(struct ifnet *, struct ifmediareq *);
209 static int	em_media_change(struct ifnet *);
210 static void	em_identify_hardware(struct adapter *);
211 static int	em_allocate_pci_resources(struct adapter *);
212 static int	em_allocate_legacy(struct adapter *);
213 static int	em_allocate_msix(struct adapter *);
214 static int	em_allocate_queues(struct adapter *);
215 static int	em_setup_msix(struct adapter *);
216 static void	em_free_pci_resources(struct adapter *);
217 static void	em_local_timer(void *);
218 static void	em_reset(struct adapter *);
219 static int	em_setup_interface(device_t, struct adapter *);
220 
221 static void	em_setup_transmit_structures(struct adapter *);
222 static void	em_initialize_transmit_unit(struct adapter *);
223 static int	em_allocate_transmit_buffers(struct tx_ring *);
224 static void	em_free_transmit_structures(struct adapter *);
225 static void	em_free_transmit_buffers(struct tx_ring *);
226 
227 static int	em_setup_receive_structures(struct adapter *);
228 static int	em_allocate_receive_buffers(struct rx_ring *);
229 static void	em_initialize_receive_unit(struct adapter *);
230 static void	em_free_receive_structures(struct adapter *);
231 static void	em_free_receive_buffers(struct rx_ring *);
232 
233 static void	em_enable_intr(struct adapter *);
234 static void	em_disable_intr(struct adapter *);
235 static void	em_update_stats_counters(struct adapter *);
236 static void	em_add_hw_stats(struct adapter *adapter);
237 static bool	em_txeof(struct tx_ring *);
238 static bool	em_rxeof(struct rx_ring *, int, int *);
239 #ifndef __NO_STRICT_ALIGNMENT
240 static int	em_fixup_rx(struct rx_ring *);
241 #endif
242 static void	em_receive_checksum(struct e1000_rx_desc *, struct mbuf *);
243 static void	em_transmit_checksum_setup(struct tx_ring *, struct mbuf *, int,
244 		    struct ip *, u32 *, u32 *);
245 static void	em_tso_setup(struct tx_ring *, struct mbuf *, int, struct ip *,
246 		    struct tcphdr *, u32 *, u32 *);
247 static void	em_set_promisc(struct adapter *);
248 static void	em_disable_promisc(struct adapter *);
249 static void	em_set_multi(struct adapter *);
250 static void	em_update_link_status(struct adapter *);
251 static void	em_refresh_mbufs(struct rx_ring *, int);
252 static void	em_register_vlan(void *, struct ifnet *, u16);
253 static void	em_unregister_vlan(void *, struct ifnet *, u16);
254 static void	em_setup_vlan_hw_support(struct adapter *);
255 static int	em_xmit(struct tx_ring *, struct mbuf **);
256 static int	em_dma_malloc(struct adapter *, bus_size_t,
257 		    struct em_dma_alloc *, int);
258 static void	em_dma_free(struct adapter *, struct em_dma_alloc *);
259 static int	em_sysctl_nvm_info(SYSCTL_HANDLER_ARGS);
260 static void	em_print_nvm_info(struct adapter *);
261 static int	em_sysctl_debug_info(SYSCTL_HANDLER_ARGS);
262 static void	em_print_debug_info(struct adapter *);
263 static int 	em_is_valid_ether_addr(u8 *);
264 static int	em_sysctl_int_delay(SYSCTL_HANDLER_ARGS);
265 static void	em_add_int_delay_sysctl(struct adapter *, const char *,
266 		    const char *, struct em_int_delay_info *, int, int);
267 /* Management and WOL Support */
268 static void	em_init_manageability(struct adapter *);
269 static void	em_release_manageability(struct adapter *);
270 static void     em_get_hw_control(struct adapter *);
271 static void     em_release_hw_control(struct adapter *);
272 static void	em_get_wakeup(device_t);
273 static void     em_enable_wakeup(device_t);
274 static int	em_enable_phy_wakeup(struct adapter *);
275 static void	em_led_func(void *, int);
276 static void	em_disable_aspm(struct adapter *);
277 
278 static int	em_irq_fast(void *);
279 
280 /* MSIX handlers */
281 static void	em_msix_tx(void *);
282 static void	em_msix_rx(void *);
283 static void	em_msix_link(void *);
284 static void	em_handle_tx(void *context, int pending);
285 static void	em_handle_rx(void *context, int pending);
286 static void	em_handle_link(void *context, int pending);
287 
288 static void	em_set_sysctl_value(struct adapter *, const char *,
289 		    const char *, int *, int);
290 static int	em_set_flowcntl(SYSCTL_HANDLER_ARGS);
291 
292 static __inline void em_rx_discard(struct rx_ring *, int);
293 
294 #ifdef DEVICE_POLLING
295 static poll_handler_t em_poll;
296 #endif /* POLLING */
297 
298 /*********************************************************************
299  *  FreeBSD Device Interface Entry Points
300  *********************************************************************/
301 
302 static device_method_t em_methods[] = {
303 	/* Device interface */
304 	DEVMETHOD(device_probe, em_probe),
305 	DEVMETHOD(device_attach, em_attach),
306 	DEVMETHOD(device_detach, em_detach),
307 	DEVMETHOD(device_shutdown, em_shutdown),
308 	DEVMETHOD(device_suspend, em_suspend),
309 	DEVMETHOD(device_resume, em_resume),
310 	{0, 0}
311 };
312 
313 static driver_t em_driver = {
314 	"em", em_methods, sizeof(struct adapter),
315 };
316 
317 devclass_t em_devclass;
318 DRIVER_MODULE(em, pci, em_driver, em_devclass, 0, 0);
319 MODULE_DEPEND(em, pci, 1, 1, 1);
320 MODULE_DEPEND(em, ether, 1, 1, 1);
321 
322 /*********************************************************************
323  *  Tunable default values.
324  *********************************************************************/
325 
326 #define EM_TICKS_TO_USECS(ticks)	((1024 * (ticks) + 500) / 1000)
327 #define EM_USECS_TO_TICKS(usecs)	((1000 * (usecs) + 512) / 1024)
328 #define M_TSO_LEN			66
329 
330 /* Allow common code without TSO */
331 #ifndef CSUM_TSO
332 #define CSUM_TSO	0
333 #endif
334 
335 static SYSCTL_NODE(_hw, OID_AUTO, em, CTLFLAG_RD, 0, "EM driver parameters");
336 
337 static int em_tx_int_delay_dflt = EM_TICKS_TO_USECS(EM_TIDV);
338 static int em_rx_int_delay_dflt = EM_TICKS_TO_USECS(EM_RDTR);
339 TUNABLE_INT("hw.em.tx_int_delay", &em_tx_int_delay_dflt);
340 TUNABLE_INT("hw.em.rx_int_delay", &em_rx_int_delay_dflt);
341 SYSCTL_INT(_hw_em, OID_AUTO, tx_int_delay, CTLFLAG_RDTUN, &em_tx_int_delay_dflt,
342     0, "Default transmit interrupt delay in usecs");
343 SYSCTL_INT(_hw_em, OID_AUTO, rx_int_delay, CTLFLAG_RDTUN, &em_rx_int_delay_dflt,
344     0, "Default receive interrupt delay in usecs");
345 
346 static int em_tx_abs_int_delay_dflt = EM_TICKS_TO_USECS(EM_TADV);
347 static int em_rx_abs_int_delay_dflt = EM_TICKS_TO_USECS(EM_RADV);
348 TUNABLE_INT("hw.em.tx_abs_int_delay", &em_tx_abs_int_delay_dflt);
349 TUNABLE_INT("hw.em.rx_abs_int_delay", &em_rx_abs_int_delay_dflt);
350 SYSCTL_INT(_hw_em, OID_AUTO, tx_abs_int_delay, CTLFLAG_RDTUN,
351     &em_tx_abs_int_delay_dflt, 0,
352     "Default transmit interrupt delay limit in usecs");
353 SYSCTL_INT(_hw_em, OID_AUTO, rx_abs_int_delay, CTLFLAG_RDTUN,
354     &em_rx_abs_int_delay_dflt, 0,
355     "Default receive interrupt delay limit in usecs");
356 
357 static int em_rxd = EM_DEFAULT_RXD;
358 static int em_txd = EM_DEFAULT_TXD;
359 TUNABLE_INT("hw.em.rxd", &em_rxd);
360 TUNABLE_INT("hw.em.txd", &em_txd);
361 SYSCTL_INT(_hw_em, OID_AUTO, rxd, CTLFLAG_RDTUN, &em_rxd, 0,
362     "Number of receive descriptors per queue");
363 SYSCTL_INT(_hw_em, OID_AUTO, txd, CTLFLAG_RDTUN, &em_txd, 0,
364     "Number of transmit descriptors per queue");
365 
366 static int em_smart_pwr_down = FALSE;
367 TUNABLE_INT("hw.em.smart_pwr_down", &em_smart_pwr_down);
368 SYSCTL_INT(_hw_em, OID_AUTO, smart_pwr_down, CTLFLAG_RDTUN, &em_smart_pwr_down,
369     0, "Set to true to leave smart power down enabled on newer adapters");
370 
371 /* Controls whether promiscuous also shows bad packets */
372 static int em_debug_sbp = FALSE;
373 TUNABLE_INT("hw.em.sbp", &em_debug_sbp);
374 SYSCTL_INT(_hw_em, OID_AUTO, sbp, CTLFLAG_RDTUN, &em_debug_sbp, 0,
375     "Show bad packets in promiscuous mode");
376 
377 static int em_enable_msix = TRUE;
378 TUNABLE_INT("hw.em.enable_msix", &em_enable_msix);
379 SYSCTL_INT(_hw_em, OID_AUTO, enable_msix, CTLFLAG_RDTUN, &em_enable_msix, 0,
380     "Enable MSI-X interrupts");
381 
382 /* How many packets rxeof tries to clean at a time */
383 static int em_rx_process_limit = 100;
384 TUNABLE_INT("hw.em.rx_process_limit", &em_rx_process_limit);
385 SYSCTL_INT(_hw_em, OID_AUTO, rx_process_limit, CTLFLAG_RDTUN,
386     &em_rx_process_limit, 0,
387     "Maximum number of received packets to process "
388     "at a time, -1 means unlimited");
389 
390 /* Energy efficient ethernet - default to OFF */
391 static int eee_setting = 0;
392 TUNABLE_INT("hw.em.eee_setting", &eee_setting);
393 SYSCTL_INT(_hw_em, OID_AUTO, eee_setting, CTLFLAG_RDTUN, &eee_setting, 0,
394     "Enable Energy Efficient Ethernet");
395 
396 /* Global used in WOL setup with multiport cards */
397 static int global_quad_port_a = 0;
398 
399 #ifdef DEV_NETMAP	/* see ixgbe.c for details */
400 #include <dev/netmap/if_em_netmap.h>
401 #endif /* DEV_NETMAP */
402 
403 /*********************************************************************
404  *  Device identification routine
405  *
406  *  em_probe determines if the driver should be loaded on
407  *  adapter based on PCI vendor/device id of the adapter.
408  *
409  *  return BUS_PROBE_DEFAULT on success, positive on failure
410  *********************************************************************/
411 
412 static int
413 em_probe(device_t dev)
414 {
415 	char		adapter_name[60];
416 	u16		pci_vendor_id = 0;
417 	u16		pci_device_id = 0;
418 	u16		pci_subvendor_id = 0;
419 	u16		pci_subdevice_id = 0;
420 	em_vendor_info_t *ent;
421 
422 	INIT_DEBUGOUT("em_probe: begin");
423 
424 	pci_vendor_id = pci_get_vendor(dev);
425 	if (pci_vendor_id != EM_VENDOR_ID)
426 		return (ENXIO);
427 
428 	pci_device_id = pci_get_device(dev);
429 	pci_subvendor_id = pci_get_subvendor(dev);
430 	pci_subdevice_id = pci_get_subdevice(dev);
431 
432 	ent = em_vendor_info_array;
433 	while (ent->vendor_id != 0) {
434 		if ((pci_vendor_id == ent->vendor_id) &&
435 		    (pci_device_id == ent->device_id) &&
436 
437 		    ((pci_subvendor_id == ent->subvendor_id) ||
438 		    (ent->subvendor_id == PCI_ANY_ID)) &&
439 
440 		    ((pci_subdevice_id == ent->subdevice_id) ||
441 		    (ent->subdevice_id == PCI_ANY_ID))) {
442 			sprintf(adapter_name, "%s %s",
443 				em_strings[ent->index],
444 				em_driver_version);
445 			device_set_desc_copy(dev, adapter_name);
446 			return (BUS_PROBE_DEFAULT);
447 		}
448 		ent++;
449 	}
450 
451 	return (ENXIO);
452 }
453 
454 /*********************************************************************
455  *  Device initialization routine
456  *
457  *  The attach entry point is called when the driver is being loaded.
458  *  This routine identifies the type of hardware, allocates all resources
459  *  and initializes the hardware.
460  *
461  *  return 0 on success, positive on failure
462  *********************************************************************/
463 
464 static int
465 em_attach(device_t dev)
466 {
467 	struct adapter	*adapter;
468 	struct e1000_hw	*hw;
469 	int		error = 0;
470 
471 	INIT_DEBUGOUT("em_attach: begin");
472 
473 	if (resource_disabled("em", device_get_unit(dev))) {
474 		device_printf(dev, "Disabled by device hint\n");
475 		return (ENXIO);
476 	}
477 
478 	adapter = device_get_softc(dev);
479 	adapter->dev = adapter->osdep.dev = dev;
480 	hw = &adapter->hw;
481 	EM_CORE_LOCK_INIT(adapter, device_get_nameunit(dev));
482 
483 	/* SYSCTL stuff */
484 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
485 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
486 	    OID_AUTO, "nvm", CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
487 	    em_sysctl_nvm_info, "I", "NVM Information");
488 
489 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
490 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
491 	    OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
492 	    em_sysctl_debug_info, "I", "Debug Information");
493 
494 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
495 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
496 	    OID_AUTO, "fc", CTLTYPE_INT|CTLFLAG_RW, adapter, 0,
497 	    em_set_flowcntl, "I", "Flow Control");
498 
499 	callout_init_mtx(&adapter->timer, &adapter->core_mtx, 0);
500 
501 	/* Determine hardware and mac info */
502 	em_identify_hardware(adapter);
503 
504 	/* Setup PCI resources */
505 	if (em_allocate_pci_resources(adapter)) {
506 		device_printf(dev, "Allocation of PCI resources failed\n");
507 		error = ENXIO;
508 		goto err_pci;
509 	}
510 
511 	/*
512 	** For ICH8 and family we need to
513 	** map the flash memory, and this
514 	** must happen after the MAC is
515 	** identified
516 	*/
517 	if ((hw->mac.type == e1000_ich8lan) ||
518 	    (hw->mac.type == e1000_ich9lan) ||
519 	    (hw->mac.type == e1000_ich10lan) ||
520 	    (hw->mac.type == e1000_pchlan) ||
521 	    (hw->mac.type == e1000_pch2lan)) {
522 		int rid = EM_BAR_TYPE_FLASH;
523 		adapter->flash = bus_alloc_resource_any(dev,
524 		    SYS_RES_MEMORY, &rid, RF_ACTIVE);
525 		if (adapter->flash == NULL) {
526 			device_printf(dev, "Mapping of Flash failed\n");
527 			error = ENXIO;
528 			goto err_pci;
529 		}
530 		/* This is used in the shared code */
531 		hw->flash_address = (u8 *)adapter->flash;
532 		adapter->osdep.flash_bus_space_tag =
533 		    rman_get_bustag(adapter->flash);
534 		adapter->osdep.flash_bus_space_handle =
535 		    rman_get_bushandle(adapter->flash);
536 	}
537 
538 	/* Do Shared Code initialization */
539 	if (e1000_setup_init_funcs(hw, TRUE)) {
540 		device_printf(dev, "Setup of Shared code failed\n");
541 		error = ENXIO;
542 		goto err_pci;
543 	}
544 
545 	e1000_get_bus_info(hw);
546 
547 	/* Set up some sysctls for the tunable interrupt delays */
548 	em_add_int_delay_sysctl(adapter, "rx_int_delay",
549 	    "receive interrupt delay in usecs", &adapter->rx_int_delay,
550 	    E1000_REGISTER(hw, E1000_RDTR), em_rx_int_delay_dflt);
551 	em_add_int_delay_sysctl(adapter, "tx_int_delay",
552 	    "transmit interrupt delay in usecs", &adapter->tx_int_delay,
553 	    E1000_REGISTER(hw, E1000_TIDV), em_tx_int_delay_dflt);
554 	em_add_int_delay_sysctl(adapter, "rx_abs_int_delay",
555 	    "receive interrupt delay limit in usecs",
556 	    &adapter->rx_abs_int_delay,
557 	    E1000_REGISTER(hw, E1000_RADV),
558 	    em_rx_abs_int_delay_dflt);
559 	em_add_int_delay_sysctl(adapter, "tx_abs_int_delay",
560 	    "transmit interrupt delay limit in usecs",
561 	    &adapter->tx_abs_int_delay,
562 	    E1000_REGISTER(hw, E1000_TADV),
563 	    em_tx_abs_int_delay_dflt);
564 
565 	/* Sysctl for limiting the amount of work done in the taskqueue */
566 	em_set_sysctl_value(adapter, "rx_processing_limit",
567 	    "max number of rx packets to process", &adapter->rx_process_limit,
568 	    em_rx_process_limit);
569 
570 	/*
571 	 * Validate number of transmit and receive descriptors. It
572 	 * must not exceed hardware maximum, and must be multiple
573 	 * of E1000_DBA_ALIGN.
574 	 */
575 	if (((em_txd * sizeof(struct e1000_tx_desc)) % EM_DBA_ALIGN) != 0 ||
576 	    (em_txd > EM_MAX_TXD) || (em_txd < EM_MIN_TXD)) {
577 		device_printf(dev, "Using %d TX descriptors instead of %d!\n",
578 		    EM_DEFAULT_TXD, em_txd);
579 		adapter->num_tx_desc = EM_DEFAULT_TXD;
580 	} else
581 		adapter->num_tx_desc = em_txd;
582 
583 	if (((em_rxd * sizeof(struct e1000_rx_desc)) % EM_DBA_ALIGN) != 0 ||
584 	    (em_rxd > EM_MAX_RXD) || (em_rxd < EM_MIN_RXD)) {
585 		device_printf(dev, "Using %d RX descriptors instead of %d!\n",
586 		    EM_DEFAULT_RXD, em_rxd);
587 		adapter->num_rx_desc = EM_DEFAULT_RXD;
588 	} else
589 		adapter->num_rx_desc = em_rxd;
590 
591 	hw->mac.autoneg = DO_AUTO_NEG;
592 	hw->phy.autoneg_wait_to_complete = FALSE;
593 	hw->phy.autoneg_advertised = AUTONEG_ADV_DEFAULT;
594 
595 	/* Copper options */
596 	if (hw->phy.media_type == e1000_media_type_copper) {
597 		hw->phy.mdix = AUTO_ALL_MODES;
598 		hw->phy.disable_polarity_correction = FALSE;
599 		hw->phy.ms_type = EM_MASTER_SLAVE;
600 	}
601 
602 	/*
603 	 * Set the frame limits assuming
604 	 * standard ethernet sized frames.
605 	 */
606 	adapter->max_frame_size = ETHERMTU + ETHER_HDR_LEN + ETHERNET_FCS_SIZE;
607 	adapter->min_frame_size = ETH_ZLEN + ETHERNET_FCS_SIZE;
608 
609 	/*
610 	 * This controls when hardware reports transmit completion
611 	 * status.
612 	 */
613 	hw->mac.report_tx_early = 1;
614 
615 	/*
616 	** Get queue/ring memory
617 	*/
618 	if (em_allocate_queues(adapter)) {
619 		error = ENOMEM;
620 		goto err_pci;
621 	}
622 
623 	/* Allocate multicast array memory. */
624 	adapter->mta = malloc(sizeof(u8) * ETH_ADDR_LEN *
625 	    MAX_NUM_MULTICAST_ADDRESSES, M_DEVBUF, M_NOWAIT);
626 	if (adapter->mta == NULL) {
627 		device_printf(dev, "Can not allocate multicast setup array\n");
628 		error = ENOMEM;
629 		goto err_late;
630 	}
631 
632 	/* Check SOL/IDER usage */
633 	if (e1000_check_reset_block(hw))
634 		device_printf(dev, "PHY reset is blocked"
635 		    " due to SOL/IDER session.\n");
636 
637 	/* Sysctl for setting Energy Efficient Ethernet */
638 	em_set_sysctl_value(adapter, "eee_control",
639 	    "enable Energy Efficient Ethernet",
640 	    &hw->dev_spec.ich8lan.eee_disable, eee_setting);
641 
642 	/*
643 	** Start from a known state, this is
644 	** important in reading the nvm and
645 	** mac from that.
646 	*/
647 	e1000_reset_hw(hw);
648 
649 
650 	/* Make sure we have a good EEPROM before we read from it */
651 	if (e1000_validate_nvm_checksum(hw) < 0) {
652 		/*
653 		** Some PCI-E parts fail the first check due to
654 		** the link being in sleep state, call it again,
655 		** if it fails a second time its a real issue.
656 		*/
657 		if (e1000_validate_nvm_checksum(hw) < 0) {
658 			device_printf(dev,
659 			    "The EEPROM Checksum Is Not Valid\n");
660 			error = EIO;
661 			goto err_late;
662 		}
663 	}
664 
665 	/* Copy the permanent MAC address out of the EEPROM */
666 	if (e1000_read_mac_addr(hw) < 0) {
667 		device_printf(dev, "EEPROM read error while reading MAC"
668 		    " address\n");
669 		error = EIO;
670 		goto err_late;
671 	}
672 
673 	if (!em_is_valid_ether_addr(hw->mac.addr)) {
674 		device_printf(dev, "Invalid MAC address\n");
675 		error = EIO;
676 		goto err_late;
677 	}
678 
679 	/*
680 	**  Do interrupt configuration
681 	*/
682 	if (adapter->msix > 1) /* Do MSIX */
683 		error = em_allocate_msix(adapter);
684 	else  /* MSI or Legacy */
685 		error = em_allocate_legacy(adapter);
686 	if (error)
687 		goto err_late;
688 
689 	/*
690 	 * Get Wake-on-Lan and Management info for later use
691 	 */
692 	em_get_wakeup(dev);
693 
694 	/* Setup OS specific network interface */
695 	if (em_setup_interface(dev, adapter) != 0)
696 		goto err_late;
697 
698 	em_reset(adapter);
699 
700 	/* Initialize statistics */
701 	em_update_stats_counters(adapter);
702 
703 	hw->mac.get_link_status = 1;
704 	em_update_link_status(adapter);
705 
706 	/* Register for VLAN events */
707 	adapter->vlan_attach = EVENTHANDLER_REGISTER(vlan_config,
708 	    em_register_vlan, adapter, EVENTHANDLER_PRI_FIRST);
709 	adapter->vlan_detach = EVENTHANDLER_REGISTER(vlan_unconfig,
710 	    em_unregister_vlan, adapter, EVENTHANDLER_PRI_FIRST);
711 
712 	em_add_hw_stats(adapter);
713 
714 	/* Non-AMT based hardware can now take control from firmware */
715 	if (adapter->has_manage && !adapter->has_amt)
716 		em_get_hw_control(adapter);
717 
718 	/* Tell the stack that the interface is not active */
719 	adapter->ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
720 	adapter->ifp->if_drv_flags |= IFF_DRV_OACTIVE;
721 
722 	adapter->led_dev = led_create(em_led_func, adapter,
723 	    device_get_nameunit(dev));
724 #ifdef DEV_NETMAP
725 	em_netmap_attach(adapter);
726 #endif /* DEV_NETMAP */
727 
728 	INIT_DEBUGOUT("em_attach: end");
729 
730 	return (0);
731 
732 err_late:
733 	em_free_transmit_structures(adapter);
734 	em_free_receive_structures(adapter);
735 	em_release_hw_control(adapter);
736 	if (adapter->ifp != NULL)
737 		if_free(adapter->ifp);
738 err_pci:
739 	em_free_pci_resources(adapter);
740 	free(adapter->mta, M_DEVBUF);
741 	EM_CORE_LOCK_DESTROY(adapter);
742 
743 	return (error);
744 }
745 
746 /*********************************************************************
747  *  Device removal routine
748  *
749  *  The detach entry point is called when the driver is being removed.
750  *  This routine stops the adapter and deallocates all the resources
751  *  that were allocated for driver operation.
752  *
753  *  return 0 on success, positive on failure
754  *********************************************************************/
755 
756 static int
757 em_detach(device_t dev)
758 {
759 	struct adapter	*adapter = device_get_softc(dev);
760 	struct ifnet	*ifp = adapter->ifp;
761 
762 	INIT_DEBUGOUT("em_detach: begin");
763 
764 	/* Make sure VLANS are not using driver */
765 	if (adapter->ifp->if_vlantrunk != NULL) {
766 		device_printf(dev,"Vlan in use, detach first\n");
767 		return (EBUSY);
768 	}
769 
770 #ifdef DEVICE_POLLING
771 	if (ifp->if_capenable & IFCAP_POLLING)
772 		ether_poll_deregister(ifp);
773 #endif
774 
775 	if (adapter->led_dev != NULL)
776 		led_destroy(adapter->led_dev);
777 
778 	EM_CORE_LOCK(adapter);
779 	adapter->in_detach = 1;
780 	em_stop(adapter);
781 	EM_CORE_UNLOCK(adapter);
782 	EM_CORE_LOCK_DESTROY(adapter);
783 
784 	e1000_phy_hw_reset(&adapter->hw);
785 
786 	em_release_manageability(adapter);
787 	em_release_hw_control(adapter);
788 
789 	/* Unregister VLAN events */
790 	if (adapter->vlan_attach != NULL)
791 		EVENTHANDLER_DEREGISTER(vlan_config, adapter->vlan_attach);
792 	if (adapter->vlan_detach != NULL)
793 		EVENTHANDLER_DEREGISTER(vlan_unconfig, adapter->vlan_detach);
794 
795 	ether_ifdetach(adapter->ifp);
796 	callout_drain(&adapter->timer);
797 
798 #ifdef DEV_NETMAP
799 	netmap_detach(ifp);
800 #endif /* DEV_NETMAP */
801 
802 	em_free_pci_resources(adapter);
803 	bus_generic_detach(dev);
804 	if_free(ifp);
805 
806 	em_free_transmit_structures(adapter);
807 	em_free_receive_structures(adapter);
808 
809 	em_release_hw_control(adapter);
810 	free(adapter->mta, M_DEVBUF);
811 
812 	return (0);
813 }
814 
815 /*********************************************************************
816  *
817  *  Shutdown entry point
818  *
819  **********************************************************************/
820 
821 static int
822 em_shutdown(device_t dev)
823 {
824 	return em_suspend(dev);
825 }
826 
827 /*
828  * Suspend/resume device methods.
829  */
830 static int
831 em_suspend(device_t dev)
832 {
833 	struct adapter *adapter = device_get_softc(dev);
834 
835 	EM_CORE_LOCK(adapter);
836 
837         em_release_manageability(adapter);
838 	em_release_hw_control(adapter);
839 	em_enable_wakeup(dev);
840 
841 	EM_CORE_UNLOCK(adapter);
842 
843 	return bus_generic_suspend(dev);
844 }
845 
846 static int
847 em_resume(device_t dev)
848 {
849 	struct adapter *adapter = device_get_softc(dev);
850 	struct ifnet *ifp = adapter->ifp;
851 
852 	EM_CORE_LOCK(adapter);
853 	if (adapter->hw.mac.type == e1000_pch2lan)
854 		e1000_resume_workarounds_pchlan(&adapter->hw);
855 	em_init_locked(adapter);
856 	em_init_manageability(adapter);
857 	EM_CORE_UNLOCK(adapter);
858 	em_start(ifp);
859 
860 	return bus_generic_resume(dev);
861 }
862 
863 
864 #ifdef EM_MULTIQUEUE
865 /*********************************************************************
866  *  Multiqueue Transmit routines
867  *
868  *  em_mq_start is called by the stack to initiate a transmit.
869  *  however, if busy the driver can queue the request rather
870  *  than do an immediate send. It is this that is an advantage
871  *  in this driver, rather than also having multiple tx queues.
872  **********************************************************************/
873 static int
874 em_mq_start_locked(struct ifnet *ifp, struct tx_ring *txr, struct mbuf *m)
875 {
876 	struct adapter  *adapter = txr->adapter;
877         struct mbuf     *next;
878         int             err = 0, enq = 0;
879 
880 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
881 	    IFF_DRV_RUNNING || adapter->link_active == 0) {
882 		if (m != NULL)
883 			err = drbr_enqueue(ifp, txr->br, m);
884 		return (err);
885 	}
886 
887 	enq = 0;
888 	if (m == NULL) {
889 		next = drbr_dequeue(ifp, txr->br);
890 	} else if (drbr_needs_enqueue(ifp, txr->br)) {
891 		if ((err = drbr_enqueue(ifp, txr->br, m)) != 0)
892 			return (err);
893 		next = drbr_dequeue(ifp, txr->br);
894 	} else
895 		next = m;
896 
897 	/* Process the queue */
898 	while (next != NULL) {
899 		if ((err = em_xmit(txr, &next)) != 0) {
900                         if (next != NULL)
901                                 err = drbr_enqueue(ifp, txr->br, next);
902                         break;
903 		}
904 		enq++;
905 		drbr_stats_update(ifp, next->m_pkthdr.len, next->m_flags);
906 		ETHER_BPF_MTAP(ifp, next);
907 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
908                         break;
909 		next = drbr_dequeue(ifp, txr->br);
910 	}
911 
912 	if (enq > 0) {
913                 /* Set the watchdog */
914                 txr->queue_status = EM_QUEUE_WORKING;
915 		txr->watchdog_time = ticks;
916 	}
917 
918 	if (txr->tx_avail < EM_MAX_SCATTER)
919 		em_txeof(txr);
920 	if (txr->tx_avail < EM_MAX_SCATTER)
921 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
922 	return (err);
923 }
924 
925 /*
926 ** Multiqueue capable stack interface
927 */
928 static int
929 em_mq_start(struct ifnet *ifp, struct mbuf *m)
930 {
931 	struct adapter	*adapter = ifp->if_softc;
932 	struct tx_ring	*txr = adapter->tx_rings;
933 	int 		error;
934 
935 	if (EM_TX_TRYLOCK(txr)) {
936 		error = em_mq_start_locked(ifp, txr, m);
937 		EM_TX_UNLOCK(txr);
938 	} else
939 		error = drbr_enqueue(ifp, txr->br, m);
940 
941 	return (error);
942 }
943 
944 /*
945 ** Flush all ring buffers
946 */
947 static void
948 em_qflush(struct ifnet *ifp)
949 {
950 	struct adapter  *adapter = ifp->if_softc;
951 	struct tx_ring  *txr = adapter->tx_rings;
952 	struct mbuf     *m;
953 
954 	for (int i = 0; i < adapter->num_queues; i++, txr++) {
955 		EM_TX_LOCK(txr);
956 		while ((m = buf_ring_dequeue_sc(txr->br)) != NULL)
957 			m_freem(m);
958 		EM_TX_UNLOCK(txr);
959 	}
960 	if_qflush(ifp);
961 }
962 #endif /* EM_MULTIQUEUE */
963 
964 static void
965 em_start_locked(struct ifnet *ifp, struct tx_ring *txr)
966 {
967 	struct adapter	*adapter = ifp->if_softc;
968 	struct mbuf	*m_head;
969 
970 	EM_TX_LOCK_ASSERT(txr);
971 
972 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING|IFF_DRV_OACTIVE)) !=
973 	    IFF_DRV_RUNNING)
974 		return;
975 
976 	if (!adapter->link_active)
977 		return;
978 
979 	while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
980         	/* Call cleanup if number of TX descriptors low */
981 		if (txr->tx_avail <= EM_TX_CLEANUP_THRESHOLD)
982 			em_txeof(txr);
983 		if (txr->tx_avail < EM_MAX_SCATTER) {
984 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
985 			break;
986 		}
987                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
988 		if (m_head == NULL)
989 			break;
990 		/*
991 		 *  Encapsulation can modify our pointer, and or make it
992 		 *  NULL on failure.  In that event, we can't requeue.
993 		 */
994 		if (em_xmit(txr, &m_head)) {
995 			if (m_head == NULL)
996 				break;
997 			IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
998 			break;
999 		}
1000 
1001 		/* Send a copy of the frame to the BPF listener */
1002 		ETHER_BPF_MTAP(ifp, m_head);
1003 
1004 		/* Set timeout in case hardware has problems transmitting. */
1005 		txr->watchdog_time = ticks;
1006                 txr->queue_status = EM_QUEUE_WORKING;
1007 	}
1008 
1009 	return;
1010 }
1011 
1012 static void
1013 em_start(struct ifnet *ifp)
1014 {
1015 	struct adapter	*adapter = ifp->if_softc;
1016 	struct tx_ring	*txr = adapter->tx_rings;
1017 
1018 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1019 		EM_TX_LOCK(txr);
1020 		em_start_locked(ifp, txr);
1021 		EM_TX_UNLOCK(txr);
1022 	}
1023 	/*
1024 	** If we went inactive schedule
1025 	** a task to clean up.
1026 	*/
1027 	if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
1028 		taskqueue_enqueue(txr->tq, &txr->tx_task);
1029 	return;
1030 }
1031 
1032 /*********************************************************************
1033  *  Ioctl entry point
1034  *
1035  *  em_ioctl is called when the user wants to configure the
1036  *  interface.
1037  *
1038  *  return 0 on success, positive on failure
1039  **********************************************************************/
1040 
1041 static int
1042 em_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
1043 {
1044 	struct adapter	*adapter = ifp->if_softc;
1045 	struct ifreq	*ifr = (struct ifreq *)data;
1046 #if defined(INET) || defined(INET6)
1047 	struct ifaddr	*ifa = (struct ifaddr *)data;
1048 #endif
1049 	bool		avoid_reset = FALSE;
1050 	int		error = 0;
1051 
1052 	if (adapter->in_detach)
1053 		return (error);
1054 
1055 	switch (command) {
1056 	case SIOCSIFADDR:
1057 #ifdef INET
1058 		if (ifa->ifa_addr->sa_family == AF_INET)
1059 			avoid_reset = TRUE;
1060 #endif
1061 #ifdef INET6
1062 		if (ifa->ifa_addr->sa_family == AF_INET6)
1063 			avoid_reset = TRUE;
1064 #endif
1065 		/*
1066 		** Calling init results in link renegotiation,
1067 		** so we avoid doing it when possible.
1068 		*/
1069 		if (avoid_reset) {
1070 			ifp->if_flags |= IFF_UP;
1071 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1072 				em_init(adapter);
1073 #ifdef INET
1074 			if (!(ifp->if_flags & IFF_NOARP))
1075 				arp_ifinit(ifp, ifa);
1076 #endif
1077 		} else
1078 			error = ether_ioctl(ifp, command, data);
1079 		break;
1080 	case SIOCSIFMTU:
1081 	    {
1082 		int max_frame_size;
1083 
1084 		IOCTL_DEBUGOUT("ioctl rcv'd: SIOCSIFMTU (Set Interface MTU)");
1085 
1086 		EM_CORE_LOCK(adapter);
1087 		switch (adapter->hw.mac.type) {
1088 		case e1000_82571:
1089 		case e1000_82572:
1090 		case e1000_ich9lan:
1091 		case e1000_ich10lan:
1092 		case e1000_pch2lan:
1093 		case e1000_82574:
1094 		case e1000_82583:
1095 		case e1000_80003es2lan:	/* 9K Jumbo Frame size */
1096 			max_frame_size = 9234;
1097 			break;
1098 		case e1000_pchlan:
1099 			max_frame_size = 4096;
1100 			break;
1101 			/* Adapters that do not support jumbo frames */
1102 		case e1000_ich8lan:
1103 			max_frame_size = ETHER_MAX_LEN;
1104 			break;
1105 		default:
1106 			max_frame_size = MAX_JUMBO_FRAME_SIZE;
1107 		}
1108 		if (ifr->ifr_mtu > max_frame_size - ETHER_HDR_LEN -
1109 		    ETHER_CRC_LEN) {
1110 			EM_CORE_UNLOCK(adapter);
1111 			error = EINVAL;
1112 			break;
1113 		}
1114 
1115 		ifp->if_mtu = ifr->ifr_mtu;
1116 		adapter->max_frame_size =
1117 		    ifp->if_mtu + ETHER_HDR_LEN + ETHER_CRC_LEN;
1118 		em_init_locked(adapter);
1119 		EM_CORE_UNLOCK(adapter);
1120 		break;
1121 	    }
1122 	case SIOCSIFFLAGS:
1123 		IOCTL_DEBUGOUT("ioctl rcv'd:\
1124 		    SIOCSIFFLAGS (Set Interface Flags)");
1125 		EM_CORE_LOCK(adapter);
1126 		if (ifp->if_flags & IFF_UP) {
1127 			if ((ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1128 				if ((ifp->if_flags ^ adapter->if_flags) &
1129 				    (IFF_PROMISC | IFF_ALLMULTI)) {
1130 					em_disable_promisc(adapter);
1131 					em_set_promisc(adapter);
1132 				}
1133 			} else
1134 				em_init_locked(adapter);
1135 		} else
1136 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1137 				em_stop(adapter);
1138 		adapter->if_flags = ifp->if_flags;
1139 		EM_CORE_UNLOCK(adapter);
1140 		break;
1141 	case SIOCADDMULTI:
1142 	case SIOCDELMULTI:
1143 		IOCTL_DEBUGOUT("ioctl rcv'd: SIOC(ADD|DEL)MULTI");
1144 		if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1145 			EM_CORE_LOCK(adapter);
1146 			em_disable_intr(adapter);
1147 			em_set_multi(adapter);
1148 #ifdef DEVICE_POLLING
1149 			if (!(ifp->if_capenable & IFCAP_POLLING))
1150 #endif
1151 				em_enable_intr(adapter);
1152 			EM_CORE_UNLOCK(adapter);
1153 		}
1154 		break;
1155 	case SIOCSIFMEDIA:
1156 		/* Check SOL/IDER usage */
1157 		EM_CORE_LOCK(adapter);
1158 		if (e1000_check_reset_block(&adapter->hw)) {
1159 			EM_CORE_UNLOCK(adapter);
1160 			device_printf(adapter->dev, "Media change is"
1161 			    " blocked due to SOL/IDER session.\n");
1162 			break;
1163 		}
1164 		EM_CORE_UNLOCK(adapter);
1165 		/* falls thru */
1166 	case SIOCGIFMEDIA:
1167 		IOCTL_DEBUGOUT("ioctl rcv'd: \
1168 		    SIOCxIFMEDIA (Get/Set Interface Media)");
1169 		error = ifmedia_ioctl(ifp, ifr, &adapter->media, command);
1170 		break;
1171 	case SIOCSIFCAP:
1172 	    {
1173 		int mask, reinit;
1174 
1175 		IOCTL_DEBUGOUT("ioctl rcv'd: SIOCSIFCAP (Set Capabilities)");
1176 		reinit = 0;
1177 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1178 #ifdef DEVICE_POLLING
1179 		if (mask & IFCAP_POLLING) {
1180 			if (ifr->ifr_reqcap & IFCAP_POLLING) {
1181 				error = ether_poll_register(em_poll, ifp);
1182 				if (error)
1183 					return (error);
1184 				EM_CORE_LOCK(adapter);
1185 				em_disable_intr(adapter);
1186 				ifp->if_capenable |= IFCAP_POLLING;
1187 				EM_CORE_UNLOCK(adapter);
1188 			} else {
1189 				error = ether_poll_deregister(ifp);
1190 				/* Enable interrupt even in error case */
1191 				EM_CORE_LOCK(adapter);
1192 				em_enable_intr(adapter);
1193 				ifp->if_capenable &= ~IFCAP_POLLING;
1194 				EM_CORE_UNLOCK(adapter);
1195 			}
1196 		}
1197 #endif
1198 		if (mask & IFCAP_HWCSUM) {
1199 			ifp->if_capenable ^= IFCAP_HWCSUM;
1200 			reinit = 1;
1201 		}
1202 		if (mask & IFCAP_TSO4) {
1203 			ifp->if_capenable ^= IFCAP_TSO4;
1204 			reinit = 1;
1205 		}
1206 		if (mask & IFCAP_VLAN_HWTAGGING) {
1207 			ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1208 			reinit = 1;
1209 		}
1210 		if (mask & IFCAP_VLAN_HWFILTER) {
1211 			ifp->if_capenable ^= IFCAP_VLAN_HWFILTER;
1212 			reinit = 1;
1213 		}
1214 		if (mask & IFCAP_VLAN_HWTSO) {
1215 			ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1216 			reinit = 1;
1217 		}
1218 		if ((mask & IFCAP_WOL) &&
1219 		    (ifp->if_capabilities & IFCAP_WOL) != 0) {
1220 			if (mask & IFCAP_WOL_MCAST)
1221 				ifp->if_capenable ^= IFCAP_WOL_MCAST;
1222 			if (mask & IFCAP_WOL_MAGIC)
1223 				ifp->if_capenable ^= IFCAP_WOL_MAGIC;
1224 		}
1225 		if (reinit && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1226 			em_init(adapter);
1227 		VLAN_CAPABILITIES(ifp);
1228 		break;
1229 	    }
1230 
1231 	default:
1232 		error = ether_ioctl(ifp, command, data);
1233 		break;
1234 	}
1235 
1236 	return (error);
1237 }
1238 
1239 
1240 /*********************************************************************
1241  *  Init entry point
1242  *
1243  *  This routine is used in two ways. It is used by the stack as
1244  *  init entry point in network interface structure. It is also used
1245  *  by the driver as a hw/sw initialization routine to get to a
1246  *  consistent state.
1247  *
1248  *  return 0 on success, positive on failure
1249  **********************************************************************/
1250 
1251 static void
1252 em_init_locked(struct adapter *adapter)
1253 {
1254 	struct ifnet	*ifp = adapter->ifp;
1255 	device_t	dev = adapter->dev;
1256 
1257 	INIT_DEBUGOUT("em_init: begin");
1258 
1259 	EM_CORE_LOCK_ASSERT(adapter);
1260 
1261 	em_disable_intr(adapter);
1262 	callout_stop(&adapter->timer);
1263 
1264 	/* Get the latest mac address, User can use a LAA */
1265         bcopy(IF_LLADDR(adapter->ifp), adapter->hw.mac.addr,
1266               ETHER_ADDR_LEN);
1267 
1268 	/* Put the address into the Receive Address Array */
1269 	e1000_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
1270 
1271 	/*
1272 	 * With the 82571 adapter, RAR[0] may be overwritten
1273 	 * when the other port is reset, we make a duplicate
1274 	 * in RAR[14] for that eventuality, this assures
1275 	 * the interface continues to function.
1276 	 */
1277 	if (adapter->hw.mac.type == e1000_82571) {
1278 		e1000_set_laa_state_82571(&adapter->hw, TRUE);
1279 		e1000_rar_set(&adapter->hw, adapter->hw.mac.addr,
1280 		    E1000_RAR_ENTRIES - 1);
1281 	}
1282 
1283 	/* Initialize the hardware */
1284 	em_reset(adapter);
1285 	em_update_link_status(adapter);
1286 
1287 	/* Setup VLAN support, basic and offload if available */
1288 	E1000_WRITE_REG(&adapter->hw, E1000_VET, ETHERTYPE_VLAN);
1289 
1290 	/* Set hardware offload abilities */
1291 	ifp->if_hwassist = 0;
1292 	if (ifp->if_capenable & IFCAP_TXCSUM)
1293 		ifp->if_hwassist |= (CSUM_TCP | CSUM_UDP);
1294 	if (ifp->if_capenable & IFCAP_TSO4)
1295 		ifp->if_hwassist |= CSUM_TSO;
1296 
1297 	/* Configure for OS presence */
1298 	em_init_manageability(adapter);
1299 
1300 	/* Prepare transmit descriptors and buffers */
1301 	em_setup_transmit_structures(adapter);
1302 	em_initialize_transmit_unit(adapter);
1303 
1304 	/* Setup Multicast table */
1305 	em_set_multi(adapter);
1306 
1307 	/*
1308 	** Figure out the desired mbuf
1309 	** pool for doing jumbos
1310 	*/
1311 	if (adapter->max_frame_size <= 2048)
1312 		adapter->rx_mbuf_sz = MCLBYTES;
1313 	else if (adapter->max_frame_size <= 4096)
1314 		adapter->rx_mbuf_sz = MJUMPAGESIZE;
1315 	else
1316 		adapter->rx_mbuf_sz = MJUM9BYTES;
1317 
1318 	/* Prepare receive descriptors and buffers */
1319 	if (em_setup_receive_structures(adapter)) {
1320 		device_printf(dev, "Could not setup receive structures\n");
1321 		em_stop(adapter);
1322 		return;
1323 	}
1324 	em_initialize_receive_unit(adapter);
1325 
1326 	/* Use real VLAN Filter support? */
1327 	if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1328 		if (ifp->if_capenable & IFCAP_VLAN_HWFILTER)
1329 			/* Use real VLAN Filter support */
1330 			em_setup_vlan_hw_support(adapter);
1331 		else {
1332 			u32 ctrl;
1333 			ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
1334 			ctrl |= E1000_CTRL_VME;
1335 			E1000_WRITE_REG(&adapter->hw, E1000_CTRL, ctrl);
1336 		}
1337 	}
1338 
1339 	/* Don't lose promiscuous settings */
1340 	em_set_promisc(adapter);
1341 
1342 	/* Set the interface as ACTIVE */
1343 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1344 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1345 
1346 	callout_reset(&adapter->timer, hz, em_local_timer, adapter);
1347 	e1000_clear_hw_cntrs_base_generic(&adapter->hw);
1348 
1349 	/* MSI/X configuration for 82574 */
1350 	if (adapter->hw.mac.type == e1000_82574) {
1351 		int tmp;
1352 		tmp = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
1353 		tmp |= E1000_CTRL_EXT_PBA_CLR;
1354 		E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT, tmp);
1355 		/* Set the IVAR - interrupt vector routing. */
1356 		E1000_WRITE_REG(&adapter->hw, E1000_IVAR, adapter->ivars);
1357 	}
1358 
1359 #ifdef DEVICE_POLLING
1360 	/*
1361 	 * Only enable interrupts if we are not polling, make sure
1362 	 * they are off otherwise.
1363 	 */
1364 	if (ifp->if_capenable & IFCAP_POLLING)
1365 		em_disable_intr(adapter);
1366 	else
1367 #endif /* DEVICE_POLLING */
1368 		em_enable_intr(adapter);
1369 
1370 	/* AMT based hardware can now take control from firmware */
1371 	if (adapter->has_manage && adapter->has_amt)
1372 		em_get_hw_control(adapter);
1373 }
1374 
1375 static void
1376 em_init(void *arg)
1377 {
1378 	struct adapter *adapter = arg;
1379 
1380 	EM_CORE_LOCK(adapter);
1381 	em_init_locked(adapter);
1382 	EM_CORE_UNLOCK(adapter);
1383 }
1384 
1385 
1386 #ifdef DEVICE_POLLING
1387 /*********************************************************************
1388  *
1389  *  Legacy polling routine: note this only works with single queue
1390  *
1391  *********************************************************************/
1392 static int
1393 em_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1394 {
1395 	struct adapter *adapter = ifp->if_softc;
1396 	struct tx_ring	*txr = adapter->tx_rings;
1397 	struct rx_ring	*rxr = adapter->rx_rings;
1398 	u32		reg_icr;
1399 	int		rx_done;
1400 
1401 	EM_CORE_LOCK(adapter);
1402 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1403 		EM_CORE_UNLOCK(adapter);
1404 		return (0);
1405 	}
1406 
1407 	if (cmd == POLL_AND_CHECK_STATUS) {
1408 		reg_icr = E1000_READ_REG(&adapter->hw, E1000_ICR);
1409 		if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1410 			callout_stop(&adapter->timer);
1411 			adapter->hw.mac.get_link_status = 1;
1412 			em_update_link_status(adapter);
1413 			callout_reset(&adapter->timer, hz,
1414 			    em_local_timer, adapter);
1415 		}
1416 	}
1417 	EM_CORE_UNLOCK(adapter);
1418 
1419 	em_rxeof(rxr, count, &rx_done);
1420 
1421 	EM_TX_LOCK(txr);
1422 	em_txeof(txr);
1423 #ifdef EM_MULTIQUEUE
1424 	if (!drbr_empty(ifp, txr->br))
1425 		em_mq_start_locked(ifp, txr, NULL);
1426 #else
1427 	em_start_locked(ifp, txr);
1428 #endif
1429 	EM_TX_UNLOCK(txr);
1430 
1431 	return (rx_done);
1432 }
1433 #endif /* DEVICE_POLLING */
1434 
1435 
1436 /*********************************************************************
1437  *
1438  *  Fast Legacy/MSI Combined Interrupt Service routine
1439  *
1440  *********************************************************************/
1441 static int
1442 em_irq_fast(void *arg)
1443 {
1444 	struct adapter	*adapter = arg;
1445 	struct ifnet	*ifp;
1446 	u32		reg_icr;
1447 
1448 	ifp = adapter->ifp;
1449 
1450 	reg_icr = E1000_READ_REG(&adapter->hw, E1000_ICR);
1451 
1452 	/* Hot eject?  */
1453 	if (reg_icr == 0xffffffff)
1454 		return FILTER_STRAY;
1455 
1456 	/* Definitely not our interrupt.  */
1457 	if (reg_icr == 0x0)
1458 		return FILTER_STRAY;
1459 
1460 	/*
1461 	 * Starting with the 82571 chip, bit 31 should be used to
1462 	 * determine whether the interrupt belongs to us.
1463 	 */
1464 	if (adapter->hw.mac.type >= e1000_82571 &&
1465 	    (reg_icr & E1000_ICR_INT_ASSERTED) == 0)
1466 		return FILTER_STRAY;
1467 
1468 	em_disable_intr(adapter);
1469 	taskqueue_enqueue(adapter->tq, &adapter->que_task);
1470 
1471 	/* Link status change */
1472 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1473 		adapter->hw.mac.get_link_status = 1;
1474 		taskqueue_enqueue(taskqueue_fast, &adapter->link_task);
1475 	}
1476 
1477 	if (reg_icr & E1000_ICR_RXO)
1478 		adapter->rx_overruns++;
1479 	return FILTER_HANDLED;
1480 }
1481 
1482 /* Combined RX/TX handler, used by Legacy and MSI */
1483 static void
1484 em_handle_que(void *context, int pending)
1485 {
1486 	struct adapter	*adapter = context;
1487 	struct ifnet	*ifp = adapter->ifp;
1488 	struct tx_ring	*txr = adapter->tx_rings;
1489 	struct rx_ring	*rxr = adapter->rx_rings;
1490 
1491 
1492 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1493 		bool more = em_rxeof(rxr, adapter->rx_process_limit, NULL);
1494 		EM_TX_LOCK(txr);
1495 		em_txeof(txr);
1496 #ifdef EM_MULTIQUEUE
1497 		if (!drbr_empty(ifp, txr->br))
1498 			em_mq_start_locked(ifp, txr, NULL);
1499 #else
1500 		em_start_locked(ifp, txr);
1501 #endif
1502 		EM_TX_UNLOCK(txr);
1503 		if (more || (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
1504 			taskqueue_enqueue(adapter->tq, &adapter->que_task);
1505 			return;
1506 		}
1507 	}
1508 
1509 	em_enable_intr(adapter);
1510 	return;
1511 }
1512 
1513 
1514 /*********************************************************************
1515  *
1516  *  MSIX Interrupt Service Routines
1517  *
1518  **********************************************************************/
1519 static void
1520 em_msix_tx(void *arg)
1521 {
1522 	struct tx_ring *txr = arg;
1523 	struct adapter *adapter = txr->adapter;
1524 	bool		more;
1525 
1526 	++txr->tx_irq;
1527 	EM_TX_LOCK(txr);
1528 	more = em_txeof(txr);
1529 	EM_TX_UNLOCK(txr);
1530 	if (more)
1531 		taskqueue_enqueue(txr->tq, &txr->tx_task);
1532 	else
1533 		/* Reenable this interrupt */
1534 		E1000_WRITE_REG(&adapter->hw, E1000_IMS, txr->ims);
1535 	return;
1536 }
1537 
1538 /*********************************************************************
1539  *
1540  *  MSIX RX Interrupt Service routine
1541  *
1542  **********************************************************************/
1543 
1544 static void
1545 em_msix_rx(void *arg)
1546 {
1547 	struct rx_ring	*rxr = arg;
1548 	struct adapter	*adapter = rxr->adapter;
1549 	bool		more;
1550 
1551 	++rxr->rx_irq;
1552 	more = em_rxeof(rxr, adapter->rx_process_limit, NULL);
1553 	if (more)
1554 		taskqueue_enqueue(rxr->tq, &rxr->rx_task);
1555 	else
1556 		/* Reenable this interrupt */
1557 		E1000_WRITE_REG(&adapter->hw, E1000_IMS, rxr->ims);
1558 	return;
1559 }
1560 
1561 /*********************************************************************
1562  *
1563  *  MSIX Link Fast Interrupt Service routine
1564  *
1565  **********************************************************************/
1566 static void
1567 em_msix_link(void *arg)
1568 {
1569 	struct adapter	*adapter = arg;
1570 	u32		reg_icr;
1571 
1572 	++adapter->link_irq;
1573 	reg_icr = E1000_READ_REG(&adapter->hw, E1000_ICR);
1574 
1575 	if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1576 		adapter->hw.mac.get_link_status = 1;
1577 		em_handle_link(adapter, 0);
1578 	} else
1579 		E1000_WRITE_REG(&adapter->hw, E1000_IMS,
1580 		    EM_MSIX_LINK | E1000_IMS_LSC);
1581 	return;
1582 }
1583 
1584 static void
1585 em_handle_rx(void *context, int pending)
1586 {
1587 	struct rx_ring	*rxr = context;
1588 	struct adapter	*adapter = rxr->adapter;
1589         bool            more;
1590 
1591 	more = em_rxeof(rxr, adapter->rx_process_limit, NULL);
1592 	if (more)
1593 		taskqueue_enqueue(rxr->tq, &rxr->rx_task);
1594 	else
1595 		/* Reenable this interrupt */
1596 		E1000_WRITE_REG(&adapter->hw, E1000_IMS, rxr->ims);
1597 }
1598 
1599 static void
1600 em_handle_tx(void *context, int pending)
1601 {
1602 	struct tx_ring	*txr = context;
1603 	struct adapter	*adapter = txr->adapter;
1604 	struct ifnet	*ifp = adapter->ifp;
1605 
1606 	EM_TX_LOCK(txr);
1607 	em_txeof(txr);
1608 #ifdef EM_MULTIQUEUE
1609 	if (!drbr_empty(ifp, txr->br))
1610 		em_mq_start_locked(ifp, txr, NULL);
1611 #else
1612 	em_start_locked(ifp, txr);
1613 #endif
1614 	E1000_WRITE_REG(&adapter->hw, E1000_IMS, txr->ims);
1615 	EM_TX_UNLOCK(txr);
1616 }
1617 
1618 static void
1619 em_handle_link(void *context, int pending)
1620 {
1621 	struct adapter	*adapter = context;
1622 	struct ifnet *ifp = adapter->ifp;
1623 
1624 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1625 		return;
1626 
1627 	EM_CORE_LOCK(adapter);
1628 	callout_stop(&adapter->timer);
1629 	em_update_link_status(adapter);
1630 	callout_reset(&adapter->timer, hz, em_local_timer, adapter);
1631 	E1000_WRITE_REG(&adapter->hw, E1000_IMS,
1632 	    EM_MSIX_LINK | E1000_IMS_LSC);
1633 	EM_CORE_UNLOCK(adapter);
1634 }
1635 
1636 
1637 /*********************************************************************
1638  *
1639  *  Media Ioctl callback
1640  *
1641  *  This routine is called whenever the user queries the status of
1642  *  the interface using ifconfig.
1643  *
1644  **********************************************************************/
1645 static void
1646 em_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1647 {
1648 	struct adapter *adapter = ifp->if_softc;
1649 	u_char fiber_type = IFM_1000_SX;
1650 
1651 	INIT_DEBUGOUT("em_media_status: begin");
1652 
1653 	EM_CORE_LOCK(adapter);
1654 	em_update_link_status(adapter);
1655 
1656 	ifmr->ifm_status = IFM_AVALID;
1657 	ifmr->ifm_active = IFM_ETHER;
1658 
1659 	if (!adapter->link_active) {
1660 		EM_CORE_UNLOCK(adapter);
1661 		return;
1662 	}
1663 
1664 	ifmr->ifm_status |= IFM_ACTIVE;
1665 
1666 	if ((adapter->hw.phy.media_type == e1000_media_type_fiber) ||
1667 	    (adapter->hw.phy.media_type == e1000_media_type_internal_serdes)) {
1668 		ifmr->ifm_active |= fiber_type | IFM_FDX;
1669 	} else {
1670 		switch (adapter->link_speed) {
1671 		case 10:
1672 			ifmr->ifm_active |= IFM_10_T;
1673 			break;
1674 		case 100:
1675 			ifmr->ifm_active |= IFM_100_TX;
1676 			break;
1677 		case 1000:
1678 			ifmr->ifm_active |= IFM_1000_T;
1679 			break;
1680 		}
1681 		if (adapter->link_duplex == FULL_DUPLEX)
1682 			ifmr->ifm_active |= IFM_FDX;
1683 		else
1684 			ifmr->ifm_active |= IFM_HDX;
1685 	}
1686 	EM_CORE_UNLOCK(adapter);
1687 }
1688 
1689 /*********************************************************************
1690  *
1691  *  Media Ioctl callback
1692  *
1693  *  This routine is called when the user changes speed/duplex using
1694  *  media/mediopt option with ifconfig.
1695  *
1696  **********************************************************************/
1697 static int
1698 em_media_change(struct ifnet *ifp)
1699 {
1700 	struct adapter *adapter = ifp->if_softc;
1701 	struct ifmedia  *ifm = &adapter->media;
1702 
1703 	INIT_DEBUGOUT("em_media_change: begin");
1704 
1705 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1706 		return (EINVAL);
1707 
1708 	EM_CORE_LOCK(adapter);
1709 	switch (IFM_SUBTYPE(ifm->ifm_media)) {
1710 	case IFM_AUTO:
1711 		adapter->hw.mac.autoneg = DO_AUTO_NEG;
1712 		adapter->hw.phy.autoneg_advertised = AUTONEG_ADV_DEFAULT;
1713 		break;
1714 	case IFM_1000_LX:
1715 	case IFM_1000_SX:
1716 	case IFM_1000_T:
1717 		adapter->hw.mac.autoneg = DO_AUTO_NEG;
1718 		adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1719 		break;
1720 	case IFM_100_TX:
1721 		adapter->hw.mac.autoneg = FALSE;
1722 		adapter->hw.phy.autoneg_advertised = 0;
1723 		if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1724 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1725 		else
1726 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1727 		break;
1728 	case IFM_10_T:
1729 		adapter->hw.mac.autoneg = FALSE;
1730 		adapter->hw.phy.autoneg_advertised = 0;
1731 		if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1732 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1733 		else
1734 			adapter->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1735 		break;
1736 	default:
1737 		device_printf(adapter->dev, "Unsupported media type\n");
1738 	}
1739 
1740 	em_init_locked(adapter);
1741 	EM_CORE_UNLOCK(adapter);
1742 
1743 	return (0);
1744 }
1745 
1746 /*********************************************************************
1747  *
1748  *  This routine maps the mbufs to tx descriptors.
1749  *
1750  *  return 0 on success, positive on failure
1751  **********************************************************************/
1752 
1753 static int
1754 em_xmit(struct tx_ring *txr, struct mbuf **m_headp)
1755 {
1756 	struct adapter		*adapter = txr->adapter;
1757 	bus_dma_segment_t	segs[EM_MAX_SCATTER];
1758 	bus_dmamap_t		map;
1759 	struct em_buffer	*tx_buffer, *tx_buffer_mapped;
1760 	struct e1000_tx_desc	*ctxd = NULL;
1761 	struct mbuf		*m_head;
1762 	struct ether_header	*eh;
1763 	struct ip		*ip = NULL;
1764 	struct tcphdr		*tp = NULL;
1765 	u32			txd_upper, txd_lower, txd_used, txd_saved;
1766 	int			ip_off, poff;
1767 	int			nsegs, i, j, first, last = 0;
1768 	int			error, do_tso, tso_desc = 0, remap = 1;
1769 
1770 retry:
1771 	m_head = *m_headp;
1772 	txd_upper = txd_lower = txd_used = txd_saved = 0;
1773 	do_tso = ((m_head->m_pkthdr.csum_flags & CSUM_TSO) != 0);
1774 	ip_off = poff = 0;
1775 
1776 	/*
1777 	 * Intel recommends entire IP/TCP header length reside in a single
1778 	 * buffer. If multiple descriptors are used to describe the IP and
1779 	 * TCP header, each descriptor should describe one or more
1780 	 * complete headers; descriptors referencing only parts of headers
1781 	 * are not supported. If all layer headers are not coalesced into
1782 	 * a single buffer, each buffer should not cross a 4KB boundary,
1783 	 * or be larger than the maximum read request size.
1784 	 * Controller also requires modifing IP/TCP header to make TSO work
1785 	 * so we firstly get a writable mbuf chain then coalesce ethernet/
1786 	 * IP/TCP header into a single buffer to meet the requirement of
1787 	 * controller. This also simplifies IP/TCP/UDP checksum offloading
1788 	 * which also has similiar restrictions.
1789 	 */
1790 	if (do_tso || m_head->m_pkthdr.csum_flags & CSUM_OFFLOAD) {
1791 		if (do_tso || (m_head->m_next != NULL &&
1792 		    m_head->m_pkthdr.csum_flags & CSUM_OFFLOAD)) {
1793 			if (M_WRITABLE(*m_headp) == 0) {
1794 				m_head = m_dup(*m_headp, M_DONTWAIT);
1795 				m_freem(*m_headp);
1796 				if (m_head == NULL) {
1797 					*m_headp = NULL;
1798 					return (ENOBUFS);
1799 				}
1800 				*m_headp = m_head;
1801 			}
1802 		}
1803 		/*
1804 		 * XXX
1805 		 * Assume IPv4, we don't have TSO/checksum offload support
1806 		 * for IPv6 yet.
1807 		 */
1808 		ip_off = sizeof(struct ether_header);
1809 		m_head = m_pullup(m_head, ip_off);
1810 		if (m_head == NULL) {
1811 			*m_headp = NULL;
1812 			return (ENOBUFS);
1813 		}
1814 		eh = mtod(m_head, struct ether_header *);
1815 		if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
1816 			ip_off = sizeof(struct ether_vlan_header);
1817 			m_head = m_pullup(m_head, ip_off);
1818 			if (m_head == NULL) {
1819 				*m_headp = NULL;
1820 				return (ENOBUFS);
1821 			}
1822 		}
1823 		m_head = m_pullup(m_head, ip_off + sizeof(struct ip));
1824 		if (m_head == NULL) {
1825 			*m_headp = NULL;
1826 			return (ENOBUFS);
1827 		}
1828 		ip = (struct ip *)(mtod(m_head, char *) + ip_off);
1829 		poff = ip_off + (ip->ip_hl << 2);
1830 		if (do_tso) {
1831 			m_head = m_pullup(m_head, poff + sizeof(struct tcphdr));
1832 			if (m_head == NULL) {
1833 				*m_headp = NULL;
1834 				return (ENOBUFS);
1835 			}
1836 			tp = (struct tcphdr *)(mtod(m_head, char *) + poff);
1837 			/*
1838 			 * TSO workaround:
1839 			 *   pull 4 more bytes of data into it.
1840 			 */
1841 			m_head = m_pullup(m_head, poff + (tp->th_off << 2) + 4);
1842 			if (m_head == NULL) {
1843 				*m_headp = NULL;
1844 				return (ENOBUFS);
1845 			}
1846 			ip = (struct ip *)(mtod(m_head, char *) + ip_off);
1847 			ip->ip_len = 0;
1848 			ip->ip_sum = 0;
1849 			/*
1850 			 * The pseudo TCP checksum does not include TCP payload
1851 			 * length so driver should recompute the checksum here
1852 			 * what hardware expect to see. This is adherence of
1853 			 * Microsoft's Large Send specification.
1854 			 */
1855 			tp = (struct tcphdr *)(mtod(m_head, char *) + poff);
1856 			tp->th_sum = in_pseudo(ip->ip_src.s_addr,
1857 			    ip->ip_dst.s_addr, htons(IPPROTO_TCP));
1858 		} else if (m_head->m_pkthdr.csum_flags & CSUM_TCP) {
1859 			m_head = m_pullup(m_head, poff + sizeof(struct tcphdr));
1860 			if (m_head == NULL) {
1861 				*m_headp = NULL;
1862 				return (ENOBUFS);
1863 			}
1864 			tp = (struct tcphdr *)(mtod(m_head, char *) + poff);
1865 			m_head = m_pullup(m_head, poff + (tp->th_off << 2));
1866 			if (m_head == NULL) {
1867 				*m_headp = NULL;
1868 				return (ENOBUFS);
1869 			}
1870 			ip = (struct ip *)(mtod(m_head, char *) + ip_off);
1871 			tp = (struct tcphdr *)(mtod(m_head, char *) + poff);
1872 		} else if (m_head->m_pkthdr.csum_flags & CSUM_UDP) {
1873 			m_head = m_pullup(m_head, poff + sizeof(struct udphdr));
1874 			if (m_head == NULL) {
1875 				*m_headp = NULL;
1876 				return (ENOBUFS);
1877 			}
1878 			ip = (struct ip *)(mtod(m_head, char *) + ip_off);
1879 		}
1880 		*m_headp = m_head;
1881 	}
1882 
1883 	/*
1884 	 * Map the packet for DMA
1885 	 *
1886 	 * Capture the first descriptor index,
1887 	 * this descriptor will have the index
1888 	 * of the EOP which is the only one that
1889 	 * now gets a DONE bit writeback.
1890 	 */
1891 	first = txr->next_avail_desc;
1892 	tx_buffer = &txr->tx_buffers[first];
1893 	tx_buffer_mapped = tx_buffer;
1894 	map = tx_buffer->map;
1895 
1896 	error = bus_dmamap_load_mbuf_sg(txr->txtag, map,
1897 	    *m_headp, segs, &nsegs, BUS_DMA_NOWAIT);
1898 
1899 	/*
1900 	 * There are two types of errors we can (try) to handle:
1901 	 * - EFBIG means the mbuf chain was too long and bus_dma ran
1902 	 *   out of segments.  Defragment the mbuf chain and try again.
1903 	 * - ENOMEM means bus_dma could not obtain enough bounce buffers
1904 	 *   at this point in time.  Defer sending and try again later.
1905 	 * All other errors, in particular EINVAL, are fatal and prevent the
1906 	 * mbuf chain from ever going through.  Drop it and report error.
1907 	 */
1908 	if (error == EFBIG && remap) {
1909 		struct mbuf *m;
1910 
1911 		m = m_defrag(*m_headp, M_DONTWAIT);
1912 		if (m == NULL) {
1913 			adapter->mbuf_alloc_failed++;
1914 			m_freem(*m_headp);
1915 			*m_headp = NULL;
1916 			return (ENOBUFS);
1917 		}
1918 		*m_headp = m;
1919 
1920 		/* Try it again, but only once */
1921 		remap = 0;
1922 		goto retry;
1923 	} else if (error == ENOMEM) {
1924 		adapter->no_tx_dma_setup++;
1925 		return (error);
1926 	} else if (error != 0) {
1927 		adapter->no_tx_dma_setup++;
1928 		m_freem(*m_headp);
1929 		*m_headp = NULL;
1930 		return (error);
1931 	}
1932 
1933 	/*
1934 	 * TSO Hardware workaround, if this packet is not
1935 	 * TSO, and is only a single descriptor long, and
1936 	 * it follows a TSO burst, then we need to add a
1937 	 * sentinel descriptor to prevent premature writeback.
1938 	 */
1939 	if ((do_tso == 0) && (txr->tx_tso == TRUE)) {
1940 		if (nsegs == 1)
1941 			tso_desc = TRUE;
1942 		txr->tx_tso = FALSE;
1943 	}
1944 
1945         if (nsegs > (txr->tx_avail - 2)) {
1946                 txr->no_desc_avail++;
1947 		bus_dmamap_unload(txr->txtag, map);
1948 		return (ENOBUFS);
1949         }
1950 	m_head = *m_headp;
1951 
1952 	/* Do hardware assists */
1953 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1954 		em_tso_setup(txr, m_head, ip_off, ip, tp,
1955 		    &txd_upper, &txd_lower);
1956 		/* we need to make a final sentinel transmit desc */
1957 		tso_desc = TRUE;
1958 	} else if (m_head->m_pkthdr.csum_flags & CSUM_OFFLOAD)
1959 		em_transmit_checksum_setup(txr, m_head,
1960 		    ip_off, ip, &txd_upper, &txd_lower);
1961 
1962 	if (m_head->m_flags & M_VLANTAG) {
1963 		/* Set the vlan id. */
1964 		txd_upper |=
1965 		    (htole16(m_head->m_pkthdr.ether_vtag) << 16);
1966                 /* Tell hardware to add tag */
1967                 txd_lower |= htole32(E1000_TXD_CMD_VLE);
1968         }
1969 
1970 	i = txr->next_avail_desc;
1971 
1972 	/* Set up our transmit descriptors */
1973 	for (j = 0; j < nsegs; j++) {
1974 		bus_size_t seg_len;
1975 		bus_addr_t seg_addr;
1976 
1977 		tx_buffer = &txr->tx_buffers[i];
1978 		ctxd = &txr->tx_base[i];
1979 		seg_addr = segs[j].ds_addr;
1980 		seg_len  = segs[j].ds_len;
1981 		/*
1982 		** TSO Workaround:
1983 		** If this is the last descriptor, we want to
1984 		** split it so we have a small final sentinel
1985 		*/
1986 		if (tso_desc && (j == (nsegs -1)) && (seg_len > 8)) {
1987 			seg_len -= 4;
1988 			ctxd->buffer_addr = htole64(seg_addr);
1989 			ctxd->lower.data = htole32(
1990 			adapter->txd_cmd | txd_lower | seg_len);
1991 			ctxd->upper.data =
1992 			    htole32(txd_upper);
1993 			if (++i == adapter->num_tx_desc)
1994 				i = 0;
1995 			/* Now make the sentinel */
1996 			++txd_used; /* using an extra txd */
1997 			ctxd = &txr->tx_base[i];
1998 			tx_buffer = &txr->tx_buffers[i];
1999 			ctxd->buffer_addr =
2000 			    htole64(seg_addr + seg_len);
2001 			ctxd->lower.data = htole32(
2002 			adapter->txd_cmd | txd_lower | 4);
2003 			ctxd->upper.data =
2004 			    htole32(txd_upper);
2005 			last = i;
2006 			if (++i == adapter->num_tx_desc)
2007 				i = 0;
2008 		} else {
2009 			ctxd->buffer_addr = htole64(seg_addr);
2010 			ctxd->lower.data = htole32(
2011 			adapter->txd_cmd | txd_lower | seg_len);
2012 			ctxd->upper.data =
2013 			    htole32(txd_upper);
2014 			last = i;
2015 			if (++i == adapter->num_tx_desc)
2016 				i = 0;
2017 		}
2018 		tx_buffer->m_head = NULL;
2019 		tx_buffer->next_eop = -1;
2020 	}
2021 
2022 	txr->next_avail_desc = i;
2023 	txr->tx_avail -= nsegs;
2024 	if (tso_desc) /* TSO used an extra for sentinel */
2025 		txr->tx_avail -= txd_used;
2026 
2027         tx_buffer->m_head = m_head;
2028 	/*
2029 	** Here we swap the map so the last descriptor,
2030 	** which gets the completion interrupt has the
2031 	** real map, and the first descriptor gets the
2032 	** unused map from this descriptor.
2033 	*/
2034 	tx_buffer_mapped->map = tx_buffer->map;
2035 	tx_buffer->map = map;
2036         bus_dmamap_sync(txr->txtag, map, BUS_DMASYNC_PREWRITE);
2037 
2038         /*
2039          * Last Descriptor of Packet
2040 	 * needs End Of Packet (EOP)
2041 	 * and Report Status (RS)
2042          */
2043         ctxd->lower.data |=
2044 	    htole32(E1000_TXD_CMD_EOP | E1000_TXD_CMD_RS);
2045 	/*
2046 	 * Keep track in the first buffer which
2047 	 * descriptor will be written back
2048 	 */
2049 	tx_buffer = &txr->tx_buffers[first];
2050 	tx_buffer->next_eop = last;
2051 	/* Update the watchdog time early and often */
2052 	txr->watchdog_time = ticks;
2053 
2054 	/*
2055 	 * Advance the Transmit Descriptor Tail (TDT), this tells the E1000
2056 	 * that this frame is available to transmit.
2057 	 */
2058 	bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
2059 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2060 	E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), i);
2061 
2062 	return (0);
2063 }
2064 
2065 static void
2066 em_set_promisc(struct adapter *adapter)
2067 {
2068 	struct ifnet	*ifp = adapter->ifp;
2069 	u32		reg_rctl;
2070 
2071 	reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2072 
2073 	if (ifp->if_flags & IFF_PROMISC) {
2074 		reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
2075 		/* Turn this on if you want to see bad packets */
2076 		if (em_debug_sbp)
2077 			reg_rctl |= E1000_RCTL_SBP;
2078 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2079 	} else if (ifp->if_flags & IFF_ALLMULTI) {
2080 		reg_rctl |= E1000_RCTL_MPE;
2081 		reg_rctl &= ~E1000_RCTL_UPE;
2082 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2083 	}
2084 }
2085 
2086 static void
2087 em_disable_promisc(struct adapter *adapter)
2088 {
2089 	u32	reg_rctl;
2090 
2091 	reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2092 
2093 	reg_rctl &=  (~E1000_RCTL_UPE);
2094 	reg_rctl &=  (~E1000_RCTL_MPE);
2095 	reg_rctl &=  (~E1000_RCTL_SBP);
2096 	E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2097 }
2098 
2099 
2100 /*********************************************************************
2101  *  Multicast Update
2102  *
2103  *  This routine is called whenever multicast address list is updated.
2104  *
2105  **********************************************************************/
2106 
2107 static void
2108 em_set_multi(struct adapter *adapter)
2109 {
2110 	struct ifnet	*ifp = adapter->ifp;
2111 	struct ifmultiaddr *ifma;
2112 	u32 reg_rctl = 0;
2113 	u8  *mta; /* Multicast array memory */
2114 	int mcnt = 0;
2115 
2116 	IOCTL_DEBUGOUT("em_set_multi: begin");
2117 
2118 	mta = adapter->mta;
2119 	bzero(mta, sizeof(u8) * ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES);
2120 
2121 	if (adapter->hw.mac.type == e1000_82542 &&
2122 	    adapter->hw.revision_id == E1000_REVISION_2) {
2123 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2124 		if (adapter->hw.bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
2125 			e1000_pci_clear_mwi(&adapter->hw);
2126 		reg_rctl |= E1000_RCTL_RST;
2127 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2128 		msec_delay(5);
2129 	}
2130 
2131 #if __FreeBSD_version < 800000
2132 	IF_ADDR_LOCK(ifp);
2133 #else
2134 	if_maddr_rlock(ifp);
2135 #endif
2136 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2137 		if (ifma->ifma_addr->sa_family != AF_LINK)
2138 			continue;
2139 
2140 		if (mcnt == MAX_NUM_MULTICAST_ADDRESSES)
2141 			break;
2142 
2143 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
2144 		    &mta[mcnt * ETH_ADDR_LEN], ETH_ADDR_LEN);
2145 		mcnt++;
2146 	}
2147 #if __FreeBSD_version < 800000
2148 	IF_ADDR_UNLOCK(ifp);
2149 #else
2150 	if_maddr_runlock(ifp);
2151 #endif
2152 	if (mcnt >= MAX_NUM_MULTICAST_ADDRESSES) {
2153 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2154 		reg_rctl |= E1000_RCTL_MPE;
2155 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2156 	} else
2157 		e1000_update_mc_addr_list(&adapter->hw, mta, mcnt);
2158 
2159 	if (adapter->hw.mac.type == e1000_82542 &&
2160 	    adapter->hw.revision_id == E1000_REVISION_2) {
2161 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
2162 		reg_rctl &= ~E1000_RCTL_RST;
2163 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, reg_rctl);
2164 		msec_delay(5);
2165 		if (adapter->hw.bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
2166 			e1000_pci_set_mwi(&adapter->hw);
2167 	}
2168 }
2169 
2170 
2171 /*********************************************************************
2172  *  Timer routine
2173  *
2174  *  This routine checks for link status and updates statistics.
2175  *
2176  **********************************************************************/
2177 
2178 static void
2179 em_local_timer(void *arg)
2180 {
2181 	struct adapter	*adapter = arg;
2182 	struct ifnet	*ifp = adapter->ifp;
2183 	struct tx_ring	*txr = adapter->tx_rings;
2184 	struct rx_ring	*rxr = adapter->rx_rings;
2185 	u32		trigger;
2186 
2187 	EM_CORE_LOCK_ASSERT(adapter);
2188 
2189 	em_update_link_status(adapter);
2190 	em_update_stats_counters(adapter);
2191 
2192 	/* Reset LAA into RAR[0] on 82571 */
2193 	if ((adapter->hw.mac.type == e1000_82571) &&
2194 	    e1000_get_laa_state_82571(&adapter->hw))
2195 		e1000_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
2196 
2197 	/* Mask to use in the irq trigger */
2198 	if (adapter->msix_mem)
2199 		trigger = rxr->ims; /* RX for 82574 */
2200 	else
2201 		trigger = E1000_ICS_RXDMT0;
2202 
2203 	/*
2204 	** Check on the state of the TX queue(s), this
2205 	** can be done without the lock because its RO
2206 	** and the HUNG state will be static if set.
2207 	*/
2208 	for (int i = 0; i < adapter->num_queues; i++, txr++) {
2209 		if ((txr->queue_status == EM_QUEUE_HUNG) &&
2210 		    (adapter->pause_frames == 0))
2211 			goto hung;
2212 		/* Schedule a TX tasklet if needed */
2213 		if (txr->tx_avail <= EM_MAX_SCATTER)
2214 			taskqueue_enqueue(txr->tq, &txr->tx_task);
2215 	}
2216 
2217 	adapter->pause_frames = 0;
2218 	callout_reset(&adapter->timer, hz, em_local_timer, adapter);
2219 #ifndef DEVICE_POLLING
2220 	/* Trigger an RX interrupt to guarantee mbuf refresh */
2221 	E1000_WRITE_REG(&adapter->hw, E1000_ICS, trigger);
2222 #endif
2223 	return;
2224 hung:
2225 	/* Looks like we're hung */
2226 	device_printf(adapter->dev, "Watchdog timeout -- resetting\n");
2227 	device_printf(adapter->dev,
2228 	    "Queue(%d) tdh = %d, hw tdt = %d\n", txr->me,
2229 	    E1000_READ_REG(&adapter->hw, E1000_TDH(txr->me)),
2230 	    E1000_READ_REG(&adapter->hw, E1000_TDT(txr->me)));
2231 	device_printf(adapter->dev,"TX(%d) desc avail = %d,"
2232 	    "Next TX to Clean = %d\n",
2233 	    txr->me, txr->tx_avail, txr->next_to_clean);
2234 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2235 	adapter->watchdog_events++;
2236 	adapter->pause_frames = 0;
2237 	em_init_locked(adapter);
2238 }
2239 
2240 
2241 static void
2242 em_update_link_status(struct adapter *adapter)
2243 {
2244 	struct e1000_hw *hw = &adapter->hw;
2245 	struct ifnet *ifp = adapter->ifp;
2246 	device_t dev = adapter->dev;
2247 	struct tx_ring *txr = adapter->tx_rings;
2248 	u32 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 			/* Do the work to read phy */
2255 			e1000_check_for_link(hw);
2256 			link_check = !hw->mac.get_link_status;
2257 			if (link_check) /* ESB2 fix */
2258 				e1000_cfg_on_link_up(hw);
2259 		} else
2260 			link_check = TRUE;
2261 		break;
2262 	case e1000_media_type_fiber:
2263 		e1000_check_for_link(hw);
2264 		link_check = (E1000_READ_REG(hw, E1000_STATUS) &
2265                                  E1000_STATUS_LU);
2266 		break;
2267 	case e1000_media_type_internal_serdes:
2268 		e1000_check_for_link(hw);
2269 		link_check = adapter->hw.mac.serdes_has_link;
2270 		break;
2271 	default:
2272 	case e1000_media_type_unknown:
2273 		break;
2274 	}
2275 
2276 	/* Now check for a transition */
2277 	if (link_check && (adapter->link_active == 0)) {
2278 		e1000_get_speed_and_duplex(hw, &adapter->link_speed,
2279 		    &adapter->link_duplex);
2280 		/* Check if we must disable SPEED_MODE bit on PCI-E */
2281 		if ((adapter->link_speed != SPEED_1000) &&
2282 		    ((hw->mac.type == e1000_82571) ||
2283 		    (hw->mac.type == e1000_82572))) {
2284 			int tarc0;
2285 			tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
2286 			tarc0 &= ~SPEED_MODE_BIT;
2287 			E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
2288 		}
2289 		if (bootverbose)
2290 			device_printf(dev, "Link is up %d Mbps %s\n",
2291 			    adapter->link_speed,
2292 			    ((adapter->link_duplex == FULL_DUPLEX) ?
2293 			    "Full Duplex" : "Half Duplex"));
2294 		adapter->link_active = 1;
2295 		adapter->smartspeed = 0;
2296 		ifp->if_baudrate = adapter->link_speed * 1000000;
2297 		if_link_state_change(ifp, LINK_STATE_UP);
2298 	} else if (!link_check && (adapter->link_active == 1)) {
2299 		ifp->if_baudrate = adapter->link_speed = 0;
2300 		adapter->link_duplex = 0;
2301 		if (bootverbose)
2302 			device_printf(dev, "Link is Down\n");
2303 		adapter->link_active = 0;
2304 		/* Link down, disable watchdog */
2305 		for (int i = 0; i < adapter->num_queues; i++, txr++)
2306 			txr->queue_status = EM_QUEUE_IDLE;
2307 		if_link_state_change(ifp, LINK_STATE_DOWN);
2308 	}
2309 }
2310 
2311 /*********************************************************************
2312  *
2313  *  This routine disables all traffic on the adapter by issuing a
2314  *  global reset on the MAC and deallocates TX/RX buffers.
2315  *
2316  *  This routine should always be called with BOTH the CORE
2317  *  and TX locks.
2318  **********************************************************************/
2319 
2320 static void
2321 em_stop(void *arg)
2322 {
2323 	struct adapter	*adapter = arg;
2324 	struct ifnet	*ifp = adapter->ifp;
2325 	struct tx_ring	*txr = adapter->tx_rings;
2326 
2327 	EM_CORE_LOCK_ASSERT(adapter);
2328 
2329 	INIT_DEBUGOUT("em_stop: begin");
2330 
2331 	em_disable_intr(adapter);
2332 	callout_stop(&adapter->timer);
2333 
2334 	/* Tell the stack that the interface is no longer active */
2335 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2336 	ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2337 
2338         /* Unarm watchdog timer. */
2339 	for (int i = 0; i < adapter->num_queues; i++, txr++) {
2340 		EM_TX_LOCK(txr);
2341 		txr->queue_status = EM_QUEUE_IDLE;
2342 		EM_TX_UNLOCK(txr);
2343 	}
2344 
2345 	e1000_reset_hw(&adapter->hw);
2346 	E1000_WRITE_REG(&adapter->hw, E1000_WUC, 0);
2347 
2348 	e1000_led_off(&adapter->hw);
2349 	e1000_cleanup_led(&adapter->hw);
2350 }
2351 
2352 
2353 /*********************************************************************
2354  *
2355  *  Determine hardware revision.
2356  *
2357  **********************************************************************/
2358 static void
2359 em_identify_hardware(struct adapter *adapter)
2360 {
2361 	device_t dev = adapter->dev;
2362 
2363 	/* Make sure our PCI config space has the necessary stuff set */
2364 	adapter->hw.bus.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
2365 	if (!((adapter->hw.bus.pci_cmd_word & PCIM_CMD_BUSMASTEREN) &&
2366 	    (adapter->hw.bus.pci_cmd_word & PCIM_CMD_MEMEN))) {
2367 		device_printf(dev, "Memory Access and/or Bus Master bits "
2368 		    "were not set!\n");
2369 		adapter->hw.bus.pci_cmd_word |=
2370 		(PCIM_CMD_BUSMASTEREN | PCIM_CMD_MEMEN);
2371 		pci_write_config(dev, PCIR_COMMAND,
2372 		    adapter->hw.bus.pci_cmd_word, 2);
2373 	}
2374 
2375 	/* Save off the information about this board */
2376 	adapter->hw.vendor_id = pci_get_vendor(dev);
2377 	adapter->hw.device_id = pci_get_device(dev);
2378 	adapter->hw.revision_id = pci_read_config(dev, PCIR_REVID, 1);
2379 	adapter->hw.subsystem_vendor_id =
2380 	    pci_read_config(dev, PCIR_SUBVEND_0, 2);
2381 	adapter->hw.subsystem_device_id =
2382 	    pci_read_config(dev, PCIR_SUBDEV_0, 2);
2383 
2384 	/* Do Shared Code Init and Setup */
2385 	if (e1000_set_mac_type(&adapter->hw)) {
2386 		device_printf(dev, "Setup init failure\n");
2387 		return;
2388 	}
2389 }
2390 
2391 static int
2392 em_allocate_pci_resources(struct adapter *adapter)
2393 {
2394 	device_t	dev = adapter->dev;
2395 	int		rid;
2396 
2397 	rid = PCIR_BAR(0);
2398 	adapter->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
2399 	    &rid, RF_ACTIVE);
2400 	if (adapter->memory == NULL) {
2401 		device_printf(dev, "Unable to allocate bus resource: memory\n");
2402 		return (ENXIO);
2403 	}
2404 	adapter->osdep.mem_bus_space_tag =
2405 	    rman_get_bustag(adapter->memory);
2406 	adapter->osdep.mem_bus_space_handle =
2407 	    rman_get_bushandle(adapter->memory);
2408 	adapter->hw.hw_addr = (u8 *)&adapter->osdep.mem_bus_space_handle;
2409 
2410 	/* Default to a single queue */
2411 	adapter->num_queues = 1;
2412 
2413 	/*
2414 	 * Setup MSI/X or MSI if PCI Express
2415 	 */
2416 	adapter->msix = em_setup_msix(adapter);
2417 
2418 	adapter->hw.back = &adapter->osdep;
2419 
2420 	return (0);
2421 }
2422 
2423 /*********************************************************************
2424  *
2425  *  Setup the Legacy or MSI Interrupt handler
2426  *
2427  **********************************************************************/
2428 int
2429 em_allocate_legacy(struct adapter *adapter)
2430 {
2431 	device_t dev = adapter->dev;
2432 	struct tx_ring	*txr = adapter->tx_rings;
2433 	int error, rid = 0;
2434 
2435 	/* Manually turn off all interrupts */
2436 	E1000_WRITE_REG(&adapter->hw, E1000_IMC, 0xffffffff);
2437 
2438 	if (adapter->msix == 1) /* using MSI */
2439 		rid = 1;
2440 	/* We allocate a single interrupt resource */
2441 	adapter->res = bus_alloc_resource_any(dev,
2442 	    SYS_RES_IRQ, &rid, RF_SHAREABLE | RF_ACTIVE);
2443 	if (adapter->res == NULL) {
2444 		device_printf(dev, "Unable to allocate bus resource: "
2445 		    "interrupt\n");
2446 		return (ENXIO);
2447 	}
2448 
2449 	/*
2450 	 * Allocate a fast interrupt and the associated
2451 	 * deferred processing contexts.
2452 	 */
2453 	TASK_INIT(&adapter->que_task, 0, em_handle_que, adapter);
2454 	adapter->tq = taskqueue_create_fast("em_taskq", M_NOWAIT,
2455 	    taskqueue_thread_enqueue, &adapter->tq);
2456 	taskqueue_start_threads(&adapter->tq, 1, PI_NET, "%s que",
2457 	    device_get_nameunit(adapter->dev));
2458 	/* Use a TX only tasklet for local timer */
2459 	TASK_INIT(&txr->tx_task, 0, em_handle_tx, txr);
2460 	txr->tq = taskqueue_create_fast("em_txq", M_NOWAIT,
2461 	    taskqueue_thread_enqueue, &txr->tq);
2462 	taskqueue_start_threads(&txr->tq, 1, PI_NET, "%s txq",
2463 	    device_get_nameunit(adapter->dev));
2464 	TASK_INIT(&adapter->link_task, 0, em_handle_link, adapter);
2465 	if ((error = bus_setup_intr(dev, adapter->res, INTR_TYPE_NET,
2466 	    em_irq_fast, NULL, adapter, &adapter->tag)) != 0) {
2467 		device_printf(dev, "Failed to register fast interrupt "
2468 			    "handler: %d\n", error);
2469 		taskqueue_free(adapter->tq);
2470 		adapter->tq = NULL;
2471 		return (error);
2472 	}
2473 
2474 	return (0);
2475 }
2476 
2477 /*********************************************************************
2478  *
2479  *  Setup the MSIX Interrupt handlers
2480  *   This is not really Multiqueue, rather
2481  *   its just seperate interrupt vectors
2482  *   for TX, RX, and Link.
2483  *
2484  **********************************************************************/
2485 int
2486 em_allocate_msix(struct adapter *adapter)
2487 {
2488 	device_t	dev = adapter->dev;
2489 	struct		tx_ring *txr = adapter->tx_rings;
2490 	struct		rx_ring *rxr = adapter->rx_rings;
2491 	int		error, rid, vector = 0;
2492 
2493 
2494 	/* Make sure all interrupts are disabled */
2495 	E1000_WRITE_REG(&adapter->hw, E1000_IMC, 0xffffffff);
2496 
2497 	/* First set up ring resources */
2498 	for (int i = 0; i < adapter->num_queues; i++, txr++, rxr++) {
2499 
2500 		/* RX ring */
2501 		rid = vector + 1;
2502 
2503 		rxr->res = bus_alloc_resource_any(dev,
2504 		    SYS_RES_IRQ, &rid, RF_ACTIVE);
2505 		if (rxr->res == NULL) {
2506 			device_printf(dev,
2507 			    "Unable to allocate bus resource: "
2508 			    "RX MSIX Interrupt %d\n", i);
2509 			return (ENXIO);
2510 		}
2511 		if ((error = bus_setup_intr(dev, rxr->res,
2512 		    INTR_TYPE_NET | INTR_MPSAFE, NULL, em_msix_rx,
2513 		    rxr, &rxr->tag)) != 0) {
2514 			device_printf(dev, "Failed to register RX handler");
2515 			return (error);
2516 		}
2517 #if __FreeBSD_version >= 800504
2518 		bus_describe_intr(dev, rxr->res, rxr->tag, "rx %d", i);
2519 #endif
2520 		rxr->msix = vector++; /* NOTE increment vector for TX */
2521 		TASK_INIT(&rxr->rx_task, 0, em_handle_rx, rxr);
2522 		rxr->tq = taskqueue_create_fast("em_rxq", M_NOWAIT,
2523 		    taskqueue_thread_enqueue, &rxr->tq);
2524 		taskqueue_start_threads(&rxr->tq, 1, PI_NET, "%s rxq",
2525 		    device_get_nameunit(adapter->dev));
2526 		/*
2527 		** Set the bit to enable interrupt
2528 		** in E1000_IMS -- bits 20 and 21
2529 		** are for RX0 and RX1, note this has
2530 		** NOTHING to do with the MSIX vector
2531 		*/
2532 		rxr->ims = 1 << (20 + i);
2533 		adapter->ivars |= (8 | rxr->msix) << (i * 4);
2534 
2535 		/* TX ring */
2536 		rid = vector + 1;
2537 		txr->res = bus_alloc_resource_any(dev,
2538 		    SYS_RES_IRQ, &rid, RF_ACTIVE);
2539 		if (txr->res == NULL) {
2540 			device_printf(dev,
2541 			    "Unable to allocate bus resource: "
2542 			    "TX MSIX Interrupt %d\n", i);
2543 			return (ENXIO);
2544 		}
2545 		if ((error = bus_setup_intr(dev, txr->res,
2546 		    INTR_TYPE_NET | INTR_MPSAFE, NULL, em_msix_tx,
2547 		    txr, &txr->tag)) != 0) {
2548 			device_printf(dev, "Failed to register TX handler");
2549 			return (error);
2550 		}
2551 #if __FreeBSD_version >= 800504
2552 		bus_describe_intr(dev, txr->res, txr->tag, "tx %d", i);
2553 #endif
2554 		txr->msix = vector++; /* Increment vector for next pass */
2555 		TASK_INIT(&txr->tx_task, 0, em_handle_tx, txr);
2556 		txr->tq = taskqueue_create_fast("em_txq", M_NOWAIT,
2557 		    taskqueue_thread_enqueue, &txr->tq);
2558 		taskqueue_start_threads(&txr->tq, 1, PI_NET, "%s txq",
2559 		    device_get_nameunit(adapter->dev));
2560 		/*
2561 		** Set the bit to enable interrupt
2562 		** in E1000_IMS -- bits 22 and 23
2563 		** are for TX0 and TX1, note this has
2564 		** NOTHING to do with the MSIX vector
2565 		*/
2566 		txr->ims = 1 << (22 + i);
2567 		adapter->ivars |= (8 | txr->msix) << (8 + (i * 4));
2568 	}
2569 
2570 	/* Link interrupt */
2571 	++rid;
2572 	adapter->res = bus_alloc_resource_any(dev,
2573 	    SYS_RES_IRQ, &rid, RF_ACTIVE);
2574 	if (!adapter->res) {
2575 		device_printf(dev,"Unable to allocate "
2576 		    "bus resource: Link interrupt [%d]\n", rid);
2577 		return (ENXIO);
2578         }
2579 	/* Set the link handler function */
2580 	error = bus_setup_intr(dev, adapter->res,
2581 	    INTR_TYPE_NET | INTR_MPSAFE, NULL,
2582 	    em_msix_link, adapter, &adapter->tag);
2583 	if (error) {
2584 		adapter->res = NULL;
2585 		device_printf(dev, "Failed to register LINK handler");
2586 		return (error);
2587 	}
2588 #if __FreeBSD_version >= 800504
2589 		bus_describe_intr(dev, adapter->res, adapter->tag, "link");
2590 #endif
2591 	adapter->linkvec = vector;
2592 	adapter->ivars |=  (8 | vector) << 16;
2593 	adapter->ivars |= 0x80000000;
2594 
2595 	return (0);
2596 }
2597 
2598 
2599 static void
2600 em_free_pci_resources(struct adapter *adapter)
2601 {
2602 	device_t	dev = adapter->dev;
2603 	struct tx_ring	*txr;
2604 	struct rx_ring	*rxr;
2605 	int		rid;
2606 
2607 
2608 	/*
2609 	** Release all the queue interrupt resources:
2610 	*/
2611 	for (int i = 0; i < adapter->num_queues; i++) {
2612 		txr = &adapter->tx_rings[i];
2613 		rxr = &adapter->rx_rings[i];
2614 		/* an early abort? */
2615 		if ((txr == NULL) || (rxr == NULL))
2616 			break;
2617 		rid = txr->msix +1;
2618 		if (txr->tag != NULL) {
2619 			bus_teardown_intr(dev, txr->res, txr->tag);
2620 			txr->tag = NULL;
2621 		}
2622 		if (txr->res != NULL)
2623 			bus_release_resource(dev, SYS_RES_IRQ,
2624 			    rid, txr->res);
2625 		rid = rxr->msix +1;
2626 		if (rxr->tag != NULL) {
2627 			bus_teardown_intr(dev, rxr->res, rxr->tag);
2628 			rxr->tag = NULL;
2629 		}
2630 		if (rxr->res != NULL)
2631 			bus_release_resource(dev, SYS_RES_IRQ,
2632 			    rid, rxr->res);
2633 	}
2634 
2635         if (adapter->linkvec) /* we are doing MSIX */
2636                 rid = adapter->linkvec + 1;
2637         else
2638                 (adapter->msix != 0) ? (rid = 1):(rid = 0);
2639 
2640 	if (adapter->tag != NULL) {
2641 		bus_teardown_intr(dev, adapter->res, adapter->tag);
2642 		adapter->tag = NULL;
2643 	}
2644 
2645 	if (adapter->res != NULL)
2646 		bus_release_resource(dev, SYS_RES_IRQ, rid, adapter->res);
2647 
2648 
2649 	if (adapter->msix)
2650 		pci_release_msi(dev);
2651 
2652 	if (adapter->msix_mem != NULL)
2653 		bus_release_resource(dev, SYS_RES_MEMORY,
2654 		    PCIR_BAR(EM_MSIX_BAR), adapter->msix_mem);
2655 
2656 	if (adapter->memory != NULL)
2657 		bus_release_resource(dev, SYS_RES_MEMORY,
2658 		    PCIR_BAR(0), adapter->memory);
2659 
2660 	if (adapter->flash != NULL)
2661 		bus_release_resource(dev, SYS_RES_MEMORY,
2662 		    EM_FLASH, adapter->flash);
2663 }
2664 
2665 /*
2666  * Setup MSI or MSI/X
2667  */
2668 static int
2669 em_setup_msix(struct adapter *adapter)
2670 {
2671 	device_t dev = adapter->dev;
2672 	int val = 0;
2673 
2674 	/*
2675 	** Setup MSI/X for Hartwell: tests have shown
2676 	** use of two queues to be unstable, and to
2677 	** provide no great gain anyway, so we simply
2678 	** seperate the interrupts and use a single queue.
2679 	*/
2680 	if ((adapter->hw.mac.type == e1000_82574) &&
2681 	    (em_enable_msix == TRUE)) {
2682 		/* Map the MSIX BAR */
2683 		int rid = PCIR_BAR(EM_MSIX_BAR);
2684 		adapter->msix_mem = bus_alloc_resource_any(dev,
2685 		    SYS_RES_MEMORY, &rid, RF_ACTIVE);
2686        		if (!adapter->msix_mem) {
2687 			/* May not be enabled */
2688                		device_printf(adapter->dev,
2689 			    "Unable to map MSIX table \n");
2690 			goto msi;
2691        		}
2692 		val = pci_msix_count(dev);
2693 		/* We only need 3 vectors */
2694 		if (val > 3)
2695 			val = 3;
2696 		if ((val != 3) && (val != 5)) {
2697 			bus_release_resource(dev, SYS_RES_MEMORY,
2698 			    PCIR_BAR(EM_MSIX_BAR), adapter->msix_mem);
2699 			adapter->msix_mem = NULL;
2700                		device_printf(adapter->dev,
2701 			    "MSIX: incorrect vectors, using MSI\n");
2702 			goto msi;
2703 		}
2704 
2705 		if (pci_alloc_msix(dev, &val) == 0) {
2706 			device_printf(adapter->dev,
2707 			    "Using MSIX interrupts "
2708 			    "with %d vectors\n", val);
2709 		}
2710 
2711 		return (val);
2712 	}
2713 msi:
2714        	val = pci_msi_count(dev);
2715        	if (val == 1 && pci_alloc_msi(dev, &val) == 0) {
2716                	adapter->msix = 1;
2717                	device_printf(adapter->dev,"Using an MSI interrupt\n");
2718 		return (val);
2719 	}
2720 	/* Should only happen due to manual configuration */
2721 	device_printf(adapter->dev,"No MSI/MSIX using a Legacy IRQ\n");
2722 	return (0);
2723 }
2724 
2725 
2726 /*********************************************************************
2727  *
2728  *  Initialize the hardware to a configuration
2729  *  as specified by the adapter structure.
2730  *
2731  **********************************************************************/
2732 static void
2733 em_reset(struct adapter *adapter)
2734 {
2735 	device_t	dev = adapter->dev;
2736 	struct ifnet	*ifp = adapter->ifp;
2737 	struct e1000_hw	*hw = &adapter->hw;
2738 	u16		rx_buffer_size;
2739 	u32		pba;
2740 
2741 	INIT_DEBUGOUT("em_reset: begin");
2742 
2743 	/* Set up smart power down as default off on newer adapters. */
2744 	if (!em_smart_pwr_down && (hw->mac.type == e1000_82571 ||
2745 	    hw->mac.type == e1000_82572)) {
2746 		u16 phy_tmp = 0;
2747 
2748 		/* Speed up time to link by disabling smart power down. */
2749 		e1000_read_phy_reg(hw, IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
2750 		phy_tmp &= ~IGP02E1000_PM_SPD;
2751 		e1000_write_phy_reg(hw, IGP02E1000_PHY_POWER_MGMT, phy_tmp);
2752 	}
2753 
2754 	/*
2755 	 * Packet Buffer Allocation (PBA)
2756 	 * Writing PBA sets the receive portion of the buffer
2757 	 * the remainder is used for the transmit buffer.
2758 	 */
2759 	switch (hw->mac.type) {
2760 	/* Total Packet Buffer on these is 48K */
2761 	case e1000_82571:
2762 	case e1000_82572:
2763 	case e1000_80003es2lan:
2764 			pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
2765 		break;
2766 	case e1000_82573: /* 82573: Total Packet Buffer is 32K */
2767 			pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
2768 		break;
2769 	case e1000_82574:
2770 	case e1000_82583:
2771 			pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
2772 		break;
2773 	case e1000_ich8lan:
2774 		pba = E1000_PBA_8K;
2775 		break;
2776 	case e1000_ich9lan:
2777 	case e1000_ich10lan:
2778 		/* Boost Receive side for jumbo frames */
2779 		if (adapter->max_frame_size > 4096)
2780 			pba = E1000_PBA_14K;
2781 		else
2782 			pba = E1000_PBA_10K;
2783 		break;
2784 	case e1000_pchlan:
2785 	case e1000_pch2lan:
2786 		pba = E1000_PBA_26K;
2787 		break;
2788 	default:
2789 		if (adapter->max_frame_size > 8192)
2790 			pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
2791 		else
2792 			pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
2793 	}
2794 	E1000_WRITE_REG(&adapter->hw, E1000_PBA, pba);
2795 
2796 	/*
2797 	 * These parameters control the automatic generation (Tx) and
2798 	 * response (Rx) to Ethernet PAUSE frames.
2799 	 * - High water mark should allow for at least two frames to be
2800 	 *   received after sending an XOFF.
2801 	 * - Low water mark works best when it is very near the high water mark.
2802 	 *   This allows the receiver to restart by sending XON when it has
2803 	 *   drained a bit. Here we use an arbitary value of 1500 which will
2804 	 *   restart after one full frame is pulled from the buffer. There
2805 	 *   could be several smaller frames in the buffer and if so they will
2806 	 *   not trigger the XON until their total number reduces the buffer
2807 	 *   by 1500.
2808 	 * - The pause time is fairly large at 1000 x 512ns = 512 usec.
2809 	 */
2810 	rx_buffer_size = ((E1000_READ_REG(hw, E1000_PBA) & 0xffff) << 10 );
2811 	hw->fc.high_water = rx_buffer_size -
2812 	    roundup2(adapter->max_frame_size, 1024);
2813 	hw->fc.low_water = hw->fc.high_water - 1500;
2814 
2815 	if (adapter->fc) /* locally set flow control value? */
2816 		hw->fc.requested_mode = adapter->fc;
2817 	else
2818 		hw->fc.requested_mode = e1000_fc_full;
2819 
2820 	if (hw->mac.type == e1000_80003es2lan)
2821 		hw->fc.pause_time = 0xFFFF;
2822 	else
2823 		hw->fc.pause_time = EM_FC_PAUSE_TIME;
2824 
2825 	hw->fc.send_xon = TRUE;
2826 
2827 	/* Device specific overrides/settings */
2828 	switch (hw->mac.type) {
2829 	case e1000_pchlan:
2830 		/* Workaround: no TX flow ctrl for PCH */
2831                 hw->fc.requested_mode = e1000_fc_rx_pause;
2832 		hw->fc.pause_time = 0xFFFF; /* override */
2833 		if (ifp->if_mtu > ETHERMTU) {
2834 			hw->fc.high_water = 0x3500;
2835 			hw->fc.low_water = 0x1500;
2836 		} else {
2837 			hw->fc.high_water = 0x5000;
2838 			hw->fc.low_water = 0x3000;
2839 		}
2840 		hw->fc.refresh_time = 0x1000;
2841 		break;
2842 	case e1000_pch2lan:
2843 		hw->fc.high_water = 0x5C20;
2844 		hw->fc.low_water = 0x5048;
2845 		hw->fc.pause_time = 0x0650;
2846 		hw->fc.refresh_time = 0x0400;
2847 		/* Jumbos need adjusted PBA */
2848 		if (ifp->if_mtu > ETHERMTU)
2849 			E1000_WRITE_REG(hw, E1000_PBA, 12);
2850 		else
2851 			E1000_WRITE_REG(hw, E1000_PBA, 26);
2852 		break;
2853         case e1000_ich9lan:
2854         case e1000_ich10lan:
2855 		if (ifp->if_mtu > ETHERMTU) {
2856 			hw->fc.high_water = 0x2800;
2857 			hw->fc.low_water = hw->fc.high_water - 8;
2858 			break;
2859 		}
2860 		/* else fall thru */
2861 	default:
2862 		if (hw->mac.type == e1000_80003es2lan)
2863 			hw->fc.pause_time = 0xFFFF;
2864 		break;
2865 	}
2866 
2867 	/* Issue a global reset */
2868 	e1000_reset_hw(hw);
2869 	E1000_WRITE_REG(hw, E1000_WUC, 0);
2870 	em_disable_aspm(adapter);
2871 	/* and a re-init */
2872 	if (e1000_init_hw(hw) < 0) {
2873 		device_printf(dev, "Hardware Initialization Failed\n");
2874 		return;
2875 	}
2876 
2877 	E1000_WRITE_REG(hw, E1000_VET, ETHERTYPE_VLAN);
2878 	e1000_get_phy_info(hw);
2879 	e1000_check_for_link(hw);
2880 	return;
2881 }
2882 
2883 /*********************************************************************
2884  *
2885  *  Setup networking device structure and register an interface.
2886  *
2887  **********************************************************************/
2888 static int
2889 em_setup_interface(device_t dev, struct adapter *adapter)
2890 {
2891 	struct ifnet   *ifp;
2892 
2893 	INIT_DEBUGOUT("em_setup_interface: begin");
2894 
2895 	ifp = adapter->ifp = if_alloc(IFT_ETHER);
2896 	if (ifp == NULL) {
2897 		device_printf(dev, "can not allocate ifnet structure\n");
2898 		return (-1);
2899 	}
2900 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2901 	ifp->if_mtu = ETHERMTU;
2902 	ifp->if_init =  em_init;
2903 	ifp->if_softc = adapter;
2904 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2905 	ifp->if_ioctl = em_ioctl;
2906 	ifp->if_start = em_start;
2907 	IFQ_SET_MAXLEN(&ifp->if_snd, adapter->num_tx_desc - 1);
2908 	ifp->if_snd.ifq_drv_maxlen = adapter->num_tx_desc - 1;
2909 	IFQ_SET_READY(&ifp->if_snd);
2910 
2911 	ether_ifattach(ifp, adapter->hw.mac.addr);
2912 
2913 	ifp->if_capabilities = ifp->if_capenable = 0;
2914 
2915 #ifdef EM_MULTIQUEUE
2916 	/* Multiqueue stack interface */
2917 	ifp->if_transmit = em_mq_start;
2918 	ifp->if_qflush = em_qflush;
2919 #endif
2920 
2921 	ifp->if_capabilities |= IFCAP_HWCSUM | IFCAP_VLAN_HWCSUM;
2922 	ifp->if_capabilities |= IFCAP_TSO4;
2923 	/*
2924 	 * Tell the upper layer(s) we
2925 	 * support full VLAN capability
2926 	 */
2927 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
2928 	ifp->if_capabilities |= IFCAP_VLAN_HWTAGGING
2929 			     |  IFCAP_VLAN_HWTSO
2930 			     |  IFCAP_VLAN_MTU;
2931 	ifp->if_capenable = ifp->if_capabilities;
2932 
2933 	/*
2934 	** Don't turn this on by default, if vlans are
2935 	** created on another pseudo device (eg. lagg)
2936 	** then vlan events are not passed thru, breaking
2937 	** operation, but with HW FILTER off it works. If
2938 	** using vlans directly on the em driver you can
2939 	** enable this and get full hardware tag filtering.
2940 	*/
2941 	ifp->if_capabilities |= IFCAP_VLAN_HWFILTER;
2942 
2943 #ifdef DEVICE_POLLING
2944 	ifp->if_capabilities |= IFCAP_POLLING;
2945 #endif
2946 
2947 	/* Enable only WOL MAGIC by default */
2948 	if (adapter->wol) {
2949 		ifp->if_capabilities |= IFCAP_WOL;
2950 		ifp->if_capenable |= IFCAP_WOL_MAGIC;
2951 	}
2952 
2953 	/*
2954 	 * Specify the media types supported by this adapter and register
2955 	 * callbacks to update media and link information
2956 	 */
2957 	ifmedia_init(&adapter->media, IFM_IMASK,
2958 	    em_media_change, em_media_status);
2959 	if ((adapter->hw.phy.media_type == e1000_media_type_fiber) ||
2960 	    (adapter->hw.phy.media_type == e1000_media_type_internal_serdes)) {
2961 		u_char fiber_type = IFM_1000_SX;	/* default type */
2962 
2963 		ifmedia_add(&adapter->media, IFM_ETHER | fiber_type | IFM_FDX,
2964 			    0, NULL);
2965 		ifmedia_add(&adapter->media, IFM_ETHER | fiber_type, 0, NULL);
2966 	} else {
2967 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_10_T, 0, NULL);
2968 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_10_T | IFM_FDX,
2969 			    0, NULL);
2970 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_100_TX,
2971 			    0, NULL);
2972 		ifmedia_add(&adapter->media, IFM_ETHER | IFM_100_TX | IFM_FDX,
2973 			    0, NULL);
2974 		if (adapter->hw.phy.type != e1000_phy_ife) {
2975 			ifmedia_add(&adapter->media,
2976 				IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL);
2977 			ifmedia_add(&adapter->media,
2978 				IFM_ETHER | IFM_1000_T, 0, NULL);
2979 		}
2980 	}
2981 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2982 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
2983 	return (0);
2984 }
2985 
2986 
2987 /*
2988  * Manage DMA'able memory.
2989  */
2990 static void
2991 em_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2992 {
2993 	if (error)
2994 		return;
2995 	*(bus_addr_t *) arg = segs[0].ds_addr;
2996 }
2997 
2998 static int
2999 em_dma_malloc(struct adapter *adapter, bus_size_t size,
3000         struct em_dma_alloc *dma, int mapflags)
3001 {
3002 	int error;
3003 
3004 	error = bus_dma_tag_create(bus_get_dma_tag(adapter->dev), /* parent */
3005 				EM_DBA_ALIGN, 0,	/* alignment, bounds */
3006 				BUS_SPACE_MAXADDR,	/* lowaddr */
3007 				BUS_SPACE_MAXADDR,	/* highaddr */
3008 				NULL, NULL,		/* filter, filterarg */
3009 				size,			/* maxsize */
3010 				1,			/* nsegments */
3011 				size,			/* maxsegsize */
3012 				0,			/* flags */
3013 				NULL,			/* lockfunc */
3014 				NULL,			/* lockarg */
3015 				&dma->dma_tag);
3016 	if (error) {
3017 		device_printf(adapter->dev,
3018 		    "%s: bus_dma_tag_create failed: %d\n",
3019 		    __func__, error);
3020 		goto fail_0;
3021 	}
3022 
3023 	error = bus_dmamem_alloc(dma->dma_tag, (void**) &dma->dma_vaddr,
3024 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &dma->dma_map);
3025 	if (error) {
3026 		device_printf(adapter->dev,
3027 		    "%s: bus_dmamem_alloc(%ju) failed: %d\n",
3028 		    __func__, (uintmax_t)size, error);
3029 		goto fail_2;
3030 	}
3031 
3032 	dma->dma_paddr = 0;
3033 	error = bus_dmamap_load(dma->dma_tag, dma->dma_map, dma->dma_vaddr,
3034 	    size, em_dmamap_cb, &dma->dma_paddr, mapflags | BUS_DMA_NOWAIT);
3035 	if (error || dma->dma_paddr == 0) {
3036 		device_printf(adapter->dev,
3037 		    "%s: bus_dmamap_load failed: %d\n",
3038 		    __func__, error);
3039 		goto fail_3;
3040 	}
3041 
3042 	return (0);
3043 
3044 fail_3:
3045 	bus_dmamap_unload(dma->dma_tag, dma->dma_map);
3046 fail_2:
3047 	bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
3048 	bus_dma_tag_destroy(dma->dma_tag);
3049 fail_0:
3050 	dma->dma_map = NULL;
3051 	dma->dma_tag = NULL;
3052 
3053 	return (error);
3054 }
3055 
3056 static void
3057 em_dma_free(struct adapter *adapter, struct em_dma_alloc *dma)
3058 {
3059 	if (dma->dma_tag == NULL)
3060 		return;
3061 	if (dma->dma_map != NULL) {
3062 		bus_dmamap_sync(dma->dma_tag, dma->dma_map,
3063 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
3064 		bus_dmamap_unload(dma->dma_tag, dma->dma_map);
3065 		bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
3066 		dma->dma_map = NULL;
3067 	}
3068 	bus_dma_tag_destroy(dma->dma_tag);
3069 	dma->dma_tag = NULL;
3070 }
3071 
3072 
3073 /*********************************************************************
3074  *
3075  *  Allocate memory for the transmit and receive rings, and then
3076  *  the descriptors associated with each, called only once at attach.
3077  *
3078  **********************************************************************/
3079 static int
3080 em_allocate_queues(struct adapter *adapter)
3081 {
3082 	device_t		dev = adapter->dev;
3083 	struct tx_ring		*txr = NULL;
3084 	struct rx_ring		*rxr = NULL;
3085 	int rsize, tsize, error = E1000_SUCCESS;
3086 	int txconf = 0, rxconf = 0;
3087 
3088 
3089 	/* Allocate the TX ring struct memory */
3090 	if (!(adapter->tx_rings =
3091 	    (struct tx_ring *) malloc(sizeof(struct tx_ring) *
3092 	    adapter->num_queues, M_DEVBUF, M_NOWAIT | M_ZERO))) {
3093 		device_printf(dev, "Unable to allocate TX ring memory\n");
3094 		error = ENOMEM;
3095 		goto fail;
3096 	}
3097 
3098 	/* Now allocate the RX */
3099 	if (!(adapter->rx_rings =
3100 	    (struct rx_ring *) malloc(sizeof(struct rx_ring) *
3101 	    adapter->num_queues, M_DEVBUF, M_NOWAIT | M_ZERO))) {
3102 		device_printf(dev, "Unable to allocate RX ring memory\n");
3103 		error = ENOMEM;
3104 		goto rx_fail;
3105 	}
3106 
3107 	tsize = roundup2(adapter->num_tx_desc *
3108 	    sizeof(struct e1000_tx_desc), EM_DBA_ALIGN);
3109 	/*
3110 	 * Now set up the TX queues, txconf is needed to handle the
3111 	 * possibility that things fail midcourse and we need to
3112 	 * undo memory gracefully
3113 	 */
3114 	for (int i = 0; i < adapter->num_queues; i++, txconf++) {
3115 		/* Set up some basics */
3116 		txr = &adapter->tx_rings[i];
3117 		txr->adapter = adapter;
3118 		txr->me = i;
3119 
3120 		/* Initialize the TX lock */
3121 		snprintf(txr->mtx_name, sizeof(txr->mtx_name), "%s:tx(%d)",
3122 		    device_get_nameunit(dev), txr->me);
3123 		mtx_init(&txr->tx_mtx, txr->mtx_name, NULL, MTX_DEF);
3124 
3125 		if (em_dma_malloc(adapter, tsize,
3126 			&txr->txdma, BUS_DMA_NOWAIT)) {
3127 			device_printf(dev,
3128 			    "Unable to allocate TX Descriptor memory\n");
3129 			error = ENOMEM;
3130 			goto err_tx_desc;
3131 		}
3132 		txr->tx_base = (struct e1000_tx_desc *)txr->txdma.dma_vaddr;
3133 		bzero((void *)txr->tx_base, tsize);
3134 
3135         	if (em_allocate_transmit_buffers(txr)) {
3136 			device_printf(dev,
3137 			    "Critical Failure setting up transmit buffers\n");
3138 			error = ENOMEM;
3139 			goto err_tx_desc;
3140         	}
3141 #if __FreeBSD_version >= 800000
3142 		/* Allocate a buf ring */
3143 		txr->br = buf_ring_alloc(4096, M_DEVBUF,
3144 		    M_WAITOK, &txr->tx_mtx);
3145 #endif
3146 	}
3147 
3148 	/*
3149 	 * Next the RX queues...
3150 	 */
3151 	rsize = roundup2(adapter->num_rx_desc *
3152 	    sizeof(struct e1000_rx_desc), EM_DBA_ALIGN);
3153 	for (int i = 0; i < adapter->num_queues; i++, rxconf++) {
3154 		rxr = &adapter->rx_rings[i];
3155 		rxr->adapter = adapter;
3156 		rxr->me = i;
3157 
3158 		/* Initialize the RX lock */
3159 		snprintf(rxr->mtx_name, sizeof(rxr->mtx_name), "%s:rx(%d)",
3160 		    device_get_nameunit(dev), txr->me);
3161 		mtx_init(&rxr->rx_mtx, rxr->mtx_name, NULL, MTX_DEF);
3162 
3163 		if (em_dma_malloc(adapter, rsize,
3164 			&rxr->rxdma, BUS_DMA_NOWAIT)) {
3165 			device_printf(dev,
3166 			    "Unable to allocate RxDescriptor memory\n");
3167 			error = ENOMEM;
3168 			goto err_rx_desc;
3169 		}
3170 		rxr->rx_base = (struct e1000_rx_desc *)rxr->rxdma.dma_vaddr;
3171 		bzero((void *)rxr->rx_base, rsize);
3172 
3173         	/* Allocate receive buffers for the ring*/
3174 		if (em_allocate_receive_buffers(rxr)) {
3175 			device_printf(dev,
3176 			    "Critical Failure setting up receive buffers\n");
3177 			error = ENOMEM;
3178 			goto err_rx_desc;
3179 		}
3180 	}
3181 
3182 	return (0);
3183 
3184 err_rx_desc:
3185 	for (rxr = adapter->rx_rings; rxconf > 0; rxr++, rxconf--)
3186 		em_dma_free(adapter, &rxr->rxdma);
3187 err_tx_desc:
3188 	for (txr = adapter->tx_rings; txconf > 0; txr++, txconf--)
3189 		em_dma_free(adapter, &txr->txdma);
3190 	free(adapter->rx_rings, M_DEVBUF);
3191 rx_fail:
3192 #if __FreeBSD_version >= 800000
3193 	buf_ring_free(txr->br, M_DEVBUF);
3194 #endif
3195 	free(adapter->tx_rings, M_DEVBUF);
3196 fail:
3197 	return (error);
3198 }
3199 
3200 
3201 /*********************************************************************
3202  *
3203  *  Allocate memory for tx_buffer structures. The tx_buffer stores all
3204  *  the information needed to transmit a packet on the wire. This is
3205  *  called only once at attach, setup is done every reset.
3206  *
3207  **********************************************************************/
3208 static int
3209 em_allocate_transmit_buffers(struct tx_ring *txr)
3210 {
3211 	struct adapter *adapter = txr->adapter;
3212 	device_t dev = adapter->dev;
3213 	struct em_buffer *txbuf;
3214 	int error, i;
3215 
3216 	/*
3217 	 * Setup DMA descriptor areas.
3218 	 */
3219 	if ((error = bus_dma_tag_create(bus_get_dma_tag(dev),
3220 			       1, 0,			/* alignment, bounds */
3221 			       BUS_SPACE_MAXADDR,	/* lowaddr */
3222 			       BUS_SPACE_MAXADDR,	/* highaddr */
3223 			       NULL, NULL,		/* filter, filterarg */
3224 			       EM_TSO_SIZE,		/* maxsize */
3225 			       EM_MAX_SCATTER,		/* nsegments */
3226 			       PAGE_SIZE,		/* maxsegsize */
3227 			       0,			/* flags */
3228 			       NULL,			/* lockfunc */
3229 			       NULL,			/* lockfuncarg */
3230 			       &txr->txtag))) {
3231 		device_printf(dev,"Unable to allocate TX DMA tag\n");
3232 		goto fail;
3233 	}
3234 
3235 	if (!(txr->tx_buffers =
3236 	    (struct em_buffer *) malloc(sizeof(struct em_buffer) *
3237 	    adapter->num_tx_desc, M_DEVBUF, M_NOWAIT | M_ZERO))) {
3238 		device_printf(dev, "Unable to allocate tx_buffer memory\n");
3239 		error = ENOMEM;
3240 		goto fail;
3241 	}
3242 
3243         /* Create the descriptor buffer dma maps */
3244 	txbuf = txr->tx_buffers;
3245 	for (i = 0; i < adapter->num_tx_desc; i++, txbuf++) {
3246 		error = bus_dmamap_create(txr->txtag, 0, &txbuf->map);
3247 		if (error != 0) {
3248 			device_printf(dev, "Unable to create TX DMA map\n");
3249 			goto fail;
3250 		}
3251 	}
3252 
3253 	return 0;
3254 fail:
3255 	/* We free all, it handles case where we are in the middle */
3256 	em_free_transmit_structures(adapter);
3257 	return (error);
3258 }
3259 
3260 /*********************************************************************
3261  *
3262  *  Initialize a transmit ring.
3263  *
3264  **********************************************************************/
3265 static void
3266 em_setup_transmit_ring(struct tx_ring *txr)
3267 {
3268 	struct adapter *adapter = txr->adapter;
3269 	struct em_buffer *txbuf;
3270 	int i;
3271 #ifdef DEV_NETMAP
3272 	struct netmap_adapter *na = NA(adapter->ifp);
3273 	struct netmap_slot *slot;
3274 #endif /* DEV_NETMAP */
3275 
3276 	/* Clear the old descriptor contents */
3277 	EM_TX_LOCK(txr);
3278 #ifdef DEV_NETMAP
3279 	slot = netmap_reset(na, NR_TX, txr->me, 0);
3280 #endif /* DEV_NETMAP */
3281 
3282 	bzero((void *)txr->tx_base,
3283 	      (sizeof(struct e1000_tx_desc)) * adapter->num_tx_desc);
3284 	/* Reset indices */
3285 	txr->next_avail_desc = 0;
3286 	txr->next_to_clean = 0;
3287 
3288 	/* Free any existing tx buffers. */
3289         txbuf = txr->tx_buffers;
3290 	for (i = 0; i < adapter->num_tx_desc; i++, txbuf++) {
3291 		if (txbuf->m_head != NULL) {
3292 			bus_dmamap_sync(txr->txtag, txbuf->map,
3293 			    BUS_DMASYNC_POSTWRITE);
3294 			bus_dmamap_unload(txr->txtag, txbuf->map);
3295 			m_freem(txbuf->m_head);
3296 			txbuf->m_head = NULL;
3297 		}
3298 #ifdef DEV_NETMAP
3299 		if (slot) {
3300 			int si = i + na->tx_rings[txr->me].nkr_hwofs;
3301 			void *addr;
3302 
3303 			if (si >= na->num_tx_desc)
3304 				si -= na->num_tx_desc;
3305 			addr = NMB(slot + si);
3306 			txr->tx_base[i].buffer_addr =
3307 			    htole64(vtophys(addr));
3308 			/* reload the map for netmap mode */
3309 			netmap_load_map(txr->txtag,
3310 			    txbuf->map, addr, na->buff_size);
3311 		}
3312 #endif /* DEV_NETMAP */
3313 
3314 		/* clear the watch index */
3315 		txbuf->next_eop = -1;
3316         }
3317 
3318 	/* Set number of descriptors available */
3319 	txr->tx_avail = adapter->num_tx_desc;
3320 	txr->queue_status = EM_QUEUE_IDLE;
3321 
3322 	/* Clear checksum offload context. */
3323 	txr->last_hw_offload = 0;
3324 	txr->last_hw_ipcss = 0;
3325 	txr->last_hw_ipcso = 0;
3326 	txr->last_hw_tucss = 0;
3327 	txr->last_hw_tucso = 0;
3328 
3329 	bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
3330 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3331 	EM_TX_UNLOCK(txr);
3332 }
3333 
3334 /*********************************************************************
3335  *
3336  *  Initialize all transmit rings.
3337  *
3338  **********************************************************************/
3339 static void
3340 em_setup_transmit_structures(struct adapter *adapter)
3341 {
3342 	struct tx_ring *txr = adapter->tx_rings;
3343 
3344 	for (int i = 0; i < adapter->num_queues; i++, txr++)
3345 		em_setup_transmit_ring(txr);
3346 
3347 	return;
3348 }
3349 
3350 /*********************************************************************
3351  *
3352  *  Enable transmit unit.
3353  *
3354  **********************************************************************/
3355 static void
3356 em_initialize_transmit_unit(struct adapter *adapter)
3357 {
3358 	struct tx_ring	*txr = adapter->tx_rings;
3359 	struct e1000_hw	*hw = &adapter->hw;
3360 	u32	tctl, tarc, tipg = 0;
3361 
3362 	 INIT_DEBUGOUT("em_initialize_transmit_unit: begin");
3363 
3364 	for (int i = 0; i < adapter->num_queues; i++, txr++) {
3365 		u64 bus_addr = txr->txdma.dma_paddr;
3366 		/* Base and Len of TX Ring */
3367 		E1000_WRITE_REG(hw, E1000_TDLEN(i),
3368 	    	    adapter->num_tx_desc * sizeof(struct e1000_tx_desc));
3369 		E1000_WRITE_REG(hw, E1000_TDBAH(i),
3370 	    	    (u32)(bus_addr >> 32));
3371 		E1000_WRITE_REG(hw, E1000_TDBAL(i),
3372 	    	    (u32)bus_addr);
3373 		/* Init the HEAD/TAIL indices */
3374 		E1000_WRITE_REG(hw, E1000_TDT(i), 0);
3375 		E1000_WRITE_REG(hw, E1000_TDH(i), 0);
3376 
3377 		HW_DEBUGOUT2("Base = %x, Length = %x\n",
3378 		    E1000_READ_REG(&adapter->hw, E1000_TDBAL(i)),
3379 		    E1000_READ_REG(&adapter->hw, E1000_TDLEN(i)));
3380 
3381 		txr->queue_status = EM_QUEUE_IDLE;
3382 	}
3383 
3384 	/* Set the default values for the Tx Inter Packet Gap timer */
3385 	switch (adapter->hw.mac.type) {
3386 	case e1000_80003es2lan:
3387 		tipg = DEFAULT_82543_TIPG_IPGR1;
3388 		tipg |= DEFAULT_80003ES2LAN_TIPG_IPGR2 <<
3389 		    E1000_TIPG_IPGR2_SHIFT;
3390 		break;
3391 	default:
3392 		if ((adapter->hw.phy.media_type == e1000_media_type_fiber) ||
3393 		    (adapter->hw.phy.media_type ==
3394 		    e1000_media_type_internal_serdes))
3395 			tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
3396 		else
3397 			tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
3398 		tipg |= DEFAULT_82543_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
3399 		tipg |= DEFAULT_82543_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
3400 	}
3401 
3402 	E1000_WRITE_REG(&adapter->hw, E1000_TIPG, tipg);
3403 	E1000_WRITE_REG(&adapter->hw, E1000_TIDV, adapter->tx_int_delay.value);
3404 
3405 	if(adapter->hw.mac.type >= e1000_82540)
3406 		E1000_WRITE_REG(&adapter->hw, E1000_TADV,
3407 		    adapter->tx_abs_int_delay.value);
3408 
3409 	if ((adapter->hw.mac.type == e1000_82571) ||
3410 	    (adapter->hw.mac.type == e1000_82572)) {
3411 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
3412 		tarc |= SPEED_MODE_BIT;
3413 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), tarc);
3414 	} else if (adapter->hw.mac.type == e1000_80003es2lan) {
3415 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
3416 		tarc |= 1;
3417 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), tarc);
3418 		tarc = E1000_READ_REG(&adapter->hw, E1000_TARC(1));
3419 		tarc |= 1;
3420 		E1000_WRITE_REG(&adapter->hw, E1000_TARC(1), tarc);
3421 	}
3422 
3423 	adapter->txd_cmd = E1000_TXD_CMD_IFCS;
3424 	if (adapter->tx_int_delay.value > 0)
3425 		adapter->txd_cmd |= E1000_TXD_CMD_IDE;
3426 
3427 	/* Program the Transmit Control Register */
3428 	tctl = E1000_READ_REG(&adapter->hw, E1000_TCTL);
3429 	tctl &= ~E1000_TCTL_CT;
3430 	tctl |= (E1000_TCTL_PSP | E1000_TCTL_RTLC | E1000_TCTL_EN |
3431 		   (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT));
3432 
3433 	if (adapter->hw.mac.type >= e1000_82571)
3434 		tctl |= E1000_TCTL_MULR;
3435 
3436 	/* This write will effectively turn on the transmit unit. */
3437 	E1000_WRITE_REG(&adapter->hw, E1000_TCTL, tctl);
3438 
3439 }
3440 
3441 
3442 /*********************************************************************
3443  *
3444  *  Free all transmit rings.
3445  *
3446  **********************************************************************/
3447 static void
3448 em_free_transmit_structures(struct adapter *adapter)
3449 {
3450 	struct tx_ring *txr = adapter->tx_rings;
3451 
3452 	for (int i = 0; i < adapter->num_queues; i++, txr++) {
3453 		EM_TX_LOCK(txr);
3454 		em_free_transmit_buffers(txr);
3455 		em_dma_free(adapter, &txr->txdma);
3456 		EM_TX_UNLOCK(txr);
3457 		EM_TX_LOCK_DESTROY(txr);
3458 	}
3459 
3460 	free(adapter->tx_rings, M_DEVBUF);
3461 }
3462 
3463 /*********************************************************************
3464  *
3465  *  Free transmit ring related data structures.
3466  *
3467  **********************************************************************/
3468 static void
3469 em_free_transmit_buffers(struct tx_ring *txr)
3470 {
3471 	struct adapter		*adapter = txr->adapter;
3472 	struct em_buffer	*txbuf;
3473 
3474 	INIT_DEBUGOUT("free_transmit_ring: begin");
3475 
3476 	if (txr->tx_buffers == NULL)
3477 		return;
3478 
3479 	for (int i = 0; i < adapter->num_tx_desc; i++) {
3480 		txbuf = &txr->tx_buffers[i];
3481 		if (txbuf->m_head != NULL) {
3482 			bus_dmamap_sync(txr->txtag, txbuf->map,
3483 			    BUS_DMASYNC_POSTWRITE);
3484 			bus_dmamap_unload(txr->txtag,
3485 			    txbuf->map);
3486 			m_freem(txbuf->m_head);
3487 			txbuf->m_head = NULL;
3488 			if (txbuf->map != NULL) {
3489 				bus_dmamap_destroy(txr->txtag,
3490 				    txbuf->map);
3491 				txbuf->map = NULL;
3492 			}
3493 		} else if (txbuf->map != NULL) {
3494 			bus_dmamap_unload(txr->txtag,
3495 			    txbuf->map);
3496 			bus_dmamap_destroy(txr->txtag,
3497 			    txbuf->map);
3498 			txbuf->map = NULL;
3499 		}
3500 	}
3501 #if __FreeBSD_version >= 800000
3502 	if (txr->br != NULL)
3503 		buf_ring_free(txr->br, M_DEVBUF);
3504 #endif
3505 	if (txr->tx_buffers != NULL) {
3506 		free(txr->tx_buffers, M_DEVBUF);
3507 		txr->tx_buffers = NULL;
3508 	}
3509 	if (txr->txtag != NULL) {
3510 		bus_dma_tag_destroy(txr->txtag);
3511 		txr->txtag = NULL;
3512 	}
3513 	return;
3514 }
3515 
3516 
3517 /*********************************************************************
3518  *  The offload context is protocol specific (TCP/UDP) and thus
3519  *  only needs to be set when the protocol changes. The occasion
3520  *  of a context change can be a performance detriment, and
3521  *  might be better just disabled. The reason arises in the way
3522  *  in which the controller supports pipelined requests from the
3523  *  Tx data DMA. Up to four requests can be pipelined, and they may
3524  *  belong to the same packet or to multiple packets. However all
3525  *  requests for one packet are issued before a request is issued
3526  *  for a subsequent packet and if a request for the next packet
3527  *  requires a context change, that request will be stalled
3528  *  until the previous request completes. This means setting up
3529  *  a new context effectively disables pipelined Tx data DMA which
3530  *  in turn greatly slow down performance to send small sized
3531  *  frames.
3532  **********************************************************************/
3533 static void
3534 em_transmit_checksum_setup(struct tx_ring *txr, struct mbuf *mp, int ip_off,
3535     struct ip *ip, u32 *txd_upper, u32 *txd_lower)
3536 {
3537 	struct adapter			*adapter = txr->adapter;
3538 	struct e1000_context_desc	*TXD = NULL;
3539 	struct em_buffer		*tx_buffer;
3540 	int				cur, hdr_len;
3541 	u32				cmd = 0;
3542 	u16				offload = 0;
3543 	u8				ipcso, ipcss, tucso, tucss;
3544 
3545 	ipcss = ipcso = tucss = tucso = 0;
3546 	hdr_len = ip_off + (ip->ip_hl << 2);
3547 	cur = txr->next_avail_desc;
3548 
3549 	/* Setup of IP header checksum. */
3550 	if (mp->m_pkthdr.csum_flags & CSUM_IP) {
3551 		*txd_upper |= E1000_TXD_POPTS_IXSM << 8;
3552 		offload |= CSUM_IP;
3553 		ipcss = ip_off;
3554 		ipcso = ip_off + offsetof(struct ip, ip_sum);
3555 		/*
3556 		 * Start offset for header checksum calculation.
3557 		 * End offset for header checksum calculation.
3558 		 * Offset of place to put the checksum.
3559 		 */
3560 		TXD = (struct e1000_context_desc *)&txr->tx_base[cur];
3561 		TXD->lower_setup.ip_fields.ipcss = ipcss;
3562 		TXD->lower_setup.ip_fields.ipcse = htole16(hdr_len);
3563 		TXD->lower_setup.ip_fields.ipcso = ipcso;
3564 		cmd |= E1000_TXD_CMD_IP;
3565 	}
3566 
3567 	if (mp->m_pkthdr.csum_flags & CSUM_TCP) {
3568  		*txd_lower = E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
3569  		*txd_upper |= E1000_TXD_POPTS_TXSM << 8;
3570  		offload |= CSUM_TCP;
3571  		tucss = hdr_len;
3572  		tucso = hdr_len + offsetof(struct tcphdr, th_sum);
3573  		/*
3574  		 * Setting up new checksum offload context for every frames
3575  		 * takes a lot of processing time for hardware. This also
3576  		 * reduces performance a lot for small sized frames so avoid
3577  		 * it if driver can use previously configured checksum
3578  		 * offload context.
3579  		 */
3580  		if (txr->last_hw_offload == offload) {
3581  			if (offload & CSUM_IP) {
3582  				if (txr->last_hw_ipcss == ipcss &&
3583  				    txr->last_hw_ipcso == ipcso &&
3584  				    txr->last_hw_tucss == tucss &&
3585  				    txr->last_hw_tucso == tucso)
3586  					return;
3587  			} else {
3588  				if (txr->last_hw_tucss == tucss &&
3589  				    txr->last_hw_tucso == tucso)
3590  					return;
3591  			}
3592   		}
3593  		txr->last_hw_offload = offload;
3594  		txr->last_hw_tucss = tucss;
3595  		txr->last_hw_tucso = tucso;
3596  		/*
3597  		 * Start offset for payload checksum calculation.
3598  		 * End offset for payload checksum calculation.
3599  		 * Offset of place to put the checksum.
3600  		 */
3601 		TXD = (struct e1000_context_desc *)&txr->tx_base[cur];
3602  		TXD->upper_setup.tcp_fields.tucss = hdr_len;
3603  		TXD->upper_setup.tcp_fields.tucse = htole16(0);
3604  		TXD->upper_setup.tcp_fields.tucso = tucso;
3605  		cmd |= E1000_TXD_CMD_TCP;
3606  	} else if (mp->m_pkthdr.csum_flags & CSUM_UDP) {
3607  		*txd_lower = E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
3608  		*txd_upper |= E1000_TXD_POPTS_TXSM << 8;
3609  		tucss = hdr_len;
3610  		tucso = hdr_len + offsetof(struct udphdr, uh_sum);
3611  		/*
3612  		 * Setting up new checksum offload context for every frames
3613  		 * takes a lot of processing time for hardware. This also
3614  		 * reduces performance a lot for small sized frames so avoid
3615  		 * it if driver can use previously configured checksum
3616  		 * offload context.
3617  		 */
3618  		if (txr->last_hw_offload == offload) {
3619  			if (offload & CSUM_IP) {
3620  				if (txr->last_hw_ipcss == ipcss &&
3621  				    txr->last_hw_ipcso == ipcso &&
3622  				    txr->last_hw_tucss == tucss &&
3623  				    txr->last_hw_tucso == tucso)
3624  					return;
3625  			} else {
3626  				if (txr->last_hw_tucss == tucss &&
3627  				    txr->last_hw_tucso == tucso)
3628  					return;
3629  			}
3630  		}
3631  		txr->last_hw_offload = offload;
3632  		txr->last_hw_tucss = tucss;
3633  		txr->last_hw_tucso = tucso;
3634  		/*
3635  		 * Start offset for header checksum calculation.
3636  		 * End offset for header checksum calculation.
3637  		 * Offset of place to put the checksum.
3638  		 */
3639 		TXD = (struct e1000_context_desc *)&txr->tx_base[cur];
3640  		TXD->upper_setup.tcp_fields.tucss = tucss;
3641  		TXD->upper_setup.tcp_fields.tucse = htole16(0);
3642  		TXD->upper_setup.tcp_fields.tucso = tucso;
3643   	}
3644 
3645  	if (offload & CSUM_IP) {
3646  		txr->last_hw_ipcss = ipcss;
3647  		txr->last_hw_ipcso = ipcso;
3648   	}
3649 
3650 	TXD->tcp_seg_setup.data = htole32(0);
3651 	TXD->cmd_and_length =
3652 	    htole32(adapter->txd_cmd | E1000_TXD_CMD_DEXT | cmd);
3653 	tx_buffer = &txr->tx_buffers[cur];
3654 	tx_buffer->m_head = NULL;
3655 	tx_buffer->next_eop = -1;
3656 
3657 	if (++cur == adapter->num_tx_desc)
3658 		cur = 0;
3659 
3660 	txr->tx_avail--;
3661 	txr->next_avail_desc = cur;
3662 }
3663 
3664 
3665 /**********************************************************************
3666  *
3667  *  Setup work for hardware segmentation offload (TSO)
3668  *
3669  **********************************************************************/
3670 static void
3671 em_tso_setup(struct tx_ring *txr, struct mbuf *mp, int ip_off,
3672     struct ip *ip, struct tcphdr *tp, u32 *txd_upper, u32 *txd_lower)
3673 {
3674 	struct adapter			*adapter = txr->adapter;
3675 	struct e1000_context_desc	*TXD;
3676 	struct em_buffer		*tx_buffer;
3677 	int cur, hdr_len;
3678 
3679 	/*
3680 	 * In theory we can use the same TSO context if and only if
3681 	 * frame is the same type(IP/TCP) and the same MSS. However
3682 	 * checking whether a frame has the same IP/TCP structure is
3683 	 * hard thing so just ignore that and always restablish a
3684 	 * new TSO context.
3685 	 */
3686 	hdr_len = ip_off + (ip->ip_hl << 2) + (tp->th_off << 2);
3687 	*txd_lower = (E1000_TXD_CMD_DEXT |	/* Extended descr type */
3688 		      E1000_TXD_DTYP_D |	/* Data descr type */
3689 		      E1000_TXD_CMD_TSE);	/* Do TSE on this packet */
3690 
3691 	/* IP and/or TCP header checksum calculation and insertion. */
3692 	*txd_upper = (E1000_TXD_POPTS_IXSM | E1000_TXD_POPTS_TXSM) << 8;
3693 
3694 	cur = txr->next_avail_desc;
3695 	tx_buffer = &txr->tx_buffers[cur];
3696 	TXD = (struct e1000_context_desc *) &txr->tx_base[cur];
3697 
3698 	/*
3699 	 * Start offset for header checksum calculation.
3700 	 * End offset for header checksum calculation.
3701 	 * Offset of place put the checksum.
3702 	 */
3703 	TXD->lower_setup.ip_fields.ipcss = ip_off;
3704 	TXD->lower_setup.ip_fields.ipcse =
3705 	    htole16(ip_off + (ip->ip_hl << 2) - 1);
3706 	TXD->lower_setup.ip_fields.ipcso = ip_off + offsetof(struct ip, ip_sum);
3707 	/*
3708 	 * Start offset for payload checksum calculation.
3709 	 * End offset for payload checksum calculation.
3710 	 * Offset of place to put the checksum.
3711 	 */
3712 	TXD->upper_setup.tcp_fields.tucss = ip_off + (ip->ip_hl << 2);
3713 	TXD->upper_setup.tcp_fields.tucse = 0;
3714 	TXD->upper_setup.tcp_fields.tucso =
3715 	    ip_off + (ip->ip_hl << 2) + offsetof(struct tcphdr, th_sum);
3716 	/*
3717 	 * Payload size per packet w/o any headers.
3718 	 * Length of all headers up to payload.
3719 	 */
3720 	TXD->tcp_seg_setup.fields.mss = htole16(mp->m_pkthdr.tso_segsz);
3721 	TXD->tcp_seg_setup.fields.hdr_len = hdr_len;
3722 
3723 	TXD->cmd_and_length = htole32(adapter->txd_cmd |
3724 				E1000_TXD_CMD_DEXT |	/* Extended descr */
3725 				E1000_TXD_CMD_TSE |	/* TSE context */
3726 				E1000_TXD_CMD_IP |	/* Do IP csum */
3727 				E1000_TXD_CMD_TCP |	/* Do TCP checksum */
3728 				(mp->m_pkthdr.len - (hdr_len))); /* Total len */
3729 
3730 	tx_buffer->m_head = NULL;
3731 	tx_buffer->next_eop = -1;
3732 
3733 	if (++cur == adapter->num_tx_desc)
3734 		cur = 0;
3735 
3736 	txr->tx_avail--;
3737 	txr->next_avail_desc = cur;
3738 	txr->tx_tso = TRUE;
3739 }
3740 
3741 
3742 /**********************************************************************
3743  *
3744  *  Examine each tx_buffer in the used queue. If the hardware is done
3745  *  processing the packet then free associated resources. The
3746  *  tx_buffer is put back on the free queue.
3747  *
3748  **********************************************************************/
3749 static bool
3750 em_txeof(struct tx_ring *txr)
3751 {
3752 	struct adapter	*adapter = txr->adapter;
3753         int first, last, done, processed;
3754         struct em_buffer *tx_buffer;
3755         struct e1000_tx_desc   *tx_desc, *eop_desc;
3756 	struct ifnet   *ifp = adapter->ifp;
3757 
3758 	EM_TX_LOCK_ASSERT(txr);
3759 #ifdef DEV_NETMAP
3760 	if (ifp->if_capenable & IFCAP_NETMAP) {
3761 		struct netmap_adapter *na = NA(ifp);
3762 
3763 		selwakeuppri(&na->tx_rings[txr->me].si, PI_NET);
3764 		EM_TX_UNLOCK(txr);
3765 		EM_CORE_LOCK(adapter);
3766 		selwakeuppri(&na->tx_rings[na->num_queues + 1].si, PI_NET);
3767 		EM_CORE_UNLOCK(adapter);
3768 		EM_TX_LOCK(txr);
3769 		return (FALSE);
3770 	}
3771 #endif /* DEV_NETMAP */
3772 
3773 	/* No work, make sure watchdog is off */
3774         if (txr->tx_avail == adapter->num_tx_desc) {
3775 		txr->queue_status = EM_QUEUE_IDLE;
3776                 return (FALSE);
3777 	}
3778 
3779 	processed = 0;
3780         first = txr->next_to_clean;
3781         tx_desc = &txr->tx_base[first];
3782         tx_buffer = &txr->tx_buffers[first];
3783 	last = tx_buffer->next_eop;
3784         eop_desc = &txr->tx_base[last];
3785 
3786 	/*
3787 	 * What this does is get the index of the
3788 	 * first descriptor AFTER the EOP of the
3789 	 * first packet, that way we can do the
3790 	 * simple comparison on the inner while loop.
3791 	 */
3792 	if (++last == adapter->num_tx_desc)
3793  		last = 0;
3794 	done = last;
3795 
3796         bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
3797             BUS_DMASYNC_POSTREAD);
3798 
3799         while (eop_desc->upper.fields.status & E1000_TXD_STAT_DD) {
3800 		/* We clean the range of the packet */
3801 		while (first != done) {
3802                 	tx_desc->upper.data = 0;
3803                 	tx_desc->lower.data = 0;
3804                 	tx_desc->buffer_addr = 0;
3805                 	++txr->tx_avail;
3806 			++processed;
3807 
3808 			if (tx_buffer->m_head) {
3809 				bus_dmamap_sync(txr->txtag,
3810 				    tx_buffer->map,
3811 				    BUS_DMASYNC_POSTWRITE);
3812 				bus_dmamap_unload(txr->txtag,
3813 				    tx_buffer->map);
3814                         	m_freem(tx_buffer->m_head);
3815                         	tx_buffer->m_head = NULL;
3816                 	}
3817 			tx_buffer->next_eop = -1;
3818 			txr->watchdog_time = ticks;
3819 
3820 	                if (++first == adapter->num_tx_desc)
3821 				first = 0;
3822 
3823 	                tx_buffer = &txr->tx_buffers[first];
3824 			tx_desc = &txr->tx_base[first];
3825 		}
3826 		++ifp->if_opackets;
3827 		/* See if we can continue to the next packet */
3828 		last = tx_buffer->next_eop;
3829 		if (last != -1) {
3830         		eop_desc = &txr->tx_base[last];
3831 			/* Get new done point */
3832 			if (++last == adapter->num_tx_desc) last = 0;
3833 			done = last;
3834 		} else
3835 			break;
3836         }
3837         bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
3838             BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3839 
3840         txr->next_to_clean = first;
3841 
3842 	/*
3843 	** Watchdog calculation, we know there's
3844 	** work outstanding or the first return
3845 	** would have been taken, so none processed
3846 	** for too long indicates a hang. local timer
3847 	** will examine this and do a reset if needed.
3848 	*/
3849 	if ((!processed) && ((ticks - txr->watchdog_time) > EM_WATCHDOG))
3850 		txr->queue_status = EM_QUEUE_HUNG;
3851 
3852         /*
3853          * If we have a minimum free, clear IFF_DRV_OACTIVE
3854          * to tell the stack that it is OK to send packets.
3855 	 * Notice that all writes of OACTIVE happen under the
3856 	 * TX lock which, with a single queue, guarantees
3857 	 * sanity.
3858          */
3859         if (txr->tx_avail >= EM_MAX_SCATTER)
3860 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3861 
3862 	/* Disable watchdog if all clean */
3863 	if (txr->tx_avail == adapter->num_tx_desc) {
3864 		txr->queue_status = EM_QUEUE_IDLE;
3865 		return (FALSE);
3866 	}
3867 
3868 	return (TRUE);
3869 }
3870 
3871 
3872 /*********************************************************************
3873  *
3874  *  Refresh RX descriptor mbufs from system mbuf buffer pool.
3875  *
3876  **********************************************************************/
3877 static void
3878 em_refresh_mbufs(struct rx_ring *rxr, int limit)
3879 {
3880 	struct adapter		*adapter = rxr->adapter;
3881 	struct mbuf		*m;
3882 	bus_dma_segment_t	segs[1];
3883 	struct em_buffer	*rxbuf;
3884 	int			i, j, error, nsegs;
3885 	bool			cleaned = FALSE;
3886 
3887 	i = j = rxr->next_to_refresh;
3888 	/*
3889 	** Get one descriptor beyond
3890 	** our work mark to control
3891 	** the loop.
3892 	*/
3893 	if (++j == adapter->num_rx_desc)
3894 		j = 0;
3895 
3896 	while (j != limit) {
3897 		rxbuf = &rxr->rx_buffers[i];
3898 		if (rxbuf->m_head == NULL) {
3899 			m = m_getjcl(M_DONTWAIT, MT_DATA,
3900 			    M_PKTHDR, adapter->rx_mbuf_sz);
3901 			/*
3902 			** If we have a temporary resource shortage
3903 			** that causes a failure, just abort refresh
3904 			** for now, we will return to this point when
3905 			** reinvoked from em_rxeof.
3906 			*/
3907 			if (m == NULL)
3908 				goto update;
3909 		} else
3910 			m = rxbuf->m_head;
3911 
3912 		m->m_len = m->m_pkthdr.len = adapter->rx_mbuf_sz;
3913 		m->m_flags |= M_PKTHDR;
3914 		m->m_data = m->m_ext.ext_buf;
3915 
3916 		/* Use bus_dma machinery to setup the memory mapping  */
3917 		error = bus_dmamap_load_mbuf_sg(rxr->rxtag, rxbuf->map,
3918 		    m, segs, &nsegs, BUS_DMA_NOWAIT);
3919 		if (error != 0) {
3920 			printf("Refresh mbufs: hdr dmamap load"
3921 			    " failure - %d\n", error);
3922 			m_free(m);
3923 			rxbuf->m_head = NULL;
3924 			goto update;
3925 		}
3926 		rxbuf->m_head = m;
3927 		bus_dmamap_sync(rxr->rxtag,
3928 		    rxbuf->map, BUS_DMASYNC_PREREAD);
3929 		rxr->rx_base[i].buffer_addr = htole64(segs[0].ds_addr);
3930 		cleaned = TRUE;
3931 
3932 		i = j; /* Next is precalulated for us */
3933 		rxr->next_to_refresh = i;
3934 		/* Calculate next controlling index */
3935 		if (++j == adapter->num_rx_desc)
3936 			j = 0;
3937 	}
3938 update:
3939 	/*
3940 	** Update the tail pointer only if,
3941 	** and as far as we have refreshed.
3942 	*/
3943 	if (cleaned)
3944 		E1000_WRITE_REG(&adapter->hw,
3945 		    E1000_RDT(rxr->me), rxr->next_to_refresh);
3946 
3947 	return;
3948 }
3949 
3950 
3951 /*********************************************************************
3952  *
3953  *  Allocate memory for rx_buffer structures. Since we use one
3954  *  rx_buffer per received packet, the maximum number of rx_buffer's
3955  *  that we'll need is equal to the number of receive descriptors
3956  *  that we've allocated.
3957  *
3958  **********************************************************************/
3959 static int
3960 em_allocate_receive_buffers(struct rx_ring *rxr)
3961 {
3962 	struct adapter		*adapter = rxr->adapter;
3963 	device_t		dev = adapter->dev;
3964 	struct em_buffer	*rxbuf;
3965 	int			error;
3966 
3967 	rxr->rx_buffers = malloc(sizeof(struct em_buffer) *
3968 	    adapter->num_rx_desc, M_DEVBUF, M_NOWAIT | M_ZERO);
3969 	if (rxr->rx_buffers == NULL) {
3970 		device_printf(dev, "Unable to allocate rx_buffer memory\n");
3971 		return (ENOMEM);
3972 	}
3973 
3974 	error = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
3975 				1, 0,			/* alignment, bounds */
3976 				BUS_SPACE_MAXADDR,	/* lowaddr */
3977 				BUS_SPACE_MAXADDR,	/* highaddr */
3978 				NULL, NULL,		/* filter, filterarg */
3979 				MJUM9BYTES,		/* maxsize */
3980 				1,			/* nsegments */
3981 				MJUM9BYTES,		/* maxsegsize */
3982 				0,			/* flags */
3983 				NULL,			/* lockfunc */
3984 				NULL,			/* lockarg */
3985 				&rxr->rxtag);
3986 	if (error) {
3987 		device_printf(dev, "%s: bus_dma_tag_create failed %d\n",
3988 		    __func__, error);
3989 		goto fail;
3990 	}
3991 
3992 	rxbuf = rxr->rx_buffers;
3993 	for (int i = 0; i < adapter->num_rx_desc; i++, rxbuf++) {
3994 		rxbuf = &rxr->rx_buffers[i];
3995 		error = bus_dmamap_create(rxr->rxtag, BUS_DMA_NOWAIT,
3996 		    &rxbuf->map);
3997 		if (error) {
3998 			device_printf(dev, "%s: bus_dmamap_create failed: %d\n",
3999 			    __func__, error);
4000 			goto fail;
4001 		}
4002 	}
4003 
4004 	return (0);
4005 
4006 fail:
4007 	em_free_receive_structures(adapter);
4008 	return (error);
4009 }
4010 
4011 
4012 /*********************************************************************
4013  *
4014  *  Initialize a receive ring and its buffers.
4015  *
4016  **********************************************************************/
4017 static int
4018 em_setup_receive_ring(struct rx_ring *rxr)
4019 {
4020 	struct	adapter 	*adapter = rxr->adapter;
4021 	struct em_buffer	*rxbuf;
4022 	bus_dma_segment_t	seg[1];
4023 	int			rsize, nsegs, error;
4024 
4025 
4026 	/* Clear the ring contents */
4027 	EM_RX_LOCK(rxr);
4028 	rsize = roundup2(adapter->num_rx_desc *
4029 	    sizeof(struct e1000_rx_desc), EM_DBA_ALIGN);
4030 	bzero((void *)rxr->rx_base, rsize);
4031 
4032 	/*
4033 	** Free current RX buffer structs and their mbufs
4034 	*/
4035 	for (int i = 0; i < adapter->num_rx_desc; i++) {
4036 		rxbuf = &rxr->rx_buffers[i];
4037 		if (rxbuf->m_head != NULL) {
4038 			bus_dmamap_sync(rxr->rxtag, rxbuf->map,
4039 			    BUS_DMASYNC_POSTREAD);
4040 			bus_dmamap_unload(rxr->rxtag, rxbuf->map);
4041 			m_freem(rxbuf->m_head);
4042 		}
4043 	}
4044 
4045 	/* Now replenish the mbufs */
4046         for (int j = 0; j != adapter->num_rx_desc; ++j) {
4047 		rxbuf = &rxr->rx_buffers[j];
4048 		rxbuf->m_head = m_getjcl(M_DONTWAIT, MT_DATA,
4049 		    M_PKTHDR, adapter->rx_mbuf_sz);
4050 		if (rxbuf->m_head == NULL) {
4051 			error = ENOBUFS;
4052 			goto fail;
4053 		}
4054 		rxbuf->m_head->m_len = adapter->rx_mbuf_sz;
4055 		rxbuf->m_head->m_flags &= ~M_HASFCS; /* we strip it */
4056 		rxbuf->m_head->m_pkthdr.len = adapter->rx_mbuf_sz;
4057 
4058 		/* Get the memory mapping */
4059 		error = bus_dmamap_load_mbuf_sg(rxr->rxtag,
4060 		    rxbuf->map, rxbuf->m_head, seg,
4061 		    &nsegs, BUS_DMA_NOWAIT);
4062 		if (error != 0) {
4063 			m_freem(rxbuf->m_head);
4064 			rxbuf->m_head = NULL;
4065 			goto fail;
4066 		}
4067 		bus_dmamap_sync(rxr->rxtag,
4068 		    rxbuf->map, BUS_DMASYNC_PREREAD);
4069 
4070 		/* Update descriptor */
4071 		rxr->rx_base[j].buffer_addr = htole64(seg[0].ds_addr);
4072 	}
4073 	rxr->next_to_check = 0;
4074 	rxr->next_to_refresh = 0;
4075 	bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
4076 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
4077 
4078 #ifdef DEV_NETMAP
4079     {
4080 	/*
4081 	 * This driver is slightly different from the standard:
4082 	 * it refills the rings in blocks of 8, so the while()
4083 	 * above completes any leftover work. Also, after if_init()
4084 	 * the ring starts at rxr->next_to_check instead of 0.
4085 	 *
4086 	 * Currently: we leave the mbufs allocated even in netmap
4087 	 * mode, and simply make the NIC ring point to the
4088 	 * correct buffer (netmap_buf or mbuf) depending on
4089 	 * the mode. To avoid mbuf leaks, when in netmap mode we
4090 	 * must make sure that next_to_refresh == next_to_check - 1
4091 	 * so that the above while() loop is never run on init.
4092 	 *
4093 	 * A better way would be to free the mbufs when entering
4094 	 * netmap mode, and set next_to_refresh/check in
4095 	 * a way that the mbufs are completely reallocated
4096 	 * when going back to standard mode.
4097 	 */
4098 	struct netmap_adapter *na = NA(adapter->ifp);
4099 	struct netmap_slot *slot = netmap_reset(na,
4100 		NR_RX, rxr->me, rxr->next_to_check);
4101 	int sj = slot ? na->rx_rings[rxr->me].nkr_hwofs : 0;
4102 
4103 	/* slot sj corresponds to entry j in the NIC ring */
4104 	if (sj < 0)
4105 		sj += adapter->num_rx_desc;
4106 
4107 	for (int j = 0; j != adapter->num_rx_desc; j++, sj++) {
4108 		void *addr;
4109 		int sz;
4110 
4111 		rxbuf = &rxr->rx_buffers[j];
4112 		/* no mbuf and regular mode -> skip this entry */
4113 		if (rxbuf->m_head == NULL && !slot)
4114 			continue;
4115 		/* Handle wrap. Cannot use "na" here, could be NULL */
4116 		if (sj >= adapter->num_rx_desc)
4117 			sj -= adapter->num_rx_desc;
4118 		/* see comment, set slot addr and map */
4119 		addr = slot ? NMB(slot + sj) : rxbuf->m_head->m_data;
4120 		sz = slot ? na->buff_size : adapter->rx_mbuf_sz;
4121 		// XXX load or reload ?
4122 		netmap_load_map(rxr->rxtag, rxbuf->map, addr, sz);
4123 		/* Update descriptor */
4124 		rxr->rx_base[j].buffer_addr = htole64(vtophys(addr));
4125 		bus_dmamap_sync(rxr->rxtag, rxbuf->map, BUS_DMASYNC_PREREAD);
4126 	}
4127     }
4128 #endif /* DEV_NETMAP */
4129 
4130 fail:
4131 	EM_RX_UNLOCK(rxr);
4132 	return (error);
4133 }
4134 
4135 /*********************************************************************
4136  *
4137  *  Initialize all receive rings.
4138  *
4139  **********************************************************************/
4140 static int
4141 em_setup_receive_structures(struct adapter *adapter)
4142 {
4143 	struct rx_ring *rxr = adapter->rx_rings;
4144 	int q;
4145 
4146 	for (q = 0; q < adapter->num_queues; q++, rxr++)
4147 		if (em_setup_receive_ring(rxr))
4148 			goto fail;
4149 
4150 	return (0);
4151 fail:
4152 	/*
4153 	 * Free RX buffers allocated so far, we will only handle
4154 	 * the rings that completed, the failing case will have
4155 	 * cleaned up for itself. 'q' failed, so its the terminus.
4156 	 */
4157 	for (int i = 0; i < q; ++i) {
4158 		rxr = &adapter->rx_rings[i];
4159 		for (int n = 0; n < adapter->num_rx_desc; n++) {
4160 			struct em_buffer *rxbuf;
4161 			rxbuf = &rxr->rx_buffers[n];
4162 			if (rxbuf->m_head != NULL) {
4163 				bus_dmamap_sync(rxr->rxtag, rxbuf->map,
4164 			  	  BUS_DMASYNC_POSTREAD);
4165 				bus_dmamap_unload(rxr->rxtag, rxbuf->map);
4166 				m_freem(rxbuf->m_head);
4167 				rxbuf->m_head = NULL;
4168 			}
4169 		}
4170 		rxr->next_to_check = 0;
4171 		rxr->next_to_refresh = 0;
4172 	}
4173 
4174 	return (ENOBUFS);
4175 }
4176 
4177 /*********************************************************************
4178  *
4179  *  Free all receive rings.
4180  *
4181  **********************************************************************/
4182 static void
4183 em_free_receive_structures(struct adapter *adapter)
4184 {
4185 	struct rx_ring *rxr = adapter->rx_rings;
4186 
4187 	for (int i = 0; i < adapter->num_queues; i++, rxr++) {
4188 		em_free_receive_buffers(rxr);
4189 		/* Free the ring memory as well */
4190 		em_dma_free(adapter, &rxr->rxdma);
4191 		EM_RX_LOCK_DESTROY(rxr);
4192 	}
4193 
4194 	free(adapter->rx_rings, M_DEVBUF);
4195 }
4196 
4197 
4198 /*********************************************************************
4199  *
4200  *  Free receive ring data structures
4201  *
4202  **********************************************************************/
4203 static void
4204 em_free_receive_buffers(struct rx_ring *rxr)
4205 {
4206 	struct adapter		*adapter = rxr->adapter;
4207 	struct em_buffer	*rxbuf = NULL;
4208 
4209 	INIT_DEBUGOUT("free_receive_buffers: begin");
4210 
4211 	if (rxr->rx_buffers != NULL) {
4212 		for (int i = 0; i < adapter->num_rx_desc; i++) {
4213 			rxbuf = &rxr->rx_buffers[i];
4214 			if (rxbuf->map != NULL) {
4215 				bus_dmamap_sync(rxr->rxtag, rxbuf->map,
4216 				    BUS_DMASYNC_POSTREAD);
4217 				bus_dmamap_unload(rxr->rxtag, rxbuf->map);
4218 				bus_dmamap_destroy(rxr->rxtag, rxbuf->map);
4219 			}
4220 			if (rxbuf->m_head != NULL) {
4221 				m_freem(rxbuf->m_head);
4222 				rxbuf->m_head = NULL;
4223 			}
4224 		}
4225 		free(rxr->rx_buffers, M_DEVBUF);
4226 		rxr->rx_buffers = NULL;
4227 		rxr->next_to_check = 0;
4228 		rxr->next_to_refresh = 0;
4229 	}
4230 
4231 	if (rxr->rxtag != NULL) {
4232 		bus_dma_tag_destroy(rxr->rxtag);
4233 		rxr->rxtag = NULL;
4234 	}
4235 
4236 	return;
4237 }
4238 
4239 
4240 /*********************************************************************
4241  *
4242  *  Enable receive unit.
4243  *
4244  **********************************************************************/
4245 #define MAX_INTS_PER_SEC	8000
4246 #define DEFAULT_ITR	     1000000000/(MAX_INTS_PER_SEC * 256)
4247 
4248 static void
4249 em_initialize_receive_unit(struct adapter *adapter)
4250 {
4251 	struct rx_ring	*rxr = adapter->rx_rings;
4252 	struct ifnet	*ifp = adapter->ifp;
4253 	struct e1000_hw	*hw = &adapter->hw;
4254 	u64	bus_addr;
4255 	u32	rctl, rxcsum;
4256 
4257 	INIT_DEBUGOUT("em_initialize_receive_units: begin");
4258 
4259 	/*
4260 	 * Make sure receives are disabled while setting
4261 	 * up the descriptor ring
4262 	 */
4263 	rctl = E1000_READ_REG(hw, E1000_RCTL);
4264 	/* Do not disable if ever enabled on this hardware */
4265 	if ((hw->mac.type != e1000_82574) && (hw->mac.type != e1000_82583))
4266 		E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
4267 
4268 	E1000_WRITE_REG(&adapter->hw, E1000_RADV,
4269 	    adapter->rx_abs_int_delay.value);
4270 	/*
4271 	 * Set the interrupt throttling rate. Value is calculated
4272 	 * as DEFAULT_ITR = 1/(MAX_INTS_PER_SEC * 256ns)
4273 	 */
4274 	E1000_WRITE_REG(hw, E1000_ITR, DEFAULT_ITR);
4275 
4276 	/*
4277 	** When using MSIX interrupts we need to throttle
4278 	** using the EITR register (82574 only)
4279 	*/
4280 	if (hw->mac.type == e1000_82574) {
4281 		for (int i = 0; i < 4; i++)
4282 			E1000_WRITE_REG(hw, E1000_EITR_82574(i),
4283 			    DEFAULT_ITR);
4284 		/* Disable accelerated acknowledge */
4285 		E1000_WRITE_REG(hw, E1000_RFCTL, E1000_RFCTL_ACK_DIS);
4286 	}
4287 
4288 	if (ifp->if_capenable & IFCAP_RXCSUM) {
4289 		rxcsum = E1000_READ_REG(hw, E1000_RXCSUM);
4290 		rxcsum |= (E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL);
4291 		E1000_WRITE_REG(hw, E1000_RXCSUM, rxcsum);
4292 	}
4293 
4294 	/*
4295 	** XXX TEMPORARY WORKAROUND: on some systems with 82573
4296 	** long latencies are observed, like Lenovo X60. This
4297 	** change eliminates the problem, but since having positive
4298 	** values in RDTR is a known source of problems on other
4299 	** platforms another solution is being sought.
4300 	*/
4301 	if (hw->mac.type == e1000_82573)
4302 		E1000_WRITE_REG(hw, E1000_RDTR, 0x20);
4303 
4304 	for (int i = 0; i < adapter->num_queues; i++, rxr++) {
4305 		/* Setup the Base and Length of the Rx Descriptor Ring */
4306 		bus_addr = rxr->rxdma.dma_paddr;
4307 		E1000_WRITE_REG(hw, E1000_RDLEN(i),
4308 		    adapter->num_rx_desc * sizeof(struct e1000_rx_desc));
4309 		E1000_WRITE_REG(hw, E1000_RDBAH(i), (u32)(bus_addr >> 32));
4310 		E1000_WRITE_REG(hw, E1000_RDBAL(i), (u32)bus_addr);
4311 		/* Setup the Head and Tail Descriptor Pointers */
4312 		E1000_WRITE_REG(hw, E1000_RDH(i), 0);
4313 		E1000_WRITE_REG(hw, E1000_RDT(i), adapter->num_rx_desc - 1);
4314 #ifdef DEV_NETMAP
4315 		/*
4316 		 * an init() while a netmap client is active must
4317 		 * preserve the rx buffers passed to userspace.
4318 		 * In this driver it means we adjust RDT to
4319 		 * something different from next_to_refresh.
4320 		 */
4321 		if (ifp->if_capenable & IFCAP_NETMAP) {
4322 			struct netmap_adapter *na = NA(adapter->ifp);
4323 			struct netmap_kring *kring = &na->rx_rings[i];
4324 			int t = rxr->next_to_refresh - kring->nr_hwavail;
4325 
4326 			if (t < 0)
4327 				t += na->num_rx_desc;
4328 			E1000_WRITE_REG(hw, E1000_RDT(i), t);
4329 		} else
4330 #endif /* DEV_NETMAP */
4331 		E1000_WRITE_REG(hw, E1000_RDT(i), adapter->num_rx_desc - 1);
4332 	}
4333 
4334 	/* Set PTHRESH for improved jumbo performance */
4335 	if (((adapter->hw.mac.type == e1000_ich9lan) ||
4336 	    (adapter->hw.mac.type == e1000_pch2lan) ||
4337 	    (adapter->hw.mac.type == e1000_ich10lan)) &&
4338 	    (ifp->if_mtu > ETHERMTU)) {
4339 		u32 rxdctl = E1000_READ_REG(hw, E1000_RXDCTL(0));
4340 		E1000_WRITE_REG(hw, E1000_RXDCTL(0), rxdctl | 3);
4341 	}
4342 
4343 	if (adapter->hw.mac.type == e1000_pch2lan) {
4344 		if (ifp->if_mtu > ETHERMTU)
4345 			e1000_lv_jumbo_workaround_ich8lan(hw, TRUE);
4346 		else
4347 			e1000_lv_jumbo_workaround_ich8lan(hw, FALSE);
4348 	}
4349 
4350 	/* Setup the Receive Control Register */
4351 	rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
4352 	rctl |= E1000_RCTL_EN | E1000_RCTL_BAM |
4353 	    E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF |
4354 	    (hw->mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
4355 
4356         /* Strip the CRC */
4357         rctl |= E1000_RCTL_SECRC;
4358 
4359         /* Make sure VLAN Filters are off */
4360         rctl &= ~E1000_RCTL_VFE;
4361 	rctl &= ~E1000_RCTL_SBP;
4362 
4363 	if (adapter->rx_mbuf_sz == MCLBYTES)
4364 		rctl |= E1000_RCTL_SZ_2048;
4365 	else if (adapter->rx_mbuf_sz == MJUMPAGESIZE)
4366 		rctl |= E1000_RCTL_SZ_4096 | E1000_RCTL_BSEX;
4367 	else if (adapter->rx_mbuf_sz > MJUMPAGESIZE)
4368 		rctl |= E1000_RCTL_SZ_8192 | E1000_RCTL_BSEX;
4369 
4370 	if (ifp->if_mtu > ETHERMTU)
4371 		rctl |= E1000_RCTL_LPE;
4372 	else
4373 		rctl &= ~E1000_RCTL_LPE;
4374 
4375 	/* Write out the settings */
4376 	E1000_WRITE_REG(hw, E1000_RCTL, rctl);
4377 
4378 	return;
4379 }
4380 
4381 
4382 /*********************************************************************
4383  *
4384  *  This routine executes in interrupt context. It replenishes
4385  *  the mbufs in the descriptor and sends data which has been
4386  *  dma'ed into host memory to upper layer.
4387  *
4388  *  We loop at most count times if count is > 0, or until done if
4389  *  count < 0.
4390  *
4391  *  For polling we also now return the number of cleaned packets
4392  *********************************************************************/
4393 static bool
4394 em_rxeof(struct rx_ring *rxr, int count, int *done)
4395 {
4396 	struct adapter		*adapter = rxr->adapter;
4397 	struct ifnet		*ifp = adapter->ifp;
4398 	struct mbuf		*mp, *sendmp;
4399 	u8			status = 0;
4400 	u16 			len;
4401 	int			i, processed, rxdone = 0;
4402 	bool			eop;
4403 	struct e1000_rx_desc	*cur;
4404 
4405 	EM_RX_LOCK(rxr);
4406 
4407 #ifdef DEV_NETMAP
4408 	if (ifp->if_capenable & IFCAP_NETMAP) {
4409 		struct netmap_adapter *na = NA(ifp);
4410 
4411 		selwakeuppri(&na->rx_rings[rxr->me].si, PI_NET);
4412 		EM_RX_UNLOCK(rxr);
4413 		EM_CORE_LOCK(adapter);
4414 		selwakeuppri(&na->rx_rings[na->num_queues + 1].si, PI_NET);
4415 		EM_CORE_UNLOCK(adapter);
4416 		return (0);
4417 	}
4418 #endif /* DEV_NETMAP */
4419 
4420 	for (i = rxr->next_to_check, processed = 0; count != 0;) {
4421 
4422 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
4423 			break;
4424 
4425 		bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
4426 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
4427 
4428 		cur = &rxr->rx_base[i];
4429 		status = cur->status;
4430 		mp = sendmp = NULL;
4431 
4432 		if ((status & E1000_RXD_STAT_DD) == 0)
4433 			break;
4434 
4435 		len = le16toh(cur->length);
4436 		eop = (status & E1000_RXD_STAT_EOP) != 0;
4437 
4438 		if ((cur->errors & E1000_RXD_ERR_FRAME_ERR_MASK) ||
4439 		    (rxr->discard == TRUE)) {
4440 			ifp->if_ierrors++;
4441 			++rxr->rx_discarded;
4442 			if (!eop) /* Catch subsequent segs */
4443 				rxr->discard = TRUE;
4444 			else
4445 				rxr->discard = FALSE;
4446 			em_rx_discard(rxr, i);
4447 			goto next_desc;
4448 		}
4449 
4450 		/* Assign correct length to the current fragment */
4451 		mp = rxr->rx_buffers[i].m_head;
4452 		mp->m_len = len;
4453 
4454 		/* Trigger for refresh */
4455 		rxr->rx_buffers[i].m_head = NULL;
4456 
4457 		/* First segment? */
4458 		if (rxr->fmp == NULL) {
4459 			mp->m_pkthdr.len = len;
4460 			rxr->fmp = rxr->lmp = mp;
4461 		} else {
4462 			/* Chain mbuf's together */
4463 			mp->m_flags &= ~M_PKTHDR;
4464 			rxr->lmp->m_next = mp;
4465 			rxr->lmp = mp;
4466 			rxr->fmp->m_pkthdr.len += len;
4467 		}
4468 
4469 		if (eop) {
4470 			--count;
4471 			sendmp = rxr->fmp;
4472 			sendmp->m_pkthdr.rcvif = ifp;
4473 			ifp->if_ipackets++;
4474 			em_receive_checksum(cur, sendmp);
4475 #ifndef __NO_STRICT_ALIGNMENT
4476 			if (adapter->max_frame_size >
4477 			    (MCLBYTES - ETHER_ALIGN) &&
4478 			    em_fixup_rx(rxr) != 0)
4479 				goto skip;
4480 #endif
4481 			if (status & E1000_RXD_STAT_VP) {
4482 				sendmp->m_pkthdr.ether_vtag =
4483 				    (le16toh(cur->special) &
4484 				    E1000_RXD_SPC_VLAN_MASK);
4485 				sendmp->m_flags |= M_VLANTAG;
4486 			}
4487 #ifndef __NO_STRICT_ALIGNMENT
4488 skip:
4489 #endif
4490 			rxr->fmp = rxr->lmp = NULL;
4491 		}
4492 next_desc:
4493 		/* Zero out the receive descriptors status. */
4494 		cur->status = 0;
4495 		++rxdone;	/* cumulative for POLL */
4496 		++processed;
4497 
4498 		/* Advance our pointers to the next descriptor. */
4499 		if (++i == adapter->num_rx_desc)
4500 			i = 0;
4501 
4502 		/* Send to the stack */
4503 		if (sendmp != NULL) {
4504 			rxr->next_to_check = i;
4505 			EM_RX_UNLOCK(rxr);
4506 			(*ifp->if_input)(ifp, sendmp);
4507 			EM_RX_LOCK(rxr);
4508 			i = rxr->next_to_check;
4509 		}
4510 
4511 		/* Only refresh mbufs every 8 descriptors */
4512 		if (processed == 8) {
4513 			em_refresh_mbufs(rxr, i);
4514 			processed = 0;
4515 		}
4516 	}
4517 
4518 	/* Catch any remaining refresh work */
4519 	if (e1000_rx_unrefreshed(rxr))
4520 		em_refresh_mbufs(rxr, i);
4521 
4522 	rxr->next_to_check = i;
4523 	if (done != NULL)
4524 		*done = rxdone;
4525 	EM_RX_UNLOCK(rxr);
4526 
4527 	return ((status & E1000_RXD_STAT_DD) ? TRUE : FALSE);
4528 }
4529 
4530 static __inline void
4531 em_rx_discard(struct rx_ring *rxr, int i)
4532 {
4533 	struct em_buffer	*rbuf;
4534 
4535 	rbuf = &rxr->rx_buffers[i];
4536 	/* Free any previous pieces */
4537 	if (rxr->fmp != NULL) {
4538 		rxr->fmp->m_flags |= M_PKTHDR;
4539 		m_freem(rxr->fmp);
4540 		rxr->fmp = NULL;
4541 		rxr->lmp = NULL;
4542 	}
4543 	/*
4544 	** Free buffer and allow em_refresh_mbufs()
4545 	** to clean up and recharge buffer.
4546 	*/
4547 	if (rbuf->m_head) {
4548 		m_free(rbuf->m_head);
4549 		rbuf->m_head = NULL;
4550 	}
4551 	return;
4552 }
4553 
4554 #ifndef __NO_STRICT_ALIGNMENT
4555 /*
4556  * When jumbo frames are enabled we should realign entire payload on
4557  * architecures with strict alignment. This is serious design mistake of 8254x
4558  * as it nullifies DMA operations. 8254x just allows RX buffer size to be
4559  * 2048/4096/8192/16384. What we really want is 2048 - ETHER_ALIGN to align its
4560  * payload. On architecures without strict alignment restrictions 8254x still
4561  * performs unaligned memory access which would reduce the performance too.
4562  * To avoid copying over an entire frame to align, we allocate a new mbuf and
4563  * copy ethernet header to the new mbuf. The new mbuf is prepended into the
4564  * existing mbuf chain.
4565  *
4566  * Be aware, best performance of the 8254x is achived only when jumbo frame is
4567  * not used at all on architectures with strict alignment.
4568  */
4569 static int
4570 em_fixup_rx(struct rx_ring *rxr)
4571 {
4572 	struct adapter *adapter = rxr->adapter;
4573 	struct mbuf *m, *n;
4574 	int error;
4575 
4576 	error = 0;
4577 	m = rxr->fmp;
4578 	if (m->m_len <= (MCLBYTES - ETHER_HDR_LEN)) {
4579 		bcopy(m->m_data, m->m_data + ETHER_HDR_LEN, m->m_len);
4580 		m->m_data += ETHER_HDR_LEN;
4581 	} else {
4582 		MGETHDR(n, M_DONTWAIT, MT_DATA);
4583 		if (n != NULL) {
4584 			bcopy(m->m_data, n->m_data, ETHER_HDR_LEN);
4585 			m->m_data += ETHER_HDR_LEN;
4586 			m->m_len -= ETHER_HDR_LEN;
4587 			n->m_len = ETHER_HDR_LEN;
4588 			M_MOVE_PKTHDR(n, m);
4589 			n->m_next = m;
4590 			rxr->fmp = n;
4591 		} else {
4592 			adapter->dropped_pkts++;
4593 			m_freem(rxr->fmp);
4594 			rxr->fmp = NULL;
4595 			error = ENOMEM;
4596 		}
4597 	}
4598 
4599 	return (error);
4600 }
4601 #endif
4602 
4603 /*********************************************************************
4604  *
4605  *  Verify that the hardware indicated that the checksum is valid.
4606  *  Inform the stack about the status of checksum so that stack
4607  *  doesn't spend time verifying the checksum.
4608  *
4609  *********************************************************************/
4610 static void
4611 em_receive_checksum(struct e1000_rx_desc *rx_desc, struct mbuf *mp)
4612 {
4613 	/* Ignore Checksum bit is set */
4614 	if (rx_desc->status & E1000_RXD_STAT_IXSM) {
4615 		mp->m_pkthdr.csum_flags = 0;
4616 		return;
4617 	}
4618 
4619 	if (rx_desc->status & E1000_RXD_STAT_IPCS) {
4620 		/* Did it pass? */
4621 		if (!(rx_desc->errors & E1000_RXD_ERR_IPE)) {
4622 			/* IP Checksum Good */
4623 			mp->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
4624 			mp->m_pkthdr.csum_flags |= CSUM_IP_VALID;
4625 
4626 		} else {
4627 			mp->m_pkthdr.csum_flags = 0;
4628 		}
4629 	}
4630 
4631 	if (rx_desc->status & E1000_RXD_STAT_TCPCS) {
4632 		/* Did it pass? */
4633 		if (!(rx_desc->errors & E1000_RXD_ERR_TCPE)) {
4634 			mp->m_pkthdr.csum_flags |=
4635 			(CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
4636 			mp->m_pkthdr.csum_data = htons(0xffff);
4637 		}
4638 	}
4639 }
4640 
4641 /*
4642  * This routine is run via an vlan
4643  * config EVENT
4644  */
4645 static void
4646 em_register_vlan(void *arg, struct ifnet *ifp, u16 vtag)
4647 {
4648 	struct adapter	*adapter = ifp->if_softc;
4649 	u32		index, bit;
4650 
4651 	if (ifp->if_softc !=  arg)   /* Not our event */
4652 		return;
4653 
4654 	if ((vtag == 0) || (vtag > 4095))       /* Invalid ID */
4655                 return;
4656 
4657 	EM_CORE_LOCK(adapter);
4658 	index = (vtag >> 5) & 0x7F;
4659 	bit = vtag & 0x1F;
4660 	adapter->shadow_vfta[index] |= (1 << bit);
4661 	++adapter->num_vlans;
4662 	/* Re-init to load the changes */
4663 	if (ifp->if_capenable & IFCAP_VLAN_HWFILTER)
4664 		em_init_locked(adapter);
4665 	EM_CORE_UNLOCK(adapter);
4666 }
4667 
4668 /*
4669  * This routine is run via an vlan
4670  * unconfig EVENT
4671  */
4672 static void
4673 em_unregister_vlan(void *arg, struct ifnet *ifp, u16 vtag)
4674 {
4675 	struct adapter	*adapter = ifp->if_softc;
4676 	u32		index, bit;
4677 
4678 	if (ifp->if_softc !=  arg)
4679 		return;
4680 
4681 	if ((vtag == 0) || (vtag > 4095))       /* Invalid */
4682                 return;
4683 
4684 	EM_CORE_LOCK(adapter);
4685 	index = (vtag >> 5) & 0x7F;
4686 	bit = vtag & 0x1F;
4687 	adapter->shadow_vfta[index] &= ~(1 << bit);
4688 	--adapter->num_vlans;
4689 	/* Re-init to load the changes */
4690 	if (ifp->if_capenable & IFCAP_VLAN_HWFILTER)
4691 		em_init_locked(adapter);
4692 	EM_CORE_UNLOCK(adapter);
4693 }
4694 
4695 static void
4696 em_setup_vlan_hw_support(struct adapter *adapter)
4697 {
4698 	struct e1000_hw *hw = &adapter->hw;
4699 	u32             reg;
4700 
4701 	/*
4702 	** We get here thru init_locked, meaning
4703 	** a soft reset, this has already cleared
4704 	** the VFTA and other state, so if there
4705 	** have been no vlan's registered do nothing.
4706 	*/
4707 	if (adapter->num_vlans == 0)
4708                 return;
4709 
4710 	/*
4711 	** A soft reset zero's out the VFTA, so
4712 	** we need to repopulate it now.
4713 	*/
4714 	for (int i = 0; i < EM_VFTA_SIZE; i++)
4715                 if (adapter->shadow_vfta[i] != 0)
4716 			E1000_WRITE_REG_ARRAY(hw, E1000_VFTA,
4717                             i, adapter->shadow_vfta[i]);
4718 
4719 	reg = E1000_READ_REG(hw, E1000_CTRL);
4720 	reg |= E1000_CTRL_VME;
4721 	E1000_WRITE_REG(hw, E1000_CTRL, reg);
4722 
4723 	/* Enable the Filter Table */
4724 	reg = E1000_READ_REG(hw, E1000_RCTL);
4725 	reg &= ~E1000_RCTL_CFIEN;
4726 	reg |= E1000_RCTL_VFE;
4727 	E1000_WRITE_REG(hw, E1000_RCTL, reg);
4728 }
4729 
4730 static void
4731 em_enable_intr(struct adapter *adapter)
4732 {
4733 	struct e1000_hw *hw = &adapter->hw;
4734 	u32 ims_mask = IMS_ENABLE_MASK;
4735 
4736 	if (hw->mac.type == e1000_82574) {
4737 		E1000_WRITE_REG(hw, EM_EIAC, EM_MSIX_MASK);
4738 		ims_mask |= EM_MSIX_MASK;
4739 	}
4740 	E1000_WRITE_REG(hw, E1000_IMS, ims_mask);
4741 }
4742 
4743 static void
4744 em_disable_intr(struct adapter *adapter)
4745 {
4746 	struct e1000_hw *hw = &adapter->hw;
4747 
4748 	if (hw->mac.type == e1000_82574)
4749 		E1000_WRITE_REG(hw, EM_EIAC, 0);
4750 	E1000_WRITE_REG(&adapter->hw, E1000_IMC, 0xffffffff);
4751 }
4752 
4753 /*
4754  * Bit of a misnomer, what this really means is
4755  * to enable OS management of the system... aka
4756  * to disable special hardware management features
4757  */
4758 static void
4759 em_init_manageability(struct adapter *adapter)
4760 {
4761 	/* A shared code workaround */
4762 #define E1000_82542_MANC2H E1000_MANC2H
4763 	if (adapter->has_manage) {
4764 		int manc2h = E1000_READ_REG(&adapter->hw, E1000_MANC2H);
4765 		int manc = E1000_READ_REG(&adapter->hw, E1000_MANC);
4766 
4767 		/* disable hardware interception of ARP */
4768 		manc &= ~(E1000_MANC_ARP_EN);
4769 
4770                 /* enable receiving management packets to the host */
4771 		manc |= E1000_MANC_EN_MNG2HOST;
4772 #define E1000_MNG2HOST_PORT_623 (1 << 5)
4773 #define E1000_MNG2HOST_PORT_664 (1 << 6)
4774 		manc2h |= E1000_MNG2HOST_PORT_623;
4775 		manc2h |= E1000_MNG2HOST_PORT_664;
4776 		E1000_WRITE_REG(&adapter->hw, E1000_MANC2H, manc2h);
4777 		E1000_WRITE_REG(&adapter->hw, E1000_MANC, manc);
4778 	}
4779 }
4780 
4781 /*
4782  * Give control back to hardware management
4783  * controller if there is one.
4784  */
4785 static void
4786 em_release_manageability(struct adapter *adapter)
4787 {
4788 	if (adapter->has_manage) {
4789 		int manc = E1000_READ_REG(&adapter->hw, E1000_MANC);
4790 
4791 		/* re-enable hardware interception of ARP */
4792 		manc |= E1000_MANC_ARP_EN;
4793 		manc &= ~E1000_MANC_EN_MNG2HOST;
4794 
4795 		E1000_WRITE_REG(&adapter->hw, E1000_MANC, manc);
4796 	}
4797 }
4798 
4799 /*
4800  * em_get_hw_control sets the {CTRL_EXT|FWSM}:DRV_LOAD bit.
4801  * For ASF and Pass Through versions of f/w this means
4802  * that the driver is loaded. For AMT version type f/w
4803  * this means that the network i/f is open.
4804  */
4805 static void
4806 em_get_hw_control(struct adapter *adapter)
4807 {
4808 	u32 ctrl_ext, swsm;
4809 
4810 	if (adapter->hw.mac.type == e1000_82573) {
4811 		swsm = E1000_READ_REG(&adapter->hw, E1000_SWSM);
4812 		E1000_WRITE_REG(&adapter->hw, E1000_SWSM,
4813 		    swsm | E1000_SWSM_DRV_LOAD);
4814 		return;
4815 	}
4816 	/* else */
4817 	ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
4818 	E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT,
4819 	    ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
4820 	return;
4821 }
4822 
4823 /*
4824  * em_release_hw_control resets {CTRL_EXT|FWSM}:DRV_LOAD bit.
4825  * For ASF and Pass Through versions of f/w this means that
4826  * the driver is no longer loaded. For AMT versions of the
4827  * f/w this means that the network i/f is closed.
4828  */
4829 static void
4830 em_release_hw_control(struct adapter *adapter)
4831 {
4832 	u32 ctrl_ext, swsm;
4833 
4834 	if (!adapter->has_manage)
4835 		return;
4836 
4837 	if (adapter->hw.mac.type == e1000_82573) {
4838 		swsm = E1000_READ_REG(&adapter->hw, E1000_SWSM);
4839 		E1000_WRITE_REG(&adapter->hw, E1000_SWSM,
4840 		    swsm & ~E1000_SWSM_DRV_LOAD);
4841 		return;
4842 	}
4843 	/* else */
4844 	ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
4845 	E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT,
4846 	    ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
4847 	return;
4848 }
4849 
4850 static int
4851 em_is_valid_ether_addr(u8 *addr)
4852 {
4853 	char zero_addr[6] = { 0, 0, 0, 0, 0, 0 };
4854 
4855 	if ((addr[0] & 1) || (!bcmp(addr, zero_addr, ETHER_ADDR_LEN))) {
4856 		return (FALSE);
4857 	}
4858 
4859 	return (TRUE);
4860 }
4861 
4862 /*
4863 ** Parse the interface capabilities with regard
4864 ** to both system management and wake-on-lan for
4865 ** later use.
4866 */
4867 static void
4868 em_get_wakeup(device_t dev)
4869 {
4870 	struct adapter	*adapter = device_get_softc(dev);
4871 	u16		eeprom_data = 0, device_id, apme_mask;
4872 
4873 	adapter->has_manage = e1000_enable_mng_pass_thru(&adapter->hw);
4874 	apme_mask = EM_EEPROM_APME;
4875 
4876 	switch (adapter->hw.mac.type) {
4877 	case e1000_82573:
4878 	case e1000_82583:
4879 		adapter->has_amt = TRUE;
4880 		/* Falls thru */
4881 	case e1000_82571:
4882 	case e1000_82572:
4883 	case e1000_80003es2lan:
4884 		if (adapter->hw.bus.func == 1) {
4885 			e1000_read_nvm(&adapter->hw,
4886 			    NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
4887 			break;
4888 		} else
4889 			e1000_read_nvm(&adapter->hw,
4890 			    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
4891 		break;
4892 	case e1000_ich8lan:
4893 	case e1000_ich9lan:
4894 	case e1000_ich10lan:
4895 	case e1000_pchlan:
4896 	case e1000_pch2lan:
4897 		apme_mask = E1000_WUC_APME;
4898 		adapter->has_amt = TRUE;
4899 		eeprom_data = E1000_READ_REG(&adapter->hw, E1000_WUC);
4900 		break;
4901 	default:
4902 		e1000_read_nvm(&adapter->hw,
4903 		    NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
4904 		break;
4905 	}
4906 	if (eeprom_data & apme_mask)
4907 		adapter->wol = (E1000_WUFC_MAG | E1000_WUFC_MC);
4908 	/*
4909          * We have the eeprom settings, now apply the special cases
4910          * where the eeprom may be wrong or the board won't support
4911          * wake on lan on a particular port
4912 	 */
4913 	device_id = pci_get_device(dev);
4914         switch (device_id) {
4915 	case E1000_DEV_ID_82571EB_FIBER:
4916 		/* Wake events only supported on port A for dual fiber
4917 		 * regardless of eeprom setting */
4918 		if (E1000_READ_REG(&adapter->hw, E1000_STATUS) &
4919 		    E1000_STATUS_FUNC_1)
4920 			adapter->wol = 0;
4921 		break;
4922 	case E1000_DEV_ID_82571EB_QUAD_COPPER:
4923 	case E1000_DEV_ID_82571EB_QUAD_FIBER:
4924 	case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
4925                 /* if quad port adapter, disable WoL on all but port A */
4926 		if (global_quad_port_a != 0)
4927 			adapter->wol = 0;
4928 		/* Reset for multiple quad port adapters */
4929 		if (++global_quad_port_a == 4)
4930 			global_quad_port_a = 0;
4931                 break;
4932 	}
4933 	return;
4934 }
4935 
4936 
4937 /*
4938  * Enable PCI Wake On Lan capability
4939  */
4940 static void
4941 em_enable_wakeup(device_t dev)
4942 {
4943 	struct adapter	*adapter = device_get_softc(dev);
4944 	struct ifnet	*ifp = adapter->ifp;
4945 	u32		pmc, ctrl, ctrl_ext, rctl;
4946 	u16     	status;
4947 
4948 	if ((pci_find_cap(dev, PCIY_PMG, &pmc) != 0))
4949 		return;
4950 
4951 	/* Advertise the wakeup capability */
4952 	ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
4953 	ctrl |= (E1000_CTRL_SWDPIN2 | E1000_CTRL_SWDPIN3);
4954 	E1000_WRITE_REG(&adapter->hw, E1000_CTRL, ctrl);
4955 	E1000_WRITE_REG(&adapter->hw, E1000_WUC, E1000_WUC_PME_EN);
4956 
4957 	if ((adapter->hw.mac.type == e1000_ich8lan) ||
4958 	    (adapter->hw.mac.type == e1000_pchlan) ||
4959 	    (adapter->hw.mac.type == e1000_ich9lan) ||
4960 	    (adapter->hw.mac.type == e1000_ich10lan))
4961 		e1000_suspend_workarounds_ich8lan(&adapter->hw);
4962 
4963 	/* Keep the laser running on Fiber adapters */
4964 	if (adapter->hw.phy.media_type == e1000_media_type_fiber ||
4965 	    adapter->hw.phy.media_type == e1000_media_type_internal_serdes) {
4966 		ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
4967 		ctrl_ext |= E1000_CTRL_EXT_SDP3_DATA;
4968 		E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT, ctrl_ext);
4969 	}
4970 
4971 	/*
4972 	** Determine type of Wakeup: note that wol
4973 	** is set with all bits on by default.
4974 	*/
4975 	if ((ifp->if_capenable & IFCAP_WOL_MAGIC) == 0)
4976 		adapter->wol &= ~E1000_WUFC_MAG;
4977 
4978 	if ((ifp->if_capenable & IFCAP_WOL_MCAST) == 0)
4979 		adapter->wol &= ~E1000_WUFC_MC;
4980 	else {
4981 		rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
4982 		rctl |= E1000_RCTL_MPE;
4983 		E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
4984 	}
4985 
4986 	if ((adapter->hw.mac.type == e1000_pchlan) ||
4987 	    (adapter->hw.mac.type == e1000_pch2lan)) {
4988 		if (em_enable_phy_wakeup(adapter))
4989 			return;
4990 	} else {
4991 		E1000_WRITE_REG(&adapter->hw, E1000_WUC, E1000_WUC_PME_EN);
4992 		E1000_WRITE_REG(&adapter->hw, E1000_WUFC, adapter->wol);
4993 	}
4994 
4995 	if (adapter->hw.phy.type == e1000_phy_igp_3)
4996 		e1000_igp3_phy_powerdown_workaround_ich8lan(&adapter->hw);
4997 
4998         /* Request PME */
4999         status = pci_read_config(dev, pmc + PCIR_POWER_STATUS, 2);
5000 	status &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE);
5001 	if (ifp->if_capenable & IFCAP_WOL)
5002 		status |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
5003         pci_write_config(dev, pmc + PCIR_POWER_STATUS, status, 2);
5004 
5005 	return;
5006 }
5007 
5008 /*
5009 ** WOL in the newer chipset interfaces (pchlan)
5010 ** require thing to be copied into the phy
5011 */
5012 static int
5013 em_enable_phy_wakeup(struct adapter *adapter)
5014 {
5015 	struct e1000_hw *hw = &adapter->hw;
5016 	u32 mreg, ret = 0;
5017 	u16 preg;
5018 
5019 	/* copy MAC RARs to PHY RARs */
5020 	e1000_copy_rx_addrs_to_phy_ich8lan(hw);
5021 
5022 	/* copy MAC MTA to PHY MTA */
5023 	for (int i = 0; i < adapter->hw.mac.mta_reg_count; i++) {
5024 		mreg = E1000_READ_REG_ARRAY(hw, E1000_MTA, i);
5025 		e1000_write_phy_reg(hw, BM_MTA(i), (u16)(mreg & 0xFFFF));
5026 		e1000_write_phy_reg(hw, BM_MTA(i) + 1,
5027 		    (u16)((mreg >> 16) & 0xFFFF));
5028 	}
5029 
5030 	/* configure PHY Rx Control register */
5031 	e1000_read_phy_reg(&adapter->hw, BM_RCTL, &preg);
5032 	mreg = E1000_READ_REG(hw, E1000_RCTL);
5033 	if (mreg & E1000_RCTL_UPE)
5034 		preg |= BM_RCTL_UPE;
5035 	if (mreg & E1000_RCTL_MPE)
5036 		preg |= BM_RCTL_MPE;
5037 	preg &= ~(BM_RCTL_MO_MASK);
5038 	if (mreg & E1000_RCTL_MO_3)
5039 		preg |= (((mreg & E1000_RCTL_MO_3) >> E1000_RCTL_MO_SHIFT)
5040 				<< BM_RCTL_MO_SHIFT);
5041 	if (mreg & E1000_RCTL_BAM)
5042 		preg |= BM_RCTL_BAM;
5043 	if (mreg & E1000_RCTL_PMCF)
5044 		preg |= BM_RCTL_PMCF;
5045 	mreg = E1000_READ_REG(hw, E1000_CTRL);
5046 	if (mreg & E1000_CTRL_RFCE)
5047 		preg |= BM_RCTL_RFCE;
5048 	e1000_write_phy_reg(&adapter->hw, BM_RCTL, preg);
5049 
5050 	/* enable PHY wakeup in MAC register */
5051 	E1000_WRITE_REG(hw, E1000_WUC,
5052 	    E1000_WUC_PHY_WAKE | E1000_WUC_PME_EN);
5053 	E1000_WRITE_REG(hw, E1000_WUFC, adapter->wol);
5054 
5055 	/* configure and enable PHY wakeup in PHY registers */
5056 	e1000_write_phy_reg(&adapter->hw, BM_WUFC, adapter->wol);
5057 	e1000_write_phy_reg(&adapter->hw, BM_WUC, E1000_WUC_PME_EN);
5058 
5059 	/* activate PHY wakeup */
5060 	ret = hw->phy.ops.acquire(hw);
5061 	if (ret) {
5062 		printf("Could not acquire PHY\n");
5063 		return ret;
5064 	}
5065 	e1000_write_phy_reg_mdic(hw, IGP01E1000_PHY_PAGE_SELECT,
5066 	                         (BM_WUC_ENABLE_PAGE << IGP_PAGE_SHIFT));
5067 	ret = e1000_read_phy_reg_mdic(hw, BM_WUC_ENABLE_REG, &preg);
5068 	if (ret) {
5069 		printf("Could not read PHY page 769\n");
5070 		goto out;
5071 	}
5072 	preg |= BM_WUC_ENABLE_BIT | BM_WUC_HOST_WU_BIT;
5073 	ret = e1000_write_phy_reg_mdic(hw, BM_WUC_ENABLE_REG, preg);
5074 	if (ret)
5075 		printf("Could not set PHY Host Wakeup bit\n");
5076 out:
5077 	hw->phy.ops.release(hw);
5078 
5079 	return ret;
5080 }
5081 
5082 static void
5083 em_led_func(void *arg, int onoff)
5084 {
5085 	struct adapter	*adapter = arg;
5086 
5087 	EM_CORE_LOCK(adapter);
5088 	if (onoff) {
5089 		e1000_setup_led(&adapter->hw);
5090 		e1000_led_on(&adapter->hw);
5091 	} else {
5092 		e1000_led_off(&adapter->hw);
5093 		e1000_cleanup_led(&adapter->hw);
5094 	}
5095 	EM_CORE_UNLOCK(adapter);
5096 }
5097 
5098 /*
5099 ** Disable the L0S and L1 LINK states
5100 */
5101 static void
5102 em_disable_aspm(struct adapter *adapter)
5103 {
5104 	int		base, reg;
5105 	u16		link_cap,link_ctrl;
5106 	device_t	dev = adapter->dev;
5107 
5108 	switch (adapter->hw.mac.type) {
5109 		case e1000_82573:
5110 		case e1000_82574:
5111 		case e1000_82583:
5112 			break;
5113 		default:
5114 			return;
5115 	}
5116 	if (pci_find_cap(dev, PCIY_EXPRESS, &base) != 0)
5117 		return;
5118 	reg = base + PCIR_EXPRESS_LINK_CAP;
5119 	link_cap = pci_read_config(dev, reg, 2);
5120 	if ((link_cap & PCIM_LINK_CAP_ASPM) == 0)
5121 		return;
5122 	reg = base + PCIR_EXPRESS_LINK_CTL;
5123 	link_ctrl = pci_read_config(dev, reg, 2);
5124 	link_ctrl &= 0xFFFC; /* turn off bit 1 and 2 */
5125 	pci_write_config(dev, reg, link_ctrl, 2);
5126 	return;
5127 }
5128 
5129 /**********************************************************************
5130  *
5131  *  Update the board statistics counters.
5132  *
5133  **********************************************************************/
5134 static void
5135 em_update_stats_counters(struct adapter *adapter)
5136 {
5137 	struct ifnet   *ifp;
5138 
5139 	if(adapter->hw.phy.media_type == e1000_media_type_copper ||
5140 	   (E1000_READ_REG(&adapter->hw, E1000_STATUS) & E1000_STATUS_LU)) {
5141 		adapter->stats.symerrs += E1000_READ_REG(&adapter->hw, E1000_SYMERRS);
5142 		adapter->stats.sec += E1000_READ_REG(&adapter->hw, E1000_SEC);
5143 	}
5144 	adapter->stats.crcerrs += E1000_READ_REG(&adapter->hw, E1000_CRCERRS);
5145 	adapter->stats.mpc += E1000_READ_REG(&adapter->hw, E1000_MPC);
5146 	adapter->stats.scc += E1000_READ_REG(&adapter->hw, E1000_SCC);
5147 	adapter->stats.ecol += E1000_READ_REG(&adapter->hw, E1000_ECOL);
5148 
5149 	adapter->stats.mcc += E1000_READ_REG(&adapter->hw, E1000_MCC);
5150 	adapter->stats.latecol += E1000_READ_REG(&adapter->hw, E1000_LATECOL);
5151 	adapter->stats.colc += E1000_READ_REG(&adapter->hw, E1000_COLC);
5152 	adapter->stats.dc += E1000_READ_REG(&adapter->hw, E1000_DC);
5153 	adapter->stats.rlec += E1000_READ_REG(&adapter->hw, E1000_RLEC);
5154 	adapter->stats.xonrxc += E1000_READ_REG(&adapter->hw, E1000_XONRXC);
5155 	adapter->stats.xontxc += E1000_READ_REG(&adapter->hw, E1000_XONTXC);
5156 	/*
5157 	** For watchdog management we need to know if we have been
5158 	** paused during the last interval, so capture that here.
5159 	*/
5160 	adapter->pause_frames = E1000_READ_REG(&adapter->hw, E1000_XOFFRXC);
5161 	adapter->stats.xoffrxc += adapter->pause_frames;
5162 	adapter->stats.xofftxc += E1000_READ_REG(&adapter->hw, E1000_XOFFTXC);
5163 	adapter->stats.fcruc += E1000_READ_REG(&adapter->hw, E1000_FCRUC);
5164 	adapter->stats.prc64 += E1000_READ_REG(&adapter->hw, E1000_PRC64);
5165 	adapter->stats.prc127 += E1000_READ_REG(&adapter->hw, E1000_PRC127);
5166 	adapter->stats.prc255 += E1000_READ_REG(&adapter->hw, E1000_PRC255);
5167 	adapter->stats.prc511 += E1000_READ_REG(&adapter->hw, E1000_PRC511);
5168 	adapter->stats.prc1023 += E1000_READ_REG(&adapter->hw, E1000_PRC1023);
5169 	adapter->stats.prc1522 += E1000_READ_REG(&adapter->hw, E1000_PRC1522);
5170 	adapter->stats.gprc += E1000_READ_REG(&adapter->hw, E1000_GPRC);
5171 	adapter->stats.bprc += E1000_READ_REG(&adapter->hw, E1000_BPRC);
5172 	adapter->stats.mprc += E1000_READ_REG(&adapter->hw, E1000_MPRC);
5173 	adapter->stats.gptc += E1000_READ_REG(&adapter->hw, E1000_GPTC);
5174 
5175 	/* For the 64-bit byte counters the low dword must be read first. */
5176 	/* Both registers clear on the read of the high dword */
5177 
5178 	adapter->stats.gorc += E1000_READ_REG(&adapter->hw, E1000_GORCL) +
5179 	    ((u64)E1000_READ_REG(&adapter->hw, E1000_GORCH) << 32);
5180 	adapter->stats.gotc += E1000_READ_REG(&adapter->hw, E1000_GOTCL) +
5181 	    ((u64)E1000_READ_REG(&adapter->hw, E1000_GOTCH) << 32);
5182 
5183 	adapter->stats.rnbc += E1000_READ_REG(&adapter->hw, E1000_RNBC);
5184 	adapter->stats.ruc += E1000_READ_REG(&adapter->hw, E1000_RUC);
5185 	adapter->stats.rfc += E1000_READ_REG(&adapter->hw, E1000_RFC);
5186 	adapter->stats.roc += E1000_READ_REG(&adapter->hw, E1000_ROC);
5187 	adapter->stats.rjc += E1000_READ_REG(&adapter->hw, E1000_RJC);
5188 
5189 	adapter->stats.tor += E1000_READ_REG(&adapter->hw, E1000_TORH);
5190 	adapter->stats.tot += E1000_READ_REG(&adapter->hw, E1000_TOTH);
5191 
5192 	adapter->stats.tpr += E1000_READ_REG(&adapter->hw, E1000_TPR);
5193 	adapter->stats.tpt += E1000_READ_REG(&adapter->hw, E1000_TPT);
5194 	adapter->stats.ptc64 += E1000_READ_REG(&adapter->hw, E1000_PTC64);
5195 	adapter->stats.ptc127 += E1000_READ_REG(&adapter->hw, E1000_PTC127);
5196 	adapter->stats.ptc255 += E1000_READ_REG(&adapter->hw, E1000_PTC255);
5197 	adapter->stats.ptc511 += E1000_READ_REG(&adapter->hw, E1000_PTC511);
5198 	adapter->stats.ptc1023 += E1000_READ_REG(&adapter->hw, E1000_PTC1023);
5199 	adapter->stats.ptc1522 += E1000_READ_REG(&adapter->hw, E1000_PTC1522);
5200 	adapter->stats.mptc += E1000_READ_REG(&adapter->hw, E1000_MPTC);
5201 	adapter->stats.bptc += E1000_READ_REG(&adapter->hw, E1000_BPTC);
5202 
5203 	/* Interrupt Counts */
5204 
5205 	adapter->stats.iac += E1000_READ_REG(&adapter->hw, E1000_IAC);
5206 	adapter->stats.icrxptc += E1000_READ_REG(&adapter->hw, E1000_ICRXPTC);
5207 	adapter->stats.icrxatc += E1000_READ_REG(&adapter->hw, E1000_ICRXATC);
5208 	adapter->stats.ictxptc += E1000_READ_REG(&adapter->hw, E1000_ICTXPTC);
5209 	adapter->stats.ictxatc += E1000_READ_REG(&adapter->hw, E1000_ICTXATC);
5210 	adapter->stats.ictxqec += E1000_READ_REG(&adapter->hw, E1000_ICTXQEC);
5211 	adapter->stats.ictxqmtc += E1000_READ_REG(&adapter->hw, E1000_ICTXQMTC);
5212 	adapter->stats.icrxdmtc += E1000_READ_REG(&adapter->hw, E1000_ICRXDMTC);
5213 	adapter->stats.icrxoc += E1000_READ_REG(&adapter->hw, E1000_ICRXOC);
5214 
5215 	if (adapter->hw.mac.type >= e1000_82543) {
5216 		adapter->stats.algnerrc +=
5217 		E1000_READ_REG(&adapter->hw, E1000_ALGNERRC);
5218 		adapter->stats.rxerrc +=
5219 		E1000_READ_REG(&adapter->hw, E1000_RXERRC);
5220 		adapter->stats.tncrs +=
5221 		E1000_READ_REG(&adapter->hw, E1000_TNCRS);
5222 		adapter->stats.cexterr +=
5223 		E1000_READ_REG(&adapter->hw, E1000_CEXTERR);
5224 		adapter->stats.tsctc +=
5225 		E1000_READ_REG(&adapter->hw, E1000_TSCTC);
5226 		adapter->stats.tsctfc +=
5227 		E1000_READ_REG(&adapter->hw, E1000_TSCTFC);
5228 	}
5229 	ifp = adapter->ifp;
5230 
5231 	ifp->if_collisions = adapter->stats.colc;
5232 
5233 	/* Rx Errors */
5234 	ifp->if_ierrors = adapter->dropped_pkts + adapter->stats.rxerrc +
5235 	    adapter->stats.crcerrs + adapter->stats.algnerrc +
5236 	    adapter->stats.ruc + adapter->stats.roc +
5237 	    adapter->stats.mpc + adapter->stats.cexterr;
5238 
5239 	/* Tx Errors */
5240 	ifp->if_oerrors = adapter->stats.ecol +
5241 	    adapter->stats.latecol + adapter->watchdog_events;
5242 }
5243 
5244 /* Export a single 32-bit register via a read-only sysctl. */
5245 static int
5246 em_sysctl_reg_handler(SYSCTL_HANDLER_ARGS)
5247 {
5248 	struct adapter *adapter;
5249 	u_int val;
5250 
5251 	adapter = oidp->oid_arg1;
5252 	val = E1000_READ_REG(&adapter->hw, oidp->oid_arg2);
5253 	return (sysctl_handle_int(oidp, &val, 0, req));
5254 }
5255 
5256 /*
5257  * Add sysctl variables, one per statistic, to the system.
5258  */
5259 static void
5260 em_add_hw_stats(struct adapter *adapter)
5261 {
5262 	device_t dev = adapter->dev;
5263 
5264 	struct tx_ring *txr = adapter->tx_rings;
5265 	struct rx_ring *rxr = adapter->rx_rings;
5266 
5267 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(dev);
5268 	struct sysctl_oid *tree = device_get_sysctl_tree(dev);
5269 	struct sysctl_oid_list *child = SYSCTL_CHILDREN(tree);
5270 	struct e1000_hw_stats *stats = &adapter->stats;
5271 
5272 	struct sysctl_oid *stat_node, *queue_node, *int_node;
5273 	struct sysctl_oid_list *stat_list, *queue_list, *int_list;
5274 
5275 #define QUEUE_NAME_LEN 32
5276 	char namebuf[QUEUE_NAME_LEN];
5277 
5278 	/* Driver Statistics */
5279 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "link_irq",
5280 			CTLFLAG_RD, &adapter->link_irq,
5281 			"Link MSIX IRQ Handled");
5282 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "mbuf_alloc_fail",
5283 			 CTLFLAG_RD, &adapter->mbuf_alloc_failed,
5284 			 "Std mbuf failed");
5285 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "cluster_alloc_fail",
5286 			 CTLFLAG_RD, &adapter->mbuf_cluster_failed,
5287 			 "Std mbuf cluster failed");
5288 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "dropped",
5289 			CTLFLAG_RD, &adapter->dropped_pkts,
5290 			"Driver dropped packets");
5291 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_dma_fail",
5292 			CTLFLAG_RD, &adapter->no_tx_dma_setup,
5293 			"Driver tx dma failure in xmit");
5294 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "rx_overruns",
5295 			CTLFLAG_RD, &adapter->rx_overruns,
5296 			"RX overruns");
5297 	SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "watchdog_timeouts",
5298 			CTLFLAG_RD, &adapter->watchdog_events,
5299 			"Watchdog timeouts");
5300 
5301 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "device_control",
5302 			CTLTYPE_UINT | CTLFLAG_RD, adapter, E1000_CTRL,
5303 			em_sysctl_reg_handler, "IU",
5304 			"Device Control Register");
5305 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "rx_control",
5306 			CTLTYPE_UINT | CTLFLAG_RD, adapter, E1000_RCTL,
5307 			em_sysctl_reg_handler, "IU",
5308 			"Receiver Control Register");
5309 	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "fc_high_water",
5310 			CTLFLAG_RD, &adapter->hw.fc.high_water, 0,
5311 			"Flow Control High Watermark");
5312 	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "fc_low_water",
5313 			CTLFLAG_RD, &adapter->hw.fc.low_water, 0,
5314 			"Flow Control Low Watermark");
5315 
5316 	for (int i = 0; i < adapter->num_queues; i++, rxr++, txr++) {
5317 		snprintf(namebuf, QUEUE_NAME_LEN, "queue%d", i);
5318 		queue_node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, namebuf,
5319 					    CTLFLAG_RD, NULL, "Queue Name");
5320 		queue_list = SYSCTL_CHILDREN(queue_node);
5321 
5322 		SYSCTL_ADD_PROC(ctx, queue_list, OID_AUTO, "txd_head",
5323 				CTLTYPE_UINT | CTLFLAG_RD, adapter,
5324 				E1000_TDH(txr->me),
5325 				em_sysctl_reg_handler, "IU",
5326  				"Transmit Descriptor Head");
5327 		SYSCTL_ADD_PROC(ctx, queue_list, OID_AUTO, "txd_tail",
5328 				CTLTYPE_UINT | CTLFLAG_RD, adapter,
5329 				E1000_TDT(txr->me),
5330 				em_sysctl_reg_handler, "IU",
5331  				"Transmit Descriptor Tail");
5332 		SYSCTL_ADD_ULONG(ctx, queue_list, OID_AUTO, "tx_irq",
5333 				CTLFLAG_RD, &txr->tx_irq,
5334 				"Queue MSI-X Transmit Interrupts");
5335 		SYSCTL_ADD_ULONG(ctx, queue_list, OID_AUTO, "no_desc_avail",
5336 				CTLFLAG_RD, &txr->no_desc_avail,
5337 				"Queue No Descriptor Available");
5338 
5339 		SYSCTL_ADD_PROC(ctx, queue_list, OID_AUTO, "rxd_head",
5340 				CTLTYPE_UINT | CTLFLAG_RD, adapter,
5341 				E1000_RDH(rxr->me),
5342 				em_sysctl_reg_handler, "IU",
5343 				"Receive Descriptor Head");
5344 		SYSCTL_ADD_PROC(ctx, queue_list, OID_AUTO, "rxd_tail",
5345 				CTLTYPE_UINT | CTLFLAG_RD, adapter,
5346 				E1000_RDT(rxr->me),
5347 				em_sysctl_reg_handler, "IU",
5348 				"Receive Descriptor Tail");
5349 		SYSCTL_ADD_ULONG(ctx, queue_list, OID_AUTO, "rx_irq",
5350 				CTLFLAG_RD, &rxr->rx_irq,
5351 				"Queue MSI-X Receive Interrupts");
5352 	}
5353 
5354 	/* MAC stats get their own sub node */
5355 
5356 	stat_node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "mac_stats",
5357 				    CTLFLAG_RD, NULL, "Statistics");
5358 	stat_list = SYSCTL_CHILDREN(stat_node);
5359 
5360 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "excess_coll",
5361 			CTLFLAG_RD, &stats->ecol,
5362 			"Excessive collisions");
5363 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "single_coll",
5364 			CTLFLAG_RD, &stats->scc,
5365 			"Single collisions");
5366 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "multiple_coll",
5367 			CTLFLAG_RD, &stats->mcc,
5368 			"Multiple collisions");
5369 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "late_coll",
5370 			CTLFLAG_RD, &stats->latecol,
5371 			"Late collisions");
5372 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "collision_count",
5373 			CTLFLAG_RD, &stats->colc,
5374 			"Collision Count");
5375 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "symbol_errors",
5376 			CTLFLAG_RD, &adapter->stats.symerrs,
5377 			"Symbol Errors");
5378 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "sequence_errors",
5379 			CTLFLAG_RD, &adapter->stats.sec,
5380 			"Sequence Errors");
5381 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "defer_count",
5382 			CTLFLAG_RD, &adapter->stats.dc,
5383 			"Defer Count");
5384 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "missed_packets",
5385 			CTLFLAG_RD, &adapter->stats.mpc,
5386 			"Missed Packets");
5387 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "recv_no_buff",
5388 			CTLFLAG_RD, &adapter->stats.rnbc,
5389 			"Receive No Buffers");
5390 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "recv_undersize",
5391 			CTLFLAG_RD, &adapter->stats.ruc,
5392 			"Receive Undersize");
5393 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "recv_fragmented",
5394 			CTLFLAG_RD, &adapter->stats.rfc,
5395 			"Fragmented Packets Received ");
5396 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "recv_oversize",
5397 			CTLFLAG_RD, &adapter->stats.roc,
5398 			"Oversized Packets Received");
5399 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "recv_jabber",
5400 			CTLFLAG_RD, &adapter->stats.rjc,
5401 			"Recevied Jabber");
5402 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "recv_errs",
5403 			CTLFLAG_RD, &adapter->stats.rxerrc,
5404 			"Receive Errors");
5405 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "crc_errs",
5406 			CTLFLAG_RD, &adapter->stats.crcerrs,
5407 			"CRC errors");
5408 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "alignment_errs",
5409 			CTLFLAG_RD, &adapter->stats.algnerrc,
5410 			"Alignment Errors");
5411 	/* On 82575 these are collision counts */
5412 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "coll_ext_errs",
5413 			CTLFLAG_RD, &adapter->stats.cexterr,
5414 			"Collision/Carrier extension errors");
5415 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "xon_recvd",
5416 			CTLFLAG_RD, &adapter->stats.xonrxc,
5417 			"XON Received");
5418 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "xon_txd",
5419 			CTLFLAG_RD, &adapter->stats.xontxc,
5420 			"XON Transmitted");
5421 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "xoff_recvd",
5422 			CTLFLAG_RD, &adapter->stats.xoffrxc,
5423 			"XOFF Received");
5424 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "xoff_txd",
5425 			CTLFLAG_RD, &adapter->stats.xofftxc,
5426 			"XOFF Transmitted");
5427 
5428 	/* Packet Reception Stats */
5429 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "total_pkts_recvd",
5430 			CTLFLAG_RD, &adapter->stats.tpr,
5431 			"Total Packets Received ");
5432 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "good_pkts_recvd",
5433 			CTLFLAG_RD, &adapter->stats.gprc,
5434 			"Good Packets Received");
5435 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "bcast_pkts_recvd",
5436 			CTLFLAG_RD, &adapter->stats.bprc,
5437 			"Broadcast Packets Received");
5438 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "mcast_pkts_recvd",
5439 			CTLFLAG_RD, &adapter->stats.mprc,
5440 			"Multicast Packets Received");
5441 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "rx_frames_64",
5442 			CTLFLAG_RD, &adapter->stats.prc64,
5443 			"64 byte frames received ");
5444 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "rx_frames_65_127",
5445 			CTLFLAG_RD, &adapter->stats.prc127,
5446 			"65-127 byte frames received");
5447 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "rx_frames_128_255",
5448 			CTLFLAG_RD, &adapter->stats.prc255,
5449 			"128-255 byte frames received");
5450 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "rx_frames_256_511",
5451 			CTLFLAG_RD, &adapter->stats.prc511,
5452 			"256-511 byte frames received");
5453 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "rx_frames_512_1023",
5454 			CTLFLAG_RD, &adapter->stats.prc1023,
5455 			"512-1023 byte frames received");
5456 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "rx_frames_1024_1522",
5457 			CTLFLAG_RD, &adapter->stats.prc1522,
5458 			"1023-1522 byte frames received");
5459  	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "good_octets_recvd",
5460  			CTLFLAG_RD, &adapter->stats.gorc,
5461  			"Good Octets Received");
5462 
5463 	/* Packet Transmission Stats */
5464  	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "good_octets_txd",
5465  			CTLFLAG_RD, &adapter->stats.gotc,
5466  			"Good Octets Transmitted");
5467 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "total_pkts_txd",
5468 			CTLFLAG_RD, &adapter->stats.tpt,
5469 			"Total Packets Transmitted");
5470 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "good_pkts_txd",
5471 			CTLFLAG_RD, &adapter->stats.gptc,
5472 			"Good Packets Transmitted");
5473 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "bcast_pkts_txd",
5474 			CTLFLAG_RD, &adapter->stats.bptc,
5475 			"Broadcast Packets Transmitted");
5476 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "mcast_pkts_txd",
5477 			CTLFLAG_RD, &adapter->stats.mptc,
5478 			"Multicast Packets Transmitted");
5479 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tx_frames_64",
5480 			CTLFLAG_RD, &adapter->stats.ptc64,
5481 			"64 byte frames transmitted ");
5482 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tx_frames_65_127",
5483 			CTLFLAG_RD, &adapter->stats.ptc127,
5484 			"65-127 byte frames transmitted");
5485 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tx_frames_128_255",
5486 			CTLFLAG_RD, &adapter->stats.ptc255,
5487 			"128-255 byte frames transmitted");
5488 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tx_frames_256_511",
5489 			CTLFLAG_RD, &adapter->stats.ptc511,
5490 			"256-511 byte frames transmitted");
5491 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tx_frames_512_1023",
5492 			CTLFLAG_RD, &adapter->stats.ptc1023,
5493 			"512-1023 byte frames transmitted");
5494 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tx_frames_1024_1522",
5495 			CTLFLAG_RD, &adapter->stats.ptc1522,
5496 			"1024-1522 byte frames transmitted");
5497 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tso_txd",
5498 			CTLFLAG_RD, &adapter->stats.tsctc,
5499 			"TSO Contexts Transmitted");
5500 	SYSCTL_ADD_UQUAD(ctx, stat_list, OID_AUTO, "tso_ctx_fail",
5501 			CTLFLAG_RD, &adapter->stats.tsctfc,
5502 			"TSO Contexts Failed");
5503 
5504 
5505 	/* Interrupt Stats */
5506 
5507 	int_node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "interrupts",
5508 				    CTLFLAG_RD, NULL, "Interrupt Statistics");
5509 	int_list = SYSCTL_CHILDREN(int_node);
5510 
5511 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "asserts",
5512 			CTLFLAG_RD, &adapter->stats.iac,
5513 			"Interrupt Assertion Count");
5514 
5515 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "rx_pkt_timer",
5516 			CTLFLAG_RD, &adapter->stats.icrxptc,
5517 			"Interrupt Cause Rx Pkt Timer Expire Count");
5518 
5519 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "rx_abs_timer",
5520 			CTLFLAG_RD, &adapter->stats.icrxatc,
5521 			"Interrupt Cause Rx Abs Timer Expire Count");
5522 
5523 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "tx_pkt_timer",
5524 			CTLFLAG_RD, &adapter->stats.ictxptc,
5525 			"Interrupt Cause Tx Pkt Timer Expire Count");
5526 
5527 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "tx_abs_timer",
5528 			CTLFLAG_RD, &adapter->stats.ictxatc,
5529 			"Interrupt Cause Tx Abs Timer Expire Count");
5530 
5531 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "tx_queue_empty",
5532 			CTLFLAG_RD, &adapter->stats.ictxqec,
5533 			"Interrupt Cause Tx Queue Empty Count");
5534 
5535 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "tx_queue_min_thresh",
5536 			CTLFLAG_RD, &adapter->stats.ictxqmtc,
5537 			"Interrupt Cause Tx Queue Min Thresh Count");
5538 
5539 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "rx_desc_min_thresh",
5540 			CTLFLAG_RD, &adapter->stats.icrxdmtc,
5541 			"Interrupt Cause Rx Desc Min Thresh Count");
5542 
5543 	SYSCTL_ADD_UQUAD(ctx, int_list, OID_AUTO, "rx_overrun",
5544 			CTLFLAG_RD, &adapter->stats.icrxoc,
5545 			"Interrupt Cause Receiver Overrun Count");
5546 }
5547 
5548 /**********************************************************************
5549  *
5550  *  This routine provides a way to dump out the adapter eeprom,
5551  *  often a useful debug/service tool. This only dumps the first
5552  *  32 words, stuff that matters is in that extent.
5553  *
5554  **********************************************************************/
5555 static int
5556 em_sysctl_nvm_info(SYSCTL_HANDLER_ARGS)
5557 {
5558 	struct adapter *adapter = (struct adapter *)arg1;
5559 	int error;
5560 	int result;
5561 
5562 	result = -1;
5563 	error = sysctl_handle_int(oidp, &result, 0, req);
5564 
5565 	if (error || !req->newptr)
5566 		return (error);
5567 
5568 	/*
5569 	 * This value will cause a hex dump of the
5570 	 * first 32 16-bit words of the EEPROM to
5571 	 * the screen.
5572 	 */
5573 	if (result == 1)
5574 		em_print_nvm_info(adapter);
5575 
5576 	return (error);
5577 }
5578 
5579 static void
5580 em_print_nvm_info(struct adapter *adapter)
5581 {
5582 	u16	eeprom_data;
5583 	int	i, j, row = 0;
5584 
5585 	/* Its a bit crude, but it gets the job done */
5586 	printf("\nInterface EEPROM Dump:\n");
5587 	printf("Offset\n0x0000  ");
5588 	for (i = 0, j = 0; i < 32; i++, j++) {
5589 		if (j == 8) { /* Make the offset block */
5590 			j = 0; ++row;
5591 			printf("\n0x00%x0  ",row);
5592 		}
5593 		e1000_read_nvm(&adapter->hw, i, 1, &eeprom_data);
5594 		printf("%04x ", eeprom_data);
5595 	}
5596 	printf("\n");
5597 }
5598 
5599 static int
5600 em_sysctl_int_delay(SYSCTL_HANDLER_ARGS)
5601 {
5602 	struct em_int_delay_info *info;
5603 	struct adapter *adapter;
5604 	u32 regval;
5605 	int error, usecs, ticks;
5606 
5607 	info = (struct em_int_delay_info *)arg1;
5608 	usecs = info->value;
5609 	error = sysctl_handle_int(oidp, &usecs, 0, req);
5610 	if (error != 0 || req->newptr == NULL)
5611 		return (error);
5612 	if (usecs < 0 || usecs > EM_TICKS_TO_USECS(65535))
5613 		return (EINVAL);
5614 	info->value = usecs;
5615 	ticks = EM_USECS_TO_TICKS(usecs);
5616 
5617 	adapter = info->adapter;
5618 
5619 	EM_CORE_LOCK(adapter);
5620 	regval = E1000_READ_OFFSET(&adapter->hw, info->offset);
5621 	regval = (regval & ~0xffff) | (ticks & 0xffff);
5622 	/* Handle a few special cases. */
5623 	switch (info->offset) {
5624 	case E1000_RDTR:
5625 		break;
5626 	case E1000_TIDV:
5627 		if (ticks == 0) {
5628 			adapter->txd_cmd &= ~E1000_TXD_CMD_IDE;
5629 			/* Don't write 0 into the TIDV register. */
5630 			regval++;
5631 		} else
5632 			adapter->txd_cmd |= E1000_TXD_CMD_IDE;
5633 		break;
5634 	}
5635 	E1000_WRITE_OFFSET(&adapter->hw, info->offset, regval);
5636 	EM_CORE_UNLOCK(adapter);
5637 	return (0);
5638 }
5639 
5640 static void
5641 em_add_int_delay_sysctl(struct adapter *adapter, const char *name,
5642 	const char *description, struct em_int_delay_info *info,
5643 	int offset, int value)
5644 {
5645 	info->adapter = adapter;
5646 	info->offset = offset;
5647 	info->value = value;
5648 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(adapter->dev),
5649 	    SYSCTL_CHILDREN(device_get_sysctl_tree(adapter->dev)),
5650 	    OID_AUTO, name, CTLTYPE_INT|CTLFLAG_RW,
5651 	    info, 0, em_sysctl_int_delay, "I", description);
5652 }
5653 
5654 static void
5655 em_set_sysctl_value(struct adapter *adapter, const char *name,
5656 	const char *description, int *limit, int value)
5657 {
5658 	*limit = value;
5659 	SYSCTL_ADD_INT(device_get_sysctl_ctx(adapter->dev),
5660 	    SYSCTL_CHILDREN(device_get_sysctl_tree(adapter->dev)),
5661 	    OID_AUTO, name, CTLTYPE_INT|CTLFLAG_RW, limit, value, description);
5662 }
5663 
5664 
5665 /*
5666 ** Set flow control using sysctl:
5667 ** Flow control values:
5668 **      0 - off
5669 **      1 - rx pause
5670 **      2 - tx pause
5671 **      3 - full
5672 */
5673 static int
5674 em_set_flowcntl(SYSCTL_HANDLER_ARGS)
5675 {
5676         int		error;
5677 	static int	input = 3; /* default is full */
5678         struct adapter	*adapter = (struct adapter *) arg1;
5679 
5680         error = sysctl_handle_int(oidp, &input, 0, req);
5681 
5682         if ((error) || (req->newptr == NULL))
5683                 return (error);
5684 
5685 	if (input == adapter->fc) /* no change? */
5686 		return (error);
5687 
5688         switch (input) {
5689                 case e1000_fc_rx_pause:
5690                 case e1000_fc_tx_pause:
5691                 case e1000_fc_full:
5692                 case e1000_fc_none:
5693                         adapter->hw.fc.requested_mode = input;
5694 			adapter->fc = input;
5695                         break;
5696                 default:
5697 			/* Do nothing */
5698 			return (error);
5699         }
5700 
5701         adapter->hw.fc.current_mode = adapter->hw.fc.requested_mode;
5702         e1000_force_mac_fc(&adapter->hw);
5703         return (error);
5704 }
5705 
5706 
5707 static int
5708 em_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
5709 {
5710 	struct adapter *adapter;
5711 	int error;
5712 	int result;
5713 
5714 	result = -1;
5715 	error = sysctl_handle_int(oidp, &result, 0, req);
5716 
5717 	if (error || !req->newptr)
5718 		return (error);
5719 
5720 	if (result == 1) {
5721 		adapter = (struct adapter *)arg1;
5722 		em_print_debug_info(adapter);
5723         }
5724 
5725 	return (error);
5726 }
5727 
5728 /*
5729 ** This routine is meant to be fluid, add whatever is
5730 ** needed for debugging a problem.  -jfv
5731 */
5732 static void
5733 em_print_debug_info(struct adapter *adapter)
5734 {
5735 	device_t dev = adapter->dev;
5736 	struct tx_ring *txr = adapter->tx_rings;
5737 	struct rx_ring *rxr = adapter->rx_rings;
5738 
5739 	if (adapter->ifp->if_drv_flags & IFF_DRV_RUNNING)
5740 		printf("Interface is RUNNING ");
5741 	else
5742 		printf("Interface is NOT RUNNING\n");
5743 
5744 	if (adapter->ifp->if_drv_flags & IFF_DRV_OACTIVE)
5745 		printf("and INACTIVE\n");
5746 	else
5747 		printf("and ACTIVE\n");
5748 
5749 	device_printf(dev, "hw tdh = %d, hw tdt = %d\n",
5750 	    E1000_READ_REG(&adapter->hw, E1000_TDH(0)),
5751 	    E1000_READ_REG(&adapter->hw, E1000_TDT(0)));
5752 	device_printf(dev, "hw rdh = %d, hw rdt = %d\n",
5753 	    E1000_READ_REG(&adapter->hw, E1000_RDH(0)),
5754 	    E1000_READ_REG(&adapter->hw, E1000_RDT(0)));
5755 	device_printf(dev, "Tx Queue Status = %d\n", txr->queue_status);
5756 	device_printf(dev, "TX descriptors avail = %d\n",
5757 	    txr->tx_avail);
5758 	device_printf(dev, "Tx Descriptors avail failure = %ld\n",
5759 	    txr->no_desc_avail);
5760 	device_printf(dev, "RX discarded packets = %ld\n",
5761 	    rxr->rx_discarded);
5762 	device_printf(dev, "RX Next to Check = %d\n", rxr->next_to_check);
5763 	device_printf(dev, "RX Next to Refresh = %d\n", rxr->next_to_refresh);
5764 }
5765