rpc_rdma.c 38.8 KB
Newer Older
1
/*
2
 * Copyright (c) 2014-2017 Oracle.  All rights reserved.
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
 * Copyright (c) 2003-2007 Network Appliance, Inc. All rights reserved.
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL) Version 2, available from the file
 * COPYING in the main directory of this source tree, or the BSD-type
 * license below:
 *
 * 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 the Network Appliance, Inc. 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.
 */

/*
 * rpc_rdma.c
 *
 * This file contains the guts of the RPC RDMA protocol, and
 * does marshaling/unmarshaling, etc. It is also where interfacing
 * to the Linux RPC framework lives.
47 48 49 50
 */

#include "xprt_rdma.h"

51 52
#include <linux/highmem.h>

Jeff Layton's avatar
Jeff Layton committed
53
#if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
54 55 56 57
# define RPCDBG_FACILITY	RPCDBG_TRANS
#endif

static const char transfertypes[][12] = {
58 59 60 61
	"inline",	/* no chunks */
	"read list",	/* some argument via rdma read */
	"*read list",	/* entire request via rdma read */
	"write list",	/* some result via rdma write */
62 63
	"reply chunk"	/* entire reply via rdma write */
};
64 65 66

/* Returns size of largest RPC-over-RDMA header in a Call message
 *
67 68
 * The largest Call header contains a full-size Read list and a
 * minimal Reply chunk.
69 70 71 72 73 74 75 76 77 78
 */
static unsigned int rpcrdma_max_call_header_size(unsigned int maxsegs)
{
	unsigned int size;

	/* Fixed header fields and list discriminators */
	size = RPCRDMA_HDRLEN_MIN;

	/* Maximum Read list size */
	maxsegs += 2;	/* segment for head and tail buffers */
79
	size = maxsegs * rpcrdma_readchunk_maxsz * sizeof(__be32);
80

81 82
	/* Minimal Read chunk size */
	size += sizeof(__be32);	/* segment count */
83
	size += rpcrdma_segment_maxsz * sizeof(__be32);
84 85
	size += sizeof(__be32);	/* list discriminator */

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	dprintk("RPC:       %s: max call header size = %u\n",
		__func__, size);
	return size;
}

/* Returns size of largest RPC-over-RDMA header in a Reply message
 *
 * There is only one Write list or one Reply chunk per Reply
 * message.  The larger list is the Write list.
 */
static unsigned int rpcrdma_max_reply_header_size(unsigned int maxsegs)
{
	unsigned int size;

	/* Fixed header fields and list discriminators */
	size = RPCRDMA_HDRLEN_MIN;

	/* Maximum Write list size */
	maxsegs += 2;	/* segment for head and tail buffers */
	size = sizeof(__be32);		/* segment count */
106
	size += maxsegs * rpcrdma_segment_maxsz * sizeof(__be32);
107 108 109 110 111 112 113
	size += sizeof(__be32);	/* list discriminator */

	dprintk("RPC:       %s: max reply header size = %u\n",
		__func__, size);
	return size;
}

114
void rpcrdma_set_max_header_sizes(struct rpcrdma_xprt *r_xprt)
115
{
116 117 118 119
	struct rpcrdma_create_data_internal *cdata = &r_xprt->rx_data;
	struct rpcrdma_ia *ia = &r_xprt->rx_ia;
	unsigned int maxsegs = ia->ri_max_segs;

120 121 122 123 124
	ia->ri_max_inline_write = cdata->inline_wsize -
				  rpcrdma_max_call_header_size(maxsegs);
	ia->ri_max_inline_read = cdata->inline_rsize -
				 rpcrdma_max_reply_header_size(maxsegs);
}
125

126 127 128
/* The client can send a request inline as long as the RPCRDMA header
 * plus the RPC call fit under the transport's inline limit. If the
 * combined call message size exceeds that limit, the client must use
129 130 131 132
 * a Read chunk for this operation.
 *
 * A Read chunk is also required if sending the RPC call inline would
 * exceed this device's max_sge limit.
133
 */
134 135
static bool rpcrdma_args_inline(struct rpcrdma_xprt *r_xprt,
				struct rpc_rqst *rqst)
136
{
137 138 139 140 141 142 143 144
	struct xdr_buf *xdr = &rqst->rq_snd_buf;
	unsigned int count, remaining, offset;

	if (xdr->len > r_xprt->rx_ia.ri_max_inline_write)
		return false;

	if (xdr->page_len) {
		remaining = xdr->page_len;
145
		offset = offset_in_page(xdr->page_base);
146 147 148 149 150 151 152 153 154 155 156
		count = 0;
		while (remaining) {
			remaining -= min_t(unsigned int,
					   PAGE_SIZE - offset, remaining);
			offset = 0;
			if (++count > r_xprt->rx_ia.ri_max_send_sges)
				return false;
		}
	}

	return true;
157 158 159 160 161 162 163 164
}

/* The client can't know how large the actual reply will be. Thus it
 * plans for the largest possible reply for that particular ULP
 * operation. If the maximum combined reply message size exceeds that
 * limit, the client must provide a write list or a reply chunk for
 * this request.
 */
165 166
static bool rpcrdma_results_inline(struct rpcrdma_xprt *r_xprt,
				   struct rpc_rqst *rqst)
167
{
168
	struct rpcrdma_ia *ia = &r_xprt->rx_ia;
169

170
	return rqst->rq_rcv_buf.buflen <= ia->ri_max_inline_read;
171 172
}

173 174 175 176 177 178
/* Split @vec on page boundaries into SGEs. FMR registers pages, not
 * a byte range. Other modes coalesce these SGEs into a single MR
 * when they can.
 *
 * Returns pointer to next available SGE, and bumps the total number
 * of SGEs consumed.
179
 */
180 181 182
static struct rpcrdma_mr_seg *
rpcrdma_convert_kvec(struct kvec *vec, struct rpcrdma_mr_seg *seg,
		     unsigned int *n)
183
{
184
	u32 remaining, page_offset;
185 186 187 188 189
	char *base;

	base = vec->iov_base;
	page_offset = offset_in_page(base);
	remaining = vec->iov_len;
190 191 192 193 194 195 196 197
	while (remaining) {
		seg->mr_page = NULL;
		seg->mr_offset = base;
		seg->mr_len = min_t(u32, PAGE_SIZE - page_offset, remaining);
		remaining -= seg->mr_len;
		base += seg->mr_len;
		++seg;
		++(*n);
198 199
		page_offset = 0;
	}
200
	return seg;
201 202
}

203 204 205
/* Convert @xdrbuf into SGEs no larger than a page each. As they
 * are registered, these SGEs are then coalesced into RDMA segments
 * when the selected memreg mode supports it.
206
 *
207
 * Returns positive number of SGEs consumed, or a negative errno.
208 209 210
 */

static int
211 212 213
rpcrdma_convert_iovs(struct rpcrdma_xprt *r_xprt, struct xdr_buf *xdrbuf,
		     unsigned int pos, enum rpcrdma_chunktype type,
		     struct rpcrdma_mr_seg *seg)
