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