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