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