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