GNU Linux-libre 4.19.245-gnu1
[releases.git] / drivers / infiniband / hw / hfi1 / file_ops.c
1 /*
2  * Copyright(c) 2015-2017 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 #include <linux/sched/mm.h>
52 #include <linux/bitmap.h>
53
54 #include <rdma/ib.h>
55
56 #include "hfi.h"
57 #include "pio.h"
58 #include "device.h"
59 #include "common.h"
60 #include "trace.h"
61 #include "mmu_rb.h"
62 #include "user_sdma.h"
63 #include "user_exp_rcv.h"
64 #include "aspm.h"
65
66 #undef pr_fmt
67 #define pr_fmt(fmt) DRIVER_NAME ": " fmt
68
69 #define SEND_CTXT_HALT_TIMEOUT 1000 /* msecs */
70
71 /*
72  * File operation functions
73  */
74 static int hfi1_file_open(struct inode *inode, struct file *fp);
75 static int hfi1_file_close(struct inode *inode, struct file *fp);
76 static ssize_t hfi1_write_iter(struct kiocb *kiocb, struct iov_iter *from);
77 static __poll_t hfi1_poll(struct file *fp, struct poll_table_struct *pt);
78 static int hfi1_file_mmap(struct file *fp, struct vm_area_struct *vma);
79
80 static u64 kvirt_to_phys(void *addr);
81 static int assign_ctxt(struct hfi1_filedata *fd, unsigned long arg, u32 len);
82 static void init_subctxts(struct hfi1_ctxtdata *uctxt,
83                           const struct hfi1_user_info *uinfo);
84 static int init_user_ctxt(struct hfi1_filedata *fd,
85                           struct hfi1_ctxtdata *uctxt);
86 static void user_init(struct hfi1_ctxtdata *uctxt);
87 static int get_ctxt_info(struct hfi1_filedata *fd, unsigned long arg, u32 len);
88 static int get_base_info(struct hfi1_filedata *fd, unsigned long arg, u32 len);
89 static int user_exp_rcv_setup(struct hfi1_filedata *fd, unsigned long arg,
90                               u32 len);
91 static int user_exp_rcv_clear(struct hfi1_filedata *fd, unsigned long arg,
92                               u32 len);
93 static int user_exp_rcv_invalid(struct hfi1_filedata *fd, unsigned long arg,
94                                 u32 len);
95 static int setup_base_ctxt(struct hfi1_filedata *fd,
96                            struct hfi1_ctxtdata *uctxt);
97 static int setup_subctxt(struct hfi1_ctxtdata *uctxt);
98
99 static int find_sub_ctxt(struct hfi1_filedata *fd,
100                          const struct hfi1_user_info *uinfo);
101 static int allocate_ctxt(struct hfi1_filedata *fd, struct hfi1_devdata *dd,
102                          struct hfi1_user_info *uinfo,
103                          struct hfi1_ctxtdata **cd);
104 static void deallocate_ctxt(struct hfi1_ctxtdata *uctxt);
105 static __poll_t poll_urgent(struct file *fp, struct poll_table_struct *pt);
106 static __poll_t poll_next(struct file *fp, struct poll_table_struct *pt);
107 static int user_event_ack(struct hfi1_ctxtdata *uctxt, u16 subctxt,
108                           unsigned long arg);
109 static int set_ctxt_pkey(struct hfi1_ctxtdata *uctxt, unsigned long arg);
110 static int ctxt_reset(struct hfi1_ctxtdata *uctxt);
111 static int manage_rcvq(struct hfi1_ctxtdata *uctxt, u16 subctxt,
112                        unsigned long arg);
113 static vm_fault_t vma_fault(struct vm_fault *vmf);
114 static long hfi1_file_ioctl(struct file *fp, unsigned int cmd,
115                             unsigned long arg);
116
117 static const struct file_operations hfi1_file_ops = {
118         .owner = THIS_MODULE,
119         .write_iter = hfi1_write_iter,
120         .open = hfi1_file_open,
121         .release = hfi1_file_close,
122         .unlocked_ioctl = hfi1_file_ioctl,
123         .poll = hfi1_poll,
124         .mmap = hfi1_file_mmap,
125         .llseek = noop_llseek,
126 };
127
128 static const struct vm_operations_struct vm_ops = {
129         .fault = vma_fault,
130 };
131
132 /*
133  * Types of memories mapped into user processes' space
134  */
135 enum mmap_types {
136         PIO_BUFS = 1,
137         PIO_BUFS_SOP,
138         PIO_CRED,
139         RCV_HDRQ,
140         RCV_EGRBUF,
141         UREGS,
142         EVENTS,
143         STATUS,
144         RTAIL,
145         SUBCTXT_UREGS,
146         SUBCTXT_RCV_HDRQ,
147         SUBCTXT_EGRBUF,
148         SDMA_COMP
149 };
150
151 /*
152  * Masks and offsets defining the mmap tokens
153  */
154 #define HFI1_MMAP_OFFSET_MASK   0xfffULL
155 #define HFI1_MMAP_OFFSET_SHIFT  0
156 #define HFI1_MMAP_SUBCTXT_MASK  0xfULL
157 #define HFI1_MMAP_SUBCTXT_SHIFT 12
158 #define HFI1_MMAP_CTXT_MASK     0xffULL
159 #define HFI1_MMAP_CTXT_SHIFT    16
160 #define HFI1_MMAP_TYPE_MASK     0xfULL
161 #define HFI1_MMAP_TYPE_SHIFT    24
162 #define HFI1_MMAP_MAGIC_MASK    0xffffffffULL
163 #define HFI1_MMAP_MAGIC_SHIFT   32
164
165 #define HFI1_MMAP_MAGIC         0xdabbad00
166
167 #define HFI1_MMAP_TOKEN_SET(field, val) \
168         (((val) & HFI1_MMAP_##field##_MASK) << HFI1_MMAP_##field##_SHIFT)
169 #define HFI1_MMAP_TOKEN_GET(field, token) \
170         (((token) >> HFI1_MMAP_##field##_SHIFT) & HFI1_MMAP_##field##_MASK)
171 #define HFI1_MMAP_TOKEN(type, ctxt, subctxt, addr)   \
172         (HFI1_MMAP_TOKEN_SET(MAGIC, HFI1_MMAP_MAGIC) | \
173         HFI1_MMAP_TOKEN_SET(TYPE, type) | \
174         HFI1_MMAP_TOKEN_SET(CTXT, ctxt) | \
175         HFI1_MMAP_TOKEN_SET(SUBCTXT, subctxt) | \
176         HFI1_MMAP_TOKEN_SET(OFFSET, (offset_in_page(addr))))
177
178 #define dbg(fmt, ...)                           \
179         pr_info(fmt, ##__VA_ARGS__)
180
181 static inline int is_valid_mmap(u64 token)
182 {
183         return (HFI1_MMAP_TOKEN_GET(MAGIC, token) == HFI1_MMAP_MAGIC);
184 }
185
186 static int hfi1_file_open(struct inode *inode, struct file *fp)
187 {
188         struct hfi1_filedata *fd;
189         struct hfi1_devdata *dd = container_of(inode->i_cdev,
190                                                struct hfi1_devdata,
191                                                user_cdev);
192
193         if (!((dd->flags & HFI1_PRESENT) && dd->kregbase1))
194                 return -EINVAL;
195
196         if (!atomic_inc_not_zero(&dd->user_refcount))
197                 return -ENXIO;
198
199         /* The real work is performed later in assign_ctxt() */
200
201         fd = kzalloc(sizeof(*fd), GFP_KERNEL);
202
203         if (!fd || init_srcu_struct(&fd->pq_srcu))
204                 goto nomem;
205         spin_lock_init(&fd->pq_rcu_lock);
206         spin_lock_init(&fd->tid_lock);
207         spin_lock_init(&fd->invalid_lock);
208         fd->rec_cpu_num = -1; /* no cpu affinity by default */
209         fd->mm = current->mm;
210         mmgrab(fd->mm);
211         fd->dd = dd;
212         kobject_get(&fd->dd->kobj);
213         fp->private_data = fd;
214         return 0;
215 nomem:
216         kfree(fd);
217         fp->private_data = NULL;
218         if (atomic_dec_and_test(&dd->user_refcount))
219                 complete(&dd->user_comp);
220         return -ENOMEM;
221 }
222
223 static long hfi1_file_ioctl(struct file *fp, unsigned int cmd,
224                             unsigned long arg)
225 {
226         struct hfi1_filedata *fd = fp->private_data;
227         struct hfi1_ctxtdata *uctxt = fd->uctxt;
228         int ret = 0;
229         int uval = 0;
230
231         hfi1_cdbg(IOCTL, "IOCTL recv: 0x%x", cmd);
232         if (cmd != HFI1_IOCTL_ASSIGN_CTXT &&
233             cmd != HFI1_IOCTL_GET_VERS &&
234             !uctxt)
235                 return -EINVAL;
236
237         switch (cmd) {
238         case HFI1_IOCTL_ASSIGN_CTXT:
239                 ret = assign_ctxt(fd, arg, _IOC_SIZE(cmd));
240                 break;
241
242         case HFI1_IOCTL_CTXT_INFO:
243                 ret = get_ctxt_info(fd, arg, _IOC_SIZE(cmd));
244                 break;
245
246         case HFI1_IOCTL_USER_INFO:
247                 ret = get_base_info(fd, arg, _IOC_SIZE(cmd));
248                 break;
249
250         case HFI1_IOCTL_CREDIT_UPD:
251                 if (uctxt)
252                         sc_return_credits(uctxt->sc);
253                 break;
254
255         case HFI1_IOCTL_TID_UPDATE:
256                 ret = user_exp_rcv_setup(fd, arg, _IOC_SIZE(cmd));
257                 break;
258
259         case HFI1_IOCTL_TID_FREE:
260                 ret = user_exp_rcv_clear(fd, arg, _IOC_SIZE(cmd));
261                 break;
262
263         case HFI1_IOCTL_TID_INVAL_READ:
264                 ret = user_exp_rcv_invalid(fd, arg, _IOC_SIZE(cmd));
265                 break;
266
267         case HFI1_IOCTL_RECV_CTRL:
268                 ret = manage_rcvq(uctxt, fd->subctxt, arg);
269                 break;
270
271         case HFI1_IOCTL_POLL_TYPE:
272                 if (get_user(uval, (int __user *)arg))
273                         return -EFAULT;
274                 uctxt->poll_type = (typeof(uctxt->poll_type))uval;
275                 break;
276
277         case HFI1_IOCTL_ACK_EVENT:
278                 ret = user_event_ack(uctxt, fd->subctxt, arg);
279                 break;
280
281         case HFI1_IOCTL_SET_PKEY:
282                 ret = set_ctxt_pkey(uctxt, arg);
283                 break;
284
285         case HFI1_IOCTL_CTXT_RESET:
286                 ret = ctxt_reset(uctxt);
287                 break;
288
289         case HFI1_IOCTL_GET_VERS:
290                 uval = HFI1_USER_SWVERSION;
291                 if (put_user(uval, (int __user *)arg))
292                         return -EFAULT;
293                 break;
294
295         default:
296                 return -EINVAL;
297         }
298
299         return ret;
300 }
301
302 static ssize_t hfi1_write_iter(struct kiocb *kiocb, struct iov_iter *from)
303 {
304         struct hfi1_filedata *fd = kiocb->ki_filp->private_data;
305         struct hfi1_user_sdma_pkt_q *pq;
306         struct hfi1_user_sdma_comp_q *cq = fd->cq;
307         int done = 0, reqs = 0;
308         unsigned long dim = from->nr_segs;
309         int idx;
310
311         idx = srcu_read_lock(&fd->pq_srcu);
312         pq = srcu_dereference(fd->pq, &fd->pq_srcu);
313         if (!cq || !pq) {
314                 srcu_read_unlock(&fd->pq_srcu, idx);
315                 return -EIO;
316         }
317
318         if (!iter_is_iovec(from) || !dim) {
319                 srcu_read_unlock(&fd->pq_srcu, idx);
320                 return -EINVAL;
321         }
322
323         trace_hfi1_sdma_request(fd->dd, fd->uctxt->ctxt, fd->subctxt, dim);
324
325         if (atomic_read(&pq->n_reqs) == pq->n_max_reqs) {
326                 srcu_read_unlock(&fd->pq_srcu, idx);
327                 return -ENOSPC;
328         }
329
330         while (dim) {
331                 int ret;
332                 unsigned long count = 0;
333
334                 ret = hfi1_user_sdma_process_request(
335                         fd, (struct iovec *)(from->iov + done),
336                         dim, &count);
337                 if (ret) {
338                         reqs = ret;
339                         break;
340                 }
341                 dim -= count;
342                 done += count;
343                 reqs++;
344         }
345
346         srcu_read_unlock(&fd->pq_srcu, idx);
347         return reqs;
348 }
349
350 static int hfi1_file_mmap(struct file *fp, struct vm_area_struct *vma)
351 {
352         struct hfi1_filedata *fd = fp->private_data;
353         struct hfi1_ctxtdata *uctxt = fd->uctxt;
354         struct hfi1_devdata *dd;
355         unsigned long flags;
356         u64 token = vma->vm_pgoff << PAGE_SHIFT,
357                 memaddr = 0;
358         void *memvirt = NULL;
359         u8 subctxt, mapio = 0, vmf = 0, type;
360         ssize_t memlen = 0;
361         int ret = 0;
362         u16 ctxt;
363
364         if (!is_valid_mmap(token) || !uctxt ||
365             !(vma->vm_flags & VM_SHARED)) {
366                 ret = -EINVAL;
367                 goto done;
368         }
369         dd = uctxt->dd;
370         ctxt = HFI1_MMAP_TOKEN_GET(CTXT, token);
371         subctxt = HFI1_MMAP_TOKEN_GET(SUBCTXT, token);
372         type = HFI1_MMAP_TOKEN_GET(TYPE, token);
373         if (ctxt != uctxt->ctxt || subctxt != fd->subctxt) {
374                 ret = -EINVAL;
375                 goto done;
376         }
377
378         flags = vma->vm_flags;
379
380         switch (type) {
381         case PIO_BUFS:
382         case PIO_BUFS_SOP:
383                 memaddr = ((dd->physaddr + TXE_PIO_SEND) +
384                                 /* chip pio base */
385                            (uctxt->sc->hw_context * BIT(16))) +
386                                 /* 64K PIO space / ctxt */
387                         (type == PIO_BUFS_SOP ?
388                                 (TXE_PIO_SIZE / 2) : 0); /* sop? */
389                 /*
390                  * Map only the amount allocated to the context, not the
391                  * entire available context's PIO space.
392                  */
393                 memlen = PAGE_ALIGN(uctxt->sc->credits * PIO_BLOCK_SIZE);
394                 flags &= ~VM_MAYREAD;
395                 flags |= VM_DONTCOPY | VM_DONTEXPAND;
396                 vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
397                 mapio = 1;
398                 break;
399         case PIO_CRED:
400                 if (flags & VM_WRITE) {
401                         ret = -EPERM;
402                         goto done;
403                 }
404                 /*
405                  * The credit return location for this context could be on the
406                  * second or third page allocated for credit returns (if number
407                  * of enabled contexts > 64 and 128 respectively).
408                  */
409                 memvirt = dd->cr_base[uctxt->numa_id].va;
410                 memaddr = virt_to_phys(memvirt) +
411                         (((u64)uctxt->sc->hw_free -
412                           (u64)dd->cr_base[uctxt->numa_id].va) & PAGE_MASK);
413                 memlen = PAGE_SIZE;
414                 flags &= ~VM_MAYWRITE;
415                 flags |= VM_DONTCOPY | VM_DONTEXPAND;
416                 /*
417                  * The driver has already allocated memory for credit
418                  * returns and programmed it into the chip. Has that
419                  * memory been flagged as non-cached?
420                  */
421                 /* vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); */
422                 mapio = 1;
423                 break;
424         case RCV_HDRQ:
425                 memlen = rcvhdrq_size(uctxt);
426                 memvirt = uctxt->rcvhdrq;
427                 break;
428         case RCV_EGRBUF: {
429                 unsigned long addr;
430                 int i;
431                 /*
432                  * The RcvEgr buffer need to be handled differently
433                  * as multiple non-contiguous pages need to be mapped
434                  * into the user process.
435                  */
436                 memlen = uctxt->egrbufs.size;
437                 if ((vma->vm_end - vma->vm_start) != memlen) {
438                         dd_dev_err(dd, "Eager buffer map size invalid (%lu != %lu)\n",
439                                    (vma->vm_end - vma->vm_start), memlen);
440                         ret = -EINVAL;
441                         goto done;
442                 }
443                 if (vma->vm_flags & VM_WRITE) {
444                         ret = -EPERM;
445                         goto done;
446                 }
447                 vma->vm_flags &= ~VM_MAYWRITE;
448                 addr = vma->vm_start;
449                 for (i = 0 ; i < uctxt->egrbufs.numbufs; i++) {
450                         memlen = uctxt->egrbufs.buffers[i].len;
451                         memvirt = uctxt->egrbufs.buffers[i].addr;
452                         ret = remap_pfn_range(
453                                 vma, addr,
454                                 /*
455                                  * virt_to_pfn() does the same, but
456                                  * it's not available on x86_64
457                                  * when CONFIG_MMU is enabled.
458                                  */
459                                 PFN_DOWN(__pa(memvirt)),
460                                 memlen,
461                                 vma->vm_page_prot);
462                         if (ret < 0)
463                                 goto done;
464                         addr += memlen;
465                 }
466                 ret = 0;
467                 goto done;
468         }
469         case UREGS:
470                 /*
471                  * Map only the page that contains this context's user
472                  * registers.
473                  */
474                 memaddr = (unsigned long)
475                         (dd->physaddr + RXE_PER_CONTEXT_USER)
476                         + (uctxt->ctxt * RXE_PER_CONTEXT_SIZE);
477                 /*
478                  * TidFlow table is on the same page as the rest of the
479                  * user registers.
480                  */
481                 memlen = PAGE_SIZE;
482                 flags |= VM_DONTCOPY | VM_DONTEXPAND;
483                 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
484                 mapio = 1;
485                 break;
486         case EVENTS:
487                 /*
488                  * Use the page where this context's flags are. User level
489                  * knows where it's own bitmap is within the page.
490                  */
491                 memaddr = (unsigned long)
492                         (dd->events + uctxt_offset(uctxt)) & PAGE_MASK;
493                 memlen = PAGE_SIZE;
494                 /*
495                  * v3.7 removes VM_RESERVED but the effect is kept by
496                  * using VM_IO.
497                  */
498                 flags |= VM_IO | VM_DONTEXPAND;
499                 vmf = 1;
500                 break;
501         case STATUS:
502                 if (flags & VM_WRITE) {
503                         ret = -EPERM;
504                         goto done;
505                 }
506                 memaddr = kvirt_to_phys((void *)dd->status);
507                 memlen = PAGE_SIZE;
508                 flags |= VM_IO | VM_DONTEXPAND;
509                 break;
510         case RTAIL:
511                 if (!HFI1_CAP_IS_USET(DMA_RTAIL)) {
512                         /*
513                          * If the memory allocation failed, the context alloc
514                          * also would have failed, so we would never get here
515                          */
516                         ret = -EINVAL;
517                         goto done;
518                 }
519                 if ((flags & VM_WRITE) || !uctxt->rcvhdrtail_kvaddr) {
520                         ret = -EPERM;
521                         goto done;
522                 }
523                 memlen = PAGE_SIZE;
524                 memvirt = (void *)uctxt->rcvhdrtail_kvaddr;
525                 flags &= ~VM_MAYWRITE;
526                 break;
527         case SUBCTXT_UREGS:
528                 memaddr = (u64)uctxt->subctxt_uregbase;
529                 memlen = PAGE_SIZE;
530                 flags |= VM_IO | VM_DONTEXPAND;
531                 vmf = 1;
532                 break;
533         case SUBCTXT_RCV_HDRQ:
534                 memaddr = (u64)uctxt->subctxt_rcvhdr_base;
535                 memlen = rcvhdrq_size(uctxt) * uctxt->subctxt_cnt;
536                 flags |= VM_IO | VM_DONTEXPAND;
537                 vmf = 1;
538                 break;
539         case SUBCTXT_EGRBUF:
540                 memaddr = (u64)uctxt->subctxt_rcvegrbuf;
541                 memlen = uctxt->egrbufs.size * uctxt->subctxt_cnt;
542                 flags |= VM_IO | VM_DONTEXPAND;
543                 flags &= ~VM_MAYWRITE;
544                 vmf = 1;
545                 break;
546         case SDMA_COMP: {
547                 struct hfi1_user_sdma_comp_q *cq = fd->cq;
548
549                 if (!cq) {
550                         ret = -EFAULT;
551                         goto done;
552                 }
553                 memaddr = (u64)cq->comps;
554                 memlen = PAGE_ALIGN(sizeof(*cq->comps) * cq->nentries);
555                 flags |= VM_IO | VM_DONTEXPAND;
556                 vmf = 1;
557                 break;
558         }
559         default:
560                 ret = -EINVAL;
561                 break;
562         }
563
564         if ((vma->vm_end - vma->vm_start) != memlen) {
565                 hfi1_cdbg(PROC, "%u:%u Memory size mismatch %lu:%lu",
566                           uctxt->ctxt, fd->subctxt,
567                           (vma->vm_end - vma->vm_start), memlen);
568                 ret = -EINVAL;
569                 goto done;
570         }
571
572         vma->vm_flags = flags;
573         hfi1_cdbg(PROC,
574                   "%u:%u type:%u io/vf:%d/%d, addr:0x%llx, len:%lu(%lu), flags:0x%lx\n",
575                     ctxt, subctxt, type, mapio, vmf, memaddr, memlen,
576                     vma->vm_end - vma->vm_start, vma->vm_flags);
577         if (vmf) {
578                 vma->vm_pgoff = PFN_DOWN(memaddr);
579                 vma->vm_ops = &vm_ops;
580                 ret = 0;
581         } else if (mapio) {
582                 ret = io_remap_pfn_range(vma, vma->vm_start,
583                                          PFN_DOWN(memaddr),
584                                          memlen,
585                                          vma->vm_page_prot);
586         } else if (memvirt) {
587                 ret = remap_pfn_range(vma, vma->vm_start,
588                                       PFN_DOWN(__pa(memvirt)),
589                                       memlen,
590                                       vma->vm_page_prot);
591         } else {
592                 ret = remap_pfn_range(vma, vma->vm_start,
593                                       PFN_DOWN(memaddr),
594                                       memlen,
595                                       vma->vm_page_prot);
596         }
597 done:
598         return ret;
599 }
600
601 /*
602  * Local (non-chip) user memory is not mapped right away but as it is
603  * accessed by the user-level code.
604  */
605 static vm_fault_t vma_fault(struct vm_fault *vmf)
606 {
607         struct page *page;
608
609         page = vmalloc_to_page((void *)(vmf->pgoff << PAGE_SHIFT));
610         if (!page)
611                 return VM_FAULT_SIGBUS;
612
613         get_page(page);
614         vmf->page = page;
615
616         return 0;
617 }
618
619 static __poll_t hfi1_poll(struct file *fp, struct poll_table_struct *pt)
620 {
621         struct hfi1_ctxtdata *uctxt;
622         __poll_t pollflag;
623
624         uctxt = ((struct hfi1_filedata *)fp->private_data)->uctxt;
625         if (!uctxt)
626                 pollflag = EPOLLERR;
627         else if (uctxt->poll_type == HFI1_POLL_TYPE_URGENT)
628                 pollflag = poll_urgent(fp, pt);
629         else  if (uctxt->poll_type == HFI1_POLL_TYPE_ANYRCV)
630                 pollflag = poll_next(fp, pt);
631         else /* invalid */
632                 pollflag = EPOLLERR;
633
634         return pollflag;
635 }
636
637 static int hfi1_file_close(struct inode *inode, struct file *fp)
638 {
639         struct hfi1_filedata *fdata = fp->private_data;
640         struct hfi1_ctxtdata *uctxt = fdata->uctxt;
641         struct hfi1_devdata *dd = container_of(inode->i_cdev,
642                                                struct hfi1_devdata,
643                                                user_cdev);
644         unsigned long flags, *ev;
645
646         fp->private_data = NULL;
647
648         if (!uctxt)
649                 goto done;
650
651         hfi1_cdbg(PROC, "closing ctxt %u:%u", uctxt->ctxt, fdata->subctxt);
652
653         flush_wc();
654         /* drain user sdma queue */
655         hfi1_user_sdma_free_queues(fdata, uctxt);
656
657         /* release the cpu */
658         hfi1_put_proc_affinity(fdata->rec_cpu_num);
659
660         /* clean up rcv side */
661         hfi1_user_exp_rcv_free(fdata);
662
663         /*
664          * fdata->uctxt is used in the above cleanup.  It is not ready to be
665          * removed until here.
666          */
667         fdata->uctxt = NULL;
668         hfi1_rcd_put(uctxt);
669
670         /*
671          * Clear any left over, unhandled events so the next process that
672          * gets this context doesn't get confused.
673          */
674         ev = dd->events + uctxt_offset(uctxt) + fdata->subctxt;
675         *ev = 0;
676
677         spin_lock_irqsave(&dd->uctxt_lock, flags);
678         __clear_bit(fdata->subctxt, uctxt->in_use_ctxts);
679         if (!bitmap_empty(uctxt->in_use_ctxts, HFI1_MAX_SHARED_CTXTS)) {
680                 spin_unlock_irqrestore(&dd->uctxt_lock, flags);
681                 goto done;
682         }
683         spin_unlock_irqrestore(&dd->uctxt_lock, flags);
684
685         /*
686          * Disable receive context and interrupt available, reset all
687          * RcvCtxtCtrl bits to default values.
688          */
689         hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_DIS |
690                      HFI1_RCVCTRL_TIDFLOW_DIS |
691                      HFI1_RCVCTRL_INTRAVAIL_DIS |
692                      HFI1_RCVCTRL_TAILUPD_DIS |
693                      HFI1_RCVCTRL_ONE_PKT_EGR_DIS |
694                      HFI1_RCVCTRL_NO_RHQ_DROP_DIS |
695                      HFI1_RCVCTRL_NO_EGR_DROP_DIS, uctxt);
696         /* Clear the context's J_KEY */
697         hfi1_clear_ctxt_jkey(dd, uctxt);
698         /*
699          * If a send context is allocated, reset context integrity
700          * checks to default and disable the send context.
701          */
702         if (uctxt->sc) {
703                 sc_disable(uctxt->sc);
704                 set_pio_integrity(uctxt->sc);
705         }
706
707         hfi1_free_ctxt_rcv_groups(uctxt);
708         hfi1_clear_ctxt_pkey(dd, uctxt);
709
710         uctxt->event_flags = 0;
711
712         deallocate_ctxt(uctxt);
713 done:
714         mmdrop(fdata->mm);
715         kobject_put(&dd->kobj);
716
717         if (atomic_dec_and_test(&dd->user_refcount))
718                 complete(&dd->user_comp);
719
720         cleanup_srcu_struct(&fdata->pq_srcu);
721         kfree(fdata);
722         return 0;
723 }
724
725 /*
726  * Convert kernel *virtual* addresses to physical addresses.
727  * This is used to vmalloc'ed addresses.
728  */
729 static u64 kvirt_to_phys(void *addr)
730 {
731         struct page *page;
732         u64 paddr = 0;
733
734         page = vmalloc_to_page(addr);
735         if (page)
736                 paddr = page_to_pfn(page) << PAGE_SHIFT;
737
738         return paddr;
739 }
740
741 /**
742  * complete_subctxt
743  * @fd: valid filedata pointer
744  *
745  * Sub-context info can only be set up after the base context
746  * has been completed.  This is indicated by the clearing of the
747  * HFI1_CTXT_BASE_UINIT bit.
748  *
749  * Wait for the bit to be cleared, and then complete the subcontext
750  * initialization.
751  *
752  */
753 static int complete_subctxt(struct hfi1_filedata *fd)
754 {
755         int ret;
756         unsigned long flags;
757
758         /*
759          * sub-context info can only be set up after the base context
760          * has been completed.
761          */
762         ret = wait_event_interruptible(
763                 fd->uctxt->wait,
764                 !test_bit(HFI1_CTXT_BASE_UNINIT, &fd->uctxt->event_flags));
765
766         if (test_bit(HFI1_CTXT_BASE_FAILED, &fd->uctxt->event_flags))
767                 ret = -ENOMEM;
768
769         /* Finish the sub-context init */
770         if (!ret) {
771                 fd->rec_cpu_num = hfi1_get_proc_affinity(fd->uctxt->numa_id);
772                 ret = init_user_ctxt(fd, fd->uctxt);
773         }
774
775         if (ret) {
776                 spin_lock_irqsave(&fd->dd->uctxt_lock, flags);
777                 __clear_bit(fd->subctxt, fd->uctxt->in_use_ctxts);
778                 spin_unlock_irqrestore(&fd->dd->uctxt_lock, flags);
779                 hfi1_rcd_put(fd->uctxt);
780                 fd->uctxt = NULL;
781         }
782
783         return ret;
784 }
785
786 static int assign_ctxt(struct hfi1_filedata *fd, unsigned long arg, u32 len)
787 {
788         int ret;
789         unsigned int swmajor;
790         struct hfi1_ctxtdata *uctxt = NULL;
791         struct hfi1_user_info uinfo;
792
793         if (fd->uctxt)
794                 return -EINVAL;
795
796         if (sizeof(uinfo) != len)
797                 return -EINVAL;
798
799         if (copy_from_user(&uinfo, (void __user *)arg, sizeof(uinfo)))
800                 return -EFAULT;
801
802         swmajor = uinfo.userversion >> 16;
803         if (swmajor != HFI1_USER_SWMAJOR)
804                 return -ENODEV;
805
806         if (uinfo.subctxt_cnt > HFI1_MAX_SHARED_CTXTS)
807                 return -EINVAL;
808
809         /*
810          * Acquire the mutex to protect against multiple creations of what
811          * could be a shared base context.
812          */
813         mutex_lock(&hfi1_mutex);
814         /*
815          * Get a sub context if available  (fd->uctxt will be set).
816          * ret < 0 error, 0 no context, 1 sub-context found
817          */
818         ret = find_sub_ctxt(fd, &uinfo);
819
820         /*
821          * Allocate a base context if context sharing is not required or a
822          * sub context wasn't found.
823          */
824         if (!ret)
825                 ret = allocate_ctxt(fd, fd->dd, &uinfo, &uctxt);
826
827         mutex_unlock(&hfi1_mutex);
828
829         /* Depending on the context type, finish the appropriate init */
830         switch (ret) {
831         case 0:
832                 ret = setup_base_ctxt(fd, uctxt);
833                 if (ret)
834                         deallocate_ctxt(uctxt);
835                 break;
836         case 1:
837                 ret = complete_subctxt(fd);
838                 break;
839         default:
840                 break;
841         }
842
843         return ret;
844 }
845
846 /**
847  * match_ctxt
848  * @fd: valid filedata pointer
849  * @uinfo: user info to compare base context with
850  * @uctxt: context to compare uinfo to.
851  *
852  * Compare the given context with the given information to see if it
853  * can be used for a sub context.
854  */
855 static int match_ctxt(struct hfi1_filedata *fd,
856                       const struct hfi1_user_info *uinfo,
857                       struct hfi1_ctxtdata *uctxt)
858 {
859         struct hfi1_devdata *dd = fd->dd;
860         unsigned long flags;
861         u16 subctxt;
862
863         /* Skip dynamically allocated kernel contexts */
864         if (uctxt->sc && (uctxt->sc->type == SC_KERNEL))
865                 return 0;
866
867         /* Skip ctxt if it doesn't match the requested one */
868         if (memcmp(uctxt->uuid, uinfo->uuid, sizeof(uctxt->uuid)) ||
869             uctxt->jkey != generate_jkey(current_uid()) ||
870             uctxt->subctxt_id != uinfo->subctxt_id ||
871             uctxt->subctxt_cnt != uinfo->subctxt_cnt)
872                 return 0;
873
874         /* Verify the sharing process matches the base */
875         if (uctxt->userversion != uinfo->userversion)
876                 return -EINVAL;
877
878         /* Find an unused sub context */
879         spin_lock_irqsave(&dd->uctxt_lock, flags);
880         if (bitmap_empty(uctxt->in_use_ctxts, HFI1_MAX_SHARED_CTXTS)) {
881                 /* context is being closed, do not use */
882                 spin_unlock_irqrestore(&dd->uctxt_lock, flags);
883                 return 0;
884         }
885
886         subctxt = find_first_zero_bit(uctxt->in_use_ctxts,
887                                       HFI1_MAX_SHARED_CTXTS);
888         if (subctxt >= uctxt->subctxt_cnt) {
889                 spin_unlock_irqrestore(&dd->uctxt_lock, flags);
890                 return -EBUSY;
891         }
892
893         fd->subctxt = subctxt;
894         __set_bit(fd->subctxt, uctxt->in_use_ctxts);
895         spin_unlock_irqrestore(&dd->uctxt_lock, flags);
896
897         fd->uctxt = uctxt;
898         hfi1_rcd_get(uctxt);
899
900         return 1;
901 }
902
903 /**
904  * find_sub_ctxt
905  * @fd: valid filedata pointer
906  * @uinfo: matching info to use to find a possible context to share.
907  *
908  * The hfi1_mutex must be held when this function is called.  It is
909  * necessary to ensure serialized creation of shared contexts.
910  *
911  * Return:
912  *    0      No sub-context found
913  *    1      Subcontext found and allocated
914  *    errno  EINVAL (incorrect parameters)
915  *           EBUSY (all sub contexts in use)
916  */
917 static int find_sub_ctxt(struct hfi1_filedata *fd,
918                          const struct hfi1_user_info *uinfo)
919 {
920         struct hfi1_ctxtdata *uctxt;
921         struct hfi1_devdata *dd = fd->dd;
922         u16 i;
923         int ret;
924
925         if (!uinfo->subctxt_cnt)
926                 return 0;
927
928         for (i = dd->first_dyn_alloc_ctxt; i < dd->num_rcv_contexts; i++) {
929                 uctxt = hfi1_rcd_get_by_index(dd, i);
930                 if (uctxt) {
931                         ret = match_ctxt(fd, uinfo, uctxt);
932                         hfi1_rcd_put(uctxt);
933                         /* value of != 0 will return */
934                         if (ret)
935                                 return ret;
936                 }
937         }
938
939         return 0;
940 }
941
942 static int allocate_ctxt(struct hfi1_filedata *fd, struct hfi1_devdata *dd,
943                          struct hfi1_user_info *uinfo,
944                          struct hfi1_ctxtdata **rcd)
945 {
946         struct hfi1_ctxtdata *uctxt;
947         int ret, numa;
948
949         if (dd->flags & HFI1_FROZEN) {
950                 /*
951                  * Pick an error that is unique from all other errors
952                  * that are returned so the user process knows that
953                  * it tried to allocate while the SPC was frozen.  It
954                  * it should be able to retry with success in a short
955                  * while.
956                  */
957                 return -EIO;
958         }
959
960         if (!dd->freectxts)
961                 return -EBUSY;
962
963         /*
964          * If we don't have a NUMA node requested, preference is towards
965          * device NUMA node.
966          */
967         fd->rec_cpu_num = hfi1_get_proc_affinity(dd->node);
968         if (fd->rec_cpu_num != -1)
969                 numa = cpu_to_node(fd->rec_cpu_num);
970         else
971                 numa = numa_node_id();
972         ret = hfi1_create_ctxtdata(dd->pport, numa, &uctxt);
973         if (ret < 0) {
974                 dd_dev_err(dd, "user ctxtdata allocation failed\n");
975                 return ret;
976         }
977         hfi1_cdbg(PROC, "[%u:%u] pid %u assigned to CPU %d (NUMA %u)",
978                   uctxt->ctxt, fd->subctxt, current->pid, fd->rec_cpu_num,
979                   uctxt->numa_id);
980
981         /*
982          * Allocate and enable a PIO send context.
983          */
984         uctxt->sc = sc_alloc(dd, SC_USER, uctxt->rcvhdrqentsize, dd->node);
985         if (!uctxt->sc) {
986                 ret = -ENOMEM;
987                 goto ctxdata_free;
988         }
989         hfi1_cdbg(PROC, "allocated send context %u(%u)\n", uctxt->sc->sw_index,
990                   uctxt->sc->hw_context);
991         ret = sc_enable(uctxt->sc);
992         if (ret)
993                 goto ctxdata_free;
994
995         /*
996          * Setup sub context information if the user-level has requested
997          * sub contexts.
998          * This has to be done here so the rest of the sub-contexts find the
999          * proper base context.
1000          * NOTE: _set_bit() can be used here because the context creation is
1001          * protected by the mutex (rather than the spin_lock), and will be the
1002          * very first instance of this context.
1003          */
1004         __set_bit(0, uctxt->in_use_ctxts);
1005         if (uinfo->subctxt_cnt)
1006                 init_subctxts(uctxt, uinfo);
1007         uctxt->userversion = uinfo->userversion;
1008         uctxt->flags = hfi1_cap_mask; /* save current flag state */
1009         init_waitqueue_head(&uctxt->wait);
1010         strlcpy(uctxt->comm, current->comm, sizeof(uctxt->comm));
1011         memcpy(uctxt->uuid, uinfo->uuid, sizeof(uctxt->uuid));
1012         uctxt->jkey = generate_jkey(current_uid());
1013         hfi1_stats.sps_ctxts++;
1014         /*
1015          * Disable ASPM when there are open user/PSM contexts to avoid
1016          * issues with ASPM L1 exit latency
1017          */
1018         if (dd->freectxts-- == dd->num_user_contexts)
1019                 aspm_disable_all(dd);
1020
1021         *rcd = uctxt;
1022
1023         return 0;
1024
1025 ctxdata_free:
1026         hfi1_free_ctxt(uctxt);
1027         return ret;
1028 }
1029
1030 static void deallocate_ctxt(struct hfi1_ctxtdata *uctxt)
1031 {
1032         mutex_lock(&hfi1_mutex);
1033         hfi1_stats.sps_ctxts--;
1034         if (++uctxt->dd->freectxts == uctxt->dd->num_user_contexts)
1035                 aspm_enable_all(uctxt->dd);
1036         mutex_unlock(&hfi1_mutex);
1037
1038         hfi1_free_ctxt(uctxt);
1039 }
1040
1041 static void init_subctxts(struct hfi1_ctxtdata *uctxt,
1042                           const struct hfi1_user_info *uinfo)
1043 {
1044         uctxt->subctxt_cnt = uinfo->subctxt_cnt;
1045         uctxt->subctxt_id = uinfo->subctxt_id;
1046         set_bit(HFI1_CTXT_BASE_UNINIT, &uctxt->event_flags);
1047 }
1048
1049 static int setup_subctxt(struct hfi1_ctxtdata *uctxt)
1050 {
1051         int ret = 0;
1052         u16 num_subctxts = uctxt->subctxt_cnt;
1053
1054         uctxt->subctxt_uregbase = vmalloc_user(PAGE_SIZE);
1055         if (!uctxt->subctxt_uregbase)
1056                 return -ENOMEM;
1057
1058         /* We can take the size of the RcvHdr Queue from the master */
1059         uctxt->subctxt_rcvhdr_base = vmalloc_user(rcvhdrq_size(uctxt) *
1060                                                   num_subctxts);
1061         if (!uctxt->subctxt_rcvhdr_base) {
1062                 ret = -ENOMEM;
1063                 goto bail_ureg;
1064         }
1065
1066         uctxt->subctxt_rcvegrbuf = vmalloc_user(uctxt->egrbufs.size *
1067                                                 num_subctxts);
1068         if (!uctxt->subctxt_rcvegrbuf) {
1069                 ret = -ENOMEM;
1070                 goto bail_rhdr;
1071         }
1072
1073         return 0;
1074
1075 bail_rhdr:
1076         vfree(uctxt->subctxt_rcvhdr_base);
1077         uctxt->subctxt_rcvhdr_base = NULL;
1078 bail_ureg:
1079         vfree(uctxt->subctxt_uregbase);
1080         uctxt->subctxt_uregbase = NULL;
1081
1082         return ret;
1083 }
1084
1085 static void user_init(struct hfi1_ctxtdata *uctxt)
1086 {
1087         unsigned int rcvctrl_ops = 0;
1088
1089         /* initialize poll variables... */
1090         uctxt->urgent = 0;
1091         uctxt->urgent_poll = 0;
1092
1093         /*
1094          * Now enable the ctxt for receive.
1095          * For chips that are set to DMA the tail register to memory
1096          * when they change (and when the update bit transitions from
1097          * 0 to 1.  So for those chips, we turn it off and then back on.
1098          * This will (very briefly) affect any other open ctxts, but the
1099          * duration is very short, and therefore isn't an issue.  We
1100          * explicitly set the in-memory tail copy to 0 beforehand, so we
1101          * don't have to wait to be sure the DMA update has happened
1102          * (chip resets head/tail to 0 on transition to enable).
1103          */
1104         if (uctxt->rcvhdrtail_kvaddr)
1105                 clear_rcvhdrtail(uctxt);
1106
1107         /* Setup J_KEY before enabling the context */
1108         hfi1_set_ctxt_jkey(uctxt->dd, uctxt, uctxt->jkey);
1109
1110         rcvctrl_ops = HFI1_RCVCTRL_CTXT_ENB;
1111         if (HFI1_CAP_UGET_MASK(uctxt->flags, HDRSUPP))
1112                 rcvctrl_ops |= HFI1_RCVCTRL_TIDFLOW_ENB;
1113         /*
1114          * Ignore the bit in the flags for now until proper
1115          * support for multiple packet per rcv array entry is
1116          * added.
1117          */
1118         if (!HFI1_CAP_UGET_MASK(uctxt->flags, MULTI_PKT_EGR))
1119                 rcvctrl_ops |= HFI1_RCVCTRL_ONE_PKT_EGR_ENB;
1120         if (HFI1_CAP_UGET_MASK(uctxt->flags, NODROP_EGR_FULL))
1121                 rcvctrl_ops |= HFI1_RCVCTRL_NO_EGR_DROP_ENB;
1122         if (HFI1_CAP_UGET_MASK(uctxt->flags, NODROP_RHQ_FULL))
1123                 rcvctrl_ops |= HFI1_RCVCTRL_NO_RHQ_DROP_ENB;
1124         /*
1125          * The RcvCtxtCtrl.TailUpd bit has to be explicitly written.
1126          * We can't rely on the correct value to be set from prior
1127          * uses of the chip or ctxt. Therefore, add the rcvctrl op
1128          * for both cases.
1129          */
1130         if (HFI1_CAP_UGET_MASK(uctxt->flags, DMA_RTAIL))
1131                 rcvctrl_ops |= HFI1_RCVCTRL_TAILUPD_ENB;
1132         else
1133                 rcvctrl_ops |= HFI1_RCVCTRL_TAILUPD_DIS;
1134         hfi1_rcvctrl(uctxt->dd, rcvctrl_ops, uctxt);
1135 }
1136
1137 static int get_ctxt_info(struct hfi1_filedata *fd, unsigned long arg, u32 len)
1138 {
1139         struct hfi1_ctxt_info cinfo;
1140         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1141
1142         if (sizeof(cinfo) != len)
1143                 return -EINVAL;
1144
1145         memset(&cinfo, 0, sizeof(cinfo));
1146         cinfo.runtime_flags = (((uctxt->flags >> HFI1_CAP_MISC_SHIFT) &
1147                                 HFI1_CAP_MISC_MASK) << HFI1_CAP_USER_SHIFT) |
1148                         HFI1_CAP_UGET_MASK(uctxt->flags, MASK) |
1149                         HFI1_CAP_KGET_MASK(uctxt->flags, K2U);
1150         /* adjust flag if this fd is not able to cache */
1151         if (!fd->handler)
1152                 cinfo.runtime_flags |= HFI1_CAP_TID_UNMAP; /* no caching */
1153
1154         cinfo.num_active = hfi1_count_active_units();
1155         cinfo.unit = uctxt->dd->unit;
1156         cinfo.ctxt = uctxt->ctxt;
1157         cinfo.subctxt = fd->subctxt;
1158         cinfo.rcvtids = roundup(uctxt->egrbufs.alloced,
1159                                 uctxt->dd->rcv_entries.group_size) +
1160                 uctxt->expected_count;
1161         cinfo.credits = uctxt->sc->credits;
1162         cinfo.numa_node = uctxt->numa_id;
1163         cinfo.rec_cpu = fd->rec_cpu_num;
1164         cinfo.send_ctxt = uctxt->sc->hw_context;
1165
1166         cinfo.egrtids = uctxt->egrbufs.alloced;
1167         cinfo.rcvhdrq_cnt = uctxt->rcvhdrq_cnt;
1168         cinfo.rcvhdrq_entsize = uctxt->rcvhdrqentsize << 2;
1169         cinfo.sdma_ring_size = fd->cq->nentries;
1170         cinfo.rcvegr_size = uctxt->egrbufs.rcvtid_size;
1171
1172         trace_hfi1_ctxt_info(uctxt->dd, uctxt->ctxt, fd->subctxt, &cinfo);
1173         if (copy_to_user((void __user *)arg, &cinfo, len))
1174                 return -EFAULT;
1175
1176         return 0;
1177 }
1178
1179 static int init_user_ctxt(struct hfi1_filedata *fd,
1180                           struct hfi1_ctxtdata *uctxt)
1181 {
1182         int ret;
1183
1184         ret = hfi1_user_sdma_alloc_queues(uctxt, fd);
1185         if (ret)
1186                 return ret;
1187
1188         ret = hfi1_user_exp_rcv_init(fd, uctxt);
1189         if (ret)
1190                 hfi1_user_sdma_free_queues(fd, uctxt);
1191
1192         return ret;
1193 }
1194
1195 static int setup_base_ctxt(struct hfi1_filedata *fd,
1196                            struct hfi1_ctxtdata *uctxt)
1197 {
1198         struct hfi1_devdata *dd = uctxt->dd;
1199         int ret = 0;
1200
1201         hfi1_init_ctxt(uctxt->sc);
1202
1203         /* Now allocate the RcvHdr queue and eager buffers. */
1204         ret = hfi1_create_rcvhdrq(dd, uctxt);
1205         if (ret)
1206                 goto done;
1207
1208         ret = hfi1_setup_eagerbufs(uctxt);
1209         if (ret)
1210                 goto done;
1211
1212         /* If sub-contexts are enabled, do the appropriate setup */
1213         if (uctxt->subctxt_cnt)
1214                 ret = setup_subctxt(uctxt);
1215         if (ret)
1216                 goto done;
1217
1218         ret = hfi1_alloc_ctxt_rcv_groups(uctxt);
1219         if (ret)
1220                 goto done;
1221
1222         ret = init_user_ctxt(fd, uctxt);
1223         if (ret)
1224                 goto done;
1225
1226         user_init(uctxt);
1227
1228         /* Now that the context is set up, the fd can get a reference. */
1229         fd->uctxt = uctxt;
1230         hfi1_rcd_get(uctxt);
1231
1232 done:
1233         if (uctxt->subctxt_cnt) {
1234                 /*
1235                  * On error, set the failed bit so sub-contexts will clean up
1236                  * correctly.
1237                  */
1238                 if (ret)
1239                         set_bit(HFI1_CTXT_BASE_FAILED, &uctxt->event_flags);
1240
1241                 /*
1242                  * Base context is done (successfully or not), notify anybody
1243                  * using a sub-context that is waiting for this completion.
1244                  */
1245                 clear_bit(HFI1_CTXT_BASE_UNINIT, &uctxt->event_flags);
1246                 wake_up(&uctxt->wait);
1247         }
1248
1249         return ret;
1250 }
1251
1252 static int get_base_info(struct hfi1_filedata *fd, unsigned long arg, u32 len)
1253 {
1254         struct hfi1_base_info binfo;
1255         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1256         struct hfi1_devdata *dd = uctxt->dd;
1257         unsigned offset;
1258
1259         trace_hfi1_uctxtdata(uctxt->dd, uctxt, fd->subctxt);
1260
1261         if (sizeof(binfo) != len)
1262                 return -EINVAL;
1263
1264         memset(&binfo, 0, sizeof(binfo));
1265         binfo.hw_version = dd->revision;
1266         binfo.sw_version = HFI1_KERN_SWVERSION;
1267         binfo.bthqp = kdeth_qp;
1268         binfo.jkey = uctxt->jkey;
1269         /*
1270          * If more than 64 contexts are enabled the allocated credit
1271          * return will span two or three contiguous pages. Since we only
1272          * map the page containing the context's credit return address,
1273          * we need to calculate the offset in the proper page.
1274          */
1275         offset = ((u64)uctxt->sc->hw_free -
1276                   (u64)dd->cr_base[uctxt->numa_id].va) % PAGE_SIZE;
1277         binfo.sc_credits_addr = HFI1_MMAP_TOKEN(PIO_CRED, uctxt->ctxt,
1278                                                 fd->subctxt, offset);
1279         binfo.pio_bufbase = HFI1_MMAP_TOKEN(PIO_BUFS, uctxt->ctxt,
1280                                             fd->subctxt,
1281                                             uctxt->sc->base_addr);
1282         binfo.pio_bufbase_sop = HFI1_MMAP_TOKEN(PIO_BUFS_SOP,
1283                                                 uctxt->ctxt,
1284                                                 fd->subctxt,
1285                                                 uctxt->sc->base_addr);
1286         binfo.rcvhdr_bufbase = HFI1_MMAP_TOKEN(RCV_HDRQ, uctxt->ctxt,
1287                                                fd->subctxt,
1288                                                uctxt->rcvhdrq);
1289         binfo.rcvegr_bufbase = HFI1_MMAP_TOKEN(RCV_EGRBUF, uctxt->ctxt,
1290                                                fd->subctxt,
1291                                                uctxt->egrbufs.rcvtids[0].dma);
1292         binfo.sdma_comp_bufbase = HFI1_MMAP_TOKEN(SDMA_COMP, uctxt->ctxt,
1293                                                   fd->subctxt, 0);
1294         /*
1295          * user regs are at
1296          * (RXE_PER_CONTEXT_USER + (ctxt * RXE_PER_CONTEXT_SIZE))
1297          */
1298         binfo.user_regbase = HFI1_MMAP_TOKEN(UREGS, uctxt->ctxt,
1299                                              fd->subctxt, 0);
1300         offset = offset_in_page((uctxt_offset(uctxt) + fd->subctxt) *
1301                                 sizeof(*dd->events));
1302         binfo.events_bufbase = HFI1_MMAP_TOKEN(EVENTS, uctxt->ctxt,
1303                                                fd->subctxt,
1304                                                offset);
1305         binfo.status_bufbase = HFI1_MMAP_TOKEN(STATUS, uctxt->ctxt,
1306                                                fd->subctxt,
1307                                                dd->status);
1308         if (HFI1_CAP_IS_USET(DMA_RTAIL))
1309                 binfo.rcvhdrtail_base = HFI1_MMAP_TOKEN(RTAIL, uctxt->ctxt,
1310                                                         fd->subctxt, 0);
1311         if (uctxt->subctxt_cnt) {
1312                 binfo.subctxt_uregbase = HFI1_MMAP_TOKEN(SUBCTXT_UREGS,
1313                                                          uctxt->ctxt,
1314                                                          fd->subctxt, 0);
1315                 binfo.subctxt_rcvhdrbuf = HFI1_MMAP_TOKEN(SUBCTXT_RCV_HDRQ,
1316                                                           uctxt->ctxt,
1317                                                           fd->subctxt, 0);
1318                 binfo.subctxt_rcvegrbuf = HFI1_MMAP_TOKEN(SUBCTXT_EGRBUF,
1319                                                           uctxt->ctxt,
1320                                                           fd->subctxt, 0);
1321         }
1322
1323         if (copy_to_user((void __user *)arg, &binfo, len))
1324                 return -EFAULT;
1325
1326         return 0;
1327 }
1328
1329 /**
1330  * user_exp_rcv_setup - Set up the given tid rcv list
1331  * @fd: file data of the current driver instance
1332  * @arg: ioctl argumnent for user space information
1333  * @len: length of data structure associated with ioctl command
1334  *
1335  * Wrapper to validate ioctl information before doing _rcv_setup.
1336  *
1337  */
1338 static int user_exp_rcv_setup(struct hfi1_filedata *fd, unsigned long arg,
1339                               u32 len)
1340 {
1341         int ret;
1342         unsigned long addr;
1343         struct hfi1_tid_info tinfo;
1344
1345         if (sizeof(tinfo) != len)
1346                 return -EINVAL;
1347
1348         if (copy_from_user(&tinfo, (void __user *)arg, (sizeof(tinfo))))
1349                 return -EFAULT;
1350
1351         ret = hfi1_user_exp_rcv_setup(fd, &tinfo);
1352         if (!ret) {
1353                 /*
1354                  * Copy the number of tidlist entries we used
1355                  * and the length of the buffer we registered.
1356                  */
1357                 addr = arg + offsetof(struct hfi1_tid_info, tidcnt);
1358                 if (copy_to_user((void __user *)addr, &tinfo.tidcnt,
1359                                  sizeof(tinfo.tidcnt)))
1360                         return -EFAULT;
1361
1362                 addr = arg + offsetof(struct hfi1_tid_info, length);
1363                 if (copy_to_user((void __user *)addr, &tinfo.length,
1364                                  sizeof(tinfo.length)))
1365                         ret = -EFAULT;
1366         }
1367
1368         return ret;
1369 }
1370
1371 /**
1372  * user_exp_rcv_clear - Clear the given tid rcv list
1373  * @fd: file data of the current driver instance
1374  * @arg: ioctl argumnent for user space information
1375  * @len: length of data structure associated with ioctl command
1376  *
1377  * The hfi1_user_exp_rcv_clear() can be called from the error path.  Because
1378  * of this, we need to use this wrapper to copy the user space information
1379  * before doing the clear.
1380  */
1381 static int user_exp_rcv_clear(struct hfi1_filedata *fd, unsigned long arg,
1382                               u32 len)
1383 {
1384         int ret;
1385         unsigned long addr;
1386         struct hfi1_tid_info tinfo;
1387
1388         if (sizeof(tinfo) != len)
1389                 return -EINVAL;
1390
1391         if (copy_from_user(&tinfo, (void __user *)arg, (sizeof(tinfo))))
1392                 return -EFAULT;
1393
1394         ret = hfi1_user_exp_rcv_clear(fd, &tinfo);
1395         if (!ret) {
1396                 addr = arg + offsetof(struct hfi1_tid_info, tidcnt);
1397                 if (copy_to_user((void __user *)addr, &tinfo.tidcnt,
1398                                  sizeof(tinfo.tidcnt)))
1399                         return -EFAULT;
1400         }
1401
1402         return ret;
1403 }
1404
1405 /**
1406  * user_exp_rcv_invalid - Invalidate the given tid rcv list
1407  * @fd: file data of the current driver instance
1408  * @arg: ioctl argumnent for user space information
1409  * @len: length of data structure associated with ioctl command
1410  *
1411  * Wrapper to validate ioctl information before doing _rcv_invalid.
1412  *
1413  */
1414 static int user_exp_rcv_invalid(struct hfi1_filedata *fd, unsigned long arg,
1415                                 u32 len)
1416 {
1417         int ret;
1418         unsigned long addr;
1419         struct hfi1_tid_info tinfo;
1420
1421         if (sizeof(tinfo) != len)
1422                 return -EINVAL;
1423
1424         if (!fd->invalid_tids)
1425                 return -EINVAL;
1426
1427         if (copy_from_user(&tinfo, (void __user *)arg, (sizeof(tinfo))))
1428                 return -EFAULT;
1429
1430         ret = hfi1_user_exp_rcv_invalid(fd, &tinfo);
1431         if (ret)
1432                 return ret;
1433
1434         addr = arg + offsetof(struct hfi1_tid_info, tidcnt);
1435         if (copy_to_user((void __user *)addr, &tinfo.tidcnt,
1436                          sizeof(tinfo.tidcnt)))
1437                 ret = -EFAULT;
1438
1439         return ret;
1440 }
1441
1442 static __poll_t poll_urgent(struct file *fp,
1443                                 struct poll_table_struct *pt)
1444 {
1445         struct hfi1_filedata *fd = fp->private_data;
1446         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1447         struct hfi1_devdata *dd = uctxt->dd;
1448         __poll_t pollflag;
1449
1450         poll_wait(fp, &uctxt->wait, pt);
1451
1452         spin_lock_irq(&dd->uctxt_lock);
1453         if (uctxt->urgent != uctxt->urgent_poll) {
1454                 pollflag = EPOLLIN | EPOLLRDNORM;
1455                 uctxt->urgent_poll = uctxt->urgent;
1456         } else {
1457                 pollflag = 0;
1458                 set_bit(HFI1_CTXT_WAITING_URG, &uctxt->event_flags);
1459         }
1460         spin_unlock_irq(&dd->uctxt_lock);
1461
1462         return pollflag;
1463 }
1464
1465 static __poll_t poll_next(struct file *fp,
1466                               struct poll_table_struct *pt)
1467 {
1468         struct hfi1_filedata *fd = fp->private_data;
1469         struct hfi1_ctxtdata *uctxt = fd->uctxt;
1470         struct hfi1_devdata *dd = uctxt->dd;
1471         __poll_t pollflag;
1472
1473         poll_wait(fp, &uctxt->wait, pt);
1474
1475         spin_lock_irq(&dd->uctxt_lock);
1476         if (hdrqempty(uctxt)) {
1477                 set_bit(HFI1_CTXT_WAITING_RCV, &uctxt->event_flags);
1478                 hfi1_rcvctrl(dd, HFI1_RCVCTRL_INTRAVAIL_ENB, uctxt);
1479                 pollflag = 0;
1480         } else {
1481                 pollflag = EPOLLIN | EPOLLRDNORM;
1482         }
1483         spin_unlock_irq(&dd->uctxt_lock);
1484
1485         return pollflag;
1486 }
1487
1488 /*
1489  * Find all user contexts in use, and set the specified bit in their
1490  * event mask.
1491  * See also find_ctxt() for a similar use, that is specific to send buffers.
1492  */
1493 int hfi1_set_uevent_bits(struct hfi1_pportdata *ppd, const int evtbit)
1494 {
1495         struct hfi1_ctxtdata *uctxt;
1496         struct hfi1_devdata *dd = ppd->dd;
1497         u16 ctxt;
1498
1499         if (!dd->events)
1500                 return -EINVAL;
1501
1502         for (ctxt = dd->first_dyn_alloc_ctxt; ctxt < dd->num_rcv_contexts;
1503              ctxt++) {
1504                 uctxt = hfi1_rcd_get_by_index(dd, ctxt);
1505                 if (uctxt) {
1506                         unsigned long *evs;
1507                         int i;
1508                         /*
1509                          * subctxt_cnt is 0 if not shared, so do base
1510                          * separately, first, then remaining subctxt, if any
1511                          */
1512                         evs = dd->events + uctxt_offset(uctxt);
1513                         set_bit(evtbit, evs);
1514                         for (i = 1; i < uctxt->subctxt_cnt; i++)
1515                                 set_bit(evtbit, evs + i);
1516                         hfi1_rcd_put(uctxt);
1517                 }
1518         }
1519
1520         return 0;
1521 }
1522
1523 /**
1524  * manage_rcvq - manage a context's receive queue
1525  * @uctxt: the context
1526  * @subctxt: the sub-context
1527  * @start_stop: action to carry out
1528  *
1529  * start_stop == 0 disables receive on the context, for use in queue
1530  * overflow conditions.  start_stop==1 re-enables, to be used to
1531  * re-init the software copy of the head register
1532  */
1533 static int manage_rcvq(struct hfi1_ctxtdata *uctxt, u16 subctxt,
1534                        unsigned long arg)
1535 {
1536         struct hfi1_devdata *dd = uctxt->dd;
1537         unsigned int rcvctrl_op;
1538         int start_stop;
1539
1540         if (subctxt)
1541                 return 0;
1542
1543         if (get_user(start_stop, (int __user *)arg))
1544                 return -EFAULT;
1545
1546         /* atomically clear receive enable ctxt. */
1547         if (start_stop) {
1548                 /*
1549                  * On enable, force in-memory copy of the tail register to
1550                  * 0, so that protocol code doesn't have to worry about
1551                  * whether or not the chip has yet updated the in-memory
1552                  * copy or not on return from the system call. The chip
1553                  * always resets it's tail register back to 0 on a
1554                  * transition from disabled to enabled.
1555                  */
1556                 if (uctxt->rcvhdrtail_kvaddr)
1557                         clear_rcvhdrtail(uctxt);
1558                 rcvctrl_op = HFI1_RCVCTRL_CTXT_ENB;
1559         } else {
1560                 rcvctrl_op = HFI1_RCVCTRL_CTXT_DIS;
1561         }
1562         hfi1_rcvctrl(dd, rcvctrl_op, uctxt);
1563         /* always; new head should be equal to new tail; see above */
1564
1565         return 0;
1566 }
1567
1568 /*
1569  * clear the event notifier events for this context.
1570  * User process then performs actions appropriate to bit having been
1571  * set, if desired, and checks again in future.
1572  */
1573 static int user_event_ack(struct hfi1_ctxtdata *uctxt, u16 subctxt,
1574                           unsigned long arg)
1575 {
1576         int i;
1577         struct hfi1_devdata *dd = uctxt->dd;
1578         unsigned long *evs;
1579         unsigned long events;
1580
1581         if (!dd->events)
1582                 return 0;
1583
1584         if (get_user(events, (unsigned long __user *)arg))
1585                 return -EFAULT;
1586
1587         evs = dd->events + uctxt_offset(uctxt) + subctxt;
1588
1589         for (i = 0; i <= _HFI1_MAX_EVENT_BIT; i++) {
1590                 if (!test_bit(i, &events))
1591                         continue;
1592                 clear_bit(i, evs);
1593         }
1594         return 0;
1595 }
1596
1597 static int set_ctxt_pkey(struct hfi1_ctxtdata *uctxt, unsigned long arg)
1598 {
1599         int i;
1600         struct hfi1_pportdata *ppd = uctxt->ppd;
1601         struct hfi1_devdata *dd = uctxt->dd;
1602         u16 pkey;
1603
1604         if (!HFI1_CAP_IS_USET(PKEY_CHECK))
1605                 return -EPERM;
1606
1607         if (get_user(pkey, (u16 __user *)arg))
1608                 return -EFAULT;
1609
1610         if (pkey == LIM_MGMT_P_KEY || pkey == FULL_MGMT_P_KEY)
1611                 return -EINVAL;
1612
1613         for (i = 0; i < ARRAY_SIZE(ppd->pkeys); i++)
1614                 if (pkey == ppd->pkeys[i])
1615                         return hfi1_set_ctxt_pkey(dd, uctxt, pkey);
1616
1617         return -ENOENT;
1618 }
1619
1620 /**
1621  * ctxt_reset - Reset the user context
1622  * @uctxt: valid user context
1623  */
1624 static int ctxt_reset(struct hfi1_ctxtdata *uctxt)
1625 {
1626         struct send_context *sc;
1627         struct hfi1_devdata *dd;
1628         int ret = 0;
1629
1630         if (!uctxt || !uctxt->dd || !uctxt->sc)
1631                 return -EINVAL;
1632
1633         /*
1634          * There is no protection here. User level has to guarantee that
1635          * no one will be writing to the send context while it is being
1636          * re-initialized.  If user level breaks that guarantee, it will
1637          * break it's own context and no one else's.
1638          */
1639         dd = uctxt->dd;
1640         sc = uctxt->sc;
1641
1642         /*
1643          * Wait until the interrupt handler has marked the context as
1644          * halted or frozen. Report error if we time out.
1645          */
1646         wait_event_interruptible_timeout(
1647                 sc->halt_wait, (sc->flags & SCF_HALTED),
1648                 msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT));
1649         if (!(sc->flags & SCF_HALTED))
1650                 return -ENOLCK;
1651
1652         /*
1653          * If the send context was halted due to a Freeze, wait until the
1654          * device has been "unfrozen" before resetting the context.
1655          */
1656         if (sc->flags & SCF_FROZEN) {
1657                 wait_event_interruptible_timeout(
1658                         dd->event_queue,
1659                         !(READ_ONCE(dd->flags) & HFI1_FROZEN),
1660                         msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT));
1661                 if (dd->flags & HFI1_FROZEN)
1662                         return -ENOLCK;
1663
1664                 if (dd->flags & HFI1_FORCED_FREEZE)
1665                         /*
1666                          * Don't allow context reset if we are into
1667                          * forced freeze
1668                          */
1669                         return -ENODEV;
1670
1671                 sc_disable(sc);
1672                 ret = sc_enable(sc);
1673                 hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_ENB, uctxt);
1674         } else {
1675                 ret = sc_restart(sc);
1676         }
1677         if (!ret)
1678                 sc_return_credits(sc);
1679
1680         return ret;
1681 }
1682
1683 static void user_remove(struct hfi1_devdata *dd)
1684 {
1685
1686         hfi1_cdev_cleanup(&dd->user_cdev, &dd->user_device);
1687 }
1688
1689 static int user_add(struct hfi1_devdata *dd)
1690 {
1691         char name[10];
1692         int ret;
1693
1694         snprintf(name, sizeof(name), "%s_%d", class_name(), dd->unit);
1695         ret = hfi1_cdev_init(dd->unit, name, &hfi1_file_ops,
1696                              &dd->user_cdev, &dd->user_device,
1697                              true, &dd->kobj);
1698         if (ret)
1699                 user_remove(dd);
1700
1701         return ret;
1702 }
1703
1704 /*
1705  * Create per-unit files in /dev
1706  */
1707 int hfi1_device_create(struct hfi1_devdata *dd)
1708 {
1709         return user_add(dd);
1710 }
1711
1712 /*
1713  * Remove per-unit files in /dev
1714  * void, core kernel returns no errors for this stuff
1715  */
1716 void hfi1_device_remove(struct hfi1_devdata *dd)
1717 {
1718         user_remove(dd);
1719 }