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