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