214
{
215 216
	unsigned long page_base;
	unsigned int len, n;
217
	struct page **ppages;
218

219
	n = 0;
220 221
	if (pos == 0)
		seg = rpcrdma_convert_kvec(&xdrbuf->head[0], seg, &n);
222

223 224
	len = xdrbuf->page_len;
	ppages = xdrbuf->pages + (xdrbuf->page_base >> PAGE_SHIFT);
225
	page_base = offset_in_page(xdrbuf->page_base);
226 227 228 229 230 231 232
	while (len) {
		if (unlikely(!*ppages)) {
			/* XXX: Certain upper layer operations do
			 *	not provide receive buffer pages.
			 */
			*ppages = alloc_page(GFP_ATOMIC);
			if (!*ppages)
233
				return -EAGAIN;
234
		}
235 236 237 238 239 240
		seg->mr_page = *ppages;
		seg->mr_offset = (char *)page_base;
		seg->mr_len = min_t(u32, PAGE_SIZE - page_base, len);
		len -= seg->mr_len;
		++ppages;
		++seg;
241
		++n;
242
		page_base = 0;
243 244
	}

245 246 247
	/* When encoding a Read chunk, the tail iovec contains an
	 * XDR pad and may be omitted.
	 */
248
	if (type == rpcrdma_readch && r_xprt->rx_ia.ri_implicit_roundup)
249
		goto out;
250

251 252 253 254
	/* When encoding a Write chunk, some servers need to see an
	 * extra segment for non-XDR-aligned Write chunks. The upper
	 * layer provides space in the tail iovec that may be used
	 * for this purpose.
255
	 */
256
	if (type == rpcrdma_writech && r_xprt->rx_ia.ri_implicit_roundup)
257
		goto out;
258

259 260
	if (xdrbuf->tail[0].iov_len)
		seg = rpcrdma_convert_kvec(&xdrbuf->tail[0], seg, &n);
261

262 263 264
out:
	if (unlikely(n > RPCRDMA_MAX_SEGS))
		return -EIO;
265 266 267
	return n;
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
static inline int
encode_item_present(struct xdr_stream *xdr)
{
	__be32 *p;

	p = xdr_reserve_space(xdr, sizeof(*p));
	if (unlikely(!p))
		return -EMSGSIZE;

	*p = xdr_one;
	return 0;
}

static inline int
encode_item_not_present(struct xdr_stream *xdr)
{
	__be32 *p;

	p = xdr_reserve_space(xdr, sizeof(*p));
	if (unlikely(!p))
		return -EMSGSIZE;
289

290 291
	*p = xdr_zero;
	return 0;
292 293
}

294
static void
295
xdr_encode_rdma_segment(__be32 *iptr, struct rpcrdma_mr *mr)
296
{
297 298 299
	*iptr++ = cpu_to_be32(mr->mr_handle);
	*iptr++ = cpu_to_be32(mr->mr_length);
	xdr_encode_hyper(iptr, mr->mr_offset);
300 301 302
}

static int
303
encode_rdma_segment(struct xdr_stream *xdr, struct rpcrdma_mr *mr)
304 305 306 307 308 309 310
{
	__be32 *p;

	p = xdr_reserve_space(xdr, 4 * sizeof(*p));
	if (unlikely(!p))
		return -EMSGSIZE;

311
	xdr_encode_rdma_segment(p, mr);
312 313 314 315
	return 0;
}

static int
316
encode_read_segment(struct xdr_stream *xdr, struct rpcrdma_mr *mr,
317 318 319 320 321 322 323 324 325 326
		    u32 position)
{
	__be32 *p;

	p = xdr_reserve_space(xdr, 6 * sizeof(*p));
	if (unlikely(!p))
		return -EMSGSIZE;

	*p++ = xdr_one;			/* Item present */
	*p++ = cpu_to_be32(position);
327
	xdr_encode_rdma_segment(p, mr);
328
	return 0;
329 330
}

331
/* Register and XDR encode the Read list. Supports encoding a list of read
332 333 334 335 336 337 338 339
 * segments that belong to a single read chunk.
 *
 * Encoding key for single-list chunks (HLOO = Handle32 Length32 Offset64):
 *
 *  Read chunklist (a linked list):
 *   N elements, position P (same P for all chunks of same arg!):
 *    1 - PHLOO - 1 - PHLOO - ... - 1 - PHLOO - 0
 *
340 341 342 343
 * Returns zero on success, or a negative errno if a failure occurred.
 * @xdr is advanced to the next position in the stream.
 *
 * Only a single @pos value is currently supported.
344
 */
345 346 347
static noinline int
rpcrdma_encode_read_list(struct rpcrdma_xprt *r_xprt, struct rpcrdma_req *req,
			 struct rpc_rqst *rqst, enum rpcrdma_chunktype rtype)
348
{
349
	struct xdr_stream *xdr = &req->rl_stream;
350
	struct rpcrdma_mr_seg *seg;
351
	struct rpcrdma_mr *mr;
352
	unsigned int pos;
353
	int nsegs;
354 355 356 357

	pos = rqst->rq_snd_buf.head[0].iov_len;
	if (rtype == rpcrdma_areadch)
		pos = 0;
358
	seg = req->rl_segments;
359 360
	nsegs = rpcrdma_convert_iovs(r_xprt, &rqst->rq_snd_buf, pos,
				     rtype, seg);
361
	if (nsegs < 0)
362
		return nsegs;
363 364

	do {
365
		seg = r_xprt->rx_ia.ri_ops->ro_map(r_xprt, seg, nsegs,
366
						   false, &mr);
367 368
		if (IS_ERR(seg))
			return PTR_ERR(seg);
369
		rpcrdma_mr_push(mr, &req->rl_registered);
370

371
		if (encode_read_segment(xdr, mr, pos) < 0)
372
			return -EMSGSIZE;
373

374
		dprintk("RPC: %5u %s: pos %u %u@0x%016llx:0x%08x (%s)\n",
375
			rqst->rq_task->tk_pid, __func__, pos,
376 377
			mr->mr_length, (unsigned long long)mr->mr_offset,
			mr->mr_handle, mr->mr_nents < nsegs ? "more" : "last");
378 379

		r_xprt->rx_stats.read_chunk_count++;
380
		nsegs -= mr->mr_nents;
381 382
	} while (nsegs);

383
	return 0;
384 385
}

386 387 388
/* Register and XDR encode the Write list. Supports encoding a list
 * containing one array of plain segments that belong to a single
 * write chunk.
389 390 391 392 393 394 395
 *
 * Encoding key for single-list chunks (HLOO = Handle32 Length32 Offset64):
 *
 *  Write chunklist (a list of (one) counted array):
 *   N elements:
 *    1 - N - HLOO - HLOO - ... - HLOO - 0
 *
396 397 398 399
 * Returns zero on success, or a negative errno if a failure occurred.
 * @xdr is advanced to the next position in the stream.
 *
 * Only a single Write chunk is currently supported.
400
 */
401
static noinline int
402
rpcrdma_encode_write_list(struct rpcrdma_xprt *r_xprt, struct rpcrdma_req *req,
403
			  struct rpc_rqst *rqst, enum rpcrdma_chunktype wtype)
404
{
405
	struct xdr_stream *xdr = &req->rl_stream;
406
	struct rpcrdma_mr_seg *seg;
407
	struct rpcrdma_mr *mr;
408
	int nsegs, nchunks;
409 410
	__be32 *segcount;

411
	seg = req->rl_segments;
412
	nsegs = rpcrdma_convert_iovs(r_xprt, &rqst->rq_rcv_buf,
413
				     rqst->rq_rcv_buf.head[0].iov_len,
414
				     wtype, seg);
415
	if (nsegs < 0)
416
		return nsegs;
417

418 419 420 421 422 423
	if (encode_item_present(xdr) < 0)
		return -EMSGSIZE;
	segcount = xdr_reserve_space(xdr, sizeof(*segcount));
	if (unlikely(!segcount))
		return -EMSGSIZE;
	/* Actual value encoded below */
424 425 426

	nchunks = 0;
	do {
427
		seg = r_xprt->rx_ia.ri_ops->ro_map(r_xprt, seg, nsegs,
428
						   true, &mr);
429 430
		if (IS_ERR(seg))
			return PTR_ERR(seg);
431
		rpcrdma_mr_push(mr, &req->rl_registered);
432

433
		if (encode_rdma_segment(xdr, mr) < 0)
434
			return -EMSGSIZE;
435

436
		dprintk("RPC: %5u %s: %u@0x016%llx:0x%08x (%s)\n",
437
			rqst->rq_task->tk_pid, __func__,
438 439
			mr->mr_length, (unsigned long long)mr->mr_offset,
			mr->mr_handle, mr->mr_nents < nsegs ? "more" : "last");
440 441 442 443

		r_xprt->rx_stats.write_chunk_count++;
		r_xprt->rx_stats.total_rdma_request += seg->mr_len;
		nchunks++;
444
		nsegs -= mr->mr_nents;
445 446 447 448 449
	} while (nsegs);

	/* Update count of segments in this Write chunk */
	*segcount = cpu_to_be32(nchunks);

450
	return 0;
451 452
}

453 454
/* Register and XDR encode the Reply chunk. Supports encoding an array
 * of plain segments that belong to a single write (reply) chunk.
455 456 457 458 459 460 461
 *
 * Encoding key for single-list chunks (HLOO = Handle32 Length32 Offset64):
 *
 *  Reply chunk (a counted array):
 *   N elements:
 *    1 - N - HLOO - HLOO - ... - HLOO
 *
462 463
 * Returns zero on success, or a negative errno if a failure occurred.
 * @xdr is advanced to the next position in the stream.
464
 */
465 466 467
static noinline int
rpcrdma_encode_reply_chunk(struct rpcrdma_xprt *r_xprt, struct rpcrdma_req *req,
			   struct rpc_rqst *rqst, enum rpcrdma_chunktype wtype)
468
{
469
	struct xdr_stream *xdr = &req->rl_stream;
470
	struct rpcrdma_mr_seg *seg;
471
	struct rpcrdma_mr *mr;
472
	int nsegs, nchunks;
473 474
	__be32 *segcount;

475
	seg = req->rl_segments;
476
	nsegs = rpcrdma_convert_iovs(r_xprt, &rqst->rq_rcv_buf, 0, wtype, seg);
477
	if (nsegs < 0)
478
		return nsegs;
479

480 481 482 483 484 485
	if (encode_item_present(xdr) < 0)
		return -EMSGSIZE;
	segcount = xdr_reserve_space(xdr, sizeof(*segcount));
	if (unlikely(!segcount))
		return -EMSGSIZE;
	/* Actual value encoded below */
486 487 488

	nchunks = 0;
	do {
489
		seg = r_xprt->rx_ia.ri_ops->ro_map(r_xprt, seg, nsegs,
490
						   true, &mr);
491 492
		if (IS_ERR(seg))
			return PTR_ERR(seg);
493
		rpcrdma_mr_push(mr, &req->rl_registered);
494

495
		if (encode_rdma_segment(xdr, mr) < 0)
496
			return -EMSGSIZE;
497

498
		dprintk("RPC: %5u %s: %u@0x%016llx:0x%08x (%s)\n",
499
			rqst->rq_task->tk_pid, __func__,
500 501
			mr->mr_length, (unsigned long long)mr->mr_offset,
			mr->mr_handle, mr->mr_nents < nsegs ? "more" : "last");
502 503 504 505

		r_xprt->rx_stats.reply_chunk_count++;
		r_xprt->rx_stats.total_rdma_request += seg->mr_len;
		nchunks++;
506
		nsegs -= mr->mr_nents;
507 508 509 510 511
	} while (nsegs);

	/* Update count of segments in the Reply chunk */
	*segcount = cpu_to_be32(nchunks);

512
	return 0;
513 514
}

515
/**
516 517
 * rpcrdma_unmap_sendctx - DMA-unmap Send buffers
 * @sc: sendctx containing SGEs to unmap
518 519 520
 *
 */
void
521
rpcrdma_unmap_sendctx(struct rpcrdma_sendctx *sc)
522
{
523
	struct rpcrdma_ia *ia = &sc->sc_xprt->rx_ia;
524 525 526
	struct ib_sge *sge;
	unsigned int count;

527 528 529
	dprintk("RPC:       %s: unmapping %u sges for sc=%p\n",
		__func__, sc->sc_unmap_count, sc);

530 531 532 533
	/* The first two SGEs contain the transport header and
	 * the inline buffer. These are always left mapped so
	 * they can be cheaply re-used.
	 */
534 535
	sge = &sc->sc_sges[2];
	for (count = sc->sc_unmap_count; count; ++sge, --count)
536 537
		ib_dma_unmap_page(ia->ri_device,
				  sge->addr, sge->length, DMA_TO_DEVICE);
538 539 540 541 542

	if (test_and_clear_bit(RPCRDMA_REQ_F_TX_RESOURCES, &sc->sc_req->rl_flags)) {
		smp_mb__after_atomic();
		wake_up_bit(&sc->sc_req->rl_flags, RPCRDMA_REQ_F_TX_RESOURCES);
	}
543 544
}

545
/* Prepare an SGE for the RPC-over-RDMA transport header.
546
 */
547 548 549
static bool
rpcrdma_prepare_hdr_sge(struct rpcrdma_ia *ia, struct rpcrdma_req *req,
			u32 len)
550
{
551
	struct rpcrdma_sendctx *sc = req->rl_sendctx;
552
	struct rpcrdma_regbuf *rb = req->rl_rdmabuf;
553
	struct ib_sge *sge = sc->sc_sges;
554

555 556 557
	if (!rpcrdma_dma_map_regbuf(ia, rb))
		goto out_regbuf;
	sge->addr = rdmab_addr(rb);
558
	sge->length = len;
559
	sge->lkey = rdmab_lkey(rb);
560

561
	ib_dma_sync_single_for_device(rdmab_device(rb), sge->addr,
562
				      sge->length, DMA_TO_DEVICE);
563
	sc->sc_wr.num_sge++;
564
	return true;
565 566 567 568

out_regbuf:
	pr_err("rpcrdma: failed to DMA map a Send buffer\n");
	return false;
569 570 571 572 573 574 575 576 577
}

/* Prepare the Send SGEs. The head and tail iovec, and each entry
 * in the page list, gets its own SGE.
 */
static bool
rpcrdma_prepare_msg_sges(struct rpcrdma_ia *ia, struct rpcrdma_req *req,
			 struct xdr_buf *xdr, enum rpcrdma_chunktype rtype)
{
578
	struct rpcrdma_sendctx *sc = req->rl_sendctx;
579 580 581
	unsigned int sge_no, page_base, len, remaining;
	struct rpcrdma_regbuf *rb = req->rl_sendbuf;
	struct ib_device *device = ia->ri_device;
582
	struct ib_sge *sge = sc->sc_sges;
583 584 585 586 587 588 589
	u32 lkey = ia->ri_pd->local_dma_lkey;
	struct page *page, **ppages;

	/* The head iovec is straightforward, as it is already
	 * DMA-mapped. Sync the content that has changed.
	 */
	if (!rpcrdma_dma_map_regbuf(ia, rb))
590
		goto out_regbuf;
591 592 593 594
	sge_no = 1;
	sge[sge_no].addr = rdmab_addr(rb);
	sge[sge_no].length = xdr->head[0].iov_len;
	sge[sge_no].lkey = rdmab_lkey(rb);
595
	ib_dma_sync_single_for_device(rdmab_device(rb), sge[sge_no].addr,
596 597 598 599 600 601 602 603 604 605
				      sge[sge_no].length, DMA_TO_DEVICE);

	/* If there is a Read chunk, the page list is being handled
	 * via explicit RDMA, and thus is skipped here. However, the
	 * tail iovec may include an XDR pad for the page list, as
	 * well as additional content, and may not reside in the
	 * same page as the head iovec.
	 */
	if (rtype == rpcrdma_readch) {
		len = xdr->tail[0].iov_len;
606

607 608 609
		/* Do not include the tail if it is only an XDR pad */
		if (len < 4)
			goto out;
610

611
		page = virt_to_page(xdr->tail[0].iov_base);
612
		page_base = offset_in_page(xdr->tail[0].iov_base);
613

614 615 616 617 618 619 620 621 622
		/* If the content in the page list is an odd length,
		 * xdr_write_pages() has added a pad at the beginning
		 * of the tail iovec. Force the tail's non-pad content
		 * to land at the next XDR position in the Send message.
		 */
		page_base += len & 3;
		len -= len & 3;
		goto map_tail;
	}
623

624 625 626 627 628
	/* If there is a page list present, temporarily DMA map
	 * and prepare an SGE for each page to be sent.
	 */
	if (xdr->page_len) {
		ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT);
629
		page_base = offset_in_page(xdr->page_base);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
		remaining = xdr->page_len;
		while (remaining) {
			sge_no++;
			if (sge_no > RPCRDMA_MAX_SEND_SGES - 2)
				goto out_mapping_overflow;

			len = min_t(u32, PAGE_SIZE - page_base, remaining);
			sge[sge_no].addr = ib_dma_map_page(device, *ppages,
							   page_base, len,
							   DMA_TO_DEVICE);
			if (ib_dma_mapping_error(device, sge[sge_no].addr))
				goto out_mapping_err;
			sge[sge_no].length = len;
			sge[sge_no].lkey = lkey;

645
			sc->sc_unmap_count++;
646 647 648
			ppages++;
			remaining -= len;
			page_base = 0;
649 650
		}
	}
651 652 653 654 655 656 657 658

	/* The tail iovec is not always constructed in the same
	 * page where the head iovec resides (see, for example,
	 * gss_wrap_req_priv). To neatly accommodate that case,
	 * DMA map it separately.
	 */
	if (xdr->tail[0].iov_len) {
		page = virt_to_page(xdr->tail[0].iov_base);
659
		page_base = offset_in_page(xdr->tail[0].iov_base);
660 661 662 663 664 665 666 667 668 669 670
		len = xdr->tail[0].iov_len;

map_tail:
		sge_no++;
		sge[sge_no].addr = ib_dma_map_page(device, page,
						   page_base, len,
						   DMA_TO_DEVICE);
		if (ib_dma_mapping_error(device, sge[sge_no].addr))
			goto out_mapping_err;
		sge[sge_no].length = len;
		sge[sge_no].lkey = lkey;
671
		sc->sc_unmap_count++;
672
	}
673 674

out:
675
	sc->sc_wr.num_sge += sge_no;
676 677
	if (sc->sc_unmap_count)
		__set_bit(RPCRDMA_REQ_F_TX_RESOURCES, &req->rl_flags);
678 679
	return true;

680 681 682 683
out_regbuf:
	pr_err("rpcrdma: failed to DMA map a Send buffer\n");
	return false;

684
out_mapping_overflow:
685
	rpcrdma_unmap_sendctx(sc);
686 687 688 689
	pr_err("rpcrdma: too many Send SGEs (%u)\n", sge_no);
	return false;

out_mapping_err:
690
	rpcrdma_unmap_sendctx(sc);
691 692 693 694
	pr_err("rpcrdma: Send mapping error\n");
	return false;
}

