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