pandora: defconfig: update
[pandora-kernel.git] / drivers / infiniband / hw / qib / qib_file_ops.c
1 /*
2  * Copyright (c) 2006, 2007, 2008, 2009, 2010 QLogic Corporation.
3  * All rights reserved.
4  * Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34
35 #include <linux/pci.h>
36 #include <linux/poll.h>
37 #include <linux/cdev.h>
38 #include <linux/swap.h>
39 #include <linux/vmalloc.h>
40 #include <linux/highmem.h>
41 #include <linux/io.h>
42 #include <linux/uio.h>
43 #include <linux/jiffies.h>
44 #include <asm/pgtable.h>
45 #include <linux/delay.h>
46 #include <linux/export.h>
47
48 #include <rdma/ib.h>
49
50 #include "qib.h"
51 #include "qib_common.h"
52 #include "qib_user_sdma.h"
53
54 static int qib_open(struct inode *, struct file *);
55 static int qib_close(struct inode *, struct file *);
56 static ssize_t qib_write(struct file *, const char __user *, size_t, loff_t *);
57 static ssize_t qib_aio_write(struct kiocb *, const struct iovec *,
58                              unsigned long, loff_t);
59 static unsigned int qib_poll(struct file *, struct poll_table_struct *);
60 static int qib_mmapf(struct file *, struct vm_area_struct *);
61
62 static const struct file_operations qib_file_ops = {
63         .owner = THIS_MODULE,
64         .write = qib_write,
65         .aio_write = qib_aio_write,
66         .open = qib_open,
67         .release = qib_close,
68         .poll = qib_poll,
69         .mmap = qib_mmapf,
70         .llseek = noop_llseek,
71 };
72
73 /*
74  * Convert kernel virtual addresses to physical addresses so they don't
75  * potentially conflict with the chip addresses used as mmap offsets.
76  * It doesn't really matter what mmap offset we use as long as we can
77  * interpret it correctly.
78  */
79 static u64 cvt_kvaddr(void *p)
80 {
81         struct page *page;
82         u64 paddr = 0;
83
84         page = vmalloc_to_page(p);
85         if (page)
86                 paddr = page_to_pfn(page) << PAGE_SHIFT;
87
88         return paddr;
89 }
90
91 static int qib_get_base_info(struct file *fp, void __user *ubase,
92                              size_t ubase_size)
93 {
94         struct qib_ctxtdata *rcd = ctxt_fp(fp);
95         int ret = 0;
96         struct qib_base_info *kinfo = NULL;
97         struct qib_devdata *dd = rcd->dd;
98         struct qib_pportdata *ppd = rcd->ppd;
99         unsigned subctxt_cnt;
100         int shared, master;
101         size_t sz;
102
103         subctxt_cnt = rcd->subctxt_cnt;
104         if (!subctxt_cnt) {
105                 shared = 0;
106                 master = 0;
107                 subctxt_cnt = 1;
108         } else {
109                 shared = 1;
110                 master = !subctxt_fp(fp);
111         }
112
113         sz = sizeof(*kinfo);
114         /* If context sharing is not requested, allow the old size structure */
115         if (!shared)
116                 sz -= 7 * sizeof(u64);
117         if (ubase_size < sz) {
118                 ret = -EINVAL;
119                 goto bail;
120         }
121
122         kinfo = kzalloc(sizeof(*kinfo), GFP_KERNEL);
123         if (kinfo == NULL) {
124                 ret = -ENOMEM;
125                 goto bail;
126         }
127
128         ret = dd->f_get_base_info(rcd, kinfo);
129         if (ret < 0)
130                 goto bail;
131
132         kinfo->spi_rcvhdr_cnt = dd->rcvhdrcnt;
133         kinfo->spi_rcvhdrent_size = dd->rcvhdrentsize;
134         kinfo->spi_tidegrcnt = rcd->rcvegrcnt;
135         kinfo->spi_rcv_egrbufsize = dd->rcvegrbufsize;
136         /*
137          * have to mmap whole thing
138          */
139         kinfo->spi_rcv_egrbuftotlen =
140                 rcd->rcvegrbuf_chunks * rcd->rcvegrbuf_size;
141         kinfo->spi_rcv_egrperchunk = rcd->rcvegrbufs_perchunk;
142         kinfo->spi_rcv_egrchunksize = kinfo->spi_rcv_egrbuftotlen /
143                 rcd->rcvegrbuf_chunks;
144         kinfo->spi_tidcnt = dd->rcvtidcnt / subctxt_cnt;
145         if (master)
146                 kinfo->spi_tidcnt += dd->rcvtidcnt % subctxt_cnt;
147         /*
148          * for this use, may be cfgctxts summed over all chips that
149          * are are configured and present
150          */
151         kinfo->spi_nctxts = dd->cfgctxts;
152         /* unit (chip/board) our context is on */
153         kinfo->spi_unit = dd->unit;
154         kinfo->spi_port = ppd->port;
155         /* for now, only a single page */
156         kinfo->spi_tid_maxsize = PAGE_SIZE;
157
158         /*
159          * Doing this per context, and based on the skip value, etc.  This has
160          * to be the actual buffer size, since the protocol code treats it
161          * as an array.
162          *
163          * These have to be set to user addresses in the user code via mmap.
164          * These values are used on return to user code for the mmap target
165          * addresses only.  For 32 bit, same 44 bit address problem, so use
166          * the physical address, not virtual.  Before 2.6.11, using the
167          * page_address() macro worked, but in 2.6.11, even that returns the
168          * full 64 bit address (upper bits all 1's).  So far, using the
169          * physical addresses (or chip offsets, for chip mapping) works, but
170          * no doubt some future kernel release will change that, and we'll be
171          * on to yet another method of dealing with this.
172          * Normally only one of rcvhdr_tailaddr or rhf_offset is useful
173          * since the chips with non-zero rhf_offset don't normally
174          * enable tail register updates to host memory, but for testing,
175          * both can be enabled and used.
176          */
177         kinfo->spi_rcvhdr_base = (u64) rcd->rcvhdrq_phys;
178         kinfo->spi_rcvhdr_tailaddr = (u64) rcd->rcvhdrqtailaddr_phys;
179         kinfo->spi_rhf_offset = dd->rhf_offset;
180         kinfo->spi_rcv_egrbufs = (u64) rcd->rcvegr_phys;
181         kinfo->spi_pioavailaddr = (u64) dd->pioavailregs_phys;
182         /* setup per-unit (not port) status area for user programs */
183         kinfo->spi_status = (u64) kinfo->spi_pioavailaddr +
184                 (char *) ppd->statusp -
185                 (char *) dd->pioavailregs_dma;
186         kinfo->spi_uregbase = (u64) dd->uregbase + dd->ureg_align * rcd->ctxt;
187         if (!shared) {
188                 kinfo->spi_piocnt = rcd->piocnt;
189                 kinfo->spi_piobufbase = (u64) rcd->piobufs;
190                 kinfo->spi_sendbuf_status = cvt_kvaddr(rcd->user_event_mask);
191         } else if (master) {
192                 kinfo->spi_piocnt = (rcd->piocnt / subctxt_cnt) +
193                                     (rcd->piocnt % subctxt_cnt);
194                 /* Master's PIO buffers are after all the slave's */
195                 kinfo->spi_piobufbase = (u64) rcd->piobufs +
196                         dd->palign *
197                         (rcd->piocnt - kinfo->spi_piocnt);
198         } else {
199                 unsigned slave = subctxt_fp(fp) - 1;
200
201                 kinfo->spi_piocnt = rcd->piocnt / subctxt_cnt;
202                 kinfo->spi_piobufbase = (u64) rcd->piobufs +
203                         dd->palign * kinfo->spi_piocnt * slave;
204         }
205
206         if (shared) {
207                 kinfo->spi_sendbuf_status =
208                         cvt_kvaddr(&rcd->user_event_mask[subctxt_fp(fp)]);
209                 /* only spi_subctxt_* fields should be set in this block! */
210                 kinfo->spi_subctxt_uregbase = cvt_kvaddr(rcd->subctxt_uregbase);
211
212                 kinfo->spi_subctxt_rcvegrbuf =
213                         cvt_kvaddr(rcd->subctxt_rcvegrbuf);
214                 kinfo->spi_subctxt_rcvhdr_base =
215                         cvt_kvaddr(rcd->subctxt_rcvhdr_base);
216         }
217
218         /*
219          * All user buffers are 2KB buffers.  If we ever support
220          * giving 4KB buffers to user processes, this will need some
221          * work.  Can't use piobufbase directly, because it has
222          * both 2K and 4K buffer base values.
223          */
224         kinfo->spi_pioindex = (kinfo->spi_piobufbase - dd->pio2k_bufbase) /
225                 dd->palign;
226         kinfo->spi_pioalign = dd->palign;
227         kinfo->spi_qpair = QIB_KD_QP;
228         /*
229          * user mode PIO buffers are always 2KB, even when 4KB can
230          * be received, and sent via the kernel; this is ibmaxlen
231          * for 2K MTU.
232          */
233         kinfo->spi_piosize = dd->piosize2k - 2 * sizeof(u32);
234         kinfo->spi_mtu = ppd->ibmaxlen; /* maxlen, not ibmtu */
235         kinfo->spi_ctxt = rcd->ctxt;
236         kinfo->spi_subctxt = subctxt_fp(fp);
237         kinfo->spi_sw_version = QIB_KERN_SWVERSION;
238         kinfo->spi_sw_version |= 1U << 31; /* QLogic-built, not kernel.org */
239         kinfo->spi_hw_version = dd->revision;
240
241         if (master)
242                 kinfo->spi_runtime_flags |= QIB_RUNTIME_MASTER;
243
244         sz = (ubase_size < sizeof(*kinfo)) ? ubase_size : sizeof(*kinfo);
245         if (copy_to_user(ubase, kinfo, sz))
246                 ret = -EFAULT;
247 bail:
248         kfree(kinfo);
249         return ret;
250 }
251
252 /**
253  * qib_tid_update - update a context TID
254  * @rcd: the context
255  * @fp: the qib device file
256  * @ti: the TID information
257  *
258  * The new implementation as of Oct 2004 is that the driver assigns
259  * the tid and returns it to the caller.   To reduce search time, we
260  * keep a cursor for each context, walking the shadow tid array to find
261  * one that's not in use.
262  *
263  * For now, if we can't allocate the full list, we fail, although
264  * in the long run, we'll allocate as many as we can, and the
265  * caller will deal with that by trying the remaining pages later.
266  * That means that when we fail, we have to mark the tids as not in
267  * use again, in our shadow copy.
268  *
269  * It's up to the caller to free the tids when they are done.
270  * We'll unlock the pages as they free them.
271  *
272  * Also, right now we are locking one page at a time, but since
273  * the intended use of this routine is for a single group of
274  * virtually contiguous pages, that should change to improve
275  * performance.
276  */
277 static int qib_tid_update(struct qib_ctxtdata *rcd, struct file *fp,
278                           const struct qib_tid_info *ti)
279 {
280         int ret = 0, ntids;
281         u32 tid, ctxttid, cnt, i, tidcnt, tidoff;
282         u16 *tidlist;
283         struct qib_devdata *dd = rcd->dd;
284         u64 physaddr;
285         unsigned long vaddr;
286         u64 __iomem *tidbase;
287         unsigned long tidmap[8];
288         struct page **pagep = NULL;
289         unsigned subctxt = subctxt_fp(fp);
290
291         if (!dd->pageshadow) {
292                 ret = -ENOMEM;
293                 goto done;
294         }
295
296         cnt = ti->tidcnt;
297         if (!cnt) {
298                 ret = -EFAULT;
299                 goto done;
300         }
301         ctxttid = rcd->ctxt * dd->rcvtidcnt;
302         if (!rcd->subctxt_cnt) {
303                 tidcnt = dd->rcvtidcnt;
304                 tid = rcd->tidcursor;
305                 tidoff = 0;
306         } else if (!subctxt) {
307                 tidcnt = (dd->rcvtidcnt / rcd->subctxt_cnt) +
308                          (dd->rcvtidcnt % rcd->subctxt_cnt);
309                 tidoff = dd->rcvtidcnt - tidcnt;
310                 ctxttid += tidoff;
311                 tid = tidcursor_fp(fp);
312         } else {
313                 tidcnt = dd->rcvtidcnt / rcd->subctxt_cnt;
314                 tidoff = tidcnt * (subctxt - 1);
315                 ctxttid += tidoff;
316                 tid = tidcursor_fp(fp);
317         }
318         if (cnt > tidcnt) {
319                 /* make sure it all fits in tid_pg_list */
320                 qib_devinfo(dd->pcidev, "Process tried to allocate %u "
321                          "TIDs, only trying max (%u)\n", cnt, tidcnt);
322                 cnt = tidcnt;
323         }
324         pagep = (struct page **) rcd->tid_pg_list;
325         tidlist = (u16 *) &pagep[dd->rcvtidcnt];
326         pagep += tidoff;
327         tidlist += tidoff;
328
329         memset(tidmap, 0, sizeof(tidmap));
330         /* before decrement; chip actual # */
331         ntids = tidcnt;
332         tidbase = (u64 __iomem *) (((char __iomem *) dd->kregbase) +
333                                    dd->rcvtidbase +
334                                    ctxttid * sizeof(*tidbase));
335
336         /* virtual address of first page in transfer */
337         vaddr = ti->tidvaddr;
338         if (!access_ok(VERIFY_WRITE, (void __user *) vaddr,
339                        cnt * PAGE_SIZE)) {
340                 ret = -EFAULT;
341                 goto done;
342         }
343         ret = qib_get_user_pages(vaddr, cnt, pagep);
344         if (ret) {
345                 /*
346                  * if (ret == -EBUSY)
347                  * We can't continue because the pagep array won't be
348                  * initialized. This should never happen,
349                  * unless perhaps the user has mpin'ed the pages
350                  * themselves.
351                  */
352                 qib_devinfo(dd->pcidev,
353                          "Failed to lock addr %p, %u pages: "
354                          "errno %d\n", (void *) vaddr, cnt, -ret);
355                 goto done;
356         }
357         for (i = 0; i < cnt; i++, vaddr += PAGE_SIZE) {
358                 for (; ntids--; tid++) {
359                         if (tid == tidcnt)
360                                 tid = 0;
361                         if (!dd->pageshadow[ctxttid + tid])
362                                 break;
363                 }
364                 if (ntids < 0) {
365                         /*
366                          * Oops, wrapped all the way through their TIDs,
367                          * and didn't have enough free; see comments at
368                          * start of routine
369                          */
370                         i--;    /* last tidlist[i] not filled in */
371                         ret = -ENOMEM;
372                         break;
373                 }
374                 tidlist[i] = tid + tidoff;
375                 /* we "know" system pages and TID pages are same size */
376                 dd->pageshadow[ctxttid + tid] = pagep[i];
377                 dd->physshadow[ctxttid + tid] =
378                         qib_map_page(dd->pcidev, pagep[i], 0, PAGE_SIZE,
379                                      PCI_DMA_FROMDEVICE);
380                 /*
381                  * don't need atomic or it's overhead
382                  */
383                 __set_bit(tid, tidmap);
384                 physaddr = dd->physshadow[ctxttid + tid];
385                 /* PERFORMANCE: below should almost certainly be cached */
386                 dd->f_put_tid(dd, &tidbase[tid],
387                                   RCVHQ_RCV_TYPE_EXPECTED, physaddr);
388                 /*
389                  * don't check this tid in qib_ctxtshadow, since we
390                  * just filled it in; start with the next one.
391                  */
392                 tid++;
393         }
394
395         if (ret) {
396                 u32 limit;
397 cleanup:
398                 /* jump here if copy out of updated info failed... */
399                 /* same code that's in qib_free_tid() */
400                 limit = sizeof(tidmap) * BITS_PER_BYTE;
401                 if (limit > tidcnt)
402                         /* just in case size changes in future */
403                         limit = tidcnt;
404                 tid = find_first_bit((const unsigned long *)tidmap, limit);
405                 for (; tid < limit; tid++) {
406                         if (!test_bit(tid, tidmap))
407                                 continue;
408                         if (dd->pageshadow[ctxttid + tid]) {
409                                 dma_addr_t phys;
410
411                                 phys = dd->physshadow[ctxttid + tid];
412                                 dd->physshadow[ctxttid + tid] = dd->tidinvalid;
413                                 /* PERFORMANCE: below should almost certainly
414                                  * be cached
415                                  */
416                                 dd->f_put_tid(dd, &tidbase[tid],
417                                               RCVHQ_RCV_TYPE_EXPECTED,
418                                               dd->tidinvalid);
419                                 pci_unmap_page(dd->pcidev, phys, PAGE_SIZE,
420                                                PCI_DMA_FROMDEVICE);
421                                 dd->pageshadow[ctxttid + tid] = NULL;
422                         }
423                 }
424                 qib_release_user_pages(pagep, cnt);
425         } else {
426                 /*
427                  * Copy the updated array, with qib_tid's filled in, back
428                  * to user.  Since we did the copy in already, this "should
429                  * never fail" If it does, we have to clean up...
430                  */
431                 if (copy_to_user((void __user *)
432                                  (unsigned long) ti->tidlist,
433                                  tidlist, cnt * sizeof(*tidlist))) {
434                         ret = -EFAULT;
435                         goto cleanup;
436                 }
437                 if (copy_to_user((void __user *) (unsigned long) ti->tidmap,
438                                  tidmap, sizeof tidmap)) {
439                         ret = -EFAULT;
440                         goto cleanup;
441                 }
442                 if (tid == tidcnt)
443                         tid = 0;
444                 if (!rcd->subctxt_cnt)
445                         rcd->tidcursor = tid;
446                 else
447                         tidcursor_fp(fp) = tid;
448         }
449
450 done:
451         return ret;
452 }
453
454 /**
455  * qib_tid_free - free a context TID
456  * @rcd: the context
457  * @subctxt: the subcontext
458  * @ti: the TID info
459  *
460  * right now we are unlocking one page at a time, but since
461  * the intended use of this routine is for a single group of
462  * virtually contiguous pages, that should change to improve
463  * performance.  We check that the TID is in range for this context
464  * but otherwise don't check validity; if user has an error and
465  * frees the wrong tid, it's only their own data that can thereby
466  * be corrupted.  We do check that the TID was in use, for sanity
467  * We always use our idea of the saved address, not the address that
468  * they pass in to us.
469  */
470 static int qib_tid_free(struct qib_ctxtdata *rcd, unsigned subctxt,
471                         const struct qib_tid_info *ti)
472 {
473         int ret = 0;
474         u32 tid, ctxttid, cnt, limit, tidcnt;
475         struct qib_devdata *dd = rcd->dd;
476         u64 __iomem *tidbase;
477         unsigned long tidmap[8];
478
479         if (!dd->pageshadow) {
480                 ret = -ENOMEM;
481                 goto done;
482         }
483
484         if (copy_from_user(tidmap, (void __user *)(unsigned long)ti->tidmap,
485                            sizeof tidmap)) {
486                 ret = -EFAULT;
487                 goto done;
488         }
489
490         ctxttid = rcd->ctxt * dd->rcvtidcnt;
491         if (!rcd->subctxt_cnt)
492                 tidcnt = dd->rcvtidcnt;
493         else if (!subctxt) {
494                 tidcnt = (dd->rcvtidcnt / rcd->subctxt_cnt) +
495                          (dd->rcvtidcnt % rcd->subctxt_cnt);
496                 ctxttid += dd->rcvtidcnt - tidcnt;
497         } else {
498                 tidcnt = dd->rcvtidcnt / rcd->subctxt_cnt;
499                 ctxttid += tidcnt * (subctxt - 1);
500         }
501         tidbase = (u64 __iomem *) ((char __iomem *)(dd->kregbase) +
502                                    dd->rcvtidbase +
503                                    ctxttid * sizeof(*tidbase));
504
505         limit = sizeof(tidmap) * BITS_PER_BYTE;
506         if (limit > tidcnt)
507                 /* just in case size changes in future */
508                 limit = tidcnt;
509         tid = find_first_bit(tidmap, limit);
510         for (cnt = 0; tid < limit; tid++) {
511                 /*
512                  * small optimization; if we detect a run of 3 or so without
513                  * any set, use find_first_bit again.  That's mainly to
514                  * accelerate the case where we wrapped, so we have some at
515                  * the beginning, and some at the end, and a big gap
516                  * in the middle.
517                  */
518                 if (!test_bit(tid, tidmap))
519                         continue;
520                 cnt++;
521                 if (dd->pageshadow[ctxttid + tid]) {
522                         struct page *p;
523                         dma_addr_t phys;
524
525                         p = dd->pageshadow[ctxttid + tid];
526                         dd->pageshadow[ctxttid + tid] = NULL;
527                         phys = dd->physshadow[ctxttid + tid];
528                         dd->physshadow[ctxttid + tid] = dd->tidinvalid;
529                         /* PERFORMANCE: below should almost certainly be
530                          * cached
531                          */
532                         dd->f_put_tid(dd, &tidbase[tid],
533                                       RCVHQ_RCV_TYPE_EXPECTED, dd->tidinvalid);
534                         pci_unmap_page(dd->pcidev, phys, PAGE_SIZE,
535                                        PCI_DMA_FROMDEVICE);
536                         qib_release_user_pages(&p, 1);
537                 }
538         }
539 done:
540         return ret;
541 }
542
543 /**
544  * qib_set_part_key - set a partition key
545  * @rcd: the context
546  * @key: the key
547  *
548  * We can have up to 4 active at a time (other than the default, which is
549  * always allowed).  This is somewhat tricky, since multiple contexts may set
550  * the same key, so we reference count them, and clean up at exit.  All 4
551  * partition keys are packed into a single qlogic_ib register.  It's an
552  * error for a process to set the same pkey multiple times.  We provide no
553  * mechanism to de-allocate a pkey at this time, we may eventually need to
554  * do that.  I've used the atomic operations, and no locking, and only make
555  * a single pass through what's available.  This should be more than
556  * adequate for some time. I'll think about spinlocks or the like if and as
557  * it's necessary.
558  */
559 static int qib_set_part_key(struct qib_ctxtdata *rcd, u16 key)
560 {
561         struct qib_pportdata *ppd = rcd->ppd;
562         int i, any = 0, pidx = -1;
563         u16 lkey = key & 0x7FFF;
564         int ret;
565
566         if (lkey == (QIB_DEFAULT_P_KEY & 0x7FFF)) {
567                 /* nothing to do; this key always valid */
568                 ret = 0;
569                 goto bail;
570         }
571
572         if (!lkey) {
573                 ret = -EINVAL;
574                 goto bail;
575         }
576
577         /*
578          * Set the full membership bit, because it has to be
579          * set in the register or the packet, and it seems
580          * cleaner to set in the register than to force all
581          * callers to set it.
582          */
583         key |= 0x8000;
584
585         for (i = 0; i < ARRAY_SIZE(rcd->pkeys); i++) {
586                 if (!rcd->pkeys[i] && pidx == -1)
587                         pidx = i;
588                 if (rcd->pkeys[i] == key) {
589                         ret = -EEXIST;
590                         goto bail;
591                 }
592         }
593         if (pidx == -1) {
594                 ret = -EBUSY;
595                 goto bail;
596         }
597         for (any = i = 0; i < ARRAY_SIZE(ppd->pkeys); i++) {
598                 if (!ppd->pkeys[i]) {
599                         any++;
600                         continue;
601                 }
602                 if (ppd->pkeys[i] == key) {
603                         atomic_t *pkrefs = &ppd->pkeyrefs[i];
604
605                         if (atomic_inc_return(pkrefs) > 1) {
606                                 rcd->pkeys[pidx] = key;
607                                 ret = 0;
608                                 goto bail;
609                         } else {
610                                 /*
611                                  * lost race, decrement count, catch below
612                                  */
613                                 atomic_dec(pkrefs);
614                                 any++;
615                         }
616                 }
617                 if ((ppd->pkeys[i] & 0x7FFF) == lkey) {
618                         /*
619                          * It makes no sense to have both the limited and
620                          * full membership PKEY set at the same time since
621                          * the unlimited one will disable the limited one.
622                          */
623                         ret = -EEXIST;
624                         goto bail;
625                 }
626         }
627         if (!any) {
628                 ret = -EBUSY;
629                 goto bail;
630         }
631         for (any = i = 0; i < ARRAY_SIZE(ppd->pkeys); i++) {
632                 if (!ppd->pkeys[i] &&
633                     atomic_inc_return(&ppd->pkeyrefs[i]) == 1) {
634                         rcd->pkeys[pidx] = key;
635                         ppd->pkeys[i] = key;
636                         (void) ppd->dd->f_set_ib_cfg(ppd, QIB_IB_CFG_PKEYS, 0);
637                         ret = 0;
638                         goto bail;
639                 }
640         }
641         ret = -EBUSY;
642
643 bail:
644         return ret;
645 }
646
647 /**
648  * qib_manage_rcvq - manage a context's receive queue
649  * @rcd: the context
650  * @subctxt: the subcontext
651  * @start_stop: action to carry out
652  *
653  * start_stop == 0 disables receive on the context, for use in queue
654  * overflow conditions.  start_stop==1 re-enables, to be used to
655  * re-init the software copy of the head register
656  */
657 static int qib_manage_rcvq(struct qib_ctxtdata *rcd, unsigned subctxt,
658                            int start_stop)
659 {
660         struct qib_devdata *dd = rcd->dd;
661         unsigned int rcvctrl_op;
662
663         if (subctxt)
664                 goto bail;
665         /* atomically clear receive enable ctxt. */
666         if (start_stop) {
667                 /*
668                  * On enable, force in-memory copy of the tail register to
669                  * 0, so that protocol code doesn't have to worry about
670                  * whether or not the chip has yet updated the in-memory
671                  * copy or not on return from the system call. The chip
672                  * always resets it's tail register back to 0 on a
673                  * transition from disabled to enabled.
674                  */
675                 if (rcd->rcvhdrtail_kvaddr)
676                         qib_clear_rcvhdrtail(rcd);
677                 rcvctrl_op = QIB_RCVCTRL_CTXT_ENB;
678         } else
679                 rcvctrl_op = QIB_RCVCTRL_CTXT_DIS;
680         dd->f_rcvctrl(rcd->ppd, rcvctrl_op, rcd->ctxt);
681         /* always; new head should be equal to new tail; see above */
682 bail:
683         return 0;
684 }
685
686 static void qib_clean_part_key(struct qib_ctxtdata *rcd,
687                                struct qib_devdata *dd)
688 {
689         int i, j, pchanged = 0;
690         u64 oldpkey;
691         struct qib_pportdata *ppd = rcd->ppd;
692
693         /* for debugging only */
694         oldpkey = (u64) ppd->pkeys[0] |
695                 ((u64) ppd->pkeys[1] << 16) |
696                 ((u64) ppd->pkeys[2] << 32) |
697                 ((u64) ppd->pkeys[3] << 48);
698
699         for (i = 0; i < ARRAY_SIZE(rcd->pkeys); i++) {
700                 if (!rcd->pkeys[i])
701                         continue;
702                 for (j = 0; j < ARRAY_SIZE(ppd->pkeys); j++) {
703                         /* check for match independent of the global bit */
704                         if ((ppd->pkeys[j] & 0x7fff) !=
705                             (rcd->pkeys[i] & 0x7fff))
706                                 continue;
707                         if (atomic_dec_and_test(&ppd->pkeyrefs[j])) {
708                                 ppd->pkeys[j] = 0;
709                                 pchanged++;
710                         }
711                         break;
712                 }
713                 rcd->pkeys[i] = 0;
714         }
715         if (pchanged)
716                 (void) ppd->dd->f_set_ib_cfg(ppd, QIB_IB_CFG_PKEYS, 0);
717 }
718
719 /* common code for the mappings on dma_alloc_coherent mem */
720 static int qib_mmap_mem(struct vm_area_struct *vma, struct qib_ctxtdata *rcd,
721                         unsigned len, void *kvaddr, u32 write_ok, char *what)
722 {
723         struct qib_devdata *dd = rcd->dd;
724         unsigned long pfn;
725         int ret;
726
727         if ((vma->vm_end - vma->vm_start) > len) {
728                 qib_devinfo(dd->pcidev,
729                          "FAIL on %s: len %lx > %x\n", what,
730                          vma->vm_end - vma->vm_start, len);
731                 ret = -EFAULT;
732                 goto bail;
733         }
734
735         /*
736          * shared context user code requires rcvhdrq mapped r/w, others
737          * only allowed readonly mapping.
738          */
739         if (!write_ok) {
740                 if (vma->vm_flags & VM_WRITE) {
741                         qib_devinfo(dd->pcidev,
742                                  "%s must be mapped readonly\n", what);
743                         ret = -EPERM;
744                         goto bail;
745                 }
746
747                 /* don't allow them to later change with mprotect */
748                 vma->vm_flags &= ~VM_MAYWRITE;
749         }
750
751         pfn = virt_to_phys(kvaddr) >> PAGE_SHIFT;
752         ret = remap_pfn_range(vma, vma->vm_start, pfn,
753                               len, vma->vm_page_prot);
754         if (ret)
755                 qib_devinfo(dd->pcidev, "%s ctxt%u mmap of %lx, %x "
756                          "bytes failed: %d\n", what, rcd->ctxt,
757                          pfn, len, ret);
758 bail:
759         return ret;
760 }
761
762 static int mmap_ureg(struct vm_area_struct *vma, struct qib_devdata *dd,
763                      u64 ureg)
764 {
765         unsigned long phys;
766         unsigned long sz;
767         int ret;
768
769         /*
770          * This is real hardware, so use io_remap.  This is the mechanism
771          * for the user process to update the head registers for their ctxt
772          * in the chip.
773          */
774         sz = dd->flags & QIB_HAS_HDRSUPP ? 2 * PAGE_SIZE : PAGE_SIZE;
775         if ((vma->vm_end - vma->vm_start) > sz) {
776                 qib_devinfo(dd->pcidev, "FAIL mmap userreg: reqlen "
777                          "%lx > PAGE\n", vma->vm_end - vma->vm_start);
778                 ret = -EFAULT;
779         } else {
780                 phys = dd->physaddr + ureg;
781                 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
782
783                 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND;
784                 ret = io_remap_pfn_range(vma, vma->vm_start,
785                                          phys >> PAGE_SHIFT,
786                                          vma->vm_end - vma->vm_start,
787                                          vma->vm_page_prot);
788         }
789         return ret;
790 }
791
792 static int mmap_piobufs(struct vm_area_struct *vma,
793                         struct qib_devdata *dd,
794                         struct qib_ctxtdata *rcd,
795                         unsigned piobufs, unsigned piocnt)
796 {
797         unsigned long phys;
798         int ret;
799
800         /*
801          * When we map the PIO buffers in the chip, we want to map them as
802          * writeonly, no read possible; unfortunately, x86 doesn't allow
803          * for this in hardware, but we still prevent users from asking
804          * for it.
805          */
806         if ((vma->vm_end - vma->vm_start) > (piocnt * dd->palign)) {
807                 qib_devinfo(dd->pcidev, "FAIL mmap piobufs: "
808                          "reqlen %lx > PAGE\n",
809                          vma->vm_end - vma->vm_start);
810                 ret = -EINVAL;
811                 goto bail;
812         }
813
814         phys = dd->physaddr + piobufs;
815
816 #if defined(__powerpc__)
817         /* There isn't a generic way to specify writethrough mappings */
818         pgprot_val(vma->vm_page_prot) |= _PAGE_NO_CACHE;
819         pgprot_val(vma->vm_page_prot) |= _PAGE_WRITETHRU;
820         pgprot_val(vma->vm_page_prot) &= ~_PAGE_GUARDED;
821 #endif
822
823         /*
824          * don't allow them to later change to readable with mprotect (for when
825          * not initially mapped readable, as is normally the case)
826          */
827         vma->vm_flags &= ~VM_MAYREAD;
828         vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND;
829
830         if (qib_wc_pat)
831                 vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
832
833         ret = io_remap_pfn_range(vma, vma->vm_start, phys >> PAGE_SHIFT,
834                                  vma->vm_end - vma->vm_start,
835                                  vma->vm_page_prot);
836 bail:
837         return ret;
838 }
839
840 static int mmap_rcvegrbufs(struct vm_area_struct *vma,
841                            struct qib_ctxtdata *rcd)
842 {
843         struct qib_devdata *dd = rcd->dd;
844         unsigned long start, size;
845         size_t total_size, i;
846         unsigned long pfn;
847         int ret;
848
849         size = rcd->rcvegrbuf_size;
850         total_size = rcd->rcvegrbuf_chunks * size;
851         if ((vma->vm_end - vma->vm_start) > total_size) {
852                 qib_devinfo(dd->pcidev, "FAIL on egr bufs: "
853                          "reqlen %lx > actual %lx\n",
854                          vma->vm_end - vma->vm_start,
855                          (unsigned long) total_size);
856                 ret = -EINVAL;
857                 goto bail;
858         }
859
860         if (vma->vm_flags & VM_WRITE) {
861                 qib_devinfo(dd->pcidev, "Can't map eager buffers as "
862                          "writable (flags=%lx)\n", vma->vm_flags);
863                 ret = -EPERM;
864                 goto bail;
865         }
866         /* don't allow them to later change to writeable with mprotect */
867         vma->vm_flags &= ~VM_MAYWRITE;
868
869         start = vma->vm_start;
870
871         for (i = 0; i < rcd->rcvegrbuf_chunks; i++, start += size) {
872                 pfn = virt_to_phys(rcd->rcvegrbuf[i]) >> PAGE_SHIFT;
873                 ret = remap_pfn_range(vma, start, pfn, size,
874                                       vma->vm_page_prot);
875                 if (ret < 0)
876                         goto bail;
877         }
878         ret = 0;
879
880 bail:
881         return ret;
882 }
883
884 /*
885  * qib_file_vma_fault - handle a VMA page fault.
886  */
887 static int qib_file_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
888 {
889         struct page *page;
890
891         page = vmalloc_to_page((void *)(vmf->pgoff << PAGE_SHIFT));
892         if (!page)
893                 return VM_FAULT_SIGBUS;
894
895         get_page(page);
896         vmf->page = page;
897
898         return 0;
899 }
900
901 static struct vm_operations_struct qib_file_vm_ops = {
902         .fault = qib_file_vma_fault,
903 };
904
905 static int mmap_kvaddr(struct vm_area_struct *vma, u64 pgaddr,
906                        struct qib_ctxtdata *rcd, unsigned subctxt)
907 {
908         struct qib_devdata *dd = rcd->dd;
909         unsigned subctxt_cnt;
910         unsigned long len;
911         void *addr;
912         size_t size;
913         int ret = 0;
914
915         subctxt_cnt = rcd->subctxt_cnt;
916         size = rcd->rcvegrbuf_chunks * rcd->rcvegrbuf_size;
917
918         /*
919          * Each process has all the subctxt uregbase, rcvhdrq, and
920          * rcvegrbufs mmapped - as an array for all the processes,
921          * and also separately for this process.
922          */
923         if (pgaddr == cvt_kvaddr(rcd->subctxt_uregbase)) {
924                 addr = rcd->subctxt_uregbase;
925                 size = PAGE_SIZE * subctxt_cnt;
926         } else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvhdr_base)) {
927                 addr = rcd->subctxt_rcvhdr_base;
928                 size = rcd->rcvhdrq_size * subctxt_cnt;
929         } else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvegrbuf)) {
930                 addr = rcd->subctxt_rcvegrbuf;
931                 size *= subctxt_cnt;
932         } else if (pgaddr == cvt_kvaddr(rcd->subctxt_uregbase +
933                                         PAGE_SIZE * subctxt)) {
934                 addr = rcd->subctxt_uregbase + PAGE_SIZE * subctxt;
935                 size = PAGE_SIZE;
936         } else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvhdr_base +
937                                         rcd->rcvhdrq_size * subctxt)) {
938                 addr = rcd->subctxt_rcvhdr_base +
939                         rcd->rcvhdrq_size * subctxt;
940                 size = rcd->rcvhdrq_size;
941         } else if (pgaddr == cvt_kvaddr(&rcd->user_event_mask[subctxt])) {
942                 addr = rcd->user_event_mask;
943                 size = PAGE_SIZE;
944         } else if (pgaddr == cvt_kvaddr(rcd->subctxt_rcvegrbuf +
945                                         size * subctxt)) {
946                 addr = rcd->subctxt_rcvegrbuf + size * subctxt;
947                 /* rcvegrbufs are read-only on the slave */
948                 if (vma->vm_flags & VM_WRITE) {
949                         qib_devinfo(dd->pcidev,
950                                  "Can't map eager buffers as "
951                                  "writable (flags=%lx)\n", vma->vm_flags);
952                         ret = -EPERM;
953                         goto bail;
954                 }
955                 /*
956                  * Don't allow permission to later change to writeable
957                  * with mprotect.
958                  */
959                 vma->vm_flags &= ~VM_MAYWRITE;
960         } else
961                 goto bail;
962         len = vma->vm_end - vma->vm_start;
963         if (len > size) {
964                 ret = -EINVAL;
965                 goto bail;
966         }
967
968         vma->vm_pgoff = (unsigned long) addr >> PAGE_SHIFT;
969         vma->vm_ops = &qib_file_vm_ops;
970         vma->vm_flags |= VM_RESERVED | VM_DONTEXPAND;
971         ret = 1;
972
973 bail:
974         return ret;
975 }
976
977 /**
978  * qib_mmapf - mmap various structures into user space
979  * @fp: the file pointer
980  * @vma: the VM area
981  *
982  * We use this to have a shared buffer between the kernel and the user code
983  * for the rcvhdr queue, egr buffers, and the per-context user regs and pio
984  * buffers in the chip.  We have the open and close entries so we can bump
985  * the ref count and keep the driver from being unloaded while still mapped.
986  */
987 static int qib_mmapf(struct file *fp, struct vm_area_struct *vma)
988 {
989         struct qib_ctxtdata *rcd;
990         struct qib_devdata *dd;
991         u64 pgaddr, ureg;
992         unsigned piobufs, piocnt;
993         int ret, match = 1;
994
995         rcd = ctxt_fp(fp);
996         if (!rcd || !(vma->vm_flags & VM_SHARED)) {
997                 ret = -EINVAL;
998                 goto bail;
999         }
1000         dd = rcd->dd;
1001
1002         /*
1003          * This is the qib_do_user_init() code, mapping the shared buffers
1004          * and per-context user registers into the user process. The address
1005          * referred to by vm_pgoff is the file offset passed via mmap().
1006          * For shared contexts, this is the kernel vmalloc() address of the
1007          * pages to share with the master.
1008          * For non-shared or master ctxts, this is a physical address.
1009          * We only do one mmap for each space mapped.
1010          */
1011         pgaddr = vma->vm_pgoff << PAGE_SHIFT;
1012
1013         /*
1014          * Check for 0 in case one of the allocations failed, but user
1015          * called mmap anyway.
1016          */
1017         if (!pgaddr)  {
1018                 ret = -EINVAL;
1019                 goto bail;
1020         }
1021
1022         /*
1023          * Physical addresses must fit in 40 bits for our hardware.
1024          * Check for kernel virtual addresses first, anything else must
1025          * match a HW or memory address.
1026          */
1027         ret = mmap_kvaddr(vma, pgaddr, rcd, subctxt_fp(fp));
1028         if (ret) {
1029                 if (ret > 0)
1030                         ret = 0;
1031                 goto bail;
1032         }
1033
1034         ureg = dd->uregbase + dd->ureg_align * rcd->ctxt;
1035         if (!rcd->subctxt_cnt) {
1036                 /* ctxt is not shared */
1037                 piocnt = rcd->piocnt;
1038                 piobufs = rcd->piobufs;
1039         } else if (!subctxt_fp(fp)) {
1040                 /* caller is the master */
1041                 piocnt = (rcd->piocnt / rcd->subctxt_cnt) +
1042                          (rcd->piocnt % rcd->subctxt_cnt);
1043                 piobufs = rcd->piobufs +
1044                         dd->palign * (rcd->piocnt - piocnt);
1045         } else {
1046                 unsigned slave = subctxt_fp(fp) - 1;
1047
1048                 /* caller is a slave */
1049                 piocnt = rcd->piocnt / rcd->subctxt_cnt;
1050                 piobufs = rcd->piobufs + dd->palign * piocnt * slave;
1051         }
1052
1053         if (pgaddr == ureg)
1054                 ret = mmap_ureg(vma, dd, ureg);
1055         else if (pgaddr == piobufs)
1056                 ret = mmap_piobufs(vma, dd, rcd, piobufs, piocnt);
1057         else if (pgaddr == dd->pioavailregs_phys)
1058                 /* in-memory copy of pioavail registers */
1059                 ret = qib_mmap_mem(vma, rcd, PAGE_SIZE,
1060                                    (void *) dd->pioavailregs_dma, 0,
1061                                    "pioavail registers");
1062         else if (pgaddr == rcd->rcvegr_phys)
1063                 ret = mmap_rcvegrbufs(vma, rcd);
1064         else if (pgaddr == (u64) rcd->rcvhdrq_phys)
1065                 /*
1066                  * The rcvhdrq itself; multiple pages, contiguous
1067                  * from an i/o perspective.  Shared contexts need
1068                  * to map r/w, so we allow writing.
1069                  */
1070                 ret = qib_mmap_mem(vma, rcd, rcd->rcvhdrq_size,
1071                                    rcd->rcvhdrq, 1, "rcvhdrq");
1072         else if (pgaddr == (u64) rcd->rcvhdrqtailaddr_phys)
1073                 /* in-memory copy of rcvhdrq tail register */
1074                 ret = qib_mmap_mem(vma, rcd, PAGE_SIZE,
1075                                    rcd->rcvhdrtail_kvaddr, 0,
1076                                    "rcvhdrq tail");
1077         else
1078                 match = 0;
1079         if (!match)
1080                 ret = -EINVAL;
1081
1082         vma->vm_private_data = NULL;
1083
1084         if (ret < 0)
1085                 qib_devinfo(dd->pcidev,
1086                          "mmap Failure %d: off %llx len %lx\n",
1087                          -ret, (unsigned long long)pgaddr,
1088                          vma->vm_end - vma->vm_start);
1089 bail:
1090         return ret;
1091 }
1092
1093 static unsigned int qib_poll_urgent(struct qib_ctxtdata *rcd,
1094                                     struct file *fp,
1095                                     struct poll_table_struct *pt)
1096 {
1097         struct qib_devdata *dd = rcd->dd;
1098         unsigned pollflag;
1099
1100         poll_wait(fp, &rcd->wait, pt);
1101
1102         spin_lock_irq(&dd->uctxt_lock);
1103         if (rcd->urgent != rcd->urgent_poll) {
1104                 pollflag = POLLIN | POLLRDNORM;
1105                 rcd->urgent_poll = rcd->urgent;
1106         } else {
1107                 pollflag = 0;
1108                 set_bit(QIB_CTXT_WAITING_URG, &rcd->flag);
1109         }
1110         spin_unlock_irq(&dd->uctxt_lock);
1111
1112         return pollflag;
1113 }
1114
1115 static unsigned int qib_poll_next(struct qib_ctxtdata *rcd,
1116                                   struct file *fp,
1117                                   struct poll_table_struct *pt)
1118 {
1119         struct qib_devdata *dd = rcd->dd;
1120         unsigned pollflag;
1121
1122         poll_wait(fp, &rcd->wait, pt);
1123
1124         spin_lock_irq(&dd->uctxt_lock);
1125         if (dd->f_hdrqempty(rcd)) {
1126                 set_bit(QIB_CTXT_WAITING_RCV, &rcd->flag);
1127                 dd->f_rcvctrl(rcd->ppd, QIB_RCVCTRL_INTRAVAIL_ENB, rcd->ctxt);
1128                 pollflag = 0;
1129         } else
1130                 pollflag = POLLIN | POLLRDNORM;
1131         spin_unlock_irq(&dd->uctxt_lock);
1132
1133         return pollflag;
1134 }
1135
1136 static unsigned int qib_poll(struct file *fp, struct poll_table_struct *pt)
1137 {
1138         struct qib_ctxtdata *rcd;
1139         unsigned pollflag;
1140
1141         rcd = ctxt_fp(fp);
1142         if (!rcd)
1143                 pollflag = POLLERR;
1144         else if (rcd->poll_type == QIB_POLL_TYPE_URGENT)
1145                 pollflag = qib_poll_urgent(rcd, fp, pt);
1146         else  if (rcd->poll_type == QIB_POLL_TYPE_ANYRCV)
1147                 pollflag = qib_poll_next(rcd, fp, pt);
1148         else /* invalid */
1149                 pollflag = POLLERR;
1150
1151         return pollflag;
1152 }
1153
1154 /*
1155  * Check that userland and driver are compatible for subcontexts.
1156  */
1157 static int qib_compatible_subctxts(int user_swmajor, int user_swminor)
1158 {
1159         /* this code is written long-hand for clarity */
1160         if (QIB_USER_SWMAJOR != user_swmajor) {
1161                 /* no promise of compatibility if major mismatch */
1162                 return 0;
1163         }
1164         if (QIB_USER_SWMAJOR == 1) {
1165                 switch (QIB_USER_SWMINOR) {
1166                 case 0:
1167                 case 1:
1168                 case 2:
1169                         /* no subctxt implementation so cannot be compatible */
1170                         return 0;
1171                 case 3:
1172                         /* 3 is only compatible with itself */
1173                         return user_swminor == 3;
1174                 default:
1175                         /* >= 4 are compatible (or are expected to be) */
1176                         return user_swminor >= 4;
1177                 }
1178         }
1179         /* make no promises yet for future major versions */
1180         return 0;
1181 }
1182
1183 static int init_subctxts(struct qib_devdata *dd,
1184                          struct qib_ctxtdata *rcd,
1185                          const struct qib_user_info *uinfo)
1186 {
1187         int ret = 0;
1188         unsigned num_subctxts;
1189         size_t size;
1190
1191         /*
1192          * If the user is requesting zero subctxts,
1193          * skip the subctxt allocation.
1194          */
1195         if (uinfo->spu_subctxt_cnt <= 0)
1196                 goto bail;
1197         num_subctxts = uinfo->spu_subctxt_cnt;
1198
1199         /* Check for subctxt compatibility */
1200         if (!qib_compatible_subctxts(uinfo->spu_userversion >> 16,
1201                 uinfo->spu_userversion & 0xffff)) {
1202                 qib_devinfo(dd->pcidev,
1203                          "Mismatched user version (%d.%d) and driver "
1204                          "version (%d.%d) while context sharing. Ensure "
1205                          "that driver and library are from the same "
1206                          "release.\n",
1207                          (int) (uinfo->spu_userversion >> 16),
1208                          (int) (uinfo->spu_userversion & 0xffff),
1209                          QIB_USER_SWMAJOR, QIB_USER_SWMINOR);
1210                 goto bail;
1211         }
1212         if (num_subctxts > QLOGIC_IB_MAX_SUBCTXT) {
1213                 ret = -EINVAL;
1214                 goto bail;
1215         }
1216
1217         rcd->subctxt_uregbase = vmalloc_user(PAGE_SIZE * num_subctxts);
1218         if (!rcd->subctxt_uregbase) {
1219                 ret = -ENOMEM;
1220                 goto bail;
1221         }
1222         /* Note: rcd->rcvhdrq_size isn't initialized yet. */
1223         size = ALIGN(dd->rcvhdrcnt * dd->rcvhdrentsize *
1224                      sizeof(u32), PAGE_SIZE) * num_subctxts;
1225         rcd->subctxt_rcvhdr_base = vmalloc_user(size);
1226         if (!rcd->subctxt_rcvhdr_base) {
1227                 ret = -ENOMEM;
1228                 goto bail_ureg;
1229         }
1230
1231         rcd->subctxt_rcvegrbuf = vmalloc_user(rcd->rcvegrbuf_chunks *
1232                                               rcd->rcvegrbuf_size *
1233                                               num_subctxts);
1234         if (!rcd->subctxt_rcvegrbuf) {
1235                 ret = -ENOMEM;
1236                 goto bail_rhdr;
1237         }
1238
1239         rcd->subctxt_cnt = uinfo->spu_subctxt_cnt;
1240         rcd->subctxt_id = uinfo->spu_subctxt_id;
1241         rcd->active_slaves = 1;
1242         rcd->redirect_seq_cnt = 1;
1243         set_bit(QIB_CTXT_MASTER_UNINIT, &rcd->flag);
1244         goto bail;
1245
1246 bail_rhdr:
1247         vfree(rcd->subctxt_rcvhdr_base);
1248 bail_ureg:
1249         vfree(rcd->subctxt_uregbase);
1250         rcd->subctxt_uregbase = NULL;
1251 bail:
1252         return ret;
1253 }
1254
1255 static int setup_ctxt(struct qib_pportdata *ppd, int ctxt,
1256                       struct file *fp, const struct qib_user_info *uinfo)
1257 {
1258         struct qib_devdata *dd = ppd->dd;
1259         struct qib_ctxtdata *rcd;
1260         void *ptmp = NULL;
1261         int ret;
1262
1263         rcd = qib_create_ctxtdata(ppd, ctxt);
1264
1265         /*
1266          * Allocate memory for use in qib_tid_update() at open to
1267          * reduce cost of expected send setup per message segment
1268          */
1269         if (rcd)
1270                 ptmp = kmalloc(dd->rcvtidcnt * sizeof(u16) +
1271                                dd->rcvtidcnt * sizeof(struct page **),
1272                                GFP_KERNEL);
1273
1274         if (!rcd || !ptmp) {
1275                 qib_dev_err(dd, "Unable to allocate ctxtdata "
1276                             "memory, failing open\n");
1277                 ret = -ENOMEM;
1278                 goto bailerr;
1279         }
1280         rcd->userversion = uinfo->spu_userversion;
1281         ret = init_subctxts(dd, rcd, uinfo);
1282         if (ret)
1283                 goto bailerr;
1284         rcd->tid_pg_list = ptmp;
1285         rcd->pid = current->pid;
1286         init_waitqueue_head(&dd->rcd[ctxt]->wait);
1287         strlcpy(rcd->comm, current->comm, sizeof(rcd->comm));
1288         ctxt_fp(fp) = rcd;
1289         qib_stats.sps_ctxts++;
1290         dd->freectxts--;
1291         ret = 0;
1292         goto bail;
1293
1294 bailerr:
1295         dd->rcd[ctxt] = NULL;
1296         kfree(rcd);
1297         kfree(ptmp);
1298 bail:
1299         return ret;
1300 }
1301
1302 static inline int usable(struct qib_pportdata *ppd)
1303 {
1304         struct qib_devdata *dd = ppd->dd;
1305
1306         return dd && (dd->flags & QIB_PRESENT) && dd->kregbase && ppd->lid &&
1307                 (ppd->lflags & QIBL_LINKACTIVE);
1308 }
1309
1310 /*
1311  * Select a context on the given device, either using a requested port
1312  * or the port based on the context number.
1313  */
1314 static int choose_port_ctxt(struct file *fp, struct qib_devdata *dd, u32 port,
1315                             const struct qib_user_info *uinfo)
1316 {
1317         struct qib_pportdata *ppd = NULL;
1318         int ret, ctxt;
1319
1320         if (port) {
1321                 if (!usable(dd->pport + port - 1)) {
1322                         ret = -ENETDOWN;
1323                         goto done;
1324                 } else
1325                         ppd = dd->pport + port - 1;
1326         }
1327         for (ctxt = dd->first_user_ctxt; ctxt < dd->cfgctxts && dd->rcd[ctxt];
1328              ctxt++)
1329                 ;
1330         if (ctxt == dd->cfgctxts) {
1331                 ret = -EBUSY;
1332                 goto done;
1333         }
1334         if (!ppd) {
1335                 u32 pidx = ctxt % dd->num_pports;
1336                 if (usable(dd->pport + pidx))
1337                         ppd = dd->pport + pidx;
1338                 else {
1339                         for (pidx = 0; pidx < dd->num_pports && !ppd;
1340                              pidx++)
1341                                 if (usable(dd->pport + pidx))
1342                                         ppd = dd->pport + pidx;
1343                 }
1344         }
1345         ret = ppd ? setup_ctxt(ppd, ctxt, fp, uinfo) : -ENETDOWN;
1346 done:
1347         return ret;
1348 }
1349
1350 static int find_free_ctxt(int unit, struct file *fp,
1351                           const struct qib_user_info *uinfo)
1352 {
1353         struct qib_devdata *dd = qib_lookup(unit);
1354         int ret;
1355
1356         if (!dd || (uinfo->spu_port && uinfo->spu_port > dd->num_pports))
1357                 ret = -ENODEV;
1358         else
1359                 ret = choose_port_ctxt(fp, dd, uinfo->spu_port, uinfo);
1360
1361         return ret;
1362 }
1363
1364 static int get_a_ctxt(struct file *fp, const struct qib_user_info *uinfo,
1365                       unsigned alg)
1366 {
1367         struct qib_devdata *udd = NULL;
1368         int ret = 0, devmax, npresent, nup, ndev, dusable = 0, i;
1369         u32 port = uinfo->spu_port, ctxt;
1370
1371         devmax = qib_count_units(&npresent, &nup);
1372         if (!npresent) {
1373                 ret = -ENXIO;
1374                 goto done;
1375         }
1376         if (nup == 0) {
1377                 ret = -ENETDOWN;
1378                 goto done;
1379         }
1380
1381         if (alg == QIB_PORT_ALG_ACROSS) {
1382                 unsigned inuse = ~0U;
1383                 /* find device (with ACTIVE ports) with fewest ctxts in use */
1384                 for (ndev = 0; ndev < devmax; ndev++) {
1385                         struct qib_devdata *dd = qib_lookup(ndev);
1386                         unsigned cused = 0, cfree = 0, pusable = 0;
1387                         if (!dd)
1388                                 continue;
1389                         if (port && port <= dd->num_pports &&
1390                             usable(dd->pport + port - 1))
1391                                 pusable = 1;
1392                         else
1393                                 for (i = 0; i < dd->num_pports; i++)
1394                                         if (usable(dd->pport + i))
1395                                                 pusable++;
1396                         if (!pusable)
1397                                 continue;
1398                         for (ctxt = dd->first_user_ctxt; ctxt < dd->cfgctxts;
1399                              ctxt++)
1400                                 if (dd->rcd[ctxt])
1401                                         cused++;
1402                                 else
1403                                         cfree++;
1404                         if (pusable && cfree && cused < inuse) {
1405                                 udd = dd;
1406                                 inuse = cused;
1407                         }
1408                 }
1409                 if (udd) {
1410                         ret = choose_port_ctxt(fp, udd, port, uinfo);
1411                         goto done;
1412                 }
1413         } else {
1414                 for (ndev = 0; ndev < devmax; ndev++) {
1415                         struct qib_devdata *dd = qib_lookup(ndev);
1416                         if (dd) {
1417                                 ret = choose_port_ctxt(fp, dd, port, uinfo);
1418                                 if (!ret)
1419                                         goto done;
1420                                 if (ret == -EBUSY)
1421                                         dusable++;
1422                         }
1423                 }
1424         }
1425         ret = dusable ? -EBUSY : -ENETDOWN;
1426
1427 done:
1428         return ret;
1429 }
1430
1431 static int find_shared_ctxt(struct file *fp,
1432                             const struct qib_user_info *uinfo)
1433 {
1434         int devmax, ndev, i;
1435         int ret = 0;
1436
1437         devmax = qib_count_units(NULL, NULL);
1438
1439         for (ndev = 0; ndev < devmax; ndev++) {
1440                 struct qib_devdata *dd = qib_lookup(ndev);
1441
1442                 /* device portion of usable() */
1443                 if (!(dd && (dd->flags & QIB_PRESENT) && dd->kregbase))
1444                         continue;
1445                 for (i = dd->first_user_ctxt; i < dd->cfgctxts; i++) {
1446                         struct qib_ctxtdata *rcd = dd->rcd[i];
1447
1448                         /* Skip ctxts which are not yet open */
1449                         if (!rcd || !rcd->cnt)
1450                                 continue;
1451                         /* Skip ctxt if it doesn't match the requested one */
1452                         if (rcd->subctxt_id != uinfo->spu_subctxt_id)
1453                                 continue;
1454                         /* Verify the sharing process matches the master */
1455                         if (rcd->subctxt_cnt != uinfo->spu_subctxt_cnt ||
1456                             rcd->userversion != uinfo->spu_userversion ||
1457                             rcd->cnt >= rcd->subctxt_cnt) {
1458                                 ret = -EINVAL;
1459                                 goto done;
1460                         }
1461                         ctxt_fp(fp) = rcd;
1462                         subctxt_fp(fp) = rcd->cnt++;
1463                         rcd->subpid[subctxt_fp(fp)] = current->pid;
1464                         tidcursor_fp(fp) = 0;
1465                         rcd->active_slaves |= 1 << subctxt_fp(fp);
1466                         ret = 1;
1467                         goto done;
1468                 }
1469         }
1470
1471 done:
1472         return ret;
1473 }
1474
1475 static int qib_open(struct inode *in, struct file *fp)
1476 {
1477         /* The real work is performed later in qib_assign_ctxt() */
1478         fp->private_data = kzalloc(sizeof(struct qib_filedata), GFP_KERNEL);
1479         if (fp->private_data) /* no cpu affinity by default */
1480                 ((struct qib_filedata *)fp->private_data)->rec_cpu_num = -1;
1481         return fp->private_data ? 0 : -ENOMEM;
1482 }
1483
1484 /*
1485  * Get ctxt early, so can set affinity prior to memory allocation.
1486  */
1487 static int qib_assign_ctxt(struct file *fp, const struct qib_user_info *uinfo)
1488 {
1489         int ret;
1490         int i_minor;
1491         unsigned swmajor, swminor, alg = QIB_PORT_ALG_ACROSS;
1492
1493         /* Check to be sure we haven't already initialized this file */
1494         if (ctxt_fp(fp)) {
1495                 ret = -EINVAL;
1496                 goto done;
1497         }
1498
1499         /* for now, if major version is different, bail */
1500         swmajor = uinfo->spu_userversion >> 16;
1501         if (swmajor != QIB_USER_SWMAJOR) {
1502                 ret = -ENODEV;
1503                 goto done;
1504         }
1505
1506         swminor = uinfo->spu_userversion & 0xffff;
1507
1508         if (swminor >= 11 && uinfo->spu_port_alg < QIB_PORT_ALG_COUNT)
1509                 alg = uinfo->spu_port_alg;
1510
1511         mutex_lock(&qib_mutex);
1512
1513         if (qib_compatible_subctxts(swmajor, swminor) &&
1514             uinfo->spu_subctxt_cnt) {
1515                 ret = find_shared_ctxt(fp, uinfo);
1516                 if (ret) {
1517                         if (ret > 0)
1518                                 ret = 0;
1519                         goto done_chk_sdma;
1520                 }
1521         }
1522
1523         i_minor = iminor(fp->f_dentry->d_inode) - QIB_USER_MINOR_BASE;
1524         if (i_minor)
1525                 ret = find_free_ctxt(i_minor - 1, fp, uinfo);
1526         else
1527                 ret = get_a_ctxt(fp, uinfo, alg);
1528
1529 done_chk_sdma:
1530         if (!ret) {
1531                 struct qib_filedata *fd = fp->private_data;
1532                 const struct qib_ctxtdata *rcd = fd->rcd;
1533                 const struct qib_devdata *dd = rcd->dd;
1534                 unsigned int weight;
1535
1536                 if (dd->flags & QIB_HAS_SEND_DMA) {
1537                         fd->pq = qib_user_sdma_queue_create(&dd->pcidev->dev,
1538                                                             dd->unit,
1539                                                             rcd->ctxt,
1540                                                             fd->subctxt);
1541                         if (!fd->pq)
1542                                 ret = -ENOMEM;
1543                 }
1544
1545                 /*
1546                  * If process has NOT already set it's affinity, select and
1547                  * reserve a processor for it, as a rendezvous for all
1548                  * users of the driver.  If they don't actually later
1549                  * set affinity to this cpu, or set it to some other cpu,
1550                  * it just means that sooner or later we don't recommend
1551                  * a cpu, and let the scheduler do it's best.
1552                  */
1553                 weight = cpumask_weight(tsk_cpus_allowed(current));
1554                 if (!ret && weight >= qib_cpulist_count) {
1555                         int cpu;
1556                         cpu = find_first_zero_bit(qib_cpulist,
1557                                                   qib_cpulist_count);
1558                         if (cpu != qib_cpulist_count) {
1559                                 __set_bit(cpu, qib_cpulist);
1560                                 fd->rec_cpu_num = cpu;
1561                         }
1562                 } else if (weight == 1 &&
1563                         test_bit(cpumask_first(tsk_cpus_allowed(current)),
1564                                  qib_cpulist))
1565                         qib_devinfo(dd->pcidev, "%s PID %u affinity "
1566                                     "set to cpu %d; already allocated\n",
1567                                     current->comm, current->pid,
1568                                     cpumask_first(tsk_cpus_allowed(current)));
1569         }
1570
1571         mutex_unlock(&qib_mutex);
1572
1573 done:
1574         return ret;
1575 }
1576
1577
1578 static int qib_do_user_init(struct file *fp,
1579                             const struct qib_user_info *uinfo)
1580 {
1581         int ret;
1582         struct qib_ctxtdata *rcd = ctxt_fp(fp);
1583         struct qib_devdata *dd;
1584         unsigned uctxt;
1585
1586         /* Subctxts don't need to initialize anything since master did it. */
1587         if (subctxt_fp(fp)) {
1588                 ret = wait_event_interruptible(rcd->wait,
1589                         !test_bit(QIB_CTXT_MASTER_UNINIT, &rcd->flag));
1590                 goto bail;
1591         }
1592
1593         dd = rcd->dd;
1594
1595         /* some ctxts may get extra buffers, calculate that here */
1596         uctxt = rcd->ctxt - dd->first_user_ctxt;
1597         if (uctxt < dd->ctxts_extrabuf) {
1598                 rcd->piocnt = dd->pbufsctxt + 1;
1599                 rcd->pio_base = rcd->piocnt * uctxt;
1600         } else {
1601                 rcd->piocnt = dd->pbufsctxt;
1602                 rcd->pio_base = rcd->piocnt * uctxt +
1603                         dd->ctxts_extrabuf;
1604         }
1605
1606         /*
1607          * All user buffers are 2KB buffers.  If we ever support
1608          * giving 4KB buffers to user processes, this will need some
1609          * work.  Can't use piobufbase directly, because it has
1610          * both 2K and 4K buffer base values.  So check and handle.
1611          */
1612         if ((rcd->pio_base + rcd->piocnt) > dd->piobcnt2k) {
1613                 if (rcd->pio_base >= dd->piobcnt2k) {
1614                         qib_dev_err(dd,
1615                                     "%u:ctxt%u: no 2KB buffers available\n",
1616                                     dd->unit, rcd->ctxt);
1617                         ret = -ENOBUFS;
1618                         goto bail;
1619                 }
1620                 rcd->piocnt = dd->piobcnt2k - rcd->pio_base;
1621                 qib_dev_err(dd, "Ctxt%u: would use 4KB bufs, using %u\n",
1622                             rcd->ctxt, rcd->piocnt);
1623         }
1624
1625         rcd->piobufs = dd->pio2k_bufbase + rcd->pio_base * dd->palign;
1626         qib_chg_pioavailkernel(dd, rcd->pio_base, rcd->piocnt,
1627                                TXCHK_CHG_TYPE_USER, rcd);
1628         /*
1629          * try to ensure that processes start up with consistent avail update
1630          * for their own range, at least.   If system very quiet, it might
1631          * have the in-memory copy out of date at startup for this range of
1632          * buffers, when a context gets re-used.  Do after the chg_pioavail
1633          * and before the rest of setup, so it's "almost certain" the dma
1634          * will have occurred (can't 100% guarantee, but should be many
1635          * decimals of 9s, with this ordering), given how much else happens
1636          * after this.
1637          */
1638         dd->f_sendctrl(dd->pport, QIB_SENDCTRL_AVAIL_BLIP);
1639
1640         /*
1641          * Now allocate the rcvhdr Q and eager TIDs; skip the TID
1642          * array for time being.  If rcd->ctxt > chip-supported,
1643          * we need to do extra stuff here to handle by handling overflow
1644          * through ctxt 0, someday
1645          */
1646         ret = qib_create_rcvhdrq(dd, rcd);
1647         if (!ret)
1648                 ret = qib_setup_eagerbufs(rcd);
1649         if (ret)
1650                 goto bail_pio;
1651
1652         rcd->tidcursor = 0; /* start at beginning after open */
1653
1654         /* initialize poll variables... */
1655         rcd->urgent = 0;
1656         rcd->urgent_poll = 0;
1657
1658         /*
1659          * Now enable the ctxt for receive.
1660          * For chips that are set to DMA the tail register to memory
1661          * when they change (and when the update bit transitions from
1662          * 0 to 1.  So for those chips, we turn it off and then back on.
1663          * This will (very briefly) affect any other open ctxts, but the
1664          * duration is very short, and therefore isn't an issue.  We
1665          * explicitly set the in-memory tail copy to 0 beforehand, so we
1666          * don't have to wait to be sure the DMA update has happened
1667          * (chip resets head/tail to 0 on transition to enable).
1668          */
1669         if (rcd->rcvhdrtail_kvaddr)
1670                 qib_clear_rcvhdrtail(rcd);
1671
1672         dd->f_rcvctrl(rcd->ppd, QIB_RCVCTRL_CTXT_ENB | QIB_RCVCTRL_TIDFLOW_ENB,
1673                       rcd->ctxt);
1674
1675         /* Notify any waiting slaves */
1676         if (rcd->subctxt_cnt) {
1677                 clear_bit(QIB_CTXT_MASTER_UNINIT, &rcd->flag);
1678                 wake_up(&rcd->wait);
1679         }
1680         return 0;
1681
1682 bail_pio:
1683         qib_chg_pioavailkernel(dd, rcd->pio_base, rcd->piocnt,
1684                                TXCHK_CHG_TYPE_KERN, rcd);
1685 bail:
1686         return ret;
1687 }
1688
1689 /**
1690  * unlock_exptid - unlock any expected TID entries context still had in use
1691  * @rcd: ctxt
1692  *
1693  * We don't actually update the chip here, because we do a bulk update
1694  * below, using f_clear_tids.
1695  */
1696 static void unlock_expected_tids(struct qib_ctxtdata *rcd)
1697 {
1698         struct qib_devdata *dd = rcd->dd;
1699         int ctxt_tidbase = rcd->ctxt * dd->rcvtidcnt;
1700         int i, cnt = 0, maxtid = ctxt_tidbase + dd->rcvtidcnt;
1701
1702         for (i = ctxt_tidbase; i < maxtid; i++) {
1703                 struct page *p = dd->pageshadow[i];
1704                 dma_addr_t phys;
1705
1706                 if (!p)
1707                         continue;
1708
1709                 phys = dd->physshadow[i];
1710                 dd->physshadow[i] = dd->tidinvalid;
1711                 dd->pageshadow[i] = NULL;
1712                 pci_unmap_page(dd->pcidev, phys, PAGE_SIZE,
1713                                PCI_DMA_FROMDEVICE);
1714                 qib_release_user_pages(&p, 1);
1715                 cnt++;
1716         }
1717 }
1718
1719 static int qib_close(struct inode *in, struct file *fp)
1720 {
1721         int ret = 0;
1722         struct qib_filedata *fd;
1723         struct qib_ctxtdata *rcd;
1724         struct qib_devdata *dd;
1725         unsigned long flags;
1726         unsigned ctxt;
1727         pid_t pid;
1728
1729         mutex_lock(&qib_mutex);
1730
1731         fd = fp->private_data;
1732         fp->private_data = NULL;
1733         rcd = fd->rcd;
1734         if (!rcd) {
1735                 mutex_unlock(&qib_mutex);
1736                 goto bail;
1737         }
1738
1739         dd = rcd->dd;
1740
1741         /* ensure all pio buffer writes in progress are flushed */
1742         qib_flush_wc();
1743
1744         /* drain user sdma queue */
1745         if (fd->pq) {
1746                 qib_user_sdma_queue_drain(rcd->ppd, fd->pq);
1747                 qib_user_sdma_queue_destroy(fd->pq);
1748         }
1749
1750         if (fd->rec_cpu_num != -1)
1751                 __clear_bit(fd->rec_cpu_num, qib_cpulist);
1752
1753         if (--rcd->cnt) {
1754                 /*
1755                  * XXX If the master closes the context before the slave(s),
1756                  * revoke the mmap for the eager receive queue so
1757                  * the slave(s) don't wait for receive data forever.
1758                  */
1759                 rcd->active_slaves &= ~(1 << fd->subctxt);
1760                 rcd->subpid[fd->subctxt] = 0;
1761                 mutex_unlock(&qib_mutex);
1762                 goto bail;
1763         }
1764
1765         /* early; no interrupt users after this */
1766         spin_lock_irqsave(&dd->uctxt_lock, flags);
1767         ctxt = rcd->ctxt;
1768         dd->rcd[ctxt] = NULL;
1769         pid = rcd->pid;
1770         rcd->pid = 0;
1771         spin_unlock_irqrestore(&dd->uctxt_lock, flags);
1772
1773         if (rcd->rcvwait_to || rcd->piowait_to ||
1774             rcd->rcvnowait || rcd->pionowait) {
1775                 rcd->rcvwait_to = 0;
1776                 rcd->piowait_to = 0;
1777                 rcd->rcvnowait = 0;
1778                 rcd->pionowait = 0;
1779         }
1780         if (rcd->flag)
1781                 rcd->flag = 0;
1782
1783         if (dd->kregbase) {
1784                 /* atomically clear receive enable ctxt and intr avail. */
1785                 dd->f_rcvctrl(rcd->ppd, QIB_RCVCTRL_CTXT_DIS |
1786                                   QIB_RCVCTRL_INTRAVAIL_DIS, ctxt);
1787
1788                 /* clean up the pkeys for this ctxt user */
1789                 qib_clean_part_key(rcd, dd);
1790                 qib_disarm_piobufs(dd, rcd->pio_base, rcd->piocnt);
1791                 qib_chg_pioavailkernel(dd, rcd->pio_base,
1792                                        rcd->piocnt, TXCHK_CHG_TYPE_KERN, NULL);
1793
1794                 dd->f_clear_tids(dd, rcd);
1795
1796                 if (dd->pageshadow)
1797                         unlock_expected_tids(rcd);
1798                 qib_stats.sps_ctxts--;
1799                 dd->freectxts++;
1800         }
1801
1802         mutex_unlock(&qib_mutex);
1803         qib_free_ctxtdata(dd, rcd); /* after releasing the mutex */
1804
1805 bail:
1806         kfree(fd);
1807         return ret;
1808 }
1809
1810 static int qib_ctxt_info(struct file *fp, struct qib_ctxt_info __user *uinfo)
1811 {
1812         struct qib_ctxt_info info;
1813         int ret;
1814         size_t sz;
1815         struct qib_ctxtdata *rcd = ctxt_fp(fp);
1816         struct qib_filedata *fd;
1817
1818         fd = fp->private_data;
1819
1820         info.num_active = qib_count_active_units();
1821         info.unit = rcd->dd->unit;
1822         info.port = rcd->ppd->port;
1823         info.ctxt = rcd->ctxt;
1824         info.subctxt =  subctxt_fp(fp);
1825         /* Number of user ctxts available for this device. */
1826         info.num_ctxts = rcd->dd->cfgctxts - rcd->dd->first_user_ctxt;
1827         info.num_subctxts = rcd->subctxt_cnt;
1828         info.rec_cpu = fd->rec_cpu_num;
1829         sz = sizeof(info);
1830
1831         if (copy_to_user(uinfo, &info, sz)) {
1832                 ret = -EFAULT;
1833                 goto bail;
1834         }
1835         ret = 0;
1836
1837 bail:
1838         return ret;
1839 }
1840
1841 static int qib_sdma_get_inflight(struct qib_user_sdma_queue *pq,
1842                                  u32 __user *inflightp)
1843 {
1844         const u32 val = qib_user_sdma_inflight_counter(pq);
1845
1846         if (put_user(val, inflightp))
1847                 return -EFAULT;
1848
1849         return 0;
1850 }
1851
1852 static int qib_sdma_get_complete(struct qib_pportdata *ppd,
1853                                  struct qib_user_sdma_queue *pq,
1854                                  u32 __user *completep)
1855 {
1856         u32 val;
1857         int err;
1858
1859         if (!pq)
1860                 return -EINVAL;
1861
1862         err = qib_user_sdma_make_progress(ppd, pq);
1863         if (err < 0)
1864                 return err;
1865
1866         val = qib_user_sdma_complete_counter(pq);
1867         if (put_user(val, completep))
1868                 return -EFAULT;
1869
1870         return 0;
1871 }
1872
1873 static int disarm_req_delay(struct qib_ctxtdata *rcd)
1874 {
1875         int ret = 0;
1876
1877         if (!usable(rcd->ppd)) {
1878                 int i;
1879                 /*
1880                  * if link is down, or otherwise not usable, delay
1881                  * the caller up to 30 seconds, so we don't thrash
1882                  * in trying to get the chip back to ACTIVE, and
1883                  * set flag so they make the call again.
1884                  */
1885                 if (rcd->user_event_mask) {
1886                         /*
1887                          * subctxt_cnt is 0 if not shared, so do base
1888                          * separately, first, then remaining subctxt, if any
1889                          */
1890                         set_bit(_QIB_EVENT_DISARM_BUFS_BIT,
1891                                 &rcd->user_event_mask[0]);
1892                         for (i = 1; i < rcd->subctxt_cnt; i++)
1893                                 set_bit(_QIB_EVENT_DISARM_BUFS_BIT,
1894                                         &rcd->user_event_mask[i]);
1895                 }
1896                 for (i = 0; !usable(rcd->ppd) && i < 300; i++)
1897                         msleep(100);
1898                 ret = -ENETDOWN;
1899         }
1900         return ret;
1901 }
1902
1903 /*
1904  * Find all user contexts in use, and set the specified bit in their
1905  * event mask.
1906  * See also find_ctxt() for a similar use, that is specific to send buffers.
1907  */
1908 int qib_set_uevent_bits(struct qib_pportdata *ppd, const int evtbit)
1909 {
1910         struct qib_ctxtdata *rcd;
1911         unsigned ctxt;
1912         int ret = 0;
1913         unsigned long flags;
1914
1915         spin_lock_irqsave(&ppd->dd->uctxt_lock, flags);
1916         for (ctxt = ppd->dd->first_user_ctxt; ctxt < ppd->dd->cfgctxts;
1917              ctxt++) {
1918                 rcd = ppd->dd->rcd[ctxt];
1919                 if (!rcd)
1920                         continue;
1921                 if (rcd->user_event_mask) {
1922                         int i;
1923                         /*
1924                          * subctxt_cnt is 0 if not shared, so do base
1925                          * separately, first, then remaining subctxt, if any
1926                          */
1927                         set_bit(evtbit, &rcd->user_event_mask[0]);
1928                         for (i = 1; i < rcd->subctxt_cnt; i++)
1929                                 set_bit(evtbit, &rcd->user_event_mask[i]);
1930                 }
1931                 ret = 1;
1932                 break;
1933         }
1934         spin_unlock_irqrestore(&ppd->dd->uctxt_lock, flags);
1935
1936         return ret;
1937 }
1938
1939 /*
1940  * clear the event notifier events for this context.
1941  * For the DISARM_BUFS case, we also take action (this obsoletes
1942  * the older QIB_CMD_DISARM_BUFS, but we keep it for backwards
1943  * compatibility.
1944  * Other bits don't currently require actions, just atomically clear.
1945  * User process then performs actions appropriate to bit having been
1946  * set, if desired, and checks again in future.
1947  */
1948 static int qib_user_event_ack(struct qib_ctxtdata *rcd, int subctxt,
1949                               unsigned long events)
1950 {
1951         int ret = 0, i;
1952
1953         for (i = 0; i <= _QIB_MAX_EVENT_BIT; i++) {
1954                 if (!test_bit(i, &events))
1955                         continue;
1956                 if (i == _QIB_EVENT_DISARM_BUFS_BIT) {
1957                         (void)qib_disarm_piobufs_ifneeded(rcd);
1958                         ret = disarm_req_delay(rcd);
1959                 } else
1960                         clear_bit(i, &rcd->user_event_mask[subctxt]);
1961         }
1962         return ret;
1963 }
1964
1965 static ssize_t qib_write(struct file *fp, const char __user *data,
1966                          size_t count, loff_t *off)
1967 {
1968         const struct qib_cmd __user *ucmd;
1969         struct qib_ctxtdata *rcd;
1970         const void __user *src;
1971         size_t consumed, copy = 0;
1972         struct qib_cmd cmd;
1973         ssize_t ret = 0;
1974         void *dest;
1975
1976         if (WARN_ON_ONCE(!ib_safe_file_access(fp)))
1977                 return -EACCES;
1978
1979         if (count < sizeof(cmd.type)) {
1980                 ret = -EINVAL;
1981                 goto bail;
1982         }
1983
1984         ucmd = (const struct qib_cmd __user *) data;
1985
1986         if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) {
1987                 ret = -EFAULT;
1988                 goto bail;
1989         }
1990
1991         consumed = sizeof(cmd.type);
1992
1993         switch (cmd.type) {
1994         case QIB_CMD_ASSIGN_CTXT:
1995         case QIB_CMD_USER_INIT:
1996                 copy = sizeof(cmd.cmd.user_info);
1997                 dest = &cmd.cmd.user_info;
1998                 src = &ucmd->cmd.user_info;
1999                 break;
2000
2001         case QIB_CMD_RECV_CTRL:
2002                 copy = sizeof(cmd.cmd.recv_ctrl);
2003                 dest = &cmd.cmd.recv_ctrl;
2004                 src = &ucmd->cmd.recv_ctrl;
2005                 break;
2006
2007         case QIB_CMD_CTXT_INFO:
2008                 copy = sizeof(cmd.cmd.ctxt_info);
2009                 dest = &cmd.cmd.ctxt_info;
2010                 src = &ucmd->cmd.ctxt_info;
2011                 break;
2012
2013         case QIB_CMD_TID_UPDATE:
2014         case QIB_CMD_TID_FREE:
2015                 copy = sizeof(cmd.cmd.tid_info);
2016                 dest = &cmd.cmd.tid_info;
2017                 src = &ucmd->cmd.tid_info;
2018                 break;
2019
2020         case QIB_CMD_SET_PART_KEY:
2021                 copy = sizeof(cmd.cmd.part_key);
2022                 dest = &cmd.cmd.part_key;
2023                 src = &ucmd->cmd.part_key;
2024                 break;
2025
2026         case QIB_CMD_DISARM_BUFS:
2027         case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */
2028                 copy = 0;
2029                 src = NULL;
2030                 dest = NULL;
2031                 break;
2032
2033         case QIB_CMD_POLL_TYPE:
2034                 copy = sizeof(cmd.cmd.poll_type);
2035                 dest = &cmd.cmd.poll_type;
2036                 src = &ucmd->cmd.poll_type;
2037                 break;
2038
2039         case QIB_CMD_ARMLAUNCH_CTRL:
2040                 copy = sizeof(cmd.cmd.armlaunch_ctrl);
2041                 dest = &cmd.cmd.armlaunch_ctrl;
2042                 src = &ucmd->cmd.armlaunch_ctrl;
2043                 break;
2044
2045         case QIB_CMD_SDMA_INFLIGHT:
2046                 copy = sizeof(cmd.cmd.sdma_inflight);
2047                 dest = &cmd.cmd.sdma_inflight;
2048                 src = &ucmd->cmd.sdma_inflight;
2049                 break;
2050
2051         case QIB_CMD_SDMA_COMPLETE:
2052                 copy = sizeof(cmd.cmd.sdma_complete);
2053                 dest = &cmd.cmd.sdma_complete;
2054                 src = &ucmd->cmd.sdma_complete;
2055                 break;
2056
2057         case QIB_CMD_ACK_EVENT:
2058                 copy = sizeof(cmd.cmd.event_mask);
2059                 dest = &cmd.cmd.event_mask;
2060                 src = &ucmd->cmd.event_mask;
2061                 break;
2062
2063         default:
2064                 ret = -EINVAL;
2065                 goto bail;
2066         }
2067
2068         if (copy) {
2069                 if ((count - consumed) < copy) {
2070                         ret = -EINVAL;
2071                         goto bail;
2072                 }
2073                 if (copy_from_user(dest, src, copy)) {
2074                         ret = -EFAULT;
2075                         goto bail;
2076                 }
2077                 consumed += copy;
2078         }
2079
2080         rcd = ctxt_fp(fp);
2081         if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) {
2082                 ret = -EINVAL;
2083                 goto bail;
2084         }
2085
2086         switch (cmd.type) {
2087         case QIB_CMD_ASSIGN_CTXT:
2088                 ret = qib_assign_ctxt(fp, &cmd.cmd.user_info);
2089                 if (ret)
2090                         goto bail;
2091                 break;
2092
2093         case QIB_CMD_USER_INIT:
2094                 ret = qib_do_user_init(fp, &cmd.cmd.user_info);
2095                 if (ret)
2096                         goto bail;
2097                 ret = qib_get_base_info(fp, (void __user *) (unsigned long)
2098                                         cmd.cmd.user_info.spu_base_info,
2099                                         cmd.cmd.user_info.spu_base_info_size);
2100                 break;
2101
2102         case QIB_CMD_RECV_CTRL:
2103                 ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl);
2104                 break;
2105
2106         case QIB_CMD_CTXT_INFO:
2107                 ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *)
2108                                     (unsigned long) cmd.cmd.ctxt_info);
2109                 break;
2110
2111         case QIB_CMD_TID_UPDATE:
2112                 ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info);
2113                 break;
2114
2115         case QIB_CMD_TID_FREE:
2116                 ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info);
2117                 break;
2118
2119         case QIB_CMD_SET_PART_KEY:
2120                 ret = qib_set_part_key(rcd, cmd.cmd.part_key);
2121                 break;
2122
2123         case QIB_CMD_DISARM_BUFS:
2124                 (void)qib_disarm_piobufs_ifneeded(rcd);
2125                 ret = disarm_req_delay(rcd);
2126                 break;
2127
2128         case QIB_CMD_PIOAVAILUPD:
2129                 qib_force_pio_avail_update(rcd->dd);
2130                 break;
2131
2132         case QIB_CMD_POLL_TYPE:
2133                 rcd->poll_type = cmd.cmd.poll_type;
2134                 break;
2135
2136         case QIB_CMD_ARMLAUNCH_CTRL:
2137                 rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl);
2138                 break;
2139
2140         case QIB_CMD_SDMA_INFLIGHT:
2141                 ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp),
2142                                             (u32 __user *) (unsigned long)
2143                                             cmd.cmd.sdma_inflight);
2144                 break;
2145
2146         case QIB_CMD_SDMA_COMPLETE:
2147                 ret = qib_sdma_get_complete(rcd->ppd,
2148                                             user_sdma_queue_fp(fp),
2149                                             (u32 __user *) (unsigned long)
2150                                             cmd.cmd.sdma_complete);
2151                 break;
2152
2153         case QIB_CMD_ACK_EVENT:
2154                 ret = qib_user_event_ack(rcd, subctxt_fp(fp),
2155                                          cmd.cmd.event_mask);
2156                 break;
2157         }
2158
2159         if (ret >= 0)
2160                 ret = consumed;
2161
2162 bail:
2163         return ret;
2164 }
2165
2166 static ssize_t qib_aio_write(struct kiocb *iocb, const struct iovec *iov,
2167                              unsigned long dim, loff_t off)
2168 {
2169         struct qib_filedata *fp = iocb->ki_filp->private_data;
2170         struct qib_ctxtdata *rcd = ctxt_fp(iocb->ki_filp);
2171         struct qib_user_sdma_queue *pq = fp->pq;
2172
2173         if (!dim || !pq)
2174                 return -EINVAL;
2175
2176         return qib_user_sdma_writev(rcd, pq, iov, dim);
2177 }
2178
2179 static struct class *qib_class;
2180 static dev_t qib_dev;
2181
2182 int qib_cdev_init(int minor, const char *name,
2183                   const struct file_operations *fops,
2184                   struct cdev **cdevp, struct device **devp)
2185 {
2186         const dev_t dev = MKDEV(MAJOR(qib_dev), minor);
2187         struct cdev *cdev;
2188         struct device *device = NULL;
2189         int ret;
2190
2191         cdev = cdev_alloc();
2192         if (!cdev) {
2193                 printk(KERN_ERR QIB_DRV_NAME
2194                        ": Could not allocate cdev for minor %d, %s\n",
2195                        minor, name);
2196                 ret = -ENOMEM;
2197                 goto done;
2198         }
2199
2200         cdev->owner = THIS_MODULE;
2201         cdev->ops = fops;
2202         kobject_set_name(&cdev->kobj, name);
2203
2204         ret = cdev_add(cdev, dev, 1);
2205         if (ret < 0) {
2206                 printk(KERN_ERR QIB_DRV_NAME
2207                        ": Could not add cdev for minor %d, %s (err %d)\n",
2208                        minor, name, -ret);
2209                 goto err_cdev;
2210         }
2211
2212         device = device_create(qib_class, NULL, dev, NULL, name);
2213         if (!IS_ERR(device))
2214                 goto done;
2215         ret = PTR_ERR(device);
2216         device = NULL;
2217         printk(KERN_ERR QIB_DRV_NAME ": Could not create "
2218                "device for minor %d, %s (err %d)\n",
2219                minor, name, -ret);
2220 err_cdev:
2221         cdev_del(cdev);
2222         cdev = NULL;
2223 done:
2224         *cdevp = cdev;
2225         *devp = device;
2226         return ret;
2227 }
2228
2229 void qib_cdev_cleanup(struct cdev **cdevp, struct device **devp)
2230 {
2231         struct device *device = *devp;
2232
2233         if (device) {
2234                 device_unregister(device);
2235                 *devp = NULL;
2236         }
2237
2238         if (*cdevp) {
2239                 cdev_del(*cdevp);
2240                 *cdevp = NULL;
2241         }
2242 }
2243
2244 static struct cdev *wildcard_cdev;
2245 static struct device *wildcard_device;
2246
2247 int __init qib_dev_init(void)
2248 {
2249         int ret;
2250
2251         ret = alloc_chrdev_region(&qib_dev, 0, QIB_NMINORS, QIB_DRV_NAME);
2252         if (ret < 0) {
2253                 printk(KERN_ERR QIB_DRV_NAME ": Could not allocate "
2254                        "chrdev region (err %d)\n", -ret);
2255                 goto done;
2256         }
2257
2258         qib_class = class_create(THIS_MODULE, "ipath");
2259         if (IS_ERR(qib_class)) {
2260                 ret = PTR_ERR(qib_class);
2261                 printk(KERN_ERR QIB_DRV_NAME ": Could not create "
2262                        "device class (err %d)\n", -ret);
2263                 unregister_chrdev_region(qib_dev, QIB_NMINORS);
2264         }
2265
2266 done:
2267         return ret;
2268 }
2269
2270 void qib_dev_cleanup(void)
2271 {
2272         if (qib_class) {
2273                 class_destroy(qib_class);
2274                 qib_class = NULL;
2275         }
2276
2277         unregister_chrdev_region(qib_dev, QIB_NMINORS);
2278 }
2279
2280 static atomic_t user_count = ATOMIC_INIT(0);
2281
2282 static void qib_user_remove(struct qib_devdata *dd)
2283 {
2284         if (atomic_dec_return(&user_count) == 0)
2285                 qib_cdev_cleanup(&wildcard_cdev, &wildcard_device);
2286
2287         qib_cdev_cleanup(&dd->user_cdev, &dd->user_device);
2288 }
2289
2290 static int qib_user_add(struct qib_devdata *dd)
2291 {
2292         char name[10];
2293         int ret;
2294
2295         if (atomic_inc_return(&user_count) == 1) {
2296                 ret = qib_cdev_init(0, "ipath", &qib_file_ops,
2297                                     &wildcard_cdev, &wildcard_device);
2298                 if (ret)
2299                         goto done;
2300         }
2301
2302         snprintf(name, sizeof(name), "ipath%d", dd->unit);
2303         ret = qib_cdev_init(dd->unit + 1, name, &qib_file_ops,
2304                             &dd->user_cdev, &dd->user_device);
2305         if (ret)
2306                 qib_user_remove(dd);
2307 done:
2308         return ret;
2309 }
2310
2311 /*
2312  * Create per-unit files in /dev
2313  */
2314 int qib_device_create(struct qib_devdata *dd)
2315 {
2316         int r, ret;
2317
2318         r = qib_user_add(dd);
2319         ret = qib_diag_add(dd);
2320         if (r && !ret)
2321                 ret = r;
2322         return ret;
2323 }
2324
2325 /*
2326  * Remove per-unit files in /dev
2327  * void, core kernel returns no errors for this stuff
2328  */
2329 void qib_device_remove(struct qib_devdata *dd)
2330 {
2331         qib_user_remove(dd);
2332         qib_diag_remove(dd);
2333 }