Whamcloud - gitweb
b=21411 Improvement for AT to handle timeout more accurate.
[fs/lustre-release.git] / lustre / ptlrpc / client.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_RPC
38 #ifndef __KERNEL__
39 #include <errno.h>
40 #include <signal.h>
41 #include <liblustre.h>
42 #endif
43
44 #include <obd_support.h>
45 #include <obd_class.h>
46 #include <lustre_lib.h>
47 #include <lustre_ha.h>
48 #include <lustre_import.h>
49 #include <lustre_req_layout.h>
50
51 #include "ptlrpc_internal.h"
52
53 void ptlrpc_init_client(int req_portal, int rep_portal, char *name,
54                         struct ptlrpc_client *cl)
55 {
56         cl->cli_request_portal = req_portal;
57         cl->cli_reply_portal   = rep_portal;
58         cl->cli_name           = name;
59 }
60
61 struct ptlrpc_connection *ptlrpc_uuid_to_connection(struct obd_uuid *uuid)
62 {
63         struct ptlrpc_connection *c;
64         lnet_nid_t                self;
65         lnet_process_id_t         peer;
66         int                       err;
67
68         err = ptlrpc_uuid_to_peer(uuid, &peer, &self);
69         if (err != 0) {
70                 CERROR("cannot find peer %s!\n", uuid->uuid);
71                 return NULL;
72         }
73
74         c = ptlrpc_connection_get(peer, self, uuid);
75         if (c) {
76                 memcpy(c->c_remote_uuid.uuid,
77                        uuid->uuid, sizeof(c->c_remote_uuid.uuid));
78         }
79
80         CDEBUG(D_INFO, "%s -> %p\n", uuid->uuid, c);
81
82         return c;
83 }
84
85 static inline struct ptlrpc_bulk_desc *new_bulk(int npages, int type, int portal)
86 {
87         struct ptlrpc_bulk_desc *desc;
88
89         OBD_ALLOC(desc, offsetof (struct ptlrpc_bulk_desc, bd_iov[npages]));
90         if (!desc)
91                 return NULL;
92
93         cfs_spin_lock_init(&desc->bd_lock);
94         cfs_waitq_init(&desc->bd_waitq);
95         desc->bd_max_iov = npages;
96         desc->bd_iov_count = 0;
97         LNetInvalidateHandle(&desc->bd_md_h);
98         desc->bd_portal = portal;
99         desc->bd_type = type;
100
101         return desc;
102 }
103
104 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_imp(struct ptlrpc_request *req,
105                                               int npages, int type, int portal)
106 {
107         struct obd_import *imp = req->rq_import;
108         struct ptlrpc_bulk_desc *desc;
109
110         ENTRY;
111         LASSERT(type == BULK_PUT_SINK || type == BULK_GET_SOURCE);
112         desc = new_bulk(npages, type, portal);
113         if (desc == NULL)
114                 RETURN(NULL);
115
116         desc->bd_import_generation = req->rq_import_generation;
117         desc->bd_import = class_import_get(imp);
118         desc->bd_req = req;
119
120         desc->bd_cbid.cbid_fn  = client_bulk_callback;
121         desc->bd_cbid.cbid_arg = desc;
122
123         /* This makes req own desc, and free it when she frees herself */
124         req->rq_bulk = desc;
125
126         return desc;
127 }
128
129 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_exp(struct ptlrpc_request *req,
130                                               int npages, int type, int portal)
131 {
132         struct obd_export *exp = req->rq_export;
133         struct ptlrpc_bulk_desc *desc;
134
135         ENTRY;
136         LASSERT(type == BULK_PUT_SOURCE || type == BULK_GET_SINK);
137
138         desc = new_bulk(npages, type, portal);
139         if (desc == NULL)
140                 RETURN(NULL);
141
142         desc->bd_export = class_export_get(exp);
143         desc->bd_req = req;
144
145         desc->bd_cbid.cbid_fn  = server_bulk_callback;
146         desc->bd_cbid.cbid_arg = desc;
147
148         /* NB we don't assign rq_bulk here; server-side requests are
149          * re-used, and the handler frees the bulk desc explicitly. */
150
151         return desc;
152 }
153
154 void ptlrpc_prep_bulk_page(struct ptlrpc_bulk_desc *desc,
155                            cfs_page_t *page, int pageoffset, int len)
156 {
157         LASSERT(desc->bd_iov_count < desc->bd_max_iov);
158         LASSERT(page != NULL);
159         LASSERT(pageoffset >= 0);
160         LASSERT(len > 0);
161         LASSERT(pageoffset + len <= CFS_PAGE_SIZE);
162
163         desc->bd_nob += len;
164
165         ptlrpc_add_bulk_page(desc, page, pageoffset, len);
166 }
167
168 void ptlrpc_free_bulk(struct ptlrpc_bulk_desc *desc)
169 {
170         ENTRY;
171
172         LASSERT(desc != NULL);
173         LASSERT(desc->bd_iov_count != LI_POISON); /* not freed already */
174         LASSERT(!desc->bd_network_rw);         /* network hands off or */
175         LASSERT((desc->bd_export != NULL) ^ (desc->bd_import != NULL));
176
177         sptlrpc_enc_pool_put_pages(desc);
178
179         if (desc->bd_export)
180                 class_export_put(desc->bd_export);
181         else
182                 class_import_put(desc->bd_import);
183
184         OBD_FREE(desc, offsetof(struct ptlrpc_bulk_desc,
185                                 bd_iov[desc->bd_max_iov]));
186         EXIT;
187 }
188
189 /* Set server timelimit for this req */
190 void ptlrpc_at_set_req_timeout(struct ptlrpc_request *req)
191 {
192         __u32 serv_est;
193         int idx;
194         struct imp_at *at;
195
196         LASSERT(req->rq_import);
197
198         if (AT_OFF) {
199                 /* non-AT settings */
200                 req->rq_timeout = req->rq_import->imp_server_timeout ?
201                                   obd_timeout / 2 : obd_timeout;
202         } else {
203                 at = &req->rq_import->imp_at;
204                 idx = import_at_get_index(req->rq_import,
205                                           req->rq_request_portal);
206                 serv_est = at_get(&at->iat_service_estimate[idx]);
207                 req->rq_timeout = at_est2timeout(serv_est);
208         }
209         /* We could get even fancier here, using history to predict increased
210            loading... */
211
212         /* Let the server know what this RPC timeout is by putting it in the
213            reqmsg*/
214         lustre_msg_set_timeout(req->rq_reqmsg, req->rq_timeout);
215 }
216
217 /* Adjust max service estimate based on server value */
218 static void ptlrpc_at_adj_service(struct ptlrpc_request *req,
219                                   unsigned int serv_est)
220 {
221         int idx;
222         unsigned int oldse;
223         struct imp_at *at;
224
225         LASSERT(req->rq_import);
226         at = &req->rq_import->imp_at;
227
228         idx = import_at_get_index(req->rq_import, req->rq_request_portal);
229         /* max service estimates are tracked on the server side,
230            so just keep minimal history here */
231         oldse = at_measured(&at->iat_service_estimate[idx], serv_est);
232         if (oldse != 0)
233                 CDEBUG(D_ADAPTTO, "The RPC service estimate for %s ptl %d "
234                        "has changed from %d to %d\n",
235                        req->rq_import->imp_obd->obd_name,req->rq_request_portal,
236                        oldse, at_get(&at->iat_service_estimate[idx]));
237 }
238
239 /* Expected network latency per remote node (secs) */
240 int ptlrpc_at_get_net_latency(struct ptlrpc_request *req)
241 {
242         return AT_OFF ? 0 : at_get(&req->rq_import->imp_at.iat_net_latency);
243 }
244
245 /* Adjust expected network latency */
246 static void ptlrpc_at_adj_net_latency(struct ptlrpc_request *req,
247                                       unsigned int service_time)
248 {
249         unsigned int nl, oldnl;
250         struct imp_at *at;
251         time_t now = cfs_time_current_sec();
252
253         LASSERT(req->rq_import);
254         at = &req->rq_import->imp_at;
255
256         /* Network latency is total time less server processing time */
257         nl = max_t(int, now - req->rq_sent - service_time, 0) +1/*st rounding*/;
258         if (service_time > now - req->rq_sent + 3 /* bz16408 */)
259                 CWARN("Reported service time %u > total measured time "
260                       CFS_DURATION_T"\n", service_time,
261                       cfs_time_sub(now, req->rq_sent));
262
263         oldnl = at_measured(&at->iat_net_latency, nl);
264         if (oldnl != 0)
265                 CDEBUG(D_ADAPTTO, "The network latency for %s (nid %s) "
266                        "has changed from %d to %d\n",
267                        req->rq_import->imp_obd->obd_name,
268                        obd_uuid2str(
269                                &req->rq_import->imp_connection->c_remote_uuid),
270                        oldnl, at_get(&at->iat_net_latency));
271 }
272
273 static int unpack_reply(struct ptlrpc_request *req)
274 {
275         int rc;
276
277         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
278                 rc = ptlrpc_unpack_rep_msg(req, req->rq_replen);
279                 if (rc) {
280                         DEBUG_REQ(D_ERROR, req, "unpack_rep failed: %d", rc);
281                         return(-EPROTO);
282                 }
283         }
284
285         rc = lustre_unpack_rep_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
286         if (rc) {
287                 DEBUG_REQ(D_ERROR, req, "unpack ptlrpc body failed: %d", rc);
288                 return(-EPROTO);
289         }
290         return 0;
291 }
292
293 /*
294  * Handle an early reply message, called with the rq_lock held.
295  * If anything goes wrong just ignore it - same as if it never happened
296  */
297 static int ptlrpc_at_recv_early_reply(struct ptlrpc_request *req)
298 {
299         struct ptlrpc_request *early_req;
300         time_t                 olddl;
301         int                    rc;
302         ENTRY;
303
304         req->rq_early = 0;
305         cfs_spin_unlock(&req->rq_lock);
306
307         rc = sptlrpc_cli_unwrap_early_reply(req, &early_req);
308         if (rc) {
309                 cfs_spin_lock(&req->rq_lock);
310                 RETURN(rc);
311         }
312
313         rc = unpack_reply(early_req);
314         if (rc == 0) {
315                 /* Expecting to increase the service time estimate here */
316                 ptlrpc_at_adj_service(req,
317                         lustre_msg_get_timeout(early_req->rq_repmsg));
318                 ptlrpc_at_adj_net_latency(req,
319                         lustre_msg_get_service_time(early_req->rq_repmsg));
320         }
321
322         sptlrpc_cli_finish_early_reply(early_req);
323
324         cfs_spin_lock(&req->rq_lock);
325
326         if (rc == 0) {
327                 /* Adjust the local timeout for this req */
328                 ptlrpc_at_set_req_timeout(req);
329
330                 olddl = req->rq_deadline;
331                 /* server assumes it now has rq_timeout from when it sent the
332                    early reply, so client should give it at least that long. */
333                 req->rq_deadline = cfs_time_current_sec() + req->rq_timeout +
334                             ptlrpc_at_get_net_latency(req);
335
336                 DEBUG_REQ(D_ADAPTTO, req,
337                           "Early reply #%d, new deadline in "CFS_DURATION_T"s "
338                           "("CFS_DURATION_T"s)", req->rq_early_count,
339                           cfs_time_sub(req->rq_deadline,
340                                        cfs_time_current_sec()),
341                           cfs_time_sub(req->rq_deadline, olddl));
342         }
343
344         RETURN(rc);
345 }
346
347 void ptlrpc_free_rq_pool(struct ptlrpc_request_pool *pool)
348 {
349         cfs_list_t *l, *tmp;
350         struct ptlrpc_request *req;
351
352         LASSERT(pool != NULL);
353
354         cfs_spin_lock(&pool->prp_lock);
355         cfs_list_for_each_safe(l, tmp, &pool->prp_req_list) {
356                 req = cfs_list_entry(l, struct ptlrpc_request, rq_list);
357                 cfs_list_del(&req->rq_list);
358                 LASSERT(req->rq_reqbuf);
359                 LASSERT(req->rq_reqbuf_len == pool->prp_rq_size);
360                 OBD_FREE(req->rq_reqbuf, pool->prp_rq_size);
361                 OBD_FREE(req, sizeof(*req));
362         }
363         cfs_spin_unlock(&pool->prp_lock);
364         OBD_FREE(pool, sizeof(*pool));
365 }
366
367 void ptlrpc_add_rqs_to_pool(struct ptlrpc_request_pool *pool, int num_rq)
368 {
369         int i;
370         int size = 1;
371
372         while (size < pool->prp_rq_size + SPTLRPC_MAX_PAYLOAD)
373                 size <<= 1;
374
375         LASSERTF(cfs_list_empty(&pool->prp_req_list) ||
376                  size == pool->prp_rq_size,
377                  "Trying to change pool size with nonempty pool "
378                  "from %d to %d bytes\n", pool->prp_rq_size, size);
379
380         cfs_spin_lock(&pool->prp_lock);
381         pool->prp_rq_size = size;
382         for (i = 0; i < num_rq; i++) {
383                 struct ptlrpc_request *req;
384                 struct lustre_msg *msg;
385
386                 cfs_spin_unlock(&pool->prp_lock);
387                 OBD_ALLOC(req, sizeof(struct ptlrpc_request));
388                 if (!req)
389                         return;
390                 OBD_ALLOC_GFP(msg, size, CFS_ALLOC_STD);
391                 if (!msg) {
392                         OBD_FREE(req, sizeof(struct ptlrpc_request));
393                         return;
394                 }
395                 req->rq_reqbuf = msg;
396                 req->rq_reqbuf_len = size;
397                 req->rq_pool = pool;
398                 cfs_spin_lock(&pool->prp_lock);
399                 cfs_list_add_tail(&req->rq_list, &pool->prp_req_list);
400         }
401         cfs_spin_unlock(&pool->prp_lock);
402         return;
403 }
404
405 struct ptlrpc_request_pool *
406 ptlrpc_init_rq_pool(int num_rq, int msgsize,
407                     void (*populate_pool)(struct ptlrpc_request_pool *, int))
408 {
409         struct ptlrpc_request_pool *pool;
410
411         OBD_ALLOC(pool, sizeof (struct ptlrpc_request_pool));
412         if (!pool)
413                 return NULL;
414
415         /* Request next power of two for the allocation, because internally
416            kernel would do exactly this */
417
418         cfs_spin_lock_init(&pool->prp_lock);
419         CFS_INIT_LIST_HEAD(&pool->prp_req_list);
420         pool->prp_rq_size = msgsize;
421         pool->prp_populate = populate_pool;
422
423         populate_pool(pool, num_rq);
424
425         if (cfs_list_empty(&pool->prp_req_list)) {
426                 /* have not allocated a single request for the pool */
427                 OBD_FREE(pool, sizeof (struct ptlrpc_request_pool));
428                 pool = NULL;
429         }
430         return pool;
431 }
432
433 static struct ptlrpc_request *
434 ptlrpc_prep_req_from_pool(struct ptlrpc_request_pool *pool)
435 {
436         struct ptlrpc_request *request;
437         struct lustre_msg *reqbuf;
438
439         if (!pool)
440                 return NULL;
441
442         cfs_spin_lock(&pool->prp_lock);
443
444         /* See if we have anything in a pool, and bail out if nothing,
445          * in writeout path, where this matters, this is safe to do, because
446          * nothing is lost in this case, and when some in-flight requests
447          * complete, this code will be called again. */
448         if (unlikely(cfs_list_empty(&pool->prp_req_list))) {
449                 cfs_spin_unlock(&pool->prp_lock);
450                 return NULL;
451         }
452
453         request = cfs_list_entry(pool->prp_req_list.next, struct ptlrpc_request,
454                                  rq_list);
455         cfs_list_del_init(&request->rq_list);
456         cfs_spin_unlock(&pool->prp_lock);
457
458         LASSERT(request->rq_reqbuf);
459         LASSERT(request->rq_pool);
460
461         reqbuf = request->rq_reqbuf;
462         memset(request, 0, sizeof(*request));
463         request->rq_reqbuf = reqbuf;
464         request->rq_reqbuf_len = pool->prp_rq_size;
465         request->rq_pool = pool;
466
467         return request;
468 }
469
470 static void __ptlrpc_free_req_to_pool(struct ptlrpc_request *request)
471 {
472         struct ptlrpc_request_pool *pool = request->rq_pool;
473
474         cfs_spin_lock(&pool->prp_lock);
475         LASSERT(cfs_list_empty(&request->rq_list));
476         LASSERT(!request->rq_receiving_reply);
477         cfs_list_add_tail(&request->rq_list, &pool->prp_req_list);
478         cfs_spin_unlock(&pool->prp_lock);
479 }
480
481 static int __ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
482                                       __u32 version, int opcode,
483                                       int count, __u32 *lengths, char **bufs,
484                                       struct ptlrpc_cli_ctx *ctx)
485 {
486         struct obd_import  *imp = request->rq_import;
487         int                 rc;
488         ENTRY;
489
490         if (unlikely(ctx))
491                 request->rq_cli_ctx = sptlrpc_cli_ctx_get(ctx);
492         else {
493                 rc = sptlrpc_req_get_ctx(request);
494                 if (rc)
495                         GOTO(out_free, rc);
496         }
497
498         sptlrpc_req_set_flavor(request, opcode);
499
500         rc = lustre_pack_request(request, imp->imp_msg_magic, count,
501                                  lengths, bufs);
502         if (rc) {
503                 LASSERT(!request->rq_pool);
504                 GOTO(out_ctx, rc);
505         }
506
507         lustre_msg_add_version(request->rq_reqmsg, version);
508         request->rq_send_state = LUSTRE_IMP_FULL;
509         request->rq_type = PTL_RPC_MSG_REQUEST;
510         request->rq_export = NULL;
511
512         request->rq_req_cbid.cbid_fn  = request_out_callback;
513         request->rq_req_cbid.cbid_arg = request;
514
515         request->rq_reply_cbid.cbid_fn  = reply_in_callback;
516         request->rq_reply_cbid.cbid_arg = request;
517
518         request->rq_reply_deadline = 0;
519         request->rq_phase = RQ_PHASE_NEW;
520         request->rq_next_phase = RQ_PHASE_UNDEFINED;
521
522         request->rq_request_portal = imp->imp_client->cli_request_portal;
523         request->rq_reply_portal = imp->imp_client->cli_reply_portal;
524
525         ptlrpc_at_set_req_timeout(request);
526
527         cfs_spin_lock_init(&request->rq_lock);
528         CFS_INIT_LIST_HEAD(&request->rq_list);
529         CFS_INIT_LIST_HEAD(&request->rq_timed_list);
530         CFS_INIT_LIST_HEAD(&request->rq_replay_list);
531         CFS_INIT_LIST_HEAD(&request->rq_ctx_chain);
532         CFS_INIT_LIST_HEAD(&request->rq_set_chain);
533         CFS_INIT_LIST_HEAD(&request->rq_history_list);
534         CFS_INIT_LIST_HEAD(&request->rq_exp_list);
535         cfs_waitq_init(&request->rq_reply_waitq);
536         request->rq_xid = ptlrpc_next_xid();
537         cfs_atomic_set(&request->rq_refcount, 1);
538
539         lustre_msg_set_opc(request->rq_reqmsg, opcode);
540
541         RETURN(0);
542 out_ctx:
543         sptlrpc_cli_ctx_put(request->rq_cli_ctx, 1);
544 out_free:
545         class_import_put(imp);
546         return rc;
547 }
548
549 int ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
550                              __u32 version, int opcode, char **bufs,
551                              struct ptlrpc_cli_ctx *ctx)
552 {
553         int count;
554
555         count = req_capsule_filled_sizes(&request->rq_pill, RCL_CLIENT);
556         return __ptlrpc_request_bufs_pack(request, version, opcode, count,
557                                           request->rq_pill.rc_area[RCL_CLIENT],
558                                           bufs, ctx);
559 }
560 EXPORT_SYMBOL(ptlrpc_request_bufs_pack);
561
562 int ptlrpc_request_pack(struct ptlrpc_request *request,
563                         __u32 version, int opcode)
564 {
565         return ptlrpc_request_bufs_pack(request, version, opcode, NULL, NULL);
566 }
567
568 static inline
569 struct ptlrpc_request *__ptlrpc_request_alloc(struct obd_import *imp,
570                                               struct ptlrpc_request_pool *pool)
571 {
572         struct ptlrpc_request *request = NULL;
573
574         if (pool)
575                 request = ptlrpc_prep_req_from_pool(pool);
576
577         if (!request)
578                 OBD_ALLOC_PTR(request);
579
580         if (request) {
581                 LASSERTF((unsigned long)imp > 0x1000, "%p", imp);
582                 LASSERT(imp != LP_POISON);
583                 LASSERTF((unsigned long)imp->imp_client > 0x1000, "%p",
584                         imp->imp_client);
585                 LASSERT(imp->imp_client != LP_POISON);
586
587                 request->rq_import = class_import_get(imp);
588         } else {
589                 CERROR("request allocation out of memory\n");
590         }
591
592         return request;
593 }
594
595 static struct ptlrpc_request *
596 ptlrpc_request_alloc_internal(struct obd_import *imp,
597                               struct ptlrpc_request_pool * pool,
598                               const struct req_format *format)
599 {
600         struct ptlrpc_request *request;
601
602         request = __ptlrpc_request_alloc(imp, pool);
603         if (request == NULL)
604                 return NULL;
605
606         req_capsule_init(&request->rq_pill, request, RCL_CLIENT);
607         req_capsule_set(&request->rq_pill, format);
608         return request;
609 }
610
611 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
612                                             const struct req_format *format)
613 {
614         return ptlrpc_request_alloc_internal(imp, NULL, format);
615 }
616
617 struct ptlrpc_request *ptlrpc_request_alloc_pool(struct obd_import *imp,
618                                             struct ptlrpc_request_pool * pool,
619                                             const struct req_format *format)
620 {
621         return ptlrpc_request_alloc_internal(imp, pool, format);
622 }
623
624 void ptlrpc_request_free(struct ptlrpc_request *request)
625 {
626         if (request->rq_pool)
627                 __ptlrpc_free_req_to_pool(request);
628         else
629                 OBD_FREE_PTR(request);
630 }
631
632 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *imp,
633                                                 const struct req_format *format,
634                                                 __u32 version, int opcode)
635 {
636         struct ptlrpc_request *req = ptlrpc_request_alloc(imp, format);
637         int                    rc;
638
639         if (req) {
640                 rc = ptlrpc_request_pack(req, version, opcode);
641                 if (rc) {
642                         ptlrpc_request_free(req);
643                         req = NULL;
644                 }
645         }
646         return req;
647 }
648
649 struct ptlrpc_request *
650 ptlrpc_prep_req_pool(struct obd_import *imp,
651                      __u32 version, int opcode,
652                      int count, __u32 *lengths, char **bufs,
653                      struct ptlrpc_request_pool *pool)
654 {
655         struct ptlrpc_request *request;
656         int                    rc;
657
658         request = __ptlrpc_request_alloc(imp, pool);
659         if (!request)
660                 return NULL;
661
662         rc = __ptlrpc_request_bufs_pack(request, version, opcode, count,
663                                         lengths, bufs, NULL);
664         if (rc) {
665                 ptlrpc_request_free(request);
666                 request = NULL;
667         }
668         return request;
669 }
670
671 struct ptlrpc_request *
672 ptlrpc_prep_req(struct obd_import *imp, __u32 version, int opcode, int count,
673                 __u32 *lengths, char **bufs)
674 {
675         return ptlrpc_prep_req_pool(imp, version, opcode, count, lengths, bufs,
676                                     NULL);
677 }
678
679 struct ptlrpc_request *ptlrpc_prep_fakereq(struct obd_import *imp,
680                                            unsigned int timeout,
681                                            ptlrpc_interpterer_t interpreter)
682 {
683         struct ptlrpc_request *request = NULL;
684         ENTRY;
685
686         OBD_ALLOC(request, sizeof(*request));
687         if (!request) {
688                 CERROR("request allocation out of memory\n");
689                 RETURN(NULL);
690         }
691
692         request->rq_send_state = LUSTRE_IMP_FULL;
693         request->rq_type = PTL_RPC_MSG_REQUEST;
694         request->rq_import = class_import_get(imp);
695         request->rq_export = NULL;
696         request->rq_import_generation = imp->imp_generation;
697
698         request->rq_timeout = timeout;
699         request->rq_sent = cfs_time_current_sec();
700         request->rq_deadline = request->rq_sent + timeout;
701         request->rq_reply_deadline = request->rq_deadline;
702         request->rq_interpret_reply = interpreter;
703         request->rq_phase = RQ_PHASE_RPC;
704         request->rq_next_phase = RQ_PHASE_INTERPRET;
705         /* don't want reply */
706         request->rq_receiving_reply = 0;
707         request->rq_must_unlink = 0;
708         request->rq_no_delay = request->rq_no_resend = 1;
709         request->rq_fake = 1;
710
711         cfs_spin_lock_init(&request->rq_lock);
712         CFS_INIT_LIST_HEAD(&request->rq_list);
713         CFS_INIT_LIST_HEAD(&request->rq_replay_list);
714         CFS_INIT_LIST_HEAD(&request->rq_set_chain);
715         CFS_INIT_LIST_HEAD(&request->rq_history_list);
716         CFS_INIT_LIST_HEAD(&request->rq_exp_list);
717         cfs_waitq_init(&request->rq_reply_waitq);
718
719         request->rq_xid = ptlrpc_next_xid();
720         cfs_atomic_set(&request->rq_refcount, 1);
721
722         RETURN(request);
723 }
724
725 void ptlrpc_fakereq_finished(struct ptlrpc_request *req)
726 {
727         /* if we kill request before timeout - need adjust counter */
728         if (req->rq_phase == RQ_PHASE_RPC) {
729                 struct ptlrpc_request_set *set = req->rq_set;
730
731                 if (set)
732                         set->set_remaining --;
733         }
734
735         ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
736         cfs_list_del_init(&req->rq_list);
737 }
738
739
740 struct ptlrpc_request_set *ptlrpc_prep_set(void)
741 {
742         struct ptlrpc_request_set *set;
743
744         ENTRY;
745         OBD_ALLOC(set, sizeof *set);
746         if (!set)
747                 RETURN(NULL);
748         CFS_INIT_LIST_HEAD(&set->set_requests);
749         cfs_waitq_init(&set->set_waitq);
750         set->set_remaining = 0;
751         cfs_spin_lock_init(&set->set_new_req_lock);
752         CFS_INIT_LIST_HEAD(&set->set_new_requests);
753         CFS_INIT_LIST_HEAD(&set->set_cblist);
754
755         RETURN(set);
756 }
757
758 /* Finish with this set; opposite of prep_set. */
759 void ptlrpc_set_destroy(struct ptlrpc_request_set *set)
760 {
761         cfs_list_t       *tmp;
762         cfs_list_t       *next;
763         int               expected_phase;
764         int               n = 0;
765         ENTRY;
766
767         /* Requests on the set should either all be completed, or all be new */
768         expected_phase = (set->set_remaining == 0) ?
769                          RQ_PHASE_COMPLETE : RQ_PHASE_NEW;
770         cfs_list_for_each (tmp, &set->set_requests) {
771                 struct ptlrpc_request *req =
772                         cfs_list_entry(tmp, struct ptlrpc_request,
773                                        rq_set_chain);
774
775                 LASSERT(req->rq_phase == expected_phase);
776                 n++;
777         }
778
779         LASSERTF(set->set_remaining == 0 || set->set_remaining == n, "%d / %d\n",
780                  set->set_remaining, n);
781
782         cfs_list_for_each_safe(tmp, next, &set->set_requests) {
783                 struct ptlrpc_request *req =
784                         cfs_list_entry(tmp, struct ptlrpc_request,
785                                        rq_set_chain);
786                 cfs_list_del_init(&req->rq_set_chain);
787
788                 LASSERT(req->rq_phase == expected_phase);
789
790                 if (req->rq_phase == RQ_PHASE_NEW) {
791                         ptlrpc_req_interpret(NULL, req, -EBADR);
792                         set->set_remaining--;
793                 }
794
795                 req->rq_set = NULL;
796                 ptlrpc_req_finished (req);
797         }
798
799         LASSERT(set->set_remaining == 0);
800
801         OBD_FREE(set, sizeof(*set));
802         EXIT;
803 }
804
805 int ptlrpc_set_add_cb(struct ptlrpc_request_set *set,
806                       set_interpreter_func fn, void *data)
807 {
808         struct ptlrpc_set_cbdata *cbdata;
809
810         OBD_ALLOC_PTR(cbdata);
811         if (cbdata == NULL)
812                 RETURN(-ENOMEM);
813
814         cbdata->psc_interpret = fn;
815         cbdata->psc_data = data;
816         cfs_list_add_tail(&cbdata->psc_item, &set->set_cblist);
817
818         RETURN(0);
819 }
820
821 void ptlrpc_set_add_req(struct ptlrpc_request_set *set,
822                         struct ptlrpc_request *req)
823 {
824         /* The set takes over the caller's request reference */
825         cfs_list_add_tail(&req->rq_set_chain, &set->set_requests);
826         req->rq_set = set;
827         set->set_remaining++;
828 }
829
830 /**
831  * Lock so many callers can add things, the context that owns the set
832  * is supposed to notice these and move them into the set proper.
833  */
834 int ptlrpc_set_add_new_req(struct ptlrpcd_ctl *pc,
835                            struct ptlrpc_request *req)
836 {
837         struct ptlrpc_request_set *set = pc->pc_set;
838
839         /*
840          * Let caller know that we stopped and will not handle this request.
841          * It needs to take care itself of request.
842          */
843         if (cfs_test_bit(LIOD_STOP, &pc->pc_flags))
844                 return -EALREADY;
845
846         cfs_spin_lock(&set->set_new_req_lock);
847         /*
848          * The set takes over the caller's request reference.
849          */
850         cfs_list_add_tail(&req->rq_set_chain, &set->set_new_requests);
851         req->rq_set = set;
852         cfs_spin_unlock(&set->set_new_req_lock);
853
854         cfs_waitq_signal(&set->set_waitq);
855         return 0;
856 }
857
858 /*
859  * Based on the current state of the import, determine if the request
860  * can be sent, is an error, or should be delayed.
861  *
862  * Returns true if this request should be delayed. If false, and
863  * *status is set, then the request can not be sent and *status is the
864  * error code.  If false and status is 0, then request can be sent.
865  *
866  * The imp->imp_lock must be held.
867  */
868 static int ptlrpc_import_delay_req(struct obd_import *imp,
869                                    struct ptlrpc_request *req, int *status)
870 {
871         int delay = 0;
872         ENTRY;
873
874         LASSERT (status != NULL);
875         *status = 0;
876
877         if (req->rq_ctx_init || req->rq_ctx_fini) {
878                 /* always allow ctx init/fini rpc go through */
879         } else if (imp->imp_state == LUSTRE_IMP_NEW) {
880                 DEBUG_REQ(D_ERROR, req, "Uninitialized import.");
881                 *status = -EIO;
882                 LBUG();
883         } else if (imp->imp_state == LUSTRE_IMP_CLOSED) {
884                 DEBUG_REQ(D_ERROR, req, "IMP_CLOSED ");
885                 *status = -EIO;
886         } else if (req->rq_send_state == LUSTRE_IMP_CONNECTING &&
887                    imp->imp_state == LUSTRE_IMP_CONNECTING) {
888                 /* allow CONNECT even if import is invalid */ ;
889                 if (cfs_atomic_read(&imp->imp_inval_count) != 0) {
890                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
891                         *status = -EIO;
892                 }
893         } else if ((imp->imp_invalid && (!imp->imp_recon_bk)) ||
894                                          imp->imp_obd->obd_no_recov) {
895                 /* If the import has been invalidated (such as by an OST
896                  * failure), and if the import(MGC) tried all of its connection
897                  * list (Bug 13464), the request must fail with -ESHUTDOWN.
898                  * This indicates the requests should be discarded; an -EIO
899                  * may result in a resend of the request. */
900                 if (!imp->imp_deactive)
901                           DEBUG_REQ(D_ERROR, req, "IMP_INVALID");
902                 *status = -ESHUTDOWN; /* bz 12940 */
903         } else if (req->rq_import_generation != imp->imp_generation) {
904                 DEBUG_REQ(D_ERROR, req, "req wrong generation:");
905                 *status = -EIO;
906         } else if (req->rq_send_state != imp->imp_state) {
907                 /* invalidate in progress - any requests should be drop */
908                 if (cfs_atomic_read(&imp->imp_inval_count) != 0) {
909                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
910                         *status = -EIO;
911                 } else if (imp->imp_dlm_fake || req->rq_no_delay) {
912                         *status = -EWOULDBLOCK;
913                 } else {
914                         delay = 1;
915                 }
916         }
917
918         RETURN(delay);
919 }
920
921 /* Conditionally suppress specific console messages */
922 static int ptlrpc_console_allow(struct ptlrpc_request *req)
923 {
924         __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
925         int err;
926
927         /* Suppress particular reconnect errors which are to be expected.  No
928          * errors are suppressed for the initial connection on an import */
929         if ((lustre_handle_is_used(&req->rq_import->imp_remote_handle)) &&
930             (opc == OST_CONNECT || opc == MDS_CONNECT || opc == MGS_CONNECT)) {
931
932                 /* Suppress timed out reconnect requests */
933                 if (req->rq_timedout)
934                         return 0;
935
936                 /* Suppress unavailable/again reconnect requests */
937                 err = lustre_msg_get_status(req->rq_repmsg);
938                 if (err == -ENODEV || err == -EAGAIN)
939                         return 0;
940         }
941
942         return 1;
943 }
944
945 static int ptlrpc_check_status(struct ptlrpc_request *req)
946 {
947         int err;
948         ENTRY;
949
950         err = lustre_msg_get_status(req->rq_repmsg);
951         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
952                 struct obd_import *imp = req->rq_import;
953                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
954                 LCONSOLE_ERROR_MSG(0x011,"an error occurred while communicating"
955                                 " with %s. The %s operation failed with %d\n",
956                                 libcfs_nid2str(imp->imp_connection->c_peer.nid),
957                                 ll_opcode2str(opc), err);
958                 RETURN(err < 0 ? err : -EINVAL);
959         }
960
961         if (err < 0) {
962                 DEBUG_REQ(D_INFO, req, "status is %d", err);
963         } else if (err > 0) {
964                 /* XXX: translate this error from net to host */
965                 DEBUG_REQ(D_INFO, req, "status is %d", err);
966         }
967
968         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
969                 struct obd_import *imp = req->rq_import;
970                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
971
972                 if (ptlrpc_console_allow(req))
973                         LCONSOLE_ERROR_MSG(0x011,"an error occurred while "
974                                            "communicating with %s. The %s "
975                                            "operation failed with %d\n",
976                                            libcfs_nid2str(
977                                            imp->imp_connection->c_peer.nid),
978                                            ll_opcode2str(opc), err);
979
980                 RETURN(err < 0 ? err : -EINVAL);
981         }
982
983         RETURN(err);
984 }
985
986 /**
987  * save pre-versions for replay
988  */
989 static void ptlrpc_save_versions(struct ptlrpc_request *req)
990 {
991         struct lustre_msg *repmsg = req->rq_repmsg;
992         struct lustre_msg *reqmsg = req->rq_reqmsg;
993         __u64 *versions = lustre_msg_get_versions(repmsg);
994         ENTRY;
995
996         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
997                 return;
998
999         LASSERT(versions);
1000         lustre_msg_set_versions(reqmsg, versions);
1001         CDEBUG(D_INFO, "Client save versions ["LPX64"/"LPX64"]\n",
1002                versions[0], versions[1]);
1003
1004         EXIT;
1005 }
1006
1007 /**
1008  * Callback function called when client receives RPC reply for \a req.
1009  */
1010 static int after_reply(struct ptlrpc_request *req)
1011 {
1012         struct obd_import *imp = req->rq_import;
1013         struct obd_device *obd = req->rq_import->imp_obd;
1014         int rc;
1015         struct timeval work_start;
1016         long timediff;
1017         ENTRY;
1018
1019         LASSERT(obd != NULL);
1020         /* repbuf must be unlinked */
1021         LASSERT(!req->rq_receiving_reply && !req->rq_must_unlink);
1022
1023         if (req->rq_reply_truncate) {
1024                 if (req->rq_no_resend) {
1025                         DEBUG_REQ(D_ERROR, req, "reply buffer overflow,"
1026                                   " expected: %d, actual size: %d",
1027                                   req->rq_nob_received, req->rq_repbuf_len);
1028                         RETURN(-EOVERFLOW);
1029                 }
1030
1031                 sptlrpc_cli_free_repbuf(req);
1032                 /* Pass the required reply buffer size (include
1033                  * space for early reply).
1034                  * NB: no need to roundup because alloc_repbuf
1035                  * will roundup it */
1036                 req->rq_replen       = req->rq_nob_received;
1037                 req->rq_nob_received = 0;
1038                 req->rq_resend       = 1;
1039                 RETURN(0);
1040         }
1041
1042         /*
1043          * NB Until this point, the whole of the incoming message,
1044          * including buflens, status etc is in the sender's byte order.
1045          */
1046         rc = sptlrpc_cli_unwrap_reply(req);
1047         if (rc) {
1048                 DEBUG_REQ(D_ERROR, req, "unwrap reply failed (%d):", rc);
1049                 RETURN(rc);
1050         }
1051
1052         /*
1053          * Security layer unwrap might ask resend this request.
1054          */
1055         if (req->rq_resend)
1056                 RETURN(0);
1057
1058         rc = unpack_reply(req);
1059         if (rc)
1060                 RETURN(rc);
1061
1062         cfs_gettimeofday(&work_start);
1063         timediff = cfs_timeval_sub(&work_start, &req->rq_arrival_time, NULL);
1064         if (obd->obd_svc_stats != NULL) {
1065                 lprocfs_counter_add(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR,
1066                                     timediff);
1067                 ptlrpc_lprocfs_rpc_sent(req, timediff);
1068         }
1069
1070         if (lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_REPLY &&
1071             lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_ERR) {
1072                 DEBUG_REQ(D_ERROR, req, "invalid packet received (type=%u)",
1073                           lustre_msg_get_type(req->rq_repmsg));
1074                 RETURN(-EPROTO);
1075         }
1076
1077         if (lustre_msg_get_opc(req->rq_reqmsg) != OBD_PING)
1078                 OBD_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_PAUSE_REP, obd_fail_val);
1079         ptlrpc_at_adj_service(req, lustre_msg_get_timeout(req->rq_repmsg));
1080         ptlrpc_at_adj_net_latency(req,
1081                                   lustre_msg_get_service_time(req->rq_repmsg));
1082
1083         rc = ptlrpc_check_status(req);
1084         imp->imp_connect_error = rc;
1085
1086         if (rc) {
1087                 /*
1088                  * Either we've been evicted, or the server has failed for
1089                  * some reason. Try to reconnect, and if that fails, punt to
1090                  * the upcall.
1091                  */
1092                 if (ll_rpc_recoverable_error(rc)) {
1093                         if (req->rq_send_state != LUSTRE_IMP_FULL ||
1094                             imp->imp_obd->obd_no_recov || imp->imp_dlm_fake) {
1095                                 RETURN(rc);
1096                         }
1097                         ptlrpc_request_handle_notconn(req);
1098                         RETURN(rc);
1099                 }
1100         } else {
1101                 /*
1102                  * Let's look if server sent slv. Do it only for RPC with
1103                  * rc == 0.
1104                  */
1105                 ldlm_cli_update_pool(req);
1106         }
1107
1108         /*
1109          * Store transno in reqmsg for replay.
1110          */
1111         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
1112                 req->rq_transno = lustre_msg_get_transno(req->rq_repmsg);
1113                 lustre_msg_set_transno(req->rq_reqmsg, req->rq_transno);
1114         }
1115
1116         if (imp->imp_replayable) {
1117                 cfs_spin_lock(&imp->imp_lock);
1118                 /*
1119                  * No point in adding already-committed requests to the replay
1120                  * list, we will just remove them immediately. b=9829
1121                  */
1122                 if (req->rq_transno != 0 &&
1123                     (req->rq_transno >
1124                      lustre_msg_get_last_committed(req->rq_repmsg) ||
1125                      req->rq_replay)) {
1126                         /** version recovery */
1127                         ptlrpc_save_versions(req);
1128                         ptlrpc_retain_replayable_request(req, imp);
1129                 } else if (req->rq_commit_cb != NULL) {
1130                         cfs_spin_unlock(&imp->imp_lock);
1131                         req->rq_commit_cb(req);
1132                         cfs_spin_lock(&imp->imp_lock);
1133                 }
1134
1135                 /*
1136                  * Replay-enabled imports return commit-status information.
1137                  */
1138                 if (lustre_msg_get_last_committed(req->rq_repmsg)) {
1139                         imp->imp_peer_committed_transno =
1140                                 lustre_msg_get_last_committed(req->rq_repmsg);
1141                 }
1142                 ptlrpc_free_committed(imp);
1143                 cfs_spin_unlock(&imp->imp_lock);
1144         }
1145
1146         RETURN(rc);
1147 }
1148
1149 static int ptlrpc_send_new_req(struct ptlrpc_request *req)
1150 {
1151         struct obd_import     *imp;
1152         int rc;
1153         ENTRY;
1154
1155         LASSERT(req->rq_phase == RQ_PHASE_NEW);
1156         if (req->rq_sent && (req->rq_sent > cfs_time_current_sec()))
1157                 RETURN (0);
1158
1159         ptlrpc_rqphase_move(req, RQ_PHASE_RPC);
1160
1161         imp = req->rq_import;
1162         cfs_spin_lock(&imp->imp_lock);
1163
1164         req->rq_import_generation = imp->imp_generation;
1165
1166         if (ptlrpc_import_delay_req(imp, req, &rc)) {
1167                 cfs_spin_lock(&req->rq_lock);
1168                 req->rq_waiting = 1;
1169                 cfs_spin_unlock(&req->rq_lock);
1170
1171                 DEBUG_REQ(D_HA, req, "req from PID %d waiting for recovery: "
1172                           "(%s != %s)", lustre_msg_get_status(req->rq_reqmsg),
1173                           ptlrpc_import_state_name(req->rq_send_state),
1174                           ptlrpc_import_state_name(imp->imp_state));
1175                 LASSERT(cfs_list_empty(&req->rq_list));
1176                 cfs_list_add_tail(&req->rq_list, &imp->imp_delayed_list);
1177                 cfs_atomic_inc(&req->rq_import->imp_inflight);
1178                 cfs_spin_unlock(&imp->imp_lock);
1179                 RETURN(0);
1180         }
1181
1182         if (rc != 0) {
1183                 cfs_spin_unlock(&imp->imp_lock);
1184                 req->rq_status = rc;
1185                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1186                 RETURN(rc);
1187         }
1188
1189         LASSERT(cfs_list_empty(&req->rq_list));
1190         cfs_list_add_tail(&req->rq_list, &imp->imp_sending_list);
1191         cfs_atomic_inc(&req->rq_import->imp_inflight);
1192         cfs_spin_unlock(&imp->imp_lock);
1193
1194         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
1195
1196         rc = sptlrpc_req_refresh_ctx(req, -1);
1197         if (rc) {
1198                 if (req->rq_err) {
1199                         req->rq_status = rc;
1200                         RETURN(1);
1201                 } else {
1202                         req->rq_wait_ctx = 1;
1203                         RETURN(0);
1204                 }
1205         }
1206
1207         CDEBUG(D_RPCTRACE, "Sending RPC pname:cluuid:pid:xid:nid:opc"
1208                " %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1209                imp->imp_obd->obd_uuid.uuid,
1210                lustre_msg_get_status(req->rq_reqmsg), req->rq_xid,
1211                libcfs_nid2str(imp->imp_connection->c_peer.nid),
1212                lustre_msg_get_opc(req->rq_reqmsg));
1213
1214         rc = ptl_send_rpc(req, 0);
1215         if (rc) {
1216                 DEBUG_REQ(D_HA, req, "send failed (%d); expect timeout", rc);
1217                 req->rq_net_err = 1;
1218                 RETURN(rc);
1219         }
1220         RETURN(0);
1221 }
1222
1223 /* this sends any unsent RPCs in @set and returns TRUE if all are sent */
1224 int ptlrpc_check_set(const struct lu_env *env, struct ptlrpc_request_set *set)
1225 {
1226         cfs_list_t *tmp;
1227         int force_timer_recalc = 0;
1228         ENTRY;
1229
1230         if (set->set_remaining == 0)
1231                 RETURN(1);
1232
1233         cfs_list_for_each(tmp, &set->set_requests) {
1234                 struct ptlrpc_request *req =
1235                         cfs_list_entry(tmp, struct ptlrpc_request,
1236                                        rq_set_chain);
1237                 struct obd_import *imp = req->rq_import;
1238                 int unregistered = 0;
1239                 int rc = 0;
1240
1241                 if (req->rq_phase == RQ_PHASE_NEW &&
1242                     ptlrpc_send_new_req(req)) {
1243                         force_timer_recalc = 1;
1244                 }
1245
1246                 /* delayed send - skip */
1247                 if (req->rq_phase == RQ_PHASE_NEW && req->rq_sent)
1248                         continue;
1249
1250                 if (!(req->rq_phase == RQ_PHASE_RPC ||
1251                       req->rq_phase == RQ_PHASE_BULK ||
1252                       req->rq_phase == RQ_PHASE_INTERPRET ||
1253                       req->rq_phase == RQ_PHASE_UNREGISTERING ||
1254                       req->rq_phase == RQ_PHASE_COMPLETE)) {
1255                         DEBUG_REQ(D_ERROR, req, "bad phase %x", req->rq_phase);
1256                         LBUG();
1257                 }
1258
1259                 if (req->rq_phase == RQ_PHASE_UNREGISTERING) {
1260                         LASSERT(req->rq_next_phase != req->rq_phase);
1261                         LASSERT(req->rq_next_phase != RQ_PHASE_UNDEFINED);
1262
1263                         /*
1264                          * Skip processing until reply is unlinked. We
1265                          * can't return to pool before that and we can't
1266                          * call interpret before that. We need to make
1267                          * sure that all rdma transfers finished and will
1268                          * not corrupt any data.
1269                          */
1270                         if (ptlrpc_client_recv_or_unlink(req) ||
1271                             ptlrpc_client_bulk_active(req))
1272                                 continue;
1273
1274                         /*
1275                          * Turn fail_loc off to prevent it from looping
1276                          * forever.
1277                          */
1278                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
1279                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK,
1280                                                      OBD_FAIL_ONCE);
1281                         }
1282                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK)) {
1283                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK,
1284                                                      OBD_FAIL_ONCE);
1285                         }
1286
1287                         /*
1288                          * Move to next phase if reply was successfully
1289                          * unlinked.
1290                          */
1291                         ptlrpc_rqphase_move(req, req->rq_next_phase);
1292                 }
1293
1294                 if (req->rq_phase == RQ_PHASE_COMPLETE)
1295                         continue;
1296
1297                 if (req->rq_phase == RQ_PHASE_INTERPRET)
1298                         GOTO(interpret, req->rq_status);
1299
1300                 /*
1301                  * Note that this also will start async reply unlink.
1302                  */
1303                 if (req->rq_net_err && !req->rq_timedout) {
1304                         ptlrpc_expire_one_request(req, 1);
1305
1306                         /*
1307                          * Check if we still need to wait for unlink.
1308                          */
1309                         if (ptlrpc_client_recv_or_unlink(req) ||
1310                             ptlrpc_client_bulk_active(req))
1311                                 continue;
1312                 }
1313
1314                 if (req->rq_err) {
1315                         req->rq_replied = 0;
1316                         if (req->rq_status == 0)
1317                                 req->rq_status = -EIO;
1318                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1319                         GOTO(interpret, req->rq_status);
1320                 }
1321
1322                 /* ptlrpc_set_wait->l_wait_event sets lwi_allow_intr
1323                  * so it sets rq_intr regardless of individual rpc
1324                  * timeouts. The synchronous IO waiting path sets 
1325                  * rq_intr irrespective of whether ptlrpcd
1326                  * has seen a timeout.  Our policy is to only interpret
1327                  * interrupted rpcs after they have timed out, so we
1328                  * need to enforce that here.
1329                  */
1330
1331                 if (req->rq_intr && (req->rq_timedout || req->rq_waiting ||
1332                                      req->rq_wait_ctx)) {
1333                         req->rq_status = -EINTR;
1334                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1335                         GOTO(interpret, req->rq_status);
1336                 }
1337
1338                 if (req->rq_phase == RQ_PHASE_RPC) {
1339                         if (req->rq_timedout || req->rq_resend ||
1340                             req->rq_waiting || req->rq_wait_ctx) {
1341                                 int status;
1342
1343                                 if (!ptlrpc_unregister_reply(req, 1))
1344                                         continue;
1345
1346                                 cfs_spin_lock(&imp->imp_lock);
1347                                 if (ptlrpc_import_delay_req(imp, req, &status)){
1348                                         /* put on delay list - only if we wait
1349                                          * recovery finished - before send */
1350                                         cfs_list_del_init(&req->rq_list);
1351                                         cfs_list_add_tail(&req->rq_list,
1352                                                           &imp-> \
1353                                                           imp_delayed_list);
1354                                         cfs_spin_unlock(&imp->imp_lock);
1355                                         continue;
1356                                 }
1357
1358                                 if (status != 0)  {
1359                                         req->rq_status = status;
1360                                         ptlrpc_rqphase_move(req,
1361                                                 RQ_PHASE_INTERPRET);
1362                                         cfs_spin_unlock(&imp->imp_lock);
1363                                         GOTO(interpret, req->rq_status);
1364                                 }
1365                                 if (req->rq_no_resend && !req->rq_wait_ctx) {
1366                                         req->rq_status = -ENOTCONN;
1367                                         ptlrpc_rqphase_move(req,
1368                                                 RQ_PHASE_INTERPRET);
1369                                         cfs_spin_unlock(&imp->imp_lock);
1370                                         GOTO(interpret, req->rq_status);
1371                                 }
1372
1373                                 cfs_list_del_init(&req->rq_list);
1374                                 cfs_list_add_tail(&req->rq_list,
1375                                               &imp->imp_sending_list);
1376
1377                                 cfs_spin_unlock(&imp->imp_lock);
1378
1379                                 req->rq_waiting = 0;
1380
1381                                 if (req->rq_timedout||req->rq_resend) {
1382                                         /* This is re-sending anyways,
1383                                          * let's mark req as resend. */
1384                                         req->rq_resend = 1;
1385                                         if (req->rq_bulk) {
1386                                                 __u64 old_xid;
1387
1388                                                 if (!ptlrpc_unregister_bulk(req, 1))
1389                                                         continue;
1390
1391                                                 /* ensure previous bulk fails */
1392                                                 old_xid = req->rq_xid;
1393                                                 req->rq_xid = ptlrpc_next_xid();
1394                                                 CDEBUG(D_HA, "resend bulk "
1395                                                        "old x"LPU64
1396                                                        " new x"LPU64"\n",
1397                                                        old_xid, req->rq_xid);
1398                                         }
1399                                 }
1400                                 /*
1401                                  * rq_wait_ctx is only touched by ptlrpcd,
1402                                  * so no lock is needed here.
1403                                  */
1404                                 status = sptlrpc_req_refresh_ctx(req, -1);
1405                                 if (status) {
1406                                         if (req->rq_err) {
1407                                                 req->rq_status = status;
1408                                                 req->rq_wait_ctx = 0;
1409                                                 force_timer_recalc = 1;
1410                                         } else {
1411                                                 req->rq_wait_ctx = 1;
1412                                         }
1413
1414                                         continue;
1415                                 } else {
1416                                         req->rq_wait_ctx = 0;
1417                                 }
1418
1419                                 rc = ptl_send_rpc(req, 0);
1420                                 if (rc) {
1421                                         DEBUG_REQ(D_HA, req, "send failed (%d)",
1422                                                   rc);
1423                                         force_timer_recalc = 1;
1424                                         req->rq_net_err = 1;
1425                                 }
1426                                 /* need to reset the timeout */
1427                                 force_timer_recalc = 1;
1428                         }
1429
1430                         cfs_spin_lock(&req->rq_lock);
1431
1432                         if (ptlrpc_client_early(req)) {
1433                                 ptlrpc_at_recv_early_reply(req);
1434                                 cfs_spin_unlock(&req->rq_lock);
1435                                 continue;
1436                         }
1437
1438                         /* Still waiting for a reply? */
1439                         if (ptlrpc_client_recv(req)) {
1440                                 cfs_spin_unlock(&req->rq_lock);
1441                                 continue;
1442                         }
1443
1444                         /* Did we actually receive a reply? */
1445                         if (!ptlrpc_client_replied(req)) {
1446                                 cfs_spin_unlock(&req->rq_lock);
1447                                 continue;
1448                         }
1449
1450                         cfs_spin_unlock(&req->rq_lock);
1451
1452                         /* unlink from net because we are going to
1453                          * swab in-place of reply buffer */
1454                         unregistered = ptlrpc_unregister_reply(req, 1);
1455                         if (!unregistered)
1456                                 continue;
1457
1458                         req->rq_status = after_reply(req);
1459                         if (req->rq_resend)
1460                                 continue;
1461
1462                         /* If there is no bulk associated with this request,
1463                          * then we're done and should let the interpreter
1464                          * process the reply. Similarly if the RPC returned
1465                          * an error, and therefore the bulk will never arrive.
1466                          */
1467                         if (req->rq_bulk == NULL || req->rq_status != 0) {
1468                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1469                                 GOTO(interpret, req->rq_status);
1470                         }
1471
1472                         ptlrpc_rqphase_move(req, RQ_PHASE_BULK);
1473                 }
1474
1475                 LASSERT(req->rq_phase == RQ_PHASE_BULK);
1476                 if (ptlrpc_client_bulk_active(req))
1477                         continue;
1478
1479                 if (!req->rq_bulk->bd_success) {
1480                         /* The RPC reply arrived OK, but the bulk screwed
1481                          * up!  Dead weird since the server told us the RPC
1482                          * was good after getting the REPLY for her GET or
1483                          * the ACK for her PUT. */
1484                         DEBUG_REQ(D_ERROR, req, "bulk transfer failed");
1485                         LBUG();
1486                 }
1487
1488                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1489
1490         interpret:
1491                 LASSERT(req->rq_phase == RQ_PHASE_INTERPRET);
1492
1493                 /* This moves to "unregistering" phase we need to wait for
1494                  * reply unlink. */
1495                 if (!unregistered && !ptlrpc_unregister_reply(req, 1))
1496                         continue;
1497
1498                 if (!ptlrpc_unregister_bulk(req, 1))
1499                         continue;
1500
1501                 /* When calling interpret receiving already should be
1502                  * finished. */
1503                 LASSERT(!req->rq_receiving_reply);
1504
1505                 ptlrpc_req_interpret(env, req, req->rq_status);
1506
1507                 ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
1508
1509                 CDEBUG(D_RPCTRACE, "Completed RPC pname:cluuid:pid:xid:nid:"
1510                        "opc %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1511                        imp->imp_obd->obd_uuid.uuid,
1512                        req->rq_reqmsg ? lustre_msg_get_status(req->rq_reqmsg):-1,
1513                        req->rq_xid,
1514                        libcfs_nid2str(imp->imp_connection->c_peer.nid),
1515                        req->rq_reqmsg ? lustre_msg_get_opc(req->rq_reqmsg) : -1);
1516
1517                 cfs_spin_lock(&imp->imp_lock);
1518                 /* Request already may be not on sending or delaying list. This
1519                  * may happen in the case of marking it erroneous for the case
1520                  * ptlrpc_import_delay_req(req, status) find it impossible to
1521                  * allow sending this rpc and returns *status != 0. */
1522                 if (!cfs_list_empty(&req->rq_list)) {
1523                         cfs_list_del_init(&req->rq_list);
1524                         cfs_atomic_dec(&imp->imp_inflight);
1525                 }
1526                 cfs_spin_unlock(&imp->imp_lock);
1527
1528                 set->set_remaining--;
1529                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1530         }
1531
1532         /* If we hit an error, we want to recover promptly. */
1533         RETURN(set->set_remaining == 0 || force_timer_recalc);
1534 }
1535
1536 /* Return 1 if we should give up, else 0 */
1537 int ptlrpc_expire_one_request(struct ptlrpc_request *req, int async_unlink)
1538 {
1539         struct obd_import *imp = req->rq_import;
1540         int rc = 0;
1541         ENTRY;
1542
1543         cfs_spin_lock(&req->rq_lock);
1544         req->rq_timedout = 1;
1545         cfs_spin_unlock(&req->rq_lock);
1546
1547         DEBUG_REQ(req->rq_fake ? D_INFO : D_WARNING, req, 
1548                   "Request x"LPU64" sent from %s to NID %s "CFS_DURATION_T"s "
1549                   "ago has %s ("CFS_DURATION_T"s prior to deadline).\n",
1550                   req->rq_xid, imp ? imp->imp_obd->obd_name : "<?>",
1551                   imp ? libcfs_nid2str(imp->imp_connection->c_peer.nid) : "<?>",
1552                   cfs_time_sub(cfs_time_current_sec(), req->rq_sent),
1553                   req->rq_net_err ? "failed due to network error" : "timed out",
1554                   cfs_time_sub(req->rq_deadline, req->rq_sent));
1555
1556         if (imp != NULL && obd_debug_peer_on_timeout)
1557                 LNetCtl(IOC_LIBCFS_DEBUG_PEER, &imp->imp_connection->c_peer);
1558
1559         ptlrpc_unregister_reply(req, async_unlink);
1560         ptlrpc_unregister_bulk(req, async_unlink);
1561
1562         if (obd_dump_on_timeout)
1563                 libcfs_debug_dumplog();
1564
1565         if (imp == NULL) {
1566                 DEBUG_REQ(D_HA, req, "NULL import: already cleaned up?");
1567                 RETURN(1);
1568         }
1569
1570         if (req->rq_fake)
1571                RETURN(1);
1572
1573         cfs_atomic_inc(&imp->imp_timeouts);
1574
1575         /* The DLM server doesn't want recovery run on its imports. */
1576         if (imp->imp_dlm_fake)
1577                 RETURN(1);
1578
1579         /* If this request is for recovery or other primordial tasks,
1580          * then error it out here. */
1581         if (req->rq_ctx_init || req->rq_ctx_fini ||
1582             req->rq_send_state != LUSTRE_IMP_FULL ||
1583             imp->imp_obd->obd_no_recov) {
1584                 DEBUG_REQ(D_RPCTRACE, req, "err -110, sent_state=%s (now=%s)",
1585                           ptlrpc_import_state_name(req->rq_send_state),
1586                           ptlrpc_import_state_name(imp->imp_state));
1587                 cfs_spin_lock(&req->rq_lock);
1588                 req->rq_status = -ETIMEDOUT;
1589                 req->rq_err = 1;
1590                 cfs_spin_unlock(&req->rq_lock);
1591                 RETURN(1);
1592         }
1593
1594         /* if a request can't be resent we can't wait for an answer after
1595            the timeout */
1596         if (req->rq_no_resend) {
1597                 DEBUG_REQ(D_RPCTRACE, req, "TIMEOUT-NORESEND:");
1598                 rc = 1;
1599         }
1600
1601         ptlrpc_fail_import(imp, lustre_msg_get_conn_cnt(req->rq_reqmsg));
1602
1603         RETURN(rc);
1604 }
1605
1606 int ptlrpc_expired_set(void *data)
1607 {
1608         struct ptlrpc_request_set *set = data;
1609         cfs_list_t                *tmp;
1610         time_t                     now = cfs_time_current_sec();
1611         ENTRY;
1612
1613         LASSERT(set != NULL);
1614
1615         /*
1616          * A timeout expired. See which reqs it applies to...
1617          */
1618         cfs_list_for_each (tmp, &set->set_requests) {
1619                 struct ptlrpc_request *req =
1620                         cfs_list_entry(tmp, struct ptlrpc_request,
1621                                        rq_set_chain);
1622
1623                 /* don't expire request waiting for context */
1624                 if (req->rq_wait_ctx)
1625                         continue;
1626
1627                 /* Request in-flight? */
1628                 if (!((req->rq_phase == RQ_PHASE_RPC &&
1629                        !req->rq_waiting && !req->rq_resend) ||
1630                       (req->rq_phase == RQ_PHASE_BULK)))
1631                         continue;
1632
1633                 if (req->rq_timedout ||     /* already dealt with */
1634                     req->rq_deadline > now) /* not expired */
1635                         continue;
1636
1637                 /* Deal with this guy. Do it asynchronously to not block
1638                  * ptlrpcd thread. */
1639                 ptlrpc_expire_one_request(req, 1);
1640         }
1641
1642         /*
1643          * When waiting for a whole set, we always break out of the
1644          * sleep so we can recalculate the timeout, or enable interrupts
1645          * if everyone's timed out.
1646          */
1647         RETURN(1);
1648 }
1649
1650 void ptlrpc_mark_interrupted(struct ptlrpc_request *req)
1651 {
1652         cfs_spin_lock(&req->rq_lock);
1653         req->rq_intr = 1;
1654         cfs_spin_unlock(&req->rq_lock);
1655 }
1656
1657 void ptlrpc_interrupted_set(void *data)
1658 {
1659         struct ptlrpc_request_set *set = data;
1660         cfs_list_t *tmp;
1661
1662         LASSERT(set != NULL);
1663         CERROR("INTERRUPTED SET %p\n", set);
1664
1665         cfs_list_for_each(tmp, &set->set_requests) {
1666                 struct ptlrpc_request *req =
1667                         cfs_list_entry(tmp, struct ptlrpc_request,
1668                                        rq_set_chain);
1669
1670                 if (req->rq_phase != RQ_PHASE_RPC &&
1671                     req->rq_phase != RQ_PHASE_UNREGISTERING)
1672                         continue;
1673
1674                 ptlrpc_mark_interrupted(req);
1675         }
1676 }
1677
1678 /**
1679  * Get the smallest timeout in the set; this does NOT set a timeout.
1680  */
1681 int ptlrpc_set_next_timeout(struct ptlrpc_request_set *set)
1682 {
1683         cfs_list_t            *tmp;
1684         time_t                 now = cfs_time_current_sec();
1685         int                    timeout = 0;
1686         struct ptlrpc_request *req;
1687         int                    deadline;
1688         ENTRY;
1689
1690         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
1691
1692         cfs_list_for_each(tmp, &set->set_requests) {
1693                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1694
1695                 /*
1696                  * Request in-flight?
1697                  */
1698                 if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
1699                       (req->rq_phase == RQ_PHASE_BULK) ||
1700                       (req->rq_phase == RQ_PHASE_NEW)))
1701                         continue;
1702
1703                 /*
1704                  * Already timed out.
1705                  */
1706                 if (req->rq_timedout)
1707                         continue;
1708
1709                 /*
1710                  * Waiting for ctx.
1711                  */
1712                 if (req->rq_wait_ctx)
1713                         continue;
1714
1715                 if (req->rq_phase == RQ_PHASE_NEW)
1716                         deadline = req->rq_sent;
1717                 else
1718                         deadline = req->rq_sent + req->rq_timeout;
1719
1720                 if (deadline <= now)    /* actually expired already */
1721                         timeout = 1;    /* ASAP */
1722                 else if (timeout == 0 || timeout > deadline - now)
1723                         timeout = deadline - now;
1724         }
1725         RETURN(timeout);
1726 }
1727
1728 int ptlrpc_set_wait(struct ptlrpc_request_set *set)
1729 {
1730         cfs_list_t            *tmp;
1731         struct ptlrpc_request *req;
1732         struct l_wait_info     lwi;
1733         int                    rc, timeout;
1734         ENTRY;
1735
1736         if (cfs_list_empty(&set->set_requests))
1737                 RETURN(0);
1738
1739         cfs_list_for_each(tmp, &set->set_requests) {
1740                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1741                 if (req->rq_phase == RQ_PHASE_NEW)
1742                         (void)ptlrpc_send_new_req(req);
1743         }
1744
1745         do {
1746                 timeout = ptlrpc_set_next_timeout(set);
1747
1748                 /* wait until all complete, interrupted, or an in-flight
1749                  * req times out */
1750                 CDEBUG(D_RPCTRACE, "set %p going to sleep for %d seconds\n",
1751                        set, timeout);
1752
1753                 if (timeout == 0 && !cfs_signal_pending())
1754                         /*
1755                          * No requests are in-flight (ether timed out
1756                          * or delayed), so we can allow interrupts.
1757                          * We still want to block for a limited time,
1758                          * so we allow interrupts during the timeout.
1759                          */
1760                         lwi = LWI_TIMEOUT_INTR_ALL(cfs_time_seconds(1), 
1761                                                    ptlrpc_expired_set,
1762                                                    ptlrpc_interrupted_set, set);
1763                 else
1764                         /*
1765                          * At least one request is in flight, so no
1766                          * interrupts are allowed. Wait until all
1767                          * complete, or an in-flight req times out. 
1768                          */
1769                         lwi = LWI_TIMEOUT(cfs_time_seconds(timeout? timeout : 1),
1770                                           ptlrpc_expired_set, set);
1771
1772                 rc = l_wait_event(set->set_waitq, ptlrpc_check_set(NULL, set), &lwi);
1773
1774                 LASSERT(rc == 0 || rc == -EINTR || rc == -ETIMEDOUT);
1775
1776                 /* -EINTR => all requests have been flagged rq_intr so next
1777                  * check completes.
1778                  * -ETIMEDOUT => someone timed out.  When all reqs have
1779                  * timed out, signals are enabled allowing completion with
1780                  * EINTR.
1781                  * I don't really care if we go once more round the loop in
1782                  * the error cases -eeb. */
1783         } while (rc != 0 || set->set_remaining != 0);
1784
1785         LASSERT(set->set_remaining == 0);
1786
1787         rc = 0;
1788         cfs_list_for_each(tmp, &set->set_requests) {
1789                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1790
1791                 LASSERT(req->rq_phase == RQ_PHASE_COMPLETE);
1792                 if (req->rq_status != 0)
1793                         rc = req->rq_status;
1794         }
1795
1796         if (set->set_interpret != NULL) {
1797                 int (*interpreter)(struct ptlrpc_request_set *set,void *,int) =
1798                         set->set_interpret;
1799                 rc = interpreter (set, set->set_arg, rc);
1800         } else {
1801                 struct ptlrpc_set_cbdata *cbdata, *n;
1802                 int err;
1803
1804                 cfs_list_for_each_entry_safe(cbdata, n,
1805                                          &set->set_cblist, psc_item) {
1806                         cfs_list_del_init(&cbdata->psc_item);
1807                         err = cbdata->psc_interpret(set, cbdata->psc_data, rc);
1808                         if (err && !rc)
1809                                 rc = err;
1810                         OBD_FREE_PTR(cbdata);
1811                 }
1812         }
1813
1814         RETURN(rc);
1815 }
1816
1817 static void __ptlrpc_free_req(struct ptlrpc_request *request, int locked)
1818 {
1819         ENTRY;
1820         if (request == NULL) {
1821                 EXIT;
1822                 return;
1823         }
1824
1825         LASSERTF(!request->rq_receiving_reply, "req %p\n", request);
1826         LASSERTF(request->rq_rqbd == NULL, "req %p\n",request);/* client-side */
1827         LASSERTF(cfs_list_empty(&request->rq_list), "req %p\n", request);
1828         LASSERTF(cfs_list_empty(&request->rq_set_chain), "req %p\n", request);
1829         LASSERTF(cfs_list_empty(&request->rq_exp_list), "req %p\n", request);
1830         LASSERTF(!request->rq_replay, "req %p\n", request);
1831         LASSERT(request->rq_cli_ctx || request->rq_fake);
1832
1833         req_capsule_fini(&request->rq_pill);
1834
1835         /* We must take it off the imp_replay_list first.  Otherwise, we'll set
1836          * request->rq_reqmsg to NULL while osc_close is dereferencing it. */
1837         if (request->rq_import != NULL) {
1838                 if (!locked)
1839                         cfs_spin_lock(&request->rq_import->imp_lock);
1840                 cfs_list_del_init(&request->rq_replay_list);
1841                 if (!locked)
1842                         cfs_spin_unlock(&request->rq_import->imp_lock);
1843         }
1844         LASSERTF(cfs_list_empty(&request->rq_replay_list), "req %p\n", request);
1845
1846         if (cfs_atomic_read(&request->rq_refcount) != 0) {
1847                 DEBUG_REQ(D_ERROR, request,
1848                           "freeing request with nonzero refcount");
1849                 LBUG();
1850         }
1851
1852         if (request->rq_repbuf != NULL)
1853                 sptlrpc_cli_free_repbuf(request);
1854         if (request->rq_export != NULL) {
1855                 class_export_put(request->rq_export);
1856                 request->rq_export = NULL;
1857         }
1858         if (request->rq_import != NULL) {
1859                 class_import_put(request->rq_import);
1860                 request->rq_import = NULL;
1861         }
1862         if (request->rq_bulk != NULL)
1863                 ptlrpc_free_bulk(request->rq_bulk);
1864
1865         if (request->rq_reqbuf != NULL || request->rq_clrbuf != NULL)
1866                 sptlrpc_cli_free_reqbuf(request);
1867
1868         if (request->rq_cli_ctx)
1869                 sptlrpc_req_put_ctx(request, !locked);
1870
1871         if (request->rq_pool)
1872                 __ptlrpc_free_req_to_pool(request);
1873         else
1874                 OBD_FREE(request, sizeof(*request));
1875         EXIT;
1876 }
1877
1878 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked);
1879 void ptlrpc_req_finished_with_imp_lock(struct ptlrpc_request *request)
1880 {
1881         LASSERT_SPIN_LOCKED(&request->rq_import->imp_lock);
1882         (void)__ptlrpc_req_finished(request, 1);
1883 }
1884
1885 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked)
1886 {
1887         ENTRY;
1888         if (request == NULL)
1889                 RETURN(1);
1890
1891         if (request == LP_POISON ||
1892             request->rq_reqmsg == LP_POISON) {
1893                 CERROR("dereferencing freed request (bug 575)\n");
1894                 LBUG();
1895                 RETURN(1);
1896         }
1897
1898         DEBUG_REQ(D_INFO, request, "refcount now %u",
1899                   cfs_atomic_read(&request->rq_refcount) - 1);
1900
1901         if (cfs_atomic_dec_and_test(&request->rq_refcount)) {
1902                 __ptlrpc_free_req(request, locked);
1903                 RETURN(1);
1904         }
1905
1906         RETURN(0);
1907 }
1908
1909 void ptlrpc_req_finished(struct ptlrpc_request *request)
1910 {
1911         __ptlrpc_req_finished(request, 0);
1912 }
1913
1914 __u64 ptlrpc_req_xid(struct ptlrpc_request *request)
1915 {
1916         return request->rq_xid;
1917 }
1918 EXPORT_SYMBOL(ptlrpc_req_xid);
1919
1920 /* Disengage the client's reply buffer from the network
1921  * NB does _NOT_ unregister any client-side bulk.
1922  * IDEMPOTENT, but _not_ safe against concurrent callers.
1923  * The request owner (i.e. the thread doing the I/O) must call...
1924  */
1925 int ptlrpc_unregister_reply(struct ptlrpc_request *request, int async)
1926 {
1927         int                rc;
1928         cfs_waitq_t       *wq;
1929         struct l_wait_info lwi;
1930
1931         /*
1932          * Might sleep.
1933          */
1934         LASSERT(!cfs_in_interrupt());
1935
1936         /*
1937          * Let's setup deadline for reply unlink.
1938          */
1939         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK) &&
1940             async && request->rq_reply_deadline == 0)
1941                 request->rq_reply_deadline = cfs_time_current_sec()+LONG_UNLINK;
1942
1943         /*
1944          * Nothing left to do.
1945          */
1946         if (!ptlrpc_client_recv_or_unlink(request))
1947                 RETURN(1);
1948
1949         LNetMDUnlink(request->rq_reply_md_h);
1950
1951         /*
1952          * Let's check it once again.
1953          */
1954         if (!ptlrpc_client_recv_or_unlink(request))
1955                 RETURN(1);
1956
1957         /*
1958          * Move to "Unregistering" phase as reply was not unlinked yet.
1959          */
1960         ptlrpc_rqphase_move(request, RQ_PHASE_UNREGISTERING);
1961
1962         /*
1963          * Do not wait for unlink to finish.
1964          */
1965         if (async)
1966                 RETURN(0);
1967
1968         /*
1969          * We have to l_wait_event() whatever the result, to give liblustre
1970          * a chance to run reply_in_callback(), and to make sure we've
1971          * unlinked before returning a req to the pool.
1972          */
1973         if (request->rq_set != NULL)
1974                 wq = &request->rq_set->set_waitq;
1975         else
1976                 wq = &request->rq_reply_waitq;
1977
1978         for (;;) {
1979                 /* Network access will complete in finite time but the HUGE
1980                  * timeout lets us CWARN for visibility of sluggish NALs */
1981                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
1982                                            cfs_time_seconds(1), NULL, NULL);
1983                 rc = l_wait_event(*wq, !ptlrpc_client_recv_or_unlink(request),
1984                                   &lwi);
1985                 if (rc == 0) {
1986                         ptlrpc_rqphase_move(request, request->rq_next_phase);
1987                         RETURN(1);
1988                 }
1989
1990                 LASSERT(rc == -ETIMEDOUT);
1991                 DEBUG_REQ(D_WARNING, request, "Unexpectedly long timeout "
1992                           "rvcng=%d unlnk=%d", request->rq_receiving_reply,
1993                           request->rq_must_unlink);
1994         }
1995         RETURN(0);
1996 }
1997
1998 /* caller must hold imp->imp_lock */
1999 void ptlrpc_free_committed(struct obd_import *imp)
2000 {
2001         cfs_list_t *tmp, *saved;
2002         struct ptlrpc_request *req;
2003         struct ptlrpc_request *last_req = NULL; /* temporary fire escape */
2004         ENTRY;
2005
2006         LASSERT(imp != NULL);
2007
2008         LASSERT_SPIN_LOCKED(&imp->imp_lock);
2009
2010
2011         if (imp->imp_peer_committed_transno == imp->imp_last_transno_checked &&
2012             imp->imp_generation == imp->imp_last_generation_checked) {
2013                 CDEBUG(D_RPCTRACE, "%s: skip recheck: last_committed "LPU64"\n",
2014                        imp->imp_obd->obd_name, imp->imp_peer_committed_transno);
2015                 EXIT;
2016                 return;
2017         }
2018         CDEBUG(D_RPCTRACE, "%s: committing for last_committed "LPU64" gen %d\n",
2019                imp->imp_obd->obd_name, imp->imp_peer_committed_transno,
2020                imp->imp_generation);
2021         imp->imp_last_transno_checked = imp->imp_peer_committed_transno;
2022         imp->imp_last_generation_checked = imp->imp_generation;
2023
2024         cfs_list_for_each_safe(tmp, saved, &imp->imp_replay_list) {
2025                 req = cfs_list_entry(tmp, struct ptlrpc_request,
2026                                      rq_replay_list);
2027
2028                 /* XXX ok to remove when 1357 resolved - rread 05/29/03  */
2029                 LASSERT(req != last_req);
2030                 last_req = req;
2031
2032                 if (req->rq_transno == 0) {
2033                         DEBUG_REQ(D_EMERG, req, "zero transno during replay");
2034                         LBUG();
2035                 }
2036                 if (req->rq_import_generation < imp->imp_generation) {
2037                         DEBUG_REQ(D_RPCTRACE, req, "free request with old gen");
2038                         GOTO(free_req, 0);
2039                 }
2040
2041                 if (req->rq_replay) {
2042                         DEBUG_REQ(D_RPCTRACE, req, "keeping (FL_REPLAY)");
2043                         continue;
2044                 }
2045
2046                 /* not yet committed */
2047                 if (req->rq_transno > imp->imp_peer_committed_transno) {
2048                         DEBUG_REQ(D_RPCTRACE, req, "stopping search");
2049                         break;
2050                 }
2051
2052                 DEBUG_REQ(D_RPCTRACE, req, "commit (last_committed "LPU64")",
2053                           imp->imp_peer_committed_transno);
2054 free_req:
2055                 cfs_spin_lock(&req->rq_lock);
2056                 req->rq_replay = 0;
2057                 cfs_spin_unlock(&req->rq_lock);
2058                 if (req->rq_commit_cb != NULL)
2059                         req->rq_commit_cb(req);
2060                 cfs_list_del_init(&req->rq_replay_list);
2061                 __ptlrpc_req_finished(req, 1);
2062         }
2063
2064         EXIT;
2065         return;
2066 }
2067
2068 void ptlrpc_cleanup_client(struct obd_import *imp)
2069 {
2070         ENTRY;
2071         EXIT;
2072         return;
2073 }
2074
2075 void ptlrpc_resend_req(struct ptlrpc_request *req)
2076 {
2077         DEBUG_REQ(D_HA, req, "going to resend");
2078         lustre_msg_set_handle(req->rq_reqmsg, &(struct lustre_handle){ 0 });
2079         req->rq_status = -EAGAIN;
2080
2081         cfs_spin_lock(&req->rq_lock);
2082         req->rq_resend = 1;
2083         req->rq_net_err = 0;
2084         req->rq_timedout = 0;
2085         if (req->rq_bulk) {
2086                 __u64 old_xid = req->rq_xid;
2087
2088                 /* ensure previous bulk fails */
2089                 req->rq_xid = ptlrpc_next_xid();
2090                 CDEBUG(D_HA, "resend bulk old x"LPU64" new x"LPU64"\n",
2091                        old_xid, req->rq_xid);
2092         }
2093         ptlrpc_client_wake_req(req);
2094         cfs_spin_unlock(&req->rq_lock);
2095 }
2096
2097 /* XXX: this function and rq_status are currently unused */
2098 void ptlrpc_restart_req(struct ptlrpc_request *req)
2099 {
2100         DEBUG_REQ(D_HA, req, "restarting (possibly-)completed request");
2101         req->rq_status = -ERESTARTSYS;
2102
2103         cfs_spin_lock(&req->rq_lock);
2104         req->rq_restart = 1;
2105         req->rq_timedout = 0;
2106         ptlrpc_client_wake_req(req);
2107         cfs_spin_unlock(&req->rq_lock);
2108 }
2109
2110 struct ptlrpc_request *ptlrpc_request_addref(struct ptlrpc_request *req)
2111 {
2112         ENTRY;
2113         cfs_atomic_inc(&req->rq_refcount);
2114         RETURN(req);
2115 }
2116
2117 void ptlrpc_retain_replayable_request(struct ptlrpc_request *req,
2118                                       struct obd_import *imp)
2119 {
2120         cfs_list_t *tmp;
2121
2122         LASSERT_SPIN_LOCKED(&imp->imp_lock);
2123
2124         if (req->rq_transno == 0) {
2125                 DEBUG_REQ(D_EMERG, req, "saving request with zero transno");
2126                 LBUG();
2127         }
2128
2129         /* clear this for new requests that were resent as well
2130            as resent replayed requests. */
2131         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
2132
2133         /* don't re-add requests that have been replayed */
2134         if (!cfs_list_empty(&req->rq_replay_list))
2135                 return;
2136
2137         lustre_msg_add_flags(req->rq_reqmsg, MSG_REPLAY);
2138
2139         LASSERT(imp->imp_replayable);
2140         /* Balanced in ptlrpc_free_committed, usually. */
2141         ptlrpc_request_addref(req);
2142         cfs_list_for_each_prev(tmp, &imp->imp_replay_list) {
2143                 struct ptlrpc_request *iter =
2144                         cfs_list_entry(tmp, struct ptlrpc_request,
2145                                        rq_replay_list);
2146
2147                 /* We may have duplicate transnos if we create and then
2148                  * open a file, or for closes retained if to match creating
2149                  * opens, so use req->rq_xid as a secondary key.
2150                  * (See bugs 684, 685, and 428.)
2151                  * XXX no longer needed, but all opens need transnos!
2152                  */
2153                 if (iter->rq_transno > req->rq_transno)
2154                         continue;
2155
2156                 if (iter->rq_transno == req->rq_transno) {
2157                         LASSERT(iter->rq_xid != req->rq_xid);
2158                         if (iter->rq_xid > req->rq_xid)
2159                                 continue;
2160                 }
2161
2162                 cfs_list_add(&req->rq_replay_list, &iter->rq_replay_list);
2163                 return;
2164         }
2165
2166         cfs_list_add(&req->rq_replay_list, &imp->imp_replay_list);
2167 }
2168
2169 int ptlrpc_queue_wait(struct ptlrpc_request *req)
2170 {
2171         struct ptlrpc_request_set *set;
2172         int rc;
2173         ENTRY;
2174
2175         LASSERT(req->rq_set == NULL);
2176         LASSERT(!req->rq_receiving_reply);
2177
2178         set = ptlrpc_prep_set();
2179         if (set == NULL) {
2180                 CERROR("Unable to allocate ptlrpc set.");
2181                 RETURN(-ENOMEM);
2182         }
2183
2184         /* for distributed debugging */
2185         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
2186
2187         /* add a ref for the set (see comment in ptlrpc_set_add_req) */
2188         ptlrpc_request_addref(req);
2189         ptlrpc_set_add_req(set, req);
2190         rc = ptlrpc_set_wait(set);
2191         ptlrpc_set_destroy(set);
2192
2193         RETURN(rc);
2194 }
2195
2196 struct ptlrpc_replay_async_args {
2197         int praa_old_state;
2198         int praa_old_status;
2199 };
2200
2201 static int ptlrpc_replay_interpret(const struct lu_env *env,
2202                                    struct ptlrpc_request *req,
2203                                    void * data, int rc)
2204 {
2205         struct ptlrpc_replay_async_args *aa = data;
2206         struct obd_import *imp = req->rq_import;
2207
2208         ENTRY;
2209         cfs_atomic_dec(&imp->imp_replay_inflight);
2210
2211         if (!ptlrpc_client_replied(req)) {
2212                 CERROR("request replay timed out, restarting recovery\n");
2213                 GOTO(out, rc = -ETIMEDOUT);
2214         }
2215
2216         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR &&
2217             (lustre_msg_get_status(req->rq_repmsg) == -ENOTCONN ||
2218              lustre_msg_get_status(req->rq_repmsg) == -ENODEV))
2219                 GOTO(out, rc = lustre_msg_get_status(req->rq_repmsg));
2220
2221         /** VBR: check version failure */
2222         if (lustre_msg_get_status(req->rq_repmsg) == -EOVERFLOW) {
2223                 /** replay was failed due to version mismatch */
2224                 DEBUG_REQ(D_WARNING, req, "Version mismatch during replay\n");
2225                 cfs_spin_lock(&imp->imp_lock);
2226                 imp->imp_vbr_failed = 1;
2227                 imp->imp_no_lock_replay = 1;
2228                 cfs_spin_unlock(&imp->imp_lock);
2229         } else {
2230                 /** The transno had better not change over replay. */
2231                 LASSERTF(lustre_msg_get_transno(req->rq_reqmsg) ==
2232                          lustre_msg_get_transno(req->rq_repmsg) ||
2233                          lustre_msg_get_transno(req->rq_repmsg) == 0,
2234                          LPX64"/"LPX64"\n",
2235                          lustre_msg_get_transno(req->rq_reqmsg),
2236                          lustre_msg_get_transno(req->rq_repmsg));
2237         }
2238
2239         cfs_spin_lock(&imp->imp_lock);
2240         /** if replays by version then gap was occur on server, no trust to locks */
2241         if (lustre_msg_get_flags(req->rq_repmsg) & MSG_VERSION_REPLAY)
2242                 imp->imp_no_lock_replay = 1;
2243         imp->imp_last_replay_transno = lustre_msg_get_transno(req->rq_reqmsg);
2244         cfs_spin_unlock(&imp->imp_lock);
2245         LASSERT(imp->imp_last_replay_transno);
2246
2247         DEBUG_REQ(D_HA, req, "got rep");
2248
2249         /* let the callback do fixups, possibly including in the request */
2250         if (req->rq_replay_cb)
2251                 req->rq_replay_cb(req);
2252
2253         if (ptlrpc_client_replied(req) &&
2254             lustre_msg_get_status(req->rq_repmsg) != aa->praa_old_status) {
2255                 DEBUG_REQ(D_ERROR, req, "status %d, old was %d",
2256                           lustre_msg_get_status(req->rq_repmsg),
2257                           aa->praa_old_status);
2258         } else {
2259                 /* Put it back for re-replay. */
2260                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
2261         }
2262
2263         /*
2264          * Errors while replay can set transno to 0, but
2265          * imp_last_replay_transno shouldn't be set to 0 anyway
2266          */
2267         if (req->rq_transno > 0) {
2268                 cfs_spin_lock(&imp->imp_lock);
2269                 LASSERT(req->rq_transno <= imp->imp_last_replay_transno);
2270                 imp->imp_last_replay_transno = req->rq_transno;
2271                 cfs_spin_unlock(&imp->imp_lock);
2272         } else
2273                 CERROR("Transno is 0 during replay!\n");
2274         /* continue with recovery */
2275         rc = ptlrpc_import_recovery_state_machine(imp);
2276  out:
2277         req->rq_send_state = aa->praa_old_state;
2278
2279         if (rc != 0)
2280                 /* this replay failed, so restart recovery */
2281                 ptlrpc_connect_import(imp, NULL);
2282
2283         RETURN(rc);
2284 }
2285
2286 int ptlrpc_replay_req(struct ptlrpc_request *req)
2287 {
2288         struct ptlrpc_replay_async_args *aa;
2289         ENTRY;
2290
2291         LASSERT(req->rq_import->imp_state == LUSTRE_IMP_REPLAY);
2292         /* Not handling automatic bulk replay yet (or ever?) */
2293         LASSERT(req->rq_bulk == NULL);
2294
2295         LASSERT (sizeof (*aa) <= sizeof (req->rq_async_args));
2296         aa = ptlrpc_req_async_args(req);
2297         memset(aa, 0, sizeof *aa);
2298
2299         /* Prepare request to be resent with ptlrpcd */
2300         aa->praa_old_state = req->rq_send_state;
2301         req->rq_send_state = LUSTRE_IMP_REPLAY;
2302         req->rq_phase = RQ_PHASE_NEW;
2303         req->rq_next_phase = RQ_PHASE_UNDEFINED;
2304         if (req->rq_repmsg)
2305                 aa->praa_old_status = lustre_msg_get_status(req->rq_repmsg);
2306         req->rq_status = 0;
2307         req->rq_interpret_reply = ptlrpc_replay_interpret;
2308         /* Readjust the timeout for current conditions */
2309         ptlrpc_at_set_req_timeout(req);
2310
2311         DEBUG_REQ(D_HA, req, "REPLAY");
2312
2313         cfs_atomic_inc(&req->rq_import->imp_replay_inflight);
2314         ptlrpc_request_addref(req); /* ptlrpcd needs a ref */
2315
2316         ptlrpcd_add_req(req, PSCOPE_OTHER);
2317         RETURN(0);
2318 }
2319
2320 void ptlrpc_abort_inflight(struct obd_import *imp)
2321 {
2322         cfs_list_t *tmp, *n;
2323         ENTRY;
2324
2325         /* Make sure that no new requests get processed for this import.
2326          * ptlrpc_{queue,set}_wait must (and does) hold imp_lock while testing
2327          * this flag and then putting requests on sending_list or delayed_list.
2328          */
2329         cfs_spin_lock(&imp->imp_lock);
2330
2331         /* XXX locking?  Maybe we should remove each request with the list
2332          * locked?  Also, how do we know if the requests on the list are
2333          * being freed at this time?
2334          */
2335         cfs_list_for_each_safe(tmp, n, &imp->imp_sending_list) {
2336                 struct ptlrpc_request *req =
2337                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2338
2339                 DEBUG_REQ(D_RPCTRACE, req, "inflight");
2340
2341                 cfs_spin_lock (&req->rq_lock);
2342                 if (req->rq_import_generation < imp->imp_generation) {
2343                         req->rq_err = 1;
2344                         req->rq_status = -EINTR;
2345                         ptlrpc_client_wake_req(req);
2346                 }
2347                 cfs_spin_unlock (&req->rq_lock);
2348         }
2349
2350         cfs_list_for_each_safe(tmp, n, &imp->imp_delayed_list) {
2351                 struct ptlrpc_request *req =
2352                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2353
2354                 DEBUG_REQ(D_RPCTRACE, req, "aborting waiting req");
2355
2356                 cfs_spin_lock (&req->rq_lock);
2357                 if (req->rq_import_generation < imp->imp_generation) {
2358                         req->rq_err = 1;
2359                         req->rq_status = -EINTR;
2360                         ptlrpc_client_wake_req(req);
2361                 }
2362                 cfs_spin_unlock (&req->rq_lock);
2363         }
2364
2365         /* Last chance to free reqs left on the replay list, but we
2366          * will still leak reqs that haven't committed.  */
2367         if (imp->imp_replayable)
2368                 ptlrpc_free_committed(imp);
2369
2370         cfs_spin_unlock(&imp->imp_lock);
2371
2372         EXIT;
2373 }
2374
2375 void ptlrpc_abort_set(struct ptlrpc_request_set *set)
2376 {
2377         cfs_list_t *tmp, *pos;
2378
2379         LASSERT(set != NULL);
2380
2381         cfs_list_for_each_safe(pos, tmp, &set->set_requests) {
2382                 struct ptlrpc_request *req =
2383                         cfs_list_entry(pos, struct ptlrpc_request,
2384                                        rq_set_chain);
2385
2386                 cfs_spin_lock(&req->rq_lock);
2387                 if (req->rq_phase != RQ_PHASE_RPC) {
2388                         cfs_spin_unlock(&req->rq_lock);
2389                         continue;
2390                 }
2391
2392                 req->rq_err = 1;
2393                 req->rq_status = -EINTR;
2394                 ptlrpc_client_wake_req(req);
2395                 cfs_spin_unlock(&req->rq_lock);
2396         }
2397 }
2398
2399 static __u64 ptlrpc_last_xid;
2400 static cfs_spinlock_t ptlrpc_last_xid_lock;
2401
2402 /* Initialize the XID for the node.  This is common among all requests on
2403  * this node, and only requires the property that it is monotonically
2404  * increasing.  It does not need to be sequential.  Since this is also used
2405  * as the RDMA match bits, it is important that a single client NOT have
2406  * the same match bits for two different in-flight requests, hence we do
2407  * NOT want to have an XID per target or similar.
2408  *
2409  * To avoid an unlikely collision between match bits after a client reboot
2410  * (which would deliver old data into the wrong RDMA buffer) initialize
2411  * the XID based on the current time, assuming a maximum RPC rate of 1M RPC/s.
2412  * If the time is clearly incorrect, we instead use a 62-bit random number.
2413  * In the worst case the random number will overflow 1M RPCs per second in
2414  * 9133 years, or permutations thereof.
2415  */
2416 #define YEAR_2004 (1ULL << 30)
2417 void ptlrpc_init_xid(void)
2418 {
2419         time_t now = cfs_time_current_sec();
2420
2421         cfs_spin_lock_init(&ptlrpc_last_xid_lock);
2422         if (now < YEAR_2004) {
2423                 ll_get_random_bytes(&ptlrpc_last_xid, sizeof(ptlrpc_last_xid));
2424                 ptlrpc_last_xid >>= 2;
2425                 ptlrpc_last_xid |= (1ULL << 61);
2426         } else {
2427                 ptlrpc_last_xid = (__u64)now << 20;
2428         }
2429 }
2430
2431 __u64 ptlrpc_next_xid(void)
2432 {
2433         __u64 tmp;
2434         cfs_spin_lock(&ptlrpc_last_xid_lock);
2435         tmp = ++ptlrpc_last_xid;
2436         cfs_spin_unlock(&ptlrpc_last_xid_lock);
2437         return tmp;
2438 }
2439
2440 __u64 ptlrpc_sample_next_xid(void)
2441 {
2442 #if BITS_PER_LONG == 32
2443         /* need to avoid possible word tearing on 32-bit systems */
2444         __u64 tmp;
2445         cfs_spin_lock(&ptlrpc_last_xid_lock);
2446         tmp = ptlrpc_last_xid + 1;
2447         cfs_spin_unlock(&ptlrpc_last_xid_lock);
2448         return tmp;
2449 #else
2450         /* No need to lock, since returned value is racy anyways */
2451         return ptlrpc_last_xid + 1;
2452 #endif
2453 }
2454 EXPORT_SYMBOL(ptlrpc_sample_next_xid);