Whamcloud - gitweb
acl includes and time_t formats cleanup.
[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 + 2 /* rounding */)
282                 CERROR("Reported service time %u > total measured time "
283                        CFS_DURATION_T"\n",
284                        st, cfs_time_sub(now, req->rq_sent));
285
286         oldnl = at_add(&at->iat_net_latency, nl);
287         if (oldnl != 0)
288                 CDEBUG(D_ADAPTTO, "The network latency for %s (nid %s) "
289                        "has changed from %d to %d\n",
290                        req->rq_import->imp_obd->obd_name,
291                        obd_uuid2str(
292                                &req->rq_import->imp_connection->c_remote_uuid),
293                        oldnl, at_get(&at->iat_net_latency));
294 }
295
296 static int unpack_reply(struct ptlrpc_request *req)
297 {
298         int rc;
299
300         /* Clear reply swab mask; we may have already swabbed an early reply */
301         req->rq_rep_swab_mask = 0;
302
303         rc = lustre_unpack_msg(req->rq_repmsg, req->rq_replen);
304         if (rc) {
305                 DEBUG_REQ(D_ERROR, req, "unpack_rep failed: %d", rc);
306                 return(-EPROTO);
307         }
308
309         rc = lustre_unpack_rep_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
310         if (rc) {
311                 DEBUG_REQ(D_ERROR, req, "unpack ptlrpc body failed: %d", rc);
312                 return(-EPROTO);
313         }
314         return 0;
315 }
316
317 /*
318  * Handle an early reply message, called with the rq_lock held.
319  * If anything goes wrong just ignore it - same as if it never happened
320  */
321 static int ptlrpc_at_recv_early_reply(struct ptlrpc_request *req) {
322         time_t          olddl;
323         int             rc;
324         ENTRY;
325
326         req->rq_early = 0;
327         spin_unlock(&req->rq_lock);
328
329         rc = sptlrpc_cli_unwrap_early_reply(req);
330         if (rc)
331                 GOTO(out, rc);
332
333         rc = unpack_reply(req);
334         if (rc)
335                 GOTO(out_cleanup, rc);
336
337         /* Expecting to increase the service time estimate here */
338         ptlrpc_at_adj_service(req);
339         ptlrpc_at_adj_net_latency(req);
340
341         /* Adjust the local timeout for this req */
342         ptlrpc_at_set_req_timeout(req);
343
344         olddl = req->rq_deadline;
345         /* server assumes it now has rq_timeout from when it sent the
346            early reply, so client should give it at least that long. */
347         req->rq_deadline = cfs_time_current_sec() + req->rq_timeout +
348                     ptlrpc_at_get_net_latency(req);
349
350         DEBUG_REQ(D_ADAPTTO, req,
351                   "Early reply #%d, new deadline in "CFS_DURATION_T"s ("
352                   CFS_DURATION_T"s)", req->rq_early_count,
353                   cfs_time_sub(req->rq_deadline, cfs_time_current_sec()),
354                   cfs_time_sub(req->rq_deadline, olddl));
355
356 out_cleanup:
357         sptlrpc_cli_finish_early_reply(req);
358 out:
359         spin_lock(&req->rq_lock);
360         RETURN(rc);
361 }
362
363 void ptlrpc_free_rq_pool(struct ptlrpc_request_pool *pool)
364 {
365         struct list_head *l, *tmp;
366         struct ptlrpc_request *req;
367
368         if (!pool)
369                 return;
370
371         list_for_each_safe(l, tmp, &pool->prp_req_list) {
372                 req = list_entry(l, struct ptlrpc_request, rq_list);
373                 list_del(&req->rq_list);
374                 LASSERT(req->rq_reqbuf);
375                 LASSERT(req->rq_reqbuf_len == pool->prp_rq_size);
376                 OBD_FREE(req->rq_reqbuf, pool->prp_rq_size);
377                 OBD_FREE(req, sizeof(*req));
378         }
379         OBD_FREE(pool, sizeof(*pool));
380 }
381
382 void ptlrpc_add_rqs_to_pool(struct ptlrpc_request_pool *pool, int num_rq)
383 {
384         int i;
385         int size = 1;
386
387         while (size < pool->prp_rq_size + SPTLRPC_MAX_PAYLOAD)
388                 size <<= 1;
389
390         LASSERTF(list_empty(&pool->prp_req_list) || size == pool->prp_rq_size,
391                  "Trying to change pool size with nonempty pool "
392                  "from %d to %d bytes\n", pool->prp_rq_size, size);
393
394         spin_lock(&pool->prp_lock);
395         pool->prp_rq_size = size;
396         for (i = 0; i < num_rq; i++) {
397                 struct ptlrpc_request *req;
398                 struct lustre_msg *msg;
399
400                 spin_unlock(&pool->prp_lock);
401                 OBD_ALLOC(req, sizeof(struct ptlrpc_request));
402                 if (!req)
403                         return;
404                 OBD_ALLOC_GFP(msg, size, CFS_ALLOC_STD);
405                 if (!msg) {
406                         OBD_FREE(req, sizeof(struct ptlrpc_request));
407                         return;
408                 }
409                 req->rq_reqbuf = msg;
410                 req->rq_reqbuf_len = size;
411                 req->rq_pool = pool;
412                 spin_lock(&pool->prp_lock);
413                 list_add_tail(&req->rq_list, &pool->prp_req_list);
414         }
415         spin_unlock(&pool->prp_lock);
416         return;
417 }
418
419 struct ptlrpc_request_pool *ptlrpc_init_rq_pool(int num_rq, int msgsize,
420                                                 void (*populate_pool)(struct ptlrpc_request_pool *, int))
421 {
422         struct ptlrpc_request_pool *pool;
423
424         OBD_ALLOC(pool, sizeof (struct ptlrpc_request_pool));
425         if (!pool)
426                 return NULL;
427
428         /* Request next power of two for the allocation, because internally
429            kernel would do exactly this */
430
431         spin_lock_init(&pool->prp_lock);
432         CFS_INIT_LIST_HEAD(&pool->prp_req_list);
433         pool->prp_rq_size = msgsize;
434         pool->prp_populate = populate_pool;
435
436         populate_pool(pool, num_rq);
437
438         if (list_empty(&pool->prp_req_list)) {
439                 /* have not allocated a single request for the pool */
440                 OBD_FREE(pool, sizeof (struct ptlrpc_request_pool));
441                 pool = NULL;
442         }
443         return pool;
444 }
445
446 static struct ptlrpc_request *ptlrpc_prep_req_from_pool(struct ptlrpc_request_pool *pool)
447 {
448         struct ptlrpc_request *request;
449         struct lustre_msg *reqbuf;
450
451         if (!pool)
452                 return NULL;
453
454         spin_lock(&pool->prp_lock);
455
456         /* See if we have anything in a pool, and bail out if nothing,
457          * in writeout path, where this matters, this is safe to do, because
458          * nothing is lost in this case, and when some in-flight requests
459          * complete, this code will be called again. */
460         if (unlikely(list_empty(&pool->prp_req_list))) {
461                 spin_unlock(&pool->prp_lock);
462                 return NULL;
463         }
464
465         request = list_entry(pool->prp_req_list.next, struct ptlrpc_request,
466                              rq_list);
467         list_del(&request->rq_list);
468         spin_unlock(&pool->prp_lock);
469
470         LASSERT(request->rq_reqbuf);
471         LASSERT(request->rq_pool);
472
473         reqbuf = request->rq_reqbuf;
474         memset(request, 0, sizeof(*request));
475         request->rq_reqbuf = reqbuf;
476         request->rq_reqbuf_len = pool->prp_rq_size;
477         request->rq_pool = pool;
478
479         return request;
480 }
481
482 static void __ptlrpc_free_req_to_pool(struct ptlrpc_request *request)
483 {
484         struct ptlrpc_request_pool *pool = request->rq_pool;
485
486         spin_lock(&pool->prp_lock);
487         LASSERT(list_empty(&request->rq_list));
488         list_add_tail(&request->rq_list, &pool->prp_req_list);
489         spin_unlock(&pool->prp_lock);
490 }
491
492 static int __ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
493                                       __u32 version, int opcode,
494                                       int count, __u32 *lengths, char **bufs,
495                                       struct ptlrpc_cli_ctx *ctx)
496 {
497         struct obd_import  *imp = request->rq_import;
498         int                 rc;
499         ENTRY;
500
501         if (unlikely(ctx))
502                 request->rq_cli_ctx = sptlrpc_cli_ctx_get(ctx);
503         else {
504                 rc = sptlrpc_req_get_ctx(request);
505                 if (rc)
506                         GOTO(out_free, rc);
507         }
508
509         sptlrpc_req_set_flavor(request, opcode);
510
511         rc = lustre_pack_request(request, imp->imp_msg_magic, count,
512                                  lengths, bufs);
513         if (rc) {
514                 LASSERT(!request->rq_pool);
515                 GOTO(out_ctx, rc);
516         }
517
518         lustre_msg_add_version(request->rq_reqmsg, version);
519         request->rq_send_state = LUSTRE_IMP_FULL;
520         request->rq_type = PTL_RPC_MSG_REQUEST;
521         request->rq_export = NULL;
522
523         request->rq_req_cbid.cbid_fn  = request_out_callback;
524         request->rq_req_cbid.cbid_arg = request;
525
526         request->rq_reply_cbid.cbid_fn  = reply_in_callback;
527         request->rq_reply_cbid.cbid_arg = request;
528
529         request->rq_phase = RQ_PHASE_NEW;
530
531         request->rq_request_portal = imp->imp_client->cli_request_portal;
532         request->rq_reply_portal = imp->imp_client->cli_reply_portal;
533
534         ptlrpc_at_set_req_timeout(request);
535
536         spin_lock_init(&request->rq_lock);
537         CFS_INIT_LIST_HEAD(&request->rq_list);
538         CFS_INIT_LIST_HEAD(&request->rq_timed_list);
539         CFS_INIT_LIST_HEAD(&request->rq_replay_list);
540         CFS_INIT_LIST_HEAD(&request->rq_mod_list);
541         CFS_INIT_LIST_HEAD(&request->rq_ctx_chain);
542         CFS_INIT_LIST_HEAD(&request->rq_set_chain);
543         CFS_INIT_LIST_HEAD(&request->rq_history_list);
544         cfs_waitq_init(&request->rq_reply_waitq);
545         request->rq_xid = ptlrpc_next_xid();
546         atomic_set(&request->rq_refcount, 1);
547
548         lustre_msg_set_opc(request->rq_reqmsg, opcode);
549
550         RETURN(0);
551 out_ctx:
552         sptlrpc_cli_ctx_put(request->rq_cli_ctx, 1);
553 out_free:
554         class_import_put(imp);
555         return rc;
556 }
557
558 int ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
559                              __u32 version, int opcode, char **bufs,
560                              struct ptlrpc_cli_ctx *ctx)
561 {
562         int count;
563
564         count = req_capsule_filled_sizes(&request->rq_pill, RCL_CLIENT);
565         return __ptlrpc_request_bufs_pack(request, version, opcode, count,
566                                           request->rq_pill.rc_area[RCL_CLIENT],
567                                           bufs, ctx);
568 }
569 EXPORT_SYMBOL(ptlrpc_request_bufs_pack);
570
571 int ptlrpc_request_pack(struct ptlrpc_request *request,
572                         __u32 version, int opcode) 
573 {
574         return ptlrpc_request_bufs_pack(request, version, opcode, NULL, NULL);
575 }
576
577 static inline
578 struct ptlrpc_request *__ptlrpc_request_alloc(struct obd_import *imp,
579                                               struct ptlrpc_request_pool *pool)
580 {
581         struct ptlrpc_request *request = NULL;
582
583         if (pool)
584                 request = ptlrpc_prep_req_from_pool(pool);
585
586         if (!request)
587                 OBD_ALLOC_PTR(request);
588
589         if (request) {
590                 LASSERT((unsigned long)imp > 0x1000);
591                 LASSERT(imp != LP_POISON);
592                 LASSERT((unsigned long)imp->imp_client > 0x1000);
593                 LASSERT(imp->imp_client != LP_POISON);
594
595                 request->rq_import = class_import_get(imp);
596         } else {
597                 CERROR("request allocation out of memory\n");
598         }
599
600         return request;
601 }
602
603 static struct ptlrpc_request *
604 ptlrpc_request_alloc_internal(struct obd_import *imp,
605                               struct ptlrpc_request_pool * pool,
606                               const struct req_format *format)
607 {
608         struct ptlrpc_request *request;
609
610         request = __ptlrpc_request_alloc(imp, pool);
611         if (request == NULL)
612                 return NULL;
613
614         req_capsule_init(&request->rq_pill, request, RCL_CLIENT);
615         req_capsule_set(&request->rq_pill, format);
616         return request;
617 }
618
619 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
620                                             const struct req_format *format)
621 {
622         return ptlrpc_request_alloc_internal(imp, NULL, format);
623 }
624
625 struct ptlrpc_request *ptlrpc_request_alloc_pool(struct obd_import *imp,
626                                             struct ptlrpc_request_pool * pool,
627                                             const struct req_format *format)
628 {
629         return ptlrpc_request_alloc_internal(imp, pool, format);
630 }
631
632 void ptlrpc_request_free(struct ptlrpc_request *request)
633 {
634         if (request->rq_pool)
635                 __ptlrpc_free_req_to_pool(request);
636         else
637                 OBD_FREE_PTR(request);
638 }
639
640 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *imp,
641                                                 const struct req_format *format,
642                                                 __u32 version, int opcode)
643 {
644         struct ptlrpc_request *req = ptlrpc_request_alloc(imp, format);
645         int                    rc;
646
647         if (req) {
648                 rc = ptlrpc_request_pack(req, version, opcode);
649                 if (rc) {
650                         ptlrpc_request_free(req);
651                         req = NULL;
652                 }
653         }
654         return req;
655 }
656
657 struct ptlrpc_request *
658 ptlrpc_prep_req_pool(struct obd_import *imp,
659                      __u32 version, int opcode,
660                      int count, __u32 *lengths, char **bufs,
661                      struct ptlrpc_request_pool *pool)
662 {
663         struct ptlrpc_request *request;
664         int                    rc;
665
666         request = __ptlrpc_request_alloc(imp, pool);
667         if (!request)
668                 return NULL;
669
670         rc = __ptlrpc_request_bufs_pack(request, version, opcode, count,
671                                         lengths, bufs, NULL);
672         if (rc) {
673                 ptlrpc_request_free(request);
674                 request = NULL;
675         }
676         return request;
677 }
678
679 struct ptlrpc_request *
680 ptlrpc_prep_req(struct obd_import *imp, __u32 version, int opcode, int count,
681                 __u32 *lengths, char **bufs)
682 {
683         return ptlrpc_prep_req_pool(imp, version, opcode, count, lengths, bufs,
684                                     NULL);
685 }
686
687 struct ptlrpc_request_set *ptlrpc_prep_set(void)
688 {
689         struct ptlrpc_request_set *set;
690
691         ENTRY;
692         OBD_ALLOC(set, sizeof *set);
693         if (!set)
694                 RETURN(NULL);
695         CFS_INIT_LIST_HEAD(&set->set_requests);
696         cfs_waitq_init(&set->set_waitq);
697         set->set_remaining = 0;
698         spin_lock_init(&set->set_new_req_lock);
699         CFS_INIT_LIST_HEAD(&set->set_new_requests);
700         CFS_INIT_LIST_HEAD(&set->set_cblist);
701         
702         RETURN(set);
703 }
704
705 /* Finish with this set; opposite of prep_set. */
706 void ptlrpc_set_destroy(struct ptlrpc_request_set *set)
707 {
708         struct list_head *tmp;
709         struct list_head *next;
710         int               expected_phase;
711         int               n = 0;
712         ENTRY;
713
714         /* Requests on the set should either all be completed, or all be new */
715         expected_phase = (set->set_remaining == 0) ?
716                          RQ_PHASE_COMPLETE : RQ_PHASE_NEW;
717         list_for_each (tmp, &set->set_requests) {
718                 struct ptlrpc_request *req =
719                         list_entry(tmp, struct ptlrpc_request, rq_set_chain);
720
721                 LASSERT(req->rq_phase == expected_phase);
722                 n++;
723         }
724
725         LASSERT(set->set_remaining == 0 || set->set_remaining == n);
726
727         list_for_each_safe(tmp, next, &set->set_requests) {
728                 struct ptlrpc_request *req =
729                         list_entry(tmp, struct ptlrpc_request, rq_set_chain);
730                 list_del_init(&req->rq_set_chain);
731
732                 LASSERT(req->rq_phase == expected_phase);
733
734                 if (req->rq_phase == RQ_PHASE_NEW) {
735
736                         if (req->rq_interpret_reply != NULL) {
737                                 int (*interpreter)(struct ptlrpc_request *,
738                                                    void *, int) =
739                                         req->rq_interpret_reply;
740
741                                 /* higher level (i.e. LOV) failed;
742                                  * let the sub reqs clean up */
743                                 req->rq_status = -EBADR;
744                                 interpreter(req, &req->rq_async_args,
745                                             req->rq_status);
746                         }
747                         set->set_remaining--;
748                 }
749
750                 req->rq_set = NULL;
751                 ptlrpc_req_finished (req);
752         }
753
754         LASSERT(set->set_remaining == 0);
755
756         OBD_FREE(set, sizeof(*set));
757         EXIT;
758 }
759
760 int ptlrpc_set_add_cb(struct ptlrpc_request_set *set,
761                       set_interpreter_func fn, void *data)
762 {
763         struct ptlrpc_set_cbdata *cbdata;
764
765         OBD_ALLOC_PTR(cbdata);
766         if (cbdata == NULL)
767                 RETURN(-ENOMEM);
768
769         cbdata->psc_interpret = fn;
770         cbdata->psc_data = data;
771         list_add_tail(&cbdata->psc_item, &set->set_cblist);
772
773         RETURN(0);
774 }
775
776 void ptlrpc_set_add_req(struct ptlrpc_request_set *set,
777                         struct ptlrpc_request *req)
778 {
779         /* The set takes over the caller's request reference */
780         list_add_tail(&req->rq_set_chain, &set->set_requests);
781         req->rq_set = set;
782         set->set_remaining++;
783
784         atomic_inc(&req->rq_import->imp_inflight);
785 }
786
787 /** 
788  * Lock so many callers can add things, the context that owns the set
789  * is supposed to notice these and move them into the set proper. 
790  */
791 int ptlrpc_set_add_new_req(struct ptlrpcd_ctl *pc,
792                            struct ptlrpc_request *req)
793 {
794         struct ptlrpc_request_set *set = pc->pc_set;
795
796         /* 
797          * Let caller know that we stopped and will not handle this request.
798          * It needs to take care itself of request.
799          */
800         if (test_bit(LIOD_STOP, &pc->pc_flags))
801                 return -EALREADY;
802
803         spin_lock(&set->set_new_req_lock);
804         /* 
805          * The set takes over the caller's request reference. 
806          */
807         list_add_tail(&req->rq_set_chain, &set->set_new_requests);
808         req->rq_set = set;
809         spin_unlock(&set->set_new_req_lock);
810
811         /*
812          * Let thead know that we added something and better it to wake up 
813          * and process.
814          */
815         cfs_waitq_signal(&set->set_waitq);
816         return 0;
817 }
818
819 /*
820  * Based on the current state of the import, determine if the request
821  * can be sent, is an error, or should be delayed.
822  *
823  * Returns true if this request should be delayed. If false, and
824  * *status is set, then the request can not be sent and *status is the
825  * error code.  If false and status is 0, then request can be sent.
826  *
827  * The imp->imp_lock must be held.
828  */
829 static int ptlrpc_import_delay_req(struct obd_import *imp,
830                                    struct ptlrpc_request *req, int *status)
831 {
832         int delay = 0;
833         ENTRY;
834
835         LASSERT (status != NULL);
836         *status = 0;
837
838         if (req->rq_ctx_init || req->rq_ctx_fini) {
839                 /* always allow ctx init/fini rpc go through */
840         } else if (imp->imp_state == LUSTRE_IMP_NEW) {
841                 DEBUG_REQ(D_ERROR, req, "Uninitialized import.");
842                 *status = -EIO;
843                 LBUG();
844         } else if (imp->imp_state == LUSTRE_IMP_CLOSED) {
845                 DEBUG_REQ(D_ERROR, req, "IMP_CLOSED ");
846                 *status = -EIO;
847         } else if (req->rq_send_state == LUSTRE_IMP_CONNECTING &&
848                    imp->imp_state == LUSTRE_IMP_CONNECTING) {
849                 /* allow CONNECT even if import is invalid */ ;
850                 if (atomic_read(&imp->imp_inval_count) != 0) {
851                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
852                         *status = -EIO;
853                 }
854         } else if ((imp->imp_invalid && (!imp->imp_recon_bk)) ||
855                                          imp->imp_obd->obd_no_recov) {
856                 /* If the import has been invalidated (such as by an OST
857                  * failure), and if the import(MGC) tried all of its connection
858                  * list (Bug 13464), the request must fail with -ESHUTDOWN.
859                  * This indicates the requests should be discarded; an -EIO
860                  * may result in a resend of the request. */
861                 if (!imp->imp_deactive)
862                           DEBUG_REQ(D_ERROR, req, "IMP_INVALID");
863                 *status = -ESHUTDOWN; /* bz 12940 */
864         } else if (req->rq_import_generation != imp->imp_generation) {
865                 DEBUG_REQ(D_ERROR, req, "req wrong generation:");
866                 *status = -EIO;
867         } else if (req->rq_send_state != imp->imp_state) {
868                 /* invalidate in progress - any requests should be drop */
869                 if (atomic_read(&imp->imp_inval_count) != 0) {
870                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
871                         *status = -EIO;
872                 } else if (imp->imp_dlm_fake || req->rq_no_delay) {
873                         *status = -EWOULDBLOCK;
874                 } else {
875                         delay = 1;
876                 }
877         }
878
879         RETURN(delay);
880 }
881
882 static int ptlrpc_check_reply(struct ptlrpc_request *req)
883 {
884         int rc = 0;
885         ENTRY;
886
887         /* serialise with network callback */
888         spin_lock(&req->rq_lock);
889
890         if (req->rq_replied)
891                 GOTO(out, rc = 1);
892
893         if (req->rq_net_err && !req->rq_timedout) {
894                 spin_unlock(&req->rq_lock);
895                 rc = ptlrpc_expire_one_request(req);
896                 spin_lock(&req->rq_lock);
897                 GOTO(out, rc);
898         }
899
900         if (req->rq_err)
901                 GOTO(out, rc = 1);
902
903         if (req->rq_resend)
904                 GOTO(out, rc = 1);
905
906         if (req->rq_restart)
907                 GOTO(out, rc = 1);
908
909         if (req->rq_early) {
910                 ptlrpc_at_recv_early_reply(req);
911                 GOTO(out, rc = 0); /* keep waiting */
912         }
913
914         EXIT;
915  out:
916         spin_unlock(&req->rq_lock);
917         DEBUG_REQ(D_NET, req, "rc = %d for", rc);
918         return rc;
919 }
920
921 static int ptlrpc_check_status(struct ptlrpc_request *req)
922 {
923         int err;
924         ENTRY;
925
926         err = lustre_msg_get_status(req->rq_repmsg);
927         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
928                 struct obd_import *imp = req->rq_import;
929                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
930                 LCONSOLE_ERROR_MSG(0x011,"an error occurred while communicating"
931                                 " with %s. The %s operation failed with %d\n",
932                                 libcfs_nid2str(imp->imp_connection->c_peer.nid),
933                                 ll_opcode2str(opc), err);
934                 RETURN(err < 0 ? err : -EINVAL);
935         }
936
937         if (err < 0) {
938                 DEBUG_REQ(D_INFO, req, "status is %d", err);
939         } else if (err > 0) {
940                 /* XXX: translate this error from net to host */
941                 DEBUG_REQ(D_INFO, req, "status is %d", err);
942         }
943
944         RETURN(err);
945 }
946
947 /**
948  * Callback function called when client receives RPC reply for \a req.
949  */
950 static int after_reply(struct ptlrpc_request *req)
951 {
952         struct obd_import *imp = req->rq_import;
953         struct obd_device *obd = req->rq_import->imp_obd;
954         int rc;
955         struct timeval work_start;
956         long timediff;
957         ENTRY;
958
959         LASSERT(!req->rq_receiving_reply);
960         LASSERT(obd);
961         LASSERT(req->rq_nob_received <= req->rq_repbuf_len);
962
963         /*
964          * NB Until this point, the whole of the incoming message,
965          * including buflens, status etc is in the sender's byte order. 
966          */
967
968         rc = sptlrpc_cli_unwrap_reply(req);
969         if (rc) {
970                 DEBUG_REQ(D_ERROR, req, "unwrap reply failed (%d):", rc);
971                 RETURN(rc);
972         }
973
974         /*
975          * Security layer unwrap might ask resend this request. 
976          */
977         if (req->rq_resend)
978                 RETURN(0);
979
980         rc = unpack_reply(req);
981         if (rc)
982                 RETURN(rc);
983
984         do_gettimeofday(&work_start);
985         timediff = cfs_timeval_sub(&work_start, &req->rq_arrival_time, NULL);
986         if (obd->obd_svc_stats != NULL)
987                 lprocfs_counter_add(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR,
988                                     timediff);
989
990         if (lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_REPLY &&
991             lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_ERR) {
992                 DEBUG_REQ(D_ERROR, req, "invalid packet received (type=%u)",
993                           lustre_msg_get_type(req->rq_repmsg));
994                 RETURN(-EPROTO);
995         }
996
997         OBD_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_PAUSE_REP, obd_fail_val);
998         ptlrpc_at_adj_service(req);
999         ptlrpc_at_adj_net_latency(req);
1000
1001         rc = ptlrpc_check_status(req);
1002         imp->imp_connect_error = rc;
1003
1004         if (rc) {
1005                 /*
1006                  * Either we've been evicted, or the server has failed for
1007                  * some reason. Try to reconnect, and if that fails, punt to
1008                  * the upcall. 
1009                  */
1010                 if (ll_rpc_recoverable_error(rc)) {
1011                         if (req->rq_send_state != LUSTRE_IMP_FULL ||
1012                             imp->imp_obd->obd_no_recov || imp->imp_dlm_fake) {
1013                                 RETURN(rc);
1014                         }
1015                         ptlrpc_request_handle_notconn(req);
1016                         RETURN(rc);
1017                 }
1018         } else {
1019                 /*
1020                  * Let's look if server sent slv. Do it only for RPC with 
1021                  * rc == 0. 
1022                  */
1023                 ldlm_cli_update_pool(req);
1024         }
1025
1026         /*
1027          * Store transno in reqmsg for replay. 
1028          */
1029         req->rq_transno = lustre_msg_get_transno(req->rq_repmsg);
1030         lustre_msg_set_transno(req->rq_reqmsg, req->rq_transno);
1031
1032         if (req->rq_import->imp_replayable) {
1033                 spin_lock(&imp->imp_lock);
1034                 /*
1035                  * No point in adding already-committed requests to the replay
1036                  * list, we will just remove them immediately. b=9829 
1037                  */
1038                 if (req->rq_transno != 0 && 
1039                     (req->rq_transno > 
1040                      lustre_msg_get_last_committed(req->rq_repmsg) ||
1041                      req->rq_replay))
1042                         ptlrpc_retain_replayable_request(req, imp);
1043                 else if (req->rq_commit_cb != NULL) {
1044                         spin_unlock(&imp->imp_lock);
1045                         req->rq_commit_cb(req);
1046                         spin_lock(&imp->imp_lock);
1047                 }
1048
1049                 /*
1050                  * Replay-enabled imports return commit-status information. 
1051                  */
1052                 if (lustre_msg_get_last_committed(req->rq_repmsg)) {
1053                         imp->imp_peer_committed_transno =
1054                                 lustre_msg_get_last_committed(req->rq_repmsg);
1055                 }
1056                 ptlrpc_free_committed(imp);
1057                 spin_unlock(&imp->imp_lock);
1058         }
1059
1060         RETURN(rc);
1061 }
1062
1063 static int ptlrpc_send_new_req(struct ptlrpc_request *req)
1064 {
1065         struct obd_import     *imp;
1066         int rc;
1067         ENTRY;
1068
1069         LASSERT(req->rq_phase == RQ_PHASE_NEW);
1070         if (req->rq_sent && (req->rq_sent > cfs_time_current_sec()))
1071                 RETURN (0);
1072         
1073         req->rq_phase = RQ_PHASE_RPC;
1074
1075         imp = req->rq_import;
1076         spin_lock(&imp->imp_lock);
1077
1078         req->rq_import_generation = imp->imp_generation;
1079
1080         if (ptlrpc_import_delay_req(imp, req, &rc)) {
1081                 spin_lock (&req->rq_lock);
1082                 req->rq_waiting = 1;
1083                 spin_unlock (&req->rq_lock);
1084
1085                 DEBUG_REQ(D_HA, req, "req from PID %d waiting for recovery: "
1086                           "(%s != %s)",
1087                           lustre_msg_get_status(req->rq_reqmsg) ,
1088                           ptlrpc_import_state_name(req->rq_send_state),
1089                           ptlrpc_import_state_name(imp->imp_state));
1090                 LASSERT(list_empty (&req->rq_list));
1091
1092                 list_add_tail(&req->rq_list, &imp->imp_delayed_list);
1093                 spin_unlock(&imp->imp_lock);
1094                 RETURN(0);
1095         }
1096
1097         if (rc != 0) {
1098                 spin_unlock(&imp->imp_lock);
1099                 req->rq_status = rc;
1100                 req->rq_phase = RQ_PHASE_INTERPRET;
1101                 RETURN(rc);
1102         }
1103
1104         /* XXX this is the same as ptlrpc_queue_wait */
1105         LASSERT(list_empty(&req->rq_list));
1106         list_add_tail(&req->rq_list, &imp->imp_sending_list);
1107         spin_unlock(&imp->imp_lock);
1108
1109         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
1110
1111         rc = sptlrpc_req_refresh_ctx(req, -1);
1112         if (rc) {
1113                 if (req->rq_err) {
1114                         req->rq_status = rc;
1115                         RETURN(1);
1116                 } else {
1117                         /* here begins timeout counting */
1118                         req->rq_sent = cfs_time_current_sec();
1119                         req->rq_wait_ctx = 1;
1120                         RETURN(0);
1121                 }
1122         }
1123
1124         CDEBUG(D_RPCTRACE, "Sending RPC pname:cluuid:pid:xid:nid:opc"
1125                " %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1126                imp->imp_obd->obd_uuid.uuid,
1127                lustre_msg_get_status(req->rq_reqmsg), req->rq_xid,
1128                libcfs_nid2str(imp->imp_connection->c_peer.nid),
1129                lustre_msg_get_opc(req->rq_reqmsg));
1130
1131         rc = ptl_send_rpc(req, 0);
1132         if (rc) {
1133                 DEBUG_REQ(D_HA, req, "send failed (%d); expect timeout", rc);
1134                 req->rq_net_err = 1;
1135                 RETURN(rc);
1136         }
1137         RETURN(0);
1138 }
1139
1140 /* this sends any unsent RPCs in @set and returns TRUE if all are sent */
1141 int ptlrpc_check_set(struct ptlrpc_request_set *set)
1142 {
1143         struct list_head *tmp;
1144         int force_timer_recalc = 0;
1145         ENTRY;
1146
1147         if (set->set_remaining == 0)
1148                 RETURN(1);
1149
1150         list_for_each(tmp, &set->set_requests) {
1151                 struct ptlrpc_request *req =
1152                         list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1153                 struct obd_import *imp = req->rq_import;
1154                 int rc = 0;
1155
1156                 if (req->rq_phase == RQ_PHASE_NEW &&
1157                     ptlrpc_send_new_req(req)) {
1158                         force_timer_recalc = 1;
1159                 }
1160                 /* delayed send - skip */
1161                 if (req->rq_phase == RQ_PHASE_NEW && req->rq_sent)
1162                         continue;
1163
1164                 if (!(req->rq_phase == RQ_PHASE_RPC ||
1165                       req->rq_phase == RQ_PHASE_BULK ||
1166                       req->rq_phase == RQ_PHASE_INTERPRET ||
1167                       req->rq_phase == RQ_PHASE_COMPLETE)) {
1168                         DEBUG_REQ(D_ERROR, req, "bad phase %x", req->rq_phase);
1169                         LBUG();
1170                 }
1171
1172                 if (req->rq_phase == RQ_PHASE_COMPLETE)
1173                         continue;
1174
1175                 if (req->rq_phase == RQ_PHASE_INTERPRET)
1176                         GOTO(interpret, req->rq_status);
1177
1178                 if (req->rq_net_err && !req->rq_timedout)
1179                         ptlrpc_expire_one_request(req);
1180
1181                 if (req->rq_err) {
1182                         ptlrpc_unregister_reply(req);
1183                         req->rq_replied = 0;
1184                         if (req->rq_status == 0)
1185                                 req->rq_status = -EIO;
1186                         req->rq_phase = RQ_PHASE_INTERPRET;
1187
1188                         spin_lock(&imp->imp_lock);
1189                         list_del_init(&req->rq_list);
1190                         spin_unlock(&imp->imp_lock);
1191
1192                         GOTO(interpret, req->rq_status);
1193                 }
1194
1195                 /* ptlrpc_queue_wait->l_wait_event guarantees that rq_intr
1196                  * will only be set after rq_timedout, but the oig waiting
1197                  * path sets rq_intr irrespective of whether ptlrpcd has
1198                  * seen a timeout.  our policy is to only interpret
1199                  * interrupted rpcs after they have timed out */
1200                 if (req->rq_intr && (req->rq_timedout || req->rq_waiting ||
1201                                      req->rq_wait_ctx)) {
1202                         /* NB could be on delayed list */
1203                         ptlrpc_unregister_reply(req);
1204                         req->rq_status = -EINTR;
1205                         req->rq_phase = RQ_PHASE_INTERPRET;
1206
1207                         spin_lock(&imp->imp_lock);
1208                         list_del_init(&req->rq_list);
1209                         spin_unlock(&imp->imp_lock);
1210
1211                         GOTO(interpret, req->rq_status);
1212                 }
1213
1214                 if (req->rq_phase == RQ_PHASE_RPC) {
1215                         if (req->rq_timedout || req->rq_resend ||
1216                             req->rq_waiting || req->rq_wait_ctx) {
1217                                 int status;
1218
1219                                 /* rq_wait_ctx is only touched in ptlrpcd,
1220                                  * no lock needed here.
1221                                  */
1222                                 if (req->rq_wait_ctx)
1223                                         goto check_ctx;
1224
1225                                 ptlrpc_unregister_reply(req);
1226
1227                                 spin_lock(&imp->imp_lock);
1228
1229                                 if (ptlrpc_import_delay_req(imp, req, &status)){
1230                                         spin_unlock(&imp->imp_lock);
1231                                         continue;
1232                                 }
1233
1234                                 list_del_init(&req->rq_list);
1235                                 if (status != 0)  {
1236                                         req->rq_status = status;
1237                                         req->rq_phase = RQ_PHASE_INTERPRET;
1238                                         spin_unlock(&imp->imp_lock);
1239                                         GOTO(interpret, req->rq_status);
1240                                 }
1241                                 if (req->rq_no_resend && !req->rq_wait_ctx) {
1242                                         req->rq_status = -ENOTCONN;
1243                                         req->rq_phase = RQ_PHASE_INTERPRET;
1244                                         spin_unlock(&imp->imp_lock);
1245                                         GOTO(interpret, req->rq_status);
1246                                 }
1247                                 list_add_tail(&req->rq_list,
1248                                               &imp->imp_sending_list);
1249
1250                                 spin_unlock(&imp->imp_lock);
1251
1252                                 req->rq_waiting = 0;
1253                                 if (req->rq_resend) {
1254                                         lustre_msg_add_flags(req->rq_reqmsg,
1255                                                              MSG_RESENT);
1256                                         if (req->rq_bulk) {
1257                                                 __u64 old_xid = req->rq_xid;
1258
1259                                                 ptlrpc_unregister_bulk (req);
1260
1261                                                 /* ensure previous bulk fails */
1262                                                 req->rq_xid = ptlrpc_next_xid();
1263                                                 CDEBUG(D_HA, "resend bulk "
1264                                                        "old x"LPU64
1265                                                        " new x"LPU64"\n",
1266                                                        old_xid, req->rq_xid);
1267                                         }
1268                                 }
1269 check_ctx:
1270                                 status = sptlrpc_req_refresh_ctx(req, -1);
1271                                 if (status) {
1272                                         if (req->rq_err) {
1273                                                 req->rq_status = status;
1274                                                 force_timer_recalc = 1;
1275                                         }
1276                                         if (!req->rq_wait_ctx) {
1277                                                 /* begins timeout counting */
1278                                                 req->rq_sent = cfs_time_current_sec();
1279                                                 req->rq_wait_ctx = 1;
1280                                         }
1281                                         continue;
1282                                 } else {
1283                                         req->rq_sent = 0;
1284                                         req->rq_wait_ctx = 0;
1285                                 }
1286
1287                                 rc = ptl_send_rpc(req, 0);
1288                                 if (rc) {
1289                                         DEBUG_REQ(D_HA, req, "send failed (%d)",
1290                                                   rc);
1291                                         force_timer_recalc = 1;
1292                                         req->rq_net_err = 1;
1293                                 }
1294                                 /* need to reset the timeout */
1295                                 force_timer_recalc = 1;
1296                         }
1297
1298                         spin_lock(&req->rq_lock);
1299
1300                         if (req->rq_early) {
1301                                 ptlrpc_at_recv_early_reply(req);
1302                                 spin_unlock(&req->rq_lock);
1303                                 continue;
1304                         }
1305
1306                         /* Still waiting for a reply? */
1307                         if (req->rq_receiving_reply) {
1308                                 spin_unlock(&req->rq_lock);
1309                                 continue;
1310                         }
1311
1312                         /* Did we actually receive a reply? */
1313                         if (!req->rq_replied) {
1314                                 spin_unlock(&req->rq_lock);
1315                                 continue;
1316                         }
1317
1318                         spin_unlock(&req->rq_lock);
1319
1320                         spin_lock(&imp->imp_lock);
1321                         list_del_init(&req->rq_list);
1322                         spin_unlock(&imp->imp_lock);
1323
1324                         req->rq_status = after_reply(req);
1325                         if (req->rq_resend) {
1326                                 /* Add this req to the delayed list so
1327                                    it can be errored if the import is
1328                                    evicted after recovery. */
1329                                 spin_lock(&imp->imp_lock);
1330                                 list_add_tail(&req->rq_list,
1331                                               &imp->imp_delayed_list);
1332                                 spin_unlock(&imp->imp_lock);
1333                                 continue;
1334                         }
1335
1336                         /* If there is no bulk associated with this request,
1337                          * then we're done and should let the interpreter
1338                          * process the reply.  Similarly if the RPC returned
1339                          * an error, and therefore the bulk will never arrive.
1340                          */
1341                         if (req->rq_bulk == NULL || req->rq_status != 0) {
1342                                 req->rq_phase = RQ_PHASE_INTERPRET;
1343                                 GOTO(interpret, req->rq_status);
1344                         }
1345
1346                         req->rq_phase = RQ_PHASE_BULK;
1347                 }
1348
1349                 LASSERT(req->rq_phase == RQ_PHASE_BULK);
1350                 if (ptlrpc_bulk_active(req->rq_bulk))
1351                         continue;
1352
1353                 if (!req->rq_bulk->bd_success) {
1354                         /* The RPC reply arrived OK, but the bulk screwed
1355                          * up!  Dead wierd since the server told us the RPC
1356                          * was good after getting the REPLY for her GET or
1357                          * the ACK for her PUT. */
1358                         DEBUG_REQ(D_ERROR, req, "bulk transfer failed");
1359                         LBUG();
1360                 }
1361
1362                 req->rq_phase = RQ_PHASE_INTERPRET;
1363
1364         interpret:
1365                 LASSERT(req->rq_phase == RQ_PHASE_INTERPRET);
1366                 LASSERT(!req->rq_receiving_reply);
1367
1368                 ptlrpc_unregister_reply(req);
1369                 if (req->rq_bulk != NULL)
1370                         ptlrpc_unregister_bulk (req);
1371
1372                 if (req->rq_interpret_reply != NULL) {
1373                         int (*interpreter)(struct ptlrpc_request *,void *,int) =
1374                                 req->rq_interpret_reply;
1375                         req->rq_status = interpreter(req, &req->rq_async_args,
1376                                                      req->rq_status);
1377                 }
1378                 req->rq_phase = RQ_PHASE_COMPLETE;
1379
1380                 CDEBUG(D_RPCTRACE, "Completed RPC pname:cluuid:pid:xid:nid:"
1381                        "opc %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1382                        imp->imp_obd->obd_uuid.uuid,
1383                        lustre_msg_get_status(req->rq_reqmsg), req->rq_xid,
1384                        libcfs_nid2str(imp->imp_connection->c_peer.nid),
1385                        lustre_msg_get_opc(req->rq_reqmsg));
1386
1387                 atomic_dec(&imp->imp_inflight);
1388                 set->set_remaining--;
1389                 cfs_waitq_signal(&imp->imp_recovery_waitq);
1390         }
1391
1392         /* If we hit an error, we want to recover promptly. */
1393         RETURN(set->set_remaining == 0 || force_timer_recalc);
1394 }
1395
1396 /* Return 1 if we should give up, else 0 */
1397 int ptlrpc_expire_one_request(struct ptlrpc_request *req)
1398 {
1399         struct obd_import *imp = req->rq_import;
1400         int rc = 0;
1401         ENTRY;
1402
1403         DEBUG_REQ(D_ERROR|D_NETERROR, req,
1404                   "%s (sent at "CFS_TIME_T", "CFS_DURATION_T"s ago)",
1405                   req->rq_net_err ? "network error" : "timeout",
1406                   req->rq_sent, cfs_time_sub(cfs_time_current_sec(),
1407                   req->rq_sent));
1408
1409         if (imp) {
1410                 LCONSOLE_WARN("Request x"LPU64" sent from %s to NID %s "
1411                               CFS_DURATION_T"s ago has timed out "
1412                               "(limit "CFS_DURATION_T"s).\n", req->rq_xid,
1413                               req->rq_import->imp_obd->obd_name,
1414                               libcfs_nid2str(imp->imp_connection->c_peer.nid),
1415                               cfs_time_sub(cfs_time_current_sec(), req->rq_sent),
1416                               cfs_time_sub(req->rq_deadline, req->rq_sent));
1417         }
1418
1419         if (imp != NULL && obd_debug_peer_on_timeout)
1420                 LNetCtl(IOC_LIBCFS_DEBUG_PEER, &imp->imp_connection->c_peer);
1421
1422         spin_lock(&req->rq_lock);
1423         req->rq_timedout = 1;
1424         req->rq_wait_ctx = 0;
1425         spin_unlock(&req->rq_lock);
1426
1427         ptlrpc_unregister_reply (req);
1428
1429         if (obd_dump_on_timeout)
1430                 libcfs_debug_dumplog();
1431
1432         if (req->rq_bulk != NULL)
1433                 ptlrpc_unregister_bulk (req);
1434
1435         if (imp == NULL) {
1436                 DEBUG_REQ(D_HA, req, "NULL import: already cleaned up?");
1437                 RETURN(1);
1438         }
1439
1440         /* The DLM server doesn't want recovery run on its imports. */
1441         if (imp->imp_dlm_fake)
1442                 RETURN(1);
1443
1444         /* If this request is for recovery or other primordial tasks,
1445          * then error it out here. */
1446         if (req->rq_ctx_init || req->rq_ctx_fini ||
1447             req->rq_send_state != LUSTRE_IMP_FULL ||
1448             imp->imp_obd->obd_no_recov) {
1449                 DEBUG_REQ(D_RPCTRACE, req, "err -110, sent_state=%s (now=%s)",
1450                           ptlrpc_import_state_name(req->rq_send_state),
1451                           ptlrpc_import_state_name(imp->imp_state));
1452                 spin_lock(&req->rq_lock);
1453                 req->rq_status = -ETIMEDOUT;
1454                 req->rq_err = 1;
1455                 spin_unlock(&req->rq_lock);
1456                 RETURN(1);
1457         }
1458         
1459         /* if a request can't be resent we can't wait for an answer after
1460            the timeout */
1461         if (req->rq_no_resend) {
1462                 DEBUG_REQ(D_RPCTRACE, req, "TIMEOUT-NORESEND:");
1463                 rc = 1;
1464         }
1465
1466         ptlrpc_fail_import(imp, lustre_msg_get_conn_cnt(req->rq_reqmsg));
1467
1468         RETURN(rc);
1469 }
1470
1471 int ptlrpc_expired_set(void *data)
1472 {
1473         struct ptlrpc_request_set *set = data;
1474         struct list_head          *tmp;
1475         time_t                     now = cfs_time_current_sec();
1476         ENTRY;
1477
1478         LASSERT(set != NULL);
1479
1480         /* A timeout expired; see which reqs it applies to... */
1481         list_for_each (tmp, &set->set_requests) {
1482                 struct ptlrpc_request *req =
1483                         list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1484
1485                 /* request in-flight? */
1486                 if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting &&
1487                        !req->rq_resend) ||
1488                       (req->rq_phase == RQ_PHASE_BULK)))
1489                         continue;
1490
1491                 if (req->rq_timedout ||           /* already dealt with */
1492                     req->rq_deadline > now)       /* not expired */
1493                         continue;
1494
1495                 /* deal with this guy */
1496                 ptlrpc_expire_one_request (req);
1497         }
1498
1499         /* When waiting for a whole set, we always to break out of the
1500          * sleep so we can recalculate the timeout, or enable interrupts
1501          * iff everyone's timed out.
1502          */
1503         RETURN(1);
1504 }
1505
1506 void ptlrpc_mark_interrupted(struct ptlrpc_request *req)
1507 {
1508         spin_lock(&req->rq_lock);
1509         req->rq_intr = 1;
1510         spin_unlock(&req->rq_lock);
1511 }
1512
1513 void ptlrpc_interrupted_set(void *data)
1514 {
1515         struct ptlrpc_request_set *set = data;
1516         struct list_head *tmp;
1517
1518         LASSERT(set != NULL);
1519         CERROR("INTERRUPTED SET %p\n", set);
1520
1521         list_for_each(tmp, &set->set_requests) {
1522                 struct ptlrpc_request *req =
1523                         list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1524
1525                 if (req->rq_phase != RQ_PHASE_RPC)
1526                         continue;
1527
1528                 ptlrpc_mark_interrupted(req);
1529         }
1530 }
1531
1532 /* get the smallest timeout in the set; this does NOT set a timeout. */
1533 int ptlrpc_set_next_timeout(struct ptlrpc_request_set *set)
1534 {
1535         struct list_head      *tmp;
1536         time_t                 now = cfs_time_current_sec();
1537         int                    timeout = 0;
1538         struct ptlrpc_request *req;
1539         int                    deadline;
1540         ENTRY;
1541
1542         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
1543
1544         list_for_each(tmp, &set->set_requests) {
1545                 req = list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1546
1547                 /* request in-flight? */
1548                 if (!((req->rq_phase == RQ_PHASE_RPC && !req->rq_waiting) ||
1549                       (req->rq_phase == RQ_PHASE_BULK) ||
1550                       (req->rq_phase == RQ_PHASE_NEW)))
1551                         continue;
1552
1553                 if (req->rq_timedout)   /* already timed out */
1554                         continue;
1555
1556                 if (req->rq_phase == RQ_PHASE_NEW)
1557                         deadline = req->rq_sent;
1558                 else
1559                         deadline = req->rq_sent + req->rq_timeout;
1560
1561                 if (deadline <= now)    /* actually expired already */
1562                         timeout = 1;    /* ASAP */
1563                 else if (timeout == 0 || timeout > deadline - now)
1564                         timeout = deadline - now;
1565         }
1566         RETURN(timeout);
1567 }
1568
1569 int ptlrpc_set_wait(struct ptlrpc_request_set *set)
1570 {
1571         struct list_head      *tmp;
1572         struct ptlrpc_request *req;
1573         struct l_wait_info     lwi;
1574         int                    rc, timeout;
1575         ENTRY;
1576
1577         if (list_empty(&set->set_requests))
1578                 RETURN(0);
1579
1580         list_for_each(tmp, &set->set_requests) {
1581                 req = list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1582                 if (req->rq_phase == RQ_PHASE_NEW)
1583                         (void)ptlrpc_send_new_req(req);
1584         }
1585
1586         do {
1587                 timeout = ptlrpc_set_next_timeout(set);
1588
1589                 /* wait until all complete, interrupted, or an in-flight
1590                  * req times out */
1591                 CDEBUG(D_RPCTRACE, "set %p going to sleep for %d seconds\n",
1592                        set, timeout);
1593                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(timeout ? timeout : 1),
1594                                        ptlrpc_expired_set,
1595                                        ptlrpc_interrupted_set, set);
1596                 rc = l_wait_event(set->set_waitq, ptlrpc_check_set(set), &lwi);
1597
1598                 LASSERT(rc == 0 || rc == -EINTR || rc == -ETIMEDOUT);
1599
1600                 /* -EINTR => all requests have been flagged rq_intr so next
1601                  * check completes.
1602                  * -ETIMEOUTD => someone timed out.  When all reqs have
1603                  * timed out, signals are enabled allowing completion with
1604                  * EINTR.
1605                  * I don't really care if we go once more round the loop in
1606                  * the error cases -eeb. */
1607         } while (rc != 0 || set->set_remaining != 0);
1608
1609         LASSERT(set->set_remaining == 0);
1610
1611         rc = 0;
1612         list_for_each(tmp, &set->set_requests) {
1613                 req = list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1614
1615                 LASSERT(req->rq_phase == RQ_PHASE_COMPLETE);
1616                 if (req->rq_status != 0)
1617                         rc = req->rq_status;
1618         }
1619
1620         if (set->set_interpret != NULL) {
1621                 int (*interpreter)(struct ptlrpc_request_set *set,void *,int) =
1622                         set->set_interpret;
1623                 rc = interpreter (set, set->set_arg, rc);
1624         } else {
1625                 struct ptlrpc_set_cbdata *cbdata, *n;
1626                 int err;
1627
1628                 list_for_each_entry_safe(cbdata, n,
1629                                          &set->set_cblist, psc_item) {
1630                         list_del_init(&cbdata->psc_item);
1631                         err = cbdata->psc_interpret(set, cbdata->psc_data, rc);
1632                         if (err && !rc)
1633                                 rc = err;
1634                         OBD_FREE_PTR(cbdata);
1635                 }
1636         }
1637
1638         RETURN(rc);
1639 }
1640
1641 static void __ptlrpc_free_req(struct ptlrpc_request *request, int locked)
1642 {
1643         ENTRY;
1644         if (request == NULL) {
1645                 EXIT;
1646                 return;
1647         }
1648
1649         LASSERTF(!request->rq_receiving_reply, "req %p\n", request);
1650         LASSERTF(request->rq_rqbd == NULL, "req %p\n",request);/* client-side */
1651         LASSERTF(list_empty(&request->rq_list), "req %p\n", request);
1652         LASSERTF(list_empty(&request->rq_set_chain), "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);