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