1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /*
3  * Copyright (c) 2016-2018 Oracle. All rights reserved.
4  * Copyright (c) 2014 Open Grid Computing, Inc. All rights reserved.
5  * Copyright (c) 2005-2006 Network Appliance, Inc. All rights reserved.
6  *
7  * This software is available to you under a choice of one of two
8  * licenses.  You may choose to be licensed under the terms of the GNU
9  * General Public License (GPL) Version 2, available from the file
10  * COPYING in the main directory of this source tree, or the BSD-type
11  * license below:
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  *
17  *      Redistributions of source code must retain the above copyright
18  *      notice, this list of conditions and the following disclaimer.
19  *
20  *      Redistributions in binary form must reproduce the above
21  *      copyright notice, this list of conditions and the following
22  *      disclaimer in the documentation and/or other materials provided
23  *      with the distribution.
24  *
25  *      Neither the name of the Network Appliance, Inc. nor the names of
26  *      its contributors may be used to endorse or promote products
27  *      derived from this software without specific prior written
28  *      permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41  *
42  * Author: Tom Tucker <tom@opengridcomputing.com>
43  */
44 
45 /* Operation
46  *
47  * The main entry point is svc_rdma_sendto. This is called by the
48  * RPC server when an RPC Reply is ready to be transmitted to a client.
49  *
50  * The passed-in svc_rqst contains a struct xdr_buf which holds an
51  * XDR-encoded RPC Reply message. sendto must construct the RPC-over-RDMA
52  * transport header, post all Write WRs needed for this Reply, then post
53  * a Send WR conveying the transport header and the RPC message itself to
54  * the client.
55  *
56  * svc_rdma_sendto must fully transmit the Reply before returning, as
57  * the svc_rqst will be recycled as soon as sendto returns. Remaining
58  * resources referred to by the svc_rqst are also recycled at that time.
59  * Therefore any resources that must remain longer must be detached
60  * from the svc_rqst and released later.
61  *
62  * Page Management
63  *
64  * The I/O that performs Reply transmission is asynchronous, and may
65  * complete well after sendto returns. Thus pages under I/O must be
66  * removed from the svc_rqst before sendto returns.
67  *
68  * The logic here depends on Send Queue and completion ordering. Since
69  * the Send WR is always posted last, it will always complete last. Thus
70  * when it completes, it is guaranteed that all previous Write WRs have
71  * also completed.
72  *
73  * Write WRs are constructed and posted. Each Write segment gets its own
74  * svc_rdma_rw_ctxt, allowing the Write completion handler to find and
75  * DMA-unmap the pages under I/O for that Write segment. The Write
76  * completion handler does not release any pages.
77  *
78  * When the Send WR is constructed, it also gets its own svc_rdma_send_ctxt.
79  * The ownership of all of the Reply's pages are transferred into that
80  * ctxt, the Send WR is posted, and sendto returns.
81  *
82  * The svc_rdma_send_ctxt is presented when the Send WR completes. The
83  * Send completion handler finally releases the Reply's pages.
84  *
85  * This mechanism also assumes that completions on the transport's Send
86  * Completion Queue do not run in parallel. Otherwise a Write completion
87  * and Send completion running at the same time could release pages that
88  * are still DMA-mapped.
89  *
90  * Error Handling
91  *
92  * - If the Send WR is posted successfully, it will either complete
93  *   successfully, or get flushed. Either way, the Send completion
94  *   handler releases the Reply's pages.
95  * - If the Send WR cannot be not posted, the forward path releases
96  *   the Reply's pages.
97  *
98  * This handles the case, without the use of page reference counting,
99  * where two different Write segments send portions of the same page.
100  */
101 
102 #include <linux/spinlock.h>
103 #include <asm/unaligned.h>
104 
105 #include <rdma/ib_verbs.h>
106 #include <rdma/rdma_cm.h>
107 
108 #include <linux/sunrpc/debug.h>
109 #include <linux/sunrpc/svc_rdma.h>
110 
111 #include "xprt_rdma.h"
112 #include <trace/events/rpcrdma.h>
113 
114 #define RPCDBG_FACILITY	RPCDBG_SVCXPRT
115 
116 static void svc_rdma_wc_send(struct ib_cq *cq, struct ib_wc *wc);
117 
118 static inline struct svc_rdma_send_ctxt *
119 svc_rdma_next_send_ctxt(struct list_head *list)
120 {
121 	return list_first_entry_or_null(list, struct svc_rdma_send_ctxt,
122 					sc_list);
123 }
124 
125 static void svc_rdma_send_cid_init(struct svcxprt_rdma *rdma,
126 				   struct rpc_rdma_cid *cid)
127 {
128 	cid->ci_queue_id = rdma->sc_sq_cq->res.id;
129 	cid->ci_completion_id = atomic_inc_return(&rdma->sc_completion_ids);
130 }
131 
132 static struct svc_rdma_send_ctxt *
133 svc_rdma_send_ctxt_alloc(struct svcxprt_rdma *rdma)
134 {
135 	struct svc_rdma_send_ctxt *ctxt;
136 	dma_addr_t addr;
137 	void *buffer;
138 	size_t size;
139 	int i;
140 
141 	size = sizeof(*ctxt);
142 	size += rdma->sc_max_send_sges * sizeof(struct ib_sge);
143 	ctxt = kmalloc(size, GFP_KERNEL);
144 	if (!ctxt)
145 		goto fail0;
146 	buffer = kmalloc(rdma->sc_max_req_size, GFP_KERNEL);
147 	if (!buffer)
148 		goto fail1;
149 	addr = ib_dma_map_single(rdma->sc_pd->device, buffer,
150 				 rdma->sc_max_req_size, DMA_TO_DEVICE);
151 	if (ib_dma_mapping_error(rdma->sc_pd->device, addr))
152 		goto fail2;
153 
154 	svc_rdma_send_cid_init(rdma, &ctxt->sc_cid);
155 
156 	ctxt->sc_send_wr.next = NULL;
157 	ctxt->sc_send_wr.wr_cqe = &ctxt->sc_cqe;
158 	ctxt->sc_send_wr.sg_list = ctxt->sc_sges;
159 	ctxt->sc_send_wr.send_flags = IB_SEND_SIGNALED;
160 	ctxt->sc_cqe.done = svc_rdma_wc_send;
161 	ctxt->sc_xprt_buf = buffer;
162 	xdr_buf_init(&ctxt->sc_hdrbuf, ctxt->sc_xprt_buf,
163 		     rdma->sc_max_req_size);
164 	ctxt->sc_sges[0].addr = addr;
165 
166 	for (i = 0; i < rdma->sc_max_send_sges; i++)
167 		ctxt->sc_sges[i].lkey = rdma->sc_pd->local_dma_lkey;
168 	return ctxt;
169 
170 fail2:
171 	kfree(buffer);
172 fail1:
173 	kfree(ctxt);
174 fail0:
175 	return NULL;
176 }
177 
178 /**
179  * svc_rdma_send_ctxts_destroy - Release all send_ctxt's for an xprt
180  * @rdma: svcxprt_rdma being torn down
181  *
182  */
183 void svc_rdma_send_ctxts_destroy(struct svcxprt_rdma *rdma)
184 {
185 	struct svc_rdma_send_ctxt *ctxt;
186 
187 	while ((ctxt = svc_rdma_next_send_ctxt(&rdma->sc_send_ctxts))) {
188 		list_del(&ctxt->sc_list);
189 		ib_dma_unmap_single(rdma->sc_pd->device,
190 				    ctxt->sc_sges[0].addr,
191 				    rdma->sc_max_req_size,
192 				    DMA_TO_DEVICE);
193 		kfree(ctxt->sc_xprt_buf);
194 		kfree(ctxt);
195 	}
196 }
197 
198 /**
199  * svc_rdma_send_ctxt_get - Get a free send_ctxt
200  * @rdma: controlling svcxprt_rdma
201  *
202  * Returns a ready-to-use send_ctxt, or NULL if none are
203  * available and a fresh one cannot be allocated.
204  */
205 struct svc_rdma_send_ctxt *svc_rdma_send_ctxt_get(struct svcxprt_rdma *rdma)
206 {
207 	struct svc_rdma_send_ctxt *ctxt;
208 
209 	spin_lock(&rdma->sc_send_lock);
210 	ctxt = svc_rdma_next_send_ctxt(&rdma->sc_send_ctxts);
211 	if (!ctxt)
212 		goto out_empty;
213 	list_del(&ctxt->sc_list);
214 	spin_unlock(&rdma->sc_send_lock);
215 
216 out:
217 	rpcrdma_set_xdrlen(&ctxt->sc_hdrbuf, 0);
218 	xdr_init_encode(&ctxt->sc_stream, &ctxt->sc_hdrbuf,
219 			ctxt->sc_xprt_buf, NULL);
220 
221 	ctxt->sc_send_wr.num_sge = 0;
222 	ctxt->sc_cur_sge_no = 0;
223 	ctxt->sc_page_count = 0;
224 	return ctxt;
225 
226 out_empty:
227 	spin_unlock(&rdma->sc_send_lock);
228 	ctxt = svc_rdma_send_ctxt_alloc(rdma);
229 	if (!ctxt)
230 		return NULL;
231 	goto out;
232 }
233 
234 /**
235  * svc_rdma_send_ctxt_put - Return send_ctxt to free list
236  * @rdma: controlling svcxprt_rdma
237  * @ctxt: object to return to the free list
238  *
239  * Pages left in sc_pages are DMA unmapped and released.
240  */
241 void svc_rdma_send_ctxt_put(struct svcxprt_rdma *rdma,
242 			    struct svc_rdma_send_ctxt *ctxt)
243 {
244 	struct ib_device *device = rdma->sc_cm_id->device;
245 	unsigned int i;
246 
247 	/* The first SGE contains the transport header, which
248 	 * remains mapped until @ctxt is destroyed.
249 	 */
250 	for (i = 1; i < ctxt->sc_send_wr.num_sge; i++) {
251 		ib_dma_unmap_page(device,
252 				  ctxt->sc_sges[i].addr,
253 				  ctxt->sc_sges[i].length,
254 				  DMA_TO_DEVICE);
255 		trace_svcrdma_dma_unmap_page(rdma,
256 					     ctxt->sc_sges[i].addr,
257 					     ctxt->sc_sges[i].length);
258 	}
259 
260 	for (i = 0; i < ctxt->sc_page_count; ++i)
261 		put_page(ctxt->sc_pages[i]);
262 
263 	spin_lock(&rdma->sc_send_lock);
264 	list_add(&ctxt->sc_list, &rdma->sc_send_ctxts);
265 	spin_unlock(&rdma->sc_send_lock);
266 }
267 
268 /**
269  * svc_rdma_wc_send - Invoked by RDMA provider for each polled Send WC
270  * @cq: Completion Queue context
271  * @wc: Work Completion object
272  *
273  * NB: The svc_xprt/svcxprt_rdma is pinned whenever it's possible that
274  * the Send completion handler could be running.
275  */
276 static void svc_rdma_wc_send(struct ib_cq *cq, struct ib_wc *wc)
277 {
278 	struct svcxprt_rdma *rdma = cq->cq_context;
279 	struct ib_cqe *cqe = wc->wr_cqe;
280 	struct svc_rdma_send_ctxt *ctxt =
281 		container_of(cqe, struct svc_rdma_send_ctxt, sc_cqe);
282 
283 	trace_svcrdma_wc_send(wc, &ctxt->sc_cid);
284 
285 	atomic_inc(&rdma->sc_sq_avail);
286 	wake_up(&rdma->sc_send_wait);
287 
288 	svc_rdma_send_ctxt_put(rdma, ctxt);
289 
290 	if (unlikely(wc->status != IB_WC_SUCCESS)) {
291 		set_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags);
292 		svc_xprt_enqueue(&rdma->sc_xprt);
293 	}
294 }
295 
296 /**
297  * svc_rdma_send - Post a single Send WR
298  * @rdma: transport on which to post the WR
299  * @ctxt: send ctxt with a Send WR ready to post
300  *
301  * Returns zero the Send WR was posted successfully. Otherwise, a
302  * negative errno is returned.
303  */
304 int svc_rdma_send(struct svcxprt_rdma *rdma, struct svc_rdma_send_ctxt *ctxt)
305 {
306 	struct ib_send_wr *wr = &ctxt->sc_send_wr;
307 	int ret;
308 
309 	might_sleep();
310 
311 	/* Sync the transport header buffer */
312 	ib_dma_sync_single_for_device(rdma->sc_pd->device,
313 				      wr->sg_list[0].addr,
314 				      wr->sg_list[0].length,
315 				      DMA_TO_DEVICE);
316 
317 	/* If the SQ is full, wait until an SQ entry is available */
318 	while (1) {
319 		if ((atomic_dec_return(&rdma->sc_sq_avail) < 0)) {
320 			atomic_inc(&rdma_stat_sq_starve);
321 			trace_svcrdma_sq_full(rdma);
322 			atomic_inc(&rdma->sc_sq_avail);
323 			wait_event(rdma->sc_send_wait,
324 				   atomic_read(&rdma->sc_sq_avail) > 1);
325 			if (test_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags))
326 				return -ENOTCONN;
327 			trace_svcrdma_sq_retry(rdma);
328 			continue;
329 		}
330 
331 		trace_svcrdma_post_send(ctxt);
332 		ret = ib_post_send(rdma->sc_qp, wr, NULL);
333 		if (ret)
334 			break;
335 		return 0;
336 	}
337 
338 	trace_svcrdma_sq_post_err(rdma, ret);
339 	set_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags);
340 	wake_up(&rdma->sc_send_wait);
341 	return ret;
342 }
343 
344 /**
345  * svc_rdma_encode_read_list - Encode RPC Reply's Read chunk list
346  * @sctxt: Send context for the RPC Reply
347  *
348  * Return values:
349  *   On success, returns length in bytes of the Reply XDR buffer
350  *   that was consumed by the Reply Read list
351  *   %-EMSGSIZE on XDR buffer overflow
352  */
353 static ssize_t svc_rdma_encode_read_list(struct svc_rdma_send_ctxt *sctxt)
354 {
355 	/* RPC-over-RDMA version 1 replies never have a Read list. */
356 	return xdr_stream_encode_item_absent(&sctxt->sc_stream);
357 }
358 
359 /**
360  * svc_rdma_encode_write_segment - Encode one Write segment
361  * @src: matching Write chunk in the RPC Call header
362  * @sctxt: Send context for the RPC Reply
363  * @remaining: remaining bytes of the payload left in the Write chunk
364  *
365  * Return values:
366  *   On success, returns length in bytes of the Reply XDR buffer
367  *   that was consumed by the Write segment
368  *   %-EMSGSIZE on XDR buffer overflow
369  */
370 static ssize_t svc_rdma_encode_write_segment(__be32 *src,
371 					     struct svc_rdma_send_ctxt *sctxt,
372 					     unsigned int *remaining)
373 {
374 	__be32 *p;
375 	const size_t len = rpcrdma_segment_maxsz * sizeof(*p);
376 	u32 handle, length;
377 	u64 offset;
378 
379 	p = xdr_reserve_space(&sctxt->sc_stream, len);
380 	if (!p)
381 		return -EMSGSIZE;
382 
383 	xdr_decode_rdma_segment(src, &handle, &length, &offset);
384 
385 	if (*remaining < length) {
386 		/* segment only partly filled */
387 		length = *remaining;
388 		*remaining = 0;
389 	} else {
390 		/* entire segment was consumed */
391 		*remaining -= length;
392 	}
393 	xdr_encode_rdma_segment(p, handle, length, offset);
394 
395 	trace_svcrdma_encode_wseg(handle, length, offset);
396 	return len;
397 }
398 
399 /**
400  * svc_rdma_encode_write_chunk - Encode one Write chunk
401  * @src: matching Write chunk in the RPC Call header
402  * @sctxt: Send context for the RPC Reply
403  * @remaining: size in bytes of the payload in the Write chunk
404  *
405  * Copy a Write chunk from the Call transport header to the
406  * Reply transport header. Update each segment's length field
407  * to reflect the number of bytes written in that segment.
408  *
409  * Return values:
410  *   On success, returns length in bytes of the Reply XDR buffer
411  *   that was consumed by the Write chunk
412  *   %-EMSGSIZE on XDR buffer overflow
413  */
414 static ssize_t svc_rdma_encode_write_chunk(__be32 *src,
415 					   struct svc_rdma_send_ctxt *sctxt,
416 					   unsigned int remaining)
417 {
418 	unsigned int i, nsegs;
419 	ssize_t len, ret;
420 
421 	len = 0;
422 	trace_svcrdma_encode_write_chunk(remaining);
423 
424 	src++;
425 	ret = xdr_stream_encode_item_present(&sctxt->sc_stream);
426 	if (ret < 0)
427 		return -EMSGSIZE;
428 	len += ret;
429 
430 	nsegs = be32_to_cpup(src++);
431 	ret = xdr_stream_encode_u32(&sctxt->sc_stream, nsegs);
432 	if (ret < 0)
433 		return -EMSGSIZE;
434 	len += ret;
435 
436 	for (i = nsegs; i; i--) {
437 		ret = svc_rdma_encode_write_segment(src, sctxt, &remaining);
438 		if (ret < 0)
439 			return -EMSGSIZE;
440 		src += rpcrdma_segment_maxsz;
441 		len += ret;
442 	}
443 
444 	return len;
445 }
446 
447 /**
448  * svc_rdma_encode_write_list - Encode RPC Reply's Write chunk list
449  * @rctxt: Reply context with information about the RPC Call
450  * @sctxt: Send context for the RPC Reply
451  *
452  * The client provides a Write chunk list in the Call message. Fill
453  * in the segments in the first Write chunk in the Reply's transport
454  * header with the number of bytes consumed in each segment.
455  * Remaining chunks are returned unused.
456  *
457  * Assumptions:
458  *  - Client has provided only one Write chunk
459  *
460  * Return values:
461  *   On success, returns length in bytes of the Reply XDR buffer
462  *   that was consumed by the Reply's Write list
463  *   %-EMSGSIZE on XDR buffer overflow
464  */
465 static ssize_t
466 svc_rdma_encode_write_list(const struct svc_rdma_recv_ctxt *rctxt,
467 			   struct svc_rdma_send_ctxt *sctxt)
468 {
469 	ssize_t len, ret;
470 
471 	len = 0;
472 	if (rctxt->rc_write_list) {
473 		ret = svc_rdma_encode_write_chunk(rctxt->rc_write_list, sctxt,
474 						  rctxt->rc_read_payload_length);
475 		if (ret < 0)
476 			return ret;
477 		len = ret;
478 	}
479 
480 	/* Terminate the Write list */
481 	ret = xdr_stream_encode_item_absent(&sctxt->sc_stream);
482 	if (ret < 0)
483 		return ret;
484 
485 	return len + ret;
486 }
487 
488 /**
489  * svc_rdma_encode_reply_chunk - Encode RPC Reply's Reply chunk
490  * @rctxt: Reply context with information about the RPC Call
491  * @sctxt: Send context for the RPC Reply
492  * @length: size in bytes of the payload in the Reply chunk
493  *
494  * Assumptions:
495  * - Reply can always fit in the client-provided Reply chunk
496  *
497  * Return values:
498  *   On success, returns length in bytes of the Reply XDR buffer
499  *   that was consumed by the Reply's Reply chunk
500  *   %-EMSGSIZE on XDR buffer overflow
501  */
502 static ssize_t
503 svc_rdma_encode_reply_chunk(const struct svc_rdma_recv_ctxt *rctxt,
504 			    struct svc_rdma_send_ctxt *sctxt,
505 			    unsigned int length)
506 {
507 	if (!rctxt->rc_reply_chunk)
508 		return xdr_stream_encode_item_absent(&sctxt->sc_stream);
509 
510 	return svc_rdma_encode_write_chunk(rctxt->rc_reply_chunk, sctxt,
511 					   length);
512 }
513 
514 static int svc_rdma_dma_map_page(struct svcxprt_rdma *rdma,
515 				 struct svc_rdma_send_ctxt *ctxt,
516 				 struct page *page,
517 				 unsigned long offset,
518 				 unsigned int len)
519 {
520 	struct ib_device *dev = rdma->sc_cm_id->device;
521 	dma_addr_t dma_addr;
522 
523 	dma_addr = ib_dma_map_page(dev, page, offset, len, DMA_TO_DEVICE);
524 	trace_svcrdma_dma_map_page(rdma, dma_addr, len);
525 	if (ib_dma_mapping_error(dev, dma_addr))
526 		goto out_maperr;
527 
528 	ctxt->sc_sges[ctxt->sc_cur_sge_no].addr = dma_addr;
529 	ctxt->sc_sges[ctxt->sc_cur_sge_no].length = len;
530 	ctxt->sc_send_wr.num_sge++;
531 	return 0;
532 
533 out_maperr:
534 	return -EIO;
535 }
536 
537 /* ib_dma_map_page() is used here because svc_rdma_dma_unmap()
538  * handles DMA-unmap and it uses ib_dma_unmap_page() exclusively.
539  */
540 static int svc_rdma_dma_map_buf(struct svcxprt_rdma *rdma,
541 				struct svc_rdma_send_ctxt *ctxt,
542 				unsigned char *base,
543 				unsigned int len)
544 {
545 	return svc_rdma_dma_map_page(rdma, ctxt, virt_to_page(base),
546 				     offset_in_page(base), len);
547 }
548 
549 /**
550  * svc_rdma_pull_up_needed - Determine whether to use pull-up
551  * @rdma: controlling transport
552  * @sctxt: send_ctxt for the Send WR
553  * @rctxt: Write and Reply chunks provided by client
554  * @xdr: xdr_buf containing RPC message to transmit
555  *
556  * Returns:
557  *	%true if pull-up must be used
558  *	%false otherwise
559  */
560 static bool svc_rdma_pull_up_needed(struct svcxprt_rdma *rdma,
561 				    struct svc_rdma_send_ctxt *sctxt,
562 				    const struct svc_rdma_recv_ctxt *rctxt,
563 				    struct xdr_buf *xdr)
564 {
565 	bool write_chunk_present = rctxt && rctxt->rc_write_list;
566 	int elements;
567 
568 	/* For small messages, copying bytes is cheaper than DMA mapping.
569 	 */
570 	if (!write_chunk_present &&
571 	    sctxt->sc_hdrbuf.len + xdr->len < RPCRDMA_PULLUP_THRESH)
572 		return true;
573 
574 	/* Check whether the xdr_buf has more elements than can
575 	 * fit in a single RDMA Send.
576 	 */
577 	/* xdr->head */
578 	elements = 1;
579 
580 	/* xdr->pages */
581 	if (!rctxt || !rctxt->rc_write_list) {
582 		unsigned int remaining;
583 		unsigned long pageoff;
584 
585 		pageoff = xdr->page_base & ~PAGE_MASK;
586 		remaining = xdr->page_len;
587 		while (remaining) {
588 			++elements;
589 			remaining -= min_t(u32, PAGE_SIZE - pageoff,
590 					   remaining);
591 			pageoff = 0;
592 		}
593 	}
594 
595 	/* xdr->tail */
596 	if (xdr->tail[0].iov_len)
597 		++elements;
598 
599 	/* assume 1 SGE is needed for the transport header */
600 	return elements >= rdma->sc_max_send_sges;
601 }
602 
603 /**
604  * svc_rdma_pull_up_reply_msg - Copy Reply into a single buffer
605  * @rdma: controlling transport
606  * @sctxt: send_ctxt for the Send WR; xprt hdr is already prepared
607  * @rctxt: Write and Reply chunks provided by client
608  * @xdr: prepared xdr_buf containing RPC message
609  *
610  * The device is not capable of sending the reply directly.
611  * Assemble the elements of @xdr into the transport header buffer.
612  *
613  * Returns zero on success, or a negative errno on failure.
614  */
615 static int svc_rdma_pull_up_reply_msg(struct svcxprt_rdma *rdma,
616 				      struct svc_rdma_send_ctxt *sctxt,
617 				      const struct svc_rdma_recv_ctxt *rctxt,
618 				      const struct xdr_buf *xdr)
619 {
620 	unsigned char *dst, *tailbase;
621 	unsigned int taillen;
622 
623 	dst = sctxt->sc_xprt_buf + sctxt->sc_hdrbuf.len;
624 	memcpy(dst, xdr->head[0].iov_base, xdr->head[0].iov_len);
625 	dst += xdr->head[0].iov_len;
626 
627 	tailbase = xdr->tail[0].iov_base;
628 	taillen = xdr->tail[0].iov_len;
629 	if (rctxt && rctxt->rc_write_list) {
630 		u32 xdrpad;
631 
632 		xdrpad = xdr_pad_size(xdr->page_len);
633 		if (taillen && xdrpad) {
634 			tailbase += xdrpad;
635 			taillen -= xdrpad;
636 		}
637 	} else {
638 		unsigned int len, remaining;
639 		unsigned long pageoff;
640 		struct page **ppages;
641 
642 		ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT);
643 		pageoff = xdr->page_base & ~PAGE_MASK;
644 		remaining = xdr->page_len;
645 		while (remaining) {
646 			len = min_t(u32, PAGE_SIZE - pageoff, remaining);
647 
648 			memcpy(dst, page_address(*ppages) + pageoff, len);
649 			remaining -= len;
650 			dst += len;
651 			pageoff = 0;
652 			ppages++;
653 		}
654 	}
655 
656 	if (taillen)
657 		memcpy(dst, tailbase, taillen);
658 
659 	sctxt->sc_sges[0].length += xdr->len;
660 	trace_svcrdma_send_pullup(sctxt->sc_sges[0].length);
661 	return 0;
662 }
663 
664 /* svc_rdma_map_reply_msg - DMA map the buffer holding RPC message
665  * @rdma: controlling transport
666  * @sctxt: send_ctxt for the Send WR
667  * @rctxt: Write and Reply chunks provided by client
668  * @xdr: prepared xdr_buf containing RPC message
669  *
670  * Load the xdr_buf into the ctxt's sge array, and DMA map each
671  * element as it is added. The Send WR's num_sge field is set.
672  *
673  * Returns zero on success, or a negative errno on failure.
674  */
675 int svc_rdma_map_reply_msg(struct svcxprt_rdma *rdma,
676 			   struct svc_rdma_send_ctxt *sctxt,
677 			   const struct svc_rdma_recv_ctxt *rctxt,
678 			   struct xdr_buf *xdr)
679 {
680 	unsigned int len, remaining;
681 	unsigned long page_off;
682 	struct page **ppages;
683 	unsigned char *base;
684 	u32 xdr_pad;
685 	int ret;
686 
687 	/* Set up the (persistently-mapped) transport header SGE. */
688 	sctxt->sc_send_wr.num_sge = 1;
689 	sctxt->sc_sges[0].length = sctxt->sc_hdrbuf.len;
690 
691 	/* If there is a Reply chunk, nothing follows the transport
692 	 * header, and we're done here.
693 	 */
694 	if (rctxt && rctxt->rc_reply_chunk)
695 		return 0;
696 
697 	/* For pull-up, svc_rdma_send() will sync the transport header.
698 	 * No additional DMA mapping is necessary.
699 	 */
700 	if (svc_rdma_pull_up_needed(rdma, sctxt, rctxt, xdr))
701 		return svc_rdma_pull_up_reply_msg(rdma, sctxt, rctxt, xdr);
702 
703 	++sctxt->sc_cur_sge_no;
704 	ret = svc_rdma_dma_map_buf(rdma, sctxt,
705 				   xdr->head[0].iov_base,
706 				   xdr->head[0].iov_len);
707 	if (ret < 0)
708 		return ret;
709 
710 	/* If a Write chunk is present, the xdr_buf's page list
711 	 * is not included inline. However the Upper Layer may
712 	 * have added XDR padding in the tail buffer, and that
713 	 * should not be included inline.
714 	 */
715 	if (rctxt && rctxt->rc_write_list) {
716 		base = xdr->tail[0].iov_base;
717 		len = xdr->tail[0].iov_len;
718 		xdr_pad = xdr_pad_size(xdr->page_len);
719 
720 		if (len && xdr_pad) {
721 			base += xdr_pad;
722 			len -= xdr_pad;
723 		}
724 
725 		goto tail;
726 	}
727 
728 	ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT);
729 	page_off = xdr->page_base & ~PAGE_MASK;
730 	remaining = xdr->page_len;
731 	while (remaining) {
732 		len = min_t(u32, PAGE_SIZE - page_off, remaining);
733 
734 		++sctxt->sc_cur_sge_no;
735 		ret = svc_rdma_dma_map_page(rdma, sctxt, *ppages++,
736 					    page_off, len);
737 		if (ret < 0)
738 			return ret;
739 
740 		remaining -= len;
741 		page_off = 0;
742 	}
743 
744 	base = xdr->tail[0].iov_base;
745 	len = xdr->tail[0].iov_len;
746 tail:
747 	if (len) {
748 		++sctxt->sc_cur_sge_no;
749 		ret = svc_rdma_dma_map_buf(rdma, sctxt, base, len);
750 		if (ret < 0)
751 			return ret;
752 	}
753 
754 	return 0;
755 }
756 
757 /* The svc_rqst and all resources it owns are released as soon as
758  * svc_rdma_sendto returns. Transfer pages under I/O to the ctxt
759  * so they are released by the Send completion handler.
760  */
761 static void svc_rdma_save_io_pages(struct svc_rqst *rqstp,
762 				   struct svc_rdma_send_ctxt *ctxt)
763 {
764 	int i, pages = rqstp->rq_next_page - rqstp->rq_respages;
765 
766 	ctxt->sc_page_count += pages;
767 	for (i = 0; i < pages; i++) {
768 		ctxt->sc_pages[i] = rqstp->rq_respages[i];
769 		rqstp->rq_respages[i] = NULL;
770 	}
771 
772 	/* Prevent svc_xprt_release from releasing pages in rq_pages */
773 	rqstp->rq_next_page = rqstp->rq_respages;
774 }
775 
776 /* Prepare the portion of the RPC Reply that will be transmitted
777  * via RDMA Send. The RPC-over-RDMA transport header is prepared
778  * in sc_sges[0], and the RPC xdr_buf is prepared in following sges.
779  *
780  * Depending on whether a Write list or Reply chunk is present,
781  * the server may send all, a portion of, or none of the xdr_buf.
782  * In the latter case, only the transport header (sc_sges[0]) is
783  * transmitted.
784  *
785  * RDMA Send is the last step of transmitting an RPC reply. Pages
786  * involved in the earlier RDMA Writes are here transferred out
787  * of the rqstp and into the sctxt's page array. These pages are
788  * DMA unmapped by each Write completion, but the subsequent Send
789  * completion finally releases these pages.
790  *
791  * Assumptions:
792  * - The Reply's transport header will never be larger than a page.
793  */
794 static int svc_rdma_send_reply_msg(struct svcxprt_rdma *rdma,
795 				   struct svc_rdma_send_ctxt *sctxt,
796 				   const struct svc_rdma_recv_ctxt *rctxt,
797 				   struct svc_rqst *rqstp)
798 {
799 	int ret;
800 
801 	ret = svc_rdma_map_reply_msg(rdma, sctxt, rctxt, &rqstp->rq_res);
802 	if (ret < 0)
803 		return ret;
804 
805 	svc_rdma_save_io_pages(rqstp, sctxt);
806 
807 	if (rctxt->rc_inv_rkey) {
808 		sctxt->sc_send_wr.opcode = IB_WR_SEND_WITH_INV;
809 		sctxt->sc_send_wr.ex.invalidate_rkey = rctxt->rc_inv_rkey;
810 	} else {
811 		sctxt->sc_send_wr.opcode = IB_WR_SEND;
812 	}
813 	return svc_rdma_send(rdma, sctxt);
814 }
815 
816 /**
817  * svc_rdma_send_error_msg - Send an RPC/RDMA v1 error response
818  * @rdma: controlling transport context
819  * @sctxt: Send context for the response
820  * @rctxt: Receive context for incoming bad message
821  * @status: negative errno indicating error that occurred
822  *
823  * Given the client-provided Read, Write, and Reply chunks, the
824  * server was not able to parse the Call or form a complete Reply.
825  * Return an RDMA_ERROR message so the client can retire the RPC
826  * transaction.
827  *
828  * The caller does not have to release @sctxt. It is released by
829  * Send completion, or by this function on error.
830  */
831 void svc_rdma_send_error_msg(struct svcxprt_rdma *rdma,
832 			     struct svc_rdma_send_ctxt *sctxt,
833 			     struct svc_rdma_recv_ctxt *rctxt,
834 			     int status)
835 {
836 	__be32 *rdma_argp = rctxt->rc_recv_buf;
837 	__be32 *p;
838 
839 	rpcrdma_set_xdrlen(&sctxt->sc_hdrbuf, 0);
840 	xdr_init_encode(&sctxt->sc_stream, &sctxt->sc_hdrbuf,
841 			sctxt->sc_xprt_buf, NULL);
842 
843 	p = xdr_reserve_space(&sctxt->sc_stream,
844 			      rpcrdma_fixed_maxsz * sizeof(*p));
845 	if (!p)
846 		goto put_ctxt;
847 
848 	*p++ = *rdma_argp;
849 	*p++ = *(rdma_argp + 1);
850 	*p++ = rdma->sc_fc_credits;
851 	*p = rdma_error;
852 
853 	switch (status) {
854 	case -EPROTONOSUPPORT:
855 		p = xdr_reserve_space(&sctxt->sc_stream, 3 * sizeof(*p));
856 		if (!p)
857 			goto put_ctxt;
858 
859 		*p++ = err_vers;
860 		*p++ = rpcrdma_version;
861 		*p = rpcrdma_version;
862 		trace_svcrdma_err_vers(*rdma_argp);
863 		break;
864 	default:
865 		p = xdr_reserve_space(&sctxt->sc_stream, sizeof(*p));
866 		if (!p)
867 			goto put_ctxt;
868 
869 		*p = err_chunk;
870 		trace_svcrdma_err_chunk(*rdma_argp);
871 	}
872 
873 	/* Remote Invalidation is skipped for simplicity. */
874 	sctxt->sc_send_wr.num_sge = 1;
875 	sctxt->sc_send_wr.opcode = IB_WR_SEND;
876 	sctxt->sc_sges[0].length = sctxt->sc_hdrbuf.len;
877 	if (svc_rdma_send(rdma, sctxt))
878 		goto put_ctxt;
879 	return;
880 
881 put_ctxt:
882 	svc_rdma_send_ctxt_put(rdma, sctxt);
883 }
884 
885 /**
886  * svc_rdma_sendto - Transmit an RPC reply
887  * @rqstp: processed RPC request, reply XDR already in ::rq_res
888  *
889  * Any resources still associated with @rqstp are released upon return.
890  * If no reply message was possible, the connection is closed.
891  *
892  * Returns:
893  *	%0 if an RPC reply has been successfully posted,
894  *	%-ENOMEM if a resource shortage occurred (connection is lost),
895  *	%-ENOTCONN if posting failed (connection is lost).
896  */
897 int svc_rdma_sendto(struct svc_rqst *rqstp)
898 {
899 	struct svc_xprt *xprt = rqstp->rq_xprt;
900 	struct svcxprt_rdma *rdma =
901 		container_of(xprt, struct svcxprt_rdma, sc_xprt);
902 	struct svc_rdma_recv_ctxt *rctxt = rqstp->rq_xprt_ctxt;
903 	__be32 *rdma_argp = rctxt->rc_recv_buf;
904 	struct svc_rdma_send_ctxt *sctxt;
905 	__be32 *p;
906 	int ret;
907 
908 	ret = -ENOTCONN;
909 	if (svc_xprt_is_dead(xprt))
910 		goto err0;
911 
912 	ret = -ENOMEM;
913 	sctxt = svc_rdma_send_ctxt_get(rdma);
914 	if (!sctxt)
915 		goto err0;
916 
917 	p = xdr_reserve_space(&sctxt->sc_stream,
918 			      rpcrdma_fixed_maxsz * sizeof(*p));
919 	if (!p)
920 		goto err0;
921 
922 	ret = svc_rdma_send_reply_chunk(rdma, rctxt, &rqstp->rq_res);
923 	if (ret < 0)
924 		goto err2;
925 
926 	*p++ = *rdma_argp;
927 	*p++ = *(rdma_argp + 1);
928 	*p++ = rdma->sc_fc_credits;
929 	*p = rctxt->rc_reply_chunk ? rdma_nomsg : rdma_msg;
930 
931 	if (svc_rdma_encode_read_list(sctxt) < 0)
932 		goto err0;
933 	if (svc_rdma_encode_write_list(rctxt, sctxt) < 0)
934 		goto err0;
935 	if (svc_rdma_encode_reply_chunk(rctxt, sctxt, ret) < 0)
936 		goto err0;
937 
938 	ret = svc_rdma_send_reply_msg(rdma, sctxt, rctxt, rqstp);
939 	if (ret < 0)
940 		goto err1;
941 	return 0;
942 
943  err2:
944 	if (ret != -E2BIG && ret != -EINVAL)
945 		goto err1;
946 
947 	/* Send completion releases payload pages that were part
948 	 * of previously posted RDMA Writes.
949 	 */
950 	svc_rdma_save_io_pages(rqstp, sctxt);
951 	svc_rdma_send_error_msg(rdma, sctxt, rctxt, ret);
952 	return 0;
953 
954  err1:
955 	svc_rdma_send_ctxt_put(rdma, sctxt);
956  err0:
957 	trace_svcrdma_send_err(rqstp, ret);
958 	set_bit(XPT_CLOSE, &xprt->xpt_flags);
959 	return -ENOTCONN;
960 }
961 
962 /**
963  * svc_rdma_result_payload - special processing for a result payload
964  * @rqstp: svc_rqst to operate on
965  * @offset: payload's byte offset in @xdr
966  * @length: size of payload, in bytes
967  *
968  * Return values:
969  *   %0 if successful or nothing needed to be done
970  *   %-EMSGSIZE on XDR buffer overflow
971  *   %-E2BIG if the payload was larger than the Write chunk
972  *   %-EINVAL if client provided too many segments
973  *   %-ENOMEM if rdma_rw context pool was exhausted
974  *   %-ENOTCONN if posting failed (connection is lost)
975  *   %-EIO if rdma_rw initialization failed (DMA mapping, etc)
976  */
977 int svc_rdma_result_payload(struct svc_rqst *rqstp, unsigned int offset,
978 			    unsigned int length)
979 {
980 	struct svc_rdma_recv_ctxt *rctxt = rqstp->rq_xprt_ctxt;
981 	struct svcxprt_rdma *rdma;
982 	struct xdr_buf subbuf;
983 	int ret;
984 
985 	if (!rctxt->rc_write_list || !length)
986 		return 0;
987 
988 	/* XXX: Just one READ payload slot for now, since our
989 	 * transport implementation currently supports only one
990 	 * Write chunk.
991 	 */
992 	rctxt->rc_read_payload_offset = offset;
993 	rctxt->rc_read_payload_length = length;
994 
995 	if (xdr_buf_subsegment(&rqstp->rq_res, &subbuf, offset, length))
996 		return -EMSGSIZE;
997 
998 	rdma = container_of(rqstp->rq_xprt, struct svcxprt_rdma, sc_xprt);
999 	ret = svc_rdma_send_write_chunk(rdma, rctxt->rc_write_list, &subbuf);
1000 	if (ret < 0)
1001 		return ret;
1002 	return 0;
1003 }
1004