Whamcloud - gitweb
LU-6210 ptlrpc: Use C99 initializer in ptlrpc_register_rqbd()
[fs/lustre-release.git] / lustre / ptlrpc / niobuf.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32
33 #define DEBUG_SUBSYSTEM S_RPC
34 #include <obd_support.h>
35 #include <lustre_net.h>
36 #include <lustre_lib.h>
37 #include <obd.h>
38 #include <obd_class.h>
39 #include "ptlrpc_internal.h"
40
41 /**
42  * Helper function. Sends \a len bytes from \a base at offset \a offset
43  * over \a conn connection to portal \a portal.
44  * Returns 0 on success or error code.
45  */
46 static int ptl_send_buf(struct lnet_handle_md *mdh, void *base, int len,
47                         enum lnet_ack_req ack, struct ptlrpc_cb_id *cbid,
48                         lnet_nid_t self, struct lnet_process_id peer_id,
49                         int portal, __u64 xid, unsigned int offset,
50                         struct lnet_handle_md *bulk_cookie)
51 {
52         int              rc;
53         struct lnet_md         md;
54         ENTRY;
55
56         LASSERT (portal != 0);
57         CDEBUG (D_INFO, "peer_id %s\n", libcfs_id2str(peer_id));
58         md.start     = base;
59         md.length    = len;
60         md.threshold = (ack == LNET_ACK_REQ) ? 2 : 1;
61         md.options   = PTLRPC_MD_OPTIONS;
62         md.user_ptr  = cbid;
63         md.eq_handle = ptlrpc_eq_h;
64         LNetInvalidateMDHandle(&md.bulk_handle);
65
66         if (bulk_cookie) {
67                 md.bulk_handle = *bulk_cookie;
68                 md.options |= LNET_MD_BULK_HANDLE;
69         }
70
71         if (unlikely(ack == LNET_ACK_REQ &&
72                      OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_ACK, OBD_FAIL_ONCE))){
73                 /* don't ask for the ack to simulate failing client */
74                 ack = LNET_NOACK_REQ;
75         }
76
77         rc = LNetMDBind (md, LNET_UNLINK, mdh);
78         if (unlikely(rc != 0)) {
79                 CERROR ("LNetMDBind failed: %d\n", rc);
80                 LASSERT (rc == -ENOMEM);
81                 RETURN (-ENOMEM);
82         }
83
84         CDEBUG(D_NET, "Sending %d bytes to portal %d, xid %lld, offset %u\n",
85                len, portal, xid, offset);
86
87         rc = LNetPut(self, *mdh, ack,
88                      peer_id, portal, xid, offset, 0);
89         if (unlikely(rc != 0)) {
90                 int rc2;
91                 /* We're going to get an UNLINK event when I unlink below,
92                  * which will complete just like any other failed send, so
93                  * I fall through and return success here! */
94                 CERROR("LNetPut(%s, %d, %lld) failed: %d\n",
95                        libcfs_id2str(peer_id), portal, xid, rc);
96                 rc2 = LNetMDUnlink(*mdh);
97                 LASSERTF(rc2 == 0, "rc2 = %d\n", rc2);
98         }
99
100         RETURN (0);
101 }
102
103 static void mdunlink_iterate_helper(struct lnet_handle_md *bd_mds, int count)
104 {
105         int i;
106
107         for (i = 0; i < count; i++)
108                 LNetMDUnlink(bd_mds[i]);
109 }
110
111 #ifdef HAVE_SERVER_SUPPORT
112 /**
113  * Prepare bulk descriptor for specified incoming request \a req that
114  * can fit \a nfrags * pages. \a type is bulk type. \a portal is where
115  * the bulk to be sent. Used on server-side after request was already
116  * received.
117  * Returns pointer to newly allocatrd initialized bulk descriptor or NULL on
118  * error.
119  */
120 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_exp(struct ptlrpc_request *req,
121                                               unsigned nfrags, unsigned max_brw,
122                                               unsigned int type,
123                                               unsigned portal,
124                                               const struct ptlrpc_bulk_frag_ops
125                                                 *ops)
126 {
127         struct obd_export *exp = req->rq_export;
128         struct ptlrpc_bulk_desc *desc;
129
130         ENTRY;
131         LASSERT(ptlrpc_is_bulk_op_active(type));
132
133         desc = ptlrpc_new_bulk(nfrags, max_brw, type, portal, ops);
134         if (desc == NULL)
135                 RETURN(NULL);
136
137         desc->bd_export = class_export_get(exp);
138         desc->bd_req = req;
139
140         desc->bd_cbid.cbid_fn  = server_bulk_callback;
141         desc->bd_cbid.cbid_arg = desc;
142
143         /* NB we don't assign rq_bulk here; server-side requests are
144          * re-used, and the handler frees the bulk desc explicitly. */
145
146         return desc;
147 }
148 EXPORT_SYMBOL(ptlrpc_prep_bulk_exp);
149
150 /**
151  * Starts bulk transfer for descriptor \a desc on the server.
152  * Returns 0 on success or error code.
153  */
154 int ptlrpc_start_bulk_transfer(struct ptlrpc_bulk_desc *desc)
155 {
156         struct obd_export        *exp = desc->bd_export;
157         lnet_nid_t                self_nid;
158         struct lnet_process_id    peer_id;
159         int                       rc = 0;
160         __u64                     mbits;
161         int                       posted_md;
162         int                       total_md;
163         struct lnet_md                 md;
164         ENTRY;
165
166         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_BULK_PUT_NET))
167                 RETURN(0);
168
169         /* NB no locking required until desc is on the network */
170         LASSERT(desc->bd_md_count == 0);
171         LASSERT(ptlrpc_is_bulk_op_active(desc->bd_type));
172
173         LASSERT(desc->bd_cbid.cbid_fn == server_bulk_callback);
174         LASSERT(desc->bd_cbid.cbid_arg == desc);
175
176         /*
177          * Multi-Rail: get the preferred self and peer NIDs from the
178          * request, so they are based on the route taken by the
179          * message.
180          */
181         self_nid = desc->bd_req->rq_self;
182         peer_id = desc->bd_req->rq_source;
183
184         /* NB total length may be 0 for a read past EOF, so we send 0
185          * length bulks, since the client expects bulk events.
186          *
187          * The client may not need all of the bulk mbits for the RPC. The RPC
188          * used the mbits of the highest bulk mbits needed, and the server masks
189          * off high bits to get bulk count for this RPC. LU-1431 */
190         mbits = desc->bd_req->rq_mbits & ~((__u64)desc->bd_md_max_brw - 1);
191         total_md = desc->bd_req->rq_mbits - mbits + 1;
192
193         desc->bd_md_count = total_md;
194         desc->bd_failure = 0;
195
196         md.user_ptr = &desc->bd_cbid;
197         md.eq_handle = ptlrpc_eq_h;
198         md.threshold = 2; /* SENT and ACK/REPLY */
199
200         for (posted_md = 0; posted_md < total_md; mbits++) {
201                 md.options = PTLRPC_MD_OPTIONS;
202
203                 /* NB it's assumed that source and sink buffer frags are
204                  * page-aligned. Otherwise we'd have to send client bulk
205                  * sizes over and split server buffer accordingly */
206                 ptlrpc_fill_bulk_md(&md, desc, posted_md);
207                 rc = LNetMDBind(md, LNET_UNLINK, &desc->bd_mds[posted_md]);
208                 if (rc != 0) {
209                         CERROR("%s: LNetMDBind failed for MD %u: rc = %d\n",
210                                exp->exp_obd->obd_name, posted_md, rc);
211                         LASSERT(rc == -ENOMEM);
212                         if (posted_md == 0) {
213                                 desc->bd_md_count = 0;
214                                 RETURN(-ENOMEM);
215                         }
216                         break;
217                 }
218
219                 /* LU-6441: last md is not sent and desc->bd_md_count == 1 */
220                 if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_CLIENT_BULK_CB3,
221                                          CFS_FAIL_ONCE) &&
222                     total_md > 1 && posted_md == total_md - 1) {
223                         posted_md++;
224                         continue;
225                 }
226
227                 /* Network is about to get at the memory */
228                 if (ptlrpc_is_bulk_put_source(desc->bd_type))
229                         rc = LNetPut(self_nid, desc->bd_mds[posted_md],
230                                      LNET_ACK_REQ, peer_id,
231                                      desc->bd_portal, mbits, 0, 0);
232                 else
233                         rc = LNetGet(self_nid, desc->bd_mds[posted_md],
234                                      peer_id, desc->bd_portal, mbits, 0);
235
236                 posted_md++;
237                 if (rc != 0) {
238                         CERROR("%s: failed bulk transfer with %s:%u x%llu: "
239                                "rc = %d\n", exp->exp_obd->obd_name,
240                                libcfs_id2str(peer_id), desc->bd_portal,
241                                mbits, rc);
242                         break;
243                 }
244         }
245
246         if (rc != 0) {
247                 /* Can't send, so we unlink the MD bound above.  The UNLINK
248                  * event this creates will signal completion with failure,
249                  * so we return SUCCESS here! */
250                 spin_lock(&desc->bd_lock);
251                 desc->bd_md_count -= total_md - posted_md;
252                 spin_unlock(&desc->bd_lock);
253                 LASSERT(desc->bd_md_count >= 0);
254
255                 mdunlink_iterate_helper(desc->bd_mds, posted_md);
256                 RETURN(0);
257         }
258
259         CDEBUG(D_NET, "Transferring %u pages %u bytes via portal %d "
260                "id %s mbits %#llx-%#llx\n", desc->bd_iov_count,
261                desc->bd_nob, desc->bd_portal, libcfs_id2str(peer_id),
262                mbits - posted_md, mbits - 1);
263
264         RETURN(0);
265 }
266
267 /**
268  * Server side bulk abort. Idempotent. Not thread-safe (i.e. only
269  * serialises with completion callback)
270  */
271 void ptlrpc_abort_bulk(struct ptlrpc_bulk_desc *desc)
272 {
273         struct l_wait_info       lwi;
274         int                      rc;
275
276         LASSERT(!in_interrupt());           /* might sleep */
277
278         if (!ptlrpc_server_bulk_active(desc))   /* completed or */
279                 return;                         /* never started */
280
281         /* We used to poison the pages with 0xab here because we did not want to
282          * send any meaningful data over the wire for evicted clients (bug 9297)
283          * However, this is no longer safe now that we use the page cache on the
284          * OSS (bug 20560) */
285
286         /* The unlink ensures the callback happens ASAP and is the last
287          * one.  If it fails, it must be because completion just happened,
288          * but we must still l_wait_event() in this case, to give liblustre
289          * a chance to run server_bulk_callback()*/
290         mdunlink_iterate_helper(desc->bd_mds, desc->bd_md_max_brw);
291
292         for (;;) {
293                 /* Network access will complete in finite time but the HUGE
294                  * timeout lets us CWARN for visibility of sluggish NALs */
295                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
296                                            cfs_time_seconds(1), NULL, NULL);
297                 rc = l_wait_event(desc->bd_waitq,
298                                   !ptlrpc_server_bulk_active(desc), &lwi);
299                 if (rc == 0)
300                         return;
301
302                 LASSERT(rc == -ETIMEDOUT);
303                 CWARN("Unexpectedly long timeout: desc %p\n", desc);
304         }
305 }
306 #endif /* HAVE_SERVER_SUPPORT */
307
308 /**
309  * Register bulk at the sender for later transfer.
310  * Returns 0 on success or error code.
311  */
312 int ptlrpc_register_bulk(struct ptlrpc_request *req)
313 {
314         struct ptlrpc_bulk_desc *desc = req->rq_bulk;
315         struct lnet_process_id peer;
316         int rc = 0;
317         int rc2;
318         int posted_md;
319         int total_md;
320         __u64 mbits;
321         struct lnet_handle_me me_h;
322         struct lnet_md md;
323         ENTRY;
324
325         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_BULK_GET_NET))
326                 RETURN(0);
327
328         /* NB no locking required until desc is on the network */
329         LASSERT(desc->bd_nob > 0);
330         LASSERT(desc->bd_md_count == 0);
331         LASSERT(desc->bd_md_max_brw <= PTLRPC_BULK_OPS_COUNT);
332         LASSERT(desc->bd_iov_count <= PTLRPC_MAX_BRW_PAGES);
333         LASSERT(desc->bd_req != NULL);
334         LASSERT(ptlrpc_is_bulk_op_passive(desc->bd_type));
335
336         /* cleanup the state of the bulk for it will be reused */
337         if (req->rq_resend || req->rq_send_state == LUSTRE_IMP_REPLAY)
338                 desc->bd_nob_transferred = 0;
339         else if (desc->bd_nob_transferred != 0)
340                 /* If the network failed after an RPC was sent, this condition
341                  * could happen.  Rather than assert (was here before), return
342                  * an EIO error. */
343                 RETURN(-EIO);
344
345         desc->bd_failure = 0;
346
347         peer = desc->bd_import->imp_connection->c_peer;
348
349         LASSERT(desc->bd_cbid.cbid_fn == client_bulk_callback);
350         LASSERT(desc->bd_cbid.cbid_arg == desc);
351
352         total_md = (desc->bd_iov_count + LNET_MAX_IOV - 1) / LNET_MAX_IOV;
353         /* rq_mbits is matchbits of the final bulk */
354         mbits = req->rq_mbits - total_md + 1;
355
356         LASSERTF(mbits == (req->rq_mbits & PTLRPC_BULK_OPS_MASK),
357                  "first mbits = x%llu, last mbits = x%llu\n",
358                  mbits, req->rq_mbits);
359         LASSERTF(!(desc->bd_registered &&
360                    req->rq_send_state != LUSTRE_IMP_REPLAY) ||
361                  mbits != desc->bd_last_mbits,
362                  "registered: %d  rq_mbits: %llu bd_last_mbits: %llu\n",
363                  desc->bd_registered, mbits, desc->bd_last_mbits);
364
365         desc->bd_registered = 1;
366         desc->bd_last_mbits = mbits;
367         desc->bd_md_count = total_md;
368         md.user_ptr = &desc->bd_cbid;
369         md.eq_handle = ptlrpc_eq_h;
370         md.threshold = 1;                       /* PUT or GET */
371
372         for (posted_md = 0; posted_md < total_md; posted_md++, mbits++) {
373                 md.options = PTLRPC_MD_OPTIONS |
374                              (ptlrpc_is_bulk_op_get(desc->bd_type) ?
375                               LNET_MD_OP_GET : LNET_MD_OP_PUT);
376                 ptlrpc_fill_bulk_md(&md, desc, posted_md);
377
378                 rc = LNetMEAttach(desc->bd_portal, peer, mbits, 0,
379                                   LNET_UNLINK, LNET_INS_AFTER, &me_h);
380                 if (rc != 0) {
381                         CERROR("%s: LNetMEAttach failed x%llu/%d: rc = %d\n",
382                                desc->bd_import->imp_obd->obd_name, mbits,
383                                posted_md, rc);
384                         break;
385                 }
386
387                 /* About to let the network at it... */
388                 rc = LNetMDAttach(me_h, md, LNET_UNLINK,
389                                   &desc->bd_mds[posted_md]);
390                 if (rc != 0) {
391                         CERROR("%s: LNetMDAttach failed x%llu/%d: rc = %d\n",
392                                desc->bd_import->imp_obd->obd_name, mbits,
393                                posted_md, rc);
394                         rc2 = LNetMEUnlink(me_h);
395                         LASSERT(rc2 == 0);
396                         break;
397                 }
398         }
399
400         if (rc != 0) {
401                 LASSERT(rc == -ENOMEM);
402                 spin_lock(&desc->bd_lock);
403                 desc->bd_md_count -= total_md - posted_md;
404                 spin_unlock(&desc->bd_lock);
405                 LASSERT(desc->bd_md_count >= 0);
406                 mdunlink_iterate_helper(desc->bd_mds, desc->bd_md_max_brw);
407                 req->rq_status = -ENOMEM;
408                 RETURN(-ENOMEM);
409         }
410
411         spin_lock(&desc->bd_lock);
412         /* Holler if peer manages to touch buffers before he knows the mbits */
413         if (desc->bd_md_count != total_md)
414                 CWARN("%s: Peer %s touched %d buffers while I registered\n",
415                       desc->bd_import->imp_obd->obd_name, libcfs_id2str(peer),
416                       total_md - desc->bd_md_count);
417         spin_unlock(&desc->bd_lock);
418
419         CDEBUG(D_NET, "Setup %u bulk %s buffers: %u pages %u bytes, "
420                "mbits x%#llx-%#llx, portal %u\n", desc->bd_md_count,
421                ptlrpc_is_bulk_op_get(desc->bd_type) ? "get-source" : "put-sink",
422                desc->bd_iov_count, desc->bd_nob,
423                desc->bd_last_mbits, req->rq_mbits, desc->bd_portal);
424
425         RETURN(0);
426 }
427
428 /**
429  * Disconnect a bulk desc from the network. Idempotent. Not
430  * thread-safe (i.e. only interlocks with completion callback).
431  * Returns 1 on success or 0 if network unregistration failed for whatever
432  * reason.
433  */
434 int ptlrpc_unregister_bulk(struct ptlrpc_request *req, int async)
435 {
436         struct ptlrpc_bulk_desc *desc = req->rq_bulk;
437         struct l_wait_info       lwi;
438         int                      rc;
439         ENTRY;
440
441         LASSERT(!in_interrupt());     /* might sleep */
442
443         /* Let's setup deadline for reply unlink. */
444         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK) &&
445             async && req->rq_bulk_deadline == 0 && cfs_fail_val == 0)
446                 req->rq_bulk_deadline = ktime_get_real_seconds() + LONG_UNLINK;
447
448         if (ptlrpc_client_bulk_active(req) == 0)        /* completed or */
449                 RETURN(1);                              /* never registered */
450
451         LASSERT(desc->bd_req == req);  /* bd_req NULL until registered */
452
453         /* the unlink ensures the callback happens ASAP and is the last
454          * one.  If it fails, it must be because completion just happened,
455          * but we must still l_wait_event() in this case to give liblustre
456          * a chance to run client_bulk_callback() */
457         mdunlink_iterate_helper(desc->bd_mds, desc->bd_md_max_brw);
458
459         if (ptlrpc_client_bulk_active(req) == 0)        /* completed or */
460                 RETURN(1);                              /* never registered */
461
462         /* Move to "Unregistering" phase as bulk was not unlinked yet. */
463         ptlrpc_rqphase_move(req, RQ_PHASE_UNREG_BULK);
464
465         /* Do not wait for unlink to finish. */
466         if (async)
467                 RETURN(0);
468
469         for (;;) {
470                 /* The wq argument is ignored by user-space wait_event macros */
471                 wait_queue_head_t *wq = (req->rq_set != NULL) ?
472                                         &req->rq_set->set_waitq :
473                                         &req->rq_reply_waitq;
474                 /* Network access will complete in finite time but the HUGE
475                  * timeout lets us CWARN for visibility of sluggish NALs */
476                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
477                                            cfs_time_seconds(1), NULL, NULL);
478                 rc = l_wait_event(*wq, !ptlrpc_client_bulk_active(req), &lwi);
479                 if (rc == 0) {
480                         ptlrpc_rqphase_move(req, req->rq_next_phase);
481                         RETURN(1);
482                 }
483
484                 LASSERT(rc == -ETIMEDOUT);
485                 DEBUG_REQ(D_WARNING, req, "Unexpectedly long timeout: desc %p",
486                           desc);
487         }
488         RETURN(0);
489 }
490
491 static void ptlrpc_at_set_reply(struct ptlrpc_request *req, int flags)
492 {
493         struct ptlrpc_service_part      *svcpt = req->rq_rqbd->rqbd_svcpt;
494         struct ptlrpc_service           *svc = svcpt->scp_service;
495         int service_time = max_t(int, ktime_get_real_seconds() -
496                                  req->rq_arrival_time.tv_sec, 1);
497
498         if (!(flags & PTLRPC_REPLY_EARLY) &&
499             (req->rq_type != PTL_RPC_MSG_ERR) &&
500             (req->rq_reqmsg != NULL) &&
501             !(lustre_msg_get_flags(req->rq_reqmsg) &
502               (MSG_RESENT | MSG_REPLAY |
503                MSG_REQ_REPLAY_DONE | MSG_LOCK_REPLAY_DONE))) {
504                 /* early replies, errors and recovery requests don't count
505                  * toward our service time estimate */
506                 int oldse = at_measured(&svcpt->scp_at_estimate, service_time);
507
508                 if (oldse != 0) {
509                         DEBUG_REQ(D_ADAPTTO, req,
510                                   "svc %s changed estimate from %d to %d",
511                                   svc->srv_name, oldse,
512                                   at_get(&svcpt->scp_at_estimate));
513                 }
514         }
515         /* Report actual service time for client latency calc */
516         lustre_msg_set_service_time(req->rq_repmsg, service_time);
517         /* Report service time estimate for future client reqs, but report 0
518          * (to be ignored by client) if it's an error reply during recovery.
519          * b=15815
520          */
521         if (req->rq_type == PTL_RPC_MSG_ERR &&
522             (req->rq_export == NULL ||
523              req->rq_export->exp_obd->obd_recovering)) {
524                 lustre_msg_set_timeout(req->rq_repmsg, 0);
525         } else {
526                 time64_t timeout;
527
528                 if (req->rq_export && req->rq_reqmsg != NULL &&
529                     (flags & PTLRPC_REPLY_EARLY) &&
530                     lustre_msg_get_flags(req->rq_reqmsg) &
531                     (MSG_REPLAY | MSG_REQ_REPLAY_DONE | MSG_LOCK_REPLAY_DONE)) {
532                         struct obd_device *exp_obd = req->rq_export->exp_obd;
533
534                         timeout = ktime_get_real_seconds() -
535                                   req->rq_arrival_time.tv_sec +
536                                   min_t(time64_t, at_extra,
537                                         exp_obd->obd_recovery_timeout / 4);
538                 } else {
539                         timeout = at_get(&svcpt->scp_at_estimate);
540                 }
541                 lustre_msg_set_timeout(req->rq_repmsg, timeout);
542         }
543
544         if (req->rq_reqmsg &&
545             !(lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT)) {
546                 CDEBUG(D_ADAPTTO, "No early reply support: flags=%#x "
547                        "req_flags=%#x magic=%x/%x len=%d\n",
548                        flags, lustre_msg_get_flags(req->rq_reqmsg),
549                        lustre_msg_get_magic(req->rq_reqmsg),
550                        lustre_msg_get_magic(req->rq_repmsg), req->rq_replen);
551         }
552 }
553
554 /**
555  * Send request reply from request \a req reply buffer.
556  * \a flags defines reply types
557  * Returns 0 on success or error code
558  */
559 int ptlrpc_send_reply(struct ptlrpc_request *req, int flags)
560 {
561         struct ptlrpc_reply_state *rs = req->rq_reply_state;
562         struct ptlrpc_connection  *conn;
563         int                        rc;
564
565         /* We must already have a reply buffer (only ptlrpc_error() may be
566          * called without one). The reply generated by sptlrpc layer (e.g.
567          * error notify, etc.) might have NULL rq->reqmsg; Otherwise we must
568          * have a request buffer which is either the actual (swabbed) incoming
569          * request, or a saved copy if this is a req saved in
570          * target_queue_final_reply().
571          */
572         LASSERT (req->rq_no_reply == 0);
573         LASSERT (req->rq_reqbuf != NULL);
574         LASSERT (rs != NULL);
575         LASSERT ((flags & PTLRPC_REPLY_MAYBE_DIFFICULT) || !rs->rs_difficult);
576         LASSERT (req->rq_repmsg != NULL);
577         LASSERT (req->rq_repmsg == rs->rs_msg);
578         LASSERT (rs->rs_cb_id.cbid_fn == reply_out_callback);
579         LASSERT (rs->rs_cb_id.cbid_arg == rs);
580
581         /* There may be no rq_export during failover */
582
583         if (unlikely(req->rq_export && req->rq_export->exp_obd &&
584                      req->rq_export->exp_obd->obd_fail)) {
585                 /* Failed obd's only send ENODEV */
586                 req->rq_type = PTL_RPC_MSG_ERR;
587                 req->rq_status = -ENODEV;
588                 CDEBUG(D_HA, "sending ENODEV from failed obd %d\n",
589                        req->rq_export->exp_obd->obd_minor);
590         }
591
592         /* In order to keep interoprability with the client (< 2.3) which
593          * doesn't have pb_jobid in ptlrpc_body, We have to shrink the
594          * ptlrpc_body in reply buffer to ptlrpc_body_v2, otherwise, the
595          * reply buffer on client will be overflow.
596          *
597          * XXX Remove this whenver we drop the interoprability with such client.
598          */
599         req->rq_replen = lustre_shrink_msg(req->rq_repmsg, 0,
600                                            sizeof(struct ptlrpc_body_v2), 1);
601
602         if (req->rq_type != PTL_RPC_MSG_ERR)
603                 req->rq_type = PTL_RPC_MSG_REPLY;
604
605         lustre_msg_set_type(req->rq_repmsg, req->rq_type);
606         lustre_msg_set_status(req->rq_repmsg,
607                               ptlrpc_status_hton(req->rq_status));
608         lustre_msg_set_opc(req->rq_repmsg,
609                 req->rq_reqmsg ? lustre_msg_get_opc(req->rq_reqmsg) : 0);
610
611         target_pack_pool_reply(req);
612
613         ptlrpc_at_set_reply(req, flags);
614
615         if (req->rq_export == NULL || req->rq_export->exp_connection == NULL)
616                 conn = ptlrpc_connection_get(req->rq_peer, req->rq_self, NULL);
617         else
618                 conn = ptlrpc_connection_addref(req->rq_export->exp_connection);
619
620         if (unlikely(conn == NULL)) {
621                 CERROR("not replying on NULL connection\n"); /* bug 9635 */
622                 return -ENOTCONN;
623         }
624         ptlrpc_rs_addref(rs);                   /* +1 ref for the network */
625
626         rc = sptlrpc_svc_wrap_reply(req);
627         if (unlikely(rc))
628                 goto out;
629
630         req->rq_sent = ktime_get_real_seconds();
631
632         rc = ptl_send_buf(&rs->rs_md_h, rs->rs_repbuf, rs->rs_repdata_len,
633                           (rs->rs_difficult && !rs->rs_no_ack) ?
634                           LNET_ACK_REQ : LNET_NOACK_REQ,
635                           &rs->rs_cb_id, req->rq_self, req->rq_source,
636                           ptlrpc_req2svc(req)->srv_rep_portal,
637                           req->rq_xid, req->rq_reply_off, NULL);
638 out:
639         if (unlikely(rc != 0))
640                 ptlrpc_req_drop_rs(req);
641         ptlrpc_connection_put(conn);
642         return rc;
643 }
644
645 int ptlrpc_reply (struct ptlrpc_request *req)
646 {
647         if (req->rq_no_reply)
648                 return 0;
649         else
650                 return (ptlrpc_send_reply(req, 0));
651 }
652
653 /**
654  * For request \a req send an error reply back. Create empty
655  * reply buffers if necessary.
656  */
657 int ptlrpc_send_error(struct ptlrpc_request *req, int may_be_difficult)
658 {
659         int rc;
660         ENTRY;
661
662         if (req->rq_no_reply)
663                 RETURN(0);
664
665         if (!req->rq_repmsg) {
666                 rc = lustre_pack_reply(req, 1, NULL, NULL);
667                 if (rc)
668                         RETURN(rc);
669         }
670
671         if (req->rq_status != -ENOSPC && req->rq_status != -EACCES &&
672             req->rq_status != -EPERM && req->rq_status != -ENOENT &&
673             req->rq_status != -EINPROGRESS && req->rq_status != -EDQUOT)
674                 req->rq_type = PTL_RPC_MSG_ERR;
675
676         rc = ptlrpc_send_reply(req, may_be_difficult);
677         RETURN(rc);
678 }
679
680 int ptlrpc_error(struct ptlrpc_request *req)
681 {
682         return ptlrpc_send_error(req, 0);
683 }
684
685 /**
686  * Send request \a request.
687  * if \a noreply is set, don't expect any reply back and don't set up
688  * reply buffers.
689  * Returns 0 on success or error code.
690  */
691 int ptl_send_rpc(struct ptlrpc_request *request, int noreply)
692 {
693         int rc;
694         int rc2;
695         int mpflag = 0;
696         struct lnet_handle_md bulk_cookie;
697         struct ptlrpc_connection *connection;
698         struct lnet_handle_me reply_me_h;
699         struct lnet_md reply_md;
700         struct obd_import *imp = request->rq_import;
701         struct obd_device *obd = imp->imp_obd;
702         ENTRY;
703
704         LNetInvalidateMDHandle(&bulk_cookie);
705
706         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_RPC))
707                 RETURN(0);
708
709         LASSERT(request->rq_type == PTL_RPC_MSG_REQUEST);
710         LASSERT(request->rq_wait_ctx == 0);
711
712         /* If this is a re-transmit, we're required to have disengaged
713          * cleanly from the previous attempt */
714         LASSERT(!request->rq_receiving_reply);
715         LASSERT(!((lustre_msg_get_flags(request->rq_reqmsg) & MSG_REPLAY) &&
716                 (imp->imp_state == LUSTRE_IMP_FULL)));
717
718         if (unlikely(obd != NULL && obd->obd_fail)) {
719                 CDEBUG(D_HA, "muting rpc for failed imp obd %s\n",
720                         obd->obd_name);
721                 /* this prevents us from waiting in ptlrpc_queue_wait */
722                 spin_lock(&request->rq_lock);
723                 request->rq_err = 1;
724                 spin_unlock(&request->rq_lock);
725                 request->rq_status = -ENODEV;
726                 RETURN(-ENODEV);
727         }
728
729         connection = imp->imp_connection;
730
731         lustre_msg_set_handle(request->rq_reqmsg,
732                               &imp->imp_remote_handle);
733         lustre_msg_set_type(request->rq_reqmsg, PTL_RPC_MSG_REQUEST);
734         lustre_msg_set_conn_cnt(request->rq_reqmsg,
735                                 imp->imp_conn_cnt);
736         lustre_msghdr_set_flags(request->rq_reqmsg,
737                                 imp->imp_msghdr_flags);
738
739         /* If it's the first time to resend the request for EINPROGRESS,
740          * we need to allocate a new XID (see after_reply()), it's different
741          * from the resend for reply timeout. */
742         if (request->rq_nr_resend != 0 &&
743             list_empty(&request->rq_unreplied_list)) {
744                 __u64 min_xid = 0;
745                 /* resend for EINPROGRESS, allocate new xid to avoid reply
746                  * reconstruction */
747                 spin_lock(&imp->imp_lock);
748                 ptlrpc_assign_next_xid_nolock(request);
749                 min_xid = ptlrpc_known_replied_xid(imp);
750                 spin_unlock(&imp->imp_lock);
751
752                 lustre_msg_set_last_xid(request->rq_reqmsg, min_xid);
753                 DEBUG_REQ(D_RPCTRACE, request, "Allocating new xid for "
754                           "resend on EINPROGRESS");
755         }
756
757         if (request->rq_bulk != NULL) {
758                 ptlrpc_set_bulk_mbits(request);
759                 lustre_msg_set_mbits(request->rq_reqmsg, request->rq_mbits);
760         }
761
762         if (list_empty(&request->rq_unreplied_list) ||
763             request->rq_xid <= imp->imp_known_replied_xid) {
764                 DEBUG_REQ(D_ERROR, request, "xid: %llu, replied: %llu, "
765                           "list_empty:%d\n", request->rq_xid,
766                           imp->imp_known_replied_xid,
767                           list_empty(&request->rq_unreplied_list));
768                 LBUG();
769         }
770
771         /** For enabled AT all request should have AT_SUPPORT in the
772          * FULL import state when OBD_CONNECT_AT is set */
773         LASSERT(AT_OFF || imp->imp_state != LUSTRE_IMP_FULL ||
774                 (imp->imp_msghdr_flags & MSGHDR_AT_SUPPORT) ||
775                 !(imp->imp_connect_data.ocd_connect_flags &
776                 OBD_CONNECT_AT));
777
778         if (request->rq_resend) {
779                 lustre_msg_add_flags(request->rq_reqmsg, MSG_RESENT);
780                 if (request->rq_resend_cb != NULL)
781                         request->rq_resend_cb(request, &request->rq_async_args);
782         }
783         if (request->rq_memalloc)
784                 mpflag = cfs_memory_pressure_get_and_set();
785
786         rc = sptlrpc_cli_wrap_request(request);
787         if (rc)
788                 GOTO(out, rc);
789
790         /* bulk register should be done after wrap_request() */
791         if (request->rq_bulk != NULL) {
792                 rc = ptlrpc_register_bulk (request);
793                 if (rc != 0)
794                         GOTO(out, rc);
795                 /*
796                  * All the mds in the request will have the same cpt
797                  * encoded in the cookie. So we can just get the first
798                  * one.
799                  */
800                 bulk_cookie = request->rq_bulk->bd_mds[0];
801         }
802
803         if (!noreply) {
804                 LASSERT (request->rq_replen != 0);
805                 if (request->rq_repbuf == NULL) {
806                         LASSERT(request->rq_repdata == NULL);
807                         LASSERT(request->rq_repmsg == NULL);
808                         rc = sptlrpc_cli_alloc_repbuf(request,
809                                                       request->rq_replen);
810                         if (rc) {
811                                 /* this prevents us from looping in
812                                  * ptlrpc_queue_wait */
813                                 spin_lock(&request->rq_lock);
814                                 request->rq_err = 1;
815                                 spin_unlock(&request->rq_lock);
816                                 request->rq_status = rc;
817                                 GOTO(cleanup_bulk, rc);
818                         }
819                 } else {
820                         request->rq_repdata = NULL;
821                         request->rq_repmsg = NULL;
822                 }
823
824                 rc = LNetMEAttach(request->rq_reply_portal,/*XXX FIXME bug 249*/
825                                   connection->c_peer, request->rq_xid, 0,
826                                   LNET_UNLINK, LNET_INS_AFTER, &reply_me_h);
827                 if (rc != 0) {
828                         CERROR("LNetMEAttach failed: %d\n", rc);
829                         LASSERT (rc == -ENOMEM);
830                         GOTO(cleanup_bulk, rc = -ENOMEM);
831                 }
832         }
833
834         spin_lock(&request->rq_lock);
835         /* We are responsible for unlinking the reply buffer */
836         request->rq_reply_unlinked = noreply;
837         request->rq_receiving_reply = !noreply;
838         /* Clear any flags that may be present from previous sends. */
839         request->rq_req_unlinked = 0;
840         request->rq_replied = 0;
841         request->rq_err = 0;
842         request->rq_timedout = 0;
843         request->rq_net_err = 0;
844         request->rq_resend = 0;
845         request->rq_restart = 0;
846         request->rq_reply_truncated = 0;
847         spin_unlock(&request->rq_lock);
848
849         if (!noreply) {
850                 reply_md.start     = request->rq_repbuf;
851                 reply_md.length    = request->rq_repbuf_len;
852                 /* Allow multiple early replies */
853                 reply_md.threshold = LNET_MD_THRESH_INF;
854                 /* Manage remote for early replies */
855                 reply_md.options   = PTLRPC_MD_OPTIONS | LNET_MD_OP_PUT |
856                         LNET_MD_MANAGE_REMOTE |
857                         LNET_MD_TRUNCATE; /* allow to make EOVERFLOW error */;
858                 reply_md.user_ptr  = &request->rq_reply_cbid;
859                 reply_md.eq_handle = ptlrpc_eq_h;
860
861                 /* We must see the unlink callback to set rq_reply_unlinked,
862                  * so we can't auto-unlink */
863                 rc = LNetMDAttach(reply_me_h, reply_md, LNET_RETAIN,
864                                   &request->rq_reply_md_h);
865                 if (rc != 0) {
866                         CERROR("LNetMDAttach failed: %d\n", rc);
867                         LASSERT (rc == -ENOMEM);
868                         spin_lock(&request->rq_lock);
869                         /* ...but the MD attach didn't succeed... */
870                         request->rq_receiving_reply = 0;
871                         spin_unlock(&request->rq_lock);
872                         GOTO(cleanup_me, rc = -ENOMEM);
873                 }
874
875                 CDEBUG(D_NET, "Setup reply buffer: %u bytes, xid %llu"
876                        ", portal %u\n",
877                        request->rq_repbuf_len, request->rq_xid,
878                        request->rq_reply_portal);
879         }
880
881         /* add references on request for request_out_callback */
882         ptlrpc_request_addref(request);
883         if (obd != NULL && obd->obd_svc_stats != NULL)
884                 lprocfs_counter_add(obd->obd_svc_stats, PTLRPC_REQACTIVE_CNTR,
885                         atomic_read(&imp->imp_inflight));
886
887         OBD_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_DELAY_SEND, request->rq_timeout + 5);
888
889         request->rq_sent_ns = ktime_get_real();
890         request->rq_sent = ktime_get_real_seconds();
891         /* We give the server rq_timeout secs to process the req, and
892            add the network latency for our local timeout. */
893         request->rq_deadline = request->rq_sent + request->rq_timeout +
894                 ptlrpc_at_get_net_latency(request);
895
896         ptlrpc_pinger_sending_on_import(imp);
897
898         DEBUG_REQ(D_INFO, request, "send flg=%x",
899                   lustre_msg_get_flags(request->rq_reqmsg));
900         rc = ptl_send_buf(&request->rq_req_md_h,
901                           request->rq_reqbuf, request->rq_reqdata_len,
902                           LNET_NOACK_REQ, &request->rq_req_cbid,
903                           LNET_NID_ANY, connection->c_peer,
904                           request->rq_request_portal,
905                           request->rq_xid, 0, &bulk_cookie);
906         if (likely(rc == 0))
907                 GOTO(out, rc);
908
909         request->rq_req_unlinked = 1;
910         ptlrpc_req_finished(request);
911         if (noreply)
912                 GOTO(out, rc);
913
914  cleanup_me:
915         /* MEUnlink is safe; the PUT didn't even get off the ground, and
916          * nobody apart from the PUT's target has the right nid+XID to
917          * access the reply buffer. */
918         rc2 = LNetMEUnlink(reply_me_h);
919         LASSERT (rc2 == 0);
920         /* UNLINKED callback called synchronously */
921         LASSERT(!request->rq_receiving_reply);
922
923  cleanup_bulk:
924         /* We do sync unlink here as there was no real transfer here so
925          * the chance to have long unlink to sluggish net is smaller here. */
926         ptlrpc_unregister_bulk(request, 0);
927  out:
928         if (rc == -ENOMEM) {
929                 /* set rq_sent so that this request is treated
930                  * as a delayed send in the upper layers */
931                 request->rq_sent = ktime_get_real_seconds();
932         }
933
934         if (request->rq_memalloc)
935                 cfs_memory_pressure_restore(mpflag);
936
937         return rc;
938 }
939 EXPORT_SYMBOL(ptl_send_rpc);
940
941 /**
942  * Register request buffer descriptor for request receiving.
943  */
944 int ptlrpc_register_rqbd(struct ptlrpc_request_buffer_desc *rqbd)
945 {
946         struct ptlrpc_service *service = rqbd->rqbd_svcpt->scp_service;
947         static struct lnet_process_id match_id = {
948                 .nid = LNET_NID_ANY,
949                 .pid = LNET_PID_ANY
950         };
951         int rc;
952         struct lnet_md md;
953         struct lnet_handle_me me_h;
954
955         CDEBUG(D_NET, "LNetMEAttach: portal %d\n",
956                service->srv_req_portal);
957
958         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_RQBD))
959                 return (-ENOMEM);
960
961         /* NB: CPT affinity service should use new LNet flag LNET_INS_LOCAL,
962          * which means buffer can only be attached on local CPT, and LND
963          * threads can find it by grabbing a local lock */
964         rc = LNetMEAttach(service->srv_req_portal,
965                           match_id, 0, ~0, LNET_UNLINK,
966                           rqbd->rqbd_svcpt->scp_cpt >= 0 ?
967                           LNET_INS_LOCAL : LNET_INS_AFTER, &me_h);
968         if (rc != 0) {
969                 CERROR("LNetMEAttach failed: %d\n", rc);
970                 return (-ENOMEM);
971         }
972
973         LASSERT(rqbd->rqbd_refcount == 0);
974         rqbd->rqbd_refcount = 1;
975
976         md.start     = rqbd->rqbd_buffer;
977         md.length    = service->srv_buf_size;
978         md.max_size  = service->srv_max_req_size;
979         md.threshold = LNET_MD_THRESH_INF;
980         md.options   = PTLRPC_MD_OPTIONS | LNET_MD_OP_PUT | LNET_MD_MAX_SIZE;
981         md.user_ptr  = &rqbd->rqbd_cbid;
982         md.eq_handle = ptlrpc_eq_h;
983
984         rc = LNetMDAttach(me_h, md, LNET_UNLINK, &rqbd->rqbd_md_h);
985         if (rc == 0)
986                 return (0);
987
988         CERROR("LNetMDAttach failed: %d; \n", rc);
989         LASSERT (rc == -ENOMEM);
990         rc = LNetMEUnlink (me_h);
991         LASSERT (rc == 0);
992         rqbd->rqbd_refcount = 0;
993
994         return (-ENOMEM);
995 }