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