]> err.no Git - linux-2.6/blob - drivers/infiniband/hw/ipath/ipath_driver.c
IB/ipath: Head of Line blocking vs forward progress of user apps
[linux-2.6] / drivers / infiniband / hw / ipath / ipath_driver.c
1 /*
2  * Copyright (c) 2006, 2007 QLogic Corporation. 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/io.h>
38 #include <linux/delay.h>
39 #include <linux/netdevice.h>
40 #include <linux/vmalloc.h>
41
42 #include "ipath_kernel.h"
43 #include "ipath_verbs.h"
44 #include "ipath_common.h"
45
46 static void ipath_update_pio_bufs(struct ipath_devdata *);
47
48 const char *ipath_get_unit_name(int unit)
49 {
50         static char iname[16];
51         snprintf(iname, sizeof iname, "infinipath%u", unit);
52         return iname;
53 }
54
55 #define DRIVER_LOAD_MSG "QLogic " IPATH_DRV_NAME " loaded: "
56 #define PFX IPATH_DRV_NAME ": "
57
58 /*
59  * The size has to be longer than this string, so we can append
60  * board/chip information to it in the init code.
61  */
62 const char ib_ipath_version[] = IPATH_IDSTR "\n";
63
64 static struct idr unit_table;
65 DEFINE_SPINLOCK(ipath_devs_lock);
66 LIST_HEAD(ipath_dev_list);
67
68 wait_queue_head_t ipath_state_wait;
69
70 unsigned ipath_debug = __IPATH_INFO;
71
72 module_param_named(debug, ipath_debug, uint, S_IWUSR | S_IRUGO);
73 MODULE_PARM_DESC(debug, "mask for debug prints");
74 EXPORT_SYMBOL_GPL(ipath_debug);
75
76 unsigned ipath_mtu4096 = 1; /* max 4KB IB mtu by default, if supported */
77 module_param_named(mtu4096, ipath_mtu4096, uint, S_IRUGO);
78 MODULE_PARM_DESC(mtu4096, "enable MTU of 4096 bytes, if supported");
79
80 static unsigned ipath_hol_timeout_ms = 13000;
81 module_param_named(hol_timeout_ms, ipath_hol_timeout_ms, uint, S_IRUGO);
82 MODULE_PARM_DESC(hol_timeout_ms,
83         "duration of user app suspension after link failure");
84
85 MODULE_LICENSE("GPL");
86 MODULE_AUTHOR("QLogic <support@pathscale.com>");
87 MODULE_DESCRIPTION("QLogic InfiniPath driver");
88
89 const char *ipath_ibcstatus_str[] = {
90         "Disabled",
91         "LinkUp",
92         "PollActive",
93         "PollQuiet",
94         "SleepDelay",
95         "SleepQuiet",
96         "LState6",              /* unused */
97         "LState7",              /* unused */
98         "CfgDebounce",
99         "CfgRcvfCfg",
100         "CfgWaitRmt",
101         "CfgIdle",
102         "RecovRetrain",
103         "LState0xD",            /* unused */
104         "RecovWaitRmt",
105         "RecovIdle",
106 };
107
108 static void __devexit ipath_remove_one(struct pci_dev *);
109 static int __devinit ipath_init_one(struct pci_dev *,
110                                     const struct pci_device_id *);
111
112 /* Only needed for registration, nothing else needs this info */
113 #define PCI_VENDOR_ID_PATHSCALE 0x1fc1
114 #define PCI_DEVICE_ID_INFINIPATH_HT 0xd
115 #define PCI_DEVICE_ID_INFINIPATH_PE800 0x10
116
117 /* Number of seconds before our card status check...  */
118 #define STATUS_TIMEOUT 60
119
120 static const struct pci_device_id ipath_pci_tbl[] = {
121         { PCI_DEVICE(PCI_VENDOR_ID_PATHSCALE, PCI_DEVICE_ID_INFINIPATH_HT) },
122         { PCI_DEVICE(PCI_VENDOR_ID_PATHSCALE, PCI_DEVICE_ID_INFINIPATH_PE800) },
123         { 0, }
124 };
125
126 MODULE_DEVICE_TABLE(pci, ipath_pci_tbl);
127
128 static struct pci_driver ipath_driver = {
129         .name = IPATH_DRV_NAME,
130         .probe = ipath_init_one,
131         .remove = __devexit_p(ipath_remove_one),
132         .id_table = ipath_pci_tbl,
133         .driver = {
134                 .groups = ipath_driver_attr_groups,
135         },
136 };
137
138 static void ipath_check_status(struct work_struct *work)
139 {
140         struct ipath_devdata *dd = container_of(work, struct ipath_devdata,
141                                                 status_work.work);
142
143         /*
144          * If we don't have any interrupts, let the user know and
145          * don't bother checking again.
146          */
147         if (dd->ipath_int_counter == 0)
148                 dev_err(&dd->pcidev->dev, "No interrupts detected.\n");
149 }
150
151 static inline void read_bars(struct ipath_devdata *dd, struct pci_dev *dev,
152                              u32 *bar0, u32 *bar1)
153 {
154         int ret;
155
156         ret = pci_read_config_dword(dev, PCI_BASE_ADDRESS_0, bar0);
157         if (ret)
158                 ipath_dev_err(dd, "failed to read bar0 before enable: "
159                               "error %d\n", -ret);
160
161         ret = pci_read_config_dword(dev, PCI_BASE_ADDRESS_1, bar1);
162         if (ret)
163                 ipath_dev_err(dd, "failed to read bar1 before enable: "
164                               "error %d\n", -ret);
165
166         ipath_dbg("Read bar0 %x bar1 %x\n", *bar0, *bar1);
167 }
168
169 static void ipath_free_devdata(struct pci_dev *pdev,
170                                struct ipath_devdata *dd)
171 {
172         unsigned long flags;
173
174         pci_set_drvdata(pdev, NULL);
175
176         if (dd->ipath_unit != -1) {
177                 spin_lock_irqsave(&ipath_devs_lock, flags);
178                 idr_remove(&unit_table, dd->ipath_unit);
179                 list_del(&dd->ipath_list);
180                 spin_unlock_irqrestore(&ipath_devs_lock, flags);
181         }
182         vfree(dd);
183 }
184
185 static struct ipath_devdata *ipath_alloc_devdata(struct pci_dev *pdev)
186 {
187         unsigned long flags;
188         struct ipath_devdata *dd;
189         int ret;
190
191         if (!idr_pre_get(&unit_table, GFP_KERNEL)) {
192                 dd = ERR_PTR(-ENOMEM);
193                 goto bail;
194         }
195
196         dd = vmalloc(sizeof(*dd));
197         if (!dd) {
198                 dd = ERR_PTR(-ENOMEM);
199                 goto bail;
200         }
201         memset(dd, 0, sizeof(*dd));
202         dd->ipath_unit = -1;
203
204         spin_lock_irqsave(&ipath_devs_lock, flags);
205
206         ret = idr_get_new(&unit_table, dd, &dd->ipath_unit);
207         if (ret < 0) {
208                 printk(KERN_ERR IPATH_DRV_NAME
209                        ": Could not allocate unit ID: error %d\n", -ret);
210                 ipath_free_devdata(pdev, dd);
211                 dd = ERR_PTR(ret);
212                 goto bail_unlock;
213         }
214
215         dd->pcidev = pdev;
216         pci_set_drvdata(pdev, dd);
217
218         INIT_DELAYED_WORK(&dd->status_work, ipath_check_status);
219
220         list_add(&dd->ipath_list, &ipath_dev_list);
221
222 bail_unlock:
223         spin_unlock_irqrestore(&ipath_devs_lock, flags);
224
225 bail:
226         return dd;
227 }
228
229 static inline struct ipath_devdata *__ipath_lookup(int unit)
230 {
231         return idr_find(&unit_table, unit);
232 }
233
234 struct ipath_devdata *ipath_lookup(int unit)
235 {
236         struct ipath_devdata *dd;
237         unsigned long flags;
238
239         spin_lock_irqsave(&ipath_devs_lock, flags);
240         dd = __ipath_lookup(unit);
241         spin_unlock_irqrestore(&ipath_devs_lock, flags);
242
243         return dd;
244 }
245
246 int ipath_count_units(int *npresentp, int *nupp, int *maxportsp)
247 {
248         int nunits, npresent, nup;
249         struct ipath_devdata *dd;
250         unsigned long flags;
251         int maxports;
252
253         nunits = npresent = nup = maxports = 0;
254
255         spin_lock_irqsave(&ipath_devs_lock, flags);
256
257         list_for_each_entry(dd, &ipath_dev_list, ipath_list) {
258                 nunits++;
259                 if ((dd->ipath_flags & IPATH_PRESENT) && dd->ipath_kregbase)
260                         npresent++;
261                 if (dd->ipath_lid &&
262                     !(dd->ipath_flags & (IPATH_DISABLED | IPATH_LINKDOWN
263                                          | IPATH_LINKUNK)))
264                         nup++;
265                 if (dd->ipath_cfgports > maxports)
266                         maxports = dd->ipath_cfgports;
267         }
268
269         spin_unlock_irqrestore(&ipath_devs_lock, flags);
270
271         if (npresentp)
272                 *npresentp = npresent;
273         if (nupp)
274                 *nupp = nup;
275         if (maxportsp)
276                 *maxportsp = maxports;
277
278         return nunits;
279 }
280
281 /*
282  * These next two routines are placeholders in case we don't have per-arch
283  * code for controlling write combining.  If explicit control of write
284  * combining is not available, performance will probably be awful.
285  */
286
287 int __attribute__((weak)) ipath_enable_wc(struct ipath_devdata *dd)
288 {
289         return -EOPNOTSUPP;
290 }
291
292 void __attribute__((weak)) ipath_disable_wc(struct ipath_devdata *dd)
293 {
294 }
295
296 /*
297  * Perform a PIO buffer bandwidth write test, to verify proper system
298  * configuration.  Even when all the setup calls work, occasionally
299  * BIOS or other issues can prevent write combining from working, or
300  * can cause other bandwidth problems to the chip.
301  *
302  * This test simply writes the same buffer over and over again, and
303  * measures close to the peak bandwidth to the chip (not testing
304  * data bandwidth to the wire).   On chips that use an address-based
305  * trigger to send packets to the wire, this is easy.  On chips that
306  * use a count to trigger, we want to make sure that the packet doesn't
307  * go out on the wire, or trigger flow control checks.
308  */
309 static void ipath_verify_pioperf(struct ipath_devdata *dd)
310 {
311         u32 pbnum, cnt, lcnt;
312         u32 __iomem *piobuf;
313         u32 *addr;
314         u64 msecs, emsecs;
315
316         piobuf = ipath_getpiobuf(dd, &pbnum);
317         if (!piobuf) {
318                 dev_info(&dd->pcidev->dev,
319                         "No PIObufs for checking perf, skipping\n");
320                 return;
321         }
322
323         /*
324          * Enough to give us a reasonable test, less than piobuf size, and
325          * likely multiple of store buffer length.
326          */
327         cnt = 1024;
328
329         addr = vmalloc(cnt);
330         if (!addr) {
331                 dev_info(&dd->pcidev->dev,
332                         "Couldn't get memory for checking PIO perf,"
333                         " skipping\n");
334                 goto done;
335         }
336
337         preempt_disable();  /* we want reasonably accurate elapsed time */
338         msecs = 1 + jiffies_to_msecs(jiffies);
339         for (lcnt = 0; lcnt < 10000U; lcnt++) {
340                 /* wait until we cross msec boundary */
341                 if (jiffies_to_msecs(jiffies) >= msecs)
342                         break;
343                 udelay(1);
344         }
345
346         ipath_disable_armlaunch(dd);
347
348         writeq(0, piobuf); /* length 0, no dwords actually sent */
349         ipath_flush_wc();
350
351         /*
352          * this is only roughly accurate, since even with preempt we
353          * still take interrupts that could take a while.   Running for
354          * >= 5 msec seems to get us "close enough" to accurate values
355          */
356         msecs = jiffies_to_msecs(jiffies);
357         for (emsecs = lcnt = 0; emsecs <= 5UL; lcnt++) {
358                 __iowrite32_copy(piobuf + 64, addr, cnt >> 2);
359                 emsecs = jiffies_to_msecs(jiffies) - msecs;
360         }
361
362         /* 1 GiB/sec, slightly over IB SDR line rate */
363         if (lcnt < (emsecs * 1024U))
364                 ipath_dev_err(dd,
365                         "Performance problem: bandwidth to PIO buffers is "
366                         "only %u MiB/sec\n",
367                         lcnt / (u32) emsecs);
368         else
369                 ipath_dbg("PIO buffer bandwidth %u MiB/sec is OK\n",
370                         lcnt / (u32) emsecs);
371
372         preempt_enable();
373
374         vfree(addr);
375
376 done:
377         /* disarm piobuf, so it's available again */
378         ipath_disarm_piobufs(dd, pbnum, 1);
379         ipath_enable_armlaunch(dd);
380 }
381
382 static int __devinit ipath_init_one(struct pci_dev *pdev,
383                                     const struct pci_device_id *ent)
384 {
385         int ret, len, j;
386         struct ipath_devdata *dd;
387         unsigned long long addr;
388         u32 bar0 = 0, bar1 = 0;
389
390         dd = ipath_alloc_devdata(pdev);
391         if (IS_ERR(dd)) {
392                 ret = PTR_ERR(dd);
393                 printk(KERN_ERR IPATH_DRV_NAME
394                        ": Could not allocate devdata: error %d\n", -ret);
395                 goto bail;
396         }
397
398         ipath_cdbg(VERBOSE, "initializing unit #%u\n", dd->ipath_unit);
399
400         ret = pci_enable_device(pdev);
401         if (ret) {
402                 /* This can happen iff:
403                  *
404                  * We did a chip reset, and then failed to reprogram the
405                  * BAR, or the chip reset due to an internal error.  We then
406                  * unloaded the driver and reloaded it.
407                  *
408                  * Both reset cases set the BAR back to initial state.  For
409                  * the latter case, the AER sticky error bit at offset 0x718
410                  * should be set, but the Linux kernel doesn't yet know
411                  * about that, it appears.  If the original BAR was retained
412                  * in the kernel data structures, this may be OK.
413                  */
414                 ipath_dev_err(dd, "enable unit %d failed: error %d\n",
415                               dd->ipath_unit, -ret);
416                 goto bail_devdata;
417         }
418         addr = pci_resource_start(pdev, 0);
419         len = pci_resource_len(pdev, 0);
420         ipath_cdbg(VERBOSE, "regbase (0) %llx len %d pdev->irq %d, vend %x/%x "
421                    "driver_data %lx\n", addr, len, pdev->irq, ent->vendor,
422                    ent->device, ent->driver_data);
423
424         read_bars(dd, pdev, &bar0, &bar1);
425
426         if (!bar1 && !(bar0 & ~0xf)) {
427                 if (addr) {
428                         dev_info(&pdev->dev, "BAR is 0 (probable RESET), "
429                                  "rewriting as %llx\n", addr);
430                         ret = pci_write_config_dword(
431                                 pdev, PCI_BASE_ADDRESS_0, addr);
432                         if (ret) {
433                                 ipath_dev_err(dd, "rewrite of BAR0 "
434                                               "failed: err %d\n", -ret);
435                                 goto bail_disable;
436                         }
437                         ret = pci_write_config_dword(
438                                 pdev, PCI_BASE_ADDRESS_1, addr >> 32);
439                         if (ret) {
440                                 ipath_dev_err(dd, "rewrite of BAR1 "
441                                               "failed: err %d\n", -ret);
442                                 goto bail_disable;
443                         }
444                 } else {
445                         ipath_dev_err(dd, "BAR is 0 (probable RESET), "
446                                       "not usable until reboot\n");
447                         ret = -ENODEV;
448                         goto bail_disable;
449                 }
450         }
451
452         ret = pci_request_regions(pdev, IPATH_DRV_NAME);
453         if (ret) {
454                 dev_info(&pdev->dev, "pci_request_regions unit %u fails: "
455                          "err %d\n", dd->ipath_unit, -ret);
456                 goto bail_disable;
457         }
458
459         ret = pci_set_dma_mask(pdev, DMA_64BIT_MASK);
460         if (ret) {
461                 /*
462                  * if the 64 bit setup fails, try 32 bit.  Some systems
463                  * do not setup 64 bit maps on systems with 2GB or less
464                  * memory installed.
465                  */
466                 ret = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
467                 if (ret) {
468                         dev_info(&pdev->dev,
469                                 "Unable to set DMA mask for unit %u: %d\n",
470                                 dd->ipath_unit, ret);
471                         goto bail_regions;
472                 }
473                 else {
474                         ipath_dbg("No 64bit DMA mask, used 32 bit mask\n");
475                         ret = pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK);
476                         if (ret)
477                                 dev_info(&pdev->dev,
478                                         "Unable to set DMA consistent mask "
479                                         "for unit %u: %d\n",
480                                         dd->ipath_unit, ret);
481
482                 }
483         }
484         else {
485                 ret = pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK);
486                 if (ret)
487                         dev_info(&pdev->dev,
488                                 "Unable to set DMA consistent mask "
489                                 "for unit %u: %d\n",
490                                 dd->ipath_unit, ret);
491         }
492
493         pci_set_master(pdev);
494
495         /*
496          * Save BARs to rewrite after device reset.  Save all 64 bits of
497          * BAR, just in case.
498          */
499         dd->ipath_pcibar0 = addr;
500         dd->ipath_pcibar1 = addr >> 32;
501         dd->ipath_deviceid = ent->device;       /* save for later use */
502         dd->ipath_vendorid = ent->vendor;
503
504         /* setup the chip-specific functions, as early as possible. */
505         switch (ent->device) {
506         case PCI_DEVICE_ID_INFINIPATH_HT:
507 #ifdef CONFIG_HT_IRQ
508                 ipath_init_iba6110_funcs(dd);
509                 break;
510 #else
511                 ipath_dev_err(dd, "QLogic HT device 0x%x cannot work if "
512                               "CONFIG_HT_IRQ is not enabled\n", ent->device);
513                 return -ENODEV;
514 #endif
515         case PCI_DEVICE_ID_INFINIPATH_PE800:
516 #ifdef CONFIG_PCI_MSI
517                 ipath_init_iba6120_funcs(dd);
518                 break;
519 #else
520                 ipath_dev_err(dd, "QLogic PCIE device 0x%x cannot work if "
521                               "CONFIG_PCI_MSI is not enabled\n", ent->device);
522                 return -ENODEV;
523 #endif
524         default:
525                 ipath_dev_err(dd, "Found unknown QLogic deviceid 0x%x, "
526                               "failing\n", ent->device);
527                 return -ENODEV;
528         }
529
530         for (j = 0; j < 6; j++) {
531                 if (!pdev->resource[j].start)
532                         continue;
533                 ipath_cdbg(VERBOSE, "BAR %d start %llx, end %llx, len %llx\n",
534                            j, (unsigned long long)pdev->resource[j].start,
535                            (unsigned long long)pdev->resource[j].end,
536                            (unsigned long long)pci_resource_len(pdev, j));
537         }
538
539         if (!addr) {
540                 ipath_dev_err(dd, "No valid address in BAR 0!\n");
541                 ret = -ENODEV;
542                 goto bail_regions;
543         }
544
545         dd->ipath_pcirev = pdev->revision;
546
547 #if defined(__powerpc__)
548         /* There isn't a generic way to specify writethrough mappings */
549         dd->ipath_kregbase = __ioremap(addr, len,
550                 (_PAGE_NO_CACHE|_PAGE_WRITETHRU));
551 #else
552         dd->ipath_kregbase = ioremap_nocache(addr, len);
553 #endif
554
555         if (!dd->ipath_kregbase) {
556                 ipath_dbg("Unable to map io addr %llx to kvirt, failing\n",
557                           addr);
558                 ret = -ENOMEM;
559                 goto bail_iounmap;
560         }
561         dd->ipath_kregend = (u64 __iomem *)
562                 ((void __iomem *)dd->ipath_kregbase + len);
563         dd->ipath_physaddr = addr;      /* used for io_remap, etc. */
564         /* for user mmap */
565         ipath_cdbg(VERBOSE, "mapped io addr %llx to kregbase %p\n",
566                    addr, dd->ipath_kregbase);
567
568         /*
569          * clear ipath_flags here instead of in ipath_init_chip as it is set
570          * by ipath_setup_htconfig.
571          */
572         dd->ipath_flags = 0;
573         dd->ipath_lli_counter = 0;
574         dd->ipath_lli_errors = 0;
575
576         if (dd->ipath_f_bus(dd, pdev))
577                 ipath_dev_err(dd, "Failed to setup config space; "
578                               "continuing anyway\n");
579
580         /*
581          * set up our interrupt handler; IRQF_SHARED probably not needed,
582          * since MSI interrupts shouldn't be shared but won't  hurt for now.
583          * check 0 irq after we return from chip-specific bus setup, since
584          * that can affect this due to setup
585          */
586         if (!dd->ipath_irq)
587                 ipath_dev_err(dd, "irq is 0, BIOS error?  Interrupts won't "
588                               "work\n");
589         else {
590                 ret = request_irq(dd->ipath_irq, ipath_intr, IRQF_SHARED,
591                                   IPATH_DRV_NAME, dd);
592                 if (ret) {
593                         ipath_dev_err(dd, "Couldn't setup irq handler, "
594                                       "irq=%d: %d\n", dd->ipath_irq, ret);
595                         goto bail_iounmap;
596                 }
597         }
598
599         ret = ipath_init_chip(dd, 0);   /* do the chip-specific init */
600         if (ret)
601                 goto bail_irqsetup;
602
603         ret = ipath_enable_wc(dd);
604
605         if (ret) {
606                 ipath_dev_err(dd, "Write combining not enabled "
607                               "(err %d): performance may be poor\n",
608                               -ret);
609                 ret = 0;
610         }
611
612         ipath_verify_pioperf(dd);
613
614         ipath_device_create_group(&pdev->dev, dd);
615         ipathfs_add_device(dd);
616         ipath_user_add(dd);
617         ipath_diag_add(dd);
618         ipath_register_ib_device(dd);
619
620         /* Check that card status in STATUS_TIMEOUT seconds. */
621         schedule_delayed_work(&dd->status_work, HZ * STATUS_TIMEOUT);
622
623         goto bail;
624
625 bail_irqsetup:
626         if (pdev->irq) free_irq(pdev->irq, dd);
627
628 bail_iounmap:
629         iounmap((volatile void __iomem *) dd->ipath_kregbase);
630
631 bail_regions:
632         pci_release_regions(pdev);
633
634 bail_disable:
635         pci_disable_device(pdev);
636
637 bail_devdata:
638         ipath_free_devdata(pdev, dd);
639
640 bail:
641         return ret;
642 }
643
644 static void __devexit cleanup_device(struct ipath_devdata *dd)
645 {
646         int port;
647
648         if (*dd->ipath_statusp & IPATH_STATUS_CHIP_PRESENT) {
649                 /* can't do anything more with chip; needs re-init */
650                 *dd->ipath_statusp &= ~IPATH_STATUS_CHIP_PRESENT;
651                 if (dd->ipath_kregbase) {
652                         /*
653                          * if we haven't already cleaned up before these are
654                          * to ensure any register reads/writes "fail" until
655                          * re-init
656                          */
657                         dd->ipath_kregbase = NULL;
658                         dd->ipath_uregbase = 0;
659                         dd->ipath_sregbase = 0;
660                         dd->ipath_cregbase = 0;
661                         dd->ipath_kregsize = 0;
662                 }
663                 ipath_disable_wc(dd);
664         }
665
666         if (dd->ipath_pioavailregs_dma) {
667                 dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE,
668                                   (void *) dd->ipath_pioavailregs_dma,
669                                   dd->ipath_pioavailregs_phys);
670                 dd->ipath_pioavailregs_dma = NULL;
671         }
672         if (dd->ipath_dummy_hdrq) {
673                 dma_free_coherent(&dd->pcidev->dev,
674                         dd->ipath_pd[0]->port_rcvhdrq_size,
675                         dd->ipath_dummy_hdrq, dd->ipath_dummy_hdrq_phys);
676                 dd->ipath_dummy_hdrq = NULL;
677         }
678
679         if (dd->ipath_pageshadow) {
680                 struct page **tmpp = dd->ipath_pageshadow;
681                 dma_addr_t *tmpd = dd->ipath_physshadow;
682                 int i, cnt = 0;
683
684                 ipath_cdbg(VERBOSE, "Unlocking any expTID pages still "
685                            "locked\n");
686                 for (port = 0; port < dd->ipath_cfgports; port++) {
687                         int port_tidbase = port * dd->ipath_rcvtidcnt;
688                         int maxtid = port_tidbase + dd->ipath_rcvtidcnt;
689                         for (i = port_tidbase; i < maxtid; i++) {
690                                 if (!tmpp[i])
691                                         continue;
692                                 pci_unmap_page(dd->pcidev, tmpd[i],
693                                         PAGE_SIZE, PCI_DMA_FROMDEVICE);
694                                 ipath_release_user_pages(&tmpp[i], 1);
695                                 tmpp[i] = NULL;
696                                 cnt++;
697                         }
698                 }
699                 if (cnt) {
700                         ipath_stats.sps_pageunlocks += cnt;
701                         ipath_cdbg(VERBOSE, "There were still %u expTID "
702                                    "entries locked\n", cnt);
703                 }
704                 if (ipath_stats.sps_pagelocks ||
705                     ipath_stats.sps_pageunlocks)
706                         ipath_cdbg(VERBOSE, "%llu pages locked, %llu "
707                                    "unlocked via ipath_m{un}lock\n",
708                                    (unsigned long long)
709                                    ipath_stats.sps_pagelocks,
710                                    (unsigned long long)
711                                    ipath_stats.sps_pageunlocks);
712
713                 ipath_cdbg(VERBOSE, "Free shadow page tid array at %p\n",
714                            dd->ipath_pageshadow);
715                 tmpp = dd->ipath_pageshadow;
716                 dd->ipath_pageshadow = NULL;
717                 vfree(tmpp);
718         }
719
720         /*
721          * free any resources still in use (usually just kernel ports)
722          * at unload; we do for portcnt, not cfgports, because cfgports
723          * could have changed while we were loaded.
724          */
725         for (port = 0; port < dd->ipath_portcnt; port++) {
726                 struct ipath_portdata *pd = dd->ipath_pd[port];
727                 dd->ipath_pd[port] = NULL;
728                 ipath_free_pddata(dd, pd);
729         }
730         kfree(dd->ipath_pd);
731         /*
732          * debuggability, in case some cleanup path tries to use it
733          * after this
734          */
735         dd->ipath_pd = NULL;
736 }
737
738 static void __devexit ipath_remove_one(struct pci_dev *pdev)
739 {
740         struct ipath_devdata *dd = pci_get_drvdata(pdev);
741
742         ipath_cdbg(VERBOSE, "removing, pdev=%p, dd=%p\n", pdev, dd);
743
744         /*
745          * disable the IB link early, to be sure no new packets arrive, which
746          * complicates the shutdown process
747          */
748         ipath_shutdown_device(dd);
749
750         cancel_delayed_work(&dd->status_work);
751         flush_scheduled_work();
752
753         if (dd->verbs_dev)
754                 ipath_unregister_ib_device(dd->verbs_dev);
755
756         ipath_diag_remove(dd);
757         ipath_user_remove(dd);
758         ipathfs_remove_device(dd);
759         ipath_device_remove_group(&pdev->dev, dd);
760
761         ipath_cdbg(VERBOSE, "Releasing pci memory regions, dd %p, "
762                    "unit %u\n", dd, (u32) dd->ipath_unit);
763
764         cleanup_device(dd);
765
766         /*
767          * turn off rcv, send, and interrupts for all ports, all drivers
768          * should also hard reset the chip here?
769          * free up port 0 (kernel) rcvhdr, egr bufs, and eventually tid bufs
770          * for all versions of the driver, if they were allocated
771          */
772         if (dd->ipath_irq) {
773                 ipath_cdbg(VERBOSE, "unit %u free irq %d\n",
774                            dd->ipath_unit, dd->ipath_irq);
775                 dd->ipath_f_free_irq(dd);
776         } else
777                 ipath_dbg("irq is 0, not doing free_irq "
778                           "for unit %u\n", dd->ipath_unit);
779         /*
780          * we check for NULL here, because it's outside
781          * the kregbase check, and we need to call it
782          * after the free_irq.  Thus it's possible that
783          * the function pointers were never initialized.
784          */
785         if (dd->ipath_f_cleanup)
786                 /* clean up chip-specific stuff */
787                 dd->ipath_f_cleanup(dd);
788
789         ipath_cdbg(VERBOSE, "Unmapping kregbase %p\n", dd->ipath_kregbase);
790         iounmap((volatile void __iomem *) dd->ipath_kregbase);
791         pci_release_regions(pdev);
792         ipath_cdbg(VERBOSE, "calling pci_disable_device\n");
793         pci_disable_device(pdev);
794
795         ipath_free_devdata(pdev, dd);
796 }
797
798 /* general driver use */
799 DEFINE_MUTEX(ipath_mutex);
800
801 static DEFINE_SPINLOCK(ipath_pioavail_lock);
802
803 /**
804  * ipath_disarm_piobufs - cancel a range of PIO buffers
805  * @dd: the infinipath device
806  * @first: the first PIO buffer to cancel
807  * @cnt: the number of PIO buffers to cancel
808  *
809  * cancel a range of PIO buffers, used when they might be armed, but
810  * not triggered.  Used at init to ensure buffer state, and also user
811  * process close, in case it died while writing to a PIO buffer
812  * Also after errors.
813  */
814 void ipath_disarm_piobufs(struct ipath_devdata *dd, unsigned first,
815                           unsigned cnt)
816 {
817         unsigned i, last = first + cnt;
818         unsigned long flags;
819
820         ipath_cdbg(PKT, "disarm %u PIObufs first=%u\n", cnt, first);
821         for (i = first; i < last; i++) {
822                 spin_lock_irqsave(&dd->ipath_sendctrl_lock, flags);
823                 /*
824                  * The disarm-related bits are write-only, so it
825                  * is ok to OR them in with our copy of sendctrl
826                  * while we hold the lock.
827                  */
828                 ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
829                         dd->ipath_sendctrl | INFINIPATH_S_DISARM |
830                         (i << INFINIPATH_S_DISARMPIOBUF_SHIFT));
831                 /* can't disarm bufs back-to-back per iba7220 spec */
832                 ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
833                 spin_unlock_irqrestore(&dd->ipath_sendctrl_lock, flags);
834         }
835
836         /*
837          * Disable PIOAVAILUPD, then re-enable, reading scratch in
838          * between.  This seems to avoid a chip timing race that causes
839          * pioavail updates to memory to stop.  We xor as we don't
840          * know the state of the bit when we're called.
841          */
842         spin_lock_irqsave(&dd->ipath_sendctrl_lock, flags);
843         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
844                 dd->ipath_sendctrl ^ INFINIPATH_S_PIOBUFAVAILUPD);
845         ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
846         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
847                          dd->ipath_sendctrl);
848         spin_unlock_irqrestore(&dd->ipath_sendctrl_lock, flags);
849 }
850
851 /**
852  * ipath_wait_linkstate - wait for an IB link state change to occur
853  * @dd: the infinipath device
854  * @state: the state to wait for
855  * @msecs: the number of milliseconds to wait
856  *
857  * wait up to msecs milliseconds for IB link state change to occur for
858  * now, take the easy polling route.  Currently used only by
859  * ipath_set_linkstate.  Returns 0 if state reached, otherwise
860  * -ETIMEDOUT state can have multiple states set, for any of several
861  * transitions.
862  */
863 int ipath_wait_linkstate(struct ipath_devdata *dd, u32 state, int msecs)
864 {
865         dd->ipath_state_wanted = state;
866         wait_event_interruptible_timeout(ipath_state_wait,
867                                          (dd->ipath_flags & state),
868                                          msecs_to_jiffies(msecs));
869         dd->ipath_state_wanted = 0;
870
871         if (!(dd->ipath_flags & state)) {
872                 u64 val;
873                 ipath_cdbg(VERBOSE, "Didn't reach linkstate %s within %u"
874                            " ms\n",
875                            /* test INIT ahead of DOWN, both can be set */
876                            (state & IPATH_LINKINIT) ? "INIT" :
877                            ((state & IPATH_LINKDOWN) ? "DOWN" :
878                             ((state & IPATH_LINKARMED) ? "ARM" : "ACTIVE")),
879                            msecs);
880                 val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_ibcstatus);
881                 ipath_cdbg(VERBOSE, "ibcc=%llx ibcstatus=%llx (%s)\n",
882                            (unsigned long long) ipath_read_kreg64(
883                                    dd, dd->ipath_kregs->kr_ibcctrl),
884                            (unsigned long long) val,
885                            ipath_ibcstatus_str[val & 0xf]);
886         }
887         return (dd->ipath_flags & state) ? 0 : -ETIMEDOUT;
888 }
889
890 /*
891  * Decode the error status into strings, deciding whether to always
892  * print * it or not depending on "normal packet errors" vs everything
893  * else.   Return 1 if "real" errors, otherwise 0 if only packet
894  * errors, so caller can decide what to print with the string.
895  */
896 int ipath_decode_err(char *buf, size_t blen, ipath_err_t err)
897 {
898         int iserr = 1;
899         *buf = '\0';
900         if (err & INFINIPATH_E_PKTERRS) {
901                 if (!(err & ~INFINIPATH_E_PKTERRS))
902                         iserr = 0; // if only packet errors.
903                 if (ipath_debug & __IPATH_ERRPKTDBG) {
904                         if (err & INFINIPATH_E_REBP)
905                                 strlcat(buf, "EBP ", blen);
906                         if (err & INFINIPATH_E_RVCRC)
907                                 strlcat(buf, "VCRC ", blen);
908                         if (err & INFINIPATH_E_RICRC) {
909                                 strlcat(buf, "CRC ", blen);
910                                 // clear for check below, so only once
911                                 err &= INFINIPATH_E_RICRC;
912                         }
913                         if (err & INFINIPATH_E_RSHORTPKTLEN)
914                                 strlcat(buf, "rshortpktlen ", blen);
915                         if (err & INFINIPATH_E_SDROPPEDDATAPKT)
916                                 strlcat(buf, "sdroppeddatapkt ", blen);
917                         if (err & INFINIPATH_E_SPKTLEN)
918                                 strlcat(buf, "spktlen ", blen);
919                 }
920                 if ((err & INFINIPATH_E_RICRC) &&
921                         !(err&(INFINIPATH_E_RVCRC|INFINIPATH_E_REBP)))
922                         strlcat(buf, "CRC ", blen);
923                 if (!iserr)
924                         goto done;
925         }
926         if (err & INFINIPATH_E_RHDRLEN)
927                 strlcat(buf, "rhdrlen ", blen);
928         if (err & INFINIPATH_E_RBADTID)
929                 strlcat(buf, "rbadtid ", blen);
930         if (err & INFINIPATH_E_RBADVERSION)
931                 strlcat(buf, "rbadversion ", blen);
932         if (err & INFINIPATH_E_RHDR)
933                 strlcat(buf, "rhdr ", blen);
934         if (err & INFINIPATH_E_RLONGPKTLEN)
935                 strlcat(buf, "rlongpktlen ", blen);
936         if (err & INFINIPATH_E_RMAXPKTLEN)
937                 strlcat(buf, "rmaxpktlen ", blen);
938         if (err & INFINIPATH_E_RMINPKTLEN)
939                 strlcat(buf, "rminpktlen ", blen);
940         if (err & INFINIPATH_E_SMINPKTLEN)
941                 strlcat(buf, "sminpktlen ", blen);
942         if (err & INFINIPATH_E_RFORMATERR)
943                 strlcat(buf, "rformaterr ", blen);
944         if (err & INFINIPATH_E_RUNSUPVL)
945                 strlcat(buf, "runsupvl ", blen);
946         if (err & INFINIPATH_E_RUNEXPCHAR)
947                 strlcat(buf, "runexpchar ", blen);
948         if (err & INFINIPATH_E_RIBFLOW)
949                 strlcat(buf, "ribflow ", blen);
950         if (err & INFINIPATH_E_SUNDERRUN)
951                 strlcat(buf, "sunderrun ", blen);
952         if (err & INFINIPATH_E_SPIOARMLAUNCH)
953                 strlcat(buf, "spioarmlaunch ", blen);
954         if (err & INFINIPATH_E_SUNEXPERRPKTNUM)
955                 strlcat(buf, "sunexperrpktnum ", blen);
956         if (err & INFINIPATH_E_SDROPPEDSMPPKT)
957                 strlcat(buf, "sdroppedsmppkt ", blen);
958         if (err & INFINIPATH_E_SMAXPKTLEN)
959                 strlcat(buf, "smaxpktlen ", blen);
960         if (err & INFINIPATH_E_SUNSUPVL)
961                 strlcat(buf, "sunsupVL ", blen);
962         if (err & INFINIPATH_E_INVALIDADDR)
963                 strlcat(buf, "invalidaddr ", blen);
964         if (err & INFINIPATH_E_RRCVEGRFULL)
965                 strlcat(buf, "rcvegrfull ", blen);
966         if (err & INFINIPATH_E_RRCVHDRFULL)
967                 strlcat(buf, "rcvhdrfull ", blen);
968         if (err & INFINIPATH_E_IBSTATUSCHANGED)
969                 strlcat(buf, "ibcstatuschg ", blen);
970         if (err & INFINIPATH_E_RIBLOSTLINK)
971                 strlcat(buf, "riblostlink ", blen);
972         if (err & INFINIPATH_E_HARDWARE)
973                 strlcat(buf, "hardware ", blen);
974         if (err & INFINIPATH_E_RESET)
975                 strlcat(buf, "reset ", blen);
976 done:
977         return iserr;
978 }
979
980 /**
981  * get_rhf_errstring - decode RHF errors
982  * @err: the err number
983  * @msg: the output buffer
984  * @len: the length of the output buffer
985  *
986  * only used one place now, may want more later
987  */
988 static void get_rhf_errstring(u32 err, char *msg, size_t len)
989 {
990         /* if no errors, and so don't need to check what's first */
991         *msg = '\0';
992
993         if (err & INFINIPATH_RHF_H_ICRCERR)
994                 strlcat(msg, "icrcerr ", len);
995         if (err & INFINIPATH_RHF_H_VCRCERR)
996                 strlcat(msg, "vcrcerr ", len);
997         if (err & INFINIPATH_RHF_H_PARITYERR)
998                 strlcat(msg, "parityerr ", len);
999         if (err & INFINIPATH_RHF_H_LENERR)
1000                 strlcat(msg, "lenerr ", len);
1001         if (err & INFINIPATH_RHF_H_MTUERR)
1002                 strlcat(msg, "mtuerr ", len);
1003         if (err & INFINIPATH_RHF_H_IHDRERR)
1004                 /* infinipath hdr checksum error */
1005                 strlcat(msg, "ipathhdrerr ", len);
1006         if (err & INFINIPATH_RHF_H_TIDERR)
1007                 strlcat(msg, "tiderr ", len);
1008         if (err & INFINIPATH_RHF_H_MKERR)
1009                 /* bad port, offset, etc. */
1010                 strlcat(msg, "invalid ipathhdr ", len);
1011         if (err & INFINIPATH_RHF_H_IBERR)
1012                 strlcat(msg, "iberr ", len);
1013         if (err & INFINIPATH_RHF_L_SWA)
1014                 strlcat(msg, "swA ", len);
1015         if (err & INFINIPATH_RHF_L_SWB)
1016                 strlcat(msg, "swB ", len);
1017 }
1018
1019 /**
1020  * ipath_get_egrbuf - get an eager buffer
1021  * @dd: the infinipath device
1022  * @bufnum: the eager buffer to get
1023  *
1024  * must only be called if ipath_pd[port] is known to be allocated
1025  */
1026 static inline void *ipath_get_egrbuf(struct ipath_devdata *dd, u32 bufnum)
1027 {
1028         return dd->ipath_port0_skbinfo ?
1029                 (void *) dd->ipath_port0_skbinfo[bufnum].skb->data : NULL;
1030 }
1031
1032 /**
1033  * ipath_alloc_skb - allocate an skb and buffer with possible constraints
1034  * @dd: the infinipath device
1035  * @gfp_mask: the sk_buff SFP mask
1036  */
1037 struct sk_buff *ipath_alloc_skb(struct ipath_devdata *dd,
1038                                 gfp_t gfp_mask)
1039 {
1040         struct sk_buff *skb;
1041         u32 len;
1042
1043         /*
1044          * Only fully supported way to handle this is to allocate lots
1045          * extra, align as needed, and then do skb_reserve().  That wastes
1046          * a lot of memory...  I'll have to hack this into infinipath_copy
1047          * also.
1048          */
1049
1050         /*
1051          * We need 2 extra bytes for ipath_ether data sent in the
1052          * key header.  In order to keep everything dword aligned,
1053          * we'll reserve 4 bytes.
1054          */
1055         len = dd->ipath_ibmaxlen + 4;
1056
1057         if (dd->ipath_flags & IPATH_4BYTE_TID) {
1058                 /* We need a 2KB multiple alignment, and there is no way
1059                  * to do it except to allocate extra and then skb_reserve
1060                  * enough to bring it up to the right alignment.
1061                  */
1062                 len += 2047;
1063         }
1064
1065         skb = __dev_alloc_skb(len, gfp_mask);
1066         if (!skb) {
1067                 ipath_dev_err(dd, "Failed to allocate skbuff, length %u\n",
1068                               len);
1069                 goto bail;
1070         }
1071
1072         skb_reserve(skb, 4);
1073
1074         if (dd->ipath_flags & IPATH_4BYTE_TID) {
1075                 u32 una = (unsigned long)skb->data & 2047;
1076                 if (una)
1077                         skb_reserve(skb, 2048 - una);
1078         }
1079
1080 bail:
1081         return skb;
1082 }
1083
1084 static void ipath_rcv_hdrerr(struct ipath_devdata *dd,
1085                              u32 eflags,
1086                              u32 l,
1087                              u32 etail,
1088                              u64 *rc)
1089 {
1090         char emsg[128];
1091         struct ipath_message_header *hdr;
1092
1093         get_rhf_errstring(eflags, emsg, sizeof emsg);
1094         hdr = (struct ipath_message_header *)&rc[1];
1095         ipath_cdbg(PKT, "RHFerrs %x hdrqtail=%x typ=%u "
1096                    "tlen=%x opcode=%x egridx=%x: %s\n",
1097                    eflags, l,
1098                    ipath_hdrget_rcv_type((__le32 *) rc),
1099                    ipath_hdrget_length_in_bytes((__le32 *) rc),
1100                    be32_to_cpu(hdr->bth[0]) >> 24,
1101                    etail, emsg);
1102
1103         /* Count local link integrity errors. */
1104         if (eflags & (INFINIPATH_RHF_H_ICRCERR | INFINIPATH_RHF_H_VCRCERR)) {
1105                 u8 n = (dd->ipath_ibcctrl >>
1106                         INFINIPATH_IBCC_PHYERRTHRESHOLD_SHIFT) &
1107                         INFINIPATH_IBCC_PHYERRTHRESHOLD_MASK;
1108
1109                 if (++dd->ipath_lli_counter > n) {
1110                         dd->ipath_lli_counter = 0;
1111                         dd->ipath_lli_errors++;
1112                 }
1113         }
1114 }
1115
1116 /*
1117  * ipath_kreceive - receive a packet
1118  * @pd: the infinipath port
1119  *
1120  * called from interrupt handler for errors or receive interrupt
1121  */
1122 void ipath_kreceive(struct ipath_portdata *pd)
1123 {
1124         u64 *rc;
1125         struct ipath_devdata *dd = pd->port_dd;
1126         void *ebuf;
1127         const u32 rsize = dd->ipath_rcvhdrentsize;      /* words */
1128         const u32 maxcnt = dd->ipath_rcvhdrcnt * rsize; /* words */
1129         u32 etail = -1, l, hdrqtail;
1130         struct ipath_message_header *hdr;
1131         u32 eflags, i, etype, tlen, pkttot = 0, updegr=0, reloop=0;
1132         static u64 totcalls;    /* stats, may eventually remove */
1133
1134         if (!dd->ipath_hdrqtailptr) {
1135                 ipath_dev_err(dd,
1136                               "hdrqtailptr not set, can't do receives\n");
1137                 goto bail;
1138         }
1139
1140         l = pd->port_head;
1141         hdrqtail = ipath_get_rcvhdrtail(pd);
1142         if (l == hdrqtail)
1143                 goto bail;
1144
1145 reloop:
1146         for (i = 0; l != hdrqtail; i++) {
1147                 u32 qp;
1148                 u8 *bthbytes;
1149
1150                 rc = (u64 *) (pd->port_rcvhdrq + (l << 2));
1151                 hdr = (struct ipath_message_header *)&rc[1];
1152                 /*
1153                  * could make a network order version of IPATH_KD_QP, and
1154                  * do the obvious shift before masking to speed this up.
1155                  */
1156                 qp = ntohl(hdr->bth[1]) & 0xffffff;
1157                 bthbytes = (u8 *) hdr->bth;
1158
1159                 eflags = ipath_hdrget_err_flags((__le32 *) rc);
1160                 etype = ipath_hdrget_rcv_type((__le32 *) rc);
1161                 /* total length */
1162                 tlen = ipath_hdrget_length_in_bytes((__le32 *) rc);
1163                 ebuf = NULL;
1164                 if (etype != RCVHQ_RCV_TYPE_EXPECTED) {
1165                         /*
1166                          * it turns out that the chips uses an eager buffer
1167                          * for all non-expected packets, whether it "needs"
1168                          * one or not.  So always get the index, but don't
1169                          * set ebuf (so we try to copy data) unless the
1170                          * length requires it.
1171                          */
1172                         etail = ipath_hdrget_index((__le32 *) rc);
1173                         if (tlen > sizeof(*hdr) ||
1174                             etype == RCVHQ_RCV_TYPE_NON_KD)
1175                                 ebuf = ipath_get_egrbuf(dd, etail);
1176                 }
1177
1178                 /*
1179                  * both tiderr and ipathhdrerr are set for all plain IB
1180                  * packets; only ipathhdrerr should be set.
1181                  */
1182
1183                 if (etype != RCVHQ_RCV_TYPE_NON_KD && etype !=
1184                     RCVHQ_RCV_TYPE_ERROR && ipath_hdrget_ipath_ver(
1185                             hdr->iph.ver_port_tid_offset) !=
1186                     IPS_PROTO_VERSION) {
1187                         ipath_cdbg(PKT, "Bad InfiniPath protocol version "
1188                                    "%x\n", etype);
1189                 }
1190
1191                 if (unlikely(eflags))
1192                         ipath_rcv_hdrerr(dd, eflags, l, etail, rc);
1193                 else if (etype == RCVHQ_RCV_TYPE_NON_KD) {
1194                         ipath_ib_rcv(dd->verbs_dev, rc + 1, ebuf, tlen);
1195                         if (dd->ipath_lli_counter)
1196                                 dd->ipath_lli_counter--;
1197                         ipath_cdbg(PKT, "typ %x, opcode %x (eager, "
1198                                    "qp=%x), len %x; ignored\n",
1199                                    etype, bthbytes[0], qp, tlen);
1200                 }
1201                 else if (etype == RCVHQ_RCV_TYPE_EAGER)
1202                         ipath_cdbg(PKT, "typ %x, opcode %x (eager, "
1203                                    "qp=%x), len %x; ignored\n",
1204                                    etype, bthbytes[0], qp, tlen);
1205                 else if (etype == RCVHQ_RCV_TYPE_EXPECTED)
1206                         ipath_dbg("Bug: Expected TID, opcode %x; ignored\n",
1207                                   be32_to_cpu(hdr->bth[0]) & 0xff);
1208                 else {
1209                         /*
1210                          * error packet, type of error unknown.
1211                          * Probably type 3, but we don't know, so don't
1212                          * even try to print the opcode, etc.
1213                          */
1214                         ipath_dbg("Error Pkt, but no eflags! egrbuf %x, "
1215                                   "len %x\nhdrq@%lx;hdrq+%x rhf: %llx; "
1216                                   "hdr %llx %llx %llx %llx %llx\n",
1217                                   etail, tlen, (unsigned long) rc, l,
1218                                   (unsigned long long) rc[0],
1219                                   (unsigned long long) rc[1],
1220                                   (unsigned long long) rc[2],
1221                                   (unsigned long long) rc[3],
1222                                   (unsigned long long) rc[4],
1223                                   (unsigned long long) rc[5]);
1224                 }
1225                 l += rsize;
1226                 if (l >= maxcnt)
1227                         l = 0;
1228                 if (etype != RCVHQ_RCV_TYPE_EXPECTED)
1229                     updegr = 1;
1230                 /*
1231                  * update head regs on last packet, and every 16 packets.
1232                  * Reduce bus traffic, while still trying to prevent
1233                  * rcvhdrq overflows, for when the queue is nearly full
1234                  */
1235                 if (l == hdrqtail || (i && !(i&0xf))) {
1236                         u64 lval;
1237                         if (l == hdrqtail)
1238                                 /* request IBA6120 interrupt only on last */
1239                                 lval = dd->ipath_rhdrhead_intr_off | l;
1240                         else
1241                                 lval = l;
1242                         (void)ipath_write_ureg(dd, ur_rcvhdrhead, lval, 0);
1243                         if (updegr) {
1244                                 (void)ipath_write_ureg(dd, ur_rcvegrindexhead,
1245                                                        etail, 0);
1246                                 updegr = 0;
1247                         }
1248                 }
1249         }
1250
1251         if (!dd->ipath_rhdrhead_intr_off && !reloop) {
1252                 /* IBA6110 workaround; we can have a race clearing chip
1253                  * interrupt with another interrupt about to be delivered,
1254                  * and can clear it before it is delivered on the GPIO
1255                  * workaround.  By doing the extra check here for the
1256                  * in-memory tail register updating while we were doing
1257                  * earlier packets, we "almost" guarantee we have covered
1258                  * that case.
1259                  */
1260                 u32 hqtail = ipath_get_rcvhdrtail(pd);
1261                 if (hqtail != hdrqtail) {
1262                         hdrqtail = hqtail;
1263                         reloop = 1; /* loop 1 extra time at most */
1264                         goto reloop;
1265                 }
1266         }
1267
1268         pkttot += i;
1269
1270         pd->port_head = l;
1271
1272         if (pkttot > ipath_stats.sps_maxpkts_call)
1273                 ipath_stats.sps_maxpkts_call = pkttot;
1274         ipath_stats.sps_port0pkts += pkttot;
1275         ipath_stats.sps_avgpkts_call =
1276                 ipath_stats.sps_port0pkts / ++totcalls;
1277
1278 bail:;
1279 }
1280
1281 /**
1282  * ipath_update_pio_bufs - update shadow copy of the PIO availability map
1283  * @dd: the infinipath device
1284  *
1285  * called whenever our local copy indicates we have run out of send buffers
1286  * NOTE: This can be called from interrupt context by some code
1287  * and from non-interrupt context by ipath_getpiobuf().
1288  */
1289
1290 static void ipath_update_pio_bufs(struct ipath_devdata *dd)
1291 {
1292         unsigned long flags;
1293         int i;
1294         const unsigned piobregs = (unsigned)dd->ipath_pioavregs;
1295
1296         /* If the generation (check) bits have changed, then we update the
1297          * busy bit for the corresponding PIO buffer.  This algorithm will
1298          * modify positions to the value they already have in some cases
1299          * (i.e., no change), but it's faster than changing only the bits
1300          * that have changed.
1301          *
1302          * We would like to do this atomicly, to avoid spinlocks in the
1303          * critical send path, but that's not really possible, given the
1304          * type of changes, and that this routine could be called on
1305          * multiple cpu's simultaneously, so we lock in this routine only,
1306          * to avoid conflicting updates; all we change is the shadow, and
1307          * it's a single 64 bit memory location, so by definition the update
1308          * is atomic in terms of what other cpu's can see in testing the
1309          * bits.  The spin_lock overhead isn't too bad, since it only
1310          * happens when all buffers are in use, so only cpu overhead, not
1311          * latency or bandwidth is affected.
1312          */
1313 #define _IPATH_ALL_CHECKBITS 0x5555555555555555ULL
1314         if (!dd->ipath_pioavailregs_dma) {
1315                 ipath_dbg("Update shadow pioavail, but regs_dma NULL!\n");
1316                 return;
1317         }
1318         if (ipath_debug & __IPATH_VERBDBG) {
1319                 /* only if packet debug and verbose */
1320                 volatile __le64 *dma = dd->ipath_pioavailregs_dma;
1321                 unsigned long *shadow = dd->ipath_pioavailshadow;
1322
1323                 ipath_cdbg(PKT, "Refill avail, dma0=%llx shad0=%lx, "
1324                            "d1=%llx s1=%lx, d2=%llx s2=%lx, d3=%llx "
1325                            "s3=%lx\n",
1326                            (unsigned long long) le64_to_cpu(dma[0]),
1327                            shadow[0],
1328                            (unsigned long long) le64_to_cpu(dma[1]),
1329                            shadow[1],
1330                            (unsigned long long) le64_to_cpu(dma[2]),
1331                            shadow[2],
1332                            (unsigned long long) le64_to_cpu(dma[3]),
1333                            shadow[3]);
1334                 if (piobregs > 4)
1335                         ipath_cdbg(
1336                                 PKT, "2nd group, dma4=%llx shad4=%lx, "
1337                                 "d5=%llx s5=%lx, d6=%llx s6=%lx, "
1338                                 "d7=%llx s7=%lx\n",
1339                                 (unsigned long long) le64_to_cpu(dma[4]),
1340                                 shadow[4],
1341                                 (unsigned long long) le64_to_cpu(dma[5]),
1342                                 shadow[5],
1343                                 (unsigned long long) le64_to_cpu(dma[6]),
1344                                 shadow[6],
1345                                 (unsigned long long) le64_to_cpu(dma[7]),
1346                                 shadow[7]);
1347         }
1348         spin_lock_irqsave(&ipath_pioavail_lock, flags);
1349         for (i = 0; i < piobregs; i++) {
1350                 u64 pchbusy, pchg, piov, pnew;
1351                 /*
1352                  * Chip Errata: bug 6641; even and odd qwords>3 are swapped
1353                  */
1354                 if (i > 3 && (dd->ipath_flags & IPATH_SWAP_PIOBUFS))
1355                         piov = le64_to_cpu(dd->ipath_pioavailregs_dma[i ^ 1]);
1356                 else
1357                         piov = le64_to_cpu(dd->ipath_pioavailregs_dma[i]);
1358                 pchg = _IPATH_ALL_CHECKBITS &
1359                         ~(dd->ipath_pioavailshadow[i] ^ piov);
1360                 pchbusy = pchg << INFINIPATH_SENDPIOAVAIL_BUSY_SHIFT;
1361                 if (pchg && (pchbusy & dd->ipath_pioavailshadow[i])) {
1362                         pnew = dd->ipath_pioavailshadow[i] & ~pchbusy;
1363                         pnew |= piov & pchbusy;
1364                         dd->ipath_pioavailshadow[i] = pnew;
1365                 }
1366         }
1367         spin_unlock_irqrestore(&ipath_pioavail_lock, flags);
1368 }
1369
1370 /**
1371  * ipath_setrcvhdrsize - set the receive header size
1372  * @dd: the infinipath device
1373  * @rhdrsize: the receive header size
1374  *
1375  * called from user init code, and also layered driver init
1376  */
1377 int ipath_setrcvhdrsize(struct ipath_devdata *dd, unsigned rhdrsize)
1378 {
1379         int ret = 0;
1380
1381         if (dd->ipath_flags & IPATH_RCVHDRSZ_SET) {
1382                 if (dd->ipath_rcvhdrsize != rhdrsize) {
1383                         dev_info(&dd->pcidev->dev,
1384                                  "Error: can't set protocol header "
1385                                  "size %u, already %u\n",
1386                                  rhdrsize, dd->ipath_rcvhdrsize);
1387                         ret = -EAGAIN;
1388                 } else
1389                         ipath_cdbg(VERBOSE, "Reuse same protocol header "
1390                                    "size %u\n", dd->ipath_rcvhdrsize);
1391         } else if (rhdrsize > (dd->ipath_rcvhdrentsize -
1392                                (sizeof(u64) / sizeof(u32)))) {
1393                 ipath_dbg("Error: can't set protocol header size %u "
1394                           "(> max %u)\n", rhdrsize,
1395                           dd->ipath_rcvhdrentsize -
1396                           (u32) (sizeof(u64) / sizeof(u32)));
1397                 ret = -EOVERFLOW;
1398         } else {
1399                 dd->ipath_flags |= IPATH_RCVHDRSZ_SET;
1400                 dd->ipath_rcvhdrsize = rhdrsize;
1401                 ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvhdrsize,
1402                                  dd->ipath_rcvhdrsize);
1403                 ipath_cdbg(VERBOSE, "Set protocol header size to %u\n",
1404                            dd->ipath_rcvhdrsize);
1405         }
1406         return ret;
1407 }
1408
1409 /**
1410  * ipath_getpiobuf - find an available pio buffer
1411  * @dd: the infinipath device
1412  * @pbufnum: the buffer number is placed here
1413  *
1414  * do appropriate marking as busy, etc.
1415  * returns buffer number if one found (>=0), negative number is error.
1416  * Used by ipath_layer_send
1417  */
1418 u32 __iomem *ipath_getpiobuf(struct ipath_devdata *dd, u32 * pbufnum)
1419 {
1420         int i, j, starti, updated = 0;
1421         unsigned piobcnt, iter;
1422         unsigned long flags;
1423         unsigned long *shadow = dd->ipath_pioavailshadow;
1424         u32 __iomem *buf;
1425
1426         piobcnt = (unsigned)(dd->ipath_piobcnt2k
1427                              + dd->ipath_piobcnt4k);
1428         starti = dd->ipath_lastport_piobuf;
1429         iter = piobcnt - starti;
1430         if (dd->ipath_upd_pio_shadow) {
1431                 /*
1432                  * Minor optimization.  If we had no buffers on last call,
1433                  * start out by doing the update; continue and do scan even
1434                  * if no buffers were updated, to be paranoid
1435                  */
1436                 ipath_update_pio_bufs(dd);
1437                 /* we scanned here, don't do it at end of scan */
1438                 updated = 1;
1439                 i = starti;
1440         } else
1441                 i = dd->ipath_lastpioindex;
1442
1443 rescan:
1444         /*
1445          * while test_and_set_bit() is atomic, we do that and then the
1446          * change_bit(), and the pair is not.  See if this is the cause
1447          * of the remaining armlaunch errors.
1448          */
1449         spin_lock_irqsave(&ipath_pioavail_lock, flags);
1450         for (j = 0; j < iter; j++, i++) {
1451                 if (i >= piobcnt)
1452                         i = starti;
1453                 /*
1454                  * To avoid bus lock overhead, we first find a candidate
1455                  * buffer, then do the test and set, and continue if that
1456                  * fails.
1457                  */
1458                 if (test_bit((2 * i) + 1, shadow) ||
1459                     test_and_set_bit((2 * i) + 1, shadow))
1460                         continue;
1461                 /* flip generation bit */
1462                 change_bit(2 * i, shadow);
1463                 break;
1464         }
1465         spin_unlock_irqrestore(&ipath_pioavail_lock, flags);
1466
1467         if (j == iter) {
1468                 volatile __le64 *dma = dd->ipath_pioavailregs_dma;
1469
1470                 /*
1471                  * first time through; shadow exhausted, but may be real
1472                  * buffers available, so go see; if any updated, rescan
1473                  * (once)
1474                  */
1475                 if (!updated) {
1476                         ipath_update_pio_bufs(dd);
1477                         updated = 1;
1478                         i = starti;
1479                         goto rescan;
1480                 }
1481                 dd->ipath_upd_pio_shadow = 1;
1482                 /*
1483                  * not atomic, but if we lose one once in a while, that's OK
1484                  */
1485                 ipath_stats.sps_nopiobufs++;
1486                 if (!(++dd->ipath_consec_nopiobuf % 100000)) {
1487                         ipath_dbg(
1488                                 "%u pio sends with no bufavail; dmacopy: "
1489                                 "%llx %llx %llx %llx; shadow:  "
1490                                 "%lx %lx %lx %lx\n",
1491                                 dd->ipath_consec_nopiobuf,
1492                                 (unsigned long long) le64_to_cpu(dma[0]),
1493                                 (unsigned long long) le64_to_cpu(dma[1]),
1494                                 (unsigned long long) le64_to_cpu(dma[2]),
1495                                 (unsigned long long) le64_to_cpu(dma[3]),
1496                                 shadow[0], shadow[1], shadow[2],
1497                                 shadow[3]);
1498                         /*
1499                          * 4 buffers per byte, 4 registers above, cover rest
1500                          * below
1501                          */
1502                         if ((dd->ipath_piobcnt2k + dd->ipath_piobcnt4k) >
1503                             (sizeof(shadow[0]) * 4 * 4))
1504                                 ipath_dbg("2nd group: dmacopy: %llx %llx "
1505                                           "%llx %llx; shadow: %lx %lx "
1506                                           "%lx %lx\n",
1507                                           (unsigned long long)
1508                                           le64_to_cpu(dma[4]),
1509                                           (unsigned long long)
1510                                           le64_to_cpu(dma[5]),
1511                                           (unsigned long long)
1512                                           le64_to_cpu(dma[6]),
1513                                           (unsigned long long)
1514                                           le64_to_cpu(dma[7]),
1515                                           shadow[4], shadow[5],
1516                                           shadow[6], shadow[7]);
1517                 }
1518                 buf = NULL;
1519                 goto bail;
1520         }
1521
1522         /*
1523          * set next starting place.  Since it's just an optimization,
1524          * it doesn't matter who wins on this, so no locking
1525          */
1526         dd->ipath_lastpioindex = i + 1;
1527         if (dd->ipath_upd_pio_shadow)
1528                 dd->ipath_upd_pio_shadow = 0;
1529         if (dd->ipath_consec_nopiobuf)
1530                 dd->ipath_consec_nopiobuf = 0;
1531         if (i < dd->ipath_piobcnt2k)
1532                 buf = (u32 __iomem *) (dd->ipath_pio2kbase +
1533                                        i * dd->ipath_palign);
1534         else
1535                 buf = (u32 __iomem *)
1536                         (dd->ipath_pio4kbase +
1537                          (i - dd->ipath_piobcnt2k) * dd->ipath_4kalign);
1538         ipath_cdbg(VERBOSE, "Return piobuf%u %uk @ %p\n",
1539                    i, (i < dd->ipath_piobcnt2k) ? 2 : 4, buf);
1540         if (pbufnum)
1541                 *pbufnum = i;
1542
1543 bail:
1544         return buf;
1545 }
1546
1547 /**
1548  * ipath_create_rcvhdrq - create a receive header queue
1549  * @dd: the infinipath device
1550  * @pd: the port data
1551  *
1552  * this must be contiguous memory (from an i/o perspective), and must be
1553  * DMA'able (which means for some systems, it will go through an IOMMU,
1554  * or be forced into a low address range).
1555  */
1556 int ipath_create_rcvhdrq(struct ipath_devdata *dd,
1557                          struct ipath_portdata *pd)
1558 {
1559         int ret = 0;
1560
1561         if (!pd->port_rcvhdrq) {
1562                 dma_addr_t phys_hdrqtail;
1563                 gfp_t gfp_flags = GFP_USER | __GFP_COMP;
1564                 int amt = ALIGN(dd->ipath_rcvhdrcnt * dd->ipath_rcvhdrentsize *
1565                                 sizeof(u32), PAGE_SIZE);
1566
1567                 pd->port_rcvhdrq = dma_alloc_coherent(
1568                         &dd->pcidev->dev, amt, &pd->port_rcvhdrq_phys,
1569                         gfp_flags);
1570
1571                 if (!pd->port_rcvhdrq) {
1572                         ipath_dev_err(dd, "attempt to allocate %d bytes "
1573                                       "for port %u rcvhdrq failed\n",
1574                                       amt, pd->port_port);
1575                         ret = -ENOMEM;
1576                         goto bail;
1577                 }
1578                 pd->port_rcvhdrtail_kvaddr = dma_alloc_coherent(
1579                         &dd->pcidev->dev, PAGE_SIZE, &phys_hdrqtail, GFP_KERNEL);
1580                 if (!pd->port_rcvhdrtail_kvaddr) {
1581                         ipath_dev_err(dd, "attempt to allocate 1 page "
1582                                       "for port %u rcvhdrqtailaddr failed\n",
1583                                       pd->port_port);
1584                         ret = -ENOMEM;
1585                         dma_free_coherent(&dd->pcidev->dev, amt,
1586                                           pd->port_rcvhdrq, pd->port_rcvhdrq_phys);
1587                         pd->port_rcvhdrq = NULL;
1588                         goto bail;
1589                 }
1590                 pd->port_rcvhdrqtailaddr_phys = phys_hdrqtail;
1591
1592                 pd->port_rcvhdrq_size = amt;
1593
1594                 ipath_cdbg(VERBOSE, "%d pages at %p (phys %lx) size=%lu "
1595                            "for port %u rcvhdr Q\n",
1596                            amt >> PAGE_SHIFT, pd->port_rcvhdrq,
1597                            (unsigned long) pd->port_rcvhdrq_phys,
1598                            (unsigned long) pd->port_rcvhdrq_size,
1599                            pd->port_port);
1600
1601                 ipath_cdbg(VERBOSE, "port %d hdrtailaddr, %llx physical\n",
1602                            pd->port_port,
1603                            (unsigned long long) phys_hdrqtail);
1604         }
1605         else
1606                 ipath_cdbg(VERBOSE, "reuse port %d rcvhdrq @%p %llx phys; "
1607                            "hdrtailaddr@%p %llx physical\n",
1608                            pd->port_port, pd->port_rcvhdrq,
1609                            (unsigned long long) pd->port_rcvhdrq_phys,
1610                            pd->port_rcvhdrtail_kvaddr, (unsigned long long)
1611                            pd->port_rcvhdrqtailaddr_phys);
1612
1613         /* clear for security and sanity on each use */
1614         memset(pd->port_rcvhdrq, 0, pd->port_rcvhdrq_size);
1615         if (pd->port_rcvhdrtail_kvaddr)
1616                 memset(pd->port_rcvhdrtail_kvaddr, 0, PAGE_SIZE);
1617
1618         /*
1619          * tell chip each time we init it, even if we are re-using previous
1620          * memory (we zero the register at process close)
1621          */
1622         ipath_write_kreg_port(dd, dd->ipath_kregs->kr_rcvhdrtailaddr,
1623                               pd->port_port, pd->port_rcvhdrqtailaddr_phys);
1624         ipath_write_kreg_port(dd, dd->ipath_kregs->kr_rcvhdraddr,
1625                               pd->port_port, pd->port_rcvhdrq_phys);
1626
1627         ret = 0;
1628 bail:
1629         return ret;
1630 }
1631
1632
1633 /*
1634  * Flush all sends that might be in the ready to send state, as well as any
1635  * that are in the process of being sent.   Used whenever we need to be
1636  * sure the send side is idle.  Cleans up all buffer state by canceling
1637  * all pio buffers, and issuing an abort, which cleans up anything in the
1638  * launch fifo.  The cancel is superfluous on some chip versions, but
1639  * it's safer to always do it.
1640  * PIOAvail bits are updated by the chip as if normal send had happened.
1641  */
1642 void ipath_cancel_sends(struct ipath_devdata *dd, int restore_sendctrl)
1643 {
1644         ipath_dbg("Cancelling all in-progress send buffers\n");
1645         dd->ipath_lastcancel = jiffies+HZ/2; /* skip armlaunch errs a bit */
1646         /*
1647          * the abort bit is auto-clearing.  We read scratch to be sure
1648          * that cancels and the abort have taken effect in the chip.
1649          */
1650         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
1651                 INFINIPATH_S_ABORT);
1652         ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
1653         ipath_disarm_piobufs(dd, 0,
1654                 (unsigned)(dd->ipath_piobcnt2k + dd->ipath_piobcnt4k));
1655         if (restore_sendctrl) /* else done by caller later */
1656                 ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl,
1657                                  dd->ipath_sendctrl);
1658
1659         /* and again, be sure all have hit the chip */
1660         ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
1661 }
1662
1663
1664 static void ipath_set_ib_lstate(struct ipath_devdata *dd, int which)
1665 {
1666         static const char *what[4] = {
1667                 [0] = "NOP",
1668                 [INFINIPATH_IBCC_LINKCMD_DOWN] = "DOWN",
1669                 [INFINIPATH_IBCC_LINKCMD_ARMED] = "ARMED",
1670                 [INFINIPATH_IBCC_LINKCMD_ACTIVE] = "ACTIVE"
1671         };
1672         int linkcmd = (which >> INFINIPATH_IBCC_LINKCMD_SHIFT) &
1673                         INFINIPATH_IBCC_LINKCMD_MASK;
1674
1675         ipath_cdbg(VERBOSE, "Trying to move unit %u to %s, current ltstate "
1676                    "is %s\n", dd->ipath_unit,
1677                    what[linkcmd],
1678                    ipath_ibcstatus_str[ipath_ib_linktrstate(dd,
1679                         ipath_read_kreg64(dd, dd->ipath_kregs->kr_ibcstatus))]);
1680         /* flush all queued sends when going to DOWN to be sure that
1681          * they don't block MAD packets */
1682         if (linkcmd == INFINIPATH_IBCC_LINKCMD_DOWN)
1683                 ipath_cancel_sends(dd, 1);
1684
1685         ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
1686                          dd->ipath_ibcctrl | which);
1687 }
1688
1689 int ipath_set_linkstate(struct ipath_devdata *dd, u8 newstate)
1690 {
1691         u32 lstate;
1692         int ret;
1693
1694         switch (newstate) {
1695         case IPATH_IB_LINKDOWN_ONLY:
1696                 ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKCMD_DOWN <<
1697                                     INFINIPATH_IBCC_LINKCMD_SHIFT);
1698                 /* don't wait */
1699                 ret = 0;
1700                 goto bail;
1701
1702         case IPATH_IB_LINKDOWN:
1703                 ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKINITCMD_POLL <<
1704                                     INFINIPATH_IBCC_LINKINITCMD_SHIFT);
1705                 /* don't wait */
1706                 ret = 0;
1707                 goto bail;
1708
1709         case IPATH_IB_LINKDOWN_SLEEP:
1710                 ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKINITCMD_SLEEP <<
1711                                     INFINIPATH_IBCC_LINKINITCMD_SHIFT);
1712                 /* don't wait */
1713                 ret = 0;
1714                 goto bail;
1715
1716         case IPATH_IB_LINKDOWN_DISABLE:
1717                 ipath_set_ib_lstate(dd,
1718                                     INFINIPATH_IBCC_LINKINITCMD_DISABLE <<
1719                                     INFINIPATH_IBCC_LINKINITCMD_SHIFT);
1720                 /* don't wait */
1721                 ret = 0;
1722                 goto bail;
1723
1724         case IPATH_IB_LINKARM:
1725                 if (dd->ipath_flags & IPATH_LINKARMED) {
1726                         ret = 0;
1727                         goto bail;
1728                 }
1729                 if (!(dd->ipath_flags &
1730                       (IPATH_LINKINIT | IPATH_LINKACTIVE))) {
1731                         ret = -EINVAL;
1732                         goto bail;
1733                 }
1734                 ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKCMD_ARMED <<
1735                                     INFINIPATH_IBCC_LINKCMD_SHIFT);
1736                 /*
1737                  * Since the port can transition to ACTIVE by receiving
1738                  * a non VL 15 packet, wait for either state.
1739                  */
1740                 lstate = IPATH_LINKARMED | IPATH_LINKACTIVE;
1741                 break;
1742
1743         case IPATH_IB_LINKACTIVE:
1744                 if (dd->ipath_flags & IPATH_LINKACTIVE) {
1745                         ret = 0;
1746                         goto bail;
1747                 }
1748                 if (!(dd->ipath_flags & IPATH_LINKARMED)) {
1749                         ret = -EINVAL;
1750                         goto bail;
1751                 }
1752                 ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKCMD_ACTIVE <<
1753                                     INFINIPATH_IBCC_LINKCMD_SHIFT);
1754                 lstate = IPATH_LINKACTIVE;
1755                 break;
1756
1757         case IPATH_IB_LINK_LOOPBACK:
1758                 dev_info(&dd->pcidev->dev, "Enabling IB local loopback\n");
1759                 dd->ipath_ibcctrl |= INFINIPATH_IBCC_LOOPBACK;
1760                 ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
1761                                  dd->ipath_ibcctrl);
1762                 ret = 0;
1763                 goto bail; // no state change to wait for
1764
1765         case IPATH_IB_LINK_EXTERNAL:
1766                 dev_info(&dd->pcidev->dev, "Disabling IB local loopback (normal)\n");
1767                 dd->ipath_ibcctrl &= ~INFINIPATH_IBCC_LOOPBACK;
1768                 ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
1769                                  dd->ipath_ibcctrl);
1770                 ret = 0;
1771                 goto bail; // no state change to wait for
1772
1773         default:
1774                 ipath_dbg("Invalid linkstate 0x%x requested\n", newstate);
1775                 ret = -EINVAL;
1776                 goto bail;
1777         }
1778         ret = ipath_wait_linkstate(dd, lstate, 2000);
1779
1780 bail:
1781         return ret;
1782 }
1783
1784 /**
1785  * ipath_set_mtu - set the MTU
1786  * @dd: the infinipath device
1787  * @arg: the new MTU
1788  *
1789  * we can handle "any" incoming size, the issue here is whether we
1790  * need to restrict our outgoing size.   For now, we don't do any
1791  * sanity checking on this, and we don't deal with what happens to
1792  * programs that are already running when the size changes.
1793  * NOTE: changing the MTU will usually cause the IBC to go back to
1794  * link initialize (IPATH_IBSTATE_INIT) state...
1795  */
1796 int ipath_set_mtu(struct ipath_devdata *dd, u16 arg)
1797 {
1798         u32 piosize;
1799         int changed = 0;
1800         int ret;
1801
1802         /*
1803          * mtu is IB data payload max.  It's the largest power of 2 less
1804          * than piosize (or even larger, since it only really controls the
1805          * largest we can receive; we can send the max of the mtu and
1806          * piosize).  We check that it's one of the valid IB sizes.
1807          */
1808         if (arg != 256 && arg != 512 && arg != 1024 && arg != 2048 &&
1809             (arg != 4096 || !ipath_mtu4096)) {
1810                 ipath_dbg("Trying to set invalid mtu %u, failing\n", arg);
1811                 ret = -EINVAL;
1812                 goto bail;
1813         }
1814         if (dd->ipath_ibmtu == arg) {
1815                 ret = 0;        /* same as current */
1816                 goto bail;
1817         }
1818
1819         piosize = dd->ipath_ibmaxlen;
1820         dd->ipath_ibmtu = arg;
1821
1822         if (arg >= (piosize - IPATH_PIO_MAXIBHDR)) {
1823                 /* Only if it's not the initial value (or reset to it) */
1824                 if (piosize != dd->ipath_init_ibmaxlen) {
1825                         if (arg > piosize && arg <= dd->ipath_init_ibmaxlen)
1826                                 piosize = dd->ipath_init_ibmaxlen;
1827                         dd->ipath_ibmaxlen = piosize;
1828                         changed = 1;
1829                 }
1830         } else if ((arg + IPATH_PIO_MAXIBHDR) != dd->ipath_ibmaxlen) {
1831                 piosize = arg + IPATH_PIO_MAXIBHDR;
1832                 ipath_cdbg(VERBOSE, "ibmaxlen was 0x%x, setting to 0x%x "
1833                            "(mtu 0x%x)\n", dd->ipath_ibmaxlen, piosize,
1834                            arg);
1835                 dd->ipath_ibmaxlen = piosize;
1836                 changed = 1;
1837         }
1838
1839         if (changed) {
1840                 u64 ibc = dd->ipath_ibcctrl, ibdw;
1841                 /*
1842                  * update our housekeeping variables, and set IBC max
1843                  * size, same as init code; max IBC is max we allow in
1844                  * buffer, less the qword pbc, plus 1 for ICRC, in dwords
1845                  */
1846                 dd->ipath_ibmaxlen = piosize - 2 * sizeof(u32);
1847                 ibdw = (dd->ipath_ibmaxlen >> 2) + 1;
1848                 ibc &= ~(INFINIPATH_IBCC_MAXPKTLEN_MASK <<
1849                          dd->ibcc_mpl_shift);
1850                 ibc |= ibdw << dd->ibcc_mpl_shift;
1851                 dd->ipath_ibcctrl = ibc;
1852                 ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
1853                                  dd->ipath_ibcctrl);
1854                 dd->ipath_f_tidtemplate(dd);
1855         }
1856
1857         ret = 0;
1858
1859 bail:
1860         return ret;
1861 }
1862
1863 int ipath_set_lid(struct ipath_devdata *dd, u32 arg, u8 lmc)
1864 {
1865         dd->ipath_lid = arg;
1866         dd->ipath_lmc = lmc;
1867
1868         return 0;
1869 }
1870
1871
1872 /**
1873  * ipath_write_kreg_port - write a device's per-port 64-bit kernel register
1874  * @dd: the infinipath device
1875  * @regno: the register number to write
1876  * @port: the port containing the register
1877  * @value: the value to write
1878  *
1879  * Registers that vary with the chip implementation constants (port)
1880  * use this routine.
1881  */
1882 void ipath_write_kreg_port(const struct ipath_devdata *dd, ipath_kreg regno,
1883                           unsigned port, u64 value)
1884 {
1885         u16 where;
1886
1887         if (port < dd->ipath_portcnt &&
1888             (regno == dd->ipath_kregs->kr_rcvhdraddr ||
1889              regno == dd->ipath_kregs->kr_rcvhdrtailaddr))
1890                 where = regno + port;
1891         else
1892                 where = -1;
1893
1894         ipath_write_kreg(dd, where, value);
1895 }
1896
1897 /*
1898  * Following deal with the "obviously simple" task of overriding the state
1899  * of the LEDS, which normally indicate link physical and logical status.
1900  * The complications arise in dealing with different hardware mappings
1901  * and the board-dependent routine being called from interrupts.
1902  * and then there's the requirement to _flash_ them.
1903  */
1904 #define LED_OVER_FREQ_SHIFT 8
1905 #define LED_OVER_FREQ_MASK (0xFF<<LED_OVER_FREQ_SHIFT)
1906 /* Below is "non-zero" to force override, but both actual LEDs are off */
1907 #define LED_OVER_BOTH_OFF (8)
1908
1909 static void ipath_run_led_override(unsigned long opaque)
1910 {
1911         struct ipath_devdata *dd = (struct ipath_devdata *)opaque;
1912         int timeoff;
1913         int pidx;
1914         u64 lstate, ltstate, val;
1915
1916         if (!(dd->ipath_flags & IPATH_INITTED))
1917                 return;
1918
1919         pidx = dd->ipath_led_override_phase++ & 1;
1920         dd->ipath_led_override = dd->ipath_led_override_vals[pidx];
1921         timeoff = dd->ipath_led_override_timeoff;
1922
1923         /*
1924          * below potentially restores the LED values per current status,
1925          * should also possibly setup the traffic-blink register,
1926          * but leave that to per-chip functions.
1927          */
1928         val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_ibcstatus);
1929         ltstate = (val >> INFINIPATH_IBCS_LINKTRAININGSTATE_SHIFT) &
1930                   dd->ibcs_lts_mask;
1931         lstate = (val >> dd->ibcs_ls_shift) & INFINIPATH_IBCS_LINKSTATE_MASK;
1932
1933         dd->ipath_f_setextled(dd, lstate, ltstate);
1934         mod_timer(&dd->ipath_led_override_timer, jiffies + timeoff);
1935 }
1936
1937 void ipath_set_led_override(struct ipath_devdata *dd, unsigned int val)
1938 {
1939         int timeoff, freq;
1940
1941         if (!(dd->ipath_flags & IPATH_INITTED))
1942                 return;
1943
1944         /* First check if we are blinking. If not, use 1HZ polling */
1945         timeoff = HZ;
1946         freq = (val & LED_OVER_FREQ_MASK) >> LED_OVER_FREQ_SHIFT;
1947
1948         if (freq) {
1949                 /* For blink, set each phase from one nybble of val */
1950                 dd->ipath_led_override_vals[0] = val & 0xF;
1951                 dd->ipath_led_override_vals[1] = (val >> 4) & 0xF;
1952                 timeoff = (HZ << 4)/freq;
1953         } else {
1954                 /* Non-blink set both phases the same. */
1955                 dd->ipath_led_override_vals[0] = val & 0xF;
1956                 dd->ipath_led_override_vals[1] = val & 0xF;
1957         }
1958         dd->ipath_led_override_timeoff = timeoff;
1959
1960         /*
1961          * If the timer has not already been started, do so. Use a "quick"
1962          * timeout so the function will be called soon, to look at our request.
1963          */
1964         if (atomic_inc_return(&dd->ipath_led_override_timer_active) == 1) {
1965                 /* Need to start timer */
1966                 init_timer(&dd->ipath_led_override_timer);
1967                 dd->ipath_led_override_timer.function =
1968                                                  ipath_run_led_override;
1969                 dd->ipath_led_override_timer.data = (unsigned long) dd;
1970                 dd->ipath_led_override_timer.expires = jiffies + 1;
1971                 add_timer(&dd->ipath_led_override_timer);
1972         } else {
1973                 atomic_dec(&dd->ipath_led_override_timer_active);
1974         }
1975 }
1976
1977 /**
1978  * ipath_shutdown_device - shut down a device
1979  * @dd: the infinipath device
1980  *
1981  * This is called to make the device quiet when we are about to
1982  * unload the driver, and also when the device is administratively
1983  * disabled.   It does not free any data structures.
1984  * Everything it does has to be setup again by ipath_init_chip(dd,1)
1985  */
1986 void ipath_shutdown_device(struct ipath_devdata *dd)
1987 {
1988         unsigned long flags;
1989
1990         ipath_dbg("Shutting down the device\n");
1991
1992         ipath_hol_up(dd); /* make sure user processes aren't suspended */
1993
1994         dd->ipath_flags |= IPATH_LINKUNK;
1995         dd->ipath_flags &= ~(IPATH_INITTED | IPATH_LINKDOWN |
1996                              IPATH_LINKINIT | IPATH_LINKARMED |
1997                              IPATH_LINKACTIVE);
1998         *dd->ipath_statusp &= ~(IPATH_STATUS_IB_CONF |
1999                                 IPATH_STATUS_IB_READY);
2000
2001         /* mask interrupts, but not errors */
2002         ipath_write_kreg(dd, dd->ipath_kregs->kr_intmask, 0ULL);
2003
2004         dd->ipath_rcvctrl = 0;
2005         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
2006                          dd->ipath_rcvctrl);
2007
2008         /*
2009          * gracefully stop all sends allowing any in progress to trickle out
2010          * first.
2011          */
2012         spin_lock_irqsave(&dd->ipath_sendctrl_lock, flags);
2013         dd->ipath_sendctrl = 0;
2014         ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl, dd->ipath_sendctrl);
2015         /* flush it */
2016         ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
2017         spin_unlock_irqrestore(&dd->ipath_sendctrl_lock, flags);
2018
2019         /*
2020          * enough for anything that's going to trickle out to have actually
2021          * done so.
2022          */
2023         udelay(5);
2024
2025         ipath_set_ib_lstate(dd, INFINIPATH_IBCC_LINKINITCMD_DISABLE <<
2026                             INFINIPATH_IBCC_LINKINITCMD_SHIFT);
2027         ipath_cancel_sends(dd, 0);
2028
2029         signal_ib_event(dd, IB_EVENT_PORT_ERR);
2030
2031         /* disable IBC */
2032         dd->ipath_control &= ~INFINIPATH_C_LINKENABLE;
2033         ipath_write_kreg(dd, dd->ipath_kregs->kr_control,
2034                          dd->ipath_control | INFINIPATH_C_FREEZEMODE);
2035
2036         /*
2037          * clear SerdesEnable and turn the leds off; do this here because
2038          * we are unloading, so don't count on interrupts to move along
2039          * Turn the LEDs off explictly for the same reason.
2040          */
2041         dd->ipath_f_quiet_serdes(dd);
2042
2043         /* stop all the timers that might still be running */
2044         del_timer_sync(&dd->ipath_hol_timer);
2045         if (dd->ipath_stats_timer_active) {
2046                 del_timer_sync(&dd->ipath_stats_timer);
2047                 dd->ipath_stats_timer_active = 0;
2048         }
2049
2050         /*
2051          * clear all interrupts and errors, so that the next time the driver
2052          * is loaded or device is enabled, we know that whatever is set
2053          * happened while we were unloaded
2054          */
2055         ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrclear,
2056                          ~0ULL & ~INFINIPATH_HWE_MEMBISTFAILED);
2057         ipath_write_kreg(dd, dd->ipath_kregs->kr_errorclear, -1LL);
2058         ipath_write_kreg(dd, dd->ipath_kregs->kr_intclear, -1LL);
2059
2060         ipath_cdbg(VERBOSE, "Flush time and errors to EEPROM\n");
2061         ipath_update_eeprom_log(dd);
2062 }
2063
2064 /**
2065  * ipath_free_pddata - free a port's allocated data
2066  * @dd: the infinipath device
2067  * @pd: the portdata structure
2068  *
2069  * free up any allocated data for a port
2070  * This should not touch anything that would affect a simultaneous
2071  * re-allocation of port data, because it is called after ipath_mutex
2072  * is released (and can be called from reinit as well).
2073  * It should never change any chip state, or global driver state.
2074  * (The only exception to global state is freeing the port0 port0_skbs.)
2075  */
2076 void ipath_free_pddata(struct ipath_devdata *dd, struct ipath_portdata *pd)
2077 {
2078         if (!pd)
2079                 return;
2080
2081         if (pd->port_rcvhdrq) {
2082                 ipath_cdbg(VERBOSE, "free closed port %d rcvhdrq @ %p "
2083                            "(size=%lu)\n", pd->port_port, pd->port_rcvhdrq,
2084                            (unsigned long) pd->port_rcvhdrq_size);
2085                 dma_free_coherent(&dd->pcidev->dev, pd->port_rcvhdrq_size,
2086                                   pd->port_rcvhdrq, pd->port_rcvhdrq_phys);
2087                 pd->port_rcvhdrq = NULL;
2088                 if (pd->port_rcvhdrtail_kvaddr) {
2089                         dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE,
2090                                          pd->port_rcvhdrtail_kvaddr,
2091                                          pd->port_rcvhdrqtailaddr_phys);
2092                         pd->port_rcvhdrtail_kvaddr = NULL;
2093                 }
2094         }
2095         if (pd->port_port && pd->port_rcvegrbuf) {
2096                 unsigned e;
2097
2098                 for (e = 0; e < pd->port_rcvegrbuf_chunks; e++) {
2099                         void *base = pd->port_rcvegrbuf[e];
2100                         size_t size = pd->port_rcvegrbuf_size;
2101
2102                         ipath_cdbg(VERBOSE, "egrbuf free(%p, %lu), "
2103                                    "chunk %u/%u\n", base,
2104                                    (unsigned long) size,
2105                                    e, pd->port_rcvegrbuf_chunks);
2106                         dma_free_coherent(&dd->pcidev->dev, size,
2107                                 base, pd->port_rcvegrbuf_phys[e]);
2108                 }
2109                 kfree(pd->port_rcvegrbuf);
2110                 pd->port_rcvegrbuf = NULL;
2111                 kfree(pd->port_rcvegrbuf_phys);
2112                 pd->port_rcvegrbuf_phys = NULL;
2113                 pd->port_rcvegrbuf_chunks = 0;
2114         } else if (pd->port_port == 0 && dd->ipath_port0_skbinfo) {
2115                 unsigned e;
2116                 struct ipath_skbinfo *skbinfo = dd->ipath_port0_skbinfo;
2117
2118                 dd->ipath_port0_skbinfo = NULL;
2119                 ipath_cdbg(VERBOSE, "free closed port %d "
2120                            "ipath_port0_skbinfo @ %p\n", pd->port_port,
2121                            skbinfo);
2122                 for (e = 0; e < dd->ipath_rcvegrcnt; e++)
2123                 if (skbinfo[e].skb) {
2124                         pci_unmap_single(dd->pcidev, skbinfo[e].phys,
2125                                          dd->ipath_ibmaxlen,
2126                                          PCI_DMA_FROMDEVICE);
2127                         dev_kfree_skb(skbinfo[e].skb);
2128                 }
2129                 vfree(skbinfo);
2130         }
2131         kfree(pd->port_tid_pg_list);
2132         vfree(pd->subport_uregbase);
2133         vfree(pd->subport_rcvegrbuf);
2134         vfree(pd->subport_rcvhdr_base);
2135         kfree(pd);
2136 }
2137
2138 static int __init infinipath_init(void)
2139 {
2140         int ret;
2141
2142         if (ipath_debug & __IPATH_DBG)
2143                 printk(KERN_INFO DRIVER_LOAD_MSG "%s", ib_ipath_version);
2144
2145         /*
2146          * These must be called before the driver is registered with
2147          * the PCI subsystem.
2148          */
2149         idr_init(&unit_table);
2150         if (!idr_pre_get(&unit_table, GFP_KERNEL)) {
2151                 ret = -ENOMEM;
2152                 goto bail;
2153         }
2154
2155         ret = pci_register_driver(&ipath_driver);
2156         if (ret < 0) {
2157                 printk(KERN_ERR IPATH_DRV_NAME
2158                        ": Unable to register driver: error %d\n", -ret);
2159                 goto bail_unit;
2160         }
2161
2162         ret = ipath_init_ipathfs();
2163         if (ret < 0) {
2164                 printk(KERN_ERR IPATH_DRV_NAME ": Unable to create "
2165                        "ipathfs: error %d\n", -ret);
2166                 goto bail_pci;
2167         }
2168
2169         goto bail;
2170
2171 bail_pci:
2172         pci_unregister_driver(&ipath_driver);
2173
2174 bail_unit:
2175         idr_destroy(&unit_table);
2176
2177 bail:
2178         return ret;
2179 }
2180
2181 static void __exit infinipath_cleanup(void)
2182 {
2183         ipath_exit_ipathfs();
2184
2185         ipath_cdbg(VERBOSE, "Unregistering pci driver\n");
2186         pci_unregister_driver(&ipath_driver);
2187
2188         idr_destroy(&unit_table);
2189 }
2190
2191 /**
2192  * ipath_reset_device - reset the chip if possible
2193  * @unit: the device to reset
2194  *
2195  * Whether or not reset is successful, we attempt to re-initialize the chip
2196  * (that is, much like a driver unload/reload).  We clear the INITTED flag
2197  * so that the various entry points will fail until we reinitialize.  For
2198  * now, we only allow this if no user ports are open that use chip resources
2199  */
2200 int ipath_reset_device(int unit)
2201 {
2202         int ret, i;
2203         struct ipath_devdata *dd = ipath_lookup(unit);
2204
2205         if (!dd) {
2206                 ret = -ENODEV;
2207                 goto bail;
2208         }
2209
2210         if (atomic_read(&dd->ipath_led_override_timer_active)) {
2211                 /* Need to stop LED timer, _then_ shut off LEDs */
2212                 del_timer_sync(&dd->ipath_led_override_timer);
2213                 atomic_set(&dd->ipath_led_override_timer_active, 0);
2214         }
2215
2216         /* Shut off LEDs after we are sure timer is not running */
2217         dd->ipath_led_override = LED_OVER_BOTH_OFF;
2218         dd->ipath_f_setextled(dd, 0, 0);
2219
2220         dev_info(&dd->pcidev->dev, "Reset on unit %u requested\n", unit);
2221
2222         if (!dd->ipath_kregbase || !(dd->ipath_flags & IPATH_PRESENT)) {
2223                 dev_info(&dd->pcidev->dev, "Invalid unit number %u or "
2224                          "not initialized or not present\n", unit);
2225                 ret = -ENXIO;
2226                 goto bail;
2227         }
2228
2229         if (dd->ipath_pd)
2230                 for (i = 1; i < dd->ipath_cfgports; i++) {
2231                         if (dd->ipath_pd[i] && dd->ipath_pd[i]->port_cnt) {
2232                                 ipath_dbg("unit %u port %d is in use "
2233                                           "(PID %u cmd %s), can't reset\n",
2234                                           unit, i,
2235                                           dd->ipath_pd[i]->port_pid,
2236                                           dd->ipath_pd[i]->port_comm);
2237                                 ret = -EBUSY;
2238                                 goto bail;
2239                         }
2240                 }
2241
2242         dd->ipath_flags &= ~IPATH_INITTED;
2243         ret = dd->ipath_f_reset(dd);
2244         if (ret != 1)
2245                 ipath_dbg("reset was not successful\n");
2246         ipath_dbg("Trying to reinitialize unit %u after reset attempt\n",
2247                   unit);
2248         ret = ipath_init_chip(dd, 1);
2249         if (ret)
2250                 ipath_dev_err(dd, "Reinitialize unit %u after "
2251                               "reset failed with %d\n", unit, ret);
2252         else
2253                 dev_info(&dd->pcidev->dev, "Reinitialized unit %u after "
2254                          "resetting\n", unit);
2255
2256 bail:
2257         return ret;
2258 }
2259
2260 /*
2261  * send a signal to all the processes that have the driver open
2262  * through the normal interfaces (i.e., everything other than diags
2263  * interface).  Returns number of signalled processes.
2264  */
2265 static int ipath_signal_procs(struct ipath_devdata *dd, int sig)
2266 {
2267         int i, sub, any = 0;
2268         pid_t pid;
2269
2270         if (!dd->ipath_pd)
2271                 return 0;
2272         for (i = 1; i < dd->ipath_cfgports; i++) {
2273                 if (!dd->ipath_pd[i] || !dd->ipath_pd[i]->port_cnt ||
2274                     !dd->ipath_pd[i]->port_pid)
2275                         continue;
2276                 pid = dd->ipath_pd[i]->port_pid;
2277                 dev_info(&dd->pcidev->dev, "context %d in use "
2278                           "(PID %u), sending signal %d\n",
2279                           i, pid, sig);
2280                 kill_proc(pid, sig, 1);
2281                 any++;
2282                 for (sub = 0; sub < INFINIPATH_MAX_SUBPORT; sub++) {
2283                         pid = dd->ipath_pd[i]->port_subpid[sub];
2284                         if (!pid)
2285                                 continue;
2286                         dev_info(&dd->pcidev->dev, "sub-context "
2287                                 "%d:%d in use (PID %u), sending "
2288                                 "signal %d\n", i, sub, pid, sig);
2289                         kill_proc(pid, sig, 1);
2290                         any++;
2291                 }
2292         }
2293         return any;
2294 }
2295
2296 static void ipath_hol_signal_down(struct ipath_devdata *dd)
2297 {
2298         if (ipath_signal_procs(dd, SIGSTOP))
2299                 ipath_dbg("Stopped some processes\n");
2300         ipath_cancel_sends(dd, 1);
2301 }
2302
2303
2304 static void ipath_hol_signal_up(struct ipath_devdata *dd)
2305 {
2306         if (ipath_signal_procs(dd, SIGCONT))
2307                 ipath_dbg("Continued some processes\n");
2308 }
2309
2310 /*
2311  * link is down, stop any users processes, and flush pending sends
2312  * to prevent HoL blocking, then start the HoL timer that
2313  * periodically continues, then stop procs, so they can detect
2314  * link down if they want, and do something about it.
2315  * Timer may already be running, so use __mod_timer, not add_timer.
2316  */
2317 void ipath_hol_down(struct ipath_devdata *dd)
2318 {
2319         dd->ipath_hol_state = IPATH_HOL_DOWN;
2320         ipath_hol_signal_down(dd);
2321         dd->ipath_hol_next = IPATH_HOL_DOWNCONT;
2322         dd->ipath_hol_timer.expires = jiffies +
2323                 msecs_to_jiffies(ipath_hol_timeout_ms);
2324         __mod_timer(&dd->ipath_hol_timer, dd->ipath_hol_timer.expires);
2325 }
2326
2327 /*
2328  * link is up, continue any user processes, and ensure timer
2329  * is a nop, if running.  Let timer keep running, if set; it
2330  * will nop when it sees the link is up
2331  */
2332 void ipath_hol_up(struct ipath_devdata *dd)
2333 {
2334         ipath_hol_signal_up(dd);
2335         dd->ipath_hol_state = IPATH_HOL_UP;
2336 }
2337
2338 /*
2339  * toggle the running/not running state of user proceses
2340  * to prevent HoL blocking on chip resources, but still allow
2341  * user processes to do link down special case handling.
2342  * Should only be called via the timer
2343  */
2344 void ipath_hol_event(unsigned long opaque)
2345 {
2346         struct ipath_devdata *dd = (struct ipath_devdata *)opaque;
2347
2348         if (dd->ipath_hol_next == IPATH_HOL_DOWNSTOP
2349                 && dd->ipath_hol_state != IPATH_HOL_UP) {
2350                 dd->ipath_hol_next = IPATH_HOL_DOWNCONT;
2351                 ipath_dbg("Stopping processes\n");
2352                 ipath_hol_signal_down(dd);
2353         } else { /* may do "extra" if also in ipath_hol_up() */
2354                 dd->ipath_hol_next = IPATH_HOL_DOWNSTOP;
2355                 ipath_dbg("Continuing processes\n");
2356                 ipath_hol_signal_up(dd);
2357         }
2358         if (dd->ipath_hol_state == IPATH_HOL_UP)
2359                 ipath_dbg("link's up, don't resched timer\n");
2360         else {
2361                 dd->ipath_hol_timer.expires = jiffies +
2362                         msecs_to_jiffies(ipath_hol_timeout_ms);
2363                 __mod_timer(&dd->ipath_hol_timer,
2364                         dd->ipath_hol_timer.expires);
2365         }
2366 }
2367
2368 int ipath_set_rx_pol_inv(struct ipath_devdata *dd, u8 new_pol_inv)
2369 {
2370         u64 val;
2371         if ( new_pol_inv > INFINIPATH_XGXS_RX_POL_MASK ) {
2372                 return -1;
2373         }
2374         if ( dd->ipath_rx_pol_inv != new_pol_inv ) {
2375                 dd->ipath_rx_pol_inv = new_pol_inv;
2376                 val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_xgxsconfig);
2377                 val &= ~(INFINIPATH_XGXS_RX_POL_MASK <<
2378                          INFINIPATH_XGXS_RX_POL_SHIFT);
2379                 val |= ((u64)dd->ipath_rx_pol_inv) <<
2380                         INFINIPATH_XGXS_RX_POL_SHIFT;
2381                 ipath_write_kreg(dd, dd->ipath_kregs->kr_xgxsconfig, val);
2382         }
2383         return 0;
2384 }
2385
2386 /*
2387  * Disable and enable the armlaunch error.  Used for PIO bandwidth testing on
2388  * the 7220, which is count-based, rather than trigger-based.  Safe for the
2389  * driver check, since it's at init.   Not completely safe when used for
2390  * user-mode checking, since some error checking can be lost, but not
2391  * particularly risky, and only has problematic side-effects in the face of
2392  * very buggy user code.  There is no reference counting, but that's also
2393  * fine, given the intended use.
2394  */
2395 void ipath_enable_armlaunch(struct ipath_devdata *dd)
2396 {
2397         dd->ipath_lasterror &= ~INFINIPATH_E_SPIOARMLAUNCH;
2398         ipath_write_kreg(dd, dd->ipath_kregs->kr_errorclear,
2399                 INFINIPATH_E_SPIOARMLAUNCH);
2400         dd->ipath_errormask |= INFINIPATH_E_SPIOARMLAUNCH;
2401         ipath_write_kreg(dd, dd->ipath_kregs->kr_errormask,
2402                 dd->ipath_errormask);
2403 }
2404
2405 void ipath_disable_armlaunch(struct ipath_devdata *dd)
2406 {
2407         /* so don't re-enable if already set */
2408         dd->ipath_maskederrs &= ~INFINIPATH_E_SPIOARMLAUNCH;
2409         dd->ipath_errormask &= ~INFINIPATH_E_SPIOARMLAUNCH;
2410         ipath_write_kreg(dd, dd->ipath_kregs->kr_errormask,
2411                 dd->ipath_errormask);
2412 }
2413
2414 module_init(infinipath_init);
2415 module_exit(infinipath_cleanup);