ig_hal: Merge intel em-7.3.4 and igb-2.3.7 hardware abstraction layer
[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         uint32_t pba;
1180         int i;
1181
1182         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1183
1184         emx_stop(sc);
1185
1186         /*
1187          * Packet Buffer Allocation (PBA)
1188          * Writing PBA sets the receive portion of the buffer
1189          * the remainder is used for the transmit buffer.
1190          */
1191         switch (sc->hw.mac.type) {
1192         /* Total Packet Buffer on these is 48K */
1193         case e1000_82571:
1194         case e1000_82572:
1195         case e1000_80003es2lan:
1196                 pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */
1197                 break;
1198
1199         case e1000_82573: /* 82573: Total Packet Buffer is 32K */
1200                 pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */
1201                 break;
1202
1203         case e1000_82574:
1204                 pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */
1205                 break;
1206
1207         default:
1208                 /* Devices before 82547 had a Packet Buffer of 64K.   */
1209                 if (sc->max_frame_size > 8192)
1210                         pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */
1211                 else
1212                         pba = E1000_PBA_48K; /* 48K for Rx, 16K for Tx */
1213         }
1214         E1000_WRITE_REG(&sc->hw, E1000_PBA, pba);
1215
1216         /* Get the latest mac address, User can use a LAA */
1217         bcopy(IF_LLADDR(ifp), sc->hw.mac.addr, ETHER_ADDR_LEN);
1218
1219         /* Put the address into the Receive Address Array */
1220         e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1221
1222         /*
1223          * With the 82571 sc, RAR[0] may be overwritten
1224          * when the other port is reset, we make a duplicate
1225          * in RAR[14] for that eventuality, this assures
1226          * the interface continues to function.
1227          */
1228         if (sc->hw.mac.type == e1000_82571) {
1229                 e1000_set_laa_state_82571(&sc->hw, TRUE);
1230                 e1000_rar_set(&sc->hw, sc->hw.mac.addr,
1231                     E1000_RAR_ENTRIES - 1);
1232         }
1233
1234         /* Initialize the hardware */
1235         if (emx_reset(sc)) {
1236                 device_printf(dev, "Unable to reset the hardware\n");
1237                 /* XXX emx_stop()? */
1238                 return;
1239         }
1240         emx_update_link_status(sc);
1241
1242         /* Setup VLAN support, basic and offload if available */
1243         E1000_WRITE_REG(&sc->hw, E1000_VET, ETHERTYPE_VLAN);
1244
1245         if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1246                 uint32_t ctrl;
1247
1248                 ctrl = E1000_READ_REG(&sc->hw, E1000_CTRL);
1249                 ctrl |= E1000_CTRL_VME;
1250                 E1000_WRITE_REG(&sc->hw, E1000_CTRL, ctrl);
1251         }
1252
1253         /* Configure for OS presence */
1254         emx_get_mgmt(sc);
1255
1256         /* Prepare transmit descriptors and buffers */
1257         emx_init_tx_ring(&sc->tx_data);
1258         emx_init_tx_unit(sc);
1259
1260         /* Setup Multicast table */
1261         emx_set_multi(sc);
1262
1263         /* Prepare receive descriptors and buffers */
1264         for (i = 0; i < sc->rx_ring_cnt; ++i) {
1265                 if (emx_init_rx_ring(&sc->rx_data[i])) {
1266                         device_printf(dev,
1267                             "Could not setup receive structures\n");
1268                         emx_stop(sc);
1269                         return;
1270                 }
1271         }
1272         emx_init_rx_unit(sc);
1273
1274         /* Don't lose promiscuous settings */
1275         emx_set_promisc(sc);
1276
1277         ifp->if_flags |= IFF_RUNNING;
1278         ifq_clr_oactive(&ifp->if_snd);
1279
1280         callout_reset(&sc->timer, hz, emx_timer, sc);
1281         e1000_clear_hw_cntrs_base_generic(&sc->hw);
1282
1283         /* MSI/X configuration for 82574 */
1284         if (sc->hw.mac.type == e1000_82574) {
1285                 int tmp;
1286
1287                 tmp = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
1288                 tmp |= E1000_CTRL_EXT_PBA_CLR;
1289                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT, tmp);
1290                 /*
1291                  * XXX MSIX
1292                  * Set the IVAR - interrupt vector routing.
1293                  * Each nibble represents a vector, high bit
1294                  * is enable, other 3 bits are the MSIX table
1295                  * entry, we map RXQ0 to 0, TXQ0 to 1, and
1296                  * Link (other) to 2, hence the magic number.
1297                  */
1298                 E1000_WRITE_REG(&sc->hw, E1000_IVAR, 0x800A0908);
1299         }
1300
1301 #ifdef IFPOLL_ENABLE
1302         /*
1303          * Only enable interrupts if we are not polling, make sure
1304          * they are off otherwise.
1305          */
1306         if (ifp->if_flags & IFF_NPOLLING)
1307                 emx_disable_intr(sc);
1308         else
1309 #endif /* IFPOLL_ENABLE */
1310                 emx_enable_intr(sc);
1311
1312         /* AMT based hardware can now take control from firmware */
1313         if ((sc->flags & (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT)) ==
1314             (EMX_FLAG_HAS_MGMT | EMX_FLAG_HAS_AMT))
1315                 emx_get_hw_control(sc);
1316 }
1317
1318 static void
1319 emx_intr(void *xsc)
1320 {
1321         emx_intr_body(xsc, TRUE);
1322 }
1323
1324 static void
1325 emx_intr_body(struct emx_softc *sc, boolean_t chk_asserted)
1326 {
1327         struct ifnet *ifp = &sc->arpcom.ac_if;
1328         uint32_t reg_icr;
1329
1330         logif(intr_beg);
1331         ASSERT_SERIALIZED(&sc->main_serialize);
1332
1333         reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
1334
1335         if (chk_asserted && (reg_icr & E1000_ICR_INT_ASSERTED) == 0) {
1336                 logif(intr_end);
1337                 return;
1338         }
1339
1340         /*
1341          * XXX: some laptops trigger several spurious interrupts
1342          * on emx(4) when in the resume cycle. The ICR register
1343          * reports all-ones value in this case. Processing such
1344          * interrupts would lead to a freeze. I don't know why.
1345          */
1346         if (reg_icr == 0xffffffff) {
1347                 logif(intr_end);
1348                 return;
1349         }
1350
1351         if (ifp->if_flags & IFF_RUNNING) {
1352                 if (reg_icr &
1353                     (E1000_ICR_RXT0 | E1000_ICR_RXDMT0 | E1000_ICR_RXO)) {
1354                         int i;
1355
1356                         for (i = 0; i < sc->rx_ring_cnt; ++i) {
1357                                 lwkt_serialize_enter(
1358                                 &sc->rx_data[i].rx_serialize);
1359                                 emx_rxeof(&sc->rx_data[i], -1);
1360                                 lwkt_serialize_exit(
1361                                 &sc->rx_data[i].rx_serialize);
1362                         }
1363                 }
1364                 if (reg_icr & E1000_ICR_TXDW) {
1365                         lwkt_serialize_enter(&sc->tx_data.tx_serialize);
1366                         emx_txeof(&sc->tx_data);
1367                         if (!ifq_is_empty(&ifp->if_snd))
1368                                 if_devstart(ifp);
1369                         lwkt_serialize_exit(&sc->tx_data.tx_serialize);
1370                 }
1371         }
1372
1373         /* Link status change */
1374         if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
1375                 emx_serialize_skipmain(sc);
1376
1377                 callout_stop(&sc->timer);
1378                 sc->hw.mac.get_link_status = 1;
1379                 emx_update_link_status(sc);
1380
1381                 /* Deal with TX cruft when link lost */
1382                 emx_tx_purge(sc);
1383
1384                 callout_reset(&sc->timer, hz, emx_timer, sc);
1385
1386                 emx_deserialize_skipmain(sc);
1387         }
1388
1389         if (reg_icr & E1000_ICR_RXO)
1390                 sc->rx_overruns++;
1391
1392         logif(intr_end);
1393 }
1394
1395 static void
1396 emx_intr_mask(void *xsc)
1397 {
1398         struct emx_softc *sc = xsc;
1399
1400         E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
1401         /*
1402          * NOTE:
1403          * ICR.INT_ASSERTED bit will never be set if IMS is 0,
1404          * so don't check it.
1405          */
1406         emx_intr_body(sc, FALSE);
1407         E1000_WRITE_REG(&sc->hw, E1000_IMS, IMS_ENABLE_MASK);
1408 }
1409
1410 static void
1411 emx_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
1412 {
1413         struct emx_softc *sc = ifp->if_softc;
1414
1415         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1416
1417         emx_update_link_status(sc);
1418
1419         ifmr->ifm_status = IFM_AVALID;
1420         ifmr->ifm_active = IFM_ETHER;
1421
1422         if (!sc->link_active)
1423                 return;
1424
1425         ifmr->ifm_status |= IFM_ACTIVE;
1426
1427         if (sc->hw.phy.media_type == e1000_media_type_fiber ||
1428             sc->hw.phy.media_type == e1000_media_type_internal_serdes) {
1429                 ifmr->ifm_active |= IFM_1000_SX | IFM_FDX;
1430         } else {
1431                 switch (sc->link_speed) {
1432                 case 10:
1433                         ifmr->ifm_active |= IFM_10_T;
1434                         break;
1435                 case 100:
1436                         ifmr->ifm_active |= IFM_100_TX;
1437                         break;
1438
1439                 case 1000:
1440                         ifmr->ifm_active |= IFM_1000_T;
1441                         break;
1442                 }
1443                 if (sc->link_duplex == FULL_DUPLEX)
1444                         ifmr->ifm_active |= IFM_FDX;
1445                 else
1446                         ifmr->ifm_active |= IFM_HDX;
1447         }
1448 }
1449
1450 static int
1451 emx_media_change(struct ifnet *ifp)
1452 {
1453         struct emx_softc *sc = ifp->if_softc;
1454         struct ifmedia *ifm = &sc->media;
1455
1456         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1457
1458         if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
1459                 return (EINVAL);
1460
1461         switch (IFM_SUBTYPE(ifm->ifm_media)) {
1462         case IFM_AUTO:
1463                 sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1464                 sc->hw.phy.autoneg_advertised = EMX_AUTONEG_ADV_DEFAULT;
1465                 break;
1466
1467         case IFM_1000_LX:
1468         case IFM_1000_SX:
1469         case IFM_1000_T:
1470                 sc->hw.mac.autoneg = EMX_DO_AUTO_NEG;
1471                 sc->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
1472                 break;
1473
1474         case IFM_100_TX:
1475                 sc->hw.mac.autoneg = FALSE;
1476                 sc->hw.phy.autoneg_advertised = 0;
1477                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1478                         sc->hw.mac.forced_speed_duplex = ADVERTISE_100_FULL;
1479                 else
1480                         sc->hw.mac.forced_speed_duplex = ADVERTISE_100_HALF;
1481                 break;
1482
1483         case IFM_10_T:
1484                 sc->hw.mac.autoneg = FALSE;
1485                 sc->hw.phy.autoneg_advertised = 0;
1486                 if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX)
1487                         sc->hw.mac.forced_speed_duplex = ADVERTISE_10_FULL;
1488                 else
1489                         sc->hw.mac.forced_speed_duplex = ADVERTISE_10_HALF;
1490                 break;
1491
1492         default:
1493                 if_printf(ifp, "Unsupported media type\n");
1494                 break;
1495         }
1496
1497         emx_init(sc);
1498
1499         return (0);
1500 }
1501
1502 static int
1503 emx_encap(struct emx_txdata *tdata, struct mbuf **m_headp,
1504     int *segs_used, int *idx)
1505 {
1506         bus_dma_segment_t segs[EMX_MAX_SCATTER];
1507         bus_dmamap_t map;
1508         struct emx_txbuf *tx_buffer, *tx_buffer_mapped;
1509         struct e1000_tx_desc *ctxd = NULL;
1510         struct mbuf *m_head = *m_headp;
1511         uint32_t txd_upper, txd_lower, cmd = 0;
1512         int maxsegs, nsegs, i, j, first, last = 0, error;
1513
1514         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1515                 error = emx_tso_pullup(tdata, m_headp);
1516                 if (error)
1517                         return error;
1518                 m_head = *m_headp;
1519         }
1520
1521         txd_upper = txd_lower = 0;
1522
1523         /*
1524          * Capture the first descriptor index, this descriptor
1525          * will have the index of the EOP which is the only one
1526          * that now gets a DONE bit writeback.
1527          */
1528         first = tdata->next_avail_tx_desc;
1529         tx_buffer = &tdata->tx_buf[first];
1530         tx_buffer_mapped = tx_buffer;
1531         map = tx_buffer->map;
1532
1533         maxsegs = tdata->num_tx_desc_avail - EMX_TX_RESERVED;
1534         KASSERT(maxsegs >= tdata->spare_tx_desc, ("not enough spare TX desc"));
1535         if (maxsegs > EMX_MAX_SCATTER)
1536                 maxsegs = EMX_MAX_SCATTER;
1537
1538         error = bus_dmamap_load_mbuf_defrag(tdata->txtag, map, m_headp,
1539                         segs, maxsegs, &nsegs, BUS_DMA_NOWAIT);
1540         if (error) {
1541                 m_freem(*m_headp);
1542                 *m_headp = NULL;
1543                 return error;
1544         }
1545         bus_dmamap_sync(tdata->txtag, map, BUS_DMASYNC_PREWRITE);
1546
1547         m_head = *m_headp;
1548         tdata->tx_nsegs += nsegs;
1549         *segs_used += nsegs;
1550
1551         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1552                 /* TSO will consume one TX desc */
1553                 i = emx_tso_setup(tdata, m_head, &txd_upper, &txd_lower);
1554                 tdata->tx_nsegs += i;
1555                 *segs_used += i;
1556         } else if (m_head->m_pkthdr.csum_flags & EMX_CSUM_FEATURES) {
1557                 /* TX csum offloading will consume one TX desc */
1558                 i = emx_txcsum(tdata, m_head, &txd_upper, &txd_lower);
1559                 tdata->tx_nsegs += i;
1560                 *segs_used += i;
1561         }
1562         i = tdata->next_avail_tx_desc;
1563
1564         /* Set up our transmit descriptors */
1565         for (j = 0; j < nsegs; j++) {
1566                 tx_buffer = &tdata->tx_buf[i];
1567                 ctxd = &tdata->tx_desc_base[i];
1568
1569                 ctxd->buffer_addr = htole64(segs[j].ds_addr);
1570                 ctxd->lower.data = htole32(E1000_TXD_CMD_IFCS |
1571                                            txd_lower | segs[j].ds_len);
1572                 ctxd->upper.data = htole32(txd_upper);
1573
1574                 last = i;
1575                 if (++i == tdata->num_tx_desc)
1576                         i = 0;
1577         }
1578
1579         tdata->next_avail_tx_desc = i;
1580
1581         KKASSERT(tdata->num_tx_desc_avail > nsegs);
1582         tdata->num_tx_desc_avail -= nsegs;
1583
1584         /* Handle VLAN tag */
1585         if (m_head->m_flags & M_VLANTAG) {
1586                 /* Set the vlan id. */
1587                 ctxd->upper.fields.special =
1588                     htole16(m_head->m_pkthdr.ether_vlantag);
1589
1590                 /* Tell hardware to add tag */
1591                 ctxd->lower.data |= htole32(E1000_TXD_CMD_VLE);
1592         }
1593
1594         tx_buffer->m_head = m_head;
1595         tx_buffer_mapped->map = tx_buffer->map;
1596         tx_buffer->map = map;
1597
1598         if (tdata->tx_nsegs >= tdata->tx_int_nsegs) {
1599                 tdata->tx_nsegs = 0;
1600
1601                 /*
1602                  * Report Status (RS) is turned on
1603                  * every tx_int_nsegs descriptors.
1604                  */
1605                 cmd = E1000_TXD_CMD_RS;
1606
1607                 /*
1608                  * Keep track of the descriptor, which will
1609                  * be written back by hardware.
1610                  */
1611                 tdata->tx_dd[tdata->tx_dd_tail] = last;
1612                 EMX_INC_TXDD_IDX(tdata->tx_dd_tail);
1613                 KKASSERT(tdata->tx_dd_tail != tdata->tx_dd_head);
1614         }
1615
1616         /*
1617          * Last Descriptor of Packet needs End Of Packet (EOP)
1618          */
1619         ctxd->lower.data |= htole32(E1000_TXD_CMD_EOP | cmd);
1620
1621         /*
1622          * Defer TDT updating, until enough descriptors are setup
1623          */
1624         *idx = i;
1625
1626         return (0);
1627 }
1628
1629 static void
1630 emx_set_promisc(struct emx_softc *sc)
1631 {
1632         struct ifnet *ifp = &sc->arpcom.ac_if;
1633         uint32_t reg_rctl;
1634
1635         reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1636
1637         if (ifp->if_flags & IFF_PROMISC) {
1638                 reg_rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
1639                 /* Turn this on if you want to see bad packets */
1640                 if (emx_debug_sbp)
1641                         reg_rctl |= E1000_RCTL_SBP;
1642                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1643         } else if (ifp->if_flags & IFF_ALLMULTI) {
1644                 reg_rctl |= E1000_RCTL_MPE;
1645                 reg_rctl &= ~E1000_RCTL_UPE;
1646                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1647         }
1648 }
1649
1650 static void
1651 emx_disable_promisc(struct emx_softc *sc)
1652 {
1653         uint32_t reg_rctl;
1654
1655         reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1656
1657         reg_rctl &= ~E1000_RCTL_UPE;
1658         reg_rctl &= ~E1000_RCTL_MPE;
1659         reg_rctl &= ~E1000_RCTL_SBP;
1660         E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1661 }
1662
1663 static void
1664 emx_set_multi(struct emx_softc *sc)
1665 {
1666         struct ifnet *ifp = &sc->arpcom.ac_if;
1667         struct ifmultiaddr *ifma;
1668         uint32_t reg_rctl = 0;
1669         uint8_t *mta;
1670         int mcnt = 0;
1671
1672         mta = sc->mta;
1673         bzero(mta, ETH_ADDR_LEN * EMX_MCAST_ADDR_MAX);
1674
1675         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1676                 if (ifma->ifma_addr->sa_family != AF_LINK)
1677                         continue;
1678
1679                 if (mcnt == EMX_MCAST_ADDR_MAX)
1680                         break;
1681
1682                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1683                       &mta[mcnt * ETHER_ADDR_LEN], ETHER_ADDR_LEN);
1684                 mcnt++;
1685         }
1686
1687         if (mcnt >= EMX_MCAST_ADDR_MAX) {
1688                 reg_rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
1689                 reg_rctl |= E1000_RCTL_MPE;
1690                 E1000_WRITE_REG(&sc->hw, E1000_RCTL, reg_rctl);
1691         } else {
1692                 e1000_update_mc_addr_list(&sc->hw, mta, mcnt);
1693         }
1694 }
1695
1696 /*
1697  * This routine checks for link status and updates statistics.
1698  */
1699 static void
1700 emx_timer(void *xsc)
1701 {
1702         struct emx_softc *sc = xsc;
1703         struct ifnet *ifp = &sc->arpcom.ac_if;
1704
1705         lwkt_serialize_enter(&sc->main_serialize);
1706
1707         emx_update_link_status(sc);
1708         emx_update_stats(sc);
1709
1710         /* Reset LAA into RAR[0] on 82571 */
1711         if (e1000_get_laa_state_82571(&sc->hw) == TRUE)
1712                 e1000_rar_set(&sc->hw, sc->hw.mac.addr, 0);
1713
1714         if (emx_display_debug_stats && (ifp->if_flags & IFF_RUNNING))
1715                 emx_print_hw_stats(sc);
1716
1717         emx_smartspeed(sc);
1718
1719         callout_reset(&sc->timer, hz, emx_timer, sc);
1720
1721         lwkt_serialize_exit(&sc->main_serialize);
1722 }
1723
1724 static void
1725 emx_update_link_status(struct emx_softc *sc)
1726 {
1727         struct e1000_hw *hw = &sc->hw;
1728         struct ifnet *ifp = &sc->arpcom.ac_if;
1729         device_t dev = sc->dev;
1730         uint32_t link_check = 0;
1731
1732         /* Get the cached link value or read phy for real */
1733         switch (hw->phy.media_type) {
1734         case e1000_media_type_copper:
1735                 if (hw->mac.get_link_status) {
1736                         /* Do the work to read phy */
1737                         e1000_check_for_link(hw);
1738                         link_check = !hw->mac.get_link_status;
1739                         if (link_check) /* ESB2 fix */
1740                                 e1000_cfg_on_link_up(hw);
1741                 } else {
1742                         link_check = TRUE;
1743                 }
1744                 break;
1745
1746         case e1000_media_type_fiber:
1747                 e1000_check_for_link(hw);
1748                 link_check = E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU;
1749                 break;
1750
1751         case e1000_media_type_internal_serdes:
1752                 e1000_check_for_link(hw);
1753                 link_check = sc->hw.mac.serdes_has_link;
1754                 break;
1755
1756         case e1000_media_type_unknown:
1757         default:
1758                 break;
1759         }
1760
1761         /* Now check for a transition */
1762         if (link_check && sc->link_active == 0) {
1763                 e1000_get_speed_and_duplex(hw, &sc->link_speed,
1764                     &sc->link_duplex);
1765
1766                 /*
1767                  * Check if we should enable/disable SPEED_MODE bit on
1768                  * 82571EB/82572EI
1769                  */
1770                 if (sc->link_speed != SPEED_1000 &&
1771                     (hw->mac.type == e1000_82571 ||
1772                      hw->mac.type == e1000_82572)) {
1773                         int tarc0;
1774
1775                         tarc0 = E1000_READ_REG(hw, E1000_TARC(0));
1776                         tarc0 &= ~EMX_TARC_SPEED_MODE;
1777                         E1000_WRITE_REG(hw, E1000_TARC(0), tarc0);
1778                 }
1779                 if (bootverbose) {
1780                         device_printf(dev, "Link is up %d Mbps %s\n",
1781                             sc->link_speed,
1782                             ((sc->link_duplex == FULL_DUPLEX) ?
1783                             "Full Duplex" : "Half Duplex"));
1784                 }
1785                 sc->link_active = 1;
1786                 sc->smartspeed = 0;
1787                 ifp->if_baudrate = sc->link_speed * 1000000;
1788                 ifp->if_link_state = LINK_STATE_UP;
1789                 if_link_state_change(ifp);
1790         } else if (!link_check && sc->link_active == 1) {
1791                 ifp->if_baudrate = sc->link_speed = 0;
1792                 sc->link_duplex = 0;
1793                 if (bootverbose)
1794                         device_printf(dev, "Link is Down\n");
1795                 sc->link_active = 0;
1796 #if 0
1797                 /* Link down, disable watchdog */
1798                 if->if_timer = 0;
1799 #endif
1800                 ifp->if_link_state = LINK_STATE_DOWN;
1801                 if_link_state_change(ifp);
1802         }
1803 }
1804
1805 static void
1806 emx_stop(struct emx_softc *sc)
1807 {
1808         struct ifnet *ifp = &sc->arpcom.ac_if;
1809         struct emx_txdata *tdata = &sc->tx_data;
1810         int i;
1811
1812         ASSERT_IFNET_SERIALIZED_ALL(ifp);
1813
1814         emx_disable_intr(sc);
1815
1816         callout_stop(&sc->timer);
1817
1818         ifp->if_flags &= ~IFF_RUNNING;
1819         ifq_clr_oactive(&ifp->if_snd);
1820         ifp->if_timer = 0;
1821
1822         /*
1823          * Disable multiple receive queues.
1824          *
1825          * NOTE:
1826          * We should disable multiple receive queues before
1827          * resetting the hardware.
1828          */
1829         E1000_WRITE_REG(&sc->hw, E1000_MRQC, 0);
1830
1831         e1000_reset_hw(&sc->hw);
1832         E1000_WRITE_REG(&sc->hw, E1000_WUC, 0);
1833
1834         for (i = 0; i < tdata->num_tx_desc; i++) {
1835                 struct emx_txbuf *tx_buffer = &tdata->tx_buf[i];
1836
1837                 if (tx_buffer->m_head != NULL) {
1838                         bus_dmamap_unload(tdata->txtag, tx_buffer->map);
1839                         m_freem(tx_buffer->m_head);
1840                         tx_buffer->m_head = NULL;
1841                 }
1842         }
1843
1844         for (i = 0; i < sc->rx_ring_cnt; ++i)
1845                 emx_free_rx_ring(&sc->rx_data[i]);
1846
1847         tdata->csum_flags = 0;
1848         tdata->csum_lhlen = 0;
1849         tdata->csum_iphlen = 0;
1850         tdata->csum_thlen = 0;
1851         tdata->csum_mss = 0;
1852         tdata->csum_pktlen = 0;
1853
1854         tdata->tx_dd_head = 0;
1855         tdata->tx_dd_tail = 0;
1856         tdata->tx_nsegs = 0;
1857 }
1858
1859 static int
1860 emx_reset(struct emx_softc *sc)
1861 {
1862         device_t dev = sc->dev;
1863         uint16_t rx_buffer_size;
1864
1865         /* Set up smart power down as default off on newer adapters. */
1866         if (!emx_smart_pwr_down &&
1867             (sc->hw.mac.type == e1000_82571 ||
1868              sc->hw.mac.type == e1000_82572)) {
1869                 uint16_t phy_tmp = 0;
1870
1871                 /* Speed up time to link by disabling smart power down. */
1872                 e1000_read_phy_reg(&sc->hw,
1873                     IGP02E1000_PHY_POWER_MGMT, &phy_tmp);
1874                 phy_tmp &= ~IGP02E1000_PM_SPD;
1875                 e1000_write_phy_reg(&sc->hw,
1876                     IGP02E1000_PHY_POWER_MGMT, phy_tmp);
1877         }
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
2212 static void
2213 emx_destroy_tx_ring(struct emx_txdata *tdata, int ndesc)
2214 {
2215         struct emx_txbuf *tx_buffer;
2216         int i;
2217
2218         /* Free Transmit Descriptor ring */
2219         if (tdata->tx_desc_base) {
2220                 bus_dmamap_unload(tdata->tx_desc_dtag, tdata->tx_desc_dmap);
2221                 bus_dmamem_free(tdata->tx_desc_dtag, tdata->tx_desc_base,
2222                                 tdata->tx_desc_dmap);
2223                 bus_dma_tag_destroy(tdata->tx_desc_dtag);
2224
2225                 tdata->tx_desc_base = NULL;
2226         }
2227
2228         if (tdata->tx_buf == NULL)
2229                 return;
2230
2231         for (i = 0; i < ndesc; i++) {
2232                 tx_buffer = &tdata->tx_buf[i];
2233
2234                 KKASSERT(tx_buffer->m_head == NULL);
2235                 bus_dmamap_destroy(tdata->txtag, tx_buffer->map);
2236         }
2237         bus_dma_tag_destroy(tdata->txtag);
2238
2239         kfree(tdata->tx_buf, M_DEVBUF);
2240         tdata->tx_buf = NULL;
2241 }
2242
2243 /*
2244  * The offload context needs to be set when we transfer the first
2245  * packet of a particular protocol (TCP/UDP).  This routine has been
2246  * enhanced to deal with inserted VLAN headers.
2247  *
2248  * If the new packet's ether header length, ip header length and
2249  * csum offloading type are same as the previous packet, we should
2250  * avoid allocating a new csum context descriptor; mainly to take
2251  * advantage of the pipeline effect of the TX data read request.
2252  *
2253  * This function returns number of TX descrptors allocated for
2254  * csum context.
2255  */
2256 static int
2257 emx_txcsum(struct emx_txdata *tdata, struct mbuf *mp,
2258            uint32_t *txd_upper, uint32_t *txd_lower)
2259 {
2260         struct e1000_context_desc *TXD;
2261         int curr_txd, ehdrlen, csum_flags;
2262         uint32_t cmd, hdr_len, ip_hlen;
2263
2264         csum_flags = mp->m_pkthdr.csum_flags & EMX_CSUM_FEATURES;
2265         ip_hlen = mp->m_pkthdr.csum_iphlen;
2266         ehdrlen = mp->m_pkthdr.csum_lhlen;
2267
2268         if (tdata->csum_lhlen == ehdrlen && tdata->csum_iphlen == ip_hlen &&
2269             tdata->csum_flags == csum_flags) {
2270                 /*
2271                  * Same csum offload context as the previous packets;
2272                  * just return.
2273                  */
2274                 *txd_upper = tdata->csum_txd_upper;
2275                 *txd_lower = tdata->csum_txd_lower;
2276                 return 0;
2277         }
2278
2279         /*
2280          * Setup a new csum offload context.
2281          */
2282
2283         curr_txd = tdata->next_avail_tx_desc;
2284         TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
2285
2286         cmd = 0;
2287
2288         /* Setup of IP header checksum. */
2289         if (csum_flags & CSUM_IP) {
2290                 /*
2291                  * Start offset for header checksum calculation.
2292                  * End offset for header checksum calculation.
2293                  * Offset of place to put the checksum.
2294                  */
2295                 TXD->lower_setup.ip_fields.ipcss = ehdrlen;
2296                 TXD->lower_setup.ip_fields.ipcse =
2297                     htole16(ehdrlen + ip_hlen - 1);
2298                 TXD->lower_setup.ip_fields.ipcso =
2299                     ehdrlen + offsetof(struct ip, ip_sum);
2300                 cmd |= E1000_TXD_CMD_IP;
2301                 *txd_upper |= E1000_TXD_POPTS_IXSM << 8;
2302         }
2303         hdr_len = ehdrlen + ip_hlen;
2304
2305         if (csum_flags & CSUM_TCP) {
2306                 /*
2307                  * Start offset for payload checksum calculation.
2308                  * End offset for payload checksum calculation.
2309                  * Offset of place to put the checksum.
2310                  */
2311                 TXD->upper_setup.tcp_fields.tucss = hdr_len;
2312                 TXD->upper_setup.tcp_fields.tucse = htole16(0);
2313                 TXD->upper_setup.tcp_fields.tucso =
2314                     hdr_len + offsetof(struct tcphdr, th_sum);
2315                 cmd |= E1000_TXD_CMD_TCP;
2316                 *txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2317         } else if (csum_flags & CSUM_UDP) {
2318                 /*
2319                  * Start offset for header checksum calculation.
2320                  * End offset for header checksum calculation.
2321                  * Offset of place to put the checksum.
2322                  */
2323                 TXD->upper_setup.tcp_fields.tucss = hdr_len;
2324                 TXD->upper_setup.tcp_fields.tucse = htole16(0);
2325                 TXD->upper_setup.tcp_fields.tucso =
2326                     hdr_len + offsetof(struct udphdr, uh_sum);
2327                 *txd_upper |= E1000_TXD_POPTS_TXSM << 8;
2328         }
2329
2330         *txd_lower = E1000_TXD_CMD_DEXT |       /* Extended descr type */
2331                      E1000_TXD_DTYP_D;          /* Data descr */
2332
2333         /* Save the information for this csum offloading context */
2334         tdata->csum_lhlen = ehdrlen;
2335         tdata->csum_iphlen = ip_hlen;
2336         tdata->csum_flags = csum_flags;
2337         tdata->csum_txd_upper = *txd_upper;
2338         tdata->csum_txd_lower = *txd_lower;
2339
2340         TXD->tcp_seg_setup.data = htole32(0);
2341         TXD->cmd_and_length =
2342             htole32(E1000_TXD_CMD_IFCS | E1000_TXD_CMD_DEXT | cmd);
2343
2344         if (++curr_txd == tdata->num_tx_desc)
2345                 curr_txd = 0;
2346
2347         KKASSERT(tdata->num_tx_desc_avail > 0);
2348         tdata->num_tx_desc_avail--;
2349
2350         tdata->next_avail_tx_desc = curr_txd;
2351         return 1;
2352 }
2353
2354 static void
2355 emx_txeof(struct emx_txdata *tdata)
2356 {
2357         struct ifnet *ifp = &tdata->sc->arpcom.ac_if;
2358         struct emx_txbuf *tx_buffer;
2359         int first, num_avail;
2360
2361         if (tdata->tx_dd_head == tdata->tx_dd_tail)
2362                 return;
2363
2364         if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2365                 return;
2366
2367         num_avail = tdata->num_tx_desc_avail;
2368         first = tdata->next_tx_to_clean;
2369
2370         while (tdata->tx_dd_head != tdata->tx_dd_tail) {
2371                 int dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2372                 struct e1000_tx_desc *tx_desc;
2373
2374                 tx_desc = &tdata->tx_desc_base[dd_idx];
2375                 if (tx_desc->upper.fields.status & E1000_TXD_STAT_DD) {
2376                         EMX_INC_TXDD_IDX(tdata->tx_dd_head);
2377
2378                         if (++dd_idx == tdata->num_tx_desc)
2379                                 dd_idx = 0;
2380
2381                         while (first != dd_idx) {
2382                                 logif(pkt_txclean);
2383
2384                                 num_avail++;
2385
2386                                 tx_buffer = &tdata->tx_buf[first];
2387                                 if (tx_buffer->m_head) {
2388                                         ifp->if_opackets++;
2389                                         bus_dmamap_unload(tdata->txtag,
2390                                                           tx_buffer->map);
2391                                         m_freem(tx_buffer->m_head);
2392                                         tx_buffer->m_head = NULL;
2393                                 }
2394
2395                                 if (++first == tdata->num_tx_desc)
2396                                         first = 0;
2397                         }
2398                 } else {
2399                         break;
2400                 }
2401         }
2402         tdata->next_tx_to_clean = first;
2403         tdata->num_tx_desc_avail = num_avail;
2404
2405         if (tdata->tx_dd_head == tdata->tx_dd_tail) {
2406                 tdata->tx_dd_head = 0;
2407                 tdata->tx_dd_tail = 0;
2408         }
2409
2410         if (!EMX_IS_OACTIVE(tdata)) {
2411                 ifq_clr_oactive(&ifp->if_snd);
2412
2413                 /* All clean, turn off the timer */
2414                 if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2415                         ifp->if_timer = 0;
2416         }
2417 }
2418
2419 static void
2420 emx_tx_collect(struct emx_txdata *tdata)
2421 {
2422         struct ifnet *ifp = &tdata->sc->arpcom.ac_if;
2423         struct emx_txbuf *tx_buffer;
2424         int tdh, first, num_avail, dd_idx = -1;
2425
2426         if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2427                 return;
2428
2429         tdh = E1000_READ_REG(&tdata->sc->hw, E1000_TDH(0));
2430         if (tdh == tdata->next_tx_to_clean)
2431                 return;
2432
2433         if (tdata->tx_dd_head != tdata->tx_dd_tail)
2434                 dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2435
2436         num_avail = tdata->num_tx_desc_avail;
2437         first = tdata->next_tx_to_clean;
2438
2439         while (first != tdh) {
2440                 logif(pkt_txclean);
2441
2442                 num_avail++;
2443
2444                 tx_buffer = &tdata->tx_buf[first];
2445                 if (tx_buffer->m_head) {
2446                         ifp->if_opackets++;
2447                         bus_dmamap_unload(tdata->txtag,
2448                                           tx_buffer->map);
2449                         m_freem(tx_buffer->m_head);
2450                         tx_buffer->m_head = NULL;
2451                 }
2452
2453                 if (first == dd_idx) {
2454                         EMX_INC_TXDD_IDX(tdata->tx_dd_head);
2455                         if (tdata->tx_dd_head == tdata->tx_dd_tail) {
2456                                 tdata->tx_dd_head = 0;
2457                                 tdata->tx_dd_tail = 0;
2458                                 dd_idx = -1;
2459                         } else {
2460                                 dd_idx = tdata->tx_dd[tdata->tx_dd_head];
2461                         }
2462                 }
2463
2464                 if (++first == tdata->num_tx_desc)
2465                         first = 0;
2466         }
2467         tdata->next_tx_to_clean = first;
2468         tdata->num_tx_desc_avail = num_avail;
2469
2470         if (!EMX_IS_OACTIVE(tdata)) {
2471                 ifq_clr_oactive(&ifp->if_snd);
2472
2473                 /* All clean, turn off the timer */
2474                 if (tdata->num_tx_desc_avail == tdata->num_tx_desc)
2475                         ifp->if_timer = 0;
2476         }
2477 }
2478
2479 /*
2480  * When Link is lost sometimes there is work still in the TX ring
2481  * which will result in a watchdog, rather than allow that do an
2482  * attempted cleanup and then reinit here.  Note that this has been
2483  * seens mostly with fiber adapters.
2484  */
2485 static void
2486 emx_tx_purge(struct emx_softc *sc)
2487 {
2488         struct ifnet *ifp = &sc->arpcom.ac_if;
2489
2490         if (!sc->link_active && ifp->if_timer) {
2491                 emx_tx_collect(&sc->tx_data);
2492                 if (ifp->if_timer) {
2493                         if_printf(ifp, "Link lost, TX pending, reinit\n");
2494                         ifp->if_timer = 0;
2495                         emx_init(sc);
2496                 }
2497         }
2498 }
2499
2500 static int
2501 emx_newbuf(struct emx_rxdata *rdata, int i, int init)
2502 {
2503         struct mbuf *m;
2504         bus_dma_segment_t seg;
2505         bus_dmamap_t map;
2506         struct emx_rxbuf *rx_buffer;
2507         int error, nseg;
2508
2509         m = m_getcl(init ? MB_WAIT : MB_DONTWAIT, MT_DATA, M_PKTHDR);
2510         if (m == NULL) {
2511                 if (init) {
2512                         if_printf(&rdata->sc->arpcom.ac_if,
2513                                   "Unable to allocate RX mbuf\n");
2514                 }
2515                 return (ENOBUFS);
2516         }
2517         m->m_len = m->m_pkthdr.len = MCLBYTES;
2518
2519         if (rdata->sc->max_frame_size <= MCLBYTES - ETHER_ALIGN)
2520                 m_adj(m, ETHER_ALIGN);
2521
2522         error = bus_dmamap_load_mbuf_segment(rdata->rxtag,
2523                         rdata->rx_sparemap, m,
2524                         &seg, 1, &nseg, BUS_DMA_NOWAIT);
2525         if (error) {
2526                 m_freem(m);
2527                 if (init) {
2528                         if_printf(&rdata->sc->arpcom.ac_if,
2529                                   "Unable to load RX mbuf\n");
2530                 }
2531                 return (error);
2532         }
2533
2534         rx_buffer = &rdata->rx_buf[i];
2535         if (rx_buffer->m_head != NULL)
2536                 bus_dmamap_unload(rdata->rxtag, rx_buffer->map);
2537
2538         map = rx_buffer->map;
2539         rx_buffer->map = rdata->rx_sparemap;
2540         rdata->rx_sparemap = map;
2541
2542         rx_buffer->m_head = m;
2543         rx_buffer->paddr = seg.ds_addr;
2544
2545         emx_setup_rxdesc(&rdata->rx_desc[i], rx_buffer);
2546         return (0);
2547 }
2548
2549 static int
2550 emx_create_rx_ring(struct emx_rxdata *rdata)
2551 {
2552         device_t dev = rdata->sc->dev;
2553         struct emx_rxbuf *rx_buffer;
2554         int i, error, rsize, nrxd;
2555
2556         /*
2557          * Validate number of receive descriptors.  It must not exceed
2558          * hardware maximum, and must be multiple of E1000_DBA_ALIGN.
2559          */
2560         nrxd = device_getenv_int(dev, "rxd", emx_rxd);
2561         if ((nrxd * sizeof(emx_rxdesc_t)) % EMX_DBA_ALIGN != 0 ||
2562             nrxd > EMX_MAX_RXD || nrxd < EMX_MIN_RXD) {
2563                 device_printf(dev, "Using %d RX descriptors instead of %d!\n",
2564                     EMX_DEFAULT_RXD, nrxd);
2565                 rdata->num_rx_desc = EMX_DEFAULT_RXD;
2566         } else {
2567                 rdata->num_rx_desc = nrxd;
2568         }
2569
2570         /*
2571          * Allocate Receive Descriptor ring
2572          */
2573         rsize = roundup2(rdata->num_rx_desc * sizeof(emx_rxdesc_t),
2574                          EMX_DBA_ALIGN);
2575         rdata->rx_desc = bus_dmamem_coherent_any(rdata->sc->parent_dtag,
2576                                 EMX_DBA_ALIGN, rsize, BUS_DMA_WAITOK,
2577                                 &rdata->rx_desc_dtag, &rdata->rx_desc_dmap,
2578                                 &rdata->rx_desc_paddr);
2579         if (rdata->rx_desc == NULL) {
2580                 device_printf(dev, "Unable to allocate rx_desc memory\n");
2581                 return ENOMEM;
2582         }
2583
2584         rsize = __VM_CACHELINE_ALIGN(
2585             sizeof(struct emx_rxbuf) * rdata->num_rx_desc);
2586         rdata->rx_buf = kmalloc_cachealign(rsize, M_DEVBUF, M_WAITOK | M_ZERO);
2587
2588         /*
2589          * Create DMA tag for rx buffers
2590          */
2591         error = bus_dma_tag_create(rdata->sc->parent_dtag, /* parent */
2592                         1, 0,                   /* alignment, bounds */
2593                         BUS_SPACE_MAXADDR,      /* lowaddr */
2594                         BUS_SPACE_MAXADDR,      /* highaddr */
2595                         NULL, NULL,             /* filter, filterarg */
2596                         MCLBYTES,               /* maxsize */
2597                         1,                      /* nsegments */
2598                         MCLBYTES,               /* maxsegsize */
2599                         BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, /* flags */
2600                         &rdata->rxtag);
2601         if (error) {
2602                 device_printf(dev, "Unable to allocate RX DMA tag\n");
2603                 kfree(rdata->rx_buf, M_DEVBUF);
2604                 rdata->rx_buf = NULL;
2605                 return error;
2606         }
2607
2608         /*
2609          * Create spare DMA map for rx buffers
2610          */
2611         error = bus_dmamap_create(rdata->rxtag, BUS_DMA_WAITOK,
2612                                   &rdata->rx_sparemap);
2613         if (error) {
2614                 device_printf(dev, "Unable to create spare RX DMA map\n");
2615                 bus_dma_tag_destroy(rdata->rxtag);
2616                 kfree(rdata->rx_buf, M_DEVBUF);
2617                 rdata->rx_buf = NULL;
2618                 return error;
2619         }
2620
2621         /*
2622          * Create DMA maps for rx buffers
2623          */
2624         for (i = 0; i < rdata->num_rx_desc; i++) {
2625                 rx_buffer = &rdata->rx_buf[i];
2626
2627                 error = bus_dmamap_create(rdata->rxtag, BUS_DMA_WAITOK,
2628                                           &rx_buffer->map);
2629                 if (error) {
2630                         device_printf(dev, "Unable to create RX DMA map\n");
2631                         emx_destroy_rx_ring(rdata, i);
2632                         return error;
2633                 }
2634         }
2635         return (0);
2636 }
2637
2638 static void
2639 emx_free_rx_ring(struct emx_rxdata *rdata)
2640 {
2641         int i;
2642
2643         for (i = 0; i < rdata->num_rx_desc; i++) {
2644                 struct emx_rxbuf *rx_buffer = &rdata->rx_buf[i];
2645
2646                 if (rx_buffer->m_head != NULL) {
2647                         bus_dmamap_unload(rdata->rxtag, rx_buffer->map);
2648                         m_freem(rx_buffer->m_head);
2649                         rx_buffer->m_head = NULL;
2650                 }
2651         }
2652
2653         if (rdata->fmp != NULL)
2654                 m_freem(rdata->fmp);
2655         rdata->fmp = NULL;
2656         rdata->lmp = NULL;
2657 }
2658
2659 static int
2660 emx_init_rx_ring(struct emx_rxdata *rdata)
2661 {
2662         int i, error;
2663
2664         /* Reset descriptor ring */
2665         bzero(rdata->rx_desc, sizeof(emx_rxdesc_t) * rdata->num_rx_desc);
2666
2667         /* Allocate new ones. */
2668         for (i = 0; i < rdata->num_rx_desc; i++) {
2669                 error = emx_newbuf(rdata, i, 1);
2670                 if (error)
2671                         return (error);
2672         }
2673
2674         /* Setup our descriptor pointers */
2675         rdata->next_rx_desc_to_check = 0;
2676
2677         return (0);
2678 }
2679
2680 static void
2681 emx_init_rx_unit(struct emx_softc *sc)
2682 {
2683         struct ifnet *ifp = &sc->arpcom.ac_if;
2684         uint64_t bus_addr;
2685         uint32_t rctl, itr, rfctl;
2686         int i;
2687
2688         /*
2689          * Make sure receives are disabled while setting
2690          * up the descriptor ring
2691          */
2692         rctl = E1000_READ_REG(&sc->hw, E1000_RCTL);
2693         E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
2694
2695         /*
2696          * Set the interrupt throttling rate. Value is calculated
2697          * as ITR = 1 / (INT_THROTTLE_CEIL * 256ns)
2698          */
2699         if (sc->int_throttle_ceil)
2700                 itr = 1000000000 / 256 / sc->int_throttle_ceil;
2701         else
2702                 itr = 0;
2703         emx_set_itr(sc, itr);
2704
2705         /* Use extended RX descriptor */
2706         rfctl = E1000_RFCTL_EXTEN;
2707
2708         /* Disable accelerated ackknowledge */
2709         if (sc->hw.mac.type == e1000_82574)
2710                 rfctl |= E1000_RFCTL_ACK_DIS;
2711
2712         E1000_WRITE_REG(&sc->hw, E1000_RFCTL, rfctl);
2713
2714         /*
2715          * Receive Checksum Offload for TCP and UDP
2716          *
2717          * Checksum offloading is also enabled if multiple receive
2718          * queue is to be supported, since we need it to figure out
2719          * packet type.
2720          */
2721         if ((ifp->if_capenable & IFCAP_RXCSUM) ||
2722             sc->rx_ring_cnt > 1) {
2723                 uint32_t rxcsum;
2724
2725                 rxcsum = E1000_READ_REG(&sc->hw, E1000_RXCSUM);
2726
2727                 /*
2728                  * NOTE:
2729                  * PCSD must be enabled to enable multiple
2730                  * receive queues.
2731                  */
2732                 rxcsum |= E1000_RXCSUM_IPOFL | E1000_RXCSUM_TUOFL |
2733                           E1000_RXCSUM_PCSD;
2734                 E1000_WRITE_REG(&sc->hw, E1000_RXCSUM, rxcsum);
2735         }
2736
2737         /*
2738          * Configure multiple receive queue (RSS)
2739          */
2740         if (sc->rx_ring_cnt > 1) {
2741                 uint8_t key[EMX_NRSSRK * EMX_RSSRK_SIZE];
2742                 uint32_t reta;
2743
2744                 KASSERT(sc->rx_ring_cnt == EMX_NRX_RING,
2745                     ("invalid number of RX ring (%d)", sc->rx_ring_cnt));
2746
2747                 /*
2748                  * NOTE:
2749                  * When we reach here, RSS has already been disabled
2750                  * in emx_stop(), so we could safely configure RSS key
2751                  * and redirect table.
2752                  */
2753
2754                 /*
2755                  * Configure RSS key
2756                  */
2757                 toeplitz_get_key(key, sizeof(key));
2758                 for (i = 0; i < EMX_NRSSRK; ++i) {
2759                         uint32_t rssrk;
2760
2761                         rssrk = EMX_RSSRK_VAL(key, i);
2762                         EMX_RSS_DPRINTF(sc, 1, "rssrk%d 0x%08x\n", i, rssrk);
2763
2764                         E1000_WRITE_REG(&sc->hw, E1000_RSSRK(i), rssrk);
2765                 }
2766
2767                 /*
2768                  * Configure RSS redirect table in following fashion:
2769                  * (hash & ring_cnt_mask) == rdr_table[(hash & rdr_table_mask)]
2770                  */
2771                 reta = 0;
2772                 for (i = 0; i < EMX_RETA_SIZE; ++i) {
2773                         uint32_t q;
2774
2775                         q = (i % sc->rx_ring_cnt) << EMX_RETA_RINGIDX_SHIFT;
2776                         reta |= q << (8 * i);
2777                 }
2778                 EMX_RSS_DPRINTF(sc, 1, "reta 0x%08x\n", reta);
2779
2780                 for (i = 0; i < EMX_NRETA; ++i)
2781                         E1000_WRITE_REG(&sc->hw, E1000_RETA(i), reta);
2782
2783                 /*
2784                  * Enable multiple receive queues.
2785                  * Enable IPv4 RSS standard hash functions.
2786                  * Disable RSS interrupt.
2787                  */
2788                 E1000_WRITE_REG(&sc->hw, E1000_MRQC,
2789                                 E1000_MRQC_ENABLE_RSS_2Q |
2790                                 E1000_MRQC_RSS_FIELD_IPV4_TCP |
2791                                 E1000_MRQC_RSS_FIELD_IPV4);
2792         }
2793
2794         /*
2795          * XXX TEMPORARY WORKAROUND: on some systems with 82573
2796          * long latencies are observed, like Lenovo X60. This
2797          * change eliminates the problem, but since having positive
2798          * values in RDTR is a known source of problems on other
2799          * platforms another solution is being sought.
2800          */
2801         if (emx_82573_workaround && sc->hw.mac.type == e1000_82573) {
2802                 E1000_WRITE_REG(&sc->hw, E1000_RADV, EMX_RADV_82573);
2803                 E1000_WRITE_REG(&sc->hw, E1000_RDTR, EMX_RDTR_82573);
2804         }
2805
2806         for (i = 0; i < sc->rx_ring_cnt; ++i) {
2807                 struct emx_rxdata *rdata = &sc->rx_data[i];
2808
2809                 /*
2810                  * Setup the Base and Length of the Rx Descriptor Ring
2811                  */
2812                 bus_addr = rdata->rx_desc_paddr;
2813                 E1000_WRITE_REG(&sc->hw, E1000_RDLEN(i),
2814                     rdata->num_rx_desc * sizeof(emx_rxdesc_t));
2815                 E1000_WRITE_REG(&sc->hw, E1000_RDBAH(i),
2816                     (uint32_t)(bus_addr >> 32));
2817                 E1000_WRITE_REG(&sc->hw, E1000_RDBAL(i),
2818                     (uint32_t)bus_addr);
2819
2820                 /*
2821                  * Setup the HW Rx Head and Tail Descriptor Pointers
2822                  */
2823                 E1000_WRITE_REG(&sc->hw, E1000_RDH(i), 0);
2824                 E1000_WRITE_REG(&sc->hw, E1000_RDT(i),
2825                     sc->rx_data[i].num_rx_desc - 1);
2826         }
2827
2828         /* Setup the Receive Control Register */
2829         rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
2830         rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_LBM_NO |
2831                 E1000_RCTL_RDMTS_HALF | E1000_RCTL_SECRC |
2832                 (sc->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
2833
2834         /* Make sure VLAN Filters are off */
2835         rctl &= ~E1000_RCTL_VFE;
2836
2837         /* Don't store bad paket */
2838         rctl &= ~E1000_RCTL_SBP;
2839
2840         /* MCLBYTES */
2841         rctl |= E1000_RCTL_SZ_2048;
2842
2843         if (ifp->if_mtu > ETHERMTU)
2844                 rctl |= E1000_RCTL_LPE;
2845         else
2846                 rctl &= ~E1000_RCTL_LPE;
2847
2848         /* Enable Receives */
2849         E1000_WRITE_REG(&sc->hw, E1000_RCTL, rctl);
2850 }
2851
2852 static void
2853 emx_destroy_rx_ring(struct emx_rxdata *rdata, int ndesc)
2854 {
2855         struct emx_rxbuf *rx_buffer;
2856         int i;
2857
2858         /* Free Receive Descriptor ring */
2859         if (rdata->rx_desc) {
2860                 bus_dmamap_unload(rdata->rx_desc_dtag, rdata->rx_desc_dmap);
2861                 bus_dmamem_free(rdata->rx_desc_dtag, rdata->rx_desc,
2862                                 rdata->rx_desc_dmap);
2863                 bus_dma_tag_destroy(rdata->rx_desc_dtag);
2864
2865                 rdata->rx_desc = NULL;
2866         }
2867
2868         if (rdata->rx_buf == NULL)
2869                 return;
2870
2871         for (i = 0; i < ndesc; i++) {
2872                 rx_buffer = &rdata->rx_buf[i];
2873
2874                 KKASSERT(rx_buffer->m_head == NULL);
2875                 bus_dmamap_destroy(rdata->rxtag, rx_buffer->map);
2876         }
2877         bus_dmamap_destroy(rdata->rxtag, rdata->rx_sparemap);
2878         bus_dma_tag_destroy(rdata->rxtag);
2879
2880         kfree(rdata->rx_buf, M_DEVBUF);
2881         rdata->rx_buf = NULL;
2882 }
2883
2884 static void
2885 emx_rxeof(struct emx_rxdata *rdata, int count)
2886 {
2887         struct ifnet *ifp = &rdata->sc->arpcom.ac_if;
2888         uint32_t staterr;
2889         emx_rxdesc_t *current_desc;
2890         struct mbuf *mp;
2891         int i;
2892
2893         i = rdata->next_rx_desc_to_check;
2894         current_desc = &rdata->rx_desc[i];
2895         staterr = le32toh(current_desc->rxd_staterr);
2896
2897         if (!(staterr & E1000_RXD_STAT_DD))
2898                 return;
2899
2900         while ((staterr & E1000_RXD_STAT_DD) && count != 0) {
2901                 struct pktinfo *pi = NULL, pi0;
2902                 struct emx_rxbuf *rx_buf = &rdata->rx_buf[i];
2903                 struct mbuf *m = NULL;
2904                 int eop, len;
2905
2906                 logif(pkt_receive);
2907
2908                 mp = rx_buf->m_head;
2909
2910                 /*
2911                  * Can't defer bus_dmamap_sync(9) because TBI_ACCEPT
2912                  * needs to access the last received byte in the mbuf.
2913                  */
2914                 bus_dmamap_sync(rdata->rxtag, rx_buf->map,
2915                                 BUS_DMASYNC_POSTREAD);
2916
2917                 len = le16toh(current_desc->rxd_length);
2918                 if (staterr & E1000_RXD_STAT_EOP) {
2919                         count--;
2920                         eop = 1;
2921                 } else {
2922                         eop = 0;
2923                 }
2924
2925                 if (!(staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK)) {
2926                         uint16_t vlan = 0;
2927                         uint32_t mrq, rss_hash;
2928
2929                         /*
2930                          * Save several necessary information,
2931                          * before emx_newbuf() destroy it.
2932                          */
2933                         if ((staterr & E1000_RXD_STAT_VP) && eop)
2934                                 vlan = le16toh(current_desc->rxd_vlan);
2935
2936                         mrq = le32toh(current_desc->rxd_mrq);
2937                         rss_hash = le32toh(current_desc->rxd_rss);
2938
2939                         EMX_RSS_DPRINTF(rdata->sc, 10,
2940                             "ring%d, mrq 0x%08x, rss_hash 0x%08x\n",
2941                             rdata->idx, mrq, rss_hash);
2942
2943                         if (emx_newbuf(rdata, i, 0) != 0) {
2944                                 ifp->if_iqdrops++;
2945                                 goto discard;
2946                         }
2947
2948                         /* Assign correct length to the current fragment */
2949                         mp->m_len = len;
2950
2951                         if (rdata->fmp == NULL) {
2952                                 mp->m_pkthdr.len = len;
2953                                 rdata->fmp = mp; /* Store the first mbuf */
2954                                 rdata->lmp = mp;
2955                         } else {
2956                                 /*
2957                                  * Chain mbuf's together
2958                                  */
2959                                 rdata->lmp->m_next = mp;
2960                                 rdata->lmp = rdata->lmp->m_next;
2961                                 rdata->fmp->m_pkthdr.len += len;
2962                         }
2963
2964                         if (eop) {
2965                                 rdata->fmp->m_pkthdr.rcvif = ifp;
2966                                 ifp->if_ipackets++;
2967
2968                                 if (ifp->if_capenable & IFCAP_RXCSUM)
2969                                         emx_rxcsum(staterr, rdata->fmp);
2970
2971                                 if (staterr & E1000_RXD_STAT_VP) {
2972                                         rdata->fmp->m_pkthdr.ether_vlantag =
2973                                             vlan;
2974                                         rdata->fmp->m_flags |= M_VLANTAG;
2975                                 }
2976                                 m = rdata->fmp;
2977                                 rdata->fmp = NULL;
2978                                 rdata->lmp = NULL;
2979
2980                                 if (ifp->if_capenable & IFCAP_RSS) {
2981                                         pi = emx_rssinfo(m, &pi0, mrq,
2982                                                          rss_hash, staterr);
2983                                 }
2984 #ifdef EMX_RSS_DEBUG
2985                                 rdata->rx_pkts++;
2986 #endif
2987                         }
2988                 } else {
2989                         ifp->if_ierrors++;
2990 discard:
2991                         emx_setup_rxdesc(current_desc, rx_buf);
2992                         if (rdata->fmp != NULL) {
2993                                 m_freem(rdata->fmp);
2994                                 rdata->fmp = NULL;
2995                                 rdata->lmp = NULL;
2996                         }
2997                         m = NULL;
2998                 }
2999
3000                 if (m != NULL)
3001                         ether_input_pkt(ifp, m, pi);
3002
3003                 /* Advance our pointers to the next descriptor. */
3004                 if (++i == rdata->num_rx_desc)
3005                         i = 0;
3006
3007                 current_desc = &rdata->rx_desc[i];
3008                 staterr = le32toh(current_desc->rxd_staterr);
3009         }
3010         rdata->next_rx_desc_to_check = i;
3011
3012         /* Advance the E1000's Receive Queue "Tail Pointer". */
3013         if (--i < 0)
3014                 i = rdata->num_rx_desc - 1;
3015         E1000_WRITE_REG(&rdata->sc->hw, E1000_RDT(rdata->idx), i);
3016 }
3017
3018 static void
3019 emx_enable_intr(struct emx_softc *sc)
3020 {
3021         uint32_t ims_mask = IMS_ENABLE_MASK;
3022
3023         lwkt_serialize_handler_enable(&sc->main_serialize);
3024
3025 #if 0
3026         if (sc->hw.mac.type == e1000_82574) {
3027                 E1000_WRITE_REG(hw, EMX_EIAC, EM_MSIX_MASK);
3028                 ims_mask |= EM_MSIX_MASK;
3029         }
3030 #endif
3031         E1000_WRITE_REG(&sc->hw, E1000_IMS, ims_mask);
3032 }
3033
3034 static void
3035 emx_disable_intr(struct emx_softc *sc)
3036 {
3037         if (sc->hw.mac.type == e1000_82574)
3038                 E1000_WRITE_REG(&sc->hw, EMX_EIAC, 0);
3039         E1000_WRITE_REG(&sc->hw, E1000_IMC, 0xffffffff);
3040
3041         lwkt_serialize_handler_disable(&sc->main_serialize);
3042 }
3043
3044 /*
3045  * Bit of a misnomer, what this really means is
3046  * to enable OS management of the system... aka
3047  * to disable special hardware management features 
3048  */
3049 static void
3050 emx_get_mgmt(struct emx_softc *sc)
3051 {
3052         /* A shared code workaround */
3053         if (sc->flags & EMX_FLAG_HAS_MGMT) {
3054                 int manc2h = E1000_READ_REG(&sc->hw, E1000_MANC2H);
3055                 int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
3056
3057                 /* disable hardware interception of ARP */
3058                 manc &= ~(E1000_MANC_ARP_EN);
3059
3060                 /* enable receiving management packets to the host */
3061                 manc |= E1000_MANC_EN_MNG2HOST;
3062 #define E1000_MNG2HOST_PORT_623 (1 << 5)
3063 #define E1000_MNG2HOST_PORT_664 (1 << 6)
3064                 manc2h |= E1000_MNG2HOST_PORT_623;
3065                 manc2h |= E1000_MNG2HOST_PORT_664;
3066                 E1000_WRITE_REG(&sc->hw, E1000_MANC2H, manc2h);
3067
3068                 E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
3069         }
3070 }
3071
3072 /*
3073  * Give control back to hardware management
3074  * controller if there is one.
3075  */
3076 static void
3077 emx_rel_mgmt(struct emx_softc *sc)
3078 {
3079         if (sc->flags & EMX_FLAG_HAS_MGMT) {
3080                 int manc = E1000_READ_REG(&sc->hw, E1000_MANC);
3081
3082                 /* re-enable hardware interception of ARP */
3083                 manc |= E1000_MANC_ARP_EN;
3084                 manc &= ~E1000_MANC_EN_MNG2HOST;
3085
3086                 E1000_WRITE_REG(&sc->hw, E1000_MANC, manc);
3087         }
3088 }
3089
3090 /*
3091  * emx_get_hw_control() sets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3092  * For ASF and Pass Through versions of f/w this means that
3093  * the driver is loaded.  For AMT version (only with 82573)
3094  * of the f/w this means that the network i/f is open.
3095  */
3096 static void
3097 emx_get_hw_control(struct emx_softc *sc)
3098 {
3099         /* Let firmware know the driver has taken over */
3100         if (sc->hw.mac.type == e1000_82573) {
3101                 uint32_t swsm;
3102
3103                 swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
3104                 E1000_WRITE_REG(&sc->hw, E1000_SWSM,
3105                     swsm | E1000_SWSM_DRV_LOAD);
3106         } else {
3107                 uint32_t ctrl_ext;
3108
3109                 ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
3110                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
3111                     ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
3112         }
3113         sc->flags |= EMX_FLAG_HW_CTRL;
3114 }
3115
3116 /*
3117  * emx_rel_hw_control() resets {CTRL_EXT|FWSM}:DRV_LOAD bit.
3118  * For ASF and Pass Through versions of f/w this means that the
3119  * driver is no longer loaded.  For AMT version (only with 82573)
3120  * of the f/w this means that the network i/f is closed.
3121  */
3122 static void
3123 emx_rel_hw_control(struct emx_softc *sc)
3124 {
3125         if ((sc->flags & EMX_FLAG_HW_CTRL) == 0)
3126                 return;
3127         sc->flags &= ~EMX_FLAG_HW_CTRL;
3128
3129         /* Let firmware taken over control of h/w */
3130         if (sc->hw.mac.type == e1000_82573) {
3131                 uint32_t swsm;
3132
3133                 swsm = E1000_READ_REG(&sc->hw, E1000_SWSM);
3134                 E1000_WRITE_REG(&sc->hw, E1000_SWSM,
3135                     swsm & ~E1000_SWSM_DRV_LOAD);
3136         } else {
3137                 uint32_t ctrl_ext;
3138
3139                 ctrl_ext = E1000_READ_REG(&sc->hw, E1000_CTRL_EXT);
3140                 E1000_WRITE_REG(&sc->hw, E1000_CTRL_EXT,
3141                     ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
3142         }
3143 }
3144
3145 static int
3146 emx_is_valid_eaddr(const uint8_t *addr)
3147 {
3148         char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
3149
3150         if ((addr[0] & 1) || !bcmp(addr, zero_addr, ETHER_ADDR_LEN))
3151                 return (FALSE);
3152
3153         return (TRUE);
3154 }
3155
3156 /*
3157  * Enable PCI Wake On Lan capability
3158  */
3159 void
3160 emx_enable_wol(device_t dev)
3161 {
3162         uint16_t cap, status;
3163         uint8_t id;
3164
3165         /* First find the capabilities pointer*/
3166         cap = pci_read_config(dev, PCIR_CAP_PTR, 2);
3167
3168         /* Read the PM Capabilities */
3169         id = pci_read_config(dev, cap, 1);
3170         if (id != PCIY_PMG)     /* Something wrong */
3171                 return;
3172
3173         /*
3174          * OK, we have the power capabilities,
3175          * so now get the status register
3176          */
3177         cap += PCIR_POWER_STATUS;
3178         status = pci_read_config(dev, cap, 2);
3179         status |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
3180         pci_write_config(dev, cap, status, 2);
3181 }
3182
3183 static void
3184 emx_update_stats(struct emx_softc *sc)
3185 {
3186         struct ifnet *ifp = &sc->arpcom.ac_if;
3187
3188         if (sc->hw.phy.media_type == e1000_media_type_copper ||
3189             (E1000_READ_REG(&sc->hw, E1000_STATUS) & E1000_STATUS_LU)) {
3190                 sc->stats.symerrs += E1000_READ_REG(&sc->hw, E1000_SYMERRS);
3191                 sc->stats.sec += E1000_READ_REG(&sc->hw, E1000_SEC);
3192         }
3193         sc->stats.crcerrs += E1000_READ_REG(&sc->hw, E1000_CRCERRS);
3194         sc->stats.mpc += E1000_READ_REG(&sc->hw, E1000_MPC);
3195         sc->stats.scc += E1000_READ_REG(&sc->hw, E1000_SCC);
3196         sc->stats.ecol += E1000_READ_REG(&sc->hw, E1000_ECOL);
3197
3198         sc->stats.mcc += E1000_READ_REG(&sc->hw, E1000_MCC);
3199         sc->stats.latecol += E1000_READ_REG(&sc->hw, E1000_LATECOL);
3200         sc->stats.colc += E1000_READ_REG(&sc->hw, E1000_COLC);
3201         sc->stats.dc += E1000_READ_REG(&sc->hw, E1000_DC);
3202         sc->stats.rlec += E1000_READ_REG(&sc->hw, E1000_RLEC);
3203         sc->stats.xonrxc += E1000_READ_REG(&sc->hw, E1000_XONRXC);
3204         sc->stats.xontxc += E1000_READ_REG(&sc->hw, E1000_XONTXC);
3205         sc->stats.xoffrxc += E1000_READ_REG(&sc->hw, E1000_XOFFRXC);
3206         sc->stats.xofftxc += E1000_READ_REG(&sc->hw, E1000_XOFFTXC);
3207         sc->stats.fcruc += E1000_READ_REG(&sc->hw, E1000_FCRUC);
3208         sc->stats.prc64 += E1000_READ_REG(&sc->hw, E1000_PRC64);
3209         sc->stats.prc127 += E1000_READ_REG(&sc->hw, E1000_PRC127);
3210         sc->stats.prc255 += E1000_READ_REG(&sc->hw, E1000_PRC255);
3211         sc->stats.prc511 += E1000_READ_REG(&sc->hw, E1000_PRC511);
3212         sc->stats.prc1023 += E1000_READ_REG(&sc->hw, E1000_PRC1023);
3213         sc->stats.prc1522 += E1000_READ_REG(&sc->hw, E1000_PRC1522);
3214         sc->stats.gprc += E1000_READ_REG(&sc->hw, E1000_GPRC);
3215         sc->stats.bprc += E1000_READ_REG(&sc->hw, E1000_BPRC);
3216         sc->stats.mprc += E1000_READ_REG(&sc->hw, E1000_MPRC);
3217         sc->stats.gptc += E1000_READ_REG(&sc->hw, E1000_GPTC);
3218
3219         /* For the 64-bit byte counters the low dword must be read first. */
3220         /* Both registers clear on the read of the high dword */
3221
3222         sc->stats.gorc += E1000_READ_REG(&sc->hw, E1000_GORCH);
3223         sc->stats.gotc += E1000_READ_REG(&sc->hw, E1000_GOTCH);
3224
3225         sc->stats.rnbc += E1000_READ_REG(&sc->hw, E1000_RNBC);
3226         sc->stats.ruc += E1000_READ_REG(&sc->hw, E1000_RUC);
3227         sc->stats.rfc += E1000_READ_REG(&sc->hw, E1000_RFC);
3228         sc->stats.roc += E1000_READ_REG(&sc->hw, E1000_ROC);
3229         sc->stats.rjc += E1000_READ_REG(&sc->hw, E1000_RJC);
3230
3231         sc->stats.tor += E1000_READ_REG(&sc->hw, E1000_TORH);
3232         sc->stats.tot += E1000_READ_REG(&sc->hw, E1000_TOTH);
3233
3234         sc->stats.tpr += E1000_READ_REG(&sc->hw, E1000_TPR);
3235         sc->stats.tpt += E1000_READ_REG(&sc->hw, E1000_TPT);
3236         sc->stats.ptc64 += E1000_READ_REG(&sc->hw, E1000_PTC64);
3237         sc->stats.ptc127 += E1000_READ_REG(&sc->hw, E1000_PTC127);
3238         sc->stats.ptc255 += E1000_READ_REG(&sc->hw, E1000_PTC255);
3239         sc->stats.ptc511 += E1000_READ_REG(&sc->hw, E1000_PTC511);
3240         sc->stats.ptc1023 += E1000_READ_REG(&sc->hw, E1000_PTC1023);
3241         sc->stats.ptc1522 += E1000_READ_REG(&sc->hw, E1000_PTC1522);
3242         sc->stats.mptc += E1000_READ_REG(&sc->hw, E1000_MPTC);
3243         sc->stats.bptc += E1000_READ_REG(&sc->hw, E1000_BPTC);
3244
3245         sc->stats.algnerrc += E1000_READ_REG(&sc->hw, E1000_ALGNERRC);
3246         sc->stats.rxerrc += E1000_READ_REG(&sc->hw, E1000_RXERRC);
3247         sc->stats.tncrs += E1000_READ_REG(&sc->hw, E1000_TNCRS);
3248         sc->stats.cexterr += E1000_READ_REG(&sc->hw, E1000_CEXTERR);
3249         sc->stats.tsctc += E1000_READ_REG(&sc->hw, E1000_TSCTC);
3250         sc->stats.tsctfc += E1000_READ_REG(&sc->hw, E1000_TSCTFC);
3251
3252         ifp->if_collisions = sc->stats.colc;
3253
3254         /* Rx Errors */
3255         ifp->if_ierrors = sc->stats.rxerrc +
3256                           sc->stats.crcerrs + sc->stats.algnerrc +
3257                           sc->stats.ruc + sc->stats.roc +
3258                           sc->stats.mpc + sc->stats.cexterr;
3259
3260         /* Tx Errors */
3261         ifp->if_oerrors = sc->stats.ecol + sc->stats.latecol;
3262 }
3263
3264 static void
3265 emx_print_debug_info(struct emx_softc *sc)
3266 {
3267         device_t dev = sc->dev;
3268         uint8_t *hw_addr = sc->hw.hw_addr;
3269
3270         device_printf(dev, "Adapter hardware address = %p \n", hw_addr);
3271         device_printf(dev, "CTRL = 0x%x RCTL = 0x%x \n",
3272             E1000_READ_REG(&sc->hw, E1000_CTRL),
3273             E1000_READ_REG(&sc->hw, E1000_RCTL));
3274         device_printf(dev, "Packet buffer = Tx=%dk Rx=%dk \n",
3275             ((E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff0000) >> 16),\
3276             (E1000_READ_REG(&sc->hw, E1000_PBA) & 0xffff) );
3277         device_printf(dev, "Flow control watermarks high = %d low = %d\n",
3278             sc->hw.fc.high_water, sc->hw.fc.low_water);
3279         device_printf(dev, "tx_int_delay = %d, tx_abs_int_delay = %d\n",
3280             E1000_READ_REG(&sc->hw, E1000_TIDV),
3281             E1000_READ_REG(&sc->hw, E1000_TADV));
3282         device_printf(dev, "rx_int_delay = %d, rx_abs_int_delay = %d\n",
3283             E1000_READ_REG(&sc->hw, E1000_RDTR),
3284             E1000_READ_REG(&sc->hw, E1000_RADV));
3285         device_printf(dev, "hw tdh = %d, hw tdt = %d\n",
3286             E1000_READ_REG(&sc->hw, E1000_TDH(0)),
3287             E1000_READ_REG(&sc->hw, E1000_TDT(0)));
3288         device_printf(dev, "hw rdh = %d, hw rdt = %d\n",
3289             E1000_READ_REG(&sc->hw, E1000_RDH(0)),
3290             E1000_READ_REG(&sc->hw, E1000_RDT(0)));
3291         device_printf(dev, "Num Tx descriptors avail = %d\n",
3292             sc->tx_data.num_tx_desc_avail);
3293
3294         device_printf(dev, "TSO segments %lu\n", sc->tx_data.tso_segments);
3295         device_printf(dev, "TSO ctx reused %lu\n", sc->tx_data.tso_ctx_reused);
3296 }
3297
3298 static void
3299 emx_print_hw_stats(struct emx_softc *sc)
3300 {
3301         device_t dev = sc->dev;
3302
3303         device_printf(dev, "Excessive collisions = %lld\n",
3304             (long long)sc->stats.ecol);
3305 #if (DEBUG_HW > 0)  /* Dont output these errors normally */
3306         device_printf(dev, "Symbol errors = %lld\n",
3307             (long long)sc->stats.symerrs);
3308 #endif
3309         device_printf(dev, "Sequence errors = %lld\n",
3310             (long long)sc->stats.sec);
3311         device_printf(dev, "Defer count = %lld\n",
3312             (long long)sc->stats.dc);
3313         device_printf(dev, "Missed Packets = %lld\n",
3314             (long long)sc->stats.mpc);
3315         device_printf(dev, "Receive No Buffers = %lld\n",
3316             (long long)sc->stats.rnbc);
3317         /* RLEC is inaccurate on some hardware, calculate our own. */
3318         device_printf(dev, "Receive Length Errors = %lld\n",
3319             ((long long)sc->stats.roc + (long long)sc->stats.ruc));
3320         device_printf(dev, "Receive errors = %lld\n",
3321             (long long)sc->stats.rxerrc);
3322         device_printf(dev, "Crc errors = %lld\n",
3323             (long long)sc->stats.crcerrs);
3324         device_printf(dev, "Alignment errors = %lld\n",
3325             (long long)sc->stats.algnerrc);
3326         device_printf(dev, "Collision/Carrier extension errors = %lld\n",
3327             (long long)sc->stats.cexterr);
3328         device_printf(dev, "RX overruns = %ld\n", sc->rx_overruns);
3329         device_printf(dev, "XON Rcvd = %lld\n",
3330             (long long)sc->stats.xonrxc);
3331         device_printf(dev, "XON Xmtd = %lld\n",
3332             (long long)sc->stats.xontxc);
3333         device_printf(dev, "XOFF Rcvd = %lld\n",
3334             (long long)sc->stats.xoffrxc);
3335         device_printf(dev, "XOFF Xmtd = %lld\n",
3336             (long long)sc->stats.xofftxc);
3337         device_printf(dev, "Good Packets Rcvd = %lld\n",
3338             (long long)sc->stats.gprc);
3339         device_printf(dev, "Good Packets Xmtd = %lld\n",
3340             (long long)sc->stats.gptc);
3341 }
3342
3343 static void
3344 emx_print_nvm_info(struct emx_softc *sc)
3345 {
3346         uint16_t eeprom_data;
3347         int i, j, row = 0;
3348
3349         /* Its a bit crude, but it gets the job done */
3350         kprintf("\nInterface EEPROM Dump:\n");
3351         kprintf("Offset\n0x0000  ");
3352         for (i = 0, j = 0; i < 32; i++, j++) {
3353                 if (j == 8) { /* Make the offset block */
3354                         j = 0; ++row;
3355                         kprintf("\n0x00%x0  ",row);
3356                 }
3357                 e1000_read_nvm(&sc->hw, i, 1, &eeprom_data);
3358                 kprintf("%04x ", eeprom_data);
3359         }
3360         kprintf("\n");
3361 }
3362
3363 static int
3364 emx_sysctl_debug_info(SYSCTL_HANDLER_ARGS)
3365 {
3366         struct emx_softc *sc;
3367         struct ifnet *ifp;
3368         int error, result;
3369
3370         result = -1;
3371         error = sysctl_handle_int(oidp, &result, 0, req);
3372         if (error || !req->newptr)
3373                 return (error);
3374
3375         sc = (struct emx_softc *)arg1;
3376         ifp = &sc->arpcom.ac_if;
3377
3378         ifnet_serialize_all(ifp);
3379
3380         if (result == 1)
3381                 emx_print_debug_info(sc);
3382
3383         /*
3384          * This value will cause a hex dump of the
3385          * first 32 16-bit words of the EEPROM to
3386          * the screen.
3387          */
3388         if (result == 2)
3389                 emx_print_nvm_info(sc);
3390
3391         ifnet_deserialize_all(ifp);
3392
3393         return (error);
3394 }
3395
3396 static int
3397 emx_sysctl_stats(SYSCTL_HANDLER_ARGS)
3398 {
3399         int error, result;
3400
3401         result = -1;
3402         error = sysctl_handle_int(oidp, &result, 0, req);
3403         if (error || !req->newptr)
3404                 return (error);
3405
3406         if (result == 1) {
3407                 struct emx_softc *sc = (struct emx_softc *)arg1;
3408                 struct ifnet *ifp = &sc->arpcom.ac_if;
3409
3410                 ifnet_serialize_all(ifp);
3411                 emx_print_hw_stats(sc);
3412                 ifnet_deserialize_all(ifp);
3413         }
3414         return (error);
3415 }
3416
3417 static void
3418 emx_add_sysctl(struct emx_softc *sc)
3419 {
3420 #ifdef EMX_RSS_DEBUG
3421         char rx_pkt[32];
3422         int i;
3423 #endif
3424
3425         sysctl_ctx_init(&sc->sysctl_ctx);
3426         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
3427                                 SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
3428                                 device_get_nameunit(sc->dev),
3429                                 CTLFLAG_RD, 0, "");
3430         if (sc->sysctl_tree == NULL) {
3431                 device_printf(sc->dev, "can't add sysctl node\n");
3432                 return;
3433         }
3434
3435         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3436                         OID_AUTO, "debug", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3437                         emx_sysctl_debug_info, "I", "Debug Information");
3438
3439         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3440                         OID_AUTO, "stats", CTLTYPE_INT|CTLFLAG_RW, sc, 0,
3441                         emx_sysctl_stats, "I", "Statistics");
3442
3443         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3444                        OID_AUTO, "rxd", CTLFLAG_RD,
3445                        &sc->rx_data[0].num_rx_desc, 0, NULL);
3446         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3447             OID_AUTO, "txd", CTLFLAG_RD, &sc->tx_data.num_tx_desc, 0, NULL);
3448
3449         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3450                         OID_AUTO, "int_throttle_ceil", CTLTYPE_INT|CTLFLAG_RW,
3451                         sc, 0, emx_sysctl_int_throttle, "I",
3452                         "interrupt throttling rate");
3453         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3454                         OID_AUTO, "int_tx_nsegs", CTLTYPE_INT|CTLFLAG_RW,
3455                         sc, 0, emx_sysctl_int_tx_nsegs, "I",
3456                         "# segments per TX interrupt");
3457         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3458                        OID_AUTO, "wreg_tx_nsegs", CTLFLAG_RW,
3459                        &sc->tx_data.tx_wreg_nsegs, 0,
3460                        "# segments before write to hardware register");
3461
3462         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3463                        OID_AUTO, "rx_ring_cnt", CTLFLAG_RD,
3464                        &sc->rx_ring_cnt, 0, "RX ring count");
3465
3466 #ifdef IFPOLL_ENABLE
3467         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3468                         OID_AUTO, "npoll_rxoff", CTLTYPE_INT|CTLFLAG_RW,
3469                         sc, 0, emx_sysctl_npoll_rxoff, "I",
3470                         "NPOLLING RX cpu offset");
3471         SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3472                         OID_AUTO, "npoll_txoff", CTLTYPE_INT|CTLFLAG_RW,
3473                         sc, 0, emx_sysctl_npoll_txoff, "I",
3474                         "NPOLLING TX cpu offset");
3475 #endif
3476
3477 #ifdef EMX_RSS_DEBUG
3478         SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
3479                        OID_AUTO, "rss_debug", CTLFLAG_RW, &sc->rss_debug,
3480                        0, "RSS debug level");
3481         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3482                 ksnprintf(rx_pkt, sizeof(rx_pkt), "rx%d_pkt", i);
3483                 SYSCTL_ADD_UINT(&sc->sysctl_ctx,
3484                                 SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
3485                                 rx_pkt, CTLFLAG_RW,
3486                                 &sc->rx_data[i].rx_pkts, 0, "RXed packets");
3487         }
3488 #endif
3489 }
3490
3491 static int
3492 emx_sysctl_int_throttle(SYSCTL_HANDLER_ARGS)
3493 {
3494         struct emx_softc *sc = (void *)arg1;
3495         struct ifnet *ifp = &sc->arpcom.ac_if;
3496         int error, throttle;
3497
3498         throttle = sc->int_throttle_ceil;
3499         error = sysctl_handle_int(oidp, &throttle, 0, req);
3500         if (error || req->newptr == NULL)
3501                 return error;
3502         if (throttle < 0 || throttle > 1000000000 / 256)
3503                 return EINVAL;
3504
3505         if (throttle) {
3506                 /*
3507                  * Set the interrupt throttling rate in 256ns increments,
3508                  * recalculate sysctl value assignment to get exact frequency.
3509                  */
3510                 throttle = 1000000000 / 256 / throttle;
3511
3512                 /* Upper 16bits of ITR is reserved and should be zero */
3513                 if (throttle & 0xffff0000)
3514                         return EINVAL;
3515         }
3516
3517         ifnet_serialize_all(ifp);
3518
3519         if (throttle)
3520                 sc->int_throttle_ceil = 1000000000 / 256 / throttle;
3521         else
3522                 sc->int_throttle_ceil = 0;
3523
3524         if (ifp->if_flags & IFF_RUNNING)
3525                 emx_set_itr(sc, throttle);
3526
3527         ifnet_deserialize_all(ifp);
3528
3529         if (bootverbose) {
3530                 if_printf(ifp, "Interrupt moderation set to %d/sec\n",
3531                           sc->int_throttle_ceil);
3532         }
3533         return 0;
3534 }
3535
3536 static int
3537 emx_sysctl_int_tx_nsegs(SYSCTL_HANDLER_ARGS)
3538 {
3539         struct emx_softc *sc = (void *)arg1;
3540         struct ifnet *ifp = &sc->arpcom.ac_if;
3541         int error, segs;
3542
3543         segs = sc->tx_data.tx_int_nsegs;
3544         error = sysctl_handle_int(oidp, &segs, 0, req);
3545         if (error || req->newptr == NULL)
3546                 return error;
3547         if (segs <= 0)
3548                 return EINVAL;
3549
3550         ifnet_serialize_all(ifp);
3551
3552         /*
3553          * Don't allow int_tx_nsegs to become:
3554          * o  Less the oact_tx_desc
3555          * o  Too large that no TX desc will cause TX interrupt to
3556          *    be generated (OACTIVE will never recover)
3557          * o  Too small that will cause tx_dd[] overflow
3558          */
3559         if (segs < sc->tx_data.oact_tx_desc ||
3560             segs >= sc->tx_data.num_tx_desc - sc->tx_data.oact_tx_desc ||
3561             segs < sc->tx_data.num_tx_desc / EMX_TXDD_SAFE) {
3562                 error = EINVAL;
3563         } else {
3564                 error = 0;
3565                 sc->tx_data.tx_int_nsegs = segs;
3566         }
3567
3568         ifnet_deserialize_all(ifp);
3569
3570         return error;
3571 }
3572
3573 #ifdef IFPOLL_ENABLE
3574
3575 static int
3576 emx_sysctl_npoll_rxoff(SYSCTL_HANDLER_ARGS)
3577 {
3578         struct emx_softc *sc = (void *)arg1;
3579         struct ifnet *ifp = &sc->arpcom.ac_if;
3580         int error, off;
3581
3582         off = sc->rx_npoll_off;
3583         error = sysctl_handle_int(oidp, &off, 0, req);
3584         if (error || req->newptr == NULL)
3585                 return error;
3586         if (off < 0)
3587                 return EINVAL;
3588
3589         ifnet_serialize_all(ifp);
3590         if (off >= ncpus2 || off % sc->rx_ring_cnt != 0) {
3591                 error = EINVAL;
3592         } else {
3593                 error = 0;
3594                 sc->rx_npoll_off = off;
3595         }
3596         ifnet_deserialize_all(ifp);
3597
3598         return error;
3599 }
3600
3601 static int
3602 emx_sysctl_npoll_txoff(SYSCTL_HANDLER_ARGS)
3603 {
3604         struct emx_softc *sc = (void *)arg1;
3605         struct ifnet *ifp = &sc->arpcom.ac_if;
3606         int error, off;
3607
3608         off = sc->tx_npoll_off;
3609         error = sysctl_handle_int(oidp, &off, 0, req);
3610         if (error || req->newptr == NULL)
3611                 return error;
3612         if (off < 0)
3613                 return EINVAL;
3614
3615         ifnet_serialize_all(ifp);
3616         if (off >= ncpus2) {
3617                 error = EINVAL;
3618         } else {
3619                 error = 0;
3620                 sc->tx_npoll_off = off;
3621         }
3622         ifnet_deserialize_all(ifp);
3623
3624         return error;
3625 }
3626
3627 #endif  /* IFPOLL_ENABLE */
3628
3629 static int
3630 emx_dma_alloc(struct emx_softc *sc)
3631 {
3632         int error, i;
3633
3634         /*
3635          * Create top level busdma tag
3636          */
3637         error = bus_dma_tag_create(NULL, 1, 0,
3638                         BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
3639                         NULL, NULL,
3640                         BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
3641                         0, &sc->parent_dtag);
3642         if (error) {
3643                 device_printf(sc->dev, "could not create top level DMA tag\n");
3644                 return error;
3645         }
3646
3647         /*
3648          * Allocate transmit descriptors ring and buffers
3649          */
3650         error = emx_create_tx_ring(&sc->tx_data);
3651         if (error) {
3652                 device_printf(sc->dev, "Could not setup transmit structures\n");
3653                 return error;
3654         }
3655
3656         /*
3657          * Allocate receive descriptors ring and buffers
3658          */
3659         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3660                 error = emx_create_rx_ring(&sc->rx_data[i]);
3661                 if (error) {
3662                         device_printf(sc->dev,
3663                             "Could not setup receive structures\n");
3664                         return error;
3665                 }
3666         }
3667         return 0;
3668 }
3669
3670 static void
3671 emx_dma_free(struct emx_softc *sc)
3672 {
3673         int i;
3674
3675         emx_destroy_tx_ring(&sc->tx_data, sc->tx_data.num_tx_desc);
3676
3677         for (i = 0; i < sc->rx_ring_cnt; ++i) {
3678                 emx_destroy_rx_ring(&sc->rx_data[i],
3679                                     sc->rx_data[i].num_rx_desc);
3680         }
3681
3682         /* Free top level busdma tag */
3683         if (sc->parent_dtag != NULL)
3684                 bus_dma_tag_destroy(sc->parent_dtag);
3685 }
3686
3687 static void
3688 emx_serialize(struct ifnet *ifp, enum ifnet_serialize slz)
3689 {
3690         struct emx_softc *sc = ifp->if_softc;
3691
3692         ifnet_serialize_array_enter(sc->serializes, EMX_NSERIALIZE,
3693             EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3694 }
3695
3696 static void
3697 emx_deserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3698 {
3699         struct emx_softc *sc = ifp->if_softc;
3700
3701         ifnet_serialize_array_exit(sc->serializes, EMX_NSERIALIZE,
3702             EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3703 }
3704
3705 static int
3706 emx_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz)
3707 {
3708         struct emx_softc *sc = ifp->if_softc;
3709
3710         return ifnet_serialize_array_try(sc->serializes, EMX_NSERIALIZE,
3711             EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz);
3712 }
3713
3714 static void
3715 emx_serialize_skipmain(struct emx_softc *sc)
3716 {
3717         lwkt_serialize_array_enter(sc->serializes, EMX_NSERIALIZE, 1);
3718 }
3719
3720 static void
3721 emx_deserialize_skipmain(struct emx_softc *sc)
3722 {
3723         lwkt_serialize_array_exit(sc->serializes, EMX_NSERIALIZE, 1);
3724 }
3725
3726 #ifdef INVARIANTS
3727
3728 static void
3729 emx_serialize_assert(struct ifnet *ifp, enum ifnet_serialize slz,
3730     boolean_t serialized)
3731 {
3732         struct emx_softc *sc = ifp->if_softc;
3733
3734         ifnet_serialize_array_assert(sc->serializes, EMX_NSERIALIZE,
3735             EMX_TX_SERIALIZE, EMX_RX_SERIALIZE, slz, serialized);
3736 }
3737
3738 #endif  /* INVARIANTS */
3739
3740 #ifdef IFPOLL_ENABLE
3741
3742 static void
3743 emx_npoll_status(struct ifnet *ifp)
3744 {
3745         struct emx_softc *sc = ifp->if_softc;
3746         uint32_t reg_icr;
3747
3748         ASSERT_SERIALIZED(&sc->main_serialize);
3749
3750         reg_icr = E1000_READ_REG(&sc->hw, E1000_ICR);
3751         if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
3752                 callout_stop(&sc->timer);
3753                 sc->hw.mac.get_link_status = 1;
3754                 emx_update_link_status(sc);
3755                 callout_reset(&sc->timer, hz, emx_timer, sc);
3756         }
3757 }
3758
3759 static void
3760 emx_npoll_tx(struct ifnet *ifp, void *arg, int cycle __unused)
3761 {
3762         struct emx_txdata *tdata = arg;
3763
3764         ASSERT_SERIALIZED(&tdata->tx_serialize);
3765
3766         emx_txeof(tdata);
3767         if (!ifq_is_empty(&ifp->if_snd))
3768                 if_devstart(ifp);
3769 }
3770
3771 static void
3772 emx_npoll_rx(struct ifnet *ifp __unused, void *arg, int cycle)
3773 {
3774         struct emx_rxdata *rdata = arg;
3775
3776         ASSERT_SERIALIZED(&rdata->rx_serialize);
3777
3778         emx_rxeof(rdata, cycle);
3779 }
3780
3781 static void
3782 emx_npoll(struct ifnet *ifp, struct ifpoll_info *info)
3783 {
3784         struct emx_softc *sc = ifp->if_softc;
3785
3786         ASSERT_IFNET_SERIALIZED_ALL(ifp);
3787
3788         if (info) {
3789                 int i, off;
3790
3791                 info->ifpi_status.status_func = emx_npoll_status;
3792                 info->ifpi_status.serializer = &sc->main_serialize;
3793
3794                 off = sc->tx_npoll_off;
3795                 KKASSERT(off < ncpus2);
3796                 info->ifpi_tx[off].poll_func = emx_npoll_tx;
3797                 info->ifpi_tx[off].arg = &sc->tx_data;
3798                 info->ifpi_tx[off].serializer = &sc->tx_data.tx_serialize;
3799
3800                 off = sc->rx_npoll_off;
3801                 for (i = 0; i < sc->rx_ring_cnt; ++i) {
3802                         struct emx_rxdata *rdata = &sc->rx_data[i];
3803                         int idx = i + off;
3804
3805                         KKASSERT(idx < ncpus2);
3806                         info->ifpi_rx[idx].poll_func = emx_npoll_rx;
3807                         info->ifpi_rx[idx].arg = rdata;
3808                         info->ifpi_rx[idx].serializer = &rdata->rx_serialize;
3809                 }
3810
3811                 if (ifp->if_flags & IFF_RUNNING)
3812                         emx_disable_intr(sc);
3813                 ifq_set_cpuid(&ifp->if_snd, sc->tx_npoll_off);
3814         } else {
3815                 if (ifp->if_flags & IFF_RUNNING)
3816                         emx_enable_intr(sc);
3817                 ifq_set_cpuid(&ifp->if_snd, rman_get_cpuid(sc->intr_res));
3818         }
3819 }
3820
3821 #endif  /* IFPOLL_ENABLE */
3822
3823 static void
3824 emx_set_itr(struct emx_softc *sc, uint32_t itr)
3825 {
3826         E1000_WRITE_REG(&sc->hw, E1000_ITR, itr);
3827         if (sc->hw.mac.type == e1000_82574) {
3828                 int i;
3829
3830                 /*
3831                  * When using MSIX interrupts we need to
3832                  * throttle using the EITR register
3833                  */
3834                 for (i = 0; i < 4; ++i)
3835                         E1000_WRITE_REG(&sc->hw, E1000_EITR_82574(i), itr);
3836         }
3837 }
3838
3839 /*
3840  * Disable the L0s, 82574L Errata #20
3841  */
3842 static void
3843 emx_disable_aspm(struct emx_softc *sc)
3844 {
3845         uint16_t link_cap, link_ctrl, disable;
3846         uint8_t pcie_ptr, reg;
3847         device_t dev = sc->dev;
3848
3849         switch (sc->hw.mac.type) {
3850         case e1000_82571:
3851         case e1000_82572:
3852         case e1000_82573:
3853                 /*
3854                  * 82573 specification update
3855                  * errata #8 disable L0s
3856                  * errata #41 disable L1
3857                  *
3858                  * 82571/82572 specification update
3859                  # errata #13 disable L1
3860                  * errata #68 disable L0s
3861                  */
3862                 disable = PCIEM_LNKCTL_ASPM_L0S | PCIEM_LNKCTL_ASPM_L1;
3863                 break;
3864
3865         case e1000_82574:
3866                 /*
3867                  * 82574 specification update errata #20
3868                  *
3869                  * There is no need to disable L1
3870                  */
3871                 disable = PCIEM_LNKCTL_ASPM_L0S;
3872                 break;
3873
3874         default:
3875                 return;
3876         }
3877
3878         pcie_ptr = pci_get_pciecap_ptr(dev);
3879         if (pcie_ptr == 0)
3880                 return;
3881
3882         link_cap = pci_read_config(dev, pcie_ptr + PCIER_LINKCAP, 2);
3883         if ((link_cap & PCIEM_LNKCAP_ASPM_MASK) == 0)
3884                 return;
3885
3886         if (bootverbose)
3887                 if_printf(&sc->arpcom.ac_if, "disable ASPM %#02x\n", disable);
3888
3889         reg = pcie_ptr + PCIER_LINKCTRL;
3890         link_ctrl = pci_read_config(dev, reg, 2);
3891         link_ctrl &= ~disable;
3892         pci_write_config(dev, reg, link_ctrl, 2);
3893 }
3894
3895 static int
3896 emx_tso_pullup(struct emx_txdata *tdata, struct mbuf **mp)
3897 {
3898         int iphlen, hoff, thoff, ex = 0;
3899         struct mbuf *m;
3900         struct ip *ip;
3901
3902         m = *mp;
3903         KASSERT(M_WRITABLE(m), ("TSO mbuf not writable"));
3904
3905         iphlen = m->m_pkthdr.csum_iphlen;
3906         thoff = m->m_pkthdr.csum_thlen;
3907         hoff = m->m_pkthdr.csum_lhlen;
3908
3909         KASSERT(iphlen > 0, ("invalid ip hlen"));
3910         KASSERT(thoff > 0, ("invalid tcp hlen"));
3911         KASSERT(hoff > 0, ("invalid ether hlen"));
3912
3913         if (tdata->sc->flags & EMX_FLAG_TSO_PULLEX)
3914                 ex = 4;
3915
3916         if (m->m_len < hoff + iphlen + thoff + ex) {
3917                 m = m_pullup(m, hoff + iphlen + thoff + ex);
3918                 if (m == NULL) {
3919                         *mp = NULL;
3920                         return ENOBUFS;
3921                 }
3922                 *mp = m;
3923         }
3924         ip = mtodoff(m, struct ip *, hoff);
3925         ip->ip_len = 0;
3926
3927         return 0;
3928 }
3929
3930 static int
3931 emx_tso_setup(struct emx_txdata *tdata, struct mbuf *mp,
3932     uint32_t *txd_upper, uint32_t *txd_lower)
3933 {
3934         struct e1000_context_desc *TXD;
3935         int hoff, iphlen, thoff, hlen;
3936         int mss, pktlen, curr_txd;
3937
3938 #ifdef EMX_TSO_DEBUG
3939         tdata->tso_segments++;
3940 #endif
3941
3942         iphlen = mp->m_pkthdr.csum_iphlen;
3943         thoff = mp->m_pkthdr.csum_thlen;
3944         hoff = mp->m_pkthdr.csum_lhlen;
3945         mss = mp->m_pkthdr.tso_segsz;
3946         pktlen = mp->m_pkthdr.len;
3947
3948         if (tdata->csum_flags == CSUM_TSO &&
3949             tdata->csum_iphlen == iphlen &&
3950             tdata->csum_lhlen == hoff &&
3951             tdata->csum_thlen == thoff &&
3952             tdata->csum_mss == mss &&
3953             tdata->csum_pktlen == pktlen) {
3954                 *txd_upper = tdata->csum_txd_upper;
3955                 *txd_lower = tdata->csum_txd_lower;
3956 #ifdef EMX_TSO_DEBUG
3957                 tdata->tso_ctx_reused++;
3958 #endif
3959                 return 0;
3960         }
3961         hlen = hoff + iphlen + thoff;
3962
3963         /*
3964          * Setup a new TSO context.
3965          */
3966
3967         curr_txd = tdata->next_avail_tx_desc;
3968         TXD = (struct e1000_context_desc *)&tdata->tx_desc_base[curr_txd];
3969
3970         *txd_lower = E1000_TXD_CMD_DEXT |       /* Extended descr type */
3971                      E1000_TXD_DTYP_D |         /* Data descr type */
3972                      E1000_TXD_CMD_TSE;         /* Do TSE on this packet */
3973
3974         /* IP and/or TCP header checksum calculation and insertion. */
3975         *txd_upper = (E1000_TXD_POPTS_IXSM | E1000_TXD_POPTS_TXSM) << 8;
3976
3977         /*
3978          * Start offset for header checksum calculation.
3979          * End offset for header checksum calculation.
3980          * Offset of place put the checksum.
3981          */
3982         TXD->lower_setup.ip_fields.ipcss = hoff;
3983         TXD->lower_setup.ip_fields.ipcse = htole16(hoff + iphlen - 1);
3984         TXD->lower_setup.ip_fields.ipcso = hoff + offsetof(struct ip, ip_sum);
3985
3986         /*
3987          * Start offset for payload checksum calculation.
3988          * End offset for payload checksum calculation.
3989          * Offset of place to put the checksum.
3990          */
3991         TXD->upper_setup.tcp_fields.tucss = hoff + iphlen;
3992         TXD->upper_setup.tcp_fields.tucse = 0;
3993         TXD->upper_setup.tcp_fields.tucso =
3994             hoff + iphlen + offsetof(struct tcphdr, th_sum);
3995
3996         /*
3997          * Payload size per packet w/o any headers.
3998          * Length of all headers up to payload.
3999          */
4000         TXD->tcp_seg_setup.fields.mss = htole16(mss);
4001         TXD->tcp_seg_setup.fields.hdr_len = hlen;
4002         TXD->cmd_and_length = htole32(E1000_TXD_CMD_IFCS |
4003                                 E1000_TXD_CMD_DEXT |    /* Extended descr */
4004                                 E1000_TXD_CMD_TSE |     /* TSE context */
4005                                 E1000_TXD_CMD_IP |      /* Do IP csum */
4006                                 E1000_TXD_CMD_TCP |     /* Do TCP checksum */
4007                                 (pktlen - hlen));       /* Total len */
4008
4009         /* Save the information for this TSO context */
4010         tdata->csum_flags = CSUM_TSO;
4011         tdata->csum_lhlen = hoff;
4012         tdata->csum_iphlen = iphlen;
4013         tdata->csum_thlen = thoff;
4014         tdata->csum_mss = mss;
4015         tdata->csum_pktlen = pktlen;
4016         tdata->csum_txd_upper = *txd_upper;
4017         tdata->csum_txd_lower = *txd_lower;
4018
4019         if (++curr_txd == tdata->num_tx_desc)
4020                 curr_txd = 0;
4021
4022         KKASSERT(tdata->num_tx_desc_avail > 0);
4023         tdata->num_tx_desc_avail--;
4024
4025         tdata->next_avail_tx_desc = curr_txd;
4026         return 1;
4027 }