user_sdma.c 47.9 KB
Newer Older
M
Mike Marciniszyn 已提交
1
/*
J
Jubin John 已提交
2
 * Copyright(c) 2015, 2016 Intel Corporation.
M
Mike Marciniszyn 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
 *
 * This file is provided under a dual BSD/GPLv2 license.  When using or
 * redistributing this file, you may do so under either license.
 *
 * GPL LICENSE SUMMARY
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * BSD LICENSE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  - Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  - Neither the name of Intel Corporation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/dmapool.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/highmem.h>
#include <linux/io.h>
#include <linux/uio.h>
#include <linux/rbtree.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/mmu_context.h>
#include <linux/module.h>
#include <linux/vmalloc.h>

#include "hfi.h"
#include "sdma.h"
#include "user_sdma.h"
#include "verbs.h"  /* for the headers */
#include "common.h" /* for struct hfi1_tid_info */
#include "trace.h"
70
#include "mmu_rb.h"
M
Mike Marciniszyn 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

static uint hfi1_sdma_comp_ring_size = 128;
module_param_named(sdma_comp_size, hfi1_sdma_comp_ring_size, uint, S_IRUGO);
MODULE_PARM_DESC(sdma_comp_size, "Size of User SDMA completion ring. Default: 128");

/* The maximum number of Data io vectors per message/request */
#define MAX_VECTORS_PER_REQ 8
/*
 * Maximum number of packet to send from each message/request
 * before moving to the next one.
 */
#define MAX_PKTS_PER_QUEUE 16

#define num_pages(x) (1 + ((((x) - 1) & PAGE_MASK) >> PAGE_SHIFT))

#define req_opcode(x) \
	(((x) >> HFI1_SDMA_REQ_OPCODE_SHIFT) & HFI1_SDMA_REQ_OPCODE_MASK)
#define req_version(x) \
	(((x) >> HFI1_SDMA_REQ_VERSION_SHIFT) & HFI1_SDMA_REQ_OPCODE_MASK)
#define req_iovcnt(x) \
	(((x) >> HFI1_SDMA_REQ_IOVCNT_SHIFT) & HFI1_SDMA_REQ_IOVCNT_MASK)

/* Number of BTH.PSN bits used for sequence number in expected rcvs */
#define BTH_SEQ_MASK 0x7ffull

/*
 * Define fields in the KDETH header so we can update the header
 * template.
 */
#define KDETH_OFFSET_SHIFT        0
#define KDETH_OFFSET_MASK         0x7fff
#define KDETH_OM_SHIFT            15
#define KDETH_OM_MASK             0x1
#define KDETH_TID_SHIFT           16
#define KDETH_TID_MASK            0x3ff
#define KDETH_TIDCTRL_SHIFT       26
#define KDETH_TIDCTRL_MASK        0x3
#define KDETH_INTR_SHIFT          28
#define KDETH_INTR_MASK           0x1
#define KDETH_SH_SHIFT            29
#define KDETH_SH_MASK             0x1
#define KDETH_HCRC_UPPER_SHIFT    16
#define KDETH_HCRC_UPPER_MASK     0xff
#define KDETH_HCRC_LOWER_SHIFT    24
#define KDETH_HCRC_LOWER_MASK     0xff

#define PBC2LRH(x) ((((x) & 0xfff) << 2) - 4)
#define LRH2PBC(x) ((((x) >> 2) + 1) & 0xfff)

