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