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