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