mxge: Cleanup attach path
[dragonfly.git] / sys / dev / netif / mxge / if_mxge.c
1 /******************************************************************************
2
3 Copyright (c) 2006-2013, Myricom Inc.
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions are met:
8
9  1. Redistributions of source code must retain the above copyright notice,
10     this list of conditions and the following disclaimer.
11
12  2. Neither the name of the Myricom Inc, nor the names of its
13     contributors may be used to endorse or promote products derived from
14     this software without specific prior written permission.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 POSSIBILITY OF SUCH DAMAGE.
27
28 $FreeBSD: head/sys/dev/mxge/if_mxge.c 254263 2013-08-12 23:30:01Z scottl $
29
30 ***************************************************************************/
31
32 #include "opt_inet.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/linker.h>
37 #include <sys/firmware.h>
38 #include <sys/endian.h>
39 #include <sys/in_cksum.h>
40 #include <sys/sockio.h>
41 #include <sys/mbuf.h>
42 #include <sys/malloc.h>
43 #include <sys/kernel.h>
44 #include <sys/module.h>
45 #include <sys/serialize.h>
46 #include <sys/socket.h>
47 #include <sys/sysctl.h>
48
49 #include <net/if.h>
50 #include <net/if_arp.h>
51 #include <net/ifq_var.h>
52 #include <net/ethernet.h>
53 #include <net/if_dl.h>
54 #include <net/if_media.h>
55
56 #include <net/bpf.h>
57
58 #include <net/if_types.h>
59 #include <net/vlan/if_vlan_var.h>
60 #include <net/zlib.h>
61
62 #include <netinet/in_systm.h>
63 #include <netinet/in.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66
67 #include <sys/bus.h>
68 #include <sys/rman.h>
69
70 #include <bus/pci/pcireg.h>
71 #include <bus/pci/pcivar.h>
72 #include <bus/pci/pci_private.h> /* XXX for pci_cfg_restore */
73
74 #include <vm/vm.h>              /* for pmap_mapdev() */
75 #include <vm/pmap.h>
76
77 #if defined(__i386__) || defined(__x86_64__)
78 #include <machine/specialreg.h>
79 #endif
80
81 #include <dev/netif/mxge/mxge_mcp.h>
82 #include <dev/netif/mxge/mcp_gen_header.h>
83 #include <dev/netif/mxge/if_mxge_var.h>
84
85 /* tunable params */
86 static int mxge_nvidia_ecrc_enable = 1;
87 static int mxge_force_firmware = 0;
88 static int mxge_intr_coal_delay = MXGE_INTR_COAL_DELAY;
89 static int mxge_deassert_wait = 1;
90 static int mxge_flow_control = 1;
91 static int mxge_ticks;
92 static int mxge_max_slices = 1;
93 static int mxge_rss_hash_type = MXGEFW_RSS_HASH_TYPE_TCP_IPV4;
94 static int mxge_always_promisc = 0;
95 static int mxge_throttle = 0;
96 static int mxge_msi_enable = 1;
97
98 static char *mxge_fw_unaligned = "mxge_ethp_z8e";
99 static char *mxge_fw_aligned = "mxge_eth_z8e";
100 static char *mxge_fw_rss_aligned = "mxge_rss_eth_z8e";
101 static char *mxge_fw_rss_unaligned = "mxge_rss_ethp_z8e";
102
103 TUNABLE_INT("hw.mxge.max_slices", &mxge_max_slices);
104 TUNABLE_INT("hw.mxge.flow_control_enabled", &mxge_flow_control);
105 TUNABLE_INT("hw.mxge.intr_coal_delay", &mxge_intr_coal_delay);  
106 TUNABLE_INT("hw.mxge.nvidia_ecrc_enable", &mxge_nvidia_ecrc_enable);    
107 TUNABLE_INT("hw.mxge.force_firmware", &mxge_force_firmware);    
108 TUNABLE_INT("hw.mxge.deassert_wait", &mxge_deassert_wait);      
109 TUNABLE_INT("hw.mxge.ticks", &mxge_ticks);
110 TUNABLE_INT("hw.mxge.always_promisc", &mxge_always_promisc);
111 TUNABLE_INT("hw.mxge.throttle", &mxge_throttle);
112 TUNABLE_INT("hw.mxge.msi.enable", &mxge_msi_enable);
113
114 static int mxge_probe(device_t dev);
115 static int mxge_attach(device_t dev);
116 static int mxge_detach(device_t dev);
117 static int mxge_shutdown(device_t dev);
118 static void mxge_intr(void *arg);
119
120 static device_method_t mxge_methods[] = {
121         /* Device interface */
122         DEVMETHOD(device_probe, mxge_probe),
123         DEVMETHOD(device_attach, mxge_attach),
124         DEVMETHOD(device_detach, mxge_detach),
125         DEVMETHOD(device_shutdown, mxge_shutdown),
126         DEVMETHOD_END
127 };
128
129 static driver_t mxge_driver = {
130         "mxge",
131         mxge_methods,
132         sizeof(mxge_softc_t),
133 };
134
135 static devclass_t mxge_devclass;
136
137 /* Declare ourselves to be a child of the PCI bus.*/
138 DRIVER_MODULE(mxge, pci, mxge_driver, mxge_devclass, NULL, NULL);
139 MODULE_DEPEND(mxge, firmware, 1, 1, 1);
140 MODULE_DEPEND(mxge, zlib, 1, 1, 1);
141
142 static int mxge_load_firmware(mxge_softc_t *sc, int adopt);
143 static int mxge_send_cmd(mxge_softc_t *sc, uint32_t cmd, mxge_cmd_t *data);
144 static int mxge_close(mxge_softc_t *sc, int down);
145 static int mxge_open(mxge_softc_t *sc);
146 static void mxge_tick(void *arg);
147
148 static int
149 mxge_probe(device_t dev)
150 {
151         int rev;
152
153         if ((pci_get_vendor(dev) == MXGE_PCI_VENDOR_MYRICOM) &&
154             ((pci_get_device(dev) == MXGE_PCI_DEVICE_Z8E) ||
155              (pci_get_device(dev) == MXGE_PCI_DEVICE_Z8E_9))) {
156                 rev = pci_get_revid(dev);
157                 switch (rev) {
158                 case MXGE_PCI_REV_Z8E:
159                         device_set_desc(dev, "Myri10G-PCIE-8A");
160                         break;
161                 case MXGE_PCI_REV_Z8ES:
162                         device_set_desc(dev, "Myri10G-PCIE-8B");
163                         break;
164                 default:
165                         device_set_desc(dev, "Myri10G-PCIE-8??");
166                         device_printf(dev, "Unrecognized rev %d NIC\n",
167                                       rev);
168                         break;  
169                 }
170                 return 0;
171         }
172         return ENXIO;
173 }
174
175 static void
176 mxge_enable_wc(mxge_softc_t *sc)
177 {
178 #if defined(__i386__) || defined(__x86_64__)
179         vm_offset_t len;
180
181         sc->wc = 1;
182         len = rman_get_size(sc->mem_res);
183         pmap_change_attr((vm_offset_t) sc->sram, len / PAGE_SIZE,
184             PAT_WRITE_COMBINING);
185 #endif
186 }
187
188 static int
189 mxge_dma_alloc(mxge_softc_t *sc, bus_dmamem_t *dma, size_t bytes,
190     bus_size_t alignment)
191 {
192         bus_size_t boundary;
193         int err;
194
195         if (bytes > 4096 && alignment == 4096)
196                 boundary = 0;
197         else
198                 boundary = 4096;
199
200         err = bus_dmamem_coherent(sc->parent_dmat, alignment, boundary,
201             BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, bytes,
202             BUS_DMA_WAITOK | BUS_DMA_ZERO, dma);
203         if (err != 0) {
204                 device_printf(sc->dev, "bus_dmamem_coherent failed: %d\n", err);
205                 return err;
206         }
207         return 0;
208 }
209
210 static void
211 mxge_dma_free(bus_dmamem_t *dma)
212 {
213         bus_dmamap_unload(dma->dmem_tag, dma->dmem_map);
214         bus_dmamem_free(dma->dmem_tag, dma->dmem_addr, dma->dmem_map);
215         bus_dma_tag_destroy(dma->dmem_tag);
216 }
217
218 /*
219  * The eeprom strings on the lanaiX have the format
220  * SN=x\0
221  * MAC=x:x:x:x:x:x\0
222  * PC=text\0
223  */
224 static int
225 mxge_parse_strings(mxge_softc_t *sc)
226 {
227         char *ptr;
228         int i, found_mac, found_sn2;
229         char *endptr;
230
231         ptr = sc->eeprom_strings;
232         found_mac = 0;
233         found_sn2 = 0;
234         while (*ptr != '\0') {
235                 if (strncmp(ptr, "MAC=", 4) == 0) {
236                         ptr += 4;
237                         for (i = 0;;) {
238                                 sc->mac_addr[i] = strtoul(ptr, &endptr, 16);
239                                 if (endptr - ptr != 2)
240                                         goto abort;
241                                 ptr = endptr;
242                                 if (++i == 6)
243                                         break;
244                                 if (*ptr++ != ':')
245                                         goto abort;
246                         }
247                         found_mac = 1;
248                 } else if (strncmp(ptr, "PC=", 3) == 0) {
249                         ptr += 3;
250                         strlcpy(sc->product_code_string, ptr,
251                             sizeof(sc->product_code_string));
252                 } else if (!found_sn2 && (strncmp(ptr, "SN=", 3) == 0)) {
253                         ptr += 3;
254                         strlcpy(sc->serial_number_string, ptr,
255                             sizeof(sc->serial_number_string));
256                 } else if (strncmp(ptr, "SN2=", 4) == 0) {
257                         /* SN2 takes precedence over SN */
258                         ptr += 4;
259                         found_sn2 = 1;
260                         strlcpy(sc->serial_number_string, ptr,
261                             sizeof(sc->serial_number_string));
262                 }
263                 while (*ptr++ != '\0') {}
264         }
265
266         if (found_mac)
267                 return 0;
268
269 abort:
270         device_printf(sc->dev, "failed to parse eeprom_strings\n");
271         return ENXIO;
272 }
273
274 #if defined(__i386__) || defined(__x86_64__)
275
276 static void
277 mxge_enable_nvidia_ecrc(mxge_softc_t *sc)
278 {
279         uint32_t val;
280         unsigned long base, off;
281         char *va, *cfgptr;
282         device_t pdev, mcp55;
283         uint16_t vendor_id, device_id, word;
284         uintptr_t bus, slot, func, ivend, idev;
285         uint32_t *ptr32;
286
287         if (!mxge_nvidia_ecrc_enable)
288                 return;
289
290         pdev = device_get_parent(device_get_parent(sc->dev));
291         if (pdev == NULL) {
292                 device_printf(sc->dev, "could not find parent?\n");
293                 return;
294         }
295         vendor_id = pci_read_config(pdev, PCIR_VENDOR, 2);
296         device_id = pci_read_config(pdev, PCIR_DEVICE, 2);
297
298         if (vendor_id != 0x10de)
299                 return;
300
301         base = 0;
302
303         if (device_id == 0x005d) {
304                 /* ck804, base address is magic */
305                 base = 0xe0000000UL;
306         } else if (device_id >= 0x0374 && device_id <= 0x378) {
307                 /* mcp55, base address stored in chipset */
308                 mcp55 = pci_find_bsf(0, 0, 0);
309                 if (mcp55 &&
310                     0x10de == pci_read_config(mcp55, PCIR_VENDOR, 2) &&
311                     0x0369 == pci_read_config(mcp55, PCIR_DEVICE, 2)) {
312                         word = pci_read_config(mcp55, 0x90, 2);
313                         base = ((unsigned long)word & 0x7ffeU) << 25;
314                 }
315         }
316         if (!base)
317                 return;
318
319         /*
320          * XXXX
321          * Test below is commented because it is believed that doing
322          * config read/write beyond 0xff will access the config space
323          * for the next larger function.  Uncomment this and remove 
324          * the hacky pmap_mapdev() way of accessing config space when
325          * FreeBSD grows support for extended pcie config space access
326          */
327 #if 0
328         /*
329          * See if we can, by some miracle, access the extended
330          * config space
331          */
332         val = pci_read_config(pdev, 0x178, 4);
333         if (val != 0xffffffff) {
334                 val |= 0x40;
335                 pci_write_config(pdev, 0x178, val, 4);
336                 return;
337         }
338 #endif
339         /*
340          * Rather than using normal pci config space writes, we must
341          * map the Nvidia config space ourselves.  This is because on
342          * opteron/nvidia class machine the 0xe000000 mapping is
343          * handled by the nvidia chipset, that means the internal PCI
344          * device (the on-chip northbridge), or the amd-8131 bridge
345          * and things behind them are not visible by this method.
346          */
347
348         BUS_READ_IVAR(device_get_parent(pdev), pdev,
349                       PCI_IVAR_BUS, &bus);
350         BUS_READ_IVAR(device_get_parent(pdev), pdev,
351                       PCI_IVAR_SLOT, &slot);
352         BUS_READ_IVAR(device_get_parent(pdev), pdev,
353                       PCI_IVAR_FUNCTION, &func);
354         BUS_READ_IVAR(device_get_parent(pdev), pdev,
355                       PCI_IVAR_VENDOR, &ivend);
356         BUS_READ_IVAR(device_get_parent(pdev), pdev,
357                       PCI_IVAR_DEVICE, &idev);
358
359         off =  base + 0x00100000UL * (unsigned long)bus +
360             0x00001000UL * (unsigned long)(func + 8 * slot);
361
362         /* map it into the kernel */
363         va = pmap_mapdev(trunc_page((vm_paddr_t)off), PAGE_SIZE);
364         if (va == NULL) {
365                 device_printf(sc->dev, "pmap_kenter_temporary didn't\n");
366                 return;
367         }
368         /* get a pointer to the config space mapped into the kernel */
369         cfgptr = va + (off & PAGE_MASK);
370
371         /* make sure that we can really access it */
372         vendor_id = *(uint16_t *)(cfgptr + PCIR_VENDOR);
373         device_id = *(uint16_t *)(cfgptr + PCIR_DEVICE);
374         if (!(vendor_id == ivend && device_id == idev)) {
375                 device_printf(sc->dev, "mapping failed: 0x%x:0x%x\n",
376                     vendor_id, device_id);
377                 pmap_unmapdev((vm_offset_t)va, PAGE_SIZE);
378                 return;
379         }
380
381         ptr32 = (uint32_t*)(cfgptr + 0x178);
382         val = *ptr32;
383
384         if (val == 0xffffffff) {
385                 device_printf(sc->dev, "extended mapping failed\n");
386                 pmap_unmapdev((vm_offset_t)va, PAGE_SIZE);
387                 return;
388         }
389         *ptr32 = val | 0x40;
390         pmap_unmapdev((vm_offset_t)va, PAGE_SIZE);
391         if (bootverbose) {
392                 device_printf(sc->dev, "Enabled ECRC on upstream "
393                     "Nvidia bridge at %d:%d:%d\n",
394                     (int)bus, (int)slot, (int)func);
395         }
396 }
397
398 #else   /* __i386__ || __x86_64__ */
399
400 static void
401 mxge_enable_nvidia_ecrc(mxge_softc_t *sc)
402 {
403         device_printf(sc->dev, "Nforce 4 chipset on non-x86/x86_64!?!?!\n");
404 }
405
406 #endif
407
408 static int
409 mxge_dma_test(mxge_softc_t *sc, int test_type)
410 {
411         mxge_cmd_t cmd;
412         bus_addr_t dmatest_bus = sc->dmabench_dma.dmem_busaddr;
413         int status;
414         uint32_t len;
415         const char *test = " ";
416
417         /*
418          * Run a small DMA test.
419          * The magic multipliers to the length tell the firmware
420          * to do DMA read, write, or read+write tests.  The
421          * results are returned in cmd.data0.  The upper 16
422          * bits of the return is the number of transfers completed.
423          * The lower 16 bits is the time in 0.5us ticks that the
424          * transfers took to complete.
425          */
426
427         len = sc->tx_boundary;
428
429         cmd.data0 = MXGE_LOWPART_TO_U32(dmatest_bus);
430         cmd.data1 = MXGE_HIGHPART_TO_U32(dmatest_bus);
431         cmd.data2 = len * 0x10000;
432         status = mxge_send_cmd(sc, test_type, &cmd);
433         if (status != 0) {
434                 test = "read";
435                 goto abort;
436         }
437         sc->read_dma = ((cmd.data0>>16) * len * 2) / (cmd.data0 & 0xffff);
438
439         cmd.data0 = MXGE_LOWPART_TO_U32(dmatest_bus);
440         cmd.data1 = MXGE_HIGHPART_TO_U32(dmatest_bus);
441         cmd.data2 = len * 0x1;
442         status = mxge_send_cmd(sc, test_type, &cmd);
443         if (status != 0) {
444                 test = "write";
445                 goto abort;
446         }
447         sc->write_dma = ((cmd.data0>>16) * len * 2) / (cmd.data0 & 0xffff);
448
449         cmd.data0 = MXGE_LOWPART_TO_U32(dmatest_bus);
450         cmd.data1 = MXGE_HIGHPART_TO_U32(dmatest_bus);
451         cmd.data2 = len * 0x10001;
452         status = mxge_send_cmd(sc, test_type, &cmd);
453         if (status != 0) {
454                 test = "read/write";
455                 goto abort;
456         }
457         sc->read_write_dma = ((cmd.data0>>16) * len * 2 * 2) /
458             (cmd.data0 & 0xffff);
459
460 abort:
461         if (status != 0 && test_type != MXGEFW_CMD_UNALIGNED_TEST) {
462                 device_printf(sc->dev, "DMA %s benchmark failed: %d\n",
463                     test, status);
464         }
465         return status;
466 }
467
468 /*
469  * The Lanai Z8E PCI-E interface achieves higher Read-DMA throughput
470  * when the PCI-E Completion packets are aligned on an 8-byte
471  * boundary.  Some PCI-E chip sets always align Completion packets; on
472  * the ones that do not, the alignment can be enforced by enabling
473  * ECRC generation (if supported).
474  *
475  * When PCI-E Completion packets are not aligned, it is actually more
476  * efficient to limit Read-DMA transactions to 2KB, rather than 4KB.
477  *
478  * If the driver can neither enable ECRC nor verify that it has
479  * already been enabled, then it must use a firmware image which works
480  * around unaligned completion packets (ethp_z8e.dat), and it should
481  * also ensure that it never gives the device a Read-DMA which is
482  * larger than 2KB by setting the tx_boundary to 2KB.  If ECRC is
483  * enabled, then the driver should use the aligned (eth_z8e.dat)
484  * firmware image, and set tx_boundary to 4KB.
485  */
486 static int
487 mxge_firmware_probe(mxge_softc_t *sc)
488 {
489         device_t dev = sc->dev;
490         int reg, status;
491         uint16_t pectl;
492
493         sc->tx_boundary = 4096;
494
495         /*
496          * Verify the max read request size was set to 4KB
497          * before trying the test with 4KB.
498          */
499         if (pci_find_extcap(dev, PCIY_EXPRESS, &reg) == 0) {
500                 pectl = pci_read_config(dev, reg + 0x8, 2);
501                 if ((pectl & (5 << 12)) != (5 << 12)) {
502                         device_printf(dev, "Max Read Req. size != 4k (0x%x)\n",
503                             pectl);
504                         sc->tx_boundary = 2048;
505                 }
506         }
507
508         /*
509          * Load the optimized firmware (which assumes aligned PCIe
510          * completions) in order to see if it works on this host.
511          */
512         sc->fw_name = mxge_fw_aligned;
513         status = mxge_load_firmware(sc, 1);
514         if (status != 0)
515                 return status;
516
517         /*
518          * Enable ECRC if possible
519          */
520         mxge_enable_nvidia_ecrc(sc);
521
522         /* 
523          * Run a DMA test which watches for unaligned completions and
524          * aborts on the first one seen.  Not required on Z8ES or newer.
525          */
526         if (pci_get_revid(sc->dev) >= MXGE_PCI_REV_Z8ES)
527                 return 0;
528
529         status = mxge_dma_test(sc, MXGEFW_CMD_UNALIGNED_TEST);
530         if (status == 0)
531                 return 0; /* keep the aligned firmware */
532
533         if (status != E2BIG)
534                 device_printf(dev, "DMA test failed: %d\n", status);
535         if (status == ENOSYS) {
536                 device_printf(dev, "Falling back to ethp! "
537                     "Please install up to date fw\n");
538         }
539         return status;
540 }
541
542 static int
543 mxge_select_firmware(mxge_softc_t *sc)
544 {
545         int aligned = 0;
546         int force_firmware = mxge_force_firmware;
547
548         if (sc->throttle)
549                 force_firmware = sc->throttle;
550
551         if (force_firmware != 0) {
552                 if (force_firmware == 1)
553                         aligned = 1;
554                 else
555                         aligned = 0;
556                 if (bootverbose) {
557                         device_printf(sc->dev,
558                             "Assuming %s completions (forced)\n",
559                             aligned ? "aligned" : "unaligned");
560                 }
561                 goto abort;
562         }
563
564         /*
565          * If the PCIe link width is 4 or less, we can use the aligned
566          * firmware and skip any checks
567          */
568         if (sc->link_width != 0 && sc->link_width <= 4) {
569                 device_printf(sc->dev, "PCIe x%d Link, "
570                     "expect reduced performance\n", sc->link_width);
571                 aligned = 1;
572                 goto abort;
573         }
574
575         if (mxge_firmware_probe(sc) == 0)
576                 return 0;
577
578 abort:
579         if (aligned) {
580                 sc->fw_name = mxge_fw_aligned;
581                 sc->tx_boundary = 4096;
582         } else {
583                 sc->fw_name = mxge_fw_unaligned;
584                 sc->tx_boundary = 2048;
585         }
586         return mxge_load_firmware(sc, 0);
587 }
588
589 static int
590 mxge_validate_firmware(mxge_softc_t *sc, const mcp_gen_header_t *hdr)
591 {
592         if (be32toh(hdr->mcp_type) != MCP_TYPE_ETH) {
593                 device_printf(sc->dev, "Bad firmware type: 0x%x\n",
594                     be32toh(hdr->mcp_type));
595                 return EIO;
596         }
597
598         /* Save firmware version for sysctl */
599         strlcpy(sc->fw_version, hdr->version, sizeof(sc->fw_version));
600         if (bootverbose)
601                 device_printf(sc->dev, "firmware id: %s\n", hdr->version);
602
603         ksscanf(sc->fw_version, "%d.%d.%d", &sc->fw_ver_major,
604             &sc->fw_ver_minor, &sc->fw_ver_tiny);
605
606         if (!(sc->fw_ver_major == MXGEFW_VERSION_MAJOR &&
607               sc->fw_ver_minor == MXGEFW_VERSION_MINOR)) {
608                 device_printf(sc->dev, "Found firmware version %s\n",
609                     sc->fw_version);
610                 device_printf(sc->dev, "Driver needs %d.%d\n",
611                     MXGEFW_VERSION_MAJOR, MXGEFW_VERSION_MINOR);
612                 return EINVAL;
613         }
614         return 0;
615 }
616
617 static void *
618 z_alloc(void *nil, u_int items, u_int size)
619 {
620         return kmalloc(items * size, M_TEMP, M_WAITOK);
621 }
622
623 static void
624 z_free(void *nil, void *ptr)
625 {
626         kfree(ptr, M_TEMP);
627 }
628
629 static int
630 mxge_load_firmware_helper(mxge_softc_t *sc, uint32_t *limit)
631 {
632         z_stream zs;
633         char *inflate_buffer;
634         const struct firmware *fw;
635         const mcp_gen_header_t *hdr;
636         unsigned hdr_offset;
637         int status;
638         unsigned int i;
639         char dummy;
640         size_t fw_len;
641
642         fw = firmware_get(sc->fw_name);
643         if (fw == NULL) {
644                 device_printf(sc->dev, "Could not find firmware image %s\n",
645                     sc->fw_name);
646                 return ENOENT;
647         }
648
649         /* Setup zlib and decompress f/w */
650         bzero(&zs, sizeof(zs));
651         zs.zalloc = z_alloc;
652         zs.zfree = z_free;
653         status = inflateInit(&zs);
654         if (status != Z_OK) {
655                 status = EIO;
656                 goto abort_with_fw;
657         }
658
659         /*
660          * The uncompressed size is stored as the firmware version,
661          * which would otherwise go unused
662          */
663         fw_len = (size_t)fw->version;
664         inflate_buffer = kmalloc(fw_len, M_TEMP, M_WAITOK);
665         zs.avail_in = fw->datasize;
666         zs.next_in = __DECONST(char *, fw->data);
667         zs.avail_out = fw_len;
668         zs.next_out = inflate_buffer;
669         status = inflate(&zs, Z_FINISH);
670         if (status != Z_STREAM_END) {
671                 device_printf(sc->dev, "zlib %d\n", status);
672                 status = EIO;
673                 goto abort_with_buffer;
674         }
675
676         /* Check id */
677         hdr_offset =
678         htobe32(*(const uint32_t *)(inflate_buffer + MCP_HEADER_PTR_OFFSET));
679         if ((hdr_offset & 3) || hdr_offset + sizeof(*hdr) > fw_len) {
680                 device_printf(sc->dev, "Bad firmware file");
681                 status = EIO;
682                 goto abort_with_buffer;
683         }
684         hdr = (const void*)(inflate_buffer + hdr_offset);
685
686         status = mxge_validate_firmware(sc, hdr);
687         if (status != 0)
688                 goto abort_with_buffer;
689
690         /* Copy the inflated firmware to NIC SRAM. */
691         for (i = 0; i < fw_len; i += 256) {
692                 mxge_pio_copy(sc->sram + MXGE_FW_OFFSET + i, inflate_buffer + i,
693                     min(256U, (unsigned)(fw_len - i)));
694                 wmb();
695                 dummy = *sc->sram;
696                 wmb();
697         }
698
699         *limit = fw_len;
700         status = 0;
701 abort_with_buffer:
702         kfree(inflate_buffer, M_TEMP);
703         inflateEnd(&zs);
704 abort_with_fw:
705         firmware_put(fw, FIRMWARE_UNLOAD);
706         return status;
707 }
708
709 /*
710  * Enable or disable periodic RDMAs from the host to make certain
711  * chipsets resend dropped PCIe messages
712  */
713 static void
714 mxge_dummy_rdma(mxge_softc_t *sc, int enable)
715 {
716         char buf_bytes[72];
717         volatile uint32_t *confirm;
718         volatile char *submit;
719         uint32_t *buf, dma_low, dma_high;
720         int i;
721
722         buf = (uint32_t *)((unsigned long)(buf_bytes + 7) & ~7UL);
723
724         /* Clear confirmation addr */
725         confirm = (volatile uint32_t *)sc->cmd;
726         *confirm = 0;
727         wmb();
728
729         /*
730          * Send an rdma command to the PCIe engine, and wait for the
731          * response in the confirmation address.  The firmware should
732          * write a -1 there to indicate it is alive and well
733          */
734         dma_low = MXGE_LOWPART_TO_U32(sc->cmd_dma.dmem_busaddr);
735         dma_high = MXGE_HIGHPART_TO_U32(sc->cmd_dma.dmem_busaddr);
736         buf[0] = htobe32(dma_high);             /* confirm addr MSW */
737         buf[1] = htobe32(dma_low);              /* confirm addr LSW */
738         buf[2] = htobe32(0xffffffff);           /* confirm data */
739         dma_low = MXGE_LOWPART_TO_U32(sc->zeropad_dma.dmem_busaddr);
740         dma_high = MXGE_HIGHPART_TO_U32(sc->zeropad_dma.dmem_busaddr);
741         buf[3] = htobe32(dma_high);             /* dummy addr MSW */
742         buf[4] = htobe32(dma_low);              /* dummy addr LSW */
743         buf[5] = htobe32(enable);               /* enable? */
744
745         submit = (volatile char *)(sc->sram + MXGEFW_BOOT_DUMMY_RDMA);
746
747         mxge_pio_copy(submit, buf, 64);
748         wmb();
749         DELAY(1000);
750         wmb();
751         i = 0;
752         while (*confirm != 0xffffffff && i < 20) {
753                 DELAY(1000);
754                 i++;
755         }
756         if (*confirm != 0xffffffff) {
757                 device_printf(sc->dev, "dummy rdma %s failed (%p = 0x%x)",
758                     (enable ? "enable" : "disable"), confirm, *confirm);
759         }
760 }
761
762 static int 
763 mxge_send_cmd(mxge_softc_t *sc, uint32_t cmd, mxge_cmd_t *data)
764 {
765         mcp_cmd_t *buf;
766         char buf_bytes[sizeof(*buf) + 8];
767         volatile mcp_cmd_response_t *response = sc->cmd;
768         volatile char *cmd_addr = sc->sram + MXGEFW_ETH_CMD;
769         uint32_t dma_low, dma_high;
770         int err, sleep_total = 0;
771
772         /*
773          * We may be called during attach, before if_serializer is available.
774          * This is not a fast path, just check for NULL
775          * XXX SERIALIZE
776          */
777         if (sc->ifp->if_serializer)
778                 ASSERT_SERIALIZED(sc->ifp->if_serializer);
779
780         /* ensure buf is aligned to 8 bytes */
781         buf = (mcp_cmd_t *)((unsigned long)(buf_bytes + 7) & ~7UL);
782
783         buf->data0 = htobe32(data->data0);
784         buf->data1 = htobe32(data->data1);
785         buf->data2 = htobe32(data->data2);
786         buf->cmd = htobe32(cmd);
787         dma_low = MXGE_LOWPART_TO_U32(sc->cmd_dma.dmem_busaddr);
788         dma_high = MXGE_HIGHPART_TO_U32(sc->cmd_dma.dmem_busaddr);
789
790         buf->response_addr.low = htobe32(dma_low);
791         buf->response_addr.high = htobe32(dma_high);
792
793         response->result = 0xffffffff;
794         wmb();
795         mxge_pio_copy((volatile void *)cmd_addr, buf, sizeof (*buf));
796
797         /* wait up to 20ms */
798         err = EAGAIN;
799         for (sleep_total = 0; sleep_total <  20; sleep_total++) {
800                 wmb();
801                 switch (be32toh(response->result)) {
802                 case 0:
803                         data->data0 = be32toh(response->data);
804                         err = 0;
805                         break;
806                 case 0xffffffff:
807                         DELAY(1000);
808                         break;
809                 case MXGEFW_CMD_UNKNOWN:
810                         err = ENOSYS;
811                         break;
812                 case MXGEFW_CMD_ERROR_UNALIGNED:
813                         err = E2BIG;
814                         break;
815                 case MXGEFW_CMD_ERROR_BUSY:
816                         err = EBUSY;
817                         break;
818                 case MXGEFW_CMD_ERROR_I2C_ABSENT:
819                         err = ENXIO;
820                         break;
821                 default:
822                         device_printf(sc->dev, 
823                                       "mxge: command %d "
824                                       "failed, result = %d\n",
825                                       cmd, be32toh(response->result));
826                         err = ENXIO;
827                         break;
828                 }
829                 if (err != EAGAIN)
830                         break;
831         }
832         if (err == EAGAIN)
833                 device_printf(sc->dev, "mxge: command %d timed out"
834                               "result = %d\n",
835                               cmd, be32toh(response->result));
836         return err;
837 }
838
839 static int
840 mxge_adopt_running_firmware(mxge_softc_t *sc)
841 {
842         struct mcp_gen_header *hdr;
843         const size_t bytes = sizeof(struct mcp_gen_header);
844         size_t hdr_offset;
845         int status;
846
847         /*
848          * Find running firmware header
849          */
850         hdr_offset =
851         htobe32(*(volatile uint32_t *)(sc->sram + MCP_HEADER_PTR_OFFSET));
852
853         if ((hdr_offset & 3) || hdr_offset + sizeof(*hdr) > sc->sram_size) {
854                 device_printf(sc->dev,
855                     "Running firmware has bad header offset (%zu)\n",
856                     hdr_offset);
857                 return EIO;
858         }
859
860         /*
861          * Copy header of running firmware from SRAM to host memory to
862          * validate firmware
863          */
864         hdr = kmalloc(bytes, M_DEVBUF, M_WAITOK);
865         bus_space_read_region_1(rman_get_bustag(sc->mem_res),
866             rman_get_bushandle(sc->mem_res), hdr_offset, (char *)hdr, bytes);
867         status = mxge_validate_firmware(sc, hdr);
868         kfree(hdr, M_DEVBUF);
869
870         /* 
871          * Check to see if adopted firmware has bug where adopting
872          * it will cause broadcasts to be filtered unless the NIC
873          * is kept in ALLMULTI mode
874          */
875         if (sc->fw_ver_major == 1 && sc->fw_ver_minor == 4 &&
876             sc->fw_ver_tiny >= 4 && sc->fw_ver_tiny <= 11) {
877                 sc->adopted_rx_filter_bug = 1;
878                 device_printf(sc->dev, "Adopting fw %d.%d.%d: "
879                     "working around rx filter bug\n",
880                     sc->fw_ver_major, sc->fw_ver_minor, sc->fw_ver_tiny);
881         }
882
883         return status;
884 }
885
886 static int
887 mxge_load_firmware(mxge_softc_t *sc, int adopt)
888 {
889         volatile uint32_t *confirm;
890         volatile char *submit;
891         char buf_bytes[72];
892         uint32_t *buf, size, dma_low, dma_high;
893         int status, i;
894
895         buf = (uint32_t *)((unsigned long)(buf_bytes + 7) & ~7UL);
896
897         size = sc->sram_size;
898         status = mxge_load_firmware_helper(sc, &size);
899         if (status) {
900                 if (!adopt)
901                         return status;
902
903                 /*
904                  * Try to use the currently running firmware, if
905                  * it is new enough
906                  */
907                 status = mxge_adopt_running_firmware(sc);
908                 if (status) {
909                         device_printf(sc->dev,
910                             "failed to adopt running firmware\n");
911                         return status;
912                 }
913                 device_printf(sc->dev,
914                     "Successfully adopted running firmware\n");
915
916                 if (sc->tx_boundary == 4096) {
917                         device_printf(sc->dev,
918                              "Using firmware currently running on NIC.  "
919                              "For optimal\n");
920                         device_printf(sc->dev,
921                              "performance consider loading "
922                              "optimized firmware\n");
923                 }
924                 sc->fw_name = mxge_fw_unaligned;
925                 sc->tx_boundary = 2048;
926                 return 0;
927         }
928
929         /* Clear confirmation addr */
930         confirm = (volatile uint32_t *)sc->cmd;
931         *confirm = 0;
932         wmb();
933
934         /*
935          * Send a reload command to the bootstrap MCP, and wait for the
936          * response in the confirmation address.  The firmware should
937          * write a -1 there to indicate it is alive and well
938          */
939
940         dma_low = MXGE_LOWPART_TO_U32(sc->cmd_dma.dmem_busaddr);
941         dma_high = MXGE_HIGHPART_TO_U32(sc->cmd_dma.dmem_busaddr);
942
943         buf[0] = htobe32(dma_high);     /* confirm addr MSW */
944         buf[1] = htobe32(dma_low);      /* confirm addr LSW */
945         buf[2] = htobe32(0xffffffff);   /* confirm data */
946
947         /*
948          * FIX: All newest firmware should un-protect the bottom of
949          * the sram before handoff. However, the very first interfaces
950          * do not. Therefore the handoff copy must skip the first 8 bytes
951          */
952                                         /* where the code starts*/
953         buf[3] = htobe32(MXGE_FW_OFFSET + 8);
954         buf[4] = htobe32(size - 8);     /* length of code */
955         buf[5] = htobe32(8);            /* where to copy to */
956         buf[6] = htobe32(0);            /* where to jump to */
957
958         submit = (volatile char *)(sc->sram + MXGEFW_BOOT_HANDOFF);
959         mxge_pio_copy(submit, buf, 64);
960         wmb();
961         DELAY(1000);
962         wmb();
963         i = 0;
964         while (*confirm != 0xffffffff && i < 20) {
965                 DELAY(1000*10);
966                 i++;
967         }
968         if (*confirm != 0xffffffff) {
969                 device_printf(sc->dev,"handoff failed (%p = 0x%x)", 
970                     confirm, *confirm);
971                 return ENXIO;
972         }
973         return 0;
974 }
975
976 static int
977 mxge_update_mac_address(mxge_softc_t *sc)
978 {
979         mxge_cmd_t cmd;
980         uint8_t *addr = sc->mac_addr;
981
982         cmd.data0 = (addr[0] << 24) | (addr[1] << 16) |
983             (addr[2] << 8) | addr[3];
984         cmd.data1 = (addr[4] << 8) | (addr[5]);
985         return mxge_send_cmd(sc, MXGEFW_SET_MAC_ADDRESS, &cmd);
986 }
987
988 static int
989 mxge_change_pause(mxge_softc_t *sc, int pause)
990 {       
991         mxge_cmd_t cmd;
992         int status;
993
994         if (pause)
995                 status = mxge_send_cmd(sc, MXGEFW_ENABLE_FLOW_CONTROL, &cmd);
996         else
997                 status = mxge_send_cmd(sc, MXGEFW_DISABLE_FLOW_CONTROL, &cmd);
998         if (status) {
999                 device_printf(sc->dev, "Failed to set flow control mode\n");
1000                 return ENXIO;
1001         }
1002         sc->pause = pause;
1003         return 0;
1004 }
1005
1006 static void
1007 mxge_change_promisc(mxge_softc_t *sc, int promisc)
1008 {       
1009         mxge_cmd_t cmd;
1010         int status;
1011
1012         if (mxge_always_promisc)
1013                 promisc = 1;
1014
1015         if (promisc)
1016                 status = mxge_send_cmd(sc, MXGEFW_ENABLE_PROMISC, &cmd);
1017         else
1018                 status = mxge_send_cmd(sc, MXGEFW_DISABLE_PROMISC, &cmd);
1019         if (status)
1020                 device_printf(sc->dev, "Failed to set promisc mode\n");
1021 }
1022
1023 static void
1024 mxge_set_multicast_list(mxge_softc_t *sc)
1025 {
1026         mxge_cmd_t cmd;
1027         struct ifmultiaddr *ifma;
1028         struct ifnet *ifp = sc->ifp;
1029         int err;
1030
1031         /* This firmware is known to not support multicast */
1032         if (!sc->fw_multicast_support)
1033                 return;
1034
1035         /* Disable multicast filtering while we play with the lists*/
1036         err = mxge_send_cmd(sc, MXGEFW_ENABLE_ALLMULTI, &cmd);
1037         if (err != 0) {
1038                 device_printf(sc->dev, "Failed MXGEFW_ENABLE_ALLMULTI,"
1039                     " error status: %d\n", err);
1040                 return;
1041         }
1042
1043         if (sc->adopted_rx_filter_bug)
1044                 return;
1045         
1046         if (ifp->if_flags & IFF_ALLMULTI) {
1047                 /* Request to disable multicast filtering, so quit here */
1048                 return;
1049         }
1050
1051         /* Flush all the filters */
1052         err = mxge_send_cmd(sc, MXGEFW_LEAVE_ALL_MULTICAST_GROUPS, &cmd);
1053         if (err != 0) {
1054                 device_printf(sc->dev,
1055                     "Failed MXGEFW_LEAVE_ALL_MULTICAST_GROUPS, "
1056                     "error status: %d\n", err);
1057                 return;
1058         }
1059
1060         /*
1061          * Walk the multicast list, and add each address
1062          */
1063         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1064                 if (ifma->ifma_addr->sa_family != AF_LINK)
1065                         continue;
1066
1067                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
1068                     &cmd.data0, 4);
1069                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr) + 4,
1070                     &cmd.data1, 2);
1071                 cmd.data0 = htonl(cmd.data0);
1072                 cmd.data1 = htonl(cmd.data1);
1073                 err = mxge_send_cmd(sc, MXGEFW_JOIN_MULTICAST_GROUP, &cmd);
1074                 if (err != 0) {
1075                         device_printf(sc->dev, "Failed "
1076                             "MXGEFW_JOIN_MULTICAST_GROUP, "
1077                             "error status: %d\n", err);
1078                         /* Abort, leaving multicast filtering off */
1079                         return;
1080                 }
1081         }
1082
1083         /* Enable multicast filtering */
1084         err = mxge_send_cmd(sc, MXGEFW_DISABLE_ALLMULTI, &cmd);
1085         if (err != 0) {
1086                 device_printf(sc->dev, "Failed MXGEFW_DISABLE_ALLMULTI, "
1087                     "error status: %d\n", err);
1088         }
1089 }
1090
1091 #if 0
1092 static int
1093 mxge_max_mtu(mxge_softc_t *sc)
1094 {
1095         mxge_cmd_t cmd;
1096         int status;
1097
1098         if (MJUMPAGESIZE - MXGEFW_PAD >  MXGEFW_MAX_MTU)
1099                 return  MXGEFW_MAX_MTU - MXGEFW_PAD;
1100
1101         /* try to set nbufs to see if it we can
1102            use virtually contiguous jumbos */
1103         cmd.data0 = 0;
1104         status = mxge_send_cmd(sc, MXGEFW_CMD_ALWAYS_USE_N_BIG_BUFFERS,
1105                                &cmd);
1106         if (status == 0)
1107                 return  MXGEFW_MAX_MTU - MXGEFW_PAD;
1108
1109         /* otherwise, we're limited to MJUMPAGESIZE */
1110         return MJUMPAGESIZE - MXGEFW_PAD;
1111 }
1112 #endif
1113
1114 static int
1115 mxge_reset(mxge_softc_t *sc, int interrupts_setup)
1116 {
1117         struct mxge_slice_state *ss;
1118         mxge_rx_done_t *rx_done;
1119         volatile uint32_t *irq_claim;
1120         mxge_cmd_t cmd;
1121         int slice, status;
1122
1123         /*
1124          * Try to send a reset command to the card to see if it
1125          * is alive
1126          */
1127         memset(&cmd, 0, sizeof (cmd));
1128         status = mxge_send_cmd(sc, MXGEFW_CMD_RESET, &cmd);
1129         if (status != 0) {
1130                 device_printf(sc->dev, "failed reset\n");
1131                 return ENXIO;
1132         }
1133
1134         mxge_dummy_rdma(sc, 1);
1135
1136         /* Set the intrq size */
1137         cmd.data0 = sc->rx_ring_size;
1138         status = mxge_send_cmd(sc, MXGEFW_CMD_SET_INTRQ_SIZE, &cmd);
1139
1140         /*
1141          * Even though we already know how many slices are supported
1142          * via mxge_slice_probe(), MXGEFW_CMD_GET_MAX_RSS_QUEUES
1143          * has magic side effects, and must be called after a reset.
1144          * It must be called prior to calling any RSS related cmds,
1145          * including assigning an interrupt queue for anything but
1146          * slice 0.  It must also be called *after*
1147          * MXGEFW_CMD_SET_INTRQ_SIZE, since the intrq size is used by
1148          * the firmware to compute offsets.
1149          */
1150         if (sc->num_slices > 1) {
1151                 /* Ask the maximum number of slices it supports */
1152                 status = mxge_send_cmd(sc, MXGEFW_CMD_GET_MAX_RSS_QUEUES, &cmd);
1153                 if (status != 0) {
1154                         device_printf(sc->dev,
1155                             "failed to get number of slices\n");
1156                         return status;
1157                 }
1158
1159                 /* 
1160                  * MXGEFW_CMD_ENABLE_RSS_QUEUES must be called prior
1161                  * to setting up the interrupt queue DMA
1162                  */
1163                 cmd.data0 = sc->num_slices;
1164                 cmd.data1 = MXGEFW_SLICE_INTR_MODE_ONE_PER_SLICE;
1165 #ifdef IFNET_BUF_RING
1166                 cmd.data1 |= MXGEFW_SLICE_ENABLE_MULTIPLE_TX_QUEUES;
1167 #endif
1168                 status = mxge_send_cmd(sc, MXGEFW_CMD_ENABLE_RSS_QUEUES, &cmd);
1169                 if (status != 0) {
1170                         device_printf(sc->dev,
1171                             "failed to set number of slices\n");
1172                         return status;
1173                 }
1174         }
1175
1176         if (interrupts_setup) {
1177                 /* Now exchange information about interrupts  */
1178                 for (slice = 0; slice < sc->num_slices; slice++) {
1179                         rx_done = &sc->ss[slice].rx_done;
1180                         memset(rx_done->entry, 0, sc->rx_ring_size);
1181                         cmd.data0 =
1182                             MXGE_LOWPART_TO_U32(rx_done->dma.dmem_busaddr);
1183                         cmd.data1 =
1184                             MXGE_HIGHPART_TO_U32(rx_done->dma.dmem_busaddr);
1185                         cmd.data2 = slice;
1186                         status |= mxge_send_cmd(sc, MXGEFW_CMD_SET_INTRQ_DMA,
1187                             &cmd);
1188                 }
1189         }
1190
1191         status |= mxge_send_cmd(sc, MXGEFW_CMD_GET_INTR_COAL_DELAY_OFFSET,
1192             &cmd);
1193         sc->intr_coal_delay_ptr = (volatile uint32_t *)(sc->sram + cmd.data0);
1194
1195         status |= mxge_send_cmd(sc, MXGEFW_CMD_GET_IRQ_ACK_OFFSET, &cmd);
1196         irq_claim = (volatile uint32_t *)(sc->sram + cmd.data0);
1197
1198         status |= mxge_send_cmd(sc,  MXGEFW_CMD_GET_IRQ_DEASSERT_OFFSET, &cmd);
1199         sc->irq_deassert = (volatile uint32_t *)(sc->sram + cmd.data0);
1200
1201         if (status != 0) {
1202                 device_printf(sc->dev, "failed set interrupt parameters\n");
1203                 return status;
1204         }
1205
1206         *sc->intr_coal_delay_ptr = htobe32(sc->intr_coal_delay);
1207
1208         /* Run a DMA benchmark */
1209         mxge_dma_test(sc, MXGEFW_DMA_TEST);
1210
1211         for (slice = 0; slice < sc->num_slices; slice++) {
1212                 ss = &sc->ss[slice];
1213
1214                 ss->irq_claim = irq_claim + (2 * slice);
1215
1216                 /* Reset mcp/driver shared state back to 0 */
1217                 ss->rx_done.idx = 0;
1218                 ss->rx_done.cnt = 0;
1219                 ss->tx.req = 0;
1220                 ss->tx.done = 0;
1221                 ss->tx.pkt_done = 0;
1222                 ss->tx.queue_active = 0;
1223                 ss->tx.activate = 0;
1224                 ss->tx.deactivate = 0;
1225                 ss->tx.wake = 0;
1226                 ss->tx.defrag = 0;
1227                 ss->tx.stall = 0;
1228                 ss->rx_big.cnt = 0;
1229                 ss->rx_small.cnt = 0;
1230                 if (ss->fw_stats != NULL)
1231                         bzero(ss->fw_stats, sizeof(*ss->fw_stats));
1232         }
1233         sc->rdma_tags_available = 15;
1234
1235         status = mxge_update_mac_address(sc);
1236         mxge_change_promisc(sc, sc->ifp->if_flags & IFF_PROMISC);
1237         mxge_change_pause(sc, sc->pause);
1238         mxge_set_multicast_list(sc);
1239
1240         if (sc->throttle) {
1241                 cmd.data0 = sc->throttle;
1242                 if (mxge_send_cmd(sc, MXGEFW_CMD_SET_THROTTLE_FACTOR, &cmd))
1243                         device_printf(sc->dev, "can't enable throttle\n");
1244         }
1245         return status;
1246 }
1247
1248 static int
1249 mxge_change_throttle(SYSCTL_HANDLER_ARGS)
1250 {
1251         mxge_cmd_t cmd;
1252         mxge_softc_t *sc;
1253         int err;
1254         unsigned int throttle;
1255
1256         sc = arg1;
1257         throttle = sc->throttle;
1258         err = sysctl_handle_int(oidp, &throttle, arg2, req);
1259         if (err != 0) {
1260                 return err;
1261         }
1262
1263         if (throttle == sc->throttle)
1264                 return 0;
1265
1266         if (throttle < MXGE_MIN_THROTTLE || throttle > MXGE_MAX_THROTTLE)
1267                 return EINVAL;
1268
1269         /* XXX SERIALIZE */
1270         lwkt_serialize_enter(sc->ifp->if_serializer);
1271
1272         cmd.data0 = throttle;
1273         err = mxge_send_cmd(sc, MXGEFW_CMD_SET_THROTTLE_FACTOR, &cmd);
1274         if (err == 0)
1275                 sc->throttle = throttle;
1276
1277         lwkt_serialize_exit(sc->ifp->if_serializer);
1278         return err;
1279 }
1280
1281 static int
1282 mxge_change_intr_coal(SYSCTL_HANDLER_ARGS)
1283 {
1284         mxge_softc_t *sc;
1285         unsigned int intr_coal_delay;
1286         int err;
1287
1288         sc = arg1;
1289         intr_coal_delay = sc->intr_coal_delay;
1290         err = sysctl_handle_int(oidp, &intr_coal_delay, arg2, req);
1291         if (err != 0) {
1292                 return err;
1293         }
1294         if (intr_coal_delay == sc->intr_coal_delay)
1295                 return 0;
1296
1297         if (intr_coal_delay == 0 || intr_coal_delay > 1000*1000)
1298                 return EINVAL;
1299
1300         /* XXX SERIALIZE */
1301         lwkt_serialize_enter(sc->ifp->if_serializer);
1302
1303         *sc->intr_coal_delay_ptr = htobe32(intr_coal_delay);
1304         sc->intr_coal_delay = intr_coal_delay;
1305
1306         lwkt_serialize_exit(sc->ifp->if_serializer);
1307         return err;
1308 }
1309
1310 static int
1311 mxge_change_flow_control(SYSCTL_HANDLER_ARGS)
1312 {
1313         mxge_softc_t *sc;
1314         unsigned int enabled;
1315         int err;
1316
1317         sc = arg1;
1318         enabled = sc->pause;
1319         err = sysctl_handle_int(oidp, &enabled, arg2, req);
1320         if (err != 0) {
1321                 return err;
1322         }
1323         if (enabled == sc->pause)
1324                 return 0;
1325
1326         /* XXX SERIALIZE */
1327         lwkt_serialize_enter(sc->ifp->if_serializer);
1328         err = mxge_change_pause(sc, enabled);
1329         lwkt_serialize_exit(sc->ifp->if_serializer);
1330
1331         return err;
1332 }
1333
1334 static int
1335 mxge_handle_be32(SYSCTL_HANDLER_ARGS)
1336 {
1337         int err;
1338
1339         if (arg1 == NULL)
1340                 return EFAULT;
1341         arg2 = be32toh(*(int *)arg1);
1342         arg1 = NULL;
1343         err = sysctl_handle_int(oidp, arg1, arg2, req);
1344
1345         return err;
1346 }
1347
1348 static void
1349 mxge_rem_sysctls(mxge_softc_t *sc)
1350 {
1351         struct mxge_slice_state *ss;
1352         int slice;
1353
1354         if (sc->slice_sysctl_tree == NULL)
1355                 return;
1356
1357         for (slice = 0; slice < sc->num_slices; slice++) {
1358                 ss = &sc->ss[slice];
1359                 if (ss == NULL || ss->sysctl_tree == NULL)
1360                         continue;
1361                 sysctl_ctx_free(&ss->sysctl_ctx);
1362                 ss->sysctl_tree = NULL;
1363         }
1364         sysctl_ctx_free(&sc->slice_sysctl_ctx);
1365         sc->slice_sysctl_tree = NULL;
1366         sysctl_ctx_free(&sc->sysctl_ctx);
1367         sc->sysctl_tree = NULL;
1368 }
1369
1370 static void
1371 mxge_add_sysctls(mxge_softc_t *sc)
1372 {
1373         struct sysctl_ctx_list *ctx;
1374         struct sysctl_oid_list *children;
1375         mcp_irq_data_t *fw;
1376         struct mxge_slice_state *ss;
1377         int slice;
1378         char slice_num[8];
1379
1380         ctx = &sc->sysctl_ctx;
1381         sysctl_ctx_init(ctx);
1382         sc->sysctl_tree = SYSCTL_ADD_NODE(ctx, SYSCTL_STATIC_CHILDREN(_hw),
1383             OID_AUTO, device_get_nameunit(sc->dev), CTLFLAG_RD, 0, "");
1384         if (sc->sysctl_tree == NULL) {
1385                 device_printf(sc->dev, "can't add sysctl node\n");
1386                 return;
1387         }
1388
1389         children = SYSCTL_CHILDREN(sc->sysctl_tree);
1390         fw = sc->ss[0].fw_stats;
1391
1392         /*
1393          * Random information
1394          */
1395         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
1396             CTLFLAG_RD, &sc->fw_version, 0, "firmware version");
1397
1398         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "serial_number",
1399             CTLFLAG_RD, &sc->serial_number_string, 0, "serial number");
1400
1401         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "product_code",
1402             CTLFLAG_RD, &sc->product_code_string, 0, "product code");
1403
1404         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcie_link_width",
1405             CTLFLAG_RD, &sc->link_width, 0, "link width");
1406
1407         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_boundary",
1408             CTLFLAG_RD, &sc->tx_boundary, 0, "tx boundary");
1409
1410         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "write_combine",
1411             CTLFLAG_RD, &sc->wc, 0, "write combining PIO");
1412
1413         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "read_dma_MBs",
1414             CTLFLAG_RD, &sc->read_dma, 0, "DMA Read speed in MB/s");
1415
1416         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "write_dma_MBs",
1417             CTLFLAG_RD, &sc->write_dma, 0, "DMA Write speed in MB/s");
1418
1419         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "read_write_dma_MBs",
1420             CTLFLAG_RD, &sc->read_write_dma, 0,
1421             "DMA concurrent Read/Write speed in MB/s");
1422
1423         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "watchdog_resets",
1424             CTLFLAG_RD, &sc->watchdog_resets, 0,
1425             "Number of times NIC was reset");
1426
1427         /*
1428          * Performance related tunables
1429          */
1430         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_coal_delay",
1431             CTLTYPE_INT|CTLFLAG_RW, sc, 0, mxge_change_intr_coal, "I",
1432             "Interrupt coalescing delay in usecs");
1433
1434         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "throttle",
1435             CTLTYPE_INT|CTLFLAG_RW, sc, 0, mxge_change_throttle, "I",
1436             "Transmit throttling");
1437
1438         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "flow_control_enabled",
1439             CTLTYPE_INT|CTLFLAG_RW, sc, 0, mxge_change_flow_control, "I",
1440             "Interrupt coalescing delay in usecs");
1441
1442         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "deassert_wait",
1443             CTLFLAG_RW, &mxge_deassert_wait, 0,
1444             "Wait for IRQ line to go low in ihandler");
1445
1446         /*
1447          * Stats block from firmware is in network byte order.
1448          * Need to swap it
1449          */
1450         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_up",
1451             CTLTYPE_INT|CTLFLAG_RD, &fw->link_up, 0,
1452             mxge_handle_be32, "I", "link up");
1453
1454         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_tags_available",
1455             CTLTYPE_INT|CTLFLAG_RD, &fw->rdma_tags_available, 0,
1456             mxge_handle_be32, "I", "rdma_tags_available");
1457
1458         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_bad_crc32",
1459             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_bad_crc32, 0,
1460             mxge_handle_be32, "I", "dropped_bad_crc32");
1461
1462         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_bad_phy",
1463             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_bad_phy, 0,
1464             mxge_handle_be32, "I", "dropped_bad_phy");
1465
1466         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_link_error_or_filtered",
1467             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_link_error_or_filtered, 0,
1468             mxge_handle_be32, "I", "dropped_link_error_or_filtered");
1469
1470         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_link_overflow",
1471             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_link_overflow, 0,
1472             mxge_handle_be32, "I", "dropped_link_overflow");
1473
1474         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_multicast_filtered",
1475             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_multicast_filtered, 0,
1476             mxge_handle_be32, "I", "dropped_multicast_filtered");
1477
1478         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_no_big_buffer",
1479             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_no_big_buffer, 0,
1480             mxge_handle_be32, "I", "dropped_no_big_buffer");
1481
1482         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_no_small_buffer",
1483             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_no_small_buffer, 0,
1484             mxge_handle_be32, "I", "dropped_no_small_buffer");
1485
1486         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_overrun",
1487             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_overrun, 0,
1488             mxge_handle_be32, "I", "dropped_overrun");
1489
1490         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_pause",
1491             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_pause, 0,
1492             mxge_handle_be32, "I", "dropped_pause");
1493
1494         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_runt",
1495             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_runt, 0,
1496             mxge_handle_be32, "I", "dropped_runt");
1497
1498         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dropped_unicast_filtered",
1499             CTLTYPE_INT|CTLFLAG_RD, &fw->dropped_unicast_filtered, 0,
1500             mxge_handle_be32, "I", "dropped_unicast_filtered");
1501
1502         /* add counters exported for debugging from all slices */
1503         sysctl_ctx_init(&sc->slice_sysctl_ctx);
1504         sc->slice_sysctl_tree = SYSCTL_ADD_NODE(&sc->slice_sysctl_ctx,
1505             children, OID_AUTO, "slice", CTLFLAG_RD, 0, "");
1506
1507         for (slice = 0; slice < sc->num_slices; slice++) {
1508                 ss = &sc->ss[slice];
1509                 sysctl_ctx_init(&ss->sysctl_ctx);
1510                 ctx = &ss->sysctl_ctx;
1511                 children = SYSCTL_CHILDREN(sc->slice_sysctl_tree);
1512                 ksprintf(slice_num, "%d", slice);
1513                 ss->sysctl_tree = SYSCTL_ADD_NODE(ctx, children, OID_AUTO,
1514                     slice_num, CTLFLAG_RD, 0, "");
1515                 children = SYSCTL_CHILDREN(ss->sysctl_tree);
1516
1517                 /*
1518                  * XXX change to ULONG
1519                  */
1520
1521                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_small_cnt",
1522                     CTLFLAG_RD, &ss->rx_small.cnt, 0, "rx_small_cnt");
1523
1524                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_big_cnt",
1525                     CTLFLAG_RD, &ss->rx_big.cnt, 0, "rx_small_cnt");
1526
1527 #ifndef IFNET_BUF_RING
1528                 /* only transmit from slice 0 for now */
1529                 if (slice > 0)
1530                         continue;
1531 #endif
1532
1533                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_req",
1534                     CTLFLAG_RD, &ss->tx.req, 0, "tx_req");
1535
1536                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_done",
1537                     CTLFLAG_RD, &ss->tx.done, 0, "tx_done");
1538
1539                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_pkt_done",
1540                     CTLFLAG_RD, &ss->tx.pkt_done, 0, "tx_done");
1541
1542                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_stall",
1543                     CTLFLAG_RD, &ss->tx.stall, 0, "tx_stall");
1544
1545                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_wake",
1546                     CTLFLAG_RD, &ss->tx.wake, 0, "tx_wake");
1547
1548                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_defrag",
1549                     CTLFLAG_RD, &ss->tx.defrag, 0, "tx_defrag");
1550
1551                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_queue_active",
1552                     CTLFLAG_RD, &ss->tx.queue_active, 0, "tx_queue_active");
1553
1554                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_activate",
1555                     CTLFLAG_RD, &ss->tx.activate, 0, "tx_activate");
1556
1557                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_deactivate",
1558                     CTLFLAG_RD, &ss->tx.deactivate, 0, "tx_deactivate");
1559         }
1560 }
1561
1562 /*
1563  * Copy an array of mcp_kreq_ether_send_t's to the mcp.  Copy 
1564  * backwards one at a time and handle ring wraps
1565  */
1566 static inline void 
1567 mxge_submit_req_backwards(mxge_tx_ring_t *tx,
1568     mcp_kreq_ether_send_t *src, int cnt)
1569 {
1570         int idx, starting_slot;
1571         starting_slot = tx->req;
1572         while (cnt > 1) {
1573                 cnt--;
1574                 idx = (starting_slot + cnt) & tx->mask;
1575                 mxge_pio_copy(&tx->lanai[idx],
1576                               &src[cnt], sizeof(*src));
1577                 wmb();
1578         }
1579 }
1580
1581 /*
1582  * Copy an array of mcp_kreq_ether_send_t's to the mcp.  Copy
1583  * at most 32 bytes at a time, so as to avoid involving the software
1584  * pio handler in the nic.   We re-write the first segment's flags
1585  * to mark them valid only after writing the entire chain 
1586  */
1587 static inline void 
1588 mxge_submit_req(mxge_tx_ring_t *tx, mcp_kreq_ether_send_t *src, int cnt)
1589 {
1590         int idx, i;
1591         uint32_t *src_ints;
1592         volatile uint32_t *dst_ints;
1593         mcp_kreq_ether_send_t *srcp;
1594         volatile mcp_kreq_ether_send_t *dstp, *dst;
1595         uint8_t last_flags;
1596
1597         idx = tx->req & tx->mask;
1598
1599         last_flags = src->flags;
1600         src->flags = 0;
1601         wmb();
1602         dst = dstp = &tx->lanai[idx];
1603         srcp = src;
1604
1605         if ((idx + cnt) < tx->mask) {
1606                 for (i = 0; i < (cnt - 1); i += 2) {
1607                         mxge_pio_copy(dstp, srcp, 2 * sizeof(*src));
1608                         wmb(); /* force write every 32 bytes */
1609                         srcp += 2;
1610                         dstp += 2;
1611                 }
1612         } else {
1613                 /* submit all but the first request, and ensure 
1614                    that it is submitted below */
1615                 mxge_submit_req_backwards(tx, src, cnt);
1616                 i = 0;
1617         }
1618         if (i < cnt) {
1619                 /* submit the first request */
1620                 mxge_pio_copy(dstp, srcp, sizeof(*src));
1621                 wmb(); /* barrier before setting valid flag */
1622         }
1623
1624         /* re-write the last 32-bits with the valid flags */
1625         src->flags = last_flags;
1626         src_ints = (uint32_t *)src;
1627         src_ints+=3;
1628         dst_ints = (volatile uint32_t *)dst;
1629         dst_ints+=3;
1630         *dst_ints =  *src_ints;
1631         tx->req += cnt;
1632         wmb();
1633 }
1634
1635 static int
1636 mxge_pullup_tso(struct mbuf **mp)
1637 {
1638         int hoff, iphlen, thoff;
1639         struct mbuf *m;
1640
1641         m = *mp;
1642         KASSERT(M_WRITABLE(m), ("TSO mbuf not writable"));
1643
1644         iphlen = m->m_pkthdr.csum_iphlen;
1645         thoff = m->m_pkthdr.csum_thlen;
1646         hoff = m->m_pkthdr.csum_lhlen;
1647
1648         KASSERT(iphlen > 0, ("invalid ip hlen"));
1649         KASSERT(thoff > 0, ("invalid tcp hlen"));
1650         KASSERT(hoff > 0, ("invalid ether hlen"));
1651
1652         if (__predict_false(m->m_len < hoff + iphlen + thoff)) {
1653                 m = m_pullup(m, hoff + iphlen + thoff);
1654                 if (m == NULL) {
1655                         *mp = NULL;
1656                         return ENOBUFS;
1657                 }
1658                 *mp = m;
1659         }
1660         return 0;
1661 }
1662
1663 static void
1664 mxge_encap_tso(struct mxge_slice_state *ss, struct mbuf *m,
1665     int busdma_seg_cnt)
1666 {
1667         mxge_tx_ring_t *tx;
1668         mcp_kreq_ether_send_t *req;
1669         bus_dma_segment_t *seg;
1670         uint32_t low, high_swapped;
1671         int len, seglen, cum_len, cum_len_next;
1672         int next_is_first, chop, cnt, rdma_count, small;
1673         uint16_t pseudo_hdr_offset, cksum_offset, mss;
1674         uint8_t flags, flags_next;
1675         static int once;
1676
1677         mss = m->m_pkthdr.tso_segsz;
1678
1679         /* negative cum_len signifies to the
1680          * send loop that we are still in the
1681          * header portion of the TSO packet.
1682          */
1683         cum_len = -(m->m_pkthdr.csum_lhlen + m->m_pkthdr.csum_iphlen +
1684             m->m_pkthdr.csum_thlen);
1685
1686         /* TSO implies checksum offload on this hardware */
1687         cksum_offset = m->m_pkthdr.csum_lhlen + m->m_pkthdr.csum_iphlen;
1688         flags = MXGEFW_FLAGS_TSO_HDR | MXGEFW_FLAGS_FIRST;
1689
1690         /* for TSO, pseudo_hdr_offset holds mss.
1691          * The firmware figures out where to put
1692          * the checksum by parsing the header. */
1693         pseudo_hdr_offset = htobe16(mss);
1694
1695         tx = &ss->tx;
1696         req = tx->req_list;
1697         seg = tx->seg_list;
1698         cnt = 0;
1699         rdma_count = 0;
1700         /* "rdma_count" is the number of RDMAs belonging to the
1701          * current packet BEFORE the current send request. For
1702          * non-TSO packets, this is equal to "count".
1703          * For TSO packets, rdma_count needs to be reset
1704          * to 0 after a segment cut.
1705          *
1706          * The rdma_count field of the send request is
1707          * the number of RDMAs of the packet starting at
1708          * that request. For TSO send requests with one ore more cuts
1709          * in the middle, this is the number of RDMAs starting
1710          * after the last cut in the request. All previous
1711          * segments before the last cut implicitly have 1 RDMA.
1712          *
1713          * Since the number of RDMAs is not known beforehand,
1714          * it must be filled-in retroactively - after each
1715          * segmentation cut or at the end of the entire packet.
1716          */
1717
1718         while (busdma_seg_cnt) {
1719                 /* Break the busdma segment up into pieces*/
1720                 low = MXGE_LOWPART_TO_U32(seg->ds_addr);
1721                 high_swapped =  htobe32(MXGE_HIGHPART_TO_U32(seg->ds_addr));
1722                 len = seg->ds_len;
1723
1724                 while (len) {
1725                         flags_next = flags & ~MXGEFW_FLAGS_FIRST;
1726                         seglen = len;
1727                         cum_len_next = cum_len + seglen;
1728                         (req-rdma_count)->rdma_count = rdma_count + 1;
1729                         if (__predict_true(cum_len >= 0)) {
1730                                 /* payload */
1731                                 chop = (cum_len_next > mss);
1732                                 cum_len_next = cum_len_next % mss;
1733                                 next_is_first = (cum_len_next == 0);
1734                                 flags |= chop * MXGEFW_FLAGS_TSO_CHOP;
1735                                 flags_next |= next_is_first *
1736                                         MXGEFW_FLAGS_FIRST;
1737                                 rdma_count |= -(chop | next_is_first);
1738                                 rdma_count += chop & !next_is_first;
1739                         } else if (cum_len_next >= 0) {
1740                                 /* header ends */
1741                                 rdma_count = -1;
1742                                 cum_len_next = 0;
1743                                 seglen = -cum_len;
1744                                 small = (mss <= MXGEFW_SEND_SMALL_SIZE);
1745                                 flags_next = MXGEFW_FLAGS_TSO_PLD |
1746                                         MXGEFW_FLAGS_FIRST | 
1747                                         (small * MXGEFW_FLAGS_SMALL);
1748                         }
1749
1750                         req->addr_high = high_swapped;
1751                         req->addr_low = htobe32(low);
1752                         req->pseudo_hdr_offset = pseudo_hdr_offset;
1753                         req->pad = 0;
1754                         req->rdma_count = 1;
1755                         req->length = htobe16(seglen);
1756                         req->cksum_offset = cksum_offset;
1757                         req->flags = flags | ((cum_len & 1) *
1758                                               MXGEFW_FLAGS_ALIGN_ODD);
1759                         low += seglen;
1760                         len -= seglen;
1761                         cum_len = cum_len_next;
1762                         flags = flags_next;
1763                         req++;
1764                         cnt++;
1765                         rdma_count++;
1766                         if (__predict_false(cksum_offset > seglen))
1767                                 cksum_offset -= seglen;
1768                         else
1769                                 cksum_offset = 0;
1770                         if (__predict_false(cnt > tx->max_desc))
1771                                 goto drop;
1772                 }
1773                 busdma_seg_cnt--;
1774                 seg++;
1775         }
1776         (req-rdma_count)->rdma_count = rdma_count;
1777
1778         do {
1779                 req--;
1780                 req->flags |= MXGEFW_FLAGS_TSO_LAST;
1781         } while (!(req->flags & (MXGEFW_FLAGS_TSO_CHOP | MXGEFW_FLAGS_FIRST)));
1782
1783         tx->info[((cnt - 1) + tx->req) & tx->mask].flag = 1;
1784         mxge_submit_req(tx, tx->req_list, cnt);
1785 #ifdef IFNET_BUF_RING
1786         if ((ss->sc->num_slices > 1) && tx->queue_active == 0) {
1787                 /* tell the NIC to start polling this slice */
1788                 *tx->send_go = 1;
1789                 tx->queue_active = 1;
1790                 tx->activate++;
1791                 wmb();
1792         }
1793 #endif
1794         return;
1795
1796 drop:
1797         bus_dmamap_unload(tx->dmat, tx->info[tx->req & tx->mask].map);
1798         m_freem(m);
1799         ss->oerrors++;
1800         if (!once) {
1801                 kprintf("tx->max_desc exceeded via TSO!\n");
1802                 kprintf("mss = %d, %ld, %d!\n", mss,
1803                        (long)seg - (long)tx->seg_list, tx->max_desc);
1804                 once = 1;
1805         }
1806 }
1807
1808 static void
1809 mxge_encap(struct mxge_slice_state *ss, struct mbuf *m)
1810 {
1811         mxge_softc_t *sc;
1812         mcp_kreq_ether_send_t *req;
1813         bus_dma_segment_t *seg;
1814         mxge_tx_ring_t *tx;
1815         int cnt, cum_len, err, i, idx, odd_flag;
1816         uint16_t pseudo_hdr_offset;
1817         uint8_t flags, cksum_offset;
1818
1819         sc = ss->sc;
1820         tx = &ss->tx;
1821
1822         if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1823                 if (mxge_pullup_tso(&m))
1824                         return;
1825         }
1826
1827         /* (try to) map the frame for DMA */
1828         idx = tx->req & tx->mask;
1829         err = bus_dmamap_load_mbuf_defrag(tx->dmat, tx->info[idx].map, &m,
1830             tx->seg_list, tx->max_desc - 2, &cnt, BUS_DMA_NOWAIT);
1831         if (__predict_false(err != 0))
1832                 goto drop;
1833         bus_dmamap_sync(tx->dmat, tx->info[idx].map, BUS_DMASYNC_PREWRITE);
1834         tx->info[idx].m = m;
1835
1836         /* TSO is different enough, we handle it in another routine */
1837         if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1838                 mxge_encap_tso(ss, m, cnt);
1839                 return;
1840         }
1841
1842         req = tx->req_list;
1843         cksum_offset = 0;
1844         pseudo_hdr_offset = 0;
1845         flags = MXGEFW_FLAGS_NO_TSO;
1846
1847         /* checksum offloading? */
1848         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1849                 cksum_offset = m->m_pkthdr.csum_lhlen + m->m_pkthdr.csum_iphlen;
1850                 pseudo_hdr_offset = cksum_offset +  m->m_pkthdr.csum_data;
1851                 pseudo_hdr_offset = htobe16(pseudo_hdr_offset);
1852                 req->cksum_offset = cksum_offset;
1853                 flags |= MXGEFW_FLAGS_CKSUM;
1854                 odd_flag = MXGEFW_FLAGS_ALIGN_ODD;
1855         } else {
1856                 odd_flag = 0;
1857         }
1858         if (m->m_pkthdr.len < MXGEFW_SEND_SMALL_SIZE)
1859                 flags |= MXGEFW_FLAGS_SMALL;
1860
1861         /* convert segments into a request list */
1862         cum_len = 0;
1863         seg = tx->seg_list;
1864         req->flags = MXGEFW_FLAGS_FIRST;
1865         for (i = 0; i < cnt; i++) {
1866                 req->addr_low = 
1867                         htobe32(MXGE_LOWPART_TO_U32(seg->ds_addr));
1868                 req->addr_high = 
1869                         htobe32(MXGE_HIGHPART_TO_U32(seg->ds_addr));
1870                 req->length = htobe16(seg->ds_len);
1871                 req->cksum_offset = cksum_offset;
1872                 if (cksum_offset > seg->ds_len)
1873                         cksum_offset -= seg->ds_len;
1874                 else
1875                         cksum_offset = 0;
1876                 req->pseudo_hdr_offset = pseudo_hdr_offset;
1877                 req->pad = 0; /* complete solid 16-byte block */
1878                 req->rdma_count = 1;
1879                 req->flags |= flags | ((cum_len & 1) * odd_flag);
1880                 cum_len += seg->ds_len;
1881                 seg++;
1882                 req++;
1883                 req->flags = 0;
1884         }
1885         req--;
1886         /* pad runts to 60 bytes */
1887         if (cum_len < 60) {
1888                 req++;
1889                 req->addr_low =
1890                     htobe32(MXGE_LOWPART_TO_U32(sc->zeropad_dma.dmem_busaddr));
1891                 req->addr_high =
1892                     htobe32(MXGE_HIGHPART_TO_U32(sc->zeropad_dma.dmem_busaddr));
1893                 req->length = htobe16(60 - cum_len);
1894                 req->cksum_offset = 0;
1895                 req->pseudo_hdr_offset = pseudo_hdr_offset;
1896                 req->pad = 0; /* complete solid 16-byte block */
1897                 req->rdma_count = 1;
1898                 req->flags |= flags | ((cum_len & 1) * odd_flag);
1899                 cnt++;
1900         }
1901
1902         tx->req_list[0].rdma_count = cnt;
1903 #if 0
1904         /* print what the firmware will see */
1905         for (i = 0; i < cnt; i++) {
1906                 kprintf("%d: addr: 0x%x 0x%x len:%d pso%d,"
1907                     "cso:%d, flags:0x%x, rdma:%d\n",
1908                     i, (int)ntohl(tx->req_list[i].addr_high),
1909                     (int)ntohl(tx->req_list[i].addr_low),
1910                     (int)ntohs(tx->req_list[i].length),
1911                     (int)ntohs(tx->req_list[i].pseudo_hdr_offset),
1912                     tx->req_list[i].cksum_offset, tx->req_list[i].flags,
1913                     tx->req_list[i].rdma_count);
1914         }
1915         kprintf("--------------\n");
1916 #endif
1917         tx->info[((cnt - 1) + tx->req) & tx->mask].flag = 1;
1918         mxge_submit_req(tx, tx->req_list, cnt);
1919 #ifdef IFNET_BUF_RING
1920         if ((ss->sc->num_slices > 1) && tx->queue_active == 0) {
1921                 /* tell the NIC to start polling this slice */
1922                 *tx->send_go = 1;
1923                 tx->queue_active = 1;
1924                 tx->activate++;
1925                 wmb();
1926         }
1927 #endif
1928         return;
1929
1930 drop:
1931         m_freem(m);
1932         ss->oerrors++;
1933 }
1934
1935 static inline void
1936 mxge_start_locked(struct mxge_slice_state *ss)
1937 {
1938         mxge_softc_t *sc;
1939         struct mbuf *m;
1940         struct ifnet *ifp;
1941         mxge_tx_ring_t *tx;
1942
1943         sc = ss->sc;
1944         ifp = sc->ifp;
1945         tx = &ss->tx;
1946         while ((tx->mask - (tx->req - tx->done)) > tx->max_desc) {
1947                 m = ifq_dequeue(&ifp->if_snd);
1948                 if (m == NULL) {
1949                         return;
1950                 }
1951                 /* let BPF see it */
1952                 BPF_MTAP(ifp, m);
1953
1954                 /* give it to the nic */
1955                 mxge_encap(ss, m);
1956         }
1957
1958         /* ran out of transmit slots */
1959         ifq_set_oactive(&ifp->if_snd);
1960 }
1961
1962 static void
1963 mxge_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
1964 {
1965         mxge_softc_t *sc = ifp->if_softc;
1966         struct mxge_slice_state *ss;
1967
1968         ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
1969         ASSERT_SERIALIZED(sc->ifp->if_serializer);
1970         /* only use the first slice for now */
1971         ss = &sc->ss[0];
1972         mxge_start_locked(ss);
1973 }
1974
1975 /*
1976  * copy an array of mcp_kreq_ether_recv_t's to the mcp.  Copy
1977  * at most 32 bytes at a time, so as to avoid involving the software
1978  * pio handler in the nic.   We re-write the first segment's low
1979  * DMA address to mark it valid only after we write the entire chunk
1980  * in a burst
1981  */
1982 static inline void
1983 mxge_submit_8rx(volatile mcp_kreq_ether_recv_t *dst,
1984     mcp_kreq_ether_recv_t *src)
1985 {
1986         uint32_t low;
1987
1988         low = src->addr_low;
1989         src->addr_low = 0xffffffff;
1990         mxge_pio_copy(dst, src, 4 * sizeof (*src));
1991         wmb();
1992         mxge_pio_copy(dst + 4, src + 4, 4 * sizeof (*src));
1993         wmb();
1994         src->addr_low = low;
1995         dst->addr_low = low;
1996         wmb();
1997 }
1998
1999 static int
2000 mxge_get_buf_small(struct mxge_slice_state *ss, bus_dmamap_t map, int idx)
2001 {
2002         bus_dma_segment_t seg;
2003         struct mbuf *m;
2004         mxge_rx_ring_t *rx = &ss->rx_small;
2005         int cnt, err;
2006
2007         m = m_gethdr(MB_DONTWAIT, MT_DATA);
2008         if (m == NULL) {
2009                 rx->alloc_fail++;
2010                 err = ENOBUFS;
2011                 goto done;
2012         }
2013         m->m_len = m->m_pkthdr.len = MHLEN;
2014         err = bus_dmamap_load_mbuf_segment(rx->dmat, map, m, 
2015                                       &seg, 1, &cnt, BUS_DMA_NOWAIT);
2016         if (err != 0) {
2017                 kprintf("can't dmamap small (%d)\n", err);
2018                 m_free(m);
2019                 goto done;
2020         }
2021         rx->info[idx].m = m;
2022         rx->shadow[idx].addr_low = 
2023                 htobe32(MXGE_LOWPART_TO_U32(seg.ds_addr));
2024         rx->shadow[idx].addr_high = 
2025                 htobe32(MXGE_HIGHPART_TO_U32(seg.ds_addr));
2026
2027 done:
2028         if ((idx & 7) == 7)
2029                 mxge_submit_8rx(&rx->lanai[idx - 7], &rx->shadow[idx - 7]);
2030         return err;
2031 }
2032
2033 static int
2034 mxge_get_buf_big(struct mxge_slice_state *ss, bus_dmamap_t map, int idx)
2035 {
2036         bus_dma_segment_t seg[3];
2037         struct mbuf *m;
2038         mxge_rx_ring_t *rx = &ss->rx_big;
2039         int cnt, err, i;
2040
2041         if (rx->cl_size == MCLBYTES)
2042                 m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
2043         else {
2044 #if 0
2045                 m = m_getjcl(MB_DONTWAIT, MT_DATA, M_PKTHDR, rx->cl_size);
2046 #else
2047                 /*
2048                  * XXX: allocate normal sized buffers for big buffers.
2049                  * We should be fine as long as we don't get any jumbo frames
2050                  */
2051                 m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
2052 #endif
2053         }
2054         if (m == NULL) {
2055                 rx->alloc_fail++;
2056                 err = ENOBUFS;
2057                 goto done;
2058         }
2059         m->m_len = m->m_pkthdr.len = rx->mlen;
2060         err = bus_dmamap_load_mbuf_segment(rx->dmat, map, m, 
2061                                       seg, 1, &cnt, BUS_DMA_NOWAIT);
2062         if (err != 0) {
2063                 kprintf("can't dmamap big (%d)\n", err);
2064                 m_free(m);
2065                 goto done;
2066         }
2067         rx->info[idx].m = m;
2068         rx->shadow[idx].addr_low = 
2069                 htobe32(MXGE_LOWPART_TO_U32(seg->ds_addr));
2070         rx->shadow[idx].addr_high = 
2071                 htobe32(MXGE_HIGHPART_TO_U32(seg->ds_addr));
2072
2073 #if MXGE_VIRT_JUMBOS
2074         for (i = 1; i < cnt; i++) {
2075                 rx->shadow[idx + i].addr_low = 
2076                         htobe32(MXGE_LOWPART_TO_U32(seg[i].ds_addr));
2077                 rx->shadow[idx + i].addr_high = 
2078                         htobe32(MXGE_HIGHPART_TO_U32(seg[i].ds_addr));
2079         }
2080 #endif
2081
2082 done:
2083         for (i = 0; i < rx->nbufs; i++) {
2084                 if ((idx & 7) == 7) {
2085                         mxge_submit_8rx(&rx->lanai[idx - 7],
2086                                         &rx->shadow[idx - 7]);
2087                 }
2088                 idx++;
2089         }
2090         return err;
2091 }
2092
2093 /* 
2094  *  Myri10GE hardware checksums are not valid if the sender
2095  *  padded the frame with non-zero padding.  This is because
2096  *  the firmware just does a simple 16-bit 1s complement
2097  *  checksum across the entire frame, excluding the first 14
2098  *  bytes.  It is best to simply to check the checksum and
2099  *  tell the stack about it only if the checksum is good
2100  */
2101 static inline uint16_t
2102 mxge_rx_csum(struct mbuf *m, int csum)
2103 {
2104         struct ether_header *eh;
2105         struct ip *ip;
2106         uint16_t c;
2107
2108         eh = mtod(m, struct ether_header *);
2109
2110         /* only deal with IPv4 TCP & UDP for now */
2111         if (__predict_false(eh->ether_type != htons(ETHERTYPE_IP)))
2112                 return 1;
2113         ip = (struct ip *)(eh + 1);
2114         if (__predict_false(ip->ip_p != IPPROTO_TCP &&
2115                             ip->ip_p != IPPROTO_UDP))
2116                 return 1;
2117 #ifdef INET
2118         c = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2119                       htonl(ntohs(csum) + ntohs(ip->ip_len) +
2120                             - (ip->ip_hl << 2) + ip->ip_p));
2121 #else
2122         c = 1;
2123 #endif
2124         c ^= 0xffff;
2125         return (c);
2126 }
2127
2128 static void
2129 mxge_vlan_tag_remove(struct mbuf *m, uint32_t *csum)
2130 {
2131         struct ether_vlan_header *evl;
2132         uint32_t partial;
2133
2134         evl = mtod(m, struct ether_vlan_header *);
2135
2136         /*
2137          * fix checksum by subtracting EVL_ENCAPLEN bytes
2138          * after what the firmware thought was the end of the ethernet
2139          * header.
2140          */
2141
2142         /* put checksum into host byte order */
2143         *csum = ntohs(*csum); 
2144         partial = ntohl(*(uint32_t *)(mtod(m, char *) + ETHER_HDR_LEN));
2145         (*csum) += ~partial;
2146         (*csum) +=  ((*csum) < ~partial);
2147         (*csum) = ((*csum) >> 16) + ((*csum) & 0xFFFF);
2148         (*csum) = ((*csum) >> 16) + ((*csum) & 0xFFFF);
2149
2150         /* restore checksum to network byte order; 
2151            later consumers expect this */
2152         *csum = htons(*csum);
2153
2154         /* save the tag */
2155         m->m_pkthdr.ether_vlantag = ntohs(evl->evl_tag);
2156         m->m_flags |= M_VLANTAG;
2157
2158         /*
2159          * Remove the 802.1q header by copying the Ethernet
2160          * addresses over it and adjusting the beginning of
2161          * the data in the mbuf.  The encapsulated Ethernet
2162          * type field is already in place.
2163          */
2164         bcopy((char *)evl, (char *)evl + EVL_ENCAPLEN,
2165               ETHER_HDR_LEN - ETHER_TYPE_LEN);
2166         m_adj(m, EVL_ENCAPLEN);
2167 }
2168
2169
2170 static inline void
2171 mxge_rx_done_big(struct mxge_slice_state *ss, uint32_t len, uint32_t csum)
2172 {
2173         mxge_softc_t *sc;
2174         struct ifnet *ifp;
2175         struct mbuf *m;
2176         struct ether_header *eh;
2177         mxge_rx_ring_t *rx;
2178         bus_dmamap_t old_map;
2179         int idx;
2180
2181         sc = ss->sc;
2182         ifp = sc->ifp;
2183         rx = &ss->rx_big;
2184         idx = rx->cnt & rx->mask;
2185         rx->cnt += rx->nbufs;
2186         /* save a pointer to the received mbuf */
2187         m = rx->info[idx].m;
2188         /* try to replace the received mbuf */
2189         if (mxge_get_buf_big(ss, rx->extra_map, idx)) {
2190                 /* drop the frame -- the old mbuf is re-cycled */
2191                 IFNET_STAT_INC(ifp, ierrors, 1);
2192                 return;
2193         }
2194
2195         /* unmap the received buffer */
2196         old_map = rx->info[idx].map;
2197         bus_dmamap_sync(rx->dmat, old_map, BUS_DMASYNC_POSTREAD);
2198         bus_dmamap_unload(rx->dmat, old_map);
2199
2200         /* swap the bus_dmamap_t's */
2201         rx->info[idx].map = rx->extra_map;
2202         rx->extra_map = old_map;
2203
2204         /* mcp implicitly skips 1st 2 bytes so that packet is properly
2205          * aligned */
2206         m->m_data += MXGEFW_PAD;
2207
2208         m->m_pkthdr.rcvif = ifp;
2209         m->m_len = m->m_pkthdr.len = len;
2210         ss->ipackets++;
2211         eh = mtod(m, struct ether_header *);
2212         if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
2213                 mxge_vlan_tag_remove(m, &csum);
2214         }
2215         /* if the checksum is valid, mark it in the mbuf header */
2216         if ((ifp->if_capenable & IFCAP_RXCSUM) &&
2217             0 == mxge_rx_csum(m, csum)) {
2218                 /* Tell the stack that the checksum is good */
2219                 m->m_pkthdr.csum_data = 0xffff;
2220                 m->m_pkthdr.csum_flags = CSUM_PSEUDO_HDR |
2221                     CSUM_DATA_VALID;
2222         }
2223 #if 0
2224         /* flowid only valid if RSS hashing is enabled */
2225         if (sc->num_slices > 1) {
2226                 m->m_pkthdr.flowid = (ss - sc->ss);
2227                 m->m_flags |= M_FLOWID;
2228         }
2229 #endif
2230         ifp->if_input(ifp, m);
2231 }
2232
2233 static inline void
2234 mxge_rx_done_small(struct mxge_slice_state *ss, uint32_t len, uint32_t csum)
2235 {
2236         mxge_softc_t *sc;
2237         struct ifnet *ifp;
2238         struct ether_header *eh;
2239         struct mbuf *m;
2240         mxge_rx_ring_t *rx;
2241         bus_dmamap_t old_map;
2242         int idx;
2243
2244         sc = ss->sc;
2245         ifp = sc->ifp;
2246         rx = &ss->rx_small;
2247         idx = rx->cnt & rx->mask;
2248         rx->cnt++;
2249         /* save a pointer to the received mbuf */
2250         m = rx->info[idx].m;
2251         /* try to replace the received mbuf */
2252         if (mxge_get_buf_small(ss, rx->extra_map, idx)) {
2253                 /* drop the frame -- the old mbuf is re-cycled */
2254                 IFNET_STAT_INC(ifp, ierrors, 1);
2255                 return;
2256         }
2257
2258         /* unmap the received buffer */
2259         old_map = rx->info[idx].map;
2260         bus_dmamap_sync(rx->dmat, old_map, BUS_DMASYNC_POSTREAD);
2261         bus_dmamap_unload(rx->dmat, old_map);
2262
2263         /* swap the bus_dmamap_t's */
2264         rx->info[idx].map = rx->extra_map;
2265         rx->extra_map = old_map;
2266
2267         /* mcp implicitly skips 1st 2 bytes so that packet is properly
2268          * aligned */
2269         m->m_data += MXGEFW_PAD;
2270
2271         m->m_pkthdr.rcvif = ifp;
2272         m->m_len = m->m_pkthdr.len = len;
2273         ss->ipackets++;
2274         eh = mtod(m, struct ether_header *);
2275         if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
2276                 mxge_vlan_tag_remove(m, &csum);
2277         }
2278         /* if the checksum is valid, mark it in the mbuf header */
2279         if ((ifp->if_capenable & IFCAP_RXCSUM) &&
2280             0 == mxge_rx_csum(m, csum)) {
2281                 /* Tell the stack that the checksum is good */
2282                 m->m_pkthdr.csum_data = 0xffff;
2283                 m->m_pkthdr.csum_flags = CSUM_PSEUDO_HDR |
2284                     CSUM_DATA_VALID;
2285         }
2286 #if 0
2287         /* flowid only valid if RSS hashing is enabled */
2288         if (sc->num_slices > 1) {
2289                 m->m_pkthdr.flowid = (ss - sc->ss);
2290                 m->m_flags |= M_FLOWID;
2291         }
2292 #endif
2293         ifp->if_input(ifp, m);
2294 }
2295
2296 static inline void
2297 mxge_clean_rx_done(struct mxge_slice_state *ss)
2298 {
2299         mxge_rx_done_t *rx_done = &ss->rx_done;
2300         int limit = 0;
2301         uint16_t length;
2302         uint16_t checksum;
2303
2304         while (rx_done->entry[rx_done->idx].length != 0) {
2305                 length = ntohs(rx_done->entry[rx_done->idx].length);
2306                 rx_done->entry[rx_done->idx].length = 0;
2307                 checksum = rx_done->entry[rx_done->idx].checksum;
2308                 if (length <= (MHLEN - MXGEFW_PAD))
2309                         mxge_rx_done_small(ss, length, checksum);
2310                 else
2311                         mxge_rx_done_big(ss, length, checksum);
2312                 rx_done->cnt++;
2313                 rx_done->idx = rx_done->cnt & rx_done->mask;
2314
2315                 /* limit potential for livelock */
2316                 if (__predict_false(++limit > rx_done->mask / 2))
2317                         break;
2318         }
2319 }
2320
2321 static inline void
2322 mxge_tx_done(struct mxge_slice_state *ss, uint32_t mcp_idx)
2323 {
2324         struct ifnet *ifp;
2325         mxge_tx_ring_t *tx;
2326         struct mbuf *m;
2327         bus_dmamap_t map;
2328         int idx;
2329
2330         tx = &ss->tx;
2331         ifp = ss->sc->ifp;
2332         ASSERT_SERIALIZED(ifp->if_serializer);
2333         while (tx->pkt_done != mcp_idx) {
2334                 idx = tx->done & tx->mask;
2335                 tx->done++;
2336                 m = tx->info[idx].m;
2337                 /* mbuf and DMA map only attached to the first
2338                    segment per-mbuf */
2339                 if (m != NULL) {
2340                         ss->obytes += m->m_pkthdr.len;
2341                         if (m->m_flags & M_MCAST)
2342                                 ss->omcasts++;
2343                         ss->opackets++;
2344                         tx->info[idx].m = NULL;
2345                         map = tx->info[idx].map;
2346                         bus_dmamap_unload(tx->dmat, map);
2347                         m_freem(m);
2348                 }
2349                 if (tx->info[idx].flag) {
2350                         tx->info[idx].flag = 0;
2351                         tx->pkt_done++;
2352                 }
2353         }
2354         
2355         /* If we have space, clear OACTIVE to tell the stack that
2356            its OK to send packets */
2357         if (tx->req - tx->done < (tx->mask + 1)/4)
2358                 ifq_clr_oactive(&ifp->if_snd);
2359
2360         if (!ifq_is_empty(&ifp->if_snd))
2361                 if_devstart(ifp);
2362
2363 #ifdef IFNET_BUF_RING
2364         if ((ss->sc->num_slices > 1) && (tx->req == tx->done)) {
2365                 /* let the NIC stop polling this queue, since there
2366                  * are no more transmits pending */
2367                 if (tx->req == tx->done) {
2368                         *tx->send_stop = 1;
2369                         tx->queue_active = 0;
2370                         tx->deactivate++;
2371                         wmb();
2372                 }
2373         }
2374 #endif
2375 }
2376
2377 static struct mxge_media_type mxge_xfp_media_types[] = {
2378         {IFM_10G_CX4,   0x7f,           "10GBASE-CX4 (module)"},
2379         {IFM_10G_SR,    (1 << 7),       "10GBASE-SR"},
2380         {IFM_10G_LR,    (1 << 6),       "10GBASE-LR"},
2381         {0,             (1 << 5),       "10GBASE-ER"},
2382         {IFM_10G_LRM,   (1 << 4),       "10GBASE-LRM"},
2383         {0,             (1 << 3),       "10GBASE-SW"},
2384         {0,             (1 << 2),       "10GBASE-LW"},
2385         {0,             (1 << 1),       "10GBASE-EW"},
2386         {0,             (1 << 0),       "Reserved"}
2387 };
2388
2389 static struct mxge_media_type mxge_sfp_media_types[] = {
2390         {IFM_10G_TWINAX,      0,        "10GBASE-Twinax"},
2391         {0,             (1 << 7),       "Reserved"},
2392         {IFM_10G_LRM,   (1 << 6),       "10GBASE-LRM"},
2393         {IFM_10G_LR,    (1 << 5),       "10GBASE-LR"},
2394         {IFM_10G_SR,    (1 << 4),       "10GBASE-SR"},
2395         {IFM_10G_TWINAX,(1 << 0),       "10GBASE-Twinax"}
2396 };
2397
2398 static void
2399 mxge_media_set(mxge_softc_t *sc, int media_type)
2400 {
2401         ifmedia_add(&sc->media, IFM_ETHER | IFM_FDX | media_type, 0, NULL);
2402         ifmedia_set(&sc->media, IFM_ETHER | IFM_FDX | media_type);
2403         sc->current_media = media_type;
2404         sc->media.ifm_media = sc->media.ifm_cur->ifm_media;
2405 }
2406
2407 static void
2408 mxge_media_init(mxge_softc_t *sc)
2409 {
2410         char *ptr;
2411         int i;
2412
2413         ifmedia_removeall(&sc->media);
2414         mxge_media_set(sc, IFM_AUTO);
2415
2416         /* 
2417          * parse the product code to deterimine the interface type
2418          * (CX4, XFP, Quad Ribbon Fiber) by looking at the character
2419          * after the 3rd dash in the driver's cached copy of the
2420          * EEPROM's product code string.
2421          */
2422         ptr = sc->product_code_string;
2423         if (ptr == NULL) {
2424                 device_printf(sc->dev, "Missing product code\n");
2425                 return;
2426         }
2427
2428         for (i = 0; i < 3; i++, ptr++) {
2429                 ptr = strchr(ptr, '-');
2430                 if (ptr == NULL) {
2431                         device_printf(sc->dev, "only %d dashes in PC?!?\n", i);
2432                         return;
2433                 }
2434         }
2435         if (*ptr == 'C' || *(ptr +1) == 'C') {
2436                 /* -C is CX4 */
2437                 sc->connector = MXGE_CX4;
2438                 mxge_media_set(sc, IFM_10G_CX4);
2439         } else if (*ptr == 'Q') {
2440                 /* -Q is Quad Ribbon Fiber */
2441                 sc->connector = MXGE_QRF;
2442                 device_printf(sc->dev, "Quad Ribbon Fiber Media\n");
2443                 /* FreeBSD has no media type for Quad ribbon fiber */
2444         } else if (*ptr == 'R') {
2445                 /* -R is XFP */
2446                 sc->connector = MXGE_XFP;
2447         } else if (*ptr == 'S' || *(ptr +1) == 'S') {
2448                 /* -S or -2S is SFP+ */
2449                 sc->connector = MXGE_SFP;
2450         } else {
2451                 device_printf(sc->dev, "Unknown media type: %c\n", *ptr);
2452         }
2453 }
2454
2455 /*
2456  * Determine the media type for a NIC.  Some XFPs will identify
2457  * themselves only when their link is up, so this is initiated via a
2458  * link up interrupt.  However, this can potentially take up to
2459  * several milliseconds, so it is run via the watchdog routine, rather
2460  * than in the interrupt handler itself. 
2461  */
2462 static void
2463 mxge_media_probe(mxge_softc_t *sc)
2464 {
2465         mxge_cmd_t cmd;
2466         const char *cage_type;
2467         struct mxge_media_type *mxge_media_types = NULL;
2468         int i, err, ms, mxge_media_type_entries;
2469         uint32_t byte;
2470
2471         sc->need_media_probe = 0;
2472
2473         if (sc->connector == MXGE_XFP) {
2474                 /* -R is XFP */
2475                 mxge_media_types = mxge_xfp_media_types;
2476                 mxge_media_type_entries = sizeof(mxge_xfp_media_types) /
2477                     sizeof(mxge_xfp_media_types[0]);
2478                 byte = MXGE_XFP_COMPLIANCE_BYTE;
2479                 cage_type = "XFP";
2480         } else  if (sc->connector == MXGE_SFP) {
2481                 /* -S or -2S is SFP+ */
2482                 mxge_media_types = mxge_sfp_media_types;
2483                 mxge_media_type_entries = sizeof(mxge_sfp_media_types) /
2484                     sizeof(mxge_sfp_media_types[0]);
2485                 cage_type = "SFP+";
2486                 byte = 3;
2487         } else {
2488                 /* nothing to do; media type cannot change */
2489                 return;
2490         }
2491
2492         /*
2493          * At this point we know the NIC has an XFP cage, so now we
2494          * try to determine what is in the cage by using the
2495          * firmware's XFP I2C commands to read the XFP 10GbE compilance
2496          * register.  We read just one byte, which may take over
2497          * a millisecond
2498          */
2499
2500         cmd.data0 = 0;   /* just fetch 1 byte, not all 256 */
2501         cmd.data1 = byte;
2502         err = mxge_send_cmd(sc, MXGEFW_CMD_I2C_READ, &cmd);
2503         if (err == MXGEFW_CMD_ERROR_I2C_FAILURE)
2504                 device_printf(sc->dev, "failed to read XFP\n");
2505         if (err == MXGEFW_CMD_ERROR_I2C_ABSENT)
2506                 device_printf(sc->dev, "Type R/S with no XFP!?!?\n");
2507         if (err != MXGEFW_CMD_OK)
2508                 return;
2509
2510         /* Now we wait for the data to be cached */
2511         cmd.data0 = byte;
2512         err = mxge_send_cmd(sc, MXGEFW_CMD_I2C_BYTE, &cmd);
2513         for (ms = 0; err == EBUSY && ms < 50; ms++) {
2514                 DELAY(1000);
2515                 cmd.data0 = byte;
2516                 err = mxge_send_cmd(sc, MXGEFW_CMD_I2C_BYTE, &cmd);
2517         }
2518         if (err != MXGEFW_CMD_OK) {
2519                 device_printf(sc->dev, "failed to read %s (%d, %dms)\n",
2520                     cage_type, err, ms);
2521                 return;
2522         }
2523
2524         if (cmd.data0 == mxge_media_types[0].bitmask) {
2525                 if (bootverbose) {
2526                         device_printf(sc->dev, "%s:%s\n", cage_type,
2527                             mxge_media_types[0].name);
2528                 }
2529                 if (sc->current_media != mxge_media_types[0].flag) {
2530                         mxge_media_init(sc);
2531                         mxge_media_set(sc, mxge_media_types[0].flag);
2532                 }
2533                 return;
2534         }
2535         for (i = 1; i < mxge_media_type_entries; i++) {
2536                 if (cmd.data0 & mxge_media_types[i].bitmask) {
2537                         if (bootverbose) {
2538                                 device_printf(sc->dev, "%s:%s\n", cage_type,
2539                                     mxge_media_types[i].name);
2540                         }
2541
2542                         if (sc->current_media != mxge_media_types[i].flag) {
2543                                 mxge_media_init(sc);
2544                                 mxge_media_set(sc, mxge_media_types[i].flag);
2545                         }
2546                         return;
2547                 }
2548         }
2549         if (bootverbose) {
2550                 device_printf(sc->dev, "%s media 0x%x unknown\n", cage_type,
2551                     cmd.data0);
2552         }
2553 }
2554
2555 static void
2556 mxge_intr(void *arg)
2557 {
2558         struct mxge_slice_state *ss = arg;
2559         mxge_softc_t *sc = ss->sc;
2560         mcp_irq_data_t *stats = ss->fw_stats;
2561         mxge_tx_ring_t *tx = &ss->tx;
2562         mxge_rx_done_t *rx_done = &ss->rx_done;
2563         uint32_t send_done_count;
2564         uint8_t valid;
2565
2566
2567 #ifndef IFNET_BUF_RING
2568         /* an interrupt on a non-zero slice is implicitly valid
2569            since MSI-X irqs are not shared */
2570         if (ss != sc->ss) {
2571                 mxge_clean_rx_done(ss);
2572                 *ss->irq_claim = be32toh(3);
2573                 return;
2574         }
2575 #endif
2576
2577         /* make sure the DMA has finished */
2578         if (!stats->valid) {
2579                 return;
2580         }
2581         valid = stats->valid;
2582
2583         if (sc->irq_type == PCI_INTR_TYPE_LEGACY) {
2584                 /* lower legacy IRQ  */
2585                 *sc->irq_deassert = 0;
2586                 if (!mxge_deassert_wait)
2587                         /* don't wait for conf. that irq is low */
2588                         stats->valid = 0;
2589         } else {
2590                 stats->valid = 0;
2591         }
2592
2593         /* loop while waiting for legacy irq deassertion */
2594         do {
2595                 /* check for transmit completes and receives */
2596                 send_done_count = be32toh(stats->send_done_count);
2597                 while ((send_done_count != tx->pkt_done) ||
2598                        (rx_done->entry[rx_done->idx].length != 0)) {
2599                         if (send_done_count != tx->pkt_done)
2600                                 mxge_tx_done(ss, (int)send_done_count);
2601                         mxge_clean_rx_done(ss);
2602                         send_done_count = be32toh(stats->send_done_count);
2603                 }
2604                 if (sc->irq_type == PCI_INTR_TYPE_LEGACY && mxge_deassert_wait)
2605                         wmb();
2606         } while (*((volatile uint8_t *) &stats->valid));
2607
2608         /* fw link & error stats meaningful only on the first slice */
2609         if (__predict_false((ss == sc->ss) && stats->stats_updated)) {
2610                 if (sc->link_state != stats->link_up) {
2611                         sc->link_state = stats->link_up;
2612                         if (sc->link_state) {
2613                                 sc->ifp->if_link_state = LINK_STATE_UP;
2614                                 if_link_state_change(sc->ifp);
2615                                 if (bootverbose)
2616                                         device_printf(sc->dev, "link up\n");
2617                         } else {
2618                                 sc->ifp->if_link_state = LINK_STATE_DOWN;
2619                                 if_link_state_change(sc->ifp);
2620                                 if (bootverbose)
2621                                         device_printf(sc->dev, "link down\n");
2622                         }
2623                         sc->need_media_probe = 1;
2624                 }
2625                 if (sc->rdma_tags_available !=
2626                     be32toh(stats->rdma_tags_available)) {
2627                         sc->rdma_tags_available = 
2628                                 be32toh(stats->rdma_tags_available);
2629                         device_printf(sc->dev, "RDMA timed out! %d tags "
2630                                       "left\n", sc->rdma_tags_available);
2631                 }
2632
2633                 if (stats->link_down) {
2634                         sc->down_cnt += stats->link_down;
2635                         sc->link_state = 0;
2636                         sc->ifp->if_link_state = LINK_STATE_DOWN;
2637                         if_link_state_change(sc->ifp);
2638                 }
2639         }
2640
2641         /* check to see if we have rx token to pass back */
2642         if (valid & 0x1)
2643             *ss->irq_claim = be32toh(3);
2644         *(ss->irq_claim + 1) = be32toh(3);
2645 }
2646
2647 static void
2648 mxge_init(void *arg)
2649 {
2650         struct mxge_softc *sc = arg;
2651
2652         ASSERT_SERIALIZED(sc->ifp->if_serializer);
2653         if ((sc->ifp->if_flags & IFF_RUNNING) == 0)
2654                 mxge_open(sc);
2655 }
2656
2657 static void
2658 mxge_free_slice_mbufs(struct mxge_slice_state *ss)
2659 {
2660         int i;
2661
2662         for (i = 0; i <= ss->rx_big.mask; i++) {
2663                 if (ss->rx_big.info[i].m == NULL)
2664                         continue;
2665                 bus_dmamap_unload(ss->rx_big.dmat,
2666                                   ss->rx_big.info[i].map);
2667                 m_freem(ss->rx_big.info[i].m);
2668                 ss->rx_big.info[i].m = NULL;
2669         }
2670
2671         for (i = 0; i <= ss->rx_small.mask; i++) {
2672                 if (ss->rx_small.info[i].m == NULL)
2673                         continue;
2674                 bus_dmamap_unload(ss->rx_small.dmat,
2675                                   ss->rx_small.info[i].map);
2676                 m_freem(ss->rx_small.info[i].m);
2677                 ss->rx_small.info[i].m = NULL;
2678         }
2679
2680         /* transmit ring used only on the first slice */
2681         if (ss->tx.info == NULL)
2682                 return;
2683
2684         for (i = 0; i <= ss->tx.mask; i++) {
2685                 ss->tx.info[i].flag = 0;
2686                 if (ss->tx.info[i].m == NULL)
2687                         continue;
2688                 bus_dmamap_unload(ss->tx.dmat,
2689                                   ss->tx.info[i].map);
2690                 m_freem(ss->tx.info[i].m);
2691                 ss->tx.info[i].m = NULL;
2692         }
2693 }
2694
2695 static void
2696 mxge_free_mbufs(mxge_softc_t *sc)
2697 {
2698         int slice;
2699
2700         for (slice = 0; slice < sc->num_slices; slice++)
2701                 mxge_free_slice_mbufs(&sc->ss[slice]);
2702 }
2703
2704 static void
2705 mxge_free_slice_rings(struct mxge_slice_state *ss)
2706 {
2707         int i;
2708
2709         if (ss->rx_done.entry != NULL)
2710                 mxge_dma_free(&ss->rx_done.dma);
2711         ss->rx_done.entry = NULL;
2712
2713         if (ss->tx.req_bytes != NULL)
2714                 kfree(ss->tx.req_bytes, M_DEVBUF);
2715         ss->tx.req_bytes = NULL;
2716
2717         if (ss->tx.seg_list != NULL)
2718                 kfree(ss->tx.seg_list, M_DEVBUF);
2719         ss->tx.seg_list = NULL;
2720
2721         if (ss->rx_small.shadow != NULL)
2722                 kfree(ss->rx_small.shadow, M_DEVBUF);
2723         ss->rx_small.shadow = NULL;
2724
2725         if (ss->rx_big.shadow != NULL)
2726                 kfree(ss->rx_big.shadow, M_DEVBUF);
2727         ss->rx_big.shadow = NULL;
2728
2729         if (ss->tx.info != NULL) {
2730                 if (ss->tx.dmat != NULL) {
2731                         for (i = 0; i <= ss->tx.mask; i++) {
2732                                 bus_dmamap_destroy(ss->tx.dmat,
2733                                     ss->tx.info[i].map);
2734                         }
2735                         bus_dma_tag_destroy(ss->tx.dmat);
2736                 }
2737                 kfree(ss->tx.info, M_DEVBUF);
2738         }
2739         ss->tx.info = NULL;
2740
2741         if (ss->rx_small.info != NULL) {
2742                 if (ss->rx_small.dmat != NULL) {
2743                         for (i = 0; i <= ss->rx_small.mask; i++) {
2744                                 bus_dmamap_destroy(ss->rx_small.dmat,
2745                                     ss->rx_small.info[i].map);
2746                         }
2747                         bus_dmamap_destroy(ss->rx_small.dmat,
2748                             ss->rx_small.extra_map);
2749                         bus_dma_tag_destroy(ss->rx_small.dmat);
2750                 }
2751                 kfree(ss->rx_small.info, M_DEVBUF);
2752         }
2753         ss->rx_small.info = NULL;
2754
2755         if (ss->rx_big.info != NULL) {
2756                 if (ss->rx_big.dmat != NULL) {
2757                         for (i = 0; i <= ss->rx_big.mask; i++) {
2758                                 bus_dmamap_destroy(ss->rx_big.dmat,
2759                                     ss->rx_big.info[i].map);
2760                         }
2761                         bus_dmamap_destroy(ss->rx_big.dmat,
2762                             ss->rx_big.extra_map);
2763                         bus_dma_tag_destroy(ss->rx_big.dmat);
2764                 }
2765                 kfree(ss->rx_big.info, M_DEVBUF);
2766         }
2767         ss->rx_big.info = NULL;
2768 }
2769
2770 static void
2771 mxge_free_rings(mxge_softc_t *sc)
2772 {
2773         int slice;
2774
2775         for (slice = 0; slice < sc->num_slices; slice++)
2776                 mxge_free_slice_rings(&sc->ss[slice]);
2777 }
2778
2779 static int
2780 mxge_alloc_slice_rings(struct mxge_slice_state *ss, int rx_ring_entries,
2781     int tx_ring_entries)
2782 {
2783         mxge_softc_t *sc = ss->sc;
2784         size_t bytes;
2785         int err, i;
2786
2787         /*
2788          * Allocate per-slice receive resources
2789          */
2790
2791         ss->rx_small.mask = ss->rx_big.mask = rx_ring_entries - 1;
2792         ss->rx_done.mask = (2 * rx_ring_entries) - 1;
2793
2794         /* Allocate the rx shadow rings */
2795         bytes = rx_ring_entries * sizeof(*ss->rx_small.shadow);
2796         ss->rx_small.shadow = kmalloc(bytes, M_DEVBUF, M_ZERO|M_WAITOK);
2797
2798         bytes = rx_ring_entries * sizeof(*ss->rx_big.shadow);
2799         ss->rx_big.shadow = kmalloc(bytes, M_DEVBUF, M_ZERO|M_WAITOK);
2800
2801         /* Allocate the rx host info rings */
2802         bytes = rx_ring_entries * sizeof(*ss->rx_small.info);
2803         ss->rx_small.info = kmalloc(bytes, M_DEVBUF, M_ZERO|M_WAITOK);
2804
2805         bytes = rx_ring_entries * sizeof(*ss->rx_big.info);
2806         ss->rx_big.info = kmalloc(bytes, M_DEVBUF, M_ZERO|M_WAITOK);
2807
2808         /* Allocate the rx busdma resources */
2809         err = bus_dma_tag_create(sc->parent_dmat,       /* parent */
2810                                  1,                     /* alignment */
2811                                  4096,                  /* boundary */
2812                                  BUS_SPACE_MAXADDR,     /* low */
2813                                  BUS_SPACE_MAXADDR,     /* high */
2814                                  NULL, NULL,            /* filter */
2815                                  MHLEN,                 /* maxsize */
2816                                  1,                     /* num segs */
2817                                  MHLEN,                 /* maxsegsize */
2818                                  BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW,
2819                                                         /* flags */
2820                                  &ss->rx_small.dmat);   /* tag */
2821         if (err != 0) {
2822                 device_printf(sc->dev, "Err %d allocating rx_small dmat\n",
2823                     err);
2824                 return err;
2825         }
2826
2827         err = bus_dma_tag_create(sc->parent_dmat,       /* parent */
2828                                  1,                     /* alignment */
2829                                  4096,                  /* boundary */
2830                                  BUS_SPACE_MAXADDR,     /* low */
2831                                  BUS_SPACE_MAXADDR,     /* high */
2832                                  NULL, NULL,            /* filter */
2833                                  3*4096,                /* maxsize */
2834                                  3,                     /* num segs */
2835                                  4096,                  /* maxsegsize*/
2836                                  BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW,
2837                                                         /* flags */
2838                                  &ss->rx_big.dmat);     /* tag */
2839         if (err != 0) {
2840                 device_printf(sc->dev, "Err %d allocating rx_big dmat\n",
2841                     err);
2842                 return err;
2843         }
2844
2845         for (i = 0; i <= ss->rx_small.mask; i++) {
2846                 err = bus_dmamap_create(ss->rx_small.dmat, BUS_DMA_WAITOK,
2847                     &ss->rx_small.info[i].map);
2848                 if (err != 0) {
2849                         device_printf(sc->dev, "Err %d rx_small dmamap\n", err);
2850                         return err;
2851                 }
2852         }
2853         err = bus_dmamap_create(ss->rx_small.dmat, BUS_DMA_WAITOK,
2854             &ss->rx_small.extra_map);
2855         if (err != 0) {
2856                 device_printf(sc->dev, "Err %d extra rx_small dmamap\n", err);
2857                 return err;
2858         }
2859
2860         for (i = 0; i <= ss->rx_big.mask; i++) {
2861                 err = bus_dmamap_create(ss->rx_big.dmat, BUS_DMA_WAITOK,
2862                     &ss->rx_big.info[i].map);
2863                 if (err != 0) {
2864                         device_printf(sc->dev, "Err %d rx_big dmamap\n", err);
2865                         return err;
2866                 }
2867         }
2868         err = bus_dmamap_create(ss->rx_big.dmat, BUS_DMA_WAITOK,
2869             &ss->rx_big.extra_map);
2870         if (err != 0) {
2871                 device_printf(sc->dev, "Err %d extra rx_big dmamap\n", err);
2872                 return err;
2873         }
2874
2875         /*
2876          * Now allocate TX resources
2877          */
2878
2879 #ifndef IFNET_BUF_RING
2880         /* only use a single TX ring for now */
2881         if (ss != ss->sc->ss)
2882                 return 0;
2883 #endif
2884
2885         ss->tx.mask = tx_ring_entries - 1;
2886         ss->tx.max_desc = MIN(MXGE_MAX_SEND_DESC, tx_ring_entries / 4);
2887
2888         /* Allocate the tx request copy block XXX */
2889         bytes = 8 + sizeof(*ss->tx.req_list) * (ss->tx.max_desc + 4);
2890         ss->tx.req_bytes = kmalloc(bytes, M_DEVBUF, M_WAITOK);
2891         /* Ensure req_list entries are aligned to 8 bytes */
2892         ss->tx.req_list = (mcp_kreq_ether_send_t *)
2893             ((unsigned long)(ss->tx.req_bytes + 7) & ~7UL);
2894
2895         /* Allocate the tx busdma segment list */
2896         bytes = sizeof(*ss->tx.seg_list) * ss->tx.max_desc;
2897         ss->tx.seg_list = kmalloc(bytes, M_DEVBUF, M_WAITOK);
2898
2899         /* Allocate the tx host info ring */
2900         bytes = tx_ring_entries * sizeof(*ss->tx.info);
2901         ss->tx.info = kmalloc(bytes, M_DEVBUF, M_ZERO|M_WAITOK);
2902         
2903         /* Allocate the tx busdma resources */
2904         err = bus_dma_tag_create(sc->parent_dmat,       /* parent */
2905                                  1,                     /* alignment */
2906                                  sc->tx_boundary,       /* boundary */
2907                                  BUS_SPACE_MAXADDR,     /* low */
2908                                  BUS_SPACE_MAXADDR,     /* high */
2909                                  NULL, NULL,            /* filter */
2910                                  IP_MAXPACKET +
2911                                  sizeof(struct ether_vlan_header),
2912                                                         /* maxsize */
2913                                  ss->tx.max_desc - 2,   /* num segs */
2914                                  sc->tx_boundary,       /* maxsegsz */
2915                                  BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW |
2916                                  BUS_DMA_ONEBPAGE,      /* flags */
2917                                  &ss->tx.dmat);         /* tag */
2918         if (err != 0) {
2919                 device_printf(sc->dev, "Err %d allocating tx dmat\n", err);
2920                 return err;
2921         }
2922
2923         /*
2924          * Now use these tags to setup DMA maps for each slot in the ring
2925          */
2926         for (i = 0; i <= ss->tx.mask; i++) {
2927                 err = bus_dmamap_create(ss->tx.dmat,
2928                     BUS_DMA_WAITOK | BUS_DMA_ONEBPAGE, &ss->tx.info[i].map);
2929                 if (err != 0) {
2930                         device_printf(sc->dev, "Err %d tx dmamap\n", err);
2931                         return err;
2932                 }
2933         }
2934         return 0;
2935 }
2936
2937 static int
2938 mxge_alloc_rings(mxge_softc_t *sc)
2939 {
2940         mxge_cmd_t cmd;
2941         int tx_ring_size;
2942         int tx_ring_entries, rx_ring_entries;
2943         int err, slice;
2944
2945         /* Get ring sizes */
2946         err = mxge_send_cmd(sc, MXGEFW_CMD_GET_SEND_RING_SIZE, &cmd);
2947         if (err != 0) {
2948                 device_printf(sc->dev, "Cannot determine tx ring sizes\n");
2949                 goto abort;
2950         }
2951         tx_ring_size = cmd.data0;
2952
2953         tx_ring_entries = tx_ring_size / sizeof(mcp_kreq_ether_send_t);
2954         rx_ring_entries = sc->rx_ring_size / sizeof(mcp_dma_addr_t);
2955         ifq_set_maxlen(&sc->ifp->if_snd, tx_ring_entries - 1);
2956         ifq_set_ready(&sc->ifp->if_snd);
2957
2958         for (slice = 0; slice < sc->num_slices; slice++) {
2959                 err = mxge_alloc_slice_rings(&sc->ss[slice],
2960                     rx_ring_entries, tx_ring_entries);
2961                 if (err != 0)
2962                         goto abort;
2963         }
2964         return 0;
2965
2966 abort:
2967         mxge_free_rings(sc);
2968         return err;
2969
2970 }
2971
2972 static void
2973 mxge_choose_params(int mtu, int *big_buf_size, int *cl_size, int *nbufs)
2974 {
2975         int bufsize = mtu + ETHER_HDR_LEN + EVL_ENCAPLEN + MXGEFW_PAD;
2976
2977         if (bufsize < MCLBYTES) {
2978                 /* easy, everything fits in a single buffer */
2979                 *big_buf_size = MCLBYTES;
2980                 *cl_size = MCLBYTES;
2981                 *nbufs = 1;
2982                 return;
2983         }
2984
2985         if (bufsize < MJUMPAGESIZE) {
2986                 /* still easy, everything still fits in a single buffer */
2987                 *big_buf_size = MJUMPAGESIZE;
2988                 *cl_size = MJUMPAGESIZE;
2989                 *nbufs = 1;
2990                 return;
2991         }
2992 #if MXGE_VIRT_JUMBOS
2993         /* now we need to use virtually contiguous buffers */
2994         *cl_size = MJUM9BYTES;
2995         *big_buf_size = 4096;
2996         *nbufs = mtu / 4096 + 1;
2997         /* needs to be a power of two, so round up */
2998         if (*nbufs == 3)
2999                 *nbufs = 4;
3000 #else
3001         *cl_size = MJUM9BYTES;
3002         *big_buf_size = MJUM9BYTES;
3003         *nbufs = 1;
3004 #endif
3005 }
3006
3007 static int
3008 mxge_slice_open(struct mxge_slice_state *ss, int nbufs, int cl_size)
3009 {
3010         mxge_softc_t *sc;
3011         mxge_cmd_t cmd;
3012         bus_dmamap_t map;
3013         int err, i, slice;
3014
3015         sc = ss->sc;
3016         slice = ss - sc->ss;
3017
3018         /* get the lanai pointers to the send and receive rings */
3019
3020         err = 0;
3021 #ifndef IFNET_BUF_RING
3022         /* We currently only send from the first slice */
3023         if (slice == 0) {
3024 #endif
3025                 cmd.data0 = slice;
3026                 err = mxge_send_cmd(sc, MXGEFW_CMD_GET_SEND_OFFSET, &cmd);
3027                 ss->tx.lanai = 
3028                         (volatile mcp_kreq_ether_send_t *)(sc->sram + cmd.data0);
3029                 ss->tx.send_go = (volatile uint32_t *)
3030                         (sc->sram + MXGEFW_ETH_SEND_GO + 64 * slice);
3031                 ss->tx.send_stop = (volatile uint32_t *)
3032                 (sc->sram + MXGEFW_ETH_SEND_STOP + 64 * slice);
3033 #ifndef IFNET_BUF_RING
3034         }
3035 #endif
3036         cmd.data0 = slice;
3037         err |= mxge_send_cmd(sc, 
3038                              MXGEFW_CMD_GET_SMALL_RX_OFFSET, &cmd);
3039         ss->rx_small.lanai = 
3040                 (volatile mcp_kreq_ether_recv_t *)(sc->sram + cmd.data0);
3041         cmd.data0 = slice;
3042         err |= mxge_send_cmd(sc, MXGEFW_CMD_GET_BIG_RX_OFFSET, &cmd);
3043         ss->rx_big.lanai = 
3044                 (volatile mcp_kreq_ether_recv_t *)(sc->sram + cmd.data0);
3045
3046         if (err != 0) {
3047                 device_printf(sc->dev, 
3048                               "failed to get ring sizes or locations\n");
3049                 return EIO;
3050         }
3051
3052         /* stock receive rings */
3053         for (i = 0; i <= ss->rx_small.mask; i++) {
3054                 map = ss->rx_small.info[i].map;
3055                 err = mxge_get_buf_small(ss, map, i);
3056                 if (err) {
3057                         device_printf(sc->dev, "alloced %d/%d smalls\n",
3058                                       i, ss->rx_small.mask + 1);
3059                         return ENOMEM;
3060                 }
3061         }
3062         for (i = 0; i <= ss->rx_big.mask; i++) {
3063                 ss->rx_big.shadow[i].addr_low = 0xffffffff;
3064                 ss->rx_big.shadow[i].addr_high = 0xffffffff;
3065         }
3066         ss->rx_big.nbufs = nbufs;
3067         ss->rx_big.cl_size = cl_size;
3068         ss->rx_big.mlen = ss->sc->ifp->if_mtu + ETHER_HDR_LEN +
3069                 EVL_ENCAPLEN + MXGEFW_PAD;
3070         for (i = 0; i <= ss->rx_big.mask; i += ss->rx_big.nbufs) {
3071                 map = ss->rx_big.info[i].map;
3072                 err = mxge_get_buf_big(ss, map, i);
3073                 if (err) {
3074                         device_printf(sc->dev, "alloced %d/%d bigs\n",
3075                                       i, ss->rx_big.mask + 1);
3076                         return ENOMEM;
3077                 }
3078         }
3079         return 0;
3080 }
3081
3082 static int 
3083 mxge_open(mxge_softc_t *sc)
3084 {
3085         mxge_cmd_t cmd;
3086         int err, big_bytes, nbufs, slice, cl_size, i;
3087         bus_addr_t bus;
3088         volatile uint8_t *itable;
3089         struct mxge_slice_state *ss;
3090
3091         ASSERT_SERIALIZED(sc->ifp->if_serializer);
3092         /* Copy the MAC address in case it was overridden */
3093         bcopy(IF_LLADDR(sc->ifp), sc->mac_addr, ETHER_ADDR_LEN);
3094
3095         err = mxge_reset(sc, 1);
3096         if (err != 0) {
3097                 device_printf(sc->dev, "failed to reset\n");
3098                 return EIO;
3099         }
3100
3101         if (sc->num_slices > 1) {
3102                 /* setup the indirection table */
3103                 cmd.data0 = sc->num_slices;
3104                 err = mxge_send_cmd(sc, MXGEFW_CMD_SET_RSS_TABLE_SIZE,
3105                                     &cmd);
3106
3107                 err |= mxge_send_cmd(sc, MXGEFW_CMD_GET_RSS_TABLE_OFFSET,
3108                                      &cmd);
3109                 if (err != 0) {
3110                         device_printf(sc->dev,
3111                                       "failed to setup rss tables\n");
3112                         return err;
3113                 }
3114
3115                 /* just enable an identity mapping */
3116                 itable = sc->sram + cmd.data0;
3117                 for (i = 0; i < sc->num_slices; i++)
3118                         itable[i] = (uint8_t)i;
3119
3120                 cmd.data0 = 1;
3121                 cmd.data1 = mxge_rss_hash_type;
3122                 err = mxge_send_cmd(sc, MXGEFW_CMD_SET_RSS_ENABLE, &cmd);
3123                 if (err != 0) {
3124                         device_printf(sc->dev, "failed to enable slices\n");
3125                         return err;
3126                 }
3127         }
3128
3129         cmd.data0 = MXGEFW_TSO_MODE_NDIS;
3130         err = mxge_send_cmd(sc, MXGEFW_CMD_SET_TSO_MODE, &cmd);
3131         if (err) {
3132                 device_printf(sc->dev, "failed set TSO mode\n");
3133                 sc->ifp->if_capenable &= ~IFCAP_TSO;
3134                 sc->ifp->if_capabilities &= ~IFCAP_TSO;
3135                 sc->ifp->if_hwassist &= ~CSUM_TSO;
3136         }
3137
3138         mxge_choose_params(sc->ifp->if_mtu, &big_bytes, &cl_size, &nbufs);
3139
3140         cmd.data0 = nbufs;
3141         err = mxge_send_cmd(sc, MXGEFW_CMD_ALWAYS_USE_N_BIG_BUFFERS,
3142                             &cmd);
3143         /* error is only meaningful if we're trying to set 
3144            MXGEFW_CMD_ALWAYS_USE_N_BIG_BUFFERS > 1 */
3145         if (err && nbufs > 1) {
3146                 device_printf(sc->dev,
3147                               "Failed to set alway-use-n to %d\n",
3148                               nbufs);
3149                 return EIO;
3150         }
3151         /* Give the firmware the mtu and the big and small buffer
3152            sizes.  The firmware wants the big buf size to be a power
3153            of two. Luckily, FreeBSD's clusters are powers of two */
3154         cmd.data0 = sc->ifp->if_mtu + ETHER_HDR_LEN + EVL_ENCAPLEN;
3155         err = mxge_send_cmd(sc, MXGEFW_CMD_SET_MTU, &cmd);
3156         cmd.data0 = MHLEN - MXGEFW_PAD;
3157         err |= mxge_send_cmd(sc, MXGEFW_CMD_SET_SMALL_BUFFER_SIZE,
3158                              &cmd);
3159         cmd.data0 = big_bytes;
3160         err |= mxge_send_cmd(sc, MXGEFW_CMD_SET_BIG_BUFFER_SIZE, &cmd);
3161
3162         if (err != 0) {
3163                 device_printf(sc->dev, "failed to setup params\n");
3164                 goto abort;
3165         }
3166
3167         /* Now give him the pointer to the stats block */
3168         for (slice = 0; 
3169 #ifdef IFNET_BUF_RING
3170              slice < sc->num_slices;
3171 #else
3172              slice < 1;
3173 #endif
3174              slice++) {
3175                 ss = &sc->ss[slice];
3176                 cmd.data0 = MXGE_LOWPART_TO_U32(ss->fw_stats_dma.dmem_busaddr);
3177                 cmd.data1 = MXGE_HIGHPART_TO_U32(ss->fw_stats_dma.dmem_busaddr);
3178                 cmd.data2 = sizeof(struct mcp_irq_data);
3179                 cmd.data2 |= (slice << 16);
3180                 err |= mxge_send_cmd(sc, MXGEFW_CMD_SET_STATS_DMA_V2, &cmd);
3181         }
3182
3183         if (err != 0) {
3184                 bus = sc->ss->fw_stats_dma.dmem_busaddr;
3185                 bus += offsetof(struct mcp_irq_data, send_done_count);
3186                 cmd.data0 = MXGE_LOWPART_TO_U32(bus);
3187                 cmd.data1 = MXGE_HIGHPART_TO_U32(bus);
3188                 err = mxge_send_cmd(sc,
3189                                     MXGEFW_CMD_SET_STATS_DMA_OBSOLETE,
3190                                     &cmd);
3191                 /* Firmware cannot support multicast without STATS_DMA_V2 */
3192                 sc->fw_multicast_support = 0;
3193         } else {
3194                 sc->fw_multicast_support = 1;
3195         }
3196
3197         if (err != 0) {
3198                 device_printf(sc->dev, "failed to setup params\n");
3199                 goto abort;
3200         }
3201
3202         for (slice = 0; slice < sc->num_slices; slice++) {
3203                 err = mxge_slice_open(&sc->ss[slice], nbufs, cl_size);
3204                 if (err != 0) {
3205                         device_printf(sc->dev, "couldn't open slice %d\n",
3206                                       slice);
3207                         goto abort;
3208                 }
3209         }
3210
3211         /* Finally, start the firmware running */
3212         err = mxge_send_cmd(sc, MXGEFW_CMD_ETHERNET_UP, &cmd);
3213         if (err) {
3214                 device_printf(sc->dev, "Couldn't bring up link\n");
3215                 goto abort;
3216         }
3217         sc->ifp->if_flags |= IFF_RUNNING;
3218         ifq_clr_oactive(&sc->ifp->if_snd);
3219
3220         return 0;
3221
3222
3223 abort:
3224         mxge_free_mbufs(sc);
3225
3226         return err;
3227 }
3228
3229 static int
3230 mxge_close(mxge_softc_t *sc, int down)
3231 {
3232         mxge_cmd_t cmd;
3233         int err, old_down_cnt;
3234
3235         ASSERT_SERIALIZED(sc->ifp->if_serializer);
3236
3237         sc->ifp->if_flags &= ~IFF_RUNNING;
3238         if (!down) {
3239                 old_down_cnt = sc->down_cnt;
3240                 wmb();
3241                 err = mxge_send_cmd(sc, MXGEFW_CMD_ETHERNET_DOWN, &cmd);
3242                 if (err) {
3243                         device_printf(sc->dev,
3244                                       "Couldn't bring down link\n");
3245                 }
3246                 if (old_down_cnt == sc->down_cnt) {
3247                         /* wait for down irq */
3248                         lwkt_serialize_exit(sc->ifp->if_serializer);
3249                         DELAY(10 * sc->intr_coal_delay);
3250                         lwkt_serialize_enter(sc->ifp->if_serializer);
3251                 }
3252                 wmb();
3253                 if (old_down_cnt == sc->down_cnt) {
3254                         device_printf(sc->dev, "never got down irq\n");
3255                 }
3256         }
3257         mxge_free_mbufs(sc);
3258
3259         return 0;
3260 }
3261
3262 static void
3263 mxge_setup_cfg_space(mxge_softc_t *sc)
3264 {
3265         device_t dev = sc->dev;
3266         int reg;
3267         uint16_t lnk, pectl;
3268
3269         /* Find the PCIe link width and set max read request to 4KB */
3270         if (pci_find_extcap(dev, PCIY_EXPRESS, &reg) == 0) {
3271                 lnk = pci_read_config(dev, reg + 0x12, 2);
3272                 sc->link_width = (lnk >> 4) & 0x3f;
3273
3274                 if (sc->pectl == 0) {
3275                         pectl = pci_read_config(dev, reg + 0x8, 2);
3276                         pectl = (pectl & ~0x7000) | (5 << 12);
3277                         pci_write_config(dev, reg + 0x8, pectl, 2);
3278                         sc->pectl = pectl;
3279                 } else {
3280                         /* Restore saved pectl after watchdog reset */
3281                         pci_write_config(dev, reg + 0x8, sc->pectl, 2);
3282                 }
3283         }
3284
3285         /* Enable DMA and memory space access */
3286         pci_enable_busmaster(dev);
3287 }
3288
3289 static uint32_t
3290 mxge_read_reboot(mxge_softc_t *sc)
3291 {
3292         device_t dev = sc->dev;
3293         uint32_t vs;
3294
3295         /* find the vendor specific offset */
3296         if (pci_find_extcap(dev, PCIY_VENDOR, &vs) != 0) {
3297                 device_printf(sc->dev,
3298                               "could not find vendor specific offset\n");
3299                 return (uint32_t)-1;
3300         }
3301         /* enable read32 mode */
3302         pci_write_config(dev, vs + 0x10, 0x3, 1);
3303         /* tell NIC which register to read */
3304         pci_write_config(dev, vs + 0x18, 0xfffffff0, 4);
3305         return (pci_read_config(dev, vs + 0x14, 4));
3306 }
3307
3308 static void
3309 mxge_watchdog_reset(mxge_softc_t *sc)
3310 {
3311         struct pci_devinfo *dinfo;
3312         int err, running;
3313         uint32_t reboot;
3314         uint16_t cmd;
3315
3316         err = ENXIO;
3317
3318         device_printf(sc->dev, "Watchdog reset!\n");
3319
3320         /* 
3321          * check to see if the NIC rebooted.  If it did, then all of
3322          * PCI config space has been reset, and things like the
3323          * busmaster bit will be zero.  If this is the case, then we
3324          * must restore PCI config space before the NIC can be used
3325          * again
3326          */
3327         cmd = pci_read_config(sc->dev, PCIR_COMMAND, 2);
3328         if (cmd == 0xffff) {
3329                 /* 
3330                  * maybe the watchdog caught the NIC rebooting; wait
3331                  * up to 100ms for it to finish.  If it does not come
3332                  * back, then give up 
3333                  */
3334                 DELAY(1000*100);
3335                 cmd = pci_read_config(sc->dev, PCIR_COMMAND, 2);
3336                 if (cmd == 0xffff) {
3337                         device_printf(sc->dev, "NIC disappeared!\n");
3338                 }
3339         }
3340         if ((cmd & PCIM_CMD_BUSMASTEREN) == 0) {
3341                 /* print the reboot status */
3342                 reboot = mxge_read_reboot(sc);
3343                 device_printf(sc->dev, "NIC rebooted, status = 0x%x\n",
3344                               reboot);
3345                 running = sc->ifp->if_flags & IFF_RUNNING;
3346                 if (running) {
3347
3348                         /* 
3349                          * quiesce NIC so that TX routines will not try to
3350                          * xmit after restoration of BAR
3351                          */
3352
3353                         /* Mark the link as down */
3354                         if (sc->link_state) {
3355                                 sc->ifp->if_link_state = LINK_STATE_DOWN;
3356                                 if_link_state_change(sc->ifp);
3357                         }
3358                         mxge_close(sc, 1);
3359                 }
3360                 /* restore PCI configuration space */
3361                 dinfo = device_get_ivars(sc->dev);
3362                 pci_cfg_restore(sc->dev, dinfo);
3363
3364                 /* and redo any changes we made to our config space */
3365                 mxge_setup_cfg_space(sc);
3366
3367                 /* reload f/w */
3368                 err = mxge_load_firmware(sc, 0);
3369                 if (err) {
3370                         device_printf(sc->dev,
3371                                       "Unable to re-load f/w\n");
3372                 }
3373                 if (running) {
3374                         if (!err) {
3375                                 err = mxge_open(sc);
3376                                 if_devstart_sched(sc->ifp);
3377                         }
3378                 }
3379                 sc->watchdog_resets++;
3380         } else {
3381                 device_printf(sc->dev,
3382                               "NIC did not reboot, not resetting\n");
3383                 err = 0;
3384         }
3385         if (err) {
3386                 device_printf(sc->dev, "watchdog reset failed\n");
3387         } else {
3388                 if (sc->dying == 2)
3389                         sc->dying = 0;
3390                 callout_reset(&sc->co_hdl, mxge_ticks, mxge_tick, sc);
3391         }
3392 }
3393
3394 static void
3395 mxge_warn_stuck(mxge_softc_t *sc, mxge_tx_ring_t *tx, int slice)
3396 {
3397         tx = &sc->ss[slice].tx;
3398         device_printf(sc->dev, "slice %d struck? ring state:\n", slice);
3399         device_printf(sc->dev,
3400                       "tx.req=%d tx.done=%d, tx.queue_active=%d\n",
3401                       tx->req, tx->done, tx->queue_active);
3402         device_printf(sc->dev, "tx.activate=%d tx.deactivate=%d\n",
3403                               tx->activate, tx->deactivate);
3404         device_printf(sc->dev, "pkt_done=%d fw=%d\n",
3405                       tx->pkt_done,
3406                       be32toh(sc->ss->fw_stats->send_done_count));
3407 }
3408
3409 static int
3410 mxge_watchdog(mxge_softc_t *sc)
3411 {
3412         mxge_tx_ring_t *tx;
3413         uint32_t rx_pause = be32toh(sc->ss->fw_stats->dropped_pause);
3414         int i, err = 0;
3415
3416         /* see if we have outstanding transmits, which
3417            have been pending for more than mxge_ticks */
3418         for (i = 0; 
3419 #ifdef IFNET_BUF_RING
3420              (i < sc->num_slices) && (err == 0);
3421 #else
3422              (i < 1) && (err == 0);
3423 #endif
3424              i++) {
3425                 tx = &sc->ss[i].tx;             
3426                 if (tx->req != tx->done &&
3427                     tx->watchdog_req != tx->watchdog_done &&
3428                     tx->done == tx->watchdog_done) {
3429                         /* check for pause blocking before resetting */
3430                         if (tx->watchdog_rx_pause == rx_pause) {
3431                                 mxge_warn_stuck(sc, tx, i);
3432                                 mxge_watchdog_reset(sc);
3433                                 return (ENXIO);
3434                         }
3435                         else
3436                                 device_printf(sc->dev, "Flow control blocking "
3437                                               "xmits, check link partner\n");
3438                 }
3439
3440                 tx->watchdog_req = tx->req;
3441                 tx->watchdog_done = tx->done;
3442                 tx->watchdog_rx_pause = rx_pause;
3443         }
3444
3445         if (sc->need_media_probe)
3446                 mxge_media_probe(sc);
3447         return (err);
3448 }
3449
3450 static u_long
3451 mxge_update_stats(mxge_softc_t *sc)
3452 {
3453         struct mxge_slice_state *ss;
3454         u_long pkts = 0;
3455         u_long ipackets = 0, old_ipackets;
3456         u_long opackets = 0, old_opackets;
3457 #ifdef IFNET_BUF_RING
3458         u_long obytes = 0;
3459         u_long omcasts = 0;
3460         u_long odrops = 0;
3461 #endif
3462         u_long oerrors = 0;
3463         int slice;
3464
3465         for (slice = 0; slice < sc->num_slices; slice++) {
3466                 ss = &sc->ss[slice];
3467                 ipackets += ss->ipackets;
3468                 opackets += ss->opackets;
3469 #ifdef IFNET_BUF_RING
3470                 obytes += ss->obytes;
3471                 omcasts += ss->omcasts;
3472                 odrops += ss->tx.br->br_drops;
3473 #endif
3474                 oerrors += ss->oerrors;
3475         }
3476         IFNET_STAT_GET(sc->ifp, ipackets, old_ipackets);
3477         IFNET_STAT_GET(sc->ifp, opackets, old_opackets);
3478
3479         pkts = ipackets - old_ipackets;
3480         pkts += opackets - old_opackets;
3481
3482         IFNET_STAT_SET(sc->ifp, ipackets, ipackets);
3483         IFNET_STAT_SET(sc->ifp, opackets, opackets);
3484 #ifdef IFNET_BUF_RING
3485         sc->ifp->if_obytes = obytes;
3486         sc->ifp->if_omcasts = omcasts;
3487         sc->ifp->if_snd.ifq_drops = odrops;
3488 #endif
3489         IFNET_STAT_SET(sc->ifp, oerrors, oerrors);
3490         return pkts;
3491 }
3492
3493 static void
3494 mxge_tick(void *arg)
3495 {
3496         mxge_softc_t *sc = arg;
3497         u_long pkts = 0;
3498         int err = 0;
3499         int running, ticks;
3500         uint16_t cmd;
3501
3502         lwkt_serialize_enter(sc->ifp->if_serializer);
3503
3504         ticks = mxge_ticks;
3505         running = sc->ifp->if_flags & IFF_RUNNING;
3506         if (running) {
3507                 /* aggregate stats from different slices */
3508                 pkts = mxge_update_stats(sc);
3509                 if (!sc->watchdog_countdown) {
3510                         err = mxge_watchdog(sc);
3511                         sc->watchdog_countdown = 4;
3512                 }
3513                 sc->watchdog_countdown--;
3514         }
3515         if (pkts == 0) {
3516                 /* ensure NIC did not suffer h/w fault while idle */
3517                 cmd = pci_read_config(sc->dev, PCIR_COMMAND, 2);                
3518                 if ((cmd & PCIM_CMD_BUSMASTEREN) == 0) {
3519                         sc->dying = 2;
3520                         mxge_watchdog_reset(sc);
3521                         err = ENXIO;
3522                 }
3523                 /* look less often if NIC is idle */
3524                 ticks *= 4;
3525         }
3526
3527         if (err == 0)
3528                 callout_reset(&sc->co_hdl, ticks, mxge_tick, sc);
3529
3530         lwkt_serialize_exit(sc->ifp->if_serializer);
3531 }
3532
3533 static int
3534 mxge_media_change(struct ifnet *ifp)
3535 {
3536         return EINVAL;
3537 }
3538
3539 static int
3540 mxge_change_mtu(mxge_softc_t *sc, int mtu)
3541 {
3542         struct ifnet *ifp = sc->ifp;
3543         int real_mtu, old_mtu;
3544         int err = 0;
3545
3546         if (ifp->if_serializer)
3547                 ASSERT_SERIALIZED(ifp->if_serializer);
3548
3549         real_mtu = mtu + ETHER_HDR_LEN + EVL_ENCAPLEN;
3550         if ((real_mtu > sc->max_mtu) || real_mtu < 60)
3551                 return EINVAL;
3552         old_mtu = ifp->if_mtu;
3553         ifp->if_mtu = mtu;
3554         if (ifp->if_flags & IFF_RUNNING) {
3555                 mxge_close(sc, 0);
3556                 err = mxge_open(sc);
3557                 if (err != 0) {
3558                         ifp->if_mtu = old_mtu;
3559                         mxge_close(sc, 0);
3560                         (void) mxge_open(sc);
3561                 }
3562         }
3563         return err;
3564 }       
3565
3566 static void
3567 mxge_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3568 {
3569         mxge_softc_t *sc = ifp->if_softc;
3570         
3571
3572         if (sc == NULL)
3573                 return;
3574         ifmr->ifm_status = IFM_AVALID;
3575         ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3576         ifmr->ifm_status |= sc->link_state ? IFM_ACTIVE : 0;
3577         ifmr->ifm_active |= sc->current_media;
3578 }
3579
3580 static int
3581 mxge_ioctl(struct ifnet *ifp, u_long command, caddr_t data,
3582     struct ucred *cr __unused)
3583 {
3584         mxge_softc_t *sc = ifp->if_softc;
3585         struct ifreq *ifr = (struct ifreq *)data;
3586         int err, mask;
3587
3588         err = 0;
3589         ASSERT_SERIALIZED(ifp->if_serializer);
3590         switch (command) {
3591         case SIOCSIFMTU:
3592                 err = mxge_change_mtu(sc, ifr->ifr_mtu);
3593                 break;
3594
3595         case SIOCSIFFLAGS:
3596                 if (sc->dying) {
3597                         return EINVAL;
3598                 }
3599                 if (ifp->if_flags & IFF_UP) {
3600                         if (!(ifp->if_flags & IFF_RUNNING)) {
3601                                 err = mxge_open(sc);
3602                         } else {
3603                                 /* take care of promis can allmulti
3604                                    flag chages */
3605                                 mxge_change_promisc(sc, 
3606                                                     ifp->if_flags & IFF_PROMISC);
3607                                 mxge_set_multicast_list(sc);
3608                         }
3609                 } else {
3610                         if (ifp->if_flags & IFF_RUNNING) {
3611                                 mxge_close(sc, 0);
3612                         }
3613                 }
3614                 break;
3615
3616         case SIOCADDMULTI:
3617         case SIOCDELMULTI:
3618                 mxge_set_multicast_list(sc);
3619                 break;
3620
3621         case SIOCSIFCAP:
3622                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
3623                 if (mask & IFCAP_TXCSUM) {
3624                         ifp->if_capenable ^= IFCAP_TXCSUM;
3625                         if (ifp->if_capenable & IFCAP_TXCSUM)
3626                                 ifp->if_hwassist |= CSUM_TCP | CSUM_UDP;
3627                         else
3628                                 ifp->if_hwassist &= ~(CSUM_TCP | CSUM_UDP);
3629                 }
3630                 if (mask & IFCAP_TSO) {
3631                         ifp->if_capenable ^= IFCAP_TSO;
3632                         if (ifp->if_capenable & IFCAP_TSO)
3633                                 ifp->if_hwassist |= CSUM_TSO;
3634                         else
3635                                 ifp->if_hwassist &= ~CSUM_TSO;
3636                 }
3637                 if (mask & IFCAP_RXCSUM)
3638                         ifp->if_capenable ^= IFCAP_RXCSUM;
3639                 if (mask & IFCAP_VLAN_HWTAGGING)
3640                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
3641                 break;
3642
3643         case SIOCGIFMEDIA:
3644                 mxge_media_probe(sc);
3645                 err = ifmedia_ioctl(ifp, (struct ifreq *)data, 
3646                                     &sc->media, command);
3647                 break;
3648
3649         default:
3650                 err = ether_ioctl(ifp, command, data);
3651                 break;
3652         }
3653         return err;
3654 }
3655
3656 static void
3657 mxge_fetch_tunables(mxge_softc_t *sc)
3658 {
3659         sc->intr_coal_delay = mxge_intr_coal_delay;
3660         if (sc->intr_coal_delay < 0 || sc->intr_coal_delay > (10 * 1000))
3661                 sc->intr_coal_delay = MXGE_INTR_COAL_DELAY;
3662
3663         /* XXX */
3664         if (mxge_ticks == 0)
3665                 mxge_ticks = hz / 2;
3666
3667         sc->pause = mxge_flow_control;
3668
3669         sc->throttle = mxge_throttle;
3670         if (sc->throttle && sc->throttle > MXGE_MAX_THROTTLE)
3671                 sc->throttle = MXGE_MAX_THROTTLE;
3672         if (sc->throttle && sc->throttle < MXGE_MIN_THROTTLE)
3673                 sc->throttle = MXGE_MIN_THROTTLE;
3674 }
3675
3676 static void
3677 mxge_free_slices(mxge_softc_t *sc)
3678 {
3679         struct mxge_slice_state *ss;
3680         int i;
3681
3682         if (sc->ss == NULL)
3683                 return;
3684
3685         for (i = 0; i < sc->num_slices; i++) {
3686                 ss = &sc->ss[i];
3687                 if (ss->fw_stats != NULL) {
3688                         mxge_dma_free(&ss->fw_stats_dma);
3689                         ss->fw_stats = NULL;
3690                 }
3691                 if (ss->rx_done.entry != NULL) {
3692                         mxge_dma_free(&ss->rx_done.dma);
3693                         ss->rx_done.entry = NULL;
3694                 }
3695         }
3696         kfree(sc->ss, M_DEVBUF);
3697         sc->ss = NULL;
3698 }
3699
3700 static int
3701 mxge_alloc_slices(mxge_softc_t *sc)
3702 {
3703         mxge_cmd_t cmd;
3704         struct mxge_slice_state *ss;
3705         size_t bytes;
3706         int err, i, max_intr_slots;
3707
3708         err = mxge_send_cmd(sc, MXGEFW_CMD_GET_RX_RING_SIZE, &cmd);
3709         if (err != 0) {
3710                 device_printf(sc->dev, "Cannot determine rx ring size\n");
3711                 return err;
3712         }
3713         sc->rx_ring_size = cmd.data0;
3714         max_intr_slots = 2 * (sc->rx_ring_size / sizeof (mcp_dma_addr_t));
3715         
3716         bytes = sizeof(*sc->ss) * sc->num_slices;
3717         sc->ss = kmalloc(bytes, M_DEVBUF, M_WAITOK | M_ZERO);
3718
3719         for (i = 0; i < sc->num_slices; i++) {
3720                 ss = &sc->ss[i];
3721
3722                 ss->sc = sc;
3723
3724                 /*
3725                  * Allocate per-slice rx interrupt queues
3726                  */
3727                 bytes = max_intr_slots * sizeof(*ss->rx_done.entry);
3728                 err = mxge_dma_alloc(sc, &ss->rx_done.dma, bytes, 4096);
3729                 if (err != 0)
3730                         goto abort;
3731                 ss->rx_done.entry = ss->rx_done.dma.dmem_addr;
3732
3733                 /* 
3734                  * Allocate the per-slice firmware stats; stats
3735                  * (including tx) are used used only on the first
3736                  * slice for now
3737                  */
3738 #ifndef IFNET_BUF_RING
3739                 if (i > 0)
3740                         continue;
3741 #endif
3742
3743                 bytes = sizeof(*ss->fw_stats);
3744                 err = mxge_dma_alloc(sc, &ss->fw_stats_dma,
3745                     sizeof(*ss->fw_stats), 64);
3746                 if (err != 0)
3747                         goto abort;
3748                 ss->fw_stats = ss->fw_stats_dma.dmem_addr;
3749         }
3750
3751         return 0;
3752
3753 abort:
3754         mxge_free_slices(sc);
3755         return ENOMEM;
3756 }
3757
3758 static void
3759 mxge_slice_probe(mxge_softc_t *sc)
3760 {
3761         mxge_cmd_t cmd;
3762         char *old_fw;
3763         int msix_cnt, status, max_intr_slots;
3764
3765         sc->num_slices = 1;
3766
3767         /*
3768          * XXX
3769          *
3770          * Don't enable multiple slices if they are not enabled,
3771          * or if this is not an SMP system 
3772          */
3773         if (mxge_max_slices == 0 || mxge_max_slices == 1 || ncpus < 2)
3774                 return;
3775
3776         /* see how many MSI-X interrupts are available */
3777         msix_cnt = pci_msix_count(sc->dev);
3778         if (msix_cnt < 2)
3779                 return;
3780
3781         /* now load the slice aware firmware see what it supports */
3782         old_fw = sc->fw_name;
3783         if (old_fw == mxge_fw_aligned)
3784                 sc->fw_name = mxge_fw_rss_aligned;
3785         else
3786                 sc->fw_name = mxge_fw_rss_unaligned;
3787         status = mxge_load_firmware(sc, 0);
3788         if (status != 0) {
3789                 device_printf(sc->dev, "Falling back to a single slice\n");
3790                 return;
3791         }
3792         
3793         /* try to send a reset command to the card to see if it
3794            is alive */
3795         memset(&cmd, 0, sizeof (cmd));
3796         status = mxge_send_cmd(sc, MXGEFW_CMD_RESET, &cmd);
3797         if (status != 0) {
3798                 device_printf(sc->dev, "failed reset\n");
3799                 goto abort_with_fw;
3800         }
3801
3802         /* get rx ring size */
3803         status = mxge_send_cmd(sc, MXGEFW_CMD_GET_RX_RING_SIZE, &cmd);
3804         if (status != 0) {
3805                 device_printf(sc->dev, "Cannot determine rx ring size\n");
3806                 goto abort_with_fw;
3807         }
3808         max_intr_slots = 2 * (cmd.data0 / sizeof (mcp_dma_addr_t));
3809
3810         /* tell it the size of the interrupt queues */
3811         cmd.data0 = max_intr_slots * sizeof (struct mcp_slot);
3812         status = mxge_send_cmd(sc, MXGEFW_CMD_SET_INTRQ_SIZE, &cmd);
3813         if (status != 0) {
3814                 device_printf(sc->dev, "failed MXGEFW_CMD_SET_INTRQ_SIZE\n");
3815                 goto abort_with_fw;
3816         }
3817
3818         /* ask the maximum number of slices it supports */
3819         status = mxge_send_cmd(sc, MXGEFW_CMD_GET_MAX_RSS_QUEUES, &cmd);
3820         if (status != 0) {
3821                 device_printf(sc->dev,
3822                               "failed MXGEFW_CMD_GET_MAX_RSS_QUEUES\n");
3823                 goto abort_with_fw;
3824         }
3825         sc->num_slices = cmd.data0;
3826         if (sc->num_slices > msix_cnt)
3827                 sc->num_slices = msix_cnt;
3828
3829         if (mxge_max_slices == -1) {
3830                 /* cap to number of CPUs in system */
3831                 if (sc->num_slices > ncpus)
3832                         sc->num_slices = ncpus;
3833         } else {
3834                 if (sc->num_slices > mxge_max_slices)
3835                         sc->num_slices = mxge_max_slices;
3836         }
3837         /* make sure it is a power of two */
3838         while (sc->num_slices & (sc->num_slices - 1))
3839                 sc->num_slices--;
3840
3841         if (bootverbose)
3842                 device_printf(sc->dev, "using %d slices\n",
3843                               sc->num_slices);
3844         
3845         return;
3846
3847 abort_with_fw:
3848         sc->fw_name = old_fw;
3849         (void) mxge_load_firmware(sc, 0);
3850 }
3851
3852 #if 0
3853 static int
3854 mxge_add_msix_irqs(mxge_softc_t *sc)
3855 {
3856         size_t bytes;
3857         int count, err, i, rid;
3858
3859         rid = PCIR_BAR(2);
3860         sc->msix_table_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3861                                                     &rid, RF_ACTIVE);
3862
3863         if (sc->msix_table_res == NULL) {
3864                 device_printf(sc->dev, "couldn't alloc MSIX table res\n");
3865                 return ENXIO;
3866         }
3867
3868         count = sc->num_slices;
3869         err = pci_alloc_msix(sc->dev, &count);
3870         if (err != 0) {
3871                 device_printf(sc->dev, "pci_alloc_msix: failed, wanted %d"
3872                               "err = %d \n", sc->num_slices, err);
3873                 goto abort_with_msix_table;
3874         }
3875         if (count < sc->num_slices) {
3876                 device_printf(sc->dev, "pci_alloc_msix: need %d, got %d\n",
3877                               count, sc->num_slices);
3878                 device_printf(sc->dev,
3879                               "Try setting hw.mxge.max_slices to %d\n",
3880                               count);
3881                 err = ENOSPC;
3882                 goto abort_with_msix;
3883         }
3884         bytes = sizeof (*sc->msix_irq_res) * sc->num_slices;
3885         sc->msix_irq_res = kmalloc(bytes, M_DEVBUF, M_NOWAIT|M_ZERO);
3886         if (sc->msix_irq_res == NULL) {
3887                 err = ENOMEM;
3888                 goto abort_with_msix;
3889         }
3890
3891         for (i = 0; i < sc->num_slices; i++) {
3892                 rid = i + 1;
3893                 sc->msix_irq_res[i] = bus_alloc_resource_any(sc->dev,
3894                                                           SYS_RES_IRQ,
3895                                                           &rid, RF_ACTIVE);
3896                 if (sc->msix_irq_res[i] == NULL) {
3897                         device_printf(sc->dev, "couldn't allocate IRQ res"
3898                                       " for message %d\n", i);
3899                         err = ENXIO;
3900                         goto abort_with_res;
3901                 }
3902         }
3903
3904         bytes = sizeof (*sc->msix_ih) * sc->num_slices;
3905         sc->msix_ih =  kmalloc(bytes, M_DEVBUF, M_NOWAIT|M_ZERO);
3906
3907         for (i = 0; i < sc->num_slices; i++) {
3908                 err = bus_setup_intr(sc->dev, sc->msix_irq_res[i], 
3909                                      INTR_MPSAFE,
3910                                      mxge_intr, &sc->ss[i], &sc->msix_ih[i],
3911                                      sc->ifp->if_serializer);
3912                 if (err != 0) {
3913                         device_printf(sc->dev, "couldn't setup intr for "
3914                                       "message %d\n", i);
3915                         goto abort_with_intr;
3916                 }
3917         }
3918
3919         if (bootverbose) {
3920                 device_printf(sc->dev, "using %d msix IRQs:",
3921                               sc->num_slices);
3922                 for (i = 0; i < sc->num_slices; i++)
3923                         kprintf(" %ld",  rman_get_start(sc->msix_irq_res[i]));
3924                 kprintf("\n");
3925         }
3926         return (0);
3927
3928 abort_with_intr:
3929         for (i = 0; i < sc->num_slices; i++) {
3930                 if (sc->msix_ih[i] != NULL) {
3931                         bus_teardown_intr(sc->dev, sc->msix_irq_res[i],
3932                                           sc->msix_ih[i]);
3933                         sc->msix_ih[i] = NULL;
3934                 }
3935         }
3936         kfree(sc->msix_ih, M_DEVBUF);
3937
3938
3939 abort_with_res:
3940         for (i = 0; i < sc->num_slices; i++) {
3941                 rid = i + 1;
3942                 if (sc->msix_irq_res[i] != NULL)
3943                         bus_release_resource(sc->dev, SYS_RES_IRQ, rid,
3944                                              sc->msix_irq_res[i]);
3945                 sc->msix_irq_res[i] = NULL;
3946         }
3947         kfree(sc->msix_irq_res, M_DEVBUF);
3948
3949
3950 abort_with_msix:
3951         pci_release_msi(sc->dev);
3952
3953 abort_with_msix_table:
3954         bus_release_resource(sc->dev, SYS_RES_MEMORY, PCIR_BAR(2),
3955                              sc->msix_table_res);
3956
3957         return err;
3958 }
3959 #endif
3960
3961 static int
3962 mxge_add_single_irq(mxge_softc_t *sc)
3963 {
3964         u_int irq_flags;
3965         int err;
3966
3967         sc->irq_type = pci_alloc_1intr(sc->dev, mxge_msi_enable,
3968             &sc->irq_rid, &irq_flags);
3969
3970         sc->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ,
3971             &sc->irq_rid, irq_flags);
3972         if (sc->irq_res == NULL) {
3973                 device_printf(sc->dev, "could not alloc interrupt\n");
3974                 return ENXIO;
3975         }
3976
3977         err = bus_setup_intr(sc->dev, sc->irq_res, INTR_MPSAFE,
3978             mxge_intr, &sc->ss[0], &sc->ih, sc->ifp->if_serializer);
3979         if (err != 0) {
3980                 bus_release_resource(sc->dev, SYS_RES_IRQ, sc->irq_rid,
3981                     sc->irq_res);
3982                 if (sc->irq_type == PCI_INTR_TYPE_MSI)
3983                         pci_release_msi(sc->dev);
3984         }
3985         return err;
3986 }
3987
3988 #if 0
3989 static void
3990 mxge_rem_msix_irqs(mxge_softc_t *sc)
3991 {
3992         int i, rid;
3993
3994         for (i = 0; i < sc->num_slices; i++) {
3995                 if (sc->msix_ih[i] != NULL) {
3996                         bus_teardown_intr(sc->dev, sc->msix_irq_res[i],
3997                                           sc->msix_ih[i]);
3998                         sc->msix_ih[i] = NULL;
3999                 }
4000         }
4001         kfree(sc->msix_ih, M_DEVBUF);
4002
4003         for (i = 0; i < sc->num_slices; i++) {
4004                 rid = i + 1;
4005                 if (sc->msix_irq_res[i] != NULL)
4006                         bus_release_resource(sc->dev, SYS_RES_IRQ, rid,
4007                                              sc->msix_irq_res[i]);
4008                 sc->msix_irq_res[i] = NULL;
4009         }
4010         kfree(sc->msix_irq_res, M_DEVBUF);
4011
4012         bus_release_resource(sc->dev, SYS_RES_MEMORY, PCIR_BAR(2),
4013                              sc->msix_table_res);
4014
4015         pci_release_msi(sc->dev);
4016         return;
4017 }
4018 #endif
4019
4020 static void
4021 mxge_rem_single_irq(mxge_softc_t *sc)
4022 {
4023         bus_teardown_intr(sc->dev, sc->irq_res, sc->ih);
4024         bus_release_resource(sc->dev, SYS_RES_IRQ, sc->irq_rid, sc->irq_res);
4025         if (sc->irq_type == PCI_INTR_TYPE_MSI)
4026                 pci_release_msi(sc->dev);
4027 }
4028
4029 static void
4030 mxge_rem_irq(mxge_softc_t *sc)
4031 {
4032 #if 0
4033         if (sc->num_slices > 1)
4034                 mxge_rem_msix_irqs(sc);
4035         else
4036 #endif
4037                 mxge_rem_single_irq(sc);
4038 }
4039
4040 static int
4041 mxge_add_irq(mxge_softc_t *sc)
4042 {
4043 #if 0
4044         int err;
4045
4046         if (sc->num_slices > 1)
4047                 err = mxge_add_msix_irqs(sc);
4048         else
4049                 err = mxge_add_single_irq(sc);
4050         
4051         if (0 && err == 0 && sc->num_slices > 1) {
4052                 mxge_rem_msix_irqs(sc);
4053                 err = mxge_add_msix_irqs(sc);
4054         }
4055         return err;
4056 #else
4057         return mxge_add_single_irq(sc);
4058 #endif
4059 }
4060
4061 static int 
4062 mxge_attach(device_t dev)
4063 {
4064         mxge_softc_t *sc = device_get_softc(dev);
4065         struct ifnet *ifp = &sc->arpcom.ac_if;
4066         int err, rid;
4067
4068         /*
4069          * Avoid rewriting half the lines in this file to use
4070          * &sc->arpcom.ac_if instead
4071          */
4072         sc->ifp = ifp;
4073         sc->dev = dev;
4074         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
4075
4076         mxge_fetch_tunables(sc);
4077
4078         err = bus_dma_tag_create(NULL,                  /* parent */
4079                                  1,                     /* alignment */
4080                                  0,                     /* boundary */
4081                                  BUS_SPACE_MAXADDR,     /* low */
4082                                  BUS_SPACE_MAXADDR,     /* high */
4083                                  NULL, NULL,            /* filter */
4084                                  BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
4085                                  0,                     /* num segs */
4086                                  BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
4087                                  0,                     /* flags */
4088                                  &sc->parent_dmat);     /* tag */
4089         if (err != 0) {
4090                 device_printf(sc->dev, "Err %d allocating parent dmat\n", err);
4091                 goto abort_with_nothing;
4092         }
4093
4094         callout_init_mp(&sc->co_hdl);
4095
4096         mxge_setup_cfg_space(sc);
4097
4098         /*
4099          * Map the board into the kernel
4100          */
4101         rid = PCIR_BARS;
4102         sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
4103             &rid, RF_ACTIVE);
4104         if (sc->mem_res == NULL) {
4105                 device_printf(dev, "could not map memory\n");
4106                 err = ENXIO;
4107                 goto abort_with_parent_dmat;
4108         }
4109
4110         sc->sram = rman_get_virtual(sc->mem_res);
4111         sc->sram_size = 2*1024*1024 - (2*(48*1024)+(32*1024)) - 0x100;
4112         if (sc->sram_size > rman_get_size(sc->mem_res)) {
4113                 device_printf(dev, "impossible memory region size %ld\n",
4114                     rman_get_size(sc->mem_res));
4115                 err = ENXIO;
4116                 goto abort_with_mem_res;
4117         }
4118
4119         /*
4120          * Make NULL terminated copy of the EEPROM strings section of
4121          * lanai SRAM
4122          */
4123         bzero(sc->eeprom_strings, MXGE_EEPROM_STRINGS_SIZE);
4124         bus_space_read_region_1(rman_get_bustag(sc->mem_res),
4125             rman_get_bushandle(sc->mem_res),
4126             sc->sram_size - MXGE_EEPROM_STRINGS_SIZE,
4127             sc->eeprom_strings, MXGE_EEPROM_STRINGS_SIZE - 2);
4128         err = mxge_parse_strings(sc);
4129         if (err != 0)
4130                 goto abort_with_mem_res;
4131
4132         /*
4133          * Enable write combining for efficient use of PCIe bus
4134          */
4135         mxge_enable_wc(sc);
4136
4137         /*
4138          * Allocate the out of band DMA memory
4139          */
4140         err = mxge_dma_alloc(sc, &sc->cmd_dma, sizeof(mxge_cmd_t), 64);
4141         if (err != 0)
4142                 goto abort_with_mem_res;
4143         sc->cmd = sc->cmd_dma.dmem_addr;
4144
4145         err = mxge_dma_alloc(sc, &sc->zeropad_dma, 64, 64);
4146         if (err != 0)
4147                 goto abort_with_cmd_dma;
4148
4149         err = mxge_dma_alloc(sc, &sc->dmabench_dma, 4096, 4096);
4150         if (err != 0)
4151                 goto abort_with_zeropad_dma;
4152
4153         /* Select & load the firmware */
4154         err = mxge_select_firmware(sc);
4155         if (err != 0)
4156                 goto abort_with_dmabench;
4157
4158         mxge_slice_probe(sc);
4159         err = mxge_alloc_slices(sc);
4160         if (err != 0)
4161                 goto abort_with_dmabench;
4162
4163         err = mxge_reset(sc, 0);
4164         if (err != 0)
4165                 goto abort_with_slices;
4166
4167         err = mxge_alloc_rings(sc);
4168         if (err != 0) {
4169                 device_printf(sc->dev, "failed to allocate rings\n");
4170                 goto abort_with_slices;
4171         }
4172
4173         ifp->if_baudrate = IF_Gbps(10UL);
4174         ifp->if_capabilities = IFCAP_RXCSUM | IFCAP_TXCSUM | IFCAP_TSO;
4175         ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_TSO;
4176
4177         ifp->if_capabilities |= IFCAP_VLAN_MTU;
4178 #if 0
4179         /* Well, its software, sigh */
4180         ifp->if_capabilities |= IFCAP_VLAN_HWTAGGING;
4181 #endif
4182         ifp->if_capenable = ifp->if_capabilities;
4183
4184         ifp->if_softc = sc;
4185         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
4186         ifp->if_init = mxge_init;
4187         ifp->if_ioctl = mxge_ioctl;
4188         ifp->if_start = mxge_start;
4189         /* XXX watchdog */
4190
4191         /* Increase TSO burst length */
4192         ifp->if_tsolen = (32 * ETHERMTU);
4193
4194         /* Initialise the ifmedia structure */
4195         ifmedia_init(&sc->media, 0, mxge_media_change, mxge_media_status);
4196         mxge_media_init(sc);
4197         mxge_media_probe(sc);
4198
4199         ether_ifattach(ifp, sc->mac_addr, NULL);
4200
4201         sc->max_mtu = ETHERMTU + EVL_ENCAPLEN;
4202         sc->dying = 0;
4203
4204         /* must come after ether_ifattach() */
4205         err = mxge_add_irq(sc);
4206         if (err != 0) {
4207                 device_printf(sc->dev, "failed to add irq\n");
4208                 goto abort_with_rings;
4209         }
4210         ifq_set_cpuid(&ifp->if_snd, rman_get_cpuid(sc->irq_res));
4211
4212         mxge_add_sysctls(sc);
4213
4214         callout_reset(&sc->co_hdl, mxge_ticks, mxge_tick, sc);
4215         return 0;
4216
4217 abort_with_rings:
4218         mxge_free_rings(sc);
4219 abort_with_slices:
4220         mxge_free_slices(sc);
4221 abort_with_dmabench:
4222         mxge_dma_free(&sc->dmabench_dma);
4223 abort_with_zeropad_dma:
4224         mxge_dma_free(&sc->zeropad_dma);
4225 abort_with_cmd_dma:
4226         mxge_dma_free(&sc->cmd_dma);
4227 abort_with_mem_res:
4228         bus_release_resource(dev, SYS_RES_MEMORY, PCIR_BARS, sc->mem_res);
4229         pci_disable_busmaster(dev);
4230 abort_with_parent_dmat:
4231         bus_dma_tag_destroy(sc->parent_dmat);
4232 abort_with_nothing:
4233         return err;
4234 }
4235
4236 static int
4237 mxge_detach(device_t dev)
4238 {
4239         mxge_softc_t *sc = device_get_softc(dev);
4240
4241         lwkt_serialize_enter(sc->ifp->if_serializer);
4242         sc->dying = 1;
4243         if (sc->ifp->if_flags & IFF_RUNNING)
4244                 mxge_close(sc, 1);
4245         /*
4246          * XXX: race: the callout callback could be spinning on
4247          * the serializer and run anyway
4248          */
4249         callout_stop(&sc->co_hdl);
4250         lwkt_serialize_exit(sc->ifp->if_serializer);
4251
4252         callout_terminate(&sc->co_hdl);
4253
4254         ether_ifdetach(sc->ifp);
4255         ifmedia_removeall(&sc->media);
4256         mxge_dummy_rdma(sc, 0);
4257         mxge_rem_sysctls(sc);
4258         mxge_rem_irq(sc);
4259         mxge_free_rings(sc);
4260         mxge_free_slices(sc);
4261         mxge_dma_free(&sc->dmabench_dma);
4262         mxge_dma_free(&sc->zeropad_dma);
4263         mxge_dma_free(&sc->cmd_dma);
4264         bus_release_resource(dev, SYS_RES_MEMORY, PCIR_BARS, sc->mem_res);
4265         pci_disable_busmaster(dev);
4266         bus_dma_tag_destroy(sc->parent_dmat);
4267         return 0;
4268 }
4269
4270 static int
4271 mxge_shutdown(device_t dev)
4272 {
4273         return 0;
4274 }