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