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