695 696 697 698 699 700 701 702 703 704 705 706 707 708
/**
 * rpcrdma_prepare_send_sges - Construct SGEs for a Send WR
 * @r_xprt: controlling transport
 * @req: context of RPC Call being marshalled
 * @hdrlen: size of transport header, in bytes
 * @xdr: xdr_buf containing RPC Call
 * @rtype: chunk type being encoded
 *
 * Returns 0 on success; otherwise a negative errno is returned.
 */
int
rpcrdma_prepare_send_sges(struct rpcrdma_xprt *r_xprt,
			  struct rpcrdma_req *req, u32 hdrlen,
			  struct xdr_buf *xdr, enum rpcrdma_chunktype rtype)
709
{
710 711 712 713 714
	req->rl_sendctx = rpcrdma_sendctx_get_locked(&r_xprt->rx_buf);
	if (!req->rl_sendctx)
		return -ENOBUFS;
	req->rl_sendctx->sc_wr.num_sge = 0;
	req->rl_sendctx->sc_unmap_count = 0;
715 716
	req->rl_sendctx->sc_req = req;
	__clear_bit(RPCRDMA_REQ_F_TX_RESOURCES, &req->rl_flags);
717

718 719
	if (!rpcrdma_prepare_hdr_sge(&r_xprt->rx_ia, req, hdrlen))
		return -EIO;
720 721

	if (rtype != rpcrdma_areadch)
722 723
		if (!rpcrdma_prepare_msg_sges(&r_xprt->rx_ia, req, xdr, rtype))
			return -EIO;
724

725
	return 0;
726 727
}

