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