#define KDETH_GET(val, field)						\
	(((le32_to_cpu((val))) >> KDETH_##field##_SHIFT) & KDETH_##field##_MASK)
#define KDETH_SET(dw, field, val) do {					\
		u32 dwval = le32_to_cpu(dw);				\
		dwval &= ~(KDETH_##field##_MASK << KDETH_##field##_SHIFT); \
		dwval |= (((val) & KDETH_##field##_MASK) << \
			  KDETH_##field##_SHIFT);			\
		dw = cpu_to_le32(dwval);				\
	} while (0)

#define AHG_HEADER_SET(arr, idx, dw, bit, width, value)			\
	do {								\
		if ((idx) < ARRAY_SIZE((arr)))				\
			(arr)[(idx++)] = sdma_build_ahg_descriptor(	\
				(__force u16)(value), (dw), (bit),	\
							(width));	\
		else							\
			return -ERANGE;					\
	} while (0)

/* KDETH OM multipliers and switch over point */
#define KDETH_OM_SMALL     4
#define KDETH_OM_LARGE     64
#define KDETH_OM_MAX_SIZE  (1 << ((KDETH_OM_LARGE / KDETH_OM_SMALL) + 1))

/* Last packet in the request */
146
#define TXREQ_FLAGS_REQ_LAST_PKT BIT(0)
M
Mike Marciniszyn 已提交
147 148 149 150 151 152 153 154

#define SDMA_REQ_IN_USE     0
#define SDMA_REQ_FOR_THREAD 1
#define SDMA_REQ_SEND_DONE  2
#define SDMA_REQ_HAVE_AHG   3
#define SDMA_REQ_HAS_ERROR  4
#define SDMA_REQ_DONE_ERROR 5

155 156 157
#define SDMA_PKT_Q_INACTIVE BIT(0)
#define SDMA_PKT_Q_ACTIVE   BIT(1)
#define SDMA_PKT_Q_DEFERRED BIT(2)
M
Mike Marciniszyn 已提交
158 159 160 161 162 163 164 165 166 167 168

/*
 * Maximum retry attempts to submit a TX request
 * before putting the process to sleep.
 */
#define MAX_DEFER_RETRY_COUNT 1

static unsigned initial_pkt_count = 8;

#define SDMA_IOWAIT_TIMEOUT 1000 /* in milliseconds */

169 170
struct sdma_mmu_node;

M
Mike Marciniszyn 已提交
171
struct user_sdma_iovec {
172
	struct list_head list;
M
Mike Marciniszyn 已提交
173 174 175 176 177
	struct iovec iov;
	/* number of pages in this vector */
	unsigned npages;
	/* array of pinned pages for this vector */
	struct page **pages;
178 179 180 181
	/*
	 * offset into the virtual address space of the vector at
	 * which we last left off.
	 */
M
Mike Marciniszyn 已提交
182
	u64 offset;
183
	struct sdma_mmu_node *node;
M
Mike Marciniszyn 已提交
184 185
};

186
#define SDMA_CACHE_NODE_EVICT 0
187

188 189
struct sdma_mmu_node {
	struct mmu_rb_node rb;
190 191
	struct list_head list;
	struct hfi1_user_sdma_pkt_q *pq;
192 193 194
	atomic_t refcount;
	struct page **pages;
	unsigned npages;
195
	unsigned long flags;
196 197
};

M
Mike Marciniszyn 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
struct user_sdma_request {
	struct sdma_req_info info;
	struct hfi1_user_sdma_pkt_q *pq;
	struct hfi1_user_sdma_comp_q *cq;
	/* This is the original header from user space */
	struct hfi1_pkt_header hdr;
	/*
	 * Pointer to the SDMA engine for this request.
	 * Since different request could be on different VLs,
	 * each request will need it's own engine pointer.
	 */
	struct sdma_engine *sde;
	u8 ahg_idx;
	u32 ahg[9];
	/*
	 * KDETH.Offset (Eager) field
	 * We need to remember the initial value so the headers
	 * can be updated properly.
	 */
	u32 koffset;
	/*
	 * KDETH.OFFSET (TID) field
	 * The offset can cover multiple packets, depending on the
	 * size of the TID entry.
	 */
	u32 tidoffset;
	/*
	 * KDETH.OM
	 * Remember this because the header template always sets it
	 * to 0.
	 */
	u8 omfactor;
	/*
	 * We copy the iovs for this request (based on
	 * info.iovcnt). These are only the data vectors
	 */
	unsigned data_iovs;
	/* total length of the data in the request */
	u32 data_len;
	/* progress index moving along the iovs array */
	unsigned iov_idx;
	struct user_sdma_iovec iovs[MAX_VECTORS_PER_REQ];
	/* number of elements copied to the tids array */
	u16 n_tids;
	/* TID array values copied from the tid_iov vector */
	u32 *tids;
	u16 tididx;
	u32 sent;
	u64 seqnum;
247
	u64 seqcomp;
248
	u64 seqsubmitted;
M
Mike Marciniszyn 已提交
249 250
	struct list_head txps;
	unsigned long flags;
251 252
	/* status of the last txreq completed */
	int status;
M
Mike Marciniszyn 已提交
253 254
};

255 256 257 258 259 260
/*
 * A single txreq could span up to 3 physical pages when the MTU
 * is sufficiently large (> 4K). Each of the IOV pointers also
 * needs it's own set of flags so the vector has been handled
 * independently of each other.
 */
M
Mike Marciniszyn 已提交
261 262 263 264
struct user_sdma_txreq {
	/* Packet header for the txreq */
	struct hfi1_pkt_header hdr;
	struct sdma_txreq txreq;
265
	struct list_head list;
M
Mike Marciniszyn 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
	struct user_sdma_request *req;
	u16 flags;
	unsigned busycount;
	u64 seqnum;
};

#define SDMA_DBG(req, fmt, ...)				     \
	hfi1_cdbg(SDMA, "[%u:%u:%u:%u] " fmt, (req)->pq->dd->unit, \
		 (req)->pq->ctxt, (req)->pq->subctxt, (req)->info.comp_idx, \
		 ##__VA_ARGS__)
#define SDMA_Q_DBG(pq, fmt, ...)			 \
	hfi1_cdbg(SDMA, "[%u:%u:%u] " fmt, (pq)->dd->unit, (pq)->ctxt, \
		 (pq)->subctxt, ##__VA_ARGS__)

static int user_sdma_send_pkts(struct user_sdma_request *, unsigned);
static int num_user_pages(const struct iovec *);
282
static void user_sdma_txreq_cb(struct sdma_txreq *, int);
283 284
static inline void pq_update(struct hfi1_user_sdma_pkt_q *);
static void user_sdma_free_request(struct user_sdma_request *, bool);
M
Mike Marciniszyn 已提交
285 286
static int pin_vector_pages(struct user_sdma_request *,
			    struct user_sdma_iovec *);
287 288
static void unpin_vector_pages(struct mm_struct *, struct page **, unsigned,
			       unsigned);
M
Mike Marciniszyn 已提交
289 290 291 292 293 294
static int check_header_template(struct user_sdma_request *,
				 struct hfi1_pkt_header *, u32, u32);
static int set_txreq_header(struct user_sdma_request *,
			    struct user_sdma_txreq *, u32);
static int set_txreq_header_ahg(struct user_sdma_request *,
				struct user_sdma_txreq *, u32);
295 296 297
static inline void set_comp_state(struct hfi1_user_sdma_pkt_q *,
				  struct hfi1_user_sdma_comp_q *,
				  u16, enum hfi1_sdma_comp_state, int);
M
Mike Marciniszyn 已提交
298 299 300 301 302 303 304 305 306
static inline u32 set_pkt_bth_psn(__be32, u8, u32);
static inline u32 get_lrh_len(struct hfi1_pkt_header, u32 len);

static int defer_packet_queue(
	struct sdma_engine *,
	struct iowait *,
	struct sdma_txreq *,
	unsigned seq);
static void activate_packet_queue(struct iowait *, int);
307 308
static bool sdma_rb_filter(struct mmu_rb_node *, unsigned long, unsigned long);
static int sdma_rb_insert(struct rb_root *, struct mmu_rb_node *);
309 310
static void sdma_rb_remove(struct rb_root *, struct mmu_rb_node *,
			   struct mm_struct *);
311 312 313 314 315 316 317 318
static int sdma_rb_invalidate(struct rb_root *, struct mmu_rb_node *);

static struct mmu_rb_ops sdma_rb_ops = {
	.filter = sdma_rb_filter,
	.insert = sdma_rb_insert,
	.remove = sdma_rb_remove,
	.invalidate = sdma_rb_invalidate
};
M
Mike Marciniszyn 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360

static int defer_packet_queue(
	struct sdma_engine *sde,
	struct iowait *wait,
	struct sdma_txreq *txreq,
	unsigned seq)
{
	struct hfi1_user_sdma_pkt_q *pq =
		container_of(wait, struct hfi1_user_sdma_pkt_q, busy);
	struct hfi1_ibdev *dev = &pq->dd->verbs_dev;
	struct user_sdma_txreq *tx =
		container_of(txreq, struct user_sdma_txreq, txreq);

	if (sdma_progress(sde, seq, txreq)) {
		if (tx->busycount++ < MAX_DEFER_RETRY_COUNT)
			goto eagain;
	}
	/*
	 * We are assuming that if the list is enqueued somewhere, it
	 * is to the dmawait list since that is the only place where
	 * it is supposed to be enqueued.
	 */
	xchg(&pq->state, SDMA_PKT_Q_DEFERRED);
	write_seqlock(&dev->iowait_lock);
	if (list_empty(&pq->busy.list))
		list_add_tail(&pq->busy.list, &sde->dmawait);
	write_sequnlock(&dev->iowait_lock);
	return -EBUSY;
eagain:
	return -EAGAIN;
}

static void activate_packet_queue(struct iowait *wait, int reason)
{
	struct hfi1_user_sdma_pkt_q *pq =
		container_of(wait, struct hfi1_user_sdma_pkt_q, busy);
	xchg(&pq->state, SDMA_PKT_Q_ACTIVE);
	wake_up(&wait->wait_dma);
};

static void sdma_kmem_cache_ctor(void *obj)
{
361
	struct user_sdma_txreq *tx = obj;
M
Mike Marciniszyn 已提交
362 363 364 365 366 367

	memset(tx, 0, sizeof(*tx));
}

int hfi1_user_sdma_alloc_queues(struct hfi1_ctxtdata *uctxt, struct file *fp)
{
368
	struct hfi1_filedata *fd;
M
Mike Marciniszyn 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381
	int ret = 0;
	unsigned memsize;
	char buf[64];
	struct hfi1_devdata *dd;
	struct hfi1_user_sdma_comp_q *cq;
	struct hfi1_user_sdma_pkt_q *pq;
	unsigned long flags;

	if (!uctxt || !fp) {
		ret = -EBADF;
		goto done;
	}

382 383
	fd = fp->private_data;

M
Mike Marciniszyn 已提交
384 385 386 387 388 389 390 391
	if (!hfi1_sdma_comp_ring_size) {
		ret = -EINVAL;
		goto done;
	}

	dd = uctxt->dd;

	pq = kzalloc(sizeof(*pq), GFP_KERNEL);
392
	if (!pq)
M
Mike Marciniszyn 已提交
393
		goto pq_nomem;
394

M
Mike Marciniszyn 已提交
395
	memsize = sizeof(*pq->reqs) * hfi1_sdma_comp_ring_size;
396
	pq->reqs = kzalloc(memsize, GFP_KERNEL);
397
	if (!pq->reqs)
M
Mike Marciniszyn 已提交
398
		goto pq_reqs_nomem;
399

M
Mike Marciniszyn 已提交
400 401 402
	INIT_LIST_HEAD(&pq->list);
	pq->dd = dd;
	pq->ctxt = uctxt->ctxt;
403
	pq->subctxt = fd->subctxt;
M
Mike Marciniszyn 已提交
404 405 406
	pq->n_max_reqs = hfi1_sdma_comp_ring_size;
	pq->state = SDMA_PKT_Q_INACTIVE;
	atomic_set(&pq->n_reqs, 0);
407
	init_waitqueue_head(&pq->wait);
408
	pq->sdma_rb_root = RB_ROOT;
409 410
	INIT_LIST_HEAD(&pq->evict);
	spin_lock_init(&pq->evict_lock);
M
Mike Marciniszyn 已提交
411 412

	iowait_init(&pq->busy, 0, NULL, defer_packet_queue,
413
		    activate_packet_queue, NULL);
M
Mike Marciniszyn 已提交
414 415
	pq->reqidx = 0;
	snprintf(buf, 64, "txreq-kmem-cache-%u-%u-%u", dd->unit, uctxt->ctxt,
416
		 fd->subctxt);
M
Mike Marciniszyn 已提交
417 418 419 420 421 422 423 424 425 426
	pq->txreq_cache = kmem_cache_create(buf,
			       sizeof(struct user_sdma_txreq),
					    L1_CACHE_BYTES,
					    SLAB_HWCACHE_ALIGN,
					    sdma_kmem_cache_ctor);
	if (!pq->txreq_cache) {
		dd_dev_err(dd, "[%u] Failed to allocate TxReq cache\n",
			   uctxt->ctxt);
		goto pq_txreq_nomem;
	}
427
	fd->pq = pq;
M
Mike Marciniszyn 已提交
428
	cq = kzalloc(sizeof(*cq), GFP_KERNEL);
429
	if (!cq)
M
Mike Marciniszyn 已提交
430 431
		goto cq_nomem;

432
	memsize = PAGE_ALIGN(sizeof(*cq->comps) * hfi1_sdma_comp_ring_size);
M
Mike Marciniszyn 已提交
433
	cq->comps = vmalloc_user(memsize);
434
	if (!cq->comps)
M
Mike Marciniszyn 已提交
435
		goto cq_comps_nomem;
436

M
Mike Marciniszyn 已提交
437
	cq->nentries = hfi1_sdma_comp_ring_size;
438
	fd->cq = cq;
M
Mike Marciniszyn 已提交
439

440 441 442 443 444 445
	ret = hfi1_mmu_rb_register(&pq->sdma_rb_root, &sdma_rb_ops);
	if (ret) {
		dd_dev_err(dd, "Failed to register with MMU %d", ret);
		goto done;
	}

M
Mike Marciniszyn 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458
	spin_lock_irqsave(&uctxt->sdma_qlock, flags);
	list_add(&pq->list, &uctxt->sdma_queues);
	spin_unlock_irqrestore(&uctxt->sdma_qlock, flags);
	goto done;

cq_comps_nomem:
	kfree(cq);
cq_nomem:
	kmem_cache_destroy(pq->txreq_cache);
pq_txreq_nomem:
	kfree(pq->reqs);
pq_reqs_nomem:
	kfree(pq);
459
	fd->pq = NULL;
M
Mike Marciniszyn 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
pq_nomem:
	ret = -ENOMEM;
done:
	return ret;
}

int hfi1_user_sdma_free_queues(struct hfi1_filedata *fd)
{
	struct hfi1_ctxtdata *uctxt = fd->uctxt;
	struct hfi1_user_sdma_pkt_q *pq;
	unsigned long flags;

	hfi1_cdbg(SDMA, "[%u:%u:%u] Freeing user SDMA queues", uctxt->dd->unit,
		  uctxt->ctxt, fd->subctxt);
	pq = fd->pq;
	if (pq) {
476
		hfi1_mmu_rb_unregister(&pq->sdma_rb_root);
M
Mike Marciniszyn 已提交
477 478 479 480 481
		spin_lock_irqsave(&uctxt->sdma_qlock, flags);
		if (!list_empty(&pq->list))
			list_del_init(&pq->list);
		spin_unlock_irqrestore(&uctxt->sdma_qlock, flags);
		iowait_sdma_drain(&pq->busy);
482 483 484 485 486
		/* Wait until all requests have been freed. */
		wait_event_interruptible(
			pq->wait,
			(ACCESS_ONCE(pq->state) == SDMA_PKT_Q_INACTIVE));
		kfree(pq->reqs);
487
		kmem_cache_destroy(pq->txreq_cache);
M
Mike Marciniszyn 已提交
488 489 490 491
		kfree(pq);
		fd->pq = NULL;
	}
	if (fd->cq) {
492
		vfree(fd->cq->comps);
M
Mike Marciniszyn 已提交
493 494 495 496 497 498
		kfree(fd->cq);
		fd->cq = NULL;
	}
	return 0;
}

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
static u8 dlid_to_selector(u16 dlid)
{
	static u8 mapping[256];
	static int initialized;
	static u8 next;
	int hash;

	if (!initialized) {
		memset(mapping, 0xFF, 256);
		initialized = 1;
	}

	hash = ((dlid >> 8) ^ dlid) & 0xFF;
	if (mapping[hash] == 0xFF) {
		mapping[hash] = next;
		next = (next + 1) & 0x7F;
	}

	return mapping[hash];
}

M
Mike Marciniszyn 已提交
520 521 522
int hfi1_user_sdma_process_request(struct file *fp, struct iovec *iovec,
				   unsigned long dim, unsigned long *count)
{
523
	int ret = 0, i;
524 525 526 527
	struct hfi1_filedata *fd = fp->private_data;
	struct hfi1_ctxtdata *uctxt = fd->uctxt;
	struct hfi1_user_sdma_pkt_q *pq = fd->pq;
	struct hfi1_user_sdma_comp_q *cq = fd->cq;
M
Mike Marciniszyn 已提交
528 529 530 531 532 533
	struct hfi1_devdata *dd = pq->dd;
	unsigned long idx = 0;
	u8 pcount = initial_pkt_count;
	struct sdma_req_info info;
	struct user_sdma_request *req;
	u8 opcode, sc, vl;
534
	int req_queued = 0;
535 536
	u16 dlid;
	u8 selector;
M
Mike Marciniszyn 已提交
537 538 539 540 541

	if (iovec[idx].iov_len < sizeof(info) + sizeof(req->hdr)) {
		hfi1_cdbg(
		   SDMA,
		   "[%u:%u:%u] First vector not big enough for header %lu/%lu",
542
		   dd->unit, uctxt->ctxt, fd->subctxt,
M
Mike Marciniszyn 已提交
543
		   iovec[idx].iov_len, sizeof(info) + sizeof(req->hdr));
544
		return -EINVAL;
M
Mike Marciniszyn 已提交
545 546 547 548
	}
	ret = copy_from_user(&info, iovec[idx].iov_base, sizeof(info));
	if (ret) {
		hfi1_cdbg(SDMA, "[%u:%u:%u] Failed to copy info QW (%d)",
549
			  dd->unit, uctxt->ctxt, fd->subctxt, ret);
550
		return -EFAULT;
M
Mike Marciniszyn 已提交
551
	}
552

553
	trace_hfi1_sdma_user_reqinfo(dd, uctxt->ctxt, fd->subctxt,
M
Mike Marciniszyn 已提交
554
				     (u16 *)&info);
555 556 557 558 559 560 561 562

	if (info.comp_idx >= hfi1_sdma_comp_ring_size) {
		hfi1_cdbg(SDMA,
			  "[%u:%u:%u:%u] Invalid comp index",
			  dd->unit, uctxt->ctxt, fd->subctxt, info.comp_idx);
		return -EINVAL;
	}

563 564 565 566 567 568 569 570 571 572 573 574
	/*
	 * Sanity check the header io vector count.  Need at least 1 vector
	 * (header) and cannot be larger than the actual io vector count.
	 */
	if (req_iovcnt(info.ctrl) < 1 || req_iovcnt(info.ctrl) > dim) {
		hfi1_cdbg(SDMA,
			  "[%u:%u:%u:%u] Invalid iov count %d, dim %ld",
			  dd->unit, uctxt->ctxt, fd->subctxt, info.comp_idx,
			  req_iovcnt(info.ctrl), dim);
		return -EINVAL;
	}

575 576
	if (cq->comps[info.comp_idx].status == QUEUED ||
	    test_bit(SDMA_REQ_IN_USE, &pq->reqs[info.comp_idx].flags)) {
M
Mike Marciniszyn 已提交
577
		hfi1_cdbg(SDMA, "[%u:%u:%u] Entry %u is in QUEUED state",
578
			  dd->unit, uctxt->ctxt, fd->subctxt,
M
Mike Marciniszyn 已提交
579
			  info.comp_idx);
580
		return -EBADSLT;
M
Mike Marciniszyn 已提交
581 582 583 584
	}
	if (!info.fragsize) {
		hfi1_cdbg(SDMA,
			  "[%u:%u:%u:%u] Request does not specify fragsize",
585
			  dd->unit, uctxt->ctxt, fd->subctxt, info.comp_idx);
586
		return -EINVAL;
M
Mike Marciniszyn 已提交
587 588 589 590 591 592
	}
	/*
	 * We've done all the safety checks that we can up to this point,
	 * "allocate" the request entry.
	 */
	hfi1_cdbg(SDMA, "[%u:%u:%u] Using req/comp entry %u\n", dd->unit,
593
		  uctxt->ctxt, fd->subctxt, info.comp_idx);
M
Mike Marciniszyn 已提交
594 595 596 597
	req = pq->reqs + info.comp_idx;
	memset(req, 0, sizeof(*req));
	/* Mark the request as IN_USE before we start filling it in. */
	set_bit(SDMA_REQ_IN_USE, &req->flags);
598
	req->data_iovs = req_iovcnt(info.ctrl) - 1; /* subtract header vector */
M
Mike Marciniszyn 已提交
599 600
	req->pq = pq;
	req->cq = cq;
601
	req->status = -1;
M
Mike Marciniszyn 已提交
602
	INIT_LIST_HEAD(&req->txps);
603

M
Mike Marciniszyn 已提交
604 605
	memcpy(&req->info, &info, sizeof(info));

606 607 608 609 610 611 612 613
	if (req_opcode(info.ctrl) == EXPECTED) {
		/* expected must have a TID info and at least one data vector */
		if (req->data_iovs < 2) {
			SDMA_DBG(req,
				 "Not enough vectors for expected request");
			ret = -EINVAL;
			goto free_req;
		}
M
Mike Marciniszyn 已提交
614
		req->data_iovs--;
615
	}
M
Mike Marciniszyn 已提交
616 617 618 619

	if (!info.npkts || req->data_iovs > MAX_VECTORS_PER_REQ) {
		SDMA_DBG(req, "Too many vectors (%u/%u)", req->data_iovs,
			 MAX_VECTORS_PER_REQ);
620
		return -EINVAL;
M
Mike Marciniszyn 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	}
	/* Copy the header from the user buffer */
	ret = copy_from_user(&req->hdr, iovec[idx].iov_base + sizeof(info),
			     sizeof(req->hdr));
	if (ret) {
		SDMA_DBG(req, "Failed to copy header template (%d)", ret);
		ret = -EFAULT;
		goto free_req;
	}

	/* If Static rate control is not enabled, sanitize the header. */
	if (!HFI1_CAP_IS_USET(STATIC_RATE_CTRL))
		req->hdr.pbc[2] = 0;

	/* Validate the opcode. Do not trust packets from user space blindly. */
	opcode = (be32_to_cpu(req->hdr.bth[0]) >> 24) & 0xff;
	if ((opcode & USER_OPCODE_CHECK_MASK) !=
	     USER_OPCODE_CHECK_VAL) {
		SDMA_DBG(req, "Invalid opcode (%d)", opcode);
		ret = -EINVAL;
		goto free_req;
	}
	/*
	 * Validate the vl. Do not trust packets from user space blindly.
	 * VL comes from PBC, SC comes from LRH, and the VL needs to
	 * match the SC look up.
	 */
	vl = (le16_to_cpu(req->hdr.pbc[0]) >> 12) & 0xF;
	sc = (((be16_to_cpu(req->hdr.lrh[0]) >> 12) & 0xF) |
	      (((le16_to_cpu(req->hdr.pbc[1]) >> 14) & 0x1) << 4));
	if (vl >= dd->pport->vls_operational ||
	    vl != sc_to_vlt(dd, sc)) {
		SDMA_DBG(req, "Invalid SC(%u)/VL(%u)", sc, vl);
		ret = -EINVAL;
		goto free_req;
	}

658 659 660 661 662 663 664
	/* Checking P_KEY for requests from user-space */
	if (egress_pkey_check(dd->pport, req->hdr.lrh, req->hdr.bth, sc,
			      PKEY_CHECK_INVALID)) {
		ret = -EINVAL;
		goto free_req;
	}

M
Mike Marciniszyn 已提交
665 666 667 668 669 670 671 672 673 674 675 676
	/*
	 * Also should check the BTH.lnh. If it says the next header is GRH then
	 * the RXE parsing will be off and will land in the middle of the KDETH
	 * or miss it entirely.
	 */
	if ((be16_to_cpu(req->hdr.lrh[0]) & 0x3) == HFI1_LRH_GRH) {
		SDMA_DBG(req, "User tried to pass in a GRH");
		ret = -EINVAL;
		goto free_req;
	}

	req->koffset = le32_to_cpu(req->hdr.kdeth.swdata[6]);
677 678 679 680
	/*
	 * Calculate the initial TID offset based on the values of
	 * KDETH.OFFSET and KDETH.OM that are passed in.
	 */
M
Mike Marciniszyn 已提交
681 682 683 684 685 686 687
	req->tidoffset = KDETH_GET(req->hdr.kdeth.ver_tid_offset, OFFSET) *
		(KDETH_GET(req->hdr.kdeth.ver_tid_offset, OM) ?
		 KDETH_OM_LARGE : KDETH_OM_SMALL);
	SDMA_DBG(req, "Initial TID offset %u", req->tidoffset);
	idx++;

	/* Save all the IO vector structures */
688
	for (i = 0; i < req->data_iovs; i++) {
689
		INIT_LIST_HEAD(&req->iovs[i].list);
M
Mike Marciniszyn 已提交
690
		memcpy(&req->iovs[i].iov, iovec + idx++, sizeof(struct iovec));
691 692 693 694 695
		ret = pin_vector_pages(req, &req->iovs[i]);
		if (ret) {
			req->status = ret;
			goto free_req;
		}
696
		req->data_len += req->iovs[i].iov.iov_len;
M
Mike Marciniszyn 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
	}
	SDMA_DBG(req, "total data length %u", req->data_len);

	if (pcount > req->info.npkts)
		pcount = req->info.npkts;
	/*
	 * Copy any TID info
	 * User space will provide the TID info only when the
	 * request type is EXPECTED. This is true even if there is
	 * only one packet in the request and the header is already
	 * setup. The reason for the singular TID case is that the
	 * driver needs to perform safety checks.
	 */
	if (req_opcode(req->info.ctrl) == EXPECTED) {
		u16 ntids = iovec[idx].iov_len / sizeof(*req->tids);

		if (!ntids || ntids > MAX_TID_PAIR_ENTRIES) {
			ret = -EINVAL;
			goto free_req;
		}
		req->tids = kcalloc(ntids, sizeof(*req->tids), GFP_KERNEL);
		if (!req->tids) {
			ret = -ENOMEM;
			goto free_req;
		}
		/*
		 * We have to copy all of the tids because they may vary
		 * in size and, therefore, the TID count might not be
		 * equal to the pkt count. However, there is no way to
		 * tell at this point.
		 */
		ret = copy_from_user(req->tids, iovec[idx].iov_base,
				     ntids * sizeof(*req->tids));
		if (ret) {
			SDMA_DBG(req, "Failed to copy %d TIDs (%d)",
				 ntids, ret);
			ret = -EFAULT;
			goto free_req;
		}
		req->n_tids = ntids;
		idx++;
	}

740 741 742
	dlid = be16_to_cpu(req->hdr.lrh[1]);
	selector = dlid_to_selector(dlid);

M
Mike Marciniszyn 已提交
743 744
	/* Have to select the engine */
	req->sde = sdma_select_engine_vl(dd,
745 746
					 (u32)(uctxt->ctxt + fd->subctxt +
					       selector),
M
Mike Marciniszyn 已提交
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
					 vl);
	if (!req->sde || !sdma_running(req->sde)) {
		ret = -ECOMM;
		goto free_req;
	}

	/* We don't need an AHG entry if the request contains only one packet */
	if (req->info.npkts > 1 && HFI1_CAP_IS_USET(SDMA_AHG)) {
		int ahg = sdma_ahg_alloc(req->sde);

		if (likely(ahg >= 0)) {
			req->ahg_idx = (u8)ahg;
			set_bit(SDMA_REQ_HAVE_AHG, &req->flags);
		}
	}

763 764
	set_comp_state(pq, cq, info.comp_idx, QUEUED, 0);
	atomic_inc(&pq->n_reqs);
765
	req_queued = 1;
M
Mike Marciniszyn 已提交
766
	/* Send the first N packets in the request to buy us some time */
767 768 769 770
	ret = user_sdma_send_pkts(req, pcount);
	if (unlikely(ret < 0 && ret != -EBUSY)) {
		req->status = ret;
		goto free_req;
M
Mike Marciniszyn 已提交
771 772
	}

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
	/*
	 * It is possible that the SDMA engine would have processed all the
	 * submitted packets by the time we get here. Therefore, only set
	 * packet queue state to ACTIVE if there are still uncompleted
	 * requests.
	 */
	if (atomic_read(&pq->n_reqs))
		xchg(&pq->state, SDMA_PKT_Q_ACTIVE);

	/*
	 * This is a somewhat blocking send implementation.
	 * The driver will block the caller until all packets of the
	 * request have been submitted to the SDMA engine. However, it
	 * will not wait for send completions.
	 */
	while (!test_bit(SDMA_REQ_SEND_DONE, &req->flags)) {
		ret = user_sdma_send_pkts(req, pcount);
		if (ret < 0) {
			if (ret != -EBUSY) {
				req->status = ret;
				set_bit(SDMA_REQ_DONE_ERROR, &req->flags);
794 795 796
				if (ACCESS_ONCE(req->seqcomp) ==
				    req->seqsubmitted - 1)
					goto free_req;
797
				return ret;
M
Mike Marciniszyn 已提交
798
			}
799 800 801 802 803
			wait_event_interruptible_timeout(
				pq->busy.wait_dma,
				(pq->state == SDMA_PKT_Q_ACTIVE),
				msecs_to_jiffies(
					SDMA_IOWAIT_TIMEOUT));
M
Mike Marciniszyn 已提交
804 805 806
		}
	}
	*count += idx;
807
	return 0;
M
Mike Marciniszyn 已提交
808
free_req:
809
	user_sdma_free_request(req, true);
810 811
	if (req_queued)
		pq_update(pq);
812
	set_comp_state(pq, cq, info.comp_idx, ERROR, req->status);
M
Mike Marciniszyn 已提交
813 814 815 816
	return ret;
}

static inline u32 compute_data_length(struct user_sdma_request *req,
817
				      struct user_sdma_txreq *tx)
M
Mike Marciniszyn 已提交
818 819 820 821 822 823
{
	/*
	 * Determine the proper size of the packet data.
	 * The size of the data of the first packet is in the header
	 * template. However, it includes the header and ICRC, which need
	 * to be subtracted.
824 825 826 827
	 * The minimum representable packet data length in a header is 4 bytes,
	 * therefore, when the data length request is less than 4 bytes, there's
	 * only one packet, and the packet data length is equal to that of the
	 * request data length.
M
Mike Marciniszyn 已提交
828 829 830 831 832 833
	 * The size of the remaining packets is the minimum of the frag
	 * size (MTU) or remaining data in the request.
	 */
	u32 len;

	if (!req->seqnum) {
834 835 836 837 838
		if (req->data_len < sizeof(u32))
			len = req->data_len;
		else
			len = ((be16_to_cpu(req->hdr.lrh[2]) << 2) -
			       (sizeof(tx->hdr) - 4));
M
Mike Marciniszyn 已提交
839 840 841
	} else if (req_opcode(req->info.ctrl) == EXPECTED) {
		u32 tidlen = EXP_TID_GET(req->tids[req->tididx], LEN) *
			PAGE_SIZE;
842 843 844 845
		/*
		 * Get the data length based on the remaining space in the
		 * TID pair.
		 */
M
Mike Marciniszyn 已提交
846 847 848 849 850 851 852 853 854
		len = min(tidlen - req->tidoffset, (u32)req->info.fragsize);
		/* If we've filled up the TID pair, move to the next one. */
		if (unlikely(!len) && ++req->tididx < req->n_tids &&
		    req->tids[req->tididx]) {
			tidlen = EXP_TID_GET(req->tids[req->tididx],
					     LEN) * PAGE_SIZE;
			req->tidoffset = 0;
			len = min_t(u32, tidlen, req->info.fragsize);
		}
855 856
		/*
		 * Since the TID pairs map entire pages, make sure that we
M
Mike Marciniszyn 已提交
857
		 * are not going to try to send more data that we have
858 859
		 * remaining.
		 */
M
Mike Marciniszyn 已提交
860
		len = min(len, req->data_len - req->sent);
861
	} else {
M
Mike Marciniszyn 已提交
862
		len = min(req->data_len - req->sent, (u32)req->info.fragsize);
863
	}
M
Mike Marciniszyn 已提交
864 865 866 867
	SDMA_DBG(req, "Data Length = %u", len);
	return len;
}

868 869 870 871 872 873 874
static inline u32 pad_len(u32 len)
{
	if (len & (sizeof(u32) - 1))
		len += sizeof(u32) - (len & (sizeof(u32) - 1));
	return len;
}

M
Mike Marciniszyn 已提交
875 876 877 878 879 880 881 882 883 884 885 886 887 888
static inline u32 get_lrh_len(struct hfi1_pkt_header hdr, u32 len)
{
	/* (Size of complete header - size of PBC) + 4B ICRC + data length */
	return ((sizeof(hdr) - sizeof(hdr.pbc)) + 4 + len);
}

static int user_sdma_send_pkts(struct user_sdma_request *req, unsigned maxpkts)
{
	int ret = 0;
	unsigned npkts = 0;
	struct user_sdma_txreq *tx = NULL;
	struct hfi1_user_sdma_pkt_q *pq = NULL;
	struct user_sdma_iovec *iovec = NULL;

889 890
	if (!req->pq)
		return -EINVAL;
M
Mike Marciniszyn 已提交
891 892 893

	pq = req->pq;

894 895 896 897 898 899
	/* If tx completion has reported an error, we are done. */
	if (test_bit(SDMA_REQ_HAS_ERROR, &req->flags)) {
		set_bit(SDMA_REQ_DONE_ERROR, &req->flags);
		return -EFAULT;
	}

M
Mike Marciniszyn 已提交
900 901 902 903 904 905
	/*
	 * Check if we might have sent the entire request already
	 */
	if (unlikely(req->seqnum == req->info.npkts)) {
		if (!list_empty(&req->txps))
			goto dosend;
906
		return ret;
M
Mike Marciniszyn 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	}

	if (!maxpkts || maxpkts > req->info.npkts - req->seqnum)
		maxpkts = req->info.npkts - req->seqnum;

	while (npkts < maxpkts) {
		u32 datalen = 0, queued = 0, data_sent = 0;
		u64 iov_offset = 0;

		/*
		 * Check whether any of the completions have come back
		 * with errors. If so, we are not going to process any
		 * more packets from this request.
		 */
		if (test_bit(SDMA_REQ_HAS_ERROR, &req->flags)) {
			set_bit(SDMA_REQ_DONE_ERROR, &req->flags);
923
			return -EFAULT;
M
Mike Marciniszyn 已提交
924 925 926
		}

		tx = kmem_cache_alloc(pq->txreq_cache, GFP_KERNEL);
927 928 929
		if (!tx)
			return -ENOMEM;

M
Mike Marciniszyn 已提交
930 931 932
		tx->flags = 0;
		tx->req = req;
		tx->busycount = 0;
933
		INIT_LIST_HEAD(&tx->list);
M
Mike Marciniszyn 已提交
934 935

		if (req->seqnum == req->info.npkts - 1)
936
			tx->flags |= TXREQ_FLAGS_REQ_LAST_PKT;
M
Mike Marciniszyn 已提交
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

		/*
		 * Calculate the payload size - this is min of the fragment
		 * (MTU) size or the remaining bytes in the request but only
		 * if we have payload data.
		 */
		if (req->data_len) {
			iovec = &req->iovs[req->iov_idx];
			if (ACCESS_ONCE(iovec->offset) == iovec->iov.iov_len) {
				if (++req->iov_idx == req->data_iovs) {
					ret = -EFAULT;
					goto free_txreq;
				}
				iovec = &req->iovs[req->iov_idx];
				WARN_ON(iovec->offset);
			}

			datalen = compute_data_length(req, tx);
			if (!datalen) {
				SDMA_DBG(req,
					 "Request has data but pkt len is 0");
				ret = -EFAULT;
				goto free_tx;
			}
		}

		if (test_bit(SDMA_REQ_HAVE_AHG, &req->flags)) {
			if (!req->seqnum) {
				u16 pbclen = le16_to_cpu(req->hdr.pbc[0]);
966 967
				u32 lrhlen = get_lrh_len(req->hdr,
							 pad_len(datalen));
M
Mike Marciniszyn 已提交
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
				/*
				 * Copy the request header into the tx header
				 * because the HW needs a cacheline-aligned
				 * address.
				 * This copy can be optimized out if the hdr
				 * member of user_sdma_request were also
				 * cacheline aligned.
				 */
				memcpy(&tx->hdr, &req->hdr, sizeof(tx->hdr));
				if (PBC2LRH(pbclen) != lrhlen) {
					pbclen = (pbclen & 0xf000) |
						LRH2PBC(lrhlen);
					tx->hdr.pbc[0] = cpu_to_le16(pbclen);
				}
				ret = sdma_txinit_ahg(&tx->txreq,
						      SDMA_TXREQ_F_AHG_COPY,
						      sizeof(tx->hdr) + datalen,
						      req->ahg_idx, 0, NULL, 0,
						      user_sdma_txreq_cb);
				if (ret)
					goto free_tx;
				ret = sdma_txadd_kvaddr(pq->dd, &tx->txreq,
							&tx->hdr,
							sizeof(tx->hdr));
				if (ret)
					goto free_txreq;
			} else {
				int changes;

				changes = set_txreq_header_ahg(req, tx,
							       datalen);
				if (changes < 0)
					goto free_tx;
				sdma_txinit_ahg(&tx->txreq,
						SDMA_TXREQ_F_USE_AHG,
						datalen, req->ahg_idx, changes,
						req->ahg, sizeof(req->hdr),
						user_sdma_txreq_cb);
			}
		} else {
			ret = sdma_txinit(&tx->txreq, 0, sizeof(req->hdr) +
					  datalen, user_sdma_txreq_cb);
			if (ret)
				goto free_tx;
			/*
			 * Modify the header for this packet. This only needs
			 * to be done if we are not going to use AHG. Otherwise,
			 * the HW will do it based on the changes we gave it
			 * during sdma_txinit_ahg().
			 */
			ret = set_txreq_header(req, tx, datalen);
			if (ret)
				goto free_txreq;
		}

		/*
		 * If the request contains any data vectors, add up to
		 * fragsize bytes to the descriptor.
		 */
		while (queued < datalen &&
		       (req->sent + data_sent) < req->data_len) {
			unsigned long base, offset;
			unsigned pageidx, len;

			base = (unsigned long)iovec->iov.iov_base;
1033 1034
			offset = offset_in_page(base + iovec->offset +
						iov_offset);
M
Mike Marciniszyn 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043
			pageidx = (((iovec->offset + iov_offset +
				     base) - (base & PAGE_MASK)) >> PAGE_SHIFT);
			len = offset + req->info.fragsize > PAGE_SIZE ?
				PAGE_SIZE - offset : req->info.fragsize;
			len = min((datalen - queued), len);
			ret = sdma_txadd_page(pq->dd, &tx->txreq,
					      iovec->pages[pageidx],
					      offset, len);
			if (ret) {
1044 1045
				SDMA_DBG(req, "SDMA txreq add page failed %d\n",
					 ret);
M
Mike Marciniszyn 已提交
1046 1047 1048 1049 1050 1051 1052
				goto free_txreq;
			}
			iov_offset += len;
			queued += len;
			data_sent += len;
			if (unlikely(queued < datalen &&
				     pageidx == iovec->npages &&
1053
				     req->iov_idx < req->data_iovs - 1)) {
M
Mike Marciniszyn 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
				iovec->offset += iov_offset;
				iovec = &req->iovs[++req->iov_idx];
				iov_offset = 0;
			}
		}
		/*
		 * The txreq was submitted successfully so we can update
		 * the counters.
		 */
		req->koffset += datalen;
		if (req_opcode(req->info.ctrl) == EXPECTED)
			req->tidoffset += datalen;
		req->sent += data_sent;
1067 1068
		if (req->data_len)
			iovec->offset += iov_offset;
1069
		list_add_tail(&tx->txreq.list, &req->txps);
M
Mike Marciniszyn 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
		/*
		 * It is important to increment this here as it is used to
		 * generate the BTH.PSN and, therefore, can't be bulk-updated
		 * outside of the loop.
		 */
		tx->seqnum = req->seqnum++;
		npkts++;
	}
dosend:
	ret = sdma_send_txlist(req->sde, &pq->busy, &req->txps);
1080 1081
	if (list_empty(&req->txps)) {
		req->seqsubmitted = req->seqnum;
M
Mike Marciniszyn 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
		if (req->seqnum == req->info.npkts) {
			set_bit(SDMA_REQ_SEND_DONE, &req->flags);
			/*
			 * The txreq has already been submitted to the HW queue
			 * so we can free the AHG entry now. Corruption will not
			 * happen due to the sequential manner in which
			 * descriptors are processed.
			 */
			if (test_bit(SDMA_REQ_HAVE_AHG, &req->flags))
				sdma_ahg_free(req->sde, req->ahg_idx);
		}
1093 1094 1095 1096
	} else if (ret > 0) {
		req->seqsubmitted += ret;
		ret = 0;
	}
1097 1098
	return ret;

M
Mike Marciniszyn 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
free_txreq:
	sdma_txclean(pq->dd, &tx->txreq);
free_tx:
	kmem_cache_free(pq->txreq_cache, tx);
	return ret;
}

/*
 * How many pages in this iovec element?
 */
static inline int num_user_pages(const struct iovec *iov)
{
1111
	const unsigned long addr  = (unsigned long)iov->iov_base;
M
Mike Marciniszyn 已提交
1112 1113 1114 1115 1116 1117 1118
	const unsigned long len   = iov->iov_len;
	const unsigned long spage = addr & PAGE_MASK;
	const unsigned long epage = (addr + len - 1) & PAGE_MASK;

	return 1 + ((epage - spage) >> PAGE_SHIFT);
}

1119 1120 1121 1122
static u32 sdma_cache_evict(struct hfi1_user_sdma_pkt_q *pq, u32 npages)
{
	u32 cleared = 0;
	struct sdma_mmu_node *node, *ptr;
1123
	struct list_head to_evict = LIST_HEAD_INIT(to_evict);
M
Mike Marciniszyn 已提交
1124

1125
	spin_lock(&pq->evict_lock);
1126 1127 1128
	list_for_each_entry_safe_reverse(node, ptr, &pq->evict, list) {
		/* Make sure that no one is still using the node. */
		if (!atomic_read(&node->refcount)) {
1129 1130 1131
			set_bit(SDMA_CACHE_NODE_EVICT, &node->flags);
			list_del_init(&node->list);
			list_add(&node->list, &to_evict);
1132 1133 1134 1135
			cleared += node->npages;
			if (cleared >= npages)
				break;
		}
M
Mike Marciniszyn 已提交
1136
	}
1137 1138 1139 1140 1141
	spin_unlock(&pq->evict_lock);

	list_for_each_entry_safe(node, ptr, &to_evict, list)
		hfi1_mmu_rb_remove(&pq->sdma_rb_root, &node->rb);

1142 1143
	return cleared;
}
1144

M
Mike Marciniszyn 已提交
1145
static int pin_vector_pages(struct user_sdma_request *req,
I
Ira Weiny 已提交
1146 1147
			    struct user_sdma_iovec *iovec)
{
1148
	int ret = 0, pinned, npages, cleared;
1149 1150 1151 1152 1153
	struct page **pages;
	struct hfi1_user_sdma_pkt_q *pq = req->pq;
	struct sdma_mmu_node *node = NULL;
	struct mmu_rb_node *rb_node;

1154 1155 1156
	rb_node = hfi1_mmu_rb_extract(&pq->sdma_rb_root,
				      (unsigned long)iovec->iov.iov_base,
				      iovec->iov.iov_len);
1157
	if (rb_node && !IS_ERR(rb_node))
1158
		node = container_of(rb_node, struct sdma_mmu_node, rb);
1159 1160
	else
		rb_node = NULL;
1161 1162 1163 1164 1165

	if (!node) {
		node = kzalloc(sizeof(*node), GFP_KERNEL);
		if (!node)
			return -ENOMEM;
1166

1167
		node->rb.addr = (unsigned long)iovec->iov.iov_base;
1168
		node->pq = pq;
1169
		atomic_set(&node->refcount, 0);
1170
		INIT_LIST_HEAD(&node->list);
M
Mike Marciniszyn 已提交
1171
	}
1172

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
	npages = num_user_pages(&iovec->iov);
	if (node->npages < npages) {
		pages = kcalloc(npages, sizeof(*pages), GFP_KERNEL);
		if (!pages) {
			SDMA_DBG(req, "Failed page array alloc");
			ret = -ENOMEM;
			goto bail;
		}
		memcpy(pages, node->pages, node->npages * sizeof(*pages));

		npages -= node->npages;
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

		/*
		 * If rb_node is NULL, it means that this is brand new node
		 * and, therefore not on the eviction list.
		 * If, however, the rb_node is non-NULL, it means that the
		 * node is already in RB tree and, therefore on the eviction
		 * list (nodes are unconditionally inserted in the eviction
		 * list). In that case, we have to remove the node prior to
		 * calling the eviction function in order to prevent it from
		 * freeing this node.
		 */
		if (rb_node) {
			spin_lock(&pq->evict_lock);
			list_del_init(&node->list);
			spin_unlock(&pq->evict_lock);
		}
1200 1201 1202 1203 1204 1205
retry:
		if (!hfi1_can_pin_pages(pq->dd, pq->n_locked, npages)) {
			cleared = sdma_cache_evict(pq, npages);
			if (cleared >= npages)
				goto retry;
		}
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
		pinned = hfi1_acquire_user_pages(
			((unsigned long)iovec->iov.iov_base +
			 (node->npages * PAGE_SIZE)), npages, 0,
			pages + node->npages);
		if (pinned < 0) {
			kfree(pages);
			ret = pinned;
			goto bail;
		}
		if (pinned != npages) {
1216 1217
			unpin_vector_pages(current->mm, pages, node->npages,
					   pinned);
1218 1219 1220 1221
			ret = -EFAULT;
			goto bail;
		}
		kfree(node->pages);
1222
		node->rb.len = iovec->iov.iov_len;
1223 1224 1225
		node->pages = pages;
		node->npages += pinned;
		npages = node->npages;
1226
		spin_lock(&pq->evict_lock);
1227
		list_add(&node->list, &pq->evict);
1228 1229
		pq->n_locked += pinned;
		spin_unlock(&pq->evict_lock);
1230 1231 1232
	}
	iovec->pages = node->pages;
	iovec->npages = npages;
1233
	iovec->node = node;
1234

1235 1236 1237 1238 1239 1240 1241 1242
	ret = hfi1_mmu_rb_insert(&req->pq->sdma_rb_root, &node->rb);
	if (ret) {
		spin_lock(&pq->evict_lock);
		if (!list_empty(&node->list))
			list_del(&node->list);
		pq->n_locked -= node->npages;
		spin_unlock(&pq->evict_lock);
		goto bail;
M
Mike Marciniszyn 已提交
1243
	}
1244
	return 0;
1245
bail:
1246 1247 1248
	if (rb_node)
		unpin_vector_pages(current->mm, node->pages, 0, node->npages);
	kfree(node);
1249
	return ret;
M
Mike Marciniszyn 已提交
1250 1251
}

1252
static void unpin_vector_pages(struct mm_struct *mm, struct page **pages,
1253
			       unsigned start, unsigned npages)
M
Mike Marciniszyn 已提交
1254
{
I
Ira Weiny 已提交
1255
	hfi1_release_user_pages(mm, pages + start, npages, false);
1256
	kfree(pages);
M
Mike Marciniszyn 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265
}

static int check_header_template(struct user_sdma_request *req,
				 struct hfi1_pkt_header *hdr, u32 lrhlen,
				 u32 datalen)
{
	/*
	 * Perform safety checks for any type of packet:
	 *    - transfer size is multiple of 64bytes
1266
	 *    - packet length is multiple of 4 bytes
M
Mike Marciniszyn 已提交
1267 1268 1269 1270 1271 1272
	 *    - packet length is not larger than MTU size
	 *
	 * These checks are only done for the first packet of the
	 * transfer since the header is "given" to us by user space.
	 * For the remainder of the packets we compute the values.
	 */
1273
	if (req->info.fragsize % PIO_BLOCK_SIZE || lrhlen & 0x3 ||
M
Mike Marciniszyn 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
	    lrhlen > get_lrh_len(*hdr, req->info.fragsize))
		return -EINVAL;

	if (req_opcode(req->info.ctrl) == EXPECTED) {
		/*
		 * The header is checked only on the first packet. Furthermore,
		 * we ensure that at least one TID entry is copied when the
		 * request is submitted. Therefore, we don't have to verify that
		 * tididx points to something sane.
		 */
		u32 tidval = req->tids[req->tididx],
			tidlen = EXP_TID_GET(tidval, LEN) * PAGE_SIZE,
			tididx = EXP_TID_GET(tidval, IDX),
			tidctrl = EXP_TID_GET(tidval, CTRL),
			tidoff;
		__le32 kval = hdr->kdeth.ver_tid_offset;

		tidoff = KDETH_GET(kval, OFFSET) *
			  (KDETH_GET(req->hdr.kdeth.ver_tid_offset, OM) ?
			   KDETH_OM_LARGE : KDETH_OM_SMALL);
		/*
		 * Expected receive packets have the following
		 * additional checks:
		 *     - offset is not larger than the TID size
		 *     - TIDCtrl values match between header and TID array
		 *     - TID indexes match between header and TID array
		 */
		if ((tidoff + datalen > tidlen) ||
		    KDETH_GET(kval, TIDCTRL) != tidctrl ||
		    KDETH_GET(kval, TID) != tididx)
			return -EINVAL;
	}
	return 0;
}

/*
 * Correctly set the BTH.PSN field based on type of
 * transfer - eager packets can just increment the PSN but
 * expected packets encode generation and sequence in the
 * BTH.PSN field so just incrementing will result in errors.
 */
static inline u32 set_pkt_bth_psn(__be32 bthpsn, u8 expct, u32 frags)
{
	u32 val = be32_to_cpu(bthpsn),
		mask = (HFI1_CAP_IS_KSET(EXTENDED_PSN) ? 0x7fffffffull :
			0xffffffull),
		psn = val & mask;
	if (expct)
		psn = (psn & ~BTH_SEQ_MASK) | ((psn + frags) & BTH_SEQ_MASK);
	else
		psn = psn + frags;
	return psn & mask;
}

static int set_txreq_header(struct user_sdma_request *req,
			    struct user_sdma_txreq *tx, u32 datalen)
{
	struct hfi1_user_sdma_pkt_q *pq = req->pq;
	struct hfi1_pkt_header *hdr = &tx->hdr;
	u16 pbclen;
	int ret;
1335
	u32 tidval = 0, lrhlen = get_lrh_len(*hdr, pad_len(datalen));
M
Mike Marciniszyn 已提交
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384

	/* Copy the header template to the request before modification */
	memcpy(hdr, &req->hdr, sizeof(*hdr));

	/*
	 * Check if the PBC and LRH length are mismatched. If so
	 * adjust both in the header.
	 */
	pbclen = le16_to_cpu(hdr->pbc[0]);
	if (PBC2LRH(pbclen) != lrhlen) {
		pbclen = (pbclen & 0xf000) | LRH2PBC(lrhlen);
		hdr->pbc[0] = cpu_to_le16(pbclen);
		hdr->lrh[2] = cpu_to_be16(lrhlen >> 2);
		/*
		 * Third packet
		 * This is the first packet in the sequence that has
		 * a "static" size that can be used for the rest of
		 * the packets (besides the last one).
		 */
		if (unlikely(req->seqnum == 2)) {
			/*
			 * From this point on the lengths in both the
			 * PBC and LRH are the same until the last
			 * packet.
			 * Adjust the template so we don't have to update
			 * every packet
			 */
			req->hdr.pbc[0] = hdr->pbc[0];
			req->hdr.lrh[2] = hdr->lrh[2];
		}
	}
	/*
	 * We only have to modify the header if this is not the
	 * first packet in the request. Otherwise, we use the
	 * header given to us.
	 */
	if (unlikely(!req->seqnum)) {
		ret = check_header_template(req, hdr, lrhlen, datalen);
		if (ret)
			return ret;
		goto done;
	}

	hdr->bth[2] = cpu_to_be32(
		set_pkt_bth_psn(hdr->bth[2],
				(req_opcode(req->info.ctrl) == EXPECTED),
				req->seqnum));

	/* Set ACK request on last packet */
1385
	if (unlikely(tx->flags & TXREQ_FLAGS_REQ_LAST_PKT))
1386
		hdr->bth[2] |= cpu_to_be32(1UL << 31);
M
Mike Marciniszyn 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399

	/* Set the new offset */
	hdr->kdeth.swdata[6] = cpu_to_le32(req->koffset);
	/* Expected packets have to fill in the new TID information */
	if (req_opcode(req->info.ctrl) == EXPECTED) {
		tidval = req->tids[req->tididx];
		/*
		 * If the offset puts us at the end of the current TID,
		 * advance everything.
		 */
		if ((req->tidoffset) == (EXP_TID_GET(tidval, LEN) *
					 PAGE_SIZE)) {
			req->tidoffset = 0;
1400 1401 1402 1403
			/*
			 * Since we don't copy all the TIDs, all at once,
			 * we have to check again.
			 */
M
Mike Marciniszyn 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
			if (++req->tididx > req->n_tids - 1 ||
			    !req->tids[req->tididx]) {
				return -EINVAL;
			}
			tidval = req->tids[req->tididx];
		}
		req->omfactor = EXP_TID_GET(tidval, LEN) * PAGE_SIZE >=
			KDETH_OM_MAX_SIZE ? KDETH_OM_LARGE : KDETH_OM_SMALL;
		/* Set KDETH.TIDCtrl based on value for this TID. */
		KDETH_SET(hdr->kdeth.ver_tid_offset, TIDCTRL,
			  EXP_TID_GET(tidval, CTRL));
		/* Set KDETH.TID based on value for this TID */
		KDETH_SET(hdr->kdeth.ver_tid_offset, TID,
			  EXP_TID_GET(tidval, IDX));
		/* Clear KDETH.SH only on the last packet */
1419
		if (unlikely(tx->flags & TXREQ_FLAGS_REQ_LAST_PKT))
M
Mike Marciniszyn 已提交
1420 1421 1422 1423 1424 1425 1426
			KDETH_SET(hdr->kdeth.ver_tid_offset, SH, 0);
		/*
		 * Set the KDETH.OFFSET and KDETH.OM based on size of
		 * transfer.
		 */
		SDMA_DBG(req, "TID offset %ubytes %uunits om%u",
			 req->tidoffset, req->tidoffset / req->omfactor,
1427
			 req->omfactor != KDETH_OM_SMALL);
M
Mike Marciniszyn 已提交
1428 1429 1430
		KDETH_SET(hdr->kdeth.ver_tid_offset, OFFSET,
			  req->tidoffset / req->omfactor);
		KDETH_SET(hdr->kdeth.ver_tid_offset, OM,
1431
			  req->omfactor != KDETH_OM_SMALL);
M
Mike Marciniszyn 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
	}
done:
	trace_hfi1_sdma_user_header(pq->dd, pq->ctxt, pq->subctxt,
				    req->info.comp_idx, hdr, tidval);
	return sdma_txadd_kvaddr(pq->dd, &tx->txreq, hdr, sizeof(*hdr));
}

static int set_txreq_header_ahg(struct user_sdma_request *req,
				struct user_sdma_txreq *tx, u32 len)
{
	int diff = 0;
	struct hfi1_user_sdma_pkt_q *pq = req->pq;
	struct hfi1_pkt_header *hdr = &req->hdr;
	u16 pbclen = le16_to_cpu(hdr->pbc[0]);
1446
	u32 val32, tidval = 0, lrhlen = get_lrh_len(*hdr, pad_len(len));
M
Mike Marciniszyn 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462

	if (PBC2LRH(pbclen) != lrhlen) {
		/* PBC.PbcLengthDWs */
		AHG_HEADER_SET(req->ahg, diff, 0, 0, 12,
			       cpu_to_le16(LRH2PBC(lrhlen)));
		/* LRH.PktLen (we need the full 16 bits due to byte swap) */
		AHG_HEADER_SET(req->ahg, diff, 3, 0, 16,
			       cpu_to_be16(lrhlen >> 2));
	}

	/*
	 * Do the common updates
	 */
	/* BTH.PSN and BTH.A */
	val32 = (be32_to_cpu(hdr->bth[2]) + req->seqnum) &
		(HFI1_CAP_IS_KSET(EXTENDED_PSN) ? 0x7fffffff : 0xffffff);
1463
	if (unlikely(tx->flags & TXREQ_FLAGS_REQ_LAST_PKT))
M
Mike Marciniszyn 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
		val32 |= 1UL << 31;
	AHG_HEADER_SET(req->ahg, diff, 6, 0, 16, cpu_to_be16(val32 >> 16));
	AHG_HEADER_SET(req->ahg, diff, 6, 16, 16, cpu_to_be16(val32 & 0xffff));
	/* KDETH.Offset */
	AHG_HEADER_SET(req->ahg, diff, 15, 0, 16,
		       cpu_to_le16(req->koffset & 0xffff));
	AHG_HEADER_SET(req->ahg, diff, 15, 16, 16,
		       cpu_to_le16(req->koffset >> 16));
	if (req_opcode(req->info.ctrl) == EXPECTED) {
		__le16 val;

		tidval = req->tids[req->tididx];

		/*
		 * If the offset puts us at the end of the current TID,
		 * advance everything.
		 */
		if ((req->tidoffset) == (EXP_TID_GET(tidval, LEN) *
					 PAGE_SIZE)) {
			req->tidoffset = 0;
1484 1485 1486 1487
			/*
			 * Since we don't copy all the TIDs, all at once,
			 * we have to check again.
			 */
M
Mike Marciniszyn 已提交
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
			if (++req->tididx > req->n_tids - 1 ||
			    !req->tids[req->tididx]) {
				return -EINVAL;
			}
			tidval = req->tids[req->tididx];
		}
		req->omfactor = ((EXP_TID_GET(tidval, LEN) *
				  PAGE_SIZE) >=
				 KDETH_OM_MAX_SIZE) ? KDETH_OM_LARGE :
			KDETH_OM_SMALL;
		/* KDETH.OM and KDETH.OFFSET (TID) */
		AHG_HEADER_SET(req->ahg, diff, 7, 0, 16,
			       ((!!(req->omfactor - KDETH_OM_SMALL)) << 15 |
				((req->tidoffset / req->omfactor) & 0x7fff)));
		/* KDETH.TIDCtrl, KDETH.TID */
		val = cpu_to_le16(((EXP_TID_GET(tidval, CTRL) & 0x3) << 10) |
					(EXP_TID_GET(tidval, IDX) & 0x3ff));
		/* Clear KDETH.SH on last packet */
1506
		if (unlikely(tx->flags & TXREQ_FLAGS_REQ_LAST_PKT)) {
M
Mike Marciniszyn 已提交
1507 1508 1509 1510
			val |= cpu_to_le16(KDETH_GET(hdr->kdeth.ver_tid_offset,
								INTR) >> 16);
			val &= cpu_to_le16(~(1U << 13));
			AHG_HEADER_SET(req->ahg, diff, 7, 16, 14, val);
1511
		} else {
M
Mike Marciniszyn 已提交
1512
			AHG_HEADER_SET(req->ahg, diff, 7, 16, 12, val);
1513
		}
M
Mike Marciniszyn 已提交
1514 1515 1516 1517 1518 1519 1520 1521
	}

	trace_hfi1_sdma_user_header_ahg(pq->dd, pq->ctxt, pq->subctxt,
					req->info.comp_idx, req->sde->this_idx,
					req->ahg_idx, req->ahg, diff, tidval);
	return diff;
}

1522 1523 1524 1525 1526 1527
/*
 * SDMA tx request completion callback. Called when the SDMA progress
 * state machine gets notification that the SDMA descriptors for this
 * tx request have been processed by the DMA engine. Called in
 * interrupt context.
 */
1528
static void user_sdma_txreq_cb(struct sdma_txreq *txreq, int status)
M
Mike Marciniszyn 已提交
1529 1530 1531
{
	struct user_sdma_txreq *tx =
		container_of(txreq, struct user_sdma_txreq, txreq);
1532
	struct user_sdma_request *req;
1533 1534 1535
	struct hfi1_user_sdma_pkt_q *pq;
	struct hfi1_user_sdma_comp_q *cq;
	u16 idx;
M
Mike Marciniszyn 已提交
1536

1537
	if (!tx->req)
M
Mike Marciniszyn 已提交
1538 1539
		return;

1540
	req = tx->req;
1541 1542
	pq = req->pq;
	cq = req->cq;
M
Mike Marciniszyn 已提交
1543 1544

	if (status != SDMA_TXREQ_S_OK) {
1545 1546
		SDMA_DBG(req, "SDMA completion with error %d",
			 status);
M
Mike Marciniszyn 已提交
1547
		set_bit(SDMA_REQ_HAS_ERROR, &req->flags);
1548 1549
	}

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
	req->seqcomp = tx->seqnum;
	kmem_cache_free(pq->txreq_cache, tx);
	tx = NULL;

	idx = req->info.comp_idx;
	if (req->status == -1 && status == SDMA_TXREQ_S_OK) {
		if (req->seqcomp == req->info.npkts - 1) {
			req->status = 0;
			user_sdma_free_request(req, false);
			pq_update(pq);
			set_comp_state(pq, cq, idx, COMPLETE, 0);
		}
M
Mike Marciniszyn 已提交
1562
	} else {
1563 1564
		if (status != SDMA_TXREQ_S_OK)
			req->status = status;
1565 1566 1567
		if (req->seqcomp == (ACCESS_ONCE(req->seqsubmitted) - 1) &&
		    (test_bit(SDMA_REQ_SEND_DONE, &req->flags) ||
		     test_bit(SDMA_REQ_DONE_ERROR, &req->flags))) {
1568 1569 1570 1571
			user_sdma_free_request(req, false);
			pq_update(pq);
			set_comp_state(pq, cq, idx, ERROR, req->status);
		}
1572 1573 1574
	}
}

1575
static inline void pq_update(struct hfi1_user_sdma_pkt_q *pq)
1576
{
1577
	if (atomic_dec_and_test(&pq->n_reqs)) {
M
Mike Marciniszyn 已提交
1578
		xchg(&pq->state, SDMA_PKT_Q_INACTIVE);
1579 1580
		wake_up(&pq->wait);
	}
M
Mike Marciniszyn 已提交
1581 1582
}

1583
static void user_sdma_free_request(struct user_sdma_request *req, bool unpin)
M
Mike Marciniszyn 已提交
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
{
	if (!list_empty(&req->txps)) {
		struct sdma_txreq *t, *p;

		list_for_each_entry_safe(t, p, &req->txps, list) {
			struct user_sdma_txreq *tx =
				container_of(t, struct user_sdma_txreq, txreq);
			list_del_init(&t->list);
			sdma_txclean(req->pq->dd, t);
			kmem_cache_free(req->pq->txreq_cache, tx);
		}
	}
	if (req->data_iovs) {
1597
		struct sdma_mmu_node *node;
M
Mike Marciniszyn 已提交
1598 1599
		int i;

1600
		for (i = 0; i < req->data_iovs; i++) {
1601 1602
			node = req->iovs[i].node;
			if (!node)
1603 1604 1605 1606 1607 1608 1609 1610
				continue;

			if (unpin)
				hfi1_mmu_rb_remove(&req->pq->sdma_rb_root,
						   &node->rb);
			else
				atomic_dec(&node->refcount);
		}
M
Mike Marciniszyn 已提交
1611 1612 1613 1614 1615
	}
	kfree(req->tids);
	clear_bit(SDMA_REQ_IN_USE, &req->flags);
}

1616 1617 1618 1619
static inline void set_comp_state(struct hfi1_user_sdma_pkt_q *pq,
				  struct hfi1_user_sdma_comp_q *cq,
				  u16 idx, enum hfi1_sdma_comp_state state,
				  int ret)
M
Mike Marciniszyn 已提交
1620
{
1621 1622 1623
	hfi1_cdbg(SDMA, "[%u:%u:%u:%u] Setting completion status %u %d",
		  pq->dd->unit, pq->ctxt, pq->subctxt, idx, state, ret);
	cq->comps[idx].status = state;
M
Mike Marciniszyn 已提交
1624
	if (state == ERROR)
1625 1626 1627
		cq->comps[idx].errcode = -ret;
	trace_hfi1_sdma_user_completion(pq->dd, pq->ctxt, pq->subctxt,
					idx, state, ret);
M
Mike Marciniszyn 已提交
1628
}
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

static bool sdma_rb_filter(struct mmu_rb_node *node, unsigned long addr,
			   unsigned long len)
{
	return (bool)(node->addr == addr);
}

static int sdma_rb_insert(struct rb_root *root, struct mmu_rb_node *mnode)
{
	struct sdma_mmu_node *node =
		container_of(mnode, struct sdma_mmu_node, rb);

	atomic_inc(&node->refcount);
	return 0;
}

static void sdma_rb_remove(struct rb_root *root, struct mmu_rb_node *mnode,
1646
			   struct mm_struct *mm)
1647 1648 1649 1650
{
	struct sdma_mmu_node *node =
		container_of(mnode, struct sdma_mmu_node, rb);

1651
	spin_lock(&node->pq->evict_lock);
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
	/*
	 * We've been called by the MMU notifier but this node has been
	 * scheduled for eviction. The eviction function will take care
	 * of freeing this node.
	 * We have to take the above lock first because we are racing
	 * against the setting of the bit in the eviction function.
	 */
	if (mm && test_bit(SDMA_CACHE_NODE_EVICT, &node->flags)) {
		spin_unlock(&node->pq->evict_lock);
		return;
	}

1664 1665
	if (!list_empty(&node->list))
		list_del(&node->list);
1666 1667 1668
	node->pq->n_locked -= node->npages;
	spin_unlock(&node->pq->evict_lock);

1669 1670 1671 1672 1673 1674
	/*
	 * If mm is set, we are being called by the MMU notifier and we
	 * should not pass a mm_struct to unpin_vector_page(). This is to
	 * prevent a deadlock when hfi1_release_user_pages() attempts to
	 * take the mmap_sem, which the MMU notifier has already taken.
	 */
1675 1676
	unpin_vector_pages(mm ? NULL : current->mm, node->pages, 0,
			   node->npages);
1677 1678 1679 1680
	/*
	 * If called by the MMU notifier, we have to adjust the pinned
	 * page count ourselves.
	 */
1681 1682
	if (mm)
		mm->pinned_vm -= node->npages;
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
	kfree(node);
}

static int sdma_rb_invalidate(struct rb_root *root, struct mmu_rb_node *mnode)
{
	struct sdma_mmu_node *node =
		container_of(mnode, struct sdma_mmu_node, rb);

	if (!atomic_read(&node->refcount))
		return 1;
	return 0;
M
Mike Marciniszyn 已提交
1694
}