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