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