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