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