[PATCH] IB/ipath: use vmalloc to allocate struct ipath_devdata
[safe/jmp/linux-2.6] / drivers / infiniband / hw / ipath / ipath_driver.c
1 /*
2  * Copyright (c) 2006 QLogic, Inc. All rights reserved.
3  * Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33
34 #include <linux/spinlock.h>
35 #include <linux/idr.h>
36 #include <linux/pci.h>
37 #include <linux/delay.h>
38 #include <linux/netdevice.h>
39 #include <linux/vmalloc.h>
40
41 #include "ipath_kernel.h"
42 #include "ips_common.h"
43 #include "ipath_layer.h"
44
45 static void ipath_update_pio_bufs(struct ipath_devdata *);
46
47 const char *ipath_get_unit_name(int unit)
48 {
49         static char iname[16];
50         snprintf(iname, sizeof iname, "infinipath%u", unit);
51         return iname;
52 }
53
54 EXPORT_SYMBOL_GPL(ipath_get_unit_name);
55
56 #define DRIVER_LOAD_MSG "QLogic " IPATH_DRV_NAME " loaded: "
57 #define PFX IPATH_DRV_NAME ": "
58
59 /*
60  * The size has to be longer than this string, so we can append
61  * board/chip information to it in the init code.
62  */
63 const char ipath_core_version[] = IPATH_IDSTR "\n";
64
65 static struct idr unit_table;
66 DEFINE_SPINLOCK(ipath_devs_lock);
67 LIST_HEAD(ipath_dev_list);
68
69 wait_queue_head_t ipath_sma_state_wait;
70
71 unsigned ipath_debug = __IPATH_INFO;
72
73 module_param_named(debug, ipath_debug, uint, S_IWUSR | S_IRUGO);
74 MODULE_PARM_DESC(debug, "mask for debug prints");
75 EXPORT_SYMBOL_GPL(ipath_debug);
76
77 MODULE_LICENSE("GPL");
78 MODULE_AUTHOR("QLogic <support@pathscale.com>");
79 MODULE_DESCRIPTION("QLogic InfiniPath driver");
80
81 const char *ipath_ibcstatus_str[] = {
82         "Disabled",
83         "LinkUp",
84         "PollActive",
85         "PollQuiet",
86         "SleepDelay",
87         "SleepQuiet",
88         "LState6",              /* unused */
89         "LState7",              /* unused */
90         "CfgDebounce",
91         "CfgRcvfCfg",
92         "CfgWaitRmt",
93         "CfgIdle",
94         "RecovRetrain",
95         "LState0xD",            /* unused */
96         "RecovWaitRmt",
97         "RecovIdle",
98 };
99
100 /*
101  * These variables are initialized in the chip-specific files
102  * but are defined here.
103  */
104 u16 ipath_gpio_sda_num, ipath_gpio_scl_num;
105 u64 ipath_gpio_sda, ipath_gpio_scl;
106 u64 infinipath_i_bitsextant;
107 ipath_err_t infinipath_e_bitsextant, infinipath_hwe_bitsextant;
108 u32 infinipath_i_rcvavail_mask, infinipath_i_rcvurg_mask;
109
110 static void __devexit ipath_remove_one(struct pci_dev *);
111 static int __devinit ipath_init_one(struct pci_dev *,
112                                     const struct pci_device_id *);
113
114 /* Only needed for registration, nothing else needs this info */
115 #define PCI_VENDOR_ID_PATHSCALE 0x1fc1
116 #define PCI_DEVICE_ID_INFINIPATH_HT 0xd
117 #define PCI_DEVICE_ID_INFINIPATH_PE800 0x10
118
119 static const struct pci_device_id ipath_pci_tbl[] = {
120         { PCI_DEVICE(PCI_VENDOR_ID_PATHSCALE, PCI_DEVICE_ID_INFINIPATH_HT) },
121         { PCI_DEVICE(PCI_VENDOR_ID_PATHSCALE, PCI_DEVICE_ID_INFINIPATH_PE800) },
122         { 0, }
123 };
124
125 MODULE_DEVICE_TABLE(pci, ipath_pci_tbl);
126
127 static struct pci_driver ipath_driver = {
128         .name = IPATH_DRV_NAME,
129         .probe = ipath_init_one,
130         .remove = __devexit_p(ipath_remove_one),
131         .id_table = ipath_pci_tbl,
132 };
133
134 /*
135  * This is where port 0's rcvhdrtail register is written back; we also
136  * want nothing else sharing the cache line, so make it a cache line
137  * in size.  Used for all units.
138  */
139 volatile __le64 *ipath_port0_rcvhdrtail;
140 dma_addr_t ipath_port0_rcvhdrtail_dma;
141 static int port0_rcvhdrtail_refs;
142
143 static inline void read_bars(struct ipath_devdata *dd, struct pci_dev *dev,
144                              u32 *bar0, u32 *bar1)
145 {
146         int ret;
147
148         ret = pci_read_config_dword(dev, PCI_BASE_ADDRESS_0, bar0);
149         if (ret)
150                 ipath_dev_err(dd, "failed to read bar0 before enable: "
151                               "error %d\n", -ret);
152
153         ret = pci_read_config_dword(dev, PCI_BASE_ADDRESS_1, bar1);
154         if (ret)
155                 ipath_dev_err(dd, "failed to read bar1 before enable: "
156                               "error %d\n", -ret);
157
158         ipath_dbg("Read bar0 %x bar1 %x\n", *bar0, *bar1);
159 }
160
161 static void ipath_free_devdata(struct pci_dev *pdev,
162                                struct ipath_devdata *dd)
163 {
164         unsigned long flags;
165
166         pci_set_drvdata(pdev, NULL);
167
168         if (dd->ipath_unit != -1) {
169                 spin_lock_irqsave(&ipath_devs_lock, flags);
170                 idr_remove(&unit_table, dd->ipath_unit);
171                 list_del(&dd->ipath_list);
172                 spin_unlock_irqrestore(&ipath_devs_lock, flags);
173         }
174         vfree(dd);
175 }
176
177 static struct ipath_devdata *ipath_alloc_devdata(struct pci_dev *pdev)
178 {
179         unsigned long flags;
180         struct ipath_devdata *dd;
181         int ret;
182
183         if (!idr_pre_get(&unit_table, GFP_KERNEL)) {
184                 dd = ERR_PTR(-ENOMEM);
185                 goto bail;
186         }
187
188         dd = vmalloc(sizeof(*dd));
189         if (!dd) {
190                 dd = ERR_PTR(-ENOMEM);
191                 goto bail;
192         }
193         memset(dd, 0, sizeof(*dd));
194         dd->ipath_unit = -1;
195
196         spin_lock_irqsave(&ipath_devs_lock, flags);
197
198         ret = idr_get_new(&unit_table, dd, &dd->ipath_unit);
199         if (ret < 0) {
200                 printk(KERN_ERR IPATH_DRV_NAME
201                        ": Could not allocate unit ID: error %d\n", -ret);
202                 ipath_free_devdata(pdev, dd);
203                 dd = ERR_PTR(ret);
204                 goto bail_unlock;
205         }
206
207         dd->pcidev = pdev;
208         pci_set_drvdata(pdev, dd);
209
210         list_add(&dd->ipath_list, &ipath_dev_list);
211
212 bail_unlock:
213         spin_unlock_irqrestore(&ipath_devs_lock, flags);
214
215 bail:
216         return dd;
217 }
218
219 static inline struct ipath_devdata *__ipath_lookup(int unit)
220 {
221         return idr_find(&unit_table, unit);
222 }
223
224 struct ipath_devdata *ipath_lookup(int unit)
225 {
226         struct ipath_devdata *dd;
227         unsigned long flags;
228
229         spin_lock_irqsave(&ipath_devs_lock, flags);
230         dd = __ipath_lookup(unit);
231         spin_unlock_irqrestore(&ipath_devs_lock, flags);
232
233         return dd;
234 }
235
236 int ipath_count_units(int *npresentp, int *nupp, u32 *maxportsp)
237 {
238         int nunits, npresent, nup;
239         struct ipath_devdata *dd;
240         unsigned long flags;
241         u32 maxports;
242
243         nunits = npresent = nup = maxports = 0;
244
245         spin_lock_irqsave(&ipath_devs_lock, flags);
246
247         list_for_each_entry(dd, &ipath_dev_list, ipath_list) {
248                 nunits++;
249                 if ((dd->ipath_flags & IPATH_PRESENT) && dd->ipath_kregbase)
250                         npresent++;
251                 if (dd->ipath_lid &&
252                     !(dd->ipath_flags & (IPATH_DISABLED | IPATH_LINKDOWN
253                                          | IPATH_LINKUNK)))
254                         nup++;
255                 if (dd->ipath_cfgports > maxports)
256                         maxports = dd->ipath_cfgports;
257         }
258
259         spin_unlock_irqrestore(&ipath_devs_lock, flags);
260
261         if (npresentp)
262                 *npresentp = npresent;
263         if (nupp)
264                 *nupp = nup;
265         if (maxportsp)
266                 *maxportsp = maxports;
267
268         return nunits;
269 }
270
271 static int init_port0_rcvhdrtail(struct pci_dev *pdev)
272 {
273         int ret;
274
275         mutex_lock(&ipath_mutex);
276
277         if (!ipath_port0_rcvhdrtail) {
278                 ipath_port0_rcvhdrtail =
279                         dma_alloc_coherent(&pdev->dev,
280                                            IPATH_PORT0_RCVHDRTAIL_SIZE,
281                                            &ipath_port0_rcvhdrtail_dma,
282                                            GFP_KERNEL);
283
284                 if (!ipath_port0_rcvhdrtail) {
285                         ret = -ENOMEM;
286                         goto bail;
287                 }
288         }
289         port0_rcvhdrtail_refs++;
290         ret = 0;
291
292 bail:
293         mutex_unlock(&ipath_mutex);
294
295         return ret;
296 }
297
298 static void cleanup_port0_rcvhdrtail(struct pci_dev *pdev)
299 {
300         mutex_lock(&ipath_mutex);
301
302         if (!--port0_rcvhdrtail_refs) {
303                 dma_free_coherent(&pdev->dev, IPATH_PORT0_RCVHDRTAIL_SIZE,
304                                   (void *) ipath_port0_rcvhdrtail,
305                                   ipath_port0_rcvhdrtail_dma);
306                 ipath_port0_rcvhdrtail = NULL;
307         }
308
309         mutex_unlock(&ipath_mutex);
310 }
311
312 /*
313  * These next two routines are placeholders in case we don't have per-arch
314  * code for controlling write combining.  If explicit control of write
315  * combining is not available, performance will probably be awful.
316  */
317
318 int __attribute__((weak)) ipath_enable_wc(struct ipath_devdata *dd)
319 {
320         return -EOPNOTSUPP;
321 }
322
323 void __attribute__((weak)) ipath_disable_wc(struct ipath_devdata *dd)
324 {
325 }
326
327 static int __devinit ipath_init_one(struct pci_dev *pdev,
328                                     const struct pci_device_id *ent)
329 {
330         int ret, len, j;
331         struct ipath_devdata *dd;
332         unsigned long long addr;
333         u32 bar0 = 0, bar1 = 0;
334         u8 rev;
335
336         ret = init_port0_rcvhdrtail(pdev);
337         if (ret < 0) {
338                 printk(KERN_ERR IPATH_DRV_NAME
339                        ": Could not allocate port0_rcvhdrtail: error %d\n",
340                        -ret);
341                 goto bail;
342         }
343
344         dd = ipath_alloc_devdata(pdev);
345         if (IS_ERR(dd)) {
346                 ret = PTR_ERR(dd);
347                 printk(KERN_ERR IPATH_DRV_NAME
348                        ": Could not allocate devdata: error %d\n", -ret);
349                 goto bail_rcvhdrtail;
350         }
351
352         ipath_cdbg(VERBOSE, "initializing unit #%u\n", dd->ipath_unit);
353
354         read_bars(dd, pdev, &bar0, &bar1);
355
356         ret = pci_enable_device(pdev);
357         if (ret) {
358                 /* This can happen iff:
359                  *
360                  * We did a chip reset, and then failed to reprogram the
361                  * BAR, or the chip reset due to an internal error.  We then
362                  * unloaded the driver and reloaded it.
363                  *
364                  * Both reset cases set the BAR back to initial state.  For
365                  * the latter case, the AER sticky error bit at offset 0x718
366                  * should be set, but the Linux kernel doesn't yet know
367                  * about that, it appears.  If the original BAR was retained
368                  * in the kernel data structures, this may be OK.
369                  */
370                 ipath_dev_err(dd, "enable unit %d failed: error %d\n",
371                               dd->ipath_unit, -ret);
372                 goto bail_devdata;
373         }
374         addr = pci_resource_start(pdev, 0);
375         len = pci_resource_len(pdev, 0);
376         ipath_cdbg(VERBOSE, "regbase (0) %llx len %d irq %x, vend %x/%x "
377                    "driver_data %lx\n", addr, len, pdev->irq, ent->vendor,
378                    ent->device, ent->driver_data);
379
380         read_bars(dd, pdev, &bar0, &bar1);
381
382         if (!bar1 && !(bar0 & ~0xf)) {
383                 if (addr) {
384                         dev_info(&pdev->dev, "BAR is 0 (probable RESET), "
385                                  "rewriting as %llx\n", addr);
386                         ret = pci_write_config_dword(
387                                 pdev, PCI_BASE_ADDRESS_0, addr);
388                         if (ret) {
389                                 ipath_dev_err(dd, "rewrite of BAR0 "
390                                               "failed: err %d\n", -ret);
391                                 goto bail_disable;
392                         }
393                         ret = pci_write_config_dword(
394                                 pdev, PCI_BASE_ADDRESS_1, addr >> 32);
395                         if (ret) {
396                                 ipath_dev_err(dd, "rewrite of BAR1 "
397                                               "failed: err %d\n", -ret);
398                                 goto bail_disable;
399                         }
400                 } else {
401                         ipath_dev_err(dd, "BAR is 0 (probable RESET), "
402                                       "not usable until reboot\n");
403                         ret = -ENODEV;
404                         goto bail_disable;
405                 }
406         }
407
408         ret = pci_request_regions(pdev, IPATH_DRV_NAME);
409         if (ret) {
410                 dev_info(&pdev->dev, "pci_request_regions unit %u fails: "
411                          "err %d\n", dd->ipath_unit, -ret);
412                 goto bail_disable;
413         }
414
415         ret = pci_set_dma_mask(pdev, DMA_64BIT_MASK);
416         if (ret) {
417                 /*
418                  * if the 64 bit setup fails, try 32 bit.  Some systems
419                  * do not setup 64 bit maps on systems with 2GB or less
420                  * memory installed.
421                  */
422                 ret = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
423                 if (ret) {
424                         dev_info(&pdev->dev,
425                                 "Unable to set DMA mask for unit %u: %d\n",
426                                 dd->ipath_unit, ret);
427                         goto bail_regions;
428                 }
429                 else {
430                         ipath_dbg("No 64bit DMA mask, used 32 bit mask\n");
431                         ret = pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK);
432                         if (ret)
433                                 dev_info(&pdev->dev,
434                                         "Unable to set DMA consistent mask "
435                                         "for unit %u: %d\n",
436                                         dd->ipath_unit, ret);
437
438                 }
439         }
440         else {
441                 ret = pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK);
442                 if (ret)
443                         dev_info(&pdev->dev,
444                                 "Unable to set DMA consistent mask "
445                                 "for unit %u: %d\n",
446                                 dd->ipath_unit, ret);
447         }
448
449         pci_set_master(pdev);
450
451         /*
452          * Save BARs to rewrite after device reset.  Save all 64 bits of
453          * BAR, just in case.
454          */
455         dd->ipath_pcibar0 = addr;
456         dd->ipath_pcibar1 = addr >> 32;
457         dd->ipath_deviceid = ent->device;       /* save for later use */
458         dd->ipath_vendorid = ent->vendor;
459
460         /* setup the chip-specific functions, as early as possible. */
461         switch (ent->device) {
462         case PCI_DEVICE_ID_INFINIPATH_HT:
463                 ipath_init_ht400_funcs(dd);
464                 break;
465         case PCI_DEVICE_ID_INFINIPATH_PE800:
466                 ipath_init_pe800_funcs(dd);
467                 break;
468         default:
469                 ipath_dev_err(dd, "Found unknown QLogic deviceid 0x%x, "
470                               "failing\n", ent->device);
471                 return -ENODEV;
472         }
473
474         for (j = 0; j < 6; j++) {
475                 if (!pdev->resource[j].start)
476                         continue;
477                 ipath_cdbg(VERBOSE, "BAR %d start %llx, end %llx, len %llx\n",
478                            j, (unsigned long long)pdev->resource[j].start,
479                            (unsigned long long)pdev->resource[j].end,
480                            (unsigned long long)pci_resource_len(pdev, j));
481         }
482
483         if (!addr) {
484                 ipath_dev_err(dd, "No valid address in BAR 0!\n");
485                 ret = -ENODEV;
486                 goto bail_regions;
487         }
488
489         dd->ipath_deviceid = ent->device;       /* save for later use */
490         dd->ipath_vendorid = ent->vendor;
491
492         ret = pci_read_config_byte(pdev, PCI_REVISION_ID, &rev);
493         if (ret) {
494                 ipath_dev_err(dd, "Failed to read PCI revision ID unit "
495                               "%u: err %d\n", dd->ipath_unit, -ret);
496                 goto bail_regions;      /* shouldn't ever happen */
497         }
498         dd->ipath_pcirev = rev;
499
500         dd->ipath_kregbase = ioremap_nocache(addr, len);
501
502         if (!dd->ipath_kregbase) {
503                 ipath_dbg("Unable to map io addr %llx to kvirt, failing\n",
504                           addr);
505                 ret = -ENOMEM;
506                 goto bail_iounmap;
507         }
508         dd->ipath_kregend = (u64 __iomem *)
509                 ((void __iomem *)dd->ipath_kregbase + len);
510         dd->ipath_physaddr = addr;      /* used for io_remap, etc. */
511         /* for user mmap */
512         ipath_cdbg(VERBOSE, "mapped io addr %llx to kregbase %p\n",
513                    addr, dd->ipath_kregbase);
514
515         /*
516          * clear ipath_flags here instead of in ipath_init_chip as it is set
517          * by ipath_setup_htconfig.
518          */
519         dd->ipath_flags = 0;
520
521         if (dd->ipath_f_bus(dd, pdev))
522                 ipath_dev_err(dd, "Failed to setup config space; "
523                               "continuing anyway\n");
524
525         /*
526          * set up our interrupt handler; SA_SHIRQ probably not needed,
527          * since MSI interrupts shouldn't be shared but won't  hurt for now.
528          * check 0 irq after we return from chip-specific bus setup, since
529          * that can affect this due to setup
530          */
531         if (!pdev->irq)
532                 ipath_dev_err(dd, "irq is 0, BIOS error?  Interrupts won't "
533                               "work\n");
534         else {
535                 ret = request_irq(pdev->irq, ipath_intr, SA_SHIRQ,
536                                   IPATH_DRV_NAME, dd);
537                 if (ret) {
538                         ipath_dev_err(dd, "Couldn't setup irq handler, "
539                                       "irq=%u: %d\n", pdev->irq, ret);
540                         goto bail_iounmap;
541                 }
542         }
543
544         ret = ipath_init_chip(dd, 0);   /* do the chip-specific init */
545         if (ret)
546                 goto bail_iounmap;
547
548         ret = ipath_enable_wc(dd);
549
550         if (ret) {
551                 ipath_dev_err(dd, "Write combining not enabled "
552                               "(err %d): performance may be poor\n",
553                               -ret);
554                 ret = 0;
555         }
556
557         ipath_device_create_group(&pdev->dev, dd);
558         ipathfs_add_device(dd);
559         ipath_user_add(dd);
560         ipath_diag_add(dd);
561         ipath_layer_add(dd);
562
563         goto bail;
564
565 bail_iounmap:
566         iounmap((volatile void __iomem *) dd->ipath_kregbase);
567
568 bail_regions:
569         pci_release_regions(pdev);
570
571 bail_disable:
572         pci_disable_device(pdev);
573
574 bail_devdata:
575         ipath_free_devdata(pdev, dd);
576
577 bail_rcvhdrtail:
578         cleanup_port0_rcvhdrtail(pdev);
579
580 bail:
581         return ret;
582 }
583
584 static void __devexit ipath_remove_one(struct pci_dev *pdev)
585 {
586         struct ipath_devdata *dd;
587
588         ipath_cdbg(VERBOSE, "removing, pdev=%p\n", pdev);
589         if (!pdev)
590                 return;
591
592         dd = pci_get_drvdata(pdev);
593         ipath_layer_remove(dd);
594         ipath_diag_remove(dd);
595         ipath_user_remove(dd);
596         ipathfs_remove_device(dd);
597         ipath_device_remove_group(&pdev->dev, dd);
598         ipath_cdbg(VERBOSE, "Releasing pci memory regions, dd %p, "
599                    "unit %u\n", dd, (u32) dd->ipath_unit);
600         if (dd->ipath_kregbase) {
601                 ipath_cdbg(VERBOSE, "Unmapping kregbase %p\n",
602                            dd->ipath_kregbase);
603                 iounmap((volatile void __iomem *) dd->ipath_kregbase);
604                 dd->ipath_kregbase = NULL;
605         }
606         pci_release_regions(pdev);
607         ipath_cdbg(VERBOSE, "calling pci_disable_device\n");
608         pci_disable_device(pdev);
609
610         ipath_free_devdata(pdev, dd);
611         cleanup_port0_rcvhdrtail(pdev);
612 }
613
614 /* general driver use */
615 DEFINE_MUTEX(ipath_mutex);
616
617 static DEFINE_SPINLOCK(ipath_pioavail_lock);
618
619 /**
620  * ipath_disarm_piobufs - cancel a range of PIO buffers
621  * @dd: the infinipath device
622  * @first: the first PIO buffer to cancel
623  * @cnt: the number of PIO buffers to cancel
624  *
625  * cancel a range of PIO buffers, used when they might be armed, but
626  * not triggered.  Used at init to ensure buffer state, and also user
627  * process close, in case it died while writing to a PIO buffer
628  * Also after errors.
629  */
630 void ipath_disarm_piobufs(struct ipath_devdata *dd, unsigned first,
631                           unsigned cnt)
632 {
633         unsigned i, last = first + cnt;
634         u64 sendctrl, sendorig;
635
636         ipath_cdbg(PKT, "disarm %u PIObufs first=%u\n", cnt, first);
637         sendorig = dd->ipath_sendctrl | INFINIPATH_S_DISARM;
638         for (i = first; i < last; i++) {
639                 sendctrl = sendorig |
640                         (i << INFINIPATH_S_DISARMPIOBUF_SHIFT);
641                 ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
642                                  sendctrl);
643         }
644
645         /*
646          * Write it again with current value, in case ipath_sendctrl changed
647          * while we were looping; no critical bits that would require
648          * locking.
649          *
650          * Write a 0, and then the original value, reading scratch in
651          * between.  This seems to avoid a chip timing race that causes
652          * pioavail updates to memory to stop.
653          */
654         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
655                          0);
656         sendorig = ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
657         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
658                          dd->ipath_sendctrl);
659 }
660
661 /**
662  * ipath_wait_linkstate - wait for an IB link state change to occur
663  * @dd: the infinipath device
664  * @state: the state to wait for
665  * @msecs: the number of milliseconds to wait
666  *
667  * wait up to msecs milliseconds for IB link state change to occur for
668  * now, take the easy polling route.  Currently used only by
669  * ipath_layer_set_linkstate.  Returns 0 if state reached, otherwise
670  * -ETIMEDOUT state can have multiple states set, for any of several
671  * transitions.
672  */
673 int ipath_wait_linkstate(struct ipath_devdata *dd, u32 state, int msecs)
674 {
675         dd->ipath_sma_state_wanted = state;
676         wait_event_interruptible_timeout(ipath_sma_state_wait,
677                                          (dd->ipath_flags & state),
678                                          msecs_to_jiffies(msecs));
679         dd->ipath_sma_state_wanted = 0;
680
681         if (!(dd->ipath_flags & state)) {
682                 u64 val;
683                 ipath_cdbg(SMA, "Didn't reach linkstate %s within %u ms\n",
684                            /* test INIT ahead of DOWN, both can be set */
685                            (state & IPATH_LINKINIT) ? "INIT" :
686                            ((state & IPATH_LINKDOWN) ? "DOWN" :
687                             ((state & IPATH_LINKARMED) ? "ARM" : "ACTIVE")),
688                            msecs);
689                 val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_ibcstatus);
690                 ipath_cdbg(VERBOSE, "ibcc=%llx ibcstatus=%llx (%s)\n",
691                            (unsigned long long) ipath_read_kreg64(
692                                    dd, dd->ipath_kregs->kr_ibcctrl),
693                            (unsigned long long) val,
694                            ipath_ibcstatus_str[val & 0xf]);
695         }
696         return (dd->ipath_flags & state) ? 0 : -ETIMEDOUT;
697 }
698
699 void ipath_decode_err(char *buf, size_t blen, ipath_err_t err)
700 {
701         *buf = '\0';
702         if (err & INFINIPATH_E_RHDRLEN)
703                 strlcat(buf, "rhdrlen ", blen);
704         if (err & INFINIPATH_E_RBADTID)
705                 strlcat(buf, "rbadtid ", blen);
706         if (err & INFINIPATH_E_RBADVERSION)
707                 strlcat(buf, "rbadversion ", blen);
708         if (err & INFINIPATH_E_RHDR)
709                 strlcat(buf, "rhdr ", blen);
710         if (err & INFINIPATH_E_RLONGPKTLEN)
711                 strlcat(buf, "rlongpktlen ", blen);
712         if (err & INFINIPATH_E_RSHORTPKTLEN)
713                 strlcat(buf, "rshortpktlen ", blen);
714         if (err & INFINIPATH_E_RMAXPKTLEN)
715                 strlcat(buf, "rmaxpktlen ", blen);
716         if (err & INFINIPATH_E_RMINPKTLEN)
717                 strlcat(buf, "rminpktlen ", blen);
718         if (err & INFINIPATH_E_RFORMATERR)
719                 strlcat(buf, "rformaterr ", blen);
720         if (err & INFINIPATH_E_RUNSUPVL)
721                 strlcat(buf, "runsupvl ", blen);
722         if (err & INFINIPATH_E_RUNEXPCHAR)
723                 strlcat(buf, "runexpchar ", blen);
724         if (err & INFINIPATH_E_RIBFLOW)
725                 strlcat(buf, "ribflow ", blen);
726         if (err & INFINIPATH_E_REBP)
727                 strlcat(buf, "EBP ", blen);
728         if (err & INFINIPATH_E_SUNDERRUN)
729                 strlcat(buf, "sunderrun ", blen);
730         if (err & INFINIPATH_E_SPIOARMLAUNCH)
731                 strlcat(buf, "spioarmlaunch ", blen);
732         if (err & INFINIPATH_E_SUNEXPERRPKTNUM)
733                 strlcat(buf, "sunexperrpktnum ", blen);
734         if (err & INFINIPATH_E_SDROPPEDDATAPKT)
735                 strlcat(buf, "sdroppeddatapkt ", blen);
736         if (err & INFINIPATH_E_SDROPPEDSMPPKT)
737                 strlcat(buf, "sdroppedsmppkt ", blen);
738         if (err & INFINIPATH_E_SMAXPKTLEN)
739                 strlcat(buf, "smaxpktlen ", blen);
740         if (err & INFINIPATH_E_SMINPKTLEN)
741                 strlcat(buf, "sminpktlen ", blen);
742         if (err & INFINIPATH_E_SUNSUPVL)
743                 strlcat(buf, "sunsupVL ", blen);
744         if (err & INFINIPATH_E_SPKTLEN)
745                 strlcat(buf, "spktlen ", blen);
746         if (err & INFINIPATH_E_INVALIDADDR)
747                 strlcat(buf, "invalidaddr ", blen);
748         if (err & INFINIPATH_E_RICRC)
749                 strlcat(buf, "CRC ", blen);
750         if (err & INFINIPATH_E_RVCRC)
751                 strlcat(buf, "VCRC ", blen);
752         if (err & INFINIPATH_E_RRCVEGRFULL)
753                 strlcat(buf, "rcvegrfull ", blen);
754         if (err & INFINIPATH_E_RRCVHDRFULL)
755                 strlcat(buf, "rcvhdrfull ", blen);
756         if (err & INFINIPATH_E_IBSTATUSCHANGED)
757                 strlcat(buf, "ibcstatuschg ", blen);
758         if (err & INFINIPATH_E_RIBLOSTLINK)
759                 strlcat(buf, "riblostlink ", blen);
760         if (err & INFINIPATH_E_HARDWARE)
761                 strlcat(buf, "hardware ", blen);
762         if (err & INFINIPATH_E_RESET)
763                 strlcat(buf, "reset ", blen);
764 }
765
766 /**
767  * get_rhf_errstring - decode RHF errors
768  * @err: the err number
769  * @msg: the output buffer
770  * @len: the length of the output buffer
771  *
772  * only used one place now, may want more later
773  */
774 static void get_rhf_errstring(u32 err, char *msg, size_t len)
775 {
776         /* if no errors, and so don't need to check what's first */
777         *msg = '\0';
778
779         if (err & INFINIPATH_RHF_H_ICRCERR)
780                 strlcat(msg, "icrcerr ", len);
781         if (err & INFINIPATH_RHF_H_VCRCERR)
782                 strlcat(msg, "vcrcerr ", len);
783         if (err & INFINIPATH_RHF_H_PARITYERR)
784                 strlcat(msg, "parityerr ", len);
785         if (err & INFINIPATH_RHF_H_LENERR)
786                 strlcat(msg, "lenerr ", len);
787         if (err & INFINIPATH_RHF_H_MTUERR)
788                 strlcat(msg, "mtuerr ", len);
789         if (err & INFINIPATH_RHF_H_IHDRERR)
790                 /* infinipath hdr checksum error */
791                 strlcat(msg, "ipathhdrerr ", len);
792         if (err & INFINIPATH_RHF_H_TIDERR)
793                 strlcat(msg, "tiderr ", len);
794         if (err & INFINIPATH_RHF_H_MKERR)
795                 /* bad port, offset, etc. */
796                 strlcat(msg, "invalid ipathhdr ", len);
797         if (err & INFINIPATH_RHF_H_IBERR)
798                 strlcat(msg, "iberr ", len);
799         if (err & INFINIPATH_RHF_L_SWA)
800                 strlcat(msg, "swA ", len);
801         if (err & INFINIPATH_RHF_L_SWB)
802                 strlcat(msg, "swB ", len);
803 }
804
805 /**
806  * ipath_get_egrbuf - get an eager buffer
807  * @dd: the infinipath device
808  * @bufnum: the eager buffer to get
809  * @err: unused
810  *
811  * must only be called if ipath_pd[port] is known to be allocated
812  */
813 static inline void *ipath_get_egrbuf(struct ipath_devdata *dd, u32 bufnum,
814                                      int err)
815 {
816         return dd->ipath_port0_skbs ?
817                 (void *)dd->ipath_port0_skbs[bufnum]->data : NULL;
818 }
819
820 /**
821  * ipath_alloc_skb - allocate an skb and buffer with possible constraints
822  * @dd: the infinipath device
823  * @gfp_mask: the sk_buff SFP mask
824  */
825 struct sk_buff *ipath_alloc_skb(struct ipath_devdata *dd,
826                                 gfp_t gfp_mask)
827 {
828         struct sk_buff *skb;
829         u32 len;
830
831         /*
832          * Only fully supported way to handle this is to allocate lots
833          * extra, align as needed, and then do skb_reserve().  That wastes
834          * a lot of memory...  I'll have to hack this into infinipath_copy
835          * also.
836          */
837
838         /*
839          * We need 4 extra bytes for unaligned transfer copying
840          */
841         if (dd->ipath_flags & IPATH_4BYTE_TID) {
842                 /* we need a 4KB multiple alignment, and there is no way
843                  * to do it except to allocate extra and then skb_reserve
844                  * enough to bring it up to the right alignment.
845                  */
846                 len = dd->ipath_ibmaxlen + 4 + (1 << 11) - 1;
847         }
848         else
849                 len = dd->ipath_ibmaxlen + 4;
850         skb = __dev_alloc_skb(len, gfp_mask);
851         if (!skb) {
852                 ipath_dev_err(dd, "Failed to allocate skbuff, length %u\n",
853                               len);
854                 goto bail;
855         }
856         if (dd->ipath_flags & IPATH_4BYTE_TID) {
857                 u32 una = ((1 << 11) - 1) & (unsigned long)(skb->data + 4);
858                 if (una)
859                         skb_reserve(skb, 4 + (1 << 11) - una);
860                 else
861                         skb_reserve(skb, 4);
862         } else
863                 skb_reserve(skb, 4);
864
865 bail:
866         return skb;
867 }
868
869 /**
870  * ipath_rcv_layer - receive a packet for the layered (ethernet) driver
871  * @dd: the infinipath device
872  * @etail: the sk_buff number
873  * @tlen: the total packet length
874  * @hdr: the ethernet header
875  *
876  * Separate routine for better overall optimization
877  */
878 static void ipath_rcv_layer(struct ipath_devdata *dd, u32 etail,
879                             u32 tlen, struct ether_header *hdr)
880 {
881         u32 elen;
882         u8 pad, *bthbytes;
883         struct sk_buff *skb, *nskb;
884
885         if (dd->ipath_port0_skbs && hdr->sub_opcode == OPCODE_ENCAP) {
886                 /*
887                  * Allocate a new sk_buff to replace the one we give
888                  * to the network stack.
889                  */
890                 nskb = ipath_alloc_skb(dd, GFP_ATOMIC);
891                 if (!nskb) {
892                         /* count OK packets that we drop */
893                         ipath_stats.sps_krdrops++;
894                         return;
895                 }
896
897                 bthbytes = (u8 *) hdr->bth;
898                 pad = (bthbytes[1] >> 4) & 3;
899                 /* +CRC32 */
900                 elen = tlen - (sizeof(*hdr) + pad + sizeof(u32));
901
902                 skb = dd->ipath_port0_skbs[etail];
903                 dd->ipath_port0_skbs[etail] = nskb;
904                 skb_put(skb, elen);
905
906                 dd->ipath_f_put_tid(dd, etail + (u64 __iomem *)
907                                     ((char __iomem *) dd->ipath_kregbase
908                                      + dd->ipath_rcvegrbase), 0,
909                                     virt_to_phys(nskb->data));
910
911                 __ipath_layer_rcv(dd, hdr, skb);
912
913                 /* another ether packet received */
914                 ipath_stats.sps_ether_rpkts++;
915         }
916         else if (hdr->sub_opcode == OPCODE_LID_ARP)
917                 __ipath_layer_rcv_lid(dd, hdr);
918 }
919
920 /*
921  * ipath_kreceive - receive a packet
922  * @dd: the infinipath device
923  *
924  * called from interrupt handler for errors or receive interrupt
925  */
926 void ipath_kreceive(struct ipath_devdata *dd)
927 {
928         u64 *rc;
929         void *ebuf;
930         const u32 rsize = dd->ipath_rcvhdrentsize;      /* words */
931         const u32 maxcnt = dd->ipath_rcvhdrcnt * rsize; /* words */
932         u32 etail = -1, l, hdrqtail;
933         struct ips_message_header *hdr;
934         u32 eflags, i, etype, tlen, pkttot = 0;
935         static u64 totcalls;    /* stats, may eventually remove */
936         char emsg[128];
937
938         if (!dd->ipath_hdrqtailptr) {
939                 ipath_dev_err(dd,
940                               "hdrqtailptr not set, can't do receives\n");
941                 goto bail;
942         }
943
944         /* There is already a thread processing this queue. */
945         if (test_and_set_bit(0, &dd->ipath_rcv_pending))
946                 goto bail;
947
948         if (dd->ipath_port0head ==
949             (u32)le64_to_cpu(*dd->ipath_hdrqtailptr))
950                 goto done;
951
952 gotmore:
953         /*
954          * read only once at start.  If in flood situation, this helps
955          * performance slightly.  If more arrive while we are processing,
956          * we'll come back here and do them
957          */
958         hdrqtail = (u32)le64_to_cpu(*dd->ipath_hdrqtailptr);
959
960         for (i = 0, l = dd->ipath_port0head; l != hdrqtail; i++) {
961                 u32 qp;
962                 u8 *bthbytes;
963
964                 rc = (u64 *) (dd->ipath_pd[0]->port_rcvhdrq + (l << 2));
965                 hdr = (struct ips_message_header *)&rc[1];
966                 /*
967                  * could make a network order version of IPATH_KD_QP, and
968                  * do the obvious shift before masking to speed this up.
969                  */
970                 qp = ntohl(hdr->bth[1]) & 0xffffff;
971                 bthbytes = (u8 *) hdr->bth;
972
973                 eflags = ips_get_hdr_err_flags((__le32 *) rc);
974                 etype = ips_get_rcv_type((__le32 *) rc);
975                 /* total length */
976                 tlen = ips_get_length_in_bytes((__le32 *) rc);
977                 ebuf = NULL;
978                 if (etype != RCVHQ_RCV_TYPE_EXPECTED) {
979                         /*
980                          * it turns out that the chips uses an eager buffer
981                          * for all non-expected packets, whether it "needs"
982                          * one or not.  So always get the index, but don't
983                          * set ebuf (so we try to copy data) unless the
984                          * length requires it.
985                          */
986                         etail = ips_get_index((__le32 *) rc);
987                         if (tlen > sizeof(*hdr) ||
988                             etype == RCVHQ_RCV_TYPE_NON_KD)
989                                 ebuf = ipath_get_egrbuf(dd, etail, 0);
990                 }
991
992                 /*
993                  * both tiderr and ipathhdrerr are set for all plain IB
994                  * packets; only ipathhdrerr should be set.
995                  */
996
997                 if (etype != RCVHQ_RCV_TYPE_NON_KD && etype !=
998                     RCVHQ_RCV_TYPE_ERROR && ips_get_ipath_ver(
999                             hdr->iph.ver_port_tid_offset) !=
1000                     IPS_PROTO_VERSION) {
1001                         ipath_cdbg(PKT, "Bad InfiniPath protocol version "
1002                                    "%x\n", etype);
1003                 }
1004
1005                 if (eflags & ~(INFINIPATH_RHF_H_TIDERR |
1006                                INFINIPATH_RHF_H_IHDRERR)) {
1007                         get_rhf_errstring(eflags, emsg, sizeof emsg);
1008                         ipath_cdbg(PKT, "RHFerrs %x hdrqtail=%x typ=%u "
1009                                    "tlen=%x opcode=%x egridx=%x: %s\n",
1010                                    eflags, l, etype, tlen, bthbytes[0],
1011                                    ips_get_index((__le32 *) rc), emsg);
1012                 } else if (etype == RCVHQ_RCV_TYPE_NON_KD) {
1013                                 int ret = __ipath_verbs_rcv(dd, rc + 1,
1014                                                             ebuf, tlen);
1015                                 if (ret == -ENODEV)
1016                                         ipath_cdbg(VERBOSE,
1017                                                    "received IB packet, "
1018                                                    "not SMA (QP=%x)\n", qp);
1019                 } else if (etype == RCVHQ_RCV_TYPE_EAGER) {
1020                         if (qp == IPATH_KD_QP &&
1021                             bthbytes[0] == ipath_layer_rcv_opcode &&
1022                             ebuf)
1023                                 ipath_rcv_layer(dd, etail, tlen,
1024                                                 (struct ether_header *)hdr);
1025                         else
1026                                 ipath_cdbg(PKT, "typ %x, opcode %x (eager, "
1027                                            "qp=%x), len %x; ignored\n",
1028                                            etype, bthbytes[0], qp, tlen);
1029                 }
1030                 else if (etype == RCVHQ_RCV_TYPE_EXPECTED)
1031                         ipath_dbg("Bug: Expected TID, opcode %x; ignored\n",
1032                                   be32_to_cpu(hdr->bth[0]) & 0xff);
1033                 else if (eflags & (INFINIPATH_RHF_H_TIDERR |
1034                                    INFINIPATH_RHF_H_IHDRERR)) {
1035                         /*
1036                          * This is a type 3 packet, only the LRH is in the
1037                          * rcvhdrq, the rest of the header is in the eager
1038                          * buffer.
1039                          */
1040                         u8 opcode;
1041                         if (ebuf) {
1042                                 bthbytes = (u8 *) ebuf;
1043                                 opcode = *bthbytes;
1044                         }
1045                         else
1046                                 opcode = 0;
1047                         get_rhf_errstring(eflags, emsg, sizeof emsg);
1048                         ipath_dbg("Err %x (%s), opcode %x, egrbuf %x, "
1049                                   "len %x\n", eflags, emsg, opcode, etail,
1050                                   tlen);
1051                 } else {
1052                         /*
1053                          * error packet, type of error  unknown.
1054                          * Probably type 3, but we don't know, so don't
1055                          * even try to print the opcode, etc.
1056                          */
1057                         ipath_dbg("Error Pkt, but no eflags! egrbuf %x, "
1058                                   "len %x\nhdrq@%lx;hdrq+%x rhf: %llx; "
1059                                   "hdr %llx %llx %llx %llx %llx\n",
1060                                   etail, tlen, (unsigned long) rc, l,
1061                                   (unsigned long long) rc[0],
1062                                   (unsigned long long) rc[1],
1063                                   (unsigned long long) rc[2],
1064                                   (unsigned long long) rc[3],
1065                                   (unsigned long long) rc[4],
1066                                   (unsigned long long) rc[5]);
1067                 }
1068                 l += rsize;
1069                 if (l >= maxcnt)
1070                         l = 0;
1071                 /*
1072                  * update for each packet, to help prevent overflows if we
1073                  * have lots of packets.
1074                  */
1075                 (void)ipath_write_ureg(dd, ur_rcvhdrhead,
1076                                        dd->ipath_rhdrhead_intr_off | l, 0);
1077                 if (etype != RCVHQ_RCV_TYPE_EXPECTED)
1078                         (void)ipath_write_ureg(dd, ur_rcvegrindexhead,
1079                                                etail, 0);
1080         }
1081
1082         pkttot += i;
1083
1084         dd->ipath_port0head = l;
1085
1086         if (hdrqtail != (u32)le64_to_cpu(*dd->ipath_hdrqtailptr))
1087                 /* more arrived while we handled first batch */
1088                 goto gotmore;
1089
1090         if (pkttot > ipath_stats.sps_maxpkts_call)
1091                 ipath_stats.sps_maxpkts_call = pkttot;
1092         ipath_stats.sps_port0pkts += pkttot;
1093         ipath_stats.sps_avgpkts_call =
1094                 ipath_stats.sps_port0pkts / ++totcalls;
1095
1096 done:
1097         clear_bit(0, &dd->ipath_rcv_pending);
1098         smp_mb__after_clear_bit();
1099
1100 bail:;
1101 }
1102
1103 /**
1104  * ipath_update_pio_bufs - update shadow copy of the PIO availability map
1105  * @dd: the infinipath device
1106  *
1107  * called whenever our local copy indicates we have run out of send buffers
1108  * NOTE: This can be called from interrupt context by some code
1109  * and from non-interrupt context by ipath_getpiobuf().
1110  */
1111
1112 static void ipath_update_pio_bufs(struct ipath_devdata *dd)
1113 {
1114         unsigned long flags;
1115         int i;
1116         const unsigned piobregs = (unsigned)dd->ipath_pioavregs;
1117
1118         /* If the generation (check) bits have changed, then we update the
1119          * busy bit for the corresponding PIO buffer.  This algorithm will
1120          * modify positions to the value they already have in some cases
1121          * (i.e., no change), but it's faster than changing only the bits
1122          * that have changed.
1123          *
1124          * We would like to do this atomicly, to avoid spinlocks in the
1125          * critical send path, but that's not really possible, given the
1126          * type of changes, and that this routine could be called on
1127          * multiple cpu's simultaneously, so we lock in this routine only,
1128          * to avoid conflicting updates; all we change is the shadow, and
1129          * it's a single 64 bit memory location, so by definition the update
1130          * is atomic in terms of what other cpu's can see in testing the
1131          * bits.  The spin_lock overhead isn't too bad, since it only
1132          * happens when all buffers are in use, so only cpu overhead, not
1133          * latency or bandwidth is affected.
1134          */
1135 #define _IPATH_ALL_CHECKBITS 0x5555555555555555ULL
1136         if (!dd->ipath_pioavailregs_dma) {
1137                 ipath_dbg("Update shadow pioavail, but regs_dma NULL!\n");
1138                 return;
1139         }
1140         if (ipath_debug & __IPATH_VERBDBG) {
1141                 /* only if packet debug and verbose */
1142                 volatile __le64 *dma = dd->ipath_pioavailregs_dma;
1143                 unsigned long *shadow = dd->ipath_pioavailshadow;
1144
1145                 ipath_cdbg(PKT, "Refill avail, dma0=%llx shad0=%lx, "
1146                            "d1=%llx s1=%lx, d2=%llx s2=%lx, d3=%llx "
1147                            "s3=%lx\n",
1148                            (unsigned long long) le64_to_cpu(dma[0]),
1149                            shadow[0],
1150                            (unsigned long long) le64_to_cpu(dma[1]),
1151                            shadow[1],
1152                            (unsigned long long) le64_to_cpu(dma[2]),
1153                            shadow[2],
1154                            (unsigned long long) le64_to_cpu(dma[3]),
1155                            shadow[3]);
1156                 if (piobregs > 4)
1157                         ipath_cdbg(
1158                                 PKT, "2nd group, dma4=%llx shad4=%lx, "
1159                                 "d5=%llx s5=%lx, d6=%llx s6=%lx, "
1160                                 "d7=%llx s7=%lx\n",
1161                                 (unsigned long long) le64_to_cpu(dma[4]),
1162                                 shadow[4],
1163                                 (unsigned long long) le64_to_cpu(dma[5]),
1164                                 shadow[5],
1165                                 (unsigned long long) le64_to_cpu(dma[6]),
1166                                 shadow[6],
1167                                 (unsigned long long) le64_to_cpu(dma[7]),
1168                                 shadow[7]);
1169         }
1170         spin_lock_irqsave(&ipath_pioavail_lock, flags);
1171         for (i = 0; i < piobregs; i++) {
1172                 u64 pchbusy, pchg, piov, pnew;
1173                 /*
1174                  * Chip Errata: bug 6641; even and odd qwords>3 are swapped
1175                  */
1176                 if (i > 3) {
1177                         if (i & 1)
1178                                 piov = le64_to_cpu(
1179                                         dd->ipath_pioavailregs_dma[i - 1]);
1180                         else
1181                                 piov = le64_to_cpu(
1182                                         dd->ipath_pioavailregs_dma[i + 1]);
1183                 } else
1184                         piov = le64_to_cpu(dd->ipath_pioavailregs_dma[i]);
1185                 pchg = _IPATH_ALL_CHECKBITS &
1186                         ~(dd->ipath_pioavailshadow[i] ^ piov);
1187                 pchbusy = pchg << INFINIPATH_SENDPIOAVAIL_BUSY_SHIFT;
1188                 if (pchg && (pchbusy & dd->ipath_pioavailshadow[i])) {
1189                         pnew = dd->ipath_pioavailshadow[i] & ~pchbusy;
1190                         pnew |= piov & pchbusy;
1191                         dd->ipath_pioavailshadow[i] = pnew;
1192                 }
1193         }
1194         spin_unlock_irqrestore(&ipath_pioavail_lock, flags);
1195 }
1196
1197 /**
1198  * ipath_setrcvhdrsize - set the receive header size
1199  * @dd: the infinipath device
1200  * @rhdrsize: the receive header size
1201  *
1202  * called from user init code, and also layered driver init
1203  */
1204 int ipath_setrcvhdrsize(struct ipath_devdata *dd, unsigned rhdrsize)
1205 {
1206         int ret = 0;
1207
1208         if (dd->ipath_flags & IPATH_RCVHDRSZ_SET) {
1209                 if (dd->ipath_rcvhdrsize != rhdrsize) {
1210                         dev_info(&dd->pcidev->dev,
1211                                  "Error: can't set protocol header "
1212                                  "size %u, already %u\n",
1213                                  rhdrsize, dd->ipath_rcvhdrsize);
1214                         ret = -EAGAIN;
1215                 } else
1216                         ipath_cdbg(VERBOSE, "Reuse same protocol header "
1217                                    "size %u\n", dd->ipath_rcvhdrsize);
1218         } else if (rhdrsize > (dd->ipath_rcvhdrentsize -
1219                                (sizeof(u64) / sizeof(u32)))) {
1220                 ipath_dbg("Error: can't set protocol header size %u "
1221                           "(> max %u)\n", rhdrsize,
1222                           dd->ipath_rcvhdrentsize -
1223                           (u32) (sizeof(u64) / sizeof(u32)));
1224                 ret = -EOVERFLOW;
1225         } else {
1226                 dd->ipath_flags |= IPATH_RCVHDRSZ_SET;
1227                 dd->ipath_rcvhdrsize = rhdrsize;
1228                 ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvhdrsize,
1229                                  dd->ipath_rcvhdrsize);
1230                 ipath_cdbg(VERBOSE, "Set protocol header size to %u\n",
1231                            dd->ipath_rcvhdrsize);
1232         }
1233         return ret;
1234 }
1235
1236 /**
1237  * ipath_getpiobuf - find an available pio buffer
1238  * @dd: the infinipath device
1239  * @pbufnum: the buffer number is placed here
1240  *
1241  * do appropriate marking as busy, etc.
1242  * returns buffer number if one found (>=0), negative number is error.
1243  * Used by ipath_sma_send_pkt and ipath_layer_send
1244  */
1245 u32 __iomem *ipath_getpiobuf(struct ipath_devdata *dd, u32 * pbufnum)
1246 {
1247         int i, j, starti, updated = 0;
1248         unsigned piobcnt, iter;
1249         unsigned long flags;
1250         unsigned long *shadow = dd->ipath_pioavailshadow;
1251         u32 __iomem *buf;
1252
1253         piobcnt = (unsigned)(dd->ipath_piobcnt2k
1254                              + dd->ipath_piobcnt4k);
1255         starti = dd->ipath_lastport_piobuf;
1256         iter = piobcnt - starti;
1257         if (dd->ipath_upd_pio_shadow) {
1258                 /*
1259                  * Minor optimization.  If we had no buffers on last call,
1260                  * start out by doing the update; continue and do scan even
1261                  * if no buffers were updated, to be paranoid
1262                  */
1263                 ipath_update_pio_bufs(dd);
1264                 /* we scanned here, don't do it at end of scan */
1265                 updated = 1;
1266                 i = starti;
1267         } else
1268                 i = dd->ipath_lastpioindex;
1269
1270 rescan:
1271         /*
1272          * while test_and_set_bit() is atomic, we do that and then the
1273          * change_bit(), and the pair is not.  See if this is the cause
1274          * of the remaining armlaunch errors.
1275          */
1276         spin_lock_irqsave(&ipath_pioavail_lock, flags);
1277         for (j = 0; j < iter; j++, i++) {
1278                 if (i >= piobcnt)
1279                         i = starti;
1280                 /*
1281                  * To avoid bus lock overhead, we first find a candidate
1282                  * buffer, then do the test and set, and continue if that
1283                  * fails.
1284                  */
1285                 if (test_bit((2 * i) + 1, shadow) ||
1286                     test_and_set_bit((2 * i) + 1, shadow))
1287                         continue;
1288                 /* flip generation bit */
1289                 change_bit(2 * i, shadow);
1290                 break;
1291         }
1292         spin_unlock_irqrestore(&ipath_pioavail_lock, flags);
1293
1294         if (j == iter) {
1295                 volatile __le64 *dma = dd->ipath_pioavailregs_dma;
1296
1297                 /*
1298                  * first time through; shadow exhausted, but may be real
1299                  * buffers available, so go see; if any updated, rescan
1300                  * (once)
1301                  */
1302                 if (!updated) {
1303                         ipath_update_pio_bufs(dd);
1304                         updated = 1;
1305                         i = starti;
1306                         goto rescan;
1307                 }
1308                 dd->ipath_upd_pio_shadow = 1;
1309                 /*
1310                  * not atomic, but if we lose one once in a while, that's OK
1311                  */
1312                 ipath_stats.sps_nopiobufs++;
1313                 if (!(++dd->ipath_consec_nopiobuf % 100000)) {
1314                         ipath_dbg(
1315                                 "%u pio sends with no bufavail; dmacopy: "
1316                                 "%llx %llx %llx %llx; shadow:  "
1317                                 "%lx %lx %lx %lx\n",
1318                                 dd->ipath_consec_nopiobuf,
1319                                 (unsigned long long) le64_to_cpu(dma[0]),
1320                                 (unsigned long long) le64_to_cpu(dma[1]),
1321                                 (unsigned long long) le64_to_cpu(dma[2]),
1322                                 (unsigned long long) le64_to_cpu(dma[3]),
1323                                 shadow[0], shadow[1], shadow[2],
1324                                 shadow[3]);
1325                         /*
1326                          * 4 buffers per byte, 4 registers above, cover rest
1327                          * below
1328                          */
1329                         if ((dd->ipath_piobcnt2k + dd->ipath_piobcnt4k) >
1330                             (sizeof(shadow[0]) * 4 * 4))
1331                                 ipath_dbg("2nd group: dmacopy: %llx %llx "
1332                                           "%llx %llx; shadow: %lx %lx "
1333                                           "%lx %lx\n",
1334                                           (unsigned long long)
1335                                           le64_to_cpu(dma[4]),
1336                                           (unsigned long long)
1337                                           le64_to_cpu(dma[5]),
1338                                           (unsigned long long)
1339                                           le64_to_cpu(dma[6]),
1340                                           (unsigned long long)
1341                                           le64_to_cpu(dma[7]),
1342                                           shadow[4], shadow[5],
1343                                           shadow[6], shadow[7]);
1344                 }
1345                 buf = NULL;
1346                 goto bail;
1347         }
1348
1349         if (updated)
1350                 /*
1351                  * ran out of bufs, now some (at least this one we just
1352                  * got) are now available, so tell the layered driver.
1353                  */
1354                 __ipath_layer_intr(dd, IPATH_LAYER_INT_SEND_CONTINUE);
1355
1356         /*
1357          * set next starting place.  Since it's just an optimization,
1358          * it doesn't matter who wins on this, so no locking
1359          */
1360         dd->ipath_lastpioindex = i + 1;
1361         if (dd->ipath_upd_pio_shadow)
1362                 dd->ipath_upd_pio_shadow = 0;
1363         if (dd->ipath_consec_nopiobuf)
1364                 dd->ipath_consec_nopiobuf = 0;
1365         if (i < dd->ipath_piobcnt2k)
1366                 buf = (u32 __iomem *) (dd->ipath_pio2kbase +
1367                                        i * dd->ipath_palign);
1368         else
1369                 buf = (u32 __iomem *)
1370                         (dd->ipath_pio4kbase +
1371                          (i - dd->ipath_piobcnt2k) * dd->ipath_4kalign);
1372         ipath_cdbg(VERBOSE, "Return piobuf%u %uk @ %p\n",
1373                    i, (i < dd->ipath_piobcnt2k) ? 2 : 4, buf);
1374         if (pbufnum)
1375                 *pbufnum = i;
1376
1377 bail:
1378         return buf;
1379 }
1380
1381 /**
1382  * ipath_create_rcvhdrq - create a receive header queue
1383  * @dd: the infinipath device
1384  * @pd: the port data
1385  *
1386  * this *must* be physically contiguous memory, and for now,
1387  * that limits it to what kmalloc can do.
1388  */
1389 int ipath_create_rcvhdrq(struct ipath_devdata *dd,
1390                          struct ipath_portdata *pd)
1391 {
1392         int ret = 0, amt;
1393
1394         amt = ALIGN(dd->ipath_rcvhdrcnt * dd->ipath_rcvhdrentsize *
1395                     sizeof(u32), PAGE_SIZE);
1396         if (!pd->port_rcvhdrq) {
1397                 /*
1398                  * not using REPEAT isn't viable; at 128KB, we can easily
1399                  * fail this.  The problem with REPEAT is we can block here
1400                  * "forever".  There isn't an inbetween, unfortunately.  We
1401                  * could reduce the risk by never freeing the rcvhdrq except
1402                  * at unload, but even then, the first time a port is used,
1403                  * we could delay for some time...
1404                  */
1405                 gfp_t gfp_flags = GFP_USER | __GFP_COMP;
1406
1407                 pd->port_rcvhdrq = dma_alloc_coherent(
1408                         &dd->pcidev->dev, amt, &pd->port_rcvhdrq_phys,
1409                         gfp_flags);
1410
1411                 if (!pd->port_rcvhdrq) {
1412                         ipath_dev_err(dd, "attempt to allocate %d bytes "
1413                                       "for port %u rcvhdrq failed\n",
1414                                       amt, pd->port_port);
1415                         ret = -ENOMEM;
1416                         goto bail;
1417                 }
1418
1419                 pd->port_rcvhdrq_size = amt;
1420
1421                 ipath_cdbg(VERBOSE, "%d pages at %p (phys %lx) size=%lu "
1422                            "for port %u rcvhdr Q\n",
1423                            amt >> PAGE_SHIFT, pd->port_rcvhdrq,
1424                            (unsigned long) pd->port_rcvhdrq_phys,
1425                            (unsigned long) pd->port_rcvhdrq_size,
1426                            pd->port_port);
1427         } else {
1428                 /*
1429                  * clear for security, sanity, and/or debugging, each
1430                  * time we reuse
1431                  */
1432                 memset(pd->port_rcvhdrq, 0, amt);
1433         }
1434
1435         /*
1436          * tell chip each time we init it, even if we are re-using previous
1437          * memory (we zero it at process close)
1438          */
1439         ipath_cdbg(VERBOSE, "writing port %d rcvhdraddr as %lx\n",
1440                    pd->port_port, (unsigned long) pd->port_rcvhdrq_phys);
1441         ipath_write_kreg_port(dd, dd->ipath_kregs->kr_rcvhdraddr,
1442                               pd->port_port, pd->port_rcvhdrq_phys);
1443
1444         ret = 0;
1445 bail:
1446         return ret;
1447 }
1448
1449 int ipath_waitfor_complete(struct ipath_devdata *dd, ipath_kreg reg_id,
1450                            u64 bits_to_wait_for, u64 * valp)
1451 {
1452         unsigned long timeout;
1453         u64 lastval, val;
1454         int ret;
1455
1456         lastval = ipath_read_kreg64(dd, reg_id);
1457         /* wait a ridiculously long time */
1458         timeout = jiffies + msecs_to_jiffies(5);
1459         do {
1460                 val = ipath_read_kreg64(dd, reg_id);
1461                 /* set so they have something, even on failures. */
1462                 *valp = val;
1463                 if ((val & bits_to_wait_for) == bits_to_wait_for) {
1464                         ret = 0;
1465                         break;
1466                 }
1467                 if (val != lastval)
1468                         ipath_cdbg(VERBOSE, "Changed from %llx to %llx, "
1469                                    "waiting for %llx bits\n",
1470                                    (unsigned long long) lastval,
1471                                    (unsigned long long) val,
1472                                    (unsigned long long) bits_to_wait_for);
1473                 cond_resched();
1474                 if (time_after(jiffies, timeout)) {
1475                         ipath_dbg("Didn't get bits %llx in register 0x%x, "
1476                                   "got %llx\n",
1477                                   (unsigned long long) bits_to_wait_for,
1478                                   reg_id, (unsigned long long) *valp);
1479                         ret = -ENODEV;
1480                         break;
1481                 }
1482         } while (1);
1483
1484         return ret;
1485 }
1486
1487 /**
1488  * ipath_waitfor_mdio_cmdready - wait for last command to complete
1489  * @dd: the infinipath device
1490  *
1491  * Like ipath_waitfor_complete(), but we wait for the CMDVALID bit to go
1492  * away indicating the last command has completed.  It doesn't return data
1493  */
1494 int ipath_waitfor_mdio_cmdready(struct ipath_devdata *dd)
1495 {
1496         unsigned long timeout;
1497         u64 val;
1498         int ret;
1499
1500         /* wait a ridiculously long time */
1501         timeout = jiffies + msecs_to_jiffies(5);
1502         do {
1503                 val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_mdio);
1504                 if (!(val & IPATH_MDIO_CMDVALID)) {
1505                         ret = 0;
1506                         break;
1507                 }
1508                 cond_resched();
1509                 if (time_after(jiffies, timeout)) {
1510                         ipath_dbg("CMDVALID stuck in mdio reg? (%llx)\n",
1511                                   (unsigned long long) val);
1512                         ret = -ENODEV;
1513                         break;
1514                 }
1515         } while (1);
1516
1517         return ret;
1518 }
1519
1520 void ipath_set_ib_lstate(struct ipath_devdata *dd, int which)
1521 {
1522         static const char *what[4] = {
1523                 [0] = "DOWN",
1524                 [INFINIPATH_IBCC_LINKCMD_INIT] = "INIT",
1525                 [INFINIPATH_IBCC_LINKCMD_ARMED] = "ARMED",
1526                 [INFINIPATH_IBCC_LINKCMD_ACTIVE] = "ACTIVE"
1527         };
1528         ipath_cdbg(SMA, "Trying to move unit %u to %s, current ltstate "
1529                    "is %s\n", dd->ipath_unit,
1530                    what[(which >> INFINIPATH_IBCC_LINKCMD_SHIFT) &
1531                         INFINIPATH_IBCC_LINKCMD_MASK],
1532                    ipath_ibcstatus_str[
1533                            (ipath_read_kreg64
1534                             (dd, dd->ipath_kregs->kr_ibcstatus) >>
1535                             INFINIPATH_IBCS_LINKTRAININGSTATE_SHIFT) &
1536                            INFINIPATH_IBCS_LINKTRAININGSTATE_MASK]);
1537
1538         ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
1539                          dd->ipath_ibcctrl | which);
1540 }
1541
1542 /**
1543  * ipath_read_kreg64_port - read a device's per-port 64-bit kernel register
1544  * @dd: the infinipath device
1545  * @regno: the register number to read
1546  * @port: the port containing the register
1547  *
1548  * Registers that vary with the chip implementation constants (port)
1549  * use this routine.
1550  */
1551 u64 ipath_read_kreg64_port(const struct ipath_devdata *dd, ipath_kreg regno,
1552                            unsigned port)
1553 {
1554         u16 where;
1555
1556         if (port < dd->ipath_portcnt &&
1557             (regno == dd->ipath_kregs->kr_rcvhdraddr ||
1558              regno == dd->ipath_kregs->kr_rcvhdrtailaddr))
1559                 where = regno + port;
1560         else
1561                 where = -1;
1562
1563         return ipath_read_kreg64(dd, where);
1564 }
1565
1566 /**
1567  * ipath_write_kreg_port - write a device's per-port 64-bit kernel register
1568  * @dd: the infinipath device
1569  * @regno: the register number to write
1570  * @port: the port containing the register
1571  * @value: the value to write
1572  *
1573  * Registers that vary with the chip implementation constants (port)
1574  * use this routine.
1575  */
1576 void ipath_write_kreg_port(const struct ipath_devdata *dd, ipath_kreg regno,
1577                           unsigned port, u64 value)
1578 {
1579         u16 where;
1580
1581         if (port < dd->ipath_portcnt &&
1582             (regno == dd->ipath_kregs->kr_rcvhdraddr ||
1583              regno == dd->ipath_kregs->kr_rcvhdrtailaddr))
1584                 where = regno + port;
1585         else
1586                 where = -1;
1587
1588         ipath_write_kreg(dd, where, value);
1589 }
1590
1591 /**
1592  * ipath_shutdown_device - shut down a device
1593  * @dd: the infinipath device
1594  *
1595  * This is called to make the device quiet when we are about to
1596  * unload the driver, and also when the device is administratively
1597  * disabled.   It does not free any data structures.
1598  * Everything it does has to be setup again by ipath_init_chip(dd,1)
1599  */
1600 void ipath_shutdown_device(struct ipath_devdata *dd)
1601 {
1602         u64 val;
1603
1604         ipath_dbg("Shutting down the device\n");
1605
1606         dd->ipath_flags |= IPATH_LINKUNK;
1607         dd->ipath_flags &= ~(IPATH_INITTED | IPATH_LINKDOWN |
1608                              IPATH_LINKINIT | IPATH_LINKARMED |
1609                              IPATH_LINKACTIVE);
1610         *dd->ipath_statusp &= ~(IPATH_STATUS_IB_CONF |
1611                                 IPATH_STATUS_IB_READY);
1612
1613         /* mask interrupts, but not errors */
1614         ipath_write_kreg(dd, dd->ipath_kregs->kr_intmask, 0ULL);
1615
1616         dd->ipath_rcvctrl = 0;
1617         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
1618                          dd->ipath_rcvctrl);
1619
1620         /*
1621          * gracefully stop all sends allowing any in progress to trickle out
1622          * first.
1623          */
1624         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl, 0ULL);
1625         /* flush it */
1626         val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
1627         /*
1628          * enough for anything that's going to trickle out to have actually
1629          * done so.
1630          */
1631         udelay(5);
1632
1633         /*
1634          * abort any armed or launched PIO buffers that didn't go. (self
1635          * clearing).  Will cause any packet currently being transmitted to
1636          * go out with an EBP, and may also cause a short packet error on
1637          * the receiver.
1638          */
1639         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
1640                          INFINIPATH_S_ABORT);
1641
1642         ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKINITCMD_DISABLE <<
1643                             INFINIPATH_IBCC_LINKINITCMD_SHIFT);
1644
1645         /*
1646          * we are shutting down, so tell the layered driver.  We don't do
1647          * this on just a link state change, much like ethernet, a cable
1648          * unplug, etc. doesn't change driver state
1649          */
1650         ipath_layer_intr(dd, IPATH_LAYER_INT_IF_DOWN);
1651
1652         /* disable IBC */
1653         dd->ipath_control &= ~INFINIPATH_C_LINKENABLE;
1654         ipath_write_kreg(dd, dd->ipath_kregs->kr_control,
1655                          dd->ipath_control | INFINIPATH_C_FREEZEMODE);
1656
1657         /*
1658          * clear SerdesEnable and turn the leds off; do this here because
1659          * we are unloading, so don't count on interrupts to move along
1660          * Turn the LEDs off explictly for the same reason.
1661          */
1662         dd->ipath_f_quiet_serdes(dd);
1663         dd->ipath_f_setextled(dd, 0, 0);
1664
1665         if (dd->ipath_stats_timer_active) {
1666                 del_timer_sync(&dd->ipath_stats_timer);
1667                 dd->ipath_stats_timer_active = 0;
1668         }
1669
1670         /*
1671          * clear all interrupts and errors, so that the next time the driver
1672          * is loaded or device is enabled, we know that whatever is set
1673          * happened while we were unloaded
1674          */
1675         ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrclear,
1676                          ~0ULL & ~INFINIPATH_HWE_MEMBISTFAILED);
1677         ipath_write_kreg(dd, dd->ipath_kregs->kr_errorclear, -1LL);
1678         ipath_write_kreg(dd, dd->ipath_kregs->kr_intclear, -1LL);
1679 }
1680
1681 /**
1682  * ipath_free_pddata - free a port's allocated data
1683  * @dd: the infinipath device
1684  * @port: the port
1685  * @freehdrq: free the port data structure if true
1686  *
1687  * when closing, free up any allocated data for a port, if the
1688  * reference count goes to zero
1689  * Note: this also optionally frees the portdata itself!
1690  * Any changes here have to be matched up with the reinit case
1691  * of ipath_init_chip(), which calls this routine on reinit after reset.
1692  */
1693 void ipath_free_pddata(struct ipath_devdata *dd, u32 port, int freehdrq)
1694 {
1695         struct ipath_portdata *pd = dd->ipath_pd[port];
1696
1697         if (!pd)
1698                 return;
1699         if (freehdrq)
1700                 /*
1701                  * only clear and free portdata if we are going to also
1702                  * release the hdrq, otherwise we leak the hdrq on each
1703                  * open/close cycle
1704                  */
1705                 dd->ipath_pd[port] = NULL;
1706         if (freehdrq && pd->port_rcvhdrq) {
1707                 ipath_cdbg(VERBOSE, "free closed port %d rcvhdrq @ %p "
1708                            "(size=%lu)\n", pd->port_port, pd->port_rcvhdrq,
1709                            (unsigned long) pd->port_rcvhdrq_size);
1710                 dma_free_coherent(&dd->pcidev->dev, pd->port_rcvhdrq_size,
1711                                   pd->port_rcvhdrq, pd->port_rcvhdrq_phys);
1712                 pd->port_rcvhdrq = NULL;
1713         }
1714         if (port && pd->port_rcvegrbuf) {
1715                 /* always free this */
1716                 if (pd->port_rcvegrbuf) {
1717                         unsigned e;
1718
1719                         for (e = 0; e < pd->port_rcvegrbuf_chunks; e++) {
1720                                 void *base = pd->port_rcvegrbuf[e];
1721                                 size_t size = pd->port_rcvegrbuf_size;
1722
1723                                 ipath_cdbg(VERBOSE, "egrbuf free(%p, %lu), "
1724                                            "chunk %u/%u\n", base,
1725                                            (unsigned long) size,
1726                                            e, pd->port_rcvegrbuf_chunks);
1727                                 dma_free_coherent(
1728                                         &dd->pcidev->dev, size, base,
1729                                         pd->port_rcvegrbuf_phys[e]);
1730                         }
1731                         vfree(pd->port_rcvegrbuf);
1732                         pd->port_rcvegrbuf = NULL;
1733                         vfree(pd->port_rcvegrbuf_phys);
1734                         pd->port_rcvegrbuf_phys = NULL;
1735                 }
1736                 pd->port_rcvegrbuf_chunks = 0;
1737         } else if (port == 0 && dd->ipath_port0_skbs) {
1738                 unsigned e;
1739                 struct sk_buff **skbs = dd->ipath_port0_skbs;
1740
1741                 dd->ipath_port0_skbs = NULL;
1742                 ipath_cdbg(VERBOSE, "free closed port %d ipath_port0_skbs "
1743                            "@ %p\n", pd->port_port, skbs);
1744                 for (e = 0; e < dd->ipath_rcvegrcnt; e++)
1745                         if (skbs[e])
1746                                 dev_kfree_skb(skbs[e]);
1747                 vfree(skbs);
1748         }
1749         if (freehdrq) {
1750                 kfree(pd->port_tid_pg_list);
1751                 kfree(pd);
1752         }
1753 }
1754
1755 static int __init infinipath_init(void)
1756 {
1757         int ret;
1758
1759         ipath_dbg(KERN_INFO DRIVER_LOAD_MSG "%s", ipath_core_version);
1760
1761         /*
1762          * These must be called before the driver is registered with
1763          * the PCI subsystem.
1764          */
1765         idr_init(&unit_table);
1766         if (!idr_pre_get(&unit_table, GFP_KERNEL)) {
1767                 ret = -ENOMEM;
1768                 goto bail;
1769         }
1770
1771         ret = pci_register_driver(&ipath_driver);
1772         if (ret < 0) {
1773                 printk(KERN_ERR IPATH_DRV_NAME
1774                        ": Unable to register driver: error %d\n", -ret);
1775                 goto bail_unit;
1776         }
1777
1778         ret = ipath_driver_create_group(&ipath_driver.driver);
1779         if (ret < 0) {
1780                 printk(KERN_ERR IPATH_DRV_NAME ": Unable to create driver "
1781                        "sysfs entries: error %d\n", -ret);
1782                 goto bail_pci;
1783         }
1784
1785         ret = ipath_init_ipathfs();
1786         if (ret < 0) {
1787                 printk(KERN_ERR IPATH_DRV_NAME ": Unable to create "
1788                        "ipathfs: error %d\n", -ret);
1789                 goto bail_group;
1790         }
1791
1792         goto bail;
1793
1794 bail_group:
1795         ipath_driver_remove_group(&ipath_driver.driver);
1796
1797 bail_pci:
1798         pci_unregister_driver(&ipath_driver);
1799
1800 bail_unit:
1801         idr_destroy(&unit_table);
1802
1803 bail:
1804         return ret;
1805 }
1806
1807 static void cleanup_device(struct ipath_devdata *dd)
1808 {
1809         int port;
1810
1811         ipath_shutdown_device(dd);
1812
1813         if (*dd->ipath_statusp & IPATH_STATUS_CHIP_PRESENT) {
1814                 /* can't do anything more with chip; needs re-init */
1815                 *dd->ipath_statusp &= ~IPATH_STATUS_CHIP_PRESENT;
1816                 if (dd->ipath_kregbase) {
1817                         /*
1818                          * if we haven't already cleaned up before these are
1819                          * to ensure any register reads/writes "fail" until
1820                          * re-init
1821                          */
1822                         dd->ipath_kregbase = NULL;
1823                         dd->ipath_uregbase = 0;
1824                         dd->ipath_sregbase = 0;
1825                         dd->ipath_cregbase = 0;
1826                         dd->ipath_kregsize = 0;
1827                 }
1828                 ipath_disable_wc(dd);
1829         }
1830
1831         if (dd->ipath_pioavailregs_dma) {
1832                 dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE,
1833                                   (void *) dd->ipath_pioavailregs_dma,
1834                                   dd->ipath_pioavailregs_phys);
1835                 dd->ipath_pioavailregs_dma = NULL;
1836         }
1837
1838         if (dd->ipath_pageshadow) {
1839                 struct page **tmpp = dd->ipath_pageshadow;
1840                 int i, cnt = 0;
1841
1842                 ipath_cdbg(VERBOSE, "Unlocking any expTID pages still "
1843                            "locked\n");
1844                 for (port = 0; port < dd->ipath_cfgports; port++) {
1845                         int port_tidbase = port * dd->ipath_rcvtidcnt;
1846                         int maxtid = port_tidbase + dd->ipath_rcvtidcnt;
1847                         for (i = port_tidbase; i < maxtid; i++) {
1848                                 if (!tmpp[i])
1849                                         continue;
1850                                 ipath_release_user_pages(&tmpp[i], 1);
1851                                 tmpp[i] = NULL;
1852                                 cnt++;
1853                         }
1854                 }
1855                 if (cnt) {
1856                         ipath_stats.sps_pageunlocks += cnt;
1857                         ipath_cdbg(VERBOSE, "There were still %u expTID "
1858                                    "entries locked\n", cnt);
1859                 }
1860                 if (ipath_stats.sps_pagelocks ||
1861                     ipath_stats.sps_pageunlocks)
1862                         ipath_cdbg(VERBOSE, "%llu pages locked, %llu "
1863                                    "unlocked via ipath_m{un}lock\n",
1864                                    (unsigned long long)
1865                                    ipath_stats.sps_pagelocks,
1866                                    (unsigned long long)
1867                                    ipath_stats.sps_pageunlocks);
1868
1869                 ipath_cdbg(VERBOSE, "Free shadow page tid array at %p\n",
1870                            dd->ipath_pageshadow);
1871                 vfree(dd->ipath_pageshadow);
1872                 dd->ipath_pageshadow = NULL;
1873         }
1874
1875         /*
1876          * free any resources still in use (usually just kernel ports)
1877          * at unload
1878          */
1879         for (port = 0; port < dd->ipath_cfgports; port++)
1880                 ipath_free_pddata(dd, port, 1);
1881         kfree(dd->ipath_pd);
1882         /*
1883          * debuggability, in case some cleanup path tries to use it
1884          * after this
1885          */
1886         dd->ipath_pd = NULL;
1887 }
1888
1889 static void __exit infinipath_cleanup(void)
1890 {
1891         struct ipath_devdata *dd, *tmp;
1892         unsigned long flags;
1893
1894         ipath_exit_ipathfs();
1895
1896         ipath_driver_remove_group(&ipath_driver.driver);
1897
1898         spin_lock_irqsave(&ipath_devs_lock, flags);
1899
1900         /*
1901          * turn off rcv, send, and interrupts for all ports, all drivers
1902          * should also hard reset the chip here?
1903          * free up port 0 (kernel) rcvhdr, egr bufs, and eventually tid bufs
1904          * for all versions of the driver, if they were allocated
1905          */
1906         list_for_each_entry_safe(dd, tmp, &ipath_dev_list, ipath_list) {
1907                 spin_unlock_irqrestore(&ipath_devs_lock, flags);
1908
1909                 if (dd->ipath_kregbase)
1910                         cleanup_device(dd);
1911
1912                 if (dd->pcidev) {
1913                         if (dd->pcidev->irq) {
1914                                 ipath_cdbg(VERBOSE,
1915                                            "unit %u free_irq of irq %x\n",
1916                                            dd->ipath_unit, dd->pcidev->irq);
1917                                 free_irq(dd->pcidev->irq, dd);
1918                         } else
1919                                 ipath_dbg("irq is 0, not doing free_irq "
1920                                           "for unit %u\n", dd->ipath_unit);
1921
1922                         /*
1923                          * we check for NULL here, because it's outside
1924                          * the kregbase check, and we need to call it
1925                          * after the free_irq.  Thus it's possible that
1926                          * the function pointers were never initialized.
1927                          */
1928                         if (dd->ipath_f_cleanup)
1929                                 /* clean up chip-specific stuff */
1930                                 dd->ipath_f_cleanup(dd);
1931
1932                         dd->pcidev = NULL;
1933                 }
1934                 spin_lock_irqsave(&ipath_devs_lock, flags);
1935         }
1936
1937         spin_unlock_irqrestore(&ipath_devs_lock, flags);
1938
1939         ipath_cdbg(VERBOSE, "Unregistering pci driver\n");
1940         pci_unregister_driver(&ipath_driver);
1941
1942         idr_destroy(&unit_table);
1943 }
1944
1945 /**
1946  * ipath_reset_device - reset the chip if possible
1947  * @unit: the device to reset
1948  *
1949  * Whether or not reset is successful, we attempt to re-initialize the chip
1950  * (that is, much like a driver unload/reload).  We clear the INITTED flag
1951  * so that the various entry points will fail until we reinitialize.  For
1952  * now, we only allow this if no user ports are open that use chip resources
1953  */
1954 int ipath_reset_device(int unit)
1955 {
1956         int ret, i;
1957         struct ipath_devdata *dd = ipath_lookup(unit);
1958
1959         if (!dd) {
1960                 ret = -ENODEV;
1961                 goto bail;
1962         }
1963
1964         dev_info(&dd->pcidev->dev, "Reset on unit %u requested\n", unit);
1965
1966         if (!dd->ipath_kregbase || !(dd->ipath_flags & IPATH_PRESENT)) {
1967                 dev_info(&dd->pcidev->dev, "Invalid unit number %u or "
1968                          "not initialized or not present\n", unit);
1969                 ret = -ENXIO;
1970                 goto bail;
1971         }
1972
1973         if (dd->ipath_pd)
1974                 for (i = 1; i < dd->ipath_cfgports; i++) {
1975                         if (dd->ipath_pd[i] && dd->ipath_pd[i]->port_cnt) {
1976                                 ipath_dbg("unit %u port %d is in use "
1977                                           "(PID %u cmd %s), can't reset\n",
1978                                           unit, i,
1979                                           dd->ipath_pd[i]->port_pid,
1980                                           dd->ipath_pd[i]->port_comm);
1981                                 ret = -EBUSY;
1982                                 goto bail;
1983                         }
1984                 }
1985
1986         dd->ipath_flags &= ~IPATH_INITTED;
1987         ret = dd->ipath_f_reset(dd);
1988         if (ret != 1)
1989                 ipath_dbg("reset was not successful\n");
1990         ipath_dbg("Trying to reinitialize unit %u after reset attempt\n",
1991                   unit);
1992         ret = ipath_init_chip(dd, 1);
1993         if (ret)
1994                 ipath_dev_err(dd, "Reinitialize unit %u after "
1995                               "reset failed with %d\n", unit, ret);
1996         else
1997                 dev_info(&dd->pcidev->dev, "Reinitialized unit %u after "
1998                          "resetting\n", unit);
1999
2000 bail:
2001         return ret;
2002 }
2003
2004 module_init(infinipath_init);
2005 module_exit(infinipath_cleanup);