728 729 730 731 732 733 734 735 736 737
/**
 * rpcrdma_marshal_req - Marshal and send one RPC request
 * @r_xprt: controlling transport
 * @rqst: RPC request to be marshaled
 *
 * For the RPC in "rqst", this function:
 *  - Chooses the transfer mode (eg., RDMA_MSG or RDMA_NOMSG)
 *  - Registers Read, Write, and Reply chunks
 *  - Constructs the transport header
 *  - Posts a Send WR to send the transport header and request
738
 *
739 740 741 742 743
 * Returns:
 *	%0 if the RPC was sent successfully,
 *	%-ENOTCONN if the connection was lost,
 *	%-EAGAIN if not enough pages are available for on-demand reply buffer,
 *	%-ENOBUFS if no MRs are available to register chunks,
744
 *	%-EMSGSIZE if the transport header is too small,
745
 *	%-EIO if a permanent problem occurred while marshaling.
746 747
 */
int
748
rpcrdma_marshal_req(struct rpcrdma_xprt *r_xprt, struct rpc_rqst *rqst)
749 750
{
	struct rpcrdma_req *req = rpcr_to_rdmar(rqst);
751
	struct xdr_stream *xdr = &req->rl_stream;
752
	enum rpcrdma_chunktype rtype, wtype;
753
	bool ddp_allowed;
754
	__be32 *p;
755
	int ret;
756

757 758 759 760 761
	rpcrdma_set_xdrlen(&req->rl_hdrbuf, 0);
	xdr_init_encode(xdr, &req->rl_hdrbuf,
			req->rl_rdmabuf->rg_base);

	/* Fixed header fields */
762
	ret = -EMSGSIZE;
763 764 765 766 767 768
	p = xdr_reserve_space(xdr, 4 * sizeof(*p));
	if (!p)
		goto out_err;
	*p++ = rqst->rq_xid;
	*p++ = rpcrdma_version;
	*p++ = cpu_to_be32(r_xprt->rx_buf.rb_max_requests);
769

770 771 772 773 774 775 776
	/* When the ULP employs a GSS flavor that guarantees integrity
	 * or privacy, direct data placement of individual data items
	 * is not allowed.
	 */
	ddp_allowed = !(rqst->rq_cred->cr_auth->au_flags &
						RPCAUTH_AUTH_DATATOUCH);

777 778 779 780
	/*
	 * Chunks needed for results?
	 *
	 * o If the expected result is under the inline threshold, all ops
781
	 *   return as inline.
782 783
	 * o Large read ops return data as write chunk(s), header as
	 *   inline.
784 785
	 * o Large non-read ops return as a single reply chunk.
	 */
786
	if (rpcrdma_results_inline(r_xprt, rqst))
787
		wtype = rpcrdma_noch;
788
	else if (ddp_allowed && rqst->rq_rcv_buf.flags & XDRBUF_READ)
789
		wtype = rpcrdma_writech;
790
	else
791
		wtype = rpcrdma_replych;
792 793 794 795 796 797 798 799

	/*
	 * Chunks needed for arguments?
	 *
	 * o If the total request is under the inline threshold, all ops
	 *   are sent as inline.
	 * o Large write ops transmit data as read chunk(s), header as
	 *   inline.
800 801
	 * o Large non-write ops are sent with the entire message as a
	 *   single read chunk (protocol 0-position special case).
802
	 *
803 804 805
	 * This assumes that the upper layer does not present a request
	 * that both has a data payload, and whose non-data arguments
	 * by themselves are larger than the inline threshold.
806
	 */
807
	if (rpcrdma_args_inline(r_xprt, rqst)) {
808
		*p++ = rdma_msg;
809
		rtype = rpcrdma_noch;
810
	} else if (ddp_allowed && rqst->rq_snd_buf.flags & XDRBUF_WRITE) {
811
		*p++ = rdma_msg;
812
		rtype = rpcrdma_readch;
813
	} else {
814
		r_xprt->rx_stats.nomsg_call_count++;
815
		*p++ = rdma_nomsg;
816 817
		rtype = rpcrdma_areadch;
	}
818

819 820 821 822 823
	/* If this is a retransmit, discard previously registered
	 * chunks. Very likely the connection has been replaced,
	 * so these registrations are invalid and unusable.
	 */
	while (unlikely(!list_empty(&req->rl_registered))) {
824
		struct rpcrdma_mr *mr;
825

826 827
		mr = rpcrdma_mr_pop(&req->rl_registered);
		rpcrdma_mr_defer_recovery(mr);
828 829
	}

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
	/* This implementation supports the following combinations
	 * of chunk lists in one RPC-over-RDMA Call message:
	 *
	 *   - Read list
	 *   - Write list
	 *   - Reply chunk
	 *   - Read list + Reply chunk
	 *
	 * It might not yet support the following combinations:
	 *
	 *   - Read list + Write list
	 *
	 * It does not support the following combinations:
	 *
	 *   - Write list + Reply chunk
	 *   - Read list + Write list + Reply chunk
	 *
	 * This implementation supports only a single chunk in each
	 * Read or Write list. Thus for example the client cannot
	 * send a Call message with a Position Zero Read chunk and a
	 * regular Read chunk at the same time.
851
	 */
852 853 854 855 856 857 858
	if (rtype != rpcrdma_noch) {
		ret = rpcrdma_encode_read_list(r_xprt, req, rqst, rtype);
		if (ret)
			goto out_err;
	}
	ret = encode_item_not_present(xdr);
	if (ret)
859
		goto out_err;
860 861 862 863 864 865 866 867

	if (wtype == rpcrdma_writech) {
		ret = rpcrdma_encode_write_list(r_xprt, req, rqst, wtype);
		if (ret)
			goto out_err;
	}
	ret = encode_item_not_present(xdr);
	if (ret)
868
		goto out_err;
869 870 871 872 873 874

	if (wtype != rpcrdma_replych)
		ret = encode_item_not_present(xdr);
	else
		ret = rpcrdma_encode_reply_chunk(r_xprt, req, rqst, wtype);
	if (ret)
875
		goto out_err;
876

877
	dprintk("RPC: %5u %s: %s/%s: hdrlen %u rpclen\n",
878 879
		rqst->rq_task->tk_pid, __func__,
		transfertypes[rtype], transfertypes[wtype],
880
		xdr_stream_pos(xdr));
881

882 883 884
	ret = rpcrdma_prepare_send_sges(r_xprt, req, xdr_stream_pos(xdr),
					&rqst->rq_snd_buf, rtype);
	if (ret)
885
		goto out_err;
886
	return 0;
887

888
out_err:
889 890
	if (ret != -ENOBUFS) {
		pr_err("rpcrdma: header marshaling failed (%d)\n", ret);
891 892
		r_xprt->rx_stats.failed_marshal_count++;
	}
893
	return ret;
894 895
}

