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