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