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