896 897 898 899 900 901 902 903 904 905
/**
 * rpcrdma_inline_fixup - Scatter inline received data into rqst's iovecs
 * @rqst: controlling RPC request
 * @srcp: points to RPC message payload in receive buffer
 * @copy_len: remaining length of receive buffer content
 * @pad: Write chunk pad bytes needed (zero for pure inline)
 *
 * The upper layer has set the maximum number of bytes it can
 * receive in each component of rq_rcv_buf. These values are set in
 * the head.iov_len, page_len, tail.iov_len, and buflen fields.
906 907 908 909 910
 *
 * Unlike the TCP equivalent (xdr_partial_copy_from_skb), in
 * many cases this function simply updates iov_base pointers in
 * rq_rcv_buf to point directly to the received reply data, to
 * avoid copying reply data.
911 912
 *
 * Returns the count of bytes which had to be memcopied.
913
 */
914
static unsigned long
915
rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len, int pad)
916
{
917 918
	unsigned long fixup_copy_count;
	int i, npages, curlen;
919
	char *destp;
920 921
	struct page **ppages;
	int page_base;
922

923 924 925 926
	/* The head iovec is redirected to the RPC reply message
	 * in the receive buffer, to avoid a memcopy.
	 */
	rqst->rq_rcv_buf.head[0].iov_base = srcp;
927
	rqst->rq_private_buf.head[0].iov_base = srcp;
928 929 930 931

	/* The contents of the receive buffer that follow
	 * head.iov_len bytes are copied into the page list.
	 */
932
	curlen = rqst->rq_rcv_buf.head[0].iov_len;
933
	if (curlen > copy_len)
934 935 936 937 938 939
		curlen = copy_len;
	dprintk("RPC:       %s: srcp 0x%p len %d hdrlen %d\n",
		__func__, srcp, copy_len, curlen);
	srcp += curlen;
	copy_len -= curlen;

940 941 942
	ppages = rqst->rq_rcv_buf.pages +
		(rqst->rq_rcv_buf.page_base >> PAGE_SHIFT);
	page_base = offset_in_page(rqst->rq_rcv_buf.page_base);
943
	fixup_copy_count = 0;
944
	if (copy_len && rqst->rq_rcv_buf.page_len) {
945 946 947 948 949 950
		int pagelist_len;

		pagelist_len = rqst->rq_rcv_buf.page_len;
		if (pagelist_len > copy_len)
			pagelist_len = copy_len;
		npages = PAGE_ALIGN(page_base + pagelist_len) >> PAGE_SHIFT;
951
		for (i = 0; i < npages; i++) {
952
			curlen = PAGE_SIZE - page_base;
953 954 955
			if (curlen > pagelist_len)
				curlen = pagelist_len;

956 957 958
			dprintk("RPC:       %s: page %d"
				" srcp 0x%p len %d curlen %d\n",
				__func__, i, srcp, copy_len, curlen);
959
			destp = kmap_atomic(ppages[i]);
960 961
			memcpy(destp + page_base, srcp, curlen);
			flush_dcache_page(ppages[i]);
962
			kunmap_atomic(destp);
963 964
			srcp += curlen;
			copy_len -= curlen;
965
			fixup_copy_count += curlen;
966 967
			pagelist_len -= curlen;
			if (!pagelist_len)
968
				break;
969
			page_base = 0;
970 971
		}

972 973 974 975 976 977 978 979
		/* Implicit padding for the last segment in a Write
		 * chunk is inserted inline at the front of the tail
		 * iovec. The upper layer ignores the content of
		 * the pad. Simply ensure inline content in the tail
		 * that follows the Write chunk is properly aligned.
		 */
		if (pad)
			srcp -= pad;
980 981
	}

982 983 984
	/* The tail iovec is redirected to the remaining data
	 * in the receive buffer, to avoid a memcopy.
	 */
985
	if (copy_len || pad) {
986
		rqst->rq_rcv_buf.tail[0].iov_base = srcp;
987 988
		rqst->rq_private_buf.tail[0].iov_base = srcp;
	}
989

990
	return fixup_copy_count;
991 992
}

