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