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