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