335796f1f61593ebcb6f037784309d89d8b2dfd9
[cascardo/linux.git] / drivers / infiniband / hw / hfi1 / file_ops.c
1 /*
2  * Copyright(c) 2015, 2016 Intel Corporation.
3  *
4  * This file is provided under a dual BSD/GPLv2 license.  When using or
5  * redistributing this file, you may do so under either license.
6  *
7  * GPL LICENSE SUMMARY
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of version 2 of the GNU General Public License as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * BSD LICENSE
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  *  - Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  *  - Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in
28  *    the documentation and/or other materials provided with the
29  *    distribution.
30  *  - Neither the name of Intel Corporation nor the names of its
31  *    contributors may be used to endorse or promote products derived
32  *    from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
35  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
36  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
37  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
38  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
39  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
41  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
42  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45  *
46  */
47 #include <linux/poll.h>
48 #include <linux/cdev.h>
49 #include <linux/vmalloc.h>
50 #include <linux/io.h>
51
52 #include <rdma/ib.h>
53
54 #include "hfi.h"
55 #include "pio.h"
56 #include "device.h"
57 #include "common.h"
58 #include "trace.h"
59 #include "user_sdma.h"
60 #include "user_exp_rcv.h"
61 #include "eprom.h"
62 #include "aspm.h"
63 #include "mmu_rb.h"
64
65 #undef pr_fmt
66 #define pr_fmt(fmt) DRIVER_NAME ": " fmt
67
68 #define SEND_CTXT_HALT_TIMEOUT 1000 /* msecs */
69
70 /*
71  * File operation functions
72  */
73 static int hfi1_file_open(struct inode *, struct file *);
74 static int hfi1_file_close(struct inode *, struct file *);
75 static ssize_t hfi1_write_iter(struct kiocb *, struct iov_iter *);
76 static unsigned int hfi1_poll(struct file *, struct poll_table_struct *);
77 static int hfi1_file_mmap(struct file *, struct vm_area_struct *);
78
79 static u64 kvirt_to_phys(void *);
80 static int assign_ctxt(struct file *, struct hfi1_user_info *);
81 static int init_subctxts(struct hfi1_ctxtdata *, const struct hfi1_user_info *);
82 static int user_init(struct file *);
83 static int get_ctxt_info(struct file *, void __user *, __u32);
84 static int get_base_info(struct file *, void __user *, __u32);
85 static int setup_ctxt(struct file *);
86 static int setup_subctxt(struct hfi1_ctxtdata *);
87 static int get_user_context(struct file *, struct hfi1_user_info *, int);
88 static int find_shared_ctxt(struct file *, const struct hfi1_user_info *);
89 static int allocate_ctxt(struct file *, struct hfi1_devdata *,
90                          struct hfi1_user_info *);
91 static unsigned int poll_urgent(struct file *, struct poll_table_struct *);
92 static unsigned int poll_next(struct file *, struct poll_table_struct *);
93 static int user_event_ack(struct hfi1_ctxtdata *, int, unsigned long);
94 static int set_ctxt_pkey(struct hfi1_ctxtdata *, unsigned, u16);
95 static int manage_rcvq(struct hfi1_ctxtdata *, unsigned, int);
96 static int vma_fault(struct vm_area_struct *, struct vm_fault *);
97 static long hfi1_file_ioctl(struct file *fp, unsigned int cmd,
98                             unsigned long arg);
99
100 static const struct file_operations hfi1_file_ops = {
101         .owner = THIS_MODULE,
102         .write_iter = hfi1_write_iter,
103         .open = hfi1_file_open,
104         .release = hfi1_file_close,
105         .unlocked_ioctl = hfi1_file_ioctl,
106         .poll = hfi1_poll,
107         .mmap = hfi1_file_mmap,
108         .llseek = noop_llseek,
109 };
110
111 static struct vm_operations_struct vm_ops = {
112         .fault = vma_fault,
113 };
114
115 /*
116  * Types of memories mapped into user processes' space
117  */
118 enum mmap_types {
119         PIO_BUFS = 1,
120         PIO_BUFS_SOP,
121         PIO_CRED,
122         RCV_HDRQ,
123         RCV_EGRBUF,
124         UREGS,
125         EVENTS,
126         STATUS,
127         RTAIL,
128         SUBCTXT_UREGS,
129         SUBCTXT_RCV_HDRQ,
130         SUBCTXT_EGRBUF,
131         SDMA_COMP
132 };
133
134 /*
135  * Masks and offsets defining the mmap tokens
136  */
137 #define HFI1_MMAP_OFFSET_MASK   0xfffULL
138 #define HFI1_MMAP_OFFSET_SHIFT  0
139 #define HFI1_MMAP_SUBCTXT_MASK  0xfULL
140 #define HFI1_MMAP_SUBCTXT_SHIFT 12
141 #define HFI1_MMAP_CTXT_MASK     0xffULL
142 #define HFI1_MMAP_CTXT_SHIFT    16
143 #define HFI1_MMAP_TYPE_MASK     0xfULL
144 #define HFI1_MMAP_TYPE_SHIFT    24
145 #define HFI1_MMAP_MAGIC_MASK    0xffffffffULL
146 #define HFI1_MMAP_MAGIC_SHIFT   32
147
148 #define HFI1_MMAP_MAGIC         0xdabbad00
149
150 #define HFI1_MMAP_TOKEN_SET(field, val) \
151         (((val) & HFI1_MMAP_##field##_MASK) << HFI1_MMAP_##field##_SHIFT)
152 #define HFI1_MMAP_TOKEN_GET(field, token) \
153         (((token) >> HFI1_MMAP_##field##_SHIFT) & HFI1_MMAP_##field##_MASK)
154 #define HFI1_MMAP_TOKEN(type, ctxt, subctxt, addr)   \
155         (HFI1_MMAP_TOKEN_SET(MAGIC, HFI1_MMAP_MAGIC) | \
156         HFI1_MMAP_TOKEN_SET(TYPE, type) | \
157         HFI1_MMAP_TOKEN_SET(CTXT, ctxt) | \
158         HFI1_MMAP_TOKEN_SET(SUBCTXT, subctxt) | \
159         HFI1_MMAP_TOKEN_SET(OFFSET, (offset_in_page(addr))))
160
161 #define dbg(fmt, ...)                           \
162         pr_info(fmt, ##__VA_ARGS__)
163
164 static inline int is_valid_mmap(u64 token)
165 {
166         return (HFI1_MMAP_TOKEN_GET(MAGIC, token) == HFI1_MMAP_MAGIC);
167 }
168
169 static int hfi1_file_open(struct inode *inode, struct file *fp)
170 {
171         struct hfi1_filedata *fd;
172         struct hfi1_devdata *dd = container_of(inode->i_cdev,
173                                                struct hfi1_devdata,
174                                                user_cdev);
175
176         /* Just take a ref now. Not all opens result in a context assign */
177         kobject_get(&dd->kobj);
178
179         /* The real work is performed later in assign_ctxt() */
180
181         fd = kzalloc(sizeof(*fd), GFP_KERNEL);
182
183         if (fd) {
184                 fd->rec_cpu_num = -1; /* no cpu affinity by default */
185                 fd->mm = current->mm;
186                 atomic_inc(&fd->mm->mm_count);
187         }
188
189         fp->private_data = fd;
190
191         return fd ? 0 : -ENOMEM;
192 }
193
194 static long hfi1_file_ioctl(struct file *fp, unsigned int cmd,
195                             unsigned long arg)
196 {
197         struct hfi1_filedata *fd = fp->private_data;
198         struct hfi1_ctxtdata *uctxt = fd->uctxt;
199         struct hfi1_user_info uinfo;
200         struct hfi1_tid_info tinfo;
201         int ret = 0;
202         unsigned long addr;
203         int uval = 0;
204         unsigned long ul_uval = 0;
205         u16 uval16 = 0;
206
207         hfi1_cdbg(IOCTL, "IOCTL recv: 0x%x", cmd);
208         if (cmd != HFI1_IOCTL_ASSIGN_CTXT &&
209             cmd != HFI1_IOCTL_GET_VERS &&
210             !uctxt)
211                 return -EINVAL;
212
213         switch (cmd) {
214         case HFI1_IOCTL_ASSIGN_CTXT:
215                 if (uctxt)
216                         return -EINVAL;
217
218                 if (copy_from_user(&uinfo,
219                                    (struct hfi1_user_info __user *)arg,
220                                    sizeof(uinfo)))
221                         return -EFAULT;
222
223                 ret = assign_ctxt(fp, &uinfo);
224                 if (ret < 0)
225                         return ret;
226                 ret = setup_ctxt(fp);
227                 if (ret)
228                         return ret;
229                 ret = user_init(fp);
230                 break;
231         case HFI1_IOCTL_CTXT_INFO:
232                 ret = get_ctxt_info(fp, (void __user *)(unsigned long)arg,
233                                     sizeof(struct hfi1_ctxt_info));
234                 break;
235         case HFI1_IOCTL_USER_INFO:
236                 ret = get_base_info(fp, (void __user *)(unsigned long)arg,
237                                     sizeof(struct hfi1_base_info));
238                 break;
239         case HFI1_IOCTL_CREDIT_UPD:
240                 if (uctxt)
241                         sc_return_credits(uctxt->sc);
242                 break;
243
244         case HFI1_IOCTL_TID_UPDATE:
245                 if (copy_from_user(&tinfo,
246                                    (struct hfi11_tid_info __user *)arg,
247                                    sizeof(tinfo)))
248                         return -EFAULT;
249
250                 ret = hfi1_user_exp_rcv_setup(fp, &tinfo);
251                 if (!ret) {
252                         /*
253                          * Copy the number of tidlist entries we used
254                          * and the length of the buffer we registered.
255                          * These fields are adjacent in the structure so
256                          * we can copy them at the same time.
257                          */
258                         addr = arg + offsetof(struct hfi1_tid_info, tidcnt);
259                         if (copy_to_user((void __user *)addr, &tinfo.tidcnt,
260                                          sizeof(tinfo.tidcnt) +
261                                          sizeof(tinfo.length)))
262                                 ret = -EFAULT;
263                 }
264                 break;
265
266         case HFI1_IOCTL_TID_FREE:
267                 if (copy_from_user(&tinfo,
268                                    (struct hfi11_tid_info __user *)arg,
269                                    sizeof(tinfo)))
270                         return -EFAULT;
271
272                 ret = hfi1_user_exp_rcv_clear(fp, &tinfo);
273                 if (ret)
274                         break;
275                 addr = arg + offsetof(struct hfi1_tid_info, tidcnt);
276                 if (copy_to_user((void __user *)addr, &tinfo.tidcnt,
277                                  sizeof(tinfo.tidcnt)))
278                         ret = -EFAULT;
279                 break;
280
281         case HFI1_IOCTL_TID_INVAL_READ:
282                 if (copy_from_user(&tinfo,
283                                    (struct hfi11_tid_info __user *)arg,
284                                    sizeof(tinfo)))
285                         return -EFAULT;
286
287                 ret = hfi1_user_exp_rcv_invalid(fp, &tinfo);
288                 if (ret)
289                         break;
290                 addr = arg + offsetof(struct hfi1_tid_info, tidcnt);
291                 if (copy_to_user((void __user *)addr, &tinfo.tidcnt,
292                                  sizeof(tinfo.tidcnt)))
293                         ret = -EFAULT;
294                 break;
295
296         case HFI1_IOCTL_RECV_CTRL:
297                 ret = get_user(uval, (int __user *)arg);
298                 if (ret != 0)
299                         return -EFAULT;
300                 ret = manage_rcvq(uctxt, fd->subctxt, uval);
301                 break;
302
303         case HFI1_IOCTL_POLL_TYPE:
304                 ret = get_user(uval, (int __user *)arg);
305                 if (ret != 0)
306                         return -EFAULT;
307                 uctxt->poll_type = (typeof(uctxt->poll_type))uval;
308                 break;
309
310         case HFI1_IOCTL_ACK_EVENT:
311                 ret = get_user(ul_uval, (unsigned long __user *)arg);
312                 if (ret != 0)
313                         return -EFAULT;
314                 ret = user_event_ack(uctxt, fd->subctxt, ul_uval);
315                 break;
316
317         case HFI1_IOCTL_SET_PKEY:
318                 ret = get_user(uval16, (u16 __user *)arg);
319                 if (ret != 0)
320                         return -EFAULT;
321                 if (HFI1_CAP_IS_USET(PKEY_CHECK))
322                         ret = set_ctxt_pkey(uctxt, fd->subctxt, uval16);
323                 else
324                         return -EPERM;
325                 break;
326
327         case HFI1_IOCTL_CTXT_RESET: {
328                 struct send_context *sc;
329                 struct hfi1_devdata *dd;
330
331                 if (!uctxt || !uctxt->dd || !uctxt->sc)
332                         return -EINVAL;
333
334                 /*
335                  * There is no protection here. User level has to
336                  * guarantee that no one will be writing to the send
337                  * context while it is being re-initialized.
338                  * If user level breaks that guarantee, it will break
339                  * it's own context and no one else's.
340                  */
341                 dd = uctxt->dd;
342                 sc = uctxt->sc;
343                 /*
344                  * Wait until the interrupt handler has marked the
345                  * context as halted or frozen. Report error if we time
346                  * out.
347                  */
348                 wait_event_interruptible_timeout(
349                         sc->halt_wait, (sc->flags & SCF_HALTED),
350                         msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT));
351                 if (!(sc->flags & SCF_HALTED))
352                         return -ENOLCK;
353
354                 /*
355                  * If the send context was halted due to a Freeze,
356                  * wait until the device has been "unfrozen" before
357                  * resetting the context.
358                  */
359                 if (sc->flags & SCF_FROZEN) {
360                         wait_event_interruptible_timeout(
361                                 dd->event_queue,
362                                 !(ACCESS_ONCE(dd->flags) & HFI1_FROZEN),
363                                 msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT));
364                         if (dd->flags & HFI1_FROZEN)
365                                 return -ENOLCK;
366
367                         if (dd->flags & HFI1_FORCED_FREEZE)
368                                 /*
369                                  * Don't allow context reset if we are into
370                                  * forced freeze
371                                  */
372                                 return -ENODEV;
373
374                         sc_disable(sc);
375                         ret = sc_enable(sc);
376                         hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_ENB,
377                                      uctxt->ctxt);
378                 } else {
379                         ret = sc_restart(sc);
380                 }
381                 if (!ret)
382                         sc_return_credits(sc);
383                 break;
384         }
385
386         case HFI1_IOCTL_GET_VERS:
387                 uval = HFI1_USER_SWVERSION;
388                 if (put_user(uval, (int __user *)arg))
389                         return -EFAULT;
390                 break;
391
392         default:
393                 return -EINVAL;
394         }
395
396         return ret;
397 }
398
399 static ssize_t hfi1_write_iter(struct kiocb *kiocb, struct iov_iter *from)
400 {
401         struct hfi1_filedata *fd = kiocb->ki_filp->private_data;
402         struct hfi1_user_sdma_pkt_q *pq = fd->pq;
403         struct hfi1_user_sdma_comp_q *cq = fd->cq;
404         int done = 0, reqs = 0;
405         unsigned long dim = from->nr_segs;
406
407         if (!cq || !pq)
408                 return -EIO;
409
410         if (!iter_is_iovec(from) || !dim)
411                 return -EINVAL;
412
413         hfi1_cdbg(SDMA, "SDMA request from %u:%u (%lu)",
414                   fd->uctxt->ctxt, fd->subctxt, dim);
415
416         if (atomic_read(&pq->n_reqs) == pq->n_max_reqs)
417                 return -ENOSPC;
418
419         while (dim) {
420                 int ret;
421                 unsigned long count = 0;
422
423                 ret = hfi1_user_sdma_process_request(
424                         kiocb->ki_filp, (struct iovec *)(from->iov + done),
425                         dim, &count);
426                 if (ret) {
427                         reqs = ret;
428                         break;
429                 }
430                 dim -= count;
431                 done += count;
432                 reqs++;
433         }
434
435         return reqs;
436 }
437
438 static int hfi1_file_mmap(struct file *fp, struct vm_area_struct *vma)
439 {
440         struct hfi1_filedata *fd = fp->private_data;
441         struct hfi1_ctxtdata *uctxt = fd->uctxt;
442         struct hfi1_devdata *dd;
443         unsigned long flags;
444         u64 token = vma->vm_pgoff << PAGE_SHIFT,
445                 memaddr = 0;
446         void *memvirt = NULL;
447         u8 subctxt, mapio = 0, vmf = 0, type;
448         ssize_t memlen = 0;
449         int ret = 0;
450         u16 ctxt;
451
452         if (!is_valid_mmap(token) || !uctxt ||
453             !(vma->vm_flags & VM_SHARED)) {
454                 ret = -EINVAL;
455                 goto done;
456         }
457         dd = uctxt->dd;
458         ctxt = HFI1_MMAP_TOKEN_GET(CTXT, token);
459         subctxt = HFI1_MMAP_TOKEN_GET(SUBCTXT, token);
460         type = HFI1_MMAP_TOKEN_GET(TYPE, token);
461         if (ctxt != uctxt->ctxt || subctxt != fd->subctxt) {
462                 ret = -EINVAL;
463                 goto done;
464         }
465
466         flags = vma->vm_flags;
467
468         switch (type) {
469         case PIO_BUFS:
470         case PIO_BUFS_SOP:
471                 memaddr = ((dd->physaddr + TXE_PIO_SEND) +
472                                 /* chip pio base */
473                            (uctxt->sc->hw_context * BIT(16))) +
474                                 /* 64K PIO space / ctxt */
475                         (type == PIO_BUFS_SOP ?
476                                 (TXE_PIO_SIZE / 2) : 0); /* sop? */
477                 /*
478                  * Map only the amount allocated to the context, not the
479                  * entire available context's PIO space.
480                  */
481                 memlen = PAGE_ALIGN(uctxt->sc->credits * PIO_BLOCK_SIZE);
482                 flags &= ~VM_MAYREAD;
483                 flags |= VM_DONTCOPY | VM_DONTEXPAND;
484                 vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
485                 mapio = 1;
486                 break;
487         case PIO_CRED:
488                 if (flags & VM_WRITE) {
489                         ret = -EPERM;
490                         goto done;
491                 }
492                 /*
493                  * The credit return location for this context could be on the
494                  * second or third page allocated for credit returns (if number
495                  * of enabled contexts > 64 and 128 respectively).
496                  */
497                 memvirt = dd->cr_base[uctxt->numa_id].va;
498                 memaddr = virt_to_phys(memvirt) +
499                         (((u64)uctxt->sc->hw_free -
500                           (u64)dd->cr_base[uctxt->numa_id].va) & PAGE_MASK);
501                 memlen = PAGE_SIZE;
502                 flags &= ~VM_MAYWRITE;
503                 flags |= VM_DONTCOPY | VM_DONTEXPAND;
504                 /*
505                  * The driver has already allocated memory for credit
506                  * returns and programmed it into the chip. Has that
507                  * memory been flagged as non-cached?
508                  */
509                 /* vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); */
510                 mapio = 1;
511                 break;
512         case RCV_HDRQ:
513                 memlen = uctxt->rcvhdrq_size;
514                 memvirt = uctxt->rcvhdrq;
515                 break;
516         case RCV_EGRBUF: {
517                 unsigned long addr;
518                 int i;
519                 /*
520                  * The RcvEgr buffer need to be handled differently
521                  * as multiple non-contiguous pages need to be mapped
522                  * into the user process.
523                  */
524                 memlen = uctxt->egrbufs.size;
525                 if ((vma->vm_end - vma->vm_start) != memlen) {
526                         dd_dev_err(dd, "Eager buffer map size invalid (%lu != %lu)\n",
527                                    (vma->vm_end - vma->vm_start), memlen);
528                         ret = -EINVAL;
529                         goto done;
530                 }
531                 if (vma->vm_flags & VM_WRITE) {
532                         ret = -EPERM;
533                         goto done;
534                 }
535                 vma->vm_flags &= ~VM_MAYWRITE;
536                 addr = vma->vm_start;
537                 for (i = 0 ; i < uctxt->egrbufs.numbufs; i++) {
538                         memlen = uctxt->egrbufs.buffers[i].len;
539                         memvirt = uctxt->egrbufs.buffers[i].addr;
540                         ret = remap_pfn_range(
541                                 vma, addr,
542                                 /*
543                                  * virt_to_pfn() does the same, but
544                                  * it's not available on x86_64
545                                  * when CONFIG_MMU is enabled.
546                                  */
547                                 PFN_DOWN(__pa(memvirt)),
548                                 memlen,
549                                 vma->vm_page_prot);
550                         if (ret < 0)
551                                 goto done;
552                         addr += memlen;
553                 }
554                 ret = 0;
555                 goto done;
556         }
557         case UREGS:
558                 /*
559                  * Map only the page that contains this context's user
560                  * registers.
561                  */
562                 memaddr = (unsigned long)
563                         (dd->physaddr + RXE_PER_CONTEXT_USER)
564                         + (uctxt->ctxt * RXE_PER_CONTEXT_SIZE);
565                 /*
566                  * TidFlow table is on the same page as the rest of the
567                  * user registers.
568                  */
569                 memlen = PAGE_SIZE;
570                 flags |= VM_DONTCOPY | VM_DONTEXPAND;
571                 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
572                 mapio = 1;
573                 break;
574         case EVENTS:
575                 /*
576                  * Use the page where this context's flags are. User level
577                  * knows where it's own bitmap is within the page.
578                  */
579                 memaddr = (unsigned long)(dd->events +
580                                           ((uctxt->ctxt - dd->first_user_ctxt) *
581                                            HFI1_MAX_SHARED_CTXTS)) & PAGE_MASK;
582                 memlen = PAGE_SIZE;
583                 /*
584                  * v3.7 removes VM_RESERVED but the effect is kept by
585                  * using VM_IO.
586                  */
587                 flags |= VM_IO | VM_DONTEXPAND;
588                 vmf = 1;
589                 break;
590         case STATUS:
591                 memaddr = kvirt_to_phys((void *)dd->status);
592                 memlen = PAGE_SIZE;
593                 flags |= VM_IO | VM_DONTEXPAND;
594                 break;
595         case RTAIL:
596                 if (!HFI1_CAP_IS_USET(DMA_RTAIL)) {
597                         /*
598                          * If the memory allocation failed, the context alloc
599                          * also would have failed, so we would never get here
600                          */
601                         ret = -EINVAL;
602                         goto done;
603                 }
604                 if (flags & VM_WRITE) {
605                         ret = -EPERM;
606                         goto done;
607                 }
608                 memlen = PAGE_SIZE;
609                 memvirt = (void *)uctxt->rcvhdrtail_kvaddr;
610                 flags &= ~VM_MAYWRITE;
611                 break;
612         case SUBCTXT_UREGS:
613                 memaddr = (u64)uctxt->subctxt_uregbase;
614                 memlen = PAGE_SIZE;
615                 flags |= VM_IO | VM_DONTEXPAND;
616                 vmf = 1;
617                 break;
618         case SUBCTXT_RCV_HDRQ:
619                 memaddr = (u64)uctxt->subctxt_rcvhdr_base;
620                 memlen = uctxt->rcvhdrq_size * uctxt->subctxt_cnt;
621                 flags |= VM_IO | VM_DONTEXPAND;
622                 vmf = 1;
623                 break;
624         case SUBCTXT_EGRBUF:
625                 memaddr = (u64)uctxt->subctxt_rcvegrbuf;
626                 memlen = uctxt->egrbufs.size * uctxt->subctxt_cnt;
627                 flags |= VM_IO | VM_DONTEXPAND;
628                 flags &= ~VM_MAYWRITE;
629                 vmf = 1;
630                 break;
631         case SDMA_COMP: {
632                 struct hfi1_user_sdma_comp_q *cq = fd->cq;
633
634                 if (!cq) {
635                         ret = -EFAULT;
636                         goto done;
637                 }
638                 memaddr = (u64)cq->comps;
639                 memlen = PAGE_ALIGN(sizeof(*cq->comps) * cq->nentries);
640                 flags |= VM_IO | VM_DONTEXPAND;
641                 vmf = 1;
642                 break;
643         }
644         default:
645                 ret = -EINVAL;
646                 break;
647         }
648
649         if ((vma->vm_end - vma->vm_start) != memlen) {
650                 hfi1_cdbg(PROC, "%u:%u Memory size mismatch %lu:%lu",
651                           uctxt->ctxt, fd->subctxt,
652                           (vma->vm_end - vma->vm_start), memlen);
653                 ret = -EINVAL;
654                 goto done;
655         }
656
657         vma->vm_flags = flags;
658         hfi1_cdbg(PROC,
659                   "%u:%u type:%u io/vf:%d/%d, addr:0x%llx, len:%lu(%lu), flags:0x%lx\n",
660                     ctxt, subctxt, type, mapio, vmf, memaddr, memlen,
661                     vma->vm_end - vma->vm_start, vma->vm_flags);
662         if (vmf) {
663                 vma->vm_pgoff = PFN_DOWN(memaddr);
664                 vma->vm_ops = &vm_ops;
665                 ret = 0;
666         } else if (mapio) {
667                 ret = io_remap_pfn_range(vma, vma->vm_start,
668                                          PFN_DOWN(memaddr),
669                                          memlen,
670                                          vma->vm_page_prot);
671         } else if (memvirt) {
672                 ret = remap_pfn_range(vma, vma->vm_start,
673                                       PFN_DOWN(__pa(memvirt)),
674                                       memlen,
675                                       vma->vm_page_prot);
676         } else {
677                 ret = remap_pfn_range(vma, vma->vm_start,
678                                       PFN_DOWN(memaddr),
679                                       memlen,
680                                       vma->vm_page_prot);
681         }
682 done:
683         return ret;
684 }
685
686 /*
687  * Local (non-chip) user memory is not mapped right away but as it is
688  * accessed by the user-level code.
689  */
690 static int vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
691 {
692         struct page *page;
693
694         page = vmalloc_to_page((void *)(vmf->pgoff << PAGE_SHIFT));
695         if (!page)
696                 return VM_FAULT_SIGBUS;
697
698         get_page(page);
699         vmf->page = page;
700
701         return 0;
702 }
703
704 static unsigned int hfi1_poll(struct file *fp, struct poll_table_struct *pt)
705 {
706         struct hfi1_ctxtdata *uctxt;
707         unsigned pollflag;
708
709         uctxt = ((struct hfi1_filedata *)fp->private_data)->uctxt;
710         if (!uctxt)
711                 pollflag = POLLERR;
712         else if (uctxt->poll_type == HFI1_POLL_TYPE_URGENT)
713                 pollflag = poll_urgent(fp, pt);
714         else  if (uctxt->poll_type == HFI1_POLL_TYPE_ANYRCV)
715                 pollflag = poll_next(fp, pt);
716         else /* invalid */
717                 pollflag = POLLERR;
718
719         return pollflag;
720 }
721
722 static int hfi1_file_close(struct inode *inode, struct file *fp)
723 {
724         struct hfi1_filedata *fdata = fp->private_data;
725         struct hfi1_ctxtdata *uctxt = fdata->uctxt;
726         struct hfi1_devdata *dd = container_of(inode->i_cdev,
727                                                struct hfi1_devdata,
728                                                user_cdev);
729         unsigned long flags, *ev;
730
731         fp->private_data = NULL;
732
733         if (!uctxt)
734                 goto done;
735
736         hfi1_cdbg(PROC, "freeing ctxt %u:%u", uctxt->ctxt, fdata->subctxt);
737         mutex_lock(&hfi1_mutex);
738
739         flush_wc();
740         /* drain user sdma queue */
741         hfi1_user_sdma_free_queues(fdata);
742
743         /* release the cpu */
744         hfi1_put_proc_affinity(fdata->rec_cpu_num);
745
746         /*
747          * Clear any left over, unhandled events so the next process that
748          * gets this context doesn't get confused.
749          */
750         ev = dd->events + ((uctxt->ctxt - dd->first_user_ctxt) *
751                            HFI1_MAX_SHARED_CTXTS) + fdata->subctxt;
752         *ev = 0;
753
754         if (--uctxt->cnt) {
755                 uctxt->active_slaves &= ~(1 << fdata->subctxt);
756                 mutex_unlock(&hfi1_mutex);
757                 goto done;
758         }
759
760         spin_lock_irqsave(&dd->uctxt_lock, flags);
761         /*
762          * Disable receive context and interrupt available, reset all
763          * RcvCtxtCtrl bits to default values.
764          */
765         hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_DIS |
766                      HFI1_RCVCTRL_TIDFLOW_DIS |
767                      HFI1_RCVCTRL_INTRAVAIL_DIS |
768                      HFI1_RCVCTRL_TAILUPD_DIS |
769                      HFI1_RCVCTRL_ONE_PKT_EGR_DIS |
770                      HFI1_RCVCTRL_NO_RHQ_DROP_DIS |
771                      HFI1_RCVCTRL_NO_EGR_DROP_DIS, uctxt->ctxt);
772         /* Clear the context's J_KEY */
773         hfi1_clear_ctxt_jkey(dd, uctxt->ctxt);
774         /*
775          * Reset context integrity checks to default.
776          * (writes to CSRs probably belong in chip.c)
777          */
778         write_kctxt_csr(dd, uctxt->sc->hw_context, SEND_CTXT_CHECK_ENABLE,
779                         hfi1_pkt_default_send_ctxt_mask(dd, uctxt->sc->type));
780         sc_disable(uctxt->sc);
781         spin_unlock_irqrestore(&dd->uctxt_lock, flags);
782
783         dd->rcd[uctxt->ctxt] = NULL;
784
785         hfi1_user_exp_rcv_free(fdata);
786         hfi1_clear_ctxt_pkey(dd, uctxt->ctxt);
787
788         uctxt->rcvwait_to = 0;
789         uctxt->piowait_to = 0;
790         uctxt->rcvnowait = 0;
791         uctxt->pionowait = 0;
792         uctxt->event_flags = 0;
793
794         hfi1_stats.sps_ctxts--;
795         if (++dd->freectxts == dd->num_user_contexts)
796                 aspm_enable_all(dd);
797         mutex_unlock(&hfi1_mutex);
798         hfi1_free_ctxtdata(dd, uctxt);
799 done:
800         mmdrop(fdata->mm);
801         kobject_put(&dd->kobj);
802         kfree(fdata);
803         return 0;
804 }
805
806 /*
807  * Convert kernel *virtual* addresses to physical addresses.
808  * This is used to vmalloc'ed addresses.
809  */
810 static u64 kvirt_to_phys(void *addr)
811 {
812         struct page *page;
813         u64 paddr = 0;
814
815         page = vmalloc_to_page(addr);
816         if (page)
817                 paddr = page_to_pfn(page) << PAGE_SHIFT;
818
819         return paddr;
820 }
821
822 static int assign_ctxt(struct file *fp, struct hfi1_user_info *uinfo)
823 {
824         int i_minor, ret = 0;
825         unsigned int swmajor, swminor;
826
827         swmajor = uinfo->userversion >> 16;
828         if (swmajor != HFI1_USER_SWMAJOR) {
829                 ret = -ENODEV;
830                 goto done;
831         }
832
833         swminor = uinfo->userversion & 0xffff;
834
835         mutex_lock(&hfi1_mutex);
836         /* First, lets check if we need to setup a shared context? */
837         if (uinfo->subctxt_cnt) {
838                 struct hfi1_filedata *fd = fp->private_data;
839
840                 ret = find_shared_ctxt(fp, uinfo);
841                 if (ret < 0)
842                         goto done_unlock;
843                 if (ret) {
844                         fd->rec_cpu_num =
845                                 hfi1_get_proc_affinity(fd->uctxt->numa_id);
846                 }
847         }
848
849         /*
850          * We execute the following block if we couldn't find a
851          * shared context or if context sharing is not required.
852          */
853         if (!ret) {
854                 i_minor = iminor(file_inode(fp)) - HFI1_USER_MINOR_BASE;
855                 ret = get_user_context(fp, uinfo, i_minor);
856         }
857 done_unlock:
858         mutex_unlock(&hfi1_mutex);
859 done:
860         return ret;
861 }
862
863 static int get_user_context(struct file *fp, struct hfi1_user_info *uinfo,
864                             int devno)
865 {
866         struct hfi1_devdata *dd = NULL;
867         int devmax, npresent, nup;
868
869         devmax = hfi1_count_units(&npresent, &nup);
870         if (!npresent)
871                 return -ENXIO;
872
873         if (!nup)
874                 return -ENETDOWN;
875
876         dd = hfi1_lookup(devno);
877         if (!dd)
878                 return -ENODEV;
879         else if (!dd->freectxts)
880                 return -EBUSY;
881
882         return allocate_ctxt(fp, dd, uinfo);
883 }
884
885 static int find_shared_ctxt(struct file *fp,
886                             const struct hfi1_user_info *uinfo)
887 {
888         int devmax, ndev, i;
889         int ret = 0;
890         struct hfi1_filedata *fd = fp->private_data;
891
892         devmax = hfi1_count_units(NULL, NULL);
893
894         for (ndev = 0; ndev < devmax; ndev++) {
895                 struct hfi1_devdata *dd = hfi1_lookup(ndev);
896
897                 if (!(dd && (dd->flags & HFI1_PRESENT) && dd->kregbase))
898                         continue;
899                 for (i = dd->first_user_ctxt; i < dd->num_rcv_contexts; i++) {
900                         struct hfi1_ctxtdata *uctxt = dd->rcd[i];
901
902                         /* Skip ctxts which are not yet open */
903                         if (!uctxt || !uctxt->cnt)
904                                 continue;
905                         /* Skip ctxt if it doesn't match the requested one */
906                         if (memcmp(uctxt->uuid, uinfo->uuid,
907                                    sizeof(uctxt->uuid)) ||
908                             uctxt->jkey != generate_jkey(current_uid()) ||
909                             uctxt->subctxt_id != uinfo->subctxt_id ||
910                             uctxt->subctxt_cnt != uinfo->subctxt_cnt)
911                                 continue;
912
913                         /* Verify the sharing process matches the master */
914                         if (uctxt->userversion != uinfo->userversion ||
915                             uctxt->cnt >= uctxt->subctxt_cnt) {
916                                 ret = -EINVAL;
917                                 goto done;
918                         }
919                         fd->uctxt = uctxt;
920                         fd->subctxt  = uctxt->cnt++;
921                         uctxt->active_slaves |= 1 << fd->subctxt;
922                         ret = 1;
923                         goto done;
924                 }
925         }
926
927 done:
928         return ret;
929 }
930
931 static int allocate_ctxt(struct file *fp, struct hfi1_devdata *dd,
932                          struct hfi1_user_info *uinfo)
933 {
934         struct hfi1_filedata *fd = fp->private_data;
935         struct hfi1_ctxtdata *uctxt;
936         unsigned ctxt;
937         int ret, numa;
938
939         if (dd->flags & HFI1_FROZEN) {
940                 /*
941                  * Pick an error that is unique from all other errors
942                  * that are returned so the user process knows that
943                  * it tried to allocate while the SPC was frozen.  It
944                  * it should be able to retry with success in a short
945                  * while.
946                  */
947                 return -EIO;
948         }
949
950         for (ctxt = dd->first_user_ctxt; ctxt < dd->num_rcv_contexts; ctxt++)
951                 if (!dd->rcd[ctxt])
952                         break;
953
954         if (ctxt == dd->num_rcv_contexts)
955                 return -EBUSY;
956
957         /*
958          * If we don't have a NUMA node requested, preference is towards
959          * device NUMA node.
960          */
961         fd->rec_cpu_num = hfi1_get_proc_affinity(dd->node);
962         if (fd->rec_cpu_num != -1)
963                 numa = cpu_to_node(fd->rec_cpu_num);
964         else
965                 numa = numa_node_id();
966         uctxt = hfi1_create_ctxtdata(dd->pport, ctxt, numa);
967         if (!uctxt) {
968                 dd_dev_err(dd,
969                            "Unable to allocate ctxtdata memory, failing open\n");
970                 return -ENOMEM;
971         }
972         hfi1_cdbg(PROC, "[%u:%u] pid %u assigned to CPU %d (NUMA %u)",
973                   uctxt->ctxt, fd->subctxt, current->pid, fd->rec_cpu_num,
974                   uctxt->numa_id);
975
976         /*
977          * Allocate and enable a PIO send context.
978          */
979         uctxt->sc = sc_alloc(dd, SC_USER, uctxt->rcvhdrqentsize,
980                              uctxt->dd->node);
981         if (!uctxt->sc)
982                 return -ENOMEM;
983
984         hfi1_cdbg(PROC, "allocated send context %u(%u)\n", uctxt->sc->sw_index,
985                   uctxt->sc->hw_context);
986         ret = sc_enable(uctxt->sc);
987         if (ret)
988                 return ret;
989         /*
990          * Setup shared context resources if the user-level has requested
991          * shared contexts and this is the 'master' process.
992          * This has to be done here so the rest of the sub-contexts find the
993          * proper master.
994          */
995         if (uinfo->subctxt_cnt && !fd->subctxt) {
996                 ret = init_subctxts(uctxt, uinfo);
997                 /*
998                  * On error, we don't need to disable and de-allocate the
999                  * send context because it will be done during file close
1000                  */
1001                 if (ret)
1002                         return ret;
1003         }
1004         uctxt->userversion = uinfo->userversion;
1005         uctxt->flags = hfi1_cap_mask; /* save current flag state */
1006         init_waitqueue_head(&uctxt->wait);
1007         strlcpy(uctxt->comm, current->comm, sizeof(uctxt->comm));
1008         memcpy(uctxt->uuid, uinfo->uuid, sizeof(uctxt->uuid));
1009         uctxt->jkey = generate_jkey(current_uid());
1010         INIT_LIST_HEAD(&uctxt->sdma_queues);
1011         spin_lock_init(&uctxt->sdma_qlock);
1012         hfi1_stats.sps_ctxts++;
1013         /*
1014          * Disable ASPM when there are open user/PSM contexts to avoid
1015          * issues with ASPM L1 exit latency
1016          */
1017         if (dd->freectxts-- == dd->num_user_contexts)
1018                 aspm_disable_all(dd);
1019         fd->uctxt = uctxt;
1020
1021         return 0;
1022 }
1023
1024 static int init_subctxts(struct hfi1_ctxtdata *uctxt,
1025                          const struct hfi1_user_info *uinfo)
1026 {
1027         unsigned num_subctxts;
1028
1029         num_subctxts = uinfo->subctxt_cnt;
1030         if (num_subctxts > HFI1_MAX_SHARED_CTXTS)
1031                 return -EINVAL;
1032
1033         uctxt->subctxt_cnt = uinfo->subctxt_cnt;
1034         uctxt->subctxt_id = uinfo->subctxt_id;
1035         uctxt->active_slaves = 1;
1036         uctxt->redirect_seq_cnt = 1;
1037         set_bit(HFI1_CTXT_MASTER_UNINIT, &uctxt->event_flags);
1038
1039         return 0;
1040 }
1041
1042 static int setup_subctxt(struct hfi1_ctxtdata *uctxt)
1043 {
1044         int ret = 0;
1045         unsigned num_subctxts = uctxt->subctxt_cnt;
1046
1047         uctxt->subctxt_uregbase = vmalloc_user(PAGE_SIZE);
1048         if (!uctxt->subctxt_uregbase) {
1049                 ret = -ENOMEM;
1050                 goto bail;
1051         }
1052         /* We can take the size of the RcvHdr Queue from the master */
1053         uctxt->subctxt_rcvhdr_base = vmalloc_user(uctxt->rcvhdrq_size *
1054                                                   num_subctxts);
1055         if (!uctxt->subctxt_rcvhdr_base) {
1056                 ret = -ENOMEM;
1057                 goto bail_ureg;
1058         }
1059
1060         uctxt->subctxt_rcvegrbuf = vmalloc_user(uctxt->egrbufs.size *
1061                                                 num_subctxts);
1062         if (!uctxt->subctxt_rcvegrbuf) {
1063                 ret = -ENOMEM;
1064                 goto bail_rhdr;
1065         }
1066         goto bail;
1067 bail_rhdr:
1068         vfree(uctxt->subctxt_rcvhdr_base);
1069 bail_ureg:
1070         vfree(uctxt->subctxt_uregbase);
1071         uctxt->subctxt_uregbase = NULL;
1072 bail:
1073         return ret;
1074 }
1075
1076 static int user_init(struct file *fp)
1077 {
1078         unsigned int rcvctrl_ops = 0;
1079         struct hfi1_filedata *fd = fp->private_data;
1080         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1081
1082         /* make sure that the context has already been setup */
1083         if (!test_bit(HFI1_CTXT_SETUP_DONE, &uctxt->event_flags))
1084                 return -EFAULT;
1085
1086         /* initialize poll variables... */
1087         uctxt->urgent = 0;
1088         uctxt->urgent_poll = 0;
1089
1090         /*
1091          * Now enable the ctxt for receive.
1092          * For chips that are set to DMA the tail register to memory
1093          * when they change (and when the update bit transitions from
1094          * 0 to 1.  So for those chips, we turn it off and then back on.
1095          * This will (very briefly) affect any other open ctxts, but the
1096          * duration is very short, and therefore isn't an issue.  We
1097          * explicitly set the in-memory tail copy to 0 beforehand, so we
1098          * don't have to wait to be sure the DMA update has happened
1099          * (chip resets head/tail to 0 on transition to enable).
1100          */
1101         if (uctxt->rcvhdrtail_kvaddr)
1102                 clear_rcvhdrtail(uctxt);
1103
1104         /* Setup J_KEY before enabling the context */
1105         hfi1_set_ctxt_jkey(uctxt->dd, uctxt->ctxt, uctxt->jkey);
1106
1107         rcvctrl_ops = HFI1_RCVCTRL_CTXT_ENB;
1108         if (HFI1_CAP_UGET_MASK(uctxt->flags, HDRSUPP))
1109                 rcvctrl_ops |= HFI1_RCVCTRL_TIDFLOW_ENB;
1110         /*
1111          * Ignore the bit in the flags for now until proper
1112          * support for multiple packet per rcv array entry is
1113          * added.
1114          */
1115         if (!HFI1_CAP_UGET_MASK(uctxt->flags, MULTI_PKT_EGR))
1116                 rcvctrl_ops |= HFI1_RCVCTRL_ONE_PKT_EGR_ENB;
1117         if (HFI1_CAP_UGET_MASK(uctxt->flags, NODROP_EGR_FULL))
1118                 rcvctrl_ops |= HFI1_RCVCTRL_NO_EGR_DROP_ENB;
1119         if (HFI1_CAP_UGET_MASK(uctxt->flags, NODROP_RHQ_FULL))
1120                 rcvctrl_ops |= HFI1_RCVCTRL_NO_RHQ_DROP_ENB;
1121         /*
1122          * The RcvCtxtCtrl.TailUpd bit has to be explicitly written.
1123          * We can't rely on the correct value to be set from prior
1124          * uses of the chip or ctxt. Therefore, add the rcvctrl op
1125          * for both cases.
1126          */
1127         if (HFI1_CAP_UGET_MASK(uctxt->flags, DMA_RTAIL))
1128                 rcvctrl_ops |= HFI1_RCVCTRL_TAILUPD_ENB;
1129         else
1130                 rcvctrl_ops |= HFI1_RCVCTRL_TAILUPD_DIS;
1131         hfi1_rcvctrl(uctxt->dd, rcvctrl_ops, uctxt->ctxt);
1132
1133         /* Notify any waiting slaves */
1134         if (uctxt->subctxt_cnt) {
1135                 clear_bit(HFI1_CTXT_MASTER_UNINIT, &uctxt->event_flags);
1136                 wake_up(&uctxt->wait);
1137         }
1138
1139         return 0;
1140 }
1141
1142 static int get_ctxt_info(struct file *fp, void __user *ubase, __u32 len)
1143 {
1144         struct hfi1_ctxt_info cinfo;
1145         struct hfi1_filedata *fd = fp->private_data;
1146         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1147         int ret = 0;
1148
1149         memset(&cinfo, 0, sizeof(cinfo));
1150         cinfo.runtime_flags = (((uctxt->flags >> HFI1_CAP_MISC_SHIFT) &
1151                                 HFI1_CAP_MISC_MASK) << HFI1_CAP_USER_SHIFT) |
1152                         HFI1_CAP_UGET_MASK(uctxt->flags, MASK) |
1153                         HFI1_CAP_KGET_MASK(uctxt->flags, K2U);
1154         /* adjust flag if this fd is not able to cache */
1155         if (!fd->handler)
1156                 cinfo.runtime_flags |= HFI1_CAP_TID_UNMAP; /* no caching */
1157
1158         cinfo.num_active = hfi1_count_active_units();
1159         cinfo.unit = uctxt->dd->unit;
1160         cinfo.ctxt = uctxt->ctxt;
1161         cinfo.subctxt = fd->subctxt;
1162         cinfo.rcvtids = roundup(uctxt->egrbufs.alloced,
1163                                 uctxt->dd->rcv_entries.group_size) +
1164                 uctxt->expected_count;
1165         cinfo.credits = uctxt->sc->credits;
1166         cinfo.numa_node = uctxt->numa_id;
1167         cinfo.rec_cpu = fd->rec_cpu_num;
1168         cinfo.send_ctxt = uctxt->sc->hw_context;
1169
1170         cinfo.egrtids = uctxt->egrbufs.alloced;
1171         cinfo.rcvhdrq_cnt = uctxt->rcvhdrq_cnt;
1172         cinfo.rcvhdrq_entsize = uctxt->rcvhdrqentsize << 2;
1173         cinfo.sdma_ring_size = fd->cq->nentries;
1174         cinfo.rcvegr_size = uctxt->egrbufs.rcvtid_size;
1175
1176         trace_hfi1_ctxt_info(uctxt->dd, uctxt->ctxt, fd->subctxt, cinfo);
1177         if (copy_to_user(ubase, &cinfo, sizeof(cinfo)))
1178                 ret = -EFAULT;
1179
1180         return ret;
1181 }
1182
1183 static int setup_ctxt(struct file *fp)
1184 {
1185         struct hfi1_filedata *fd = fp->private_data;
1186         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1187         struct hfi1_devdata *dd = uctxt->dd;
1188         int ret = 0;
1189
1190         /*
1191          * Context should be set up only once, including allocation and
1192          * programming of eager buffers. This is done if context sharing
1193          * is not requested or by the master process.
1194          */
1195         if (!uctxt->subctxt_cnt || !fd->subctxt) {
1196                 ret = hfi1_init_ctxt(uctxt->sc);
1197                 if (ret)
1198                         goto done;
1199
1200                 /* Now allocate the RcvHdr queue and eager buffers. */
1201                 ret = hfi1_create_rcvhdrq(dd, uctxt);
1202                 if (ret)
1203                         goto done;
1204                 ret = hfi1_setup_eagerbufs(uctxt);
1205                 if (ret)
1206                         goto done;
1207                 if (uctxt->subctxt_cnt && !fd->subctxt) {
1208                         ret = setup_subctxt(uctxt);
1209                         if (ret)
1210                                 goto done;
1211                 }
1212         } else {
1213                 ret = wait_event_interruptible(uctxt->wait, !test_bit(
1214                                                HFI1_CTXT_MASTER_UNINIT,
1215                                                &uctxt->event_flags));
1216                 if (ret)
1217                         goto done;
1218         }
1219
1220         ret = hfi1_user_sdma_alloc_queues(uctxt, fp);
1221         if (ret)
1222                 goto done;
1223         /*
1224          * Expected receive has to be setup for all processes (including
1225          * shared contexts). However, it has to be done after the master
1226          * context has been fully configured as it depends on the
1227          * eager/expected split of the RcvArray entries.
1228          * Setting it up here ensures that the subcontexts will be waiting
1229          * (due to the above wait_event_interruptible() until the master
1230          * is setup.
1231          */
1232         ret = hfi1_user_exp_rcv_init(fp);
1233         if (ret)
1234                 goto done;
1235
1236         set_bit(HFI1_CTXT_SETUP_DONE, &uctxt->event_flags);
1237 done:
1238         return ret;
1239 }
1240
1241 static int get_base_info(struct file *fp, void __user *ubase, __u32 len)
1242 {
1243         struct hfi1_base_info binfo;
1244         struct hfi1_filedata *fd = fp->private_data;
1245         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1246         struct hfi1_devdata *dd = uctxt->dd;
1247         ssize_t sz;
1248         unsigned offset;
1249         int ret = 0;
1250
1251         trace_hfi1_uctxtdata(uctxt->dd, uctxt);
1252
1253         memset(&binfo, 0, sizeof(binfo));
1254         binfo.hw_version = dd->revision;
1255         binfo.sw_version = HFI1_KERN_SWVERSION;
1256         binfo.bthqp = kdeth_qp;
1257         binfo.jkey = uctxt->jkey;
1258         /*
1259          * If more than 64 contexts are enabled the allocated credit
1260          * return will span two or three contiguous pages. Since we only
1261          * map the page containing the context's credit return address,
1262          * we need to calculate the offset in the proper page.
1263          */
1264         offset = ((u64)uctxt->sc->hw_free -
1265                   (u64)dd->cr_base[uctxt->numa_id].va) % PAGE_SIZE;
1266         binfo.sc_credits_addr = HFI1_MMAP_TOKEN(PIO_CRED, uctxt->ctxt,
1267                                                 fd->subctxt, offset);
1268         binfo.pio_bufbase = HFI1_MMAP_TOKEN(PIO_BUFS, uctxt->ctxt,
1269                                             fd->subctxt,
1270                                             uctxt->sc->base_addr);
1271         binfo.pio_bufbase_sop = HFI1_MMAP_TOKEN(PIO_BUFS_SOP,
1272                                                 uctxt->ctxt,
1273                                                 fd->subctxt,
1274                                                 uctxt->sc->base_addr);
1275         binfo.rcvhdr_bufbase = HFI1_MMAP_TOKEN(RCV_HDRQ, uctxt->ctxt,
1276                                                fd->subctxt,
1277                                                uctxt->rcvhdrq);
1278         binfo.rcvegr_bufbase = HFI1_MMAP_TOKEN(RCV_EGRBUF, uctxt->ctxt,
1279                                                fd->subctxt,
1280                                                uctxt->egrbufs.rcvtids[0].dma);
1281         binfo.sdma_comp_bufbase = HFI1_MMAP_TOKEN(SDMA_COMP, uctxt->ctxt,
1282                                                  fd->subctxt, 0);
1283         /*
1284          * user regs are at
1285          * (RXE_PER_CONTEXT_USER + (ctxt * RXE_PER_CONTEXT_SIZE))
1286          */
1287         binfo.user_regbase = HFI1_MMAP_TOKEN(UREGS, uctxt->ctxt,
1288                                             fd->subctxt, 0);
1289         offset = offset_in_page((((uctxt->ctxt - dd->first_user_ctxt) *
1290                     HFI1_MAX_SHARED_CTXTS) + fd->subctxt) *
1291                   sizeof(*dd->events));
1292         binfo.events_bufbase = HFI1_MMAP_TOKEN(EVENTS, uctxt->ctxt,
1293                                               fd->subctxt,
1294                                               offset);
1295         binfo.status_bufbase = HFI1_MMAP_TOKEN(STATUS, uctxt->ctxt,
1296                                               fd->subctxt,
1297                                               dd->status);
1298         if (HFI1_CAP_IS_USET(DMA_RTAIL))
1299                 binfo.rcvhdrtail_base = HFI1_MMAP_TOKEN(RTAIL, uctxt->ctxt,
1300                                                        fd->subctxt, 0);
1301         if (uctxt->subctxt_cnt) {
1302                 binfo.subctxt_uregbase = HFI1_MMAP_TOKEN(SUBCTXT_UREGS,
1303                                                         uctxt->ctxt,
1304                                                         fd->subctxt, 0);
1305                 binfo.subctxt_rcvhdrbuf = HFI1_MMAP_TOKEN(SUBCTXT_RCV_HDRQ,
1306                                                          uctxt->ctxt,
1307                                                          fd->subctxt, 0);
1308                 binfo.subctxt_rcvegrbuf = HFI1_MMAP_TOKEN(SUBCTXT_EGRBUF,
1309                                                          uctxt->ctxt,
1310                                                          fd->subctxt, 0);
1311         }
1312         sz = (len < sizeof(binfo)) ? len : sizeof(binfo);
1313         if (copy_to_user(ubase, &binfo, sz))
1314                 ret = -EFAULT;
1315         return ret;
1316 }
1317
1318 static unsigned int poll_urgent(struct file *fp,
1319                                 struct poll_table_struct *pt)
1320 {
1321         struct hfi1_filedata *fd = fp->private_data;
1322         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1323         struct hfi1_devdata *dd = uctxt->dd;
1324         unsigned pollflag;
1325
1326         poll_wait(fp, &uctxt->wait, pt);
1327
1328         spin_lock_irq(&dd->uctxt_lock);
1329         if (uctxt->urgent != uctxt->urgent_poll) {
1330                 pollflag = POLLIN | POLLRDNORM;
1331                 uctxt->urgent_poll = uctxt->urgent;
1332         } else {
1333                 pollflag = 0;
1334                 set_bit(HFI1_CTXT_WAITING_URG, &uctxt->event_flags);
1335         }
1336         spin_unlock_irq(&dd->uctxt_lock);
1337
1338         return pollflag;
1339 }
1340
1341 static unsigned int poll_next(struct file *fp,
1342                               struct poll_table_struct *pt)
1343 {
1344         struct hfi1_filedata *fd = fp->private_data;
1345         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1346         struct hfi1_devdata *dd = uctxt->dd;
1347         unsigned pollflag;
1348
1349         poll_wait(fp, &uctxt->wait, pt);
1350
1351         spin_lock_irq(&dd->uctxt_lock);
1352         if (hdrqempty(uctxt)) {
1353                 set_bit(HFI1_CTXT_WAITING_RCV, &uctxt->event_flags);
1354                 hfi1_rcvctrl(dd, HFI1_RCVCTRL_INTRAVAIL_ENB, uctxt->ctxt);
1355                 pollflag = 0;
1356         } else {
1357                 pollflag = POLLIN | POLLRDNORM;
1358         }
1359         spin_unlock_irq(&dd->uctxt_lock);
1360
1361         return pollflag;
1362 }
1363
1364 /*
1365  * Find all user contexts in use, and set the specified bit in their
1366  * event mask.
1367  * See also find_ctxt() for a similar use, that is specific to send buffers.
1368  */
1369 int hfi1_set_uevent_bits(struct hfi1_pportdata *ppd, const int evtbit)
1370 {
1371         struct hfi1_ctxtdata *uctxt;
1372         struct hfi1_devdata *dd = ppd->dd;
1373         unsigned ctxt;
1374         int ret = 0;
1375         unsigned long flags;
1376
1377         if (!dd->events) {
1378                 ret = -EINVAL;
1379                 goto done;
1380         }
1381
1382         spin_lock_irqsave(&dd->uctxt_lock, flags);
1383         for (ctxt = dd->first_user_ctxt; ctxt < dd->num_rcv_contexts;
1384              ctxt++) {
1385                 uctxt = dd->rcd[ctxt];
1386                 if (uctxt) {
1387                         unsigned long *evs = dd->events +
1388                                 (uctxt->ctxt - dd->first_user_ctxt) *
1389                                 HFI1_MAX_SHARED_CTXTS;
1390                         int i;
1391                         /*
1392                          * subctxt_cnt is 0 if not shared, so do base
1393                          * separately, first, then remaining subctxt, if any
1394                          */
1395                         set_bit(evtbit, evs);
1396                         for (i = 1; i < uctxt->subctxt_cnt; i++)
1397                                 set_bit(evtbit, evs + i);
1398                 }
1399         }
1400         spin_unlock_irqrestore(&dd->uctxt_lock, flags);
1401 done:
1402         return ret;
1403 }
1404
1405 /**
1406  * manage_rcvq - manage a context's receive queue
1407  * @uctxt: the context
1408  * @subctxt: the sub-context
1409  * @start_stop: action to carry out
1410  *
1411  * start_stop == 0 disables receive on the context, for use in queue
1412  * overflow conditions.  start_stop==1 re-enables, to be used to
1413  * re-init the software copy of the head register
1414  */
1415 static int manage_rcvq(struct hfi1_ctxtdata *uctxt, unsigned subctxt,
1416                        int start_stop)
1417 {
1418         struct hfi1_devdata *dd = uctxt->dd;
1419         unsigned int rcvctrl_op;
1420
1421         if (subctxt)
1422                 goto bail;
1423         /* atomically clear receive enable ctxt. */
1424         if (start_stop) {
1425                 /*
1426                  * On enable, force in-memory copy of the tail register to
1427                  * 0, so that protocol code doesn't have to worry about
1428                  * whether or not the chip has yet updated the in-memory
1429                  * copy or not on return from the system call. The chip
1430                  * always resets it's tail register back to 0 on a
1431                  * transition from disabled to enabled.
1432                  */
1433                 if (uctxt->rcvhdrtail_kvaddr)
1434                         clear_rcvhdrtail(uctxt);
1435                 rcvctrl_op = HFI1_RCVCTRL_CTXT_ENB;
1436         } else {
1437                 rcvctrl_op = HFI1_RCVCTRL_CTXT_DIS;
1438         }
1439         hfi1_rcvctrl(dd, rcvctrl_op, uctxt->ctxt);
1440         /* always; new head should be equal to new tail; see above */
1441 bail:
1442         return 0;
1443 }
1444
1445 /*
1446  * clear the event notifier events for this context.
1447  * User process then performs actions appropriate to bit having been
1448  * set, if desired, and checks again in future.
1449  */
1450 static int user_event_ack(struct hfi1_ctxtdata *uctxt, int subctxt,
1451                           unsigned long events)
1452 {
1453         int i;
1454         struct hfi1_devdata *dd = uctxt->dd;
1455         unsigned long *evs;
1456
1457         if (!dd->events)
1458                 return 0;
1459
1460         evs = dd->events + ((uctxt->ctxt - dd->first_user_ctxt) *
1461                             HFI1_MAX_SHARED_CTXTS) + subctxt;
1462
1463         for (i = 0; i <= _HFI1_MAX_EVENT_BIT; i++) {
1464                 if (!test_bit(i, &events))
1465                         continue;
1466                 clear_bit(i, evs);
1467         }
1468         return 0;
1469 }
1470
1471 static int set_ctxt_pkey(struct hfi1_ctxtdata *uctxt, unsigned subctxt,
1472                          u16 pkey)
1473 {
1474         int ret = -ENOENT, i, intable = 0;
1475         struct hfi1_pportdata *ppd = uctxt->ppd;
1476         struct hfi1_devdata *dd = uctxt->dd;
1477
1478         if (pkey == LIM_MGMT_P_KEY || pkey == FULL_MGMT_P_KEY) {
1479                 ret = -EINVAL;
1480                 goto done;
1481         }
1482
1483         for (i = 0; i < ARRAY_SIZE(ppd->pkeys); i++)
1484                 if (pkey == ppd->pkeys[i]) {
1485                         intable = 1;
1486                         break;
1487                 }
1488
1489         if (intable)
1490                 ret = hfi1_set_ctxt_pkey(dd, uctxt->ctxt, pkey);
1491 done:
1492         return ret;
1493 }
1494
1495 static void user_remove(struct hfi1_devdata *dd)
1496 {
1497
1498         hfi1_cdev_cleanup(&dd->user_cdev, &dd->user_device);
1499 }
1500
1501 static int user_add(struct hfi1_devdata *dd)
1502 {
1503         char name[10];
1504         int ret;
1505
1506         snprintf(name, sizeof(name), "%s_%d", class_name(), dd->unit);
1507         ret = hfi1_cdev_init(dd->unit, name, &hfi1_file_ops,
1508                              &dd->user_cdev, &dd->user_device,
1509                              true, &dd->kobj);
1510         if (ret)
1511                 user_remove(dd);
1512
1513         return ret;
1514 }
1515
1516 /*
1517  * Create per-unit files in /dev
1518  */
1519 int hfi1_device_create(struct hfi1_devdata *dd)
1520 {
1521         return user_add(dd);
1522 }
1523
1524 /*
1525  * Remove per-unit files in /dev
1526  * void, core kernel returns no errors for this stuff
1527  */
1528 void hfi1_device_remove(struct hfi1_devdata *dd)
1529 {
1530         user_remove(dd);
1531 }