]> asedeno.scripts.mit.edu Git - linux.git/blob - net/sunrpc/xprtrdma/verbs.c
74dbba84ad386b5e6d9930760f21a1481f503523
[linux.git] / net / sunrpc / xprtrdma / verbs.c
1 /*
2  * Copyright (c) 2003-2007 Network Appliance, Inc. All rights reserved.
3  *
4  * This software is available to you under a choice of one of two
5  * licenses.  You may choose to be licensed under the terms of the GNU
6  * General Public License (GPL) Version 2, available from the file
7  * COPYING in the main directory of this source tree, or the BSD-type
8  * license below:
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  *      Redistributions of source code must retain the above copyright
15  *      notice, this list of conditions and the following disclaimer.
16  *
17  *      Redistributions in binary form must reproduce the above
18  *      copyright notice, this list of conditions and the following
19  *      disclaimer in the documentation and/or other materials provided
20  *      with the distribution.
21  *
22  *      Neither the name of the Network Appliance, Inc. nor the names of
23  *      its contributors may be used to endorse or promote products
24  *      derived from this software without specific prior written
25  *      permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39
40 /*
41  * verbs.c
42  *
43  * Encapsulates the major functions managing:
44  *  o adapters
45  *  o endpoints
46  *  o connections
47  *  o buffer memory
48  */
49
50 #include <linux/interrupt.h>
51 #include <linux/slab.h>
52 #include <linux/prefetch.h>
53 #include <linux/sunrpc/addr.h>
54 #include <linux/sunrpc/svc_rdma.h>
55 #include <asm/bitops.h>
56
57 #include <rdma/ib_cm.h>
58
59 #include "xprt_rdma.h"
60
61 /*
62  * Globals/Macros
63  */
64
65 #if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
66 # define RPCDBG_FACILITY        RPCDBG_TRANS
67 #endif
68
69 /*
70  * internal functions
71  */
72 static void rpcrdma_create_mrs(struct rpcrdma_xprt *r_xprt);
73 static void rpcrdma_destroy_mrs(struct rpcrdma_buffer *buf);
74 static void rpcrdma_dma_unmap_regbuf(struct rpcrdma_regbuf *rb);
75
76 static struct workqueue_struct *rpcrdma_receive_wq __read_mostly;
77
78 int
79 rpcrdma_alloc_wq(void)
80 {
81         struct workqueue_struct *recv_wq;
82
83         recv_wq = alloc_workqueue("xprtrdma_receive",
84                                   WQ_MEM_RECLAIM | WQ_UNBOUND | WQ_HIGHPRI,
85                                   0);
86         if (!recv_wq)
87                 return -ENOMEM;
88
89         rpcrdma_receive_wq = recv_wq;
90         return 0;
91 }
92
93 void
94 rpcrdma_destroy_wq(void)
95 {
96         struct workqueue_struct *wq;
97
98         if (rpcrdma_receive_wq) {
99                 wq = rpcrdma_receive_wq;
100                 rpcrdma_receive_wq = NULL;
101                 destroy_workqueue(wq);
102         }
103 }
104
105 static void
106 rpcrdma_qp_async_error_upcall(struct ib_event *event, void *context)
107 {
108         struct rpcrdma_ep *ep = context;
109
110         pr_err("rpcrdma: %s on device %s ep %p\n",
111                ib_event_msg(event->event), event->device->name, context);
112
113         if (ep->rep_connected == 1) {
114                 ep->rep_connected = -EIO;
115                 rpcrdma_conn_func(ep);
116                 wake_up_all(&ep->rep_connect_wait);
117         }
118 }
119
120 /**
121  * rpcrdma_wc_send - Invoked by RDMA provider for each polled Send WC
122  * @cq: completion queue (ignored)
123  * @wc: completed WR
124  *
125  */
126 static void
127 rpcrdma_wc_send(struct ib_cq *cq, struct ib_wc *wc)
128 {
129         /* WARNING: Only wr_cqe and status are reliable at this point */
130         if (wc->status != IB_WC_SUCCESS && wc->status != IB_WC_WR_FLUSH_ERR)
131                 pr_err("rpcrdma: Send: %s (%u/0x%x)\n",
132                        ib_wc_status_msg(wc->status),
133                        wc->status, wc->vendor_err);
134 }
135
136 /* Perform basic sanity checking to avoid using garbage
137  * to update the credit grant value.
138  */
139 static void
140 rpcrdma_update_granted_credits(struct rpcrdma_rep *rep)
141 {
142         struct rpcrdma_msg *rmsgp = rdmab_to_msg(rep->rr_rdmabuf);
143         struct rpcrdma_buffer *buffer = &rep->rr_rxprt->rx_buf;
144         u32 credits;
145
146         if (rep->rr_len < RPCRDMA_HDRLEN_ERR)
147                 return;
148
149         credits = be32_to_cpu(rmsgp->rm_credit);
150         if (credits == 0)
151                 credits = 1;    /* don't deadlock */
152         else if (credits > buffer->rb_max_requests)
153                 credits = buffer->rb_max_requests;
154
155         atomic_set(&buffer->rb_credits, credits);
156 }
157
158 /**
159  * rpcrdma_wc_receive - Invoked by RDMA provider for each polled Receive WC
160  * @cq: completion queue (ignored)
161  * @wc: completed WR
162  *
163  */
164 static void
165 rpcrdma_wc_receive(struct ib_cq *cq, struct ib_wc *wc)
166 {
167         struct ib_cqe *cqe = wc->wr_cqe;
168         struct rpcrdma_rep *rep = container_of(cqe, struct rpcrdma_rep,
169                                                rr_cqe);
170
171         /* WARNING: Only wr_id and status are reliable at this point */
172         if (wc->status != IB_WC_SUCCESS)
173                 goto out_fail;
174
175         /* status == SUCCESS means all fields in wc are trustworthy */
176         dprintk("RPC:       %s: rep %p opcode 'recv', length %u: success\n",
177                 __func__, rep, wc->byte_len);
178
179         rep->rr_len = wc->byte_len;
180         rpcrdma_set_xdrlen(&rep->rr_hdrbuf, wc->byte_len);
181         rep->rr_wc_flags = wc->wc_flags;
182         rep->rr_inv_rkey = wc->ex.invalidate_rkey;
183
184         ib_dma_sync_single_for_cpu(rdmab_device(rep->rr_rdmabuf),
185                                    rdmab_addr(rep->rr_rdmabuf),
186                                    rep->rr_len, DMA_FROM_DEVICE);
187
188         rpcrdma_update_granted_credits(rep);
189
190 out_schedule:
191         queue_work(rpcrdma_receive_wq, &rep->rr_work);
192         return;
193
194 out_fail:
195         if (wc->status != IB_WC_WR_FLUSH_ERR)
196                 pr_err("rpcrdma: Recv: %s (%u/0x%x)\n",
197                        ib_wc_status_msg(wc->status),
198                        wc->status, wc->vendor_err);
199         rep->rr_len = RPCRDMA_BAD_LEN;
200         goto out_schedule;
201 }
202
203 static void
204 rpcrdma_update_connect_private(struct rpcrdma_xprt *r_xprt,
205                                struct rdma_conn_param *param)
206 {
207         struct rpcrdma_create_data_internal *cdata = &r_xprt->rx_data;
208         const struct rpcrdma_connect_private *pmsg = param->private_data;
209         unsigned int rsize, wsize;
210
211         /* Default settings for RPC-over-RDMA Version One */
212         r_xprt->rx_ia.ri_reminv_expected = false;
213         r_xprt->rx_ia.ri_implicit_roundup = xprt_rdma_pad_optimize;
214         rsize = RPCRDMA_V1_DEF_INLINE_SIZE;
215         wsize = RPCRDMA_V1_DEF_INLINE_SIZE;
216
217         if (pmsg &&
218             pmsg->cp_magic == rpcrdma_cmp_magic &&
219             pmsg->cp_version == RPCRDMA_CMP_VERSION) {
220                 r_xprt->rx_ia.ri_reminv_expected = true;
221                 r_xprt->rx_ia.ri_implicit_roundup = true;
222                 rsize = rpcrdma_decode_buffer_size(pmsg->cp_send_size);
223                 wsize = rpcrdma_decode_buffer_size(pmsg->cp_recv_size);
224         }
225
226         if (rsize < cdata->inline_rsize)
227                 cdata->inline_rsize = rsize;
228         if (wsize < cdata->inline_wsize)
229                 cdata->inline_wsize = wsize;
230         dprintk("RPC:       %s: max send %u, max recv %u\n",
231                 __func__, cdata->inline_wsize, cdata->inline_rsize);
232         rpcrdma_set_max_header_sizes(r_xprt);
233 }
234
235 static int
236 rpcrdma_conn_upcall(struct rdma_cm_id *id, struct rdma_cm_event *event)
237 {
238         struct rpcrdma_xprt *xprt = id->context;
239         struct rpcrdma_ia *ia = &xprt->rx_ia;
240         struct rpcrdma_ep *ep = &xprt->rx_ep;
241 #if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
242         struct sockaddr *sap = (struct sockaddr *)&ep->rep_remote_addr;
243 #endif
244         int connstate = 0;
245
246         switch (event->event) {
247         case RDMA_CM_EVENT_ADDR_RESOLVED:
248         case RDMA_CM_EVENT_ROUTE_RESOLVED:
249                 ia->ri_async_rc = 0;
250                 complete(&ia->ri_done);
251                 break;
252         case RDMA_CM_EVENT_ADDR_ERROR:
253                 ia->ri_async_rc = -EHOSTUNREACH;
254                 dprintk("RPC:       %s: CM address resolution error, ep 0x%p\n",
255                         __func__, ep);
256                 complete(&ia->ri_done);
257                 break;
258         case RDMA_CM_EVENT_ROUTE_ERROR:
259                 ia->ri_async_rc = -ENETUNREACH;
260                 dprintk("RPC:       %s: CM route resolution error, ep 0x%p\n",
261                         __func__, ep);
262                 complete(&ia->ri_done);
263                 break;
264         case RDMA_CM_EVENT_DEVICE_REMOVAL:
265 #if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
266                 pr_info("rpcrdma: removing device %s for %pIS:%u\n",
267                         ia->ri_device->name,
268                         sap, rpc_get_port(sap));
269 #endif
270                 set_bit(RPCRDMA_IAF_REMOVING, &ia->ri_flags);
271                 ep->rep_connected = -ENODEV;
272                 xprt_force_disconnect(&xprt->rx_xprt);
273                 wait_for_completion(&ia->ri_remove_done);
274
275                 ia->ri_id = NULL;
276                 ia->ri_pd = NULL;
277                 ia->ri_device = NULL;
278                 /* Return 1 to ensure the core destroys the id. */
279                 return 1;
280         case RDMA_CM_EVENT_ESTABLISHED:
281                 connstate = 1;
282                 rpcrdma_update_connect_private(xprt, &event->param.conn);
283                 goto connected;
284         case RDMA_CM_EVENT_CONNECT_ERROR:
285                 connstate = -ENOTCONN;
286                 goto connected;
287         case RDMA_CM_EVENT_UNREACHABLE:
288                 connstate = -ENETDOWN;
289                 goto connected;
290         case RDMA_CM_EVENT_REJECTED:
291                 dprintk("rpcrdma: connection to %pIS:%u rejected: %s\n",
292                         sap, rpc_get_port(sap),
293                         rdma_reject_msg(id, event->status));
294                 connstate = -ECONNREFUSED;
295                 if (event->status == IB_CM_REJ_STALE_CONN)
296                         connstate = -EAGAIN;
297                 goto connected;
298         case RDMA_CM_EVENT_DISCONNECTED:
299                 connstate = -ECONNABORTED;
300 connected:
301                 atomic_set(&xprt->rx_buf.rb_credits, 1);
302                 ep->rep_connected = connstate;
303                 rpcrdma_conn_func(ep);
304                 wake_up_all(&ep->rep_connect_wait);
305                 /*FALLTHROUGH*/
306         default:
307                 dprintk("RPC:       %s: %pIS:%u on %s/%s (ep 0x%p): %s\n",
308                         __func__, sap, rpc_get_port(sap),
309                         ia->ri_device->name, ia->ri_ops->ro_displayname,
310                         ep, rdma_event_msg(event->event));
311                 break;
312         }
313
314         return 0;
315 }
316
317 static struct rdma_cm_id *
318 rpcrdma_create_id(struct rpcrdma_xprt *xprt,
319                         struct rpcrdma_ia *ia, struct sockaddr *addr)
320 {
321         unsigned long wtimeout = msecs_to_jiffies(RDMA_RESOLVE_TIMEOUT) + 1;
322         struct rdma_cm_id *id;
323         int rc;
324
325         init_completion(&ia->ri_done);
326         init_completion(&ia->ri_remove_done);
327
328         id = rdma_create_id(&init_net, rpcrdma_conn_upcall, xprt, RDMA_PS_TCP,
329                             IB_QPT_RC);
330         if (IS_ERR(id)) {
331                 rc = PTR_ERR(id);
332                 dprintk("RPC:       %s: rdma_create_id() failed %i\n",
333                         __func__, rc);
334                 return id;
335         }
336
337         ia->ri_async_rc = -ETIMEDOUT;
338         rc = rdma_resolve_addr(id, NULL, addr, RDMA_RESOLVE_TIMEOUT);
339         if (rc) {
340                 dprintk("RPC:       %s: rdma_resolve_addr() failed %i\n",
341                         __func__, rc);
342                 goto out;
343         }
344         rc = wait_for_completion_interruptible_timeout(&ia->ri_done, wtimeout);
345         if (rc < 0) {
346                 dprintk("RPC:       %s: wait() exited: %i\n",
347                         __func__, rc);
348                 goto out;
349         }
350
351         rc = ia->ri_async_rc;
352         if (rc)
353                 goto out;
354
355         ia->ri_async_rc = -ETIMEDOUT;
356         rc = rdma_resolve_route(id, RDMA_RESOLVE_TIMEOUT);
357         if (rc) {
358                 dprintk("RPC:       %s: rdma_resolve_route() failed %i\n",
359                         __func__, rc);
360                 goto out;
361         }
362         rc = wait_for_completion_interruptible_timeout(&ia->ri_done, wtimeout);
363         if (rc < 0) {
364                 dprintk("RPC:       %s: wait() exited: %i\n",
365                         __func__, rc);
366                 goto out;
367         }
368         rc = ia->ri_async_rc;
369         if (rc)
370                 goto out;
371
372         return id;
373
374 out:
375         rdma_destroy_id(id);
376         return ERR_PTR(rc);
377 }
378
379 /*
380  * Exported functions.
381  */
382
383 /**
384  * rpcrdma_ia_open - Open and initialize an Interface Adapter.
385  * @xprt: controlling transport
386  * @addr: IP address of remote peer
387  *
388  * Returns 0 on success, negative errno if an appropriate
389  * Interface Adapter could not be found and opened.
390  */
391 int
392 rpcrdma_ia_open(struct rpcrdma_xprt *xprt, struct sockaddr *addr)
393 {
394         struct rpcrdma_ia *ia = &xprt->rx_ia;
395         int rc;
396
397         ia->ri_id = rpcrdma_create_id(xprt, ia, addr);
398         if (IS_ERR(ia->ri_id)) {
399                 rc = PTR_ERR(ia->ri_id);
400                 goto out_err;
401         }
402         ia->ri_device = ia->ri_id->device;
403
404         ia->ri_pd = ib_alloc_pd(ia->ri_device, 0);
405         if (IS_ERR(ia->ri_pd)) {
406                 rc = PTR_ERR(ia->ri_pd);
407                 pr_err("rpcrdma: ib_alloc_pd() returned %d\n", rc);
408                 goto out_err;
409         }
410
411         switch (xprt_rdma_memreg_strategy) {
412         case RPCRDMA_FRMR:
413                 if (frwr_is_supported(ia)) {
414                         ia->ri_ops = &rpcrdma_frwr_memreg_ops;
415                         break;
416                 }
417                 /*FALLTHROUGH*/
418         case RPCRDMA_MTHCAFMR:
419                 if (fmr_is_supported(ia)) {
420                         ia->ri_ops = &rpcrdma_fmr_memreg_ops;
421                         break;
422                 }
423                 /*FALLTHROUGH*/
424         default:
425                 pr_err("rpcrdma: Device %s does not support memreg mode %d\n",
426                        ia->ri_device->name, xprt_rdma_memreg_strategy);
427                 rc = -EINVAL;
428                 goto out_err;
429         }
430
431         return 0;
432
433 out_err:
434         rpcrdma_ia_close(ia);
435         return rc;
436 }
437
438 /**
439  * rpcrdma_ia_remove - Handle device driver unload
440  * @ia: interface adapter being removed
441  *
442  * Divest transport H/W resources associated with this adapter,
443  * but allow it to be restored later.
444  */
445 void
446 rpcrdma_ia_remove(struct rpcrdma_ia *ia)
447 {
448         struct rpcrdma_xprt *r_xprt = container_of(ia, struct rpcrdma_xprt,
449                                                    rx_ia);
450         struct rpcrdma_ep *ep = &r_xprt->rx_ep;
451         struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
452         struct rpcrdma_req *req;
453         struct rpcrdma_rep *rep;
454
455         cancel_delayed_work_sync(&buf->rb_refresh_worker);
456
457         /* This is similar to rpcrdma_ep_destroy, but:
458          * - Don't cancel the connect worker.
459          * - Don't call rpcrdma_ep_disconnect, which waits
460          *   for another conn upcall, which will deadlock.
461          * - rdma_disconnect is unneeded, the underlying
462          *   connection is already gone.
463          */
464         if (ia->ri_id->qp) {
465                 ib_drain_qp(ia->ri_id->qp);
466                 rdma_destroy_qp(ia->ri_id);
467                 ia->ri_id->qp = NULL;
468         }
469         ib_free_cq(ep->rep_attr.recv_cq);
470         ib_free_cq(ep->rep_attr.send_cq);
471
472         /* The ULP is responsible for ensuring all DMA
473          * mappings and MRs are gone.
474          */
475         list_for_each_entry(rep, &buf->rb_recv_bufs, rr_list)
476                 rpcrdma_dma_unmap_regbuf(rep->rr_rdmabuf);
477         list_for_each_entry(req, &buf->rb_allreqs, rl_all) {
478                 rpcrdma_dma_unmap_regbuf(req->rl_rdmabuf);
479                 rpcrdma_dma_unmap_regbuf(req->rl_sendbuf);
480                 rpcrdma_dma_unmap_regbuf(req->rl_recvbuf);
481         }
482         rpcrdma_destroy_mrs(buf);
483
484         /* Allow waiters to continue */
485         complete(&ia->ri_remove_done);
486 }
487
488 /**
489  * rpcrdma_ia_close - Clean up/close an IA.
490  * @ia: interface adapter to close
491  *
492  */
493 void
494 rpcrdma_ia_close(struct rpcrdma_ia *ia)
495 {
496         dprintk("RPC:       %s: entering\n", __func__);
497         if (ia->ri_id != NULL && !IS_ERR(ia->ri_id)) {
498                 if (ia->ri_id->qp)
499                         rdma_destroy_qp(ia->ri_id);
500                 rdma_destroy_id(ia->ri_id);
501         }
502         ia->ri_id = NULL;
503         ia->ri_device = NULL;
504
505         /* If the pd is still busy, xprtrdma missed freeing a resource */
506         if (ia->ri_pd && !IS_ERR(ia->ri_pd))
507                 ib_dealloc_pd(ia->ri_pd);
508         ia->ri_pd = NULL;
509 }
510
511 /*
512  * Create unconnected endpoint.
513  */
514 int
515 rpcrdma_ep_create(struct rpcrdma_ep *ep, struct rpcrdma_ia *ia,
516                   struct rpcrdma_create_data_internal *cdata)
517 {
518         struct rpcrdma_connect_private *pmsg = &ep->rep_cm_private;
519         unsigned int max_qp_wr, max_sge;
520         struct ib_cq *sendcq, *recvcq;
521         int rc;
522
523         max_sge = min_t(unsigned int, ia->ri_device->attrs.max_sge,
524                         RPCRDMA_MAX_SEND_SGES);
525         if (max_sge < RPCRDMA_MIN_SEND_SGES) {
526                 pr_warn("rpcrdma: HCA provides only %d send SGEs\n", max_sge);
527                 return -ENOMEM;
528         }
529         ia->ri_max_send_sges = max_sge - RPCRDMA_MIN_SEND_SGES;
530
531         if (ia->ri_device->attrs.max_qp_wr <= RPCRDMA_BACKWARD_WRS) {
532                 dprintk("RPC:       %s: insufficient wqe's available\n",
533                         __func__);
534                 return -ENOMEM;
535         }
536         max_qp_wr = ia->ri_device->attrs.max_qp_wr - RPCRDMA_BACKWARD_WRS - 1;
537
538         /* check provider's send/recv wr limits */
539         if (cdata->max_requests > max_qp_wr)
540                 cdata->max_requests = max_qp_wr;
541
542         ep->rep_attr.event_handler = rpcrdma_qp_async_error_upcall;
543         ep->rep_attr.qp_context = ep;
544         ep->rep_attr.srq = NULL;
545         ep->rep_attr.cap.max_send_wr = cdata->max_requests;
546         ep->rep_attr.cap.max_send_wr += RPCRDMA_BACKWARD_WRS;
547         ep->rep_attr.cap.max_send_wr += 1;      /* drain cqe */
548         rc = ia->ri_ops->ro_open(ia, ep, cdata);
549         if (rc)
550                 return rc;
551         ep->rep_attr.cap.max_recv_wr = cdata->max_requests;
552         ep->rep_attr.cap.max_recv_wr += RPCRDMA_BACKWARD_WRS;
553         ep->rep_attr.cap.max_recv_wr += 1;      /* drain cqe */
554         ep->rep_attr.cap.max_send_sge = max_sge;
555         ep->rep_attr.cap.max_recv_sge = 1;
556         ep->rep_attr.cap.max_inline_data = 0;
557         ep->rep_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
558         ep->rep_attr.qp_type = IB_QPT_RC;
559         ep->rep_attr.port_num = ~0;
560
561         dprintk("RPC:       %s: requested max: dtos: send %d recv %d; "
562                 "iovs: send %d recv %d\n",
563                 __func__,
564                 ep->rep_attr.cap.max_send_wr,
565                 ep->rep_attr.cap.max_recv_wr,
566                 ep->rep_attr.cap.max_send_sge,
567                 ep->rep_attr.cap.max_recv_sge);
568
569         /* set trigger for requesting send completion */
570         ep->rep_cqinit = ep->rep_attr.cap.max_send_wr/2 - 1;
571         if (ep->rep_cqinit <= 2)
572                 ep->rep_cqinit = 0;     /* always signal? */
573         rpcrdma_init_cqcount(ep, 0);
574         init_waitqueue_head(&ep->rep_connect_wait);
575         INIT_DELAYED_WORK(&ep->rep_connect_worker, rpcrdma_connect_worker);
576
577         sendcq = ib_alloc_cq(ia->ri_device, NULL,
578                              ep->rep_attr.cap.max_send_wr + 1,
579                              0, IB_POLL_SOFTIRQ);
580         if (IS_ERR(sendcq)) {
581                 rc = PTR_ERR(sendcq);
582                 dprintk("RPC:       %s: failed to create send CQ: %i\n",
583                         __func__, rc);
584                 goto out1;
585         }
586
587         recvcq = ib_alloc_cq(ia->ri_device, NULL,
588                              ep->rep_attr.cap.max_recv_wr + 1,
589                              0, IB_POLL_SOFTIRQ);
590         if (IS_ERR(recvcq)) {
591                 rc = PTR_ERR(recvcq);
592                 dprintk("RPC:       %s: failed to create recv CQ: %i\n",
593                         __func__, rc);
594                 goto out2;
595         }
596
597         ep->rep_attr.send_cq = sendcq;
598         ep->rep_attr.recv_cq = recvcq;
599
600         /* Initialize cma parameters */
601         memset(&ep->rep_remote_cma, 0, sizeof(ep->rep_remote_cma));
602
603         /* Prepare RDMA-CM private message */
604         pmsg->cp_magic = rpcrdma_cmp_magic;
605         pmsg->cp_version = RPCRDMA_CMP_VERSION;
606         pmsg->cp_flags |= ia->ri_ops->ro_send_w_inv_ok;
607         pmsg->cp_send_size = rpcrdma_encode_buffer_size(cdata->inline_wsize);
608         pmsg->cp_recv_size = rpcrdma_encode_buffer_size(cdata->inline_rsize);
609         ep->rep_remote_cma.private_data = pmsg;
610         ep->rep_remote_cma.private_data_len = sizeof(*pmsg);
611
612         /* Client offers RDMA Read but does not initiate */
613         ep->rep_remote_cma.initiator_depth = 0;
614         if (ia->ri_device->attrs.max_qp_rd_atom > 32)   /* arbitrary but <= 255 */
615                 ep->rep_remote_cma.responder_resources = 32;
616         else
617                 ep->rep_remote_cma.responder_resources =
618                                                 ia->ri_device->attrs.max_qp_rd_atom;
619
620         /* Limit transport retries so client can detect server
621          * GID changes quickly. RPC layer handles re-establishing
622          * transport connection and retransmission.
623          */
624         ep->rep_remote_cma.retry_count = 6;
625
626         /* RPC-over-RDMA handles its own flow control. In addition,
627          * make all RNR NAKs visible so we know that RPC-over-RDMA
628          * flow control is working correctly (no NAKs should be seen).
629          */
630         ep->rep_remote_cma.flow_control = 0;
631         ep->rep_remote_cma.rnr_retry_count = 0;
632
633         return 0;
634
635 out2:
636         ib_free_cq(sendcq);
637 out1:
638         return rc;
639 }
640
641 /*
642  * rpcrdma_ep_destroy
643  *
644  * Disconnect and destroy endpoint. After this, the only
645  * valid operations on the ep are to free it (if dynamically
646  * allocated) or re-create it.
647  */
648 void
649 rpcrdma_ep_destroy(struct rpcrdma_ep *ep, struct rpcrdma_ia *ia)
650 {
651         dprintk("RPC:       %s: entering, connected is %d\n",
652                 __func__, ep->rep_connected);
653
654         cancel_delayed_work_sync(&ep->rep_connect_worker);
655
656         if (ia->ri_id->qp) {
657                 rpcrdma_ep_disconnect(ep, ia);
658                 rdma_destroy_qp(ia->ri_id);
659                 ia->ri_id->qp = NULL;
660         }
661
662         ib_free_cq(ep->rep_attr.recv_cq);
663         ib_free_cq(ep->rep_attr.send_cq);
664 }
665
666 /* Re-establish a connection after a device removal event.
667  * Unlike a normal reconnection, a fresh PD and a new set
668  * of MRs and buffers is needed.
669  */
670 static int
671 rpcrdma_ep_recreate_xprt(struct rpcrdma_xprt *r_xprt,
672                          struct rpcrdma_ep *ep, struct rpcrdma_ia *ia)
673 {
674         struct sockaddr *sap = (struct sockaddr *)&r_xprt->rx_data.addr;
675         int rc, err;
676
677         pr_info("%s: r_xprt = %p\n", __func__, r_xprt);
678
679         rc = -EHOSTUNREACH;
680         if (rpcrdma_ia_open(r_xprt, sap))
681                 goto out1;
682
683         rc = -ENOMEM;
684         err = rpcrdma_ep_create(ep, ia, &r_xprt->rx_data);
685         if (err) {
686                 pr_err("rpcrdma: rpcrdma_ep_create returned %d\n", err);
687                 goto out2;
688         }
689
690         rc = -ENETUNREACH;
691         err = rdma_create_qp(ia->ri_id, ia->ri_pd, &ep->rep_attr);
692         if (err) {
693                 pr_err("rpcrdma: rdma_create_qp returned %d\n", err);
694                 goto out3;
695         }
696
697         rpcrdma_create_mrs(r_xprt);
698         return 0;
699
700 out3:
701         rpcrdma_ep_destroy(ep, ia);
702 out2:
703         rpcrdma_ia_close(ia);
704 out1:
705         return rc;
706 }
707
708 static int
709 rpcrdma_ep_reconnect(struct rpcrdma_xprt *r_xprt, struct rpcrdma_ep *ep,
710                      struct rpcrdma_ia *ia)
711 {
712         struct sockaddr *sap = (struct sockaddr *)&r_xprt->rx_data.addr;
713         struct rdma_cm_id *id, *old;
714         int err, rc;
715
716         dprintk("RPC:       %s: reconnecting...\n", __func__);
717
718         rpcrdma_ep_disconnect(ep, ia);
719
720         rc = -EHOSTUNREACH;
721         id = rpcrdma_create_id(r_xprt, ia, sap);
722         if (IS_ERR(id))
723                 goto out;
724
725         /* As long as the new ID points to the same device as the
726          * old ID, we can reuse the transport's existing PD and all
727          * previously allocated MRs. Also, the same device means
728          * the transport's previous DMA mappings are still valid.
729          *
730          * This is a sanity check only. There should be no way these
731          * point to two different devices here.
732          */
733         old = id;
734         rc = -ENETUNREACH;
735         if (ia->ri_device != id->device) {
736                 pr_err("rpcrdma: can't reconnect on different device!\n");
737                 goto out_destroy;
738         }
739
740         err = rdma_create_qp(id, ia->ri_pd, &ep->rep_attr);
741         if (err) {
742                 dprintk("RPC:       %s: rdma_create_qp returned %d\n",
743                         __func__, err);
744                 goto out_destroy;
745         }
746
747         /* Atomically replace the transport's ID and QP. */
748         rc = 0;
749         old = ia->ri_id;
750         ia->ri_id = id;
751         rdma_destroy_qp(old);
752
753 out_destroy:
754         rdma_destroy_id(old);
755 out:
756         return rc;
757 }
758
759 /*
760  * Connect unconnected endpoint.
761  */
762 int
763 rpcrdma_ep_connect(struct rpcrdma_ep *ep, struct rpcrdma_ia *ia)
764 {
765         struct rpcrdma_xprt *r_xprt = container_of(ia, struct rpcrdma_xprt,
766                                                    rx_ia);
767         unsigned int extras;
768         int rc;
769
770 retry:
771         switch (ep->rep_connected) {
772         case 0:
773                 dprintk("RPC:       %s: connecting...\n", __func__);
774                 rc = rdma_create_qp(ia->ri_id, ia->ri_pd, &ep->rep_attr);
775                 if (rc) {
776                         dprintk("RPC:       %s: rdma_create_qp failed %i\n",
777                                 __func__, rc);
778                         rc = -ENETUNREACH;
779                         goto out_noupdate;
780                 }
781                 break;
782         case -ENODEV:
783                 rc = rpcrdma_ep_recreate_xprt(r_xprt, ep, ia);
784                 if (rc)
785                         goto out_noupdate;
786                 break;
787         default:
788                 rc = rpcrdma_ep_reconnect(r_xprt, ep, ia);
789                 if (rc)
790                         goto out;
791         }
792
793         ep->rep_connected = 0;
794
795         rc = rdma_connect(ia->ri_id, &ep->rep_remote_cma);
796         if (rc) {
797                 dprintk("RPC:       %s: rdma_connect() failed with %i\n",
798                                 __func__, rc);
799                 goto out;
800         }
801
802         wait_event_interruptible(ep->rep_connect_wait, ep->rep_connected != 0);
803         if (ep->rep_connected <= 0) {
804                 if (ep->rep_connected == -EAGAIN)
805                         goto retry;
806                 rc = ep->rep_connected;
807                 goto out;
808         }
809
810         dprintk("RPC:       %s: connected\n", __func__);
811         extras = r_xprt->rx_buf.rb_bc_srv_max_requests;
812         if (extras)
813                 rpcrdma_ep_post_extra_recv(r_xprt, extras);
814
815 out:
816         if (rc)
817                 ep->rep_connected = rc;
818
819 out_noupdate:
820         return rc;
821 }
822
823 /*
824  * rpcrdma_ep_disconnect
825  *
826  * This is separate from destroy to facilitate the ability
827  * to reconnect without recreating the endpoint.
828  *
829  * This call is not reentrant, and must not be made in parallel
830  * on the same endpoint.
831  */
832 void
833 rpcrdma_ep_disconnect(struct rpcrdma_ep *ep, struct rpcrdma_ia *ia)
834 {
835         int rc;
836
837         rc = rdma_disconnect(ia->ri_id);
838         if (!rc) {
839                 /* returns without wait if not connected */
840                 wait_event_interruptible(ep->rep_connect_wait,
841                                                         ep->rep_connected != 1);
842                 dprintk("RPC:       %s: after wait, %sconnected\n", __func__,
843                         (ep->rep_connected == 1) ? "still " : "dis");
844         } else {
845                 dprintk("RPC:       %s: rdma_disconnect %i\n", __func__, rc);
846                 ep->rep_connected = rc;
847         }
848
849         ib_drain_qp(ia->ri_id->qp);
850 }
851
852 static void
853 rpcrdma_mr_recovery_worker(struct work_struct *work)
854 {
855         struct rpcrdma_buffer *buf = container_of(work, struct rpcrdma_buffer,
856                                                   rb_recovery_worker.work);
857         struct rpcrdma_mw *mw;
858
859         spin_lock(&buf->rb_recovery_lock);
860         while (!list_empty(&buf->rb_stale_mrs)) {
861                 mw = rpcrdma_pop_mw(&buf->rb_stale_mrs);
862                 spin_unlock(&buf->rb_recovery_lock);
863
864                 dprintk("RPC:       %s: recovering MR %p\n", __func__, mw);
865                 mw->mw_xprt->rx_ia.ri_ops->ro_recover_mr(mw);
866
867                 spin_lock(&buf->rb_recovery_lock);
868         }
869         spin_unlock(&buf->rb_recovery_lock);
870 }
871
872 void
873 rpcrdma_defer_mr_recovery(struct rpcrdma_mw *mw)
874 {
875         struct rpcrdma_xprt *r_xprt = mw->mw_xprt;
876         struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
877
878         spin_lock(&buf->rb_recovery_lock);
879         rpcrdma_push_mw(mw, &buf->rb_stale_mrs);
880         spin_unlock(&buf->rb_recovery_lock);
881
882         schedule_delayed_work(&buf->rb_recovery_worker, 0);
883 }
884
885 static void
886 rpcrdma_create_mrs(struct rpcrdma_xprt *r_xprt)
887 {
888         struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
889         struct rpcrdma_ia *ia = &r_xprt->rx_ia;
890         unsigned int count;
891         LIST_HEAD(free);
892         LIST_HEAD(all);
893
894         for (count = 0; count < 32; count++) {
895                 struct rpcrdma_mw *mw;
896                 int rc;
897
898                 mw = kzalloc(sizeof(*mw), GFP_KERNEL);
899                 if (!mw)
900                         break;
901
902                 rc = ia->ri_ops->ro_init_mr(ia, mw);
903                 if (rc) {
904                         kfree(mw);
905                         break;
906                 }
907
908                 mw->mw_xprt = r_xprt;
909
910                 list_add(&mw->mw_list, &free);
911                 list_add(&mw->mw_all, &all);
912         }
913
914         spin_lock(&buf->rb_mwlock);
915         list_splice(&free, &buf->rb_mws);
916         list_splice(&all, &buf->rb_all);
917         r_xprt->rx_stats.mrs_allocated += count;
918         spin_unlock(&buf->rb_mwlock);
919
920         dprintk("RPC:       %s: created %u MRs\n", __func__, count);
921 }
922
923 static void
924 rpcrdma_mr_refresh_worker(struct work_struct *work)
925 {
926         struct rpcrdma_buffer *buf = container_of(work, struct rpcrdma_buffer,
927                                                   rb_refresh_worker.work);
928         struct rpcrdma_xprt *r_xprt = container_of(buf, struct rpcrdma_xprt,
929                                                    rx_buf);
930
931         rpcrdma_create_mrs(r_xprt);
932 }
933
934 struct rpcrdma_req *
935 rpcrdma_create_req(struct rpcrdma_xprt *r_xprt)
936 {
937         struct rpcrdma_buffer *buffer = &r_xprt->rx_buf;
938         struct rpcrdma_req *req;
939
940         req = kzalloc(sizeof(*req), GFP_KERNEL);
941         if (req == NULL)
942                 return ERR_PTR(-ENOMEM);
943
944         spin_lock(&buffer->rb_reqslock);
945         list_add(&req->rl_all, &buffer->rb_allreqs);
946         spin_unlock(&buffer->rb_reqslock);
947         req->rl_cqe.done = rpcrdma_wc_send;
948         req->rl_buffer = &r_xprt->rx_buf;
949         INIT_LIST_HEAD(&req->rl_registered);
950         req->rl_send_wr.next = NULL;
951         req->rl_send_wr.wr_cqe = &req->rl_cqe;
952         req->rl_send_wr.sg_list = req->rl_send_sge;
953         req->rl_send_wr.opcode = IB_WR_SEND;
954         return req;
955 }
956
957 struct rpcrdma_rep *
958 rpcrdma_create_rep(struct rpcrdma_xprt *r_xprt)
959 {
960         struct rpcrdma_create_data_internal *cdata = &r_xprt->rx_data;
961         struct rpcrdma_rep *rep;
962         int rc;
963
964         rc = -ENOMEM;
965         rep = kzalloc(sizeof(*rep), GFP_KERNEL);
966         if (rep == NULL)
967                 goto out;
968
969         rep->rr_rdmabuf = rpcrdma_alloc_regbuf(cdata->inline_rsize,
970                                                DMA_FROM_DEVICE, GFP_KERNEL);
971         if (IS_ERR(rep->rr_rdmabuf)) {
972                 rc = PTR_ERR(rep->rr_rdmabuf);
973                 goto out_free;
974         }
975         xdr_buf_init(&rep->rr_hdrbuf, rep->rr_rdmabuf->rg_base,
976                      rdmab_length(rep->rr_rdmabuf));
977
978         rep->rr_cqe.done = rpcrdma_wc_receive;
979         rep->rr_rxprt = r_xprt;
980         INIT_WORK(&rep->rr_work, rpcrdma_reply_handler);
981         rep->rr_recv_wr.next = NULL;
982         rep->rr_recv_wr.wr_cqe = &rep->rr_cqe;
983         rep->rr_recv_wr.sg_list = &rep->rr_rdmabuf->rg_iov;
984         rep->rr_recv_wr.num_sge = 1;
985         return rep;
986
987 out_free:
988         kfree(rep);
989 out:
990         return ERR_PTR(rc);
991 }
992
993 int
994 rpcrdma_buffer_create(struct rpcrdma_xprt *r_xprt)
995 {
996         struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
997         int i, rc;
998
999         buf->rb_max_requests = r_xprt->rx_data.max_requests;
1000         buf->rb_bc_srv_max_requests = 0;
1001         atomic_set(&buf->rb_credits, 1);
1002         spin_lock_init(&buf->rb_mwlock);
1003         spin_lock_init(&buf->rb_lock);
1004         spin_lock_init(&buf->rb_recovery_lock);
1005         INIT_LIST_HEAD(&buf->rb_mws);
1006         INIT_LIST_HEAD(&buf->rb_all);
1007         INIT_LIST_HEAD(&buf->rb_pending);
1008         INIT_LIST_HEAD(&buf->rb_stale_mrs);
1009         INIT_DELAYED_WORK(&buf->rb_refresh_worker,
1010                           rpcrdma_mr_refresh_worker);
1011         INIT_DELAYED_WORK(&buf->rb_recovery_worker,
1012                           rpcrdma_mr_recovery_worker);
1013
1014         rpcrdma_create_mrs(r_xprt);
1015
1016         INIT_LIST_HEAD(&buf->rb_send_bufs);
1017         INIT_LIST_HEAD(&buf->rb_allreqs);
1018         spin_lock_init(&buf->rb_reqslock);
1019         for (i = 0; i < buf->rb_max_requests; i++) {
1020                 struct rpcrdma_req *req;
1021
1022                 req = rpcrdma_create_req(r_xprt);
1023                 if (IS_ERR(req)) {
1024                         dprintk("RPC:       %s: request buffer %d alloc"
1025                                 " failed\n", __func__, i);
1026                         rc = PTR_ERR(req);
1027                         goto out;
1028                 }
1029                 req->rl_backchannel = false;
1030                 list_add(&req->rl_list, &buf->rb_send_bufs);
1031         }
1032
1033         INIT_LIST_HEAD(&buf->rb_recv_bufs);
1034         for (i = 0; i < buf->rb_max_requests + RPCRDMA_MAX_BC_REQUESTS; i++) {
1035                 struct rpcrdma_rep *rep;
1036
1037                 rep = rpcrdma_create_rep(r_xprt);
1038                 if (IS_ERR(rep)) {
1039                         dprintk("RPC:       %s: reply buffer %d alloc failed\n",
1040                                 __func__, i);
1041                         rc = PTR_ERR(rep);
1042                         goto out;
1043                 }
1044                 list_add(&rep->rr_list, &buf->rb_recv_bufs);
1045         }
1046
1047         return 0;
1048 out:
1049         rpcrdma_buffer_destroy(buf);
1050         return rc;
1051 }
1052
1053 static struct rpcrdma_req *
1054 rpcrdma_buffer_get_req_locked(struct rpcrdma_buffer *buf)
1055 {
1056         struct rpcrdma_req *req;
1057
1058         req = list_first_entry(&buf->rb_send_bufs,
1059                                struct rpcrdma_req, rl_list);
1060         list_del_init(&req->rl_list);
1061         return req;
1062 }
1063
1064 static struct rpcrdma_rep *
1065 rpcrdma_buffer_get_rep_locked(struct rpcrdma_buffer *buf)
1066 {
1067         struct rpcrdma_rep *rep;
1068
1069         rep = list_first_entry(&buf->rb_recv_bufs,
1070                                struct rpcrdma_rep, rr_list);
1071         list_del(&rep->rr_list);
1072         return rep;
1073 }
1074
1075 static void
1076 rpcrdma_destroy_rep(struct rpcrdma_rep *rep)
1077 {
1078         rpcrdma_free_regbuf(rep->rr_rdmabuf);
1079         kfree(rep);
1080 }
1081
1082 void
1083 rpcrdma_destroy_req(struct rpcrdma_req *req)
1084 {
1085         rpcrdma_free_regbuf(req->rl_recvbuf);
1086         rpcrdma_free_regbuf(req->rl_sendbuf);
1087         rpcrdma_free_regbuf(req->rl_rdmabuf);
1088         kfree(req);
1089 }
1090
1091 static void
1092 rpcrdma_destroy_mrs(struct rpcrdma_buffer *buf)
1093 {
1094         struct rpcrdma_xprt *r_xprt = container_of(buf, struct rpcrdma_xprt,
1095                                                    rx_buf);
1096         struct rpcrdma_ia *ia = rdmab_to_ia(buf);
1097         struct rpcrdma_mw *mw;
1098         unsigned int count;
1099
1100         count = 0;
1101         spin_lock(&buf->rb_mwlock);
1102         while (!list_empty(&buf->rb_all)) {
1103                 mw = list_entry(buf->rb_all.next, struct rpcrdma_mw, mw_all);
1104                 list_del(&mw->mw_all);
1105
1106                 spin_unlock(&buf->rb_mwlock);
1107                 ia->ri_ops->ro_release_mr(mw);
1108                 count++;
1109                 spin_lock(&buf->rb_mwlock);
1110         }
1111         spin_unlock(&buf->rb_mwlock);
1112         r_xprt->rx_stats.mrs_allocated = 0;
1113
1114         dprintk("RPC:       %s: released %u MRs\n", __func__, count);
1115 }
1116
1117 void
1118 rpcrdma_buffer_destroy(struct rpcrdma_buffer *buf)
1119 {
1120         cancel_delayed_work_sync(&buf->rb_recovery_worker);
1121         cancel_delayed_work_sync(&buf->rb_refresh_worker);
1122
1123         while (!list_empty(&buf->rb_recv_bufs)) {
1124                 struct rpcrdma_rep *rep;
1125
1126                 rep = rpcrdma_buffer_get_rep_locked(buf);
1127                 rpcrdma_destroy_rep(rep);
1128         }
1129         buf->rb_send_count = 0;
1130
1131         spin_lock(&buf->rb_reqslock);
1132         while (!list_empty(&buf->rb_allreqs)) {
1133                 struct rpcrdma_req *req;
1134
1135                 req = list_first_entry(&buf->rb_allreqs,
1136                                        struct rpcrdma_req, rl_all);
1137                 list_del(&req->rl_all);
1138
1139                 spin_unlock(&buf->rb_reqslock);
1140                 rpcrdma_destroy_req(req);
1141                 spin_lock(&buf->rb_reqslock);
1142         }
1143         spin_unlock(&buf->rb_reqslock);
1144         buf->rb_recv_count = 0;
1145
1146         rpcrdma_destroy_mrs(buf);
1147 }
1148
1149 struct rpcrdma_mw *
1150 rpcrdma_get_mw(struct rpcrdma_xprt *r_xprt)
1151 {
1152         struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
1153         struct rpcrdma_mw *mw = NULL;
1154
1155         spin_lock(&buf->rb_mwlock);
1156         if (!list_empty(&buf->rb_mws))
1157                 mw = rpcrdma_pop_mw(&buf->rb_mws);
1158         spin_unlock(&buf->rb_mwlock);
1159
1160         if (!mw)
1161                 goto out_nomws;
1162         mw->mw_flags = 0;
1163         return mw;
1164
1165 out_nomws:
1166         dprintk("RPC:       %s: no MWs available\n", __func__);
1167         if (r_xprt->rx_ep.rep_connected != -ENODEV)
1168                 schedule_delayed_work(&buf->rb_refresh_worker, 0);
1169
1170         /* Allow the reply handler and refresh worker to run */
1171         cond_resched();
1172
1173         return NULL;
1174 }
1175
1176 void
1177 rpcrdma_put_mw(struct rpcrdma_xprt *r_xprt, struct rpcrdma_mw *mw)
1178 {
1179         struct rpcrdma_buffer *buf = &r_xprt->rx_buf;
1180
1181         spin_lock(&buf->rb_mwlock);
1182         rpcrdma_push_mw(mw, &buf->rb_mws);
1183         spin_unlock(&buf->rb_mwlock);
1184 }
1185
1186 static struct rpcrdma_rep *
1187 rpcrdma_buffer_get_rep(struct rpcrdma_buffer *buffers)
1188 {
1189         /* If an RPC previously completed without a reply (say, a
1190          * credential problem or a soft timeout occurs) then hold off
1191          * on supplying more Receive buffers until the number of new
1192          * pending RPCs catches up to the number of posted Receives.
1193          */
1194         if (unlikely(buffers->rb_send_count < buffers->rb_recv_count))
1195                 return NULL;
1196
1197         if (unlikely(list_empty(&buffers->rb_recv_bufs)))
1198                 return NULL;
1199         buffers->rb_recv_count++;
1200         return rpcrdma_buffer_get_rep_locked(buffers);
1201 }
1202
1203 /*
1204  * Get a set of request/reply buffers.
1205  *
1206  * Reply buffer (if available) is attached to send buffer upon return.
1207  */
1208 struct rpcrdma_req *
1209 rpcrdma_buffer_get(struct rpcrdma_buffer *buffers)
1210 {
1211         struct rpcrdma_req *req;
1212
1213         spin_lock(&buffers->rb_lock);
1214         if (list_empty(&buffers->rb_send_bufs))
1215                 goto out_reqbuf;
1216         buffers->rb_send_count++;
1217         req = rpcrdma_buffer_get_req_locked(buffers);
1218         req->rl_reply = rpcrdma_buffer_get_rep(buffers);
1219         spin_unlock(&buffers->rb_lock);
1220         return req;
1221
1222 out_reqbuf:
1223         spin_unlock(&buffers->rb_lock);
1224         pr_warn("RPC:       %s: out of request buffers\n", __func__);
1225         return NULL;
1226 }
1227
1228 /*
1229  * Put request/reply buffers back into pool.
1230  * Pre-decrement counter/array index.
1231  */
1232 void
1233 rpcrdma_buffer_put(struct rpcrdma_req *req)
1234 {
1235         struct rpcrdma_buffer *buffers = req->rl_buffer;
1236         struct rpcrdma_rep *rep = req->rl_reply;
1237
1238         req->rl_send_wr.num_sge = 0;
1239         req->rl_reply = NULL;
1240
1241         spin_lock(&buffers->rb_lock);
1242         buffers->rb_send_count--;
1243         list_add_tail(&req->rl_list, &buffers->rb_send_bufs);
1244         if (rep) {
1245                 buffers->rb_recv_count--;
1246                 list_add_tail(&rep->rr_list, &buffers->rb_recv_bufs);
1247         }
1248         spin_unlock(&buffers->rb_lock);
1249 }
1250
1251 /*
1252  * Recover reply buffers from pool.
1253  * This happens when recovering from disconnect.
1254  */
1255 void
1256 rpcrdma_recv_buffer_get(struct rpcrdma_req *req)
1257 {
1258         struct rpcrdma_buffer *buffers = req->rl_buffer;
1259
1260         spin_lock(&buffers->rb_lock);
1261         req->rl_reply = rpcrdma_buffer_get_rep(buffers);
1262         spin_unlock(&buffers->rb_lock);
1263 }
1264
1265 /*
1266  * Put reply buffers back into pool when not attached to
1267  * request. This happens in error conditions.
1268  */
1269 void
1270 rpcrdma_recv_buffer_put(struct rpcrdma_rep *rep)
1271 {
1272         struct rpcrdma_buffer *buffers = &rep->rr_rxprt->rx_buf;
1273
1274         spin_lock(&buffers->rb_lock);
1275         buffers->rb_recv_count--;
1276         list_add_tail(&rep->rr_list, &buffers->rb_recv_bufs);
1277         spin_unlock(&buffers->rb_lock);
1278 }
1279
1280 /**
1281  * rpcrdma_alloc_regbuf - allocate and DMA-map memory for SEND/RECV buffers
1282  * @size: size of buffer to be allocated, in bytes
1283  * @direction: direction of data movement
1284  * @flags: GFP flags
1285  *
1286  * Returns an ERR_PTR, or a pointer to a regbuf, a buffer that
1287  * can be persistently DMA-mapped for I/O.
1288  *
1289  * xprtrdma uses a regbuf for posting an outgoing RDMA SEND, or for
1290  * receiving the payload of RDMA RECV operations. During Long Calls
1291  * or Replies they may be registered externally via ro_map.
1292  */
1293 struct rpcrdma_regbuf *
1294 rpcrdma_alloc_regbuf(size_t size, enum dma_data_direction direction,
1295                      gfp_t flags)
1296 {
1297         struct rpcrdma_regbuf *rb;
1298
1299         rb = kmalloc(sizeof(*rb) + size, flags);
1300         if (rb == NULL)
1301                 return ERR_PTR(-ENOMEM);
1302
1303         rb->rg_device = NULL;
1304         rb->rg_direction = direction;
1305         rb->rg_iov.length = size;
1306
1307         return rb;
1308 }
1309
1310 /**
1311  * __rpcrdma_map_regbuf - DMA-map a regbuf
1312  * @ia: controlling rpcrdma_ia
1313  * @rb: regbuf to be mapped
1314  */
1315 bool
1316 __rpcrdma_dma_map_regbuf(struct rpcrdma_ia *ia, struct rpcrdma_regbuf *rb)
1317 {
1318         struct ib_device *device = ia->ri_device;
1319
1320         if (rb->rg_direction == DMA_NONE)
1321                 return false;
1322
1323         rb->rg_iov.addr = ib_dma_map_single(device,
1324                                             (void *)rb->rg_base,
1325                                             rdmab_length(rb),
1326                                             rb->rg_direction);
1327         if (ib_dma_mapping_error(device, rdmab_addr(rb)))
1328                 return false;
1329
1330         rb->rg_device = device;
1331         rb->rg_iov.lkey = ia->ri_pd->local_dma_lkey;
1332         return true;
1333 }
1334
1335 static void
1336 rpcrdma_dma_unmap_regbuf(struct rpcrdma_regbuf *rb)
1337 {
1338         if (!rpcrdma_regbuf_is_mapped(rb))
1339                 return;
1340
1341         ib_dma_unmap_single(rb->rg_device, rdmab_addr(rb),
1342                             rdmab_length(rb), rb->rg_direction);
1343         rb->rg_device = NULL;
1344 }
1345
1346 /**
1347  * rpcrdma_free_regbuf - deregister and free registered buffer
1348  * @rb: regbuf to be deregistered and freed
1349  */
1350 void
1351 rpcrdma_free_regbuf(struct rpcrdma_regbuf *rb)
1352 {
1353         if (!rb)
1354                 return;
1355
1356         rpcrdma_dma_unmap_regbuf(rb);
1357         kfree(rb);
1358 }
1359
1360 /*
1361  * Prepost any receive buffer, then post send.
1362  *
1363  * Receive buffer is donated to hardware, reclaimed upon recv completion.
1364  */
1365 int
1366 rpcrdma_ep_post(struct rpcrdma_ia *ia,
1367                 struct rpcrdma_ep *ep,
1368                 struct rpcrdma_req *req)
1369 {
1370         struct ib_send_wr *send_wr = &req->rl_send_wr;
1371         struct ib_send_wr *send_wr_fail;
1372         int rc;
1373
1374         if (req->rl_reply) {
1375                 rc = rpcrdma_ep_post_recv(ia, req->rl_reply);
1376                 if (rc)
1377                         return rc;
1378                 req->rl_reply = NULL;
1379         }
1380
1381         dprintk("RPC:       %s: posting %d s/g entries\n",
1382                 __func__, send_wr->num_sge);
1383
1384         rpcrdma_set_signaled(ep, send_wr);
1385         rc = ib_post_send(ia->ri_id->qp, send_wr, &send_wr_fail);
1386         if (rc)
1387                 goto out_postsend_err;
1388         return 0;
1389
1390 out_postsend_err:
1391         pr_err("rpcrdma: RDMA Send ib_post_send returned %i\n", rc);
1392         return -ENOTCONN;
1393 }
1394
1395 int
1396 rpcrdma_ep_post_recv(struct rpcrdma_ia *ia,
1397                      struct rpcrdma_rep *rep)
1398 {
1399         struct ib_recv_wr *recv_wr_fail;
1400         int rc;
1401
1402         if (!rpcrdma_dma_map_regbuf(ia, rep->rr_rdmabuf))
1403                 goto out_map;
1404         rc = ib_post_recv(ia->ri_id->qp, &rep->rr_recv_wr, &recv_wr_fail);
1405         if (rc)
1406                 goto out_postrecv;
1407         return 0;
1408
1409 out_map:
1410         pr_err("rpcrdma: failed to DMA map the Receive buffer\n");
1411         return -EIO;
1412
1413 out_postrecv:
1414         pr_err("rpcrdma: ib_post_recv returned %i\n", rc);
1415         return -ENOTCONN;
1416 }
1417
1418 /**
1419  * rpcrdma_ep_post_extra_recv - Post buffers for incoming backchannel requests
1420  * @r_xprt: transport associated with these backchannel resources
1421  * @min_reqs: minimum number of incoming requests expected
1422  *
1423  * Returns zero if all requested buffers were posted, or a negative errno.
1424  */
1425 int
1426 rpcrdma_ep_post_extra_recv(struct rpcrdma_xprt *r_xprt, unsigned int count)
1427 {
1428         struct rpcrdma_buffer *buffers = &r_xprt->rx_buf;
1429         struct rpcrdma_ia *ia = &r_xprt->rx_ia;
1430         struct rpcrdma_rep *rep;
1431         int rc;
1432
1433         while (count--) {
1434                 spin_lock(&buffers->rb_lock);
1435                 if (list_empty(&buffers->rb_recv_bufs))
1436                         goto out_reqbuf;
1437                 rep = rpcrdma_buffer_get_rep_locked(buffers);
1438                 spin_unlock(&buffers->rb_lock);
1439
1440                 rc = rpcrdma_ep_post_recv(ia, rep);
1441                 if (rc)
1442                         goto out_rc;
1443         }
1444
1445         return 0;
1446
1447 out_reqbuf:
1448         spin_unlock(&buffers->rb_lock);
1449         pr_warn("%s: no extra receive buffers\n", __func__);
1450         return -ENOMEM;
1451
1452 out_rc:
1453         rpcrdma_recv_buffer_put(rep);
1454         return rc;
1455 }