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