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