Whamcloud - gitweb
LU-6179 llite: remove LOCKAHEAD_OLD compatibility
[fs/lustre-release.git] / lustre / ptlrpc / client.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) 2011, 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 /** Implementation of client-side PortalRPC interfaces */
34
35 #define DEBUG_SUBSYSTEM S_RPC
36
37 #include <linux/delay.h>
38 #include <linux/random.h>
39
40 #include <lnet/lib-lnet.h>
41 #include <obd_support.h>
42 #include <obd_class.h>
43 #include <lustre_lib.h>
44 #include <lustre_ha.h>
45 #include <lustre_import.h>
46 #include <lustre_req_layout.h>
47
48 #include "ptlrpc_internal.h"
49
50 static void ptlrpc_prep_bulk_page_pin(struct ptlrpc_bulk_desc *desc,
51                                       struct page *page, int pageoffset,
52                                       int len)
53 {
54         __ptlrpc_prep_bulk_page(desc, page, pageoffset, len, 1);
55 }
56
57 static void ptlrpc_prep_bulk_page_nopin(struct ptlrpc_bulk_desc *desc,
58                                         struct page *page, int pageoffset,
59                                         int len)
60 {
61         __ptlrpc_prep_bulk_page(desc, page, pageoffset, len, 0);
62 }
63
64 static void ptlrpc_release_bulk_page_pin(struct ptlrpc_bulk_desc *desc)
65 {
66         int i;
67
68         for (i = 0; i < desc->bd_iov_count ; i++)
69                 put_page(desc->bd_vec[i].bv_page);
70 }
71
72 static int ptlrpc_prep_bulk_frag_pages(struct ptlrpc_bulk_desc *desc,
73                                        void *frag, int len)
74 {
75         unsigned int offset = (unsigned long)frag & ~PAGE_MASK;
76
77         ENTRY;
78         while (len > 0) {
79                 int page_len = min_t(unsigned int, PAGE_SIZE - offset,
80                                      len);
81                 unsigned long vaddr = (unsigned long)frag;
82
83                 ptlrpc_prep_bulk_page_nopin(desc,
84                                             lnet_kvaddr_to_page(vaddr),
85                                             offset, page_len);
86                 offset = 0;
87                 len -= page_len;
88                 frag += page_len;
89         }
90
91         RETURN(desc->bd_nob);
92 }
93
94 const struct ptlrpc_bulk_frag_ops ptlrpc_bulk_kiov_pin_ops = {
95         .add_kiov_frag  = ptlrpc_prep_bulk_page_pin,
96         .release_frags  = ptlrpc_release_bulk_page_pin,
97 };
98 EXPORT_SYMBOL(ptlrpc_bulk_kiov_pin_ops);
99
100 const struct ptlrpc_bulk_frag_ops ptlrpc_bulk_kiov_nopin_ops = {
101         .add_kiov_frag  = ptlrpc_prep_bulk_page_nopin,
102         .release_frags  = ptlrpc_release_bulk_noop,
103         .add_iov_frag   = ptlrpc_prep_bulk_frag_pages,
104 };
105 EXPORT_SYMBOL(ptlrpc_bulk_kiov_nopin_ops);
106
107 static int ptlrpc_send_new_req(struct ptlrpc_request *req);
108 static int ptlrpcd_check_work(struct ptlrpc_request *req);
109 static int ptlrpc_unregister_reply(struct ptlrpc_request *request, int async);
110
111 /**
112  * Initialize passed in client structure \a cl.
113  */
114 void ptlrpc_init_client(int req_portal, int rep_portal, const char *name,
115                         struct ptlrpc_client *cl)
116 {
117         cl->cli_request_portal = req_portal;
118         cl->cli_reply_portal   = rep_portal;
119         cl->cli_name           = name;
120 }
121 EXPORT_SYMBOL(ptlrpc_init_client);
122
123 /**
124  * Return PortalRPC connection for remore uud \a uuid
125  */
126 struct ptlrpc_connection *ptlrpc_uuid_to_connection(struct obd_uuid *uuid,
127                                                     lnet_nid_t nid4refnet)
128 {
129         struct ptlrpc_connection *c;
130         lnet_nid_t self;
131         struct lnet_process_id peer;
132         int err;
133
134         /*
135          * ptlrpc_uuid_to_peer() initializes its 2nd parameter
136          * before accessing its values.
137          */
138         /* coverity[uninit_use_in_call] */
139         peer.nid = nid4refnet;
140         err = ptlrpc_uuid_to_peer(uuid, &peer, &self);
141         if (err != 0) {
142                 CNETERR("cannot find peer %s!\n", uuid->uuid);
143                 return NULL;
144         }
145
146         c = ptlrpc_connection_get(peer, self, uuid);
147         if (c) {
148                 memcpy(c->c_remote_uuid.uuid,
149                        uuid->uuid, sizeof(c->c_remote_uuid.uuid));
150         }
151
152         CDEBUG(D_INFO, "%s -> %p\n", uuid->uuid, c);
153
154         return c;
155 }
156
157 /**
158  * Allocate and initialize new bulk descriptor on the sender.
159  * Returns pointer to the descriptor or NULL on error.
160  */
161 struct ptlrpc_bulk_desc *ptlrpc_new_bulk(unsigned int nfrags,
162                                          unsigned int max_brw,
163                                          enum ptlrpc_bulk_op_type type,
164                                          unsigned int portal,
165                                          const struct ptlrpc_bulk_frag_ops *ops)
166 {
167         struct ptlrpc_bulk_desc *desc;
168         int i;
169
170         LASSERT(ops->add_kiov_frag != NULL);
171
172         OBD_ALLOC_PTR(desc);
173         if (!desc)
174                 return NULL;
175
176         OBD_ALLOC_LARGE(desc->bd_vec,
177                         nfrags * sizeof(*desc->bd_vec));
178         if (!desc->bd_vec)
179                 goto out;
180
181         spin_lock_init(&desc->bd_lock);
182         init_waitqueue_head(&desc->bd_waitq);
183         desc->bd_max_iov = nfrags;
184         desc->bd_iov_count = 0;
185         desc->bd_portal = portal;
186         desc->bd_type = type;
187         desc->bd_md_count = 0;
188         desc->bd_frag_ops = ops;
189         LASSERT(max_brw > 0);
190         desc->bd_md_max_brw = min(max_brw, PTLRPC_BULK_OPS_COUNT);
191         /*
192          * PTLRPC_BULK_OPS_COUNT is the compile-time transfer limit for this
193          * node. Negotiated ocd_brw_size will always be <= this number.
194          */
195         for (i = 0; i < PTLRPC_BULK_OPS_COUNT; i++)
196                 LNetInvalidateMDHandle(&desc->bd_mds[i]);
197
198         return desc;
199 out:
200         OBD_FREE_PTR(desc);
201         return NULL;
202 }
203
204 /**
205  * Prepare bulk descriptor for specified outgoing request \a req that
206  * can fit \a nfrags * pages. \a type is bulk type. \a portal is where
207  * the bulk to be sent. Used on client-side.
208  * Returns pointer to newly allocatrd initialized bulk descriptor or NULL on
209  * error.
210  */
211 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_imp(struct ptlrpc_request *req,
212                                               unsigned int nfrags,
213                                               unsigned int max_brw,
214                                               unsigned int type,
215                                               unsigned int portal,
216                                               const struct ptlrpc_bulk_frag_ops
217                                                 *ops)
218 {
219         struct obd_import *imp = req->rq_import;
220         struct ptlrpc_bulk_desc *desc;
221
222         ENTRY;
223         LASSERT(ptlrpc_is_bulk_op_passive(type));
224
225         desc = ptlrpc_new_bulk(nfrags, max_brw, type, portal, ops);
226         if (!desc)
227                 RETURN(NULL);
228
229         desc->bd_import = class_import_get(imp);
230         desc->bd_req = req;
231
232         desc->bd_cbid.cbid_fn  = client_bulk_callback;
233         desc->bd_cbid.cbid_arg = desc;
234
235         /* This makes req own desc, and free it when she frees herself */
236         req->rq_bulk = desc;
237
238         return desc;
239 }
240 EXPORT_SYMBOL(ptlrpc_prep_bulk_imp);
241
242 void __ptlrpc_prep_bulk_page(struct ptlrpc_bulk_desc *desc,
243                              struct page *page, int pageoffset, int len,
244                              int pin)
245 {
246         struct bio_vec *kiov;
247
248         LASSERT(desc->bd_iov_count < desc->bd_max_iov);
249         LASSERT(page != NULL);
250         LASSERT(pageoffset >= 0);
251         LASSERT(len > 0);
252         LASSERT(pageoffset + len <= PAGE_SIZE);
253
254         kiov = &desc->bd_vec[desc->bd_iov_count];
255
256         desc->bd_nob += len;
257
258         if (pin)
259                 get_page(page);
260
261         kiov->bv_page = page;
262         kiov->bv_offset = pageoffset;
263         kiov->bv_len = len;
264
265         desc->bd_iov_count++;
266 }
267 EXPORT_SYMBOL(__ptlrpc_prep_bulk_page);
268
269 void ptlrpc_free_bulk(struct ptlrpc_bulk_desc *desc)
270 {
271         ENTRY;
272
273         LASSERT(desc != NULL);
274         LASSERT(desc->bd_iov_count != LI_POISON); /* not freed already */
275         LASSERT(desc->bd_md_count == 0);         /* network hands off */
276         LASSERT((desc->bd_export != NULL) ^ (desc->bd_import != NULL));
277         LASSERT(desc->bd_frag_ops != NULL);
278
279         sptlrpc_enc_pool_put_pages(desc);
280
281         if (desc->bd_export)
282                 class_export_put(desc->bd_export);
283         else
284                 class_import_put(desc->bd_import);
285
286         if (desc->bd_frag_ops->release_frags != NULL)
287                 desc->bd_frag_ops->release_frags(desc);
288
289         OBD_FREE_LARGE(desc->bd_vec,
290                        desc->bd_max_iov * sizeof(*desc->bd_vec));
291         OBD_FREE_PTR(desc);
292         EXIT;
293 }
294 EXPORT_SYMBOL(ptlrpc_free_bulk);
295
296 /**
297  * Set server timelimit for this req, i.e. how long are we willing to wait
298  * for reply before timing out this request.
299  */
300 void ptlrpc_at_set_req_timeout(struct ptlrpc_request *req)
301 {
302         __u32 serv_est;
303         int idx;
304         struct imp_at *at;
305
306         LASSERT(req->rq_import);
307
308         if (AT_OFF) {
309                 /* non-AT settings */
310                 /**
311                  * \a imp_server_timeout means this is reverse import and
312                  * we send (currently only) ASTs to the client and cannot afford
313                  * to wait too long for the reply, otherwise the other client
314                  * (because of which we are sending this request) would
315                  * timeout waiting for us
316                  */
317                 req->rq_timeout = req->rq_import->imp_server_timeout ?
318                                   obd_timeout / 2 : obd_timeout;
319         } else {
320                 at = &req->rq_import->imp_at;
321                 idx = import_at_get_index(req->rq_import,
322                                           req->rq_request_portal);
323                 serv_est = at_get(&at->iat_service_estimate[idx]);
324                 req->rq_timeout = at_est2timeout(serv_est);
325         }
326         /*
327          * We could get even fancier here, using history to predict increased
328          * loading...
329          */
330
331         /*
332          * Let the server know what this RPC timeout is by putting it in the
333          * reqmsg
334          */
335         lustre_msg_set_timeout(req->rq_reqmsg, req->rq_timeout);
336 }
337 EXPORT_SYMBOL(ptlrpc_at_set_req_timeout);
338
339 /* Adjust max service estimate based on server value */
340 static void ptlrpc_at_adj_service(struct ptlrpc_request *req,
341                                   unsigned int serv_est)
342 {
343         int idx;
344         unsigned int oldse;
345         struct imp_at *at;
346
347         LASSERT(req->rq_import);
348         at = &req->rq_import->imp_at;
349
350         idx = import_at_get_index(req->rq_import, req->rq_request_portal);
351         /*
352          * max service estimates are tracked on the server side,
353          * so just keep minimal history here
354          */
355         oldse = at_measured(&at->iat_service_estimate[idx], serv_est);
356         if (oldse != 0)
357                 CDEBUG(D_ADAPTTO,
358                        "The RPC service estimate for %s ptl %d has changed from %d to %d\n",
359                        req->rq_import->imp_obd->obd_name,
360                        req->rq_request_portal,
361                        oldse, at_get(&at->iat_service_estimate[idx]));
362 }
363
364 /* Expected network latency per remote node (secs) */
365 int ptlrpc_at_get_net_latency(struct ptlrpc_request *req)
366 {
367         return AT_OFF ? 0 : at_get(&req->rq_import->imp_at.iat_net_latency);
368 }
369
370 /* Adjust expected network latency */
371 void ptlrpc_at_adj_net_latency(struct ptlrpc_request *req,
372                                timeout_t service_timeout)
373 {
374         unsigned int nl, oldnl;
375         struct imp_at *at;
376         time64_t now = ktime_get_real_seconds();
377
378         LASSERT(req->rq_import);
379
380         if (service_timeout > now - req->rq_sent + 3) {
381                 /*
382                  * b=16408, however, this can also happen if early reply
383                  * is lost and client RPC is expired and resent, early reply
384                  * or reply of original RPC can still be fit in reply buffer
385                  * of resent RPC, now client is measuring time from the
386                  * resent time, but server sent back service time of original
387                  * RPC.
388                  */
389                 CDEBUG((lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT) ?
390                        D_ADAPTTO : D_WARNING,
391                        "Reported service time %u > total measured time %lld\n",
392                        service_timeout, now - req->rq_sent);
393                 return;
394         }
395
396         /* Network latency is total time less server processing time */
397         nl = max_t(int, now - req->rq_sent -
398                         service_timeout, 0) + 1; /* st rounding */
399         at = &req->rq_import->imp_at;
400
401         oldnl = at_measured(&at->iat_net_latency, nl);
402         if (oldnl != 0)
403                 CDEBUG(D_ADAPTTO,
404                        "The network latency for %s (nid %s) has changed from %d to %d\n",
405                        req->rq_import->imp_obd->obd_name,
406                        obd_uuid2str(&req->rq_import->imp_connection->c_remote_uuid),
407                        oldnl, at_get(&at->iat_net_latency));
408 }
409
410 static int unpack_reply(struct ptlrpc_request *req)
411 {
412         int rc;
413
414         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
415                 rc = ptlrpc_unpack_rep_msg(req, req->rq_replen);
416                 if (rc) {
417                         DEBUG_REQ(D_ERROR, req, "unpack_rep failed: rc = %d",
418                                   rc);
419                         return -EPROTO;
420                 }
421         }
422
423         rc = lustre_unpack_rep_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
424         if (rc) {
425                 DEBUG_REQ(D_ERROR, req, "unpack ptlrpc body failed: rc = %d",
426                           rc);
427                 return -EPROTO;
428         }
429         return 0;
430 }
431
432 /**
433  * Handle an early reply message, called with the rq_lock held.
434  * If anything goes wrong just ignore it - same as if it never happened
435  */
436 static int ptlrpc_at_recv_early_reply(struct ptlrpc_request *req)
437 __must_hold(&req->rq_lock)
438 {
439         struct ptlrpc_request *early_req;
440         timeout_t service_timeout;
441         time64_t olddl;
442         int rc;
443
444         ENTRY;
445         req->rq_early = 0;
446         spin_unlock(&req->rq_lock);
447
448         rc = sptlrpc_cli_unwrap_early_reply(req, &early_req);
449         if (rc) {
450                 spin_lock(&req->rq_lock);
451                 RETURN(rc);
452         }
453
454         rc = unpack_reply(early_req);
455         if (rc != 0) {
456                 sptlrpc_cli_finish_early_reply(early_req);
457                 spin_lock(&req->rq_lock);
458                 RETURN(rc);
459         }
460
461         /*
462          * Use new timeout value just to adjust the local value for this
463          * request, don't include it into at_history. It is unclear yet why
464          * service time increased and should it be counted or skipped, e.g.
465          * that can be recovery case or some error or server, the real reply
466          * will add all new data if it is worth to add.
467          */
468         req->rq_timeout = lustre_msg_get_timeout(early_req->rq_repmsg);
469         lustre_msg_set_timeout(req->rq_reqmsg, req->rq_timeout);
470
471         /* Network latency can be adjusted, it is pure network delays */
472         service_timeout = lustre_msg_get_service_timeout(early_req->rq_repmsg);
473         ptlrpc_at_adj_net_latency(req, service_timeout);
474
475         sptlrpc_cli_finish_early_reply(early_req);
476
477         spin_lock(&req->rq_lock);
478         olddl = req->rq_deadline;
479         /*
480          * server assumes it now has rq_timeout from when the request
481          * arrived, so the client should give it at least that long.
482          * since we don't know the arrival time we'll use the original
483          * sent time
484          */
485         req->rq_deadline = req->rq_sent + req->rq_timeout +
486                            ptlrpc_at_get_net_latency(req);
487
488         /* The below message is checked in replay-single.sh test_65{a,b} */
489         /* The below message is checked in sanity-{gss,krb5} test_8 */
490         DEBUG_REQ(D_ADAPTTO, req,
491                   "Early reply #%d, new deadline in %llds (%llds)",
492                   req->rq_early_count,
493                   req->rq_deadline - ktime_get_real_seconds(),
494                   req->rq_deadline - olddl);
495
496         RETURN(rc);
497 }
498
499 static struct kmem_cache *request_cache;
500
501 int ptlrpc_request_cache_init(void)
502 {
503         request_cache = kmem_cache_create("ptlrpc_cache",
504                                           sizeof(struct ptlrpc_request),
505                                           0, SLAB_HWCACHE_ALIGN, NULL);
506         return request_cache ? 0 : -ENOMEM;
507 }
508
509 void ptlrpc_request_cache_fini(void)
510 {
511         kmem_cache_destroy(request_cache);
512 }
513
514 struct ptlrpc_request *ptlrpc_request_cache_alloc(gfp_t flags)
515 {
516         struct ptlrpc_request *req;
517
518         OBD_SLAB_ALLOC_PTR_GFP(req, request_cache, flags);
519         return req;
520 }
521
522 void ptlrpc_request_cache_free(struct ptlrpc_request *req)
523 {
524         OBD_SLAB_FREE_PTR(req, request_cache);
525 }
526
527 /**
528  * Wind down request pool \a pool.
529  * Frees all requests from the pool too
530  */
531 void ptlrpc_free_rq_pool(struct ptlrpc_request_pool *pool)
532 {
533         struct list_head *l, *tmp;
534         struct ptlrpc_request *req;
535
536         LASSERT(pool != NULL);
537
538         spin_lock(&pool->prp_lock);
539         list_for_each_safe(l, tmp, &pool->prp_req_list) {
540                 req = list_entry(l, struct ptlrpc_request, rq_list);
541                 list_del(&req->rq_list);
542                 LASSERT(req->rq_reqbuf);
543                 LASSERT(req->rq_reqbuf_len == pool->prp_rq_size);
544                 OBD_FREE_LARGE(req->rq_reqbuf, pool->prp_rq_size);
545                 ptlrpc_request_cache_free(req);
546         }
547         spin_unlock(&pool->prp_lock);
548         OBD_FREE(pool, sizeof(*pool));
549 }
550 EXPORT_SYMBOL(ptlrpc_free_rq_pool);
551
552 /**
553  * Allocates, initializes and adds \a num_rq requests to the pool \a pool
554  */
555 int ptlrpc_add_rqs_to_pool(struct ptlrpc_request_pool *pool, int num_rq)
556 {
557         int i;
558         int size = 1;
559
560         while (size < pool->prp_rq_size)
561                 size <<= 1;
562
563         LASSERTF(list_empty(&pool->prp_req_list) ||
564                  size == pool->prp_rq_size,
565                  "Trying to change pool size with nonempty pool from %d to %d bytes\n",
566                  pool->prp_rq_size, size);
567
568         pool->prp_rq_size = size;
569         for (i = 0; i < num_rq; i++) {
570                 struct ptlrpc_request *req;
571                 struct lustre_msg *msg;
572
573                 req = ptlrpc_request_cache_alloc(GFP_NOFS);
574                 if (!req)
575                         return i;
576                 OBD_ALLOC_LARGE(msg, size);
577                 if (!msg) {
578                         ptlrpc_request_cache_free(req);
579                         return i;
580                 }
581                 req->rq_reqbuf = msg;
582                 req->rq_reqbuf_len = size;
583                 req->rq_pool = pool;
584                 spin_lock(&pool->prp_lock);
585                 list_add_tail(&req->rq_list, &pool->prp_req_list);
586                 spin_unlock(&pool->prp_lock);
587         }
588         return num_rq;
589 }
590 EXPORT_SYMBOL(ptlrpc_add_rqs_to_pool);
591
592 /**
593  * Create and initialize new request pool with given attributes:
594  * \a num_rq - initial number of requests to create for the pool
595  * \a msgsize - maximum message size possible for requests in thid pool
596  * \a populate_pool - function to be called when more requests need to be added
597  *                    to the pool
598  * Returns pointer to newly created pool or NULL on error.
599  */
600 struct ptlrpc_request_pool *
601 ptlrpc_init_rq_pool(int num_rq, int msgsize,
602                     int (*populate_pool)(struct ptlrpc_request_pool *, int))
603 {
604         struct ptlrpc_request_pool *pool;
605
606         OBD_ALLOC_PTR(pool);
607         if (!pool)
608                 return NULL;
609
610         /*
611          * Request next power of two for the allocation, because internally
612          * kernel would do exactly this
613          */
614         spin_lock_init(&pool->prp_lock);
615         INIT_LIST_HEAD(&pool->prp_req_list);
616         pool->prp_rq_size = msgsize + SPTLRPC_MAX_PAYLOAD;
617         pool->prp_populate = populate_pool;
618
619         populate_pool(pool, num_rq);
620
621         return pool;
622 }
623 EXPORT_SYMBOL(ptlrpc_init_rq_pool);
624
625 /**
626  * Fetches one request from pool \a pool
627  */
628 static struct ptlrpc_request *
629 ptlrpc_prep_req_from_pool(struct ptlrpc_request_pool *pool)
630 {
631         struct ptlrpc_request *request;
632         struct lustre_msg *reqbuf;
633
634         if (!pool)
635                 return NULL;
636
637         spin_lock(&pool->prp_lock);
638
639         /*
640          * See if we have anything in a pool, and bail out if nothing,
641          * in writeout path, where this matters, this is safe to do, because
642          * nothing is lost in this case, and when some in-flight requests
643          * complete, this code will be called again.
644          */
645         if (unlikely(list_empty(&pool->prp_req_list))) {
646                 spin_unlock(&pool->prp_lock);
647                 return NULL;
648         }
649
650         request = list_entry(pool->prp_req_list.next, struct ptlrpc_request,
651                              rq_list);
652         list_del_init(&request->rq_list);
653         spin_unlock(&pool->prp_lock);
654
655         LASSERT(request->rq_reqbuf);
656         LASSERT(request->rq_pool);
657
658         reqbuf = request->rq_reqbuf;
659         memset(request, 0, sizeof(*request));
660         request->rq_reqbuf = reqbuf;
661         request->rq_reqbuf_len = pool->prp_rq_size;
662         request->rq_pool = pool;
663
664         return request;
665 }
666
667 /**
668  * Returns freed \a request to pool.
669  */
670 static void __ptlrpc_free_req_to_pool(struct ptlrpc_request *request)
671 {
672         struct ptlrpc_request_pool *pool = request->rq_pool;
673
674         spin_lock(&pool->prp_lock);
675         LASSERT(list_empty(&request->rq_list));
676         LASSERT(!request->rq_receiving_reply);
677         list_add_tail(&request->rq_list, &pool->prp_req_list);
678         spin_unlock(&pool->prp_lock);
679 }
680
681 void ptlrpc_add_unreplied(struct ptlrpc_request *req)
682 {
683         struct obd_import *imp = req->rq_import;
684         struct list_head *tmp;
685         struct ptlrpc_request *iter;
686
687         assert_spin_locked(&imp->imp_lock);
688         LASSERT(list_empty(&req->rq_unreplied_list));
689
690         /* unreplied list is sorted by xid in ascending order */
691         list_for_each_prev(tmp, &imp->imp_unreplied_list) {
692                 iter = list_entry(tmp, struct ptlrpc_request,
693                                   rq_unreplied_list);
694
695                 LASSERT(req->rq_xid != iter->rq_xid);
696                 if (req->rq_xid < iter->rq_xid)
697                         continue;
698                 list_add(&req->rq_unreplied_list, &iter->rq_unreplied_list);
699                 return;
700         }
701         list_add(&req->rq_unreplied_list, &imp->imp_unreplied_list);
702 }
703
704 void ptlrpc_assign_next_xid_nolock(struct ptlrpc_request *req)
705 {
706         req->rq_xid = ptlrpc_next_xid();
707         ptlrpc_add_unreplied(req);
708 }
709
710 static inline void ptlrpc_assign_next_xid(struct ptlrpc_request *req)
711 {
712         spin_lock(&req->rq_import->imp_lock);
713         ptlrpc_assign_next_xid_nolock(req);
714         spin_unlock(&req->rq_import->imp_lock);
715 }
716
717 static atomic64_t ptlrpc_last_xid;
718
719 static void ptlrpc_reassign_next_xid(struct ptlrpc_request *req)
720 {
721         spin_lock(&req->rq_import->imp_lock);
722         list_del_init(&req->rq_unreplied_list);
723         ptlrpc_assign_next_xid_nolock(req);
724         spin_unlock(&req->rq_import->imp_lock);
725         DEBUG_REQ(D_RPCTRACE, req, "reassign xid");
726 }
727
728 void ptlrpc_get_mod_rpc_slot(struct ptlrpc_request *req)
729 {
730         struct client_obd *cli = &req->rq_import->imp_obd->u.cli;
731         __u32 opc;
732         __u16 tag;
733
734         opc = lustre_msg_get_opc(req->rq_reqmsg);
735         tag = obd_get_mod_rpc_slot(cli, opc);
736         lustre_msg_set_tag(req->rq_reqmsg, tag);
737         ptlrpc_reassign_next_xid(req);
738 }
739 EXPORT_SYMBOL(ptlrpc_get_mod_rpc_slot);
740
741 void ptlrpc_put_mod_rpc_slot(struct ptlrpc_request *req)
742 {
743         __u16 tag = lustre_msg_get_tag(req->rq_reqmsg);
744
745         if (tag != 0) {
746                 struct client_obd *cli = &req->rq_import->imp_obd->u.cli;
747                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
748
749                 obd_put_mod_rpc_slot(cli, opc, tag);
750         }
751 }
752 EXPORT_SYMBOL(ptlrpc_put_mod_rpc_slot);
753
754 int ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
755                              __u32 version, int opcode, char **bufs,
756                              struct ptlrpc_cli_ctx *ctx)
757 {
758         int count;
759         struct obd_import *imp;
760         __u32 *lengths;
761         int rc;
762
763         ENTRY;
764
765         count = req_capsule_filled_sizes(&request->rq_pill, RCL_CLIENT);
766         imp = request->rq_import;
767         lengths = request->rq_pill.rc_area[RCL_CLIENT];
768
769         if (ctx) {
770                 request->rq_cli_ctx = sptlrpc_cli_ctx_get(ctx);
771         } else {
772                 rc = sptlrpc_req_get_ctx(request);
773                 if (rc)
774                         GOTO(out_free, rc);
775         }
776         sptlrpc_req_set_flavor(request, opcode);
777
778         rc = lustre_pack_request(request, imp->imp_msg_magic, count,
779                                  lengths, bufs);
780         if (rc)
781                 GOTO(out_ctx, rc);
782
783         lustre_msg_add_version(request->rq_reqmsg, version);
784         request->rq_send_state = LUSTRE_IMP_FULL;
785         request->rq_type = PTL_RPC_MSG_REQUEST;
786
787         request->rq_req_cbid.cbid_fn  = request_out_callback;
788         request->rq_req_cbid.cbid_arg = request;
789
790         request->rq_reply_cbid.cbid_fn  = reply_in_callback;
791         request->rq_reply_cbid.cbid_arg = request;
792
793         request->rq_reply_deadline = 0;
794         request->rq_bulk_deadline = 0;
795         request->rq_req_deadline = 0;
796         request->rq_phase = RQ_PHASE_NEW;
797         request->rq_next_phase = RQ_PHASE_UNDEFINED;
798
799         request->rq_request_portal = imp->imp_client->cli_request_portal;
800         request->rq_reply_portal = imp->imp_client->cli_reply_portal;
801
802         ptlrpc_at_set_req_timeout(request);
803
804         lustre_msg_set_opc(request->rq_reqmsg, opcode);
805
806         /* Let's setup deadline for req/reply/bulk unlink for opcode. */
807         if (cfs_fail_val == opcode) {
808                 time64_t *fail_t = NULL, *fail2_t = NULL;
809
810                 if (CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK)) {
811                         fail_t = &request->rq_bulk_deadline;
812                 } else if (CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
813                         fail_t = &request->rq_reply_deadline;
814                 } else if (CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REQ_UNLINK)) {
815                         fail_t = &request->rq_req_deadline;
816                 } else if (CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BOTH_UNLINK)) {
817                         fail_t = &request->rq_reply_deadline;
818                         fail2_t = &request->rq_bulk_deadline;
819                 } else if (CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_ROUND_XID)) {
820                         time64_t now = ktime_get_real_seconds();
821                         u64 xid = ((u64)now >> 4) << 24;
822
823                         atomic64_set(&ptlrpc_last_xid, xid);
824                 }
825
826                 if (fail_t) {
827                         *fail_t = ktime_get_real_seconds() + LONG_UNLINK;
828
829                         if (fail2_t)
830                                 *fail2_t = ktime_get_real_seconds() +
831                                            LONG_UNLINK;
832
833                         /*
834                          * The RPC is infected, let the test to change the
835                          * fail_loc
836                          */
837                         msleep(4 * MSEC_PER_SEC);
838                 }
839         }
840         ptlrpc_assign_next_xid(request);
841
842         RETURN(0);
843
844 out_ctx:
845         LASSERT(!request->rq_pool);
846         sptlrpc_cli_ctx_put(request->rq_cli_ctx, 1);
847 out_free:
848         class_import_put(imp);
849
850         return rc;
851 }
852 EXPORT_SYMBOL(ptlrpc_request_bufs_pack);
853
854 /**
855  * Pack request buffers for network transfer, performing necessary encryption
856  * steps if necessary.
857  */
858 int ptlrpc_request_pack(struct ptlrpc_request *request,
859                         __u32 version, int opcode)
860 {
861         return ptlrpc_request_bufs_pack(request, version, opcode, NULL, NULL);
862 }
863 EXPORT_SYMBOL(ptlrpc_request_pack);
864
865 /**
866  * Helper function to allocate new request on import \a imp
867  * and possibly using existing request from pool \a pool if provided.
868  * Returns allocated request structure with import field filled or
869  * NULL on error.
870  */
871 static inline
872 struct ptlrpc_request *__ptlrpc_request_alloc(struct obd_import *imp,
873                                               struct ptlrpc_request_pool *pool)
874 {
875         struct ptlrpc_request *request = NULL;
876
877         request = ptlrpc_request_cache_alloc(GFP_NOFS);
878
879         if (!request && pool)
880                 request = ptlrpc_prep_req_from_pool(pool);
881
882         if (request) {
883                 ptlrpc_cli_req_init(request);
884
885                 LASSERTF((unsigned long)imp > 0x1000, "%p", imp);
886                 LASSERT(imp != LP_POISON);
887                 LASSERTF((unsigned long)imp->imp_client > 0x1000, "%p\n",
888                          imp->imp_client);
889                 LASSERT(imp->imp_client != LP_POISON);
890
891                 request->rq_import = class_import_get(imp);
892         } else {
893                 CERROR("request allocation out of memory\n");
894         }
895
896         return request;
897 }
898
899 /**
900  * Helper function for creating a request.
901  * Calls __ptlrpc_request_alloc to allocate new request sturcture and inits
902  * buffer structures according to capsule template \a format.
903  * Returns allocated request structure pointer or NULL on error.
904  */
905 static struct ptlrpc_request *
906 ptlrpc_request_alloc_internal(struct obd_import *imp,
907                               struct ptlrpc_request_pool *pool,
908                               const struct req_format *format)
909 {
910         struct ptlrpc_request *request;
911
912         request = __ptlrpc_request_alloc(imp, pool);
913         if (!request)
914                 return NULL;
915
916         /*
917          * initiate connection if needed when the import has been
918          * referenced by the new request to avoid races with disconnect
919          */
920         if (unlikely(imp->imp_state == LUSTRE_IMP_IDLE)) {
921                 int rc;
922
923                 CDEBUG_LIMIT(imp->imp_idle_debug,
924                              "%s: reconnect after %llds idle\n",
925                              imp->imp_obd->obd_name, ktime_get_real_seconds() -
926                                                      imp->imp_last_reply_time);
927                 spin_lock(&imp->imp_lock);
928                 if (imp->imp_state == LUSTRE_IMP_IDLE) {
929                         imp->imp_generation++;
930                         imp->imp_initiated_at = imp->imp_generation;
931                         imp->imp_state = LUSTRE_IMP_NEW;
932
933                         /* connect_import_locked releases imp_lock */
934                         rc = ptlrpc_connect_import_locked(imp);
935                         if (rc < 0) {
936                                 ptlrpc_request_free(request);
937                                 return NULL;
938                         }
939                         ptlrpc_pinger_add_import(imp);
940                 } else {
941                         spin_unlock(&imp->imp_lock);
942                 }
943         }
944
945         req_capsule_init(&request->rq_pill, request, RCL_CLIENT);
946         req_capsule_set(&request->rq_pill, format);
947         return request;
948 }
949
950 /**
951  * Allocate new request structure for import \a imp and initialize its
952  * buffer structure according to capsule template \a format.
953  */
954 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
955                                             const struct req_format *format)
956 {
957         return ptlrpc_request_alloc_internal(imp, NULL, format);
958 }
959 EXPORT_SYMBOL(ptlrpc_request_alloc);
960
961 /**
962  * Allocate new request structure for import \a imp from pool \a pool and
963  * initialize its buffer structure according to capsule template \a format.
964  */
965 struct ptlrpc_request *
966 ptlrpc_request_alloc_pool(struct obd_import *imp,
967                           struct ptlrpc_request_pool *pool,
968                           const struct req_format *format)
969 {
970         return ptlrpc_request_alloc_internal(imp, pool, format);
971 }
972 EXPORT_SYMBOL(ptlrpc_request_alloc_pool);
973
974 /**
975  * For requests not from pool, free memory of the request structure.
976  * For requests obtained from a pool earlier, return request back to pool.
977  */
978 void ptlrpc_request_free(struct ptlrpc_request *request)
979 {
980         if (request->rq_pool)
981                 __ptlrpc_free_req_to_pool(request);
982         else
983                 ptlrpc_request_cache_free(request);
984 }
985 EXPORT_SYMBOL(ptlrpc_request_free);
986
987 /**
988  * Allocate new request for operatione \a opcode and immediatelly pack it for
989  * network transfer.
990  * Only used for simple requests like OBD_PING where the only important
991  * part of the request is operation itself.
992  * Returns allocated request or NULL on error.
993  */
994 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *imp,
995                                                  const struct req_format *format,
996                                                  __u32 version, int opcode)
997 {
998         struct ptlrpc_request *req = ptlrpc_request_alloc(imp, format);
999         int rc;
1000
1001         if (req) {
1002                 rc = ptlrpc_request_pack(req, version, opcode);
1003                 if (rc) {
1004                         ptlrpc_request_free(req);
1005                         req = NULL;
1006                 }
1007         }
1008         return req;
1009 }
1010 EXPORT_SYMBOL(ptlrpc_request_alloc_pack);
1011
1012 /**
1013  * Allocate and initialize new request set structure on the current CPT.
1014  * Returns a pointer to the newly allocated set structure or NULL on error.
1015  */
1016 struct ptlrpc_request_set *ptlrpc_prep_set(void)
1017 {
1018         struct ptlrpc_request_set *set;
1019         int cpt;
1020
1021         ENTRY;
1022         cpt = cfs_cpt_current(cfs_cpt_tab, 0);
1023         OBD_CPT_ALLOC(set, cfs_cpt_tab, cpt, sizeof(*set));
1024         if (!set)
1025                 RETURN(NULL);
1026         atomic_set(&set->set_refcount, 1);
1027         INIT_LIST_HEAD(&set->set_requests);
1028         init_waitqueue_head(&set->set_waitq);
1029         atomic_set(&set->set_new_count, 0);
1030         atomic_set(&set->set_remaining, 0);
1031         spin_lock_init(&set->set_new_req_lock);
1032         INIT_LIST_HEAD(&set->set_new_requests);
1033         set->set_max_inflight = UINT_MAX;
1034         set->set_producer     = NULL;
1035         set->set_producer_arg = NULL;
1036         set->set_rc           = 0;
1037
1038         RETURN(set);
1039 }
1040 EXPORT_SYMBOL(ptlrpc_prep_set);
1041
1042 /**
1043  * Allocate and initialize new request set structure with flow control
1044  * extension. This extension allows to control the number of requests in-flight
1045  * for the whole set. A callback function to generate requests must be provided
1046  * and the request set will keep the number of requests sent over the wire to
1047  * @max_inflight.
1048  * Returns a pointer to the newly allocated set structure or NULL on error.
1049  */
1050 struct ptlrpc_request_set *ptlrpc_prep_fcset(int max, set_producer_func func,
1051                                              void *arg)
1052
1053 {
1054         struct ptlrpc_request_set *set;
1055
1056         set = ptlrpc_prep_set();
1057         if (!set)
1058                 RETURN(NULL);
1059
1060         set->set_max_inflight  = max;
1061         set->set_producer      = func;
1062         set->set_producer_arg  = arg;
1063
1064         RETURN(set);
1065 }
1066
1067 /**
1068  * Wind down and free request set structure previously allocated with
1069  * ptlrpc_prep_set.
1070  * Ensures that all requests on the set have completed and removes
1071  * all requests from the request list in a set.
1072  * If any unsent request happen to be on the list, pretends that they got
1073  * an error in flight and calls their completion handler.
1074  */
1075 void ptlrpc_set_destroy(struct ptlrpc_request_set *set)
1076 {
1077         struct list_head *tmp;
1078         struct list_head *next;
1079         int expected_phase;
1080         int n = 0;
1081
1082         ENTRY;
1083
1084         /* Requests on the set should either all be completed, or all be new */
1085         expected_phase = (atomic_read(&set->set_remaining) == 0) ?
1086                          RQ_PHASE_COMPLETE : RQ_PHASE_NEW;
1087         list_for_each(tmp, &set->set_requests) {
1088                 struct ptlrpc_request *req =
1089                         list_entry(tmp, struct ptlrpc_request,
1090                                    rq_set_chain);
1091
1092                 LASSERT(req->rq_phase == expected_phase);
1093                 n++;
1094         }
1095
1096         LASSERTF(atomic_read(&set->set_remaining) == 0 ||
1097                  atomic_read(&set->set_remaining) == n, "%d / %d\n",
1098                  atomic_read(&set->set_remaining), n);
1099
1100         list_for_each_safe(tmp, next, &set->set_requests) {
1101                 struct ptlrpc_request *req =
1102                         list_entry(tmp, struct ptlrpc_request,
1103                                    rq_set_chain);
1104                 list_del_init(&req->rq_set_chain);
1105
1106                 LASSERT(req->rq_phase == expected_phase);
1107
1108                 if (req->rq_phase == RQ_PHASE_NEW) {
1109                         ptlrpc_req_interpret(NULL, req, -EBADR);
1110                         atomic_dec(&set->set_remaining);
1111                 }
1112
1113                 spin_lock(&req->rq_lock);
1114                 req->rq_set = NULL;
1115                 req->rq_invalid_rqset = 0;
1116                 spin_unlock(&req->rq_lock);
1117
1118                 ptlrpc_req_finished(req);
1119         }
1120
1121         LASSERT(atomic_read(&set->set_remaining) == 0);
1122
1123         ptlrpc_reqset_put(set);
1124         EXIT;
1125 }
1126 EXPORT_SYMBOL(ptlrpc_set_destroy);
1127
1128 /**
1129  * Add a new request to the general purpose request set.
1130  * Assumes request reference from the caller.
1131  */
1132 void ptlrpc_set_add_req(struct ptlrpc_request_set *set,
1133                         struct ptlrpc_request *req)
1134 {
1135         if (set == PTLRPCD_SET) {
1136                 ptlrpcd_add_req(req);
1137                 return;
1138         }
1139
1140         LASSERT(req->rq_import->imp_state != LUSTRE_IMP_IDLE);
1141         LASSERT(list_empty(&req->rq_set_chain));
1142
1143         if (req->rq_allow_intr)
1144                 set->set_allow_intr = 1;
1145
1146         /* The set takes over the caller's request reference */
1147         list_add_tail(&req->rq_set_chain, &set->set_requests);
1148         req->rq_set = set;
1149         atomic_inc(&set->set_remaining);
1150         req->rq_queued_time = ktime_get_seconds();
1151
1152         if (req->rq_reqmsg)
1153                 lustre_msg_set_jobid(req->rq_reqmsg, NULL);
1154
1155         if (set->set_producer)
1156                 /*
1157                  * If the request set has a producer callback, the RPC must be
1158                  * sent straight away
1159                  */
1160                 ptlrpc_send_new_req(req);
1161 }
1162 EXPORT_SYMBOL(ptlrpc_set_add_req);
1163
1164 /**
1165  * Add a request to a request with dedicated server thread
1166  * and wake the thread to make any necessary processing.
1167  * Currently only used for ptlrpcd.
1168  */
1169 void ptlrpc_set_add_new_req(struct ptlrpcd_ctl *pc,
1170                             struct ptlrpc_request *req)
1171 {
1172         struct ptlrpc_request_set *set = pc->pc_set;
1173         int count, i;
1174
1175         LASSERT(req->rq_set == NULL);
1176         LASSERT(test_bit(LIOD_STOP, &pc->pc_flags) == 0);
1177
1178         spin_lock(&set->set_new_req_lock);
1179         /*
1180          * The set takes over the caller's request reference.
1181          */
1182         req->rq_set = set;
1183         req->rq_queued_time = ktime_get_seconds();
1184         list_add_tail(&req->rq_set_chain, &set->set_new_requests);
1185         count = atomic_inc_return(&set->set_new_count);
1186         spin_unlock(&set->set_new_req_lock);
1187
1188         /* Only need to call wakeup once for the first entry. */
1189         if (count == 1) {
1190                 wake_up(&set->set_waitq);
1191
1192                 /*
1193                  * XXX: It maybe unnecessary to wakeup all the partners. But to
1194                  *      guarantee the async RPC can be processed ASAP, we have
1195                  *      no other better choice. It maybe fixed in future.
1196                  */
1197                 for (i = 0; i < pc->pc_npartners; i++)
1198                         wake_up(&pc->pc_partners[i]->pc_set->set_waitq);
1199         }
1200 }
1201
1202 /**
1203  * Based on the current state of the import, determine if the request
1204  * can be sent, is an error, or should be delayed.
1205  *
1206  * Returns true if this request should be delayed. If false, and
1207  * *status is set, then the request can not be sent and *status is the
1208  * error code.  If false and status is 0, then request can be sent.
1209  *
1210  * The imp->imp_lock must be held.
1211  */
1212 static int ptlrpc_import_delay_req(struct obd_import *imp,
1213                                    struct ptlrpc_request *req, int *status)
1214 {
1215         int delay = 0;
1216
1217         ENTRY;
1218         LASSERT(status);
1219         *status = 0;
1220
1221         if (req->rq_ctx_init || req->rq_ctx_fini) {
1222                 /* always allow ctx init/fini rpc go through */
1223         } else if (imp->imp_state == LUSTRE_IMP_NEW) {
1224                 DEBUG_REQ(D_ERROR, req, "Uninitialized import");
1225                 *status = -EIO;
1226         } else if (imp->imp_state == LUSTRE_IMP_CLOSED) {
1227                 unsigned int opc = lustre_msg_get_opc(req->rq_reqmsg);
1228
1229                 /*
1230                  * pings or MDS-equivalent STATFS may safely
1231                  * race with umount
1232                  */
1233                 DEBUG_REQ((opc == OBD_PING || opc == OST_STATFS) ?
1234                           D_HA : D_ERROR, req, "IMP_CLOSED");
1235                 *status = -EIO;
1236         } else if (ptlrpc_send_limit_expired(req)) {
1237                 /* probably doesn't need to be a D_ERROR afterinitial testing */
1238                 DEBUG_REQ(D_HA, req, "send limit expired");
1239                 *status = -ETIMEDOUT;
1240         } else if (req->rq_send_state == LUSTRE_IMP_CONNECTING &&
1241                    imp->imp_state == LUSTRE_IMP_CONNECTING) {
1242                 ;/* allow CONNECT even if import is invalid */
1243                 if (atomic_read(&imp->imp_inval_count) != 0) {
1244                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
1245                         *status = -EIO;
1246                 }
1247         } else if (imp->imp_invalid || imp->imp_obd->obd_no_recov) {
1248                 if (!imp->imp_deactive)
1249                         DEBUG_REQ(D_NET, req, "IMP_INVALID");
1250                 *status = -ESHUTDOWN; /* b=12940 */
1251         } else if (req->rq_import_generation != imp->imp_generation) {
1252                 DEBUG_REQ(D_ERROR, req, "req wrong generation:");
1253                 *status = -EIO;
1254         } else if (req->rq_send_state != imp->imp_state) {
1255                 /* invalidate in progress - any requests should be drop */
1256                 if (atomic_read(&imp->imp_inval_count) != 0) {
1257                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
1258                         *status = -EIO;
1259                 } else if (req->rq_no_delay &&
1260                            imp->imp_generation != imp->imp_initiated_at) {
1261                         /* ignore nodelay for requests initiating connections */
1262                         *status = -EWOULDBLOCK;
1263                 } else if (req->rq_allow_replay &&
1264                            (imp->imp_state == LUSTRE_IMP_REPLAY ||
1265                             imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS ||
1266                             imp->imp_state == LUSTRE_IMP_REPLAY_WAIT ||
1267                             imp->imp_state == LUSTRE_IMP_RECOVER)) {
1268                         DEBUG_REQ(D_HA, req, "allow during recovery");
1269                 } else {
1270                         delay = 1;
1271                 }
1272         }
1273
1274         RETURN(delay);
1275 }
1276
1277 /**
1278  * Decide if the error message should be printed to the console or not.
1279  * Makes its decision based on request type, status, and failure frequency.
1280  *
1281  * \param[in] req  request that failed and may need a console message
1282  *
1283  * \retval false if no message should be printed
1284  * \retval true  if console message should be printed
1285  */
1286 static bool ptlrpc_console_allow(struct ptlrpc_request *req, __u32 opc, int err)
1287 {
1288         LASSERT(req->rq_reqmsg != NULL);
1289
1290         /* Suppress particular reconnect errors which are to be expected. */
1291         if (opc == OST_CONNECT || opc == MDS_CONNECT || opc == MGS_CONNECT) {
1292                 /* Suppress timed out reconnect requests */
1293                 if (lustre_handle_is_used(&req->rq_import->imp_remote_handle) ||
1294                     req->rq_timedout)
1295                         return false;
1296
1297                 /*
1298                  * Suppress most unavailable/again reconnect requests, but
1299                  * print occasionally so it is clear client is trying to
1300                  * connect to a server where no target is running.
1301                  */
1302                 if ((err == -ENODEV || err == -EAGAIN) &&
1303                     req->rq_import->imp_conn_cnt % 30 != 20)
1304                         return false;
1305         }
1306
1307         if (opc == LDLM_ENQUEUE && err == -EAGAIN)
1308                 /* -EAGAIN is normal when using POSIX flocks */
1309                 return false;
1310
1311         if (opc == OBD_PING && (err == -ENODEV || err == -ENOTCONN) &&
1312             (req->rq_xid & 0xf) != 10)
1313                 /* Suppress most ping requests, they may fail occasionally */
1314                 return false;
1315
1316         return true;
1317 }
1318
1319 /**
1320  * Check request processing status.
1321  * Returns the status.
1322  */
1323 static int ptlrpc_check_status(struct ptlrpc_request *req)
1324 {
1325         int rc;
1326
1327         ENTRY;
1328         rc = lustre_msg_get_status(req->rq_repmsg);
1329         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
1330                 struct obd_import *imp = req->rq_import;
1331                 lnet_nid_t nid = imp->imp_connection->c_peer.nid;
1332                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1333
1334                 if (ptlrpc_console_allow(req, opc, rc))
1335                         LCONSOLE_ERROR_MSG(0x11,
1336                                            "%s: operation %s to node %s failed: rc = %d\n",
1337                                            imp->imp_obd->obd_name,
1338                                            ll_opcode2str(opc),
1339                                            libcfs_nid2str(nid), rc);
1340                 RETURN(rc < 0 ? rc : -EINVAL);
1341         }
1342
1343         if (rc)
1344                 DEBUG_REQ(D_INFO, req, "check status: rc = %d", rc);
1345
1346         RETURN(rc);
1347 }
1348
1349 /**
1350  * save pre-versions of objects into request for replay.
1351  * Versions are obtained from server reply.
1352  * used for VBR.
1353  */
1354 static void ptlrpc_save_versions(struct ptlrpc_request *req)
1355 {
1356         struct lustre_msg *repmsg = req->rq_repmsg;
1357         struct lustre_msg *reqmsg = req->rq_reqmsg;
1358         __u64 *versions = lustre_msg_get_versions(repmsg);
1359
1360         ENTRY;
1361         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1362                 return;
1363
1364         LASSERT(versions);
1365         lustre_msg_set_versions(reqmsg, versions);
1366         CDEBUG(D_INFO, "Client save versions [%#llx/%#llx]\n",
1367                versions[0], versions[1]);
1368
1369         EXIT;
1370 }
1371
1372 __u64 ptlrpc_known_replied_xid(struct obd_import *imp)
1373 {
1374         struct ptlrpc_request *req;
1375
1376         assert_spin_locked(&imp->imp_lock);
1377         if (list_empty(&imp->imp_unreplied_list))
1378                 return 0;
1379
1380         req = list_entry(imp->imp_unreplied_list.next, struct ptlrpc_request,
1381                          rq_unreplied_list);
1382         LASSERTF(req->rq_xid >= 1, "XID:%llu\n", req->rq_xid);
1383
1384         if (imp->imp_known_replied_xid < req->rq_xid - 1)
1385                 imp->imp_known_replied_xid = req->rq_xid - 1;
1386
1387         return req->rq_xid - 1;
1388 }
1389
1390 /**
1391  * Callback function called when client receives RPC reply for \a req.
1392  * Returns 0 on success or error code.
1393  * The return alue would be assigned to req->rq_status by the caller
1394  * as request processing status.
1395  * This function also decides if the request needs to be saved for later replay.
1396  */
1397 static int after_reply(struct ptlrpc_request *req)
1398 {
1399         struct obd_import *imp = req->rq_import;
1400         struct obd_device *obd = req->rq_import->imp_obd;
1401         ktime_t work_start;
1402         u64 committed;
1403         s64 timediff;
1404         int rc;
1405
1406         ENTRY;
1407         LASSERT(obd != NULL);
1408         /* repbuf must be unlinked */
1409         LASSERT(!req->rq_receiving_reply && req->rq_reply_unlinked);
1410
1411         if (req->rq_reply_truncated) {
1412                 if (ptlrpc_no_resend(req)) {
1413                         DEBUG_REQ(D_ERROR, req,
1414                                   "reply buffer overflow, expected=%d, actual size=%d",
1415                                   req->rq_nob_received, req->rq_repbuf_len);
1416                         RETURN(-EOVERFLOW);
1417                 }
1418
1419                 sptlrpc_cli_free_repbuf(req);
1420                 /*
1421                  * Pass the required reply buffer size (include
1422                  * space for early reply).
1423                  * NB: no need to roundup because alloc_repbuf
1424                  * will roundup it
1425                  */
1426                 req->rq_replen = req->rq_nob_received;
1427                 req->rq_nob_received = 0;
1428                 spin_lock(&req->rq_lock);
1429                 req->rq_resend       = 1;
1430                 spin_unlock(&req->rq_lock);
1431                 RETURN(0);
1432         }
1433
1434         work_start = ktime_get_real();
1435         timediff = ktime_us_delta(work_start, req->rq_sent_ns);
1436
1437         /*
1438          * NB Until this point, the whole of the incoming message,
1439          * including buflens, status etc is in the sender's byte order.
1440          */
1441         rc = sptlrpc_cli_unwrap_reply(req);
1442         if (rc) {
1443                 DEBUG_REQ(D_ERROR, req, "unwrap reply failed: rc = %d", rc);
1444                 RETURN(rc);
1445         }
1446
1447         /*
1448          * Security layer unwrap might ask resend this request.
1449          */
1450         if (req->rq_resend)
1451                 RETURN(0);
1452
1453         rc = unpack_reply(req);
1454         if (rc)
1455                 RETURN(rc);
1456
1457         /* retry indefinitely on EINPROGRESS */
1458         if (lustre_msg_get_status(req->rq_repmsg) == -EINPROGRESS &&
1459             ptlrpc_no_resend(req) == 0 && !req->rq_no_retry_einprogress) {
1460                 time64_t now = ktime_get_real_seconds();
1461
1462                 DEBUG_REQ((req->rq_nr_resend % 8 == 1 ? D_WARNING : 0) |
1463                           D_RPCTRACE, req, "resending request on EINPROGRESS");
1464                 spin_lock(&req->rq_lock);
1465                 req->rq_resend = 1;
1466                 spin_unlock(&req->rq_lock);
1467                 req->rq_nr_resend++;
1468
1469                 /* Readjust the timeout for current conditions */
1470                 ptlrpc_at_set_req_timeout(req);
1471                 /*
1472                  * delay resend to give a chance to the server to get ready.
1473                  * The delay is increased by 1s on every resend and is capped to
1474                  * the current request timeout (i.e. obd_timeout if AT is off,
1475                  * or AT service time x 125% + 5s, see at_est2timeout)
1476                  */
1477                 if (req->rq_nr_resend > req->rq_timeout)
1478                         req->rq_sent = now + req->rq_timeout;
1479                 else
1480                         req->rq_sent = now + req->rq_nr_resend;
1481
1482                 /* Resend for EINPROGRESS will use a new XID */
1483                 spin_lock(&imp->imp_lock);
1484                 list_del_init(&req->rq_unreplied_list);
1485                 spin_unlock(&imp->imp_lock);
1486
1487                 RETURN(0);
1488         }
1489
1490         if (obd->obd_svc_stats) {
1491                 lprocfs_counter_add(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR,
1492                                     timediff);
1493                 ptlrpc_lprocfs_rpc_sent(req, timediff);
1494         }
1495
1496         if (lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_REPLY &&
1497             lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_ERR) {
1498                 DEBUG_REQ(D_ERROR, req, "invalid packet received (type=%u)",
1499                           lustre_msg_get_type(req->rq_repmsg));
1500                 RETURN(-EPROTO);
1501         }
1502
1503         if (lustre_msg_get_opc(req->rq_reqmsg) != OBD_PING)
1504                 CFS_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_PAUSE_REP, cfs_fail_val);
1505         ptlrpc_at_adj_service(req, lustre_msg_get_timeout(req->rq_repmsg));
1506         ptlrpc_at_adj_net_latency(req,
1507                                   lustre_msg_get_service_timeout(req->rq_repmsg));
1508
1509         rc = ptlrpc_check_status(req);
1510
1511         if (rc) {
1512                 /*
1513                  * Either we've been evicted, or the server has failed for
1514                  * some reason. Try to reconnect, and if that fails, punt to
1515                  * the upcall.
1516                  */
1517                 if (ptlrpc_recoverable_error(rc)) {
1518                         if (req->rq_send_state != LUSTRE_IMP_FULL ||
1519                             imp->imp_obd->obd_no_recov || imp->imp_dlm_fake) {
1520                                 RETURN(rc);
1521                         }
1522                         ptlrpc_request_handle_notconn(req);
1523                         RETURN(rc);
1524                 }
1525         } else {
1526                 /*
1527                  * Let's look if server sent slv. Do it only for RPC with
1528                  * rc == 0.
1529                  */
1530                 ldlm_cli_update_pool(req);
1531         }
1532
1533         /*
1534          * Store transno in reqmsg for replay.
1535          */
1536         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
1537                 req->rq_transno = lustre_msg_get_transno(req->rq_repmsg);
1538                 lustre_msg_set_transno(req->rq_reqmsg, req->rq_transno);
1539         }
1540
1541         if (imp->imp_replayable) {
1542                 spin_lock(&imp->imp_lock);
1543                 /*
1544                  * No point in adding already-committed requests to the replay
1545                  * list, we will just remove them immediately. b=9829
1546                  */
1547                 if (req->rq_transno != 0 &&
1548                     (req->rq_transno >
1549                      lustre_msg_get_last_committed(req->rq_repmsg) ||
1550                      req->rq_replay)) {
1551                         /** version recovery */
1552                         ptlrpc_save_versions(req);
1553                         ptlrpc_retain_replayable_request(req, imp);
1554                 } else if (req->rq_commit_cb &&
1555                            list_empty(&req->rq_replay_list)) {
1556                         /*
1557                          * NB: don't call rq_commit_cb if it's already on
1558                          * rq_replay_list, ptlrpc_free_committed() will call
1559                          * it later, see LU-3618 for details
1560                          */
1561                         spin_unlock(&imp->imp_lock);
1562                         req->rq_commit_cb(req);
1563                         spin_lock(&imp->imp_lock);
1564                 }
1565
1566                 /*
1567                  * Replay-enabled imports return commit-status information.
1568                  */
1569                 committed = lustre_msg_get_last_committed(req->rq_repmsg);
1570                 if (likely(committed > imp->imp_peer_committed_transno))
1571                         imp->imp_peer_committed_transno = committed;
1572
1573                 ptlrpc_free_committed(imp);
1574
1575                 if (!list_empty(&imp->imp_replay_list)) {
1576                         struct ptlrpc_request *last;
1577
1578                         last = list_entry(imp->imp_replay_list.prev,
1579                                           struct ptlrpc_request,
1580                                           rq_replay_list);
1581                         /*
1582                          * Requests with rq_replay stay on the list even if no
1583                          * commit is expected.
1584                          */
1585                         if (last->rq_transno > imp->imp_peer_committed_transno)
1586                                 ptlrpc_pinger_commit_expected(imp);
1587                 }
1588
1589                 spin_unlock(&imp->imp_lock);
1590         }
1591
1592         RETURN(rc);
1593 }
1594
1595 /**
1596  * Helper function to send request \a req over the network for the first time
1597  * Also adjusts request phase.
1598  * Returns 0 on success or error code.
1599  */
1600 static int ptlrpc_send_new_req(struct ptlrpc_request *req)
1601 {
1602         struct obd_import *imp = req->rq_import;
1603         __u64 min_xid = 0;
1604         int rc;
1605
1606         ENTRY;
1607         LASSERT(req->rq_phase == RQ_PHASE_NEW);
1608
1609         /* do not try to go further if there is not enough memory in enc_pool */
1610         if (req->rq_sent && req->rq_bulk)
1611                 if (req->rq_bulk->bd_iov_count > get_free_pages_in_pool() &&
1612                     pool_is_at_full_capacity())
1613                         RETURN(-ENOMEM);
1614
1615         if (req->rq_sent && (req->rq_sent > ktime_get_real_seconds()) &&
1616             (!req->rq_generation_set ||
1617              req->rq_import_generation == imp->imp_generation))
1618                 RETURN(0);
1619
1620         ptlrpc_rqphase_move(req, RQ_PHASE_RPC);
1621
1622         spin_lock(&imp->imp_lock);
1623
1624         LASSERT(req->rq_xid != 0);
1625         LASSERT(!list_empty(&req->rq_unreplied_list));
1626
1627         if (!req->rq_generation_set)
1628                 req->rq_import_generation = imp->imp_generation;
1629
1630         if (ptlrpc_import_delay_req(imp, req, &rc)) {
1631                 spin_lock(&req->rq_lock);
1632                 req->rq_waiting = 1;
1633                 spin_unlock(&req->rq_lock);
1634
1635                 DEBUG_REQ(D_HA, req, "req waiting for recovery: (%s != %s)",
1636                           ptlrpc_import_state_name(req->rq_send_state),
1637                           ptlrpc_import_state_name(imp->imp_state));
1638                 LASSERT(list_empty(&req->rq_list));
1639                 list_add_tail(&req->rq_list, &imp->imp_delayed_list);
1640                 atomic_inc(&req->rq_import->imp_inflight);
1641                 spin_unlock(&imp->imp_lock);
1642                 RETURN(0);
1643         }
1644
1645         if (rc != 0) {
1646                 spin_unlock(&imp->imp_lock);
1647                 req->rq_status = rc;
1648                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1649                 RETURN(rc);
1650         }
1651
1652         LASSERT(list_empty(&req->rq_list));
1653         list_add_tail(&req->rq_list, &imp->imp_sending_list);
1654         atomic_inc(&req->rq_import->imp_inflight);
1655
1656         /*
1657          * find the known replied XID from the unreplied list, CONNECT
1658          * and DISCONNECT requests are skipped to make the sanity check
1659          * on server side happy. see process_req_last_xid().
1660          *
1661          * For CONNECT: Because replay requests have lower XID, it'll
1662          * break the sanity check if CONNECT bump the exp_last_xid on
1663          * server.
1664          *
1665          * For DISCONNECT: Since client will abort inflight RPC before
1666          * sending DISCONNECT, DISCONNECT may carry an XID which higher
1667          * than the inflight RPC.
1668          */
1669         if (!ptlrpc_req_is_connect(req) && !ptlrpc_req_is_disconnect(req))
1670                 min_xid = ptlrpc_known_replied_xid(imp);
1671         spin_unlock(&imp->imp_lock);
1672
1673         lustre_msg_set_last_xid(req->rq_reqmsg, min_xid);
1674
1675         lustre_msg_set_status(req->rq_reqmsg, current->pid);
1676
1677         rc = sptlrpc_req_refresh_ctx(req, 0);
1678         if (rc) {
1679                 if (req->rq_err) {
1680                         req->rq_status = rc;
1681                         RETURN(1);
1682                 } else {
1683                         spin_lock(&req->rq_lock);
1684                         req->rq_wait_ctx = 1;
1685                         spin_unlock(&req->rq_lock);
1686                         RETURN(0);
1687                 }
1688         }
1689
1690         CDEBUG(D_RPCTRACE,
1691                "Sending RPC req@%p pname:cluuid:pid:xid:nid:opc:job %s:%s:%d:%llu:%s:%d:%s\n",
1692                req, current->comm,
1693                imp->imp_obd->obd_uuid.uuid,
1694                lustre_msg_get_status(req->rq_reqmsg), req->rq_xid,
1695                obd_import_nid2str(imp), lustre_msg_get_opc(req->rq_reqmsg),
1696                lustre_msg_get_jobid(req->rq_reqmsg) ?: "");
1697
1698         rc = ptl_send_rpc(req, 0);
1699         if (rc == -ENOMEM) {
1700                 spin_lock(&imp->imp_lock);
1701                 if (!list_empty(&req->rq_list)) {
1702                         list_del_init(&req->rq_list);
1703                         if (atomic_dec_and_test(&req->rq_import->imp_inflight))
1704                                 wake_up(&req->rq_import->imp_recovery_waitq);
1705                 }
1706                 spin_unlock(&imp->imp_lock);
1707                 ptlrpc_rqphase_move(req, RQ_PHASE_NEW);
1708                 RETURN(rc);
1709         }
1710         if (rc) {
1711                 DEBUG_REQ(D_HA, req, "send failed, expect timeout: rc = %d",
1712                           rc);
1713                 spin_lock(&req->rq_lock);
1714                 req->rq_net_err = 1;
1715                 spin_unlock(&req->rq_lock);
1716                 RETURN(rc);
1717         }
1718         RETURN(0);
1719 }
1720
1721 static inline int ptlrpc_set_producer(struct ptlrpc_request_set *set)
1722 {
1723         int remaining, rc;
1724
1725         ENTRY;
1726         LASSERT(set->set_producer != NULL);
1727
1728         remaining = atomic_read(&set->set_remaining);
1729
1730         /*
1731          * populate the ->set_requests list with requests until we
1732          * reach the maximum number of RPCs in flight for this set
1733          */
1734         while (atomic_read(&set->set_remaining) < set->set_max_inflight) {
1735                 rc = set->set_producer(set, set->set_producer_arg);
1736                 if (rc == -ENOENT) {
1737                         /* no more RPC to produce */
1738                         set->set_producer     = NULL;
1739                         set->set_producer_arg = NULL;
1740                         RETURN(0);
1741                 }
1742         }
1743
1744         RETURN((atomic_read(&set->set_remaining) - remaining));
1745 }
1746
1747 /**
1748  * this sends any unsent RPCs in \a set and returns 1 if all are sent
1749  * and no more replies are expected.
1750  * (it is possible to get less replies than requests sent e.g. due to timed out
1751  * requests or requests that we had trouble to send out)
1752  *
1753  * NOTE: This function contains a potential schedule point (cond_resched()).
1754  */
1755 int ptlrpc_check_set(const struct lu_env *env, struct ptlrpc_request_set *set)
1756 {
1757         struct list_head *tmp, *next;
1758         LIST_HEAD(comp_reqs);
1759         int force_timer_recalc = 0;
1760
1761         ENTRY;
1762         if (atomic_read(&set->set_remaining) == 0)
1763                 RETURN(1);
1764
1765         list_for_each_safe(tmp, next, &set->set_requests) {
1766                 struct ptlrpc_request *req =
1767                         list_entry(tmp, struct ptlrpc_request,
1768                                    rq_set_chain);
1769                 struct obd_import *imp = req->rq_import;
1770                 int unregistered = 0;
1771                 int async = 1;
1772                 int rc = 0;
1773
1774                 if (req->rq_phase == RQ_PHASE_COMPLETE) {
1775                         list_move_tail(&req->rq_set_chain, &comp_reqs);
1776                         continue;
1777                 }
1778
1779                 /*
1780                  * This schedule point is mainly for the ptlrpcd caller of this
1781                  * function.  Most ptlrpc sets are not long-lived and unbounded
1782                  * in length, but at the least the set used by the ptlrpcd is.
1783                  * Since the processing time is unbounded, we need to insert an
1784                  * explicit schedule point to make the thread well-behaved.
1785                  */
1786                 cond_resched();
1787
1788                 /*
1789                  * If the caller requires to allow to be interpreted by force
1790                  * and it has really been interpreted, then move the request
1791                  * to RQ_PHASE_INTERPRET phase in spite of what the current
1792                  * phase is.
1793                  */
1794                 if (unlikely(req->rq_allow_intr && req->rq_intr)) {
1795                         req->rq_status = -EINTR;
1796                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1797
1798                         /*
1799                          * Since it is interpreted and we have to wait for
1800                          * the reply to be unlinked, then use sync mode.
1801                          */
1802                         async = 0;
1803
1804                         GOTO(interpret, req->rq_status);
1805                 }
1806
1807                 if (req->rq_phase == RQ_PHASE_NEW && ptlrpc_send_new_req(req))
1808                         force_timer_recalc = 1;
1809
1810                 /* delayed send - skip */
1811                 if (req->rq_phase == RQ_PHASE_NEW && req->rq_sent)
1812                         continue;
1813
1814                 /* delayed resend - skip */
1815                 if (req->rq_phase == RQ_PHASE_RPC && req->rq_resend &&
1816                     req->rq_sent > ktime_get_real_seconds())
1817                         continue;
1818
1819                 if (!(req->rq_phase == RQ_PHASE_RPC ||
1820                       req->rq_phase == RQ_PHASE_BULK ||
1821                       req->rq_phase == RQ_PHASE_INTERPRET ||
1822                       req->rq_phase == RQ_PHASE_UNREG_RPC ||
1823                       req->rq_phase == RQ_PHASE_UNREG_BULK)) {
1824                         DEBUG_REQ(D_ERROR, req, "bad phase %x", req->rq_phase);
1825                         LBUG();
1826                 }
1827
1828                 if (req->rq_phase == RQ_PHASE_UNREG_RPC ||
1829                     req->rq_phase == RQ_PHASE_UNREG_BULK) {
1830                         LASSERT(req->rq_next_phase != req->rq_phase);
1831                         LASSERT(req->rq_next_phase != RQ_PHASE_UNDEFINED);
1832
1833                         if (req->rq_req_deadline &&
1834                             !OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REQ_UNLINK))
1835                                 req->rq_req_deadline = 0;
1836                         if (req->rq_reply_deadline &&
1837                             !OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK))
1838                                 req->rq_reply_deadline = 0;
1839                         if (req->rq_bulk_deadline &&
1840                             !OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK))
1841                                 req->rq_bulk_deadline = 0;
1842
1843                         /*
1844                          * Skip processing until reply is unlinked. We
1845                          * can't return to pool before that and we can't
1846                          * call interpret before that. We need to make
1847                          * sure that all rdma transfers finished and will
1848                          * not corrupt any data.
1849                          */
1850                         if (req->rq_phase == RQ_PHASE_UNREG_RPC &&
1851                             ptlrpc_client_recv_or_unlink(req))
1852                                 continue;
1853                         if (req->rq_phase == RQ_PHASE_UNREG_BULK &&
1854                             ptlrpc_client_bulk_active(req))
1855                                 continue;
1856
1857                         /*
1858                          * Turn fail_loc off to prevent it from looping
1859                          * forever.
1860                          */
1861                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
1862                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK,
1863                                                      OBD_FAIL_ONCE);
1864                         }
1865                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK)) {
1866                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK,
1867                                                      OBD_FAIL_ONCE);
1868                         }
1869
1870                         /*
1871                          * Move to next phase if reply was successfully
1872                          * unlinked.
1873                          */
1874                         ptlrpc_rqphase_move(req, req->rq_next_phase);
1875                 }
1876
1877                 if (req->rq_phase == RQ_PHASE_INTERPRET)
1878                         GOTO(interpret, req->rq_status);
1879
1880                 /*
1881                  * Note that this also will start async reply unlink.
1882                  */
1883                 if (req->rq_net_err && !req->rq_timedout) {
1884                         ptlrpc_expire_one_request(req, 1);
1885
1886                         /*
1887                          * Check if we still need to wait for unlink.
1888                          */
1889                         if (ptlrpc_client_recv_or_unlink(req) ||
1890                             ptlrpc_client_bulk_active(req))
1891                                 continue;
1892                         /* If there is no need to resend, fail it now. */
1893                         if (req->rq_no_resend) {
1894                                 if (req->rq_status == 0)
1895                                         req->rq_status = -EIO;
1896                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1897                                 GOTO(interpret, req->rq_status);
1898                         } else {
1899                                 continue;
1900                         }
1901                 }
1902
1903                 if (req->rq_err) {
1904                         spin_lock(&req->rq_lock);
1905                         req->rq_replied = 0;
1906                         spin_unlock(&req->rq_lock);
1907                         if (req->rq_status == 0)
1908                                 req->rq_status = -EIO;
1909                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1910                         GOTO(interpret, req->rq_status);
1911                 }
1912
1913                 /*
1914                  * ptlrpc_set_wait uses l_wait_event_abortable_timeout()
1915                  * so it sets rq_intr regardless of individual rpc
1916                  * timeouts. The synchronous IO waiting path sets
1917                  * rq_intr irrespective of whether ptlrpcd
1918                  * has seen a timeout.  Our policy is to only interpret
1919                  * interrupted rpcs after they have timed out, so we
1920                  * need to enforce that here.
1921                  */
1922
1923                 if (req->rq_intr && (req->rq_timedout || req->rq_waiting ||
1924                                      req->rq_wait_ctx)) {
1925                         req->rq_status = -EINTR;
1926                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1927                         GOTO(interpret, req->rq_status);
1928                 }
1929
1930                 if (req->rq_phase == RQ_PHASE_RPC) {
1931                         if (req->rq_timedout || req->rq_resend ||
1932                             req->rq_waiting || req->rq_wait_ctx) {
1933                                 int status;
1934
1935                                 if (!ptlrpc_unregister_reply(req, 1)) {
1936                                         ptlrpc_unregister_bulk(req, 1);
1937                                         continue;
1938                                 }
1939
1940                                 spin_lock(&imp->imp_lock);
1941                                 if (ptlrpc_import_delay_req(imp, req,
1942                                                             &status)) {
1943                                         /*
1944                                          * put on delay list - only if we wait
1945                                          * recovery finished - before send
1946                                          */
1947                                         list_move_tail(&req->rq_list,
1948                                                        &imp->imp_delayed_list);
1949                                         spin_unlock(&imp->imp_lock);
1950                                         continue;
1951                                 }
1952
1953                                 if (status != 0)  {
1954                                         req->rq_status = status;
1955                                         ptlrpc_rqphase_move(req,
1956                                                             RQ_PHASE_INTERPRET);
1957                                         spin_unlock(&imp->imp_lock);
1958                                         GOTO(interpret, req->rq_status);
1959                                 }
1960                                 /* ignore on just initiated connections */
1961                                 if (ptlrpc_no_resend(req) &&
1962                                     !req->rq_wait_ctx &&
1963                                     imp->imp_generation !=
1964                                     imp->imp_initiated_at) {
1965                                         req->rq_status = -ENOTCONN;
1966                                         ptlrpc_rqphase_move(req,
1967                                                             RQ_PHASE_INTERPRET);
1968                                         spin_unlock(&imp->imp_lock);
1969                                         GOTO(interpret, req->rq_status);
1970                                 }
1971
1972                                 list_move_tail(&req->rq_list,
1973                                                &imp->imp_sending_list);
1974
1975                                 spin_unlock(&imp->imp_lock);
1976
1977                                 spin_lock(&req->rq_lock);
1978                                 req->rq_waiting = 0;
1979                                 spin_unlock(&req->rq_lock);
1980
1981                                 if (req->rq_timedout || req->rq_resend) {
1982                                         /*
1983                                          * This is re-sending anyways,
1984                                          * let's mark req as resend.
1985                                          */
1986                                         spin_lock(&req->rq_lock);
1987                                         req->rq_resend = 1;
1988                                         spin_unlock(&req->rq_lock);
1989                                 }
1990                                 /*
1991                                  * rq_wait_ctx is only touched by ptlrpcd,
1992                                  * so no lock is needed here.
1993                                  */
1994                                 status = sptlrpc_req_refresh_ctx(req, 0);
1995                                 if (status) {
1996                                         if (req->rq_err) {
1997                                                 req->rq_status = status;
1998                                                 spin_lock(&req->rq_lock);
1999                                                 req->rq_wait_ctx = 0;
2000                                                 spin_unlock(&req->rq_lock);
2001                                                 force_timer_recalc = 1;
2002                                         } else {
2003                                                 spin_lock(&req->rq_lock);
2004                                                 req->rq_wait_ctx = 1;
2005                                                 spin_unlock(&req->rq_lock);
2006                                         }
2007
2008                                         continue;
2009                                 } else {
2010                                         spin_lock(&req->rq_lock);
2011                                         req->rq_wait_ctx = 0;
2012                                         spin_unlock(&req->rq_lock);
2013                                 }
2014
2015                                 /*
2016                                  * In any case, the previous bulk should be
2017                                  * cleaned up to prepare for the new sending
2018                                  */
2019                                 if (req->rq_bulk &&
2020                                     !ptlrpc_unregister_bulk(req, 1))
2021                                         continue;
2022
2023                                 rc = ptl_send_rpc(req, 0);
2024                                 if (rc == -ENOMEM) {
2025                                         spin_lock(&imp->imp_lock);
2026                                         if (!list_empty(&req->rq_list))
2027                                                 list_del_init(&req->rq_list);
2028                                         spin_unlock(&imp->imp_lock);
2029                                         ptlrpc_rqphase_move(req, RQ_PHASE_NEW);
2030                                         continue;
2031                                 }
2032                                 if (rc) {
2033                                         DEBUG_REQ(D_HA, req,
2034                                                   "send failed: rc = %d", rc);
2035                                         force_timer_recalc = 1;
2036                                         spin_lock(&req->rq_lock);
2037                                         req->rq_net_err = 1;
2038                                         spin_unlock(&req->rq_lock);
2039                                         continue;
2040                                 }
2041                                 /* need to reset the timeout */
2042                                 force_timer_recalc = 1;
2043                         }
2044
2045                         spin_lock(&req->rq_lock);
2046
2047                         if (ptlrpc_client_early(req)) {
2048                                 ptlrpc_at_recv_early_reply(req);
2049                                 spin_unlock(&req->rq_lock);
2050                                 continue;
2051                         }
2052
2053                         /* Still waiting for a reply? */
2054                         if (ptlrpc_client_recv(req)) {
2055                                 spin_unlock(&req->rq_lock);
2056                                 continue;
2057                         }
2058
2059                         /* Did we actually receive a reply? */
2060                         if (!ptlrpc_client_replied(req)) {
2061                                 spin_unlock(&req->rq_lock);
2062                                 continue;
2063                         }
2064
2065                         spin_unlock(&req->rq_lock);
2066
2067                         /*
2068                          * unlink from net because we are going to
2069                          * swab in-place of reply buffer
2070                          */
2071                         unregistered = ptlrpc_unregister_reply(req, 1);
2072                         if (!unregistered)
2073                                 continue;
2074
2075                         req->rq_status = after_reply(req);
2076                         if (req->rq_resend)
2077                                 continue;
2078
2079                         /*
2080                          * If there is no bulk associated with this request,
2081                          * then we're done and should let the interpreter
2082                          * process the reply. Similarly if the RPC returned
2083                          * an error, and therefore the bulk will never arrive.
2084                          */
2085                         if (!req->rq_bulk || req->rq_status < 0) {
2086                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
2087                                 GOTO(interpret, req->rq_status);
2088                         }
2089
2090                         ptlrpc_rqphase_move(req, RQ_PHASE_BULK);
2091                 }
2092
2093                 LASSERT(req->rq_phase == RQ_PHASE_BULK);
2094                 if (ptlrpc_client_bulk_active(req))
2095                         continue;
2096
2097                 if (req->rq_bulk->bd_failure) {
2098                         /*
2099                          * The RPC reply arrived OK, but the bulk screwed
2100                          * up!  Dead weird since the server told us the RPC
2101                          * was good after getting the REPLY for her GET or
2102                          * the ACK for her PUT.
2103                          */
2104                         DEBUG_REQ(D_ERROR, req, "bulk transfer failed");
2105                         req->rq_status = -EIO;
2106                 }
2107
2108                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
2109
2110 interpret:
2111                 LASSERT(req->rq_phase == RQ_PHASE_INTERPRET);
2112
2113                 /*
2114                  * This moves to "unregistering" phase we need to wait for
2115                  * reply unlink.
2116                  */
2117                 if (!unregistered && !ptlrpc_unregister_reply(req, async)) {
2118                         /* start async bulk unlink too */
2119                         ptlrpc_unregister_bulk(req, 1);
2120                         continue;
2121                 }
2122
2123                 if (!ptlrpc_unregister_bulk(req, async))
2124                         continue;
2125
2126                 /*
2127                  * When calling interpret receiving already should be
2128                  * finished.
2129                  */
2130                 LASSERT(!req->rq_receiving_reply);
2131
2132                 ptlrpc_req_interpret(env, req, req->rq_status);
2133
2134                 if (ptlrpcd_check_work(req)) {
2135                         atomic_dec(&set->set_remaining);
2136                         continue;
2137                 }
2138                 ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
2139
2140                 if (req->rq_reqmsg)
2141                         CDEBUG(D_RPCTRACE,
2142                                "Completed RPC req@%p pname:cluuid:pid:xid:nid:opc:job %s:%s:%d:%llu:%s:%d:%s\n",
2143                                req, current->comm,
2144                                imp->imp_obd->obd_uuid.uuid,
2145                                lustre_msg_get_status(req->rq_reqmsg),
2146                                req->rq_xid,
2147                                obd_import_nid2str(imp),
2148                                lustre_msg_get_opc(req->rq_reqmsg),
2149                                lustre_msg_get_jobid(req->rq_reqmsg) ?: "");
2150
2151                 spin_lock(&imp->imp_lock);
2152                 /*
2153                  * Request already may be not on sending or delaying list. This
2154                  * may happen in the case of marking it erroneous for the case
2155                  * ptlrpc_import_delay_req(req, status) find it impossible to
2156                  * allow sending this rpc and returns *status != 0.
2157                  */
2158                 if (!list_empty(&req->rq_list)) {
2159                         list_del_init(&req->rq_list);
2160                         if (atomic_dec_and_test(&imp->imp_inflight))
2161                                 wake_up(&imp->imp_recovery_waitq);
2162                 }
2163                 list_del_init(&req->rq_unreplied_list);
2164                 spin_unlock(&imp->imp_lock);
2165
2166                 atomic_dec(&set->set_remaining);
2167                 wake_up(&imp->imp_recovery_waitq);
2168
2169                 if (set->set_producer) {
2170                         /* produce a new request if possible */
2171                         if (ptlrpc_set_producer(set) > 0)
2172                                 force_timer_recalc = 1;
2173
2174                         /*
2175                          * free the request that has just been completed
2176                          * in order not to pollute set->set_requests
2177                          */
2178                         list_del_init(&req->rq_set_chain);
2179                         spin_lock(&req->rq_lock);
2180                         req->rq_set = NULL;
2181                         req->rq_invalid_rqset = 0;
2182                         spin_unlock(&req->rq_lock);
2183
2184                         /* record rq_status to compute the final status later */
2185                         if (req->rq_status != 0)
2186                                 set->set_rc = req->rq_status;
2187                         ptlrpc_req_finished(req);
2188                 } else {
2189                         list_move_tail(&req->rq_set_chain, &comp_reqs);
2190                 }
2191         }
2192
2193         /*
2194          * move completed request at the head of list so it's easier for
2195          * caller to find them
2196          */
2197         list_splice(&comp_reqs, &set->set_requests);
2198
2199         /* If we hit an error, we want to recover promptly. */
2200         RETURN(atomic_read(&set->set_remaining) == 0 || force_timer_recalc);
2201 }
2202 EXPORT_SYMBOL(ptlrpc_check_set);
2203
2204 /**
2205  * Time out request \a req. is \a async_unlink is set, that means do not wait
2206  * until LNet actually confirms network buffer unlinking.
2207  * Return 1 if we should give up further retrying attempts or 0 otherwise.
2208  */
2209 int ptlrpc_expire_one_request(struct ptlrpc_request *req, int async_unlink)
2210 {
2211         struct obd_import *imp = req->rq_import;
2212         unsigned int debug_mask = D_RPCTRACE;
2213         int rc = 0;
2214
2215         ENTRY;
2216         spin_lock(&req->rq_lock);
2217         req->rq_timedout = 1;
2218         spin_unlock(&req->rq_lock);
2219
2220         if (ptlrpc_console_allow(req, lustre_msg_get_opc(req->rq_reqmsg),
2221                                  lustre_msg_get_status(req->rq_reqmsg)))
2222                 debug_mask = D_WARNING;
2223         DEBUG_REQ(debug_mask, req, "Request sent has %s: [sent %lld/real %lld]",
2224                   req->rq_net_err ? "failed due to network error" :
2225                      ((req->rq_real_sent == 0 ||
2226                        req->rq_real_sent < req->rq_sent ||
2227                        req->rq_real_sent >= req->rq_deadline) ?
2228                       "timed out for sent delay" : "timed out for slow reply"),
2229                   (s64)req->rq_sent, (s64)req->rq_real_sent);
2230
2231         if (imp && obd_debug_peer_on_timeout)
2232                 LNetDebugPeer(imp->imp_connection->c_peer);
2233
2234         ptlrpc_unregister_reply(req, async_unlink);
2235         ptlrpc_unregister_bulk(req, async_unlink);
2236
2237         if (obd_dump_on_timeout)
2238                 libcfs_debug_dumplog();
2239
2240         if (!imp) {
2241                 DEBUG_REQ(D_HA, req, "NULL import: already cleaned up?");
2242                 RETURN(1);
2243         }
2244
2245         atomic_inc(&imp->imp_timeouts);
2246
2247         /* The DLM server doesn't want recovery run on its imports. */
2248         if (imp->imp_dlm_fake)
2249                 RETURN(1);
2250
2251         /*
2252          * If this request is for recovery or other primordial tasks,
2253          * then error it out here.
2254          */
2255         if (req->rq_ctx_init || req->rq_ctx_fini ||
2256             req->rq_send_state != LUSTRE_IMP_FULL ||
2257             imp->imp_obd->obd_no_recov) {
2258                 DEBUG_REQ(D_RPCTRACE, req, "err -110, sent_state=%s (now=%s)",
2259                           ptlrpc_import_state_name(req->rq_send_state),
2260                           ptlrpc_import_state_name(imp->imp_state));
2261                 spin_lock(&req->rq_lock);
2262                 req->rq_status = -ETIMEDOUT;
2263                 req->rq_err = 1;
2264                 spin_unlock(&req->rq_lock);
2265                 RETURN(1);
2266         }
2267
2268         /*
2269          * if a request can't be resent we can't wait for an answer after
2270          * the timeout
2271          */
2272         if (ptlrpc_no_resend(req)) {
2273                 DEBUG_REQ(D_RPCTRACE, req, "TIMEOUT-NORESEND:");
2274                 rc = 1;
2275         }
2276
2277         ptlrpc_fail_import(imp, lustre_msg_get_conn_cnt(req->rq_reqmsg));
2278
2279         RETURN(rc);
2280 }
2281
2282 /**
2283  * Time out all uncompleted requests in request set pointed by \a data
2284  * This is called when a wait times out.
2285  */
2286 void ptlrpc_expired_set(struct ptlrpc_request_set *set)
2287 {
2288         struct list_head *tmp;
2289         time64_t now = ktime_get_real_seconds();
2290
2291         ENTRY;
2292         LASSERT(set != NULL);
2293
2294         /*
2295          * A timeout expired. See which reqs it applies to...
2296          */
2297         list_for_each(tmp, &set->set_requests) {
2298                 struct ptlrpc_request *req =
2299                         list_entry(tmp, struct ptlrpc_request,
2300                                    rq_set_chain);
2301
2302                 /* don't expire request waiting for context */
2303                 if (req->rq_wait_ctx)
2304                         continue;
2305
2306                 /* Request in-flight? */
2307                 if (!((req->rq_phase == RQ_PHASE_RPC &&
2308                        !req->rq_waiting && !req->rq_resend) ||
2309                       (req->rq_phase == RQ_PHASE_BULK)))
2310                         continue;
2311
2312                 if (req->rq_timedout ||     /* already dealt with */
2313                     req->rq_deadline > now) /* not expired */
2314                         continue;
2315
2316                 /*
2317                  * Deal with this guy. Do it asynchronously to not block
2318                  * ptlrpcd thread.
2319                  */
2320                 ptlrpc_expire_one_request(req, 1);
2321         }
2322 }
2323
2324 /**
2325  * Interrupts (sets interrupted flag) all uncompleted requests in
2326  * a set \a data. This is called when a wait_event is interrupted
2327  * by a signal.
2328  */
2329 static void ptlrpc_interrupted_set(struct ptlrpc_request_set *set)
2330 {
2331         struct list_head *tmp;
2332
2333         LASSERT(set != NULL);
2334         CDEBUG(D_RPCTRACE, "INTERRUPTED SET %p\n", set);
2335
2336         list_for_each(tmp, &set->set_requests) {
2337                 struct ptlrpc_request *req =
2338                         list_entry(tmp, struct ptlrpc_request, rq_set_chain);
2339
2340                 if (req->rq_intr)
2341                         continue;
2342
2343                 if (req->rq_phase != RQ_PHASE_RPC &&
2344                     req->rq_phase != RQ_PHASE_UNREG_RPC &&
2345                     !req->rq_allow_intr)
2346                         continue;
2347
2348                 spin_lock(&req->rq_lock);
2349                 req->rq_intr = 1;
2350                 spin_unlock(&req->rq_lock);
2351         }
2352 }
2353
2354 /**
2355  * Get the smallest timeout in the set; this does NOT set a timeout.
2356  */
2357 time64_t ptlrpc_set_next_timeout(struct ptlrpc_request_set *set)
2358 {
2359         struct list_head *tmp;
2360         time64_t now = ktime_get_real_seconds();
2361         int timeout = 0;
2362         struct ptlrpc_request *req;
2363         time64_t deadline;
2364
2365         ENTRY;
2366         list_for_each(tmp, &set->set_requests) {
2367                 req = list_entry(tmp, struct ptlrpc_request, rq_set_chain);
2368
2369                 /* Request in-flight? */
2370                 if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
2371                       (req->rq_phase == RQ_PHASE_BULK) ||
2372                       (req->rq_phase == RQ_PHASE_NEW)))
2373                         continue;
2374
2375                 /* Already timed out. */
2376                 if (req->rq_timedout)
2377                         continue;
2378
2379                 /* Waiting for ctx. */
2380                 if (req->rq_wait_ctx)
2381                         continue;
2382
2383                 if (req->rq_phase == RQ_PHASE_NEW)
2384                         deadline = req->rq_sent;
2385                 else if (req->rq_phase == RQ_PHASE_RPC && req->rq_resend)
2386                         deadline = req->rq_sent;
2387                 else
2388                         deadline = req->rq_sent + req->rq_timeout;
2389
2390                 if (deadline <= now)    /* actually expired already */
2391                         timeout = 1;    /* ASAP */
2392                 else if (timeout == 0 || timeout > deadline - now)
2393                         timeout = deadline - now;
2394         }
2395         RETURN(timeout);
2396 }
2397
2398 /**
2399  * Send all unset request from the set and then wait untill all
2400  * requests in the set complete (either get a reply, timeout, get an
2401  * error or otherwise be interrupted).
2402  * Returns 0 on success or error code otherwise.
2403  */
2404 int ptlrpc_set_wait(const struct lu_env *env, struct ptlrpc_request_set *set)
2405 {
2406         struct list_head *tmp;
2407         struct ptlrpc_request *req;
2408         time64_t timeout;
2409         int rc;
2410
2411         ENTRY;
2412         if (set->set_producer)
2413                 (void)ptlrpc_set_producer(set);
2414         else
2415                 list_for_each(tmp, &set->set_requests) {
2416                         req = list_entry(tmp, struct ptlrpc_request,
2417                                          rq_set_chain);
2418                         if (req->rq_phase == RQ_PHASE_NEW)
2419                                 (void)ptlrpc_send_new_req(req);
2420                 }
2421
2422         if (list_empty(&set->set_requests))
2423                 RETURN(0);
2424
2425         do {
2426                 timeout = ptlrpc_set_next_timeout(set);
2427
2428                 /*
2429                  * wait until all complete, interrupted, or an in-flight
2430                  * req times out
2431                  */
2432                 CDEBUG(D_RPCTRACE, "set %p going to sleep for %lld seconds\n",
2433                        set, timeout);
2434
2435                 if ((timeout == 0 && !signal_pending(current)) ||
2436                     set->set_allow_intr) {
2437                         /*
2438                          * No requests are in-flight (ether timed out
2439                          * or delayed), so we can allow interrupts.
2440                          * We still want to block for a limited time,
2441                          * so we allow interrupts during the timeout.
2442                          */
2443                         rc = l_wait_event_abortable_timeout(
2444                                 set->set_waitq,
2445                                 ptlrpc_check_set(NULL, set),
2446                                 cfs_time_seconds(timeout ? timeout : 1));
2447                         if (rc == 0) {
2448                                 rc = -ETIMEDOUT;
2449                                 ptlrpc_expired_set(set);
2450                         } else if (rc < 0) {
2451                                 rc = -EINTR;
2452                                 ptlrpc_interrupted_set(set);
2453                         } else {
2454                                 rc = 0;
2455                         }
2456                 } else {
2457                         /*
2458                          * At least one request is in flight, so no
2459                          * interrupts are allowed. Wait until all
2460                          * complete, or an in-flight req times out.
2461                          */
2462                         rc = wait_event_idle_timeout(
2463                                 set->set_waitq,
2464                                 ptlrpc_check_set(NULL, set),
2465                                 cfs_time_seconds(timeout ? timeout : 1));
2466                         if (rc == 0) {
2467                                 ptlrpc_expired_set(set);
2468                                 rc = -ETIMEDOUT;
2469                         } else {
2470                                 rc = 0;
2471                         }
2472
2473                         /*
2474                          * LU-769 - if we ignored the signal because
2475                          * it was already pending when we started, we
2476                          * need to handle it now or we risk it being
2477                          * ignored forever
2478                          */
2479                         if (rc == -ETIMEDOUT &&
2480                             signal_pending(current)) {
2481                                 sigset_t blocked_sigs;
2482
2483                                 cfs_block_sigsinv(LUSTRE_FATAL_SIGS,
2484                                                   &blocked_sigs);
2485                                 /*
2486                                  * In fact we only interrupt for the
2487                                  * "fatal" signals like SIGINT or
2488                                  * SIGKILL. We still ignore less
2489                                  * important signals since ptlrpc set
2490                                  * is not easily reentrant from
2491                                  * userspace again
2492                                  */
2493                                 if (signal_pending(current))
2494                                         ptlrpc_interrupted_set(set);
2495                                 cfs_restore_sigs(&blocked_sigs);
2496                         }
2497                 }
2498
2499                 LASSERT(rc == 0 || rc == -EINTR || rc == -ETIMEDOUT);
2500
2501                 /*
2502                  * -EINTR => all requests have been flagged rq_intr so next
2503                  * check completes.
2504                  * -ETIMEDOUT => someone timed out.  When all reqs have
2505                  * timed out, signals are enabled allowing completion with
2506                  * EINTR.
2507                  * I don't really care if we go once more round the loop in
2508                  * the error cases -eeb.
2509                  */
2510                 if (rc == 0 && atomic_read(&set->set_remaining) == 0) {
2511                         list_for_each(tmp, &set->set_requests) {
2512                                 req = list_entry(tmp, struct ptlrpc_request,
2513                                                  rq_set_chain);
2514                                 spin_lock(&req->rq_lock);
2515                                 req->rq_invalid_rqset = 1;
2516                                 spin_unlock(&req->rq_lock);
2517                         }
2518                 }
2519         } while (rc != 0 || atomic_read(&set->set_remaining) != 0);
2520
2521         LASSERT(atomic_read(&set->set_remaining) == 0);
2522
2523         rc = set->set_rc; /* rq_status of already freed requests if any */
2524         list_for_each(tmp, &set->set_requests) {
2525                 req = list_entry(tmp, struct ptlrpc_request, rq_set_chain);
2526
2527                 LASSERT(req->rq_phase == RQ_PHASE_COMPLETE);
2528                 if (req->rq_status != 0)
2529                         rc = req->rq_status;
2530         }
2531
2532         RETURN(rc);
2533 }
2534 EXPORT_SYMBOL(ptlrpc_set_wait);
2535
2536 /**
2537  * Helper fuction for request freeing.
2538  * Called when request count reached zero and request needs to be freed.
2539  * Removes request from all sorts of sending/replay lists it might be on,
2540  * frees network buffers if any are present.
2541  * If \a locked is set, that means caller is already holding import imp_lock
2542  * and so we no longer need to reobtain it (for certain lists manipulations)
2543  */
2544 static void __ptlrpc_free_req(struct ptlrpc_request *request, int locked)
2545 {
2546         ENTRY;
2547
2548         if (!request)
2549                 RETURN_EXIT;
2550
2551         LASSERT(!request->rq_srv_req);
2552         LASSERT(request->rq_export == NULL);
2553         LASSERTF(!request->rq_receiving_reply, "req %p\n", request);
2554         LASSERTF(list_empty(&request->rq_list), "req %p\n", request);
2555         LASSERTF(list_empty(&request->rq_set_chain), "req %p\n", request);
2556         LASSERTF(!request->rq_replay, "req %p\n", request);
2557
2558         req_capsule_fini(&request->rq_pill);
2559
2560         /*
2561          * We must take it off the imp_replay_list first.  Otherwise, we'll set
2562          * request->rq_reqmsg to NULL while osc_close is dereferencing it.
2563          */
2564         if (request->rq_import) {
2565                 if (!locked)
2566                         spin_lock(&request->rq_import->imp_lock);
2567                 list_del_init(&request->rq_replay_list);
2568                 list_del_init(&request->rq_unreplied_list);
2569                 if (!locked)
2570                         spin_unlock(&request->rq_import->imp_lock);
2571         }
2572         LASSERTF(list_empty(&request->rq_replay_list), "req %p\n", request);
2573
2574         if (atomic_read(&request->rq_refcount) != 0) {
2575                 DEBUG_REQ(D_ERROR, request,
2576                           "freeing request with nonzero refcount");
2577                 LBUG();
2578         }
2579
2580         if (request->rq_repbuf)
2581                 sptlrpc_cli_free_repbuf(request);
2582
2583         if (request->rq_import) {
2584                 class_import_put(request->rq_import);
2585                 request->rq_import = NULL;
2586         }
2587         if (request->rq_bulk)
2588                 ptlrpc_free_bulk(request->rq_bulk);
2589
2590         if (request->rq_reqbuf || request->rq_clrbuf)
2591                 sptlrpc_cli_free_reqbuf(request);
2592
2593         if (request->rq_cli_ctx)
2594                 sptlrpc_req_put_ctx(request, !locked);
2595
2596         if (request->rq_pool)
2597                 __ptlrpc_free_req_to_pool(request);
2598         else
2599                 ptlrpc_request_cache_free(request);
2600         EXIT;
2601 }
2602
2603 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked);
2604 /**
2605  * Drop one request reference. Must be called with import imp_lock held.
2606  * When reference count drops to zero, request is freed.
2607  */
2608 void ptlrpc_req_finished_with_imp_lock(struct ptlrpc_request *request)
2609 {
2610         assert_spin_locked(&request->rq_import->imp_lock);
2611         (void)__ptlrpc_req_finished(request, 1);
2612 }
2613
2614 /**
2615  * Helper function
2616  * Drops one reference count for request \a request.
2617  * \a locked set indicates that caller holds import imp_lock.
2618  * Frees the request whe reference count reaches zero.
2619  *
2620  * \retval 1    the request is freed
2621  * \retval 0    some others still hold references on the request
2622  */
2623 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked)
2624 {
2625         int count;
2626
2627         ENTRY;
2628         if (!request)
2629                 RETURN(1);
2630
2631         LASSERT(request != LP_POISON);
2632         LASSERT(request->rq_reqmsg != LP_POISON);
2633
2634         DEBUG_REQ(D_INFO, request, "refcount now %u",
2635                   atomic_read(&request->rq_refcount) - 1);
2636
2637         spin_lock(&request->rq_lock);
2638         count = atomic_dec_return(&request->rq_refcount);
2639         LASSERTF(count >= 0, "Invalid ref count %d\n", count);
2640
2641         /*
2642          * For open RPC, the client does not know the EA size (LOV, ACL, and
2643          * so on) before replied, then the client has to reserve very large
2644          * reply buffer. Such buffer will not be released until the RPC freed.
2645          * Since The open RPC is replayable, we need to keep it in the replay
2646          * list until close. If there are a lot of files opened concurrently,
2647          * then the client may be OOM.
2648          *
2649          * If fact, it is unnecessary to keep reply buffer for open replay,
2650          * related EAs have already been saved via mdc_save_lovea() before
2651          * coming here. So it is safe to free the reply buffer some earlier
2652          * before releasing the RPC to avoid client OOM. LU-9514
2653          */
2654         if (count == 1 && request->rq_early_free_repbuf && request->rq_repbuf) {
2655                 spin_lock(&request->rq_early_free_lock);
2656                 sptlrpc_cli_free_repbuf(request);
2657                 request->rq_repbuf = NULL;
2658                 request->rq_repbuf_len = 0;
2659                 request->rq_repdata = NULL;
2660                 request->rq_reqdata_len = 0;
2661                 spin_unlock(&request->rq_early_free_lock);
2662         }
2663         spin_unlock(&request->rq_lock);
2664
2665         if (!count)
2666                 __ptlrpc_free_req(request, locked);
2667
2668         RETURN(!count);
2669 }
2670
2671 /**
2672  * Drops one reference count for a request.
2673  */
2674 void ptlrpc_req_finished(struct ptlrpc_request *request)
2675 {
2676         __ptlrpc_req_finished(request, 0);
2677 }
2678 EXPORT_SYMBOL(ptlrpc_req_finished);
2679
2680 /**
2681  * Returns xid of a \a request
2682  */
2683 __u64 ptlrpc_req_xid(struct ptlrpc_request *request)
2684 {
2685         return request->rq_xid;
2686 }
2687 EXPORT_SYMBOL(ptlrpc_req_xid);
2688
2689 /**
2690  * Disengage the client's reply buffer from the network
2691  * NB does _NOT_ unregister any client-side bulk.
2692  * IDEMPOTENT, but _not_ safe against concurrent callers.
2693  * The request owner (i.e. the thread doing the I/O) must call...
2694  * Returns 0 on success or 1 if unregistering cannot be made.
2695  */
2696 static int ptlrpc_unregister_reply(struct ptlrpc_request *request, int async)
2697 {
2698         /*
2699          * Might sleep.
2700          */
2701         LASSERT(!in_interrupt());
2702
2703         /* Let's setup deadline for reply unlink. */
2704         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK) &&
2705             async && request->rq_reply_deadline == 0 && cfs_fail_val == 0)
2706                 request->rq_reply_deadline = ktime_get_real_seconds() +
2707                                              LONG_UNLINK;
2708
2709         /*
2710          * Nothing left to do.
2711          */
2712         if (!ptlrpc_client_recv_or_unlink(request))
2713                 RETURN(1);
2714
2715         LNetMDUnlink(request->rq_reply_md_h);
2716
2717         /*
2718          * Let's check it once again.
2719          */
2720         if (!ptlrpc_client_recv_or_unlink(request))
2721                 RETURN(1);
2722
2723         /* Move to "Unregistering" phase as reply was not unlinked yet. */
2724         ptlrpc_rqphase_move(request, RQ_PHASE_UNREG_RPC);
2725
2726         /*
2727          * Do not wait for unlink to finish.
2728          */
2729         if (async)
2730                 RETURN(0);
2731
2732         /*
2733          * We have to wait_event_idle_timeout() whatever the result, to get
2734          * a chance to run reply_in_callback(), and to make sure we've
2735          * unlinked before returning a req to the pool.
2736          */
2737         for (;;) {
2738                 wait_queue_head_t *wq = (request->rq_set) ?
2739                                         &request->rq_set->set_waitq :
2740                                         &request->rq_reply_waitq;
2741                 int seconds = LONG_UNLINK;
2742                 /*
2743                  * Network access will complete in finite time but the HUGE
2744                  * timeout lets us CWARN for visibility of sluggish NALs
2745                  */
2746                 while (seconds > 0 &&
2747                        wait_event_idle_timeout(
2748                                *wq,
2749                                !ptlrpc_client_recv_or_unlink(request),
2750                                cfs_time_seconds(1)) == 0)
2751                         seconds -= 1;
2752                 if (seconds > 0) {
2753                         ptlrpc_rqphase_move(request, request->rq_next_phase);
2754                         RETURN(1);
2755                 }
2756
2757                 DEBUG_REQ(D_WARNING, request,
2758                           "Unexpectedly long timeout receiving_reply=%d req_ulinked=%d reply_unlinked=%d",
2759                           request->rq_receiving_reply,
2760                           request->rq_req_unlinked,
2761                           request->rq_reply_unlinked);
2762         }
2763         RETURN(0);
2764 }
2765
2766 static void ptlrpc_free_request(struct ptlrpc_request *req)
2767 {
2768         spin_lock(&req->rq_lock);
2769         req->rq_replay = 0;
2770         spin_unlock(&req->rq_lock);
2771
2772         if (req->rq_commit_cb)
2773                 req->rq_commit_cb(req);
2774         list_del_init(&req->rq_replay_list);
2775
2776         __ptlrpc_req_finished(req, 1);
2777 }
2778
2779 /**
2780  * the request is committed and dropped from the replay list of its import
2781  */
2782 void ptlrpc_request_committed(struct ptlrpc_request *req, int force)
2783 {
2784         struct obd_import *imp = req->rq_import;
2785
2786         spin_lock(&imp->imp_lock);
2787         if (list_empty(&req->rq_replay_list)) {
2788                 spin_unlock(&imp->imp_lock);
2789                 return;
2790         }
2791
2792         if (force || req->rq_transno <= imp->imp_peer_committed_transno) {
2793                 if (imp->imp_replay_cursor == &req->rq_replay_list)
2794                         imp->imp_replay_cursor = req->rq_replay_list.next;
2795                 ptlrpc_free_request(req);
2796         }
2797
2798         spin_unlock(&imp->imp_lock);
2799 }
2800 EXPORT_SYMBOL(ptlrpc_request_committed);
2801
2802 /**
2803  * Iterates through replay_list on import and prunes
2804  * all requests have transno smaller than last_committed for the
2805  * import and don't have rq_replay set.
2806  * Since requests are sorted in transno order, stops when meetign first
2807  * transno bigger than last_committed.
2808  * caller must hold imp->imp_lock
2809  */
2810 void ptlrpc_free_committed(struct obd_import *imp)
2811 {
2812         struct ptlrpc_request *req, *saved;
2813         struct ptlrpc_request *last_req = NULL; /* temporary fire escape */
2814         bool skip_committed_list = true;
2815
2816         ENTRY;
2817         LASSERT(imp != NULL);
2818         assert_spin_locked(&imp->imp_lock);
2819
2820         if (imp->imp_peer_committed_transno == imp->imp_last_transno_checked &&
2821             imp->imp_generation == imp->imp_last_generation_checked) {
2822                 CDEBUG(D_INFO, "%s: skip recheck: last_committed %llu\n",
2823                        imp->imp_obd->obd_name, imp->imp_peer_committed_transno);
2824                 RETURN_EXIT;
2825         }
2826         CDEBUG(D_RPCTRACE, "%s: committing for last_committed %llu gen %d\n",
2827                imp->imp_obd->obd_name, imp->imp_peer_committed_transno,
2828                imp->imp_generation);
2829
2830         if (imp->imp_generation != imp->imp_last_generation_checked ||
2831             imp->imp_last_transno_checked == 0)
2832                 skip_committed_list = false;
2833
2834         imp->imp_last_transno_checked = imp->imp_peer_committed_transno;
2835         imp->imp_last_generation_checked = imp->imp_generation;
2836
2837         list_for_each_entry_safe(req, saved, &imp->imp_replay_list,
2838                                  rq_replay_list) {
2839                 /* XXX ok to remove when 1357 resolved - rread 05/29/03  */
2840                 LASSERT(req != last_req);
2841                 last_req = req;
2842
2843                 if (req->rq_transno == 0) {
2844                         DEBUG_REQ(D_EMERG, req, "zero transno during replay");
2845                         LBUG();
2846                 }
2847                 if (req->rq_import_generation < imp->imp_generation) {
2848                         DEBUG_REQ(D_RPCTRACE, req, "free request with old gen");
2849                         GOTO(free_req, 0);
2850                 }
2851
2852                 /* not yet committed */
2853                 if (req->rq_transno > imp->imp_peer_committed_transno) {
2854                         DEBUG_REQ(D_RPCTRACE, req, "stopping search");
2855                         break;
2856                 }
2857
2858                 if (req->rq_replay) {
2859                         DEBUG_REQ(D_RPCTRACE, req, "keeping (FL_REPLAY)");
2860                         list_move_tail(&req->rq_replay_list,
2861                                        &imp->imp_committed_list);
2862                         continue;
2863                 }
2864
2865                 DEBUG_REQ(D_INFO, req, "commit (last_committed %llu)",
2866                           imp->imp_peer_committed_transno);
2867 free_req:
2868                 ptlrpc_free_request(req);
2869         }
2870
2871         if (skip_committed_list)
2872                 GOTO(out, 0);
2873
2874         list_for_each_entry_safe(req, saved, &imp->imp_committed_list,
2875                                  rq_replay_list) {
2876                 LASSERT(req->rq_transno != 0);
2877                 if (req->rq_import_generation < imp->imp_generation ||
2878                     !req->rq_replay) {
2879                         DEBUG_REQ(D_RPCTRACE, req, "free %s open request",
2880                                   req->rq_import_generation <
2881                                   imp->imp_generation ? "stale" : "closed");
2882
2883                         if (imp->imp_replay_cursor == &req->rq_replay_list)
2884                                 imp->imp_replay_cursor =
2885                                         req->rq_replay_list.next;
2886
2887                         ptlrpc_free_request(req);
2888                 }
2889         }
2890 out:
2891         EXIT;
2892 }
2893
2894 void ptlrpc_cleanup_client(struct obd_import *imp)
2895 {
2896         ENTRY;
2897         EXIT;
2898 }
2899
2900 /**
2901  * Schedule previously sent request for resend.
2902  * For bulk requests we assign new xid (to avoid problems with
2903  * lost replies and therefore several transfers landing into same buffer
2904  * from different sending attempts).
2905  */
2906 void ptlrpc_resend_req(struct ptlrpc_request *req)
2907 {
2908         DEBUG_REQ(D_HA, req, "going to resend");
2909         spin_lock(&req->rq_lock);
2910
2911         /*
2912          * Request got reply but linked to the import list still.
2913          * Let ptlrpc_check_set() process it.
2914          */
2915         if (ptlrpc_client_replied(req)) {
2916                 spin_unlock(&req->rq_lock);
2917                 DEBUG_REQ(D_HA, req, "it has reply, so skip it");
2918                 return;
2919         }
2920
2921         req->rq_status = -EAGAIN;
2922
2923         req->rq_resend = 1;
2924         req->rq_net_err = 0;
2925         req->rq_timedout = 0;
2926
2927         ptlrpc_client_wake_req(req);
2928         spin_unlock(&req->rq_lock);
2929 }
2930
2931 /* XXX: this function and rq_status are currently unused */
2932 void ptlrpc_restart_req(struct ptlrpc_request *req)
2933 {
2934         DEBUG_REQ(D_HA, req, "restarting (possibly-)completed request");
2935         req->rq_status = -ERESTARTSYS;
2936
2937         spin_lock(&req->rq_lock);
2938         req->rq_restart = 1;
2939         req->rq_timedout = 0;
2940         ptlrpc_client_wake_req(req);
2941         spin_unlock(&req->rq_lock);
2942 }
2943
2944 /**
2945  * Grab additional reference on a request \a req
2946  */
2947 struct ptlrpc_request *ptlrpc_request_addref(struct ptlrpc_request *req)
2948 {
2949         ENTRY;
2950         atomic_inc(&req->rq_refcount);
2951         RETURN(req);
2952 }
2953 EXPORT_SYMBOL(ptlrpc_request_addref);
2954
2955 /**
2956  * Add a request to import replay_list.
2957  * Must be called under imp_lock
2958  */
2959 void ptlrpc_retain_replayable_request(struct ptlrpc_request *req,
2960                                       struct obd_import *imp)
2961 {
2962         struct list_head *tmp;
2963
2964         assert_spin_locked(&imp->imp_lock);
2965
2966         if (req->rq_transno == 0) {
2967                 DEBUG_REQ(D_EMERG, req, "saving request with zero transno");
2968                 LBUG();
2969         }
2970
2971         /*
2972          * clear this for new requests that were resent as well
2973          * as resent replayed requests.
2974          */
2975         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
2976
2977         /* don't re-add requests that have been replayed */
2978         if (!list_empty(&req->rq_replay_list))
2979                 return;
2980
2981         lustre_msg_add_flags(req->rq_reqmsg, MSG_REPLAY);
2982
2983         spin_lock(&req->rq_lock);
2984         req->rq_resend = 0;
2985         spin_unlock(&req->rq_lock);
2986
2987         LASSERT(imp->imp_replayable);
2988         /* Balanced in ptlrpc_free_committed, usually. */
2989         ptlrpc_request_addref(req);
2990         list_for_each_prev(tmp, &imp->imp_replay_list) {
2991                 struct ptlrpc_request *iter = list_entry(tmp,
2992                                                          struct ptlrpc_request,
2993                                                          rq_replay_list);
2994
2995                 /*
2996                  * We may have duplicate transnos if we create and then
2997                  * open a file, or for closes retained if to match creating
2998                  * opens, so use req->rq_xid as a secondary key.
2999                  * (See bugs 684, 685, and 428.)
3000                  * XXX no longer needed, but all opens need transnos!
3001                  */
3002                 if (iter->rq_transno > req->rq_transno)
3003                         continue;
3004
3005                 if (iter->rq_transno == req->rq_transno) {
3006                         LASSERT(iter->rq_xid != req->rq_xid);
3007                         if (iter->rq_xid > req->rq_xid)
3008                                 continue;
3009                 }
3010
3011                 list_add(&req->rq_replay_list, &iter->rq_replay_list);
3012                 return;
3013         }
3014
3015         list_add(&req->rq_replay_list, &imp->imp_replay_list);
3016 }
3017
3018 /**
3019  * Send request and wait until it completes.
3020  * Returns request processing status.
3021  */
3022 int ptlrpc_queue_wait(struct ptlrpc_request *req)
3023 {
3024         struct ptlrpc_request_set *set;
3025         int rc;
3026
3027         ENTRY;
3028         LASSERT(req->rq_set == NULL);
3029         LASSERT(!req->rq_receiving_reply);
3030
3031         set = ptlrpc_prep_set();
3032         if (!set) {
3033                 CERROR("cannot allocate ptlrpc set: rc = %d\n", -ENOMEM);
3034                 RETURN(-ENOMEM);
3035         }
3036
3037         /* for distributed debugging */
3038         lustre_msg_set_status(req->rq_reqmsg, current->pid);
3039
3040         /* add a ref for the set (see comment in ptlrpc_set_add_req) */
3041         ptlrpc_request_addref(req);
3042         ptlrpc_set_add_req(set, req);
3043         rc = ptlrpc_set_wait(NULL, set);
3044         ptlrpc_set_destroy(set);
3045
3046         RETURN(rc);
3047 }
3048 EXPORT_SYMBOL(ptlrpc_queue_wait);
3049
3050 /**
3051  * Callback used for replayed requests reply processing.
3052  * In case of successful reply calls registered request replay callback.
3053  * In case of error restart replay process.
3054  */
3055 static int ptlrpc_replay_interpret(const struct lu_env *env,
3056                                    struct ptlrpc_request *req,
3057                                    void *args, int rc)
3058 {
3059         struct ptlrpc_replay_async_args *aa = args;
3060         struct obd_import *imp = req->rq_import;
3061
3062         ENTRY;
3063         atomic_dec(&imp->imp_replay_inflight);
3064
3065         /*
3066          * Note: if it is bulk replay (MDS-MDS replay), then even if
3067          * server got the request, but bulk transfer timeout, let's
3068          * replay the bulk req again
3069          */
3070         if (!ptlrpc_client_replied(req) ||
3071             (req->rq_bulk &&
3072              lustre_msg_get_status(req->rq_repmsg) == -ETIMEDOUT)) {
3073                 DEBUG_REQ(D_ERROR, req, "request replay timed out");
3074                 GOTO(out, rc = -ETIMEDOUT);
3075         }
3076
3077         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR &&
3078             (lustre_msg_get_status(req->rq_repmsg) == -ENOTCONN ||
3079             lustre_msg_get_status(req->rq_repmsg) == -ENODEV))
3080                 GOTO(out, rc = lustre_msg_get_status(req->rq_repmsg));
3081
3082         /** VBR: check version failure */
3083         if (lustre_msg_get_status(req->rq_repmsg) == -EOVERFLOW) {
3084                 /** replay was failed due to version mismatch */
3085                 DEBUG_REQ(D_WARNING, req, "Version mismatch during replay");
3086                 spin_lock(&imp->imp_lock);
3087                 imp->imp_vbr_failed = 1;
3088                 spin_unlock(&imp->imp_lock);
3089                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
3090         } else {
3091                 /** The transno had better not change over replay. */
3092                 LASSERTF(lustre_msg_get_transno(req->rq_reqmsg) ==
3093                          lustre_msg_get_transno(req->rq_repmsg) ||
3094                          lustre_msg_get_transno(req->rq_repmsg) == 0,
3095                          "%#llx/%#llx\n",
3096                          lustre_msg_get_transno(req->rq_reqmsg),
3097                          lustre_msg_get_transno(req->rq_repmsg));
3098         }
3099
3100         spin_lock(&imp->imp_lock);
3101         imp->imp_last_replay_transno = lustre_msg_get_transno(req->rq_reqmsg);
3102         spin_unlock(&imp->imp_lock);
3103         LASSERT(imp->imp_last_replay_transno);
3104
3105         /* transaction number shouldn't be bigger than the latest replayed */
3106         if (req->rq_transno > lustre_msg_get_transno(req->rq_reqmsg)) {
3107                 DEBUG_REQ(D_ERROR, req,
3108                           "Reported transno=%llu is bigger than replayed=%llu",
3109                           req->rq_transno,
3110                           lustre_msg_get_transno(req->rq_reqmsg));
3111                 GOTO(out, rc = -EINVAL);
3112         }
3113
3114         DEBUG_REQ(D_HA, req, "got reply");
3115
3116         /* let the callback do fixups, possibly including in the request */
3117         if (req->rq_replay_cb)
3118                 req->rq_replay_cb(req);
3119
3120         if (ptlrpc_client_replied(req) &&
3121             lustre_msg_get_status(req->rq_repmsg) != aa->praa_old_status) {
3122                 DEBUG_REQ(D_ERROR, req, "status %d, old was %d",
3123                           lustre_msg_get_status(req->rq_repmsg),
3124                           aa->praa_old_status);
3125
3126                 /*
3127                  * Note: If the replay fails for MDT-MDT recovery, let's
3128                  * abort all of the following requests in the replay
3129                  * and sending list, because MDT-MDT update requests
3130                  * are dependent on each other, see LU-7039
3131                  */
3132                 if (imp->imp_connect_flags_orig & OBD_CONNECT_MDS_MDS) {
3133                         struct ptlrpc_request *free_req;
3134                         struct ptlrpc_request *tmp;
3135
3136                         spin_lock(&imp->imp_lock);
3137                         list_for_each_entry_safe(free_req, tmp,
3138                                                  &imp->imp_replay_list,
3139                                                  rq_replay_list) {
3140                                 ptlrpc_free_request(free_req);
3141                         }
3142
3143                         list_for_each_entry_safe(free_req, tmp,
3144                                                  &imp->imp_committed_list,
3145                                                  rq_replay_list) {
3146                                 ptlrpc_free_request(free_req);
3147                         }
3148
3149                         list_for_each_entry_safe(free_req, tmp,
3150                                                  &imp->imp_delayed_list,
3151                                                  rq_list) {
3152                                 spin_lock(&free_req->rq_lock);
3153                                 free_req->rq_err = 1;
3154                                 free_req->rq_status = -EIO;
3155                                 ptlrpc_client_wake_req(free_req);
3156                                 spin_unlock(&free_req->rq_lock);
3157                         }
3158
3159                         list_for_each_entry_safe(free_req, tmp,
3160                                                  &imp->imp_sending_list,
3161                                                  rq_list) {
3162                                 spin_lock(&free_req->rq_lock);
3163                                 free_req->rq_err = 1;
3164                                 free_req->rq_status = -EIO;
3165                                 ptlrpc_client_wake_req(free_req);
3166                                 spin_unlock(&free_req->rq_lock);
3167                         }
3168                         spin_unlock(&imp->imp_lock);
3169                 }
3170         } else {
3171                 /* Put it back for re-replay. */
3172                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
3173         }
3174
3175         /*
3176          * Errors while replay can set transno to 0, but
3177          * imp_last_replay_transno shouldn't be set to 0 anyway
3178          */
3179         if (req->rq_transno == 0)
3180                 CERROR("Transno is 0 during replay!\n");
3181
3182         /* continue with recovery */
3183         rc = ptlrpc_import_recovery_state_machine(imp);
3184  out:
3185         req->rq_send_state = aa->praa_old_state;
3186
3187         if (rc != 0)
3188                 /* this replay failed, so restart recovery */
3189                 ptlrpc_connect_import(imp);
3190
3191         RETURN(rc);
3192 }
3193
3194 /**
3195  * Prepares and queues request for replay.
3196  * Adds it to ptlrpcd queue for actual sending.
3197  * Returns 0 on success.
3198  */
3199 int ptlrpc_replay_req(struct ptlrpc_request *req)
3200 {
3201         struct ptlrpc_replay_async_args *aa;
3202
3203         ENTRY;
3204
3205         LASSERT(req->rq_import->imp_state == LUSTRE_IMP_REPLAY);
3206
3207         aa = ptlrpc_req_async_args(aa, req);
3208         memset(aa, 0, sizeof(*aa));
3209
3210         /* Prepare request to be resent with ptlrpcd */
3211         aa->praa_old_state = req->rq_send_state;
3212         req->rq_send_state = LUSTRE_IMP_REPLAY;
3213         req->rq_phase = RQ_PHASE_NEW;
3214         req->rq_next_phase = RQ_PHASE_UNDEFINED;
3215         if (req->rq_repmsg)
3216                 aa->praa_old_status = lustre_msg_get_status(req->rq_repmsg);
3217         req->rq_status = 0;
3218         req->rq_interpret_reply = ptlrpc_replay_interpret;
3219         /* Readjust the timeout for current conditions */
3220         ptlrpc_at_set_req_timeout(req);
3221
3222         /* Tell server net_latency to calculate how long to wait for reply. */
3223         lustre_msg_set_service_timeout(req->rq_reqmsg,
3224                                        ptlrpc_at_get_net_latency(req));
3225         DEBUG_REQ(D_HA, req, "REPLAY");
3226
3227         atomic_inc(&req->rq_import->imp_replay_inflight);
3228         spin_lock(&req->rq_lock);
3229         req->rq_early_free_repbuf = 0;
3230         spin_unlock(&req->rq_lock);
3231         ptlrpc_request_addref(req); /* ptlrpcd needs a ref */
3232
3233         ptlrpcd_add_req(req);
3234         RETURN(0);
3235 }
3236
3237 /**
3238  * Aborts all in-flight request on import \a imp sending and delayed lists
3239  */
3240 void ptlrpc_abort_inflight(struct obd_import *imp)
3241 {
3242         struct list_head *tmp, *n;
3243         ENTRY;
3244
3245         /*
3246          * Make sure that no new requests get processed for this import.
3247          * ptlrpc_{queue,set}_wait must (and does) hold imp_lock while testing
3248          * this flag and then putting requests on sending_list or delayed_list.
3249          */
3250         assert_spin_locked(&imp->imp_lock);
3251
3252         /*
3253          * XXX locking?  Maybe we should remove each request with the list
3254          * locked?  Also, how do we know if the requests on the list are
3255          * being freed at this time?
3256          */
3257         list_for_each_safe(tmp, n, &imp->imp_sending_list) {
3258                 struct ptlrpc_request *req = list_entry(tmp,
3259                                                         struct ptlrpc_request,
3260                                                         rq_list);
3261
3262                 DEBUG_REQ(D_RPCTRACE, req, "inflight");
3263
3264                 spin_lock(&req->rq_lock);
3265                 if (req->rq_import_generation < imp->imp_generation) {
3266                         req->rq_err = 1;
3267                         req->rq_status = -EIO;
3268                         ptlrpc_client_wake_req(req);
3269                 }
3270                 spin_unlock(&req->rq_lock);
3271         }
3272
3273         list_for_each_safe(tmp, n, &imp->imp_delayed_list) {
3274                 struct ptlrpc_request *req =
3275                         list_entry(tmp, struct ptlrpc_request, rq_list);
3276
3277                 DEBUG_REQ(D_RPCTRACE, req, "aborting waiting req");
3278
3279                 spin_lock(&req->rq_lock);
3280                 if (req->rq_import_generation < imp->imp_generation) {
3281                         req->rq_err = 1;
3282                         req->rq_status = -EIO;
3283                         ptlrpc_client_wake_req(req);
3284                 }
3285                 spin_unlock(&req->rq_lock);
3286         }
3287
3288         /*
3289          * Last chance to free reqs left on the replay list, but we
3290          * will still leak reqs that haven't committed.
3291          */
3292         if (imp->imp_replayable)
3293                 ptlrpc_free_committed(imp);
3294
3295         EXIT;
3296 }
3297
3298 /**
3299  * Abort all uncompleted requests in request set \a set
3300  */
3301 void ptlrpc_abort_set(struct ptlrpc_request_set *set)
3302 {
3303         struct list_head *tmp, *pos;
3304
3305         LASSERT(set != NULL);
3306
3307         list_for_each_safe(pos, tmp, &set->set_requests) {
3308                 struct ptlrpc_request *req =
3309                         list_entry(pos, struct ptlrpc_request,
3310                                    rq_set_chain);
3311
3312                 spin_lock(&req->rq_lock);
3313                 if (req->rq_phase != RQ_PHASE_RPC) {
3314                         spin_unlock(&req->rq_lock);
3315                         continue;
3316                 }
3317
3318                 req->rq_err = 1;
3319                 req->rq_status = -EINTR;
3320                 ptlrpc_client_wake_req(req);
3321                 spin_unlock(&req->rq_lock);
3322         }
3323 }
3324
3325 /**
3326  * Initialize the XID for the node.  This is common among all requests on
3327  * this node, and only requires the property that it is monotonically
3328  * increasing.  It does not need to be sequential.  Since this is also used
3329  * as the RDMA match bits, it is important that a single client NOT have
3330  * the same match bits for two different in-flight requests, hence we do
3331  * NOT want to have an XID per target or similar.
3332  *
3333  * To avoid an unlikely collision between match bits after a client reboot
3334  * (which would deliver old data into the wrong RDMA buffer) initialize
3335  * the XID based on the current time, assuming a maximum RPC rate of 1M RPC/s.
3336  * If the time is clearly incorrect, we instead use a 62-bit random number.
3337  * In the worst case the random number will overflow 1M RPCs per second in
3338  * 9133 years, or permutations thereof.
3339  */
3340 #define YEAR_2004 (1ULL << 30)
3341 void ptlrpc_init_xid(void)
3342 {
3343         time64_t now = ktime_get_real_seconds();
3344         u64 xid;
3345
3346         if (now < YEAR_2004) {
3347                 get_random_bytes(&xid, sizeof(xid));
3348                 xid >>= 2;
3349                 xid |= (1ULL << 61);
3350         } else {
3351                 xid = (u64)now << 20;
3352         }
3353
3354         /* Need to always be aligned to a power-of-two for mutli-bulk BRW */
3355         BUILD_BUG_ON((PTLRPC_BULK_OPS_COUNT & (PTLRPC_BULK_OPS_COUNT - 1)) !=
3356                      0);
3357         xid &= PTLRPC_BULK_OPS_MASK;
3358         atomic64_set(&ptlrpc_last_xid, xid);
3359 }
3360
3361 /**
3362  * Increase xid and returns resulting new value to the caller.
3363  *
3364  * Multi-bulk BRW RPCs consume multiple XIDs for each bulk transfer, starting
3365  * at the returned xid, up to xid + PTLRPC_BULK_OPS_COUNT - 1. The BRW RPC
3366  * itself uses the last bulk xid needed, so the server can determine the
3367  * the number of bulk transfers from the RPC XID and a bitmask.  The starting
3368  * xid must align to a power-of-two value.
3369  *
3370  * This is assumed to be true due to the initial ptlrpc_last_xid
3371  * value also being initialized to a power-of-two value. LU-1431
3372  */
3373 __u64 ptlrpc_next_xid(void)
3374 {
3375         return atomic64_add_return(PTLRPC_BULK_OPS_COUNT, &ptlrpc_last_xid);
3376 }
3377
3378 /**
3379  * If request has a new allocated XID (new request or EINPROGRESS resend),
3380  * use this XID as matchbits of bulk, otherwise allocate a new matchbits for
3381  * request to ensure previous bulk fails and avoid problems with lost replies
3382  * and therefore several transfers landing into the same buffer from different
3383  * sending attempts.
3384  */
3385 void ptlrpc_set_bulk_mbits(struct ptlrpc_request *req)
3386 {
3387         struct ptlrpc_bulk_desc *bd = req->rq_bulk;
3388
3389         LASSERT(bd != NULL);
3390
3391         /*
3392          * Generate new matchbits for all resend requests, including
3393          * resend replay.
3394          */
3395         if (req->rq_resend) {
3396                 __u64 old_mbits = req->rq_mbits;
3397
3398                 /*
3399                  * First time resend on -EINPROGRESS will generate new xid,
3400                  * so we can actually use the rq_xid as rq_mbits in such case,
3401                  * however, it's bit hard to distinguish such resend with a
3402                  * 'resend for the -EINPROGRESS resend'. To make it simple,
3403                  * we opt to generate mbits for all resend cases.
3404                  */
3405                 if (OCD_HAS_FLAG(&bd->bd_import->imp_connect_data,
3406                                  BULK_MBITS)) {
3407                         req->rq_mbits = ptlrpc_next_xid();
3408                 } else {
3409                         /*
3410                          * Old version transfers rq_xid to peer as
3411                          * matchbits.
3412                          */
3413                         spin_lock(&req->rq_import->imp_lock);
3414                         list_del_init(&req->rq_unreplied_list);
3415                         ptlrpc_assign_next_xid_nolock(req);
3416                         spin_unlock(&req->rq_import->imp_lock);
3417                         req->rq_mbits = req->rq_xid;
3418                 }
3419                 CDEBUG(D_HA, "resend bulk old x%llu new x%llu\n",
3420                        old_mbits, req->rq_mbits);
3421         } else if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
3422                 /* Request being sent first time, use xid as matchbits. */
3423                 if (OCD_HAS_FLAG(&bd->bd_import->imp_connect_data, BULK_MBITS)
3424                     || req->rq_mbits == 0) {
3425                         req->rq_mbits = req->rq_xid;
3426                 } else {
3427                         int total_md = (bd->bd_iov_count + LNET_MAX_IOV - 1) /
3428                                         LNET_MAX_IOV;
3429                         req->rq_mbits -= total_md - 1;
3430                 }
3431         } else {
3432                 /*
3433                  * Replay request, xid and matchbits have already been
3434                  * correctly assigned.
3435                  */
3436                 return;
3437         }
3438
3439         /*
3440          * For multi-bulk RPCs, rq_mbits is the last mbits needed for bulks so
3441          * that server can infer the number of bulks that were prepared,
3442          * see LU-1431
3443          */
3444         req->rq_mbits += ((bd->bd_iov_count + LNET_MAX_IOV - 1) /
3445                           LNET_MAX_IOV) - 1;
3446
3447         /*
3448          * Set rq_xid as rq_mbits to indicate the final bulk for the old
3449          * server which does not support OBD_CONNECT_BULK_MBITS. LU-6808.
3450          *
3451          * It's ok to directly set the rq_xid here, since this xid bump
3452          * won't affect the request position in unreplied list.
3453          */
3454         if (!OCD_HAS_FLAG(&bd->bd_import->imp_connect_data, BULK_MBITS))
3455                 req->rq_xid = req->rq_mbits;
3456 }
3457
3458 /**
3459  * Get a glimpse at what next xid value might have been.
3460  * Returns possible next xid.
3461  */
3462 __u64 ptlrpc_sample_next_xid(void)
3463 {
3464         return atomic64_read(&ptlrpc_last_xid) + PTLRPC_BULK_OPS_COUNT;
3465 }
3466 EXPORT_SYMBOL(ptlrpc_sample_next_xid);
3467
3468 /**
3469  * Functions for operating ptlrpc workers.
3470  *
3471  * A ptlrpc work is a function which will be running inside ptlrpc context.
3472  * The callback shouldn't sleep otherwise it will block that ptlrpcd thread.
3473  *
3474  * 1. after a work is created, it can be used many times, that is:
3475  *         handler = ptlrpcd_alloc_work();
3476  *         ptlrpcd_queue_work();
3477  *
3478  *    queue it again when necessary:
3479  *         ptlrpcd_queue_work();
3480  *         ptlrpcd_destroy_work();
3481  * 2. ptlrpcd_queue_work() can be called by multiple processes meanwhile, but
3482  *    it will only be queued once in any time. Also as its name implies, it may
3483  *    have delay before it really runs by ptlrpcd thread.
3484  */
3485 struct ptlrpc_work_async_args {
3486         int (*cb)(const struct lu_env *, void *);
3487         void *cbdata;
3488 };
3489
3490 static void ptlrpcd_add_work_req(struct ptlrpc_request *req)
3491 {
3492         /* re-initialize the req */
3493         req->rq_timeout         = obd_timeout;
3494         req->rq_sent            = ktime_get_real_seconds();
3495         req->rq_deadline        = req->rq_sent + req->rq_timeout;
3496         req->rq_phase           = RQ_PHASE_INTERPRET;
3497         req->rq_next_phase      = RQ_PHASE_COMPLETE;
3498         req->rq_xid             = ptlrpc_next_xid();
3499         req->rq_import_generation = req->rq_import->imp_generation;
3500
3501         ptlrpcd_add_req(req);
3502 }
3503
3504 static int work_interpreter(const struct lu_env *env,
3505                             struct ptlrpc_request *req, void *args, int rc)
3506 {
3507         struct ptlrpc_work_async_args *arg = args;
3508
3509         LASSERT(ptlrpcd_check_work(req));
3510         LASSERT(arg->cb != NULL);
3511
3512         rc = arg->cb(env, arg->cbdata);
3513
3514         list_del_init(&req->rq_set_chain);
3515         req->rq_set = NULL;
3516
3517         if (atomic_dec_return(&req->rq_refcount) > 1) {
3518                 atomic_set(&req->rq_refcount, 2);
3519                 ptlrpcd_add_work_req(req);
3520         }
3521         return rc;
3522 }
3523
3524 static int worker_format;
3525
3526 static int ptlrpcd_check_work(struct ptlrpc_request *req)
3527 {
3528         return req->rq_pill.rc_fmt == (void *)&worker_format;
3529 }
3530
3531 /**
3532  * Create a work for ptlrpc.
3533  */
3534 void *ptlrpcd_alloc_work(struct obd_import *imp,
3535                          int (*cb)(const struct lu_env *, void *), void *cbdata)
3536 {
3537         struct ptlrpc_request *req = NULL;
3538         struct ptlrpc_work_async_args *args;
3539
3540         ENTRY;
3541         might_sleep();
3542
3543         if (!cb)
3544                 RETURN(ERR_PTR(-EINVAL));
3545
3546         /* copy some code from deprecated fakereq. */
3547         req = ptlrpc_request_cache_alloc(GFP_NOFS);
3548         if (!req) {
3549                 CERROR("ptlrpc: run out of memory!\n");
3550                 RETURN(ERR_PTR(-ENOMEM));
3551         }
3552
3553         ptlrpc_cli_req_init(req);
3554
3555         req->rq_send_state = LUSTRE_IMP_FULL;
3556         req->rq_type = PTL_RPC_MSG_REQUEST;
3557         req->rq_import = class_import_get(imp);
3558         req->rq_interpret_reply = work_interpreter;
3559         /* don't want reply */
3560         req->rq_no_delay = req->rq_no_resend = 1;
3561         req->rq_pill.rc_fmt = (void *)&worker_format;
3562
3563         args = ptlrpc_req_async_args(args, req);
3564         args->cb     = cb;
3565         args->cbdata = cbdata;
3566
3567         RETURN(req);
3568 }
3569 EXPORT_SYMBOL(ptlrpcd_alloc_work);
3570
3571 void ptlrpcd_destroy_work(void *handler)
3572 {
3573         struct ptlrpc_request *req = handler;
3574
3575         if (req)
3576                 ptlrpc_req_finished(req);
3577 }
3578 EXPORT_SYMBOL(ptlrpcd_destroy_work);
3579
3580 int ptlrpcd_queue_work(void *handler)
3581 {
3582         struct ptlrpc_request *req = handler;
3583
3584         /*
3585          * Check if the req is already being queued.
3586          *
3587          * Here comes a trick: it lacks a way of checking if a req is being
3588          * processed reliably in ptlrpc. Here I have to use refcount of req
3589          * for this purpose. This is okay because the caller should use this
3590          * req as opaque data. - Jinshan
3591          */
3592         LASSERT(atomic_read(&req->rq_refcount) > 0);
3593         if (atomic_inc_return(&req->rq_refcount) == 2)
3594                 ptlrpcd_add_work_req(req);
3595         return 0;
3596 }
3597 EXPORT_SYMBOL(ptlrpcd_queue_work);