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