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