993 994 995 996 997 998
/* By convention, backchannel calls arrive via rdma_msg type
 * messages, and never populate the chunk lists. This makes
 * the RPC/RDMA header small and fixed in size, so it is
 * straightforward to check the RPC header's direction field.
 */
static bool
999
rpcrdma_is_bcall(struct rpcrdma_xprt *r_xprt, struct rpcrdma_rep *rep)
1000
#if defined(CONFIG_SUNRPC_BACKCHANNEL)
1001
{
1002 1003
	struct xdr_stream *xdr = &rep->rr_stream;
	__be32 *p;
1004

1005
	if (rep->rr_proc != rdma_msg)
1006
		return false;
1007 1008 1009 1010 1011 1012

	/* Peek at stream contents without advancing. */
	p = xdr_inline_decode(xdr, 0);

	/* Chunk lists */
	if (*p++ != xdr_zero)
1013
		return false;
1014
	if (*p++ != xdr_zero)
1015
		return false;
1016
	if (*p++ != xdr_zero)
1017 1018
		return false;

1019
	/* RPC header */
1020
	if (*p++ != rep->rr_xid)
1021
		return false;
1022
	if (*p != cpu_to_be32(RPC_CALL))
1023 1024
		return false;

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
	/* Now that we are sure this is a backchannel call,
	 * advance to the RPC header.
	 */
	p = xdr_inline_decode(xdr, 3 * sizeof(*p));
	if (unlikely(!p))
		goto out_short;

	rpcrdma_bc_receive_call(r_xprt, rep);
	return true;

out_short:
	pr_warn("RPC/RDMA short backward direction call\n");
	if (rpcrdma_ep_post_recv(&r_xprt->rx_ia, rep))
		xprt_disconnect_done(&r_xprt->rx_xprt);
1039 1040
	return true;
}
1041 1042 1043 1044
#else	/* CONFIG_SUNRPC_BACKCHANNEL */
{
	return false;
}
1045 1046
#endif	/* CONFIG_SUNRPC_BACKCHANNEL */

1047
static int decode_rdma_segment(struct xdr_stream *xdr, u32 *length)
1048 1049 1050
{
	__be32 *p;

1051
	p = xdr_inline_decode(xdr, 4 * sizeof(*p));
1052 1053 1054
	if (unlikely(!p))
		return -EIO;

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	ifdebug(FACILITY) {
		u64 offset;
		u32 handle;

		handle = be32_to_cpup(p++);
		*length = be32_to_cpup(p++);
		xdr_decode_hyper(p, &offset);
		dprintk("RPC:       %s:   segment %u@0x%016llx:0x%08x\n",
			__func__, *length, (unsigned long long)offset,
			handle);
	} else {
		*length = be32_to_cpup(p + 1);
	}

	return 0;
}
1071

