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