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