1072 1073 1074 1075 1076 1077 1078 1079
static int decode_write_chunk(struct xdr_stream *xdr, u32 *length)
{
	u32 segcount, seglength;
	__be32 *p;

	p = xdr_inline_decode(xdr, sizeof(*p));
	if (unlikely(!p))
		return -EIO;
1080

1081 1082 1083 1084
	*length = 0;
	segcount = be32_to_cpup(p);
	while (segcount--) {
		if (decode_rdma_segment(xdr, &seglength))
1085
			return -EIO;
1086 1087
		*length += seglength;
	}
1088

1089 1090 1091 1092
	dprintk("RPC:       %s: segcount=%u, %u bytes\n",
		__func__, be32_to_cpup(p), *length);
	return 0;
}
1093

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
/* In RPC-over-RDMA Version One replies, a Read list is never
 * expected. This decoder is a stub that returns an error if
 * a Read list is present.
 */
static int decode_read_list(struct xdr_stream *xdr)
{
	__be32 *p;

	p = xdr_inline_decode(xdr, sizeof(*p));
	if (unlikely(!p))
		return -EIO;
	if (unlikely(*p != xdr_zero))
		return -EIO;
	return 0;
}

/* Supports only one Write chunk in the Write list
 */
static int decode_write_list(struct xdr_stream *xdr, u32 *length)
{
	u32 chunklen;
	bool first;
	__be32 *p;

	*length = 0;
	first = true;
	do {
1121
		p = xdr_inline_decode(xdr, sizeof(*p));
1122 1123 1124 1125 1126
		if (unlikely(!p))
			return -EIO;
		if (*p == xdr_zero)
			break;
		if (!first)
1127 1128
			return -EIO;

1129
		if (decode_write_chunk(xdr, &chunklen))
1130
			return -EIO;
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
		*length += chunklen;
		first = false;
	} while (true);
	return 0;
}

static int decode_reply_chunk(struct xdr_stream *xdr, u32 *length)
{
	__be32 *p;

	p = xdr_inline_decode(xdr, sizeof(*p));
	if (unlikely(!p))
		return -EIO;

	*length = 0;
	if (*p != xdr_zero)
		if (decode_write_chunk(xdr, length))
			return -EIO;
	return 0;
}
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
static int
rpcrdma_decode_msg(struct rpcrdma_xprt *r_xprt, struct rpcrdma_rep *rep,
		   struct rpc_rqst *rqst)
{
	struct xdr_stream *xdr = &rep->rr_stream;
	u32 writelist, replychunk, rpclen;
	char *base;

	/* Decode the chunk lists */
	if (decode_read_list(xdr))
		return -EIO;
	if (decode_write_list(xdr, &writelist))
		return -EIO;
	if (decode_reply_chunk(xdr, &replychunk))
		return -EIO;

	/* RDMA_MSG sanity checks */
	if (unlikely(replychunk))
		return -EIO;

	/* Build the RPC reply's Payload stream in rqst->rq_rcv_buf */
	base = (char *)xdr_inline_decode(xdr, 0);
	rpclen = xdr_stream_remaining(xdr);
1175
	r_xprt->rx_stats.fixup_copy_count +=
1176
		rpcrdma_inline_fixup(rqst, base, rpclen, writelist & 3);
1177

1178 1179
	r_xprt->rx_stats.total_rdma_reply += writelist;
	return rpclen + xdr_align_size(writelist);
1180 1181 1182 1183 1184 1185
}

static noinline int
rpcrdma_decode_nomsg(struct rpcrdma_xprt *r_xprt, struct rpcrdma_rep *rep)
{
	struct xdr_stream *xdr = &rep->rr_stream;
1186
	u32 writelist, replychunk;
1187

1188 1189
	/* Decode the chunk lists */
	if (decode_read_list(xdr))
1190
		return -EIO;
1191
	if (decode_write_list(xdr, &writelist))
1192
		return -EIO;
1193
	if (decode_reply_chunk(xdr, &replychunk))
1194 1195
		return -EIO;

1196 1197 1198 1199
	/* RDMA_NOMSG sanity checks */
	if (unlikely(writelist))
		return -EIO;
	if (unlikely(!replychunk))
1200 1201
		return -EIO;

1202 1203 1204
	/* Reply chunk buffer already is the reply vector */
	r_xprt->rx_stats.total_rdma_reply += replychunk;
	return replychunk;
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
}

static noinline int
rpcrdma_decode_error(struct rpcrdma_xprt *r_xprt, struct rpcrdma_rep *rep,
		     struct rpc_rqst *rqst)
{
	struct xdr_stream *xdr = &rep->rr_stream;
	__be32 *p;

	p = xdr_inline_decode(xdr, sizeof(*p));
	if (unlikely(!p))
		return -EIO;

	switch (*p) {
	case err_vers:
		p = xdr_inline_decode(xdr, 2 * sizeof(*p));
		if (!p)
			break;
		dprintk("RPC: %5u: %s: server reports version error (%u-%u)\n",
			rqst->rq_task->tk_pid, __func__,
			be32_to_cpup(p), be32_to_cpu(*(p + 1)));
		break;
	case err_chunk:
		dprintk("RPC: %5u: %s: server reports header decoding error\n",
			rqst->rq_task->tk_pid, __func__);
		break;
	default:
		dprintk("RPC: %5u: %s: server reports unrecognized error %d\n",
			rqst->rq_task->tk_pid, __func__, be32_to_cpup(p));
	}

	r_xprt->rx_stats.bad_reply_count++;
	return -EREMOTEIO;
}

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
/* Perform XID lookup, reconstruction of the RPC reply, and
 * RPC completion while holding the transport lock to ensure
 * the rep, rqst, and rq_task pointers remain stable.
 */
void rpcrdma_complete_rqst(struct rpcrdma_rep *rep)
{
	struct rpcrdma_xprt *r_xprt = rep->rr_rxprt;
	struct rpc_xprt *xprt = &r_xprt->rx_xprt;
	struct rpc_rqst *rqst = rep->rr_rqst;
	unsigned long cwnd;
	int status;

	xprt->reestablish_timeout = 0;

	switch (rep->rr_proc) {
	case rdma_msg:
		status = rpcrdma_decode_msg(r_xprt, rep, rqst);
		break;
	case rdma_nomsg:
		status = rpcrdma_decode_nomsg(r_xprt, rep);
		break;
	case rdma_error:
		status = rpcrdma_decode_error(r_xprt, rep, rqst);
		break;
	default:
		status = -EIO;
	}
	if (status < 0)
		goto out_badheader;

out:
	spin_lock(&xprt->recv_lock);
	cwnd = xprt->cwnd;
1273
	xprt->cwnd = r_xprt->rx_buf.rb_credits << RPC_CWNDSHIFT;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
	if (xprt->cwnd > cwnd)
		xprt_release_rqst_cong(rqst->rq_task);

	xprt_complete_rqst(rqst->rq_task, status);
	xprt_unpin_rqst(rqst);
	spin_unlock(&xprt->recv_lock);
	return;

/* If the incoming reply terminated a pending RPC, the next
 * RPC call will post a replacement receive buffer as it is
 * being marshaled.
 */
out_badheader:
	dprintk("RPC: %5u %s: invalid rpcrdma reply (type %u)\n",
		rqst->rq_task->tk_pid, __func__, be32_to_cpu(rep->rr_proc));
	r_xprt->rx_stats.bad_reply_count++;
	status = -EIO;
	goto out;
}

