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