kernel: Move us to using M_NOWAIT and M_WAITOK for mbuf 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_ifpoll.h"
68 #include "opt_emx.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/serialize2.h>
82 #include <sys/socket.h>
83 #include <sys/sockio.h>
84 #include <sys/sysctl.h>
85 #include <sys/systm.h>
86
87 #include <net/bpf.h>
88 #include <net/ethernet.h>
89 #include <net/if.h>
90 #include <net/if_arp.h>
91 #include <net/if_dl.h>
92 #include <net/if_media.h>
93 #include <net/ifq_var.h>
94 #include <net/toeplitz.h>
95 #include <net/toeplitz2.h>
96 #include <net/vlan/if_vlan_var.h>
97 #include <net/vlan/if_vlan_ether.h>
98 #include <net/if_poll.h>
99
100 #include <netinet/in_systm.h>
101 #include <netinet/in.h>
102 #include <netinet/ip.h>
103 #include <netinet/tcp.h>
104 #include <netinet/udp.h>
105
106 #include <bus/pci/pcivar.h>
107 #include <bus/pci/pcireg.h>
108
109 #include <dev/netif/ig_hal/e1000_api.h>
110 #include <dev/netif/ig_hal/e1000_82571.h>
111 #include <dev/netif/emx/if_emx.h>
112
113 #define DEBUG_HW 0
114
115 #ifdef EMX_RSS_DEBUG
116 #define EMX_RSS_DPRINTF(sc, lvl, fmt, ...) \
117 do { \
118         if (sc->rss_debug >= lvl) \
119                 if_printf(&sc->arpcom.ac_if, fmt, __VA_ARGS__); \
120 } while (0)
121 #else   /* !EMX_RSS_DEBUG */
122 #define EMX_RSS_DPRINTF(sc, lvl, fmt, ...)      ((void)0)
123 #endif  /* EMX_RSS_DEBUG */
124
125 #define EMX_NAME        "Intel(R) PRO/1000 "
126
127 #define EMX_DEVICE(id)  \
128         { EMX_VENDOR_ID, E1000_DEV_ID_##id, EMX_NAME #id }
129 #define EMX_DEVICE_NULL { 0, 0, NULL }
130
131 static const struct emx_device {
132         uint16_t        vid;
133         uint16_t        did;
134         const char      *desc;
135 } emx_devices[] = {
136         EMX_DEVICE(82571EB_COPPER),
137         EMX_DEVICE(82571EB_FIBER),
138         EMX_DEVICE(82571EB_SERDES),
139         EMX_DEVICE(82571EB_SERDES_DUAL),
140         EMX_DEVICE(82571EB_SERDES_QUAD),
141         EMX_DEVICE(82571EB_QUAD_COPPER),
142         EMX_DEVICE(82571EB_QUAD_COPPER_BP),
143         EMX_DEVICE(82571EB_QUAD_COPPER_LP),
144         EMX_DEVICE(82571EB_QUAD_FIBER),
145         EMX_DEVICE(82571PT_QUAD_COPPER),
146
147         EMX_DEVICE(82572EI_COPPER),
148         EMX_DEVICE(82572EI_FIBER),
149         EMX_DEVICE(82572EI_SERDES),
150         EMX_DEVICE(82572EI),
151
152         EMX_DEVICE(82573E),
153         EMX_DEVICE(82573E_IAMT),
154         EMX_DEVICE(82573L),
155
156         EMX_DEVICE(80003ES2LAN_COPPER_SPT),
157         EMX_DEVICE(80003ES2LAN_SERDES_SPT),
158         EMX_DEVICE(80003ES2LAN_COPPER_DPT),
159         EMX_DEVICE(80003ES2LAN_SERDES_DPT),
160
161         EMX_DEVICE(82574L),
162         EMX_DEVICE(82574LA),
163
164         EMX_DEVICE(PCH_LPT_I217_LM),
165         EMX_DEVICE(PCH_LPT_I217_V),
166         EMX_DEVICE(PCH_LPTLP_I218_LM),
167         EMX_DEVICE(PCH_LPTLP_I218_V),
168         EMX_DEVICE(PCH_I218_LM2),
169         EMX_DEVICE(PCH_I218_V2),
170         EMX_DEVICE(PCH_I218_LM3),
171         EMX_DEVICE(PCH_I218_V3),
172
173         /* required last entry */
174         EMX_DEVICE_NULL
175 };
176
177 static int      emx_probe(device_t);
178 static int      emx_attach(device_t);
179 static int      emx_detach(device_t);
180 static int      emx_shutdown(device_t);
181 static int      emx_suspend(device_t);
182 static int      emx_resume(device_t);
183
184 static void     emx_init(void *);
185 static void     emx_stop(struct emx_softc *);
186 static int      emx_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
187 static void     emx_start(struct ifnet *, struct ifaltq_subque *);
188 #ifdef IFPOLL_ENABLE
189 static void     emx_npoll(struct ifnet *, struct ifpoll_info *);
190 static void     emx_npoll_status(struct ifnet *);
191 static void     emx_npoll_tx(struct ifnet *, void *, int);
192 static void     emx_npoll_rx(struct ifnet *, void *, int);
193 #endif
194 static void     emx_watchdog(struct ifaltq_subque *);
195 static void     emx_media_status(struct ifnet *, struct ifmediareq *);
196 static int      emx_media_change(struct ifnet *);
197 static void     emx_timer(void *);
198 static void     emx_serialize(struct ifnet *, enum ifnet_serialize);
199 static void     emx_deserialize(struct ifnet *, enum ifnet_serialize);
200 static int      emx_tryserialize(struct ifnet *, enum ifnet_serialize);
201 #ifdef INVARIANTS
202 static void     emx_serialize_assert(struct ifnet *, enum ifnet_serialize,
203                     boolean_t);
204 #endif
205
206 static void     emx_intr(void *);
207 static void     emx_intr_mask(void *);
208 static void     emx_intr_body(struct emx_softc *, boolean_t);
209 static void     emx_rxeof(struct emx_rxdata *, int);
210 static void     emx_txeof(struct emx_txdata *);
211 static void     emx_tx_collect(struct emx_txdata *);
212 static void     emx_tx_purge(struct emx_softc *);
213 static void     emx_enable_intr(struct emx_softc *);
214 static void     emx_disable_intr(struct emx_softc *);
215
216 static int      emx_dma_alloc(struct emx_softc *);
217 static void     emx_dma_free(struct emx_softc *);
218 static void     emx_init_tx_ring(struct emx_txdata *);
219 static int      emx_init_rx_ring(struct emx_rxdata *);
220 static void     emx_free_tx_ring(struct emx_txdata *);
221 static void     emx_free_rx_ring(struct emx_rxdata *);
222 static int      emx_create_tx_ring(struct emx_txdata *);
223 static int      emx_create_rx_ring(struct emx_rxdata *);
224 static void     emx_destroy_tx_ring(struct emx_txdata *, int);
225 static void     emx_destroy_rx_ring(struct emx_rxdata *, int);
226 static int      emx_newbuf(struct emx_rxdata *, int, int);
227 static int      emx_encap(struct emx_txdata *, struct mbuf **, int *, int *);
228 static int      emx_txcsum(struct emx_txdata *, struct mbuf *,
229                     uint32_t *, uint32_t *);
230 static int      emx_tso_pullup(struct emx_txdata *, struct mbuf **);
231 static int      emx_tso_setup(struct emx_txdata *, struct mbuf *,
232                     uint32_t *, uint32_t *);
233 static int      emx_get_txring_inuse(const struct emx_softc *, boolean_t);
234
235 static int      emx_is_valid_eaddr(const uint8_t *);
236 static int      emx_reset(struct emx_softc *);
237 static void     emx_setup_ifp(struct emx_softc *);
238 static void     emx_init_tx_unit(struct emx_softc *);
239 static void     emx_init_rx_unit(struct emx_softc *);
240 static void     emx_update_stats(struct emx_softc *);
241 static void     emx_set_promisc(struct emx_softc *);
242 static void     emx_disable_promisc(struct emx_softc *);
243 static void     emx_set_multi(struct emx_softc *);
244 static void     emx_update_link_status(struct emx_softc *);
245 static void     emx_smartspeed(struct emx_softc *);
246 static void     emx_set_itr(struct emx_softc *, uint32_t);
247 static void     emx_disable_aspm(struct emx_softc *);
248
249 static void     emx_print_debug_info(struct emx_softc *);
250 static void     emx_print_nvm_info(struct emx_softc *);
251 static void     emx_print_hw_stats(struct emx_softc *);
252
253 static int      emx_sysctl_stats(SYSCTL_HANDLER_ARGS);
254 static int      emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS);
255 static int      emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS);
256 static int      emx_sysctl_tx_intr_nsegs(SYSCTL_HANDLER_ARGS);
257 static int      emx_sysctl_tx_wreg_nsegs(SYSCTL_HANDLER_ARGS);
258 #ifdef IFPOLL_ENABLE
259 static int      emx_sysctl_npoll_rxoff(SYSCTL_HANDLER_ARGS);
260 static int      emx_sysctl_npoll_txoff(SYSCTL_HANDLER_ARGS);
261 #endif
262 static void     emx_add_sysctl(struct emx_softc *);
263
264 static void     emx_serialize_skipmain(struct emx_softc *);
265 static void     emx_deserialize_skipmain(struct emx_softc *);
266
267 /* Management and WOL Support */
268 static void     emx_get_mgmt(struct emx_softc *);
269 static void     emx_rel_mgmt(struct emx_softc *);
270 static void     emx_get_hw_control(struct emx_softc *);
271 static void     emx_rel_hw_control(struct emx_softc *);
272 static void     emx_enable_wol(device_t);
273
274 static device_method_t emx_methods[] = {
275         /* Device interface */
276         DEVMETHOD(device_probe,         emx_probe),
277         DEVMETHOD(device_attach,        emx_attach),
278         DEVMETHOD(device_detach,        emx_detach),
279         DEVMETHOD(device_shutdown,      emx_shutdown),
280         DEVMETHOD(device_suspend,       emx_suspend),
281         DEVMETHOD(device_resume,        emx_resume),
282         DEVMETHOD_END
283 };
284
285 static driver_t emx_driver = {
286         "emx",
287         emx_methods,
288         sizeof(struct emx_softc),
289 };
290
291 static devclass_t emx_devclass;
292
293 DECLARE_DUMMY_MODULE(if_emx);
294 MODULE_DEPEND(emx, ig_hal, 1, 1, 1);
295 DRIVER_MODULE(if_emx, pci, emx_driver, emx_devclass, NULL, NULL);
296
297 /*
298  * Tunables
299  */
300 static int      emx_int_throttle_ceil = EMX_DEFAULT_ITR;
301 static int      emx_rxd = EMX_DEFAULT_RXD;
302 static int      emx_txd = EMX_DEFAULT_TXD;
303 static int      emx_smart_pwr_down = 0;
304 static int      emx_rxr = 0;
305 static int      emx_txr = 1;
306
307 /* Controls whether promiscuous also shows bad packets */
308 static int      emx_debug_sbp = 0;
309
310 static int      emx_82573_workaround = 1;
311 static int      emx_msi_enable = 1;
312
313 TUNABLE_INT("hw.emx.int_throttle_ceil", &emx_int_throttle_ceil);
314 TUNABLE_INT("hw.emx.rxd", &emx_rxd);
315 TUNABLE_INT("hw.emx.rxr", &emx_rxr);
316 TUNABLE_INT("hw.emx.txd", &emx_txd);
317 TUNABLE_INT("hw.emx.txr", &emx_txr);
318 TUNABLE_INT("hw.emx.smart_pwr_down", &emx_smart_pwr_down);
319 TUNABLE_INT("hw.emx.sbp", &emx_debug_sbp);
320 TUNABLE_INT("hw.emx.82573_workaround", &emx_82573_workaround);
321 TUNABLE_INT("hw.emx.msi.enable", &emx_msi_enable);
322
323 /* Global used in WOL setup with multiport cards */
324 static int      emx_global_quad_port_a = 0;
325
326 /* Set this to one to display debug statistics */
327 static int      emx_display_debug_stats = 0;
328
329 #if !defined(KTR_IF_EMX)
330 #define KTR_IF_EMX      KTR_ALL
331 #endif
332 KTR_INFO_MASTER(if_emx);
333 KTR_INFO(KTR_IF_EMX, if_emx, intr_beg, 0, "intr begin");
334 KTR_INFO(KTR_IF_EMX, if_emx, intr_end, 1, "intr end");
335 KTR_INFO(KTR_IF_EMX, if_emx, pkt_receive, 4, "rx packet");
336 KTR_INFO(KTR_IF_EMX, if_emx, pkt_txqueue, 5, "tx packet");
337 KTR_INFO(KTR_IF_EMX, if_emx, pkt_txclean, 6, "tx clean");
338 #define logif(name)     KTR_LOG(if_emx_ ## name)
339
340 static __inline void
341 emx_setup_rxdesc(emx_rxdesc_t *rxd, const struct emx_rxbuf *rxbuf)
342 {
343         rxd->rxd_bufaddr = htole64(rxbuf->paddr);
344         /* DD bit must be cleared */
345         rxd->rxd_staterr = 0;
346 }
347
348 static __inline void
349 emx_rxcsum(uint32_t staterr, struct mbuf *mp)
350 {
351         /* Ignore Checksum bit is set */
352         if (staterr & E1000_RXD_STAT_IXSM)
353                 return;
354
355         if ((staterr & (E1000_RXD_STAT_IPCS | E1000_RXDEXT_STATERR_IPE)) ==
356             E1000_RXD_STAT_IPCS)
357                 mp->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
358
359         if ((staterr & (E1000_RXD_STAT_TCPCS | E1000_RXDEXT_STATERR_TCPE)) ==
360             E1000_RXD_STAT_TCPCS) {
361                 mp->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
362                                            CSUM_PSEUDO_HDR |
363                                            CSUM_FRAG_NOT_CHECKED;
364                 mp->m_pkthdr.csum_data = htons(0xffff);
365         }
366 }
367
368 static __inline struct pktinfo *
369 emx_rssinfo(struct mbuf *m, struct pktinfo *pi,
370             uint32_t mrq, uint32_t hash, uint32_t staterr)
371 {
372         switch (mrq & EMX_RXDMRQ_RSSTYPE_MASK) {
373         case EMX_RXDMRQ_IPV4_TCP:
374                 pi->pi_netisr = NETISR_IP;
375                 pi->pi_flags = 0;
376                 pi->pi_l3proto = IPPROTO_TCP;
377                 break;
378
379         case EMX_RXDMRQ_IPV6_TCP:
380                 pi->pi_netisr = NETISR_IPV6;
381                 pi->pi_flags = 0;
382                 pi->pi_l3proto = IPPROTO_TCP;
383                 break;
384
385         case EMX_RXDMRQ_IPV4:
386                 if (staterr & E1000_RXD_STAT_IXSM)
387                         return NULL;
388
389                 if ((staterr &
390                      (E1000_RXD_STAT_TCPCS | E1000_RXDEXT_STATERR_TCPE)) ==
391                     E1000_RXD_STAT_TCPCS) {
392                         pi->pi_netisr = NETISR_IP;
393                         pi->pi_flags = 0;
394                         pi->pi_l3proto = IPPROTO_UDP;
395                         break;
396                 }
397                 /* FALL THROUGH */
398         default:
399                 return NULL;
400         }
401
402         m->m_flags |= M_HASH;
403         m->m_pkthdr.hash = toeplitz_hash(hash);
404         return pi;
405 }
406
407 static int
408 emx_probe(device_t dev)
409 {
410         const struct emx_device *d;
411         uint16_t vid, did;
412
413         vid = pci_get_vendor(dev);
414         did = pci_get_device(dev);
415
416         for (d = emx_devices; d->desc != NULL; ++d) {
417                 if (vid == d->vid && did == d->did) {
418                         device_set_desc(dev, d->desc);
419                         device_set_async_attach(dev, TRUE);
420                         return 0;
421                 }
422         }
423         return ENXIO;
424 }
425
426 static int
427 emx_attach(device_t dev)
428 {
429         struct emx_softc *sc = device_get_softc(dev);
430         int error = 0, i, throttle, msi_enable, tx_ring_max;
431         u_int intr_flags;
432         uint16_t eeprom_data, device_id, apme_mask;
433         driver_intr_t *intr_func;
434 #ifdef IFPOLL_ENABLE
435         int offset, offset_def;
436 #endif
437
438         /*
439          * Setup RX rings
440          */
441         for (i = 0; i < EMX_NRX_RING; ++i) {
442                 sc->rx_data[i].sc = sc;
443                 sc->rx_data[i].idx = i;
444         }
445
446         /*
447          * Setup TX ring
448          */
449         for (i = 0; i < EMX_NTX_RING; ++i) {
450                 sc->tx_data[i].sc = sc;
451                 sc->tx_data[i].idx = i;
452         }
453
454         /*
455          * Initialize serializers
456          */
457         lwkt_serialize_init(&sc->main_serialize);
458         for (i = 0; i < EMX_NTX_RING; ++i)
459                 lwkt_serialize_init(&sc->tx_data[i].tx_serialize);
460         for (i = 0; i < EMX_NRX_RING; ++i)
461                 lwkt_serialize_init(&sc->rx_data[i].rx_serialize);
462
463         /*
464          * Initialize serializer array
465          */
466         i = 0;
467
468         KKASSERT(i < EMX_NSERIALIZE);
469         sc->serializes[i++] = &sc->main_serialize;
470
471         KKASSERT(i < EMX_NSERIALIZE);
472         sc->serializes[i++] = &sc->tx_data[0].tx_serialize;
473         KKASSERT(i < EMX_NSERIALIZE);
474         sc->serializes[i++] = &sc->tx_data[1].tx_serialize;
475
476         KKASSERT(i < EMX_NSERIALIZE);
477         sc->serializes[i++] = &sc->rx_data[0].rx_serialize;
478         KKASSERT(i < EMX_NSERIALIZE);
479         sc->serializes[i++] = &sc->rx_data[1].rx_serialize;
480
481         KKASSERT(i == EMX_NSERIALIZE);
482
483         ifmedia_init(&sc->media, IFM_IMASK, emx_media_change, emx_media_status);
484         callout_init_mp(&sc->timer);
485
486         sc->dev = sc->osdep.dev = dev;
487
488         /*
489          * Determine hardware and mac type
490          */
491         sc->hw.vendor_id = pci_get_vendor(dev);
492         sc->hw.device_id = pci_get_device(dev);
493         sc->hw.revision_id = pci_get_revid(dev);
494         sc->hw.subsystem_vendor_id = pci_get_subvendor(dev);
495         sc->hw.subsystem_device_id = pci_get_subdevice(dev);
496
497         if (e1000_set_mac_type(&sc->hw))
498                 return ENXIO;
499
500         /* Enable bus mastering */
501         pci_enable_busmaster(dev);
502
503         /*
504          * Allocate IO memory
505          */
506         sc->memory_rid = EMX_BAR_MEM;
507         sc->memory = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
508                                             &sc->memory_rid, RF_ACTIVE);
509         if (sc->memory == NULL) {
510                 device_printf(dev, "Unable to allocate bus resource: memory\n");
511                 error = ENXIO;
512                 goto fail;
513         }
514         sc->osdep.mem_bus_space_tag = rman_get_bustag(sc->memory);
515         sc->osdep.mem_bus_space_handle = rman_get_bushandle(sc->memory);
516
517         /* XXX This is quite goofy, it is not actually used */
518         sc->hw.hw_addr = (uint8_t *)&sc->osdep.mem_bus_space_handle;
519
520         /*
521          * Don't enable MSI-X on 82574, see:
522          * 82574 specification update errata #15
523          *
524          * Don't enable MSI on 82571/82572, see:
525          * 82571/82572 specification update errata #63
526          */
527         msi_enable = emx_msi_enable;
528         if (msi_enable &&
529             (sc->hw.mac.type == e1000_82571 ||
530              sc->hw.mac.type == e1000_82572))
531                 msi_enable = 0;
532
533         /*
534          * Allocate interrupt
535          */
536         sc->intr_type = pci_alloc_1intr(dev, msi_enable,
537             &sc->intr_rid, &intr_flags);
538
539         if (sc->intr_type == PCI_INTR_TYPE_LEGACY) {
540                 int unshared;
541
542                 unshared = device_getenv_int(dev, "irq.unshared", 0);
543                 if (!unshared) {
544                         sc->flags |= EMX_FLAG_SHARED_INTR;
545                         if (bootverbose)
546                                 device_printf(dev, "IRQ shared\n");
547                 } else {
548                         intr_flags &= ~RF_SHAREABLE;
549                         if (bootverbose)
550                                 device_printf(dev, "IRQ unshared\n");
551                 }
552         }
553
554         sc->intr_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->intr_rid,
555             intr_flags);
556         if (sc->intr_res == NULL) {
557                 device_printf(dev, "Unable to allocate bus resource: "
558                     "interrupt\n");
559                 error = ENXIO;
560                 goto fail;
561         }
562
563         /* Save PCI command register for Shared Code */
564         sc->hw.bus.pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
565         sc->hw.back = &sc->osdep;
566
567         /*
568          * For I217/I218, we need to map the flash memory and this
569          * must happen after the MAC is identified.
570          */
571         if (sc->hw.mac.type == e1000_pch_lpt) {
572                 sc->flash_rid = EMX_BAR_FLASH;
573
574                 sc->flash = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
575                     &sc->flash_rid, RF_ACTIVE);
576                 if (sc->flash == NULL) {
577                         device_printf(dev, "Mapping of Flash failed\n");
578                         error = ENXIO;
579                         goto fail;
580                 }
581                 sc->osdep.flash_bus_space_tag = rman_get_bustag(sc->flash);
582                 sc->osdep.flash_bus_space_handle =
583                     rman_get_bushandle(sc->flash);
584
585                 /*
586                  * This is used in the shared code
587                  * XXX this goof is actually not used.
588                  */
589                 sc->hw.flash_address = (uint8_t *)sc->flash;
590         }
591
592         /* Do Shared Code initialization */
593         if (e1000_setup_init_funcs(&sc->hw, TRUE)) {
594                 device_printf(dev, "Setup of Shared code failed\n");
595                 error = ENXIO;
596                 goto fail;
597         }
598         e1000_get_bus_info(&sc->hw);
599
600         sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
601         sc->hw.phy.autoneg_wait_to_complete = FALSE;
602         sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
603
604         /*
605          * Interrupt throttle rate
606          */
607         throttle = device_getenv_int(dev, "int_throttle_ceil",
608             emx_int_throttle_ceil);
609         if (throttle == 0) {
610                 sc->int_throttle_ceil = 0;
611         } else {
612                 if (throttle < 0)
613                         throttle = EMX_DEFAULT_ITR;
614
615                 /* Recalculate the tunable value to get the exact frequency. */
616                 throttle = 1000000000 / 256 / throttle;
617
618                 /* Upper 16bits of ITR is reserved and should be zero */
619                 if (throttle & 0xffff0000)
620                         throttle = 1000000000 / 256 / EMX_DEFAULT_ITR;
621
622                 sc->int_throttle_ceil = 1000000000 / 256 / throttle;
623         }
624
625         e1000_init_script_state_82541(&sc->hw, TRUE);
626         e1000_set_tbi_compatibility_82543(&sc->hw, TRUE);
627
628         /* Copper options */
629         if (sc->hw.phy.media_type == e1000_media_type_copper) {
630                 sc->hw.phy.mdix = EMX_AUTO_ALL_MODES;
631                 sc->hw.phy.disable_polarity_correction = FALSE;
632                 sc->hw.phy.ms_type = EMX_MASTER_SLAVE;
633         }
634
635         /* Set the frame limits assuming standard ethernet sized frames. */
636         sc->hw.mac.max_frame_size = ETHERMTU + ETHER_HDR_LEN + ETHER_CRC_LEN;
637
638         /* This controls when hardware reports transmit completion status. */
639         sc->hw.mac.report_tx_early = 1;
640
641         /* Calculate # of RX rings */
642         sc->rx_ring_cnt = device_getenv_int(dev, "rxr", emx_rxr);
643         sc->rx_ring_cnt = if_ring_count2(sc->rx_ring_cnt, EMX_NRX_RING);
644
645         /*
646          * Calculate # of TX rings
647          *
648          * XXX
649          * I217/I218 claims to have 2 TX queues
650          *
651          * NOTE:
652          * Don't enable multiple TX queues on 82574; it always gives
653          * watchdog timeout on TX queue0, when multiple TCP streams are
654          * received.  It was originally suspected that the hardware TX
655          * checksum offloading caused this watchdog timeout, since only
656          * TCP ACKs are sent during TCP receiving tests.  However, even
657          * if the hardware TX checksum offloading is disable, TX queue0
658          * still will give watchdog.
659          */
660         tx_ring_max = 1;
661         if (sc->hw.mac.type == e1000_82571 ||
662             sc->hw.mac.type == e1000_82572 ||
663             sc->hw.mac.type == e1000_80003es2lan ||
664             sc->hw.mac.type == e1000_pch_lpt)
665                 tx_ring_max = EMX_NTX_RING;
666         sc->tx_ring_cnt = device_getenv_int(dev, "txr", emx_txr);
667         sc->tx_ring_cnt = if_ring_count2(sc->tx_ring_cnt, tx_ring_max);
668
669         /* Allocate RX/TX rings' busdma(9) stuffs */
670         error = emx_dma_alloc(sc);
671         if (error)
672                 goto fail;
673
674         /* Allocate multicast array memory. */
675         sc->mta = kmalloc(ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX,
676             M_DEVBUF, M_WAITOK);
677
678         /* Indicate SOL/IDER usage */
679         if (e1000_check_reset_block(&sc->hw)) {
680                 device_printf(dev,
681                     "PHY reset is blocked due to SOL/IDER session.\n");
682         }
683
684         /* Disable EEE on I217/I218 */
685         sc->hw.dev_spec.ich8lan.eee_disable = 1;
686
687         /*
688          * Start from a known state, this is important in reading the
689          * nvm and mac from that.
690          */
691         e1000_reset_hw(&sc->hw);
692
693         /* Make sure we have a good EEPROM before we read from it */
694         if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
695                 /*
696                  * Some PCI-E parts fail the first check due to
697                  * the link being in sleep state, call it again,
698                  * if it fails a second time its a real issue.
699                  */
700                 if (e1000_validate_nvm_checksum(&sc->hw) < 0) {
701                         device_printf(dev,
702                             "The EEPROM Checksum Is Not Valid\n");
703                         error = EIO;
704                         goto fail;
705                 }
706         }
707
708         /* Copy the permanent MAC address out of the EEPROM */
709         if (e1000_read_mac_addr(&sc->hw) < 0) {
710                 device_printf(dev, "EEPROM read error while reading MAC"
711                     " address\n");
712                 error = EIO;
713                 goto fail;
714         }
715         if (!emx_is_valid_eaddr(sc->hw.mac.addr)) {
716                 device_printf(dev, "Invalid MAC address\n");
717                 error = EIO;
718                 goto fail;
719         }
720
721         /* Disable ULP support */
722         e1000_disable_ulp_lpt_lp(&sc->hw, TRUE);
723
724         /* Determine if we have to control management hardware */
725         if (e1000_enable_mng_pass_thru(&sc->hw))
726                 sc->flags |= EMX_FLAG_HAS_MGMT;
727
728         /*
729          * Setup Wake-on-Lan
730          */
731         apme_mask = EMX_EEPROM_APME;
732         eeprom_data = 0;
733         switch (sc->hw.mac.type) {
734         case e1000_82573:
735                 sc->flags |= EMX_FLAG_HAS_AMT;
736                 /* FALL THROUGH */
737
738         case e1000_82571:
739         case e1000_82572:
740         case e1000_80003es2lan:
741                 if (sc->hw.bus.func == 1) {
742                         e1000_read_nvm(&sc->hw,
743                             NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
744                 } else {
745                         e1000_read_nvm(&sc->hw,
746                             NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
747                 }
748                 break;
749
750         default:
751                 e1000_read_nvm(&sc->hw,
752                     NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
753                 break;
754         }
755         if (eeprom_data & apme_mask)
756                 sc->wol = E1000_WUFC_MAG | E1000_WUFC_MC;
757
758         /*
759          * We have the eeprom settings, now apply the special cases
760          * where the eeprom may be wrong or the board won't support
761          * wake on lan on a particular port
762          */
763         device_id = pci_get_device(dev);
764         switch (device_id) {
765         case E1000_DEV_ID_82571EB_FIBER:
766                 /*
767                  * Wake events only supported on port A for dual fiber
768                  * regardless of eeprom setting
769                  */
770                 if (E1000_READ_REG(&sc->hw, E1000_STATUS) &
771                     E1000_STATUS_FUNC_1)
772                         sc->wol = 0;
773                 break;
774
775         case E1000_DEV_ID_82571EB_QUAD_COPPER:
776         case E1000_DEV_ID_82571EB_QUAD_FIBER:
777         case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
778                 /* if quad port sc, disable WoL on all but port A */
779                 if (emx_global_quad_port_a != 0)
780                         sc->wol = 0;
781                 /* Reset for multiple quad port adapters */
782                 if (++emx_global_quad_port_a == 4)
783                         emx_global_quad_port_a = 0;
784                 break;
785         }
786
787         /* XXX disable wol */
788         sc->wol = 0;
789
790 #ifdef IFPOLL_ENABLE
791         /*
792          * NPOLLING RX CPU offset
793          */
794         if (sc->rx_ring_cnt == ncpus2) {
795                 offset = 0;
796         } else {
797                 offset_def = (sc->rx_ring_cnt * device_get_unit(dev)) % ncpus2;
798                 offset = device_getenv_int(dev, "npoll.rxoff", offset_def);
799                 if (offset >= ncpus2 ||
800                     offset % sc->rx_ring_cnt != 0) {
801                         device_printf(dev, "invalid npoll.rxoff %d, use %d\n",
802                             offset, offset_def);
803                         offset = offset_def;
804                 }
805         }
806         sc->rx_npoll_off = offset;
807
808         /*
809          * NPOLLING TX CPU offset
810          */
811         if (sc->tx_ring_cnt == ncpus2) {
812                 offset = 0;
813         } else {
814                 offset_def = (sc->tx_ring_cnt * device_get_unit(dev)) % ncpus2;
815                 offset = device_getenv_int(dev, "npoll.txoff", offset_def);
816                 if (offset >= ncpus2 ||
817                     offset % sc->tx_ring_cnt != 0) {
818                         device_printf(dev, "invalid npoll.txoff %d, use %d\n",
819                             offset, offset_def);
820                         offset = offset_def;
821                 }
822         }
823         sc->tx_npoll_off = offset;
824 #endif
825         sc->tx_ring_inuse = emx_get_txring_inuse(sc, FALSE);
826
827         /* Setup OS specific network interface */
828         emx_setup_ifp(sc);
829
830         /* Add sysctl tree, must after em_setup_ifp() */
831         emx_add_sysctl(sc);
832
833         /* Reset the hardware */
834         error = emx_reset(sc);
835         if (error) {
836                 /*
837                  * Some 82573 parts fail the first reset, call it again,
838                  * if it fails a second time its a real issue.
839                  */
840                 error = emx_reset(sc);
841                 if (error) {
842                         device_printf(dev, "Unable to reset the hardware\n");
843                         ether_ifdetach(&sc->arpcom.ac_if);
844                         goto fail;
845                 }
846         }
847
848         /* Initialize statistics */
849         emx_update_stats(sc);
850
851         sc->hw.mac.get_link_status = 1;
852         emx_update_link_status(sc);
853
854         /* Non-AMT based hardware can now take control from firmware */
855         if ((sc->flags & (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT)) ==
856             EMX_FLAG_HAS_MGMT)
857                 emx_get_hw_control(sc);
858
859         /*
860          * Missing Interrupt Following ICR read:
861          *
862          * 82571/82572 specification update errata #76
863          * 82573 specification update errata #31
864          * 82574 specification update errata #12
865          */
866         intr_func = emx_intr;
867         if ((sc->flags & EMX_FLAG_SHARED_INTR) &&
868             (sc->hw.mac.type == e1000_82571 ||
869              sc->hw.mac.type == e1000_82572 ||
870              sc->hw.mac.type == e1000_82573 ||
871              sc->hw.mac.type == e1000_82574))
872                 intr_func = emx_intr_mask;
873
874         error = bus_setup_intr(dev, sc->intr_res, INTR_MPSAFE, intr_func, sc,
875                                &sc->intr_tag, &sc->main_serialize);
876         if (error) {
877                 device_printf(dev, "Failed to register interrupt handler");
878                 ether_ifdetach(&sc->arpcom.ac_if);
879                 goto fail;
880         }
881         return (0);
882 fail:
883         emx_detach(dev);
884         return (error);
885 }
886
887 static int
888 emx_detach(device_t dev)
889 {
890         struct emx_softc *sc = device_get_softc(dev);
891
892         if (device_is_attached(dev)) {
893                 struct ifnet *ifp = &sc->arpcom.ac_if;
894
895                 ifnet_serialize_all(ifp);
896
897                 emx_stop(sc);
898
899                 e1000_phy_hw_reset(&sc->hw);
900
901                 emx_rel_mgmt(sc);
902                 emx_rel_hw_control(sc);
903
904                 if (sc->wol) {
905                         E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
906                         E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
907                         emx_enable_wol(dev);
908                 }
909
910                 bus_teardown_intr(dev, sc->intr_res, sc->intr_tag);
911
912                 ifnet_deserialize_all(ifp);
913
914                 ether_ifdetach(ifp);
915         } else if (sc->memory != NULL) {
916                 emx_rel_hw_control(sc);
917         }
918
919         ifmedia_removeall(&sc->media);
920         bus_generic_detach(dev);
921
922         if (sc->intr_res != NULL) {
923                 bus_release_resource(dev, SYS_RES_IRQ, sc->intr_rid,
924                                      sc->intr_res);
925         }
926
927         if (sc->intr_type == PCI_INTR_TYPE_MSI)
928                 pci_release_msi(dev);
929
930         if (sc->memory != NULL) {
931                 bus_release_resource(dev, SYS_RES_MEMORY, sc->memory_rid,
932                                      sc->memory);
933         }
934
935         if (sc->flash != NULL) {
936                 bus_release_resource(dev, SYS_RES_MEMORY, sc->flash_rid,
937                     sc->flash);
938         }
939
940         emx_dma_free(sc);
941
942         if (sc->mta != NULL)
943                 kfree(sc->mta, M_DEVBUF);
944
945         return (0);
946 }
947
948 static int
949 emx_shutdown(device_t dev)
950 {
951         return emx_suspend(dev);
952 }
953
954 static int
955 emx_suspend(device_t dev)
956 {
957         struct emx_softc *sc = device_get_softc(dev);
958         struct ifnet *ifp = &sc->arpcom.ac_if;
959
960         ifnet_serialize_all(ifp);
961
962         emx_stop(sc);
963
964         emx_rel_mgmt(sc);
965         emx_rel_hw_control(sc);
966
967         if (sc->wol) {
968                 E1000_WRITE_REG(&sc->hw, E1000_WUC, E1000_WUC_PME_EN);
969                 E1000_WRITE_REG(&sc->hw, E1000_WUFC, sc->wol);
970                 emx_enable_wol(dev);
971         }
972
973         ifnet_deserialize_all(ifp);
974
975         return bus_generic_suspend(dev);
976 }
977
978 static int
979 emx_resume(device_t dev)
980 {
981         struct emx_softc *sc = device_get_softc(dev);
982         struct ifnet *ifp = &sc->arpcom.ac_if;
983         int i;
984
985         ifnet_serialize_all(ifp);
986
987         emx_init(sc);
988         emx_get_mgmt(sc);
989         for (i = 0; i < sc->tx_ring_inuse; ++i)
990                 ifsq_devstart_sched(sc->tx_data[i].ifsq);
991
992         ifnet_deserialize_all(ifp);
993
994         return bus_generic_resume(dev);
995 }
996
997 static void
998 emx_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
999 {
1000         struct emx_softc *sc = ifp->if_softc;
1001         struct emx_txdata *tdata = ifsq_get_priv(ifsq);
1002         struct mbuf *m_head;
1003         int idx = -1, nsegs = 0;
1004
1005         KKASSERT(tdata->ifsq == ifsq);
1006         ASSERT_SERIALIZED(&tdata->tx_serialize);
1007
1008         if ((ifp->if_flags & IFF_RUNNING) == 0 || ifsq_is_oactive(ifsq))
1009                 return;
1010
1011         if (!sc->link_active || (tdata->tx_flags & EMX_TXFLAG_ENABLED) == 0) {
1012                 ifsq_purge(ifsq);
1013                 return;
1014         }
1015
1016         while (!ifsq_is_empty(ifsq)) {
1017                 /* Now do we at least have a minimal? */
1018                 if (EMX_IS_OACTIVE(tdata)) {
1019                         emx_tx_collect(tdata);
1020                         if (EMX_IS_OACTIVE(tdata)) {
1021                                 ifsq_set_oactive(ifsq);
1022                                 break;
1023                         }
1024                 }
1025
1026                 logif(pkt_txqueue);
1027                 m_head = ifsq_dequeue(ifsq);
1028                 if (m_head == NULL)
1029                         break;
1030
1031                 if (emx_encap(tdata, &m_head, &nsegs, &idx)) {
1032                         IFNET_STAT_INC(ifp, oerrors, 1);
1033                         emx_tx_collect(tdata);
1034                         continue;
1035                 }
1036
1037                 if (nsegs >= tdata->tx_wreg_nsegs) {
1038                         E1000_WRITE_REG(&sc->hw, E1000_TDT(tdata->idx), idx);
1039                         nsegs = 0;
1040                         idx = -1;
1041                 }
1042
1043                 /* Send a copy of the frame to the BPF listener */
1044                 ETHER_BPF_MTAP(ifp, m_head);
1045
1046                 /* Set timeout in case hardware has problems transmitting. */
1047                 tdata->tx_watchdog.wd_timer = EMX_TX_TIMEOUT;
1048         }
1049         if (idx >= 0)
1050                 E1000_WRITE_REG(&sc->hw, E1000_TDT(tdata->idx), idx);
1051 }
1052
1053 static int
1054 emx_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
1055 {
1056         struct emx_softc *sc = ifp->if_softc;
1057         struct ifreq *ifr = (struct ifreq *)data;
1058         uint16_t eeprom_data = 0;
1059         int max_frame_size, mask, reinit;
1060         int error = 0;
1061
1062         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1063
1064         switch (command) {
1065         case SIOCSIFMTU:
1066                 switch (sc->hw.mac.type) {
1067                 case e1000_82573:
1068                         /*
1069                          * 82573 only supports jumbo frames
1070                          * if ASPM is disabled.
1071                          */
1072                         e1000_read_nvm(&sc->hw, NVM_INIT_3GIO_3, 1,
1073                                        &eeprom_data);
1074                         if (eeprom_data & NVM_WORD1A_ASPM_MASK) {
1075                                 max_frame_size = ETHER_MAX_LEN;
1076                                 break;
1077                         }
1078                         /* FALL THROUGH */
1079
1080                 /* Limit Jumbo Frame size */
1081                 case e1000_82571:
1082                 case e1000_82572:
1083                 case e1000_82574:
1084                 case e1000_pch_lpt:
1085                 case e1000_80003es2lan:
1086                         max_frame_size = 9234;
1087                         break;
1088
1089                 default:
1090                         max_frame_size = MAX_JUMBO_FRAME_SIZE;
1091                         break;
1092                 }
1093                 if (ifr->ifr_mtu > max_frame_size - ETHER_HDR_LEN -
1094                     ETHER_CRC_LEN) {
1095                         error = EINVAL;
1096                         break;
1097                 }
1098
1099                 ifp->if_mtu = ifr->ifr_mtu;
1100                 sc->hw.mac.max_frame_size = ifp->if_mtu + ETHER_HDR_LEN +
1101                     ETHER_CRC_LEN;
1102
1103                 if (ifp->if_flags & IFF_RUNNING)
1104                         emx_init(sc);
1105                 break;
1106
1107         case SIOCSIFFLAGS:
1108                 if (ifp->if_flags & IFF_UP) {
1109                         if ((ifp->if_flags & IFF_RUNNING)) {
1110                                 if ((ifp->if_flags ^ sc->if_flags) &
1111                                     (IFF_PROMISC | IFF_ALLMULTI)) {
1112                                         emx_disable_promisc(sc);
1113                                         emx_set_promisc(sc);
1114                                 }
1115                         } else {
1116                                 emx_init(sc);
1117                         }
1118                 } else if (ifp->if_flags & IFF_RUNNING) {
1119                         emx_stop(sc);
1120                 }
1121                 sc->if_flags = ifp->if_flags;
1122                 break;
1123
1124         case SIOCADDMULTI:
1125         case SIOCDELMULTI:
1126                 if (ifp->if_flags & IFF_RUNNING) {
1127                         emx_disable_intr(sc);
1128                         emx_set_multi(sc);
1129 #ifdef IFPOLL_ENABLE
1130                         if (!(ifp->if_flags & IFF_NPOLLING))
1131 #endif
1132                                 emx_enable_intr(sc);
1133                 }
1134                 break;
1135
1136         case SIOCSIFMEDIA:
1137                 /* Check SOL/IDER usage */
1138                 if (e1000_check_reset_block(&sc->hw)) {
1139                         device_printf(sc->dev, "Media change is"
1140                             " blocked due to SOL/IDER session.\n");
1141                         break;
1142                 }
1143                 /* FALL THROUGH */
1144
1145         case SIOCGIFMEDIA:
1146                 error = ifmedia_ioctl(ifp, ifr, &sc->media, command);
1147                 break;
1148
1149         case SIOCSIFCAP:
1150                 reinit = 0;
1151                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1152                 if (mask & IFCAP_RXCSUM) {
1153                         ifp->if_capenable ^= IFCAP_RXCSUM;
1154                         reinit = 1;
1155                 }
1156                 if (mask & IFCAP_VLAN_HWTAGGING) {
1157                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1158                         reinit = 1;
1159                 }
1160                 if (mask & IFCAP_TXCSUM) {
1161                         ifp->if_capenable ^= IFCAP_TXCSUM;
1162                         if (ifp->if_capenable & IFCAP_TXCSUM)
1163                                 ifp->if_hwassist |= EMX_CSUM_FEATURES;
1164                         else
1165                                 ifp->if_hwassist &= ~EMX_CSUM_FEATURES;
1166                 }
1167                 if (mask & IFCAP_TSO) {
1168                         ifp->if_capenable ^= IFCAP_TSO;
1169                         if (ifp->if_capenable & IFCAP_TSO)
1170                                 ifp->if_hwassist |= CSUM_TSO;
1171                         else
1172                                 ifp->if_hwassist &= ~CSUM_TSO;
1173                 }
1174                 if (mask & IFCAP_RSS)
1175                         ifp->if_capenable ^= IFCAP_RSS;
1176                 if (reinit && (ifp->if_flags & IFF_RUNNING))
1177                         emx_init(sc);
1178                 break;
1179
1180         default:
1181                 error = ether_ioctl(ifp, command, data);
1182                 break;
1183         }
1184         return (error);
1185 }
1186
1187 static void
1188 emx_watchdog(struct ifaltq_subque *ifsq)
1189 {
1190         struct emx_txdata *tdata = ifsq_get_priv(ifsq);
1191         struct ifnet *ifp = ifsq_get_ifp(ifsq);
1192         struct emx_softc *sc = ifp->if_softc;
1193         int i;
1194
1195         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1196
1197         /*
1198          * The timer is set to 5 every time start queues a packet.
1199          * Then txeof keeps resetting it as long as it cleans at
1200          * least one descriptor.
1201          * Finally, anytime all descriptors are clean the timer is
1202          * set to 0.
1203          */
1204
1205         if (E1000_READ_REG(&sc->hw, E1000_TDT(tdata->idx)) ==
1206             E1000_READ_REG(&sc->hw, E1000_TDH(tdata->idx))) {
1207                 /*
1208                  * If we reach here, all TX jobs are completed and
1209                  * the TX engine should have been idled for some time.
1210                  * We don't need to call ifsq_devstart_sched() here.
1211                  */
1212                 ifsq_clr_oactive(ifsq);
1213                 tdata->tx_watchdog.wd_timer = 0;
1214                 return;
1215         }
1216
1217         /*
1218          * If we are in this routine because of pause frames, then
1219          * don't reset the hardware.
1220          */
1221         if (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_TXOFF) {
1222                 tdata->tx_watchdog.wd_timer = EMX_TX_TIMEOUT;
1223                 return;
1224         }
1225
1226         if_printf(ifp, "TX %d watchdog timeout -- resetting\n", tdata->idx);
1227
1228         IFNET_STAT_INC(ifp, oerrors, 1);
1229
1230         emx_init(sc);
1231         for (i = 0; i < sc->tx_ring_inuse; ++i)
1232                 ifsq_devstart_sched(sc->tx_data[i].ifsq);
1233 }
1234
1235 static void
1236 emx_init(void *xsc)
1237 {
1238         struct emx_softc *sc = xsc;
1239         struct ifnet *ifp = &sc->arpcom.ac_if;
1240         device_t dev = sc->dev;
1241         boolean_t polling;
1242         int i;
1243
1244         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1245
1246         emx_stop(sc);
1247
1248         /* Get the latest mac address, User can use a LAA */
1249         bcopy(IF_LLADDR(ifp), sc->hw.mac.addr, ETHER_ADDR_LEN);
1250
1251         /* Put the address into the Receive Address Array */
1252         e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1253
1254         /*
1255          * With the 82571 sc, RAR[0] may be overwritten
1256          * when the other port is reset, we make a duplicate
1257          * in RAR[14] for that eventuality, this assures
1258          * the interface continues to function.
1259          */
1260         if (sc->hw.mac.type == e1000_82571) {
1261                 e1000_set_laa_state_82571(&sc->hw, TRUE);
1262                 e1000_rar_set(&sc->hw, sc->hw.mac.addr,
1263                     E1000_RAR_ENTRIES - 1);
1264         }
1265
1266         /* Initialize the hardware */
1267         if (emx_reset(sc)) {
1268                 device_printf(dev, "Unable to reset the hardware\n");
1269                 /* XXX emx_stop()? */
1270                 return;
1271         }
1272         emx_update_link_status(sc);
1273
1274         /* Setup VLAN support, basic and offload if available */
1275         E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1276
1277         if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1278                 uint32_t ctrl;
1279
1280                 ctrl = E1000_READ_REG(&sc->hw, E1000_CTRL);
1281                 ctrl |= E1000_CTRL_VME;
1282                 E1000_WRITE_REG(&sc->hw, E1000_CTRL, ctrl);
1283         }
1284
1285         /* Configure for OS presence */
1286         emx_get_mgmt(sc);
1287
1288         polling = FALSE;
1289 #ifdef IFPOLL_ENABLE
1290         if (ifp->if_flags & IFF_NPOLLING)
1291                 polling = TRUE;
1292 #endif
1293         sc->tx_ring_inuse = emx_get_txring_inuse(sc, polling);
1294         ifq_set_subq_mask(&ifp->if_snd, sc->tx_ring_inuse - 1);
1295
1296         /* Prepare transmit descriptors and buffers */
1297         for (i = 0; i < sc->tx_ring_inuse; ++i)
1298                 emx_init_tx_ring(&sc->tx_data[i]);
1299         emx_init_tx_unit(sc);
1300
1301         /* Setup Multicast table */
1302         emx_set_multi(sc);
1303
1304         /* Prepare receive descriptors and buffers */
1305         for (i = 0; i < sc->rx_ring_cnt; ++i) {
1306                 if (emx_init_rx_ring(&sc->rx_data[i])) {
1307                         device_printf(dev,
1308                             "Could not setup receive structures\n");
1309                         emx_stop(sc);
1310                         return;
1311                 }
1312         }
1313         emx_init_rx_unit(sc);
1314
1315         /* Don't lose promiscuous settings */
1316         emx_set_promisc(sc);
1317
1318         ifp->if_flags |= IFF_RUNNING;
1319         for (i = 0; i < sc->tx_ring_inuse; ++i) {
1320                 ifsq_clr_oactive(sc->tx_data[i].ifsq);
1321                 ifsq_watchdog_start(&sc->tx_data[i].tx_watchdog);
1322         }
1323
1324         callout_reset(&sc->timer, hz, emx_timer, sc);
1325         e1000_clear_hw_cntrs_base_generic(&sc->hw);
1326
1327         /* MSI/X configuration for 82574 */
1328         if (sc->hw.mac.type == e1000_82574) {
1329                 int tmp;
1330
1331                 tmp = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
1332                 tmp |= E1000_CTRL_EXT_PBA_CLR;
1333                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT, tmp);
1334                 /*
1335                  * XXX MSIX
1336                  * Set the IVAR - interrupt vector routing.
1337                  * Each nibble represents a vector, high bit
1338                  * is enable, other 3 bits are the MSIX table
1339                  * entry, we map RXQ0 to 0, TXQ0 to 1, and
1340                  * Link (other) to 2, hence the magic number.
1341                  */
1342                 E1000_WRITE_REG(&sc->hw, E1000_IVAR, 0x800A0908);
1343         }
1344
1345         /*
1346          * Only enable interrupts if we are not polling, make sure
1347          * they are off otherwise.
1348          */
1349         if (polling)
1350                 emx_disable_intr(sc);
1351         else
1352                 emx_enable_intr(sc);
1353
1354         /* AMT based hardware can now take control from firmware */
1355         if ((sc->flags & (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT)) ==
1356             (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT))
1357                 emx_get_hw_control(sc);
1358 }
1359
1360 static void
1361 emx_intr(void *xsc)
1362 {
1363         emx_intr_body(xsc, TRUE);
1364 }
1365
1366 static void
1367 emx_intr_body(struct emx_softc *sc, boolean_t chk_asserted)
1368 {
1369         struct ifnet *ifp = &sc->arpcom.ac_if;
1370         uint32_t reg_icr;
1371
1372         logif(intr_beg);
1373         ASSERT_SERIALIZED(&sc->main_serialize);
1374
1375         reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
1376
1377         if (chk_asserted && (reg_icr & E1000_ICR_INT_ASSERTED) == 0) {
1378                 logif(intr_end);
1379                 return;
1380         }
1381
1382         /*
1383          * XXX: some laptops trigger several spurious interrupts
1384          * on emx(4) when in the resume cycle. The ICR register
1385          * reports all-ones value in this case. Processing such
1386          * interrupts would lead to a freeze. I don't know why.
1387          */
1388         if (reg_icr == 0xffffffff) {
1389                 logif(intr_end);
1390                 return;
1391         }
1392
1393         if (ifp->if_flags & IFF_RUNNING) {
1394                 if (reg_icr &
1395                     (E1000_ICR_RXT0 | E1000_ICR_RXDMT0 | E1000_ICR_RXO)) {
1396                         int i;
1397
1398                         for (i = 0; i < sc->rx_ring_cnt; ++i) {
1399                                 lwkt_serialize_enter(
1400                                 &sc->rx_data[i].rx_serialize);
1401                                 emx_rxeof(&sc->rx_data[i], -1);
1402                                 lwkt_serialize_exit(
1403                                 &sc->rx_data[i].rx_serialize);
1404                         }
1405                 }
1406                 if (reg_icr & E1000_ICR_TXDW) {
1407                         struct emx_txdata *tdata = &sc->tx_data[0];
1408
1409                         lwkt_serialize_enter(&tdata->tx_serialize);
1410                         emx_txeof(tdata);
1411                         if (!ifsq_is_empty(tdata->ifsq))
1412                                 ifsq_devstart(tdata->ifsq);
1413                         lwkt_serialize_exit(&tdata->tx_serialize);
1414                 }
1415         }
1416
1417         /* Link status change */
1418         if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1419                 emx_serialize_skipmain(sc);
1420
1421                 callout_stop(&sc->timer);
1422                 sc->hw.mac.get_link_status = 1;
1423                 emx_update_link_status(sc);
1424
1425                 /* Deal with TX cruft when link lost */
1426                 emx_tx_purge(sc);
1427
1428                 callout_reset(&sc->timer, hz, emx_timer, sc);
1429
1430                 emx_deserialize_skipmain(sc);
1431         }
1432
1433         if (reg_icr & E1000_ICR_RXO)
1434                 sc->rx_overruns++;
1435
1436         logif(intr_end);
1437 }
1438
1439 static void
1440 emx_intr_mask(void *xsc)
1441 {
1442         struct emx_softc *sc = xsc;
1443
1444         E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
1445         /*
1446          * NOTE:
1447          * ICR.INT_ASSERTED bit will never be set if IMS is 0,
1448          * so don't check it.
1449          */
1450         emx_intr_body(sc, FALSE);
1451         E1000_WRITE_REG(&sc->hw, E1000_IMS, IMS_ENABLE_MASK);
1452 }
1453
1454 static void
1455 emx_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1456 {
1457         struct emx_softc *sc = ifp->if_softc;
1458
1459         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1460
1461         emx_update_link_status(sc);
1462
1463         ifmr->ifm_status = IFM_AVALID;
1464         ifmr->ifm_active = IFM_ETHER;
1465
1466         if (!sc->link_active)
1467                 return;
1468
1469         ifmr->ifm_status |= IFM_ACTIVE;
1470
1471         if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1472             sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1473                 ifmr->ifm_active |= IFM_1000_SX | IFM_FDX;
1474         } else {
1475                 switch (sc->link_speed) {
1476                 case 10:
1477                         ifmr->ifm_active |= IFM_10_T;
1478                         break;
1479                 case 100:
1480                         ifmr->ifm_active |= IFM_100_TX;
1481                         break;
1482
1483                 case 1000:
1484                         ifmr->ifm_active |= IFM_1000_T;
1485                         break;
1486                 }
1487                 if (sc->link_duplex == FULL_DUPLEX)
1488                         ifmr->ifm_active |= IFM_FDX;
1489                 else
1490                         ifmr->ifm_active |= IFM_HDX;
1491         }
1492 }
1493
1494 static int
1495 emx_media_change(struct ifnet *ifp)
1496 {
1497         struct emx_softc *sc = ifp->if_softc;
1498         struct ifmedia *ifm = &sc->media;
1499
1500         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1501
1502         if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1503                 return (EINVAL);
1504
1505         switch (IFM_SUBTYPE(ifm->ifm_media)) {
1506         case IFM_AUTO:
1507                 sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1508                 sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
1509                 break;
1510
1511         case IFM_1000_LX:
1512         case IFM_1000_SX:
1513         case IFM_1000_T:
1514                 sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1515                 sc->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1516                 break;
1517
1518         case IFM_100_TX:
1519                 sc->hw.mac.autoneg = FALSE;
1520                 sc->hw.phy.autoneg_advertised = 0;
1521                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1522                         sc->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1523                 else
1524                         sc->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1525                 break;
1526
1527         case IFM_10_T:
1528                 sc->hw.mac.autoneg = FALSE;
1529                 sc->hw.phy.autoneg_advertised = 0;
1530                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1531                         sc->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1532                 else
1533                         sc->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1534                 break;
1535
1536         default:
1537                 if_printf(ifp, "Unsupported media type\n");
1538                 break;
1539         }
1540
1541         emx_init(sc);
1542
1543         return (0);
1544 }
1545
1546 static int
1547 emx_encap(struct emx_txdata *tdata, struct mbuf **m_headp,
1548     int *segs_used, int *idx)
1549 {
1550         bus_dma_segment_t segs[EMX_MAX_SCATTER];
1551         bus_dmamap_t map;
1552         struct emx_txbuf *tx_buffer, *tx_buffer_mapped;
1553         struct e1000_tx_desc *ctxd = NULL;
1554         struct mbuf *m_head = *m_headp;
1555         uint32_t txd_upper, txd_lower, cmd = 0;
1556         int maxsegs, nsegs, i, j, first, last = 0, error;
1557
1558         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1559                 error = emx_tso_pullup(tdata, m_headp);
1560                 if (error)
1561                         return error;
1562                 m_head = *m_headp;
1563         }
1564
1565         txd_upper = txd_lower = 0;
1566
1567         /*
1568          * Capture the first descriptor index, this descriptor
1569          * will have the index of the EOP which is the only one
1570          * that now gets a DONE bit writeback.
1571          */
1572         first = tdata->next_avail_tx_desc;
1573         tx_buffer = &tdata->tx_buf[first];
1574         tx_buffer_mapped = tx_buffer;
1575         map = tx_buffer->map;
1576
1577         maxsegs = tdata->num_tx_desc_avail - EMX_TX_RESERVED;
1578         KASSERT(maxsegs >= tdata->spare_tx_desc, ("not enough spare TX desc"));
1579         if (maxsegs > EMX_MAX_SCATTER)
1580                 maxsegs = EMX_MAX_SCATTER;
1581
1582         error = bus_dmamap_load_mbuf_defrag(tdata->txtag, map, m_headp,
1583                         segs, maxsegs, &nsegs, BUS_DMA_NOWAIT);
1584         if (error) {
1585                 m_freem(*m_headp);
1586                 *m_headp = NULL;
1587                 return error;
1588         }
1589         bus_dmamap_sync(tdata->txtag, map, BUS_DMASYNC_PREWRITE);
1590
1591         m_head = *m_headp;
1592         tdata->tx_nsegs += nsegs;
1593         *segs_used += nsegs;
1594
1595         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1596                 /* TSO will consume one TX desc */
1597                 i = emx_tso_setup(tdata, m_head, &txd_upper, &txd_lower);
1598                 tdata->tx_nsegs += i;
1599                 *segs_used += i;
1600         } else if (m_head->m_pkthdr.csum_flags & EMX_CSUM_FEATURES) {
1601                 /* TX csum offloading will consume one TX desc */
1602                 i = emx_txcsum(tdata, m_head, &txd_upper, &txd_lower);
1603                 tdata->tx_nsegs += i;
1604                 *segs_used += i;
1605         }
1606
1607         /* Handle VLAN tag */
1608         if (m_head->m_flags & M_VLANTAG) {
1609                 /* Set the vlan id. */
1610                 txd_upper |= (htole16(m_head->m_pkthdr.ether_vlantag) << 16);
1611                 /* Tell hardware to add tag */
1612                 txd_lower |= htole32(E1000_TXD_CMD_VLE);
1613         }
1614
1615         i = tdata->next_avail_tx_desc;
1616
1617         /* Set up our transmit descriptors */
1618         for (j = 0; j < nsegs; j++) {
1619                 tx_buffer = &tdata->tx_buf[i];
1620                 ctxd = &tdata->tx_desc_base[i];
1621
1622                 ctxd->buffer_addr = htole64(segs[j].ds_addr);
1623                 ctxd->lower.data = htole32(E1000_TXD_CMD_IFCS |
1624                                            txd_lower | segs[j].ds_len);
1625                 ctxd->upper.data = htole32(txd_upper);
1626
1627                 last = i;
1628                 if (++i == tdata->num_tx_desc)
1629                         i = 0;
1630         }
1631
1632         tdata->next_avail_tx_desc = i;
1633
1634         KKASSERT(tdata->num_tx_desc_avail > nsegs);
1635         tdata->num_tx_desc_avail -= nsegs;
1636
1637         tx_buffer->m_head = m_head;
1638         tx_buffer_mapped->map = tx_buffer->map;
1639         tx_buffer->map = map;
1640
1641         if (tdata->tx_nsegs >= tdata->tx_intr_nsegs) {
1642                 tdata->tx_nsegs = 0;
1643
1644                 /*
1645                  * Report Status (RS) is turned on
1646                  * every tx_intr_nsegs descriptors.
1647                  */
1648                 cmd = E1000_TXD_CMD_RS;
1649
1650                 /*
1651                  * Keep track of the descriptor, which will
1652                  * be written back by hardware.
1653                  */
1654                 tdata->tx_dd[tdata->tx_dd_tail] = last;
1655                 EMX_INC_TXDD_IDX(tdata->tx_dd_tail);
1656                 KKASSERT(tdata->tx_dd_tail != tdata->tx_dd_head);
1657         }
1658
1659         /*
1660          * Last Descriptor of Packet needs End Of Packet (EOP)
1661          */
1662         ctxd->lower.data |= htole32(E1000_TXD_CMD_EOP | cmd);
1663
1664         /*
1665          * Defer TDT updating, until enough descriptors are setup
1666          */
1667         *idx = i;
1668
1669 #ifdef EMX_TSS_DEBUG
1670         tdata->tx_pkts++;
1671 #endif
1672
1673         return (0);
1674 }
1675
1676 static void
1677 emx_set_promisc(struct emx_softc *sc)
1678 {
1679         struct ifnet *ifp = &sc->arpcom.ac_if;
1680         uint32_t reg_rctl;
1681
1682         reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1683
1684         if (ifp->if_flags & IFF_PROMISC) {
1685                 reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
1686                 /* Turn this on if you want to see bad packets */
1687                 if (emx_debug_sbp)
1688                         reg_rctl |= E1000_RCTL_SBP;
1689                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1690         } else if (ifp->if_flags & IFF_ALLMULTI) {
1691                 reg_rctl |= E1000_RCTL_MPE;
1692                 reg_rctl &= ~E1000_RCTL_UPE;
1693                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1694         }
1695 }
1696
1697 static void
1698 emx_disable_promisc(struct emx_softc *sc)
1699 {
1700         uint32_t reg_rctl;
1701
1702         reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1703
1704         reg_rctl &= ~E1000_RCTL_UPE;
1705         reg_rctl &= ~E1000_RCTL_MPE;
1706         reg_rctl &= ~E1000_RCTL_SBP;
1707         E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1708 }
1709
1710 static void
1711 emx_set_multi(struct emx_softc *sc)
1712 {
1713         struct ifnet *ifp = &sc->arpcom.ac_if;
1714         struct ifmultiaddr *ifma;
1715         uint32_t reg_rctl = 0;
1716         uint8_t *mta;
1717         int mcnt = 0;
1718
1719         mta = sc->mta;
1720         bzero(mta, ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX);
1721
1722         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1723                 if (ifma->ifma_addr->sa_family != AF_LINK)
1724                         continue;
1725
1726                 if (mcnt == EMX_MCAST_ADDR_MAX)
1727                         break;
1728
1729                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1730                       &mta[mcnt * ETHER_ADDR_LEN], ETHER_ADDR_LEN);
1731                 mcnt++;
1732         }
1733
1734         if (mcnt >= EMX_MCAST_ADDR_MAX) {
1735                 reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1736                 reg_rctl |= E1000_RCTL_MPE;
1737                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1738         } else {
1739                 e1000_update_mc_addr_list(&sc->hw, mta, mcnt);
1740         }
1741 }
1742
1743 /*
1744  * This routine checks for link status and updates statistics.
1745  */
1746 static void
1747 emx_timer(void *xsc)
1748 {
1749         struct emx_softc *sc = xsc;
1750         struct ifnet *ifp = &sc->arpcom.ac_if;
1751
1752         lwkt_serialize_enter(&sc->main_serialize);
1753
1754         emx_update_link_status(sc);
1755         emx_update_stats(sc);
1756
1757         /* Reset LAA into RAR[0] on 82571 */
1758         if (e1000_get_laa_state_82571(&sc->hw) == TRUE)
1759                 e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1760
1761         if (emx_display_debug_stats && (ifp->if_flags & IFF_RUNNING))
1762                 emx_print_hw_stats(sc);
1763
1764         emx_smartspeed(sc);
1765
1766         callout_reset(&sc->timer, hz, emx_timer, sc);
1767
1768         lwkt_serialize_exit(&sc->main_serialize);
1769 }
1770
1771 static void
1772 emx_update_link_status(struct emx_softc *sc)
1773 {
1774         struct e1000_hw *hw = &sc->hw;
1775         struct ifnet *ifp = &sc->arpcom.ac_if;
1776         device_t dev = sc->dev;
1777         uint32_t link_check = 0;
1778
1779         /* Get the cached link value or read phy for real */
1780         switch (hw->phy.media_type) {
1781         case e1000_media_type_copper:
1782                 if (hw->mac.get_link_status) {
1783                         /* Do the work to read phy */
1784                         e1000_check_for_link(hw);
1785                         link_check = !hw->mac.get_link_status;
1786                         if (link_check) /* ESB2 fix */
1787                                 e1000_cfg_on_link_up(hw);
1788                 } else {
1789                         link_check = TRUE;
1790                 }
1791                 break;
1792
1793         case e1000_media_type_fiber:
1794                 e1000_check_for_link(hw);
1795                 link_check = E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU;
1796                 break;
1797
1798         case e1000_media_type_internal_serdes:
1799                 e1000_check_for_link(hw);
1800                 link_check = sc->hw.mac.serdes_has_link;
1801                 break;
1802
1803         case e1000_media_type_unknown:
1804         default:
1805                 break;
1806         }
1807
1808         /* Now check for a transition */
1809         if (link_check && sc->link_active == 0) {
1810                 e1000_get_speed_and_duplex(hw, &sc->link_speed,
1811                     &sc->link_duplex);
1812
1813                 /*
1814                  * Check if we should enable/disable SPEED_MODE bit on
1815                  * 82571EB/82572EI
1816                  */
1817                 if (sc->link_speed != SPEED_1000 &&
1818                     (hw->mac.type == e1000_82571 ||
1819                      hw->mac.type == e1000_82572)) {
1820                         int tarc0;
1821
1822                         tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
1823                         tarc0 &= ~EMX_TARC_SPEED_MODE;
1824                         E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
1825                 }
1826                 if (bootverbose) {
1827                         device_printf(dev, "Link is up %d Mbps %s\n",
1828                             sc->link_speed,
1829                             ((sc->link_duplex == FULL_DUPLEX) ?
1830                             "Full Duplex" : "Half Duplex"));
1831                 }
1832                 sc->link_active = 1;
1833                 sc->smartspeed = 0;
1834                 ifp->if_baudrate = sc->link_speed * 1000000;
1835                 ifp->if_link_state = LINK_STATE_UP;
1836                 if_link_state_change(ifp);
1837         } else if (!link_check && sc->link_active == 1) {
1838                 ifp->if_baudrate = sc->link_speed = 0;
1839                 sc->link_duplex = 0;
1840                 if (bootverbose)
1841                         device_printf(dev, "Link is Down\n");
1842                 sc->link_active = 0;
1843                 ifp->if_link_state = LINK_STATE_DOWN;
1844                 if_link_state_change(ifp);
1845         }
1846 }
1847
1848 static void
1849 emx_stop(struct emx_softc *sc)
1850 {
1851         struct ifnet *ifp = &sc->arpcom.ac_if;
1852         int i;
1853
1854         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1855
1856         emx_disable_intr(sc);
1857
1858         callout_stop(&sc->timer);
1859
1860         ifp->if_flags &= ~IFF_RUNNING;
1861         for (i = 0; i < sc->tx_ring_cnt; ++i) {
1862                 struct emx_txdata *tdata = &sc->tx_data[i];
1863
1864                 ifsq_clr_oactive(tdata->ifsq);
1865                 ifsq_watchdog_stop(&tdata->tx_watchdog);
1866                 tdata->tx_flags &= ~EMX_TXFLAG_ENABLED;
1867         }
1868
1869         /*
1870          * Disable multiple receive queues.
1871          *
1872          * NOTE:
1873          * We should disable multiple receive queues before
1874          * resetting the hardware.
1875          */
1876         E1000_WRITE_REG(&sc->hw, E1000_MRQC, 0);
1877
1878         e1000_reset_hw(&sc->hw);
1879         E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1880
1881         for (i = 0; i < sc->tx_ring_cnt; ++i)
1882                 emx_free_tx_ring(&sc->tx_data[i]);
1883         for (i = 0; i < sc->rx_ring_cnt; ++i)
1884                 emx_free_rx_ring(&sc->rx_data[i]);
1885 }
1886
1887 static int
1888 emx_reset(struct emx_softc *sc)
1889 {
1890         device_t dev = sc->dev;
1891         uint16_t rx_buffer_size;
1892         uint32_t pba;
1893
1894         /* Set up smart power down as default off on newer adapters. */
1895         if (!emx_smart_pwr_down &&
1896             (sc->hw.mac.type == e1000_82571 ||
1897              sc->hw.mac.type == e1000_82572)) {
1898                 uint16_t phy_tmp = 0;
1899
1900                 /* Speed up time to link by disabling smart power down. */
1901                 e1000_read_phy_reg(&sc->hw,
1902                     IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
1903                 phy_tmp &= ~IGP02E1000_PM_SPD;
1904                 e1000_write_phy_reg(&sc->hw,
1905                     IGP02E1000_PHY_POWER_MGMT, phy_tmp);
1906         }
1907
1908         /*
1909          * Packet Buffer Allocation (PBA)
1910          * Writing PBA sets the receive portion of the buffer
1911          * the remainder is used for the transmit buffer.
1912          */
1913         switch (sc->hw.mac.type) {
1914         /* Total Packet Buffer on these is 48K */
1915         case e1000_82571:
1916         case e1000_82572:
1917         case e1000_80003es2lan:
1918                 pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
1919                 break;
1920
1921         case e1000_82573: /* 82573: Total Packet Buffer is 32K */
1922                 pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
1923                 break;
1924
1925         case e1000_82574:
1926                 pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
1927                 break;
1928
1929         case e1000_pch_lpt:
1930                 pba = E1000_PBA_26K;
1931                 break;
1932
1933         default:
1934                 /* Devices before 82547 had a Packet Buffer of 64K.   */
1935                 if (sc->hw.mac.max_frame_size > 8192)
1936                         pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
1937                 else
1938                         pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
1939         }
1940         E1000_WRITE_REG(&sc->hw, E1000_PBA, pba);
1941
1942         /*
1943          * These parameters control the automatic generation (Tx) and
1944          * response (Rx) to Ethernet PAUSE frames.
1945          * - High water mark should allow for at least two frames to be
1946          *   received after sending an XOFF.
1947          * - Low water mark works best when it is very near the high water mark.
1948          *   This allows the receiver to restart by sending XON when it has
1949          *   drained a bit. Here we use an arbitary value of 1500 which will
1950          *   restart after one full frame is pulled from the buffer. There
1951          *   could be several smaller frames in the buffer and if so they will
1952          *   not trigger the XON until their total number reduces the buffer
1953          *   by 1500.
1954          * - The pause time is fairly large at 1000 x 512ns = 512 usec.
1955          */
1956         rx_buffer_size = (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) << 10;
1957
1958         sc->hw.fc.high_water = rx_buffer_size -
1959             roundup2(sc->hw.mac.max_frame_size, 1024);
1960         sc->hw.fc.low_water = sc->hw.fc.high_water - 1500;
1961
1962         sc->hw.fc.pause_time = EMX_FC_PAUSE_TIME;
1963         sc->hw.fc.send_xon = TRUE;
1964         sc->hw.fc.requested_mode = e1000_fc_full;
1965
1966         /*
1967          * Device specific overrides/settings
1968          */
1969         if (sc->hw.mac.type == e1000_pch_lpt) {
1970                 sc->hw.fc.high_water = 0x5C20;
1971                 sc->hw.fc.low_water = 0x5048;
1972                 sc->hw.fc.pause_time = 0x0650;
1973                 sc->hw.fc.refresh_time = 0x0400;
1974                 /* Jumbos need adjusted PBA */
1975                 if (sc->arpcom.ac_if.if_mtu > ETHERMTU)
1976                         E1000_WRITE_REG(&sc->hw, E1000_PBA, 12);
1977                 else
1978                         E1000_WRITE_REG(&sc->hw, E1000_PBA, 26);
1979         } else if (sc->hw.mac.type == e1000_80003es2lan) {
1980                 sc->hw.fc.pause_time = 0xFFFF;
1981         }
1982
1983         /* Issue a global reset */
1984         e1000_reset_hw(&sc->hw);
1985         E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1986         emx_disable_aspm(sc);
1987
1988         if (e1000_init_hw(&sc->hw) < 0) {
1989                 device_printf(dev, "Hardware Initialization Failed\n");
1990                 return (EIO);
1991         }
1992
1993         E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1994         e1000_get_phy_info(&sc->hw);
1995         e1000_check_for_link(&sc->hw);
1996
1997         return (0);
1998 }
1999
2000 static void
2001 emx_setup_ifp(struct emx_softc *sc)
2002 {
2003         struct ifnet *ifp = &sc->arpcom.ac_if;
2004         int i;
2005
2006         if_initname(ifp, device_get_name(sc->dev),
2007                     device_get_unit(sc->dev));
2008         ifp->if_softc = sc;
2009         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2010         ifp->if_init =  emx_init;
2011         ifp->if_ioctl = emx_ioctl;
2012         ifp->if_start = emx_start;
2013 #ifdef IFPOLL_ENABLE
2014         ifp->if_npoll = emx_npoll;
2015 #endif
2016         ifp->if_serialize = emx_serialize;
2017         ifp->if_deserialize = emx_deserialize;
2018         ifp->if_tryserialize = emx_tryserialize;
2019 #ifdef INVARIANTS
2020         ifp->if_serialize_assert = emx_serialize_assert;
2021 #endif
2022
2023         ifq_set_maxlen(&ifp->if_snd, sc->tx_data[0].num_tx_desc - 1);
2024         ifq_set_ready(&ifp->if_snd);
2025         ifq_set_subq_cnt(&ifp->if_snd, sc->tx_ring_cnt);
2026
2027         ifp->if_mapsubq = ifq_mapsubq_mask;
2028         ifq_set_subq_mask(&ifp->if_snd, 0);
2029
2030         ether_ifattach(ifp, sc->hw.mac.addr, NULL);
2031
2032         ifp->if_capabilities = IFCAP_HWCSUM |
2033                                IFCAP_VLAN_HWTAGGING |
2034                                IFCAP_VLAN_MTU |
2035                                IFCAP_TSO;
2036         if (sc->rx_ring_cnt > 1)
2037                 ifp->if_capabilities |= IFCAP_RSS;
2038         ifp->if_capenable = ifp->if_capabilities;
2039         ifp->if_hwassist = EMX_CSUM_FEATURES | CSUM_TSO;
2040
2041         /*
2042          * Tell the upper layer(s) we support long frames.
2043          */
2044         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
2045
2046         for (i = 0; i < sc->tx_ring_cnt; ++i) {
2047                 struct ifaltq_subque *ifsq = ifq_get_subq(&ifp->if_snd, i);
2048                 struct emx_txdata *tdata = &sc->tx_data[i];
2049
2050                 ifsq_set_cpuid(ifsq, rman_get_cpuid(sc->intr_res));
2051                 ifsq_set_priv(ifsq, tdata);
2052                 ifsq_set_hw_serialize(ifsq, &tdata->tx_serialize);
2053                 tdata->ifsq = ifsq;
2054
2055                 ifsq_watchdog_init(&tdata->tx_watchdog, ifsq, emx_watchdog);
2056         }
2057
2058         /*
2059          * Specify the media types supported by this sc and register
2060          * callbacks to update media and link information
2061          */
2062         if (sc->hw.phy.media_type == e1000_media_type_fiber ||
2063             sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
2064                 ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_SX | IFM_FDX,
2065                             0, NULL);
2066                 ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_SX, 0, NULL);
2067         } else {
2068                 ifmedia_add(&sc->media, IFM_ETHER | IFM_10_T, 0, NULL);
2069                 ifmedia_add(&sc->media, IFM_ETHER | IFM_10_T | IFM_FDX,
2070                             0, NULL);
2071                 ifmedia_add(&sc->media, IFM_ETHER | IFM_100_TX, 0, NULL);
2072                 ifmedia_add(&sc->media, IFM_ETHER | IFM_100_TX | IFM_FDX,
2073                             0, NULL);
2074                 if (sc->hw.phy.type != e1000_phy_ife) {
2075                         ifmedia_add(&sc->media,
2076                                 IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL);
2077                         ifmedia_add(&sc->media,
2078                                 IFM_ETHER | IFM_1000_T, 0, NULL);
2079                 }
2080         }
2081         ifmedia_add(&sc->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2082         ifmedia_set(&sc->media, IFM_ETHER | IFM_AUTO);
2083 }
2084
2085 /*
2086  * Workaround for SmartSpeed on 82541 and 82547 controllers
2087  */
2088 static void
2089 emx_smartspeed(struct emx_softc *sc)
2090 {
2091         uint16_t phy_tmp;
2092
2093         if (sc->link_active || sc->hw.phy.type != e1000_phy_igp ||
2094             sc->hw.mac.autoneg == 0 ||
2095             (sc->hw.phy.autoneg_advertised & ADVERTISE_1000_FULL) == 0)
2096                 return;
2097
2098         if (sc->smartspeed == 0) {
2099                 /*
2100                  * If Master/Slave config fault is asserted twice,
2101                  * we assume back-to-back
2102                  */
2103                 e1000_read_phy_reg(&sc->hw, PHY_1000T_STATUS, &phy_tmp);
2104                 if (!(phy_tmp & SR_1000T_MS_CONFIG_FAULT))
2105                         return;
2106                 e1000_read_phy_reg(&sc->hw, PHY_1000T_STATUS, &phy_tmp);
2107                 if (phy_tmp & SR_1000T_MS_CONFIG_FAULT) {
2108                         e1000_read_phy_reg(&sc->hw,
2109                             PHY_1000T_CTRL, &phy_tmp);
2110                         if (phy_tmp & CR_1000T_MS_ENABLE) {
2111                                 phy_tmp &= ~CR_1000T_MS_ENABLE;
2112                                 e1000_write_phy_reg(&sc->hw,
2113                                     PHY_1000T_CTRL, phy_tmp);
2114                                 sc->smartspeed++;
2115                                 if (sc->hw.mac.autoneg &&
2116                                     !e1000_phy_setup_autoneg(&sc->hw) &&
2117                                     !e1000_read_phy_reg(&sc->hw,
2118                                      PHY_CONTROL, &phy_tmp)) {
2119                                         phy_tmp |= MII_CR_AUTO_NEG_EN |
2120                                                    MII_CR_RESTART_AUTO_NEG;
2121                                         e1000_write_phy_reg(&sc->hw,
2122                                             PHY_CONTROL, phy_tmp);
2123                                 }
2124                         }
2125                 }
2126                 return;
2127         } else if (sc->smartspeed == EMX_SMARTSPEED_DOWNSHIFT) {
2128                 /* If still no link, perhaps using 2/3 pair cable */
2129                 e1000_read_phy_reg(&sc->hw, PHY_1000T_CTRL, &phy_tmp);
2130                 phy_tmp |= CR_1000T_MS_ENABLE;
2131                 e1000_write_phy_reg(&sc->hw, PHY_1000T_CTRL, phy_tmp);
2132                 if (sc->hw.mac.autoneg &&
2133                     !e1000_phy_setup_autoneg(&sc->hw) &&
2134                     !e1000_read_phy_reg(&sc->hw, PHY_CONTROL, &phy_tmp)) {
2135                         phy_tmp |= MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
2136                         e1000_write_phy_reg(&sc->hw, PHY_CONTROL, phy_tmp);
2137                 }
2138         }
2139
2140         /* Restart process after EMX_SMARTSPEED_MAX iterations */
2141         if (sc->smartspeed++ == EMX_SMARTSPEED_MAX)
2142                 sc->smartspeed = 0;
2143 }
2144
2145 static int
2146 emx_create_tx_ring(struct emx_txdata *tdata)
2147 {
2148         device_t dev = tdata->sc->dev;
2149         struct emx_txbuf *tx_buffer;
2150         int error, i, tsize, ntxd;
2151
2152         /*
2153          * Validate number of transmit descriptors.  It must not exceed
2154          * hardware maximum, and must be multiple of E1000_DBA_ALIGN.
2155          */
2156         ntxd = device_getenv_int(dev, "txd", emx_txd);
2157         if ((ntxd * sizeof(struct e1000_tx_desc)) % EMX_DBA_ALIGN != 0 ||
2158             ntxd > EMX_MAX_TXD || ntxd < EMX_MIN_TXD) {
2159                 device_printf(dev, "Using %d TX descriptors instead of %d!\n",
2160                     EMX_DEFAULT_TXD, ntxd);
2161                 tdata->num_tx_desc = EMX_DEFAULT_TXD;
2162         } else {
2163                 tdata->num_tx_desc = ntxd;
2164         }
2165
2166         /*
2167          * Allocate Transmit Descriptor ring
2168          */
2169         tsize = roundup2(tdata->num_tx_desc * sizeof(struct e1000_tx_desc),
2170                          EMX_DBA_ALIGN);
2171         tdata->tx_desc_base = bus_dmamem_coherent_any(tdata->sc->parent_dtag,
2172                                 EMX_DBA_ALIGN, tsize, BUS_DMA_WAITOK,
2173                                 &tdata->tx_desc_dtag, &tdata->tx_desc_dmap,
2174                                 &tdata->tx_desc_paddr);
2175         if (tdata->tx_desc_base == NULL) {
2176                 device_printf(dev, "Unable to allocate tx_desc memory\n");
2177                 return ENOMEM;
2178         }
2179
2180         tsize = __VM_CACHELINE_ALIGN(
2181             sizeof(struct emx_txbuf) * tdata->num_tx_desc);
2182         tdata->tx_buf = kmalloc_cachealign(tsize, M_DEVBUF, M_WAITOK | M_ZERO);
2183
2184         /*
2185          * Create DMA tags for tx buffers
2186          */
2187         error = bus_dma_tag_create(tdata->sc->parent_dtag, /* parent */
2188                         1, 0,                   /* alignment, bounds */
2189                         BUS_SPACE_MAXADDR,      /* lowaddr */
2190                         BUS_SPACE_MAXADDR,      /* highaddr */
2191                         NULL, NULL,             /* filter, filterarg */
2192                         EMX_TSO_SIZE,           /* maxsize */
2193                         EMX_MAX_SCATTER,        /* nsegments */
2194                         EMX_MAX_SEGSIZE,        /* maxsegsize */
2195                         BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW |
2196                         BUS_DMA_ONEBPAGE,       /* flags */
2197                         &tdata->txtag);
2198         if (error) {
2199                 device_printf(dev, "Unable to allocate TX DMA tag\n");
2200                 kfree(tdata->tx_buf, M_DEVBUF);
2201                 tdata->tx_buf = NULL;
2202                 return error;
2203         }
2204
2205         /*
2206          * Create DMA maps for tx buffers
2207          */
2208         for (i = 0; i < tdata->num_tx_desc; i++) {
2209                 tx_buffer = &tdata->tx_buf[i];
2210
2211                 error = bus_dmamap_create(tdata->txtag,
2212                                           BUS_DMA_WAITOK | BUS_DMA_ONEBPAGE,
2213                                           &tx_buffer->map);
2214                 if (error) {
2215                         device_printf(dev, "Unable to create TX DMA map\n");
2216                         emx_destroy_tx_ring(tdata, i);
2217                         return error;
2218                 }
2219         }
2220
2221         /*
2222          * Setup TX parameters
2223          */
2224         tdata->spare_tx_desc = EMX_TX_SPARE;
2225         tdata->tx_wreg_nsegs = EMX_DEFAULT_TXWREG;
2226
2227         /*
2228          * Keep following relationship between spare_tx_desc, oact_tx_desc
2229          * and tx_intr_nsegs:
2230          * (spare_tx_desc + EMX_TX_RESERVED) <=
2231          * oact_tx_desc <= EMX_TX_OACTIVE_MAX <= tx_intr_nsegs
2232          */
2233         tdata->oact_tx_desc = tdata->num_tx_desc / 8;
2234         if (tdata->oact_tx_desc > EMX_TX_OACTIVE_MAX)
2235                 tdata->oact_tx_desc = EMX_TX_OACTIVE_MAX;
2236         if (tdata->oact_tx_desc < tdata->spare_tx_desc + EMX_TX_RESERVED)
2237                 tdata->oact_tx_desc = tdata->spare_tx_desc + EMX_TX_RESERVED;
2238
2239         tdata->tx_intr_nsegs = tdata->num_tx_desc / 16;
2240         if (tdata->tx_intr_nsegs < tdata->oact_tx_desc)
2241                 tdata->tx_intr_nsegs = tdata->oact_tx_desc;
2242
2243         /*
2244          * Pullup extra 4bytes into the first data segment for TSO, see:
2245          * 82571/82572 specification update errata #7
2246          *
2247          * Same applies to I217 (and maybe I218).
2248          *
2249          * NOTE:
2250          * 4bytes instead of 2bytes, which are mentioned in the errata,
2251          * are pulled; mainly to keep rest of the data properly aligned.
2252          */
2253         if (tdata->sc->hw.mac.type == e1000_82571 ||
2254             tdata->sc->hw.mac.type == e1000_82572 ||
2255             tdata->sc->hw.mac.type == e1000_pch_lpt)
2256                 tdata->tx_flags |= EMX_TXFLAG_TSO_PULLEX;
2257
2258         return (0);
2259 }
2260
2261 static void
2262 emx_init_tx_ring(struct emx_txdata *tdata)
2263 {
2264         /* Clear the old ring contents */
2265         bzero(tdata->tx_desc_base,
2266               sizeof(struct e1000_tx_desc) * tdata->num_tx_desc);
2267
2268         /* Reset state */
2269         tdata->next_avail_tx_desc = 0;
2270         tdata->next_tx_to_clean = 0;
2271         tdata->num_tx_desc_avail = tdata->num_tx_desc;
2272
2273         tdata->tx_flags |= EMX_TXFLAG_ENABLED;
2274         if (tdata->sc->tx_ring_inuse > 1) {
2275                 tdata->tx_flags |= EMX_TXFLAG_FORCECTX;
2276                 if (bootverbose) {
2277                         if_printf(&tdata->sc->arpcom.ac_if,
2278                             "TX %d force ctx setup\n", tdata->idx);
2279                 }
2280         }
2281 }
2282
2283 static void
2284 emx_init_tx_unit(struct emx_softc *sc)
2285 {
2286         uint32_t tctl, tarc, tipg = 0;
2287         int i;
2288
2289         for (i = 0; i < sc->tx_ring_inuse; ++i) {
2290                 struct emx_txdata *tdata = &sc->tx_data[i];
2291                 uint64_t bus_addr;
2292
2293                 /* Setup the Base and Length of the Tx Descriptor Ring */
2294                 bus_addr = tdata->tx_desc_paddr;
2295                 E1000_WRITE_REG(&sc->hw, E1000_TDLEN(i),
2296                     tdata->num_tx_desc * sizeof(struct e1000_tx_desc));
2297                 E1000_WRITE_REG(&sc->hw, E1000_TDBAH(i),
2298                     (uint32_t)(bus_addr >> 32));
2299                 E1000_WRITE_REG(&sc->hw, E1000_TDBAL(i),
2300                     (uint32_t)bus_addr);
2301                 /* Setup the HW Tx Head and Tail descriptor pointers */
2302                 E1000_WRITE_REG(&sc->hw, E1000_TDT(i), 0);
2303                 E1000_WRITE_REG(&sc->hw, E1000_TDH(i), 0);
2304         }
2305
2306         /* Set the default values for the Tx Inter Packet Gap timer */
2307         switch (sc->hw.mac.type) {
2308         case e1000_80003es2lan:
2309                 tipg = DEFAULT_82543_TIPG_IPGR1;
2310                 tipg |= DEFAULT_80003ES2LAN_TIPG_IPGR2 <<
2311                     E1000_TIPG_IPGR2_SHIFT;
2312                 break;
2313
2314         default:
2315                 if (sc->hw.phy.media_type == e1000_media_type_fiber ||
2316                     sc->hw.phy.media_type == e1000_media_type_internal_serdes)
2317                         tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
2318                 else
2319                         tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
2320                 tipg |= DEFAULT_82543_TIPG_IPGR1 << E1000_TIPG_IPGR1_SHIFT;
2321                 tipg |= DEFAULT_82543_TIPG_IPGR2 << E1000_TIPG_IPGR2_SHIFT;
2322                 break;
2323         }
2324
2325         E1000_WRITE_REG(&sc->hw, E1000_TIPG, tipg);
2326
2327         /* NOTE: 0 is not allowed for TIDV */
2328         E1000_WRITE_REG(&sc->hw, E1000_TIDV, 1);
2329         E1000_WRITE_REG(&sc->hw, E1000_TADV, 0);
2330
2331         if (sc->hw.mac.type == e1000_82571 ||
2332             sc->hw.mac.type == e1000_82572) {
2333                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
2334                 tarc |= EMX_TARC_SPEED_MODE;
2335                 E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
2336         } else if (sc->hw.mac.type == e1000_80003es2lan) {
2337                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
2338                 tarc |= 1;
2339                 E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
2340                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
2341                 tarc |= 1;
2342                 E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
2343         }
2344
2345         /* Program the Transmit Control Register */
2346         tctl = E1000_READ_REG(&sc->hw, E1000_TCTL);
2347         tctl &= ~E1000_TCTL_CT;
2348         tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC | E1000_TCTL_EN |
2349                 (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
2350         tctl |= E1000_TCTL_MULR;
2351
2352         /* This write will effectively turn on the transmit unit. */
2353         E1000_WRITE_REG(&sc->hw, E1000_TCTL, tctl);
2354
2355         if (sc->hw.mac.type == e1000_82571 ||
2356             sc->hw.mac.type == e1000_82572 ||
2357             sc->hw.mac.type == e1000_80003es2lan) {
2358                 /* Bit 28 of TARC1 must be cleared when MULR is enabled */
2359                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
2360                 tarc &= ~(1 << 28);
2361                 E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
2362         }
2363
2364         if (sc->tx_ring_inuse > 1) {
2365                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(0));
2366                 tarc &= ~EMX_TARC_COUNT_MASK;
2367                 tarc |= 1;
2368                 E1000_WRITE_REG(&sc->hw, E1000_TARC(0), tarc);
2369
2370                 tarc = E1000_READ_REG(&sc->hw, E1000_TARC(1));
2371                 tarc &= ~EMX_TARC_COUNT_MASK;
2372                 tarc |= 1;
2373                 E1000_WRITE_REG(&sc->hw, E1000_TARC(1), tarc);
2374         }
2375 }
2376
2377 static void
2378 emx_destroy_tx_ring(struct emx_txdata *tdata, int ndesc)
2379 {
2380         struct emx_txbuf *tx_buffer;
2381         int i;
2382
2383         /* Free Transmit Descriptor ring */
2384         if (tdata->tx_desc_base) {
2385                 bus_dmamap_unload(tdata->tx_desc_dtag, tdata->tx_desc_dmap);
2386                 bus_dmamem_free(tdata->tx_desc_dtag, tdata->tx_desc_base,
2387                                 tdata->tx_desc_dmap);
2388                 bus_dma_tag_destroy(tdata->tx_desc_dtag);
2389
2390                 tdata->tx_desc_base = NULL;
2391         }
2392
2393         if (tdata->tx_buf == NULL)
2394                 return;
2395
2396         for (i = 0; i < ndesc; i++) {
2397                 tx_buffer = &tdata->tx_buf[i];
2398
2399                 KKASSERT(tx_buffer->m_head == NULL);
2400                 bus_dmamap_destroy(tdata->txtag, tx_buffer->map);
2401         }
2402         bus_dma_tag_destroy(tdata->txtag);
2403
2404         kfree(tdata->tx_buf, M_DEVBUF);
2405         tdata->tx_buf = NULL;
2406 }
2407
2408 /*
2409  * The offload context needs to be set when we transfer the first
2410  * packet of a particular protocol (TCP/UDP).  This routine has been
2411  * enhanced to deal with inserted VLAN headers.
2412  *
2413  * If the new packet's ether header length, ip header length and
2414  * csum offloading type are same as the previous packet, we should
2415  * avoid allocating a new csum context descriptor; mainly to take
2416  * advantage of the pipeline effect of the TX data read request.
2417  *
2418  * This function returns number of TX descrptors allocated for
2419  * csum context.
2420  */
2421 static int
2422 emx_txcsum(struct emx_txdata *tdata, struct mbuf *mp,
2423            uint32_t *txd_upper, uint32_t *txd_lower)
2424 {
2425         struct e1000_context_desc *TXD;
2426         int curr_txd, ehdrlen, csum_flags;
2427         uint32_t cmd, hdr_len, ip_hlen;
2428
2429         csum_flags = mp->m_pkthdr.csum_flags & EMX_CSUM_FEATURES;
2430         ip_hlen = mp->m_pkthdr.csum_iphlen;
2431         ehdrlen = mp->m_pkthdr.csum_lhlen;
2432
2433         if ((tdata->tx_flags & EMX_TXFLAG_FORCECTX) == 0 &&
2434             tdata->csum_lhlen == ehdrlen && tdata->csum_iphlen == ip_hlen &&
2435             tdata->csum_flags == csum_flags) {
2436                 /*
2437                  * Same csum offload context as the previous packets;
2438                  * just return.
2439                  */
2440                 *txd_upper = tdata->csum_txd_upper;
2441                 *txd_lower = tdata->csum_txd_lower;
2442                 return 0;
2443         }
2444
2445         /*
2446          * Setup a new csum offload context.
2447          */
2448
2449         curr_txd = tdata->next_avail_tx_desc;
2450         TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
2451
2452         cmd = 0;
2453
2454         /* Setup of IP header checksum. */
2455         if (csum_flags & CSUM_IP) {
2456                 /*
2457                  * Start offset for header checksum calculation.
2458                  * End offset for header checksum calculation.
2459                  * Offset of place to put the checksum.
2460                  */
2461                 TXD->lower_setup.ip_fields.ipcss = ehdrlen;
2462                 TXD->lower_setup.ip_fields.ipcse =
2463                     htole16(ehdrlen + ip_hlen - 1);
2464                 TXD->lower_setup.ip_fields.ipcso =
2465                     ehdrlen + offsetof(struct ip, ip_sum);
2466                 cmd |= E1000_TXD_CMD_IP;
2467                 *txd_upper |= E1000_TXD_POPTS_IXSM << 8;
2468         }
2469         hdr_len = ehdrlen + ip_hlen;
2470
2471         if (csum_flags & CSUM_TCP) {
2472                 /*
2473                  * Start offset for payload checksum calculation.
2474                  * End offset for payload checksum calculation.
2475                  * Offset of place to put the checksum.
2476                  */
2477                 TXD->upper_setup.tcp_fields.tucss = hdr_len;
2478                 TXD->upper_setup.tcp_fields.tucse = htole16(0);
2479                 TXD->upper_setup.tcp_fields.tucso =
2480                     hdr_len + offsetof(struct tcphdr, th_sum);
2481                 cmd |= E1000_TXD_CMD_TCP;
2482                 *txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2483         } else if (csum_flags & CSUM_UDP) {
2484                 /*
2485                  * Start offset for header checksum calculation.
2486                  * End offset for header checksum calculation.
2487                  * Offset of place to put the checksum.
2488                  */
2489                 TXD->upper_setup.tcp_fields.tucss = hdr_len;
2490                 TXD->upper_setup.tcp_fields.tucse = htole16(0);
2491                 TXD->upper_setup.tcp_fields.tucso =
2492                     hdr_len + offsetof(struct udphdr, uh_sum);
2493                 *txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2494         }
2495
2496         *txd_lower = E1000_TXD_CMD_DEXT |       /* Extended descr type */
2497                      E1000_TXD_DTYP_D;          /* Data descr */
2498
2499         /* Save the information for this csum offloading context */
2500         tdata->csum_lhlen = ehdrlen;
2501         tdata->csum_iphlen = ip_hlen;
2502         tdata->csum_flags = csum_flags;
2503         tdata->csum_txd_upper = *txd_upper;
2504         tdata->csum_txd_lower = *txd_lower;
2505
2506         TXD->tcp_seg_setup.data = htole32(0);
2507         TXD->cmd_and_length =
2508             htole32(E1000_TXD_CMD_IFCS | E1000_TXD_CMD_DEXT | cmd);
2509
2510         if (++curr_txd == tdata->num_tx_desc)
2511                 curr_txd = 0;
2512
2513         KKASSERT(tdata->num_tx_desc_avail > 0);
2514         tdata->num_tx_desc_avail--;
2515
2516         tdata->next_avail_tx_desc = curr_txd;
2517         return 1;
2518 }
2519
2520 static void
2521 emx_txeof(struct emx_txdata *tdata)
2522 {
2523         struct ifnet *ifp = &tdata->sc->arpcom.ac_if;
2524         struct emx_txbuf *tx_buffer;
2525         int first, num_avail;
2526
2527         if (tdata->tx_dd_head == tdata->tx_dd_tail)
2528                 return;
2529
2530         if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2531                 return;
2532
2533         num_avail = tdata->num_tx_desc_avail;
2534         first = tdata->next_tx_to_clean;
2535
2536         while (tdata->tx_dd_head != tdata->tx_dd_tail) {
2537                 int dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2538                 struct e1000_tx_desc *tx_desc;
2539
2540                 tx_desc = &tdata->tx_desc_base[dd_idx];
2541                 if (tx_desc->upper.fields.status & E1000_TXD_STAT_DD) {
2542                         EMX_INC_TXDD_IDX(tdata->tx_dd_head);
2543
2544                         if (++dd_idx == tdata->num_tx_desc)
2545                                 dd_idx = 0;
2546
2547                         while (first != dd_idx) {
2548                                 logif(pkt_txclean);
2549
2550                                 num_avail++;
2551
2552                                 tx_buffer = &tdata->tx_buf[first];
2553                                 if (tx_buffer->m_head) {
2554                                         IFNET_STAT_INC(ifp, opackets, 1);
2555                                         bus_dmamap_unload(tdata->txtag,
2556                                                           tx_buffer->map);
2557                                         m_freem(tx_buffer->m_head);
2558                                         tx_buffer->m_head = NULL;
2559                                 }
2560
2561                                 if (++first == tdata->num_tx_desc)
2562                                         first = 0;
2563                         }
2564                 } else {
2565                         break;
2566                 }
2567         }
2568         tdata->next_tx_to_clean = first;
2569         tdata->num_tx_desc_avail = num_avail;
2570
2571         if (tdata->tx_dd_head == tdata->tx_dd_tail) {
2572                 tdata->tx_dd_head = 0;
2573                 tdata->tx_dd_tail = 0;
2574         }
2575
2576         if (!EMX_IS_OACTIVE(tdata)) {
2577                 ifsq_clr_oactive(tdata->ifsq);
2578
2579                 /* All clean, turn off the timer */
2580                 if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2581                         tdata->tx_watchdog.wd_timer = 0;
2582         }
2583 }
2584
2585 static void
2586 emx_tx_collect(struct emx_txdata *tdata)
2587 {
2588         struct ifnet *ifp = &tdata->sc->arpcom.ac_if;
2589         struct emx_txbuf *tx_buffer;
2590         int tdh, first, num_avail, dd_idx = -1;
2591
2592         if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2593                 return;
2594
2595         tdh = E1000_READ_REG(&tdata->sc->hw, E1000_TDH(tdata->idx));
2596         if (tdh == tdata->next_tx_to_clean)
2597                 return;
2598
2599         if (tdata->tx_dd_head != tdata->tx_dd_tail)
2600                 dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2601
2602         num_avail = tdata->num_tx_desc_avail;
2603         first = tdata->next_tx_to_clean;
2604
2605         while (first != tdh) {
2606                 logif(pkt_txclean);
2607
2608                 num_avail++;
2609
2610                 tx_buffer = &tdata->tx_buf[first];
2611                 if (tx_buffer->m_head) {
2612                         IFNET_STAT_INC(ifp, opackets, 1);
2613                         bus_dmamap_unload(tdata->txtag,
2614                                           tx_buffer->map);
2615                         m_freem(tx_buffer->m_head);
2616                         tx_buffer->m_head = NULL;
2617                 }
2618
2619                 if (first == dd_idx) {
2620                         EMX_INC_TXDD_IDX(tdata->tx_dd_head);
2621                         if (tdata->tx_dd_head == tdata->tx_dd_tail) {
2622                                 tdata->tx_dd_head = 0;
2623                                 tdata->tx_dd_tail = 0;
2624                                 dd_idx = -1;
2625                         } else {
2626                                 dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2627                         }
2628                 }
2629
2630                 if (++first == tdata->num_tx_desc)
2631                         first = 0;
2632         }
2633         tdata->next_tx_to_clean = first;
2634         tdata->num_tx_desc_avail = num_avail;
2635
2636         if (!EMX_IS_OACTIVE(tdata)) {
2637                 ifsq_clr_oactive(tdata->ifsq);
2638
2639                 /* All clean, turn off the timer */
2640                 if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2641                         tdata->tx_watchdog.wd_timer = 0;
2642         }
2643 }
2644
2645 /*
2646  * When Link is lost sometimes there is work still in the TX ring
2647  * which will result in a watchdog, rather than allow that do an
2648  * attempted cleanup and then reinit here.  Note that this has been
2649  * seens mostly with fiber adapters.
2650  */
2651 static void
2652 emx_tx_purge(struct emx_softc *sc)
2653 {
2654         int i;
2655
2656         if (sc->link_active)
2657                 return;
2658
2659         for (i = 0; i < sc->tx_ring_inuse; ++i) {
2660                 struct emx_txdata *tdata = &sc->tx_data[i];
2661
2662                 if (tdata->tx_watchdog.wd_timer) {
2663                         emx_tx_collect(tdata);
2664                         if (tdata->tx_watchdog.wd_timer) {
2665                                 if_printf(&sc->arpcom.ac_if,
2666                                     "Link lost, TX pending, reinit\n");
2667                                 emx_init(sc);
2668                                 return;
2669                         }
2670                 }
2671         }
2672 }
2673
2674 static int
2675 emx_newbuf(struct emx_rxdata *rdata, int i, int init)
2676 {
2677         struct mbuf *m;
2678         bus_dma_segment_t seg;
2679         bus_dmamap_t map;
2680         struct emx_rxbuf *rx_buffer;
2681         int error, nseg;
2682
2683         m = m_getcl(init ? M_WAITOK : M_NOWAIT, MT_DATA, M_PKTHDR);
2684         if (m == NULL) {
2685                 if (init) {
2686                         if_printf(&rdata->sc->arpcom.ac_if,
2687                                   "Unable to allocate RX mbuf\n");
2688                 }
2689                 return (ENOBUFS);
2690         }
2691         m->m_len = m->m_pkthdr.len = MCLBYTES;
2692
2693         if (rdata->sc->hw.mac.max_frame_size <= MCLBYTES - ETHER_ALIGN)
2694                 m_adj(m, ETHER_ALIGN);
2695
2696         error = bus_dmamap_load_mbuf_segment(rdata->rxtag,
2697                         rdata->rx_sparemap, m,
2698                         &seg, 1, &nseg, BUS_DMA_NOWAIT);
2699         if (error) {
2700                 m_freem(m);
2701                 if (init) {
2702                         if_printf(&rdata->sc->arpcom.ac_if,
2703                                   "Unable to load RX mbuf\n");
2704                 }
2705                 return (error);
2706         }
2707
2708         rx_buffer = &rdata->rx_buf[i];
2709         if (rx_buffer->m_head != NULL)
2710                 bus_dmamap_unload(rdata->rxtag, rx_buffer->map);
2711
2712         map = rx_buffer->map;
2713         rx_buffer->map = rdata->rx_sparemap;
2714         rdata->rx_sparemap = map;
2715
2716         rx_buffer->m_head = m;
2717         rx_buffer->paddr = seg.ds_addr;
2718
2719         emx_setup_rxdesc(&rdata->rx_desc[i], rx_buffer);
2720         return (0);
2721 }
2722
2723 static int
2724 emx_create_rx_ring(struct emx_rxdata *rdata)
2725 {
2726         device_t dev = rdata->sc->dev;
2727         struct emx_rxbuf *rx_buffer;
2728         int i, error, rsize, nrxd;
2729
2730         /*
2731          * Validate number of receive descriptors.  It must not exceed
2732          * hardware maximum, and must be multiple of E1000_DBA_ALIGN.
2733          */
2734         nrxd = device_getenv_int(dev, "rxd", emx_rxd);
2735         if ((nrxd * sizeof(emx_rxdesc_t)) % EMX_DBA_ALIGN != 0 ||
2736             nrxd > EMX_MAX_RXD || nrxd < EMX_MIN_RXD) {
2737                 device_printf(dev, "Using %d RX descriptors instead of %d!\n",
2738                     EMX_DEFAULT_RXD, nrxd);
2739                 rdata->num_rx_desc = EMX_DEFAULT_RXD;
2740         } else {
2741                 rdata->num_rx_desc = nrxd;
2742         }
2743
2744         /*
2745          * Allocate Receive Descriptor ring
2746          */
2747         rsize = roundup2(rdata->num_rx_desc * sizeof(emx_rxdesc_t),
2748                          EMX_DBA_ALIGN);
2749         rdata->rx_desc = bus_dmamem_coherent_any(rdata->sc->parent_dtag,
2750                                 EMX_DBA_ALIGN, rsize, BUS_DMA_WAITOK,
2751                                 &rdata->rx_desc_dtag, &rdata->rx_desc_dmap,
2752                                 &rdata->rx_desc_paddr);
2753         if (rdata->rx_desc == NULL) {
2754                 device_printf(dev, "Unable to allocate rx_desc memory\n");
2755                 return ENOMEM;
2756         }
2757
2758         rsize = __VM_CACHELINE_ALIGN(
2759             sizeof(struct emx_rxbuf) * rdata->num_rx_desc);
2760         rdata->rx_buf = kmalloc_cachealign(rsize, M_DEVBUF, M_WAITOK | M_ZERO);
2761
2762         /*
2763          * Create DMA tag for rx buffers
2764          */
2765         error = bus_dma_tag_create(rdata->sc->parent_dtag, /* parent */
2766                         1, 0,                   /* alignment, bounds */
2767                         BUS_SPACE_MAXADDR,      /* lowaddr */
2768                         BUS_SPACE_MAXADDR,      /* highaddr */
2769                         NULL, NULL,             /* filter, filterarg */
2770                         MCLBYTES,               /* maxsize */
2771                         1,                      /* nsegments */
2772                         MCLBYTES,               /* maxsegsize */
2773                         BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, /* flags */
2774                         &rdata->rxtag);
2775         if (error) {
2776                 device_printf(dev, "Unable to allocate RX DMA tag\n");
2777                 kfree(rdata->rx_buf, M_DEVBUF);
2778                 rdata->rx_buf = NULL;
2779                 return error;
2780         }
2781
2782         /*
2783          * Create spare DMA map for rx buffers
2784          */
2785         error = bus_dmamap_create(rdata->rxtag, BUS_DMA_WAITOK,
2786                                   &rdata->rx_sparemap);
2787         if (error) {
2788                 device_printf(dev, "Unable to create spare RX DMA map\n");
2789                 bus_dma_tag_destroy(rdata->rxtag);
2790                 kfree(rdata->rx_buf, M_DEVBUF);
2791                 rdata->rx_buf = NULL;
2792                 return error;
2793         }
2794
2795         /*
2796          * Create DMA maps for rx buffers
2797          */
2798         for (i = 0; i < rdata->num_rx_desc; i++) {
2799                 rx_buffer = &rdata->rx_buf[i];
2800
2801                 error = bus_dmamap_create(rdata->rxtag, BUS_DMA_WAITOK,
2802                                           &rx_buffer->map);
2803                 if (error) {
2804                         device_printf(dev, "Unable to create RX DMA map\n");
2805                         emx_destroy_rx_ring(rdata, i);
2806                         return error;
2807                 }
2808         }
2809         return (0);
2810 }
2811
2812 static void
2813 emx_free_rx_ring(struct emx_rxdata *rdata)
2814 {
2815         int i;
2816
2817         for (i = 0; i < rdata->num_rx_desc; i++) {
2818                 struct emx_rxbuf *rx_buffer = &rdata->rx_buf[i];
2819
2820                 if (rx_buffer->m_head != NULL) {
2821                         bus_dmamap_unload(rdata->rxtag, rx_buffer->map);
2822                         m_freem(rx_buffer->m_head);
2823                         rx_buffer->m_head = NULL;
2824                 }
2825         }
2826
2827         if (rdata->fmp != NULL)
2828                 m_freem(rdata->fmp);
2829         rdata->fmp = NULL;
2830         rdata->lmp = NULL;
2831 }
2832
2833 static void
2834 emx_free_tx_ring(struct emx_txdata *tdata)
2835 {
2836         int i;
2837
2838         for (i = 0; i < tdata->num_tx_desc; i++) {
2839                 struct emx_txbuf *tx_buffer = &tdata->tx_buf[i];
2840
2841                 if (tx_buffer->m_head != NULL) {
2842                         bus_dmamap_unload(tdata->txtag, tx_buffer->map);
2843                         m_freem(tx_buffer->m_head);
2844                         tx_buffer->m_head = NULL;
2845                 }
2846         }
2847
2848         tdata->tx_flags &= ~EMX_TXFLAG_FORCECTX;
2849
2850         tdata->csum_flags = 0;
2851         tdata->csum_lhlen = 0;
2852         tdata->csum_iphlen = 0;
2853         tdata->csum_thlen = 0;
2854         tdata->csum_mss = 0;
2855         tdata->csum_pktlen = 0;
2856
2857         tdata->tx_dd_head = 0;
2858         tdata->tx_dd_tail = 0;
2859         tdata->tx_nsegs = 0;
2860 }
2861
2862 static int
2863 emx_init_rx_ring(struct emx_rxdata *rdata)
2864 {
2865         int i, error;
2866
2867         /* Reset descriptor ring */
2868         bzero(rdata->rx_desc, sizeof(emx_rxdesc_t) * rdata->num_rx_desc);
2869
2870         /* Allocate new ones. */
2871         for (i = 0; i < rdata->num_rx_desc; i++) {
2872                 error = emx_newbuf(rdata, i, 1);
2873                 if (error)
2874                         return (error);
2875         }
2876
2877         /* Setup our descriptor pointers */
2878         rdata->next_rx_desc_to_check = 0;
2879
2880         return (0);
2881 }
2882
2883 static void
2884 emx_init_rx_unit(struct emx_softc *sc)
2885 {
2886         struct ifnet *ifp = &sc->arpcom.ac_if;
2887         uint64_t bus_addr;
2888         uint32_t rctl, itr, rfctl;
2889         int i;
2890
2891         /*
2892          * Make sure receives are disabled while setting
2893          * up the descriptor ring
2894          */
2895         rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
2896         E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
2897
2898         /*
2899          * Set the interrupt throttling rate. Value is calculated
2900          * as ITR = 1 / (INT_THROTTLE_CEIL * 256ns)
2901          */
2902         if (sc->int_throttle_ceil)
2903                 itr = 1000000000 / 256 / sc->int_throttle_ceil;
2904         else
2905                 itr = 0;
2906         emx_set_itr(sc, itr);
2907
2908         /* Use extended RX descriptor */
2909         rfctl = E1000_RFCTL_EXTEN;
2910
2911         /* Disable accelerated ackknowledge */
2912         if (sc->hw.mac.type == e1000_82574)
2913                 rfctl |= E1000_RFCTL_ACK_DIS;
2914
2915         E1000_WRITE_REG(&sc->hw, E1000_RFCTL, rfctl);
2916
2917         /*
2918          * Receive Checksum Offload for TCP and UDP
2919          *
2920          * Checksum offloading is also enabled if multiple receive
2921          * queue is to be supported, since we need it to figure out
2922          * packet type.
2923          */
2924         if ((ifp->if_capenable & IFCAP_RXCSUM) ||
2925             sc->rx_ring_cnt > 1) {
2926                 uint32_t rxcsum;
2927
2928                 rxcsum = E1000_READ_REG(&sc->hw, E1000_RXCSUM);
2929
2930                 /*
2931                  * NOTE:
2932                  * PCSD must be enabled to enable multiple
2933                  * receive queues.
2934                  */
2935                 rxcsum |= E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL |
2936                           E1000_RXCSUM_PCSD;
2937                 E1000_WRITE_REG(&sc->hw, E1000_RXCSUM, rxcsum);
2938         }
2939
2940         /*
2941          * Configure multiple receive queue (RSS)
2942          */
2943         if (sc->rx_ring_cnt > 1) {
2944                 uint8_t key[EMX_NRSSRK * EMX_RSSRK_SIZE];
2945                 uint32_t reta;
2946
2947                 KASSERT(sc->rx_ring_cnt == EMX_NRX_RING,
2948                     ("invalid number of RX ring (%d)", sc->rx_ring_cnt));
2949
2950                 /*
2951                  * NOTE:
2952                  * When we reach here, RSS has already been disabled
2953                  * in emx_stop(), so we could safely configure RSS key
2954                  * and redirect table.
2955                  */
2956
2957                 /*
2958                  * Configure RSS key
2959                  */
2960                 toeplitz_get_key(key, sizeof(key));
2961                 for (i = 0; i < EMX_NRSSRK; ++i) {
2962                         uint32_t rssrk;
2963
2964                         rssrk = EMX_RSSRK_VAL(key, i);
2965                         EMX_RSS_DPRINTF(sc, 1, "rssrk%d 0x%08x\n", i, rssrk);
2966
2967                         E1000_WRITE_REG(&sc->hw, E1000_RSSRK(i), rssrk);
2968                 }
2969
2970                 /*
2971                  * Configure RSS redirect table in following fashion:
2972                  * (hash & ring_cnt_mask) == rdr_table[(hash & rdr_table_mask)]
2973                  */
2974                 reta = 0;
2975                 for (i = 0; i < EMX_RETA_SIZE; ++i) {
2976                         uint32_t q;
2977
2978                         q = (i % sc->rx_ring_cnt) << EMX_RETA_RINGIDX_SHIFT;
2979                         reta |= q << (8 * i);
2980                 }
2981                 EMX_RSS_DPRINTF(sc, 1, "reta 0x%08x\n", reta);
2982
2983                 for (i = 0; i < EMX_NRETA; ++i)
2984                         E1000_WRITE_REG(&sc->hw, E1000_RETA(i), reta);
2985
2986                 /*
2987                  * Enable multiple receive queues.
2988                  * Enable IPv4 RSS standard hash functions.
2989                  * Disable RSS interrupt.
2990                  */
2991                 E1000_WRITE_REG(&sc->hw, E1000_MRQC,
2992                                 E1000_MRQC_ENABLE_RSS_2Q |
2993                                 E1000_MRQC_RSS_FIELD_IPV4_TCP |
2994                                 E1000_MRQC_RSS_FIELD_IPV4);
2995         }
2996
2997         /*
2998          * XXX TEMPORARY WORKAROUND: on some systems with 82573
2999          * long latencies are observed, like Lenovo X60. This
3000          * change eliminates the problem, but since having positive
3001          * values in RDTR is a known source of problems on other
3002          * platforms another solution is being sought.
3003          */
3004         if (emx_82573_workaround && sc->hw.mac.type == e1000_82573) {
3005                 E1000_WRITE_REG(&sc->hw, E1000_RADV, EMX_RADV_82573);
3006                 E1000_WRITE_REG(&sc->hw, E1000_RDTR, EMX_RDTR_82573);
3007         }
3008
3009         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3010                 struct emx_rxdata *rdata = &sc->rx_data[i];
3011
3012                 /*
3013                  * Setup the Base and Length of the Rx Descriptor Ring
3014                  */
3015                 bus_addr = rdata->rx_desc_paddr;
3016                 E1000_WRITE_REG(&sc->hw, E1000_RDLEN(i),
3017                     rdata->num_rx_desc * sizeof(emx_rxdesc_t));
3018                 E1000_WRITE_REG(&sc->hw, E1000_RDBAH(i),
3019                     (uint32_t)(bus_addr >> 32));
3020                 E1000_WRITE_REG(&sc->hw, E1000_RDBAL(i),
3021                     (uint32_t)bus_addr);
3022
3023                 /*
3024                  * Setup the HW Rx Head and Tail Descriptor Pointers
3025                  */
3026                 E1000_WRITE_REG(&sc->hw, E1000_RDH(i), 0);
3027                 E1000_WRITE_REG(&sc->hw, E1000_RDT(i),
3028                     sc->rx_data[i].num_rx_desc - 1);
3029         }
3030
3031         if (sc->hw.mac.type >= e1000_pch2lan) {
3032                 if (ifp->if_mtu > ETHERMTU)
3033                         e1000_lv_jumbo_workaround_ich8lan(&sc->hw, TRUE);
3034                 else
3035                         e1000_lv_jumbo_workaround_ich8lan(&sc->hw, FALSE);
3036         }
3037
3038         /* Setup the Receive Control Register */
3039         rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
3040         rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO |
3041                 E1000_RCTL_RDMTS_HALF | E1000_RCTL_SECRC |
3042                 (sc->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
3043
3044         /* Make sure VLAN Filters are off */
3045         rctl &= ~E1000_RCTL_VFE;
3046
3047         /* Don't store bad paket */
3048         rctl &= ~E1000_RCTL_SBP;
3049
3050         /* MCLBYTES */
3051         rctl |= E1000_RCTL_SZ_2048;
3052
3053         if (ifp->if_mtu > ETHERMTU)
3054                 rctl |= E1000_RCTL_LPE;
3055         else
3056                 rctl &= ~E1000_RCTL_LPE;
3057
3058         /* Enable Receives */
3059         E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl);
3060 }
3061
3062 static void
3063 emx_destroy_rx_ring(struct emx_rxdata *rdata, int ndesc)
3064 {
3065         struct emx_rxbuf *rx_buffer;
3066         int i;
3067
3068         /* Free Receive Descriptor ring */
3069         if (rdata->rx_desc) {
3070                 bus_dmamap_unload(rdata->rx_desc_dtag, rdata->rx_desc_dmap);
3071                 bus_dmamem_free(rdata->rx_desc_dtag, rdata->rx_desc,
3072                                 rdata->rx_desc_dmap);
3073                 bus_dma_tag_destroy(rdata->rx_desc_dtag);
3074
3075                 rdata->rx_desc = NULL;
3076         }
3077
3078         if (rdata->rx_buf == NULL)
3079                 return;
3080
3081         for (i = 0; i < ndesc; i++) {
3082                 rx_buffer = &rdata->rx_buf[i];
3083
3084                 KKASSERT(rx_buffer->m_head == NULL);
3085                 bus_dmamap_destroy(rdata->rxtag, rx_buffer->map);
3086         }
3087         bus_dmamap_destroy(rdata->rxtag, rdata->rx_sparemap);
3088         bus_dma_tag_destroy(rdata->rxtag);
3089
3090         kfree(rdata->rx_buf, M_DEVBUF);
3091         rdata->rx_buf = NULL;
3092 }
3093
3094 static void
3095 emx_rxeof(struct emx_rxdata *rdata, int count)
3096 {
3097         struct ifnet *ifp = &rdata->sc->arpcom.ac_if;
3098         uint32_t staterr;
3099         emx_rxdesc_t *current_desc;
3100         struct mbuf *mp;
3101         int i, cpuid = mycpuid;
3102
3103         i = rdata->next_rx_desc_to_check;
3104         current_desc = &rdata->rx_desc[i];
3105         staterr = le32toh(current_desc->rxd_staterr);
3106
3107         if (!(staterr & E1000_RXD_STAT_DD))
3108                 return;
3109
3110         while ((staterr & E1000_RXD_STAT_DD) && count != 0) {
3111                 struct pktinfo *pi = NULL, pi0;
3112                 struct emx_rxbuf *rx_buf = &rdata->rx_buf[i];
3113                 struct mbuf *m = NULL;
3114                 int eop, len;
3115
3116                 logif(pkt_receive);
3117
3118                 mp = rx_buf->m_head;
3119
3120                 /*
3121                  * Can't defer bus_dmamap_sync(9) because TBI_ACCEPT
3122                  * needs to access the last received byte in the mbuf.
3123                  */
3124                 bus_dmamap_sync(rdata->rxtag, rx_buf->map,
3125                                 BUS_DMASYNC_POSTREAD);
3126
3127                 len = le16toh(current_desc->rxd_length);
3128                 if (staterr & E1000_RXD_STAT_EOP) {
3129                         count--;
3130                         eop = 1;
3131                 } else {
3132                         eop = 0;
3133                 }
3134
3135                 if (!(staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK)) {
3136                         uint16_t vlan = 0;
3137                         uint32_t mrq, rss_hash;
3138
3139                         /*
3140                          * Save several necessary information,
3141                          * before emx_newbuf() destroy it.
3142                          */
3143                         if ((staterr & E1000_RXD_STAT_VP) && eop)
3144                                 vlan = le16toh(current_desc->rxd_vlan);
3145
3146                         mrq = le32toh(current_desc->rxd_mrq);
3147                         rss_hash = le32toh(current_desc->rxd_rss);
3148
3149                         EMX_RSS_DPRINTF(rdata->sc, 10,
3150                             "ring%d, mrq 0x%08x, rss_hash 0x%08x\n",
3151                             rdata->idx, mrq, rss_hash);
3152
3153                         if (emx_newbuf(rdata, i, 0) != 0) {
3154                                 IFNET_STAT_INC(ifp, iqdrops, 1);
3155                                 goto discard;
3156                         }
3157
3158                         /* Assign correct length to the current fragment */
3159                         mp->m_len = len;
3160
3161                         if (rdata->fmp == NULL) {
3162                                 mp->m_pkthdr.len = len;
3163                                 rdata->fmp = mp; /* Store the first mbuf */
3164                                 rdata->lmp = mp;
3165                         } else {
3166                                 /*
3167                                  * Chain mbuf's together
3168                                  */
3169                                 rdata->lmp->m_next = mp;
3170                                 rdata->lmp = rdata->lmp->m_next;
3171                                 rdata->fmp->m_pkthdr.len += len;
3172                         }
3173
3174                         if (eop) {
3175                                 rdata->fmp->m_pkthdr.rcvif = ifp;
3176                                 IFNET_STAT_INC(ifp, ipackets, 1);
3177
3178                                 if (ifp->if_capenable & IFCAP_RXCSUM)
3179                                         emx_rxcsum(staterr, rdata->fmp);
3180
3181                                 if (staterr & E1000_RXD_STAT_VP) {
3182                                         rdata->fmp->m_pkthdr.ether_vlantag =
3183                                             vlan;
3184                                         rdata->fmp->m_flags |= M_VLANTAG;
3185                                 }
3186                                 m = rdata->fmp;
3187                                 rdata->fmp = NULL;
3188                                 rdata->lmp = NULL;
3189
3190                                 if (ifp->if_capenable & IFCAP_RSS) {
3191                                         pi = emx_rssinfo(m, &pi0, mrq,
3192                                                          rss_hash, staterr);
3193                                 }
3194 #ifdef EMX_RSS_DEBUG
3195                                 rdata->rx_pkts++;
3196 #endif
3197                         }
3198                 } else {
3199                         IFNET_STAT_INC(ifp, ierrors, 1);
3200 discard:
3201                         emx_setup_rxdesc(current_desc, rx_buf);
3202                         if (rdata->fmp != NULL) {
3203                                 m_freem(rdata->fmp);
3204                                 rdata->fmp = NULL;
3205                                 rdata->lmp = NULL;
3206                         }
3207                         m = NULL;
3208                 }
3209
3210                 if (m != NULL)
3211                         ifp->if_input(ifp, m, pi, cpuid);
3212
3213                 /* Advance our pointers to the next descriptor. */
3214                 if (++i == rdata->num_rx_desc)
3215                         i = 0;
3216
3217                 current_desc = &rdata->rx_desc[i];
3218                 staterr = le32toh(current_desc->rxd_staterr);
3219         }
3220         rdata->next_rx_desc_to_check = i;
3221
3222         /* Advance the E1000's Receive Queue "Tail Pointer". */
3223         if (--i < 0)
3224                 i = rdata->num_rx_desc - 1;
3225         E1000_WRITE_REG(&rdata->sc->hw, E1000_RDT(rdata->idx), i);
3226 }
3227
3228 static void
3229 emx_enable_intr(struct emx_softc *sc)
3230 {
3231         uint32_t ims_mask = IMS_ENABLE_MASK;
3232
3233         lwkt_serialize_handler_enable(&sc->main_serialize);
3234
3235 #if 0
3236         if (sc->hw.mac.type == e1000_82574) {
3237                 E1000_WRITE_REG(hw, EMX_EIAC, EM_MSIX_MASK);
3238                 ims_mask |= EM_MSIX_MASK;
3239         }
3240 #endif
3241         E1000_WRITE_REG(&sc->hw, E1000_IMS, ims_mask);
3242 }
3243
3244 static void
3245 emx_disable_intr(struct emx_softc *sc)
3246 {
3247         if (sc->hw.mac.type == e1000_82574)
3248                 E1000_WRITE_REG(&sc->hw, EMX_EIAC, 0);
3249         E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
3250
3251         lwkt_serialize_handler_disable(&sc->main_serialize);
3252 }
3253
3254 /*
3255  * Bit of a misnomer, what this really means is
3256  * to enable OS management of the system... aka
3257  * to disable special hardware management features 
3258  */
3259 static void
3260 emx_get_mgmt(struct emx_softc *sc)
3261 {
3262         /* A shared code workaround */
3263         if (sc->flags & EMX_FLAG_HAS_MGMT) {
3264                 int manc2h = E1000_READ_REG(&sc->hw, E1000_MANC2H);
3265                 int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
3266
3267                 /* disable hardware interception of ARP */
3268                 manc &= ~(E1000_MANC_ARP_EN);
3269
3270                 /* enable receiving management packets to the host */
3271                 manc |= E1000_MANC_EN_MNG2HOST;
3272 #define E1000_MNG2HOST_PORT_623 (1 << 5)
3273 #define E1000_MNG2HOST_PORT_664 (1 << 6)
3274                 manc2h |= E1000_MNG2HOST_PORT_623;
3275                 manc2h |= E1000_MNG2HOST_PORT_664;
3276                 E1000_WRITE_REG(&sc->hw, E1000_MANC2H, manc2h);
3277
3278                 E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
3279         }
3280 }
3281
3282 /*
3283  * Give control back to hardware management
3284  * controller if there is one.
3285  */
3286 static void
3287 emx_rel_mgmt(struct emx_softc *sc)
3288 {
3289         if (sc->flags & EMX_FLAG_HAS_MGMT) {
3290                 int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
3291
3292                 /* re-enable hardware interception of ARP */
3293                 manc |= E1000_MANC_ARP_EN;
3294                 manc &= ~E1000_MANC_EN_MNG2HOST;
3295
3296                 E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
3297         }
3298 }
3299
3300 /*
3301  * emx_get_hw_control() sets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3302  * For ASF and Pass Through versions of f/w this means that
3303  * the driver is loaded.  For AMT version (only with 82573)
3304  * of the f/w this means that the network i/f is open.
3305  */
3306 static void
3307 emx_get_hw_control(struct emx_softc *sc)
3308 {
3309         /* Let firmware know the driver has taken over */
3310         if (sc->hw.mac.type == e1000_82573) {
3311                 uint32_t swsm;
3312
3313                 swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
3314                 E1000_WRITE_REG(&sc->hw, E1000_SWSM,
3315                     swsm | E1000_SWSM_DRV_LOAD);
3316         } else {
3317                 uint32_t ctrl_ext;
3318
3319                 ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
3320                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
3321                     ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
3322         }
3323         sc->flags |= EMX_FLAG_HW_CTRL;
3324 }
3325
3326 /*
3327  * emx_rel_hw_control() resets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3328  * For ASF and Pass Through versions of f/w this means that the
3329  * driver is no longer loaded.  For AMT version (only with 82573)
3330  * of the f/w this means that the network i/f is closed.
3331  */
3332 static void
3333 emx_rel_hw_control(struct emx_softc *sc)
3334 {
3335         if ((sc->flags & EMX_FLAG_HW_CTRL) == 0)
3336                 return;
3337         sc->flags &= ~EMX_FLAG_HW_CTRL;
3338
3339         /* Let firmware taken over control of h/w */
3340         if (sc->hw.mac.type == e1000_82573) {
3341                 uint32_t swsm;
3342
3343                 swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
3344                 E1000_WRITE_REG(&sc->hw, E1000_SWSM,
3345                     swsm & ~E1000_SWSM_DRV_LOAD);
3346         } else {
3347                 uint32_t ctrl_ext;
3348
3349                 ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
3350                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
3351                     ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
3352         }
3353 }
3354
3355 static int
3356 emx_is_valid_eaddr(const uint8_t *addr)
3357 {
3358         char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
3359
3360         if ((addr[0] & 1) || !bcmp(addr, zero_addr, ETHER_ADDR_LEN))
3361                 return (FALSE);
3362
3363         return (TRUE);
3364 }
3365
3366 /*
3367  * Enable PCI Wake On Lan capability
3368  */
3369 void
3370 emx_enable_wol(device_t dev)
3371 {
3372         uint16_t cap, status;
3373         uint8_t id;
3374
3375         /* First find the capabilities pointer*/
3376         cap = pci_read_config(dev, PCIR_CAP_PTR, 2);
3377
3378         /* Read the PM Capabilities */
3379         id = pci_read_config(dev, cap, 1);
3380         if (id != PCIY_PMG)     /* Something wrong */
3381                 return;
3382
3383         /*
3384          * OK, we have the power capabilities,
3385          * so now get the status register
3386          */
3387         cap += PCIR_POWER_STATUS;
3388         status = pci_read_config(dev, cap, 2);
3389         status |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
3390         pci_write_config(dev, cap, status, 2);
3391 }
3392
3393 static void
3394 emx_update_stats(struct emx_softc *sc)
3395 {
3396         struct ifnet *ifp = &sc->arpcom.ac_if;
3397
3398         if (sc->hw.phy.media_type == e1000_media_type_copper ||
3399             (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_LU)) {
3400                 sc->stats.symerrs += E1000_READ_REG(&sc->hw, E1000_SYMERRS);
3401                 sc->stats.sec += E1000_READ_REG(&sc->hw, E1000_SEC);
3402         }
3403         sc->stats.crcerrs += E1000_READ_REG(&sc->hw, E1000_CRCERRS);
3404         sc->stats.mpc += E1000_READ_REG(&sc->hw, E1000_MPC);
3405         sc->stats.scc += E1000_READ_REG(&sc->hw, E1000_SCC);
3406         sc->stats.ecol += E1000_READ_REG(&sc->hw, E1000_ECOL);
3407
3408         sc->stats.mcc += E1000_READ_REG(&sc->hw, E1000_MCC);
3409         sc->stats.latecol += E1000_READ_REG(&sc->hw, E1000_LATECOL);
3410         sc->stats.colc += E1000_READ_REG(&sc->hw, E1000_COLC);
3411         sc->stats.dc += E1000_READ_REG(&sc->hw, E1000_DC);
3412         sc->stats.rlec += E1000_READ_REG(&sc->hw, E1000_RLEC);
3413         sc->stats.xonrxc += E1000_READ_REG(&sc->hw, E1000_XONRXC);
3414         sc->stats.xontxc += E1000_READ_REG(&sc->hw, E1000_XONTXC);
3415         sc->stats.xoffrxc += E1000_READ_REG(&sc->hw, E1000_XOFFRXC);
3416         sc->stats.xofftxc += E1000_READ_REG(&sc->hw, E1000_XOFFTXC);
3417         sc->stats.fcruc += E1000_READ_REG(&sc->hw, E1000_FCRUC);
3418         sc->stats.prc64 += E1000_READ_REG(&sc->hw, E1000_PRC64);
3419         sc->stats.prc127 += E1000_READ_REG(&sc->hw, E1000_PRC127);
3420         sc->stats.prc255 += E1000_READ_REG(&sc->hw, E1000_PRC255);
3421         sc->stats.prc511 += E1000_READ_REG(&sc->hw, E1000_PRC511);
3422         sc->stats.prc1023 += E1000_READ_REG(&sc->hw, E1000_PRC1023);
3423         sc->stats.prc1522 += E1000_READ_REG(&sc->hw, E1000_PRC1522);
3424         sc->stats.gprc += E1000_READ_REG(&sc->hw, E1000_GPRC);
3425         sc->stats.bprc += E1000_READ_REG(&sc->hw, E1000_BPRC);
3426         sc->stats.mprc += E1000_READ_REG(&sc->hw, E1000_MPRC);
3427         sc->stats.gptc += E1000_READ_REG(&sc->hw, E1000_GPTC);
3428
3429         /* For the 64-bit byte counters the low dword must be read first. */
3430         /* Both registers clear on the read of the high dword */
3431
3432         sc->stats.gorc += E1000_READ_REG(&sc->hw, E1000_GORCH);
3433         sc->stats.gotc += E1000_READ_REG(&sc->hw, E1000_GOTCH);
3434
3435         sc->stats.rnbc += E1000_READ_REG(&sc->hw, E1000_RNBC);
3436         sc->stats.ruc += E1000_READ_REG(&sc->hw, E1000_RUC);
3437         sc->stats.rfc += E1000_READ_REG(&sc->hw, E1000_RFC);
3438         sc->stats.roc += E1000_READ_REG(&sc->hw, E1000_ROC);
3439         sc->stats.rjc += E1000_READ_REG(&sc->hw, E1000_RJC);
3440
3441         sc->stats.tor += E1000_READ_REG(&sc->hw, E1000_TORH);
3442         sc->stats.tot += E1000_READ_REG(&sc->hw, E1000_TOTH);
3443
3444         sc->stats.tpr += E1000_READ_REG(&sc->hw, E1000_TPR);
3445         sc->stats.tpt += E1000_READ_REG(&sc->hw, E1000_TPT);
3446         sc->stats.ptc64 += E1000_READ_REG(&sc->hw, E1000_PTC64);
3447         sc->stats.ptc127 += E1000_READ_REG(&sc->hw, E1000_PTC127);
3448         sc->stats.ptc255 += E1000_READ_REG(&sc->hw, E1000_PTC255);
3449         sc->stats.ptc511 += E1000_READ_REG(&sc->hw, E1000_PTC511);
3450         sc->stats.ptc1023 += E1000_READ_REG(&sc->hw, E1000_PTC1023);
3451         sc->stats.ptc1522 += E1000_READ_REG(&sc->hw, E1000_PTC1522);
3452         sc->stats.mptc += E1000_READ_REG(&sc->hw, E1000_MPTC);
3453         sc->stats.bptc += E1000_READ_REG(&sc->hw, E1000_BPTC);
3454
3455         sc->stats.algnerrc += E1000_READ_REG(&sc->hw, E1000_ALGNERRC);
3456         sc->stats.rxerrc += E1000_READ_REG(&sc->hw, E1000_RXERRC);
3457         sc->stats.tncrs += E1000_READ_REG(&sc->hw, E1000_TNCRS);
3458         sc->stats.cexterr += E1000_READ_REG(&sc->hw, E1000_CEXTERR);
3459         sc->stats.tsctc += E1000_READ_REG(&sc->hw, E1000_TSCTC);
3460         sc->stats.tsctfc += E1000_READ_REG(&sc->hw, E1000_TSCTFC);
3461
3462         IFNET_STAT_SET(ifp, collisions, sc->stats.colc);
3463
3464         /* Rx Errors */
3465         IFNET_STAT_SET(ifp, ierrors,
3466             sc->stats.rxerrc + sc->stats.crcerrs + sc->stats.algnerrc +
3467             sc->stats.ruc + sc->stats.roc + sc->stats.mpc + sc->stats.cexterr);
3468
3469         /* Tx Errors */
3470         IFNET_STAT_SET(ifp, oerrors, sc->stats.ecol + sc->stats.latecol);
3471 }
3472
3473 static void
3474 emx_print_debug_info(struct emx_softc *sc)
3475 {
3476         device_t dev = sc->dev;
3477         uint8_t *hw_addr = sc->hw.hw_addr;
3478         int i;
3479
3480         device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
3481         device_printf(dev, "CTRL = 0x%x RCTL = 0x%x \n",
3482             E1000_READ_REG(&sc->hw, E1000_CTRL),
3483             E1000_READ_REG(&sc->hw, E1000_RCTL));
3484         device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk \n",
3485             ((E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff0000) >> 16),\
3486             (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) );
3487         device_printf(dev, "Flow control watermarks high = %d low = %d\n",
3488             sc->hw.fc.high_water, sc->hw.fc.low_water);
3489         device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
3490             E1000_READ_REG(&sc->hw, E1000_TIDV),
3491             E1000_READ_REG(&sc->hw, E1000_TADV));
3492         device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
3493             E1000_READ_REG(&sc->hw, E1000_RDTR),
3494             E1000_READ_REG(&sc->hw, E1000_RADV));
3495
3496         for (i = 0; i < sc->tx_ring_cnt; ++i) {
3497                 device_printf(dev, "hw %d tdh = %d, hw tdt = %d\n", i,
3498                     E1000_READ_REG(&sc->hw, E1000_TDH(i)),
3499                     E1000_READ_REG(&sc->hw, E1000_TDT(i)));
3500         }
3501         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3502                 device_printf(dev, "hw %d rdh = %d, hw rdt = %d\n", i,
3503                     E1000_READ_REG(&sc->hw, E1000_RDH(i)),
3504                     E1000_READ_REG(&sc->hw, E1000_RDT(i)));
3505         }
3506
3507         for (i = 0; i < sc->tx_ring_cnt; ++i) {
3508                 device_printf(dev, "TX %d Tx descriptors avail = %d\n", i,
3509                     sc->tx_data[i].num_tx_desc_avail);
3510                 device_printf(dev, "TX %d TSO segments = %lu\n", i,
3511                     sc->tx_data[i].tso_segments);
3512                 device_printf(dev, "TX %d TSO ctx reused = %lu\n", i,
3513                     sc->tx_data[i].tso_ctx_reused);
3514         }
3515 }
3516
3517 static void
3518 emx_print_hw_stats(struct emx_softc *sc)
3519 {
3520         device_t dev = sc->dev;
3521
3522         device_printf(dev, "Excessive collisions = %lld\n",
3523             (long long)sc->stats.ecol);
3524 #if (DEBUG_HW > 0)  /* Dont output these errors normally */
3525         device_printf(dev, "Symbol errors = %lld\n",
3526             (long long)sc->stats.symerrs);
3527 #endif
3528         device_printf(dev, "Sequence errors = %lld\n",
3529             (long long)sc->stats.sec);
3530         device_printf(dev, "Defer count = %lld\n",
3531             (long long)sc->stats.dc);
3532         device_printf(dev, "Missed Packets = %lld\n",
3533             (long long)sc->stats.mpc);
3534         device_printf(dev, "Receive No Buffers = %lld\n",
3535             (long long)sc->stats.rnbc);
3536         /* RLEC is inaccurate on some hardware, calculate our own. */
3537         device_printf(dev, "Receive Length Errors = %lld\n",
3538             ((long long)sc->stats.roc + (long long)sc->stats.ruc));
3539         device_printf(dev, "Receive errors = %lld\n",
3540             (long long)sc->stats.rxerrc);
3541         device_printf(dev, "Crc errors = %lld\n",
3542             (long long)sc->stats.crcerrs);
3543         device_printf(dev, "Alignment errors = %lld\n",
3544             (long long)sc->stats.algnerrc);
3545         device_printf(dev, "Collision/Carrier extension errors = %lld\n",
3546             (long long)sc->stats.cexterr);
3547         device_printf(dev, "RX overruns = %ld\n", sc->rx_overruns);
3548         device_printf(dev, "XON Rcvd = %lld\n",
3549             (long long)sc->stats.xonrxc);
3550         device_printf(dev, "XON Xmtd = %lld\n",
3551             (long long)sc->stats.xontxc);
3552         device_printf(dev, "XOFF Rcvd = %lld\n",
3553             (long long)sc->stats.xoffrxc);
3554         device_printf(dev, "XOFF Xmtd = %lld\n",
3555             (long long)sc->stats.xofftxc);
3556         device_printf(dev, "Good Packets Rcvd = %lld\n",
3557             (long long)sc->stats.gprc);
3558         device_printf(dev, "Good Packets Xmtd = %lld\n",
3559             (long long)sc->stats.gptc);
3560 }
3561
3562 static void
3563 emx_print_nvm_info(struct emx_softc *sc)
3564 {
3565         uint16_t eeprom_data;
3566         int i, j, row = 0;
3567
3568         /* Its a bit crude, but it gets the job done */
3569         kprintf("\nInterface EEPROM Dump:\n");
3570         kprintf("Offset\n0x0000  ");
3571         for (i = 0, j = 0; i < 32; i++, j++) {
3572                 if (j == 8) { /* Make the offset block */
3573                         j = 0; ++row;
3574                         kprintf("\n0x00%x0  ",row);
3575                 }
3576                 e1000_read_nvm(&sc->hw, i, 1, &eeprom_data);
3577                 kprintf("%04x ", eeprom_data);
3578         }
3579         kprintf("\n");
3580 }
3581
3582 static int
3583 emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
3584 {
3585         struct emx_softc *sc;
3586         struct ifnet *ifp;
3587         int error, result;
3588
3589         result = -1;
3590         error = sysctl_handle_int(oidp, &result, 0, req);
3591         if (error || !req->newptr)
3592                 return (error);
3593
3594         sc = (struct emx_softc *)arg1;
3595         ifp = &sc->arpcom.ac_if;
3596
3597         ifnet_serialize_all(ifp);
3598
3599         if (result == 1)
3600                 emx_print_debug_info(sc);
3601
3602         /*
3603          * This value will cause a hex dump of the
3604          * first 32 16-bit words of the EEPROM to
3605          * the screen.
3606          */
3607         if (result == 2)
3608                 emx_print_nvm_info(sc);
3609
3610         ifnet_deserialize_all(ifp);
3611
3612         return (error);
3613 }
3614
3615 static int
3616 emx_sysctl_stats(SYSCTL_HANDLER_ARGS)
3617 {
3618         int error, result;
3619
3620         result = -1;
3621         error = sysctl_handle_int(oidp, &result, 0, req);
3622         if (error || !req->newptr)
3623                 return (error);
3624
3625         if (result == 1) {
3626                 struct emx_softc *sc = (struct emx_softc *)arg1;
3627                 struct ifnet *ifp = &sc->arpcom.ac_if;
3628
3629                 ifnet_serialize_all(ifp);
3630                 emx_print_hw_stats(sc);
3631                 ifnet_deserialize_all(ifp);
3632         }
3633         return (error);
3634 }
3635
3636 static void
3637 emx_add_sysctl(struct emx_softc *sc)
3638 {
3639         struct sysctl_ctx_list *ctx;
3640         struct sysctl_oid *tree;
3641 #if defined(EMX_RSS_DEBUG) || defined(EMX_TSS_DEBUG)
3642         char pkt_desc[32];
3643         int i;
3644 #endif
3645
3646         ctx = device_get_sysctl_ctx(sc->dev);
3647         tree = device_get_sysctl_tree(sc->dev);
3648         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3649                         OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3650                         emx_sysctl_debug_info, "I", "Debug Information");
3651
3652         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3653                         OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3654                         emx_sysctl_stats, "I", "Statistics");
3655
3656         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
3657             OID_AUTO, "rxd", CTLFLAG_RD, &sc->rx_data[0].num_rx_desc, 0,
3658             "# of RX descs");
3659         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
3660             OID_AUTO, "txd", CTLFLAG_RD, &sc->tx_data[0].num_tx_desc, 0,
3661             "# of TX descs");
3662
3663         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3664             OID_AUTO, "int_throttle_ceil", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3665             emx_sysctl_int_throttle, "I", "interrupt throttling rate");
3666         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3667             OID_AUTO, "tx_intr_nsegs", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3668             emx_sysctl_tx_intr_nsegs, "I", "# segments per TX interrupt");
3669         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3670             OID_AUTO, "tx_wreg_nsegs", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3671             emx_sysctl_tx_wreg_nsegs, "I",
3672             "# segments sent before write to hardware register");
3673
3674         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
3675             OID_AUTO, "rx_ring_cnt", CTLFLAG_RD, &sc->rx_ring_cnt, 0,
3676             "# of RX rings");
3677         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
3678             OID_AUTO, "tx_ring_cnt", CTLFLAG_RD, &sc->tx_ring_cnt, 0,
3679             "# of TX rings");
3680         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
3681             OID_AUTO, "tx_ring_inuse", CTLFLAG_RD, &sc->tx_ring_inuse, 0,
3682             "# of TX rings used");
3683
3684 #ifdef IFPOLL_ENABLE
3685         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3686                         OID_AUTO, "npoll_rxoff", CTLTYPE_INT|CTLFLAG_RW,
3687                         sc, 0, emx_sysctl_npoll_rxoff, "I",
3688                         "NPOLLING RX cpu offset");
3689         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree),
3690                         OID_AUTO, "npoll_txoff", CTLTYPE_INT|CTLFLAG_RW,
3691                         sc, 0, emx_sysctl_npoll_txoff, "I",
3692                         "NPOLLING TX cpu offset");
3693 #endif
3694
3695 #ifdef EMX_RSS_DEBUG
3696         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree),
3697                        OID_AUTO, "rss_debug", CTLFLAG_RW, &sc->rss_debug,
3698                        0, "RSS debug level");
3699         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3700                 ksnprintf(pkt_desc, sizeof(pkt_desc), "rx%d_pkt", i);
3701                 SYSCTL_ADD_ULONG(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3702                     pkt_desc, CTLFLAG_RW, &sc->rx_data[i].rx_pkts,
3703                     "RXed packets");
3704         }
3705 #endif
3706 #ifdef EMX_TSS_DEBUG
3707         for (i = 0; i < sc->tx_ring_cnt; ++i) {
3708                 ksnprintf(pkt_desc, sizeof(pkt_desc), "tx%d_pkt", i);
3709                 SYSCTL_ADD_ULONG(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3710                     pkt_desc, CTLFLAG_RW, &sc->tx_data[i].tx_pkts,
3711                     "TXed packets");
3712         }
3713 #endif
3714 }
3715
3716 static int
3717 emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
3718 {
3719         struct emx_softc *sc = (void *)arg1;
3720         struct ifnet *ifp = &sc->arpcom.ac_if;
3721         int error, throttle;
3722
3723         throttle = sc->int_throttle_ceil;
3724         error = sysctl_handle_int(oidp, &throttle, 0, req);
3725         if (error || req->newptr == NULL)
3726                 return error;
3727         if (throttle < 0 || throttle > 1000000000 / 256)
3728                 return EINVAL;
3729
3730         if (throttle) {
3731                 /*
3732                  * Set the interrupt throttling rate in 256ns increments,
3733                  * recalculate sysctl value assignment to get exact frequency.
3734                  */
3735                 throttle = 1000000000 / 256 / throttle;
3736
3737                 /* Upper 16bits of ITR is reserved and should be zero */
3738                 if (throttle & 0xffff0000)
3739                         return EINVAL;
3740         }
3741
3742         ifnet_serialize_all(ifp);
3743
3744         if (throttle)
3745                 sc->int_throttle_ceil = 1000000000 / 256 / throttle;
3746         else
3747                 sc->int_throttle_ceil = 0;
3748
3749         if (ifp->if_flags & IFF_RUNNING)
3750                 emx_set_itr(sc, throttle);
3751
3752         ifnet_deserialize_all(ifp);
3753
3754         if (bootverbose) {
3755                 if_printf(ifp, "Interrupt moderation set to %d/sec\n",
3756                           sc->int_throttle_ceil);
3757         }
3758         return 0;
3759 }
3760
3761 static int
3762 emx_sysctl_tx_intr_nsegs(SYSCTL_HANDLER_ARGS)
3763 {
3764         struct emx_softc *sc = (void *)arg1;
3765         struct ifnet *ifp = &sc->arpcom.ac_if;
3766         struct emx_txdata *tdata = &sc->tx_data[0];
3767         int error, segs;
3768
3769         segs = tdata->tx_intr_nsegs;
3770         error = sysctl_handle_int(oidp, &segs, 0, req);
3771         if (error || req->newptr == NULL)
3772                 return error;
3773         if (segs <= 0)
3774                 return EINVAL;
3775
3776         ifnet_serialize_all(ifp);
3777
3778         /*
3779          * Don't allow tx_intr_nsegs to become:
3780          * o  Less the oact_tx_desc
3781          * o  Too large that no TX desc will cause TX interrupt to
3782          *    be generated (OACTIVE will never recover)
3783          * o  Too small that will cause tx_dd[] overflow
3784          */
3785         if (segs < tdata->oact_tx_desc ||
3786             segs >= tdata->num_tx_desc - tdata->oact_tx_desc ||
3787             segs < tdata->num_tx_desc / EMX_TXDD_SAFE) {
3788                 error = EINVAL;
3789         } else {
3790                 int i;
3791
3792                 error = 0;
3793                 for (i = 0; i < sc->tx_ring_cnt; ++i)
3794                         sc->tx_data[i].tx_intr_nsegs = segs;
3795         }
3796
3797         ifnet_deserialize_all(ifp);
3798
3799         return error;
3800 }
3801
3802 static int
3803 emx_sysctl_tx_wreg_nsegs(SYSCTL_HANDLER_ARGS)
3804 {
3805         struct emx_softc *sc = (void *)arg1;
3806         struct ifnet *ifp = &sc->arpcom.ac_if;
3807         int error, nsegs, i;
3808
3809         nsegs = sc->tx_data[0].tx_wreg_nsegs;
3810         error = sysctl_handle_int(oidp, &nsegs, 0, req);
3811         if (error || req->newptr == NULL)
3812                 return error;
3813
3814         ifnet_serialize_all(ifp);
3815         for (i = 0; i < sc->tx_ring_cnt; ++i)
3816                 sc->tx_data[i].tx_wreg_nsegs =nsegs;
3817         ifnet_deserialize_all(ifp);
3818
3819         return 0;
3820 }
3821
3822 #ifdef IFPOLL_ENABLE
3823
3824 static int
3825 emx_sysctl_npoll_rxoff(SYSCTL_HANDLER_ARGS)
3826 {
3827         struct emx_softc *sc = (void *)arg1;
3828         struct ifnet *ifp = &sc->arpcom.ac_if;
3829         int error, off;
3830
3831         off = sc->rx_npoll_off;
3832         error = sysctl_handle_int(oidp, &off, 0, req);
3833         if (error || req->newptr == NULL)
3834                 return error;
3835         if (off < 0)
3836                 return EINVAL;
3837
3838         ifnet_serialize_all(ifp);
3839         if (off >= ncpus2 || off % sc->rx_ring_cnt != 0) {
3840                 error = EINVAL;
3841         } else {
3842                 error = 0;
3843                 sc->rx_npoll_off = off;
3844         }
3845         ifnet_deserialize_all(ifp);
3846
3847         return error;
3848 }
3849
3850 static int
3851 emx_sysctl_npoll_txoff(SYSCTL_HANDLER_ARGS)
3852 {
3853         struct emx_softc *sc = (void *)arg1;
3854         struct ifnet *ifp = &sc->arpcom.ac_if;
3855         int error, off;
3856
3857         off = sc->tx_npoll_off;
3858         error = sysctl_handle_int(oidp, &off, 0, req);
3859         if (error || req->newptr == NULL)
3860                 return error;
3861         if (off < 0)
3862                 return EINVAL;
3863
3864         ifnet_serialize_all(ifp);
3865         if (off >= ncpus2 || off % sc->tx_ring_cnt != 0) {
3866                 error = EINVAL;
3867         } else {
3868                 error = 0;
3869                 sc->tx_npoll_off = off;
3870         }
3871         ifnet_deserialize_all(ifp);
3872
3873         return error;
3874 }
3875
3876 #endif  /* IFPOLL_ENABLE */
3877
3878 static int
3879 emx_dma_alloc(struct emx_softc *sc)
3880 {
3881         int error, i;
3882
3883         /*
3884          * Create top level busdma tag
3885          */
3886         error = bus_dma_tag_create(NULL, 1, 0,
3887                         BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
3888                         NULL, NULL,
3889                         BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
3890                         0, &sc->parent_dtag);
3891         if (error) {
3892                 device_printf(sc->dev, "could not create top level DMA tag\n");
3893                 return error;
3894         }
3895
3896         /*
3897          * Allocate transmit descriptors ring and buffers
3898          */
3899         for (i = 0; i < sc->tx_ring_cnt; ++i) {
3900                 error = emx_create_tx_ring(&sc->tx_data[i]);
3901                 if (error) {
3902                         device_printf(sc->dev,
3903                             "Could not setup transmit structures\n");
3904                         return error;
3905                 }
3906         }
3907
3908         /*
3909          * Allocate receive descriptors ring and buffers
3910          */
3911         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3912                 error = emx_create_rx_ring(&sc->rx_data[i]);
3913                 if (error) {
3914                         device_printf(sc->dev,
3915                             "Could not setup receive structures\n");
3916                         return error;
3917                 }
3918         }
3919         return 0;
3920 }
3921
3922 static void
3923 emx_dma_free(struct emx_softc *sc)
3924 {
3925         int i;
3926
3927         for (i = 0; i < sc->tx_ring_cnt; ++i) {
3928                 emx_destroy_tx_ring(&sc->tx_data[i],
3929                     sc->tx_data[i].num_tx_desc);
3930         }
3931
3932         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3933                 emx_destroy_rx_ring(&sc->rx_data[i],
3934                     sc->rx_data[i].num_rx_desc);
3935         }
3936
3937         /* Free top level busdma tag */
3938         if (sc->parent_dtag != NULL)
3939                 bus_dma_tag_destroy(sc->parent_dtag);
3940 }
3941
3942 static void
3943 emx_serialize(struct ifnet *ifp, enum ifnet_serialize slz)
3944 {
3945         struct emx_softc *sc = ifp->if_softc;
3946
3947         ifnet_serialize_array_enter(sc->serializes, EMX_NSERIALIZE, slz);
3948 }
3949
3950 static void
3951 emx_deserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3952 {
3953         struct emx_softc *sc = ifp->if_softc;
3954
3955         ifnet_serialize_array_exit(sc->serializes, EMX_NSERIALIZE, slz);
3956 }
3957
3958 static int
3959 emx_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3960 {
3961         struct emx_softc *sc = ifp->if_softc;
3962
3963         return ifnet_serialize_array_try(sc->serializes, EMX_NSERIALIZE, slz);
3964 }
3965
3966 static void
3967 emx_serialize_skipmain(struct emx_softc *sc)
3968 {
3969         lwkt_serialize_array_enter(sc->serializes, EMX_NSERIALIZE, 1);
3970 }
3971
3972 static void
3973 emx_deserialize_skipmain(struct emx_softc *sc)
3974 {
3975         lwkt_serialize_array_exit(sc->serializes, EMX_NSERIALIZE, 1);
3976 }
3977
3978 #ifdef INVARIANTS
3979
3980 static void
3981 emx_serialize_assert(struct ifnet *ifp, enum ifnet_serialize slz,
3982     boolean_t serialized)
3983 {
3984         struct emx_softc *sc = ifp->if_softc;
3985
3986         ifnet_serialize_array_assert(sc->serializes, EMX_NSERIALIZE,
3987             slz, serialized);
3988 }
3989
3990 #endif  /* INVARIANTS */
3991
3992 #ifdef IFPOLL_ENABLE
3993
3994 static void
3995 emx_npoll_status(struct ifnet *ifp)
3996 {
3997         struct emx_softc *sc = ifp->if_softc;
3998         uint32_t reg_icr;
3999
4000         ASSERT_SERIALIZED(&sc->main_serialize);
4001
4002         reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
4003         if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
4004                 callout_stop(&sc->timer);
4005                 sc->hw.mac.get_link_status = 1;
4006                 emx_update_link_status(sc);
4007                 callout_reset(&sc->timer, hz, emx_timer, sc);
4008         }
4009 }
4010
4011 static void
4012 emx_npoll_tx(struct ifnet *ifp, void *arg, int cycle __unused)
4013 {
4014         struct emx_txdata *tdata = arg;
4015
4016         ASSERT_SERIALIZED(&tdata->tx_serialize);
4017
4018         emx_txeof(tdata);
4019         if (!ifsq_is_empty(tdata->ifsq))
4020                 ifsq_devstart(tdata->ifsq);
4021 }
4022
4023 static void
4024 emx_npoll_rx(struct ifnet *ifp __unused, void *arg, int cycle)
4025 {
4026         struct emx_rxdata *rdata = arg;
4027
4028         ASSERT_SERIALIZED(&rdata->rx_serialize);
4029
4030         emx_rxeof(rdata, cycle);
4031 }
4032
4033 static void
4034 emx_npoll(struct ifnet *ifp, struct ifpoll_info *info)
4035 {
4036         struct emx_softc *sc = ifp->if_softc;
4037         int i, txr_cnt;
4038
4039         ASSERT_IFNET_SERIALIZED_ALL(ifp);
4040
4041         if (info) {
4042                 int off;
4043
4044                 info->ifpi_status.status_func = emx_npoll_status;
4045                 info->ifpi_status.serializer = &sc->main_serialize;
4046
4047                 txr_cnt = emx_get_txring_inuse(sc, TRUE);
4048                 off = sc->tx_npoll_off;
4049                 for (i = 0; i < txr_cnt; ++i) {
4050                         struct emx_txdata *tdata = &sc->tx_data[i];
4051                         int idx = i + off;
4052
4053                         KKASSERT(idx < ncpus2);
4054                         info->ifpi_tx[idx].poll_func = emx_npoll_tx;
4055                         info->ifpi_tx[idx].arg = tdata;
4056                         info->ifpi_tx[idx].serializer = &tdata->tx_serialize;
4057                         ifsq_set_cpuid(tdata->ifsq, idx);
4058                 }
4059
4060                 off = sc->rx_npoll_off;
4061                 for (i = 0; i < sc->rx_ring_cnt; ++i) {
4062                         struct emx_rxdata *rdata = &sc->rx_data[i];
4063                         int idx = i + off;
4064
4065                         KKASSERT(idx < ncpus2);
4066                         info->ifpi_rx[idx].poll_func = emx_npoll_rx;
4067                         info->ifpi_rx[idx].arg = rdata;
4068                         info->ifpi_rx[idx].serializer = &rdata->rx_serialize;
4069                 }
4070
4071                 if (ifp->if_flags & IFF_RUNNING) {
4072                         if (txr_cnt == sc->tx_ring_inuse)
4073                                 emx_disable_intr(sc);
4074                         else
4075                                 emx_init(sc);
4076                 }
4077         } else {
4078                 for (i = 0; i < sc->tx_ring_cnt; ++i) {
4079                         struct emx_txdata *tdata = &sc->tx_data[i];
4080
4081                         ifsq_set_cpuid(tdata->ifsq,
4082                             rman_get_cpuid(sc->intr_res));
4083                 }
4084
4085                 if (ifp->if_flags & IFF_RUNNING) {
4086                         txr_cnt = emx_get_txring_inuse(sc, FALSE);
4087                         if (txr_cnt == sc->tx_ring_inuse)
4088                                 emx_enable_intr(sc);
4089                         else
4090                                 emx_init(sc);
4091                 }
4092         }
4093 }
4094
4095 #endif  /* IFPOLL_ENABLE */
4096
4097 static void
4098 emx_set_itr(struct emx_softc *sc, uint32_t itr)
4099 {
4100         E1000_WRITE_REG(&sc->hw, E1000_ITR, itr);
4101         if (sc->hw.mac.type == e1000_82574) {
4102                 int i;
4103
4104                 /*
4105                  * When using MSIX interrupts we need to
4106                  * throttle using the EITR register
4107                  */
4108                 for (i = 0; i < 4; ++i)
4109                         E1000_WRITE_REG(&sc->hw, E1000_EITR_82574(i), itr);
4110         }
4111 }
4112
4113 /*
4114  * Disable the L0s, 82574L Errata #20
4115  */
4116 static void
4117 emx_disable_aspm(struct emx_softc *sc)
4118 {
4119         uint16_t link_cap, link_ctrl, disable;
4120         uint8_t pcie_ptr, reg;
4121         device_t dev = sc->dev;
4122
4123         switch (sc->hw.mac.type) {
4124         case e1000_82571:
4125         case e1000_82572:
4126         case e1000_82573:
4127                 /*
4128                  * 82573 specification update
4129                  * errata #8 disable L0s
4130                  * errata #41 disable L1
4131                  *
4132                  * 82571/82572 specification update
4133                  # errata #13 disable L1
4134                  * errata #68 disable L0s
4135                  */
4136                 disable = PCIEM_LNKCTL_ASPM_L0S | PCIEM_LNKCTL_ASPM_L1;
4137                 break;
4138
4139         case e1000_82574:
4140                 /*
4141                  * 82574 specification update errata #20
4142                  *
4143                  * There is no need to disable L1
4144                  */
4145                 disable = PCIEM_LNKCTL_ASPM_L0S;
4146                 break;
4147
4148         default:
4149                 return;
4150         }
4151
4152         pcie_ptr = pci_get_pciecap_ptr(dev);
4153         if (pcie_ptr == 0)
4154                 return;
4155
4156         link_cap = pci_read_config(dev, pcie_ptr + PCIER_LINKCAP, 2);
4157         if ((link_cap & PCIEM_LNKCAP_ASPM_MASK) == 0)
4158                 return;
4159
4160         if (bootverbose)
4161                 if_printf(&sc->arpcom.ac_if, "disable ASPM %#02x\n", disable);
4162
4163         reg = pcie_ptr + PCIER_LINKCTRL;
4164         link_ctrl = pci_read_config(dev, reg, 2);
4165         link_ctrl &= ~disable;
4166         pci_write_config(dev, reg, link_ctrl, 2);
4167 }
4168
4169 static int
4170 emx_tso_pullup(struct emx_txdata *tdata, struct mbuf **mp)
4171 {
4172         int iphlen, hoff, thoff, ex = 0;
4173         struct mbuf *m;
4174         struct ip *ip;
4175
4176         m = *mp;
4177         KASSERT(M_WRITABLE(m), ("TSO mbuf not writable"));
4178
4179         iphlen = m->m_pkthdr.csum_iphlen;
4180         thoff = m->m_pkthdr.csum_thlen;
4181         hoff = m->m_pkthdr.csum_lhlen;
4182
4183         KASSERT(iphlen > 0, ("invalid ip hlen"));
4184         KASSERT(thoff > 0, ("invalid tcp hlen"));
4185         KASSERT(hoff > 0, ("invalid ether hlen"));
4186
4187         if (tdata->tx_flags & EMX_TXFLAG_TSO_PULLEX)
4188                 ex = 4;
4189
4190         if (m->m_len < hoff + iphlen + thoff + ex) {
4191                 m = m_pullup(m, hoff + iphlen + thoff + ex);
4192                 if (m == NULL) {
4193                         *mp = NULL;
4194                         return ENOBUFS;
4195                 }
4196                 *mp = m;
4197         }
4198         ip = mtodoff(m, struct ip *, hoff);
4199         ip->ip_len = 0;
4200
4201         return 0;
4202 }
4203
4204 static int
4205 emx_tso_setup(struct emx_txdata *tdata, struct mbuf *mp,
4206     uint32_t *txd_upper, uint32_t *txd_lower)
4207 {
4208         struct e1000_context_desc *TXD;
4209         int hoff, iphlen, thoff, hlen;
4210         int mss, pktlen, curr_txd;
4211
4212 #ifdef EMX_TSO_DEBUG
4213         tdata->tso_segments++;
4214 #endif
4215
4216         iphlen = mp->m_pkthdr.csum_iphlen;
4217         thoff = mp->m_pkthdr.csum_thlen;
4218         hoff = mp->m_pkthdr.csum_lhlen;
4219         mss = mp->m_pkthdr.tso_segsz;
4220         pktlen = mp->m_pkthdr.len;
4221
4222         if ((tdata->tx_flags & EMX_TXFLAG_FORCECTX) == 0 &&
4223             tdata->csum_flags == CSUM_TSO &&
4224             tdata->csum_iphlen == iphlen &&
4225             tdata->csum_lhlen == hoff &&
4226             tdata->csum_thlen == thoff &&
4227             tdata->csum_mss == mss &&
4228             tdata->csum_pktlen == pktlen) {
4229                 *txd_upper = tdata->csum_txd_upper;
4230                 *txd_lower = tdata->csum_txd_lower;
4231 #ifdef EMX_TSO_DEBUG
4232                 tdata->tso_ctx_reused++;
4233 #endif
4234                 return 0;
4235         }
4236         hlen = hoff + iphlen + thoff;
4237
4238         /*
4239          * Setup a new TSO context.
4240          */
4241
4242         curr_txd = tdata->next_avail_tx_desc;
4243         TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
4244
4245         *txd_lower = E1000_TXD_CMD_DEXT |       /* Extended descr type */
4246                      E1000_TXD_DTYP_D |         /* Data descr type */
4247                      E1000_TXD_CMD_TSE;         /* Do TSE on this packet */
4248
4249         /* IP and/or TCP header checksum calculation and insertion. */
4250         *txd_upper = (E1000_TXD_POPTS_IXSM | E1000_TXD_POPTS_TXSM) << 8;
4251
4252         /*
4253          * Start offset for header checksum calculation.
4254          * End offset for header checksum calculation.
4255          * Offset of place put the checksum.
4256          */
4257         TXD->lower_setup.ip_fields.ipcss = hoff;
4258         TXD->lower_setup.ip_fields.ipcse = htole16(hoff + iphlen - 1);
4259         TXD->lower_setup.ip_fields.ipcso = hoff + offsetof(struct ip, ip_sum);
4260
4261         /*
4262          * Start offset for payload checksum calculation.
4263          * End offset for payload checksum calculation.
4264          * Offset of place to put the checksum.
4265          */
4266         TXD->upper_setup.tcp_fields.tucss = hoff + iphlen;
4267         TXD->upper_setup.tcp_fields.tucse = 0;
4268         TXD->upper_setup.tcp_fields.tucso =
4269             hoff + iphlen + offsetof(struct tcphdr, th_sum);
4270
4271         /*
4272          * Payload size per packet w/o any headers.
4273          * Length of all headers up to payload.
4274          */
4275         TXD->tcp_seg_setup.fields.mss = htole16(mss);
4276         TXD->tcp_seg_setup.fields.hdr_len = hlen;
4277         TXD->cmd_and_length = htole32(E1000_TXD_CMD_IFCS |
4278                                 E1000_TXD_CMD_DEXT |    /* Extended descr */
4279                                 E1000_TXD_CMD_TSE |     /* TSE context */
4280                                 E1000_TXD_CMD_IP |      /* Do IP csum */
4281                                 E1000_TXD_CMD_TCP |     /* Do TCP checksum */
4282                                 (pktlen - hlen));       /* Total len */
4283
4284         /* Save the information for this TSO context */
4285         tdata->csum_flags = CSUM_TSO;
4286         tdata->csum_lhlen = hoff;
4287         tdata->csum_iphlen = iphlen;
4288         tdata->csum_thlen = thoff;
4289         tdata->csum_mss = mss;
4290         tdata->csum_pktlen = pktlen;
4291         tdata->csum_txd_upper = *txd_upper;
4292         tdata->csum_txd_lower = *txd_lower;
4293
4294         if (++curr_txd == tdata->num_tx_desc)
4295                 curr_txd = 0;
4296
4297         KKASSERT(tdata->num_tx_desc_avail > 0);
4298         tdata->num_tx_desc_avail--;
4299
4300         tdata->next_avail_tx_desc = curr_txd;
4301         return 1;
4302 }
4303
4304 static int
4305 emx_get_txring_inuse(const struct emx_softc *sc, boolean_t polling)
4306 {
4307         if (polling)
4308                 return sc->tx_ring_cnt;
4309         else
4310                 return 1;
4311 }