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