Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / dev / netif / emx / if_emx.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 #include "opt_polling.h"
68 #include "opt_serializer.h"
69
70 #include <sys/param.h>
71 #include <sys/bus.h>
72 #include <sys/endian.h>
73 #include <sys/interrupt.h>
74 #include <sys/kernel.h>
75 #include <sys/ktr.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/proc.h>
79 #include <sys/rman.h>
80 #include <sys/serialize.h>
81 #include <sys/socket.h>
82 #include <sys/sockio.h>
83 #include <sys/sysctl.h>
84 #include <sys/systm.h>
85
86 #include <net/bpf.h>
87 #include <net/ethernet.h>
88 #include <net/if.h>
89 #include <net/if_arp.h>
90 #include <net/if_dl.h>
91 #include <net/if_media.h>
92 #include <net/ifq_var.h>
93 #include <net/vlan/if_vlan_var.h>
94 #include <net/vlan/if_vlan_ether.h>
95
96 #include <netinet/in_systm.h>
97 #include <netinet/in.h>
98 #include <netinet/ip.h>
99 #include <netinet/tcp.h>
100 #include <netinet/udp.h>
101
102 #include <bus/pci/pcivar.h>
103 #include <bus/pci/pcireg.h>
104
105 #include <dev/netif/ig_hal/e1000_api.h>
106 #include <dev/netif/ig_hal/e1000_82571.h>
107 #include <dev/netif/emx/if_emx.h>
108
109 #define EMX_NAME        "Intel(R) PRO/1000 "
110
111 #define EMX_DEVICE(id)  \
112         { EMX_VENDOR_ID, E1000_DEV_ID_##id, EMX_NAME #id }
113 #define EMX_DEVICE_NULL { 0, 0, NULL }
114
115 static const struct emx_device {
116         uint16_t        vid;
117         uint16_t        did;
118         const char      *desc;
119 } emx_devices[] = {
120         EMX_DEVICE(82571EB_COPPER),
121         EMX_DEVICE(82571EB_FIBER),
122         EMX_DEVICE(82571EB_SERDES),
123         EMX_DEVICE(82571EB_SERDES_DUAL),
124         EMX_DEVICE(82571EB_SERDES_QUAD),
125         EMX_DEVICE(82571EB_QUAD_COPPER),
126         EMX_DEVICE(82571EB_QUAD_COPPER_LP),
127         EMX_DEVICE(82571EB_QUAD_FIBER),
128         EMX_DEVICE(82571PT_QUAD_COPPER),
129
130         EMX_DEVICE(82572EI_COPPER),
131         EMX_DEVICE(82572EI_FIBER),
132         EMX_DEVICE(82572EI_SERDES),
133         EMX_DEVICE(82572EI),
134
135         EMX_DEVICE(82573E),
136         EMX_DEVICE(82573E_IAMT),
137         EMX_DEVICE(82573L),
138
139         EMX_DEVICE(80003ES2LAN_COPPER_SPT),
140         EMX_DEVICE(80003ES2LAN_SERDES_SPT),
141         EMX_DEVICE(80003ES2LAN_COPPER_DPT),
142         EMX_DEVICE(80003ES2LAN_SERDES_DPT),
143
144         EMX_DEVICE(82574L),
145
146         /* required last entry */
147         EMX_DEVICE_NULL
148 };
149
150 static int      emx_probe(device_t);
151 static int      emx_attach(device_t);
152 static int      emx_detach(device_t);
153 static int      emx_shutdown(device_t);
154 static int      emx_suspend(device_t);
155 static int      emx_resume(device_t);
156
157 static void     emx_init(void *);
158 static void     emx_stop(struct emx_softc *);
159 static int      emx_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
160 static void     emx_start(struct ifnet *);
161 #ifdef DEVICE_POLLING
162 static void     emx_poll(struct ifnet *, enum poll_cmd, int);
163 #endif
164 static void     emx_watchdog(struct ifnet *);
165 static void     emx_media_status(struct ifnet *, struct ifmediareq *);
166 static int      emx_media_change(struct ifnet *);
167 static void     emx_timer(void *);
168
169 static void     emx_intr(void *);
170 static void     emx_rxeof(struct emx_softc *, int);
171 static void     emx_txeof(struct emx_softc *);
172 static void     emx_tx_collect(struct emx_softc *);
173 static void     emx_tx_purge(struct emx_softc *);
174 static void     emx_enable_intr(struct emx_softc *);
175 static void     emx_disable_intr(struct emx_softc *);
176
177 static int      emx_dma_malloc(struct emx_softc *, bus_size_t,
178                     struct emx_dma *);
179 static void     emx_dma_free(struct emx_softc *, struct emx_dma *);
180 static void     emx_init_tx_ring(struct emx_softc *);
181 static int      emx_init_rx_ring(struct emx_softc *);
182 static int      emx_create_tx_ring(struct emx_softc *);
183 static int      emx_create_rx_ring(struct emx_softc *);
184 static void     emx_destroy_tx_ring(struct emx_softc *, int);
185 static void     emx_destroy_rx_ring(struct emx_softc *, int);
186 static int      emx_newbuf(struct emx_softc *, int, int);
187 static int      emx_encap(struct emx_softc *, struct mbuf **);
188 static void     emx_rxcsum(struct emx_softc *, struct e1000_rx_desc *,
189                     struct mbuf *);
190 static int      emx_txcsum_pullup(struct emx_softc *, struct mbuf **);
191 static int      emx_txcsum(struct emx_softc *, struct mbuf *,
192                     uint32_t *, uint32_t *);
193
194 static int      emx_is_valid_eaddr(const uint8_t *);
195 static int      emx_hw_init(struct emx_softc *);
196 static void     emx_setup_ifp(struct emx_softc *);
197 static void     emx_init_tx_unit(struct emx_softc *);
198 static void     emx_init_rx_unit(struct emx_softc *);
199 static void     emx_update_stats(struct emx_softc *);
200 static void     emx_set_promisc(struct emx_softc *);
201 static void     emx_disable_promisc(struct emx_softc *);
202 static void     emx_set_multi(struct emx_softc *);
203 static void     emx_update_link_status(struct emx_softc *);
204 static void     emx_smartspeed(struct emx_softc *);
205
206 static void     emx_print_debug_info(struct emx_softc *);
207 static void     emx_print_nvm_info(struct emx_softc *);
208 static void     emx_print_hw_stats(struct emx_softc *);
209
210 static int      emx_sysctl_stats(SYSCTL_HANDLER_ARGS);
211 static int      emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS);
212 static int      emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS);
213 static int      emx_sysctl_int_tx_nsegs(SYSCTL_HANDLER_ARGS);
214 static void     emx_add_sysctl(struct emx_softc *);
215
216 /* Management and WOL Support */
217 static void     emx_get_mgmt(struct emx_softc *);
218 static void     emx_rel_mgmt(struct emx_softc *);
219 static void     emx_get_hw_control(struct emx_softc *);
220 static void     emx_rel_hw_control(struct emx_softc *);
221 static void     emx_enable_wol(device_t);
222
223 static device_method_t emx_methods[] = {
224         /* Device interface */
225         DEVMETHOD(device_probe,         emx_probe),
226         DEVMETHOD(device_attach,        emx_attach),
227         DEVMETHOD(device_detach,        emx_detach),
228         DEVMETHOD(device_shutdown,      emx_shutdown),
229         DEVMETHOD(device_suspend,       emx_suspend),
230         DEVMETHOD(device_resume,        emx_resume),
231         { 0, 0 }
232 };
233
234 static driver_t emx_driver = {
235         "emx",
236         emx_methods,
237         sizeof(struct emx_softc),
238 };
239
240 static devclass_t emx_devclass;
241
242 DECLARE_DUMMY_MODULE(if_emx);
243 MODULE_DEPEND(emx, ig_hal, 1, 1, 1);
244 DRIVER_MODULE(if_emx, pci, emx_driver, emx_devclass, 0, 0);
245
246 /*
247  * Tunables
248  */
249 static int      emx_int_throttle_ceil = EMX_DEFAULT_ITR;
250 static int      emx_rxd = EMX_DEFAULT_RXD;
251 static int      emx_txd = EMX_DEFAULT_TXD;
252 static int      emx_smart_pwr_down = FALSE;
253
254 /* Controls whether promiscuous also shows bad packets */
255 static int      emx_debug_sbp = FALSE;
256
257 static int      emx_82573_workaround = TRUE;
258
259 TUNABLE_INT("hw.emx.int_throttle_ceil", &emx_int_throttle_ceil);
260 TUNABLE_INT("hw.emx.rxd", &emx_rxd);
261 TUNABLE_INT("hw.emx.txd", &emx_txd);
262 TUNABLE_INT("hw.emx.smart_pwr_down", &emx_smart_pwr_down);
263 TUNABLE_INT("hw.emx.sbp", &emx_debug_sbp);
264 TUNABLE_INT("hw.emx.82573_workaround", &emx_82573_workaround);
265
266 /* Global used in WOL setup with multiport cards */
267 static int      emx_global_quad_port_a = 0;
268
269 /* Set this to one to display debug statistics */
270 static int      emx_display_debug_stats = 0;
271
272 #if !defined(KTR_IF_EMX)
273 #define KTR_IF_EMX      KTR_ALL
274 #endif
275 KTR_INFO_MASTER(if_emx);
276 KTR_INFO(KTR_IF_EMX, if_emx, intr_beg, 0, "intr begin", 0);
277 KTR_INFO(KTR_IF_EMX, if_emx, intr_end, 1, "intr end", 0);
278 KTR_INFO(KTR_IF_EMX, if_emx, pkt_receive, 4, "rx packet", 0);
279 KTR_INFO(KTR_IF_EMX, if_emx, pkt_txqueue, 5, "tx packet", 0);
280 KTR_INFO(KTR_IF_EMX, if_emx, pkt_txclean, 6, "tx clean", 0);
281 #define logif(name)     KTR_LOG(if_emx_ ## name)
282
283 static int
284 emx_probe(device_t dev)
285 {
286         const struct emx_device *d;
287         uint16_t vid, did;
288
289         vid = pci_get_vendor(dev);
290         did = pci_get_device(dev);
291
292         for (d = emx_devices; d->desc != NULL; ++d) {
293                 if (vid == d->vid && did == d->did) {
294                         device_set_desc(dev, d->desc);
295                         device_set_async_attach(dev, TRUE);
296                         return 0;
297                 }
298         }
299         return ENXIO;
300 }
301
302 static int
303 emx_attach(device_t dev)
304 {
305         struct emx_softc *sc = device_get_softc(dev);
306         struct ifnet *ifp = &sc->arpcom.ac_if;
307         int tsize, rsize;
308         int error = 0;
309         uint16_t eeprom_data, device_id;
310
311         callout_init(&sc->timer);
312
313         sc->dev = sc->osdep.dev = dev;
314
315         /*
316          * Determine hardware and mac type
317          */
318         sc->hw.vendor_id = pci_get_vendor(dev);
319         sc->hw.device_id = pci_get_device(dev);
320         sc->hw.revision_id = pci_get_revid(dev);
321         sc->hw.subsystem_vendor_id = pci_get_subvendor(dev);
322         sc->hw.subsystem_device_id = pci_get_subdevice(dev);
323
324         if (e1000_set_mac_type(&sc->hw))
325                 return ENXIO;
326
327         /* Enable bus mastering */
328         pci_enable_busmaster(dev);
329
330         /*
331          * Allocate IO memory
332          */
333         sc->memory_rid = EMX_BAR_MEM;
334         sc->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
335                                             &sc->memory_rid, RF_ACTIVE);
336         if (sc->memory == NULL) {
337                 device_printf(dev, "Unable to allocate bus resource: memory\n");
338                 error = ENXIO;
339                 goto fail;
340         }
341         sc->osdep.mem_bus_space_tag = rman_get_bustag(sc->memory);
342         sc->osdep.mem_bus_space_handle = rman_get_bushandle(sc->memory);
343
344         /* XXX This is quite goofy, it is not actually used */
345         sc->hw.hw_addr = (uint8_t *)&sc->osdep.mem_bus_space_handle;
346
347         /*
348          * Allocate interrupt
349          */
350         sc->intr_rid = 0;
351         sc->intr_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->intr_rid,
352                                               RF_SHAREABLE | RF_ACTIVE);
353         if (sc->intr_res == NULL) {
354                 device_printf(dev, "Unable to allocate bus resource: "
355                     "interrupt\n");
356                 error = ENXIO;
357                 goto fail;
358         }
359
360         /* Save PCI command register for Shared Code */
361         sc->hw.bus.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
362         sc->hw.back = &sc->osdep;
363
364         /* Do Shared Code initialization */
365         if (e1000_setup_init_funcs(&sc->hw, TRUE)) {
366                 device_printf(dev, "Setup of Shared code failed\n");
367                 error = ENXIO;
368                 goto fail;
369         }
370         e1000_get_bus_info(&sc->hw);
371
372         /*
373          * Validate number of transmit and receive descriptors.  It
374          * must not exceed hardware maximum, and must be multiple
375          * of E1000_DBA_ALIGN.
376          */
377         if ((emx_txd * sizeof(struct e1000_tx_desc)) % EMX_DBA_ALIGN != 0 ||
378             emx_txd > EMX_MAX_TXD || emx_txd < EMX_MIN_TXD) {
379                 device_printf(dev, "Using %d TX descriptors instead of %d!\n",
380                     EMX_DEFAULT_TXD, emx_txd);
381                 sc->num_tx_desc = EMX_DEFAULT_TXD;
382         } else {
383                 sc->num_tx_desc = emx_txd;
384         }
385         if ((emx_rxd * sizeof(struct e1000_rx_desc)) % EMX_DBA_ALIGN != 0 ||
386             emx_rxd > EMX_MAX_RXD || emx_rxd < EMX_MIN_RXD) {
387                 device_printf(dev, "Using %d RX descriptors instead of %d!\n",
388                     EMX_DEFAULT_RXD, emx_rxd);
389                 sc->num_rx_desc = EMX_DEFAULT_RXD;
390         } else {
391                 sc->num_rx_desc = emx_rxd;
392         }
393
394         sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
395         sc->hw.phy.autoneg_wait_to_complete = FALSE;
396         sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
397         sc->rx_buffer_len = MCLBYTES;
398
399         /*
400          * Interrupt throttle rate
401          */
402         if (emx_int_throttle_ceil == 0) {
403                 sc->int_throttle_ceil = 0;
404         } else {
405                 int throttle = emx_int_throttle_ceil;
406
407                 if (throttle < 0)
408                         throttle = EMX_DEFAULT_ITR;
409
410                 /* Recalculate the tunable value to get the exact frequency. */
411                 throttle = 1000000000 / 256 / throttle;
412
413                 /* Upper 16bits of ITR is reserved and should be zero */
414                 if (throttle & 0xffff0000)
415                         throttle = 1000000000 / 256 / EMX_DEFAULT_ITR;
416
417                 sc->int_throttle_ceil = 1000000000 / 256 / throttle;
418         }
419
420         e1000_init_script_state_82541(&sc->hw, TRUE);
421         e1000_set_tbi_compatibility_82543(&sc->hw, TRUE);
422
423         /* Copper options */
424         if (sc->hw.phy.media_type == e1000_media_type_copper) {
425                 sc->hw.phy.mdix = EMX_AUTO_ALL_MODES;
426                 sc->hw.phy.disable_polarity_correction = FALSE;
427                 sc->hw.phy.ms_type = EMX_MASTER_SLAVE;
428         }
429
430         /* Set the frame limits assuming standard ethernet sized frames. */
431         sc->max_frame_size = ETHERMTU + ETHER_HDR_LEN + ETHER_CRC_LEN;
432         sc->min_frame_size = ETHER_MIN_LEN;
433
434         /* This controls when hardware reports transmit completion status. */
435         sc->hw.mac.report_tx_early = 1;
436
437         /*
438          * Create top level busdma tag
439          */
440         error = bus_dma_tag_create(NULL, 1, 0,
441                         BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
442                         NULL, NULL,
443                         BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
444                         0, &sc->parent_dtag);
445         if (error) {
446                 device_printf(dev, "could not create top level DMA tag\n");
447                 goto fail;
448         }
449
450         /*
451          * Allocate Transmit Descriptor ring
452          */
453         tsize = roundup2(sc->num_tx_desc * sizeof(struct e1000_tx_desc),
454                          EMX_DBA_ALIGN);
455         error = emx_dma_malloc(sc, tsize, &sc->txdma);
456         if (error) {
457                 device_printf(dev, "Unable to allocate tx_desc memory\n");
458                 goto fail;
459         }
460         sc->tx_desc_base = sc->txdma.dma_vaddr;
461
462         /*
463          * Allocate Receive Descriptor ring
464          */
465         rsize = roundup2(sc->num_rx_desc * sizeof(struct e1000_rx_desc),
466                          EMX_DBA_ALIGN);
467         error = emx_dma_malloc(sc, rsize, &sc->rxdma);
468         if (error) {
469                 device_printf(dev, "Unable to allocate rx_desc memory\n");
470                 goto fail;
471         }
472         sc->rx_desc_base = sc->rxdma.dma_vaddr;
473
474         /* Make sure we have a good EEPROM before we read from it */
475         if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
476                 /*
477                  * Some PCI-E parts fail the first check due to
478                  * the link being in sleep state, call it again,
479                  * if it fails a second time its a real issue.
480                  */
481                 if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
482                         device_printf(dev,
483                             "The EEPROM Checksum Is Not Valid\n");
484                         error = EIO;
485                         goto fail;
486                 }
487         }
488
489         /* Initialize the hardware */
490         error = emx_hw_init(sc);
491         if (error) {
492                 device_printf(dev, "Unable to initialize the hardware\n");
493                 goto fail;
494         }
495
496         /* Copy the permanent MAC address out of the EEPROM */
497         if (e1000_read_mac_addr(&sc->hw) < 0) {
498                 device_printf(dev, "EEPROM read error while reading MAC"
499                     " address\n");
500                 error = EIO;
501                 goto fail;
502         }
503         if (!emx_is_valid_eaddr(sc->hw.mac.addr)) {
504                 device_printf(dev, "Invalid MAC address\n");
505                 error = EIO;
506                 goto fail;
507         }
508
509         /* Allocate transmit descriptors and buffers */
510         error = emx_create_tx_ring(sc);
511         if (error) {
512                 device_printf(dev, "Could not setup transmit structures\n");
513                 goto fail;
514         }
515
516         /* Allocate receive descriptors and buffers */
517         error = emx_create_rx_ring(sc);
518         if (error) {
519                 device_printf(dev, "Could not setup receive structures\n");
520                 goto fail;
521         }
522
523         /* Manually turn off all interrupts */
524         E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
525
526         /* Setup OS specific network interface */
527         emx_setup_ifp(sc);
528
529         /* Add sysctl tree, must after emx_setup_ifp() */
530         emx_add_sysctl(sc);
531
532         /* Initialize statistics */
533         emx_update_stats(sc);
534
535         sc->hw.mac.get_link_status = 1;
536         emx_update_link_status(sc);
537
538         /* Indicate SOL/IDER usage */
539         if (e1000_check_reset_block(&sc->hw)) {
540                 device_printf(dev,
541                     "PHY reset is blocked due to SOL/IDER session.\n");
542         }
543
544         /* Determine if we have to control management hardware */
545         sc->has_manage = e1000_enable_mng_pass_thru(&sc->hw);
546
547         /*
548          * Setup Wake-on-Lan
549          */
550         switch (sc->hw.mac.type) {
551         case e1000_82571:
552         case e1000_80003es2lan:
553                 if (sc->hw.bus.func == 1) {
554                         e1000_read_nvm(&sc->hw,
555                             NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
556                 } else {
557                         e1000_read_nvm(&sc->hw,
558                             NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
559                 }
560                 eeprom_data &= EMX_EEPROM_APME;
561                 break;
562
563         default:
564                 /* APME bit in EEPROM is mapped to WUC.APME */
565                 eeprom_data =
566                     E1000_READ_REG(&sc->hw, E1000_WUC) & E1000_WUC_APME;
567                 break;
568         }
569         if (eeprom_data)
570                 sc->wol = E1000_WUFC_MAG;
571         /*
572          * We have the eeprom settings, now apply the special cases
573          * where the eeprom may be wrong or the board won't support
574          * wake on lan on a particular port
575          */
576         device_id = pci_get_device(dev);
577         switch (device_id) {
578         case E1000_DEV_ID_82571EB_FIBER:
579                 /*
580                  * Wake events only supported on port A for dual fiber
581                  * regardless of eeprom setting
582                  */
583                 if (E1000_READ_REG(&sc->hw, E1000_STATUS) &
584                     E1000_STATUS_FUNC_1)
585                         sc->wol = 0;
586                 break;
587
588         case E1000_DEV_ID_82571EB_QUAD_COPPER:
589         case E1000_DEV_ID_82571EB_QUAD_FIBER:
590         case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
591                 /* if quad port sc, disable WoL on all but port A */
592                 if (emx_global_quad_port_a != 0)
593                         sc->wol = 0;
594                 /* Reset for multiple quad port adapters */
595                 if (++emx_global_quad_port_a == 4)
596                         emx_global_quad_port_a = 0;
597                 break;
598         }
599
600         /* XXX disable wol */
601         sc->wol = 0;
602
603         sc->spare_tx_desc = EMX_TX_SPARE;
604
605         /*
606          * Keep following relationship between spare_tx_desc, oact_tx_desc
607          * and tx_int_nsegs:
608          * (spare_tx_desc + EMX_TX_RESERVED) <=
609          * oact_tx_desc <= EMX_TX_OACTIVE_MAX <= tx_int_nsegs
610          */
611         sc->oact_tx_desc = sc->num_tx_desc / 8;
612         if (sc->oact_tx_desc > EMX_TX_OACTIVE_MAX)
613                 sc->oact_tx_desc = EMX_TX_OACTIVE_MAX;
614         if (sc->oact_tx_desc < sc->spare_tx_desc + EMX_TX_RESERVED)
615                 sc->oact_tx_desc = sc->spare_tx_desc + EMX_TX_RESERVED;
616
617         sc->tx_int_nsegs = sc->num_tx_desc / 16;
618         if (sc->tx_int_nsegs < sc->oact_tx_desc)
619                 sc->tx_int_nsegs = sc->oact_tx_desc;
620
621         error = bus_setup_intr(dev, sc->intr_res, INTR_MPSAFE, emx_intr, sc,
622                                &sc->intr_tag, ifp->if_serializer);
623         if (error) {
624                 device_printf(dev, "Failed to register interrupt handler");
625                 ether_ifdetach(&sc->arpcom.ac_if);
626                 goto fail;
627         }
628
629         ifp->if_cpuid = ithread_cpuid(rman_get_start(sc->intr_res));
630         KKASSERT(ifp->if_cpuid >= 0 && ifp->if_cpuid < ncpus);
631         return (0);
632 fail:
633         emx_detach(dev);
634         return (error);
635 }
636
637 static int
638 emx_detach(device_t dev)
639 {
640         struct emx_softc *sc = device_get_softc(dev);
641
642         if (device_is_attached(dev)) {
643                 struct ifnet *ifp = &sc->arpcom.ac_if;
644
645                 lwkt_serialize_enter(ifp->if_serializer);
646
647                 emx_stop(sc);
648
649                 e1000_phy_hw_reset(&sc->hw);
650
651                 emx_rel_mgmt(sc);
652
653                 if (sc->hw.mac.type == e1000_82573 &&
654                     e1000_check_mng_mode(&sc->hw))
655                         emx_rel_hw_control(sc);
656
657                 if (sc->wol) {
658                         E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
659                         E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
660                         emx_enable_wol(dev);
661                 }
662
663                 bus_teardown_intr(dev, sc->intr_res, sc->intr_tag);
664
665                 lwkt_serialize_exit(ifp->if_serializer);
666
667                 ether_ifdetach(ifp);
668         }
669         bus_generic_detach(dev);
670
671         if (sc->intr_res != NULL) {
672                 bus_release_resource(dev, SYS_RES_IRQ, sc->intr_rid,
673                                      sc->intr_res);
674         }
675
676         if (sc->memory != NULL) {
677                 bus_release_resource(dev, SYS_RES_MEMORY, sc->memory_rid,
678                                      sc->memory);
679         }
680
681         emx_destroy_tx_ring(sc, sc->num_tx_desc);
682         emx_destroy_rx_ring(sc, sc->num_rx_desc);
683
684         /* Free Transmit Descriptor ring */
685         if (sc->tx_desc_base)
686                 emx_dma_free(sc, &sc->txdma);
687
688         /* Free Receive Descriptor ring */
689         if (sc->rx_desc_base)
690                 emx_dma_free(sc, &sc->rxdma);
691
692         /* Free top level busdma tag */
693         if (sc->parent_dtag != NULL)
694                 bus_dma_tag_destroy(sc->parent_dtag);
695
696         /* Free sysctl tree */
697         if (sc->sysctl_tree != NULL)
698                 sysctl_ctx_free(&sc->sysctl_ctx);
699
700         return (0);
701 }
702
703 static int
704 emx_shutdown(device_t dev)
705 {
706         return emx_suspend(dev);
707 }
708
709 static int
710 emx_suspend(device_t dev)
711 {
712         struct emx_softc *sc = device_get_softc(dev);
713         struct ifnet *ifp = &sc->arpcom.ac_if;
714
715         lwkt_serialize_enter(ifp->if_serializer);
716
717         emx_stop(sc);
718
719         emx_rel_mgmt(sc);
720
721         if (sc->hw.mac.type == e1000_82573 &&
722             e1000_check_mng_mode(&sc->hw))
723                 emx_rel_hw_control(sc);
724
725         if (sc->wol) {
726                 E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
727                 E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
728                 emx_enable_wol(dev);
729         }
730
731         lwkt_serialize_exit(ifp->if_serializer);
732
733         return bus_generic_suspend(dev);
734 }
735
736 static int
737 emx_resume(device_t dev)
738 {
739         struct emx_softc *sc = device_get_softc(dev);
740         struct ifnet *ifp = &sc->arpcom.ac_if;
741
742         lwkt_serialize_enter(ifp->if_serializer);
743
744         emx_init(sc);
745         emx_get_mgmt(sc);
746         if_devstart(ifp);
747
748         lwkt_serialize_exit(ifp->if_serializer);
749
750         return bus_generic_resume(dev);
751 }
752
753 static void
754 emx_start(struct ifnet *ifp)
755 {
756         struct emx_softc *sc = ifp->if_softc;
757         struct mbuf *m_head;
758
759         ASSERT_SERIALIZED(ifp->if_serializer);
760
761         if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
762                 return;
763
764         if (!sc->link_active) {
765                 ifq_purge(&ifp->if_snd);
766                 return;
767         }
768
769         while (!ifq_is_empty(&ifp->if_snd)) {
770                 /* Now do we at least have a minimal? */
771                 if (EMX_IS_OACTIVE(sc)) {
772                         emx_tx_collect(sc);
773                         if (EMX_IS_OACTIVE(sc)) {
774                                 ifp->if_flags |= IFF_OACTIVE;
775                                 sc->no_tx_desc_avail1++;
776                                 break;
777                         }
778                 }
779
780                 logif(pkt_txqueue);
781                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
782                 if (m_head == NULL)
783                         break;
784
785                 if (emx_encap(sc, &m_head)) {
786                         ifp->if_oerrors++;
787                         emx_tx_collect(sc);
788                         continue;
789                 }
790
791                 /* Send a copy of the frame to the BPF listener */
792                 ETHER_BPF_MTAP(ifp, m_head);
793
794                 /* Set timeout in case hardware has problems transmitting. */
795                 ifp->if_timer = EMX_TX_TIMEOUT;
796         }
797 }
798
799 static int
800 emx_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
801 {
802         struct emx_softc *sc = ifp->if_softc;
803         struct ifreq *ifr = (struct ifreq *)data;
804         uint16_t eeprom_data = 0;
805         int max_frame_size, mask, reinit;
806         int error = 0;
807
808         ASSERT_SERIALIZED(ifp->if_serializer);
809
810         switch (command) {
811         case SIOCSIFMTU:
812                 switch (sc->hw.mac.type) {
813                 case e1000_82573:
814                         /*
815                          * 82573 only supports jumbo frames
816                          * if ASPM is disabled.
817                          */
818                         e1000_read_nvm(&sc->hw, NVM_INIT_3GIO_3, 1,
819                                        &eeprom_data);
820                         if (eeprom_data & NVM_WORD1A_ASPM_MASK) {
821                                 max_frame_size = ETHER_MAX_LEN;
822                                 break;
823                         }
824                         /* FALL THROUGH */
825
826                 /* Limit Jumbo Frame size */
827                 case e1000_82571:
828                 case e1000_82572:
829                 case e1000_82574:
830                 case e1000_80003es2lan:
831                         max_frame_size = 9234;
832                         break;
833
834                 default:
835                         max_frame_size = MAX_JUMBO_FRAME_SIZE;
836                         break;
837                 }
838                 if (ifr->ifr_mtu > max_frame_size - ETHER_HDR_LEN -
839                     ETHER_CRC_LEN) {
840                         error = EINVAL;
841                         break;
842                 }
843
844                 ifp->if_mtu = ifr->ifr_mtu;
845                 sc->max_frame_size = ifp->if_mtu + ETHER_HDR_LEN +
846                                      ETHER_CRC_LEN;
847
848                 if (ifp->if_flags & IFF_RUNNING)
849                         emx_init(sc);
850                 break;
851
852         case SIOCSIFFLAGS:
853                 if (ifp->if_flags & IFF_UP) {
854                         if ((ifp->if_flags & IFF_RUNNING)) {
855                                 if ((ifp->if_flags ^ sc->if_flags) &
856                                     (IFF_PROMISC | IFF_ALLMULTI)) {
857                                         emx_disable_promisc(sc);
858                                         emx_set_promisc(sc);
859                                 }
860                         } else {
861                                 emx_init(sc);
862                         }
863                 } else if (ifp->if_flags & IFF_RUNNING) {
864                         emx_stop(sc);
865                 }
866                 sc->if_flags = ifp->if_flags;
867                 break;
868
869         case SIOCADDMULTI:
870         case SIOCDELMULTI:
871                 if (ifp->if_flags & IFF_RUNNING) {
872                         emx_disable_intr(sc);
873                         emx_set_multi(sc);
874 #ifdef DEVICE_POLLING
875                         if (!(ifp->if_flags & IFF_POLLING))
876 #endif
877                                 emx_enable_intr(sc);
878                 }
879                 break;
880
881         case SIOCSIFMEDIA:
882                 /* Check SOL/IDER usage */
883                 if (e1000_check_reset_block(&sc->hw)) {
884                         device_printf(sc->dev, "Media change is"
885                             " blocked due to SOL/IDER session.\n");
886                         break;
887                 }
888                 /* FALL THROUGH */
889
890         case SIOCGIFMEDIA:
891                 error = ifmedia_ioctl(ifp, ifr, &sc->media, command);
892                 break;
893
894         case SIOCSIFCAP:
895                 reinit = 0;
896                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
897                 if (mask & IFCAP_HWCSUM) {
898                         ifp->if_capenable ^= (mask & IFCAP_HWCSUM);
899                         reinit = 1;
900                 }
901                 if (mask & IFCAP_VLAN_HWTAGGING) {
902                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
903                         reinit = 1;
904                 }
905                 if (reinit && (ifp->if_flags & IFF_RUNNING))
906                         emx_init(sc);
907                 break;
908
909         default:
910                 error = ether_ioctl(ifp, command, data);
911                 break;
912         }
913         return (error);
914 }
915
916 static void
917 emx_watchdog(struct ifnet *ifp)
918 {
919         struct emx_softc *sc = ifp->if_softc;
920
921         ASSERT_SERIALIZED(ifp->if_serializer);
922
923         /*
924          * The timer is set to 5 every time start queues a packet.
925          * Then txeof keeps resetting it as long as it cleans at
926          * least one descriptor.
927          * Finally, anytime all descriptors are clean the timer is
928          * set to 0.
929          */
930
931         if (E1000_READ_REG(&sc->hw, E1000_TDT(0)) ==
932             E1000_READ_REG(&sc->hw, E1000_TDH(0))) {
933                 /*
934                  * If we reach here, all TX jobs are completed and
935                  * the TX engine should have been idled for some time.
936                  * We don't need to call if_devstart() here.
937                  */
938                 ifp->if_flags &= ~IFF_OACTIVE;
939                 ifp->if_timer = 0;
940                 return;
941         }
942
943         /*
944          * If we are in this routine because of pause frames, then
945          * don't reset the hardware.
946          */
947         if (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_TXOFF) {
948                 ifp->if_timer = EMX_TX_TIMEOUT;
949                 return;
950         }
951
952         if (e1000_check_for_link(&sc->hw) == 0)
953                 if_printf(ifp, "watchdog timeout -- resetting\n");
954
955         ifp->if_oerrors++;
956         sc->watchdog_events++;
957
958         emx_init(sc);
959
960         if (!ifq_is_empty(&ifp->if_snd))
961                 if_devstart(ifp);
962 }
963
964 static void
965 emx_init(void *xsc)
966 {
967         struct emx_softc *sc = xsc;
968         struct ifnet *ifp = &sc->arpcom.ac_if;
969         device_t dev = sc->dev;
970         uint32_t pba;
971
972         ASSERT_SERIALIZED(ifp->if_serializer);
973
974         emx_stop(sc);
975
976         /*
977          * Packet Buffer Allocation (PBA)
978          * Writing PBA sets the receive portion of the buffer
979          * the remainder is used for the transmit buffer.
980          */
981         switch (sc->hw.mac.type) {
982         /* Total Packet Buffer on these is 48K */
983         case e1000_82571:
984         case e1000_82572:
985         case e1000_80003es2lan:
986                 pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
987                 break;
988
989         case e1000_82573: /* 82573: Total Packet Buffer is 32K */
990                 pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
991                 break;
992
993         case e1000_82574:
994                 pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
995                 break;
996
997         default:
998                 /* Devices before 82547 had a Packet Buffer of 64K.   */
999                 if (sc->max_frame_size > 8192)
1000                         pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
1001                 else
1002                         pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
1003         }
1004         E1000_WRITE_REG(&sc->hw, E1000_PBA, pba);
1005
1006         /* Get the latest mac address, User can use a LAA */
1007         bcopy(IF_LLADDR(ifp), sc->hw.mac.addr, ETHER_ADDR_LEN);
1008
1009         /* Put the address into the Receive Address Array */
1010         e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1011
1012         /*
1013          * With the 82571 sc, RAR[0] may be overwritten
1014          * when the other port is reset, we make a duplicate
1015          * in RAR[14] for that eventuality, this assures
1016          * the interface continues to function.
1017          */
1018         if (sc->hw.mac.type == e1000_82571) {
1019                 e1000_set_laa_state_82571(&sc->hw, TRUE);
1020                 e1000_rar_set(&sc->hw, sc->hw.mac.addr,
1021                     E1000_RAR_ENTRIES - 1);
1022         }
1023
1024         /* Initialize the hardware */
1025         if (emx_hw_init(sc)) {
1026                 device_printf(dev, "Unable to initialize the hardware\n");
1027                 /* XXX emx_stop()? */
1028                 return;
1029         }
1030         emx_update_link_status(sc);
1031
1032         /* Setup VLAN support, basic and offload if available */
1033         E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1034
1035         if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1036                 uint32_t ctrl;
1037
1038                 ctrl = E1000_READ_REG(&sc->hw, E1000_CTRL);
1039                 ctrl |= E1000_CTRL_VME;
1040                 E1000_WRITE_REG(&sc->hw, E1000_CTRL, ctrl);
1041         }
1042
1043         /* Set hardware offload abilities */
1044         if (ifp->if_capenable & IFCAP_TXCSUM)
1045                 ifp->if_hwassist = EMX_CSUM_FEATURES;
1046         else
1047                 ifp->if_hwassist = 0;
1048
1049         /* Configure for OS presence */
1050         emx_get_mgmt(sc);
1051
1052         /* Prepare transmit descriptors and buffers */
1053         emx_init_tx_ring(sc);
1054         emx_init_tx_unit(sc);
1055
1056         /* Setup Multicast table */
1057         emx_set_multi(sc);
1058
1059         /* Prepare receive descriptors and buffers */
1060         if (emx_init_rx_ring(sc)) {
1061                 device_printf(dev, "Could not setup receive structures\n");
1062                 emx_stop(sc);
1063                 return;
1064         }
1065         emx_init_rx_unit(sc);
1066
1067         /* Don't lose promiscuous settings */
1068         emx_set_promisc(sc);
1069
1070         ifp->if_flags |= IFF_RUNNING;
1071         ifp->if_flags &= ~IFF_OACTIVE;
1072
1073         callout_reset(&sc->timer, hz, emx_timer, sc);
1074         e1000_clear_hw_cntrs_base_generic(&sc->hw);
1075
1076         /* MSI/X configuration for 82574 */
1077         if (sc->hw.mac.type == e1000_82574) {
1078                 int tmp;
1079
1080                 tmp = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
1081                 tmp |= E1000_CTRL_EXT_PBA_CLR;
1082                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT, tmp);
1083                 /*
1084                  * Set the IVAR - interrupt vector routing.
1085                  * Each nibble represents a vector, high bit
1086                  * is enable, other 3 bits are the MSIX table
1087                  * entry, we map RXQ0 to 0, TXQ0 to 1, and
1088                  * Link (other) to 2, hence the magic number.
1089                  */
1090                 E1000_WRITE_REG(&sc->hw, E1000_IVAR, 0x800A0908);
1091         }
1092
1093 #ifdef DEVICE_POLLING
1094         /*
1095          * Only enable interrupts if we are not polling, make sure
1096          * they are off otherwise.
1097          */
1098         if (ifp->if_flags & IFF_POLLING)
1099                 emx_disable_intr(sc);
1100         else
1101 #endif /* DEVICE_POLLING */
1102                 emx_enable_intr(sc);
1103
1104         /* Don't reset the phy next time init gets called */
1105         sc->hw.phy.reset_disable = TRUE;
1106 }
1107
1108 #ifdef DEVICE_POLLING
1109
1110 static void
1111 emx_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
1112 {
1113         struct emx_softc *sc = ifp->if_softc;
1114         uint32_t reg_icr;
1115
1116         ASSERT_SERIALIZED(ifp->if_serializer);
1117
1118         switch (cmd) {
1119         case POLL_REGISTER:
1120                 emx_disable_intr(sc);
1121                 break;
1122
1123         case POLL_DEREGISTER:
1124                 emx_enable_intr(sc);
1125                 break;
1126
1127         case POLL_AND_CHECK_STATUS:
1128                 reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
1129                 if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1130                         callout_stop(&sc->timer);
1131                         sc->hw.mac.get_link_status = 1;
1132                         emx_update_link_status(sc);
1133                         callout_reset(&sc->timer, hz, emx_timer, sc);
1134                 }
1135                 /* FALL THROUGH */
1136         case POLL_ONLY:
1137                 if (ifp->if_flags & IFF_RUNNING) {
1138                         emx_rxeof(sc, count);
1139                         emx_txeof(sc);
1140
1141                         if (!ifq_is_empty(&ifp->if_snd))
1142                                 if_devstart(ifp);
1143                 }
1144                 break;
1145         }
1146 }
1147
1148 #endif /* DEVICE_POLLING */
1149
1150 static void
1151 emx_intr(void *xsc)
1152 {
1153         struct emx_softc *sc = xsc;
1154         struct ifnet *ifp = &sc->arpcom.ac_if;
1155         uint32_t reg_icr;
1156
1157         logif(intr_beg);
1158         ASSERT_SERIALIZED(ifp->if_serializer);
1159
1160         reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
1161
1162         if ((reg_icr & E1000_ICR_INT_ASSERTED) == 0) {
1163                 logif(intr_end);
1164                 return;
1165         }
1166
1167         /*
1168          * XXX: some laptops trigger several spurious interrupts
1169          * on em(4) when in the resume cycle. The ICR register
1170          * reports all-ones value in this case. Processing such
1171          * interrupts would lead to a freeze. I don't know why.
1172          */
1173         if (reg_icr == 0xffffffff) {
1174                 logif(intr_end);
1175                 return;
1176         }
1177
1178         if (ifp->if_flags & IFF_RUNNING) {
1179                 if (reg_icr &
1180                     (E1000_IMS_RXT0 | E1000_IMS_RXDMT0 | E1000_ICR_RXO))
1181                         emx_rxeof(sc, -1);
1182                 if (reg_icr & E1000_IMS_TXDW) {
1183                         emx_txeof(sc);
1184                         if (!ifq_is_empty(&ifp->if_snd))
1185                                 if_devstart(ifp);
1186                 }
1187         }
1188
1189         /* Link status change */
1190         if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1191                 callout_stop(&sc->timer);
1192                 sc->hw.mac.get_link_status = 1;
1193                 emx_update_link_status(sc);
1194
1195                 /* Deal with TX cruft when link lost */
1196                 emx_tx_purge(sc);
1197
1198                 callout_reset(&sc->timer, hz, emx_timer, sc);
1199         }
1200
1201         if (reg_icr & E1000_ICR_RXO)
1202                 sc->rx_overruns++;
1203
1204         logif(intr_end);
1205 }
1206
1207 static void
1208 emx_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1209 {
1210         struct emx_softc *sc = ifp->if_softc;
1211
1212         ASSERT_SERIALIZED(ifp->if_serializer);
1213
1214         emx_update_link_status(sc);
1215
1216         ifmr->ifm_status = IFM_AVALID;
1217         ifmr->ifm_active = IFM_ETHER;
1218
1219         if (!sc->link_active)
1220                 return;
1221
1222         ifmr->ifm_status |= IFM_ACTIVE;
1223
1224         if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1225             sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1226                 ifmr->ifm_active |= IFM_1000_SX | IFM_FDX;
1227         } else {
1228                 switch (sc->link_speed) {
1229                 case 10:
1230                         ifmr->ifm_active |= IFM_10_T;
1231                         break;
1232                 case 100:
1233                         ifmr->ifm_active |= IFM_100_TX;
1234                         break;
1235
1236                 case 1000:
1237                         ifmr->ifm_active |= IFM_1000_T;
1238                         break;
1239                 }
1240                 if (sc->link_duplex == FULL_DUPLEX)
1241                         ifmr->ifm_active |= IFM_FDX;
1242                 else
1243                         ifmr->ifm_active |= IFM_HDX;
1244         }
1245 }
1246
1247 static int
1248 emx_media_change(struct ifnet *ifp)
1249 {
1250         struct emx_softc *sc = ifp->if_softc;
1251         struct ifmedia *ifm = &sc->media;
1252
1253         ASSERT_SERIALIZED(ifp->if_serializer);
1254
1255         if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1256                 return (EINVAL);
1257
1258         switch (IFM_SUBTYPE(ifm->ifm_media)) {
1259         case IFM_AUTO:
1260                 sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1261                 sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
1262                 break;
1263
1264         case IFM_1000_LX:
1265         case IFM_1000_SX:
1266         case IFM_1000_T:
1267                 sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1268                 sc->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1269                 break;
1270
1271         case IFM_100_TX:
1272                 sc->hw.mac.autoneg = FALSE;
1273                 sc->hw.phy.autoneg_advertised = 0;
1274                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1275                         sc->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1276                 else
1277                         sc->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1278                 break;
1279
1280         case IFM_10_T:
1281                 sc->hw.mac.autoneg = FALSE;
1282                 sc->hw.phy.autoneg_advertised = 0;
1283                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1284                         sc->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1285                 else
1286                         sc->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1287                 break;
1288
1289         default:
1290                 if_printf(ifp, "Unsupported media type\n");
1291                 break;
1292         }
1293
1294         /*
1295          * As the speed/duplex settings my have changed we need to
1296          * reset the PHY.
1297          */
1298         sc->hw.phy.reset_disable = FALSE;
1299
1300         emx_init(sc);
1301
1302         return (0);
1303 }
1304
1305 static int
1306 emx_encap(struct emx_softc *sc, struct mbuf **m_headp)
1307 {
1308         bus_dma_segment_t segs[EMX_MAX_SCATTER];
1309         bus_dmamap_t map;
1310         struct emx_buf *tx_buffer, *tx_buffer_mapped;
1311         struct e1000_tx_desc *ctxd = NULL;
1312         struct mbuf *m_head = *m_headp;
1313         uint32_t txd_upper, txd_lower, cmd = 0;
1314         int maxsegs, nsegs, i, j, first, last = 0, error;
1315
1316         if (__predict_false(m_head->m_len < EMX_TXCSUM_MINHL) &&
1317             (m_head->m_flags & EMX_CSUM_FEATURES)) {
1318                 /*
1319                  * Make sure that ethernet header and ip.ip_hl are in
1320                  * contiguous memory, since if TXCSUM is enabled, later
1321                  * TX context descriptor's setup need to access ip.ip_hl.
1322                  */
1323                 error = emx_txcsum_pullup(sc, m_headp);
1324                 if (error) {
1325                         KKASSERT(*m_headp == NULL);
1326                         return error;
1327                 }
1328                 m_head = *m_headp;
1329         }
1330
1331         txd_upper = txd_lower = 0;
1332
1333         /*
1334          * Capture the first descriptor index, this descriptor
1335          * will have the index of the EOP which is the only one
1336          * that now gets a DONE bit writeback.
1337          */
1338         first = sc->next_avail_tx_desc;
1339         tx_buffer = &sc->tx_buffer_area[first];
1340         tx_buffer_mapped = tx_buffer;
1341         map = tx_buffer->map;
1342
1343         maxsegs = sc->num_tx_desc_avail - EMX_TX_RESERVED;
1344         KASSERT(maxsegs >= sc->spare_tx_desc, ("not enough spare TX desc\n"));
1345         if (maxsegs > EMX_MAX_SCATTER)
1346                 maxsegs = EMX_MAX_SCATTER;
1347
1348         error = bus_dmamap_load_mbuf_defrag(sc->txtag, map, m_headp,
1349                         segs, maxsegs, &nsegs, BUS_DMA_NOWAIT);
1350         if (error) {
1351                 if (error == ENOBUFS)
1352                         sc->mbuf_alloc_failed++;
1353                 else
1354                         sc->no_tx_dma_setup++;
1355
1356                 m_freem(*m_headp);
1357                 *m_headp = NULL;
1358                 return error;
1359         }
1360         bus_dmamap_sync(sc->txtag, map, BUS_DMASYNC_PREWRITE);
1361
1362         m_head = *m_headp;
1363         sc->tx_nsegs += nsegs;
1364
1365         if (m_head->m_pkthdr.csum_flags & EMX_CSUM_FEATURES) {
1366                 /* TX csum offloading will consume one TX desc */
1367                 sc->tx_nsegs += emx_txcsum(sc, m_head, &txd_upper, &txd_lower);
1368         }
1369         i = sc->next_avail_tx_desc;
1370
1371         /* Set up our transmit descriptors */
1372         for (j = 0; j < nsegs; j++) {
1373                 tx_buffer = &sc->tx_buffer_area[i];
1374                 ctxd = &sc->tx_desc_base[i];
1375
1376                 ctxd->buffer_addr = htole64(segs[j].ds_addr);
1377                 ctxd->lower.data = htole32(E1000_TXD_CMD_IFCS |
1378                                            txd_lower | segs[j].ds_len);
1379                 ctxd->upper.data = htole32(txd_upper);
1380
1381                 last = i;
1382                 if (++i == sc->num_tx_desc)
1383                         i = 0;
1384
1385                 tx_buffer->m_head = NULL;
1386         }
1387
1388         sc->next_avail_tx_desc = i;
1389
1390         KKASSERT(sc->num_tx_desc_avail > nsegs);
1391         sc->num_tx_desc_avail -= nsegs;
1392
1393         /* Handle VLAN tag */
1394         if (m_head->m_flags & M_VLANTAG) {
1395                 /* Set the vlan id. */
1396                 ctxd->upper.fields.special =
1397                     htole16(m_head->m_pkthdr.ether_vlantag);
1398
1399                 /* Tell hardware to add tag */
1400                 ctxd->lower.data |= htole32(E1000_TXD_CMD_VLE);
1401         }
1402
1403         tx_buffer->m_head = m_head;
1404         tx_buffer_mapped->map = tx_buffer->map;
1405         tx_buffer->map = map;
1406
1407         if (sc->tx_nsegs >= sc->tx_int_nsegs) {
1408                 sc->tx_nsegs = 0;
1409                 cmd = E1000_TXD_CMD_RS;
1410
1411                 sc->tx_dd[sc->tx_dd_tail] = last;
1412                 EMX_INC_TXDD_IDX(sc->tx_dd_tail);
1413                 KKASSERT(sc->tx_dd_tail != sc->tx_dd_head);
1414         }
1415
1416         /*
1417          * Last Descriptor of Packet needs End Of Packet (EOP)
1418          * and Report Status (RS)
1419          */
1420         ctxd->lower.data |= htole32(E1000_TXD_CMD_EOP | cmd);
1421
1422         /*
1423          * Keep track in the first buffer which descriptor will be
1424          * written back
1425          */
1426         tx_buffer = &sc->tx_buffer_area[first];
1427
1428         /*
1429          * Advance the Transmit Descriptor Tail (TDT), this tells
1430          * the E1000 that this frame is available to transmit.
1431          */
1432         E1000_WRITE_REG(&sc->hw, E1000_TDT(0), i);
1433
1434         return (0);
1435 }
1436
1437 static void
1438 emx_set_promisc(struct emx_softc *sc)
1439 {
1440         struct ifnet *ifp = &sc->arpcom.ac_if;
1441         uint32_t reg_rctl;
1442
1443         reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1444
1445         if (ifp->if_flags & IFF_PROMISC) {
1446                 reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
1447                 /* Turn this on if you want to see bad packets */
1448                 if (emx_debug_sbp)
1449                         reg_rctl |= E1000_RCTL_SBP;
1450                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1451         } else if (ifp->if_flags & IFF_ALLMULTI) {
1452                 reg_rctl |= E1000_RCTL_MPE;
1453                 reg_rctl &= ~E1000_RCTL_UPE;
1454                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1455         }
1456 }
1457
1458 static void
1459 emx_disable_promisc(struct emx_softc *sc)
1460 {
1461         uint32_t reg_rctl;
1462
1463         reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1464
1465         reg_rctl &= ~E1000_RCTL_UPE;
1466         reg_rctl &= ~E1000_RCTL_MPE;
1467         reg_rctl &= ~E1000_RCTL_SBP;
1468         E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1469 }
1470
1471 static void
1472 emx_set_multi(struct emx_softc *sc)
1473 {
1474         struct ifnet *ifp = &sc->arpcom.ac_if;
1475         struct ifmultiaddr *ifma;
1476         uint32_t reg_rctl = 0;
1477         uint8_t  mta[512]; /* Largest MTS is 4096 bits */
1478         int mcnt = 0;
1479
1480         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1481                 if (ifma->ifma_addr->sa_family != AF_LINK)
1482                         continue;
1483
1484                 if (mcnt == EMX_MCAST_ADDR_MAX)
1485                         break;
1486
1487                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1488                       &mta[mcnt * ETHER_ADDR_LEN], ETHER_ADDR_LEN);
1489                 mcnt++;
1490         }
1491
1492         if (mcnt >= EMX_MCAST_ADDR_MAX) {
1493                 reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1494                 reg_rctl |= E1000_RCTL_MPE;
1495                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1496         } else {
1497                 e1000_update_mc_addr_list(&sc->hw, mta,
1498                     mcnt, 1, sc->hw.mac.rar_entry_count);
1499         }
1500 }
1501
1502 /*
1503  * This routine checks for link status and updates statistics.
1504  */
1505 static void
1506 emx_timer(void *xsc)
1507 {
1508         struct emx_softc *sc = xsc;
1509         struct ifnet *ifp = &sc->arpcom.ac_if;
1510
1511         lwkt_serialize_enter(ifp->if_serializer);
1512
1513         emx_update_link_status(sc);
1514         emx_update_stats(sc);
1515
1516         /* Reset LAA into RAR[0] on 82571 */
1517         if (e1000_get_laa_state_82571(&sc->hw) == TRUE)
1518                 e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1519
1520         if (emx_display_debug_stats && (ifp->if_flags & IFF_RUNNING))
1521                 emx_print_hw_stats(sc);
1522
1523         emx_smartspeed(sc);
1524
1525         callout_reset(&sc->timer, hz, emx_timer, sc);
1526
1527         lwkt_serialize_exit(ifp->if_serializer);
1528 }
1529
1530 static void
1531 emx_update_link_status(struct emx_softc *sc)
1532 {
1533         struct e1000_hw *hw = &sc->hw;
1534         struct ifnet *ifp = &sc->arpcom.ac_if;
1535         device_t dev = sc->dev;
1536         uint32_t link_check = 0;
1537
1538         /* Get the cached link value or read phy for real */
1539         switch (hw->phy.media_type) {
1540         case e1000_media_type_copper:
1541                 if (hw->mac.get_link_status) {
1542                         /* Do the work to read phy */
1543                         e1000_check_for_link(hw);
1544                         link_check = !hw->mac.get_link_status;
1545                         if (link_check) /* ESB2 fix */
1546                                 e1000_cfg_on_link_up(hw);
1547                 } else {
1548                         link_check = TRUE;
1549                 }
1550                 break;
1551
1552         case e1000_media_type_fiber:
1553                 e1000_check_for_link(hw);
1554                 link_check = E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU;
1555                 break;
1556
1557         case e1000_media_type_internal_serdes:
1558                 e1000_check_for_link(hw);
1559                 link_check = sc->hw.mac.serdes_has_link;
1560                 break;
1561
1562         case e1000_media_type_unknown:
1563         default:
1564                 break;
1565         }
1566
1567         /* Now check for a transition */
1568         if (link_check && sc->link_active == 0) {
1569                 e1000_get_speed_and_duplex(hw, &sc->link_speed,
1570                     &sc->link_duplex);
1571
1572                 /*
1573                  * Check if we should enable/disable SPEED_MODE bit on
1574                  * 82571EB/82572EI
1575                  */
1576                 if (hw->mac.type == e1000_82571 ||
1577                     hw->mac.type == e1000_82572) {
1578                         int tarc0;
1579
1580                         tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
1581                         if (sc->link_speed != SPEED_1000)
1582                                 tarc0 &= ~EMX_TARC_SPEED_MODE;
1583                         else
1584                                 tarc0 |= EMX_TARC_SPEED_MODE;
1585                         E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
1586                 }
1587                 if (bootverbose) {
1588                         device_printf(dev, "Link is up %d Mbps %s\n",
1589                             sc->link_speed,
1590                             ((sc->link_duplex == FULL_DUPLEX) ?
1591                             "Full Duplex" : "Half Duplex"));
1592                 }
1593                 sc->link_active = 1;
1594                 sc->smartspeed = 0;
1595                 ifp->if_baudrate = sc->link_speed * 1000000;
1596                 ifp->if_link_state = LINK_STATE_UP;
1597                 if_link_state_change(ifp);
1598         } else if (!link_check && sc->link_active == 1) {
1599                 ifp->if_baudrate = sc->link_speed = 0;
1600                 sc->link_duplex = 0;
1601                 if (bootverbose)
1602                         device_printf(dev, "Link is Down\n");
1603                 sc->link_active = 0;
1604 #if 0
1605                 /* Link down, disable watchdog */
1606                 if->if_timer = 0;
1607 #endif
1608                 ifp->if_link_state = LINK_STATE_DOWN;
1609                 if_link_state_change(ifp);
1610         }
1611 }
1612
1613 static void
1614 emx_stop(struct emx_softc *sc)
1615 {
1616         struct ifnet *ifp = &sc->arpcom.ac_if;
1617         int i;
1618
1619         ASSERT_SERIALIZED(ifp->if_serializer);
1620
1621         emx_disable_intr(sc);
1622
1623         callout_stop(&sc->timer);
1624
1625         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
1626         ifp->if_timer = 0;
1627
1628         e1000_reset_hw(&sc->hw);
1629         E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1630
1631         for (i = 0; i < sc->num_tx_desc; i++) {
1632                 struct emx_buf *tx_buffer = &sc->tx_buffer_area[i];
1633
1634                 if (tx_buffer->m_head != NULL) {
1635                         bus_dmamap_unload(sc->txtag, tx_buffer->map);
1636                         m_freem(tx_buffer->m_head);
1637                         tx_buffer->m_head = NULL;
1638                 }
1639         }
1640
1641         for (i = 0; i < sc->num_rx_desc; i++) {
1642                 struct emx_buf *rx_buffer = &sc->rx_buffer_area[i];
1643
1644                 if (rx_buffer->m_head != NULL) {
1645                         bus_dmamap_unload(sc->rxtag, rx_buffer->map);
1646                         m_freem(rx_buffer->m_head);
1647                         rx_buffer->m_head = NULL;
1648                 }
1649         }
1650
1651         if (sc->fmp != NULL)
1652                 m_freem(sc->fmp);
1653         sc->fmp = NULL;
1654         sc->lmp = NULL;
1655
1656         sc->csum_flags = 0;
1657         sc->csum_ehlen = 0;
1658         sc->csum_iphlen = 0;
1659
1660         sc->tx_dd_head = 0;
1661         sc->tx_dd_tail = 0;
1662         sc->tx_nsegs = 0;
1663 }
1664
1665 static int
1666 emx_hw_init(struct emx_softc *sc)
1667 {
1668         device_t dev = sc->dev;
1669         uint16_t rx_buffer_size;
1670
1671         /* Issue a global reset */
1672         e1000_reset_hw(&sc->hw);
1673
1674         /* Get control from any management/hw control */
1675         if (sc->hw.mac.type == e1000_82573 &&
1676             e1000_check_mng_mode(&sc->hw))
1677                 emx_get_hw_control(sc);
1678
1679         /* Set up smart power down as default off on newer adapters. */
1680         if (!emx_smart_pwr_down &&
1681             (sc->hw.mac.type == e1000_82571 ||
1682              sc->hw.mac.type == e1000_82572)) {
1683                 uint16_t phy_tmp = 0;
1684
1685                 /* Speed up time to link by disabling smart power down. */
1686                 e1000_read_phy_reg(&sc->hw,
1687                     IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
1688                 phy_tmp &= ~IGP02E1000_PM_SPD;
1689                 e1000_write_phy_reg(&sc->hw,
1690                     IGP02E1000_PHY_POWER_MGMT, phy_tmp);
1691         }
1692
1693         /*
1694          * These parameters control the automatic generation (Tx) and
1695          * response (Rx) to Ethernet PAUSE frames.
1696          * - High water mark should allow for at least two frames to be
1697          *   received after sending an XOFF.
1698          * - Low water mark works best when it is very near the high water mark.
1699          *   This allows the receiver to restart by sending XON when it has
1700          *   drained a bit. Here we use an arbitary value of 1500 which will
1701          *   restart after one full frame is pulled from the buffer. There
1702          *   could be several smaller frames in the buffer and if so they will
1703          *   not trigger the XON until their total number reduces the buffer
1704          *   by 1500.
1705          * - The pause time is fairly large at 1000 x 512ns = 512 usec.
1706          */
1707         rx_buffer_size = (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) << 10;
1708
1709         sc->hw.fc.high_water = rx_buffer_size -
1710                                roundup2(sc->max_frame_size, 1024);
1711         sc->hw.fc.low_water = sc->hw.fc.high_water - 1500;
1712
1713         if (sc->hw.mac.type == e1000_80003es2lan)
1714                 sc->hw.fc.pause_time = 0xFFFF;
1715         else
1716                 sc->hw.fc.pause_time = EMX_FC_PAUSE_TIME;
1717         sc->hw.fc.send_xon = TRUE;
1718         sc->hw.fc.requested_mode = e1000_fc_full;
1719
1720         if (e1000_init_hw(&sc->hw) < 0) {
1721                 device_printf(dev, "Hardware Initialization Failed\n");
1722                 return (EIO);
1723         }
1724
1725         e1000_check_for_link(&sc->hw);
1726
1727         return (0);
1728 }
1729
1730 static void
1731 emx_setup_ifp(struct emx_softc *sc)
1732 {
1733         struct ifnet *ifp = &sc->arpcom.ac_if;
1734
1735         if_initname(ifp, device_get_name(sc->dev),
1736                     device_get_unit(sc->dev));
1737         ifp->if_softc = sc;
1738         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1739         ifp->if_init =  emx_init;
1740         ifp->if_ioctl = emx_ioctl;
1741         ifp->if_start = emx_start;
1742 #ifdef DEVICE_POLLING
1743         ifp->if_poll = emx_poll;
1744 #endif
1745         ifp->if_watchdog = emx_watchdog;
1746         ifq_set_maxlen(&ifp->if_snd, sc->num_tx_desc - 1);
1747         ifq_set_ready(&ifp->if_snd);
1748
1749         ether_ifattach(ifp, sc->hw.mac.addr, NULL);
1750
1751         ifp->if_capabilities = IFCAP_HWCSUM |
1752                                IFCAP_VLAN_HWTAGGING |
1753                                IFCAP_VLAN_MTU;
1754         ifp->if_capenable = ifp->if_capabilities;
1755         ifp->if_hwassist = EMX_CSUM_FEATURES;
1756
1757         /*
1758          * Tell the upper layer(s) we support long frames.
1759          */
1760         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
1761
1762         /*
1763          * Specify the media types supported by this sc and register
1764          * callbacks to update media and link information
1765          */
1766         ifmedia_init(&sc->media, IFM_IMASK,
1767                      emx_media_change, emx_media_status);
1768         if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1769             sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1770                 ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_SX | IFM_FDX,
1771                             0, NULL);
1772                 ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_SX, 0, NULL);
1773         } else {
1774                 ifmedia_add(&sc->media, IFM_ETHER | IFM_10_T, 0, NULL);
1775                 ifmedia_add(&sc->media, IFM_ETHER | IFM_10_T | IFM_FDX,
1776                             0, NULL);
1777                 ifmedia_add(&sc->media, IFM_ETHER | IFM_100_TX, 0, NULL);
1778                 ifmedia_add(&sc->media, IFM_ETHER | IFM_100_TX | IFM_FDX,
1779                             0, NULL);
1780                 if (sc->hw.phy.type != e1000_phy_ife) {
1781                         ifmedia_add(&sc->media,
1782                                 IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL);
1783                         ifmedia_add(&sc->media,
1784                                 IFM_ETHER | IFM_1000_T, 0, NULL);
1785                 }
1786         }
1787         ifmedia_add(&sc->media, IFM_ETHER | IFM_AUTO, 0, NULL);
1788         ifmedia_set(&sc->media, IFM_ETHER | IFM_AUTO);
1789 }
1790
1791 /*
1792  * Workaround for SmartSpeed on 82541 and 82547 controllers
1793  */
1794 static void
1795 emx_smartspeed(struct emx_softc *sc)
1796 {
1797         uint16_t phy_tmp;
1798
1799         if (sc->link_active || sc->hw.phy.type != e1000_phy_igp ||
1800             sc->hw.mac.autoneg == 0 ||
1801             (sc->hw.phy.autoneg_advertised & ADVERTISE_1000_FULL) == 0)
1802                 return;
1803
1804         if (sc->smartspeed == 0) {
1805                 /*
1806                  * If Master/Slave config fault is asserted twice,
1807                  * we assume back-to-back
1808                  */
1809                 e1000_read_phy_reg(&sc->hw, PHY_1000T_STATUS, &phy_tmp);
1810                 if (!(phy_tmp & SR_1000T_MS_CONFIG_FAULT))
1811                         return;
1812                 e1000_read_phy_reg(&sc->hw, PHY_1000T_STATUS, &phy_tmp);
1813                 if (phy_tmp & SR_1000T_MS_CONFIG_FAULT) {
1814                         e1000_read_phy_reg(&sc->hw,
1815                             PHY_1000T_CTRL, &phy_tmp);
1816                         if (phy_tmp & CR_1000T_MS_ENABLE) {
1817                                 phy_tmp &= ~CR_1000T_MS_ENABLE;
1818                                 e1000_write_phy_reg(&sc->hw,
1819                                     PHY_1000T_CTRL, phy_tmp);
1820                                 sc->smartspeed++;
1821                                 if (sc->hw.mac.autoneg &&
1822                                     !e1000_phy_setup_autoneg(&sc->hw) &&
1823                                     !e1000_read_phy_reg(&sc->hw,
1824                                      PHY_CONTROL, &phy_tmp)) {
1825                                         phy_tmp |= MII_CR_AUTO_NEG_EN |
1826                                                    MII_CR_RESTART_AUTO_NEG;
1827                                         e1000_write_phy_reg(&sc->hw,
1828                                             PHY_CONTROL, phy_tmp);
1829                                 }
1830                         }
1831                 }
1832                 return;
1833         } else if (sc->smartspeed == EMX_SMARTSPEED_DOWNSHIFT) {
1834                 /* If still no link, perhaps using 2/3 pair cable */
1835                 e1000_read_phy_reg(&sc->hw, PHY_1000T_CTRL, &phy_tmp);
1836                 phy_tmp |= CR_1000T_MS_ENABLE;
1837                 e1000_write_phy_reg(&sc->hw, PHY_1000T_CTRL, phy_tmp);
1838                 if (sc->hw.mac.autoneg &&
1839                     !e1000_phy_setup_autoneg(&sc->hw) &&
1840                     !e1000_read_phy_reg(&sc->hw, PHY_CONTROL, &phy_tmp)) {
1841                         phy_tmp |= MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
1842                         e1000_write_phy_reg(&sc->hw, PHY_CONTROL, phy_tmp);
1843                 }
1844         }
1845
1846         /* Restart process after EMX_SMARTSPEED_MAX iterations */
1847         if (sc->smartspeed++ == EMX_SMARTSPEED_MAX)
1848                 sc->smartspeed = 0;
1849 }
1850
1851 static int
1852 emx_dma_malloc(struct emx_softc *sc, bus_size_t size,
1853                struct emx_dma *dma)
1854 {
1855         dma->dma_vaddr = bus_dmamem_coherent_any(sc->parent_dtag,
1856                                 EMX_DBA_ALIGN, size, BUS_DMA_WAITOK,
1857                                 &dma->dma_tag, &dma->dma_map,
1858                                 &dma->dma_paddr);
1859         if (dma->dma_vaddr == NULL)
1860                 return ENOMEM;
1861         else
1862                 return 0;
1863 }
1864
1865 static void
1866 emx_dma_free(struct emx_softc *sc, struct emx_dma *dma)
1867 {
1868         if (dma->dma_tag == NULL)
1869                 return;
1870         bus_dmamap_unload(dma->dma_tag, dma->dma_map);
1871         bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
1872         bus_dma_tag_destroy(dma->dma_tag);
1873 }
1874
1875 static int
1876 emx_create_tx_ring(struct emx_softc *sc)
1877 {
1878         device_t dev = sc->dev;
1879         struct emx_buf *tx_buffer;
1880         int error, i;
1881
1882         sc->tx_buffer_area =
1883                 kmalloc(sizeof(struct emx_buf) * sc->num_tx_desc,
1884                         M_DEVBUF, M_WAITOK | M_ZERO);
1885
1886         /*
1887          * Create DMA tags for tx buffers
1888          */
1889         error = bus_dma_tag_create(sc->parent_dtag, /* parent */
1890                         1, 0,                   /* alignment, bounds */
1891                         BUS_SPACE_MAXADDR,      /* lowaddr */
1892                         BUS_SPACE_MAXADDR,      /* highaddr */
1893                         NULL, NULL,             /* filter, filterarg */
1894                         EMX_TSO_SIZE,           /* maxsize */
1895                         EMX_MAX_SCATTER,        /* nsegments */
1896                         EMX_MAX_SEGSIZE,        /* maxsegsize */
1897                         BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW |
1898                         BUS_DMA_ONEBPAGE,       /* flags */
1899                         &sc->txtag);
1900         if (error) {
1901                 device_printf(dev, "Unable to allocate TX DMA tag\n");
1902                 kfree(sc->tx_buffer_area, M_DEVBUF);
1903                 sc->tx_buffer_area = NULL;
1904                 return error;
1905         }
1906
1907         /*
1908          * Create DMA maps for tx buffers
1909          */
1910         for (i = 0; i < sc->num_tx_desc; i++) {
1911                 tx_buffer = &sc->tx_buffer_area[i];
1912
1913                 error = bus_dmamap_create(sc->txtag,
1914                                           BUS_DMA_WAITOK | BUS_DMA_ONEBPAGE,
1915                                           &tx_buffer->map);
1916                 if (error) {
1917                         device_printf(dev, "Unable to create TX DMA map\n");
1918                         emx_destroy_tx_ring(sc, i);
1919                         return error;
1920                 }
1921         }
1922         return (0);
1923 }
1924
1925 static void
1926 emx_init_tx_ring(struct emx_softc *sc)
1927 {
1928         /* Clear the old ring contents */
1929         bzero(sc->tx_desc_base,
1930               sizeof(struct e1000_tx_desc) * sc->num_tx_desc);
1931
1932         /* Reset state */
1933         sc->next_avail_tx_desc = 0;
1934         sc->next_tx_to_clean = 0;
1935         sc->num_tx_desc_avail = sc->num_tx_desc;
1936 }
1937
1938 static void
1939 emx_init_tx_unit(struct emx_softc *sc)
1940 {
1941         uint32_t tctl, tarc, tipg = 0;
1942         uint64_t bus_addr;
1943
1944         /* Setup the Base and Length of the Tx Descriptor Ring */
1945         bus_addr = sc->txdma.dma_paddr;
1946         E1000_WRITE_REG(&sc->hw, E1000_TDLEN(0),
1947             sc->num_tx_desc * sizeof(struct e1000_tx_desc));
1948         E1000_WRITE_REG(&sc->hw, E1000_TDBAH(0),
1949             (uint32_t)(bus_addr >> 32));
1950         E1000_WRITE_REG(&sc->hw, E1000_TDBAL(0),
1951             (uint32_t)bus_addr);
1952         /* Setup the HW Tx Head and Tail descriptor pointers */
1953         E1000_WRITE_REG(&sc->hw, E1000_TDT(0), 0);
1954         E1000_WRITE_REG(&sc->hw, E1000_TDH(0), 0);
1955
1956         /* Set the default values for the Tx Inter Packet Gap timer */
1957         switch (sc->hw.mac.type) {
1958         case e1000_80003es2lan:
1959                 tipg = DEFAULT_82543_TIPG_IPGR1;
1960                 tipg |= DEFAULT_80003ES2LAN_TIPG_IPGR2 <<
1961                     E1000_TIPG_IPGR2_SHIFT;
1962                 break;
1963
1964         default:
1965                 if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1966                     sc->hw.phy.media_type == e1000_media_type_internal_serdes)
1967                         tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
1968                 else
1969                         tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
1970                 tipg |= DEFAULT_82543_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
1971                 tipg |= DEFAULT_82543_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
1972                 break;
1973         }
1974
1975         E1000_WRITE_REG(&sc->hw, E1000_TIPG, tipg);
1976
1977         /* NOTE: 0 is not allowed for TIDV */
1978         E1000_WRITE_REG(&sc->hw, E1000_TIDV, 1);
1979         E1000_WRITE_REG(&sc->hw, E1000_TADV, 0);
1980
1981         if (sc->hw.mac.type == e1000_82571 ||
1982             sc->hw.mac.type == e1000_82572) {
1983                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
1984                 tarc |= EMX_TARC_SPEED_MODE;
1985                 E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
1986         } else if (sc->hw.mac.type == e1000_80003es2lan) {
1987                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
1988                 tarc |= 1;
1989                 E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
1990                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
1991                 tarc |= 1;
1992                 E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
1993         }
1994
1995         /* Program the Transmit Control Register */
1996         tctl = E1000_READ_REG(&sc->hw, E1000_TCTL);
1997         tctl &= ~E1000_TCTL_CT;
1998         tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC | E1000_TCTL_EN |
1999                 (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
2000         tctl |= E1000_TCTL_MULR;
2001
2002         /* This write will effectively turn on the transmit unit. */
2003         E1000_WRITE_REG(&sc->hw, E1000_TCTL, tctl);
2004 }
2005
2006 static void
2007 emx_destroy_tx_ring(struct emx_softc *sc, int ndesc)
2008 {
2009         struct emx_buf *tx_buffer;
2010         int i;
2011
2012         if (sc->tx_buffer_area == NULL)
2013                 return;
2014
2015         for (i = 0; i < ndesc; i++) {
2016                 tx_buffer = &sc->tx_buffer_area[i];
2017
2018                 KKASSERT(tx_buffer->m_head == NULL);
2019                 bus_dmamap_destroy(sc->txtag, tx_buffer->map);
2020         }
2021         bus_dma_tag_destroy(sc->txtag);
2022
2023         kfree(sc->tx_buffer_area, M_DEVBUF);
2024         sc->tx_buffer_area = NULL;
2025 }
2026
2027 /*
2028  * The offload context needs to be set when we transfer the first
2029  * packet of a particular protocol (TCP/UDP).  This routine has been
2030  * enhanced to deal with inserted VLAN headers.
2031  *
2032  * If the new packet's ether header length, ip header length and
2033  * csum offloading type are same as the previous packet, we should
2034  * avoid allocating a new csum context descriptor; mainly to take
2035  * advantage of the pipeline effect of the TX data read request.
2036  *
2037  * This function returns number of TX descrptors allocated for
2038  * csum context.
2039  */
2040 static int
2041 emx_txcsum(struct emx_softc *sc, struct mbuf *mp,
2042            uint32_t *txd_upper, uint32_t *txd_lower)
2043 {
2044         struct e1000_context_desc *TXD;
2045         struct emx_buf *tx_buffer;
2046         struct ether_vlan_header *eh;
2047         struct ip *ip;
2048         int curr_txd, ehdrlen, csum_flags;
2049         uint32_t cmd, hdr_len, ip_hlen;
2050         uint16_t etype;
2051
2052         /*
2053          * Determine where frame payload starts.
2054          * Jump over vlan headers if already present,
2055          * helpful for QinQ too.
2056          */
2057         KASSERT(mp->m_len >= ETHER_HDR_LEN,
2058                 ("emx_txcsum_pullup is not called (eh)?\n"));
2059         eh = mtod(mp, struct ether_vlan_header *);
2060         if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
2061                 KASSERT(mp->m_len >= ETHER_HDR_LEN + EVL_ENCAPLEN,
2062                         ("emx_txcsum_pullup is not called (evh)?\n"));
2063                 etype = ntohs(eh->evl_proto);
2064                 ehdrlen = ETHER_HDR_LEN + EVL_ENCAPLEN;
2065         } else {
2066                 etype = ntohs(eh->evl_encap_proto);
2067                 ehdrlen = ETHER_HDR_LEN;
2068         }
2069
2070         /*
2071          * We only support TCP/UDP for IPv4 for the moment.
2072          * TODO: Support SCTP too when it hits the tree.
2073          */
2074         if (etype != ETHERTYPE_IP)
2075                 return 0;
2076
2077         KASSERT(mp->m_len >= ehdrlen + EMX_IPVHL_SIZE,
2078                 ("emx_txcsum_pullup is not called (eh+ip_vhl)?\n"));
2079
2080         /* NOTE: We could only safely access ip.ip_vhl part */
2081         ip = (struct ip *)(mp->m_data + ehdrlen);
2082         ip_hlen = ip->ip_hl << 2;
2083
2084         csum_flags = mp->m_pkthdr.csum_flags & EMX_CSUM_FEATURES;
2085
2086         if (sc->csum_ehlen == ehdrlen && sc->csum_iphlen == ip_hlen &&
2087             sc->csum_flags == csum_flags) {
2088                 /*
2089                  * Same csum offload context as the previous packets;
2090                  * just return.
2091                  */
2092                 *txd_upper = sc->csum_txd_upper;
2093                 *txd_lower = sc->csum_txd_lower;
2094                 return 0;
2095         }
2096
2097         /*
2098          * Setup a new csum offload context.
2099          */
2100
2101         curr_txd = sc->next_avail_tx_desc;
2102         tx_buffer = &sc->tx_buffer_area[curr_txd];
2103         TXD = (struct e1000_context_desc *)&sc->tx_desc_base[curr_txd];
2104
2105         cmd = 0;
2106
2107         /* Setup of IP header checksum. */
2108         if (csum_flags & CSUM_IP) {
2109                 /*
2110                  * Start offset for header checksum calculation.
2111                  * End offset for header checksum calculation.
2112                  * Offset of place to put the checksum.
2113                  */
2114                 TXD->lower_setup.ip_fields.ipcss = ehdrlen;
2115                 TXD->lower_setup.ip_fields.ipcse =
2116                     htole16(ehdrlen + ip_hlen - 1);
2117                 TXD->lower_setup.ip_fields.ipcso =
2118                     ehdrlen + offsetof(struct ip, ip_sum);
2119                 cmd |= E1000_TXD_CMD_IP;
2120                 *txd_upper |= E1000_TXD_POPTS_IXSM << 8;
2121         }
2122         hdr_len = ehdrlen + ip_hlen;
2123
2124         if (csum_flags & CSUM_TCP) {
2125                 /*
2126                  * Start offset for payload checksum calculation.
2127                  * End offset for payload checksum calculation.
2128                  * Offset of place to put the checksum.
2129                  */
2130                 TXD->upper_setup.tcp_fields.tucss = hdr_len;
2131                 TXD->upper_setup.tcp_fields.tucse = htole16(0);
2132                 TXD->upper_setup.tcp_fields.tucso =
2133                     hdr_len + offsetof(struct tcphdr, th_sum);
2134                 cmd |= E1000_TXD_CMD_TCP;
2135                 *txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2136         } else if (csum_flags & CSUM_UDP) {
2137                 /*
2138                  * Start offset for header checksum calculation.
2139                  * End offset for header checksum calculation.
2140                  * Offset of place to put the checksum.
2141                  */
2142                 TXD->upper_setup.tcp_fields.tucss = hdr_len;
2143                 TXD->upper_setup.tcp_fields.tucse = htole16(0);
2144                 TXD->upper_setup.tcp_fields.tucso =
2145                     hdr_len + offsetof(struct udphdr, uh_sum);
2146                 *txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2147         }
2148
2149         *txd_lower = E1000_TXD_CMD_DEXT |       /* Extended descr type */
2150                      E1000_TXD_DTYP_D;          /* Data descr */
2151
2152         /* Save the information for this csum offloading context */
2153         sc->csum_ehlen = ehdrlen;
2154         sc->csum_iphlen = ip_hlen;
2155         sc->csum_flags = csum_flags;
2156         sc->csum_txd_upper = *txd_upper;
2157         sc->csum_txd_lower = *txd_lower;
2158
2159         TXD->tcp_seg_setup.data = htole32(0);
2160         TXD->cmd_and_length =
2161             htole32(E1000_TXD_CMD_IFCS | E1000_TXD_CMD_DEXT | cmd);
2162         tx_buffer->m_head = NULL;
2163
2164         if (++curr_txd == sc->num_tx_desc)
2165                 curr_txd = 0;
2166
2167         KKASSERT(sc->num_tx_desc_avail > 0);
2168         sc->num_tx_desc_avail--;
2169
2170         sc->next_avail_tx_desc = curr_txd;
2171         return 1;
2172 }
2173
2174 static int
2175 emx_txcsum_pullup(struct emx_softc *sc, struct mbuf **m0)
2176 {
2177         struct mbuf *m = *m0;
2178         struct ether_header *eh;
2179         int len;
2180
2181         sc->tx_csum_try_pullup++;
2182
2183         len = ETHER_HDR_LEN + EMX_IPVHL_SIZE;
2184
2185         if (__predict_false(!M_WRITABLE(m))) {
2186                 if (__predict_false(m->m_len < ETHER_HDR_LEN)) {
2187                         sc->tx_csum_drop1++;
2188                         m_freem(m);
2189                         *m0 = NULL;
2190                         return ENOBUFS;
2191                 }
2192                 eh = mtod(m, struct ether_header *);
2193
2194                 if (eh->ether_type == htons(ETHERTYPE_VLAN))
2195                         len += EVL_ENCAPLEN;
2196
2197                 if (__predict_false(m->m_len < len)) {
2198                         sc->tx_csum_drop2++;
2199                         m_freem(m);
2200                         *m0 = NULL;
2201                         return ENOBUFS;
2202                 }
2203                 return 0;
2204         }
2205
2206         if (__predict_false(m->m_len < ETHER_HDR_LEN)) {
2207                 sc->tx_csum_pullup1++;
2208                 m = m_pullup(m, ETHER_HDR_LEN);
2209                 if (m == NULL) {
2210                         sc->tx_csum_pullup1_failed++;
2211                         *m0 = NULL;
2212                         return ENOBUFS;
2213                 }
2214                 *m0 = m;
2215         }
2216         eh = mtod(m, struct ether_header *);
2217
2218         if (eh->ether_type == htons(ETHERTYPE_VLAN))
2219                 len += EVL_ENCAPLEN;
2220
2221         if (__predict_false(m->m_len < len)) {
2222                 sc->tx_csum_pullup2++;
2223                 m = m_pullup(m, len);
2224                 if (m == NULL) {
2225                         sc->tx_csum_pullup2_failed++;
2226                         *m0 = NULL;
2227                         return ENOBUFS;
2228                 }
2229                 *m0 = m;
2230         }
2231         return 0;
2232 }
2233
2234 static void
2235 emx_txeof(struct emx_softc *sc)
2236 {
2237         struct ifnet *ifp = &sc->arpcom.ac_if;
2238         struct e1000_tx_desc *tx_desc;
2239         struct emx_buf *tx_buffer;
2240         int first, num_avail;
2241
2242         if (sc->tx_dd_head == sc->tx_dd_tail)
2243                 return;
2244
2245         if (sc->num_tx_desc_avail == sc->num_tx_desc)
2246                 return;
2247
2248         num_avail = sc->num_tx_desc_avail;
2249         first = sc->next_tx_to_clean;
2250
2251         while (sc->tx_dd_head != sc->tx_dd_tail) {
2252                 int dd_idx = sc->tx_dd[sc->tx_dd_head];
2253
2254                 tx_desc = &sc->tx_desc_base[dd_idx];
2255
2256                 if (tx_desc->upper.fields.status & E1000_TXD_STAT_DD) {
2257                         EMX_INC_TXDD_IDX(sc->tx_dd_head);
2258
2259                         if (++dd_idx == sc->num_tx_desc)
2260                                 dd_idx = 0;
2261
2262                         while (first != dd_idx) {
2263                                 logif(pkt_txclean);
2264
2265                                 tx_buffer = &sc->tx_buffer_area[first];
2266                                 tx_desc = &sc->tx_desc_base[first];
2267
2268                                 tx_desc->upper.data = 0;
2269                                 tx_desc->lower.data = 0;
2270                                 tx_desc->buffer_addr = 0;
2271                                 num_avail++;
2272
2273                                 if (tx_buffer->m_head) {
2274                                         ifp->if_opackets++;
2275                                         bus_dmamap_unload(sc->txtag,
2276                                                           tx_buffer->map);
2277                                         m_freem(tx_buffer->m_head);
2278                                         tx_buffer->m_head = NULL;
2279                                 }
2280
2281                                 if (++first == sc->num_tx_desc)
2282                                         first = 0;
2283                         }
2284                 } else {
2285                         break;
2286                 }
2287         }
2288         sc->next_tx_to_clean = first;
2289         sc->num_tx_desc_avail = num_avail;
2290
2291         if (sc->tx_dd_head == sc->tx_dd_tail) {
2292                 sc->tx_dd_head = 0;
2293                 sc->tx_dd_tail = 0;
2294         }
2295
2296         if (!EMX_IS_OACTIVE(sc)) {
2297                 ifp->if_flags &= ~IFF_OACTIVE;
2298
2299                 /* All clean, turn off the timer */
2300                 if (sc->num_tx_desc_avail == sc->num_tx_desc)
2301                         ifp->if_timer = 0;
2302         }
2303 }
2304
2305 static void
2306 emx_tx_collect(struct emx_softc *sc)
2307 {
2308         struct ifnet *ifp = &sc->arpcom.ac_if;
2309         struct e1000_tx_desc *tx_desc;
2310         struct emx_buf *tx_buffer;
2311         int tdh, first, num_avail, dd_idx = -1;
2312
2313         if (sc->num_tx_desc_avail == sc->num_tx_desc)
2314                 return;
2315
2316         tdh = E1000_READ_REG(&sc->hw, E1000_TDH(0));
2317         if (tdh == sc->next_tx_to_clean)
2318                 return;
2319
2320         if (sc->tx_dd_head != sc->tx_dd_tail)
2321                 dd_idx = sc->tx_dd[sc->tx_dd_head];
2322
2323         num_avail = sc->num_tx_desc_avail;
2324         first = sc->next_tx_to_clean;
2325
2326         while (first != tdh) {
2327                 logif(pkt_txclean);
2328
2329                 tx_buffer = &sc->tx_buffer_area[first];
2330                 tx_desc = &sc->tx_desc_base[first];
2331
2332                 tx_desc->upper.data = 0;
2333                 tx_desc->lower.data = 0;
2334                 tx_desc->buffer_addr = 0;
2335                 num_avail++;
2336
2337                 if (tx_buffer->m_head) {
2338                         ifp->if_opackets++;
2339                         bus_dmamap_unload(sc->txtag,
2340                                           tx_buffer->map);
2341                         m_freem(tx_buffer->m_head);
2342                         tx_buffer->m_head = NULL;
2343                 }
2344
2345                 if (first == dd_idx) {
2346                         EMX_INC_TXDD_IDX(sc->tx_dd_head);
2347                         if (sc->tx_dd_head == sc->tx_dd_tail) {
2348                                 sc->tx_dd_head = 0;
2349                                 sc->tx_dd_tail = 0;
2350                                 dd_idx = -1;
2351                         } else {
2352                                 dd_idx = sc->tx_dd[sc->tx_dd_head];
2353                         }
2354                 }
2355
2356                 if (++first == sc->num_tx_desc)
2357                         first = 0;
2358         }
2359         sc->next_tx_to_clean = first;
2360         sc->num_tx_desc_avail = num_avail;
2361
2362         if (!EMX_IS_OACTIVE(sc)) {
2363                 ifp->if_flags &= ~IFF_OACTIVE;
2364
2365                 /* All clean, turn off the timer */
2366                 if (sc->num_tx_desc_avail == sc->num_tx_desc)
2367                         ifp->if_timer = 0;
2368         }
2369 }
2370
2371 /*
2372  * When Link is lost sometimes there is work still in the TX ring
2373  * which will result in a watchdog, rather than allow that do an
2374  * attempted cleanup and then reinit here.  Note that this has been
2375  * seens mostly with fiber adapters.
2376  */
2377 static void
2378 emx_tx_purge(struct emx_softc *sc)
2379 {
2380         struct ifnet *ifp = &sc->arpcom.ac_if;
2381
2382         if (!sc->link_active && ifp->if_timer) {
2383                 emx_tx_collect(sc);
2384                 if (ifp->if_timer) {
2385                         if_printf(ifp, "Link lost, TX pending, reinit\n");
2386                         ifp->if_timer = 0;
2387                         emx_init(sc);
2388                 }
2389         }
2390 }
2391
2392 static int
2393 emx_newbuf(struct emx_softc *sc, int i, int init)
2394 {
2395         struct mbuf *m;
2396         bus_dma_segment_t seg;
2397         bus_dmamap_t map;
2398         struct emx_buf *rx_buffer;
2399         int error, nseg;
2400
2401         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
2402         if (m == NULL) {
2403                 sc->mbuf_cluster_failed++;
2404                 if (init) {
2405                         if_printf(&sc->arpcom.ac_if,
2406                                   "Unable to allocate RX mbuf\n");
2407                 }
2408                 return (ENOBUFS);
2409         }
2410         m->m_len = m->m_pkthdr.len = MCLBYTES;
2411
2412         if (sc->max_frame_size <= MCLBYTES - ETHER_ALIGN)
2413                 m_adj(m, ETHER_ALIGN);
2414
2415         error = bus_dmamap_load_mbuf_segment(sc->rxtag,
2416                         sc->rx_sparemap, m,
2417                         &seg, 1, &nseg, BUS_DMA_NOWAIT);
2418         if (error) {
2419                 m_freem(m);
2420                 if (init) {
2421                         if_printf(&sc->arpcom.ac_if,
2422                                   "Unable to load RX mbuf\n");
2423                 }
2424                 return (error);
2425         }
2426
2427         rx_buffer = &sc->rx_buffer_area[i];
2428         if (rx_buffer->m_head != NULL)
2429                 bus_dmamap_unload(sc->rxtag, rx_buffer->map);
2430
2431         map = rx_buffer->map;
2432         rx_buffer->map = sc->rx_sparemap;
2433         sc->rx_sparemap = map;
2434
2435         rx_buffer->m_head = m;
2436
2437         sc->rx_desc_base[i].buffer_addr = htole64(seg.ds_addr);
2438         return (0);
2439 }
2440
2441 static int
2442 emx_create_rx_ring(struct emx_softc *sc)
2443 {
2444         device_t dev = sc->dev;
2445         struct emx_buf *rx_buffer;
2446         int i, error;
2447
2448         sc->rx_buffer_area =
2449                 kmalloc(sizeof(struct emx_buf) * sc->num_rx_desc,
2450                         M_DEVBUF, M_WAITOK | M_ZERO);
2451
2452         /*
2453          * Create DMA tag for rx buffers
2454          */
2455         error = bus_dma_tag_create(sc->parent_dtag, /* parent */
2456                         1, 0,                   /* alignment, bounds */
2457                         BUS_SPACE_MAXADDR,      /* lowaddr */
2458                         BUS_SPACE_MAXADDR,      /* highaddr */
2459                         NULL, NULL,             /* filter, filterarg */
2460                         MCLBYTES,               /* maxsize */
2461                         1,                      /* nsegments */
2462                         MCLBYTES,               /* maxsegsize */
2463                         BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, /* flags */
2464                         &sc->rxtag);
2465         if (error) {
2466                 device_printf(dev, "Unable to allocate RX DMA tag\n");
2467                 kfree(sc->rx_buffer_area, M_DEVBUF);
2468                 sc->rx_buffer_area = NULL;
2469                 return error;
2470         }
2471
2472         /*
2473          * Create spare DMA map for rx buffers
2474          */
2475         error = bus_dmamap_create(sc->rxtag, BUS_DMA_WAITOK,
2476                                   &sc->rx_sparemap);
2477         if (error) {
2478                 device_printf(dev, "Unable to create spare RX DMA map\n");
2479                 bus_dma_tag_destroy(sc->rxtag);
2480                 kfree(sc->rx_buffer_area, M_DEVBUF);
2481                 sc->rx_buffer_area = NULL;
2482                 return error;
2483         }
2484
2485         /*
2486          * Create DMA maps for rx buffers
2487          */
2488         for (i = 0; i < sc->num_rx_desc; i++) {
2489                 rx_buffer = &sc->rx_buffer_area[i];
2490
2491                 error = bus_dmamap_create(sc->rxtag, BUS_DMA_WAITOK,
2492                                           &rx_buffer->map);
2493                 if (error) {
2494                         device_printf(dev, "Unable to create RX DMA map\n");
2495                         emx_destroy_rx_ring(sc, i);
2496                         return error;
2497                 }
2498         }
2499         return (0);
2500 }
2501
2502 static int
2503 emx_init_rx_ring(struct emx_softc *sc)
2504 {
2505         int i, error;
2506
2507         /* Reset descriptor ring */
2508         bzero(sc->rx_desc_base,
2509               sizeof(struct e1000_rx_desc) * sc->num_rx_desc);
2510
2511         /* Allocate new ones. */
2512         for (i = 0; i < sc->num_rx_desc; i++) {
2513                 error = emx_newbuf(sc, i, 1);
2514                 if (error)
2515                         return (error);
2516         }
2517
2518         /* Setup our descriptor pointers */
2519         sc->next_rx_desc_to_check = 0;
2520
2521         return (0);
2522 }
2523
2524 static void
2525 emx_init_rx_unit(struct emx_softc *sc)
2526 {
2527         struct ifnet *ifp = &sc->arpcom.ac_if;
2528         uint64_t bus_addr;
2529         uint32_t rctl, rxcsum;
2530
2531         /*
2532          * Make sure receives are disabled while setting
2533          * up the descriptor ring
2534          */
2535         rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
2536         E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
2537
2538         /*
2539          * Set the interrupt throttling rate. Value is calculated
2540          * as ITR = 1 / (INT_THROTTLE_CEIL * 256ns)
2541          */
2542         if (sc->int_throttle_ceil) {
2543                 E1000_WRITE_REG(&sc->hw, E1000_ITR,
2544                         1000000000 / 256 / sc->int_throttle_ceil);
2545         } else {
2546                 E1000_WRITE_REG(&sc->hw, E1000_ITR, 0);
2547         }
2548
2549         /* Disable accelerated ackknowledge */
2550         if (sc->hw.mac.type == e1000_82574) {
2551                 E1000_WRITE_REG(&sc->hw,
2552                     E1000_RFCTL, E1000_RFCTL_ACK_DIS);
2553         }
2554
2555         /* Setup the Base and Length of the Rx Descriptor Ring */
2556         bus_addr = sc->rxdma.dma_paddr;
2557         E1000_WRITE_REG(&sc->hw, E1000_RDLEN(0),
2558             sc->num_rx_desc * sizeof(struct e1000_rx_desc));
2559         E1000_WRITE_REG(&sc->hw, E1000_RDBAH(0), (uint32_t)(bus_addr >> 32));
2560         E1000_WRITE_REG(&sc->hw, E1000_RDBAL(0), (uint32_t)bus_addr);
2561
2562         /* Setup the Receive Control Register */
2563         rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
2564         rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO |
2565                 E1000_RCTL_RDMTS_HALF |
2566                 (sc->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
2567
2568         /* Make sure VLAN Filters are off */
2569         rctl &= ~E1000_RCTL_VFE;
2570
2571         if (e1000_tbi_sbp_enabled_82543(&sc->hw))
2572                 rctl |= E1000_RCTL_SBP;
2573         else
2574                 rctl &= ~E1000_RCTL_SBP;
2575
2576         switch (sc->rx_buffer_len) {
2577         default:
2578         case 2048:
2579                 rctl |= E1000_RCTL_SZ_2048;
2580                 break;
2581
2582         case 4096:
2583                 rctl |= E1000_RCTL_SZ_4096 |
2584                     E1000_RCTL_BSEX | E1000_RCTL_LPE;
2585                 break;
2586
2587         case 8192:
2588                 rctl |= E1000_RCTL_SZ_8192 |
2589                     E1000_RCTL_BSEX | E1000_RCTL_LPE;
2590                 break;
2591
2592         case 16384:
2593                 rctl |= E1000_RCTL_SZ_16384 |
2594                     E1000_RCTL_BSEX | E1000_RCTL_LPE;
2595                 break;
2596         }
2597
2598         if (ifp->if_mtu > ETHERMTU)
2599                 rctl |= E1000_RCTL_LPE;
2600         else
2601                 rctl &= ~E1000_RCTL_LPE;
2602
2603         /* Receive Checksum Offload for TCP and UDP */
2604         if (ifp->if_capenable & IFCAP_RXCSUM) {
2605                 rxcsum = E1000_READ_REG(&sc->hw, E1000_RXCSUM);
2606                 rxcsum |= (E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL);
2607                 E1000_WRITE_REG(&sc->hw, E1000_RXCSUM, rxcsum);
2608         }
2609
2610         /*
2611          * XXX TEMPORARY WORKAROUND: on some systems with 82573
2612          * long latencies are observed, like Lenovo X60. This
2613          * change eliminates the problem, but since having positive
2614          * values in RDTR is a known source of problems on other
2615          * platforms another solution is being sought.
2616          */
2617         if (emx_82573_workaround && sc->hw.mac.type == e1000_82573) {
2618                 E1000_WRITE_REG(&sc->hw, E1000_RADV, EMX_RADV_82573);
2619                 E1000_WRITE_REG(&sc->hw, E1000_RDTR, EMX_RDTR_82573);
2620         }
2621
2622         /* Enable Receives */
2623         E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl);
2624
2625         /*
2626          * Setup the HW Rx Head and Tail Descriptor Pointers
2627          */
2628         E1000_WRITE_REG(&sc->hw, E1000_RDH(0), 0);
2629         E1000_WRITE_REG(&sc->hw, E1000_RDT(0), sc->num_rx_desc - 1);
2630 }
2631
2632 static void
2633 emx_destroy_rx_ring(struct emx_softc *sc, int ndesc)
2634 {
2635         struct emx_buf *rx_buffer;
2636         int i;
2637
2638         if (sc->rx_buffer_area == NULL)
2639                 return;
2640
2641         for (i = 0; i < ndesc; i++) {
2642                 rx_buffer = &sc->rx_buffer_area[i];
2643
2644                 KKASSERT(rx_buffer->m_head == NULL);
2645                 bus_dmamap_destroy(sc->rxtag, rx_buffer->map);
2646         }
2647         bus_dmamap_destroy(sc->rxtag, sc->rx_sparemap);
2648         bus_dma_tag_destroy(sc->rxtag);
2649
2650         kfree(sc->rx_buffer_area, M_DEVBUF);
2651         sc->rx_buffer_area = NULL;
2652 }
2653
2654 static void
2655 emx_rxeof(struct emx_softc *sc, int count)
2656 {
2657         struct ifnet *ifp = &sc->arpcom.ac_if;
2658         uint8_t status, accept_frame = 0, eop = 0;
2659         uint16_t len, desc_len, prev_len_adj;
2660         struct e1000_rx_desc *current_desc;
2661         struct mbuf *mp;
2662         int i;
2663         struct mbuf_chain chain[MAXCPU];
2664
2665         i = sc->next_rx_desc_to_check;
2666         current_desc = &sc->rx_desc_base[i];
2667
2668         if (!(current_desc->status & E1000_RXD_STAT_DD))
2669                 return;
2670
2671         ether_input_chain_init(chain);
2672
2673         while ((current_desc->status & E1000_RXD_STAT_DD) && count != 0) {
2674                 struct mbuf *m = NULL;
2675
2676                 logif(pkt_receive);
2677
2678                 mp = sc->rx_buffer_area[i].m_head;
2679
2680                 /*
2681                  * Can't defer bus_dmamap_sync(9) because TBI_ACCEPT
2682                  * needs to access the last received byte in the mbuf.
2683                  */
2684                 bus_dmamap_sync(sc->rxtag, sc->rx_buffer_area[i].map,
2685                                 BUS_DMASYNC_POSTREAD);
2686
2687                 accept_frame = 1;
2688                 prev_len_adj = 0;
2689                 desc_len = le16toh(current_desc->length);
2690                 status = current_desc->status;
2691                 if (status & E1000_RXD_STAT_EOP) {
2692                         count--;
2693                         eop = 1;
2694                         if (desc_len < ETHER_CRC_LEN) {
2695                                 len = 0;
2696                                 prev_len_adj = ETHER_CRC_LEN - desc_len;
2697                         } else {
2698                                 len = desc_len - ETHER_CRC_LEN;
2699                         }
2700                 } else {
2701                         eop = 0;
2702                         len = desc_len;
2703                 }
2704
2705                 if (current_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK)
2706                         accept_frame = 0;
2707
2708                 if (accept_frame) {
2709                         if (emx_newbuf(sc, i, 0) != 0) {
2710                                 ifp->if_iqdrops++;
2711                                 goto discard;
2712                         }
2713
2714                         /* Assign correct length to the current fragment */
2715                         mp->m_len = len;
2716
2717                         if (sc->fmp == NULL) {
2718                                 mp->m_pkthdr.len = len;
2719                                 sc->fmp = mp; /* Store the first mbuf */
2720                                 sc->lmp = mp;
2721                         } else {
2722                                 /*
2723                                  * Chain mbuf's together
2724                                  */
2725
2726                                 /*
2727                                  * Adjust length of previous mbuf in chain if
2728                                  * we received less than 4 bytes in the last
2729                                  * descriptor.
2730                                  */
2731                                 if (prev_len_adj > 0) {
2732                                         sc->lmp->m_len -= prev_len_adj;
2733                                         sc->fmp->m_pkthdr.len -= prev_len_adj;
2734                                 }
2735                                 sc->lmp->m_next = mp;
2736                                 sc->lmp = sc->lmp->m_next;
2737                                 sc->fmp->m_pkthdr.len += len;
2738                         }
2739
2740                         if (eop) {
2741                                 sc->fmp->m_pkthdr.rcvif = ifp;
2742                                 ifp->if_ipackets++;
2743
2744                                 if (ifp->if_capenable & IFCAP_RXCSUM)
2745                                         emx_rxcsum(sc, current_desc, sc->fmp);
2746
2747                                 if (status & E1000_RXD_STAT_VP) {
2748                                         sc->fmp->m_pkthdr.ether_vlantag =
2749                                             (le16toh(current_desc->special) &
2750                                             E1000_RXD_SPC_VLAN_MASK);
2751                                         sc->fmp->m_flags |= M_VLANTAG;
2752                                 }
2753                                 m = sc->fmp;
2754                                 sc->fmp = NULL;
2755                                 sc->lmp = NULL;
2756                         }
2757                 } else {
2758                         ifp->if_ierrors++;
2759 discard:
2760 #ifdef foo
2761                         /* Reuse loaded DMA map and just update mbuf chain */
2762                         mp = sc->rx_buffer_area[i].m_head;
2763                         mp->m_len = mp->m_pkthdr.len = MCLBYTES;
2764                         mp->m_data = mp->m_ext.ext_buf;
2765                         mp->m_next = NULL;
2766                         if (sc->max_frame_size <= (MCLBYTES - ETHER_ALIGN))
2767                                 m_adj(mp, ETHER_ALIGN);
2768 #endif
2769                         if (sc->fmp != NULL) {
2770                                 m_freem(sc->fmp);
2771                                 sc->fmp = NULL;
2772                                 sc->lmp = NULL;
2773                         }
2774                         m = NULL;
2775                 }
2776
2777                 /* Zero out the receive descriptors status. */
2778                 current_desc->status = 0;
2779
2780                 if (m != NULL)
2781                         ether_input_chain(ifp, m, chain);
2782
2783                 /* Advance our pointers to the next descriptor. */
2784                 if (++i == sc->num_rx_desc)
2785                         i = 0;
2786                 current_desc = &sc->rx_desc_base[i];
2787         }
2788         sc->next_rx_desc_to_check = i;
2789
2790         ether_input_dispatch(chain);
2791
2792         /* Advance the E1000's Receive Queue #0  "Tail Pointer". */
2793         if (--i < 0)
2794                 i = sc->num_rx_desc - 1;
2795         E1000_WRITE_REG(&sc->hw, E1000_RDT(0), i);
2796 }
2797
2798 static void
2799 emx_rxcsum(struct emx_softc *sc, struct e1000_rx_desc *rx_desc,
2800            struct mbuf *mp)
2801 {
2802         /* Ignore Checksum bit is set */
2803         if (rx_desc->status & E1000_RXD_STAT_IXSM)
2804                 return;
2805
2806         if ((rx_desc->status & E1000_RXD_STAT_IPCS) &&
2807             !(rx_desc->errors & E1000_RXD_ERR_IPE))
2808                 mp->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
2809
2810         if ((rx_desc->status & E1000_RXD_STAT_TCPCS) &&
2811             !(rx_desc->errors & E1000_RXD_ERR_TCPE)) {
2812                 mp->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
2813                                            CSUM_PSEUDO_HDR |
2814                                            CSUM_FRAG_NOT_CHECKED;
2815                 mp->m_pkthdr.csum_data = htons(0xffff);
2816         }
2817 }
2818
2819 static void
2820 emx_enable_intr(struct emx_softc *sc)
2821 {
2822         lwkt_serialize_handler_enable(sc->arpcom.ac_if.if_serializer);
2823         E1000_WRITE_REG(&sc->hw, E1000_IMS, IMS_ENABLE_MASK);
2824 }
2825
2826 static void
2827 emx_disable_intr(struct emx_softc *sc)
2828 {
2829         E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
2830         lwkt_serialize_handler_disable(sc->arpcom.ac_if.if_serializer);
2831 }
2832
2833 /*
2834  * Bit of a misnomer, what this really means is
2835  * to enable OS management of the system... aka
2836  * to disable special hardware management features 
2837  */
2838 static void
2839 emx_get_mgmt(struct emx_softc *sc)
2840 {
2841         /* A shared code workaround */
2842         if (sc->has_manage) {
2843                 int manc2h = E1000_READ_REG(&sc->hw, E1000_MANC2H);
2844                 int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
2845
2846                 /* disable hardware interception of ARP */
2847                 manc &= ~(E1000_MANC_ARP_EN);
2848
2849                 /* enable receiving management packets to the host */
2850                 manc |= E1000_MANC_EN_MNG2HOST;
2851 #define E1000_MNG2HOST_PORT_623 (1 << 5)
2852 #define E1000_MNG2HOST_PORT_664 (1 << 6)
2853                 manc2h |= E1000_MNG2HOST_PORT_623;
2854                 manc2h |= E1000_MNG2HOST_PORT_664;
2855                 E1000_WRITE_REG(&sc->hw, E1000_MANC2H, manc2h);
2856
2857                 E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
2858         }
2859 }
2860
2861 /*
2862  * Give control back to hardware management
2863  * controller if there is one.
2864  */
2865 static void
2866 emx_rel_mgmt(struct emx_softc *sc)
2867 {
2868         if (sc->has_manage) {
2869                 int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
2870
2871                 /* re-enable hardware interception of ARP */
2872                 manc |= E1000_MANC_ARP_EN;
2873                 manc &= ~E1000_MANC_EN_MNG2HOST;
2874
2875                 E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
2876         }
2877 }
2878
2879 /*
2880  * emx_get_hw_control() sets {CTRL_EXT|FWSM}:DRV_LOAD bit.
2881  * For ASF and Pass Through versions of f/w this means that
2882  * the driver is loaded.  For AMT version (only with 82573)
2883  * of the f/w this means that the network i/f is open.
2884  */
2885 static void
2886 emx_get_hw_control(struct emx_softc *sc)
2887 {
2888         uint32_t ctrl_ext, swsm;
2889
2890         /* Let firmware know the driver has taken over */
2891         switch (sc->hw.mac.type) {
2892         case e1000_82573:
2893                 swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
2894                 E1000_WRITE_REG(&sc->hw, E1000_SWSM,
2895                     swsm | E1000_SWSM_DRV_LOAD);
2896                 break;
2897
2898         case e1000_82571:
2899         case e1000_82572:
2900         case e1000_80003es2lan:
2901                 ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
2902                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
2903                     ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
2904                 break;
2905
2906         default:
2907                 break;
2908         }
2909 }
2910
2911 /*
2912  * emx_rel_hw_control() resets {CTRL_EXT|FWSM}:DRV_LOAD bit.
2913  * For ASF and Pass Through versions of f/w this means that the
2914  * driver is no longer loaded.  For AMT version (only with 82573)
2915  * of the f/w this means that the network i/f is closed.
2916  */
2917 static void
2918 emx_rel_hw_control(struct emx_softc *sc)
2919 {
2920         uint32_t ctrl_ext, swsm;
2921
2922         /* Let firmware taken over control of h/w */
2923         switch (sc->hw.mac.type) {
2924         case e1000_82573:
2925                 swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
2926                 E1000_WRITE_REG(&sc->hw, E1000_SWSM,
2927                     swsm & ~E1000_SWSM_DRV_LOAD);
2928                 break;
2929
2930         case e1000_82571:
2931         case e1000_82572:
2932         case e1000_80003es2lan:
2933                 ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
2934                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
2935                     ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
2936                 break;
2937
2938         default:
2939                 break;
2940         }
2941 }
2942
2943 static int
2944 emx_is_valid_eaddr(const uint8_t *addr)
2945 {
2946         char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
2947
2948         if ((addr[0] & 1) || !bcmp(addr, zero_addr, ETHER_ADDR_LEN))
2949                 return (FALSE);
2950
2951         return (TRUE);
2952 }
2953
2954 /*
2955  * Enable PCI Wake On Lan capability
2956  */
2957 void
2958 emx_enable_wol(device_t dev)
2959 {
2960         uint16_t cap, status;
2961         uint8_t id;
2962
2963         /* First find the capabilities pointer*/
2964         cap = pci_read_config(dev, PCIR_CAP_PTR, 2);
2965
2966         /* Read the PM Capabilities */
2967         id = pci_read_config(dev, cap, 1);
2968         if (id != PCIY_PMG)     /* Something wrong */
2969                 return;
2970
2971         /*
2972          * OK, we have the power capabilities,
2973          * so now get the status register
2974          */
2975         cap += PCIR_POWER_STATUS;
2976         status = pci_read_config(dev, cap, 2);
2977         status |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
2978         pci_write_config(dev, cap, status, 2);
2979 }
2980
2981 static void
2982 emx_update_stats(struct emx_softc *sc)
2983 {
2984         struct ifnet *ifp = &sc->arpcom.ac_if;
2985
2986         if (sc->hw.phy.media_type == e1000_media_type_copper ||
2987             (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_LU)) {
2988                 sc->stats.symerrs += E1000_READ_REG(&sc->hw, E1000_SYMERRS);
2989                 sc->stats.sec += E1000_READ_REG(&sc->hw, E1000_SEC);
2990         }
2991         sc->stats.crcerrs += E1000_READ_REG(&sc->hw, E1000_CRCERRS);
2992         sc->stats.mpc += E1000_READ_REG(&sc->hw, E1000_MPC);
2993         sc->stats.scc += E1000_READ_REG(&sc->hw, E1000_SCC);
2994         sc->stats.ecol += E1000_READ_REG(&sc->hw, E1000_ECOL);
2995
2996         sc->stats.mcc += E1000_READ_REG(&sc->hw, E1000_MCC);
2997         sc->stats.latecol += E1000_READ_REG(&sc->hw, E1000_LATECOL);
2998         sc->stats.colc += E1000_READ_REG(&sc->hw, E1000_COLC);
2999         sc->stats.dc += E1000_READ_REG(&sc->hw, E1000_DC);
3000         sc->stats.rlec += E1000_READ_REG(&sc->hw, E1000_RLEC);
3001         sc->stats.xonrxc += E1000_READ_REG(&sc->hw, E1000_XONRXC);
3002         sc->stats.xontxc += E1000_READ_REG(&sc->hw, E1000_XONTXC);
3003         sc->stats.xoffrxc += E1000_READ_REG(&sc->hw, E1000_XOFFRXC);
3004         sc->stats.xofftxc += E1000_READ_REG(&sc->hw, E1000_XOFFTXC);
3005         sc->stats.fcruc += E1000_READ_REG(&sc->hw, E1000_FCRUC);
3006         sc->stats.prc64 += E1000_READ_REG(&sc->hw, E1000_PRC64);
3007         sc->stats.prc127 += E1000_READ_REG(&sc->hw, E1000_PRC127);
3008         sc->stats.prc255 += E1000_READ_REG(&sc->hw, E1000_PRC255);
3009         sc->stats.prc511 += E1000_READ_REG(&sc->hw, E1000_PRC511);
3010         sc->stats.prc1023 += E1000_READ_REG(&sc->hw, E1000_PRC1023);
3011         sc->stats.prc1522 += E1000_READ_REG(&sc->hw, E1000_PRC1522);
3012         sc->stats.gprc += E1000_READ_REG(&sc->hw, E1000_GPRC);
3013         sc->stats.bprc += E1000_READ_REG(&sc->hw, E1000_BPRC);
3014         sc->stats.mprc += E1000_READ_REG(&sc->hw, E1000_MPRC);
3015         sc->stats.gptc += E1000_READ_REG(&sc->hw, E1000_GPTC);
3016
3017         /* For the 64-bit byte counters the low dword must be read first. */
3018         /* Both registers clear on the read of the high dword */
3019
3020         sc->stats.gorc += E1000_READ_REG(&sc->hw, E1000_GORCH);
3021         sc->stats.gotc += E1000_READ_REG(&sc->hw, E1000_GOTCH);
3022
3023         sc->stats.rnbc += E1000_READ_REG(&sc->hw, E1000_RNBC);
3024         sc->stats.ruc += E1000_READ_REG(&sc->hw, E1000_RUC);
3025         sc->stats.rfc += E1000_READ_REG(&sc->hw, E1000_RFC);
3026         sc->stats.roc += E1000_READ_REG(&sc->hw, E1000_ROC);
3027         sc->stats.rjc += E1000_READ_REG(&sc->hw, E1000_RJC);
3028
3029         sc->stats.tor += E1000_READ_REG(&sc->hw, E1000_TORH);
3030         sc->stats.tot += E1000_READ_REG(&sc->hw, E1000_TOTH);
3031
3032         sc->stats.tpr += E1000_READ_REG(&sc->hw, E1000_TPR);
3033         sc->stats.tpt += E1000_READ_REG(&sc->hw, E1000_TPT);
3034         sc->stats.ptc64 += E1000_READ_REG(&sc->hw, E1000_PTC64);
3035         sc->stats.ptc127 += E1000_READ_REG(&sc->hw, E1000_PTC127);
3036         sc->stats.ptc255 += E1000_READ_REG(&sc->hw, E1000_PTC255);
3037         sc->stats.ptc511 += E1000_READ_REG(&sc->hw, E1000_PTC511);
3038         sc->stats.ptc1023 += E1000_READ_REG(&sc->hw, E1000_PTC1023);
3039         sc->stats.ptc1522 += E1000_READ_REG(&sc->hw, E1000_PTC1522);
3040         sc->stats.mptc += E1000_READ_REG(&sc->hw, E1000_MPTC);
3041         sc->stats.bptc += E1000_READ_REG(&sc->hw, E1000_BPTC);
3042
3043         sc->stats.algnerrc += E1000_READ_REG(&sc->hw, E1000_ALGNERRC);
3044         sc->stats.rxerrc += E1000_READ_REG(&sc->hw, E1000_RXERRC);
3045         sc->stats.tncrs += E1000_READ_REG(&sc->hw, E1000_TNCRS);
3046         sc->stats.cexterr += E1000_READ_REG(&sc->hw, E1000_CEXTERR);
3047         sc->stats.tsctc += E1000_READ_REG(&sc->hw, E1000_TSCTC);
3048         sc->stats.tsctfc += E1000_READ_REG(&sc->hw, E1000_TSCTFC);
3049
3050         ifp->if_collisions = sc->stats.colc;
3051
3052         /* Rx Errors */
3053         ifp->if_ierrors = sc->dropped_pkts + sc->stats.rxerrc +
3054                           sc->stats.crcerrs + sc->stats.algnerrc +
3055                           sc->stats.ruc + sc->stats.roc +
3056                           sc->stats.mpc + sc->stats.cexterr;
3057
3058         /* Tx Errors */
3059         ifp->if_oerrors = sc->stats.ecol + sc->stats.latecol +
3060                           sc->watchdog_events;
3061 }
3062
3063 static void
3064 emx_print_debug_info(struct emx_softc *sc)
3065 {
3066         device_t dev = sc->dev;
3067         uint8_t *hw_addr = sc->hw.hw_addr;
3068
3069         device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
3070         device_printf(dev, "CTRL = 0x%x RCTL = 0x%x \n",
3071             E1000_READ_REG(&sc->hw, E1000_CTRL),
3072             E1000_READ_REG(&sc->hw, E1000_RCTL));
3073         device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk \n",
3074             ((E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff0000) >> 16),\
3075             (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) );
3076         device_printf(dev, "Flow control watermarks high = %d low = %d\n",
3077             sc->hw.fc.high_water, sc->hw.fc.low_water);
3078         device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
3079             E1000_READ_REG(&sc->hw, E1000_TIDV),
3080             E1000_READ_REG(&sc->hw, E1000_TADV));
3081         device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
3082             E1000_READ_REG(&sc->hw, E1000_RDTR),
3083             E1000_READ_REG(&sc->hw, E1000_RADV));
3084         device_printf(dev, "hw tdh = %d, hw tdt = %d\n",
3085             E1000_READ_REG(&sc->hw, E1000_TDH(0)),
3086             E1000_READ_REG(&sc->hw, E1000_TDT(0)));
3087         device_printf(dev, "hw rdh = %d, hw rdt = %d\n",
3088             E1000_READ_REG(&sc->hw, E1000_RDH(0)),
3089             E1000_READ_REG(&sc->hw, E1000_RDT(0)));
3090         device_printf(dev, "Num Tx descriptors avail = %d\n",
3091             sc->num_tx_desc_avail);
3092         device_printf(dev, "Tx Descriptors not avail1 = %ld\n",
3093             sc->no_tx_desc_avail1);
3094         device_printf(dev, "Tx Descriptors not avail2 = %ld\n",
3095             sc->no_tx_desc_avail2);
3096         device_printf(dev, "Std mbuf failed = %ld\n",
3097             sc->mbuf_alloc_failed);
3098         device_printf(dev, "Std mbuf cluster failed = %ld\n",
3099             sc->mbuf_cluster_failed);
3100         device_printf(dev, "Driver dropped packets = %ld\n",
3101             sc->dropped_pkts);
3102         device_printf(dev, "Driver tx dma failure in encap = %ld\n",
3103             sc->no_tx_dma_setup);
3104
3105         device_printf(dev, "TXCSUM try pullup = %lu\n",
3106             sc->tx_csum_try_pullup);
3107         device_printf(dev, "TXCSUM m_pullup(eh) called = %lu\n",
3108             sc->tx_csum_pullup1);
3109         device_printf(dev, "TXCSUM m_pullup(eh) failed = %lu\n",
3110             sc->tx_csum_pullup1_failed);
3111         device_printf(dev, "TXCSUM m_pullup(eh+ip) called = %lu\n",
3112             sc->tx_csum_pullup2);
3113         device_printf(dev, "TXCSUM m_pullup(eh+ip) failed = %lu\n",
3114             sc->tx_csum_pullup2_failed);
3115         device_printf(dev, "TXCSUM non-writable(eh) droped = %lu\n",
3116             sc->tx_csum_drop1);
3117         device_printf(dev, "TXCSUM non-writable(eh+ip) droped = %lu\n",
3118             sc->tx_csum_drop2);
3119 }
3120
3121 static void
3122 emx_print_hw_stats(struct emx_softc *sc)
3123 {
3124         device_t dev = sc->dev;
3125
3126         device_printf(dev, "Excessive collisions = %lld\n",
3127             (long long)sc->stats.ecol);
3128 #if (DEBUG_HW > 0)  /* Dont output these errors normally */
3129         device_printf(dev, "Symbol errors = %lld\n",
3130             (long long)sc->stats.symerrs);
3131 #endif
3132         device_printf(dev, "Sequence errors = %lld\n",
3133             (long long)sc->stats.sec);
3134         device_printf(dev, "Defer count = %lld\n",
3135             (long long)sc->stats.dc);
3136         device_printf(dev, "Missed Packets = %lld\n",
3137             (long long)sc->stats.mpc);
3138         device_printf(dev, "Receive No Buffers = %lld\n",
3139             (long long)sc->stats.rnbc);
3140         /* RLEC is inaccurate on some hardware, calculate our own. */
3141         device_printf(dev, "Receive Length Errors = %lld\n",
3142             ((long long)sc->stats.roc + (long long)sc->stats.ruc));
3143         device_printf(dev, "Receive errors = %lld\n",
3144             (long long)sc->stats.rxerrc);
3145         device_printf(dev, "Crc errors = %lld\n",
3146             (long long)sc->stats.crcerrs);
3147         device_printf(dev, "Alignment errors = %lld\n",
3148             (long long)sc->stats.algnerrc);
3149         device_printf(dev, "Collision/Carrier extension errors = %lld\n",
3150             (long long)sc->stats.cexterr);
3151         device_printf(dev, "RX overruns = %ld\n", sc->rx_overruns);
3152         device_printf(dev, "watchdog timeouts = %ld\n",
3153             sc->watchdog_events);
3154         device_printf(dev, "XON Rcvd = %lld\n",
3155             (long long)sc->stats.xonrxc);
3156         device_printf(dev, "XON Xmtd = %lld\n",
3157             (long long)sc->stats.xontxc);
3158         device_printf(dev, "XOFF Rcvd = %lld\n",
3159             (long long)sc->stats.xoffrxc);
3160         device_printf(dev, "XOFF Xmtd = %lld\n",
3161             (long long)sc->stats.xofftxc);
3162         device_printf(dev, "Good Packets Rcvd = %lld\n",
3163             (long long)sc->stats.gprc);
3164         device_printf(dev, "Good Packets Xmtd = %lld\n",
3165             (long long)sc->stats.gptc);
3166 }
3167
3168 static void
3169 emx_print_nvm_info(struct emx_softc *sc)
3170 {
3171         uint16_t eeprom_data;
3172         int i, j, row = 0;
3173
3174         /* Its a bit crude, but it gets the job done */
3175         kprintf("\nInterface EEPROM Dump:\n");
3176         kprintf("Offset\n0x0000  ");
3177         for (i = 0, j = 0; i < 32; i++, j++) {
3178                 if (j == 8) { /* Make the offset block */
3179                         j = 0; ++row;
3180                         kprintf("\n0x00%x0  ",row);
3181                 }
3182                 e1000_read_nvm(&sc->hw, i, 1, &eeprom_data);
3183                 kprintf("%04x ", eeprom_data);
3184         }
3185         kprintf("\n");
3186 }
3187
3188 static int
3189 emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
3190 {
3191         struct emx_softc *sc;
3192         struct ifnet *ifp;
3193         int error, result;
3194
3195         result = -1;
3196         error = sysctl_handle_int(oidp, &result, 0, req);
3197         if (error || !req->newptr)
3198                 return (error);
3199
3200         sc = (struct emx_softc *)arg1;
3201         ifp = &sc->arpcom.ac_if;
3202
3203         lwkt_serialize_enter(ifp->if_serializer);
3204
3205         if (result == 1)
3206                 emx_print_debug_info(sc);
3207
3208         /*
3209          * This value will cause a hex dump of the
3210          * first 32 16-bit words of the EEPROM to
3211          * the screen.
3212          */
3213         if (result == 2)
3214                 emx_print_nvm_info(sc);
3215
3216         lwkt_serialize_exit(ifp->if_serializer);
3217
3218         return (error);
3219 }
3220
3221 static int
3222 emx_sysctl_stats(SYSCTL_HANDLER_ARGS)
3223 {
3224         int error, result;
3225
3226         result = -1;
3227         error = sysctl_handle_int(oidp, &result, 0, req);
3228         if (error || !req->newptr)
3229                 return (error);
3230
3231         if (result == 1) {
3232                 struct emx_softc *sc = (struct emx_softc *)arg1;
3233                 struct ifnet *ifp = &sc->arpcom.ac_if;
3234
3235                 lwkt_serialize_enter(ifp->if_serializer);
3236                 emx_print_hw_stats(sc);
3237                 lwkt_serialize_exit(ifp->if_serializer);
3238         }
3239         return (error);
3240 }
3241
3242 static void
3243 emx_add_sysctl(struct emx_softc *sc)
3244 {
3245 #ifdef PROFILE_SERIALIZER
3246         struct ifnet *ifp = &sc->arpcom.ac_if;
3247 #endif
3248
3249         sysctl_ctx_init(&sc->sysctl_ctx);
3250         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
3251                                 SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
3252                                 device_get_nameunit(sc->dev),
3253                                 CTLFLAG_RD, 0, "");
3254         if (sc->sysctl_tree == NULL) {
3255                 device_printf(sc->dev, "can't add sysctl node\n");
3256                 return;
3257         }
3258
3259         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3260                         OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3261                         emx_sysctl_debug_info, "I", "Debug Information");
3262
3263         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3264                         OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3265                         emx_sysctl_stats, "I", "Statistics");
3266
3267         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3268                         OID_AUTO, "rxd", CTLFLAG_RD, &sc->num_rx_desc, 0, NULL);
3269         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3270                         OID_AUTO, "txd", CTLFLAG_RD, &sc->num_tx_desc, 0, NULL);
3271
3272 #ifdef PROFILE_SERIALIZER
3273         SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3274                         OID_AUTO, "serializer_sleep", CTLFLAG_RW,
3275                         &ifp->if_serializer->sleep_cnt, 0, NULL);
3276         SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3277                         OID_AUTO, "serializer_tryfail", CTLFLAG_RW,
3278                         &ifp->if_serializer->tryfail_cnt, 0, NULL);
3279         SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3280                         OID_AUTO, "serializer_enter", CTLFLAG_RW,
3281                         &ifp->if_serializer->enter_cnt, 0, NULL);
3282         SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3283                         OID_AUTO, "serializer_try", CTLFLAG_RW,
3284                         &ifp->if_serializer->try_cnt, 0, NULL);
3285 #endif
3286
3287         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3288                         OID_AUTO, "int_throttle_ceil", CTLTYPE_INT|CTLFLAG_RW,
3289                         sc, 0, emx_sysctl_int_throttle, "I",
3290                         "interrupt throttling rate");
3291         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3292                         OID_AUTO, "int_tx_nsegs", CTLTYPE_INT|CTLFLAG_RW,
3293                         sc, 0, emx_sysctl_int_tx_nsegs, "I",
3294                         "# segments per TX interrupt");
3295 }
3296
3297 static int
3298 emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
3299 {
3300         struct emx_softc *sc = (void *)arg1;
3301         struct ifnet *ifp = &sc->arpcom.ac_if;
3302         int error, throttle;
3303
3304         throttle = sc->int_throttle_ceil;
3305         error = sysctl_handle_int(oidp, &throttle, 0, req);
3306         if (error || req->newptr == NULL)
3307                 return error;
3308         if (throttle < 0 || throttle > 1000000000 / 256)
3309                 return EINVAL;
3310
3311         if (throttle) {
3312                 /*
3313                  * Set the interrupt throttling rate in 256ns increments,
3314                  * recalculate sysctl value assignment to get exact frequency.
3315                  */
3316                 throttle = 1000000000 / 256 / throttle;
3317
3318                 /* Upper 16bits of ITR is reserved and should be zero */
3319                 if (throttle & 0xffff0000)
3320                         return EINVAL;
3321         }
3322
3323         lwkt_serialize_enter(ifp->if_serializer);
3324
3325         if (throttle)
3326                 sc->int_throttle_ceil = 1000000000 / 256 / throttle;
3327         else
3328                 sc->int_throttle_ceil = 0;
3329
3330         if (ifp->if_flags & IFF_RUNNING)
3331                 E1000_WRITE_REG(&sc->hw, E1000_ITR, throttle);
3332
3333         lwkt_serialize_exit(ifp->if_serializer);
3334
3335         if (bootverbose) {
3336                 if_printf(ifp, "Interrupt moderation set to %d/sec\n",
3337                           sc->int_throttle_ceil);
3338         }
3339         return 0;
3340 }
3341
3342 static int
3343 emx_sysctl_int_tx_nsegs(SYSCTL_HANDLER_ARGS)
3344 {
3345         struct emx_softc *sc = (void *)arg1;
3346         struct ifnet *ifp = &sc->arpcom.ac_if;
3347         int error, segs;
3348
3349         segs = sc->tx_int_nsegs;
3350         error = sysctl_handle_int(oidp, &segs, 0, req);
3351         if (error || req->newptr == NULL)
3352                 return error;
3353         if (segs <= 0)
3354                 return EINVAL;
3355
3356         lwkt_serialize_enter(ifp->if_serializer);
3357
3358         /*
3359          * Don't allow int_tx_nsegs to become:
3360          * o  Less the oact_tx_desc
3361          * o  Too large that no TX desc will cause TX interrupt to
3362          *    be generated (OACTIVE will never recover)
3363          * o  Too small that will cause tx_dd[] overflow
3364          */
3365         if (segs < sc->oact_tx_desc ||
3366             segs >= sc->num_tx_desc - sc->oact_tx_desc ||
3367             segs < sc->num_tx_desc / EMX_TXDD_SAFE) {
3368                 error = EINVAL;
3369         } else {
3370                 error = 0;
3371                 sc->tx_int_nsegs = segs;
3372         }
3373
3374         lwkt_serialize_exit(ifp->if_serializer);
3375
3376         return error;
3377 }