1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
void rpcrdma_release_rqst(struct rpcrdma_xprt *r_xprt, struct rpcrdma_req *req)
{
	/* Invalidate and unmap the data payloads before waking
	 * the waiting application. This guarantees the memory
	 * regions are properly fenced from the server before the
	 * application accesses the data. It also ensures proper
	 * send flow control: waking the next RPC waits until this
	 * RPC has relinquished all its Send Queue entries.
	 */
	if (!list_empty(&req->rl_registered))
		r_xprt->rx_ia.ri_ops->ro_unmap_sync(r_xprt,
						    &req->rl_registered);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

	/* Ensure that any DMA mapped pages associated with
	 * the Send of the RPC Call have been unmapped before
	 * allowing the RPC to complete. This protects argument
	 * memory not controlled by the RPC client from being
	 * re-used before we're done with it.
	 */
	if (test_bit(RPCRDMA_REQ_F_TX_RESOURCES, &req->rl_flags)) {
		r_xprt->rx_stats.reply_waits_for_send++;
		out_of_line_wait_on_bit(&req->rl_flags,
					RPCRDMA_REQ_F_TX_RESOURCES,
					bit_wait,
					TASK_UNINTERRUPTIBLE);
	}
1320 1321
}

1322 1323 1324 1325 1326 1327 1328 1329
/* Reply handling runs in the poll worker thread. Anything that
 * might wait is deferred to a separate workqueue.
 */
void rpcrdma_deferred_completion(struct work_struct *work)
{
	struct rpcrdma_rep *rep =
			container_of(work, struct rpcrdma_rep, rr_work);
	struct rpcrdma_req *req = rpcr_to_rdmar(rep->rr_rqst);
1330
	struct rpcrdma_xprt *r_xprt = rep->rr_rxprt;
1331

1332 1333 1334
	if (rep->rr_wc_flags & IB_WC_WITH_INVALIDATE)
		r_xprt->rx_ia.ri_ops->ro_reminv(rep, &req->rl_registered);
	rpcrdma_release_rqst(r_xprt, req);
1335 1336 1337
	rpcrdma_complete_rqst(rep);
}

1338 1339
/* Process received RPC/RDMA messages.
 *
1340 1341 1342
 * Errors must result in the RPC task either being awakened, or
 * allowed to timeout, to discover the errors at that time.
 */
1343
void rpcrdma_reply_handler(struct rpcrdma_rep *rep)
1344
{
1345 1346
	struct rpcrdma_xprt *r_xprt = rep->rr_rxprt;
	struct rpc_xprt *xprt = &r_xprt->rx_xprt;
1347
	struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
1348 1349
	struct rpcrdma_req *req;
	struct rpc_rqst *rqst;
1350
	u32 credits;
1351
	__be32 *p;
1352

1353 1354
	dprintk("RPC:       %s: incoming rep %p\n", __func__, rep);

1355
	if (rep->rr_hdrbuf.head[0].iov_len == 0)
1356
		goto out_badstatus;
1357

1358
	xdr_init_decode(&rep->rr_stream, &rep->rr_hdrbuf,
1359 1360 1361
			rep->rr_hdrbuf.head[0].iov_base);

	/* Fixed transport header fields */
1362
	p = xdr_inline_decode(&rep->rr_stream, 4 * sizeof(*p));
1363
	if (unlikely(!p))
1364
		goto out_shortreply;
1365 1366
	rep->rr_xid = *p++;
	rep->rr_vers = *p++;
1367
	credits = be32_to_cpu(*p++);
1368
	rep->rr_proc = *p++;
1369

1370
	if (rep->rr_vers != rpcrdma_version)
1371 1372
		goto out_badversion;

1373
	if (rpcrdma_is_bcall(r_xprt, rep))
1374
		return;
1375

1376 1377 1378
	/* Match incoming rpcrdma_rep to an rpcrdma_req to
	 * get context for handling any incoming chunks.
	 */
1379
	spin_lock(&xprt->recv_lock);
1380
	rqst = xprt_lookup_rqst(xprt, rep->rr_xid);
1381 1382 1383
	if (!rqst)
		goto out_norqst;
	xprt_pin_rqst(rqst);
1384 1385 1386 1387 1388 1389 1390

	if (credits == 0)
		credits = 1;	/* don't deadlock */
	else if (credits > buf->rb_max_requests)
		credits = buf->rb_max_requests;
	buf->rb_credits = credits;

1391
	spin_unlock(&xprt->recv_lock);
1392

1393
	req = rpcr_to_rdmar(rqst);
1394
	req->rl_reply = rep;
1395
	rep->rr_rqst = rqst;
1396
	clear_bit(RPCRDMA_REQ_F_PENDING, &req->rl_flags);
1397

1398
	dprintk("RPC:       %s: reply %p completes request %p (xid 0x%08x)\n",
1399
		__func__, rep, req, be32_to_cpu(rep->rr_xid));
1400

1401
	queue_work_on(req->rl_cpu, rpcrdma_receive_wq, &rep->rr_work);
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
	return;

out_badstatus:
	rpcrdma_recv_buffer_put(rep);
	if (r_xprt->rx_ep.rep_connected == 1) {
		r_xprt->rx_ep.rep_connected = -EIO;
		rpcrdma_conn_func(&r_xprt->rx_ep);
	}
	return;

out_badversion:
	dprintk("RPC:       %s: invalid version %d\n",
1414
		__func__, be32_to_cpu(rep->rr_vers));
1415
	goto repost;
1416

1417 1418
/* The RPC transaction has already been terminated, or the header
 * is corrupt.
1419
 */
1420
out_norqst:
1421
	spin_unlock(&xprt->recv_lock);
1422
	dprintk("RPC:       %s: no match for incoming xid 0x%08x\n",
1423
		__func__, be32_to_cpu(rep->rr_xid));
1424 1425
	goto repost;

1426 1427
out_shortreply:
	dprintk("RPC:       %s: short/invalid reply\n", __func__);
1428

1429 1430 1431
/* If no pending RPC transaction was matched, post a replacement
 * receive buffer before returning.
 */
1432 1433
repost:
	r_xprt->rx_stats.bad_reply_count++;
1434
	if (rpcrdma_ep_post_recv(&r_xprt->rx_ia, rep))
1435
		rpcrdma_recv_buffer_put(rep);
1436
}