xref: /linux/net/sunrpc/xprtrdma/svc_rdma_sendto.c (revision 02680c23d7b3febe45ea3d4f9818c2b2dc89020a)
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 static void svc_rdma_wc_send(struct ib_cq *cq, struct ib_wc *wc);
115 
116 static inline struct svc_rdma_send_ctxt *
117 svc_rdma_next_send_ctxt(struct list_head *list)
118 {
119 	return list_first_entry_or_null(list, struct svc_rdma_send_ctxt,
120 					sc_list);
121 }
122 
123 static void svc_rdma_send_cid_init(struct svcxprt_rdma *rdma,
124 				   struct rpc_rdma_cid *cid)
125 {
126 	cid->ci_queue_id = rdma->sc_sq_cq->res.id;
127 	cid->ci_completion_id = atomic_inc_return(&rdma->sc_completion_ids);
128 }
129 
130 static struct svc_rdma_send_ctxt *
131 svc_rdma_send_ctxt_alloc(struct svcxprt_rdma *rdma)
132 {
133 	struct svc_rdma_send_ctxt *ctxt;
134 	dma_addr_t addr;
135 	void *buffer;
136 	size_t size;
137 	int i;
138 
139 	size = sizeof(*ctxt);
140 	size += rdma->sc_max_send_sges * sizeof(struct ib_sge);
141 	ctxt = kmalloc(size, GFP_KERNEL);
142 	if (!ctxt)
143 		goto fail0;
144 	buffer = kmalloc(rdma->sc_max_req_size, GFP_KERNEL);
145 	if (!buffer)
146 		goto fail1;
147 	addr = ib_dma_map_single(rdma->sc_pd->device, buffer,
148 				 rdma->sc_max_req_size, DMA_TO_DEVICE);
149 	if (ib_dma_mapping_error(rdma->sc_pd->device, addr))
150 		goto fail2;
151 
152 	svc_rdma_send_cid_init(rdma, &ctxt->sc_cid);
153 
154 	ctxt->sc_send_wr.next = NULL;
155 	ctxt->sc_send_wr.wr_cqe = &ctxt->sc_cqe;
156 	ctxt->sc_send_wr.sg_list = ctxt->sc_sges;
157 	ctxt->sc_send_wr.send_flags = IB_SEND_SIGNALED;
158 	init_completion(&ctxt->sc_done);
159 	ctxt->sc_cqe.done = svc_rdma_wc_send;
160 	ctxt->sc_xprt_buf = buffer;
161 	xdr_buf_init(&ctxt->sc_hdrbuf, ctxt->sc_xprt_buf,
162 		     rdma->sc_max_req_size);
163 	ctxt->sc_sges[0].addr = addr;
164 
165 	for (i = 0; i < rdma->sc_max_send_sges; i++)
166 		ctxt->sc_sges[i].lkey = rdma->sc_pd->local_dma_lkey;
167 	return ctxt;
168 
169 fail2:
170 	kfree(buffer);
171 fail1:
172 	kfree(ctxt);
173 fail0:
174 	return NULL;
175 }
176 
177 /**
178  * svc_rdma_send_ctxts_destroy - Release all send_ctxt's for an xprt
179  * @rdma: svcxprt_rdma being torn down
180  *
181  */
182 void svc_rdma_send_ctxts_destroy(struct svcxprt_rdma *rdma)
183 {
184 	struct svc_rdma_send_ctxt *ctxt;
185 
186 	while ((ctxt = svc_rdma_next_send_ctxt(&rdma->sc_send_ctxts))) {
187 		list_del(&ctxt->sc_list);
188 		ib_dma_unmap_single(rdma->sc_pd->device,
189 				    ctxt->sc_sges[0].addr,
190 				    rdma->sc_max_req_size,
191 				    DMA_TO_DEVICE);
192 		kfree(ctxt->sc_xprt_buf);
193 		kfree(ctxt);
194 	}
195 }
196 
197 /**
198  * svc_rdma_send_ctxt_get - Get a free send_ctxt
199  * @rdma: controlling svcxprt_rdma
200  *
201  * Returns a ready-to-use send_ctxt, or NULL if none are
202  * available and a fresh one cannot be allocated.
203  */
204 struct svc_rdma_send_ctxt *svc_rdma_send_ctxt_get(struct svcxprt_rdma *rdma)
205 {
206 	struct svc_rdma_send_ctxt *ctxt;
207 
208 	spin_lock(&rdma->sc_send_lock);
209 	ctxt = svc_rdma_next_send_ctxt(&rdma->sc_send_ctxts);
210 	if (!ctxt)
211 		goto out_empty;
212 	list_del(&ctxt->sc_list);
213 	spin_unlock(&rdma->sc_send_lock);
214 
215 out:
216 	rpcrdma_set_xdrlen(&ctxt->sc_hdrbuf, 0);
217 	xdr_init_encode(&ctxt->sc_stream, &ctxt->sc_hdrbuf,
218 			ctxt->sc_xprt_buf, NULL);
219 
220 	ctxt->sc_send_wr.num_sge = 0;
221 	ctxt->sc_cur_sge_no = 0;
222 	return ctxt;
223 
224 out_empty:
225 	spin_unlock(&rdma->sc_send_lock);
226 	ctxt = svc_rdma_send_ctxt_alloc(rdma);
227 	if (!ctxt)
228 		return NULL;
229 	goto out;
230 }
231 
232 /**
233  * svc_rdma_send_ctxt_put - Return send_ctxt to free list
234  * @rdma: controlling svcxprt_rdma
235  * @ctxt: object to return to the free list
236  */
237 void svc_rdma_send_ctxt_put(struct svcxprt_rdma *rdma,
238 			    struct svc_rdma_send_ctxt *ctxt)
239 {
240 	struct ib_device *device = rdma->sc_cm_id->device;
241 	unsigned int i;
242 
243 	/* The first SGE contains the transport header, which
244 	 * remains mapped until @ctxt is destroyed.
245 	 */
246 	for (i = 1; i < ctxt->sc_send_wr.num_sge; i++) {
247 		ib_dma_unmap_page(device,
248 				  ctxt->sc_sges[i].addr,
249 				  ctxt->sc_sges[i].length,
250 				  DMA_TO_DEVICE);
251 		trace_svcrdma_dma_unmap_page(rdma,
252 					     ctxt->sc_sges[i].addr,
253 					     ctxt->sc_sges[i].length);
254 	}
255 
256 	spin_lock(&rdma->sc_send_lock);
257 	list_add(&ctxt->sc_list, &rdma->sc_send_ctxts);
258 	spin_unlock(&rdma->sc_send_lock);
259 }
260 
261 /**
262  * svc_rdma_wc_send - Invoked by RDMA provider for each polled Send WC
263  * @cq: Completion Queue context
264  * @wc: Work Completion object
265  *
266  * NB: The svc_xprt/svcxprt_rdma is pinned whenever it's possible that
267  * the Send completion handler could be running.
268  */
269 static void svc_rdma_wc_send(struct ib_cq *cq, struct ib_wc *wc)
270 {
271 	struct svcxprt_rdma *rdma = cq->cq_context;
272 	struct ib_cqe *cqe = wc->wr_cqe;
273 	struct svc_rdma_send_ctxt *ctxt =
274 		container_of(cqe, struct svc_rdma_send_ctxt, sc_cqe);
275 
276 	trace_svcrdma_wc_send(wc, &ctxt->sc_cid);
277 
278 	complete(&ctxt->sc_done);
279 
280 	atomic_inc(&rdma->sc_sq_avail);
281 	wake_up(&rdma->sc_send_wait);
282 
283 	if (unlikely(wc->status != IB_WC_SUCCESS))
284 		svc_xprt_deferred_close(&rdma->sc_xprt);
285 }
286 
287 /**
288  * svc_rdma_send - Post a single Send WR
289  * @rdma: transport on which to post the WR
290  * @ctxt: send ctxt with a Send WR ready to post
291  *
292  * Returns zero if the Send WR was posted successfully. Otherwise, a
293  * negative errno is returned.
294  */
295 int svc_rdma_send(struct svcxprt_rdma *rdma, struct svc_rdma_send_ctxt *ctxt)
296 {
297 	struct ib_send_wr *wr = &ctxt->sc_send_wr;
298 	int ret;
299 
300 	reinit_completion(&ctxt->sc_done);
301 
302 	/* Sync the transport header buffer */
303 	ib_dma_sync_single_for_device(rdma->sc_pd->device,
304 				      wr->sg_list[0].addr,
305 				      wr->sg_list[0].length,
306 				      DMA_TO_DEVICE);
307 
308 	/* If the SQ is full, wait until an SQ entry is available */
309 	while (1) {
310 		if ((atomic_dec_return(&rdma->sc_sq_avail) < 0)) {
311 			percpu_counter_inc(&svcrdma_stat_sq_starve);
312 			trace_svcrdma_sq_full(rdma);
313 			atomic_inc(&rdma->sc_sq_avail);
314 			wait_event(rdma->sc_send_wait,
315 				   atomic_read(&rdma->sc_sq_avail) > 1);
316 			if (test_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags))
317 				return -ENOTCONN;
318 			trace_svcrdma_sq_retry(rdma);
319 			continue;
320 		}
321 
322 		trace_svcrdma_post_send(ctxt);
323 		ret = ib_post_send(rdma->sc_qp, wr, NULL);
324 		if (ret)
325 			break;
326 		return 0;
327 	}
328 
329 	trace_svcrdma_sq_post_err(rdma, ret);
330 	svc_xprt_deferred_close(&rdma->sc_xprt);
331 	wake_up(&rdma->sc_send_wait);
332 	return ret;
333 }
334 
335 /**
336  * svc_rdma_encode_read_list - Encode RPC Reply's Read chunk list
337  * @sctxt: Send context for the RPC Reply
338  *
339  * Return values:
340  *   On success, returns length in bytes of the Reply XDR buffer
341  *   that was consumed by the Reply Read list
342  *   %-EMSGSIZE on XDR buffer overflow
343  */
344 static ssize_t svc_rdma_encode_read_list(struct svc_rdma_send_ctxt *sctxt)
345 {
346 	/* RPC-over-RDMA version 1 replies never have a Read list. */
347 	return xdr_stream_encode_item_absent(&sctxt->sc_stream);
348 }
349 
350 /**
351  * svc_rdma_encode_write_segment - Encode one Write segment
352  * @sctxt: Send context for the RPC Reply
353  * @chunk: Write chunk to push
354  * @remaining: remaining bytes of the payload left in the Write chunk
355  * @segno: which segment in the chunk
356  *
357  * Return values:
358  *   On success, returns length in bytes of the Reply XDR buffer
359  *   that was consumed by the Write segment, and updates @remaining
360  *   %-EMSGSIZE on XDR buffer overflow
361  */
362 static ssize_t svc_rdma_encode_write_segment(struct svc_rdma_send_ctxt *sctxt,
363 					     const struct svc_rdma_chunk *chunk,
364 					     u32 *remaining, unsigned int segno)
365 {
366 	const struct svc_rdma_segment *segment = &chunk->ch_segments[segno];
367 	const size_t len = rpcrdma_segment_maxsz * sizeof(__be32);
368 	u32 length;
369 	__be32 *p;
370 
371 	p = xdr_reserve_space(&sctxt->sc_stream, len);
372 	if (!p)
373 		return -EMSGSIZE;
374 
375 	length = min_t(u32, *remaining, segment->rs_length);
376 	*remaining -= length;
377 	xdr_encode_rdma_segment(p, segment->rs_handle, length,
378 				segment->rs_offset);
379 	trace_svcrdma_encode_wseg(sctxt, segno, segment->rs_handle, length,
380 				  segment->rs_offset);
381 	return len;
382 }
383 
384 /**
385  * svc_rdma_encode_write_chunk - Encode one Write chunk
386  * @sctxt: Send context for the RPC Reply
387  * @chunk: Write chunk to push
388  *
389  * Copy a Write chunk from the Call transport header to the
390  * Reply transport header. Update each segment's length field
391  * to reflect the number of bytes written in that segment.
392  *
393  * Return values:
394  *   On success, returns length in bytes of the Reply XDR buffer
395  *   that was consumed by the Write chunk
396  *   %-EMSGSIZE on XDR buffer overflow
397  */
398 static ssize_t svc_rdma_encode_write_chunk(struct svc_rdma_send_ctxt *sctxt,
399 					   const struct svc_rdma_chunk *chunk)
400 {
401 	u32 remaining = chunk->ch_payload_length;
402 	unsigned int segno;
403 	ssize_t len, ret;
404 
405 	len = 0;
406 	ret = xdr_stream_encode_item_present(&sctxt->sc_stream);
407 	if (ret < 0)
408 		return ret;
409 	len += ret;
410 
411 	ret = xdr_stream_encode_u32(&sctxt->sc_stream, chunk->ch_segcount);
412 	if (ret < 0)
413 		return ret;
414 	len += ret;
415 
416 	for (segno = 0; segno < chunk->ch_segcount; segno++) {
417 		ret = svc_rdma_encode_write_segment(sctxt, chunk, &remaining, segno);
418 		if (ret < 0)
419 			return ret;
420 		len += ret;
421 	}
422 
423 	return len;
424 }
425 
426 /**
427  * svc_rdma_encode_write_list - Encode RPC Reply's Write chunk list
428  * @rctxt: Reply context with information about the RPC Call
429  * @sctxt: Send context for the RPC Reply
430  *
431  * Return values:
432  *   On success, returns length in bytes of the Reply XDR buffer
433  *   that was consumed by the Reply's Write list
434  *   %-EMSGSIZE on XDR buffer overflow
435  */
436 static ssize_t svc_rdma_encode_write_list(struct svc_rdma_recv_ctxt *rctxt,
437 					  struct svc_rdma_send_ctxt *sctxt)
438 {
439 	struct svc_rdma_chunk *chunk;
440 	ssize_t len, ret;
441 
442 	len = 0;
443 	pcl_for_each_chunk(chunk, &rctxt->rc_write_pcl) {
444 		ret = svc_rdma_encode_write_chunk(sctxt, chunk);
445 		if (ret < 0)
446 			return ret;
447 		len += ret;
448 	}
449 
450 	/* Terminate the Write list */
451 	ret = xdr_stream_encode_item_absent(&sctxt->sc_stream);
452 	if (ret < 0)
453 		return ret;
454 
455 	return len + ret;
456 }
457 
458 /**
459  * svc_rdma_encode_reply_chunk - Encode RPC Reply's Reply chunk
460  * @rctxt: Reply context with information about the RPC Call
461  * @sctxt: Send context for the RPC Reply
462  * @length: size in bytes of the payload in the Reply chunk
463  *
464  * Return values:
465  *   On success, returns length in bytes of the Reply XDR buffer
466  *   that was consumed by the Reply's Reply chunk
467  *   %-EMSGSIZE on XDR buffer overflow
468  *   %-E2BIG if the RPC message is larger than the Reply chunk
469  */
470 static ssize_t
471 svc_rdma_encode_reply_chunk(struct svc_rdma_recv_ctxt *rctxt,
472 			    struct svc_rdma_send_ctxt *sctxt,
473 			    unsigned int length)
474 {
475 	struct svc_rdma_chunk *chunk;
476 
477 	if (pcl_is_empty(&rctxt->rc_reply_pcl))
478 		return xdr_stream_encode_item_absent(&sctxt->sc_stream);
479 
480 	chunk = pcl_first_chunk(&rctxt->rc_reply_pcl);
481 	if (length > chunk->ch_length)
482 		return -E2BIG;
483 
484 	chunk->ch_payload_length = length;
485 	return svc_rdma_encode_write_chunk(sctxt, chunk);
486 }
487 
488 struct svc_rdma_map_data {
489 	struct svcxprt_rdma		*md_rdma;
490 	struct svc_rdma_send_ctxt	*md_ctxt;
491 };
492 
493 /**
494  * svc_rdma_page_dma_map - DMA map one page
495  * @data: pointer to arguments
496  * @page: struct page to DMA map
497  * @offset: offset into the page
498  * @len: number of bytes to map
499  *
500  * Returns:
501  *   %0 if DMA mapping was successful
502  *   %-EIO if the page cannot be DMA mapped
503  */
504 static int svc_rdma_page_dma_map(void *data, struct page *page,
505 				 unsigned long offset, unsigned int len)
506 {
507 	struct svc_rdma_map_data *args = data;
508 	struct svcxprt_rdma *rdma = args->md_rdma;
509 	struct svc_rdma_send_ctxt *ctxt = args->md_ctxt;
510 	struct ib_device *dev = rdma->sc_cm_id->device;
511 	dma_addr_t dma_addr;
512 
513 	++ctxt->sc_cur_sge_no;
514 
515 	dma_addr = ib_dma_map_page(dev, page, offset, len, DMA_TO_DEVICE);
516 	if (ib_dma_mapping_error(dev, dma_addr))
517 		goto out_maperr;
518 
519 	trace_svcrdma_dma_map_page(rdma, dma_addr, len);
520 	ctxt->sc_sges[ctxt->sc_cur_sge_no].addr = dma_addr;
521 	ctxt->sc_sges[ctxt->sc_cur_sge_no].length = len;
522 	ctxt->sc_send_wr.num_sge++;
523 	return 0;
524 
525 out_maperr:
526 	trace_svcrdma_dma_map_err(rdma, dma_addr, len);
527 	return -EIO;
528 }
529 
530 /**
531  * svc_rdma_iov_dma_map - DMA map an iovec
532  * @data: pointer to arguments
533  * @iov: kvec to DMA map
534  *
535  * ib_dma_map_page() is used here because svc_rdma_dma_unmap()
536  * handles DMA-unmap and it uses ib_dma_unmap_page() exclusively.
537  *
538  * Returns:
539  *   %0 if DMA mapping was successful
540  *   %-EIO if the iovec cannot be DMA mapped
541  */
542 static int svc_rdma_iov_dma_map(void *data, const struct kvec *iov)
543 {
544 	if (!iov->iov_len)
545 		return 0;
546 	return svc_rdma_page_dma_map(data, virt_to_page(iov->iov_base),
547 				     offset_in_page(iov->iov_base),
548 				     iov->iov_len);
549 }
550 
551 /**
552  * svc_rdma_xb_dma_map - DMA map all segments of an xdr_buf
553  * @xdr: xdr_buf containing portion of an RPC message to transmit
554  * @data: pointer to arguments
555  *
556  * Returns:
557  *   %0 if DMA mapping was successful
558  *   %-EIO if DMA mapping failed
559  *
560  * On failure, any DMA mappings that have been already done must be
561  * unmapped by the caller.
562  */
563 static int svc_rdma_xb_dma_map(const struct xdr_buf *xdr, void *data)
564 {
565 	unsigned int len, remaining;
566 	unsigned long pageoff;
567 	struct page **ppages;
568 	int ret;
569 
570 	ret = svc_rdma_iov_dma_map(data, &xdr->head[0]);
571 	if (ret < 0)
572 		return ret;
573 
574 	ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT);
575 	pageoff = offset_in_page(xdr->page_base);
576 	remaining = xdr->page_len;
577 	while (remaining) {
578 		len = min_t(u32, PAGE_SIZE - pageoff, remaining);
579 
580 		ret = svc_rdma_page_dma_map(data, *ppages++, pageoff, len);
581 		if (ret < 0)
582 			return ret;
583 
584 		remaining -= len;
585 		pageoff = 0;
586 	}
587 
588 	ret = svc_rdma_iov_dma_map(data, &xdr->tail[0]);
589 	if (ret < 0)
590 		return ret;
591 
592 	return xdr->len;
593 }
594 
595 struct svc_rdma_pullup_data {
596 	u8		*pd_dest;
597 	unsigned int	pd_length;
598 	unsigned int	pd_num_sges;
599 };
600 
601 /**
602  * svc_rdma_xb_count_sges - Count how many SGEs will be needed
603  * @xdr: xdr_buf containing portion of an RPC message to transmit
604  * @data: pointer to arguments
605  *
606  * Returns:
607  *   Number of SGEs needed to Send the contents of @xdr inline
608  */
609 static int svc_rdma_xb_count_sges(const struct xdr_buf *xdr,
610 				  void *data)
611 {
612 	struct svc_rdma_pullup_data *args = data;
613 	unsigned int remaining;
614 	unsigned long offset;
615 
616 	if (xdr->head[0].iov_len)
617 		++args->pd_num_sges;
618 
619 	offset = offset_in_page(xdr->page_base);
620 	remaining = xdr->page_len;
621 	while (remaining) {
622 		++args->pd_num_sges;
623 		remaining -= min_t(u32, PAGE_SIZE - offset, remaining);
624 		offset = 0;
625 	}
626 
627 	if (xdr->tail[0].iov_len)
628 		++args->pd_num_sges;
629 
630 	args->pd_length += xdr->len;
631 	return 0;
632 }
633 
634 /**
635  * svc_rdma_pull_up_needed - Determine whether to use pull-up
636  * @rdma: controlling transport
637  * @sctxt: send_ctxt for the Send WR
638  * @rctxt: Write and Reply chunks provided by client
639  * @xdr: xdr_buf containing RPC message to transmit
640  *
641  * Returns:
642  *   %true if pull-up must be used
643  *   %false otherwise
644  */
645 static bool svc_rdma_pull_up_needed(const struct svcxprt_rdma *rdma,
646 				    const struct svc_rdma_send_ctxt *sctxt,
647 				    const struct svc_rdma_recv_ctxt *rctxt,
648 				    const struct xdr_buf *xdr)
649 {
650 	/* Resources needed for the transport header */
651 	struct svc_rdma_pullup_data args = {
652 		.pd_length	= sctxt->sc_hdrbuf.len,
653 		.pd_num_sges	= 1,
654 	};
655 	int ret;
656 
657 	ret = pcl_process_nonpayloads(&rctxt->rc_write_pcl, xdr,
658 				      svc_rdma_xb_count_sges, &args);
659 	if (ret < 0)
660 		return false;
661 
662 	if (args.pd_length < RPCRDMA_PULLUP_THRESH)
663 		return true;
664 	return args.pd_num_sges >= rdma->sc_max_send_sges;
665 }
666 
667 /**
668  * svc_rdma_xb_linearize - Copy region of xdr_buf to flat buffer
669  * @xdr: xdr_buf containing portion of an RPC message to copy
670  * @data: pointer to arguments
671  *
672  * Returns:
673  *   Always zero.
674  */
675 static int svc_rdma_xb_linearize(const struct xdr_buf *xdr,
676 				 void *data)
677 {
678 	struct svc_rdma_pullup_data *args = data;
679 	unsigned int len, remaining;
680 	unsigned long pageoff;
681 	struct page **ppages;
682 
683 	if (xdr->head[0].iov_len) {
684 		memcpy(args->pd_dest, xdr->head[0].iov_base, xdr->head[0].iov_len);
685 		args->pd_dest += xdr->head[0].iov_len;
686 	}
687 
688 	ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT);
689 	pageoff = offset_in_page(xdr->page_base);
690 	remaining = xdr->page_len;
691 	while (remaining) {
692 		len = min_t(u32, PAGE_SIZE - pageoff, remaining);
693 		memcpy(args->pd_dest, page_address(*ppages) + pageoff, len);
694 		remaining -= len;
695 		args->pd_dest += len;
696 		pageoff = 0;
697 		ppages++;
698 	}
699 
700 	if (xdr->tail[0].iov_len) {
701 		memcpy(args->pd_dest, xdr->tail[0].iov_base, xdr->tail[0].iov_len);
702 		args->pd_dest += xdr->tail[0].iov_len;
703 	}
704 
705 	args->pd_length += xdr->len;
706 	return 0;
707 }
708 
709 /**
710  * svc_rdma_pull_up_reply_msg - Copy Reply into a single buffer
711  * @rdma: controlling transport
712  * @sctxt: send_ctxt for the Send WR; xprt hdr is already prepared
713  * @rctxt: Write and Reply chunks provided by client
714  * @xdr: prepared xdr_buf containing RPC message
715  *
716  * The device is not capable of sending the reply directly.
717  * Assemble the elements of @xdr into the transport header buffer.
718  *
719  * Assumptions:
720  *  pull_up_needed has determined that @xdr will fit in the buffer.
721  *
722  * Returns:
723  *   %0 if pull-up was successful
724  *   %-EMSGSIZE if a buffer manipulation problem occurred
725  */
726 static int svc_rdma_pull_up_reply_msg(const struct svcxprt_rdma *rdma,
727 				      struct svc_rdma_send_ctxt *sctxt,
728 				      const struct svc_rdma_recv_ctxt *rctxt,
729 				      const struct xdr_buf *xdr)
730 {
731 	struct svc_rdma_pullup_data args = {
732 		.pd_dest	= sctxt->sc_xprt_buf + sctxt->sc_hdrbuf.len,
733 	};
734 	int ret;
735 
736 	ret = pcl_process_nonpayloads(&rctxt->rc_write_pcl, xdr,
737 				      svc_rdma_xb_linearize, &args);
738 	if (ret < 0)
739 		return ret;
740 
741 	sctxt->sc_sges[0].length = sctxt->sc_hdrbuf.len + args.pd_length;
742 	trace_svcrdma_send_pullup(sctxt, args.pd_length);
743 	return 0;
744 }
745 
746 /* svc_rdma_map_reply_msg - DMA map the buffer holding RPC message
747  * @rdma: controlling transport
748  * @sctxt: send_ctxt for the Send WR
749  * @rctxt: Write and Reply chunks provided by client
750  * @xdr: prepared xdr_buf containing RPC message
751  *
752  * Returns:
753  *   %0 if DMA mapping was successful.
754  *   %-EMSGSIZE if a buffer manipulation problem occurred
755  *   %-EIO if DMA mapping failed
756  *
757  * The Send WR's num_sge field is set in all cases.
758  */
759 int svc_rdma_map_reply_msg(struct svcxprt_rdma *rdma,
760 			   struct svc_rdma_send_ctxt *sctxt,
761 			   const struct svc_rdma_recv_ctxt *rctxt,
762 			   const struct xdr_buf *xdr)
763 {
764 	struct svc_rdma_map_data args = {
765 		.md_rdma	= rdma,
766 		.md_ctxt	= sctxt,
767 	};
768 
769 	/* Set up the (persistently-mapped) transport header SGE. */
770 	sctxt->sc_send_wr.num_sge = 1;
771 	sctxt->sc_sges[0].length = sctxt->sc_hdrbuf.len;
772 
773 	/* If there is a Reply chunk, nothing follows the transport
774 	 * header, and we're done here.
775 	 */
776 	if (!pcl_is_empty(&rctxt->rc_reply_pcl))
777 		return 0;
778 
779 	/* For pull-up, svc_rdma_send() will sync the transport header.
780 	 * No additional DMA mapping is necessary.
781 	 */
782 	if (svc_rdma_pull_up_needed(rdma, sctxt, rctxt, xdr))
783 		return svc_rdma_pull_up_reply_msg(rdma, sctxt, rctxt, xdr);
784 
785 	return pcl_process_nonpayloads(&rctxt->rc_write_pcl, xdr,
786 				       svc_rdma_xb_dma_map, &args);
787 }
788 
789 /* Prepare the portion of the RPC Reply that will be transmitted
790  * via RDMA Send. The RPC-over-RDMA transport header is prepared
791  * in sc_sges[0], and the RPC xdr_buf is prepared in following sges.
792  *
793  * Depending on whether a Write list or Reply chunk is present,
794  * the server may send all, a portion of, or none of the xdr_buf.
795  * In the latter case, only the transport header (sc_sges[0]) is
796  * transmitted.
797  *
798  * RDMA Send is the last step of transmitting an RPC reply. Pages
799  * involved in the earlier RDMA Writes are here transferred out
800  * of the rqstp and into the sctxt's page array. These pages are
801  * DMA unmapped by each Write completion, but the subsequent Send
802  * completion finally releases these pages.
803  *
804  * Assumptions:
805  * - The Reply's transport header will never be larger than a page.
806  */
807 static int svc_rdma_send_reply_msg(struct svcxprt_rdma *rdma,
808 				   struct svc_rdma_send_ctxt *sctxt,
809 				   const struct svc_rdma_recv_ctxt *rctxt,
810 				   struct svc_rqst *rqstp)
811 {
812 	int ret;
813 
814 	ret = svc_rdma_map_reply_msg(rdma, sctxt, rctxt, &rqstp->rq_res);
815 	if (ret < 0)
816 		return ret;
817 
818 	if (rctxt->rc_inv_rkey) {
819 		sctxt->sc_send_wr.opcode = IB_WR_SEND_WITH_INV;
820 		sctxt->sc_send_wr.ex.invalidate_rkey = rctxt->rc_inv_rkey;
821 	} else {
822 		sctxt->sc_send_wr.opcode = IB_WR_SEND;
823 	}
824 
825 	ret = svc_rdma_send(rdma, sctxt);
826 	if (ret < 0)
827 		return ret;
828 
829 	ret = wait_for_completion_killable(&sctxt->sc_done);
830 	svc_rdma_send_ctxt_put(rdma, sctxt);
831 	return ret;
832 }
833 
834 /**
835  * svc_rdma_send_error_msg - Send an RPC/RDMA v1 error response
836  * @rdma: controlling transport context
837  * @sctxt: Send context for the response
838  * @rctxt: Receive context for incoming bad message
839  * @status: negative errno indicating error that occurred
840  *
841  * Given the client-provided Read, Write, and Reply chunks, the
842  * server was not able to parse the Call or form a complete Reply.
843  * Return an RDMA_ERROR message so the client can retire the RPC
844  * transaction.
845  *
846  * The caller does not have to release @sctxt. It is released by
847  * Send completion, or by this function on error.
848  */
849 void svc_rdma_send_error_msg(struct svcxprt_rdma *rdma,
850 			     struct svc_rdma_send_ctxt *sctxt,
851 			     struct svc_rdma_recv_ctxt *rctxt,
852 			     int status)
853 {
854 	__be32 *rdma_argp = rctxt->rc_recv_buf;
855 	__be32 *p;
856 
857 	rpcrdma_set_xdrlen(&sctxt->sc_hdrbuf, 0);
858 	xdr_init_encode(&sctxt->sc_stream, &sctxt->sc_hdrbuf,
859 			sctxt->sc_xprt_buf, NULL);
860 
861 	p = xdr_reserve_space(&sctxt->sc_stream,
862 			      rpcrdma_fixed_maxsz * sizeof(*p));
863 	if (!p)
864 		goto put_ctxt;
865 
866 	*p++ = *rdma_argp;
867 	*p++ = *(rdma_argp + 1);
868 	*p++ = rdma->sc_fc_credits;
869 	*p = rdma_error;
870 
871 	switch (status) {
872 	case -EPROTONOSUPPORT:
873 		p = xdr_reserve_space(&sctxt->sc_stream, 3 * sizeof(*p));
874 		if (!p)
875 			goto put_ctxt;
876 
877 		*p++ = err_vers;
878 		*p++ = rpcrdma_version;
879 		*p = rpcrdma_version;
880 		trace_svcrdma_err_vers(*rdma_argp);
881 		break;
882 	default:
883 		p = xdr_reserve_space(&sctxt->sc_stream, sizeof(*p));
884 		if (!p)
885 			goto put_ctxt;
886 
887 		*p = err_chunk;
888 		trace_svcrdma_err_chunk(*rdma_argp);
889 	}
890 
891 	/* Remote Invalidation is skipped for simplicity. */
892 	sctxt->sc_send_wr.num_sge = 1;
893 	sctxt->sc_send_wr.opcode = IB_WR_SEND;
894 	sctxt->sc_sges[0].length = sctxt->sc_hdrbuf.len;
895 	if (svc_rdma_send(rdma, sctxt))
896 		goto put_ctxt;
897 
898 	wait_for_completion_killable(&sctxt->sc_done);
899 
900 put_ctxt:
901 	svc_rdma_send_ctxt_put(rdma, sctxt);
902 }
903 
904 /**
905  * svc_rdma_sendto - Transmit an RPC reply
906  * @rqstp: processed RPC request, reply XDR already in ::rq_res
907  *
908  * Any resources still associated with @rqstp are released upon return.
909  * If no reply message was possible, the connection is closed.
910  *
911  * Returns:
912  *	%0 if an RPC reply has been successfully posted,
913  *	%-ENOMEM if a resource shortage occurred (connection is lost),
914  *	%-ENOTCONN if posting failed (connection is lost).
915  */
916 int svc_rdma_sendto(struct svc_rqst *rqstp)
917 {
918 	struct svc_xprt *xprt = rqstp->rq_xprt;
919 	struct svcxprt_rdma *rdma =
920 		container_of(xprt, struct svcxprt_rdma, sc_xprt);
921 	struct svc_rdma_recv_ctxt *rctxt = rqstp->rq_xprt_ctxt;
922 	__be32 *rdma_argp = rctxt->rc_recv_buf;
923 	struct svc_rdma_send_ctxt *sctxt;
924 	unsigned int rc_size;
925 	__be32 *p;
926 	int ret;
927 
928 	ret = -ENOTCONN;
929 	if (svc_xprt_is_dead(xprt))
930 		goto drop_connection;
931 
932 	ret = -ENOMEM;
933 	sctxt = svc_rdma_send_ctxt_get(rdma);
934 	if (!sctxt)
935 		goto drop_connection;
936 
937 	ret = -EMSGSIZE;
938 	p = xdr_reserve_space(&sctxt->sc_stream,
939 			      rpcrdma_fixed_maxsz * sizeof(*p));
940 	if (!p)
941 		goto put_ctxt;
942 
943 	ret = svc_rdma_send_reply_chunk(rdma, rctxt, &rqstp->rq_res);
944 	if (ret < 0)
945 		goto reply_chunk;
946 	rc_size = ret;
947 
948 	*p++ = *rdma_argp;
949 	*p++ = *(rdma_argp + 1);
950 	*p++ = rdma->sc_fc_credits;
951 	*p = pcl_is_empty(&rctxt->rc_reply_pcl) ? rdma_msg : rdma_nomsg;
952 
953 	ret = svc_rdma_encode_read_list(sctxt);
954 	if (ret < 0)
955 		goto put_ctxt;
956 	ret = svc_rdma_encode_write_list(rctxt, sctxt);
957 	if (ret < 0)
958 		goto put_ctxt;
959 	ret = svc_rdma_encode_reply_chunk(rctxt, sctxt, rc_size);
960 	if (ret < 0)
961 		goto put_ctxt;
962 
963 	ret = svc_rdma_send_reply_msg(rdma, sctxt, rctxt, rqstp);
964 	if (ret < 0)
965 		goto put_ctxt;
966 
967 	/* Prevent svc_xprt_release() from releasing the page backing
968 	 * rq_res.head[0].iov_base. It's no longer being accessed by
969 	 * the I/O device. */
970 	rqstp->rq_respages++;
971 	return 0;
972 
973 reply_chunk:
974 	if (ret != -E2BIG && ret != -EINVAL)
975 		goto put_ctxt;
976 
977 	svc_rdma_send_error_msg(rdma, sctxt, rctxt, ret);
978 	return 0;
979 
980 put_ctxt:
981 	svc_rdma_send_ctxt_put(rdma, sctxt);
982 drop_connection:
983 	trace_svcrdma_send_err(rqstp, ret);
984 	svc_xprt_deferred_close(&rdma->sc_xprt);
985 	return -ENOTCONN;
986 }
987 
988 /**
989  * svc_rdma_result_payload - special processing for a result payload
990  * @rqstp: svc_rqst to operate on
991  * @offset: payload's byte offset in @xdr
992  * @length: size of payload, in bytes
993  *
994  * Return values:
995  *   %0 if successful or nothing needed to be done
996  *   %-EMSGSIZE on XDR buffer overflow
997  *   %-E2BIG if the payload was larger than the Write chunk
998  *   %-EINVAL if client provided too many segments
999  *   %-ENOMEM if rdma_rw context pool was exhausted
1000  *   %-ENOTCONN if posting failed (connection is lost)
1001  *   %-EIO if rdma_rw initialization failed (DMA mapping, etc)
1002  */
1003 int svc_rdma_result_payload(struct svc_rqst *rqstp, unsigned int offset,
1004 			    unsigned int length)
1005 {
1006 	struct svc_rdma_recv_ctxt *rctxt = rqstp->rq_xprt_ctxt;
1007 	struct svc_rdma_chunk *chunk;
1008 	struct svcxprt_rdma *rdma;
1009 	struct xdr_buf subbuf;
1010 	int ret;
1011 
1012 	chunk = rctxt->rc_cur_result_payload;
1013 	if (!length || !chunk)
1014 		return 0;
1015 	rctxt->rc_cur_result_payload =
1016 		pcl_next_chunk(&rctxt->rc_write_pcl, chunk);
1017 	if (length > chunk->ch_length)
1018 		return -E2BIG;
1019 
1020 	chunk->ch_position = offset;
1021 	chunk->ch_payload_length = length;
1022 
1023 	if (xdr_buf_subsegment(&rqstp->rq_res, &subbuf, offset, length))
1024 		return -EMSGSIZE;
1025 
1026 	rdma = container_of(rqstp->rq_xprt, struct svcxprt_rdma, sc_xprt);
1027 	ret = svc_rdma_send_write_chunk(rdma, chunk, &subbuf);
1028 	if (ret < 0)
1029 		return ret;
1030 	return 0;
1031 }
1032