Don't let PROMISC interfere hardware vlan tagging operation. Enable hardware
[dragonfly.git] / sys / dev / netif / em / if_em.c
1 /*
2  *
3  * Copyright (c) 2004 Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
4  *
5  * Copyright (c) 2001-2006, Intel Corporation
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  *  1. Redistributions of source code must retain the above copyright notice,
12  *     this list of conditions and the following disclaimer.
13  * 
14  *  2. Redistributions in binary form must reproduce the above copyright
15  *     notice, this list of conditions and the following disclaimer in the
16  *     documentation and/or other materials provided with the distribution.
17  * 
18  *  3. Neither the name of the Intel Corporation nor the names of its
19  *     contributors may be used to endorse or promote products derived from
20  *     this software without specific prior written permission.
21  * 
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  *
35  * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
36  * 
37  * This code is derived from software contributed to The DragonFly Project
38  * by Matthew Dillon <dillon@backplane.com>
39  * 
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in
48  *    the documentation and/or other materials provided with the
49  *    distribution.
50  * 3. Neither the name of The DragonFly Project nor the names of its
51  *    contributors may be used to endorse or promote products derived
52  *    from this software without specific, prior written permission.
53  * 
54  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
55  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
56  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
57  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
58  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
59  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
60  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
61  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
62  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
63  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
64  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  * 
67  * $DragonFly: src/sys/dev/netif/em/if_em.c,v 1.76 2008/07/22 12:08:41 sephe Exp $
68  * $FreeBSD$
69  */
70 /*
71  * SERIALIZATION API RULES:
72  *
73  * - If the driver uses the same serializer for the interrupt as for the
74  *   ifnet, most of the serialization will be done automatically for the
75  *   driver.  
76  *
77  * - ifmedia entry points will be serialized by the ifmedia code using the
78  *   ifnet serializer.
79  *
80  * - if_* entry points except for if_input will be serialized by the IF
81  *   and protocol layers.
82  *
83  * - The device driver must be sure to serialize access from timeout code
84  *   installed by the device driver.
85  *
86  * - The device driver typically holds the serializer at the time it wishes
87  *   to call if_input.  If so, it should pass the serializer to if_input and
88  *   note that the serializer might be dropped temporarily by if_input 
89  *   (e.g. in case it has to bridge the packet to another interface).
90  *
91  *   NOTE!  Since callers into the device driver hold the ifnet serializer,
92  *   the device driver may be holding a serializer at the time it calls
93  *   if_input even if it is not serializer-aware.
94  */
95
96 #include "opt_polling.h"
97 #include "opt_inet.h"
98 #include "opt_serializer.h"
99 #include "opt_ethernet.h"
100
101 #include <sys/param.h>
102 #include <sys/bus.h>
103 #include <sys/endian.h>
104 #include <sys/interrupt.h>
105 #include <sys/kernel.h>
106 #include <sys/ktr.h>
107 #include <sys/malloc.h>
108 #include <sys/mbuf.h>
109 #include <sys/module.h>
110 #include <sys/rman.h>
111 #include <sys/serialize.h>
112 #include <sys/socket.h>
113 #include <sys/sockio.h>
114 #include <sys/sysctl.h>
115
116 #include <net/bpf.h>
117 #include <net/ethernet.h>
118 #include <net/if.h>
119 #include <net/if_arp.h>
120 #include <net/if_dl.h>
121 #include <net/if_media.h>
122 #include <net/if_types.h>
123 #include <net/ifq_var.h>
124 #include <net/vlan/if_vlan_var.h>
125 #include <net/vlan/if_vlan_ether.h>
126
127 #ifdef INET
128 #include <netinet/in.h>
129 #include <netinet/in_systm.h>
130 #include <netinet/in_var.h>
131 #include <netinet/ip.h>
132 #include <netinet/tcp.h>
133 #include <netinet/udp.h>
134 #endif
135
136 #include <dev/netif/em/if_em_hw.h>
137 #include <dev/netif/em/if_em.h>
138
139 #define EM_X60_WORKAROUND
140
141 /*********************************************************************
142  *  Set this to one to display debug statistics
143  *********************************************************************/
144 int     em_display_debug_stats = 0;
145
146 /*********************************************************************
147  *  Driver version
148  *********************************************************************/
149
150 char em_driver_version[] = "6.2.9";
151
152
153 /*********************************************************************
154  *  PCI Device ID Table
155  *
156  *  Used by probe to select devices to load on
157  *  Last field stores an index into em_strings
158  *  Last entry must be all 0s
159  *
160  *  { Vendor ID, Device ID, SubVendor ID, SubDevice ID, String Index }
161  *********************************************************************/
162
163 static em_vendor_info_t em_vendor_info_array[] =
164 {
165         /* Intel(R) PRO/1000 Network Connection */
166         { 0x8086, E1000_DEV_ID_82540EM,         PCI_ANY_ID, PCI_ANY_ID, 0},
167         { 0x8086, E1000_DEV_ID_82540EM_LOM,     PCI_ANY_ID, PCI_ANY_ID, 0},
168         { 0x8086, E1000_DEV_ID_82540EP,         PCI_ANY_ID, PCI_ANY_ID, 0},
169         { 0x8086, E1000_DEV_ID_82540EP_LOM,     PCI_ANY_ID, PCI_ANY_ID, 0},
170         { 0x8086, E1000_DEV_ID_82540EP_LP,      PCI_ANY_ID, PCI_ANY_ID, 0},
171
172         { 0x8086, E1000_DEV_ID_82541EI,         PCI_ANY_ID, PCI_ANY_ID, 0},
173         { 0x8086, E1000_DEV_ID_82541ER,         PCI_ANY_ID, PCI_ANY_ID, 0},
174         { 0x8086, E1000_DEV_ID_82541ER_LOM,     PCI_ANY_ID, PCI_ANY_ID, 0},
175         { 0x8086, E1000_DEV_ID_82541EI_MOBILE,  PCI_ANY_ID, PCI_ANY_ID, 0},
176         { 0x8086, E1000_DEV_ID_82541GI,         PCI_ANY_ID, PCI_ANY_ID, 0},
177         { 0x8086, E1000_DEV_ID_82541GI_LF,      PCI_ANY_ID, PCI_ANY_ID, 0},
178         { 0x8086, E1000_DEV_ID_82541GI_MOBILE,  PCI_ANY_ID, PCI_ANY_ID, 0},
179
180         { 0x8086, E1000_DEV_ID_82542,           PCI_ANY_ID, PCI_ANY_ID, 0},
181
182         { 0x8086, E1000_DEV_ID_82543GC_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
183         { 0x8086, E1000_DEV_ID_82543GC_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
184
185         { 0x8086, E1000_DEV_ID_82544EI_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
186         { 0x8086, E1000_DEV_ID_82544EI_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
187         { 0x8086, E1000_DEV_ID_82544GC_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
188         { 0x8086, E1000_DEV_ID_82544GC_LOM,     PCI_ANY_ID, PCI_ANY_ID, 0},
189
190         { 0x8086, E1000_DEV_ID_82545EM_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
191         { 0x8086, E1000_DEV_ID_82545EM_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
192         { 0x8086, E1000_DEV_ID_82545GM_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
193         { 0x8086, E1000_DEV_ID_82545GM_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
194         { 0x8086, E1000_DEV_ID_82545GM_SERDES,  PCI_ANY_ID, PCI_ANY_ID, 0},
195
196         { 0x8086, E1000_DEV_ID_82546EB_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
197         { 0x8086, E1000_DEV_ID_82546EB_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
198         { 0x8086, E1000_DEV_ID_82546EB_QUAD_COPPER, PCI_ANY_ID, PCI_ANY_ID, 0},
199         { 0x8086, E1000_DEV_ID_82546GB_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
200         { 0x8086, E1000_DEV_ID_82546GB_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
201         { 0x8086, E1000_DEV_ID_82546GB_SERDES,  PCI_ANY_ID, PCI_ANY_ID, 0},
202         { 0x8086, E1000_DEV_ID_82546GB_PCIE,    PCI_ANY_ID, PCI_ANY_ID, 0},
203         { 0x8086, E1000_DEV_ID_82546GB_QUAD_COPPER, PCI_ANY_ID, PCI_ANY_ID, 0},
204         { 0x8086, E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3,
205                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
206
207         { 0x8086, E1000_DEV_ID_82547EI,         PCI_ANY_ID, PCI_ANY_ID, 0},
208         { 0x8086, E1000_DEV_ID_82547EI_MOBILE,  PCI_ANY_ID, PCI_ANY_ID, 0},
209         { 0x8086, E1000_DEV_ID_82547GI,         PCI_ANY_ID, PCI_ANY_ID, 0},
210
211         { 0x8086, E1000_DEV_ID_82571EB_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
212         { 0x8086, E1000_DEV_ID_82571EB_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
213         { 0x8086, E1000_DEV_ID_82571EB_SERDES,  PCI_ANY_ID, PCI_ANY_ID, 0},
214         { 0x8086, E1000_DEV_ID_82571EB_QUAD_COPPER,
215                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
216         { 0x8086, E1000_DEV_ID_82571EB_QUAD_COPPER_LOWPROFILE,
217                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
218
219         { 0x8086, E1000_DEV_ID_82571EB_QUAD_FIBER,
220                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
221         { 0x8086, E1000_DEV_ID_82571PT_QUAD_COPPER,
222                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
223         { 0x8086, E1000_DEV_ID_82572EI_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
224         { 0x8086, E1000_DEV_ID_82572EI_FIBER,   PCI_ANY_ID, PCI_ANY_ID, 0},
225         { 0x8086, E1000_DEV_ID_82572EI_SERDES,  PCI_ANY_ID, PCI_ANY_ID, 0},
226         { 0x8086, E1000_DEV_ID_82572EI,         PCI_ANY_ID, PCI_ANY_ID, 0},
227
228         { 0x8086, E1000_DEV_ID_82573E,          PCI_ANY_ID, PCI_ANY_ID, 0},
229         { 0x8086, E1000_DEV_ID_82573E_IAMT,     PCI_ANY_ID, PCI_ANY_ID, 0},
230         { 0x8086, E1000_DEV_ID_82573L,          PCI_ANY_ID, PCI_ANY_ID, 0},
231
232         { 0x8086, E1000_DEV_ID_80003ES2LAN_COPPER_SPT,
233                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
234         { 0x8086, E1000_DEV_ID_80003ES2LAN_SERDES_SPT,
235                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
236         { 0x8086, E1000_DEV_ID_80003ES2LAN_COPPER_DPT,
237                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
238         { 0x8086, E1000_DEV_ID_80003ES2LAN_SERDES_DPT,
239                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
240
241         { 0x8086, E1000_DEV_ID_ICH8_IGP_M_AMT,  PCI_ANY_ID, PCI_ANY_ID, 0},
242         { 0x8086, E1000_DEV_ID_ICH8_IGP_AMT,    PCI_ANY_ID, PCI_ANY_ID, 0},
243         { 0x8086, E1000_DEV_ID_ICH8_IGP_C,      PCI_ANY_ID, PCI_ANY_ID, 0},
244         { 0x8086, E1000_DEV_ID_ICH8_IFE,        PCI_ANY_ID, PCI_ANY_ID, 0},
245         { 0x8086, E1000_DEV_ID_ICH8_IFE_GT,     PCI_ANY_ID, PCI_ANY_ID, 0},
246         { 0x8086, E1000_DEV_ID_ICH8_IFE_G,      PCI_ANY_ID, PCI_ANY_ID, 0},
247         { 0x8086, E1000_DEV_ID_ICH8_IGP_M,      PCI_ANY_ID, PCI_ANY_ID, 0},
248
249         { 0x8086, E1000_DEV_ID_ICH9_IGP_AMT,    PCI_ANY_ID, PCI_ANY_ID, 0},
250         { 0x8086, E1000_DEV_ID_ICH9_IGP_C,      PCI_ANY_ID, PCI_ANY_ID, 0},
251         { 0x8086, E1000_DEV_ID_ICH9_IFE,        PCI_ANY_ID, PCI_ANY_ID, 0},
252         { 0x8086, E1000_DEV_ID_ICH9_IFE_GT,     PCI_ANY_ID, PCI_ANY_ID, 0},
253         { 0x8086, E1000_DEV_ID_ICH9_IFE_G,      PCI_ANY_ID, PCI_ANY_ID, 0},
254
255         { 0x8086, E1000_DEV_ID_82575EB_COPPER,  PCI_ANY_ID, PCI_ANY_ID, 0},
256         { 0x8086, E1000_DEV_ID_82575EB_FIBER_SERDES,
257                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
258         { 0x8086, E1000_DEV_ID_82575GB_QUAD_COPPER,
259                                                 PCI_ANY_ID, PCI_ANY_ID, 0},
260         { 0x8086, 0x101A, PCI_ANY_ID, PCI_ANY_ID, 0},
261         { 0x8086, 0x1014, PCI_ANY_ID, PCI_ANY_ID, 0},
262         /* required last entry */
263         { 0, 0, 0, 0, 0}
264 };
265
266 /*********************************************************************
267  *  Table of branding strings for all supported NICs.
268  *********************************************************************/
269
270 static const char *em_strings[] = {
271         "Intel(R) PRO/1000 Network Connection"
272 };
273
274 /*********************************************************************
275  *  Function prototypes
276  *********************************************************************/
277 static int      em_probe(device_t);
278 static int      em_attach(device_t);
279 static int      em_detach(device_t);
280 static int      em_shutdown(device_t);
281 static void     em_intr(void *);
282 static int      em_suspend(device_t);
283 static int      em_resume(device_t);
284 static void     em_start(struct ifnet *);
285 static int      em_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
286 static void     em_watchdog(struct ifnet *);
287 static void     em_init(void *);
288 static void     em_stop(void *);
289 static void     em_media_status(struct ifnet *, struct ifmediareq *);
290 static int      em_media_change(struct ifnet *);
291 static void     em_identify_hardware(struct adapter *);
292 static int      em_allocate_pci_resources(device_t);
293 static void     em_free_pci_resources(device_t);
294 static void     em_local_timer(void *);
295 static int      em_hardware_init(struct adapter *);
296 static void     em_setup_interface(device_t, struct adapter *);
297 static int      em_setup_transmit_structures(struct adapter *);
298 static void     em_initialize_transmit_unit(struct adapter *);
299 static int      em_setup_receive_structures(struct adapter *);
300 static void     em_initialize_receive_unit(struct adapter *);
301 static void     em_enable_intr(struct adapter *);
302 static void     em_disable_intr(struct adapter *);
303 static void     em_free_transmit_structures(struct adapter *);
304 static void     em_free_receive_structures(struct adapter *);
305 static void     em_update_stats_counters(struct adapter *);
306 static void     em_txeof(struct adapter *);
307 static int      em_allocate_receive_structures(struct adapter *);
308 static void     em_rxeof(struct adapter *, int);
309 static void     em_receive_checksum(struct adapter *, struct em_rx_desc *,
310                                     struct mbuf *);
311 static void     em_transmit_checksum_setup(struct adapter *, struct mbuf *,
312                                            uint32_t *, uint32_t *);
313 static void     em_set_promisc(struct adapter *);
314 static void     em_disable_promisc(struct adapter *);
315 static void     em_set_multi(struct adapter *);
316 static void     em_print_hw_stats(struct adapter *);
317 static void     em_update_link_status(struct adapter *);
318 static int      em_get_buf(int i, struct adapter *, struct mbuf *, int how);
319 static void     em_enable_vlans(struct adapter *);
320 static void     em_disable_vlans(struct adapter *) __unused;
321 static int      em_encap(struct adapter *, struct mbuf *);
322 static void     em_smartspeed(struct adapter *);
323 static int      em_82547_fifo_workaround(struct adapter *, int);
324 static void     em_82547_update_fifo_head(struct adapter *, int);
325 static int      em_82547_tx_fifo_reset(struct adapter *);
326 static void     em_82547_move_tail(void *);
327 static void     em_82547_move_tail_serialized(struct adapter *);
328 static int      em_dma_malloc(struct adapter *, bus_size_t,
329                               struct em_dma_alloc *);
330 static void     em_dma_free(struct adapter *, struct em_dma_alloc *);
331 static void     em_print_debug_info(struct adapter *);
332 static int      em_is_valid_ether_addr(uint8_t *);
333 static int      em_sysctl_stats(SYSCTL_HANDLER_ARGS);
334 static int      em_sysctl_debug_info(SYSCTL_HANDLER_ARGS);
335 static uint32_t em_fill_descriptors(bus_addr_t address, uint32_t length, 
336                                    PDESC_ARRAY desc_array);
337 static int      em_sysctl_int_delay(SYSCTL_HANDLER_ARGS);
338 static int      em_sysctl_int_throttle(SYSCTL_HANDLER_ARGS);
339 static void     em_add_int_delay_sysctl(struct adapter *, const char *,
340                                         const char *,
341                                         struct em_int_delay_info *, int, int);
342
343 /*********************************************************************
344  *  FreeBSD Device Interface Entry Points
345  *********************************************************************/
346
347 static device_method_t em_methods[] = {
348         /* Device interface */
349         DEVMETHOD(device_probe, em_probe),
350         DEVMETHOD(device_attach, em_attach),
351         DEVMETHOD(device_detach, em_detach),
352         DEVMETHOD(device_shutdown, em_shutdown),
353         DEVMETHOD(device_suspend, em_suspend),
354         DEVMETHOD(device_resume, em_resume),
355         {0, 0}
356 };
357
358 static driver_t em_driver = {
359         "em", em_methods, sizeof(struct adapter),
360 };
361
362 static devclass_t em_devclass;
363
364 DECLARE_DUMMY_MODULE(if_em);
365 DRIVER_MODULE(if_em, pci, em_driver, em_devclass, 0, 0);
366
367 /*********************************************************************
368  *  Tunable default values.
369  *********************************************************************/
370
371 #define E1000_TICKS_TO_USECS(ticks)     ((1024 * (ticks) + 500) / 1000)
372 #define E1000_USECS_TO_TICKS(usecs)     ((1000 * (usecs) + 512) / 1024)
373
374 static int em_tx_int_delay_dflt = E1000_TICKS_TO_USECS(EM_TIDV);
375 static int em_rx_int_delay_dflt = E1000_TICKS_TO_USECS(EM_RDTR);
376 static int em_tx_abs_int_delay_dflt = E1000_TICKS_TO_USECS(EM_TADV);
377 static int em_rx_abs_int_delay_dflt = E1000_TICKS_TO_USECS(EM_RADV);
378 static int em_int_throttle_ceil = 10000;
379 static int em_rxd = EM_DEFAULT_RXD;
380 static int em_txd = EM_DEFAULT_TXD;
381 static int em_smart_pwr_down = FALSE;
382
383 TUNABLE_INT("hw.em.tx_int_delay", &em_tx_int_delay_dflt);
384 TUNABLE_INT("hw.em.rx_int_delay", &em_rx_int_delay_dflt);
385 TUNABLE_INT("hw.em.tx_abs_int_delay", &em_tx_abs_int_delay_dflt);
386 TUNABLE_INT("hw.em.rx_abs_int_delay", &em_rx_abs_int_delay_dflt);
387 TUNABLE_INT("hw.em.int_throttle_ceil", &em_int_throttle_ceil);
388 TUNABLE_INT("hw.em.rxd", &em_rxd);
389 TUNABLE_INT("hw.em.txd", &em_txd);
390 TUNABLE_INT("hw.em.smart_pwr_down", &em_smart_pwr_down);
391
392 /*
393  * Kernel trace for characterization of operations
394  */
395 #if !defined(KTR_IF_EM)
396 #define KTR_IF_EM       KTR_ALL
397 #endif
398 KTR_INFO_MASTER(if_em);
399 KTR_INFO(KTR_IF_EM, if_em, intr_beg, 0, "intr begin", 0);
400 KTR_INFO(KTR_IF_EM, if_em, intr_end, 1, "intr end", 0);
401 KTR_INFO(KTR_IF_EM, if_em, pkt_receive, 4, "rx packet", 0);
402 KTR_INFO(KTR_IF_EM, if_em, pkt_txqueue, 5, "tx packet", 0);
403 KTR_INFO(KTR_IF_EM, if_em, pkt_txclean, 6, "tx clean", 0);
404 #define logif(name)     KTR_LOG(if_em_ ## name)
405
406 /*********************************************************************
407  *  Device identification routine
408  *
409  *  em_probe determines if the driver should be loaded on
410  *  adapter based on PCI vendor/device id of the adapter.
411  *
412  *  return 0 on success, positive on failure
413  *********************************************************************/
414
415 static int
416 em_probe(device_t dev)
417 {
418         em_vendor_info_t *ent;
419
420         uint16_t pci_vendor_id = 0;
421         uint16_t pci_device_id = 0;
422         uint16_t pci_subvendor_id = 0;
423         uint16_t pci_subdevice_id = 0;
424         char adapter_name[60];
425
426         INIT_DEBUGOUT("em_probe: begin");
427
428         pci_vendor_id = pci_get_vendor(dev);
429         if (pci_vendor_id != EM_VENDOR_ID)
430                 return (ENXIO);
431
432         pci_device_id = pci_get_device(dev);
433         pci_subvendor_id = pci_get_subvendor(dev);
434         pci_subdevice_id = pci_get_subdevice(dev);
435
436         ent = em_vendor_info_array;
437         while (ent->vendor_id != 0) {
438                 if ((pci_vendor_id == ent->vendor_id) &&
439                     (pci_device_id == ent->device_id) &&
440
441                     ((pci_subvendor_id == ent->subvendor_id) ||
442                      (ent->subvendor_id == PCI_ANY_ID)) &&
443
444                     ((pci_subdevice_id == ent->subdevice_id) ||
445                      (ent->subdevice_id == PCI_ANY_ID))) {
446                         ksnprintf(adapter_name, sizeof(adapter_name),
447                                  "%s, Version - %s",  em_strings[ent->index], 
448                                  em_driver_version);
449                         device_set_desc_copy(dev, adapter_name);
450                         device_set_async_attach(dev, TRUE);
451                         return (0);
452                 }
453                 ent++;
454         }
455
456         return (ENXIO);
457 }
458
459 /*********************************************************************
460  *  Device initialization routine
461  *
462  *  The attach entry point is called when the driver is being loaded.
463  *  This routine identifies the type of hardware, allocates all resources
464  *  and initializes the hardware.
465  *
466  *  return 0 on success, positive on failure
467  *********************************************************************/
468
469 static int
470 em_attach(device_t dev)
471 {
472         struct adapter *adapter;
473         struct ifnet *ifp;
474         int tsize, rsize;
475         int error = 0;
476
477         INIT_DEBUGOUT("em_attach: begin");
478
479         adapter = device_get_softc(dev);
480         ifp = &adapter->interface_data.ac_if;
481
482         callout_init(&adapter->timer);
483         callout_init(&adapter->tx_fifo_timer);
484
485         adapter->dev = dev;
486         adapter->osdep.dev = dev;
487
488         /* SYSCTL stuff */
489         sysctl_ctx_init(&adapter->sysctl_ctx);
490         adapter->sysctl_tree = SYSCTL_ADD_NODE(&adapter->sysctl_ctx,
491                                                SYSCTL_STATIC_CHILDREN(_hw),
492                                                OID_AUTO, 
493                                                device_get_nameunit(dev),
494                                                CTLFLAG_RD,
495                                                0, "");
496
497         if (adapter->sysctl_tree == NULL) {
498                 device_printf(dev, "Unable to create sysctl tree\n");
499                 return EIO;
500         }
501
502         SYSCTL_ADD_PROC(&adapter->sysctl_ctx,  
503                         SYSCTL_CHILDREN(adapter->sysctl_tree),
504                         OID_AUTO, "debug_info", CTLTYPE_INT|CTLFLAG_RW, 
505                         (void *)adapter, 0,
506                         em_sysctl_debug_info, "I", "Debug Information");
507
508         SYSCTL_ADD_PROC(&adapter->sysctl_ctx,  
509                         SYSCTL_CHILDREN(adapter->sysctl_tree),
510                         OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, 
511                         (void *)adapter, 0,
512                         em_sysctl_stats, "I", "Statistics");
513
514         /* Determine hardware revision */
515         em_identify_hardware(adapter);
516
517         /* Set up some sysctls for the tunable interrupt delays */
518         em_add_int_delay_sysctl(adapter, "rx_int_delay",
519                                 "receive interrupt delay in usecs",
520                                 &adapter->rx_int_delay,
521                                 E1000_REG_OFFSET(&adapter->hw, RDTR),
522                                 em_rx_int_delay_dflt);
523         em_add_int_delay_sysctl(adapter, "tx_int_delay",
524                                 "transmit interrupt delay in usecs",
525                                 &adapter->tx_int_delay,
526                                 E1000_REG_OFFSET(&adapter->hw, TIDV),
527                                 em_tx_int_delay_dflt);
528         if (adapter->hw.mac_type >= em_82540) {
529                 em_add_int_delay_sysctl(adapter, "rx_abs_int_delay",
530                                         "receive interrupt delay limit in usecs",
531                                         &adapter->rx_abs_int_delay,
532                                         E1000_REG_OFFSET(&adapter->hw, RADV),
533                                         em_rx_abs_int_delay_dflt);
534                 em_add_int_delay_sysctl(adapter, "tx_abs_int_delay",
535                                         "transmit interrupt delay limit in usecs",
536                                         &adapter->tx_abs_int_delay,
537                                         E1000_REG_OFFSET(&adapter->hw, TADV),
538                                         em_tx_abs_int_delay_dflt);
539                 SYSCTL_ADD_PROC(&adapter->sysctl_ctx,
540                         SYSCTL_CHILDREN(adapter->sysctl_tree),
541                         OID_AUTO, "int_throttle_ceil", CTLTYPE_INT|CTLFLAG_RW,
542                         adapter, 0, em_sysctl_int_throttle, "I", NULL);
543         }
544
545         /*
546          * Validate number of transmit and receive descriptors. It
547          * must not exceed hardware maximum, and must be multiple
548          * of EM_DBA_ALIGN.
549          */
550         if (((em_txd * sizeof(struct em_tx_desc)) % EM_DBA_ALIGN) != 0 ||
551             (adapter->hw.mac_type >= em_82544 && em_txd > EM_MAX_TXD) ||
552             (adapter->hw.mac_type < em_82544 && em_txd > EM_MAX_TXD_82543) ||
553             (em_txd < EM_MIN_TXD)) {
554                 device_printf(dev, "Using %d TX descriptors instead of %d!\n",
555                               EM_DEFAULT_TXD, em_txd);
556                 adapter->num_tx_desc = EM_DEFAULT_TXD;
557         } else {
558                 adapter->num_tx_desc = em_txd;
559         }
560  
561         if (((em_rxd * sizeof(struct em_rx_desc)) % EM_DBA_ALIGN) != 0 ||
562             (adapter->hw.mac_type >= em_82544 && em_rxd > EM_MAX_RXD) ||
563             (adapter->hw.mac_type < em_82544 && em_rxd > EM_MAX_RXD_82543) ||
564             (em_rxd < EM_MIN_RXD)) {
565                 device_printf(dev, "Using %d RX descriptors instead of %d!\n",
566                               EM_DEFAULT_RXD, em_rxd);
567                 adapter->num_rx_desc = EM_DEFAULT_RXD;
568         } else {
569                 adapter->num_rx_desc = em_rxd;
570         }
571
572         SYSCTL_ADD_INT(&adapter->sysctl_ctx,
573                        SYSCTL_CHILDREN(adapter->sysctl_tree), OID_AUTO, "rxd",
574                        CTLFLAG_RD, &adapter->num_rx_desc, 0, NULL);
575         SYSCTL_ADD_INT(&adapter->sysctl_ctx,
576                        SYSCTL_CHILDREN(adapter->sysctl_tree), OID_AUTO, "txd",
577                        CTLFLAG_RD, &adapter->num_tx_desc, 0, NULL);
578
579         adapter->hw.autoneg = DO_AUTO_NEG;
580         adapter->hw.wait_autoneg_complete = WAIT_FOR_AUTO_NEG_DEFAULT;
581         adapter->hw.autoneg_advertised = AUTONEG_ADV_DEFAULT;
582         adapter->hw.tbi_compatibility_en = TRUE;
583         adapter->rx_buffer_len = EM_RXBUFFER_2048;
584
585         adapter->hw.phy_init_script = 1;
586         adapter->hw.phy_reset_disable = FALSE;
587
588 #ifndef EM_MASTER_SLAVE
589         adapter->hw.master_slave = em_ms_hw_default;
590 #else
591         adapter->hw.master_slave = EM_MASTER_SLAVE;
592 #endif
593
594         /*
595          * Set the max frame size assuming standard ethernet
596          * sized frames.
597          */   
598         adapter->hw.max_frame_size = ETHERMTU + ETHER_HDR_LEN + ETHER_CRC_LEN;
599
600         adapter->hw.min_frame_size =
601             MINIMUM_ETHERNET_PACKET_SIZE + ETHER_CRC_LEN;
602
603         /*
604          * This controls when hardware reports transmit completion
605          * status.
606          */
607         adapter->hw.report_tx_early = 1;
608
609         error = em_allocate_pci_resources(dev);
610         if (error)
611                 goto fail;
612
613         /* Initialize eeprom parameters */
614         em_init_eeprom_params(&adapter->hw);
615
616         tsize = roundup2(adapter->num_tx_desc * sizeof(struct em_tx_desc),
617                          EM_DBA_ALIGN);
618
619         /* Allocate Transmit Descriptor ring */
620         error = em_dma_malloc(adapter, tsize, &adapter->txdma);
621         if (error) {
622                 device_printf(dev, "Unable to allocate TxDescriptor memory\n");
623                 goto fail;
624         }
625         adapter->tx_desc_base = (struct em_tx_desc *)adapter->txdma.dma_vaddr;
626
627         rsize = roundup2(adapter->num_rx_desc * sizeof(struct em_rx_desc),
628                          EM_DBA_ALIGN);
629
630         /* Allocate Receive Descriptor ring */
631         error = em_dma_malloc(adapter, rsize, &adapter->rxdma);
632         if (error) {
633                 device_printf(dev, "Unable to allocate rx_desc memory\n");
634                 goto fail;
635         }
636         adapter->rx_desc_base = (struct em_rx_desc *)adapter->rxdma.dma_vaddr;
637
638         /* Initialize the hardware */
639         if (em_hardware_init(adapter)) {
640                 device_printf(dev, "Unable to initialize the hardware\n");
641                 error = EIO;
642                 goto fail;
643         }
644
645         /* Copy the permanent MAC address out of the EEPROM */
646         if (em_read_mac_addr(&adapter->hw) < 0) {
647                 device_printf(dev,
648                               "EEPROM read error while reading MAC address\n");
649                 error = EIO;
650                 goto fail;
651         }
652
653         if (!em_is_valid_ether_addr(adapter->hw.mac_addr)) {
654                 device_printf(dev, "Invalid MAC address\n");
655                 error = EIO;
656                 goto fail;
657         }
658
659         /* Setup OS specific network interface */
660         em_setup_interface(dev, adapter);
661
662         /* Initialize statistics */
663         em_clear_hw_cntrs(&adapter->hw);
664         em_update_stats_counters(adapter);
665         adapter->hw.get_link_status = 1;
666         em_update_link_status(adapter);
667
668         /* Indicate SOL/IDER usage */
669         if (em_check_phy_reset_block(&adapter->hw)) {
670                 device_printf(dev, "PHY reset is blocked due to "
671                               "SOL/IDER session.\n");
672         }
673  
674         /* Identify 82544 on PCIX */
675         em_get_bus_info(&adapter->hw);
676         if (adapter->hw.bus_type == em_bus_type_pcix &&
677             adapter->hw.mac_type == em_82544)
678                 adapter->pcix_82544 = TRUE;
679         else
680                 adapter->pcix_82544 = FALSE;
681
682         error = bus_setup_intr(dev, adapter->res_interrupt, INTR_NETSAFE,
683                            em_intr, adapter,
684                            &adapter->int_handler_tag, ifp->if_serializer);
685         if (error) {
686                 device_printf(dev, "Error registering interrupt handler!\n");
687                 ether_ifdetach(ifp);
688                 goto fail;
689         }
690
691         ifp->if_cpuid = ithread_cpuid(rman_get_start(adapter->res_interrupt));
692         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
693         INIT_DEBUGOUT("em_attach: end");
694         return(0);
695
696 fail:
697         em_detach(dev);
698         return(error);
699 }
700
701 /*********************************************************************
702  *  Device removal routine
703  *
704  *  The detach entry point is called when the driver is being removed.
705  *  This routine stops the adapter and deallocates all the resources
706  *  that were allocated for driver operation.
707  *
708  *  return 0 on success, positive on failure
709  *********************************************************************/
710
711 static int
712 em_detach(device_t dev)
713 {
714         struct adapter *adapter = device_get_softc(dev);
715
716         INIT_DEBUGOUT("em_detach: begin");
717
718         if (device_is_attached(dev)) {
719                 struct ifnet *ifp = &adapter->interface_data.ac_if;
720
721                 lwkt_serialize_enter(ifp->if_serializer);
722                 adapter->in_detach = 1;
723                 em_stop(adapter);
724                 em_phy_hw_reset(&adapter->hw);
725                 bus_teardown_intr(dev, adapter->res_interrupt, 
726                                   adapter->int_handler_tag);
727                 lwkt_serialize_exit(ifp->if_serializer);
728
729                 ether_ifdetach(ifp);
730         }
731         bus_generic_detach(dev);
732
733         em_free_pci_resources(dev);
734
735         /* Free Transmit Descriptor ring */
736         if (adapter->tx_desc_base != NULL) {
737                 em_dma_free(adapter, &adapter->txdma);
738                 adapter->tx_desc_base = NULL;
739         }
740
741         /* Free Receive Descriptor ring */
742         if (adapter->rx_desc_base != NULL) {
743                 em_dma_free(adapter, &adapter->rxdma);
744                 adapter->rx_desc_base = NULL;
745         }
746
747         /* Free sysctl tree */
748         if (adapter->sysctl_tree != NULL) {
749                 adapter->sysctl_tree = NULL;
750                 sysctl_ctx_free(&adapter->sysctl_ctx);
751         }
752
753         return (0);
754 }
755
756 /*********************************************************************
757  *
758  *  Shutdown entry point
759  *
760  **********************************************************************/
761
762 static int
763 em_shutdown(device_t dev)
764 {
765         struct adapter *adapter = device_get_softc(dev);
766         struct ifnet *ifp = &adapter->interface_data.ac_if;
767
768         lwkt_serialize_enter(ifp->if_serializer);
769         em_stop(adapter);
770         lwkt_serialize_exit(ifp->if_serializer);
771
772         return (0);
773 }
774
775 /*
776  * Suspend/resume device methods.
777  */
778 static int
779 em_suspend(device_t dev)
780 {
781         struct adapter *adapter = device_get_softc(dev);
782         struct ifnet *ifp = &adapter->interface_data.ac_if;
783
784         lwkt_serialize_enter(ifp->if_serializer);
785         em_stop(adapter);
786         lwkt_serialize_exit(ifp->if_serializer);
787         return (0);
788 }
789
790 static int
791 em_resume(device_t dev)
792 {
793         struct adapter *adapter = device_get_softc(dev);
794         struct ifnet *ifp = &adapter->interface_data.ac_if;
795
796         lwkt_serialize_enter(ifp->if_serializer);
797         ifp->if_flags &= ~IFF_RUNNING;
798         em_init(adapter);
799         if_devstart(ifp);
800         lwkt_serialize_exit(ifp->if_serializer);
801
802         return bus_generic_resume(dev);
803 }
804
805 /*********************************************************************
806  *  Transmit entry point
807  *
808  *  em_start is called by the stack to initiate a transmit.
809  *  The driver will remain in this routine as long as there are
810  *  packets to transmit and transmit resources are available.
811  *  In case resources are not available stack is notified and
812  *  the packet is requeued.
813  **********************************************************************/
814
815 static void
816 em_start(struct ifnet *ifp)
817 {
818         struct mbuf *m_head;
819         struct adapter *adapter = ifp->if_softc;
820
821         ASSERT_SERIALIZED(ifp->if_serializer);
822
823         if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
824                 return;
825         if (!adapter->link_active) {
826                 ifq_purge(&ifp->if_snd);
827                 return;
828         }
829         while (!ifq_is_empty(&ifp->if_snd)) {
830                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
831                 if (m_head == NULL)
832                         break;
833
834                 logif(pkt_txqueue);
835                 if (em_encap(adapter, m_head)) {
836                         ifp->if_flags |= IFF_OACTIVE;
837                         ifq_prepend(&ifp->if_snd, m_head);
838                         break;
839                 }
840
841                 /* Send a copy of the frame to the BPF listener */
842                 ETHER_BPF_MTAP(ifp, m_head);
843
844                 /* Set timeout in case hardware has problems transmitting. */
845                 ifp->if_timer = EM_TX_TIMEOUT;
846         }
847 }
848
849 /*********************************************************************
850  *  Ioctl entry point
851  *
852  *  em_ioctl is called when the user wants to configure the
853  *  interface.
854  *
855  *  return 0 on success, positive on failure
856  **********************************************************************/
857
858 static int
859 em_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
860 {
861         int max_frame_size, mask, error = 0, reinit = 0;
862         struct ifreq *ifr = (struct ifreq *) data;
863         struct adapter *adapter = ifp->if_softc;
864         uint16_t eeprom_data = 0;
865
866         ASSERT_SERIALIZED(ifp->if_serializer);
867
868         if (adapter->in_detach)
869                 return 0;
870
871         switch (command) {
872         case SIOCSIFMTU:
873                 IOCTL_DEBUGOUT("ioctl rcv'd: SIOCSIFMTU (Set Interface MTU)");
874                 switch (adapter->hw.mac_type) {
875                 case em_82573:
876                         /*
877                          * 82573 only supports jumbo frames
878                          * if ASPM is disabled.
879                          */
880                         em_read_eeprom(&adapter->hw, EEPROM_INIT_3GIO_3,
881                             1, &eeprom_data);
882                         if (eeprom_data & EEPROM_WORD1A_ASPM_MASK) {
883                                 max_frame_size = ETHER_MAX_LEN;
884                                 break;
885                         }
886                         /* Allow Jumbo frames */
887                         /* FALLTHROUGH */
888                 case em_82571:
889                 case em_82572:
890                 case em_ich9lan:
891                 case em_80003es2lan:    /* Limit Jumbo Frame size */
892                         max_frame_size = 9234;
893                         break;
894                 case em_ich8lan:
895                         /* ICH8 does not support jumbo frames */
896                         max_frame_size = ETHER_MAX_LEN;
897                         break;
898                 default:
899                         max_frame_size = MAX_JUMBO_FRAME_SIZE;
900                         break;
901                 }
902                 if (ifr->ifr_mtu >
903                         max_frame_size - ETHER_HDR_LEN - ETHER_CRC_LEN) {
904                         error = EINVAL;
905                 } else {
906                         ifp->if_mtu = ifr->ifr_mtu;
907                         adapter->hw.max_frame_size = 
908                         ifp->if_mtu + ETHER_HDR_LEN + ETHER_CRC_LEN;
909                         ifp->if_flags &= ~IFF_RUNNING;
910                         em_init(adapter);
911                 }
912                 break;
913         case SIOCSIFFLAGS:
914                 IOCTL_DEBUGOUT("ioctl rcv'd: SIOCSIFFLAGS "
915                                "(Set Interface Flags)");
916                 if (ifp->if_flags & IFF_UP) {
917                         if (!(ifp->if_flags & IFF_RUNNING)) {
918                                 em_init(adapter);
919                         } else if ((ifp->if_flags ^ adapter->if_flags) &
920                                    (IFF_PROMISC | IFF_ALLMULTI)) {
921                                 em_disable_promisc(adapter);
922                                 em_set_promisc(adapter);
923                         }
924                 } else {
925                         if (ifp->if_flags & IFF_RUNNING)
926                                 em_stop(adapter);
927                 }
928                 adapter->if_flags = ifp->if_flags;
929                 break;
930         case SIOCADDMULTI:
931         case SIOCDELMULTI:
932                 IOCTL_DEBUGOUT("ioctl rcv'd: SIOC(ADD|DEL)MULTI");
933                 if (ifp->if_flags & IFF_RUNNING) {
934                         em_disable_intr(adapter);
935                         em_set_multi(adapter);
936                         if (adapter->hw.mac_type == em_82542_rev2_0)
937                                 em_initialize_receive_unit(adapter);
938 #ifdef DEVICE_POLLING
939                         /* Do not enable interrupt if polling(4) is enabled */
940                         if ((ifp->if_flags & IFF_POLLING) == 0)
941 #endif
942                         em_enable_intr(adapter);
943                 }
944                 break;
945         case SIOCSIFMEDIA:
946                 /* Check SOL/IDER usage */
947                 if (em_check_phy_reset_block(&adapter->hw)) {
948                         if_printf(ifp, "Media change is blocked due to "
949                                   "SOL/IDER session.\n");
950                         break;
951                 }
952                 /* FALLTHROUGH */
953         case SIOCGIFMEDIA:
954                 IOCTL_DEBUGOUT("ioctl rcv'd: SIOCxIFMEDIA "
955                                "(Get/Set Interface Media)");
956                 error = ifmedia_ioctl(ifp, ifr, &adapter->media, command);
957                 break;
958         case SIOCSIFCAP:
959                 IOCTL_DEBUGOUT("ioctl rcv'd: SIOCSIFCAP (Set Capabilities)");
960                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
961                 if (mask & IFCAP_HWCSUM) {
962                         ifp->if_capenable ^= IFCAP_HWCSUM;
963                         reinit = 1;
964                 }
965                 if (mask & IFCAP_VLAN_HWTAGGING) {
966                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
967                         reinit = 1;
968                 }
969                 if (reinit && (ifp->if_flags & IFF_RUNNING)) {
970                         ifp->if_flags &= ~IFF_RUNNING;
971                         em_init(adapter);
972                 }
973                 break;
974         default:
975                 error = ether_ioctl(ifp, command, data);
976                 break;
977         }
978
979         return (error);
980 }
981
982 /*********************************************************************
983  *  Watchdog entry point
984  *
985  *  This routine is called whenever hardware quits transmitting.
986  *
987  **********************************************************************/
988
989 static void
990 em_watchdog(struct ifnet *ifp)
991 {
992         struct adapter *adapter = ifp->if_softc;
993
994         /*
995          * If we are in this routine because of pause frames, then
996          * don't reset the hardware.
997          */
998         if (E1000_READ_REG(&adapter->hw, STATUS) & E1000_STATUS_TXOFF) {
999                 ifp->if_timer = EM_TX_TIMEOUT;
1000                 return;
1001         }
1002
1003         if (em_check_for_link(&adapter->hw) == 0)
1004                 if_printf(ifp, "watchdog timeout -- resetting\n");
1005
1006         ifp->if_flags &= ~IFF_RUNNING;
1007         em_init(adapter);
1008
1009         adapter->watchdog_timeouts++;
1010 }
1011
1012 /*********************************************************************
1013  *  Init entry point
1014  *
1015  *  This routine is used in two ways. It is used by the stack as
1016  *  init entry point in network interface structure. It is also used
1017  *  by the driver as a hw/sw initialization routine to get to a
1018  *  consistent state.
1019  *
1020  *  return 0 on success, positive on failure
1021  **********************************************************************/
1022
1023 static void
1024 em_init(void *arg)
1025 {
1026         struct adapter *adapter = arg;
1027         uint32_t pba;
1028         struct ifnet *ifp = &adapter->interface_data.ac_if;
1029
1030         ASSERT_SERIALIZED(ifp->if_serializer);
1031
1032         INIT_DEBUGOUT("em_init: begin");
1033
1034         if (ifp->if_flags & IFF_RUNNING)
1035                 return;
1036
1037         em_stop(adapter);
1038
1039         /*
1040          * Packet Buffer Allocation (PBA)
1041          * Writing PBA sets the receive portion of the buffer
1042          * the remainder is used for the transmit buffer.
1043          *
1044          * Devices before the 82547 had a Packet Buffer of 64K.
1045          *   Default allocation: PBA=48K for Rx, leaving 16K for Tx.
1046          * After the 82547 the buffer was reduced to 40K.
1047          *   Default allocation: PBA=30K for Rx, leaving 10K for Tx.
1048          *   Note: default does not leave enough room for Jumbo Frame >10k.
1049          */
1050         switch (adapter->hw.mac_type) {
1051         case em_82547:
1052         case em_82547_rev_2: /* 82547: Total Packet Buffer is 40K */
1053                 if (adapter->hw.max_frame_size > EM_RXBUFFER_8192)
1054                         pba = E1000_PBA_22K; /* 22K for Rx, 18K for Tx */
1055                 else
1056                         pba = E1000_PBA_30K; /* 30K for Rx, 10K for Tx */
1057
1058                 adapter->tx_fifo_head = 0;
1059                 adapter->tx_head_addr = pba << EM_TX_HEAD_ADDR_SHIFT;
1060                 adapter->tx_fifo_size =
1061                         (E1000_PBA_40K - pba) << EM_PBA_BYTES_SHIFT;
1062                 break;
1063         /* Total Packet Buffer on these is 48K */
1064         case em_82571:
1065         case em_82572:
1066         case em_80003es2lan:
1067                 pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
1068                 break;
1069         case em_82573: /* 82573: Total Packet Buffer is 32K */
1070                 pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
1071                 break;
1072         case em_ich8lan:
1073                 pba = E1000_PBA_8K;
1074                 break;
1075         case em_ich9lan:
1076 #define E1000_PBA_10K   0x000A
1077                 pba = E1000_PBA_10K;
1078                 break;
1079         default:
1080                 /* Devices before 82547 had a Packet Buffer of 64K.   */
1081                 if(adapter->hw.max_frame_size > EM_RXBUFFER_8192)
1082                         pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
1083                 else
1084                         pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
1085         }
1086
1087         INIT_DEBUGOUT1("em_init: pba=%dK",pba);
1088         E1000_WRITE_REG(&adapter->hw, PBA, pba);
1089
1090         /* Get the latest mac address, User can use a LAA */
1091         bcopy(adapter->interface_data.ac_enaddr, adapter->hw.mac_addr,
1092               ETHER_ADDR_LEN);
1093
1094         /* Initialize the hardware */
1095         if (em_hardware_init(adapter)) {
1096                 if_printf(ifp, "Unable to initialize the hardware\n");
1097                 return;
1098         }
1099         em_update_link_status(adapter);
1100
1101         if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING)
1102                 em_enable_vlans(adapter);
1103
1104         /* Set hardware offload abilities */
1105         if (adapter->hw.mac_type >= em_82543) {
1106                 if (ifp->if_capenable & IFCAP_TXCSUM)
1107                         ifp->if_hwassist = EM_CHECKSUM_FEATURES;
1108                 else
1109                         ifp->if_hwassist = 0;
1110         }
1111
1112         /* Prepare transmit descriptors and buffers */
1113         if (em_setup_transmit_structures(adapter)) {
1114                 if_printf(ifp, "Could not setup transmit structures\n");
1115                 em_stop(adapter);
1116                 return;
1117         }
1118         em_initialize_transmit_unit(adapter);
1119
1120         /* Setup Multicast table */
1121         em_set_multi(adapter);
1122
1123         /* Prepare receive descriptors and buffers */
1124         if (em_setup_receive_structures(adapter)) {
1125                 if_printf(ifp, "Could not setup receive structures\n");
1126                 em_stop(adapter);
1127                 return;
1128         }
1129         em_initialize_receive_unit(adapter);
1130
1131         /* Don't lose promiscuous settings */
1132         em_set_promisc(adapter);
1133
1134         ifp->if_flags |= IFF_RUNNING;
1135         ifp->if_flags &= ~IFF_OACTIVE;
1136
1137         callout_reset(&adapter->timer, hz, em_local_timer, adapter);
1138         em_clear_hw_cntrs(&adapter->hw);
1139
1140 #ifdef DEVICE_POLLING
1141         /* Do not enable interrupt if polling(4) is enabled */
1142         if (ifp->if_flags & IFF_POLLING)
1143                 em_disable_intr(adapter);
1144         else
1145 #endif
1146         em_enable_intr(adapter);
1147
1148         /* Don't reset the phy next time init gets called */
1149         adapter->hw.phy_reset_disable = TRUE;
1150 }
1151
1152 #ifdef DEVICE_POLLING
1153
1154 static void
1155 em_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1156 {
1157         struct adapter *adapter = ifp->if_softc;
1158         uint32_t reg_icr;
1159
1160         ASSERT_SERIALIZED(ifp->if_serializer);
1161
1162         switch(cmd) {
1163         case POLL_REGISTER:
1164                 em_disable_intr(adapter);
1165                 break;
1166         case POLL_DEREGISTER:
1167                 em_enable_intr(adapter);
1168                 break;
1169         case POLL_AND_CHECK_STATUS:
1170                 reg_icr = E1000_READ_REG(&adapter->hw, ICR);
1171                 if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1172                         callout_stop(&adapter->timer);
1173                         adapter->hw.get_link_status = 1;
1174                         em_check_for_link(&adapter->hw);
1175                         em_update_link_status(adapter);
1176                         callout_reset(&adapter->timer, hz, em_local_timer,
1177                                       adapter);
1178                 }
1179                 /* fall through */
1180         case POLL_ONLY:
1181                 if (ifp->if_flags & IFF_RUNNING) {
1182                         em_rxeof(adapter, count);
1183                         em_txeof(adapter);
1184
1185                         if (!ifq_is_empty(&ifp->if_snd))
1186                                 if_devstart(ifp);
1187                 }
1188                 break;
1189         }
1190 }
1191
1192 #endif /* DEVICE_POLLING */
1193
1194 /*********************************************************************
1195  *
1196  *  Interrupt Service routine
1197  *
1198  *********************************************************************/
1199 static void
1200 em_intr(void *arg)
1201 {
1202         uint32_t reg_icr;
1203         struct ifnet *ifp;
1204         struct adapter *adapter = arg;
1205
1206         ifp = &adapter->interface_data.ac_if;  
1207
1208         logif(intr_beg);
1209         ASSERT_SERIALIZED(ifp->if_serializer);
1210
1211         reg_icr = E1000_READ_REG(&adapter->hw, ICR);
1212         if ((adapter->hw.mac_type >= em_82571 &&
1213              (reg_icr & E1000_ICR_INT_ASSERTED) == 0) ||
1214             reg_icr == 0) {
1215                 logif(intr_end);
1216                 return;
1217         }
1218
1219         /*
1220          * XXX: some laptops trigger several spurious interrupts on em(4)
1221          * when in the resume cycle. The ICR register reports all-ones
1222          * value in this case. Processing such interrupts would lead to
1223          * a freeze. I don't know why.
1224          */
1225         if (reg_icr == 0xffffffff) {
1226                 logif(intr_end);
1227                 return;
1228         }
1229
1230         /*
1231          * note: do not attempt to improve efficiency by looping.  This 
1232          * only results in unnecessary piecemeal collection of received
1233          * packets and unnecessary piecemeal cleanups of the transmit ring.
1234          */
1235         if (ifp->if_flags & IFF_RUNNING) {
1236                 em_rxeof(adapter, -1);
1237                 em_txeof(adapter);
1238         }
1239
1240         /* Link status change */
1241         if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1242                 callout_stop(&adapter->timer);
1243                 adapter->hw.get_link_status = 1;
1244                 em_check_for_link(&adapter->hw);
1245                 em_update_link_status(adapter);
1246                 callout_reset(&adapter->timer, hz, em_local_timer, adapter);
1247         }
1248
1249         if (reg_icr & E1000_ICR_RXO)
1250                 adapter->rx_overruns++;
1251
1252         if ((ifp->if_flags & IFF_RUNNING) && !ifq_is_empty(&ifp->if_snd))
1253                 if_devstart(ifp);
1254
1255         logif(intr_end);
1256 }
1257
1258 /*********************************************************************
1259  *
1260  *  Media Ioctl callback
1261  *
1262  *  This routine is called whenever the user queries the status of
1263  *  the interface using ifconfig.
1264  *
1265  **********************************************************************/
1266 static void
1267 em_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1268 {
1269         struct adapter *adapter = ifp->if_softc;
1270         u_char fiber_type = IFM_1000_SX;
1271
1272         INIT_DEBUGOUT("em_media_status: begin");
1273
1274         ASSERT_SERIALIZED(ifp->if_serializer);
1275
1276         em_check_for_link(&adapter->hw);
1277         em_update_link_status(adapter);
1278
1279         ifmr->ifm_status = IFM_AVALID;
1280         ifmr->ifm_active = IFM_ETHER;
1281
1282         if (!adapter->link_active)
1283                 return;
1284
1285         ifmr->ifm_status |= IFM_ACTIVE;
1286
1287         if (adapter->hw.media_type == em_media_type_fiber ||
1288             adapter->hw.media_type == em_media_type_internal_serdes) {
1289                 if (adapter->hw.mac_type == em_82545)
1290                         fiber_type = IFM_1000_LX;
1291                 ifmr->ifm_active |= fiber_type | IFM_FDX;
1292         } else {
1293                 switch (adapter->link_speed) {
1294                 case 10:
1295                         ifmr->ifm_active |= IFM_10_T;
1296                         break;
1297                 case 100:
1298                         ifmr->ifm_active |= IFM_100_TX;
1299                         break;
1300                 case 1000:
1301                         ifmr->ifm_active |= IFM_1000_T;
1302                         break;
1303                 }
1304                 if (adapter->link_duplex == FULL_DUPLEX)
1305                         ifmr->ifm_active |= IFM_FDX;
1306                 else
1307                         ifmr->ifm_active |= IFM_HDX;
1308         }
1309 }
1310
1311 /*********************************************************************
1312  *
1313  *  Media Ioctl callback
1314  *
1315  *  This routine is called when the user changes speed/duplex using
1316  *  media/mediopt option with ifconfig.
1317  *
1318  **********************************************************************/
1319 static int
1320 em_media_change(struct ifnet *ifp)
1321 {
1322         struct adapter *adapter = ifp->if_softc;
1323         struct ifmedia *ifm = &adapter->media;
1324
1325         INIT_DEBUGOUT("em_media_change: begin");
1326
1327         ASSERT_SERIALIZED(ifp->if_serializer);
1328
1329         if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1330                 return (EINVAL);
1331
1332         switch (IFM_SUBTYPE(ifm->ifm_media)) {
1333         case IFM_AUTO:
1334                 adapter->hw.autoneg = DO_AUTO_NEG;
1335                 adapter->hw.autoneg_advertised = AUTONEG_ADV_DEFAULT;
1336                 break;
1337         case IFM_1000_LX:
1338         case IFM_1000_SX:
1339         case IFM_1000_T:
1340                 adapter->hw.autoneg = DO_AUTO_NEG;
1341                 adapter->hw.autoneg_advertised = ADVERTISE_1000_FULL;
1342                 break;
1343         case IFM_100_TX:
1344                 adapter->hw.autoneg = FALSE;
1345                 adapter->hw.autoneg_advertised = 0;
1346                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1347                         adapter->hw.forced_speed_duplex = em_100_full;
1348                 else
1349                         adapter->hw.forced_speed_duplex = em_100_half;
1350                 break;
1351         case IFM_10_T:
1352                 adapter->hw.autoneg = FALSE;
1353                 adapter->hw.autoneg_advertised = 0;
1354                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1355                         adapter->hw.forced_speed_duplex = em_10_full;
1356                 else
1357                         adapter->hw.forced_speed_duplex = em_10_half;
1358                 break;
1359         default:
1360                 if_printf(ifp, "Unsupported media type\n");
1361         }
1362         /*
1363          * As the speed/duplex settings may have changed we need to
1364          * reset the PHY.
1365          */
1366         adapter->hw.phy_reset_disable = FALSE;
1367
1368         ifp->if_flags &= ~IFF_RUNNING;
1369         em_init(adapter);
1370
1371         return(0);
1372 }
1373
1374 static void
1375 em_tx_cb(void *arg, bus_dma_segment_t *seg, int nsegs, bus_size_t mapsize,
1376          int error)
1377 {
1378         struct em_q *q = arg;
1379
1380         if (error)
1381                 return;
1382         KASSERT(nsegs <= EM_MAX_SCATTER,
1383                 ("Too many DMA segments returned when mapping tx packet"));
1384         q->nsegs = nsegs;
1385         bcopy(seg, q->segs, nsegs * sizeof(seg[0]));
1386 }
1387
1388 /*********************************************************************
1389  *
1390  *  This routine maps the mbufs to tx descriptors.
1391  *
1392  *  return 0 on success, positive on failure
1393  **********************************************************************/
1394 static int
1395 em_encap(struct adapter *adapter, struct mbuf *m_head)
1396 {
1397         uint32_t txd_upper = 0, txd_lower = 0, txd_used = 0, txd_saved = 0;
1398         int i, j, error, last = 0;
1399
1400         struct em_q q;
1401         struct em_buffer *tx_buffer = NULL, *tx_buffer_first;
1402         bus_dmamap_t map;
1403         struct em_tx_desc *current_tx_desc = NULL;
1404         struct ifnet *ifp = &adapter->interface_data.ac_if;
1405
1406         /*
1407          * Force a cleanup if number of TX descriptors
1408          * available hits the threshold
1409          */
1410         if (adapter->num_tx_desc_avail <= EM_TX_CLEANUP_THRESHOLD) {
1411                 em_txeof(adapter);
1412                 if (adapter->num_tx_desc_avail <= EM_TX_CLEANUP_THRESHOLD) {
1413                         adapter->no_tx_desc_avail1++;
1414                         return (ENOBUFS);
1415                 }
1416         }
1417
1418         /*
1419          * Capture the first descriptor index, this descriptor will have
1420          * the index of the EOP which is the only one that now gets a
1421          * DONE bit writeback.
1422          */
1423         tx_buffer_first = &adapter->tx_buffer_area[adapter->next_avail_tx_desc];
1424
1425         /*
1426          * Map the packet for DMA.
1427          */
1428         map = tx_buffer_first->map;
1429         error = bus_dmamap_load_mbuf(adapter->txtag, map, m_head, em_tx_cb,
1430                                      &q, BUS_DMA_NOWAIT);
1431         if (error != 0) {
1432                 adapter->no_tx_dma_setup++;
1433                 return (error);
1434         }
1435         KASSERT(q.nsegs != 0, ("em_encap: empty packet"));
1436
1437         if (q.nsegs > (adapter->num_tx_desc_avail - 2)) {
1438                 adapter->no_tx_desc_avail2++;
1439                 error = ENOBUFS;
1440                 goto fail;
1441         }
1442
1443         if (ifp->if_hwassist > 0) {
1444                 em_transmit_checksum_setup(adapter,  m_head,
1445                                            &txd_upper, &txd_lower);
1446         }
1447
1448         i = adapter->next_avail_tx_desc;
1449         if (adapter->pcix_82544)
1450                 txd_saved = i;
1451
1452         /* Set up our transmit descriptors */
1453         for (j = 0; j < q.nsegs; j++) {
1454                 /* If adapter is 82544 and on PCIX bus */
1455                 if(adapter->pcix_82544) {
1456                         DESC_ARRAY desc_array;
1457                         uint32_t array_elements, counter;
1458
1459                         /* 
1460                          * Check the Address and Length combination and
1461                          * split the data accordingly
1462                          */
1463                         array_elements = em_fill_descriptors(q.segs[j].ds_addr,
1464                                                 q.segs[j].ds_len, &desc_array);
1465                         for (counter = 0; counter < array_elements; counter++) {
1466                                 if (txd_used == adapter->num_tx_desc_avail) {
1467                                         adapter->next_avail_tx_desc = txd_saved;
1468                                         adapter->no_tx_desc_avail2++;
1469                                         error = ENOBUFS;
1470                                         goto fail;
1471                                 }
1472                                 tx_buffer = &adapter->tx_buffer_area[i];
1473                                 current_tx_desc = &adapter->tx_desc_base[i];
1474                                 current_tx_desc->buffer_addr = htole64(
1475                                         desc_array.descriptor[counter].address);
1476                                 current_tx_desc->lower.data = htole32(
1477                                         adapter->txd_cmd | txd_lower |
1478                                         (uint16_t)desc_array.descriptor[counter].length);
1479                                 current_tx_desc->upper.data = htole32(txd_upper);
1480
1481                                 last = i;
1482                                 if (++i == adapter->num_tx_desc)
1483                                         i = 0;
1484
1485                                 tx_buffer->m_head = NULL;
1486                                 tx_buffer->next_eop = -1;
1487                                 txd_used++;
1488                         }
1489                 } else {
1490                         tx_buffer = &adapter->tx_buffer_area[i];
1491                         current_tx_desc = &adapter->tx_desc_base[i];
1492
1493                         current_tx_desc->buffer_addr = htole64(q.segs[j].ds_addr);
1494                         current_tx_desc->lower.data = htole32(
1495                                 adapter->txd_cmd | txd_lower | q.segs[j].ds_len);
1496                         current_tx_desc->upper.data = htole32(txd_upper);
1497
1498                         last = i;
1499                         if (++i == adapter->num_tx_desc)
1500                                 i = 0;
1501
1502                         tx_buffer->m_head = NULL;
1503                         tx_buffer->next_eop = -1;
1504                 }
1505         }
1506
1507         adapter->next_avail_tx_desc = i;
1508         if (adapter->pcix_82544)
1509                 adapter->num_tx_desc_avail -= txd_used;
1510         else
1511                 adapter->num_tx_desc_avail -= q.nsegs;
1512
1513         /* Find out if we are in vlan mode */
1514         if (m_head->m_flags & M_VLANTAG) {
1515                 /* Set the vlan id */
1516                 current_tx_desc->upper.fields.special =
1517                         htole16(m_head->m_pkthdr.ether_vlantag);
1518
1519                 /* Tell hardware to add tag */
1520                 current_tx_desc->lower.data |= htole32(E1000_TXD_CMD_VLE);
1521         }
1522
1523         tx_buffer->m_head = m_head;
1524         tx_buffer_first->map = tx_buffer->map;
1525         tx_buffer->map = map;
1526         bus_dmamap_sync(adapter->txtag, map, BUS_DMASYNC_PREWRITE);
1527
1528         /*
1529          * Last Descriptor of Packet needs End Of Packet (EOP)
1530          * and Report Status (RS)
1531          */
1532         current_tx_desc->lower.data |=
1533                 htole32(E1000_TXD_CMD_EOP | E1000_TXD_CMD_RS);
1534
1535         /*
1536          * Keep track in the first buffer which descriptor will be
1537          * written back.
1538          */
1539         tx_buffer_first->next_eop = last;
1540
1541         bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
1542                         BUS_DMASYNC_PREWRITE);
1543
1544         /* 
1545          * Advance the Transmit Descriptor Tail (Tdt), this tells the E1000
1546          * that this frame is available to transmit.
1547          */
1548         if (adapter->hw.mac_type == em_82547 &&
1549             adapter->link_duplex == HALF_DUPLEX) {
1550                 em_82547_move_tail_serialized(adapter);
1551         } else {
1552                 E1000_WRITE_REG(&adapter->hw, TDT, i);
1553                 if (adapter->hw.mac_type == em_82547) {
1554                         em_82547_update_fifo_head(adapter,
1555                                                   m_head->m_pkthdr.len);
1556                 }
1557         }
1558
1559         return (0);
1560 fail:
1561         bus_dmamap_unload(adapter->txtag, map);
1562         return error;
1563 }
1564
1565 /*********************************************************************
1566  *
1567  * 82547 workaround to avoid controller hang in half-duplex environment.
1568  * The workaround is to avoid queuing a large packet that would span
1569  * the internal Tx FIFO ring boundary. We need to reset the FIFO pointers
1570  * in this case. We do that only when FIFO is quiescent.
1571  *
1572  **********************************************************************/
1573 static void
1574 em_82547_move_tail(void *arg)
1575 {
1576         struct adapter *adapter = arg;
1577         struct ifnet *ifp = &adapter->interface_data.ac_if;
1578
1579         lwkt_serialize_enter(ifp->if_serializer);
1580         em_82547_move_tail_serialized(adapter);
1581         lwkt_serialize_exit(ifp->if_serializer);
1582 }
1583
1584 static void
1585 em_82547_move_tail_serialized(struct adapter *adapter)
1586 {
1587         uint16_t hw_tdt;
1588         uint16_t sw_tdt;
1589         struct em_tx_desc *tx_desc;
1590         uint16_t length = 0;
1591         boolean_t eop = 0;
1592
1593         hw_tdt = E1000_READ_REG(&adapter->hw, TDT);
1594         sw_tdt = adapter->next_avail_tx_desc;
1595
1596         while (hw_tdt != sw_tdt) {
1597                 tx_desc = &adapter->tx_desc_base[hw_tdt];
1598                 length += tx_desc->lower.flags.length;
1599                 eop = tx_desc->lower.data & E1000_TXD_CMD_EOP;
1600                 if (++hw_tdt == adapter->num_tx_desc)
1601                         hw_tdt = 0;
1602
1603                 if (eop) {
1604                         if (em_82547_fifo_workaround(adapter, length)) {
1605                                 adapter->tx_fifo_wrk_cnt++;
1606                                 callout_reset(&adapter->tx_fifo_timer, 1,
1607                                         em_82547_move_tail, adapter);
1608                                 break;
1609                         }
1610                         E1000_WRITE_REG(&adapter->hw, TDT, hw_tdt);
1611                         em_82547_update_fifo_head(adapter, length);
1612                         length = 0;
1613                 }
1614         }       
1615 }
1616
1617 static int
1618 em_82547_fifo_workaround(struct adapter *adapter, int len)
1619 {       
1620         int fifo_space, fifo_pkt_len;
1621
1622         fifo_pkt_len = roundup2(len + EM_FIFO_HDR, EM_FIFO_HDR);
1623
1624         if (adapter->link_duplex == HALF_DUPLEX) {
1625                 fifo_space = adapter->tx_fifo_size - adapter->tx_fifo_head;
1626
1627                 if (fifo_pkt_len >= (EM_82547_PKT_THRESH + fifo_space)) {
1628                         if (em_82547_tx_fifo_reset(adapter))
1629                                 return (0);
1630                         else
1631                                 return (1);
1632                 }
1633         }
1634
1635         return (0);
1636 }
1637
1638 static void
1639 em_82547_update_fifo_head(struct adapter *adapter, int len)
1640 {
1641         int fifo_pkt_len = roundup2(len + EM_FIFO_HDR, EM_FIFO_HDR);
1642
1643         /* tx_fifo_head is always 16 byte aligned */
1644         adapter->tx_fifo_head += fifo_pkt_len;
1645         if (adapter->tx_fifo_head >= adapter->tx_fifo_size)
1646                 adapter->tx_fifo_head -= adapter->tx_fifo_size;
1647 }
1648
1649 static int
1650 em_82547_tx_fifo_reset(struct adapter *adapter)
1651 {
1652         uint32_t tctl;
1653
1654         if (E1000_READ_REG(&adapter->hw, TDT) == E1000_READ_REG(&adapter->hw, TDH) &&
1655             E1000_READ_REG(&adapter->hw, TDFT) == E1000_READ_REG(&adapter->hw, TDFH) &&
1656             E1000_READ_REG(&adapter->hw, TDFTS) == E1000_READ_REG(&adapter->hw, TDFHS) &&
1657             E1000_READ_REG(&adapter->hw, TDFPC) == 0) {
1658                 /* Disable TX unit */
1659                 tctl = E1000_READ_REG(&adapter->hw, TCTL);
1660                 E1000_WRITE_REG(&adapter->hw, TCTL, tctl & ~E1000_TCTL_EN);
1661
1662                 /* Reset FIFO pointers */
1663                 E1000_WRITE_REG(&adapter->hw, TDFT,  adapter->tx_head_addr);
1664                 E1000_WRITE_REG(&adapter->hw, TDFH,  adapter->tx_head_addr);
1665                 E1000_WRITE_REG(&adapter->hw, TDFTS, adapter->tx_head_addr);
1666                 E1000_WRITE_REG(&adapter->hw, TDFHS, adapter->tx_head_addr);
1667
1668                 /* Re-enable TX unit */
1669                 E1000_WRITE_REG(&adapter->hw, TCTL, tctl);
1670                 E1000_WRITE_FLUSH(&adapter->hw);
1671
1672                 adapter->tx_fifo_head = 0;
1673                 adapter->tx_fifo_reset_cnt++;
1674
1675                 return (TRUE);
1676         } else {
1677                 return (FALSE);
1678         }
1679 }
1680
1681 static void
1682 em_set_promisc(struct adapter *adapter)
1683 {
1684         uint32_t reg_rctl;
1685         struct ifnet *ifp = &adapter->interface_data.ac_if;
1686
1687         reg_rctl = E1000_READ_REG(&adapter->hw, RCTL);
1688
1689         if (ifp->if_flags & IFF_PROMISC) {
1690                 reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
1691                 E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
1692         } else if (ifp->if_flags & IFF_ALLMULTI) {
1693                 reg_rctl |= E1000_RCTL_MPE;
1694                 reg_rctl &= ~E1000_RCTL_UPE;
1695                 E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
1696         }
1697 }
1698
1699 static void
1700 em_disable_promisc(struct adapter *adapter)
1701 {
1702         uint32_t reg_rctl;
1703
1704         reg_rctl = E1000_READ_REG(&adapter->hw, RCTL);
1705
1706         reg_rctl &= (~E1000_RCTL_UPE);
1707         reg_rctl &= (~E1000_RCTL_MPE);
1708         E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
1709 }
1710
1711 /*********************************************************************
1712  *  Multicast Update
1713  *
1714  *  This routine is called whenever multicast address list is updated.
1715  *
1716  **********************************************************************/
1717
1718 static void
1719 em_set_multi(struct adapter *adapter)
1720 {
1721         uint32_t reg_rctl = 0;
1722         uint8_t mta[MAX_NUM_MULTICAST_ADDRESSES * ETH_LENGTH_OF_ADDRESS];
1723         struct ifmultiaddr *ifma;
1724         int mcnt = 0;
1725         struct ifnet *ifp = &adapter->interface_data.ac_if;
1726
1727         IOCTL_DEBUGOUT("em_set_multi: begin");
1728
1729         if (adapter->hw.mac_type == em_82542_rev2_0) {
1730                 reg_rctl = E1000_READ_REG(&adapter->hw, RCTL);
1731                 if (adapter->hw.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
1732                         em_pci_clear_mwi(&adapter->hw);
1733                 reg_rctl |= E1000_RCTL_RST;
1734                 E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
1735                 msec_delay(5);
1736         }
1737
1738         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1739                 if (ifma->ifma_addr->sa_family != AF_LINK)
1740                         continue;
1741
1742                 if (mcnt == MAX_NUM_MULTICAST_ADDRESSES)
1743                         break;
1744
1745                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1746                       &mta[mcnt*ETH_LENGTH_OF_ADDRESS], ETH_LENGTH_OF_ADDRESS);
1747                 mcnt++;
1748         }
1749
1750         if (mcnt >= MAX_NUM_MULTICAST_ADDRESSES) {
1751                 reg_rctl = E1000_READ_REG(&adapter->hw, RCTL);
1752                 reg_rctl |= E1000_RCTL_MPE;
1753                 E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
1754         } else {
1755                 em_mc_addr_list_update(&adapter->hw, mta, mcnt, 0, 1);
1756         }
1757
1758         if (adapter->hw.mac_type == em_82542_rev2_0) {
1759                 reg_rctl = E1000_READ_REG(&adapter->hw, RCTL);
1760                 reg_rctl &= ~E1000_RCTL_RST;
1761                 E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
1762                 msec_delay(5);
1763                 if (adapter->hw.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
1764                         em_pci_set_mwi(&adapter->hw);
1765         }
1766 }
1767
1768 /*********************************************************************
1769  *  Timer routine
1770  *
1771  *  This routine checks for link status and updates statistics.
1772  *
1773  **********************************************************************/
1774
1775 static void
1776 em_local_timer(void *arg)
1777 {
1778         struct ifnet *ifp;
1779         struct adapter *adapter = arg;
1780         ifp = &adapter->interface_data.ac_if;
1781
1782         lwkt_serialize_enter(ifp->if_serializer);
1783
1784         em_check_for_link(&adapter->hw);
1785         em_update_link_status(adapter);
1786         em_update_stats_counters(adapter);
1787         if (em_display_debug_stats && ifp->if_flags & IFF_RUNNING)
1788                 em_print_hw_stats(adapter);
1789         em_smartspeed(adapter);
1790
1791         callout_reset(&adapter->timer, hz, em_local_timer, adapter);
1792
1793         lwkt_serialize_exit(ifp->if_serializer);
1794 }
1795
1796 static void
1797 em_update_link_status(struct adapter *adapter)
1798 {
1799         struct ifnet *ifp;
1800         ifp = &adapter->interface_data.ac_if;
1801
1802         if (E1000_READ_REG(&adapter->hw, STATUS) & E1000_STATUS_LU) {
1803                 if (adapter->link_active == 0) {
1804                         em_get_speed_and_duplex(&adapter->hw, 
1805                                                 &adapter->link_speed, 
1806                                                 &adapter->link_duplex);
1807                         /* Check if we may set SPEED_MODE bit on PCI-E */
1808                         if (adapter->link_speed == SPEED_1000 &&
1809                             (adapter->hw.mac_type == em_82571 ||
1810                              adapter->hw.mac_type == em_82572)) {
1811                                 int tarc0;
1812
1813                                 tarc0 = E1000_READ_REG(&adapter->hw, TARC0);
1814                                 tarc0 |= SPEED_MODE_BIT;
1815                                 E1000_WRITE_REG(&adapter->hw, TARC0, tarc0);
1816                         }
1817                         if (bootverbose) {
1818                                 if_printf(&adapter->interface_data.ac_if,
1819                                           "Link is up %d Mbps %s\n",
1820                                           adapter->link_speed,
1821                                           adapter->link_duplex == FULL_DUPLEX ?
1822                                                 "Full Duplex" : "Half Duplex");
1823                         }
1824                         adapter->link_active = 1;
1825                         adapter->smartspeed = 0;
1826                         ifp->if_baudrate = adapter->link_speed * 1000000;
1827                         ifp->if_link_state = LINK_STATE_UP;
1828                         if_link_state_change(ifp);
1829                 }
1830         } else {
1831                 if (adapter->link_active == 1) {
1832                         ifp->if_baudrate = 0;
1833                         adapter->link_speed = 0;
1834                         adapter->link_duplex = 0;
1835                         if (bootverbose) {
1836                                 if_printf(&adapter->interface_data.ac_if,
1837                                           "Link is Down\n");
1838                         }
1839                         adapter->link_active = 0;
1840                         ifp->if_link_state = LINK_STATE_DOWN;
1841                         if_link_state_change(ifp);
1842                 }
1843         }
1844 }
1845
1846 /*********************************************************************
1847  *
1848  *  This routine disables all traffic on the adapter by issuing a
1849  *  global reset on the MAC and deallocates TX/RX buffers.
1850  *
1851  **********************************************************************/
1852
1853 static void
1854 em_stop(void *arg)
1855 {
1856         struct ifnet   *ifp;
1857         struct adapter * adapter = arg;
1858         ifp = &adapter->interface_data.ac_if;
1859
1860         ASSERT_SERIALIZED(ifp->if_serializer);
1861
1862         INIT_DEBUGOUT("em_stop: begin");
1863         em_disable_intr(adapter);
1864         em_reset_hw(&adapter->hw);
1865         callout_stop(&adapter->timer);
1866         callout_stop(&adapter->tx_fifo_timer);
1867         em_free_transmit_structures(adapter);
1868         em_free_receive_structures(adapter);
1869
1870         /* Tell the stack that the interface is no longer active */
1871         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1872         ifp->if_timer = 0;
1873 }
1874
1875 /*********************************************************************
1876  *
1877  *  Determine hardware revision.
1878  *
1879  **********************************************************************/
1880 static void
1881 em_identify_hardware(struct adapter *adapter)
1882 {
1883         device_t dev = adapter->dev;
1884
1885         /* Make sure our PCI config space has the necessary stuff set */
1886         adapter->hw.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
1887         if (!((adapter->hw.pci_cmd_word & PCIM_CMD_BUSMASTEREN) &&
1888               (adapter->hw.pci_cmd_word & PCIM_CMD_MEMEN))) {
1889                 device_printf(dev, "Memory Access and/or Bus Master bits "
1890                               "were not set!\n");
1891                 adapter->hw.pci_cmd_word |= PCIM_CMD_BUSMASTEREN |
1892                                             PCIM_CMD_MEMEN;
1893                 pci_write_config(dev, PCIR_COMMAND,
1894                                  adapter->hw.pci_cmd_word, 2);
1895         }
1896
1897         /* Save off the information about this board */
1898         adapter->hw.vendor_id = pci_get_vendor(dev);
1899         adapter->hw.device_id = pci_get_device(dev);
1900         adapter->hw.revision_id = pci_get_revid(dev);
1901         adapter->hw.subsystem_vendor_id = pci_get_subvendor(dev);
1902         adapter->hw.subsystem_id = pci_get_subdevice(dev);
1903
1904         /* Identify the MAC */
1905         if (em_set_mac_type(&adapter->hw))
1906                 device_printf(dev, "Unknown MAC Type\n");
1907
1908         if (adapter->hw.mac_type == em_82541 ||
1909             adapter->hw.mac_type == em_82541_rev_2 ||
1910             adapter->hw.mac_type == em_82547 ||
1911             adapter->hw.mac_type == em_82547_rev_2)
1912                 adapter->hw.phy_init_script = TRUE;
1913 }
1914
1915 static int
1916 em_allocate_pci_resources(device_t dev)
1917 {
1918         struct adapter *adapter = device_get_softc(dev);
1919         int rid;
1920
1921         rid = PCIR_BAR(0);
1922         adapter->res_memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
1923                                                      &rid, RF_ACTIVE);
1924         if (adapter->res_memory == NULL) {
1925                 device_printf(dev, "Unable to allocate bus resource: memory\n");
1926                 return ENXIO;
1927         }
1928         adapter->osdep.mem_bus_space_tag =
1929                 rman_get_bustag(adapter->res_memory);
1930         adapter->osdep.mem_bus_space_handle =
1931             rman_get_bushandle(adapter->res_memory);
1932         adapter->hw.hw_addr = (uint8_t *)&adapter->osdep.mem_bus_space_handle;
1933
1934         if (adapter->hw.mac_type > em_82543) {
1935                 /* Figure our where our IO BAR is ? */
1936                 for (rid = PCIR_BAR(0); rid < PCIR_CIS;) {
1937                         uint32_t val;
1938
1939                         val = pci_read_config(dev, rid, 4);
1940                         if (EM_BAR_TYPE(val) == EM_BAR_TYPE_IO) {
1941                                 adapter->io_rid = rid;
1942                                 break;
1943                         }
1944                         rid += 4;
1945                         /* check for 64bit BAR */
1946                         if (EM_BAR_MEM_TYPE(val) == EM_BAR_MEM_TYPE_64BIT)
1947                                 rid += 4;
1948                 }
1949                 if (rid >= PCIR_CIS) {
1950                         device_printf(dev, "Unable to locate IO BAR\n");
1951                         return (ENXIO);
1952                 }
1953
1954                 adapter->res_ioport = bus_alloc_resource_any(dev,
1955                     SYS_RES_IOPORT, &adapter->io_rid, RF_ACTIVE);
1956                 if (!(adapter->res_ioport)) {
1957                         device_printf(dev, "Unable to allocate bus resource: "
1958                                       "ioport\n");
1959                         return ENXIO;
1960                 }
1961                 adapter->hw.io_base = 0;
1962                 adapter->osdep.io_bus_space_tag =
1963                         rman_get_bustag(adapter->res_ioport);
1964                 adapter->osdep.io_bus_space_handle =
1965                         rman_get_bushandle(adapter->res_ioport);
1966         }
1967
1968         /* For ICH8 we need to find the flash memory. */
1969         if ((adapter->hw.mac_type == em_ich8lan) ||
1970             (adapter->hw.mac_type == em_ich9lan)) {
1971                 rid = EM_FLASH;
1972                 adapter->flash_mem = bus_alloc_resource_any(dev,
1973                     SYS_RES_MEMORY, &rid, RF_ACTIVE);
1974                 if (adapter->flash_mem == NULL) {
1975                         device_printf(dev, "Unable to allocate bus resource: "
1976                                       "flash memory\n");
1977                         return ENXIO;
1978                 }
1979                 adapter->osdep.flash_bus_space_tag =
1980                     rman_get_bustag(adapter->flash_mem);
1981                 adapter->osdep.flash_bus_space_handle =
1982                     rman_get_bushandle(adapter->flash_mem);
1983         }
1984
1985         rid = 0x0;
1986         adapter->res_interrupt = bus_alloc_resource_any(dev, SYS_RES_IRQ,
1987             &rid, RF_SHAREABLE | RF_ACTIVE);
1988         if (adapter->res_interrupt == NULL) {
1989                 device_printf(dev, "Unable to allocate bus resource: "
1990                               "interrupt\n");
1991                 return ENXIO;
1992         }
1993
1994         adapter->hw.back = &adapter->osdep;
1995
1996         return 0;
1997 }
1998
1999 static void
2000 em_free_pci_resources(device_t dev)
2001 {
2002         struct adapter *adapter = device_get_softc(dev);
2003
2004         if (adapter->res_interrupt != NULL) {
2005                 bus_release_resource(dev, SYS_RES_IRQ, 0, 
2006                                      adapter->res_interrupt);
2007         }
2008         if (adapter->res_memory != NULL) {
2009                 bus_release_resource(dev, SYS_RES_MEMORY, PCIR_BAR(0), 
2010                                      adapter->res_memory);
2011         }
2012
2013         if (adapter->res_ioport != NULL) {
2014                 bus_release_resource(dev, SYS_RES_IOPORT, adapter->io_rid, 
2015                                      adapter->res_ioport);
2016         }
2017
2018         if (adapter->flash_mem != NULL) {
2019                 bus_release_resource(dev, SYS_RES_MEMORY, EM_FLASH,
2020                                      adapter->flash_mem);
2021         }
2022 }
2023
2024 /*********************************************************************
2025  *
2026  *  Initialize the hardware to a configuration as specified by the
2027  *  adapter structure. The controller is reset, the EEPROM is
2028  *  verified, the MAC address is set, then the shared initialization
2029  *  routines are called.
2030  *
2031  **********************************************************************/
2032 static int
2033 em_hardware_init(struct adapter *adapter)
2034 {
2035         uint16_t        rx_buffer_size;
2036
2037         INIT_DEBUGOUT("em_hardware_init: begin");
2038         /* Issue a global reset */
2039         em_reset_hw(&adapter->hw);
2040
2041         /* When hardware is reset, fifo_head is also reset */
2042         adapter->tx_fifo_head = 0;
2043
2044         /* Make sure we have a good EEPROM before we read from it */
2045         if (em_validate_eeprom_checksum(&adapter->hw) < 0) {
2046                 if (em_validate_eeprom_checksum(&adapter->hw) < 0) {
2047                         device_printf(adapter->dev,
2048                                       "The EEPROM Checksum Is Not Valid\n");
2049                         return (EIO);
2050                 }
2051         }
2052
2053         if (em_read_part_num(&adapter->hw, &(adapter->part_num)) < 0) {
2054                 device_printf(adapter->dev,
2055                               "EEPROM read error while reading part number\n");
2056                 return (EIO);
2057         }
2058
2059         /* Set up smart power down as default off on newer adapters. */
2060         if (!em_smart_pwr_down &&
2061             (adapter->hw.mac_type == em_82571 ||
2062              adapter->hw.mac_type == em_82572)) {
2063                 uint16_t phy_tmp = 0;
2064
2065                 /* Speed up time to link by disabling smart power down. */
2066                 em_read_phy_reg(&adapter->hw, IGP02E1000_PHY_POWER_MGMT,
2067                                 &phy_tmp);
2068                 phy_tmp &= ~IGP02E1000_PM_SPD;
2069                 em_write_phy_reg(&adapter->hw, IGP02E1000_PHY_POWER_MGMT,
2070                                  phy_tmp);
2071         }
2072
2073         /*
2074          * These parameters control the automatic generation (Tx) and
2075          * response (Rx) to Ethernet PAUSE frames.
2076          * - High water mark should allow for at least two frames to be
2077          *   received after sending an XOFF.
2078          * - Low water mark works best when it is very near the high water mark.
2079          *   This allows the receiver to restart by sending XON when it has
2080          *   drained a bit.  Here we use an arbitary value of 1500 which will
2081          *   restart after one full frame is pulled from the buffer.  There
2082          *   could be several smaller frames in the buffer and if so they will
2083          *   not trigger the XON until their total number reduces the buffer
2084          *   by 1500.
2085          * - The pause time is fairly large at 1000 x 512ns = 512 usec.
2086          */
2087         rx_buffer_size = ((E1000_READ_REG(&adapter->hw, PBA) & 0xffff) << 10);
2088
2089         adapter->hw.fc_high_water =
2090             rx_buffer_size - roundup2(adapter->hw.max_frame_size, 1024); 
2091         adapter->hw.fc_low_water = adapter->hw.fc_high_water - 1500;
2092         if (adapter->hw.mac_type == em_80003es2lan)
2093                 adapter->hw.fc_pause_time = 0xFFFF;
2094         else
2095                 adapter->hw.fc_pause_time = 1000;
2096         adapter->hw.fc_send_xon = TRUE;
2097         adapter->hw.fc = E1000_FC_FULL;
2098
2099         if (em_init_hw(&adapter->hw) < 0) {
2100                 device_printf(adapter->dev, "Hardware Initialization Failed");
2101                 return (EIO);
2102         }
2103
2104         em_check_for_link(&adapter->hw);
2105
2106         return (0);
2107 }
2108
2109 /*********************************************************************
2110  *
2111  *  Setup networking device structure and register an interface.
2112  *
2113  **********************************************************************/
2114 static void
2115 em_setup_interface(device_t dev, struct adapter *adapter)
2116 {
2117         struct ifnet *ifp;
2118         u_char fiber_type = IFM_1000_SX;        /* default type */
2119         INIT_DEBUGOUT("em_setup_interface: begin");
2120
2121         ifp = &adapter->interface_data.ac_if;
2122         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2123         ifp->if_mtu = ETHERMTU;
2124         ifp->if_baudrate = 1000000000;
2125         ifp->if_init =  em_init;
2126         ifp->if_softc = adapter;
2127         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2128         ifp->if_ioctl = em_ioctl;
2129         ifp->if_start = em_start;
2130 #ifdef DEVICE_POLLING
2131         ifp->if_poll = em_poll;
2132 #endif
2133         ifp->if_watchdog = em_watchdog;
2134         ifq_set_maxlen(&ifp->if_snd, adapter->num_tx_desc - 1);
2135         ifq_set_ready(&ifp->if_snd);
2136
2137         if (adapter->hw.mac_type >= em_82543)
2138                 ifp->if_capabilities |= IFCAP_HWCSUM;
2139
2140         ifp->if_capenable = ifp->if_capabilities;
2141
2142         ether_ifattach(ifp, adapter->hw.mac_addr, NULL);
2143
2144 #ifdef PROFILE_SERIALIZER
2145         SYSCTL_ADD_UINT(&adapter->sysctl_ctx,
2146                         SYSCTL_CHILDREN(adapter->sysctl_tree), OID_AUTO,
2147                         "serializer_sleep", CTLFLAG_RW,
2148                         &ifp->if_serializer->sleep_cnt, 0, NULL);
2149         SYSCTL_ADD_UINT(&adapter->sysctl_ctx,
2150                         SYSCTL_CHILDREN(adapter->sysctl_tree), OID_AUTO,
2151                         "serializer_tryfail", CTLFLAG_RW,
2152                         &ifp->if_serializer->tryfail_cnt, 0, NULL);
2153         SYSCTL_ADD_UINT(&adapter->sysctl_ctx,
2154                         SYSCTL_CHILDREN(adapter->sysctl_tree), OID_AUTO,
2155                         "serializer_enter", CTLFLAG_RW,
2156                         &ifp->if_serializer->enter_cnt, 0, NULL);
2157         SYSCTL_ADD_UINT(&adapter->sysctl_ctx,
2158                         SYSCTL_CHILDREN(adapter->sysctl_tree), OID_AUTO,
2159                         "serializer_try", CTLFLAG_RW,
2160                         &ifp->if_serializer->try_cnt, 0, NULL);
2161 #endif
2162
2163         /*
2164          * Tell the upper layer(s) we support long frames.
2165          */
2166         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
2167         ifp->if_capabilities |= IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU;
2168         ifp->if_capenable |= IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU;
2169
2170         /*
2171          * Specify the media types supported by this adapter and register
2172          * callbacks to update media and link information
2173          */
2174         ifmedia_init(&adapter->media, IFM_IMASK, em_media_change,
2175                      em_media_status);
2176         if (adapter->hw.media_type == em_media_type_fiber ||
2177             adapter->hw.media_type == em_media_type_internal_serdes) {
2178                 if (adapter->hw.mac_type == em_82545)
2179                         fiber_type = IFM_1000_LX;
2180                 ifmedia_add(&adapter->media, IFM_ETHER | fiber_type | IFM_FDX, 
2181                             0, NULL);
2182                 ifmedia_add(&adapter->media, IFM_ETHER | fiber_type, 0, NULL);
2183         } else {
2184                 ifmedia_add(&adapter->media, IFM_ETHER | IFM_10_T, 0, NULL);
2185                 ifmedia_add(&adapter->media, IFM_ETHER | IFM_10_T | IFM_FDX,
2186                             0, NULL);
2187                 ifmedia_add(&adapter->media, IFM_ETHER | IFM_100_TX,
2188                             0, NULL);
2189                 ifmedia_add(&adapter->media, IFM_ETHER | IFM_100_TX | IFM_FDX,
2190                             0, NULL);
2191                 ifmedia_add(&adapter->media, IFM_ETHER | IFM_1000_T | IFM_FDX,
2192                             0, NULL);
2193                 ifmedia_add(&adapter->media, IFM_ETHER | IFM_1000_T, 0, NULL);
2194         }
2195         ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2196         ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
2197 }
2198
2199 /*********************************************************************
2200  *
2201  *  Workaround for SmartSpeed on 82541 and 82547 controllers
2202  *
2203  **********************************************************************/
2204 static void
2205 em_smartspeed(struct adapter *adapter)
2206 {
2207         uint16_t phy_tmp;
2208
2209         if (adapter->link_active || (adapter->hw.phy_type != em_phy_igp) ||
2210             !adapter->hw.autoneg ||
2211             !(adapter->hw.autoneg_advertised & ADVERTISE_1000_FULL))
2212                 return;
2213
2214         if (adapter->smartspeed == 0) {
2215                 /*
2216                  * If Master/Slave config fault is asserted twice,
2217                  * we assume back-to-back.
2218                  */
2219                 em_read_phy_reg(&adapter->hw, PHY_1000T_STATUS, &phy_tmp);
2220                 if (!(phy_tmp & SR_1000T_MS_CONFIG_FAULT))
2221                         return;
2222                 em_read_phy_reg(&adapter->hw, PHY_1000T_STATUS, &phy_tmp);
2223                 if (phy_tmp & SR_1000T_MS_CONFIG_FAULT) {
2224                         em_read_phy_reg(&adapter->hw, PHY_1000T_CTRL, &phy_tmp);
2225                         if (phy_tmp & CR_1000T_MS_ENABLE) {
2226                                 phy_tmp &= ~CR_1000T_MS_ENABLE;
2227                                 em_write_phy_reg(&adapter->hw,
2228                                                  PHY_1000T_CTRL, phy_tmp);
2229                                 adapter->smartspeed++;
2230                                 if (adapter->hw.autoneg &&
2231                                     !em_phy_setup_autoneg(&adapter->hw) &&
2232                                     !em_read_phy_reg(&adapter->hw, PHY_CTRL,
2233                                                      &phy_tmp)) {
2234                                         phy_tmp |= (MII_CR_AUTO_NEG_EN |
2235                                                     MII_CR_RESTART_AUTO_NEG);
2236                                         em_write_phy_reg(&adapter->hw,
2237                                                          PHY_CTRL, phy_tmp);
2238                                 }
2239                         }
2240                 }
2241                 return;
2242         } else if (adapter->smartspeed == EM_SMARTSPEED_DOWNSHIFT) {
2243                 /* If still no link, perhaps using 2/3 pair cable */
2244                 em_read_phy_reg(&adapter->hw, PHY_1000T_CTRL, &phy_tmp);
2245                 phy_tmp |= CR_1000T_MS_ENABLE;
2246                 em_write_phy_reg(&adapter->hw, PHY_1000T_CTRL, phy_tmp);
2247                 if (adapter->hw.autoneg &&
2248                     !em_phy_setup_autoneg(&adapter->hw) &&
2249                     !em_read_phy_reg(&adapter->hw, PHY_CTRL, &phy_tmp)) {
2250                         phy_tmp |= (MII_CR_AUTO_NEG_EN |
2251                                     MII_CR_RESTART_AUTO_NEG);
2252                         em_write_phy_reg(&adapter->hw, PHY_CTRL, phy_tmp);
2253                 }
2254         }
2255         /* Restart process after EM_SMARTSPEED_MAX iterations */
2256         if (adapter->smartspeed++ == EM_SMARTSPEED_MAX)
2257                 adapter->smartspeed = 0;
2258 }
2259
2260 /*
2261  * Manage DMA'able memory.
2262  */
2263 static void
2264 em_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2265 {
2266         if (error)
2267                 return;
2268         *(bus_addr_t *)arg = segs->ds_addr;
2269 }
2270
2271 static int
2272 em_dma_malloc(struct adapter *adapter, bus_size_t size,
2273               struct em_dma_alloc *dma)
2274 {
2275         device_t dev = adapter->dev;
2276         int error;
2277
2278         error = bus_dma_tag_create(NULL,                /* parent */
2279                                    EM_DBA_ALIGN, 0,     /* alignment, bounds */
2280                                    BUS_SPACE_MAXADDR,   /* lowaddr */
2281                                    BUS_SPACE_MAXADDR,   /* highaddr */
2282                                    NULL, NULL,          /* filter, filterarg */
2283                                    size,                /* maxsize */
2284                                    1,                   /* nsegments */
2285                                    size,                /* maxsegsize */
2286                                    0,                   /* flags */
2287                                    &dma->dma_tag);
2288         if (error) {
2289                 device_printf(dev, "%s: bus_dma_tag_create failed; error %d\n",
2290                               __func__, error);
2291                 return error;
2292         }
2293
2294         error = bus_dmamem_alloc(dma->dma_tag, (void**)&dma->dma_vaddr,
2295                                  BUS_DMA_WAITOK, &dma->dma_map);
2296         if (error) {
2297                 device_printf(dev, "%s: bus_dmammem_alloc failed; "
2298                               "size %llu, error %d\n",
2299                               __func__, (uintmax_t)size, error);
2300                 goto fail;
2301         }
2302
2303         error = bus_dmamap_load(dma->dma_tag, dma->dma_map,
2304                                 dma->dma_vaddr, size,
2305                                 em_dmamap_cb, &dma->dma_paddr,
2306                                 BUS_DMA_WAITOK);
2307         if (error) {
2308                 device_printf(dev, "%s: bus_dmamap_load failed; error %u\n",
2309                               __func__, error);
2310                 bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
2311                 goto fail;
2312         }
2313
2314         return 0;
2315 fail:
2316         bus_dma_tag_destroy(dma->dma_tag);
2317         dma->dma_tag = NULL;
2318         return error;
2319 }
2320
2321 static void
2322 em_dma_free(struct adapter *adapter, struct em_dma_alloc *dma)
2323 {
2324         if (dma->dma_tag != NULL) {
2325                 bus_dmamap_unload(dma->dma_tag, dma->dma_map);
2326                 bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
2327                 bus_dma_tag_destroy(dma->dma_tag);
2328                 dma->dma_tag = NULL;
2329         }
2330 }
2331
2332 /*********************************************************************
2333  *
2334  *  Allocate and initialize transmit structures.
2335  *
2336  **********************************************************************/
2337 static int
2338 em_setup_transmit_structures(struct adapter *adapter)
2339 {
2340         struct em_buffer *tx_buffer;
2341         bus_size_t size;
2342         int error, i;
2343
2344         /*
2345          * Setup DMA descriptor areas.
2346          */
2347         size = roundup2(adapter->hw.max_frame_size, MCLBYTES);
2348         if (bus_dma_tag_create(NULL,                    /* parent */
2349                                1, 0,                    /* alignment, bounds */
2350                                BUS_SPACE_MAXADDR,       /* lowaddr */ 
2351                                BUS_SPACE_MAXADDR,       /* highaddr */
2352                                NULL, NULL,              /* filter, filterarg */
2353                                size,                    /* maxsize */
2354                                EM_MAX_SCATTER,          /* nsegments */
2355                                size,                    /* maxsegsize */
2356                                0,                       /* flags */ 
2357                                &adapter->txtag)) {
2358                 device_printf(adapter->dev, "Unable to allocate TX DMA tag\n");
2359                 return(ENOMEM);
2360         }
2361
2362         adapter->tx_buffer_area =
2363                 kmalloc(sizeof(struct em_buffer) * adapter->num_tx_desc,
2364                         M_DEVBUF, M_WAITOK | M_ZERO);
2365
2366         bzero(adapter->tx_desc_base,
2367               sizeof(struct em_tx_desc) * adapter->num_tx_desc);
2368         tx_buffer = adapter->tx_buffer_area;
2369         for (i = 0; i < adapter->num_tx_desc; i++) {
2370                 error = bus_dmamap_create(adapter->txtag, 0, &tx_buffer->map);
2371                 if (error) {
2372                         device_printf(adapter->dev,
2373                                       "Unable to create TX DMA map\n");
2374                         goto fail;
2375                 }
2376                 tx_buffer++;
2377         }
2378
2379         adapter->next_avail_tx_desc = 0;
2380         adapter->next_tx_to_clean = 0;
2381
2382         /* Set number of descriptors available */
2383         adapter->num_tx_desc_avail = adapter->num_tx_desc;
2384
2385         /* Set checksum context */
2386         adapter->active_checksum_context = OFFLOAD_NONE;
2387
2388         bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
2389                         BUS_DMASYNC_PREWRITE);
2390
2391         return (0);
2392 fail:
2393         em_free_transmit_structures(adapter);
2394         return (error);
2395 }
2396
2397 /*********************************************************************
2398  *
2399  *  Enable transmit unit.
2400  *
2401  **********************************************************************/
2402 static void
2403 em_initialize_transmit_unit(struct adapter *adapter)
2404 {
2405         uint32_t reg_tctl;
2406         uint32_t reg_tipg = 0;
2407         uint64_t bus_addr;
2408
2409         INIT_DEBUGOUT("em_initialize_transmit_unit: begin");
2410
2411         /* Setup the Base and Length of the Tx Descriptor Ring */
2412         bus_addr = adapter->txdma.dma_paddr;
2413         E1000_WRITE_REG(&adapter->hw, TDLEN,
2414                         adapter->num_tx_desc * sizeof(struct em_tx_desc));
2415         E1000_WRITE_REG(&adapter->hw, TDBAH, (uint32_t)(bus_addr >> 32));
2416         E1000_WRITE_REG(&adapter->hw, TDBAL, (uint32_t)bus_addr);
2417
2418         /* Setup the HW Tx Head and Tail descriptor pointers */
2419         E1000_WRITE_REG(&adapter->hw, TDT, 0);
2420         E1000_WRITE_REG(&adapter->hw, TDH, 0);
2421
2422         HW_DEBUGOUT2("Base = %x, Length = %x\n",
2423                      E1000_READ_REG(&adapter->hw, TDBAL),
2424                      E1000_READ_REG(&adapter->hw, TDLEN));
2425
2426         /* Set the default values for the Tx Inter Packet Gap timer */
2427         switch (adapter->hw.mac_type) {
2428         case em_82542_rev2_0:
2429         case em_82542_rev2_1:
2430                 reg_tipg = DEFAULT_82542_TIPG_IPGT;
2431                 reg_tipg |= DEFAULT_82542_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
2432                 reg_tipg |= DEFAULT_82542_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
2433                 break;
2434         case em_80003es2lan:
2435                 reg_tipg = DEFAULT_82543_TIPG_IPGR1;
2436                 reg_tipg |=
2437                     DEFAULT_80003ES2LAN_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
2438                 break;
2439         default:
2440                 if (adapter->hw.media_type == em_media_type_fiber ||
2441                     adapter->hw.media_type == em_media_type_internal_serdes)
2442                         reg_tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
2443                 else
2444                         reg_tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
2445                 reg_tipg |= DEFAULT_82543_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
2446                 reg_tipg |= DEFAULT_82543_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
2447         }
2448
2449         E1000_WRITE_REG(&adapter->hw, TIPG, reg_tipg);
2450         E1000_WRITE_REG(&adapter->hw, TIDV, adapter->tx_int_delay.value);
2451         if (adapter->hw.mac_type >= em_82540) {
2452                 E1000_WRITE_REG(&adapter->hw, TADV,
2453                                 adapter->tx_abs_int_delay.value);
2454         }
2455
2456         /* Program the Transmit Control Register */
2457         reg_tctl = E1000_TCTL_PSP | E1000_TCTL_EN |
2458                    (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
2459         if (adapter->hw.mac_type >= em_82571)
2460                 reg_tctl |= E1000_TCTL_MULR;
2461         if (adapter->link_duplex == 1)
2462                 reg_tctl |= E1000_FDX_COLLISION_DISTANCE << E1000_COLD_SHIFT;
2463         else
2464                 reg_tctl |= E1000_HDX_COLLISION_DISTANCE << E1000_COLD_SHIFT;
2465
2466         /* This write will effectively turn on the transmit unit. */
2467         E1000_WRITE_REG(&adapter->hw, TCTL, reg_tctl);
2468
2469         /* Setup Transmit Descriptor Base Settings */
2470         adapter->txd_cmd = E1000_TXD_CMD_IFCS;
2471
2472         if (adapter->tx_int_delay.value > 0)
2473                 adapter->txd_cmd |= E1000_TXD_CMD_IDE;
2474 }
2475
2476 /*********************************************************************
2477  *
2478  *  Free all transmit related data structures.
2479  *
2480  **********************************************************************/
2481 static void
2482 em_free_transmit_structures(struct adapter *adapter)
2483 {
2484         struct em_buffer *tx_buffer;
2485         int i;
2486
2487         INIT_DEBUGOUT("free_transmit_structures: begin");
2488
2489         if (adapter->tx_buffer_area != NULL) {
2490                 tx_buffer = adapter->tx_buffer_area;
2491                 for (i = 0; i < adapter->num_tx_desc; i++, tx_buffer++) {
2492                         if (tx_buffer->m_head != NULL) {
2493                                 bus_dmamap_unload(adapter->txtag,
2494                                                   tx_buffer->map);
2495                                 m_freem(tx_buffer->m_head);
2496                         }
2497
2498                         if (tx_buffer->map != NULL) {
2499                                 bus_dmamap_destroy(adapter->txtag, tx_buffer->map);
2500                                 tx_buffer->map = NULL;
2501                         }
2502                         tx_buffer->m_head = NULL;
2503                 }
2504         }
2505         if (adapter->tx_buffer_area != NULL) {
2506                 kfree(adapter->tx_buffer_area, M_DEVBUF);
2507                 adapter->tx_buffer_area = NULL;
2508         }
2509         if (adapter->txtag != NULL) {
2510                 bus_dma_tag_destroy(adapter->txtag);
2511                 adapter->txtag = NULL;
2512         }
2513 }
2514
2515 /*********************************************************************
2516  *
2517  *  The offload context needs to be set when we transfer the first
2518  *  packet of a particular protocol (TCP/UDP). We change the
2519  *  context only if the protocol type changes.
2520  *
2521  **********************************************************************/
2522 static void
2523 em_transmit_checksum_setup(struct adapter *adapter,
2524                            struct mbuf *mp,
2525                            uint32_t *txd_upper,
2526                            uint32_t *txd_lower) 
2527 {
2528         struct em_context_desc *TXD;
2529         struct em_buffer *tx_buffer;
2530         int curr_txd;
2531
2532         if (mp->m_pkthdr.csum_flags) {
2533                 if (mp->m_pkthdr.csum_flags & CSUM_TCP) {
2534                         *txd_upper = E1000_TXD_POPTS_TXSM << 8;
2535                         *txd_lower = E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
2536                         if (adapter->active_checksum_context == OFFLOAD_TCP_IP)
2537                                 return;
2538                         else
2539                                 adapter->active_checksum_context = OFFLOAD_TCP_IP;
2540                 } else if (mp->m_pkthdr.csum_flags & CSUM_UDP) {
2541                         *txd_upper = E1000_TXD_POPTS_TXSM << 8;
2542                         *txd_lower = E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
2543                         if (adapter->active_checksum_context == OFFLOAD_UDP_IP)
2544                                 return;
2545                         else
2546                                 adapter->active_checksum_context = OFFLOAD_UDP_IP;
2547                 } else {
2548                         *txd_upper = 0;
2549                         *txd_lower = 0;
2550                         return;
2551                 }
2552         } else {
2553                 *txd_upper = 0;
2554                 *txd_lower = 0;
2555                 return;
2556         }
2557
2558         /*
2559          * If we reach this point, the checksum offload context
2560          * needs to be reset.
2561          */
2562         curr_txd = adapter->next_avail_tx_desc;
2563         tx_buffer = &adapter->tx_buffer_area[curr_txd];
2564         TXD = (struct em_context_desc *) &adapter->tx_desc_base[curr_txd];
2565
2566         TXD->lower_setup.ip_fields.ipcss = ETHER_HDR_LEN;
2567         TXD->lower_setup.ip_fields.ipcso =
2568             ETHER_HDR_LEN + offsetof(struct ip, ip_sum);
2569         TXD->lower_setup.ip_fields.ipcse =
2570             htole16(ETHER_HDR_LEN + sizeof(struct ip) - 1);
2571
2572         TXD->upper_setup.tcp_fields.tucss =
2573             ETHER_HDR_LEN + sizeof(struct ip);
2574         TXD->upper_setup.tcp_fields.tucse = htole16(0);
2575
2576         if (adapter->active_checksum_context == OFFLOAD_TCP_IP) {
2577                 TXD->upper_setup.tcp_fields.tucso =
2578                         ETHER_HDR_LEN + sizeof(struct ip) +
2579                         offsetof(struct tcphdr, th_sum);
2580         } else if (adapter->active_checksum_context == OFFLOAD_UDP_IP) {
2581                 TXD->upper_setup.tcp_fields.tucso =
2582                         ETHER_HDR_LEN + sizeof(struct ip) +
2583                         offsetof(struct udphdr, uh_sum);
2584         }
2585
2586         TXD->tcp_seg_setup.data = htole32(0);
2587         TXD->cmd_and_length = htole32(adapter->txd_cmd | E1000_TXD_CMD_DEXT);
2588
2589         tx_buffer->m_head = NULL;
2590         tx_buffer->next_eop = -1;
2591
2592         if (++curr_txd == adapter->num_tx_desc)
2593                 curr_txd = 0;
2594
2595         adapter->num_tx_desc_avail--;
2596         adapter->next_avail_tx_desc = curr_txd;
2597 }
2598
2599 /**********************************************************************
2600  *
2601  *  Examine each tx_buffer in the used queue. If the hardware is done
2602  *  processing the packet then free associated resources. The
2603  *  tx_buffer is put back on the free queue.
2604  *
2605  **********************************************************************/
2606
2607 static void
2608 em_txeof(struct adapter *adapter)
2609 {
2610         int first, last, done, num_avail;
2611         struct em_buffer *tx_buffer;
2612         struct em_tx_desc *tx_desc, *eop_desc;
2613         struct ifnet *ifp = &adapter->interface_data.ac_if;
2614
2615         if (adapter->num_tx_desc_avail == adapter->num_tx_desc)
2616                 return;
2617
2618         num_avail = adapter->num_tx_desc_avail; 
2619         first = adapter->next_tx_to_clean;
2620         tx_desc = &adapter->tx_desc_base[first];
2621         tx_buffer = &adapter->tx_buffer_area[first];
2622         last = tx_buffer->next_eop;
2623         KKASSERT(last >= 0 && last < adapter->num_tx_desc);
2624         eop_desc = &adapter->tx_desc_base[last];
2625
2626         /*
2627          * Now caculate the terminating index for the cleanup loop below
2628          */
2629         if (++last == adapter->num_tx_desc)
2630                 last = 0;
2631         done = last;
2632
2633         bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
2634                         BUS_DMASYNC_POSTREAD);
2635
2636         while (eop_desc->upper.fields.status & E1000_TXD_STAT_DD) {
2637                 while (first != done) {
2638                         tx_desc->upper.data = 0;
2639                         tx_desc->lower.data = 0;
2640                         num_avail++;
2641
2642                         logif(pkt_txclean);
2643
2644                         if (tx_buffer->m_head) {
2645                                 ifp->if_opackets++;
2646                                 bus_dmamap_sync(adapter->txtag, tx_buffer->map,
2647                                                 BUS_DMASYNC_POSTWRITE);
2648                                 bus_dmamap_unload(adapter->txtag,
2649                                                   tx_buffer->map);
2650
2651                                 m_freem(tx_buffer->m_head);
2652                                 tx_buffer->m_head = NULL;
2653                         }
2654                         tx_buffer->next_eop = -1;
2655
2656                         if (++first == adapter->num_tx_desc)
2657                                 first = 0;
2658
2659                         tx_buffer = &adapter->tx_buffer_area[first];
2660                         tx_desc = &adapter->tx_desc_base[first];
2661                 }
2662                 /* See if we can continue to the next packet */
2663                 last = tx_buffer->next_eop;
2664                 if (last != -1) {
2665                         KKASSERT(last >= 0 && last < adapter->num_tx_desc);
2666                         eop_desc = &adapter->tx_desc_base[last];
2667                         if (++last == adapter->num_tx_desc)
2668                                 last = 0;
2669                         done = last;
2670                 } else {
2671                         break;
2672                 }
2673         }
2674
2675         bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
2676                         BUS_DMASYNC_PREWRITE);
2677
2678         adapter->next_tx_to_clean = first;
2679
2680         /*
2681          * If we have enough room, clear IFF_OACTIVE to tell the stack
2682          * that it is OK to send packets.
2683          * If there are no pending descriptors, clear the timeout. Otherwise,
2684          * if some descriptors have been freed, restart the timeout.
2685          */
2686         if (num_avail > EM_TX_CLEANUP_THRESHOLD) {
2687                 ifp->if_flags &= ~IFF_OACTIVE;
2688                 if (num_avail == adapter->num_tx_desc)
2689                         ifp->if_timer = 0;
2690                 else if (num_avail == adapter->num_tx_desc_avail)
2691                         ifp->if_timer = EM_TX_TIMEOUT;
2692         }
2693         adapter->num_tx_desc_avail = num_avail;
2694 }
2695
2696 /*********************************************************************
2697  *
2698  *  Get a buffer from system mbuf buffer pool.
2699  *
2700  **********************************************************************/
2701 static int
2702 em_get_buf(int i, struct adapter *adapter, struct mbuf *nmp, int how)
2703 {
2704         struct mbuf *mp = nmp;
2705         struct em_buffer *rx_buffer;
2706         struct ifnet *ifp;
2707         bus_addr_t paddr;
2708         int error;
2709
2710         ifp = &adapter->interface_data.ac_if;
2711
2712         if (mp == NULL) {
2713                 mp = m_getcl(how, MT_DATA, M_PKTHDR);
2714                 if (mp == NULL) {
2715                         adapter->mbuf_cluster_failed++;
2716                         return (ENOBUFS);
2717                 }
2718                 mp->m_len = mp->m_pkthdr.len = MCLBYTES;
2719         } else {
2720                 mp->m_len = mp->m_pkthdr.len = MCLBYTES;
2721                 mp->m_data = mp->m_ext.ext_buf;
2722                 mp->m_next = NULL;
2723         }
2724
2725         if (ifp->if_mtu <= ETHERMTU)
2726                 m_adj(mp, ETHER_ALIGN);
2727
2728         rx_buffer = &adapter->rx_buffer_area[i];
2729
2730         /*
2731          * Using memory from the mbuf cluster pool, invoke the
2732          * bus_dma machinery to arrange the memory mapping.
2733          */
2734         error = bus_dmamap_load(adapter->rxtag, rx_buffer->map,
2735                                 mtod(mp, void *), mp->m_len,
2736                                 em_dmamap_cb, &paddr, 0);
2737         if (error) {
2738                 m_freem(mp);
2739                 return (error);
2740         }
2741         rx_buffer->m_head = mp;
2742         adapter->rx_desc_base[i].buffer_addr = htole64(paddr);
2743         bus_dmamap_sync(adapter->rxtag, rx_buffer->map, BUS_DMASYNC_PREREAD);
2744
2745         return (0);
2746 }
2747
2748 /*********************************************************************
2749  *
2750  *  Allocate memory for rx_buffer structures. Since we use one
2751  *  rx_buffer per received packet, the maximum number of rx_buffer's
2752  *  that we'll need is equal to the number of receive descriptors
2753  *  that we've allocated.
2754  *
2755  **********************************************************************/
2756 static int
2757 em_allocate_receive_structures(struct adapter *adapter)
2758 {
2759         int i, error, size;
2760         struct em_buffer *rx_buffer;
2761
2762         size = adapter->num_rx_desc * sizeof(struct em_buffer);
2763         adapter->rx_buffer_area = kmalloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
2764
2765         error = bus_dma_tag_create(NULL,                /* parent */
2766                                    1, 0,                /* alignment, bounds */
2767                                    BUS_SPACE_MAXADDR,   /* lowaddr */
2768                                    BUS_SPACE_MAXADDR,   /* highaddr */
2769                                    NULL, NULL,          /* filter, filterarg */
2770                                    MCLBYTES,            /* maxsize */
2771                                    1,                   /* nsegments */
2772                                    MCLBYTES,            /* maxsegsize */
2773                                    0,                   /* flags */
2774                                    &adapter->rxtag);
2775         if (error) {
2776                 device_printf(adapter->dev, "%s: bus_dma_tag_create failed; "
2777                               "error %u\n", __func__, error);
2778                 goto fail;
2779         }
2780  
2781         rx_buffer = adapter->rx_buffer_area;
2782         for (i = 0; i < adapter->num_rx_desc; i++, rx_buffer++) {
2783                 error = bus_dmamap_create(adapter->rxtag, BUS_DMA_NOWAIT,
2784                                           &rx_buffer->map);
2785                 if (error) {
2786                         device_printf(adapter->dev,
2787                                       "%s: bus_dmamap_create failed; "
2788                                       "error %u\n", __func__, error);
2789                         goto fail;
2790                 }
2791         }
2792
2793         for (i = 0; i < adapter->num_rx_desc; i++) {
2794                 error = em_get_buf(i, adapter, NULL, MB_DONTWAIT);
2795                 if (error)
2796                         goto fail;
2797         }
2798
2799         bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
2800                         BUS_DMASYNC_PREWRITE);
2801
2802         return (0);
2803 fail:
2804         em_free_receive_structures(adapter);
2805         return (error);
2806 }
2807
2808 /*********************************************************************
2809  *
2810  *  Allocate and initialize receive structures.
2811  *
2812  **********************************************************************/
2813 static int
2814 em_setup_receive_structures(struct adapter *adapter)
2815 {
2816         int error;
2817
2818         bzero(adapter->rx_desc_base,
2819               sizeof(struct em_rx_desc) * adapter->num_rx_desc);
2820
2821         error = em_allocate_receive_structures(adapter);
2822         if (error)
2823                 return (error);
2824
2825         /* Setup our descriptor pointers */
2826         adapter->next_rx_desc_to_check = 0;
2827
2828         return (0);
2829 }
2830
2831 /*********************************************************************
2832  *
2833  *  Enable receive unit.
2834  *
2835  **********************************************************************/
2836 static void
2837 em_initialize_receive_unit(struct adapter *adapter)
2838 {
2839         uint32_t reg_rctl;
2840         uint32_t reg_rxcsum;
2841         struct ifnet *ifp;
2842         uint64_t bus_addr;
2843  
2844         INIT_DEBUGOUT("em_initialize_receive_unit: begin");
2845
2846         ifp = &adapter->interface_data.ac_if;
2847
2848         /*
2849          * Make sure receives are disabled while setting
2850          * up the descriptor ring
2851          */
2852         E1000_WRITE_REG(&adapter->hw, RCTL, 0);
2853
2854         /* Set the Receive Delay Timer Register */
2855         E1000_WRITE_REG(&adapter->hw, RDTR, 
2856                         adapter->rx_int_delay.value | E1000_RDT_FPDB);
2857
2858         if(adapter->hw.mac_type >= em_82540) {
2859                 E1000_WRITE_REG(&adapter->hw, RADV,
2860                                 adapter->rx_abs_int_delay.value);
2861
2862                 /* Set the interrupt throttling rate in 256ns increments */  
2863                 if (em_int_throttle_ceil) {
2864                         E1000_WRITE_REG(&adapter->hw, ITR,
2865                                 1000000000 / 256 / em_int_throttle_ceil);
2866                 } else {
2867                         E1000_WRITE_REG(&adapter->hw, ITR, 0);
2868                 }
2869         }
2870
2871         /* Setup the Base and Length of the Rx Descriptor Ring */
2872         bus_addr = adapter->rxdma.dma_paddr;
2873         E1000_WRITE_REG(&adapter->hw, RDLEN, adapter->num_rx_desc *
2874                         sizeof(struct em_rx_desc));
2875         E1000_WRITE_REG(&adapter->hw, RDBAH, (uint32_t)(bus_addr >> 32));
2876         E1000_WRITE_REG(&adapter->hw, RDBAL, (uint32_t)bus_addr);
2877
2878         /* Setup the Receive Control Register */
2879         reg_rctl = E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO |
2880                    E1000_RCTL_RDMTS_HALF |
2881                    (adapter->hw.mc_filter_type << E1000_RCTL_MO_SHIFT);
2882
2883         if (adapter->hw.tbi_compatibility_on == TRUE)
2884                 reg_rctl |= E1000_RCTL_SBP;
2885
2886         switch (adapter->rx_buffer_len) {
2887         default:
2888         case EM_RXBUFFER_2048:
2889                 reg_rctl |= E1000_RCTL_SZ_2048;
2890                 break;
2891         case EM_RXBUFFER_4096:
2892                 reg_rctl |= E1000_RCTL_SZ_4096 | E1000_RCTL_BSEX |
2893                             E1000_RCTL_LPE;
2894                 break;            
2895         case EM_RXBUFFER_8192:
2896                 reg_rctl |= E1000_RCTL_SZ_8192 | E1000_RCTL_BSEX |
2897                             E1000_RCTL_LPE;
2898                 break;
2899         case EM_RXBUFFER_16384:
2900                 reg_rctl |= E1000_RCTL_SZ_16384 | E1000_RCTL_BSEX |
2901                             E1000_RCTL_LPE;
2902                 break;
2903         }
2904
2905         if (ifp->if_mtu > ETHERMTU)
2906                 reg_rctl |= E1000_RCTL_LPE;
2907
2908         /* Enable 82543 Receive Checksum Offload for TCP and UDP */
2909         if ((adapter->hw.mac_type >= em_82543) &&
2910             (ifp->if_capenable & IFCAP_RXCSUM)) {
2911                 reg_rxcsum = E1000_READ_REG(&adapter->hw, RXCSUM);
2912                 reg_rxcsum |= (E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL);
2913                 E1000_WRITE_REG(&adapter->hw, RXCSUM, reg_rxcsum);
2914         }
2915
2916 #ifdef EM_X60_WORKAROUND
2917         if (adapter->hw.mac_type == em_82573)
2918                 E1000_WRITE_REG(&adapter->hw, RDTR, 32);
2919 #endif
2920
2921         /* Enable Receives */
2922         E1000_WRITE_REG(&adapter->hw, RCTL, reg_rctl);
2923
2924         /* Setup the HW Rx Head and Tail Descriptor Pointers */
2925         E1000_WRITE_REG(&adapter->hw, RDH, 0);
2926         E1000_WRITE_REG(&adapter->hw, RDT, adapter->num_rx_desc - 1);
2927 }
2928
2929 /*********************************************************************
2930  *
2931  *  Free receive related data structures.
2932  *
2933  **********************************************************************/
2934 static void
2935 em_free_receive_structures(struct adapter *adapter)
2936 {
2937         struct em_buffer *rx_buffer;
2938         int i;
2939
2940         INIT_DEBUGOUT("free_receive_structures: begin");
2941
2942         if (adapter->rx_buffer_area != NULL) {
2943                 rx_buffer = adapter->rx_buffer_area;
2944                 for (i = 0; i < adapter->num_rx_desc; i++, rx_buffer++) {
2945                         if (rx_buffer->m_head != NULL) {
2946                                 bus_dmamap_unload(adapter->rxtag,
2947                                                   rx_buffer->map);
2948                                 m_freem(rx_buffer->m_head);
2949                                 rx_buffer->m_head = NULL;
2950                         }
2951                         if (rx_buffer->map != NULL) {
2952                                 bus_dmamap_destroy(adapter->rxtag,
2953                                                    rx_buffer->map);
2954                                 rx_buffer->map = NULL;
2955                         }
2956                 }
2957         }
2958         if (adapter->rx_buffer_area != NULL) {
2959                 kfree(adapter->rx_buffer_area, M_DEVBUF);
2960                 adapter->rx_buffer_area = NULL;
2961         }
2962         if (adapter->rxtag != NULL) {
2963                 bus_dma_tag_destroy(adapter->rxtag);
2964                 adapter->rxtag = NULL;
2965         }
2966 }
2967
2968 /*********************************************************************
2969  *
2970  *  This routine executes in interrupt context. It replenishes
2971  *  the mbufs in the descriptor and sends data which has been
2972  *  dma'ed into host memory to upper layer.
2973  *
2974  *  We loop at most count times if count is > 0, or until done if
2975  *  count < 0.
2976  *
2977  *********************************************************************/
2978 static void
2979 em_rxeof(struct adapter *adapter, int count)
2980 {
2981         struct ifnet *ifp;
2982         struct mbuf *mp;
2983         uint8_t accept_frame = 0;
2984         uint8_t eop = 0;
2985         uint16_t len, desc_len, prev_len_adj;
2986         int i;
2987 #ifdef ETHER_INPUT_CHAIN
2988         struct mbuf_chain chain[MAXCPU];
2989 #endif
2990
2991         /* Pointer to the receive descriptor being examined. */
2992         struct em_rx_desc *current_desc;
2993
2994         ifp = &adapter->interface_data.ac_if;
2995         i = adapter->next_rx_desc_to_check;
2996         current_desc = &adapter->rx_desc_base[i];
2997
2998         bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
2999                         BUS_DMASYNC_POSTREAD);
3000
3001         if (!(current_desc->status & E1000_RXD_STAT_DD))
3002                 return;
3003
3004 #ifdef ETHER_INPUT_CHAIN
3005         ether_input_chain_init(chain);
3006 #endif
3007
3008         while ((current_desc->status & E1000_RXD_STAT_DD) && count != 0) {
3009                 logif(pkt_receive);
3010                 mp = adapter->rx_buffer_area[i].m_head;
3011                 bus_dmamap_sync(adapter->rxtag, adapter->rx_buffer_area[i].map,
3012                                 BUS_DMASYNC_POSTREAD);
3013                 bus_dmamap_unload(adapter->rxtag,
3014                                   adapter->rx_buffer_area[i].map);
3015
3016                 accept_frame = 1;
3017                 prev_len_adj = 0;
3018                 desc_len = le16toh(current_desc->length);
3019                 if (current_desc->status & E1000_RXD_STAT_EOP) {
3020                         count--;
3021                         eop = 1;
3022                         if (desc_len < ETHER_CRC_LEN) {
3023                                 len = 0;
3024                                 prev_len_adj = ETHER_CRC_LEN - desc_len;
3025                         } else {
3026                                 len = desc_len - ETHER_CRC_LEN;
3027                         }
3028                 } else {
3029                         eop = 0;
3030                         len = desc_len;
3031                 }
3032
3033                 if (current_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK) {
3034                         uint8_t last_byte;
3035                         uint32_t pkt_len = desc_len;
3036
3037                         if (adapter->fmp != NULL)
3038                                 pkt_len += adapter->fmp->m_pkthdr.len; 
3039
3040                         last_byte = *(mtod(mp, caddr_t) + desc_len - 1);
3041
3042                         if (TBI_ACCEPT(&adapter->hw, current_desc->status, 
3043                                        current_desc->errors, 
3044                                        pkt_len, last_byte)) {
3045                                 em_tbi_adjust_stats(&adapter->hw, 
3046                                                     &adapter->stats, 
3047                                                     pkt_len, 
3048                                                     adapter->hw.mac_addr);
3049                                 if (len > 0)
3050                                         len--;
3051                         } else {
3052                                 accept_frame = 0;
3053                         }
3054                 }
3055
3056                 if (accept_frame) {
3057                         if (em_get_buf(i, adapter, NULL, MB_DONTWAIT) == ENOBUFS) {
3058                                 adapter->dropped_pkts++;
3059                                 em_get_buf(i, adapter, mp, MB_DONTWAIT);
3060                                 if (adapter->fmp != NULL)
3061                                         m_freem(adapter->fmp);
3062                                 adapter->fmp = NULL;
3063                                 adapter->lmp = NULL;
3064                                 goto skip;
3065                         }
3066
3067                         /* Assign correct length to the current fragment */
3068                         mp->m_len = len;
3069
3070                         if (adapter->fmp == NULL) {
3071                                 mp->m_pkthdr.len = len;
3072                                 adapter->fmp = mp;       /* Store the first mbuf */
3073                                 adapter->lmp = mp;
3074                         } else {
3075                                 /* Chain mbuf's together */
3076                                 /* 
3077                                  * Adjust length of previous mbuf in chain if
3078                                  * we received less than 4 bytes in the last
3079                                  * descriptor.
3080                                  */
3081                                 if (prev_len_adj > 0) {
3082                                         adapter->lmp->m_len -= prev_len_adj;
3083                                         adapter->fmp->m_pkthdr.len -= prev_len_adj;
3084                                 }
3085                                 adapter->lmp->m_next = mp;
3086                                 adapter->lmp = adapter->lmp->m_next;
3087                                 adapter->fmp->m_pkthdr.len += len;
3088                         }
3089
3090                         if (eop) {
3091                                 adapter->fmp->m_pkthdr.rcvif = ifp;
3092                                 ifp->if_ipackets++;
3093
3094                                 em_receive_checksum(adapter, current_desc,
3095                                                     adapter->fmp);
3096                                 if (current_desc->status & E1000_RXD_STAT_VP) {
3097                                         adapter->fmp->m_flags |= M_VLANTAG;
3098                                         adapter->fmp->m_pkthdr.ether_vlantag =
3099                                                 (current_desc->special &
3100                                                  E1000_RXD_SPC_VLAN_MASK);
3101                                 }
3102 #ifdef ETHER_INPUT_CHAIN
3103 #ifdef ETHER_INPUT2
3104                                 ether_input_chain2(ifp, adapter->fmp, chain);
3105 #else
3106                                 ether_input_chain(ifp, adapter->fmp, chain);
3107 #endif
3108 #else
3109                                 ifp->if_input(ifp, adapter->fmp);
3110 #endif
3111                                 adapter->fmp = NULL;
3112                                 adapter->lmp = NULL;
3113                         }
3114                 } else {
3115                         adapter->dropped_pkts++;
3116                         em_get_buf(i, adapter, mp, MB_DONTWAIT);
3117                         if (adapter->fmp != NULL) 
3118                                 m_freem(adapter->fmp);
3119                         adapter->fmp = NULL;
3120                         adapter->lmp = NULL;
3121                 }
3122
3123 skip:
3124                 /* Zero out the receive descriptors status. */
3125                 current_desc->status = 0;
3126
3127                 /* Advance our pointers to the next descriptor. */
3128                 if (++i == adapter->num_rx_desc) {
3129                         i = 0;
3130                         current_desc = adapter->rx_desc_base;
3131                 } else {
3132                         current_desc++;
3133                 }
3134         }
3135
3136 #ifdef ETHER_INPUT_CHAIN
3137         ether_input_dispatch(chain);
3138 #endif
3139
3140         bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
3141                         BUS_DMASYNC_PREWRITE);
3142
3143         adapter->next_rx_desc_to_check = i;
3144
3145         /* Advance the E1000's Receive Queue #0  "Tail Pointer". */
3146         if (--i < 0)
3147                 i = adapter->num_rx_desc - 1;
3148
3149         E1000_WRITE_REG(&adapter->hw, RDT, i);
3150 }
3151
3152 /*********************************************************************
3153  *
3154  *  Verify that the hardware indicated that the checksum is valid.
3155  *  Inform the stack about the status of checksum so that stack
3156  *  doesn't spend time verifying the checksum.
3157  *
3158  *********************************************************************/
3159 static void
3160 em_receive_checksum(struct adapter *adapter,
3161                     struct em_rx_desc *rx_desc,
3162                     struct mbuf *mp)
3163 {
3164         /* 82543 or newer only */
3165         if ((adapter->hw.mac_type < em_82543) ||
3166             /* Ignore Checksum bit is set */
3167             (rx_desc->status & E1000_RXD_STAT_IXSM)) {
3168                 mp->m_pkthdr.csum_flags = 0;
3169                 return;
3170         }
3171
3172         if (rx_desc->status & E1000_RXD_STAT_IPCS) {
3173                 /* Did it pass? */
3174                 if (!(rx_desc->errors & E1000_RXD_ERR_IPE)) {
3175                         /* IP Checksum Good */
3176                         mp->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
3177                         mp->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3178                 } else {
3179                         mp->m_pkthdr.csum_flags = 0;
3180                 }
3181         }
3182
3183         if (rx_desc->status & E1000_RXD_STAT_TCPCS) {
3184                 /* Did it pass? */
3185                 if (!(rx_desc->errors & E1000_RXD_ERR_TCPE)) {
3186                         mp->m_pkthdr.csum_flags |=
3187                         (CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
3188                          CSUM_FRAG_NOT_CHECKED);
3189                         mp->m_pkthdr.csum_data = htons(0xffff);
3190                 }
3191         }
3192 }
3193
3194
3195 static void 
3196 em_enable_vlans(struct adapter *adapter)
3197 {
3198         uint32_t ctrl;
3199
3200         E1000_WRITE_REG(&adapter->hw, VET, ETHERTYPE_VLAN);
3201
3202         ctrl = E1000_READ_REG(&adapter->hw, CTRL);
3203         ctrl |= E1000_CTRL_VME;
3204         E1000_WRITE_REG(&adapter->hw, CTRL, ctrl);
3205 }
3206
3207 static void
3208 em_disable_vlans(struct adapter *adapter)
3209 {
3210         uint32_t ctrl;
3211
3212         ctrl = E1000_READ_REG(&adapter->hw, CTRL);
3213         ctrl &= ~E1000_CTRL_VME;
3214         E1000_WRITE_REG(&adapter->hw, CTRL, ctrl);
3215 }
3216
3217 /*
3218  * note: we must call bus_enable_intr() prior to enabling the hardware
3219  * interrupt and bus_disable_intr() after disabling the hardware interrupt
3220  * in order to avoid handler execution races from scheduled interrupt
3221  * threads.
3222  */
3223 static void
3224 em_enable_intr(struct adapter *adapter)
3225 {
3226         struct ifnet *ifp = &adapter->interface_data.ac_if;
3227         
3228         if ((ifp->if_flags & IFF_POLLING) == 0) {
3229                 lwkt_serialize_handler_enable(ifp->if_serializer);
3230                 E1000_WRITE_REG(&adapter->hw, IMS, (IMS_ENABLE_MASK));
3231         }
3232 }
3233
3234 static void
3235 em_disable_intr(struct adapter *adapter)
3236 {
3237         /*
3238          * The first version of 82542 had an errata where when link was forced
3239          * it would stay up even up even if the cable was disconnected.
3240          * Sequence errors were used to detect the disconnect and then the
3241          * driver would unforce the link.  This code in the in the ISR.  For
3242          * this to work correctly the Sequence error interrupt had to be
3243          * enabled all the time.
3244          */
3245         if (adapter->hw.mac_type == em_82542_rev2_0) {
3246                 E1000_WRITE_REG(&adapter->hw, IMC,
3247                                 (0xffffffff & ~E1000_IMC_RXSEQ));
3248         } else {
3249                 E1000_WRITE_REG(&adapter->hw, IMC, 0xffffffff);
3250         }
3251
3252         lwkt_serialize_handler_disable(adapter->interface_data.ac_if.if_serializer);
3253 }
3254
3255 static int
3256 em_is_valid_ether_addr(uint8_t *addr)
3257 {
3258         static const char zero_addr[6] = { 0, 0, 0, 0, 0, 0 };
3259
3260         if ((addr[0] & 1) || !bcmp(addr, zero_addr, ETHER_ADDR_LEN))
3261                 return (FALSE);
3262         else
3263                 return (TRUE);
3264 }
3265
3266 void
3267 em_write_pci_cfg(struct em_hw *hw, uint32_t reg, uint16_t *value)
3268 {
3269         pci_write_config(((struct em_osdep *)hw->back)->dev, reg, *value, 2);
3270 }
3271
3272 void
3273 em_read_pci_cfg(struct em_hw *hw, uint32_t reg, uint16_t *value)
3274 {
3275         *value = pci_read_config(((struct em_osdep *)hw->back)->dev, reg, 2);
3276 }
3277
3278 void
3279 em_pci_set_mwi(struct em_hw *hw)
3280 {
3281         pci_write_config(((struct em_osdep *)hw->back)->dev, PCIR_COMMAND,
3282                          (hw->pci_cmd_word | CMD_MEM_WRT_INVALIDATE), 2);
3283 }
3284
3285 void
3286 em_pci_clear_mwi(struct em_hw *hw)
3287 {
3288         pci_write_config(((struct em_osdep *)hw->back)->dev, PCIR_COMMAND,
3289                          (hw->pci_cmd_word & ~CMD_MEM_WRT_INVALIDATE), 2);
3290 }
3291
3292 uint32_t
3293 em_io_read(struct em_hw *hw, unsigned long port)
3294 {
3295         struct em_osdep *io = hw->back;
3296
3297         return bus_space_read_4(io->io_bus_space_tag,
3298                                 io->io_bus_space_handle, port);
3299 }
3300
3301 void
3302 em_io_write(struct em_hw *hw, unsigned long port, uint32_t value)
3303 {
3304         struct em_osdep *io = hw->back;
3305
3306         bus_space_write_4(io->io_bus_space_tag,
3307                           io->io_bus_space_handle, port, value);
3308 }
3309
3310 /*
3311  * We may eventually really do this, but its unnecessary 
3312  * for now so we just return unsupported.
3313  */
3314 int32_t
3315 em_read_pcie_cap_reg(struct em_hw *hw, uint32_t reg, uint16_t *value)
3316 {
3317         return (0);
3318 }
3319
3320
3321 /*********************************************************************
3322  * 82544 Coexistence issue workaround.
3323  *    There are 2 issues.
3324  *      1. Transmit Hang issue.
3325  *    To detect this issue, following equation can be used...
3326  *          SIZE[3:0] + ADDR[2:0] = SUM[3:0].
3327  *          If SUM[3:0] is in between 1 to 4, we will have this issue.
3328  *
3329  *      2. DAC issue.
3330  *    To detect this issue, following equation can be used...
3331  *          SIZE[3:0] + ADDR[2:0] = SUM[3:0].
3332  *          If SUM[3:0] is in between 9 to c, we will have this issue.
3333  *
3334  *
3335  *    WORKAROUND:
3336  *          Make sure we do not have ending address as 1,2,3,4(Hang) or
3337  *          9,a,b,c (DAC)
3338  *
3339 *************************************************************************/
3340 static uint32_t
3341 em_fill_descriptors(bus_addr_t address, uint32_t length, PDESC_ARRAY desc_array)
3342 {
3343         /* Since issue is sensitive to length and address.*/
3344         /* Let us first check the address...*/
3345         uint32_t safe_terminator;
3346         if (length <= 4) {
3347                 desc_array->descriptor[0].address = address;
3348                 desc_array->descriptor[0].length = length;
3349                 desc_array->elements = 1;
3350                 return (desc_array->elements);
3351         }
3352         safe_terminator = (uint32_t)((((uint32_t)address & 0x7) + (length & 0xF)) & 0xF);
3353         /* if it does not fall between 0x1 to 0x4 and 0x9 to 0xC then return */ 
3354         if (safe_terminator == 0 ||
3355             (safe_terminator > 4 && safe_terminator < 9) || 
3356             (safe_terminator > 0xC && safe_terminator <= 0xF)) {
3357                 desc_array->descriptor[0].address = address;
3358                 desc_array->descriptor[0].length = length;
3359                 desc_array->elements = 1;
3360                 return (desc_array->elements);
3361         }
3362
3363         desc_array->descriptor[0].address = address;
3364         desc_array->descriptor[0].length = length - 4;
3365         desc_array->descriptor[1].address = address + (length - 4);
3366         desc_array->descriptor[1].length = 4;
3367         desc_array->elements = 2;
3368         return (desc_array->elements);
3369 }
3370
3371 /**********************************************************************
3372  *
3373  *  Update the board statistics counters.
3374  *
3375  **********************************************************************/
3376 static void
3377 em_update_stats_counters(struct adapter *adapter)
3378 {
3379         struct ifnet   *ifp;
3380
3381         if (adapter->hw.media_type == em_media_type_copper ||
3382             (E1000_READ_REG(&adapter->hw, STATUS) & E1000_STATUS_LU)) {
3383                 adapter->stats.symerrs += E1000_READ_REG(&adapter->hw, SYMERRS);
3384                 adapter->stats.sec += E1000_READ_REG(&adapter->hw, SEC);
3385         }
3386         adapter->stats.crcerrs += E1000_READ_REG(&adapter->hw, CRCERRS);
3387         adapter->stats.mpc += E1000_READ_REG(&adapter->hw, MPC);
3388         adapter->stats.scc += E1000_READ_REG(&adapter->hw, SCC);
3389         adapter->stats.ecol += E1000_READ_REG(&adapter->hw, ECOL);
3390
3391         adapter->stats.mcc += E1000_READ_REG(&adapter->hw, MCC);
3392         adapter->stats.latecol += E1000_READ_REG(&adapter->hw, LATECOL);
3393         adapter->stats.colc += E1000_READ_REG(&adapter->hw, COLC);
3394         adapter->stats.dc += E1000_READ_REG(&adapter->hw, DC);
3395         adapter->stats.rlec += E1000_READ_REG(&adapter->hw, RLEC);
3396         adapter->stats.xonrxc += E1000_READ_REG(&adapter->hw, XONRXC);
3397         adapter->stats.xontxc += E1000_READ_REG(&adapter->hw, XONTXC);
3398         adapter->stats.xoffrxc += E1000_READ_REG(&adapter->hw, XOFFRXC);
3399         adapter->stats.xofftxc += E1000_READ_REG(&adapter->hw, XOFFTXC);
3400         adapter->stats.fcruc += E1000_READ_REG(&adapter->hw, FCRUC);
3401         adapter->stats.prc64 += E1000_READ_REG(&adapter->hw, PRC64);
3402         adapter->stats.prc127 += E1000_READ_REG(&adapter->hw, PRC127);
3403         adapter->stats.prc255 += E1000_READ_REG(&adapter->hw, PRC255);
3404         adapter->stats.prc511 += E1000_READ_REG(&adapter->hw, PRC511);
3405         adapter->stats.prc1023 += E1000_READ_REG(&adapter->hw, PRC1023);
3406         adapter->stats.prc1522 += E1000_READ_REG(&adapter->hw, PRC1522);
3407         adapter->stats.gprc += E1000_READ_REG(&adapter->hw, GPRC);
3408         adapter->stats.bprc += E1000_READ_REG(&adapter->hw, BPRC);
3409         adapter->stats.mprc += E1000_READ_REG(&adapter->hw, MPRC);
3410         adapter->stats.gptc += E1000_READ_REG(&adapter->hw, GPTC);
3411
3412         /* For the 64-bit byte counters the low dword must be read first. */
3413         /* Both registers clear on the read of the high dword */
3414
3415         adapter->stats.gorcl += E1000_READ_REG(&adapter->hw, GORCL);
3416         adapter->stats.gorch += E1000_READ_REG(&adapter->hw, GORCH);
3417         adapter->stats.gotcl += E1000_READ_REG(&adapter->hw, GOTCL);
3418         adapter->stats.gotch += E1000_READ_REG(&adapter->hw, GOTCH);
3419
3420         adapter->stats.rnbc += E1000_READ_REG(&adapter->hw, RNBC);
3421         adapter->stats.ruc += E1000_READ_REG(&adapter->hw, RUC);
3422         adapter->stats.rfc += E1000_READ_REG(&adapter->hw, RFC);
3423         adapter->stats.roc += E1000_READ_REG(&adapter->hw, ROC);
3424         adapter->stats.rjc += E1000_READ_REG(&adapter->hw, RJC);
3425
3426         adapter->stats.torl += E1000_READ_REG(&adapter->hw, TORL);
3427         adapter->stats.torh += E1000_READ_REG(&adapter->hw, TORH);
3428         adapter->stats.totl += E1000_READ_REG(&adapter->hw, TOTL);
3429         adapter->stats.toth += E1000_READ_REG(&adapter->hw, TOTH);
3430
3431         adapter->stats.tpr += E1000_READ_REG(&adapter->hw, TPR);
3432         adapter->stats.tpt += E1000_READ_REG(&adapter->hw, TPT);
3433         adapter->stats.ptc64 += E1000_READ_REG(&adapter->hw, PTC64);
3434         adapter->stats.ptc127 += E1000_READ_REG(&adapter->hw, PTC127);
3435         adapter->stats.ptc255 += E1000_READ_REG(&adapter->hw, PTC255);
3436         adapter->stats.ptc511 += E1000_READ_REG(&adapter->hw, PTC511);
3437         adapter->stats.ptc1023 += E1000_READ_REG(&adapter->hw, PTC1023);
3438         adapter->stats.ptc1522 += E1000_READ_REG(&adapter->hw, PTC1522);
3439         adapter->stats.mptc += E1000_READ_REG(&adapter->hw, MPTC);
3440         adapter->stats.bptc += E1000_READ_REG(&adapter->hw, BPTC);
3441
3442         if (adapter->hw.mac_type >= em_82543) {
3443                 adapter->stats.algnerrc += 
3444                     E1000_READ_REG(&adapter->hw, ALGNERRC);
3445                 adapter->stats.rxerrc += 
3446                     E1000_READ_REG(&adapter->hw, RXERRC);
3447                 adapter->stats.tncrs += 
3448                     E1000_READ_REG(&adapter->hw, TNCRS);
3449                 adapter->stats.cexterr += 
3450                     E1000_READ_REG(&adapter->hw, CEXTERR);
3451                 adapter->stats.tsctc += 
3452                     E1000_READ_REG(&adapter->hw, TSCTC);
3453                 adapter->stats.tsctfc += 
3454                     E1000_READ_REG(&adapter->hw, TSCTFC);
3455         }
3456         ifp = &adapter->interface_data.ac_if;
3457
3458         /* Fill out the OS statistics structure */
3459         ifp->if_collisions = adapter->stats.colc;
3460
3461         /* Rx Errors */
3462         ifp->if_ierrors =
3463                 adapter->dropped_pkts +
3464                 adapter->stats.rxerrc +
3465                 adapter->stats.crcerrs +
3466                 adapter->stats.algnerrc +
3467                 adapter->stats.ruc + adapter->stats.roc +
3468                 adapter->stats.mpc + adapter->stats.cexterr +
3469                 adapter->rx_overruns;
3470
3471         /* Tx Errors */
3472         ifp->if_oerrors = adapter->stats.ecol + adapter->stats.latecol +
3473                           adapter->watchdog_timeouts;
3474 }
3475
3476
3477 /**********************************************************************
3478  *
3479  *  This routine is called only when em_display_debug_stats is enabled.
3480  *  This routine provides a way to take a look at important statistics
3481  *  maintained by the driver and hardware.
3482  *
3483  **********************************************************************/
3484 static void
3485 em_print_debug_info(struct adapter *adapter)
3486 {
3487         device_t dev= adapter->dev;
3488         uint8_t *hw_addr = adapter->hw.hw_addr;
3489
3490         device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
3491         device_printf(dev, "CTRL  = 0x%x RCTL = 0x%x\n",
3492                       E1000_READ_REG(&adapter->hw, CTRL),
3493                       E1000_READ_REG(&adapter->hw, RCTL));
3494         device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk\n",
3495                       ((E1000_READ_REG(&adapter->hw, PBA) & 0xffff0000) >> 16),
3496                       (E1000_READ_REG(&adapter->hw, PBA) & 0xffff));
3497         device_printf(dev, "Flow control watermarks high = %d low = %d\n",
3498                       adapter->hw.fc_high_water, adapter->hw.fc_low_water);
3499         device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
3500                       E1000_READ_REG(&adapter->hw, TIDV),
3501                       E1000_READ_REG(&adapter->hw, TADV));
3502         device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
3503                       E1000_READ_REG(&adapter->hw, RDTR),
3504                       E1000_READ_REG(&adapter->hw, RADV));
3505         device_printf(dev, "fifo workaround = %lld, fifo_reset_count = %lld\n",
3506                       (long long)adapter->tx_fifo_wrk_cnt,
3507                       (long long)adapter->tx_fifo_reset_cnt);
3508         device_printf(dev, "hw tdh = %d, hw tdt = %d\n",
3509                       E1000_READ_REG(&adapter->hw, TDH),
3510                       E1000_READ_REG(&adapter->hw, TDT));
3511         device_printf(dev, "Num Tx descriptors avail = %d\n",
3512                       adapter->num_tx_desc_avail);
3513         device_printf(dev, "Tx Descriptors not avail1 = %ld\n",
3514                       adapter->no_tx_desc_avail1);
3515         device_printf(dev, "Tx Descriptors not avail2 = %ld\n",
3516                       adapter->no_tx_desc_avail2);
3517         device_printf(dev, "Std mbuf failed = %ld\n",
3518                       adapter->mbuf_alloc_failed);
3519         device_printf(dev, "Std mbuf cluster failed = %ld\n",
3520                       adapter->mbuf_cluster_failed);
3521         device_printf(dev, "Driver dropped packets = %ld\n",
3522                       adapter->dropped_pkts);
3523 }
3524
3525 static void
3526 em_print_hw_stats(struct adapter *adapter)
3527 {
3528         device_t dev= adapter->dev;
3529
3530         device_printf(dev, "Excessive collisions = %lld\n",
3531                       (long long)adapter->stats.ecol);
3532         device_printf(dev, "Symbol errors = %lld\n",
3533                       (long long)adapter->stats.symerrs);
3534         device_printf(dev, "Sequence errors = %lld\n",
3535                       (long long)adapter->stats.sec);
3536         device_printf(dev, "Defer count = %lld\n",
3537                       (long long)adapter->stats.dc);
3538
3539         device_printf(dev, "Missed Packets = %lld\n",
3540                       (long long)adapter->stats.mpc);
3541         device_printf(dev, "Receive No Buffers = %lld\n",
3542                       (long long)adapter->stats.rnbc);
3543         /* RLEC is inaccurate on some hardware, calculate our own. */
3544         device_printf(dev, "Receive Length errors = %lld\n",
3545                       (long long)adapter->stats.roc +
3546                       (long long)adapter->stats.ruc);
3547         device_printf(dev, "Receive errors = %lld\n",
3548                       (long long)adapter->stats.rxerrc);
3549         device_printf(dev, "Crc errors = %lld\n",
3550                       (long long)adapter->stats.crcerrs);
3551         device_printf(dev, "Alignment errors = %lld\n",
3552                       (long long)adapter->stats.algnerrc);
3553         device_printf(dev, "Carrier extension errors = %lld\n",
3554                       (long long)adapter->stats.cexterr);
3555         device_printf(dev, "RX overruns = %lu\n", adapter->rx_overruns);
3556         device_printf(dev, "Watchdog timeouts = %lu\n",
3557                       adapter->watchdog_timeouts);
3558
3559         device_printf(dev, "XON Rcvd = %lld\n",
3560                       (long long)adapter->stats.xonrxc);
3561         device_printf(dev, "XON Xmtd = %lld\n",
3562                       (long long)adapter->stats.xontxc);
3563         device_printf(dev, "XOFF Rcvd = %lld\n",
3564                       (long long)adapter->stats.xoffrxc);
3565         device_printf(dev, "XOFF Xmtd = %lld\n",
3566                       (long long)adapter->stats.xofftxc);
3567
3568         device_printf(dev, "Good Packets Rcvd = %lld\n",
3569                       (long long)adapter->stats.gprc);
3570         device_printf(dev, "Good Packets Xmtd = %lld\n",
3571                       (long long)adapter->stats.gptc);
3572 }
3573
3574 static int
3575 em_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
3576 {
3577         int error;
3578         int result;
3579         struct adapter *adapter;
3580
3581         result = -1;
3582         error = sysctl_handle_int(oidp, &result, 0, req);
3583
3584         if (error || !req->newptr)
3585                 return (error);
3586
3587         if (result == 1) {
3588                 adapter = (struct adapter *)arg1;
3589                 em_print_debug_info(adapter);
3590         }
3591
3592         return (error);
3593 }
3594
3595 static int
3596 em_sysctl_stats(SYSCTL_HANDLER_ARGS)
3597 {
3598         int error;
3599         int result;
3600         struct adapter *adapter;
3601
3602         result = -1;
3603         error = sysctl_handle_int(oidp, &result, 0, req);
3604
3605         if (error || !req->newptr)
3606                 return (error);
3607
3608         if (result == 1) {
3609                 adapter = (struct adapter *)arg1;
3610                 em_print_hw_stats(adapter);
3611         }
3612
3613         return (error);
3614 }
3615
3616 static int
3617 em_sysctl_int_delay(SYSCTL_HANDLER_ARGS)
3618 {
3619         struct em_int_delay_info *info;
3620         struct adapter *adapter;
3621         uint32_t regval;
3622         int error;
3623         int usecs;
3624         int ticks;
3625
3626         info = (struct em_int_delay_info *)arg1;
3627         adapter = info->adapter;
3628         usecs = info->value;
3629         error = sysctl_handle_int(oidp, &usecs, 0, req);
3630         if (error != 0 || req->newptr == NULL)
3631                 return (error);
3632         if (usecs < 0 || usecs > E1000_TICKS_TO_USECS(65535))
3633                 return (EINVAL);
3634         info->value = usecs;
3635         ticks = E1000_USECS_TO_TICKS(usecs);
3636
3637         lwkt_serialize_enter(adapter->interface_data.ac_if.if_serializer);
3638         regval = E1000_READ_OFFSET(&adapter->hw, info->offset);
3639         regval = (regval & ~0xffff) | (ticks & 0xffff);
3640         /* Handle a few special cases. */
3641         switch (info->offset) {
3642         case E1000_RDTR:
3643         case E1000_82542_RDTR:
3644                 regval |= E1000_RDT_FPDB;
3645                 break;
3646         case E1000_TIDV:
3647         case E1000_82542_TIDV:
3648                 if (ticks == 0) {
3649                         adapter->txd_cmd &= ~E1000_TXD_CMD_IDE;
3650                         /* Don't write 0 into the TIDV register. */
3651                         regval++;
3652                 } else
3653                         adapter->txd_cmd |= E1000_TXD_CMD_IDE;
3654                 break;
3655         }
3656         E1000_WRITE_OFFSET(&adapter->hw, info->offset, regval);
3657         lwkt_serialize_exit(adapter->interface_data.ac_if.if_serializer);
3658         return (0);
3659 }
3660
3661 static void
3662 em_add_int_delay_sysctl(struct adapter *adapter, const char *name,
3663                         const char *description, struct em_int_delay_info *info,
3664                         int offset, int value)
3665 {
3666         info->adapter = adapter;
3667         info->offset = offset;
3668         info->value = value;
3669         SYSCTL_ADD_PROC(&adapter->sysctl_ctx,
3670                         SYSCTL_CHILDREN(adapter->sysctl_tree),
3671                         OID_AUTO, name, CTLTYPE_INT|CTLFLAG_RW,
3672                         info, 0, em_sysctl_int_delay, "I", description);
3673 }
3674
3675 static int
3676 em_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
3677 {
3678         struct adapter *adapter = (void *)arg1;
3679         int error;
3680         int throttle;
3681
3682         throttle = em_int_throttle_ceil;
3683         error = sysctl_handle_int(oidp, &throttle, 0, req);
3684         if (error || req->newptr == NULL)
3685                 return error;
3686         if (throttle < 0 || throttle > 1000000000 / 256)
3687                 return EINVAL;
3688         if (throttle) {
3689                 /*
3690                  * Set the interrupt throttling rate in 256ns increments,
3691                  * recalculate sysctl value assignment to get exact frequency.
3692                  */
3693                 throttle = 1000000000 / 256 / throttle;
3694                 lwkt_serialize_enter(adapter->interface_data.ac_if.if_serializer);
3695                 em_int_throttle_ceil = 1000000000 / 256 / throttle;
3696                 E1000_WRITE_REG(&adapter->hw, ITR, throttle);
3697                 lwkt_serialize_exit(adapter->interface_data.ac_if.if_serializer);
3698         } else {
3699                 lwkt_serialize_enter(adapter->interface_data.ac_if.if_serializer);
3700                 em_int_throttle_ceil = 0;
3701                 E1000_WRITE_REG(&adapter->hw, ITR, 0);
3702                 lwkt_serialize_exit(adapter->interface_data.ac_if.if_serializer);
3703         }
3704         device_printf(adapter->dev, "Interrupt moderation set to %d/sec\n", 
3705                         em_int_throttle_ceil);
3706         return 0;
3707 }