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