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