Whamcloud - gitweb
ae3565f749686ec5e5810e451547c3218ceff4e9
[fs/lustre-release.git] / lustre / ptlrpc / client.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 /** Implementation of client-side PortalRPC interfaces */
38
39 #define DEBUG_SUBSYSTEM S_RPC
40 #ifndef __KERNEL__
41 #include <errno.h>
42 #include <signal.h>
43 #include <liblustre.h>
44 #endif
45
46 #include <obd_support.h>
47 #include <obd_class.h>
48 #include <lustre_lib.h>
49 #include <lustre_ha.h>
50 #include <lustre_import.h>
51 #include <lustre_req_layout.h>
52
53 #include "ptlrpc_internal.h"
54
55 /**
56  * Initialize passed in client structure \a cl.
57  */
58 void ptlrpc_init_client(int req_portal, int rep_portal, char *name,
59                         struct ptlrpc_client *cl)
60 {
61         cl->cli_request_portal = req_portal;
62         cl->cli_reply_portal   = rep_portal;
63         cl->cli_name           = name;
64 }
65
66 /**
67  * Return PortalRPC connection for remore uud \a uuid
68  */
69 struct ptlrpc_connection *ptlrpc_uuid_to_connection(struct obd_uuid *uuid)
70 {
71         struct ptlrpc_connection *c;
72         lnet_nid_t                self;
73         lnet_process_id_t         peer;
74         int                       err;
75
76         err = ptlrpc_uuid_to_peer(uuid, &peer, &self);
77         if (err != 0) {
78                 CNETERR("cannot find peer %s!\n", uuid->uuid);
79                 return NULL;
80         }
81
82         c = ptlrpc_connection_get(peer, self, uuid);
83         if (c) {
84                 memcpy(c->c_remote_uuid.uuid,
85                        uuid->uuid, sizeof(c->c_remote_uuid.uuid));
86         }
87
88         CDEBUG(D_INFO, "%s -> %p\n", uuid->uuid, c);
89
90         return c;
91 }
92
93 /**
94  * Allocate and initialize new bulk descriptor
95  * Returns pointer to the descriptor or NULL on error.
96  */
97 static inline struct ptlrpc_bulk_desc *new_bulk(int npages, int type, int portal)
98 {
99         struct ptlrpc_bulk_desc *desc;
100
101         OBD_ALLOC(desc, offsetof (struct ptlrpc_bulk_desc, bd_iov[npages]));
102         if (!desc)
103                 return NULL;
104
105         cfs_spin_lock_init(&desc->bd_lock);
106         cfs_waitq_init(&desc->bd_waitq);
107         desc->bd_max_iov = npages;
108         desc->bd_iov_count = 0;
109         LNetInvalidateHandle(&desc->bd_md_h);
110         desc->bd_portal = portal;
111         desc->bd_type = type;
112
113         return desc;
114 }
115
116 /**
117  * Prepare bulk descriptor for specified outgoing request \a req that
118  * can fit \a npages * pages. \a type is bulk type. \a portal is where
119  * the bulk to be sent. Used on client-side.
120  * Returns pointer to newly allocatrd initialized bulk descriptor or NULL on
121  * error.
122  */
123 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_imp(struct ptlrpc_request *req,
124                                               int npages, int type, int portal)
125 {
126         struct obd_import *imp = req->rq_import;
127         struct ptlrpc_bulk_desc *desc;
128
129         ENTRY;
130         LASSERT(type == BULK_PUT_SINK || type == BULK_GET_SOURCE);
131         desc = new_bulk(npages, type, portal);
132         if (desc == NULL)
133                 RETURN(NULL);
134
135         desc->bd_import_generation = req->rq_import_generation;
136         desc->bd_import = class_import_get(imp);
137         desc->bd_req = req;
138
139         desc->bd_cbid.cbid_fn  = client_bulk_callback;
140         desc->bd_cbid.cbid_arg = desc;
141
142         /* This makes req own desc, and free it when she frees herself */
143         req->rq_bulk = desc;
144
145         return desc;
146 }
147
148 /**
149  * Prepare bulk descriptor for specified incoming request \a req that
150  * can fit \a npages * pages. \a type is bulk type. \a portal is where
151  * the bulk to be sent. Used on server-side after request was already
152  * received.
153  * Returns pointer to newly allocatrd initialized bulk descriptor or NULL on
154  * error.
155  */
156 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_exp(struct ptlrpc_request *req,
157                                               int npages, int type, int portal)
158 {
159         struct obd_export *exp = req->rq_export;
160         struct ptlrpc_bulk_desc *desc;
161
162         ENTRY;
163         LASSERT(type == BULK_PUT_SOURCE || type == BULK_GET_SINK);
164
165         desc = new_bulk(npages, type, portal);
166         if (desc == NULL)
167                 RETURN(NULL);
168
169         desc->bd_export = class_export_get(exp);
170         desc->bd_req = req;
171
172         desc->bd_cbid.cbid_fn  = server_bulk_callback;
173         desc->bd_cbid.cbid_arg = desc;
174
175         /* NB we don't assign rq_bulk here; server-side requests are
176          * re-used, and the handler frees the bulk desc explicitly. */
177
178         return desc;
179 }
180
181 /**
182  * Add a page \a page to the bulk descriptor \a desc.
183  * Data to transfer in the page starts at offset \a pageoffset and
184  * amount of data to transfer from the page is \a len
185  */
186 void ptlrpc_prep_bulk_page(struct ptlrpc_bulk_desc *desc,
187                            cfs_page_t *page, int pageoffset, int len)
188 {
189         LASSERT(desc->bd_iov_count < desc->bd_max_iov);
190         LASSERT(page != NULL);
191         LASSERT(pageoffset >= 0);
192         LASSERT(len > 0);
193         LASSERT(pageoffset + len <= CFS_PAGE_SIZE);
194
195         desc->bd_nob += len;
196
197         cfs_page_pin(page);
198         ptlrpc_add_bulk_page(desc, page, pageoffset, len);
199 }
200
201 /**
202  * Uninitialize and free bulk descriptor \a desc.
203  * Works on bulk descriptors both from server and client side.
204  */
205 void ptlrpc_free_bulk(struct ptlrpc_bulk_desc *desc)
206 {
207         int i;
208         ENTRY;
209
210         LASSERT(desc != NULL);
211         LASSERT(desc->bd_iov_count != LI_POISON); /* not freed already */
212         LASSERT(!desc->bd_network_rw);         /* network hands off or */
213         LASSERT((desc->bd_export != NULL) ^ (desc->bd_import != NULL));
214
215         sptlrpc_enc_pool_put_pages(desc);
216
217         if (desc->bd_export)
218                 class_export_put(desc->bd_export);
219         else
220                 class_import_put(desc->bd_import);
221
222         for (i = 0; i < desc->bd_iov_count ; i++)
223                 cfs_page_unpin(desc->bd_iov[i].kiov_page);
224
225         OBD_FREE(desc, offsetof(struct ptlrpc_bulk_desc,
226                                 bd_iov[desc->bd_max_iov]));
227         EXIT;
228 }
229
230 /**
231  * Set server timelimit for this req, i.e. how long are we willing to wait
232  * for reply before timing out this request.
233  */
234 void ptlrpc_at_set_req_timeout(struct ptlrpc_request *req)
235 {
236         __u32 serv_est;
237         int idx;
238         struct imp_at *at;
239
240         LASSERT(req->rq_import);
241
242         if (AT_OFF) {
243                 /* non-AT settings */
244                 /**
245                  * \a imp_server_timeout means this is reverse import and
246                  * we send (currently only) ASTs to the client and cannot afford
247                  * to wait too long for the reply, otherwise the other client
248                  * (because of which we are sending this request) would
249                  * timeout waiting for us
250                  */
251                 req->rq_timeout = req->rq_import->imp_server_timeout ?
252                                   obd_timeout / 2 : obd_timeout;
253         } else {
254                 at = &req->rq_import->imp_at;
255                 idx = import_at_get_index(req->rq_import,
256                                           req->rq_request_portal);
257                 serv_est = at_get(&at->iat_service_estimate[idx]);
258                 req->rq_timeout = at_est2timeout(serv_est);
259         }
260         /* We could get even fancier here, using history to predict increased
261            loading... */
262
263         /* Let the server know what this RPC timeout is by putting it in the
264            reqmsg*/
265         lustre_msg_set_timeout(req->rq_reqmsg, req->rq_timeout);
266 }
267
268 /* Adjust max service estimate based on server value */
269 static void ptlrpc_at_adj_service(struct ptlrpc_request *req,
270                                   unsigned int serv_est)
271 {
272         int idx;
273         unsigned int oldse;
274         struct imp_at *at;
275
276         LASSERT(req->rq_import);
277         at = &req->rq_import->imp_at;
278
279         idx = import_at_get_index(req->rq_import, req->rq_request_portal);
280         /* max service estimates are tracked on the server side,
281            so just keep minimal history here */
282         oldse = at_measured(&at->iat_service_estimate[idx], serv_est);
283         if (oldse != 0)
284                 CDEBUG(D_ADAPTTO, "The RPC service estimate for %s ptl %d "
285                        "has changed from %d to %d\n",
286                        req->rq_import->imp_obd->obd_name,req->rq_request_portal,
287                        oldse, at_get(&at->iat_service_estimate[idx]));
288 }
289
290 /* Expected network latency per remote node (secs) */
291 int ptlrpc_at_get_net_latency(struct ptlrpc_request *req)
292 {
293         return AT_OFF ? 0 : at_get(&req->rq_import->imp_at.iat_net_latency);
294 }
295
296 /* Adjust expected network latency */
297 static void ptlrpc_at_adj_net_latency(struct ptlrpc_request *req,
298                                       unsigned int service_time)
299 {
300         unsigned int nl, oldnl;
301         struct imp_at *at;
302         time_t now = cfs_time_current_sec();
303
304         LASSERT(req->rq_import);
305         at = &req->rq_import->imp_at;
306
307         /* Network latency is total time less server processing time */
308         nl = max_t(int, now - req->rq_sent - service_time, 0) +1/*st rounding*/;
309         if (service_time > now - req->rq_sent + 3 /* bz16408 */)
310                 CWARN("Reported service time %u > total measured time "
311                       CFS_DURATION_T"\n", service_time,
312                       cfs_time_sub(now, req->rq_sent));
313
314         oldnl = at_measured(&at->iat_net_latency, nl);
315         if (oldnl != 0)
316                 CDEBUG(D_ADAPTTO, "The network latency for %s (nid %s) "
317                        "has changed from %d to %d\n",
318                        req->rq_import->imp_obd->obd_name,
319                        obd_uuid2str(
320                                &req->rq_import->imp_connection->c_remote_uuid),
321                        oldnl, at_get(&at->iat_net_latency));
322 }
323
324 static int unpack_reply(struct ptlrpc_request *req)
325 {
326         int rc;
327
328         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
329                 rc = ptlrpc_unpack_rep_msg(req, req->rq_replen);
330                 if (rc) {
331                         DEBUG_REQ(D_ERROR, req, "unpack_rep failed: %d", rc);
332                         return(-EPROTO);
333                 }
334         }
335
336         rc = lustre_unpack_rep_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
337         if (rc) {
338                 DEBUG_REQ(D_ERROR, req, "unpack ptlrpc body failed: %d", rc);
339                 return(-EPROTO);
340         }
341         return 0;
342 }
343
344 /**
345  * Handle an early reply message, called with the rq_lock held.
346  * If anything goes wrong just ignore it - same as if it never happened
347  */
348 static int ptlrpc_at_recv_early_reply(struct ptlrpc_request *req)
349 {
350         struct ptlrpc_request *early_req;
351         time_t                 olddl;
352         int                    rc;
353         ENTRY;
354
355         req->rq_early = 0;
356         cfs_spin_unlock(&req->rq_lock);
357
358         rc = sptlrpc_cli_unwrap_early_reply(req, &early_req);
359         if (rc) {
360                 cfs_spin_lock(&req->rq_lock);
361                 RETURN(rc);
362         }
363
364         rc = unpack_reply(early_req);
365         if (rc == 0) {
366                 /* Expecting to increase the service time estimate here */
367                 ptlrpc_at_adj_service(req,
368                         lustre_msg_get_timeout(early_req->rq_repmsg));
369                 ptlrpc_at_adj_net_latency(req,
370                         lustre_msg_get_service_time(early_req->rq_repmsg));
371         }
372
373         sptlrpc_cli_finish_early_reply(early_req);
374
375         cfs_spin_lock(&req->rq_lock);
376
377         if (rc == 0) {
378                 /* Adjust the local timeout for this req */
379                 ptlrpc_at_set_req_timeout(req);
380
381                 olddl = req->rq_deadline;
382                 /* server assumes it now has rq_timeout from when it sent the
383                    early reply, so client should give it at least that long. */
384                 req->rq_deadline = cfs_time_current_sec() + req->rq_timeout +
385                             ptlrpc_at_get_net_latency(req);
386
387                 DEBUG_REQ(D_ADAPTTO, req,
388                           "Early reply #%d, new deadline in "CFS_DURATION_T"s "
389                           "("CFS_DURATION_T"s)", req->rq_early_count,
390                           cfs_time_sub(req->rq_deadline,
391                                        cfs_time_current_sec()),
392                           cfs_time_sub(req->rq_deadline, olddl));
393         }
394
395         RETURN(rc);
396 }
397
398 /**
399  * Wind down request pool \a pool.
400  * Frees all requests from the pool too
401  */
402 void ptlrpc_free_rq_pool(struct ptlrpc_request_pool *pool)
403 {
404         cfs_list_t *l, *tmp;
405         struct ptlrpc_request *req;
406
407         LASSERT(pool != NULL);
408
409         cfs_spin_lock(&pool->prp_lock);
410         cfs_list_for_each_safe(l, tmp, &pool->prp_req_list) {
411                 req = cfs_list_entry(l, struct ptlrpc_request, rq_list);
412                 cfs_list_del(&req->rq_list);
413                 LASSERT(req->rq_reqbuf);
414                 LASSERT(req->rq_reqbuf_len == pool->prp_rq_size);
415                 OBD_FREE_LARGE(req->rq_reqbuf, pool->prp_rq_size);
416                 OBD_FREE(req, sizeof(*req));
417         }
418         cfs_spin_unlock(&pool->prp_lock);
419         OBD_FREE(pool, sizeof(*pool));
420 }
421
422 /**
423  * Allocates, initializes and adds \a num_rq requests to the pool \a pool
424  */
425 void ptlrpc_add_rqs_to_pool(struct ptlrpc_request_pool *pool, int num_rq)
426 {
427         int i;
428         int size = 1;
429
430         while (size < pool->prp_rq_size)
431                 size <<= 1;
432
433         LASSERTF(cfs_list_empty(&pool->prp_req_list) ||
434                  size == pool->prp_rq_size,
435                  "Trying to change pool size with nonempty pool "
436                  "from %d to %d bytes\n", pool->prp_rq_size, size);
437
438         cfs_spin_lock(&pool->prp_lock);
439         pool->prp_rq_size = size;
440         for (i = 0; i < num_rq; i++) {
441                 struct ptlrpc_request *req;
442                 struct lustre_msg *msg;
443
444                 cfs_spin_unlock(&pool->prp_lock);
445                 OBD_ALLOC(req, sizeof(struct ptlrpc_request));
446                 if (!req)
447                         return;
448                 OBD_ALLOC_LARGE(msg, size);
449                 if (!msg) {
450                         OBD_FREE(req, sizeof(struct ptlrpc_request));
451                         return;
452                 }
453                 req->rq_reqbuf = msg;
454                 req->rq_reqbuf_len = size;
455                 req->rq_pool = pool;
456                 cfs_spin_lock(&pool->prp_lock);
457                 cfs_list_add_tail(&req->rq_list, &pool->prp_req_list);
458         }
459         cfs_spin_unlock(&pool->prp_lock);
460         return;
461 }
462
463 /**
464  * Create and initialize new request pool with given attributes:
465  * \a num_rq - initial number of requests to create for the pool
466  * \a msgsize - maximum message size possible for requests in thid pool
467  * \a populate_pool - function to be called when more requests need to be added
468  *                    to the pool
469  * Returns pointer to newly created pool or NULL on error.
470  */
471 struct ptlrpc_request_pool *
472 ptlrpc_init_rq_pool(int num_rq, int msgsize,
473                     void (*populate_pool)(struct ptlrpc_request_pool *, int))
474 {
475         struct ptlrpc_request_pool *pool;
476
477         OBD_ALLOC(pool, sizeof (struct ptlrpc_request_pool));
478         if (!pool)
479                 return NULL;
480
481         /* Request next power of two for the allocation, because internally
482            kernel would do exactly this */
483
484         cfs_spin_lock_init(&pool->prp_lock);
485         CFS_INIT_LIST_HEAD(&pool->prp_req_list);
486         pool->prp_rq_size = msgsize + SPTLRPC_MAX_PAYLOAD;
487         pool->prp_populate = populate_pool;
488
489         populate_pool(pool, num_rq);
490
491         if (cfs_list_empty(&pool->prp_req_list)) {
492                 /* have not allocated a single request for the pool */
493                 OBD_FREE(pool, sizeof (struct ptlrpc_request_pool));
494                 pool = NULL;
495         }
496         return pool;
497 }
498
499 /**
500  * Fetches one request from pool \a pool
501  */
502 static struct ptlrpc_request *
503 ptlrpc_prep_req_from_pool(struct ptlrpc_request_pool *pool)
504 {
505         struct ptlrpc_request *request;
506         struct lustre_msg *reqbuf;
507
508         if (!pool)
509                 return NULL;
510
511         cfs_spin_lock(&pool->prp_lock);
512
513         /* See if we have anything in a pool, and bail out if nothing,
514          * in writeout path, where this matters, this is safe to do, because
515          * nothing is lost in this case, and when some in-flight requests
516          * complete, this code will be called again. */
517         if (unlikely(cfs_list_empty(&pool->prp_req_list))) {
518                 cfs_spin_unlock(&pool->prp_lock);
519                 return NULL;
520         }
521
522         request = cfs_list_entry(pool->prp_req_list.next, struct ptlrpc_request,
523                                  rq_list);
524         cfs_list_del_init(&request->rq_list);
525         cfs_spin_unlock(&pool->prp_lock);
526
527         LASSERT(request->rq_reqbuf);
528         LASSERT(request->rq_pool);
529
530         reqbuf = request->rq_reqbuf;
531         memset(request, 0, sizeof(*request));
532         request->rq_reqbuf = reqbuf;
533         request->rq_reqbuf_len = pool->prp_rq_size;
534         request->rq_pool = pool;
535
536         return request;
537 }
538
539 /**
540  * Returns freed \a request to pool.
541  */
542 static void __ptlrpc_free_req_to_pool(struct ptlrpc_request *request)
543 {
544         struct ptlrpc_request_pool *pool = request->rq_pool;
545
546         cfs_spin_lock(&pool->prp_lock);
547         LASSERT(cfs_list_empty(&request->rq_list));
548         LASSERT(!request->rq_receiving_reply);
549         cfs_list_add_tail(&request->rq_list, &pool->prp_req_list);
550         cfs_spin_unlock(&pool->prp_lock);
551 }
552
553 static int __ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
554                                       __u32 version, int opcode,
555                                       int count, __u32 *lengths, char **bufs,
556                                       struct ptlrpc_cli_ctx *ctx)
557 {
558         struct obd_import  *imp = request->rq_import;
559         int                 rc;
560         ENTRY;
561
562         if (unlikely(ctx))
563                 request->rq_cli_ctx = sptlrpc_cli_ctx_get(ctx);
564         else {
565                 rc = sptlrpc_req_get_ctx(request);
566                 if (rc)
567                         GOTO(out_free, rc);
568         }
569
570         sptlrpc_req_set_flavor(request, opcode);
571
572         rc = lustre_pack_request(request, imp->imp_msg_magic, count,
573                                  lengths, bufs);
574         if (rc) {
575                 LASSERT(!request->rq_pool);
576                 GOTO(out_ctx, rc);
577         }
578
579         lustre_msg_add_version(request->rq_reqmsg, version);
580         request->rq_send_state = LUSTRE_IMP_FULL;
581         request->rq_type = PTL_RPC_MSG_REQUEST;
582         request->rq_export = NULL;
583
584         request->rq_req_cbid.cbid_fn  = request_out_callback;
585         request->rq_req_cbid.cbid_arg = request;
586
587         request->rq_reply_cbid.cbid_fn  = reply_in_callback;
588         request->rq_reply_cbid.cbid_arg = request;
589
590         request->rq_reply_deadline = 0;
591         request->rq_phase = RQ_PHASE_NEW;
592         request->rq_next_phase = RQ_PHASE_UNDEFINED;
593
594         request->rq_request_portal = imp->imp_client->cli_request_portal;
595         request->rq_reply_portal = imp->imp_client->cli_reply_portal;
596
597         ptlrpc_at_set_req_timeout(request);
598
599         cfs_spin_lock_init(&request->rq_lock);
600         CFS_INIT_LIST_HEAD(&request->rq_list);
601         CFS_INIT_LIST_HEAD(&request->rq_timed_list);
602         CFS_INIT_LIST_HEAD(&request->rq_replay_list);
603         CFS_INIT_LIST_HEAD(&request->rq_ctx_chain);
604         CFS_INIT_LIST_HEAD(&request->rq_set_chain);
605         CFS_INIT_LIST_HEAD(&request->rq_history_list);
606         CFS_INIT_LIST_HEAD(&request->rq_exp_list);
607         cfs_waitq_init(&request->rq_reply_waitq);
608         cfs_waitq_init(&request->rq_set_waitq);
609         request->rq_xid = ptlrpc_next_xid();
610         cfs_atomic_set(&request->rq_refcount, 1);
611
612         lustre_msg_set_opc(request->rq_reqmsg, opcode);
613
614         RETURN(0);
615 out_ctx:
616         sptlrpc_cli_ctx_put(request->rq_cli_ctx, 1);
617 out_free:
618         class_import_put(imp);
619         return rc;
620 }
621
622 int ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
623                              __u32 version, int opcode, char **bufs,
624                              struct ptlrpc_cli_ctx *ctx)
625 {
626         int count;
627
628         count = req_capsule_filled_sizes(&request->rq_pill, RCL_CLIENT);
629         return __ptlrpc_request_bufs_pack(request, version, opcode, count,
630                                           request->rq_pill.rc_area[RCL_CLIENT],
631                                           bufs, ctx);
632 }
633 EXPORT_SYMBOL(ptlrpc_request_bufs_pack);
634
635 /**
636  * Pack request buffers for network transfer, performing necessary encryption
637  * steps if necessary.
638  */
639 int ptlrpc_request_pack(struct ptlrpc_request *request,
640                         __u32 version, int opcode)
641 {
642         return ptlrpc_request_bufs_pack(request, version, opcode, NULL, NULL);
643 }
644
645 /**
646  * Helper function to allocate new request on import \a imp
647  * and possibly using existing request from pool \a pool if provided.
648  * Returns allocated request structure with import field filled or
649  * NULL on error.
650  */
651 static inline
652 struct ptlrpc_request *__ptlrpc_request_alloc(struct obd_import *imp,
653                                               struct ptlrpc_request_pool *pool)
654 {
655         struct ptlrpc_request *request = NULL;
656
657         if (pool)
658                 request = ptlrpc_prep_req_from_pool(pool);
659
660         if (!request)
661                 OBD_ALLOC_PTR(request);
662
663         if (request) {
664                 LASSERTF((unsigned long)imp > 0x1000, "%p", imp);
665                 LASSERT(imp != LP_POISON);
666                 LASSERTF((unsigned long)imp->imp_client > 0x1000, "%p",
667                         imp->imp_client);
668                 LASSERT(imp->imp_client != LP_POISON);
669
670                 request->rq_import = class_import_get(imp);
671         } else {
672                 CERROR("request allocation out of memory\n");
673         }
674
675         return request;
676 }
677
678 /**
679  * Helper function for creating a request.
680  * Calls __ptlrpc_request_alloc to allocate new request sturcture and inits
681  * buffer structures according to capsule template \a format.
682  * Returns allocated request structure pointer or NULL on error.
683  */
684 static struct ptlrpc_request *
685 ptlrpc_request_alloc_internal(struct obd_import *imp,
686                               struct ptlrpc_request_pool * pool,
687                               const struct req_format *format)
688 {
689         struct ptlrpc_request *request;
690
691         request = __ptlrpc_request_alloc(imp, pool);
692         if (request == NULL)
693                 return NULL;
694
695         req_capsule_init(&request->rq_pill, request, RCL_CLIENT);
696         req_capsule_set(&request->rq_pill, format);
697         return request;
698 }
699
700 /**
701  * Allocate new request structure for import \a imp and initialize its
702  * buffer structure according to capsule template \a format.
703  */
704 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
705                                             const struct req_format *format)
706 {
707         return ptlrpc_request_alloc_internal(imp, NULL, format);
708 }
709
710 /**
711  * Allocate new request structure for import \a imp from pool \a pool and
712  * initialize its buffer structure according to capsule template \a format.
713  */
714 struct ptlrpc_request *ptlrpc_request_alloc_pool(struct obd_import *imp,
715                                             struct ptlrpc_request_pool * pool,
716                                             const struct req_format *format)
717 {
718         return ptlrpc_request_alloc_internal(imp, pool, format);
719 }
720
721 /**
722  * For requests not from pool, free memory of the request structure.
723  * For requests obtained from a pool earlier, return request back to pool.
724  */
725 void ptlrpc_request_free(struct ptlrpc_request *request)
726 {
727         if (request->rq_pool)
728                 __ptlrpc_free_req_to_pool(request);
729         else
730                 OBD_FREE_PTR(request);
731 }
732
733 /**
734  * Allocate new request for operatione \a opcode and immediatelly pack it for
735  * network transfer.
736  * Only used for simple requests like OBD_PING where the only important
737  * part of the request is operation itself.
738  * Returns allocated request or NULL on error.
739  */
740 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *imp,
741                                                 const struct req_format *format,
742                                                 __u32 version, int opcode)
743 {
744         struct ptlrpc_request *req = ptlrpc_request_alloc(imp, format);
745         int                    rc;
746
747         if (req) {
748                 rc = ptlrpc_request_pack(req, version, opcode);
749                 if (rc) {
750                         ptlrpc_request_free(req);
751                         req = NULL;
752                 }
753         }
754         return req;
755 }
756
757 /**
758  * Prepare request (fetched from pool \a poolif not NULL) on import \a imp
759  * for operation \a opcode. Request would contain \a count buffers.
760  * Sizes of buffers are described in array \a lengths and buffers themselves
761  * are provided by a pointer \a bufs.
762  * Returns prepared request structure pointer or NULL on error.
763  */
764 struct ptlrpc_request *
765 ptlrpc_prep_req_pool(struct obd_import *imp,
766                      __u32 version, int opcode,
767                      int count, __u32 *lengths, char **bufs,
768                      struct ptlrpc_request_pool *pool)
769 {
770         struct ptlrpc_request *request;
771         int                    rc;
772
773         request = __ptlrpc_request_alloc(imp, pool);
774         if (!request)
775                 return NULL;
776
777         rc = __ptlrpc_request_bufs_pack(request, version, opcode, count,
778                                         lengths, bufs, NULL);
779         if (rc) {
780                 ptlrpc_request_free(request);
781                 request = NULL;
782         }
783         return request;
784 }
785
786 /**
787  * Same as ptlrpc_prep_req_pool, but without pool
788  */
789 struct ptlrpc_request *
790 ptlrpc_prep_req(struct obd_import *imp, __u32 version, int opcode, int count,
791                 __u32 *lengths, char **bufs)
792 {
793         return ptlrpc_prep_req_pool(imp, version, opcode, count, lengths, bufs,
794                                     NULL);
795 }
796
797 /**
798  * Allocate "fake" request that would not be sent anywhere in the end.
799  * Only used as a hack because we have no other way of performing
800  * async actions in lustre between layers.
801  * Used on MDS to request object preallocations from more than one OST at a
802  * time.
803  */
804 struct ptlrpc_request *ptlrpc_prep_fakereq(struct obd_import *imp,
805                                            unsigned int timeout,
806                                            ptlrpc_interpterer_t interpreter)
807 {
808         struct ptlrpc_request *request = NULL;
809         ENTRY;
810
811         OBD_ALLOC(request, sizeof(*request));
812         if (!request) {
813                 CERROR("request allocation out of memory\n");
814                 RETURN(NULL);
815         }
816
817         request->rq_send_state = LUSTRE_IMP_FULL;
818         request->rq_type = PTL_RPC_MSG_REQUEST;
819         request->rq_import = class_import_get(imp);
820         request->rq_export = NULL;
821         request->rq_import_generation = imp->imp_generation;
822
823         request->rq_timeout = timeout;
824         request->rq_sent = cfs_time_current_sec();
825         request->rq_deadline = request->rq_sent + timeout;
826         request->rq_reply_deadline = request->rq_deadline;
827         request->rq_interpret_reply = interpreter;
828         request->rq_phase = RQ_PHASE_RPC;
829         request->rq_next_phase = RQ_PHASE_INTERPRET;
830         /* don't want reply */
831         request->rq_receiving_reply = 0;
832         request->rq_must_unlink = 0;
833         request->rq_no_delay = request->rq_no_resend = 1;
834         request->rq_fake = 1;
835
836         cfs_spin_lock_init(&request->rq_lock);
837         CFS_INIT_LIST_HEAD(&request->rq_list);
838         CFS_INIT_LIST_HEAD(&request->rq_replay_list);
839         CFS_INIT_LIST_HEAD(&request->rq_set_chain);
840         CFS_INIT_LIST_HEAD(&request->rq_history_list);
841         CFS_INIT_LIST_HEAD(&request->rq_exp_list);
842         cfs_waitq_init(&request->rq_reply_waitq);
843         cfs_waitq_init(&request->rq_set_waitq);
844
845         request->rq_xid = ptlrpc_next_xid();
846         cfs_atomic_set(&request->rq_refcount, 1);
847
848         RETURN(request);
849 }
850
851 /**
852  * Indicate that processing of "fake" request is finished.
853  */
854 void ptlrpc_fakereq_finished(struct ptlrpc_request *req)
855 {
856         /* if we kill request before timeout - need adjust counter */
857         if (req->rq_phase == RQ_PHASE_RPC) {
858                 struct ptlrpc_request_set *set = req->rq_set;
859
860                 if (set)
861                         cfs_atomic_dec(&set->set_remaining);
862         }
863
864         ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
865         cfs_list_del_init(&req->rq_list);
866 }
867
868 /**
869  * Allocate and initialize new request set structure.
870  * Returns a pointer to the newly allocated set structure or NULL on error.
871  */
872 struct ptlrpc_request_set *ptlrpc_prep_set(void)
873 {
874         struct ptlrpc_request_set *set;
875
876         ENTRY;
877         OBD_ALLOC(set, sizeof *set);
878         if (!set)
879                 RETURN(NULL);
880         CFS_INIT_LIST_HEAD(&set->set_requests);
881         cfs_waitq_init(&set->set_waitq);
882         cfs_atomic_set(&set->set_remaining, 0);
883         cfs_spin_lock_init(&set->set_new_req_lock);
884         CFS_INIT_LIST_HEAD(&set->set_new_requests);
885         CFS_INIT_LIST_HEAD(&set->set_cblist);
886
887         RETURN(set);
888 }
889
890 /**
891  * Wind down and free request set structure previously allocated with
892  * ptlrpc_prep_set.
893  * Ensures that all requests on the set have completed and removes
894  * all requests from the request list in a set.
895  * If any unsent request happen to be on the list, pretends that they got
896  * an error in flight and calls their completion handler.
897  */
898 void ptlrpc_set_destroy(struct ptlrpc_request_set *set)
899 {
900         cfs_list_t       *tmp;
901         cfs_list_t       *next;
902         int               expected_phase;
903         int               n = 0;
904         ENTRY;
905
906         /* Requests on the set should either all be completed, or all be new */
907         expected_phase = (cfs_atomic_read(&set->set_remaining) == 0) ?
908                          RQ_PHASE_COMPLETE : RQ_PHASE_NEW;
909         cfs_list_for_each (tmp, &set->set_requests) {
910                 struct ptlrpc_request *req =
911                         cfs_list_entry(tmp, struct ptlrpc_request,
912                                        rq_set_chain);
913
914                 LASSERT(req->rq_phase == expected_phase);
915                 n++;
916         }
917
918         LASSERTF(cfs_atomic_read(&set->set_remaining) == 0 || 
919                  cfs_atomic_read(&set->set_remaining) == n, "%d / %d\n",
920                  cfs_atomic_read(&set->set_remaining), n);
921
922         cfs_list_for_each_safe(tmp, next, &set->set_requests) {
923                 struct ptlrpc_request *req =
924                         cfs_list_entry(tmp, struct ptlrpc_request,
925                                        rq_set_chain);
926                 cfs_list_del_init(&req->rq_set_chain);
927
928                 LASSERT(req->rq_phase == expected_phase);
929
930                 if (req->rq_phase == RQ_PHASE_NEW) {
931                         ptlrpc_req_interpret(NULL, req, -EBADR);
932                         cfs_atomic_dec(&set->set_remaining);
933                 }
934
935                 cfs_spin_lock(&req->rq_lock);
936                 req->rq_set = NULL;
937                 req->rq_invalid_rqset = 0;
938                 cfs_spin_unlock(&req->rq_lock);
939
940                 ptlrpc_req_finished (req);
941         }
942
943         LASSERT(cfs_atomic_read(&set->set_remaining) == 0);
944
945         OBD_FREE(set, sizeof(*set));
946         EXIT;
947 }
948
949 /**
950  * Add a callback function \a fn to the set.
951  * This function would be called when all requests on this set are completed.
952  * The function will be passed \a data argument.
953  */
954 int ptlrpc_set_add_cb(struct ptlrpc_request_set *set,
955                       set_interpreter_func fn, void *data)
956 {
957         struct ptlrpc_set_cbdata *cbdata;
958
959         OBD_ALLOC_PTR(cbdata);
960         if (cbdata == NULL)
961                 RETURN(-ENOMEM);
962
963         cbdata->psc_interpret = fn;
964         cbdata->psc_data = data;
965         cfs_list_add_tail(&cbdata->psc_item, &set->set_cblist);
966
967         RETURN(0);
968 }
969
970 /**
971  * Add a new request to the general purpose request set.
972  * Assumes request reference from the caller.
973  */
974 void ptlrpc_set_add_req(struct ptlrpc_request_set *set,
975                         struct ptlrpc_request *req)
976 {
977         /* The set takes over the caller's request reference */
978         cfs_list_add_tail(&req->rq_set_chain, &set->set_requests);
979         req->rq_set = set;
980         cfs_atomic_inc(&set->set_remaining);
981         req->rq_queued_time = cfs_time_current(); /* Where is the best place to set this? */
982 }
983
984 /**
985  * Add a request to a request with dedicated server thread
986  * and wake the thread to make any necessary processing.
987  * Currently only used for ptlrpcd.
988  * Returns 0 if succesful or non zero error code on error.
989  * (the only possible error for now is if the dedicated server thread
990  * is shutting down)
991  */
992 int ptlrpc_set_add_new_req(struct ptlrpcd_ctl *pc,
993                            struct ptlrpc_request *req)
994 {
995         struct ptlrpc_request_set *set = pc->pc_set;
996
997         /*
998          * Let caller know that we stopped and will not handle this request.
999          * It needs to take care itself of request.
1000          */
1001         if (cfs_test_bit(LIOD_STOP, &pc->pc_flags))
1002                 return -EALREADY;
1003
1004         cfs_spin_lock(&set->set_new_req_lock);
1005         /*
1006          * The set takes over the caller's request reference.
1007          */
1008         cfs_list_add_tail(&req->rq_set_chain, &set->set_new_requests);
1009         req->rq_set = set;
1010         cfs_spin_unlock(&set->set_new_req_lock);
1011
1012         cfs_waitq_signal(&set->set_waitq);
1013         return 0;
1014 }
1015
1016 /**
1017  * Based on the current state of the import, determine if the request
1018  * can be sent, is an error, or should be delayed.
1019  *
1020  * Returns true if this request should be delayed. If false, and
1021  * *status is set, then the request can not be sent and *status is the
1022  * error code.  If false and status is 0, then request can be sent.
1023  *
1024  * The imp->imp_lock must be held.
1025  */
1026 static int ptlrpc_import_delay_req(struct obd_import *imp,
1027                                    struct ptlrpc_request *req, int *status)
1028 {
1029         int delay = 0;
1030         ENTRY;
1031
1032         LASSERT (status != NULL);
1033         *status = 0;
1034
1035         if (req->rq_ctx_init || req->rq_ctx_fini) {
1036                 /* always allow ctx init/fini rpc go through */
1037         } else if (imp->imp_state == LUSTRE_IMP_NEW) {
1038                 DEBUG_REQ(D_ERROR, req, "Uninitialized import.");
1039                 *status = -EIO;
1040                 LBUG();
1041         } else if (imp->imp_state == LUSTRE_IMP_CLOSED) {
1042                 DEBUG_REQ(D_ERROR, req, "IMP_CLOSED ");
1043                 *status = -EIO;
1044         } else if (ptlrpc_send_limit_expired(req)) {
1045                 /* probably doesn't need to be a D_ERROR after initial testing */
1046                 DEBUG_REQ(D_ERROR, req, "send limit expired ");
1047                 *status = -EIO;
1048         } else if (req->rq_send_state == LUSTRE_IMP_CONNECTING &&
1049                    imp->imp_state == LUSTRE_IMP_CONNECTING) {
1050                 /* allow CONNECT even if import is invalid */ ;
1051                 if (cfs_atomic_read(&imp->imp_inval_count) != 0) {
1052                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
1053                         *status = -EIO;
1054                 }
1055         } else if (imp->imp_invalid || imp->imp_obd->obd_no_recov) {
1056                 if (!imp->imp_deactive)
1057                           DEBUG_REQ(D_ERROR, req, "IMP_INVALID");
1058                 *status = -ESHUTDOWN; /* bz 12940 */
1059         } else if (req->rq_import_generation != imp->imp_generation) {
1060                 DEBUG_REQ(D_ERROR, req, "req wrong generation:");
1061                 *status = -EIO;
1062         } else if (req->rq_send_state != imp->imp_state) {
1063                 /* invalidate in progress - any requests should be drop */
1064                 if (cfs_atomic_read(&imp->imp_inval_count) != 0) {
1065                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
1066                         *status = -EIO;
1067                 } else if (imp->imp_dlm_fake || req->rq_no_delay) {
1068                         *status = -EWOULDBLOCK;
1069                 } else {
1070                         delay = 1;
1071                 }
1072         }
1073
1074         RETURN(delay);
1075 }
1076
1077 /**
1078  * Decide if the eror message regarding provided request \a req
1079  * should be printed to the console or not.
1080  * Makes it's decision on request status and other properties.
1081  * Returns 1 to print error on the system console or 0 if not.
1082  */
1083 static int ptlrpc_console_allow(struct ptlrpc_request *req)
1084 {
1085         __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1086         int err;
1087
1088         /* Suppress particular reconnect errors which are to be expected.  No
1089          * errors are suppressed for the initial connection on an import */
1090         if ((lustre_handle_is_used(&req->rq_import->imp_remote_handle)) &&
1091             (opc == OST_CONNECT || opc == MDS_CONNECT || opc == MGS_CONNECT)) {
1092
1093                 /* Suppress timed out reconnect requests */
1094                 if (req->rq_timedout)
1095                         return 0;
1096
1097                 /* Suppress unavailable/again reconnect requests */
1098                 err = lustre_msg_get_status(req->rq_repmsg);
1099                 if (err == -ENODEV || err == -EAGAIN)
1100                         return 0;
1101         }
1102
1103         return 1;
1104 }
1105
1106 /**
1107  * Check request processing status.
1108  * Returns the status.
1109  */
1110 static int ptlrpc_check_status(struct ptlrpc_request *req)
1111 {
1112         int err;
1113         ENTRY;
1114
1115         err = lustre_msg_get_status(req->rq_repmsg);
1116         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
1117                 struct obd_import *imp = req->rq_import;
1118                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1119                 LCONSOLE_ERROR_MSG(0x011,"an error occurred while communicating"
1120                                 " with %s. The %s operation failed with %d\n",
1121                                 libcfs_nid2str(imp->imp_connection->c_peer.nid),
1122                                 ll_opcode2str(opc), err);
1123                 RETURN(err < 0 ? err : -EINVAL);
1124         }
1125
1126         if (err < 0) {
1127                 DEBUG_REQ(D_INFO, req, "status is %d", err);
1128         } else if (err > 0) {
1129                 /* XXX: translate this error from net to host */
1130                 DEBUG_REQ(D_INFO, req, "status is %d", err);
1131         }
1132
1133         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
1134                 struct obd_import *imp = req->rq_import;
1135                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1136
1137                 if (ptlrpc_console_allow(req))
1138                         LCONSOLE_ERROR_MSG(0x011,"an error occurred while "
1139                                            "communicating with %s. The %s "
1140                                            "operation failed with %d\n",
1141                                            libcfs_nid2str(
1142                                            imp->imp_connection->c_peer.nid),
1143                                            ll_opcode2str(opc), err);
1144
1145                 RETURN(err < 0 ? err : -EINVAL);
1146         }
1147
1148         RETURN(err);
1149 }
1150
1151 /**
1152  * save pre-versions of objects into request for replay.
1153  * Versions are obtained from server reply.
1154  * used for VBR.
1155  */
1156 static void ptlrpc_save_versions(struct ptlrpc_request *req)
1157 {
1158         struct lustre_msg *repmsg = req->rq_repmsg;
1159         struct lustre_msg *reqmsg = req->rq_reqmsg;
1160         __u64 *versions = lustre_msg_get_versions(repmsg);
1161         ENTRY;
1162
1163         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1164                 return;
1165
1166         LASSERT(versions);
1167         lustre_msg_set_versions(reqmsg, versions);
1168         CDEBUG(D_INFO, "Client save versions ["LPX64"/"LPX64"]\n",
1169                versions[0], versions[1]);
1170
1171         EXIT;
1172 }
1173
1174 /**
1175  * Callback function called when client receives RPC reply for \a req.
1176  * Returns 0 on success or error code.
1177  * The return alue would be assigned to req->rq_status by the caller
1178  * as request processing status.
1179  * This function also decides if the request needs to be saved for later replay.
1180  */
1181 static int after_reply(struct ptlrpc_request *req)
1182 {
1183         struct obd_import *imp = req->rq_import;
1184         struct obd_device *obd = req->rq_import->imp_obd;
1185         int rc;
1186         struct timeval work_start;
1187         long timediff;
1188         ENTRY;
1189
1190         LASSERT(obd != NULL);
1191         /* repbuf must be unlinked */
1192         LASSERT(!req->rq_receiving_reply && !req->rq_must_unlink);
1193
1194         if (req->rq_reply_truncate) {
1195                 if (ptlrpc_no_resend(req)) {
1196                         DEBUG_REQ(D_ERROR, req, "reply buffer overflow,"
1197                                   " expected: %d, actual size: %d",
1198                                   req->rq_nob_received, req->rq_repbuf_len);
1199                         RETURN(-EOVERFLOW);
1200                 }
1201
1202                 sptlrpc_cli_free_repbuf(req);
1203                 /* Pass the required reply buffer size (include
1204                  * space for early reply).
1205                  * NB: no need to roundup because alloc_repbuf
1206                  * will roundup it */
1207                 req->rq_replen       = req->rq_nob_received;
1208                 req->rq_nob_received = 0;
1209                 req->rq_resend       = 1;
1210                 RETURN(0);
1211         }
1212
1213         /*
1214          * NB Until this point, the whole of the incoming message,
1215          * including buflens, status etc is in the sender's byte order.
1216          */
1217         rc = sptlrpc_cli_unwrap_reply(req);
1218         if (rc) {
1219                 DEBUG_REQ(D_ERROR, req, "unwrap reply failed (%d):", rc);
1220                 RETURN(rc);
1221         }
1222
1223         /*
1224          * Security layer unwrap might ask resend this request.
1225          */
1226         if (req->rq_resend)
1227                 RETURN(0);
1228
1229         rc = unpack_reply(req);
1230         if (rc)
1231                 RETURN(rc);
1232
1233         cfs_gettimeofday(&work_start);
1234         timediff = cfs_timeval_sub(&work_start, &req->rq_arrival_time, NULL);
1235         if (obd->obd_svc_stats != NULL) {
1236                 lprocfs_counter_add(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR,
1237                                     timediff);
1238                 ptlrpc_lprocfs_rpc_sent(req, timediff);
1239         }
1240
1241         if (lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_REPLY &&
1242             lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_ERR) {
1243                 DEBUG_REQ(D_ERROR, req, "invalid packet received (type=%u)",
1244                           lustre_msg_get_type(req->rq_repmsg));
1245                 RETURN(-EPROTO);
1246         }
1247
1248         if (lustre_msg_get_opc(req->rq_reqmsg) != OBD_PING)
1249                 OBD_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_PAUSE_REP, obd_fail_val);
1250         ptlrpc_at_adj_service(req, lustre_msg_get_timeout(req->rq_repmsg));
1251         ptlrpc_at_adj_net_latency(req,
1252                                   lustre_msg_get_service_time(req->rq_repmsg));
1253
1254         rc = ptlrpc_check_status(req);
1255         imp->imp_connect_error = rc;
1256
1257         if (rc) {
1258                 /*
1259                  * Either we've been evicted, or the server has failed for
1260                  * some reason. Try to reconnect, and if that fails, punt to
1261                  * the upcall.
1262                  */
1263                 if (ll_rpc_recoverable_error(rc)) {
1264                         if (req->rq_send_state != LUSTRE_IMP_FULL ||
1265                             imp->imp_obd->obd_no_recov || imp->imp_dlm_fake) {
1266                                 RETURN(rc);
1267                         }
1268                         ptlrpc_request_handle_notconn(req);
1269                         RETURN(rc);
1270                 }
1271         } else {
1272                 /*
1273                  * Let's look if server sent slv. Do it only for RPC with
1274                  * rc == 0.
1275                  */
1276                 ldlm_cli_update_pool(req);
1277         }
1278
1279         /*
1280          * Store transno in reqmsg for replay.
1281          */
1282         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
1283                 req->rq_transno = lustre_msg_get_transno(req->rq_repmsg);
1284                 lustre_msg_set_transno(req->rq_reqmsg, req->rq_transno);
1285         }
1286
1287         if (imp->imp_replayable) {
1288                 cfs_spin_lock(&imp->imp_lock);
1289                 /*
1290                  * No point in adding already-committed requests to the replay
1291                  * list, we will just remove them immediately. b=9829
1292                  */
1293                 if (req->rq_transno != 0 &&
1294                     (req->rq_transno >
1295                      lustre_msg_get_last_committed(req->rq_repmsg) ||
1296                      req->rq_replay)) {
1297                         /** version recovery */
1298                         ptlrpc_save_versions(req);
1299                         ptlrpc_retain_replayable_request(req, imp);
1300                 } else if (req->rq_commit_cb != NULL) {
1301                         cfs_spin_unlock(&imp->imp_lock);
1302                         req->rq_commit_cb(req);
1303                         cfs_spin_lock(&imp->imp_lock);
1304                 }
1305
1306                 /*
1307                  * Replay-enabled imports return commit-status information.
1308                  */
1309                 if (lustre_msg_get_last_committed(req->rq_repmsg)) {
1310                         imp->imp_peer_committed_transno =
1311                                 lustre_msg_get_last_committed(req->rq_repmsg);
1312                 }
1313                 ptlrpc_free_committed(imp);
1314
1315                 if (req->rq_transno > imp->imp_peer_committed_transno)
1316                         ptlrpc_pinger_commit_expected(imp);
1317
1318                 cfs_spin_unlock(&imp->imp_lock);
1319         }
1320
1321         RETURN(rc);
1322 }
1323
1324 /**
1325  * Helper function to send request \a req over the network for the first time
1326  * Also adjusts request phase.
1327  * Returns 0 on success or error code.
1328  */ 
1329 static int ptlrpc_send_new_req(struct ptlrpc_request *req)
1330 {
1331         struct obd_import     *imp;
1332         int rc;
1333         ENTRY;
1334
1335         LASSERT(req->rq_phase == RQ_PHASE_NEW);
1336         if (req->rq_sent && (req->rq_sent > cfs_time_current_sec()))
1337                 RETURN (0);
1338
1339         ptlrpc_rqphase_move(req, RQ_PHASE_RPC);
1340
1341         imp = req->rq_import;
1342         cfs_spin_lock(&imp->imp_lock);
1343
1344         req->rq_import_generation = imp->imp_generation;
1345
1346         if (ptlrpc_import_delay_req(imp, req, &rc)) {
1347                 cfs_spin_lock(&req->rq_lock);
1348                 req->rq_waiting = 1;
1349                 cfs_spin_unlock(&req->rq_lock);
1350
1351                 DEBUG_REQ(D_HA, req, "req from PID %d waiting for recovery: "
1352                           "(%s != %s)", lustre_msg_get_status(req->rq_reqmsg),
1353                           ptlrpc_import_state_name(req->rq_send_state),
1354                           ptlrpc_import_state_name(imp->imp_state));
1355                 LASSERT(cfs_list_empty(&req->rq_list));
1356                 cfs_list_add_tail(&req->rq_list, &imp->imp_delayed_list);
1357                 cfs_atomic_inc(&req->rq_import->imp_inflight);
1358                 cfs_spin_unlock(&imp->imp_lock);
1359                 RETURN(0);
1360         }
1361
1362         if (rc != 0) {
1363                 cfs_spin_unlock(&imp->imp_lock);
1364                 req->rq_status = rc;
1365                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1366                 RETURN(rc);
1367         }
1368
1369         LASSERT(cfs_list_empty(&req->rq_list));
1370         cfs_list_add_tail(&req->rq_list, &imp->imp_sending_list);
1371         cfs_atomic_inc(&req->rq_import->imp_inflight);
1372         cfs_spin_unlock(&imp->imp_lock);
1373
1374         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
1375
1376         rc = sptlrpc_req_refresh_ctx(req, -1);
1377         if (rc) {
1378                 if (req->rq_err) {
1379                         req->rq_status = rc;
1380                         RETURN(1);
1381                 } else {
1382                         req->rq_wait_ctx = 1;
1383                         RETURN(0);
1384                 }
1385         }
1386
1387         CDEBUG(D_RPCTRACE, "Sending RPC pname:cluuid:pid:xid:nid:opc"
1388                " %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1389                imp->imp_obd->obd_uuid.uuid,
1390                lustre_msg_get_status(req->rq_reqmsg), req->rq_xid,
1391                libcfs_nid2str(imp->imp_connection->c_peer.nid),
1392                lustre_msg_get_opc(req->rq_reqmsg));
1393
1394         rc = ptl_send_rpc(req, 0);
1395         if (rc) {
1396                 DEBUG_REQ(D_HA, req, "send failed (%d); expect timeout", rc);
1397                 req->rq_net_err = 1;
1398                 RETURN(rc);
1399         }
1400         RETURN(0);
1401 }
1402
1403 /**
1404  * this sends any unsent RPCs in \a set and returns 1 if all are sent
1405  * and no more replies are expected.
1406  * (it is possible to get less replies than requests sent e.g. due to timed out
1407  * requests or requests that we had trouble to send out)
1408  */
1409 int ptlrpc_check_set(const struct lu_env *env, struct ptlrpc_request_set *set)
1410 {
1411         cfs_list_t *tmp;
1412         int force_timer_recalc = 0;
1413         ENTRY;
1414
1415         if (cfs_atomic_read(&set->set_remaining) == 0)
1416                 RETURN(1);
1417
1418         cfs_list_for_each(tmp, &set->set_requests) {
1419                 struct ptlrpc_request *req =
1420                         cfs_list_entry(tmp, struct ptlrpc_request,
1421                                        rq_set_chain);
1422                 struct obd_import *imp = req->rq_import;
1423                 int unregistered = 0;
1424                 int rc = 0;
1425
1426                 if (req->rq_phase == RQ_PHASE_NEW &&
1427                     ptlrpc_send_new_req(req)) {
1428                         force_timer_recalc = 1;
1429                 }
1430
1431                 /* delayed send - skip */
1432                 if (req->rq_phase == RQ_PHASE_NEW && req->rq_sent)
1433                         continue;
1434
1435                 if (!(req->rq_phase == RQ_PHASE_RPC ||
1436                       req->rq_phase == RQ_PHASE_BULK ||
1437                       req->rq_phase == RQ_PHASE_INTERPRET ||
1438                       req->rq_phase == RQ_PHASE_UNREGISTERING ||
1439                       req->rq_phase == RQ_PHASE_COMPLETE)) {
1440                         DEBUG_REQ(D_ERROR, req, "bad phase %x", req->rq_phase);
1441                         LBUG();
1442                 }
1443
1444                 if (req->rq_phase == RQ_PHASE_UNREGISTERING) {
1445                         LASSERT(req->rq_next_phase != req->rq_phase);
1446                         LASSERT(req->rq_next_phase != RQ_PHASE_UNDEFINED);
1447
1448                         /*
1449                          * Skip processing until reply is unlinked. We
1450                          * can't return to pool before that and we can't
1451                          * call interpret before that. We need to make
1452                          * sure that all rdma transfers finished and will
1453                          * not corrupt any data.
1454                          */
1455                         if (ptlrpc_client_recv_or_unlink(req) ||
1456                             ptlrpc_client_bulk_active(req))
1457                                 continue;
1458
1459                         /*
1460                          * Turn fail_loc off to prevent it from looping
1461                          * forever.
1462                          */
1463                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
1464                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK,
1465                                                      OBD_FAIL_ONCE);
1466                         }
1467                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK)) {
1468                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK,
1469                                                      OBD_FAIL_ONCE);
1470                         }
1471
1472                         /*
1473                          * Move to next phase if reply was successfully
1474                          * unlinked.
1475                          */
1476                         ptlrpc_rqphase_move(req, req->rq_next_phase);
1477                 }
1478
1479                 if (req->rq_phase == RQ_PHASE_COMPLETE)
1480                         continue;
1481
1482                 if (req->rq_phase == RQ_PHASE_INTERPRET)
1483                         GOTO(interpret, req->rq_status);
1484
1485                 /*
1486                  * Note that this also will start async reply unlink.
1487                  */
1488                 if (req->rq_net_err && !req->rq_timedout) {
1489                         ptlrpc_expire_one_request(req, 1);
1490
1491                         /*
1492                          * Check if we still need to wait for unlink.
1493                          */
1494                         if (ptlrpc_client_recv_or_unlink(req) ||
1495                             ptlrpc_client_bulk_active(req))
1496                                 continue;
1497                         /* If there is no need to resend, fail it now. */
1498                         if (req->rq_no_resend) {
1499                                 if (req->rq_status == 0)
1500                                         req->rq_status = -EIO;
1501                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1502                                 GOTO(interpret, req->rq_status);
1503                         } else {
1504                                 continue;
1505                         }
1506                 }
1507
1508                 if (req->rq_err) {
1509                         cfs_spin_lock(&req->rq_lock);
1510                         req->rq_replied = 0;
1511                         cfs_spin_unlock(&req->rq_lock);
1512                         if (req->rq_status == 0)
1513                                 req->rq_status = -EIO;
1514                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1515                         GOTO(interpret, req->rq_status);
1516                 }
1517
1518                 /* ptlrpc_set_wait->l_wait_event sets lwi_allow_intr
1519                  * so it sets rq_intr regardless of individual rpc
1520                  * timeouts. The synchronous IO waiting path sets 
1521                  * rq_intr irrespective of whether ptlrpcd
1522                  * has seen a timeout.  Our policy is to only interpret
1523                  * interrupted rpcs after they have timed out, so we
1524                  * need to enforce that here.
1525                  */
1526
1527                 if (req->rq_intr && (req->rq_timedout || req->rq_waiting ||
1528                                      req->rq_wait_ctx)) {
1529                         req->rq_status = -EINTR;
1530                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1531                         GOTO(interpret, req->rq_status);
1532                 }
1533
1534                 if (req->rq_phase == RQ_PHASE_RPC) {
1535                         if (req->rq_timedout || req->rq_resend ||
1536                             req->rq_waiting || req->rq_wait_ctx) {
1537                                 int status;
1538
1539                                 if (!ptlrpc_unregister_reply(req, 1))
1540                                         continue;
1541
1542                                 cfs_spin_lock(&imp->imp_lock);
1543                                 if (ptlrpc_import_delay_req(imp, req, &status)){
1544                                         /* put on delay list - only if we wait
1545                                          * recovery finished - before send */
1546                                         cfs_list_del_init(&req->rq_list);
1547                                         cfs_list_add_tail(&req->rq_list,
1548                                                           &imp-> \
1549                                                           imp_delayed_list);
1550                                         cfs_spin_unlock(&imp->imp_lock);
1551                                         continue;
1552                                 }
1553
1554                                 if (status != 0)  {
1555                                         req->rq_status = status;
1556                                         ptlrpc_rqphase_move(req,
1557                                                 RQ_PHASE_INTERPRET);
1558                                         cfs_spin_unlock(&imp->imp_lock);
1559                                         GOTO(interpret, req->rq_status);
1560                                 }
1561                                 if (ptlrpc_no_resend(req) && !req->rq_wait_ctx) {
1562                                         req->rq_status = -ENOTCONN;
1563                                         ptlrpc_rqphase_move(req,
1564                                                 RQ_PHASE_INTERPRET);
1565                                         cfs_spin_unlock(&imp->imp_lock);
1566                                         GOTO(interpret, req->rq_status);
1567                                 }
1568
1569                                 cfs_list_del_init(&req->rq_list);
1570                                 cfs_list_add_tail(&req->rq_list,
1571                                               &imp->imp_sending_list);
1572
1573                                 cfs_spin_unlock(&imp->imp_lock);
1574
1575                                 cfs_spin_lock(&req->rq_lock);
1576                                 req->rq_waiting = 0;
1577                                 cfs_spin_unlock(&req->rq_lock);
1578
1579                                 if (req->rq_timedout || req->rq_resend) {
1580                                         /* This is re-sending anyways,
1581                                          * let's mark req as resend. */
1582                                         cfs_spin_lock(&req->rq_lock);
1583                                         req->rq_resend = 1;
1584                                         cfs_spin_unlock(&req->rq_lock);
1585                                         if (req->rq_bulk) {
1586                                                 __u64 old_xid;
1587
1588                                                 if (!ptlrpc_unregister_bulk(req, 1))
1589                                                         continue;
1590
1591                                                 /* ensure previous bulk fails */
1592                                                 old_xid = req->rq_xid;
1593                                                 req->rq_xid = ptlrpc_next_xid();
1594                                                 CDEBUG(D_HA, "resend bulk "
1595                                                        "old x"LPU64
1596                                                        " new x"LPU64"\n",
1597                                                        old_xid, req->rq_xid);
1598                                         }
1599                                 }
1600                                 /*
1601                                  * rq_wait_ctx is only touched by ptlrpcd,
1602                                  * so no lock is needed here.
1603                                  */
1604                                 status = sptlrpc_req_refresh_ctx(req, -1);
1605                                 if (status) {
1606                                         if (req->rq_err) {
1607                                                 req->rq_status = status;
1608                                                 cfs_spin_lock(&req->rq_lock);
1609                                                 req->rq_wait_ctx = 0;
1610                                                 cfs_spin_unlock(&req->rq_lock);
1611                                                 force_timer_recalc = 1;
1612                                         } else {
1613                                                 cfs_spin_lock(&req->rq_lock);
1614                                                 req->rq_wait_ctx = 1;
1615                                                 cfs_spin_unlock(&req->rq_lock);
1616                                         }
1617
1618                                         continue;
1619                                 } else {
1620                                         cfs_spin_lock(&req->rq_lock);
1621                                         req->rq_wait_ctx = 0;
1622                                         cfs_spin_unlock(&req->rq_lock);
1623                                 }
1624
1625                                 rc = ptl_send_rpc(req, 0);
1626                                 if (rc) {
1627                                         DEBUG_REQ(D_HA, req, "send failed (%d)",
1628                                                   rc);
1629                                         force_timer_recalc = 1;
1630                                         cfs_spin_lock(&req->rq_lock);
1631                                         req->rq_net_err = 1;
1632                                         cfs_spin_unlock(&req->rq_lock);
1633                                 }
1634                                 /* need to reset the timeout */
1635                                 force_timer_recalc = 1;
1636                         }
1637
1638                         cfs_spin_lock(&req->rq_lock);
1639
1640                         if (ptlrpc_client_early(req)) {
1641                                 ptlrpc_at_recv_early_reply(req);
1642                                 cfs_spin_unlock(&req->rq_lock);
1643                                 continue;
1644                         }
1645
1646                         /* Still waiting for a reply? */
1647                         if (ptlrpc_client_recv(req)) {
1648                                 cfs_spin_unlock(&req->rq_lock);
1649                                 continue;
1650                         }
1651
1652                         /* Did we actually receive a reply? */
1653                         if (!ptlrpc_client_replied(req)) {
1654                                 cfs_spin_unlock(&req->rq_lock);
1655                                 continue;
1656                         }
1657
1658                         cfs_spin_unlock(&req->rq_lock);
1659
1660                         /* unlink from net because we are going to
1661                          * swab in-place of reply buffer */
1662                         unregistered = ptlrpc_unregister_reply(req, 1);
1663                         if (!unregistered)
1664                                 continue;
1665
1666                         req->rq_status = after_reply(req);
1667                         if (req->rq_resend)
1668                                 continue;
1669
1670                         /* If there is no bulk associated with this request,
1671                          * then we're done and should let the interpreter
1672                          * process the reply. Similarly if the RPC returned
1673                          * an error, and therefore the bulk will never arrive.
1674                          */
1675                         if (req->rq_bulk == NULL || req->rq_status != 0) {
1676                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1677                                 GOTO(interpret, req->rq_status);
1678                         }
1679
1680                         ptlrpc_rqphase_move(req, RQ_PHASE_BULK);
1681                 }
1682
1683                 LASSERT(req->rq_phase == RQ_PHASE_BULK);
1684                 if (ptlrpc_client_bulk_active(req))
1685                         continue;
1686
1687                 if (!req->rq_bulk->bd_success) {
1688                         /* The RPC reply arrived OK, but the bulk screwed
1689                          * up!  Dead weird since the server told us the RPC
1690                          * was good after getting the REPLY for her GET or
1691                          * the ACK for her PUT. */
1692                         DEBUG_REQ(D_ERROR, req, "bulk transfer failed");
1693                         LBUG();
1694                 }
1695
1696                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1697
1698         interpret:
1699                 LASSERT(req->rq_phase == RQ_PHASE_INTERPRET);
1700
1701                 /* This moves to "unregistering" phase we need to wait for
1702                  * reply unlink. */
1703                 if (!unregistered && !ptlrpc_unregister_reply(req, 1)) {
1704                         /* start async bulk unlink too */
1705                         ptlrpc_unregister_bulk(req, 1);
1706                         continue;
1707                 }
1708
1709                 if (!ptlrpc_unregister_bulk(req, 1))
1710                         continue;
1711
1712                 /* When calling interpret receiving already should be
1713                  * finished. */
1714                 LASSERT(!req->rq_receiving_reply);
1715
1716                 ptlrpc_req_interpret(env, req, req->rq_status);
1717
1718                 ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
1719
1720                 CDEBUG(D_RPCTRACE, "Completed RPC pname:cluuid:pid:xid:nid:"
1721                        "opc %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1722                        imp->imp_obd->obd_uuid.uuid,
1723                        req->rq_reqmsg ? lustre_msg_get_status(req->rq_reqmsg):-1,
1724                        req->rq_xid,
1725                        libcfs_nid2str(imp->imp_connection->c_peer.nid),
1726                        req->rq_reqmsg ? lustre_msg_get_opc(req->rq_reqmsg) : -1);
1727
1728                 cfs_spin_lock(&imp->imp_lock);
1729                 /* Request already may be not on sending or delaying list. This
1730                  * may happen in the case of marking it erroneous for the case
1731                  * ptlrpc_import_delay_req(req, status) find it impossible to
1732                  * allow sending this rpc and returns *status != 0. */
1733                 if (!cfs_list_empty(&req->rq_list)) {
1734                         cfs_list_del_init(&req->rq_list);
1735                         cfs_atomic_dec(&imp->imp_inflight);
1736                 }
1737                 cfs_spin_unlock(&imp->imp_lock);
1738
1739                 cfs_atomic_dec(&set->set_remaining);
1740                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1741         }
1742
1743         /* If we hit an error, we want to recover promptly. */
1744         RETURN(cfs_atomic_read(&set->set_remaining) == 0 || force_timer_recalc);
1745 }
1746
1747 /**
1748  * Time out request \a req. is \a async_unlink is set, that means do not wait
1749  * until LNet actually confirms network buffer unlinking.
1750  * Return 1 if we should give up further retrying attempts or 0 otherwise.
1751  */
1752 int ptlrpc_expire_one_request(struct ptlrpc_request *req, int async_unlink)
1753 {
1754         struct obd_import *imp = req->rq_import;
1755         int rc = 0;
1756         ENTRY;
1757
1758         cfs_spin_lock(&req->rq_lock);
1759         req->rq_timedout = 1;
1760         cfs_spin_unlock(&req->rq_lock);
1761
1762         DEBUG_REQ(req->rq_fake ? D_INFO : D_WARNING, req, "Request x"LPU64
1763                   " sent from %s to NID %s has %s: [sent "CFS_DURATION_T"] "
1764                   "[real_sent "CFS_DURATION_T"] [current "CFS_DURATION_T"] "
1765                   "[deadline "CFS_DURATION_T"s] [delay "CFS_DURATION_T"s]",
1766                   req->rq_xid, imp ? imp->imp_obd->obd_name : "<?>",
1767                   imp ? libcfs_nid2str(imp->imp_connection->c_peer.nid) : "<?>", 
1768                   req->rq_net_err ? "failed due to network error" :
1769                      ((req->rq_real_sent == 0 ||
1770                        cfs_time_before(req->rq_real_sent, req->rq_sent) ||
1771                        cfs_time_aftereq(req->rq_real_sent, req->rq_deadline)) ?
1772                       "timed out for sent delay" : "timed out for slow reply"),
1773                   req->rq_sent, req->rq_real_sent, cfs_time_current_sec(),
1774                   cfs_time_sub(req->rq_deadline, req->rq_sent),
1775                   cfs_time_sub(cfs_time_current_sec(), req->rq_deadline));
1776
1777         if (imp != NULL && obd_debug_peer_on_timeout)
1778                 LNetCtl(IOC_LIBCFS_DEBUG_PEER, &imp->imp_connection->c_peer);
1779
1780         ptlrpc_unregister_reply(req, async_unlink);
1781         ptlrpc_unregister_bulk(req, async_unlink);
1782
1783         if (obd_dump_on_timeout)
1784                 libcfs_debug_dumplog();
1785
1786         if (imp == NULL) {
1787                 DEBUG_REQ(D_HA, req, "NULL import: already cleaned up?");
1788                 RETURN(1);
1789         }
1790
1791         if (req->rq_fake)
1792                RETURN(1);
1793
1794         cfs_atomic_inc(&imp->imp_timeouts);
1795
1796         /* The DLM server doesn't want recovery run on its imports. */
1797         if (imp->imp_dlm_fake)
1798                 RETURN(1);
1799
1800         /* If this request is for recovery or other primordial tasks,
1801          * then error it out here. */
1802         if (req->rq_ctx_init || req->rq_ctx_fini ||
1803             req->rq_send_state != LUSTRE_IMP_FULL ||
1804             imp->imp_obd->obd_no_recov) {
1805                 DEBUG_REQ(D_RPCTRACE, req, "err -110, sent_state=%s (now=%s)",
1806                           ptlrpc_import_state_name(req->rq_send_state),
1807                           ptlrpc_import_state_name(imp->imp_state));
1808                 cfs_spin_lock(&req->rq_lock);
1809                 req->rq_status = -ETIMEDOUT;
1810                 req->rq_err = 1;
1811                 cfs_spin_unlock(&req->rq_lock);
1812                 RETURN(1);
1813         }
1814
1815         /* if a request can't be resent we can't wait for an answer after
1816            the timeout */
1817         if (ptlrpc_no_resend(req)) {
1818                 DEBUG_REQ(D_RPCTRACE, req, "TIMEOUT-NORESEND:");
1819                 rc = 1;
1820         }
1821
1822         ptlrpc_fail_import(imp, lustre_msg_get_conn_cnt(req->rq_reqmsg));
1823
1824         RETURN(rc);
1825 }
1826
1827 /**
1828  * Time out all uncompleted requests in request set pointed by \a data
1829  * Callback used when waiting on sets with l_wait_event.
1830  * Always returns 1.
1831  */
1832 int ptlrpc_expired_set(void *data)
1833 {
1834         struct ptlrpc_request_set *set = data;
1835         cfs_list_t                *tmp;
1836         time_t                     now = cfs_time_current_sec();
1837         ENTRY;
1838
1839         LASSERT(set != NULL);
1840
1841         /*
1842          * A timeout expired. See which reqs it applies to...
1843          */
1844         cfs_list_for_each (tmp, &set->set_requests) {
1845                 struct ptlrpc_request *req =
1846                         cfs_list_entry(tmp, struct ptlrpc_request,
1847                                        rq_set_chain);
1848
1849                 /* don't expire request waiting for context */
1850                 if (req->rq_wait_ctx)
1851                         continue;
1852
1853                 /* Request in-flight? */
1854                 if (!((req->rq_phase == RQ_PHASE_RPC &&
1855                        !req->rq_waiting && !req->rq_resend) ||
1856                       (req->rq_phase == RQ_PHASE_BULK)))
1857                         continue;
1858
1859                 if (req->rq_timedout ||     /* already dealt with */
1860                     req->rq_deadline > now) /* not expired */
1861                         continue;
1862
1863                 /* Deal with this guy. Do it asynchronously to not block
1864                  * ptlrpcd thread. */
1865                 ptlrpc_expire_one_request(req, 1);
1866         }
1867
1868         /*
1869          * When waiting for a whole set, we always break out of the
1870          * sleep so we can recalculate the timeout, or enable interrupts
1871          * if everyone's timed out.
1872          */
1873         RETURN(1);
1874 }
1875
1876 /**
1877  * Sets rq_intr flag in \a req under spinlock.
1878  */
1879 void ptlrpc_mark_interrupted(struct ptlrpc_request *req)
1880 {
1881         cfs_spin_lock(&req->rq_lock);
1882         req->rq_intr = 1;
1883         cfs_spin_unlock(&req->rq_lock);
1884 }
1885
1886 /**
1887  * Interrupts (sets interrupted flag) all uncompleted requests in
1888  * a set \a data. Callback for l_wait_event for interruptible waits.
1889  */
1890 void ptlrpc_interrupted_set(void *data)
1891 {
1892         struct ptlrpc_request_set *set = data;
1893         cfs_list_t *tmp;
1894
1895         LASSERT(set != NULL);
1896         CERROR("INTERRUPTED SET %p\n", set);
1897
1898         cfs_list_for_each(tmp, &set->set_requests) {
1899                 struct ptlrpc_request *req =
1900                         cfs_list_entry(tmp, struct ptlrpc_request,
1901                                        rq_set_chain);
1902
1903                 if (req->rq_phase != RQ_PHASE_RPC &&
1904                     req->rq_phase != RQ_PHASE_UNREGISTERING)
1905                         continue;
1906
1907                 ptlrpc_mark_interrupted(req);
1908         }
1909 }
1910
1911 /**
1912  * Get the smallest timeout in the set; this does NOT set a timeout.
1913  */
1914 int ptlrpc_set_next_timeout(struct ptlrpc_request_set *set)
1915 {
1916         cfs_list_t            *tmp;
1917         time_t                 now = cfs_time_current_sec();
1918         int                    timeout = 0;
1919         struct ptlrpc_request *req;
1920         int                    deadline;
1921         ENTRY;
1922
1923         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
1924
1925         cfs_list_for_each(tmp, &set->set_requests) {
1926                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1927
1928                 /*
1929                  * Request in-flight?
1930                  */
1931                 if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
1932                       (req->rq_phase == RQ_PHASE_BULK) ||
1933                       (req->rq_phase == RQ_PHASE_NEW)))
1934                         continue;
1935
1936                 /*
1937                  * Already timed out.
1938                  */
1939                 if (req->rq_timedout)
1940                         continue;
1941
1942                 /*
1943                  * Waiting for ctx.
1944                  */
1945                 if (req->rq_wait_ctx)
1946                         continue;
1947
1948                 if (req->rq_phase == RQ_PHASE_NEW)
1949                         deadline = req->rq_sent;
1950                 else
1951                         deadline = req->rq_sent + req->rq_timeout;
1952
1953                 if (deadline <= now)    /* actually expired already */
1954                         timeout = 1;    /* ASAP */
1955                 else if (timeout == 0 || timeout > deadline - now)
1956                         timeout = deadline - now;
1957         }
1958         RETURN(timeout);
1959 }
1960
1961 /**
1962  * Send all unset request from the set and then wait untill all
1963  * requests in the set complete (either get a reply, timeout, get an
1964  * error or otherwise be interrupted).
1965  * Returns 0 on success or error code otherwise.
1966  */
1967 int ptlrpc_set_wait(struct ptlrpc_request_set *set)
1968 {
1969         cfs_list_t            *tmp;
1970         struct ptlrpc_request *req;
1971         struct l_wait_info     lwi;
1972         int                    rc, timeout;
1973         ENTRY;
1974
1975         if (cfs_list_empty(&set->set_requests))
1976                 RETURN(0);
1977
1978         cfs_list_for_each(tmp, &set->set_requests) {
1979                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1980                 if (req->rq_phase == RQ_PHASE_NEW)
1981                         (void)ptlrpc_send_new_req(req);
1982         }
1983
1984         do {
1985                 timeout = ptlrpc_set_next_timeout(set);
1986
1987                 /* wait until all complete, interrupted, or an in-flight
1988                  * req times out */
1989                 CDEBUG(D_RPCTRACE, "set %p going to sleep for %d seconds\n",
1990                        set, timeout);
1991
1992                 if (timeout == 0 && !cfs_signal_pending())
1993                         /*
1994                          * No requests are in-flight (ether timed out
1995                          * or delayed), so we can allow interrupts.
1996                          * We still want to block for a limited time,
1997                          * so we allow interrupts during the timeout.
1998                          */
1999                         lwi = LWI_TIMEOUT_INTR_ALL(cfs_time_seconds(1), 
2000                                                    ptlrpc_expired_set,
2001                                                    ptlrpc_interrupted_set, set);
2002                 else
2003                         /*
2004                          * At least one request is in flight, so no
2005                          * interrupts are allowed. Wait until all
2006                          * complete, or an in-flight req times out. 
2007                          */
2008                         lwi = LWI_TIMEOUT(cfs_time_seconds(timeout? timeout : 1),
2009                                           ptlrpc_expired_set, set);
2010
2011                 rc = l_wait_event(set->set_waitq, ptlrpc_check_set(NULL, set), &lwi);
2012
2013                 LASSERT(rc == 0 || rc == -EINTR || rc == -ETIMEDOUT);
2014
2015                 /* -EINTR => all requests have been flagged rq_intr so next
2016                  * check completes.
2017                  * -ETIMEDOUT => someone timed out.  When all reqs have
2018                  * timed out, signals are enabled allowing completion with
2019                  * EINTR.
2020                  * I don't really care if we go once more round the loop in
2021                  * the error cases -eeb. */
2022                 if (rc == 0 && cfs_atomic_read(&set->set_remaining) == 0) {
2023                         cfs_list_for_each(tmp, &set->set_requests) {
2024                                 req = cfs_list_entry(tmp, struct ptlrpc_request,
2025                                                      rq_set_chain);
2026                                 cfs_spin_lock(&req->rq_lock);
2027                                 req->rq_invalid_rqset = 1;
2028                                 cfs_spin_unlock(&req->rq_lock);
2029                         }
2030                 }
2031         } while (rc != 0 || cfs_atomic_read(&set->set_remaining) != 0);
2032
2033         LASSERT(cfs_atomic_read(&set->set_remaining) == 0);
2034
2035         rc = 0;
2036         cfs_list_for_each(tmp, &set->set_requests) {
2037                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
2038
2039                 LASSERT(req->rq_phase == RQ_PHASE_COMPLETE);
2040                 if (req->rq_status != 0)
2041                         rc = req->rq_status;
2042         }
2043
2044         if (set->set_interpret != NULL) {
2045                 int (*interpreter)(struct ptlrpc_request_set *set,void *,int) =
2046                         set->set_interpret;
2047                 rc = interpreter (set, set->set_arg, rc);
2048         } else {
2049                 struct ptlrpc_set_cbdata *cbdata, *n;
2050                 int err;
2051
2052                 cfs_list_for_each_entry_safe(cbdata, n,
2053                                          &set->set_cblist, psc_item) {
2054                         cfs_list_del_init(&cbdata->psc_item);
2055                         err = cbdata->psc_interpret(set, cbdata->psc_data, rc);
2056                         if (err && !rc)
2057                                 rc = err;
2058                         OBD_FREE_PTR(cbdata);
2059                 }
2060         }
2061
2062         RETURN(rc);
2063 }
2064
2065 /**
2066  * Helper fuction for request freeing.
2067  * Called when request count reached zero and request needs to be freed.
2068  * Removes request from all sorts of sending/replay lists it might be on,
2069  * frees network buffers if any are present.
2070  * If \a locked is set, that means caller is already holding import imp_lock
2071  * and so we no longer need to reobtain it (for certain lists manipulations)
2072  */
2073 static void __ptlrpc_free_req(struct ptlrpc_request *request, int locked)
2074 {
2075         ENTRY;
2076         if (request == NULL) {
2077                 EXIT;
2078                 return;
2079         }
2080
2081         LASSERTF(!request->rq_receiving_reply, "req %p\n", request);
2082         LASSERTF(request->rq_rqbd == NULL, "req %p\n",request);/* client-side */
2083         LASSERTF(cfs_list_empty(&request->rq_list), "req %p\n", request);
2084         LASSERTF(cfs_list_empty(&request->rq_set_chain), "req %p\n", request);
2085         LASSERTF(cfs_list_empty(&request->rq_exp_list), "req %p\n", request);
2086         LASSERTF(!request->rq_replay, "req %p\n", request);
2087         LASSERT(request->rq_cli_ctx || request->rq_fake);
2088
2089         req_capsule_fini(&request->rq_pill);
2090
2091         /* We must take it off the imp_replay_list first.  Otherwise, we'll set
2092          * request->rq_reqmsg to NULL while osc_close is dereferencing it. */
2093         if (request->rq_import != NULL) {
2094                 if (!locked)
2095                         cfs_spin_lock(&request->rq_import->imp_lock);
2096                 cfs_list_del_init(&request->rq_replay_list);
2097                 if (!locked)
2098                         cfs_spin_unlock(&request->rq_import->imp_lock);
2099         }
2100         LASSERTF(cfs_list_empty(&request->rq_replay_list), "req %p\n", request);
2101
2102         if (cfs_atomic_read(&request->rq_refcount) != 0) {
2103                 DEBUG_REQ(D_ERROR, request,
2104                           "freeing request with nonzero refcount");
2105                 LBUG();
2106         }
2107
2108         if (request->rq_repbuf != NULL)
2109                 sptlrpc_cli_free_repbuf(request);
2110         if (request->rq_export != NULL) {
2111                 class_export_put(request->rq_export);
2112                 request->rq_export = NULL;
2113         }
2114         if (request->rq_import != NULL) {
2115                 class_import_put(request->rq_import);
2116                 request->rq_import = NULL;
2117         }
2118         if (request->rq_bulk != NULL)
2119                 ptlrpc_free_bulk(request->rq_bulk);
2120
2121         if (request->rq_reqbuf != NULL || request->rq_clrbuf != NULL)
2122                 sptlrpc_cli_free_reqbuf(request);
2123
2124         if (request->rq_cli_ctx)
2125                 sptlrpc_req_put_ctx(request, !locked);
2126
2127         if (request->rq_pool)
2128                 __ptlrpc_free_req_to_pool(request);
2129         else
2130                 OBD_FREE(request, sizeof(*request));
2131         EXIT;
2132 }
2133
2134 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked);
2135 /**
2136  * Drop one request reference. Must be called with import imp_lock held.
2137  * When reference count drops to zero, reuqest is freed.
2138  */
2139 void ptlrpc_req_finished_with_imp_lock(struct ptlrpc_request *request)
2140 {
2141         LASSERT_SPIN_LOCKED(&request->rq_import->imp_lock);
2142         (void)__ptlrpc_req_finished(request, 1);
2143 }
2144
2145 /**
2146  * Helper function
2147  * Drops one reference count for request \a request.
2148  * \a locked set indicates that caller holds import imp_lock.
2149  * Frees the request whe reference count reaches zero.
2150  */
2151 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked)
2152 {
2153         ENTRY;
2154         if (request == NULL)
2155                 RETURN(1);
2156
2157         if (request == LP_POISON ||
2158             request->rq_reqmsg == LP_POISON) {
2159                 CERROR("dereferencing freed request (bug 575)\n");
2160                 LBUG();
2161                 RETURN(1);
2162         }
2163
2164         DEBUG_REQ(D_INFO, request, "refcount now %u",
2165                   cfs_atomic_read(&request->rq_refcount) - 1);
2166
2167         if (cfs_atomic_dec_and_test(&request->rq_refcount)) {
2168                 __ptlrpc_free_req(request, locked);
2169                 RETURN(1);
2170         }
2171
2172         RETURN(0);
2173 }
2174
2175 /**
2176  * Drops one reference count for a request.
2177  */
2178 void ptlrpc_req_finished(struct ptlrpc_request *request)
2179 {
2180         __ptlrpc_req_finished(request, 0);
2181 }
2182
2183 /**
2184  * Returns xid of a \a request
2185  */
2186 __u64 ptlrpc_req_xid(struct ptlrpc_request *request)
2187 {
2188         return request->rq_xid;
2189 }
2190 EXPORT_SYMBOL(ptlrpc_req_xid);
2191
2192 /**
2193  * Disengage the client's reply buffer from the network
2194  * NB does _NOT_ unregister any client-side bulk.
2195  * IDEMPOTENT, but _not_ safe against concurrent callers.
2196  * The request owner (i.e. the thread doing the I/O) must call...
2197  * Returns 0 on success or 1 if unregistering cannot be made.
2198  */
2199 int ptlrpc_unregister_reply(struct ptlrpc_request *request, int async)
2200 {
2201         int                rc;
2202         cfs_waitq_t       *wq;
2203         struct l_wait_info lwi;
2204
2205         /*
2206          * Might sleep.
2207          */
2208         LASSERT(!cfs_in_interrupt());
2209
2210         /*
2211          * Let's setup deadline for reply unlink.
2212          */
2213         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK) &&
2214             async && request->rq_reply_deadline == 0)
2215                 request->rq_reply_deadline = cfs_time_current_sec()+LONG_UNLINK;
2216
2217         /*
2218          * Nothing left to do.
2219          */
2220         if (!ptlrpc_client_recv_or_unlink(request))
2221                 RETURN(1);
2222
2223         LNetMDUnlink(request->rq_reply_md_h);
2224
2225         /*
2226          * Let's check it once again.
2227          */
2228         if (!ptlrpc_client_recv_or_unlink(request))
2229                 RETURN(1);
2230
2231         /*
2232          * Move to "Unregistering" phase as reply was not unlinked yet.
2233          */
2234         ptlrpc_rqphase_move(request, RQ_PHASE_UNREGISTERING);
2235
2236         /*
2237          * Do not wait for unlink to finish.
2238          */
2239         if (async)
2240                 RETURN(0);
2241
2242         /*
2243          * We have to l_wait_event() whatever the result, to give liblustre
2244          * a chance to run reply_in_callback(), and to make sure we've
2245          * unlinked before returning a req to the pool.
2246          */
2247         if (request->rq_set != NULL)
2248                 wq = &request->rq_set->set_waitq;
2249         else
2250                 wq = &request->rq_reply_waitq;
2251
2252         for (;;) {
2253                 /* Network access will complete in finite time but the HUGE
2254                  * timeout lets us CWARN for visibility of sluggish NALs */
2255                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
2256                                            cfs_time_seconds(1), NULL, NULL);
2257                 rc = l_wait_event(*wq, !ptlrpc_client_recv_or_unlink(request),
2258                                   &lwi);
2259                 if (rc == 0) {
2260                         ptlrpc_rqphase_move(request, request->rq_next_phase);
2261                         RETURN(1);
2262                 }
2263
2264                 LASSERT(rc == -ETIMEDOUT);
2265                 DEBUG_REQ(D_WARNING, request, "Unexpectedly long timeout "
2266                           "rvcng=%d unlnk=%d", request->rq_receiving_reply,
2267                           request->rq_must_unlink);
2268         }
2269         RETURN(0);
2270 }
2271
2272 /**
2273  * Iterates through replay_list on import and prunes
2274  * all requests have transno smaller than last_committed for the
2275  * import and don't have rq_replay set.
2276  * Since requests are sorted in transno order, stops when meetign first
2277  * transno bigger than last_committed.
2278  * caller must hold imp->imp_lock
2279  */
2280 void ptlrpc_free_committed(struct obd_import *imp)
2281 {
2282         cfs_list_t *tmp, *saved;
2283         struct ptlrpc_request *req;
2284         struct ptlrpc_request *last_req = NULL; /* temporary fire escape */
2285         ENTRY;
2286
2287         LASSERT(imp != NULL);
2288
2289         LASSERT_SPIN_LOCKED(&imp->imp_lock);
2290
2291
2292         if (imp->imp_peer_committed_transno == imp->imp_last_transno_checked &&
2293             imp->imp_generation == imp->imp_last_generation_checked) {
2294                 CDEBUG(D_INFO, "%s: skip recheck: last_committed "LPU64"\n",
2295                        imp->imp_obd->obd_name, imp->imp_peer_committed_transno);
2296                 EXIT;
2297                 return;
2298         }
2299         CDEBUG(D_RPCTRACE, "%s: committing for last_committed "LPU64" gen %d\n",
2300                imp->imp_obd->obd_name, imp->imp_peer_committed_transno,
2301                imp->imp_generation);
2302         imp->imp_last_transno_checked = imp->imp_peer_committed_transno;
2303         imp->imp_last_generation_checked = imp->imp_generation;
2304
2305         cfs_list_for_each_safe(tmp, saved, &imp->imp_replay_list) {
2306                 req = cfs_list_entry(tmp, struct ptlrpc_request,
2307                                      rq_replay_list);
2308
2309                 /* XXX ok to remove when 1357 resolved - rread 05/29/03  */
2310                 LASSERT(req != last_req);
2311                 last_req = req;
2312
2313                 if (req->rq_transno == 0) {
2314                         DEBUG_REQ(D_EMERG, req, "zero transno during replay");
2315                         LBUG();
2316                 }
2317                 if (req->rq_import_generation < imp->imp_generation) {
2318                         DEBUG_REQ(D_RPCTRACE, req, "free request with old gen");
2319                         GOTO(free_req, 0);
2320                 }
2321
2322                 if (req->rq_replay) {
2323                         DEBUG_REQ(D_RPCTRACE, req, "keeping (FL_REPLAY)");
2324                         continue;
2325                 }
2326
2327                 /* not yet committed */
2328                 if (req->rq_transno > imp->imp_peer_committed_transno) {
2329                         DEBUG_REQ(D_RPCTRACE, req, "stopping search");
2330                         break;
2331                 }
2332
2333                 DEBUG_REQ(D_INFO, req, "commit (last_committed "LPU64")",
2334                           imp->imp_peer_committed_transno);
2335 free_req:
2336                 cfs_spin_lock(&req->rq_lock);
2337                 req->rq_replay = 0;
2338                 cfs_spin_unlock(&req->rq_lock);
2339                 if (req->rq_commit_cb != NULL)
2340                         req->rq_commit_cb(req);
2341                 cfs_list_del_init(&req->rq_replay_list);
2342                 __ptlrpc_req_finished(req, 1);
2343         }
2344
2345         EXIT;
2346         return;
2347 }
2348
2349 void ptlrpc_cleanup_client(struct obd_import *imp)
2350 {
2351         ENTRY;
2352         EXIT;
2353         return;
2354 }
2355
2356 /**
2357  * Schedule previously sent request for resend.
2358  * For bulk requests we assign new xid (to avoid problems with
2359  * lost replies and therefore several transfers landing into same buffer
2360  * from different sending attempts).
2361  */
2362 void ptlrpc_resend_req(struct ptlrpc_request *req)
2363 {
2364         DEBUG_REQ(D_HA, req, "going to resend");
2365         lustre_msg_set_handle(req->rq_reqmsg, &(struct lustre_handle){ 0 });
2366         req->rq_status = -EAGAIN;
2367
2368         cfs_spin_lock(&req->rq_lock);
2369         req->rq_resend = 1;
2370         req->rq_net_err = 0;
2371         req->rq_timedout = 0;
2372         if (req->rq_bulk) {
2373                 __u64 old_xid = req->rq_xid;
2374
2375                 /* ensure previous bulk fails */
2376                 req->rq_xid = ptlrpc_next_xid();
2377                 CDEBUG(D_HA, "resend bulk old x"LPU64" new x"LPU64"\n",
2378                        old_xid, req->rq_xid);
2379         }
2380         ptlrpc_client_wake_req(req);
2381         cfs_spin_unlock(&req->rq_lock);
2382 }
2383
2384 /* XXX: this function and rq_status are currently unused */
2385 void ptlrpc_restart_req(struct ptlrpc_request *req)
2386 {
2387         DEBUG_REQ(D_HA, req, "restarting (possibly-)completed request");
2388         req->rq_status = -ERESTARTSYS;
2389
2390         cfs_spin_lock(&req->rq_lock);
2391         req->rq_restart = 1;
2392         req->rq_timedout = 0;
2393         ptlrpc_client_wake_req(req);
2394         cfs_spin_unlock(&req->rq_lock);
2395 }
2396
2397 /**
2398  * Grab additional reference on a request \a req
2399  */
2400 struct ptlrpc_request *ptlrpc_request_addref(struct ptlrpc_request *req)
2401 {
2402         ENTRY;
2403         cfs_atomic_inc(&req->rq_refcount);
2404         RETURN(req);
2405 }
2406
2407 /**
2408  * Add a request to import replay_list.
2409  * Must be called under imp_lock
2410  */
2411 void ptlrpc_retain_replayable_request(struct ptlrpc_request *req,
2412                                       struct obd_import *imp)
2413 {
2414         cfs_list_t *tmp;
2415
2416         LASSERT_SPIN_LOCKED(&imp->imp_lock);
2417
2418         if (req->rq_transno == 0) {
2419                 DEBUG_REQ(D_EMERG, req, "saving request with zero transno");
2420                 LBUG();
2421         }
2422
2423         /* clear this for new requests that were resent as well
2424            as resent replayed requests. */
2425         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
2426
2427         /* don't re-add requests that have been replayed */
2428         if (!cfs_list_empty(&req->rq_replay_list))
2429                 return;
2430
2431         lustre_msg_add_flags(req->rq_reqmsg, MSG_REPLAY);
2432
2433         LASSERT(imp->imp_replayable);
2434         /* Balanced in ptlrpc_free_committed, usually. */
2435         ptlrpc_request_addref(req);
2436         cfs_list_for_each_prev(tmp, &imp->imp_replay_list) {
2437                 struct ptlrpc_request *iter =
2438                         cfs_list_entry(tmp, struct ptlrpc_request,
2439                                        rq_replay_list);
2440
2441                 /* We may have duplicate transnos if we create and then
2442                  * open a file, or for closes retained if to match creating
2443                  * opens, so use req->rq_xid as a secondary key.
2444                  * (See bugs 684, 685, and 428.)
2445                  * XXX no longer needed, but all opens need transnos!
2446                  */
2447                 if (iter->rq_transno > req->rq_transno)
2448                         continue;
2449
2450                 if (iter->rq_transno == req->rq_transno) {
2451                         LASSERT(iter->rq_xid != req->rq_xid);
2452                         if (iter->rq_xid > req->rq_xid)
2453                                 continue;
2454                 }
2455
2456                 cfs_list_add(&req->rq_replay_list, &iter->rq_replay_list);
2457                 return;
2458         }
2459
2460         cfs_list_add(&req->rq_replay_list, &imp->imp_replay_list);
2461 }
2462
2463 /**
2464  * Send request and wait until it completes.
2465  * Returns request processing status.
2466  */
2467 int ptlrpc_queue_wait(struct ptlrpc_request *req)
2468 {
2469         struct ptlrpc_request_set *set;
2470         int rc;
2471         ENTRY;
2472
2473         LASSERT(req->rq_set == NULL);
2474         LASSERT(!req->rq_receiving_reply);
2475
2476         set = ptlrpc_prep_set();
2477         if (set == NULL) {
2478                 CERROR("Unable to allocate ptlrpc set.");
2479                 RETURN(-ENOMEM);
2480         }
2481
2482         /* for distributed debugging */
2483         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
2484
2485         /* add a ref for the set (see comment in ptlrpc_set_add_req) */
2486         ptlrpc_request_addref(req);
2487         ptlrpc_set_add_req(set, req);
2488         rc = ptlrpc_set_wait(set);
2489         ptlrpc_set_destroy(set);
2490
2491         RETURN(rc);
2492 }
2493
2494 struct ptlrpc_replay_async_args {
2495         int praa_old_state;
2496         int praa_old_status;
2497 };
2498
2499 /**
2500  * Callback used for replayed requests reply processing.
2501  * In case of succesful reply calls registeresd request replay callback.
2502  * In case of error restart replay process.
2503  */
2504 static int ptlrpc_replay_interpret(const struct lu_env *env,
2505                                    struct ptlrpc_request *req,
2506                                    void * data, int rc)
2507 {
2508         struct ptlrpc_replay_async_args *aa = data;
2509         struct obd_import *imp = req->rq_import;
2510
2511         ENTRY;
2512         cfs_atomic_dec(&imp->imp_replay_inflight);
2513
2514         if (!ptlrpc_client_replied(req)) {
2515                 CERROR("request replay timed out, restarting recovery\n");
2516                 GOTO(out, rc = -ETIMEDOUT);
2517         }
2518
2519         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR &&
2520             (lustre_msg_get_status(req->rq_repmsg) == -ENOTCONN ||
2521              lustre_msg_get_status(req->rq_repmsg) == -ENODEV))
2522                 GOTO(out, rc = lustre_msg_get_status(req->rq_repmsg));
2523
2524         /** VBR: check version failure */
2525         if (lustre_msg_get_status(req->rq_repmsg) == -EOVERFLOW) {
2526                 /** replay was failed due to version mismatch */
2527                 DEBUG_REQ(D_WARNING, req, "Version mismatch during replay\n");
2528                 cfs_spin_lock(&imp->imp_lock);
2529                 imp->imp_vbr_failed = 1;
2530                 imp->imp_no_lock_replay = 1;
2531                 cfs_spin_unlock(&imp->imp_lock);
2532                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
2533         } else {
2534                 /** The transno had better not change over replay. */
2535                 LASSERTF(lustre_msg_get_transno(req->rq_reqmsg) ==
2536                          lustre_msg_get_transno(req->rq_repmsg) ||
2537                          lustre_msg_get_transno(req->rq_repmsg) == 0,
2538                          LPX64"/"LPX64"\n",
2539                          lustre_msg_get_transno(req->rq_reqmsg),
2540                          lustre_msg_get_transno(req->rq_repmsg));
2541         }
2542
2543         cfs_spin_lock(&imp->imp_lock);
2544         /** if replays by version then gap was occur on server, no trust to locks */
2545         if (lustre_msg_get_flags(req->rq_repmsg) & MSG_VERSION_REPLAY)
2546                 imp->imp_no_lock_replay = 1;
2547         imp->imp_last_replay_transno = lustre_msg_get_transno(req->rq_reqmsg);
2548         cfs_spin_unlock(&imp->imp_lock);
2549         LASSERT(imp->imp_last_replay_transno);
2550
2551         /* transaction number shouldn't be bigger than the latest replayed */
2552         if (req->rq_transno > lustre_msg_get_transno(req->rq_reqmsg)) {
2553                 DEBUG_REQ(D_ERROR, req,
2554                           "Reported transno "LPU64" is bigger than the "
2555                           "replayed one: "LPU64, req->rq_transno,
2556                           lustre_msg_get_transno(req->rq_reqmsg));
2557                 GOTO(out, rc = -EINVAL);
2558         }
2559
2560         DEBUG_REQ(D_HA, req, "got rep");
2561
2562         /* let the callback do fixups, possibly including in the request */
2563         if (req->rq_replay_cb)
2564                 req->rq_replay_cb(req);
2565
2566         if (ptlrpc_client_replied(req) &&
2567             lustre_msg_get_status(req->rq_repmsg) != aa->praa_old_status) {
2568                 DEBUG_REQ(D_ERROR, req, "status %d, old was %d",
2569                           lustre_msg_get_status(req->rq_repmsg),
2570                           aa->praa_old_status);
2571         } else {
2572                 /* Put it back for re-replay. */
2573                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
2574         }
2575
2576         /*
2577          * Errors while replay can set transno to 0, but
2578          * imp_last_replay_transno shouldn't be set to 0 anyway
2579          */
2580         if (req->rq_transno == 0)
2581                 CERROR("Transno is 0 during replay!\n");
2582
2583         /* continue with recovery */
2584         rc = ptlrpc_import_recovery_state_machine(imp);
2585  out:
2586         req->rq_send_state = aa->praa_old_state;
2587
2588         if (rc != 0)
2589                 /* this replay failed, so restart recovery */
2590                 ptlrpc_connect_import(imp, NULL);
2591
2592         RETURN(rc);
2593 }
2594
2595 /**
2596  * Prepares and queues request for replay.
2597  * Adds it to ptlrpcd queue for actual sending.
2598  * Returns 0 on success.
2599  */
2600 int ptlrpc_replay_req(struct ptlrpc_request *req)
2601 {
2602         struct ptlrpc_replay_async_args *aa;
2603         ENTRY;
2604
2605         LASSERT(req->rq_import->imp_state == LUSTRE_IMP_REPLAY);
2606
2607         LASSERT (sizeof (*aa) <= sizeof (req->rq_async_args));
2608         aa = ptlrpc_req_async_args(req);
2609         memset(aa, 0, sizeof *aa);
2610
2611         /* Prepare request to be resent with ptlrpcd */
2612         aa->praa_old_state = req->rq_send_state;
2613         req->rq_send_state = LUSTRE_IMP_REPLAY;
2614         req->rq_phase = RQ_PHASE_NEW;
2615         req->rq_next_phase = RQ_PHASE_UNDEFINED;
2616         if (req->rq_repmsg)
2617                 aa->praa_old_status = lustre_msg_get_status(req->rq_repmsg);
2618         req->rq_status = 0;
2619         req->rq_interpret_reply = ptlrpc_replay_interpret;
2620         /* Readjust the timeout for current conditions */
2621         ptlrpc_at_set_req_timeout(req);
2622
2623         DEBUG_REQ(D_HA, req, "REPLAY");
2624
2625         cfs_atomic_inc(&req->rq_import->imp_replay_inflight);
2626         ptlrpc_request_addref(req); /* ptlrpcd needs a ref */
2627
2628         ptlrpcd_add_req(req, PSCOPE_OTHER);
2629         RETURN(0);
2630 }
2631
2632 /**
2633  * Aborts all in-flight request on import \a imp sending and delayed lists
2634  */
2635 void ptlrpc_abort_inflight(struct obd_import *imp)
2636 {
2637         cfs_list_t *tmp, *n;
2638         ENTRY;
2639
2640         /* Make sure that no new requests get processed for this import.
2641          * ptlrpc_{queue,set}_wait must (and does) hold imp_lock while testing
2642          * this flag and then putting requests on sending_list or delayed_list.
2643          */
2644         cfs_spin_lock(&imp->imp_lock);
2645
2646         /* XXX locking?  Maybe we should remove each request with the list
2647          * locked?  Also, how do we know if the requests on the list are
2648          * being freed at this time?
2649          */
2650         cfs_list_for_each_safe(tmp, n, &imp->imp_sending_list) {
2651                 struct ptlrpc_request *req =
2652                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2653
2654                 DEBUG_REQ(D_RPCTRACE, req, "inflight");
2655
2656                 cfs_spin_lock (&req->rq_lock);
2657                 if (req->rq_import_generation < imp->imp_generation) {
2658                         req->rq_err = 1;
2659                         req->rq_status = -EINTR;
2660                         ptlrpc_client_wake_req(req);
2661                 }
2662                 cfs_spin_unlock (&req->rq_lock);
2663         }
2664
2665         cfs_list_for_each_safe(tmp, n, &imp->imp_delayed_list) {
2666                 struct ptlrpc_request *req =
2667                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2668
2669                 DEBUG_REQ(D_RPCTRACE, req, "aborting waiting req");
2670
2671                 cfs_spin_lock (&req->rq_lock);
2672                 if (req->rq_import_generation < imp->imp_generation) {
2673                         req->rq_err = 1;
2674                         req->rq_status = -EINTR;
2675                         ptlrpc_client_wake_req(req);
2676                 }
2677                 cfs_spin_unlock (&req->rq_lock);
2678         }
2679
2680         /* Last chance to free reqs left on the replay list, but we
2681          * will still leak reqs that haven't committed.  */
2682         if (imp->imp_replayable)
2683                 ptlrpc_free_committed(imp);
2684
2685         cfs_spin_unlock(&imp->imp_lock);
2686
2687         EXIT;
2688 }
2689
2690 /**
2691  * Abort all uncompleted requests in request set \a set
2692  */
2693 void ptlrpc_abort_set(struct ptlrpc_request_set *set)
2694 {
2695         cfs_list_t *tmp, *pos;
2696
2697         LASSERT(set != NULL);
2698
2699         cfs_list_for_each_safe(pos, tmp, &set->set_requests) {
2700                 struct ptlrpc_request *req =
2701                         cfs_list_entry(pos, struct ptlrpc_request,
2702                                        rq_set_chain);
2703
2704                 cfs_spin_lock(&req->rq_lock);
2705                 if (req->rq_phase != RQ_PHASE_RPC) {
2706                         cfs_spin_unlock(&req->rq_lock);
2707                         continue;
2708                 }
2709
2710                 req->rq_err = 1;
2711                 req->rq_status = -EINTR;
2712                 ptlrpc_client_wake_req(req);
2713                 cfs_spin_unlock(&req->rq_lock);
2714         }
2715 }
2716
2717 static __u64 ptlrpc_last_xid;
2718 static cfs_spinlock_t ptlrpc_last_xid_lock;
2719
2720 /**
2721  * Initialize the XID for the node.  This is common among all requests on
2722  * this node, and only requires the property that it is monotonically
2723  * increasing.  It does not need to be sequential.  Since this is also used
2724  * as the RDMA match bits, it is important that a single client NOT have
2725  * the same match bits for two different in-flight requests, hence we do
2726  * NOT want to have an XID per target or similar.
2727  *
2728  * To avoid an unlikely collision between match bits after a client reboot
2729  * (which would deliver old data into the wrong RDMA buffer) initialize
2730  * the XID based on the current time, assuming a maximum RPC rate of 1M RPC/s.
2731  * If the time is clearly incorrect, we instead use a 62-bit random number.
2732  * In the worst case the random number will overflow 1M RPCs per second in
2733  * 9133 years, or permutations thereof.
2734  */
2735 #define YEAR_2004 (1ULL << 30)
2736 void ptlrpc_init_xid(void)
2737 {
2738         time_t now = cfs_time_current_sec();
2739
2740         cfs_spin_lock_init(&ptlrpc_last_xid_lock);
2741         if (now < YEAR_2004) {
2742                 cfs_get_random_bytes(&ptlrpc_last_xid, sizeof(ptlrpc_last_xid));
2743                 ptlrpc_last_xid >>= 2;
2744                 ptlrpc_last_xid |= (1ULL << 61);
2745         } else {
2746                 ptlrpc_last_xid = (__u64)now << 20;
2747         }
2748 }
2749
2750 /**
2751  * Increase xid and returns resultng new value to the caller.
2752  */
2753 __u64 ptlrpc_next_xid(void)
2754 {
2755         __u64 tmp;
2756         cfs_spin_lock(&ptlrpc_last_xid_lock);
2757         tmp = ++ptlrpc_last_xid;
2758         cfs_spin_unlock(&ptlrpc_last_xid_lock);
2759         return tmp;
2760 }
2761
2762 /**
2763  * Get a glimpse at what next xid value might have been.
2764  * Returns possible next xid.
2765  */
2766 __u64 ptlrpc_sample_next_xid(void)
2767 {
2768 #if BITS_PER_LONG == 32
2769         /* need to avoid possible word tearing on 32-bit systems */
2770         __u64 tmp;
2771         cfs_spin_lock(&ptlrpc_last_xid_lock);
2772         tmp = ptlrpc_last_xid + 1;
2773         cfs_spin_unlock(&ptlrpc_last_xid_lock);
2774         return tmp;
2775 #else
2776         /* No need to lock, since returned value is racy anyways */
2777         return ptlrpc_last_xid + 1;
2778 #endif
2779 }
2780 EXPORT_SYMBOL(ptlrpc_sample_next_xid);