]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/infiniband/hw/ipath/ipath_file_ops.c
IB/ipath: Driver support for userspace sharing of HW contexts
[linux-2.6-omap-h63xx.git] / drivers / infiniband / hw / ipath / ipath_file_ops.c
1 /*
2  * Copyright (c) 2006 QLogic, Inc. All rights reserved.
3  * Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33
34 #include <linux/pci.h>
35 #include <linux/poll.h>
36 #include <linux/cdev.h>
37 #include <linux/swap.h>
38 #include <linux/vmalloc.h>
39 #include <asm/pgtable.h>
40
41 #include "ipath_kernel.h"
42 #include "ipath_common.h"
43
44 /*
45  * mmap64 doesn't allow all 64 bits for 32-bit applications
46  * so only use the low 43 bits.
47  */
48 #define MMAP64_MASK     0x7FFFFFFFFFFUL
49
50 static int ipath_open(struct inode *, struct file *);
51 static int ipath_close(struct inode *, struct file *);
52 static ssize_t ipath_write(struct file *, const char __user *, size_t,
53                            loff_t *);
54 static unsigned int ipath_poll(struct file *, struct poll_table_struct *);
55 static int ipath_mmap(struct file *, struct vm_area_struct *);
56
57 static struct file_operations ipath_file_ops = {
58         .owner = THIS_MODULE,
59         .write = ipath_write,
60         .open = ipath_open,
61         .release = ipath_close,
62         .poll = ipath_poll,
63         .mmap = ipath_mmap
64 };
65
66 static int ipath_get_base_info(struct file *fp,
67                                void __user *ubase, size_t ubase_size)
68 {
69         struct ipath_portdata *pd = port_fp(fp);
70         int ret = 0;
71         struct ipath_base_info *kinfo = NULL;
72         struct ipath_devdata *dd = pd->port_dd;
73         unsigned subport_cnt;
74         int shared, master;
75         size_t sz;
76
77         subport_cnt = pd->port_subport_cnt;
78         if (!subport_cnt) {
79                 shared = 0;
80                 master = 0;
81                 subport_cnt = 1;
82         } else {
83                 shared = 1;
84                 master = !subport_fp(fp);
85         }
86
87         sz = sizeof(*kinfo);
88         /* If port sharing is not requested, allow the old size structure */
89         if (!shared)
90                 sz -= 3 * sizeof(u64);
91         if (ubase_size < sz) {
92                 ipath_cdbg(PROC,
93                            "Base size %zu, need %zu (version mismatch?)\n",
94                            ubase_size, sz);
95                 ret = -EINVAL;
96                 goto bail;
97         }
98
99         kinfo = kzalloc(sizeof(*kinfo), GFP_KERNEL);
100         if (kinfo == NULL) {
101                 ret = -ENOMEM;
102                 goto bail;
103         }
104
105         ret = dd->ipath_f_get_base_info(pd, kinfo);
106         if (ret < 0)
107                 goto bail;
108
109         kinfo->spi_rcvhdr_cnt = dd->ipath_rcvhdrcnt;
110         kinfo->spi_rcvhdrent_size = dd->ipath_rcvhdrentsize;
111         kinfo->spi_tidegrcnt = dd->ipath_rcvegrcnt;
112         kinfo->spi_rcv_egrbufsize = dd->ipath_rcvegrbufsize;
113         /*
114          * have to mmap whole thing
115          */
116         kinfo->spi_rcv_egrbuftotlen =
117                 pd->port_rcvegrbuf_chunks * pd->port_rcvegrbuf_size;
118         kinfo->spi_rcv_egrperchunk = pd->port_rcvegrbufs_perchunk;
119         kinfo->spi_rcv_egrchunksize = kinfo->spi_rcv_egrbuftotlen /
120                 pd->port_rcvegrbuf_chunks;
121         kinfo->spi_tidcnt = dd->ipath_rcvtidcnt / subport_cnt;
122         if (master)
123                 kinfo->spi_tidcnt += dd->ipath_rcvtidcnt % subport_cnt;
124         /*
125          * for this use, may be ipath_cfgports summed over all chips that
126          * are are configured and present
127          */
128         kinfo->spi_nports = dd->ipath_cfgports;
129         /* unit (chip/board) our port is on */
130         kinfo->spi_unit = dd->ipath_unit;
131         /* for now, only a single page */
132         kinfo->spi_tid_maxsize = PAGE_SIZE;
133
134         /*
135          * Doing this per port, and based on the skip value, etc.  This has
136          * to be the actual buffer size, since the protocol code treats it
137          * as an array.
138          *
139          * These have to be set to user addresses in the user code via mmap.
140          * These values are used on return to user code for the mmap target
141          * addresses only.  For 32 bit, same 44 bit address problem, so use
142          * the physical address, not virtual.  Before 2.6.11, using the
143          * page_address() macro worked, but in 2.6.11, even that returns the
144          * full 64 bit address (upper bits all 1's).  So far, using the
145          * physical addresses (or chip offsets, for chip mapping) works, but
146          * no doubt some future kernel release will change that, and we'll be
147          * on to yet another method of dealing with this.
148          */
149         kinfo->spi_rcvhdr_base = (u64) pd->port_rcvhdrq_phys;
150         kinfo->spi_rcvhdr_tailaddr = (u64) pd->port_rcvhdrqtailaddr_phys;
151         kinfo->spi_rcv_egrbufs = (u64) pd->port_rcvegr_phys;
152         kinfo->spi_pioavailaddr = (u64) dd->ipath_pioavailregs_phys;
153         kinfo->spi_status = (u64) kinfo->spi_pioavailaddr +
154                 (void *) dd->ipath_statusp -
155                 (void *) dd->ipath_pioavailregs_dma;
156         if (!shared) {
157                 kinfo->spi_piocnt = dd->ipath_pbufsport;
158                 kinfo->spi_piobufbase = (u64) pd->port_piobufs;
159                 kinfo->__spi_uregbase = (u64) dd->ipath_uregbase +
160                         dd->ipath_palign * pd->port_port;
161         } else if (master) {
162                 kinfo->spi_piocnt = (dd->ipath_pbufsport / subport_cnt) +
163                                     (dd->ipath_pbufsport % subport_cnt);
164                 /* Master's PIO buffers are after all the slave's */
165                 kinfo->spi_piobufbase = (u64) pd->port_piobufs +
166                         dd->ipath_palign *
167                         (dd->ipath_pbufsport - kinfo->spi_piocnt);
168                 kinfo->__spi_uregbase = (u64) dd->ipath_uregbase +
169                         dd->ipath_palign * pd->port_port;
170         } else {
171                 unsigned slave = subport_fp(fp) - 1;
172
173                 kinfo->spi_piocnt = dd->ipath_pbufsport / subport_cnt;
174                 kinfo->spi_piobufbase = (u64) pd->port_piobufs +
175                         dd->ipath_palign * kinfo->spi_piocnt * slave;
176                 kinfo->__spi_uregbase = ((u64) pd->subport_uregbase +
177                         PAGE_SIZE * slave) & MMAP64_MASK;
178
179                 kinfo->spi_rcvhdr_base = ((u64) pd->subport_rcvhdr_base +
180                         pd->port_rcvhdrq_size * slave) & MMAP64_MASK;
181                 kinfo->spi_rcvhdr_tailaddr =
182                         (u64) pd->port_rcvhdrqtailaddr_phys & MMAP64_MASK;
183                 kinfo->spi_rcv_egrbufs = ((u64) pd->subport_rcvegrbuf +
184                         dd->ipath_rcvegrcnt * dd->ipath_rcvegrbufsize * slave) &
185                         MMAP64_MASK;
186         }
187
188         kinfo->spi_pioindex = (kinfo->spi_piobufbase - dd->ipath_piobufbase) /
189                 dd->ipath_palign;
190         kinfo->spi_pioalign = dd->ipath_palign;
191
192         kinfo->spi_qpair = IPATH_KD_QP;
193         kinfo->spi_piosize = dd->ipath_ibmaxlen;
194         kinfo->spi_mtu = dd->ipath_ibmaxlen;    /* maxlen, not ibmtu */
195         kinfo->spi_port = pd->port_port;
196         kinfo->spi_subport = subport_fp(fp);
197         kinfo->spi_sw_version = IPATH_KERN_SWVERSION;
198         kinfo->spi_hw_version = dd->ipath_revision;
199
200         if (master) {
201                 kinfo->spi_runtime_flags |= IPATH_RUNTIME_MASTER;
202                 kinfo->spi_subport_uregbase =
203                         (u64) pd->subport_uregbase & MMAP64_MASK;
204                 kinfo->spi_subport_rcvegrbuf =
205                         (u64) pd->subport_rcvegrbuf & MMAP64_MASK;
206                 kinfo->spi_subport_rcvhdr_base =
207                         (u64) pd->subport_rcvhdr_base & MMAP64_MASK;
208                 ipath_cdbg(PROC, "port %u flags %x %llx %llx %llx\n",
209                         kinfo->spi_port,
210                         kinfo->spi_runtime_flags,
211                         kinfo->spi_subport_uregbase,
212                         kinfo->spi_subport_rcvegrbuf,
213                         kinfo->spi_subport_rcvhdr_base);
214         }
215
216         if (copy_to_user(ubase, kinfo, sizeof(*kinfo)))
217                 ret = -EFAULT;
218
219 bail:
220         kfree(kinfo);
221         return ret;
222 }
223
224 /**
225  * ipath_tid_update - update a port TID
226  * @pd: the port
227  * @fp: the ipath device file
228  * @ti: the TID information
229  *
230  * The new implementation as of Oct 2004 is that the driver assigns
231  * the tid and returns it to the caller.   To make it easier to
232  * catch bugs, and to reduce search time, we keep a cursor for
233  * each port, walking the shadow tid array to find one that's not
234  * in use.
235  *
236  * For now, if we can't allocate the full list, we fail, although
237  * in the long run, we'll allocate as many as we can, and the
238  * caller will deal with that by trying the remaining pages later.
239  * That means that when we fail, we have to mark the tids as not in
240  * use again, in our shadow copy.
241  *
242  * It's up to the caller to free the tids when they are done.
243  * We'll unlock the pages as they free them.
244  *
245  * Also, right now we are locking one page at a time, but since
246  * the intended use of this routine is for a single group of
247  * virtually contiguous pages, that should change to improve
248  * performance.
249  */
250 static int ipath_tid_update(struct ipath_portdata *pd, struct file *fp,
251                             const struct ipath_tid_info *ti)
252 {
253         int ret = 0, ntids;
254         u32 tid, porttid, cnt, i, tidcnt, tidoff;
255         u16 *tidlist;
256         struct ipath_devdata *dd = pd->port_dd;
257         u64 physaddr;
258         unsigned long vaddr;
259         u64 __iomem *tidbase;
260         unsigned long tidmap[8];
261         struct page **pagep = NULL;
262         unsigned subport = subport_fp(fp);
263
264         if (!dd->ipath_pageshadow) {
265                 ret = -ENOMEM;
266                 goto done;
267         }
268
269         cnt = ti->tidcnt;
270         if (!cnt) {
271                 ipath_dbg("After copyin, tidcnt 0, tidlist %llx\n",
272                           (unsigned long long) ti->tidlist);
273                 /*
274                  * Should we treat as success?  likely a bug
275                  */
276                 ret = -EFAULT;
277                 goto done;
278         }
279         porttid = pd->port_port * dd->ipath_rcvtidcnt;
280         if (!pd->port_subport_cnt) {
281                 tidcnt = dd->ipath_rcvtidcnt;
282                 tid = pd->port_tidcursor;
283                 tidoff = 0;
284         } else if (!subport) {
285                 tidcnt = (dd->ipath_rcvtidcnt / pd->port_subport_cnt) +
286                          (dd->ipath_rcvtidcnt % pd->port_subport_cnt);
287                 tidoff = dd->ipath_rcvtidcnt - tidcnt;
288                 porttid += tidoff;
289                 tid = tidcursor_fp(fp);
290         } else {
291                 tidcnt = dd->ipath_rcvtidcnt / pd->port_subport_cnt;
292                 tidoff = tidcnt * (subport - 1);
293                 porttid += tidoff;
294                 tid = tidcursor_fp(fp);
295         }
296         if (cnt > tidcnt) {
297                 /* make sure it all fits in port_tid_pg_list */
298                 dev_info(&dd->pcidev->dev, "Process tried to allocate %u "
299                          "TIDs, only trying max (%u)\n", cnt, tidcnt);
300                 cnt = tidcnt;
301         }
302         pagep = &((struct page **) pd->port_tid_pg_list)[tidoff];
303         tidlist = &((u16 *) &pagep[dd->ipath_rcvtidcnt])[tidoff];
304
305         memset(tidmap, 0, sizeof(tidmap));
306         /* before decrement; chip actual # */
307         ntids = tidcnt;
308         tidbase = (u64 __iomem *) (((char __iomem *) dd->ipath_kregbase) +
309                                    dd->ipath_rcvtidbase +
310                                    porttid * sizeof(*tidbase));
311
312         ipath_cdbg(VERBOSE, "Port%u %u tids, cursor %u, tidbase %p\n",
313                    pd->port_port, cnt, tid, tidbase);
314
315         /* virtual address of first page in transfer */
316         vaddr = ti->tidvaddr;
317         if (!access_ok(VERIFY_WRITE, (void __user *) vaddr,
318                        cnt * PAGE_SIZE)) {
319                 ipath_dbg("Fail vaddr %p, %u pages, !access_ok\n",
320                           (void *)vaddr, cnt);
321                 ret = -EFAULT;
322                 goto done;
323         }
324         ret = ipath_get_user_pages(vaddr, cnt, pagep);
325         if (ret) {
326                 if (ret == -EBUSY) {
327                         ipath_dbg("Failed to lock addr %p, %u pages "
328                                   "(already locked)\n",
329                                   (void *) vaddr, cnt);
330                         /*
331                          * for now, continue, and see what happens but with
332                          * the new implementation, this should never happen,
333                          * unless perhaps the user has mpin'ed the pages
334                          * themselves (something we need to test)
335                          */
336                         ret = 0;
337                 } else {
338                         dev_info(&dd->pcidev->dev,
339                                  "Failed to lock addr %p, %u pages: "
340                                  "errno %d\n", (void *) vaddr, cnt, -ret);
341                         goto done;
342                 }
343         }
344         for (i = 0; i < cnt; i++, vaddr += PAGE_SIZE) {
345                 for (; ntids--; tid++) {
346                         if (tid == tidcnt)
347                                 tid = 0;
348                         if (!dd->ipath_pageshadow[porttid + tid])
349                                 break;
350                 }
351                 if (ntids < 0) {
352                         /*
353                          * oops, wrapped all the way through their TIDs,
354                          * and didn't have enough free; see comments at
355                          * start of routine
356                          */
357                         ipath_dbg("Not enough free TIDs for %u pages "
358                                   "(index %d), failing\n", cnt, i);
359                         i--;    /* last tidlist[i] not filled in */
360                         ret = -ENOMEM;
361                         break;
362                 }
363                 tidlist[i] = tid + tidoff;
364                 ipath_cdbg(VERBOSE, "Updating idx %u to TID %u, "
365                            "vaddr %lx\n", i, tid + tidoff, vaddr);
366                 /* we "know" system pages and TID pages are same size */
367                 dd->ipath_pageshadow[porttid + tid] = pagep[i];
368                 /*
369                  * don't need atomic or it's overhead
370                  */
371                 __set_bit(tid, tidmap);
372                 physaddr = page_to_phys(pagep[i]);
373                 ipath_stats.sps_pagelocks++;
374                 ipath_cdbg(VERBOSE,
375                            "TID %u, vaddr %lx, physaddr %llx pgp %p\n",
376                            tid, vaddr, (unsigned long long) physaddr,
377                            pagep[i]);
378                 dd->ipath_f_put_tid(dd, &tidbase[tid], 1, physaddr);
379                 /*
380                  * don't check this tid in ipath_portshadow, since we
381                  * just filled it in; start with the next one.
382                  */
383                 tid++;
384         }
385
386         if (ret) {
387                 u32 limit;
388         cleanup:
389                 /* jump here if copy out of updated info failed... */
390                 ipath_dbg("After failure (ret=%d), undo %d of %d entries\n",
391                           -ret, i, cnt);
392                 /* same code that's in ipath_free_tid() */
393                 limit = sizeof(tidmap) * BITS_PER_BYTE;
394                 if (limit > tidcnt)
395                         /* just in case size changes in future */
396                         limit = tidcnt;
397                 tid = find_first_bit((const unsigned long *)tidmap, limit);
398                 for (; tid < limit; tid++) {
399                         if (!test_bit(tid, tidmap))
400                                 continue;
401                         if (dd->ipath_pageshadow[porttid + tid]) {
402                                 ipath_cdbg(VERBOSE, "Freeing TID %u\n",
403                                            tid);
404                                 dd->ipath_f_put_tid(dd, &tidbase[tid], 1,
405                                                     dd->ipath_tidinvalid);
406                                 dd->ipath_pageshadow[porttid + tid] = NULL;
407                                 ipath_stats.sps_pageunlocks++;
408                         }
409                 }
410                 ipath_release_user_pages(pagep, cnt);
411         } else {
412                 /*
413                  * Copy the updated array, with ipath_tid's filled in, back
414                  * to user.  Since we did the copy in already, this "should
415                  * never fail" If it does, we have to clean up...
416                  */
417                 if (copy_to_user((void __user *)
418                                  (unsigned long) ti->tidlist,
419                                  tidlist, cnt * sizeof(*tidlist))) {
420                         ret = -EFAULT;
421                         goto cleanup;
422                 }
423                 if (copy_to_user((void __user *) (unsigned long) ti->tidmap,
424                                  tidmap, sizeof tidmap)) {
425                         ret = -EFAULT;
426                         goto cleanup;
427                 }
428                 if (tid == tidcnt)
429                         tid = 0;
430                 if (!pd->port_subport_cnt)
431                         pd->port_tidcursor = tid;
432                 else
433                         tidcursor_fp(fp) = tid;
434         }
435
436 done:
437         if (ret)
438                 ipath_dbg("Failed to map %u TID pages, failing with %d\n",
439                           ti->tidcnt, -ret);
440         return ret;
441 }
442
443 /**
444  * ipath_tid_free - free a port TID
445  * @pd: the port
446  * @subport: the subport
447  * @ti: the TID info
448  *
449  * right now we are unlocking one page at a time, but since
450  * the intended use of this routine is for a single group of
451  * virtually contiguous pages, that should change to improve
452  * performance.  We check that the TID is in range for this port
453  * but otherwise don't check validity; if user has an error and
454  * frees the wrong tid, it's only their own data that can thereby
455  * be corrupted.  We do check that the TID was in use, for sanity
456  * We always use our idea of the saved address, not the address that
457  * they pass in to us.
458  */
459
460 static int ipath_tid_free(struct ipath_portdata *pd, unsigned subport,
461                           const struct ipath_tid_info *ti)
462 {
463         int ret = 0;
464         u32 tid, porttid, cnt, limit, tidcnt;
465         struct ipath_devdata *dd = pd->port_dd;
466         u64 __iomem *tidbase;
467         unsigned long tidmap[8];
468
469         if (!dd->ipath_pageshadow) {
470                 ret = -ENOMEM;
471                 goto done;
472         }
473
474         if (copy_from_user(tidmap, (void __user *)(unsigned long)ti->tidmap,
475                            sizeof tidmap)) {
476                 ret = -EFAULT;
477                 goto done;
478         }
479
480         porttid = pd->port_port * dd->ipath_rcvtidcnt;
481         if (!pd->port_subport_cnt)
482                 tidcnt = dd->ipath_rcvtidcnt;
483         else if (!subport) {
484                 tidcnt = (dd->ipath_rcvtidcnt / pd->port_subport_cnt) +
485                          (dd->ipath_rcvtidcnt % pd->port_subport_cnt);
486                 porttid += dd->ipath_rcvtidcnt - tidcnt;
487         } else {
488                 tidcnt = dd->ipath_rcvtidcnt / pd->port_subport_cnt;
489                 porttid += tidcnt * (subport - 1);
490         }
491         tidbase = (u64 __iomem *) ((char __iomem *)(dd->ipath_kregbase) +
492                                    dd->ipath_rcvtidbase +
493                                    porttid * sizeof(*tidbase));
494
495         limit = sizeof(tidmap) * BITS_PER_BYTE;
496         if (limit > tidcnt)
497                 /* just in case size changes in future */
498                 limit = tidcnt;
499         tid = find_first_bit(tidmap, limit);
500         ipath_cdbg(VERBOSE, "Port%u free %u tids; first bit (max=%d) "
501                    "set is %d, porttid %u\n", pd->port_port, ti->tidcnt,
502                    limit, tid, porttid);
503         for (cnt = 0; tid < limit; tid++) {
504                 /*
505                  * small optimization; if we detect a run of 3 or so without
506                  * any set, use find_first_bit again.  That's mainly to
507                  * accelerate the case where we wrapped, so we have some at
508                  * the beginning, and some at the end, and a big gap
509                  * in the middle.
510                  */
511                 if (!test_bit(tid, tidmap))
512                         continue;
513                 cnt++;
514                 if (dd->ipath_pageshadow[porttid + tid]) {
515                         ipath_cdbg(VERBOSE, "PID %u freeing TID %u\n",
516                                    pd->port_pid, tid);
517                         dd->ipath_f_put_tid(dd, &tidbase[tid], 1,
518                                             dd->ipath_tidinvalid);
519                         ipath_release_user_pages(
520                                 &dd->ipath_pageshadow[porttid + tid], 1);
521                         dd->ipath_pageshadow[porttid + tid] = NULL;
522                         ipath_stats.sps_pageunlocks++;
523                 } else
524                         ipath_dbg("Unused tid %u, ignoring\n", tid);
525         }
526         if (cnt != ti->tidcnt)
527                 ipath_dbg("passed in tidcnt %d, only %d bits set in map\n",
528                           ti->tidcnt, cnt);
529 done:
530         if (ret)
531                 ipath_dbg("Failed to unmap %u TID pages, failing with %d\n",
532                           ti->tidcnt, -ret);
533         return ret;
534 }
535
536 /**
537  * ipath_set_part_key - set a partition key
538  * @pd: the port
539  * @key: the key
540  *
541  * We can have up to 4 active at a time (other than the default, which is
542  * always allowed).  This is somewhat tricky, since multiple ports may set
543  * the same key, so we reference count them, and clean up at exit.  All 4
544  * partition keys are packed into a single infinipath register.  It's an
545  * error for a process to set the same pkey multiple times.  We provide no
546  * mechanism to de-allocate a pkey at this time, we may eventually need to
547  * do that.  I've used the atomic operations, and no locking, and only make
548  * a single pass through what's available.  This should be more than
549  * adequate for some time. I'll think about spinlocks or the like if and as
550  * it's necessary.
551  */
552 static int ipath_set_part_key(struct ipath_portdata *pd, u16 key)
553 {
554         struct ipath_devdata *dd = pd->port_dd;
555         int i, any = 0, pidx = -1;
556         u16 lkey = key & 0x7FFF;
557         int ret;
558
559         if (lkey == (IPATH_DEFAULT_P_KEY & 0x7FFF)) {
560                 /* nothing to do; this key always valid */
561                 ret = 0;
562                 goto bail;
563         }
564
565         ipath_cdbg(VERBOSE, "p%u try to set pkey %hx, current keys "
566                    "%hx:%x %hx:%x %hx:%x %hx:%x\n",
567                    pd->port_port, key, dd->ipath_pkeys[0],
568                    atomic_read(&dd->ipath_pkeyrefs[0]), dd->ipath_pkeys[1],
569                    atomic_read(&dd->ipath_pkeyrefs[1]), dd->ipath_pkeys[2],
570                    atomic_read(&dd->ipath_pkeyrefs[2]), dd->ipath_pkeys[3],
571                    atomic_read(&dd->ipath_pkeyrefs[3]));
572
573         if (!lkey) {
574                 ipath_cdbg(PROC, "p%u tries to set key 0, not allowed\n",
575                            pd->port_port);
576                 ret = -EINVAL;
577                 goto bail;
578         }
579
580         /*
581          * Set the full membership bit, because it has to be
582          * set in the register or the packet, and it seems
583          * cleaner to set in the register than to force all
584          * callers to set it. (see bug 4331)
585          */
586         key |= 0x8000;
587
588         for (i = 0; i < ARRAY_SIZE(pd->port_pkeys); i++) {
589                 if (!pd->port_pkeys[i] && pidx == -1)
590                         pidx = i;
591                 if (pd->port_pkeys[i] == key) {
592                         ipath_cdbg(VERBOSE, "p%u tries to set same pkey "
593                                    "(%x) more than once\n",
594                                    pd->port_port, key);
595                         ret = -EEXIST;
596                         goto bail;
597                 }
598         }
599         if (pidx == -1) {
600                 ipath_dbg("All pkeys for port %u already in use, "
601                           "can't set %x\n", pd->port_port, key);
602                 ret = -EBUSY;
603                 goto bail;
604         }
605         for (any = i = 0; i < ARRAY_SIZE(dd->ipath_pkeys); i++) {
606                 if (!dd->ipath_pkeys[i]) {
607                         any++;
608                         continue;
609                 }
610                 if (dd->ipath_pkeys[i] == key) {
611                         atomic_t *pkrefs = &dd->ipath_pkeyrefs[i];
612
613                         if (atomic_inc_return(pkrefs) > 1) {
614                                 pd->port_pkeys[pidx] = key;
615                                 ipath_cdbg(VERBOSE, "p%u set key %x "
616                                            "matches #%d, count now %d\n",
617                                            pd->port_port, key, i,
618                                            atomic_read(pkrefs));
619                                 ret = 0;
620                                 goto bail;
621                         } else {
622                                 /*
623                                  * lost race, decrement count, catch below
624                                  */
625                                 atomic_dec(pkrefs);
626                                 ipath_cdbg(VERBOSE, "Lost race, count was "
627                                            "0, after dec, it's %d\n",
628                                            atomic_read(pkrefs));
629                                 any++;
630                         }
631                 }
632                 if ((dd->ipath_pkeys[i] & 0x7FFF) == lkey) {
633                         /*
634                          * It makes no sense to have both the limited and
635                          * full membership PKEY set at the same time since
636                          * the unlimited one will disable the limited one.
637                          */
638                         ret = -EEXIST;
639                         goto bail;
640                 }
641         }
642         if (!any) {
643                 ipath_dbg("port %u, all pkeys already in use, "
644                           "can't set %x\n", pd->port_port, key);
645                 ret = -EBUSY;
646                 goto bail;
647         }
648         for (any = i = 0; i < ARRAY_SIZE(dd->ipath_pkeys); i++) {
649                 if (!dd->ipath_pkeys[i] &&
650                     atomic_inc_return(&dd->ipath_pkeyrefs[i]) == 1) {
651                         u64 pkey;
652
653                         /* for ipathstats, etc. */
654                         ipath_stats.sps_pkeys[i] = lkey;
655                         pd->port_pkeys[pidx] = dd->ipath_pkeys[i] = key;
656                         pkey =
657                                 (u64) dd->ipath_pkeys[0] |
658                                 ((u64) dd->ipath_pkeys[1] << 16) |
659                                 ((u64) dd->ipath_pkeys[2] << 32) |
660                                 ((u64) dd->ipath_pkeys[3] << 48);
661                         ipath_cdbg(PROC, "p%u set key %x in #%d, "
662                                    "portidx %d, new pkey reg %llx\n",
663                                    pd->port_port, key, i, pidx,
664                                    (unsigned long long) pkey);
665                         ipath_write_kreg(
666                                 dd, dd->ipath_kregs->kr_partitionkey, pkey);
667
668                         ret = 0;
669                         goto bail;
670                 }
671         }
672         ipath_dbg("port %u, all pkeys already in use 2nd pass, "
673                   "can't set %x\n", pd->port_port, key);
674         ret = -EBUSY;
675
676 bail:
677         return ret;
678 }
679
680 /**
681  * ipath_manage_rcvq - manage a port's receive queue
682  * @pd: the port
683  * @subport: the subport
684  * @start_stop: action to carry out
685  *
686  * start_stop == 0 disables receive on the port, for use in queue
687  * overflow conditions.  start_stop==1 re-enables, to be used to
688  * re-init the software copy of the head register
689  */
690 static int ipath_manage_rcvq(struct ipath_portdata *pd, unsigned subport,
691                              int start_stop)
692 {
693         struct ipath_devdata *dd = pd->port_dd;
694         u64 tval;
695
696         ipath_cdbg(PROC, "%sabling rcv for unit %u port %u:%u\n",
697                    start_stop ? "en" : "dis", dd->ipath_unit,
698                    pd->port_port, subport);
699         if (subport)
700                 goto bail;
701         /* atomically clear receive enable port. */
702         if (start_stop) {
703                 /*
704                  * On enable, force in-memory copy of the tail register to
705                  * 0, so that protocol code doesn't have to worry about
706                  * whether or not the chip has yet updated the in-memory
707                  * copy or not on return from the system call. The chip
708                  * always resets it's tail register back to 0 on a
709                  * transition from disabled to enabled.  This could cause a
710                  * problem if software was broken, and did the enable w/o
711                  * the disable, but eventually the in-memory copy will be
712                  * updated and correct itself, even in the face of software
713                  * bugs.
714                  */
715                 *pd->port_rcvhdrtail_kvaddr = 0;
716                 set_bit(INFINIPATH_R_PORTENABLE_SHIFT + pd->port_port,
717                         &dd->ipath_rcvctrl);
718         } else
719                 clear_bit(INFINIPATH_R_PORTENABLE_SHIFT + pd->port_port,
720                           &dd->ipath_rcvctrl);
721         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
722                          dd->ipath_rcvctrl);
723         /* now be sure chip saw it before we return */
724         tval = ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
725         if (start_stop) {
726                 /*
727                  * And try to be sure that tail reg update has happened too.
728                  * This should in theory interlock with the RXE changes to
729                  * the tail register.  Don't assign it to the tail register
730                  * in memory copy, since we could overwrite an update by the
731                  * chip if we did.
732                  */
733                 tval = ipath_read_ureg32(dd, ur_rcvhdrtail, pd->port_port);
734         }
735         /* always; new head should be equal to new tail; see above */
736 bail:
737         return 0;
738 }
739
740 static void ipath_clean_part_key(struct ipath_portdata *pd,
741                                  struct ipath_devdata *dd)
742 {
743         int i, j, pchanged = 0;
744         u64 oldpkey;
745
746         /* for debugging only */
747         oldpkey = (u64) dd->ipath_pkeys[0] |
748                 ((u64) dd->ipath_pkeys[1] << 16) |
749                 ((u64) dd->ipath_pkeys[2] << 32) |
750                 ((u64) dd->ipath_pkeys[3] << 48);
751
752         for (i = 0; i < ARRAY_SIZE(pd->port_pkeys); i++) {
753                 if (!pd->port_pkeys[i])
754                         continue;
755                 ipath_cdbg(VERBOSE, "look for key[%d] %hx in pkeys\n", i,
756                            pd->port_pkeys[i]);
757                 for (j = 0; j < ARRAY_SIZE(dd->ipath_pkeys); j++) {
758                         /* check for match independent of the global bit */
759                         if ((dd->ipath_pkeys[j] & 0x7fff) !=
760                             (pd->port_pkeys[i] & 0x7fff))
761                                 continue;
762                         if (atomic_dec_and_test(&dd->ipath_pkeyrefs[j])) {
763                                 ipath_cdbg(VERBOSE, "p%u clear key "
764                                            "%x matches #%d\n",
765                                            pd->port_port,
766                                            pd->port_pkeys[i], j);
767                                 ipath_stats.sps_pkeys[j] =
768                                         dd->ipath_pkeys[j] = 0;
769                                 pchanged++;
770                         }
771                         else ipath_cdbg(
772                                 VERBOSE, "p%u key %x matches #%d, "
773                                 "but ref still %d\n", pd->port_port,
774                                 pd->port_pkeys[i], j,
775                                 atomic_read(&dd->ipath_pkeyrefs[j]));
776                         break;
777                 }
778                 pd->port_pkeys[i] = 0;
779         }
780         if (pchanged) {
781                 u64 pkey = (u64) dd->ipath_pkeys[0] |
782                         ((u64) dd->ipath_pkeys[1] << 16) |
783                         ((u64) dd->ipath_pkeys[2] << 32) |
784                         ((u64) dd->ipath_pkeys[3] << 48);
785                 ipath_cdbg(VERBOSE, "p%u old pkey reg %llx, "
786                            "new pkey reg %llx\n", pd->port_port,
787                            (unsigned long long) oldpkey,
788                            (unsigned long long) pkey);
789                 ipath_write_kreg(dd, dd->ipath_kregs->kr_partitionkey,
790                                  pkey);
791         }
792 }
793
794 /*
795  * Initialize the port data with the receive buffer sizes
796  * so this can be done while the master port is locked.
797  * Otherwise, there is a race with a slave opening the port
798  * and seeing these fields uninitialized.
799  */
800 static void init_user_egr_sizes(struct ipath_portdata *pd)
801 {
802         struct ipath_devdata *dd = pd->port_dd;
803         unsigned egrperchunk, egrcnt, size;
804
805         /*
806          * to avoid wasting a lot of memory, we allocate 32KB chunks of
807          * physically contiguous memory, advance through it until used up
808          * and then allocate more.  Of course, we need memory to store those
809          * extra pointers, now.  Started out with 256KB, but under heavy
810          * memory pressure (creating large files and then copying them over
811          * NFS while doing lots of MPI jobs), we hit some allocation
812          * failures, even though we can sleep...  (2.6.10) Still get
813          * failures at 64K.  32K is the lowest we can go without wasting
814          * additional memory.
815          */
816         size = 0x8000;
817         egrperchunk = size / dd->ipath_rcvegrbufsize;
818         egrcnt = dd->ipath_rcvegrcnt;
819         pd->port_rcvegrbuf_chunks = (egrcnt + egrperchunk - 1) / egrperchunk;
820         pd->port_rcvegrbufs_perchunk = egrperchunk;
821         pd->port_rcvegrbuf_size = size;
822 }
823
824 /**
825  * ipath_create_user_egr - allocate eager TID buffers
826  * @pd: the port to allocate TID buffers for
827  *
828  * This routine is now quite different for user and kernel, because
829  * the kernel uses skb's, for the accelerated network performance
830  * This is the user port version
831  *
832  * Allocate the eager TID buffers and program them into infinipath
833  * They are no longer completely contiguous, we do multiple allocation
834  * calls.
835  */
836 static int ipath_create_user_egr(struct ipath_portdata *pd)
837 {
838         struct ipath_devdata *dd = pd->port_dd;
839         unsigned e, egrcnt, egrperchunk, chunk, egrsize, egroff;
840         size_t size;
841         int ret;
842         gfp_t gfp_flags;
843
844         /*
845          * GFP_USER, but without GFP_FS, so buffer cache can be
846          * coalesced (we hope); otherwise, even at order 4,
847          * heavy filesystem activity makes these fail, and we can
848          * use compound pages.
849          */
850         gfp_flags = __GFP_WAIT | __GFP_IO | __GFP_COMP;
851
852         egrcnt = dd->ipath_rcvegrcnt;
853         /* TID number offset for this port */
854         egroff = pd->port_port * egrcnt;
855         egrsize = dd->ipath_rcvegrbufsize;
856         ipath_cdbg(VERBOSE, "Allocating %d egr buffers, at egrtid "
857                    "offset %x, egrsize %u\n", egrcnt, egroff, egrsize);
858
859         chunk = pd->port_rcvegrbuf_chunks;
860         egrperchunk = pd->port_rcvegrbufs_perchunk;
861         size = pd->port_rcvegrbuf_size;
862         pd->port_rcvegrbuf = kmalloc(chunk * sizeof(pd->port_rcvegrbuf[0]),
863                                      GFP_KERNEL);
864         if (!pd->port_rcvegrbuf) {
865                 ret = -ENOMEM;
866                 goto bail;
867         }
868         pd->port_rcvegrbuf_phys =
869                 kmalloc(chunk * sizeof(pd->port_rcvegrbuf_phys[0]),
870                         GFP_KERNEL);
871         if (!pd->port_rcvegrbuf_phys) {
872                 ret = -ENOMEM;
873                 goto bail_rcvegrbuf;
874         }
875         for (e = 0; e < pd->port_rcvegrbuf_chunks; e++) {
876
877                 pd->port_rcvegrbuf[e] = dma_alloc_coherent(
878                         &dd->pcidev->dev, size, &pd->port_rcvegrbuf_phys[e],
879                         gfp_flags);
880
881                 if (!pd->port_rcvegrbuf[e]) {
882                         ret = -ENOMEM;
883                         goto bail_rcvegrbuf_phys;
884                 }
885         }
886
887         pd->port_rcvegr_phys = pd->port_rcvegrbuf_phys[0];
888
889         for (e = chunk = 0; chunk < pd->port_rcvegrbuf_chunks; chunk++) {
890                 dma_addr_t pa = pd->port_rcvegrbuf_phys[chunk];
891                 unsigned i;
892
893                 for (i = 0; e < egrcnt && i < egrperchunk; e++, i++) {
894                         dd->ipath_f_put_tid(dd, e + egroff +
895                                             (u64 __iomem *)
896                                             ((char __iomem *)
897                                              dd->ipath_kregbase +
898                                              dd->ipath_rcvegrbase), 0, pa);
899                         pa += egrsize;
900                 }
901                 cond_resched(); /* don't hog the cpu */
902         }
903
904         ret = 0;
905         goto bail;
906
907 bail_rcvegrbuf_phys:
908         for (e = 0; e < pd->port_rcvegrbuf_chunks &&
909                 pd->port_rcvegrbuf[e]; e++) {
910                 dma_free_coherent(&dd->pcidev->dev, size,
911                                   pd->port_rcvegrbuf[e],
912                                   pd->port_rcvegrbuf_phys[e]);
913
914         }
915         kfree(pd->port_rcvegrbuf_phys);
916         pd->port_rcvegrbuf_phys = NULL;
917 bail_rcvegrbuf:
918         kfree(pd->port_rcvegrbuf);
919         pd->port_rcvegrbuf = NULL;
920 bail:
921         return ret;
922 }
923
924
925 /* common code for the mappings on dma_alloc_coherent mem */
926 static int ipath_mmap_mem(struct vm_area_struct *vma,
927                              struct ipath_portdata *pd, unsigned len,
928                              int write_ok, dma_addr_t addr, char *what)
929 {
930         struct ipath_devdata *dd = pd->port_dd;
931         unsigned pfn = (unsigned long)addr >> PAGE_SHIFT;
932         int ret;
933
934         if ((vma->vm_end - vma->vm_start) > len) {
935                 dev_info(&dd->pcidev->dev,
936                          "FAIL on %s: len %lx > %x\n", what,
937                          vma->vm_end - vma->vm_start, len);
938                 ret = -EFAULT;
939                 goto bail;
940         }
941
942         if (!write_ok) {
943                 if (vma->vm_flags & VM_WRITE) {
944                         dev_info(&dd->pcidev->dev,
945                                  "%s must be mapped readonly\n", what);
946                         ret = -EPERM;
947                         goto bail;
948                 }
949
950                 /* don't allow them to later change with mprotect */
951                 vma->vm_flags &= ~VM_MAYWRITE;
952         }
953
954         ret = remap_pfn_range(vma, vma->vm_start, pfn,
955                               len, vma->vm_page_prot);
956         if (ret)
957                 dev_info(&dd->pcidev->dev,
958                          "%s port%u mmap of %lx, %x bytes r%c failed: %d\n",
959                          what, pd->port_port, (unsigned long)addr, len,
960                          write_ok?'w':'o', ret);
961         else
962                 ipath_cdbg(VERBOSE, "%s port%u mmaped %lx, %x bytes r%c\n",
963                         what, pd->port_port, (unsigned long)addr, len,
964                          write_ok?'w':'o');
965 bail:
966         return ret;
967 }
968
969 static int mmap_ureg(struct vm_area_struct *vma, struct ipath_devdata *dd,
970                      u64 ureg)
971 {
972         unsigned long phys;
973         int ret;
974
975         /*
976          * This is real hardware, so use io_remap.  This is the mechanism
977          * for the user process to update the head registers for their port
978          * in the chip.
979          */
980         if ((vma->vm_end - vma->vm_start) > PAGE_SIZE) {
981                 dev_info(&dd->pcidev->dev, "FAIL mmap userreg: reqlen "
982                          "%lx > PAGE\n", vma->vm_end - vma->vm_start);
983                 ret = -EFAULT;
984         } else {
985                 phys = dd->ipath_physaddr + ureg;
986                 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
987
988                 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND;
989                 ret = io_remap_pfn_range(vma, vma->vm_start,
990                                          phys >> PAGE_SHIFT,
991                                          vma->vm_end - vma->vm_start,
992                                          vma->vm_page_prot);
993         }
994         return ret;
995 }
996
997 static int mmap_piobufs(struct vm_area_struct *vma,
998                         struct ipath_devdata *dd,
999                         struct ipath_portdata *pd,
1000                         unsigned piobufs, unsigned piocnt)
1001 {
1002         unsigned long phys;
1003         int ret;
1004
1005         /*
1006          * When we map the PIO buffers in the chip, we want to map them as
1007          * writeonly, no read possible.   This prevents access to previous
1008          * process data, and catches users who might try to read the i/o
1009          * space due to a bug.
1010          */
1011         if ((vma->vm_end - vma->vm_start) > (piocnt * dd->ipath_palign)) {
1012                 dev_info(&dd->pcidev->dev, "FAIL mmap piobufs: "
1013                          "reqlen %lx > PAGE\n",
1014                          vma->vm_end - vma->vm_start);
1015                 ret = -EINVAL;
1016                 goto bail;
1017         }
1018
1019         phys = dd->ipath_physaddr + piobufs;
1020
1021         /*
1022          * Don't mark this as non-cached, or we don't get the
1023          * write combining behavior we want on the PIO buffers!
1024          */
1025
1026 #if defined(__powerpc__)
1027         /* There isn't a generic way to specify writethrough mappings */
1028         pgprot_val(vma->vm_page_prot) |= _PAGE_NO_CACHE;
1029         pgprot_val(vma->vm_page_prot) |= _PAGE_WRITETHRU;
1030         pgprot_val(vma->vm_page_prot) &= ~_PAGE_GUARDED;
1031 #endif
1032
1033         /*
1034          * don't allow them to later change to readable with mprotect (for when
1035          * not initially mapped readable, as is normally the case)
1036          */
1037         vma->vm_flags &= ~VM_MAYREAD;
1038         vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND;
1039
1040         ret = io_remap_pfn_range(vma, vma->vm_start, phys >> PAGE_SHIFT,
1041                                  vma->vm_end - vma->vm_start,
1042                                  vma->vm_page_prot);
1043 bail:
1044         return ret;
1045 }
1046
1047 static int mmap_rcvegrbufs(struct vm_area_struct *vma,
1048                            struct ipath_portdata *pd)
1049 {
1050         struct ipath_devdata *dd = pd->port_dd;
1051         unsigned long start, size;
1052         size_t total_size, i;
1053         dma_addr_t *phys;
1054         int ret;
1055
1056         size = pd->port_rcvegrbuf_size;
1057         total_size = pd->port_rcvegrbuf_chunks * size;
1058         if ((vma->vm_end - vma->vm_start) > total_size) {
1059                 dev_info(&dd->pcidev->dev, "FAIL on egr bufs: "
1060                          "reqlen %lx > actual %lx\n",
1061                          vma->vm_end - vma->vm_start,
1062                          (unsigned long) total_size);
1063                 ret = -EINVAL;
1064                 goto bail;
1065         }
1066
1067         if (vma->vm_flags & VM_WRITE) {
1068                 dev_info(&dd->pcidev->dev, "Can't map eager buffers as "
1069                          "writable (flags=%lx)\n", vma->vm_flags);
1070                 ret = -EPERM;
1071                 goto bail;
1072         }
1073         /* don't allow them to later change to writeable with mprotect */
1074         vma->vm_flags &= ~VM_MAYWRITE;
1075
1076         start = vma->vm_start;
1077         phys = pd->port_rcvegrbuf_phys;
1078
1079         for (i = 0; i < pd->port_rcvegrbuf_chunks; i++, start += size) {
1080                 ret = remap_pfn_range(vma, start, phys[i] >> PAGE_SHIFT,
1081                                       size, vma->vm_page_prot);
1082                 if (ret < 0)
1083                         goto bail;
1084         }
1085         ret = 0;
1086
1087 bail:
1088         return ret;
1089 }
1090
1091 /*
1092  * ipath_file_vma_nopage - handle a VMA page fault.
1093  */
1094 static struct page *ipath_file_vma_nopage(struct vm_area_struct *vma,
1095                                           unsigned long address, int *type)
1096 {
1097         unsigned long offset = address - vma->vm_start;
1098         struct page *page = NOPAGE_SIGBUS;
1099         void *pageptr;
1100
1101         /*
1102          * Convert the vmalloc address into a struct page.
1103          */
1104         pageptr = (void *)(offset + (vma->vm_pgoff << PAGE_SHIFT));
1105         page = vmalloc_to_page(pageptr);
1106         if (!page)
1107                 goto out;
1108
1109         /* Increment the reference count. */
1110         get_page(page);
1111         if (type)
1112                 *type = VM_FAULT_MINOR;
1113 out:
1114         return page;
1115 }
1116
1117 static struct vm_operations_struct ipath_file_vm_ops = {
1118         .nopage = ipath_file_vma_nopage,
1119 };
1120
1121 static int mmap_kvaddr(struct vm_area_struct *vma, u64 pgaddr,
1122                        struct ipath_portdata *pd, unsigned subport)
1123 {
1124         unsigned long len;
1125         struct ipath_devdata *dd;
1126         void *addr;
1127         size_t size;
1128         int ret;
1129
1130         /* If the port is not shared, all addresses should be physical */
1131         if (!pd->port_subport_cnt) {
1132                 ret = -EINVAL;
1133                 goto bail;
1134         }
1135
1136         dd = pd->port_dd;
1137         size = pd->port_rcvegrbuf_chunks * pd->port_rcvegrbuf_size;
1138
1139         /*
1140          * Master has all the slave uregbase, rcvhdrq, and
1141          * rcvegrbufs mmapped.
1142          */
1143         if (subport == 0) {
1144                 unsigned num_slaves = pd->port_subport_cnt - 1;
1145
1146                 if (pgaddr == ((u64) pd->subport_uregbase & MMAP64_MASK)) {
1147                         addr = pd->subport_uregbase;
1148                         size = PAGE_SIZE * num_slaves;
1149                 } else if (pgaddr == ((u64) pd->subport_rcvhdr_base &
1150                                       MMAP64_MASK)) {
1151                         addr = pd->subport_rcvhdr_base;
1152                         size = pd->port_rcvhdrq_size * num_slaves;
1153                 } else if (pgaddr == ((u64) pd->subport_rcvegrbuf &
1154                                       MMAP64_MASK)) {
1155                         addr = pd->subport_rcvegrbuf;
1156                         size *= num_slaves;
1157                 } else {
1158                         ret = -EINVAL;
1159                         goto bail;
1160                 }
1161         } else if (pgaddr == (((u64) pd->subport_uregbase +
1162                                PAGE_SIZE * (subport - 1)) & MMAP64_MASK)) {
1163                 addr = pd->subport_uregbase + PAGE_SIZE * (subport - 1);
1164                 size = PAGE_SIZE;
1165         } else if (pgaddr == (((u64) pd->subport_rcvhdr_base +
1166                                pd->port_rcvhdrq_size * (subport - 1)) &
1167                               MMAP64_MASK)) {
1168                 addr = pd->subport_rcvhdr_base +
1169                         pd->port_rcvhdrq_size * (subport - 1);
1170                 size = pd->port_rcvhdrq_size;
1171         } else if (pgaddr == (((u64) pd->subport_rcvegrbuf +
1172                                size * (subport - 1)) & MMAP64_MASK)) {
1173                 addr = pd->subport_rcvegrbuf + size * (subport - 1);
1174                 /* rcvegrbufs are read-only on the slave */
1175                 if (vma->vm_flags & VM_WRITE) {
1176                         dev_info(&dd->pcidev->dev,
1177                                  "Can't map eager buffers as "
1178                                  "writable (flags=%lx)\n", vma->vm_flags);
1179                         ret = -EPERM;
1180                         goto bail;
1181                 }
1182                 /*
1183                  * Don't allow permission to later change to writeable
1184                  * with mprotect.
1185                  */
1186                 vma->vm_flags &= ~VM_MAYWRITE;
1187         } else {
1188                 ret = -EINVAL;
1189                 goto bail;
1190         }
1191         len = vma->vm_end - vma->vm_start;
1192         if (len > size) {
1193                 ipath_cdbg(MM, "FAIL: reqlen %lx > %zx\n", len, size);
1194                 ret = -EINVAL;
1195                 goto bail;
1196         }
1197
1198         vma->vm_pgoff = (unsigned long) addr >> PAGE_SHIFT;
1199         vma->vm_ops = &ipath_file_vm_ops;
1200         vma->vm_flags |= VM_RESERVED | VM_DONTEXPAND;
1201         ret = 0;
1202
1203 bail:
1204         return ret;
1205 }
1206
1207 /**
1208  * ipath_mmap - mmap various structures into user space
1209  * @fp: the file pointer
1210  * @vma: the VM area
1211  *
1212  * We use this to have a shared buffer between the kernel and the user code
1213  * for the rcvhdr queue, egr buffers, and the per-port user regs and pio
1214  * buffers in the chip.  We have the open and close entries so we can bump
1215  * the ref count and keep the driver from being unloaded while still mapped.
1216  */
1217 static int ipath_mmap(struct file *fp, struct vm_area_struct *vma)
1218 {
1219         struct ipath_portdata *pd;
1220         struct ipath_devdata *dd;
1221         u64 pgaddr, ureg;
1222         unsigned piobufs, piocnt;
1223         int ret;
1224
1225         pd = port_fp(fp);
1226         if (!pd) {
1227                 ret = -EINVAL;
1228                 goto bail;
1229         }
1230         dd = pd->port_dd;
1231
1232         /*
1233          * This is the ipath_do_user_init() code, mapping the shared buffers
1234          * into the user process. The address referred to by vm_pgoff is the
1235          * file offset passed via mmap().  For shared ports, this is the
1236          * kernel vmalloc() address of the pages to share with the master.
1237          * For non-shared or master ports, this is a physical address.
1238          * We only do one mmap for each space mapped.
1239          */
1240         pgaddr = vma->vm_pgoff << PAGE_SHIFT;
1241
1242         /*
1243          * Check for 0 in case one of the allocations failed, but user
1244          * called mmap anyway.
1245          */
1246         if (!pgaddr)  {
1247                 ret = -EINVAL;
1248                 goto bail;
1249         }
1250
1251         ipath_cdbg(MM, "pgaddr %llx vm_start=%lx len %lx port %u:%u:%u\n",
1252                    (unsigned long long) pgaddr, vma->vm_start,
1253                    vma->vm_end - vma->vm_start, dd->ipath_unit,
1254                    pd->port_port, subport_fp(fp));
1255
1256         /*
1257          * Physical addresses must fit in 40 bits for our hardware.
1258          * Check for kernel virtual addresses first, anything else must
1259          * match a HW or memory address.
1260          */
1261         if (pgaddr >= (1ULL<<40)) {
1262                 ret = mmap_kvaddr(vma, pgaddr, pd, subport_fp(fp));
1263                 goto bail;
1264         }
1265
1266         if (!pd->port_subport_cnt) {
1267                 /* port is not shared */
1268                 ureg = dd->ipath_uregbase + dd->ipath_palign * pd->port_port;
1269                 piocnt = dd->ipath_pbufsport;
1270                 piobufs = pd->port_piobufs;
1271         } else if (!subport_fp(fp)) {
1272                 /* caller is the master */
1273                 ureg = dd->ipath_uregbase + dd->ipath_palign * pd->port_port;
1274                 piocnt = (dd->ipath_pbufsport / pd->port_subport_cnt) +
1275                          (dd->ipath_pbufsport % pd->port_subport_cnt);
1276                 piobufs = pd->port_piobufs +
1277                         dd->ipath_palign * (dd->ipath_pbufsport - piocnt);
1278         } else {
1279                 unsigned slave = subport_fp(fp) - 1;
1280
1281                 /* caller is a slave */
1282                 ureg = 0;
1283                 piocnt = dd->ipath_pbufsport / pd->port_subport_cnt;
1284                 piobufs = pd->port_piobufs + dd->ipath_palign * piocnt * slave;
1285         }
1286
1287         if (pgaddr == ureg)
1288                 ret = mmap_ureg(vma, dd, ureg);
1289         else if (pgaddr == piobufs)
1290                 ret = mmap_piobufs(vma, dd, pd, piobufs, piocnt);
1291         else if (pgaddr == dd->ipath_pioavailregs_phys)
1292                 /* in-memory copy of pioavail registers */
1293                 ret = ipath_mmap_mem(vma, pd, PAGE_SIZE, 0,
1294                                      dd->ipath_pioavailregs_phys,
1295                                      "pioavail registers");
1296         else if (subport_fp(fp))
1297                 /* Subports don't mmap the physical receive buffers */
1298                 ret = -EINVAL;
1299         else if (pgaddr == pd->port_rcvegr_phys)
1300                 ret = mmap_rcvegrbufs(vma, pd);
1301         else if (pgaddr == (u64) pd->port_rcvhdrq_phys)
1302                 /*
1303                  * The rcvhdrq itself; readonly except on HT (so have
1304                  * to allow writable mapping), multiple pages, contiguous
1305                  * from an i/o perspective.
1306                  */
1307                 ret = ipath_mmap_mem(vma, pd, pd->port_rcvhdrq_size, 1,
1308                                      pd->port_rcvhdrq_phys,
1309                                      "rcvhdrq");
1310         else if (pgaddr == (u64) pd->port_rcvhdrqtailaddr_phys)
1311                 /* in-memory copy of rcvhdrq tail register */
1312                 ret = ipath_mmap_mem(vma, pd, PAGE_SIZE, 0,
1313                                      pd->port_rcvhdrqtailaddr_phys,
1314                                      "rcvhdrq tail");
1315         else
1316                 ret = -EINVAL;
1317
1318         vma->vm_private_data = NULL;
1319
1320         if (ret < 0)
1321                 dev_info(&dd->pcidev->dev,
1322                          "Failure %d on off %llx len %lx\n",
1323                          -ret, (unsigned long long)pgaddr,
1324                          vma->vm_end - vma->vm_start);
1325 bail:
1326         return ret;
1327 }
1328
1329 static unsigned int ipath_poll(struct file *fp,
1330                                struct poll_table_struct *pt)
1331 {
1332         struct ipath_portdata *pd;
1333         u32 head, tail;
1334         int bit;
1335         unsigned pollflag = 0;
1336         struct ipath_devdata *dd;
1337
1338         pd = port_fp(fp);
1339         if (!pd)
1340                 goto bail;
1341         dd = pd->port_dd;
1342
1343         bit = pd->port_port + INFINIPATH_R_INTRAVAIL_SHIFT;
1344         set_bit(bit, &dd->ipath_rcvctrl);
1345
1346         /*
1347          * Before blocking, make sure that head is still == tail,
1348          * reading from the chip, so we can be sure the interrupt
1349          * enable has made it to the chip.  If not equal, disable
1350          * interrupt again and return immediately.  This avoids races,
1351          * and the overhead of the chip read doesn't matter much at
1352          * this point, since we are waiting for something anyway.
1353          */
1354
1355         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
1356                          dd->ipath_rcvctrl);
1357
1358         head = ipath_read_ureg32(dd, ur_rcvhdrhead, pd->port_port);
1359         tail = ipath_read_ureg32(dd, ur_rcvhdrtail, pd->port_port);
1360
1361         if (tail == head) {
1362                 set_bit(IPATH_PORT_WAITING_RCV, &pd->port_flag);
1363                 if (dd->ipath_rhdrhead_intr_off) /* arm rcv interrupt */
1364                         (void)ipath_write_ureg(dd, ur_rcvhdrhead,
1365                                                dd->ipath_rhdrhead_intr_off
1366                                                | head, pd->port_port);
1367                 poll_wait(fp, &pd->port_wait, pt);
1368
1369                 if (test_bit(IPATH_PORT_WAITING_RCV, &pd->port_flag)) {
1370                         /* timed out, no packets received */
1371                         clear_bit(IPATH_PORT_WAITING_RCV, &pd->port_flag);
1372                         pd->port_rcvwait_to++;
1373                 }
1374                 else
1375                         pollflag = POLLIN | POLLRDNORM;
1376         }
1377         else {
1378                 /* it's already happened; don't do wait_event overhead */
1379                 pollflag = POLLIN | POLLRDNORM;
1380                 pd->port_rcvnowait++;
1381         }
1382
1383         clear_bit(bit, &dd->ipath_rcvctrl);
1384         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
1385                          dd->ipath_rcvctrl);
1386
1387 bail:
1388         return pollflag;
1389 }
1390
1391 static int init_subports(struct ipath_devdata *dd,
1392                          struct ipath_portdata *pd,
1393                          const struct ipath_user_info *uinfo)
1394 {
1395         int ret = 0;
1396         unsigned num_slaves;
1397         size_t size;
1398
1399         /* Old user binaries don't know about subports */
1400         if ((uinfo->spu_userversion & 0xffff) != IPATH_USER_SWMINOR)
1401                 goto bail;
1402         /*
1403          * If the user is requesting zero or one port,
1404          * skip the subport allocation.
1405          */
1406         if (uinfo->spu_subport_cnt <= 1)
1407                 goto bail;
1408         if (uinfo->spu_subport_cnt > 4) {
1409                 ret = -EINVAL;
1410                 goto bail;
1411         }
1412
1413         num_slaves = uinfo->spu_subport_cnt - 1;
1414         pd->subport_uregbase = vmalloc(PAGE_SIZE * num_slaves);
1415         if (!pd->subport_uregbase) {
1416                 ret = -ENOMEM;
1417                 goto bail;
1418         }
1419         /* Note: pd->port_rcvhdrq_size isn't initialized yet. */
1420         size = ALIGN(dd->ipath_rcvhdrcnt * dd->ipath_rcvhdrentsize *
1421                      sizeof(u32), PAGE_SIZE) * num_slaves;
1422         pd->subport_rcvhdr_base = vmalloc(size);
1423         if (!pd->subport_rcvhdr_base) {
1424                 ret = -ENOMEM;
1425                 goto bail_ureg;
1426         }
1427
1428         pd->subport_rcvegrbuf = vmalloc(pd->port_rcvegrbuf_chunks *
1429                                         pd->port_rcvegrbuf_size *
1430                                         num_slaves);
1431         if (!pd->subport_rcvegrbuf) {
1432                 ret = -ENOMEM;
1433                 goto bail_rhdr;
1434         }
1435
1436         pd->port_subport_cnt = uinfo->spu_subport_cnt;
1437         pd->port_subport_id = uinfo->spu_subport_id;
1438         pd->active_slaves = 1;
1439         goto bail;
1440
1441 bail_rhdr:
1442         vfree(pd->subport_rcvhdr_base);
1443 bail_ureg:
1444         vfree(pd->subport_uregbase);
1445         pd->subport_uregbase = NULL;
1446 bail:
1447         return ret;
1448 }
1449
1450 static int try_alloc_port(struct ipath_devdata *dd, int port,
1451                           struct file *fp,
1452                           const struct ipath_user_info *uinfo)
1453 {
1454         struct ipath_portdata *pd;
1455         int ret;
1456
1457         if (!(pd = dd->ipath_pd[port])) {
1458                 void *ptmp;
1459
1460                 pd = kzalloc(sizeof(struct ipath_portdata), GFP_KERNEL);
1461
1462                 /*
1463                  * Allocate memory for use in ipath_tid_update() just once
1464                  * at open, not per call.  Reduces cost of expected send
1465                  * setup.
1466                  */
1467                 ptmp = kmalloc(dd->ipath_rcvtidcnt * sizeof(u16) +
1468                                dd->ipath_rcvtidcnt * sizeof(struct page **),
1469                                GFP_KERNEL);
1470                 if (!pd || !ptmp) {
1471                         ipath_dev_err(dd, "Unable to allocate portdata "
1472                                       "memory, failing open\n");
1473                         ret = -ENOMEM;
1474                         kfree(pd);
1475                         kfree(ptmp);
1476                         goto bail;
1477                 }
1478                 dd->ipath_pd[port] = pd;
1479                 dd->ipath_pd[port]->port_port = port;
1480                 dd->ipath_pd[port]->port_dd = dd;
1481                 dd->ipath_pd[port]->port_tid_pg_list = ptmp;
1482                 init_waitqueue_head(&dd->ipath_pd[port]->port_wait);
1483         }
1484         if (!pd->port_cnt) {
1485                 pd->userversion = uinfo->spu_userversion;
1486                 init_user_egr_sizes(pd);
1487                 if ((ret = init_subports(dd, pd, uinfo)) != 0)
1488                         goto bail;
1489                 ipath_cdbg(PROC, "%s[%u] opened unit:port %u:%u\n",
1490                            current->comm, current->pid, dd->ipath_unit,
1491                            port);
1492                 pd->port_cnt = 1;
1493                 port_fp(fp) = pd;
1494                 pd->port_pid = current->pid;
1495                 strncpy(pd->port_comm, current->comm, sizeof(pd->port_comm));
1496                 ipath_stats.sps_ports++;
1497                 ret = 0;
1498         } else
1499                 ret = -EBUSY;
1500
1501 bail:
1502         return ret;
1503 }
1504
1505 static inline int usable(struct ipath_devdata *dd)
1506 {
1507         return dd &&
1508                 (dd->ipath_flags & IPATH_PRESENT) &&
1509                 dd->ipath_kregbase &&
1510                 dd->ipath_lid &&
1511                 !(dd->ipath_flags & (IPATH_LINKDOWN | IPATH_DISABLED
1512                                      | IPATH_LINKUNK));
1513 }
1514
1515 static int find_free_port(int unit, struct file *fp,
1516                           const struct ipath_user_info *uinfo)
1517 {
1518         struct ipath_devdata *dd = ipath_lookup(unit);
1519         int ret, i;
1520
1521         if (!dd) {
1522                 ret = -ENODEV;
1523                 goto bail;
1524         }
1525
1526         if (!usable(dd)) {
1527                 ret = -ENETDOWN;
1528                 goto bail;
1529         }
1530
1531         for (i = 1; i < dd->ipath_cfgports; i++) {
1532                 ret = try_alloc_port(dd, i, fp, uinfo);
1533                 if (ret != -EBUSY)
1534                         goto bail;
1535         }
1536         ret = -EBUSY;
1537
1538 bail:
1539         return ret;
1540 }
1541
1542 static int find_best_unit(struct file *fp,
1543                           const struct ipath_user_info *uinfo)
1544 {
1545         int ret = 0, i, prefunit = -1, devmax;
1546         int maxofallports, npresent, nup;
1547         int ndev;
1548
1549         devmax = ipath_count_units(&npresent, &nup, &maxofallports);
1550
1551         /*
1552          * This code is present to allow a knowledgeable person to
1553          * specify the layout of processes to processors before opening
1554          * this driver, and then we'll assign the process to the "closest"
1555          * InfiniPath chip to that processor (we assume reasonable connectivity,
1556          * for now).  This code assumes that if affinity has been set
1557          * before this point, that at most one cpu is set; for now this
1558          * is reasonable.  I check for both cpus_empty() and cpus_full(),
1559          * in case some kernel variant sets none of the bits when no
1560          * affinity is set.  2.6.11 and 12 kernels have all present
1561          * cpus set.  Some day we'll have to fix it up further to handle
1562          * a cpu subset.  This algorithm fails for two HT chips connected
1563          * in tunnel fashion.  Eventually this needs real topology
1564          * information.  There may be some issues with dual core numbering
1565          * as well.  This needs more work prior to release.
1566          */
1567         if (!cpus_empty(current->cpus_allowed) &&
1568             !cpus_full(current->cpus_allowed)) {
1569                 int ncpus = num_online_cpus(), curcpu = -1;
1570                 for (i = 0; i < ncpus; i++)
1571                         if (cpu_isset(i, current->cpus_allowed)) {
1572                                 ipath_cdbg(PROC, "%s[%u] affinity set for "
1573                                            "cpu %d\n", current->comm,
1574                                            current->pid, i);
1575                                 curcpu = i;
1576                         }
1577                 if (curcpu != -1) {
1578                         if (npresent) {
1579                                 prefunit = curcpu / (ncpus / npresent);
1580                                 ipath_dbg("%s[%u] %d chips, %d cpus, "
1581                                           "%d cpus/chip, select unit %d\n",
1582                                           current->comm, current->pid,
1583                                           npresent, ncpus, ncpus / npresent,
1584                                           prefunit);
1585                         }
1586                 }
1587         }
1588
1589         /*
1590          * user ports start at 1, kernel port is 0
1591          * For now, we do round-robin access across all chips
1592          */
1593
1594         if (prefunit != -1)
1595                 devmax = prefunit + 1;
1596 recheck:
1597         for (i = 1; i < maxofallports; i++) {
1598                 for (ndev = prefunit != -1 ? prefunit : 0; ndev < devmax;
1599                      ndev++) {
1600                         struct ipath_devdata *dd = ipath_lookup(ndev);
1601
1602                         if (!usable(dd))
1603                                 continue; /* can't use this unit */
1604                         if (i >= dd->ipath_cfgports)
1605                                 /*
1606                                  * Maxed out on users of this unit. Try
1607                                  * next.
1608                                  */
1609                                 continue;
1610                         ret = try_alloc_port(dd, i, fp, uinfo);
1611                         if (!ret)
1612                                 goto done;
1613                 }
1614         }
1615
1616         if (npresent) {
1617                 if (nup == 0) {
1618                         ret = -ENETDOWN;
1619                         ipath_dbg("No ports available (none initialized "
1620                                   "and ready)\n");
1621                 } else {
1622                         if (prefunit > 0) {
1623                                 /* if started above 0, retry from 0 */
1624                                 ipath_cdbg(PROC,
1625                                            "%s[%u] no ports on prefunit "
1626                                            "%d, clear and re-check\n",
1627                                            current->comm, current->pid,
1628                                            prefunit);
1629                                 devmax = ipath_count_units(NULL, NULL,
1630                                                            NULL);
1631                                 prefunit = -1;
1632                                 goto recheck;
1633                         }
1634                         ret = -EBUSY;
1635                         ipath_dbg("No ports available\n");
1636                 }
1637         } else {
1638                 ret = -ENXIO;
1639                 ipath_dbg("No boards found\n");
1640         }
1641
1642 done:
1643         return ret;
1644 }
1645
1646 static int find_shared_port(struct file *fp,
1647                             const struct ipath_user_info *uinfo)
1648 {
1649         int devmax, ndev, i;
1650         int ret = 0;
1651
1652         devmax = ipath_count_units(NULL, NULL, NULL);
1653
1654         for (ndev = 0; ndev < devmax; ndev++) {
1655                 struct ipath_devdata *dd = ipath_lookup(ndev);
1656
1657                 if (!dd)
1658                         continue;
1659                 for (i = 1; i < dd->ipath_cfgports; i++) {
1660                         struct ipath_portdata *pd = dd->ipath_pd[i];
1661
1662                         /* Skip ports which are not yet open */
1663                         if (!pd || !pd->port_cnt)
1664                                 continue;
1665                         /* Skip port if it doesn't match the requested one */
1666                         if (pd->port_subport_id != uinfo->spu_subport_id)
1667                                 continue;
1668                         /* Verify the sharing process matches the master */
1669                         if (pd->port_subport_cnt != uinfo->spu_subport_cnt ||
1670                             pd->userversion != uinfo->spu_userversion ||
1671                             pd->port_cnt >= pd->port_subport_cnt) {
1672                                 ret = -EINVAL;
1673                                 goto done;
1674                         }
1675                         port_fp(fp) = pd;
1676                         subport_fp(fp) = pd->port_cnt++;
1677                         tidcursor_fp(fp) = 0;
1678                         pd->active_slaves |= 1 << subport_fp(fp);
1679                         ipath_cdbg(PROC,
1680                                    "%s[%u] %u sharing %s[%u] unit:port %u:%u\n",
1681                                    current->comm, current->pid,
1682                                    subport_fp(fp),
1683                                    pd->port_comm, pd->port_pid,
1684                                    dd->ipath_unit, pd->port_port);
1685                         ret = 1;
1686                         goto done;
1687                 }
1688         }
1689
1690 done:
1691         return ret;
1692 }
1693
1694 static int ipath_open(struct inode *in, struct file *fp)
1695 {
1696         /* The real work is performed later in ipath_do_user_init() */
1697         fp->private_data = kzalloc(sizeof(struct ipath_filedata), GFP_KERNEL);
1698         return fp->private_data ? 0 : -ENOMEM;
1699 }
1700
1701 static int ipath_do_user_init(struct file *fp,
1702                               const struct ipath_user_info *uinfo)
1703 {
1704         int ret;
1705         struct ipath_portdata *pd;
1706         struct ipath_devdata *dd;
1707         u32 head32;
1708         int i_minor;
1709         unsigned swminor;
1710
1711         /* Check to be sure we haven't already initialized this file */
1712         if (port_fp(fp)) {
1713                 ret = -EINVAL;
1714                 goto done;
1715         }
1716
1717         /* for now, if major version is different, bail */
1718         if ((uinfo->spu_userversion >> 16) != IPATH_USER_SWMAJOR) {
1719                 ipath_dbg("User major version %d not same as driver "
1720                           "major %d\n", uinfo->spu_userversion >> 16,
1721                           IPATH_USER_SWMAJOR);
1722                 ret = -ENODEV;
1723                 goto done;
1724         }
1725
1726         swminor = uinfo->spu_userversion & 0xffff;
1727         if (swminor != IPATH_USER_SWMINOR)
1728                 ipath_dbg("User minor version %d not same as driver "
1729                           "minor %d\n", swminor, IPATH_USER_SWMINOR);
1730
1731         mutex_lock(&ipath_mutex);
1732
1733         if (swminor == IPATH_USER_SWMINOR && uinfo->spu_subport_cnt &&
1734             (ret = find_shared_port(fp, uinfo))) {
1735                 mutex_unlock(&ipath_mutex);
1736                 if (ret > 0)
1737                         ret = 0;
1738                 goto done;
1739         }
1740
1741         i_minor = iminor(fp->f_dentry->d_inode) - IPATH_USER_MINOR_BASE;
1742         ipath_cdbg(VERBOSE, "open on dev %lx (minor %d)\n",
1743                    (long)fp->f_dentry->d_inode->i_rdev, i_minor);
1744
1745         if (i_minor)
1746                 ret = find_free_port(i_minor - 1, fp, uinfo);
1747         else
1748                 ret = find_best_unit(fp, uinfo);
1749
1750         mutex_unlock(&ipath_mutex);
1751
1752         if (ret)
1753                 goto done;
1754
1755         pd = port_fp(fp);
1756         dd = pd->port_dd;
1757
1758         if (uinfo->spu_rcvhdrsize) {
1759                 ret = ipath_setrcvhdrsize(dd, uinfo->spu_rcvhdrsize);
1760                 if (ret)
1761                         goto done;
1762         }
1763
1764         /* for now we do nothing with rcvhdrcnt: uinfo->spu_rcvhdrcnt */
1765
1766         /* for right now, kernel piobufs are at end, so port 1 is at 0 */
1767         pd->port_piobufs = dd->ipath_piobufbase +
1768                 dd->ipath_pbufsport * (pd->port_port - 1) * dd->ipath_palign;
1769         ipath_cdbg(VERBOSE, "Set base of piobufs for port %u to 0x%x\n",
1770                    pd->port_port, pd->port_piobufs);
1771
1772         /*
1773          * Now allocate the rcvhdr Q and eager TIDs; skip the TID
1774          * array for time being.  If pd->port_port > chip-supported,
1775          * we need to do extra stuff here to handle by handling overflow
1776          * through port 0, someday
1777          */
1778         ret = ipath_create_rcvhdrq(dd, pd);
1779         if (!ret)
1780                 ret = ipath_create_user_egr(pd);
1781         if (ret)
1782                 goto done;
1783
1784         /*
1785          * set the eager head register for this port to the current values
1786          * of the tail pointers, since we don't know if they were
1787          * updated on last use of the port.
1788          */
1789         head32 = ipath_read_ureg32(dd, ur_rcvegrindextail, pd->port_port);
1790         ipath_write_ureg(dd, ur_rcvegrindexhead, head32, pd->port_port);
1791         dd->ipath_lastegrheads[pd->port_port] = -1;
1792         dd->ipath_lastrcvhdrqtails[pd->port_port] = -1;
1793         ipath_cdbg(VERBOSE, "Wrote port%d egrhead %x from tail regs\n",
1794                 pd->port_port, head32);
1795         pd->port_tidcursor = 0; /* start at beginning after open */
1796         /*
1797          * now enable the port; the tail registers will be written to memory
1798          * by the chip as soon as it sees the write to
1799          * dd->ipath_kregs->kr_rcvctrl.  The update only happens on
1800          * transition from 0 to 1, so clear it first, then set it as part of
1801          * enabling the port.  This will (very briefly) affect any other
1802          * open ports, but it shouldn't be long enough to be an issue.
1803          * We explictly set the in-memory copy to 0 beforehand, so we don't
1804          * have to wait to be sure the DMA update has happened.
1805          */
1806         *pd->port_rcvhdrtail_kvaddr = 0ULL;
1807         set_bit(INFINIPATH_R_PORTENABLE_SHIFT + pd->port_port,
1808                 &dd->ipath_rcvctrl);
1809         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
1810                          dd->ipath_rcvctrl & ~INFINIPATH_R_TAILUPD);
1811         ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
1812                          dd->ipath_rcvctrl);
1813 done:
1814         return ret;
1815 }
1816
1817 /**
1818  * unlock_exptid - unlock any expected TID entries port still had in use
1819  * @pd: port
1820  *
1821  * We don't actually update the chip here, because we do a bulk update
1822  * below, using ipath_f_clear_tids.
1823  */
1824 static void unlock_expected_tids(struct ipath_portdata *pd)
1825 {
1826         struct ipath_devdata *dd = pd->port_dd;
1827         int port_tidbase = pd->port_port * dd->ipath_rcvtidcnt;
1828         int i, cnt = 0, maxtid = port_tidbase + dd->ipath_rcvtidcnt;
1829
1830         ipath_cdbg(VERBOSE, "Port %u unlocking any locked expTID pages\n",
1831                    pd->port_port);
1832         for (i = port_tidbase; i < maxtid; i++) {
1833                 if (!dd->ipath_pageshadow[i])
1834                         continue;
1835
1836                 ipath_release_user_pages_on_close(&dd->ipath_pageshadow[i],
1837                                                   1);
1838                 dd->ipath_pageshadow[i] = NULL;
1839                 cnt++;
1840                 ipath_stats.sps_pageunlocks++;
1841         }
1842         if (cnt)
1843                 ipath_cdbg(VERBOSE, "Port %u locked %u expTID entries\n",
1844                            pd->port_port, cnt);
1845
1846         if (ipath_stats.sps_pagelocks || ipath_stats.sps_pageunlocks)
1847                 ipath_cdbg(VERBOSE, "%llu pages locked, %llu unlocked\n",
1848                            (unsigned long long) ipath_stats.sps_pagelocks,
1849                            (unsigned long long)
1850                            ipath_stats.sps_pageunlocks);
1851 }
1852
1853 static int ipath_close(struct inode *in, struct file *fp)
1854 {
1855         int ret = 0;
1856         struct ipath_filedata *fd;
1857         struct ipath_portdata *pd;
1858         struct ipath_devdata *dd;
1859         unsigned port;
1860
1861         ipath_cdbg(VERBOSE, "close on dev %lx, private data %p\n",
1862                    (long)in->i_rdev, fp->private_data);
1863
1864         mutex_lock(&ipath_mutex);
1865
1866         fd = (struct ipath_filedata *) fp->private_data;
1867         fp->private_data = NULL;
1868         pd = fd->pd;
1869         if (!pd) {
1870                 mutex_unlock(&ipath_mutex);
1871                 goto bail;
1872         }
1873         if (--pd->port_cnt) {
1874                 /*
1875                  * XXX If the master closes the port before the slave(s),
1876                  * revoke the mmap for the eager receive queue so
1877                  * the slave(s) don't wait for receive data forever.
1878                  */
1879                 pd->active_slaves &= ~(1 << fd->subport);
1880                 mutex_unlock(&ipath_mutex);
1881                 goto bail;
1882         }
1883         port = pd->port_port;
1884         dd = pd->port_dd;
1885
1886         if (pd->port_hdrqfull) {
1887                 ipath_cdbg(PROC, "%s[%u] had %u rcvhdrqfull errors "
1888                            "during run\n", pd->port_comm, pd->port_pid,
1889                            pd->port_hdrqfull);
1890                 pd->port_hdrqfull = 0;
1891         }
1892
1893         if (pd->port_rcvwait_to || pd->port_piowait_to
1894             || pd->port_rcvnowait || pd->port_pionowait) {
1895                 ipath_cdbg(VERBOSE, "port%u, %u rcv, %u pio wait timeo; "
1896                            "%u rcv %u, pio already\n",
1897                            pd->port_port, pd->port_rcvwait_to,
1898                            pd->port_piowait_to, pd->port_rcvnowait,
1899                            pd->port_pionowait);
1900                 pd->port_rcvwait_to = pd->port_piowait_to =
1901                         pd->port_rcvnowait = pd->port_pionowait = 0;
1902         }
1903         if (pd->port_flag) {
1904                 ipath_dbg("port %u port_flag still set to 0x%lx\n",
1905                           pd->port_port, pd->port_flag);
1906                 pd->port_flag = 0;
1907         }
1908
1909         if (dd->ipath_kregbase) {
1910                 int i;
1911                 /* atomically clear receive enable port. */
1912                 clear_bit(INFINIPATH_R_PORTENABLE_SHIFT + port,
1913                           &dd->ipath_rcvctrl);
1914                 ipath_write_kreg( dd, dd->ipath_kregs->kr_rcvctrl,
1915                         dd->ipath_rcvctrl);
1916                 /* and read back from chip to be sure that nothing
1917                  * else is in flight when we do the rest */
1918                 (void)ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
1919
1920                 /* clean up the pkeys for this port user */
1921                 ipath_clean_part_key(pd, dd);
1922                 /*
1923                  * be paranoid, and never write 0's to these, just use an
1924                  * unused part of the port 0 tail page.  Of course,
1925                  * rcvhdraddr points to a large chunk of memory, so this
1926                  * could still trash things, but at least it won't trash
1927                  * page 0, and by disabling the port, it should stop "soon",
1928                  * even if a packet or two is in already in flight after we
1929                  * disabled the port.
1930                  */
1931                 ipath_write_kreg_port(dd,
1932                         dd->ipath_kregs->kr_rcvhdrtailaddr, port,
1933                         dd->ipath_dummy_hdrq_phys);
1934                 ipath_write_kreg_port(dd, dd->ipath_kregs->kr_rcvhdraddr,
1935                         pd->port_port, dd->ipath_dummy_hdrq_phys);
1936
1937                 i = dd->ipath_pbufsport * (port - 1);
1938                 ipath_disarm_piobufs(dd, i, dd->ipath_pbufsport);
1939
1940                 if (dd->ipath_pageshadow)
1941                         unlock_expected_tids(pd);
1942                 ipath_stats.sps_ports--;
1943                 ipath_cdbg(PROC, "%s[%u] closed port %u:%u\n",
1944                            pd->port_comm, pd->port_pid,
1945                            dd->ipath_unit, port);
1946
1947                 dd->ipath_f_clear_tids(dd, pd->port_port);
1948         }
1949
1950         pd->port_pid = 0;
1951         dd->ipath_pd[pd->port_port] = NULL; /* before releasing mutex */
1952         mutex_unlock(&ipath_mutex);
1953         ipath_free_pddata(dd, pd); /* after releasing the mutex */
1954
1955 bail:
1956         kfree(fd);
1957         return ret;
1958 }
1959
1960 static int ipath_port_info(struct ipath_portdata *pd, u16 subport,
1961                            struct ipath_port_info __user *uinfo)
1962 {
1963         struct ipath_port_info info;
1964         int nup;
1965         int ret;
1966         size_t sz;
1967
1968         (void) ipath_count_units(NULL, &nup, NULL);
1969         info.num_active = nup;
1970         info.unit = pd->port_dd->ipath_unit;
1971         info.port = pd->port_port;
1972         info.subport = subport;
1973         /* Don't return new fields if old library opened the port. */
1974         if ((pd->userversion & 0xffff) == IPATH_USER_SWMINOR) {
1975                 /* Number of user ports available for this device. */
1976                 info.num_ports = pd->port_dd->ipath_cfgports - 1;
1977                 info.num_subports = pd->port_subport_cnt;
1978                 sz = sizeof(info);
1979         } else
1980                 sz = sizeof(info) - 2 * sizeof(u16);
1981
1982         if (copy_to_user(uinfo, &info, sz)) {
1983                 ret = -EFAULT;
1984                 goto bail;
1985         }
1986         ret = 0;
1987
1988 bail:
1989         return ret;
1990 }
1991
1992 static int ipath_get_slave_info(struct ipath_portdata *pd,
1993                                 void __user *slave_mask_addr)
1994 {
1995         int ret = 0;
1996
1997         if (copy_to_user(slave_mask_addr, &pd->active_slaves, sizeof(u32)))
1998                 ret = -EFAULT;
1999         return ret;
2000 }
2001
2002 static ssize_t ipath_write(struct file *fp, const char __user *data,
2003                            size_t count, loff_t *off)
2004 {
2005         const struct ipath_cmd __user *ucmd;
2006         struct ipath_portdata *pd;
2007         const void __user *src;
2008         size_t consumed, copy;
2009         struct ipath_cmd cmd;
2010         ssize_t ret = 0;
2011         void *dest;
2012
2013         if (count < sizeof(cmd.type)) {
2014                 ret = -EINVAL;
2015                 goto bail;
2016         }
2017
2018         ucmd = (const struct ipath_cmd __user *) data;
2019
2020         if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) {
2021                 ret = -EFAULT;
2022                 goto bail;
2023         }
2024
2025         consumed = sizeof(cmd.type);
2026
2027         switch (cmd.type) {
2028         case IPATH_CMD_USER_INIT:
2029                 copy = sizeof(cmd.cmd.user_info);
2030                 dest = &cmd.cmd.user_info;
2031                 src = &ucmd->cmd.user_info;
2032                 break;
2033         case IPATH_CMD_RECV_CTRL:
2034                 copy = sizeof(cmd.cmd.recv_ctrl);
2035                 dest = &cmd.cmd.recv_ctrl;
2036                 src = &ucmd->cmd.recv_ctrl;
2037                 break;
2038         case IPATH_CMD_PORT_INFO:
2039                 copy = sizeof(cmd.cmd.port_info);
2040                 dest = &cmd.cmd.port_info;
2041                 src = &ucmd->cmd.port_info;
2042                 break;
2043         case IPATH_CMD_TID_UPDATE:
2044         case IPATH_CMD_TID_FREE:
2045                 copy = sizeof(cmd.cmd.tid_info);
2046                 dest = &cmd.cmd.tid_info;
2047                 src = &ucmd->cmd.tid_info;
2048                 break;
2049         case IPATH_CMD_SET_PART_KEY:
2050                 copy = sizeof(cmd.cmd.part_key);
2051                 dest = &cmd.cmd.part_key;
2052                 src = &ucmd->cmd.part_key;
2053                 break;
2054         case IPATH_CMD_SLAVE_INFO:
2055                 copy = sizeof(cmd.cmd.slave_mask_addr);
2056                 dest = &cmd.cmd.slave_mask_addr;
2057                 src = &ucmd->cmd.slave_mask_addr;
2058                 break;
2059         default:
2060                 ret = -EINVAL;
2061                 goto bail;
2062         }
2063
2064         if ((count - consumed) < copy) {
2065                 ret = -EINVAL;
2066                 goto bail;
2067         }
2068
2069         if (copy_from_user(dest, src, copy)) {
2070                 ret = -EFAULT;
2071                 goto bail;
2072         }
2073
2074         consumed += copy;
2075         pd = port_fp(fp);
2076         if (!pd && cmd.type != IPATH_CMD_USER_INIT) {
2077                 ret = -EINVAL;
2078                 goto bail;
2079         }
2080
2081         switch (cmd.type) {
2082         case IPATH_CMD_USER_INIT:
2083                 ret = ipath_do_user_init(fp, &cmd.cmd.user_info);
2084                 if (ret)
2085                         goto bail;
2086                 ret = ipath_get_base_info(
2087                         fp, (void __user *) (unsigned long)
2088                         cmd.cmd.user_info.spu_base_info,
2089                         cmd.cmd.user_info.spu_base_info_size);
2090                 break;
2091         case IPATH_CMD_RECV_CTRL:
2092                 ret = ipath_manage_rcvq(pd, subport_fp(fp), cmd.cmd.recv_ctrl);
2093                 break;
2094         case IPATH_CMD_PORT_INFO:
2095                 ret = ipath_port_info(pd, subport_fp(fp),
2096                                       (struct ipath_port_info __user *)
2097                                       (unsigned long) cmd.cmd.port_info);
2098                 break;
2099         case IPATH_CMD_TID_UPDATE:
2100                 ret = ipath_tid_update(pd, fp, &cmd.cmd.tid_info);
2101                 break;
2102         case IPATH_CMD_TID_FREE:
2103                 ret = ipath_tid_free(pd, subport_fp(fp), &cmd.cmd.tid_info);
2104                 break;
2105         case IPATH_CMD_SET_PART_KEY:
2106                 ret = ipath_set_part_key(pd, cmd.cmd.part_key);
2107                 break;
2108         case IPATH_CMD_SLAVE_INFO:
2109                 ret = ipath_get_slave_info(pd,
2110                                            (void __user *) (unsigned long)
2111                                            cmd.cmd.slave_mask_addr);
2112                 break;
2113         }
2114
2115         if (ret >= 0)
2116                 ret = consumed;
2117
2118 bail:
2119         return ret;
2120 }
2121
2122 static struct class *ipath_class;
2123
2124 static int init_cdev(int minor, char *name, struct file_operations *fops,
2125                      struct cdev **cdevp, struct class_device **class_devp)
2126 {
2127         const dev_t dev = MKDEV(IPATH_MAJOR, minor);
2128         struct cdev *cdev = NULL;
2129         struct class_device *class_dev = NULL;
2130         int ret;
2131
2132         cdev = cdev_alloc();
2133         if (!cdev) {
2134                 printk(KERN_ERR IPATH_DRV_NAME
2135                        ": Could not allocate cdev for minor %d, %s\n",
2136                        minor, name);
2137                 ret = -ENOMEM;
2138                 goto done;
2139         }
2140
2141         cdev->owner = THIS_MODULE;
2142         cdev->ops = fops;
2143         kobject_set_name(&cdev->kobj, name);
2144
2145         ret = cdev_add(cdev, dev, 1);
2146         if (ret < 0) {
2147                 printk(KERN_ERR IPATH_DRV_NAME
2148                        ": Could not add cdev for minor %d, %s (err %d)\n",
2149                        minor, name, -ret);
2150                 goto err_cdev;
2151         }
2152
2153         class_dev = class_device_create(ipath_class, NULL, dev, NULL, name);
2154
2155         if (IS_ERR(class_dev)) {
2156                 ret = PTR_ERR(class_dev);
2157                 printk(KERN_ERR IPATH_DRV_NAME ": Could not create "
2158                        "class_dev for minor %d, %s (err %d)\n",
2159                        minor, name, -ret);
2160                 goto err_cdev;
2161         }
2162
2163         goto done;
2164
2165 err_cdev:
2166         cdev_del(cdev);
2167         cdev = NULL;
2168
2169 done:
2170         if (ret >= 0) {
2171                 *cdevp = cdev;
2172                 *class_devp = class_dev;
2173         } else {
2174                 *cdevp = NULL;
2175                 *class_devp = NULL;
2176         }
2177
2178         return ret;
2179 }
2180
2181 int ipath_cdev_init(int minor, char *name, struct file_operations *fops,
2182                     struct cdev **cdevp, struct class_device **class_devp)
2183 {
2184         return init_cdev(minor, name, fops, cdevp, class_devp);
2185 }
2186
2187 static void cleanup_cdev(struct cdev **cdevp,
2188                          struct class_device **class_devp)
2189 {
2190         struct class_device *class_dev = *class_devp;
2191
2192         if (class_dev) {
2193                 class_device_unregister(class_dev);
2194                 *class_devp = NULL;
2195         }
2196
2197         if (*cdevp) {
2198                 cdev_del(*cdevp);
2199                 *cdevp = NULL;
2200         }
2201 }
2202
2203 void ipath_cdev_cleanup(struct cdev **cdevp,
2204                         struct class_device **class_devp)
2205 {
2206         cleanup_cdev(cdevp, class_devp);
2207 }
2208
2209 static struct cdev *wildcard_cdev;
2210 static struct class_device *wildcard_class_dev;
2211
2212 static const dev_t dev = MKDEV(IPATH_MAJOR, 0);
2213
2214 static int user_init(void)
2215 {
2216         int ret;
2217
2218         ret = register_chrdev_region(dev, IPATH_NMINORS, IPATH_DRV_NAME);
2219         if (ret < 0) {
2220                 printk(KERN_ERR IPATH_DRV_NAME ": Could not register "
2221                        "chrdev region (err %d)\n", -ret);
2222                 goto done;
2223         }
2224
2225         ipath_class = class_create(THIS_MODULE, IPATH_DRV_NAME);
2226
2227         if (IS_ERR(ipath_class)) {
2228                 ret = PTR_ERR(ipath_class);
2229                 printk(KERN_ERR IPATH_DRV_NAME ": Could not create "
2230                        "device class (err %d)\n", -ret);
2231                 goto bail;
2232         }
2233
2234         goto done;
2235 bail:
2236         unregister_chrdev_region(dev, IPATH_NMINORS);
2237 done:
2238         return ret;
2239 }
2240
2241 static void user_cleanup(void)
2242 {
2243         if (ipath_class) {
2244                 class_destroy(ipath_class);
2245                 ipath_class = NULL;
2246         }
2247
2248         unregister_chrdev_region(dev, IPATH_NMINORS);
2249 }
2250
2251 static atomic_t user_count = ATOMIC_INIT(0);
2252 static atomic_t user_setup = ATOMIC_INIT(0);
2253
2254 int ipath_user_add(struct ipath_devdata *dd)
2255 {
2256         char name[10];
2257         int ret;
2258
2259         if (atomic_inc_return(&user_count) == 1) {
2260                 ret = user_init();
2261                 if (ret < 0) {
2262                         ipath_dev_err(dd, "Unable to set up user support: "
2263                                       "error %d\n", -ret);
2264                         goto bail;
2265                 }
2266                 ret = init_cdev(0, "ipath", &ipath_file_ops, &wildcard_cdev,
2267                                 &wildcard_class_dev);
2268                 if (ret < 0) {
2269                         ipath_dev_err(dd, "Could not create wildcard "
2270                                       "minor: error %d\n", -ret);
2271                         goto bail_user;
2272                 }
2273
2274                 atomic_set(&user_setup, 1);
2275         }
2276
2277         snprintf(name, sizeof(name), "ipath%d", dd->ipath_unit);
2278
2279         ret = init_cdev(dd->ipath_unit + 1, name, &ipath_file_ops,
2280                         &dd->user_cdev, &dd->user_class_dev);
2281         if (ret < 0)
2282                 ipath_dev_err(dd, "Could not create user minor %d, %s\n",
2283                               dd->ipath_unit + 1, name);
2284
2285         goto bail;
2286
2287 bail_user:
2288         user_cleanup();
2289 bail:
2290         return ret;
2291 }
2292
2293 void ipath_user_remove(struct ipath_devdata *dd)
2294 {
2295         cleanup_cdev(&dd->user_cdev, &dd->user_class_dev);
2296
2297         if (atomic_dec_return(&user_count) == 0) {
2298                 if (atomic_read(&user_setup) == 0)
2299                         goto bail;
2300
2301                 cleanup_cdev(&wildcard_cdev, &wildcard_class_dev);
2302                 user_cleanup();
2303
2304                 atomic_set(&user_setup, 0);
2305         }
2306 bail:
2307         return;
2308 }