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