Whamcloud - gitweb
LU-904 ptlrpc: redo io on -EINPROGRESS
[fs/lustre-release.git] / lustre / ptlrpc / client.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  *
32  * Copyright (c) 2011, 2012, Whamcloud, Inc.
33  */
34 /*
35  * This file is part of Lustre, http://www.lustre.org/
36  * Lustre is a trademark of Sun Microsystems, Inc.
37  */
38
39 /** Implementation of client-side PortalRPC interfaces */
40
41 #define DEBUG_SUBSYSTEM S_RPC
42 #ifndef __KERNEL__
43 #include <errno.h>
44 #include <signal.h>
45 #include <liblustre.h>
46 #endif
47
48 #include <obd_support.h>
49 #include <obd_class.h>
50 #include <lustre_lib.h>
51 #include <lustre_ha.h>
52 #include <lustre_import.h>
53 #include <lustre_req_layout.h>
54
55 #include "ptlrpc_internal.h"
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         return ptlrpc_request_bufs_pack(request, version, opcode, NULL, NULL);
612 }
613
614 /**
615  * Helper function to allocate new request on import \a imp
616  * and possibly using existing request from pool \a pool if provided.
617  * Returns allocated request structure with import field filled or
618  * NULL on error.
619  */
620 static inline
621 struct ptlrpc_request *__ptlrpc_request_alloc(struct obd_import *imp,
622                                               struct ptlrpc_request_pool *pool)
623 {
624         struct ptlrpc_request *request = NULL;
625
626         if (pool)
627                 request = ptlrpc_prep_req_from_pool(pool);
628
629         if (!request)
630                 OBD_ALLOC_PTR(request);
631
632         if (request) {
633                 LASSERTF((unsigned long)imp > 0x1000, "%p", imp);
634                 LASSERT(imp != LP_POISON);
635                 LASSERTF((unsigned long)imp->imp_client > 0x1000, "%p",
636                         imp->imp_client);
637                 LASSERT(imp->imp_client != LP_POISON);
638
639                 request->rq_import = class_import_get(imp);
640         } else {
641                 CERROR("request allocation out of memory\n");
642         }
643
644         return request;
645 }
646
647 /**
648  * Helper function for creating a request.
649  * Calls __ptlrpc_request_alloc to allocate new request sturcture and inits
650  * buffer structures according to capsule template \a format.
651  * Returns allocated request structure pointer or NULL on error.
652  */
653 static struct ptlrpc_request *
654 ptlrpc_request_alloc_internal(struct obd_import *imp,
655                               struct ptlrpc_request_pool * pool,
656                               const struct req_format *format)
657 {
658         struct ptlrpc_request *request;
659
660         request = __ptlrpc_request_alloc(imp, pool);
661         if (request == NULL)
662                 return NULL;
663
664         req_capsule_init(&request->rq_pill, request, RCL_CLIENT);
665         req_capsule_set(&request->rq_pill, format);
666         return request;
667 }
668
669 /**
670  * Allocate new request structure for import \a imp and initialize its
671  * buffer structure according to capsule template \a format.
672  */
673 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
674                                             const struct req_format *format)
675 {
676         return ptlrpc_request_alloc_internal(imp, NULL, format);
677 }
678
679 /**
680  * Allocate new request structure for import \a imp from pool \a pool and
681  * initialize its buffer structure according to capsule template \a format.
682  */
683 struct ptlrpc_request *ptlrpc_request_alloc_pool(struct obd_import *imp,
684                                             struct ptlrpc_request_pool * pool,
685                                             const struct req_format *format)
686 {
687         return ptlrpc_request_alloc_internal(imp, pool, format);
688 }
689
690 /**
691  * For requests not from pool, free memory of the request structure.
692  * For requests obtained from a pool earlier, return request back to pool.
693  */
694 void ptlrpc_request_free(struct ptlrpc_request *request)
695 {
696         if (request->rq_pool)
697                 __ptlrpc_free_req_to_pool(request);
698         else
699                 OBD_FREE_PTR(request);
700 }
701
702 /**
703  * Allocate new request for operatione \a opcode and immediatelly pack it for
704  * network transfer.
705  * Only used for simple requests like OBD_PING where the only important
706  * part of the request is operation itself.
707  * Returns allocated request or NULL on error.
708  */
709 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *imp,
710                                                 const struct req_format *format,
711                                                 __u32 version, int opcode)
712 {
713         struct ptlrpc_request *req = ptlrpc_request_alloc(imp, format);
714         int                    rc;
715
716         if (req) {
717                 rc = ptlrpc_request_pack(req, version, opcode);
718                 if (rc) {
719                         ptlrpc_request_free(req);
720                         req = NULL;
721                 }
722         }
723         return req;
724 }
725
726 /**
727  * Prepare request (fetched from pool \a poolif not NULL) on import \a imp
728  * for operation \a opcode. Request would contain \a count buffers.
729  * Sizes of buffers are described in array \a lengths and buffers themselves
730  * are provided by a pointer \a bufs.
731  * Returns prepared request structure pointer or NULL on error.
732  */
733 struct ptlrpc_request *
734 ptlrpc_prep_req_pool(struct obd_import *imp,
735                      __u32 version, int opcode,
736                      int count, __u32 *lengths, char **bufs,
737                      struct ptlrpc_request_pool *pool)
738 {
739         struct ptlrpc_request *request;
740         int                    rc;
741
742         request = __ptlrpc_request_alloc(imp, pool);
743         if (!request)
744                 return NULL;
745
746         rc = __ptlrpc_request_bufs_pack(request, version, opcode, count,
747                                         lengths, bufs, NULL);
748         if (rc) {
749                 ptlrpc_request_free(request);
750                 request = NULL;
751         }
752         return request;
753 }
754
755 /**
756  * Same as ptlrpc_prep_req_pool, but without pool
757  */
758 struct ptlrpc_request *
759 ptlrpc_prep_req(struct obd_import *imp, __u32 version, int opcode, int count,
760                 __u32 *lengths, char **bufs)
761 {
762         return ptlrpc_prep_req_pool(imp, version, opcode, count, lengths, bufs,
763                                     NULL);
764 }
765
766 /**
767  * Allocate "fake" request that would not be sent anywhere in the end.
768  * Only used as a hack because we have no other way of performing
769  * async actions in lustre between layers.
770  * Used on MDS to request object preallocations from more than one OST at a
771  * time.
772  */
773 struct ptlrpc_request *ptlrpc_prep_fakereq(struct obd_import *imp,
774                                            unsigned int timeout,
775                                            ptlrpc_interpterer_t interpreter)
776 {
777         struct ptlrpc_request *request = NULL;
778         ENTRY;
779
780         OBD_ALLOC(request, sizeof(*request));
781         if (!request) {
782                 CERROR("request allocation out of memory\n");
783                 RETURN(NULL);
784         }
785
786         request->rq_send_state = LUSTRE_IMP_FULL;
787         request->rq_type = PTL_RPC_MSG_REQUEST;
788         request->rq_import = class_import_get(imp);
789         request->rq_export = NULL;
790         request->rq_import_generation = imp->imp_generation;
791
792         request->rq_timeout = timeout;
793         request->rq_sent = cfs_time_current_sec();
794         request->rq_deadline = request->rq_sent + timeout;
795         request->rq_reply_deadline = request->rq_deadline;
796         request->rq_interpret_reply = interpreter;
797         request->rq_phase = RQ_PHASE_RPC;
798         request->rq_next_phase = RQ_PHASE_INTERPRET;
799         /* don't want reply */
800         request->rq_receiving_reply = 0;
801         request->rq_must_unlink = 0;
802         request->rq_no_delay = request->rq_no_resend = 1;
803         request->rq_fake = 1;
804
805         cfs_spin_lock_init(&request->rq_lock);
806         CFS_INIT_LIST_HEAD(&request->rq_list);
807         CFS_INIT_LIST_HEAD(&request->rq_replay_list);
808         CFS_INIT_LIST_HEAD(&request->rq_set_chain);
809         CFS_INIT_LIST_HEAD(&request->rq_history_list);
810         CFS_INIT_LIST_HEAD(&request->rq_exp_list);
811         cfs_waitq_init(&request->rq_reply_waitq);
812         cfs_waitq_init(&request->rq_set_waitq);
813
814         request->rq_xid = ptlrpc_next_xid();
815         cfs_atomic_set(&request->rq_refcount, 1);
816
817         RETURN(request);
818 }
819
820 /**
821  * Indicate that processing of "fake" request is finished.
822  */
823 void ptlrpc_fakereq_finished(struct ptlrpc_request *req)
824 {
825         struct ptlrpc_request_set *set = req->rq_set;
826         int wakeup = 0;
827
828         /* hold ref on the request to prevent others (ptlrpcd) to free it */
829         ptlrpc_request_addref(req);
830         cfs_list_del_init(&req->rq_list);
831
832         /* if we kill request before timeout - need adjust counter */
833         if (req->rq_phase == RQ_PHASE_RPC && set != NULL &&
834             cfs_atomic_dec_and_test(&set->set_remaining))
835                 wakeup = 1;
836
837         ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
838
839         /* Only need to call wakeup once when to be empty. */
840         if (wakeup)
841                 cfs_waitq_signal(&set->set_waitq);
842         ptlrpc_req_finished(req);
843 }
844
845 /**
846  * Allocate and initialize new request set structure.
847  * Returns a pointer to the newly allocated set structure or NULL on error.
848  */
849 struct ptlrpc_request_set *ptlrpc_prep_set(void)
850 {
851         struct ptlrpc_request_set *set;
852
853         ENTRY;
854         OBD_ALLOC(set, sizeof *set);
855         if (!set)
856                 RETURN(NULL);
857         cfs_atomic_set(&set->set_refcount, 1);
858         CFS_INIT_LIST_HEAD(&set->set_requests);
859         cfs_waitq_init(&set->set_waitq);
860         cfs_atomic_set(&set->set_new_count, 0);
861         cfs_atomic_set(&set->set_remaining, 0);
862         cfs_spin_lock_init(&set->set_new_req_lock);
863         CFS_INIT_LIST_HEAD(&set->set_new_requests);
864         CFS_INIT_LIST_HEAD(&set->set_cblist);
865
866         RETURN(set);
867 }
868
869 /**
870  * Wind down and free request set structure previously allocated with
871  * ptlrpc_prep_set.
872  * Ensures that all requests on the set have completed and removes
873  * all requests from the request list in a set.
874  * If any unsent request happen to be on the list, pretends that they got
875  * an error in flight and calls their completion handler.
876  */
877 void ptlrpc_set_destroy(struct ptlrpc_request_set *set)
878 {
879         cfs_list_t       *tmp;
880         cfs_list_t       *next;
881         int               expected_phase;
882         int               n = 0;
883         ENTRY;
884
885         /* Requests on the set should either all be completed, or all be new */
886         expected_phase = (cfs_atomic_read(&set->set_remaining) == 0) ?
887                          RQ_PHASE_COMPLETE : RQ_PHASE_NEW;
888         cfs_list_for_each (tmp, &set->set_requests) {
889                 struct ptlrpc_request *req =
890                         cfs_list_entry(tmp, struct ptlrpc_request,
891                                        rq_set_chain);
892
893                 LASSERT(req->rq_phase == expected_phase);
894                 n++;
895         }
896
897         LASSERTF(cfs_atomic_read(&set->set_remaining) == 0 || 
898                  cfs_atomic_read(&set->set_remaining) == n, "%d / %d\n",
899                  cfs_atomic_read(&set->set_remaining), n);
900
901         cfs_list_for_each_safe(tmp, next, &set->set_requests) {
902                 struct ptlrpc_request *req =
903                         cfs_list_entry(tmp, struct ptlrpc_request,
904                                        rq_set_chain);
905                 cfs_list_del_init(&req->rq_set_chain);
906
907                 LASSERT(req->rq_phase == expected_phase);
908
909                 if (req->rq_phase == RQ_PHASE_NEW) {
910                         ptlrpc_req_interpret(NULL, req, -EBADR);
911                         cfs_atomic_dec(&set->set_remaining);
912                 }
913
914                 cfs_spin_lock(&req->rq_lock);
915                 req->rq_set = NULL;
916                 req->rq_invalid_rqset = 0;
917                 cfs_spin_unlock(&req->rq_lock);
918
919                 ptlrpc_req_finished (req);
920         }
921
922         LASSERT(cfs_atomic_read(&set->set_remaining) == 0);
923
924         ptlrpc_reqset_put(set);
925         EXIT;
926 }
927
928 /**
929  * Add a callback function \a fn to the set.
930  * This function would be called when all requests on this set are completed.
931  * The function will be passed \a data argument.
932  */
933 int ptlrpc_set_add_cb(struct ptlrpc_request_set *set,
934                       set_interpreter_func fn, void *data)
935 {
936         struct ptlrpc_set_cbdata *cbdata;
937
938         OBD_ALLOC_PTR(cbdata);
939         if (cbdata == NULL)
940                 RETURN(-ENOMEM);
941
942         cbdata->psc_interpret = fn;
943         cbdata->psc_data = data;
944         cfs_list_add_tail(&cbdata->psc_item, &set->set_cblist);
945
946         RETURN(0);
947 }
948
949 /**
950  * Add a new request to the general purpose request set.
951  * Assumes request reference from the caller.
952  */
953 void ptlrpc_set_add_req(struct ptlrpc_request_set *set,
954                         struct ptlrpc_request *req)
955 {
956         LASSERT(cfs_list_empty(&req->rq_set_chain));
957
958         /* The set takes over the caller's request reference */
959         cfs_list_add_tail(&req->rq_set_chain, &set->set_requests);
960         req->rq_set = set;
961         cfs_atomic_inc(&set->set_remaining);
962         req->rq_queued_time = cfs_time_current();
963 }
964
965 /**
966  * Add a request to a request with dedicated server thread
967  * and wake the thread to make any necessary processing.
968  * Currently only used for ptlrpcd.
969  */
970 void ptlrpc_set_add_new_req(struct ptlrpcd_ctl *pc,
971                            struct ptlrpc_request *req)
972 {
973         struct ptlrpc_request_set *set = pc->pc_set;
974         int count, i;
975
976         LASSERT(req->rq_set == NULL);
977         LASSERT(cfs_test_bit(LIOD_STOP, &pc->pc_flags) == 0);
978
979         cfs_spin_lock(&set->set_new_req_lock);
980         /*
981          * The set takes over the caller's request reference.
982          */
983         req->rq_set = set;
984         req->rq_queued_time = cfs_time_current();
985         cfs_list_add_tail(&req->rq_set_chain, &set->set_new_requests);
986         count = cfs_atomic_inc_return(&set->set_new_count);
987         cfs_spin_unlock(&set->set_new_req_lock);
988
989         /* Only need to call wakeup once for the first entry. */
990         if (count == 1) {
991                 cfs_waitq_signal(&set->set_waitq);
992
993                 /* XXX: It maybe unnecessary to wakeup all the partners. But to
994                  *      guarantee the async RPC can be processed ASAP, we have
995                  *      no other better choice. It maybe fixed in future. */
996                 for (i = 0; i < pc->pc_npartners; i++)
997                         cfs_waitq_signal(&pc->pc_partners[i]->pc_set->set_waitq);
998         }
999 }
1000
1001 /**
1002  * Based on the current state of the import, determine if the request
1003  * can be sent, is an error, or should be delayed.
1004  *
1005  * Returns true if this request should be delayed. If false, and
1006  * *status is set, then the request can not be sent and *status is the
1007  * error code.  If false and status is 0, then request can be sent.
1008  *
1009  * The imp->imp_lock must be held.
1010  */
1011 static int ptlrpc_import_delay_req(struct obd_import *imp,
1012                                    struct ptlrpc_request *req, int *status)
1013 {
1014         int delay = 0;
1015         ENTRY;
1016
1017         LASSERT (status != NULL);
1018         *status = 0;
1019
1020         if (req->rq_ctx_init || req->rq_ctx_fini) {
1021                 /* always allow ctx init/fini rpc go through */
1022         } else if (imp->imp_state == LUSTRE_IMP_NEW) {
1023                 DEBUG_REQ(D_ERROR, req, "Uninitialized import.");
1024                 *status = -EIO;
1025                 LBUG();
1026         } else if (imp->imp_state == LUSTRE_IMP_CLOSED) {
1027                 DEBUG_REQ(D_ERROR, req, "IMP_CLOSED ");
1028                 *status = -EIO;
1029         } else if (ptlrpc_send_limit_expired(req)) {
1030                 /* probably doesn't need to be a D_ERROR after initial testing */
1031                 DEBUG_REQ(D_ERROR, req, "send limit expired ");
1032                 *status = -EIO;
1033         } else if (req->rq_send_state == LUSTRE_IMP_CONNECTING &&
1034                    imp->imp_state == LUSTRE_IMP_CONNECTING) {
1035                 /* allow CONNECT even if import is invalid */ ;
1036                 if (cfs_atomic_read(&imp->imp_inval_count) != 0) {
1037                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
1038                         *status = -EIO;
1039                 }
1040         } else if (imp->imp_invalid || imp->imp_obd->obd_no_recov) {
1041                 if (!imp->imp_deactive)
1042                           DEBUG_REQ(D_ERROR, req, "IMP_INVALID");
1043                 *status = -ESHUTDOWN; /* bz 12940 */
1044         } else if (req->rq_import_generation != imp->imp_generation) {
1045                 DEBUG_REQ(D_ERROR, req, "req wrong generation:");
1046                 *status = -EIO;
1047         } else if (req->rq_send_state != imp->imp_state) {
1048                 /* invalidate in progress - any requests should be drop */
1049                 if (cfs_atomic_read(&imp->imp_inval_count) != 0) {
1050                         DEBUG_REQ(D_ERROR, req, "invalidate in flight");
1051                         *status = -EIO;
1052                 } else if (imp->imp_dlm_fake || req->rq_no_delay) {
1053                         *status = -EWOULDBLOCK;
1054                 } else {
1055                         delay = 1;
1056                 }
1057         }
1058
1059         RETURN(delay);
1060 }
1061
1062 /**
1063  * Decide if the eror message regarding provided request \a req
1064  * should be printed to the console or not.
1065  * Makes it's decision on request status and other properties.
1066  * Returns 1 to print error on the system console or 0 if not.
1067  */
1068 static int ptlrpc_console_allow(struct ptlrpc_request *req)
1069 {
1070         __u32 opc;
1071         int err;
1072
1073         /* Fake requests include no rq_reqmsg */
1074         if (req->rq_fake)
1075                 return 0;
1076
1077         LASSERT(req->rq_reqmsg != NULL);
1078         opc = lustre_msg_get_opc(req->rq_reqmsg);
1079
1080         /* Suppress particular reconnect errors which are to be expected.  No
1081          * errors are suppressed for the initial connection on an import */
1082         if ((lustre_handle_is_used(&req->rq_import->imp_remote_handle)) &&
1083             (opc == OST_CONNECT || opc == MDS_CONNECT || opc == MGS_CONNECT)) {
1084
1085                 /* Suppress timed out reconnect requests */
1086                 if (req->rq_timedout)
1087                         return 0;
1088
1089                 /* Suppress unavailable/again reconnect requests */
1090                 err = lustre_msg_get_status(req->rq_repmsg);
1091                 if (err == -ENODEV || err == -EAGAIN)
1092                         return 0;
1093         }
1094
1095         return 1;
1096 }
1097
1098 /**
1099  * Check request processing status.
1100  * Returns the status.
1101  */
1102 static int ptlrpc_check_status(struct ptlrpc_request *req)
1103 {
1104         int err;
1105         ENTRY;
1106
1107         err = lustre_msg_get_status(req->rq_repmsg);
1108         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
1109                 struct obd_import *imp = req->rq_import;
1110                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1111                 LCONSOLE_ERROR_MSG(0x011,"an error occurred while communicating"
1112                                 " with %s. The %s operation failed with %d\n",
1113                                 libcfs_nid2str(imp->imp_connection->c_peer.nid),
1114                                 ll_opcode2str(opc), err);
1115                 RETURN(err < 0 ? err : -EINVAL);
1116         }
1117
1118         if (err < 0) {
1119                 DEBUG_REQ(D_INFO, req, "status is %d", err);
1120         } else if (err > 0) {
1121                 /* XXX: translate this error from net to host */
1122                 DEBUG_REQ(D_INFO, req, "status is %d", err);
1123         }
1124
1125         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR) {
1126                 struct obd_import *imp = req->rq_import;
1127                 __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
1128
1129                 if (ptlrpc_console_allow(req))
1130                         LCONSOLE_ERROR_MSG(0x011,"an error occurred while "
1131                                            "communicating with %s. The %s "
1132                                            "operation failed with %d\n",
1133                                            libcfs_nid2str(
1134                                            imp->imp_connection->c_peer.nid),
1135                                            ll_opcode2str(opc), err);
1136
1137                 RETURN(err < 0 ? err : -EINVAL);
1138         }
1139
1140         RETURN(err);
1141 }
1142
1143 /**
1144  * save pre-versions of objects into request for replay.
1145  * Versions are obtained from server reply.
1146  * used for VBR.
1147  */
1148 static void ptlrpc_save_versions(struct ptlrpc_request *req)
1149 {
1150         struct lustre_msg *repmsg = req->rq_repmsg;
1151         struct lustre_msg *reqmsg = req->rq_reqmsg;
1152         __u64 *versions = lustre_msg_get_versions(repmsg);
1153         ENTRY;
1154
1155         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1156                 return;
1157
1158         LASSERT(versions);
1159         lustre_msg_set_versions(reqmsg, versions);
1160         CDEBUG(D_INFO, "Client save versions ["LPX64"/"LPX64"]\n",
1161                versions[0], versions[1]);
1162
1163         EXIT;
1164 }
1165
1166 /**
1167  * Callback function called when client receives RPC reply for \a req.
1168  * Returns 0 on success or error code.
1169  * The return alue would be assigned to req->rq_status by the caller
1170  * as request processing status.
1171  * This function also decides if the request needs to be saved for later replay.
1172  */
1173 static int after_reply(struct ptlrpc_request *req)
1174 {
1175         struct obd_import *imp = req->rq_import;
1176         struct obd_device *obd = req->rq_import->imp_obd;
1177         int rc;
1178         struct timeval work_start;
1179         long timediff;
1180         ENTRY;
1181
1182         LASSERT(obd != NULL);
1183         /* repbuf must be unlinked */
1184         LASSERT(!req->rq_receiving_reply && !req->rq_must_unlink);
1185
1186         if (req->rq_reply_truncate) {
1187                 if (ptlrpc_no_resend(req)) {
1188                         DEBUG_REQ(D_ERROR, req, "reply buffer overflow,"
1189                                   " expected: %d, actual size: %d",
1190                                   req->rq_nob_received, req->rq_repbuf_len);
1191                         RETURN(-EOVERFLOW);
1192                 }
1193
1194                 sptlrpc_cli_free_repbuf(req);
1195                 /* Pass the required reply buffer size (include
1196                  * space for early reply).
1197                  * NB: no need to roundup because alloc_repbuf
1198                  * will roundup it */
1199                 req->rq_replen       = req->rq_nob_received;
1200                 req->rq_nob_received = 0;
1201                 req->rq_resend       = 1;
1202                 RETURN(0);
1203         }
1204
1205         /*
1206          * NB Until this point, the whole of the incoming message,
1207          * including buflens, status etc is in the sender's byte order.
1208          */
1209         rc = sptlrpc_cli_unwrap_reply(req);
1210         if (rc) {
1211                 DEBUG_REQ(D_ERROR, req, "unwrap reply failed (%d):", rc);
1212                 RETURN(rc);
1213         }
1214
1215         /*
1216          * Security layer unwrap might ask resend this request.
1217          */
1218         if (req->rq_resend)
1219                 RETURN(0);
1220
1221         rc = unpack_reply(req);
1222         if (rc)
1223                 RETURN(rc);
1224
1225         cfs_gettimeofday(&work_start);
1226         timediff = cfs_timeval_sub(&work_start, &req->rq_arrival_time, NULL);
1227         if (obd->obd_svc_stats != NULL) {
1228                 lprocfs_counter_add(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR,
1229                                     timediff);
1230                 ptlrpc_lprocfs_rpc_sent(req, timediff);
1231         }
1232
1233         if (lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_REPLY &&
1234             lustre_msg_get_type(req->rq_repmsg) != PTL_RPC_MSG_ERR) {
1235                 DEBUG_REQ(D_ERROR, req, "invalid packet received (type=%u)",
1236                           lustre_msg_get_type(req->rq_repmsg));
1237                 RETURN(-EPROTO);
1238         }
1239
1240         if (lustre_msg_get_opc(req->rq_reqmsg) != OBD_PING)
1241                 CFS_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_PAUSE_REP, cfs_fail_val);
1242         ptlrpc_at_adj_service(req, lustre_msg_get_timeout(req->rq_repmsg));
1243         ptlrpc_at_adj_net_latency(req,
1244                                   lustre_msg_get_service_time(req->rq_repmsg));
1245
1246         rc = ptlrpc_check_status(req);
1247         imp->imp_connect_error = rc;
1248
1249         if (rc) {
1250                 /*
1251                  * Either we've been evicted, or the server has failed for
1252                  * some reason. Try to reconnect, and if that fails, punt to
1253                  * the upcall.
1254                  */
1255                 if (ll_rpc_recoverable_error(rc)) {
1256                         if (req->rq_send_state != LUSTRE_IMP_FULL ||
1257                             imp->imp_obd->obd_no_recov || imp->imp_dlm_fake) {
1258                                 RETURN(rc);
1259                         }
1260                         ptlrpc_request_handle_notconn(req);
1261                         RETURN(rc);
1262                 }
1263         } else {
1264                 /*
1265                  * Let's look if server sent slv. Do it only for RPC with
1266                  * rc == 0.
1267                  */
1268                 ldlm_cli_update_pool(req);
1269         }
1270
1271         /*
1272          * Store transno in reqmsg for replay.
1273          */
1274         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
1275                 req->rq_transno = lustre_msg_get_transno(req->rq_repmsg);
1276                 lustre_msg_set_transno(req->rq_reqmsg, req->rq_transno);
1277         }
1278
1279         if (imp->imp_replayable) {
1280                 cfs_spin_lock(&imp->imp_lock);
1281                 /*
1282                  * No point in adding already-committed requests to the replay
1283                  * list, we will just remove them immediately. b=9829
1284                  */
1285                 if (req->rq_transno != 0 &&
1286                     (req->rq_transno >
1287                      lustre_msg_get_last_committed(req->rq_repmsg) ||
1288                      req->rq_replay)) {
1289                         /** version recovery */
1290                         ptlrpc_save_versions(req);
1291                         ptlrpc_retain_replayable_request(req, imp);
1292                 } else if (req->rq_commit_cb != NULL) {
1293                         cfs_spin_unlock(&imp->imp_lock);
1294                         req->rq_commit_cb(req);
1295                         cfs_spin_lock(&imp->imp_lock);
1296                 }
1297
1298                 /*
1299                  * Replay-enabled imports return commit-status information.
1300                  */
1301                 if (lustre_msg_get_last_committed(req->rq_repmsg)) {
1302                         imp->imp_peer_committed_transno =
1303                                 lustre_msg_get_last_committed(req->rq_repmsg);
1304                 }
1305                 ptlrpc_free_committed(imp);
1306
1307                 if (req->rq_transno > imp->imp_peer_committed_transno)
1308                         ptlrpc_pinger_commit_expected(imp);
1309
1310                 cfs_spin_unlock(&imp->imp_lock);
1311         }
1312
1313         RETURN(rc);
1314 }
1315
1316 /**
1317  * Helper function to send request \a req over the network for the first time
1318  * Also adjusts request phase.
1319  * Returns 0 on success or error code.
1320  */
1321 static int ptlrpc_send_new_req(struct ptlrpc_request *req)
1322 {
1323         struct obd_import     *imp = req->rq_import;
1324         int rc;
1325         ENTRY;
1326
1327         LASSERT(req->rq_phase == RQ_PHASE_NEW);
1328         if (req->rq_sent && (req->rq_sent > cfs_time_current_sec()) &&
1329             (!req->rq_generation_set ||
1330              req->rq_import_generation == imp->imp_generation))
1331                 RETURN (0);
1332
1333         ptlrpc_rqphase_move(req, RQ_PHASE_RPC);
1334
1335         cfs_spin_lock(&imp->imp_lock);
1336
1337         if (!req->rq_generation_set)
1338                 req->rq_import_generation = imp->imp_generation;
1339
1340         if (ptlrpc_import_delay_req(imp, req, &rc)) {
1341                 cfs_spin_lock(&req->rq_lock);
1342                 req->rq_waiting = 1;
1343                 cfs_spin_unlock(&req->rq_lock);
1344
1345                 DEBUG_REQ(D_HA, req, "req from PID %d waiting for recovery: "
1346                           "(%s != %s)", lustre_msg_get_status(req->rq_reqmsg),
1347                           ptlrpc_import_state_name(req->rq_send_state),
1348                           ptlrpc_import_state_name(imp->imp_state));
1349                 LASSERT(cfs_list_empty(&req->rq_list));
1350                 cfs_list_add_tail(&req->rq_list, &imp->imp_delayed_list);
1351                 cfs_atomic_inc(&req->rq_import->imp_inflight);
1352                 cfs_spin_unlock(&imp->imp_lock);
1353                 RETURN(0);
1354         }
1355
1356         if (rc != 0) {
1357                 cfs_spin_unlock(&imp->imp_lock);
1358                 req->rq_status = rc;
1359                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1360                 RETURN(rc);
1361         }
1362
1363         LASSERT(cfs_list_empty(&req->rq_list));
1364         cfs_list_add_tail(&req->rq_list, &imp->imp_sending_list);
1365         cfs_atomic_inc(&req->rq_import->imp_inflight);
1366         cfs_spin_unlock(&imp->imp_lock);
1367
1368         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
1369
1370         rc = sptlrpc_req_refresh_ctx(req, -1);
1371         if (rc) {
1372                 if (req->rq_err) {
1373                         req->rq_status = rc;
1374                         RETURN(1);
1375                 } else {
1376                         req->rq_wait_ctx = 1;
1377                         RETURN(0);
1378                 }
1379         }
1380
1381         CDEBUG(D_RPCTRACE, "Sending RPC pname:cluuid:pid:xid:nid:opc"
1382                " %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1383                imp->imp_obd->obd_uuid.uuid,
1384                lustre_msg_get_status(req->rq_reqmsg), req->rq_xid,
1385                libcfs_nid2str(imp->imp_connection->c_peer.nid),
1386                lustre_msg_get_opc(req->rq_reqmsg));
1387
1388         rc = ptl_send_rpc(req, 0);
1389         if (rc) {
1390                 DEBUG_REQ(D_HA, req, "send failed (%d); expect timeout", rc);
1391                 req->rq_net_err = 1;
1392                 RETURN(rc);
1393         }
1394         RETURN(0);
1395 }
1396
1397 /**
1398  * this sends any unsent RPCs in \a set and returns 1 if all are sent
1399  * and no more replies are expected.
1400  * (it is possible to get less replies than requests sent e.g. due to timed out
1401  * requests or requests that we had trouble to send out)
1402  */
1403 int ptlrpc_check_set(const struct lu_env *env, struct ptlrpc_request_set *set)
1404 {
1405         cfs_list_t *tmp;
1406         int force_timer_recalc = 0;
1407         ENTRY;
1408
1409         if (cfs_atomic_read(&set->set_remaining) == 0)
1410                 RETURN(1);
1411
1412         cfs_list_for_each(tmp, &set->set_requests) {
1413                 struct ptlrpc_request *req =
1414                         cfs_list_entry(tmp, struct ptlrpc_request,
1415                                        rq_set_chain);
1416                 struct obd_import *imp = req->rq_import;
1417                 int unregistered = 0;
1418                 int rc = 0;
1419
1420                 if (req->rq_phase == RQ_PHASE_NEW &&
1421                     ptlrpc_send_new_req(req)) {
1422                         force_timer_recalc = 1;
1423                 }
1424
1425                 /* delayed send - skip */
1426                 if (req->rq_phase == RQ_PHASE_NEW && req->rq_sent)
1427                         continue;
1428
1429                 if (!(req->rq_phase == RQ_PHASE_RPC ||
1430                       req->rq_phase == RQ_PHASE_BULK ||
1431                       req->rq_phase == RQ_PHASE_INTERPRET ||
1432                       req->rq_phase == RQ_PHASE_UNREGISTERING ||
1433                       req->rq_phase == RQ_PHASE_COMPLETE)) {
1434                         DEBUG_REQ(D_ERROR, req, "bad phase %x", req->rq_phase);
1435                         LBUG();
1436                 }
1437
1438                 if (req->rq_phase == RQ_PHASE_UNREGISTERING) {
1439                         LASSERT(req->rq_next_phase != req->rq_phase);
1440                         LASSERT(req->rq_next_phase != RQ_PHASE_UNDEFINED);
1441
1442                         /*
1443                          * Skip processing until reply is unlinked. We
1444                          * can't return to pool before that and we can't
1445                          * call interpret before that. We need to make
1446                          * sure that all rdma transfers finished and will
1447                          * not corrupt any data.
1448                          */
1449                         if (ptlrpc_client_recv_or_unlink(req) ||
1450                             ptlrpc_client_bulk_active(req))
1451                                 continue;
1452
1453                         /*
1454                          * Turn fail_loc off to prevent it from looping
1455                          * forever.
1456                          */
1457                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
1458                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK,
1459                                                      OBD_FAIL_ONCE);
1460                         }
1461                         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK)) {
1462                                 OBD_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_LONG_BULK_UNLINK,
1463                                                      OBD_FAIL_ONCE);
1464                         }
1465
1466                         /*
1467                          * Move to next phase if reply was successfully
1468                          * unlinked.
1469                          */
1470                         ptlrpc_rqphase_move(req, req->rq_next_phase);
1471                 }
1472
1473                 if (req->rq_phase == RQ_PHASE_COMPLETE)
1474                         continue;
1475
1476                 if (req->rq_phase == RQ_PHASE_INTERPRET)
1477                         GOTO(interpret, req->rq_status);
1478
1479                 /*
1480                  * Note that this also will start async reply unlink.
1481                  */
1482                 if (req->rq_net_err && !req->rq_timedout) {
1483                         ptlrpc_expire_one_request(req, 1);
1484
1485                         /*
1486                          * Check if we still need to wait for unlink.
1487                          */
1488                         if (ptlrpc_client_recv_or_unlink(req) ||
1489                             ptlrpc_client_bulk_active(req))
1490                                 continue;
1491                         /* If there is no need to resend, fail it now. */
1492                         if (req->rq_no_resend) {
1493                                 if (req->rq_status == 0)
1494                                         req->rq_status = -EIO;
1495                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1496                                 GOTO(interpret, req->rq_status);
1497                         } else {
1498                                 continue;
1499                         }
1500                 }
1501
1502                 if (req->rq_err) {
1503                         cfs_spin_lock(&req->rq_lock);
1504                         req->rq_replied = 0;
1505                         cfs_spin_unlock(&req->rq_lock);
1506                         if (req->rq_status == 0)
1507                                 req->rq_status = -EIO;
1508                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1509                         GOTO(interpret, req->rq_status);
1510                 }
1511
1512                 /* ptlrpc_set_wait->l_wait_event sets lwi_allow_intr
1513                  * so it sets rq_intr regardless of individual rpc
1514                  * timeouts. The synchronous IO waiting path sets 
1515                  * rq_intr irrespective of whether ptlrpcd
1516                  * has seen a timeout.  Our policy is to only interpret
1517                  * interrupted rpcs after they have timed out, so we
1518                  * need to enforce that here.
1519                  */
1520
1521                 if (req->rq_intr && (req->rq_timedout || req->rq_waiting ||
1522                                      req->rq_wait_ctx)) {
1523                         req->rq_status = -EINTR;
1524                         ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1525                         GOTO(interpret, req->rq_status);
1526                 }
1527
1528                 if (req->rq_phase == RQ_PHASE_RPC) {
1529                         if (req->rq_timedout || req->rq_resend ||
1530                             req->rq_waiting || req->rq_wait_ctx) {
1531                                 int status;
1532
1533                                 if (!ptlrpc_unregister_reply(req, 1))
1534                                         continue;
1535
1536                                 cfs_spin_lock(&imp->imp_lock);
1537                                 if (ptlrpc_import_delay_req(imp, req, &status)){
1538                                         /* put on delay list - only if we wait
1539                                          * recovery finished - before send */
1540                                         cfs_list_del_init(&req->rq_list);
1541                                         cfs_list_add_tail(&req->rq_list,
1542                                                           &imp-> \
1543                                                           imp_delayed_list);
1544                                         cfs_spin_unlock(&imp->imp_lock);
1545                                         continue;
1546                                 }
1547
1548                                 if (status != 0)  {
1549                                         req->rq_status = status;
1550                                         ptlrpc_rqphase_move(req,
1551                                                 RQ_PHASE_INTERPRET);
1552                                         cfs_spin_unlock(&imp->imp_lock);
1553                                         GOTO(interpret, req->rq_status);
1554                                 }
1555                                 if (ptlrpc_no_resend(req) && !req->rq_wait_ctx) {
1556                                         req->rq_status = -ENOTCONN;
1557                                         ptlrpc_rqphase_move(req,
1558                                                 RQ_PHASE_INTERPRET);
1559                                         cfs_spin_unlock(&imp->imp_lock);
1560                                         GOTO(interpret, req->rq_status);
1561                                 }
1562
1563                                 cfs_list_del_init(&req->rq_list);
1564                                 cfs_list_add_tail(&req->rq_list,
1565                                               &imp->imp_sending_list);
1566
1567                                 cfs_spin_unlock(&imp->imp_lock);
1568
1569                                 cfs_spin_lock(&req->rq_lock);
1570                                 req->rq_waiting = 0;
1571                                 cfs_spin_unlock(&req->rq_lock);
1572
1573                                 if (req->rq_timedout || req->rq_resend) {
1574                                         /* This is re-sending anyways,
1575                                          * let's mark req as resend. */
1576                                         cfs_spin_lock(&req->rq_lock);
1577                                         req->rq_resend = 1;
1578                                         cfs_spin_unlock(&req->rq_lock);
1579                                         if (req->rq_bulk) {
1580                                                 __u64 old_xid;
1581
1582                                                 if (!ptlrpc_unregister_bulk(req, 1))
1583                                                         continue;
1584
1585                                                 /* ensure previous bulk fails */
1586                                                 old_xid = req->rq_xid;
1587                                                 req->rq_xid = ptlrpc_next_xid();
1588                                                 CDEBUG(D_HA, "resend bulk "
1589                                                        "old x"LPU64
1590                                                        " new x"LPU64"\n",
1591                                                        old_xid, req->rq_xid);
1592                                         }
1593                                 }
1594                                 /*
1595                                  * rq_wait_ctx is only touched by ptlrpcd,
1596                                  * so no lock is needed here.
1597                                  */
1598                                 status = sptlrpc_req_refresh_ctx(req, -1);
1599                                 if (status) {
1600                                         if (req->rq_err) {
1601                                                 req->rq_status = status;
1602                                                 cfs_spin_lock(&req->rq_lock);
1603                                                 req->rq_wait_ctx = 0;
1604                                                 cfs_spin_unlock(&req->rq_lock);
1605                                                 force_timer_recalc = 1;
1606                                         } else {
1607                                                 cfs_spin_lock(&req->rq_lock);
1608                                                 req->rq_wait_ctx = 1;
1609                                                 cfs_spin_unlock(&req->rq_lock);
1610                                         }
1611
1612                                         continue;
1613                                 } else {
1614                                         cfs_spin_lock(&req->rq_lock);
1615                                         req->rq_wait_ctx = 0;
1616                                         cfs_spin_unlock(&req->rq_lock);
1617                                 }
1618
1619                                 rc = ptl_send_rpc(req, 0);
1620                                 if (rc) {
1621                                         DEBUG_REQ(D_HA, req, "send failed (%d)",
1622                                                   rc);
1623                                         force_timer_recalc = 1;
1624                                         cfs_spin_lock(&req->rq_lock);
1625                                         req->rq_net_err = 1;
1626                                         cfs_spin_unlock(&req->rq_lock);
1627                                 }
1628                                 /* need to reset the timeout */
1629                                 force_timer_recalc = 1;
1630                         }
1631
1632                         cfs_spin_lock(&req->rq_lock);
1633
1634                         if (ptlrpc_client_early(req)) {
1635                                 ptlrpc_at_recv_early_reply(req);
1636                                 cfs_spin_unlock(&req->rq_lock);
1637                                 continue;
1638                         }
1639
1640                         /* Still waiting for a reply? */
1641                         if (ptlrpc_client_recv(req)) {
1642                                 cfs_spin_unlock(&req->rq_lock);
1643                                 continue;
1644                         }
1645
1646                         /* Did we actually receive a reply? */
1647                         if (!ptlrpc_client_replied(req)) {
1648                                 cfs_spin_unlock(&req->rq_lock);
1649                                 continue;
1650                         }
1651
1652                         cfs_spin_unlock(&req->rq_lock);
1653
1654                         /* unlink from net because we are going to
1655                          * swab in-place of reply buffer */
1656                         unregistered = ptlrpc_unregister_reply(req, 1);
1657                         if (!unregistered)
1658                                 continue;
1659
1660                         req->rq_status = after_reply(req);
1661                         if (req->rq_resend)
1662                                 continue;
1663
1664                         /* If there is no bulk associated with this request,
1665                          * then we're done and should let the interpreter
1666                          * process the reply. Similarly if the RPC returned
1667                          * an error, and therefore the bulk will never arrive.
1668                          */
1669                         if (req->rq_bulk == NULL || req->rq_status < 0) {
1670                                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1671                                 GOTO(interpret, req->rq_status);
1672                         }
1673
1674                         ptlrpc_rqphase_move(req, RQ_PHASE_BULK);
1675                 }
1676
1677                 LASSERT(req->rq_phase == RQ_PHASE_BULK);
1678                 if (ptlrpc_client_bulk_active(req))
1679                         continue;
1680
1681                 if (!req->rq_bulk->bd_success) {
1682                         /* The RPC reply arrived OK, but the bulk screwed
1683                          * up!  Dead weird since the server told us the RPC
1684                          * was good after getting the REPLY for her GET or
1685                          * the ACK for her PUT. */
1686                         DEBUG_REQ(D_ERROR, req, "bulk transfer failed");
1687                         req->rq_status = -EIO;
1688                 }
1689
1690                 ptlrpc_rqphase_move(req, RQ_PHASE_INTERPRET);
1691
1692         interpret:
1693                 LASSERT(req->rq_phase == RQ_PHASE_INTERPRET);
1694
1695                 /* This moves to "unregistering" phase we need to wait for
1696                  * reply unlink. */
1697                 if (!unregistered && !ptlrpc_unregister_reply(req, 1)) {
1698                         /* start async bulk unlink too */
1699                         ptlrpc_unregister_bulk(req, 1);
1700                         continue;
1701                 }
1702
1703                 if (!ptlrpc_unregister_bulk(req, 1))
1704                         continue;
1705
1706                 /* When calling interpret receiving already should be
1707                  * finished. */
1708                 LASSERT(!req->rq_receiving_reply);
1709
1710                 ptlrpc_req_interpret(env, req, req->rq_status);
1711
1712                 ptlrpc_rqphase_move(req, RQ_PHASE_COMPLETE);
1713
1714                 CDEBUG(D_RPCTRACE, "Completed RPC pname:cluuid:pid:xid:nid:"
1715                        "opc %s:%s:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
1716                        imp->imp_obd->obd_uuid.uuid,
1717                        req->rq_reqmsg ? lustre_msg_get_status(req->rq_reqmsg):-1,
1718                        req->rq_xid,
1719                        libcfs_nid2str(imp->imp_connection->c_peer.nid),
1720                        req->rq_reqmsg ? lustre_msg_get_opc(req->rq_reqmsg) : -1);
1721
1722                 cfs_spin_lock(&imp->imp_lock);
1723                 /* Request already may be not on sending or delaying list. This
1724                  * may happen in the case of marking it erroneous for the case
1725                  * ptlrpc_import_delay_req(req, status) find it impossible to
1726                  * allow sending this rpc and returns *status != 0. */
1727                 if (!cfs_list_empty(&req->rq_list)) {
1728                         cfs_list_del_init(&req->rq_list);
1729                         cfs_atomic_dec(&imp->imp_inflight);
1730                 }
1731                 cfs_spin_unlock(&imp->imp_lock);
1732
1733                 cfs_atomic_dec(&set->set_remaining);
1734                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1735         }
1736
1737         /* If we hit an error, we want to recover promptly. */
1738         RETURN(cfs_atomic_read(&set->set_remaining) == 0 || force_timer_recalc);
1739 }
1740
1741 /**
1742  * Time out request \a req. is \a async_unlink is set, that means do not wait
1743  * until LNet actually confirms network buffer unlinking.
1744  * Return 1 if we should give up further retrying attempts or 0 otherwise.
1745  */
1746 int ptlrpc_expire_one_request(struct ptlrpc_request *req, int async_unlink)
1747 {
1748         struct obd_import *imp = req->rq_import;
1749         int rc = 0;
1750         ENTRY;
1751
1752         cfs_spin_lock(&req->rq_lock);
1753         req->rq_timedout = 1;
1754         cfs_spin_unlock(&req->rq_lock);
1755
1756         DEBUG_REQ(req->rq_fake ? D_INFO : D_WARNING, req, "Request "
1757                   " sent has %s: [sent "CFS_DURATION_T"/"
1758                   "real "CFS_DURATION_T"]",
1759                   req->rq_net_err ? "failed due to network error" :
1760                      ((req->rq_real_sent == 0 ||
1761                        cfs_time_before(req->rq_real_sent, req->rq_sent) ||
1762                        cfs_time_aftereq(req->rq_real_sent, req->rq_deadline)) ?
1763                       "timed out for sent delay" : "timed out for slow reply"),
1764                   req->rq_sent, req->rq_real_sent);
1765
1766         if (imp != NULL && obd_debug_peer_on_timeout)
1767                 LNetCtl(IOC_LIBCFS_DEBUG_PEER, &imp->imp_connection->c_peer);
1768
1769         ptlrpc_unregister_reply(req, async_unlink);
1770         ptlrpc_unregister_bulk(req, async_unlink);
1771
1772         if (obd_dump_on_timeout)
1773                 libcfs_debug_dumplog();
1774
1775         if (imp == NULL) {
1776                 DEBUG_REQ(D_HA, req, "NULL import: already cleaned up?");
1777                 RETURN(1);
1778         }
1779
1780         if (req->rq_fake)
1781                RETURN(1);
1782
1783         cfs_atomic_inc(&imp->imp_timeouts);
1784
1785         /* The DLM server doesn't want recovery run on its imports. */
1786         if (imp->imp_dlm_fake)
1787                 RETURN(1);
1788
1789         /* If this request is for recovery or other primordial tasks,
1790          * then error it out here. */
1791         if (req->rq_ctx_init || req->rq_ctx_fini ||
1792             req->rq_send_state != LUSTRE_IMP_FULL ||
1793             imp->imp_obd->obd_no_recov) {
1794                 DEBUG_REQ(D_RPCTRACE, req, "err -110, sent_state=%s (now=%s)",
1795                           ptlrpc_import_state_name(req->rq_send_state),
1796                           ptlrpc_import_state_name(imp->imp_state));
1797                 cfs_spin_lock(&req->rq_lock);
1798                 req->rq_status = -ETIMEDOUT;
1799                 req->rq_err = 1;
1800                 cfs_spin_unlock(&req->rq_lock);
1801                 RETURN(1);
1802         }
1803
1804         /* if a request can't be resent we can't wait for an answer after
1805            the timeout */
1806         if (ptlrpc_no_resend(req)) {
1807                 DEBUG_REQ(D_RPCTRACE, req, "TIMEOUT-NORESEND:");
1808                 rc = 1;
1809         }
1810
1811         ptlrpc_fail_import(imp, lustre_msg_get_conn_cnt(req->rq_reqmsg));
1812
1813         RETURN(rc);
1814 }
1815
1816 /**
1817  * Time out all uncompleted requests in request set pointed by \a data
1818  * Callback used when waiting on sets with l_wait_event.
1819  * Always returns 1.
1820  */
1821 int ptlrpc_expired_set(void *data)
1822 {
1823         struct ptlrpc_request_set *set = data;
1824         cfs_list_t                *tmp;
1825         time_t                     now = cfs_time_current_sec();
1826         ENTRY;
1827
1828         LASSERT(set != NULL);
1829
1830         /*
1831          * A timeout expired. See which reqs it applies to...
1832          */
1833         cfs_list_for_each (tmp, &set->set_requests) {
1834                 struct ptlrpc_request *req =
1835                         cfs_list_entry(tmp, struct ptlrpc_request,
1836                                        rq_set_chain);
1837
1838                 /* don't expire request waiting for context */
1839                 if (req->rq_wait_ctx)
1840                         continue;
1841
1842                 /* Request in-flight? */
1843                 if (!((req->rq_phase == RQ_PHASE_RPC &&
1844                        !req->rq_waiting && !req->rq_resend) ||
1845                       (req->rq_phase == RQ_PHASE_BULK)))
1846                         continue;
1847
1848                 if (req->rq_timedout ||     /* already dealt with */
1849                     req->rq_deadline > now) /* not expired */
1850                         continue;
1851
1852                 /* Deal with this guy. Do it asynchronously to not block
1853                  * ptlrpcd thread. */
1854                 ptlrpc_expire_one_request(req, 1);
1855         }
1856
1857         /*
1858          * When waiting for a whole set, we always break out of the
1859          * sleep so we can recalculate the timeout, or enable interrupts
1860          * if everyone's timed out.
1861          */
1862         RETURN(1);
1863 }
1864
1865 /**
1866  * Sets rq_intr flag in \a req under spinlock.
1867  */
1868 void ptlrpc_mark_interrupted(struct ptlrpc_request *req)
1869 {
1870         cfs_spin_lock(&req->rq_lock);
1871         req->rq_intr = 1;
1872         cfs_spin_unlock(&req->rq_lock);
1873 }
1874
1875 /**
1876  * Interrupts (sets interrupted flag) all uncompleted requests in
1877  * a set \a data. Callback for l_wait_event for interruptible waits.
1878  */
1879 void ptlrpc_interrupted_set(void *data)
1880 {
1881         struct ptlrpc_request_set *set = data;
1882         cfs_list_t *tmp;
1883
1884         LASSERT(set != NULL);
1885         CDEBUG(D_RPCTRACE, "INTERRUPTED SET %p\n", set);
1886
1887         cfs_list_for_each(tmp, &set->set_requests) {
1888                 struct ptlrpc_request *req =
1889                         cfs_list_entry(tmp, struct ptlrpc_request,
1890                                        rq_set_chain);
1891
1892                 if (req->rq_phase != RQ_PHASE_RPC &&
1893                     req->rq_phase != RQ_PHASE_UNREGISTERING)
1894                         continue;
1895
1896                 ptlrpc_mark_interrupted(req);
1897         }
1898 }
1899
1900 /**
1901  * Get the smallest timeout in the set; this does NOT set a timeout.
1902  */
1903 int ptlrpc_set_next_timeout(struct ptlrpc_request_set *set)
1904 {
1905         cfs_list_t            *tmp;
1906         time_t                 now = cfs_time_current_sec();
1907         int                    timeout = 0;
1908         struct ptlrpc_request *req;
1909         int                    deadline;
1910         ENTRY;
1911
1912         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
1913
1914         cfs_list_for_each(tmp, &set->set_requests) {
1915                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1916
1917                 /*
1918                  * Request in-flight?
1919                  */
1920                 if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
1921                       (req->rq_phase == RQ_PHASE_BULK) ||
1922                       (req->rq_phase == RQ_PHASE_NEW)))
1923                         continue;
1924
1925                 /*
1926                  * Already timed out.
1927                  */
1928                 if (req->rq_timedout)
1929                         continue;
1930
1931                 /*
1932                  * Waiting for ctx.
1933                  */
1934                 if (req->rq_wait_ctx)
1935                         continue;
1936
1937                 if (req->rq_phase == RQ_PHASE_NEW)
1938                         deadline = req->rq_sent;
1939                 else
1940                         deadline = req->rq_sent + req->rq_timeout;
1941
1942                 if (deadline <= now)    /* actually expired already */
1943                         timeout = 1;    /* ASAP */
1944                 else if (timeout == 0 || timeout > deadline - now)
1945                         timeout = deadline - now;
1946         }
1947         RETURN(timeout);
1948 }
1949
1950 /**
1951  * Send all unset request from the set and then wait untill all
1952  * requests in the set complete (either get a reply, timeout, get an
1953  * error or otherwise be interrupted).
1954  * Returns 0 on success or error code otherwise.
1955  */
1956 int ptlrpc_set_wait(struct ptlrpc_request_set *set)
1957 {
1958         cfs_list_t            *tmp;
1959         struct ptlrpc_request *req;
1960         struct l_wait_info     lwi;
1961         int                    rc, timeout;
1962         ENTRY;
1963
1964         if (cfs_list_empty(&set->set_requests))
1965                 RETURN(0);
1966
1967         cfs_list_for_each(tmp, &set->set_requests) {
1968                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
1969                 if (req->rq_phase == RQ_PHASE_NEW)
1970                         (void)ptlrpc_send_new_req(req);
1971         }
1972
1973         do {
1974                 timeout = ptlrpc_set_next_timeout(set);
1975
1976                 /* wait until all complete, interrupted, or an in-flight
1977                  * req times out */
1978                 CDEBUG(D_RPCTRACE, "set %p going to sleep for %d seconds\n",
1979                        set, timeout);
1980
1981                 if (timeout == 0 && !cfs_signal_pending())
1982                         /*
1983                          * No requests are in-flight (ether timed out
1984                          * or delayed), so we can allow interrupts.
1985                          * We still want to block for a limited time,
1986                          * so we allow interrupts during the timeout.
1987                          */
1988                         lwi = LWI_TIMEOUT_INTR_ALL(cfs_time_seconds(1), 
1989                                                    ptlrpc_expired_set,
1990                                                    ptlrpc_interrupted_set, set);
1991                 else
1992                         /*
1993                          * At least one request is in flight, so no
1994                          * interrupts are allowed. Wait until all
1995                          * complete, or an in-flight req times out. 
1996                          */
1997                         lwi = LWI_TIMEOUT(cfs_time_seconds(timeout? timeout : 1),
1998                                           ptlrpc_expired_set, set);
1999
2000                 rc = l_wait_event(set->set_waitq, ptlrpc_check_set(NULL, set), &lwi);
2001
2002                 /* LU-769 - if we ignored the signal because it was already
2003                  * pending when we started, we need to handle it now or we risk
2004                  * it being ignored forever */
2005                 if (rc == -ETIMEDOUT && !lwi.lwi_allow_intr &&
2006                     cfs_signal_pending()) {
2007                         cfs_sigset_t blocked_sigs =
2008                                            cfs_block_sigsinv(LUSTRE_FATAL_SIGS);
2009
2010                         /* In fact we only interrupt for the "fatal" signals
2011                          * like SIGINT or SIGKILL. We still ignore less
2012                          * important signals since ptlrpc set is not easily
2013                          * reentrant from userspace again */
2014                         if (cfs_signal_pending())
2015                                 ptlrpc_interrupted_set(set);
2016                         cfs_block_sigs(blocked_sigs);
2017                 }
2018
2019                 LASSERT(rc == 0 || rc == -EINTR || rc == -ETIMEDOUT);
2020
2021                 /* -EINTR => all requests have been flagged rq_intr so next
2022                  * check completes.
2023                  * -ETIMEDOUT => someone timed out.  When all reqs have
2024                  * timed out, signals are enabled allowing completion with
2025                  * EINTR.
2026                  * I don't really care if we go once more round the loop in
2027                  * the error cases -eeb. */
2028                 if (rc == 0 && cfs_atomic_read(&set->set_remaining) == 0) {
2029                         cfs_list_for_each(tmp, &set->set_requests) {
2030                                 req = cfs_list_entry(tmp, struct ptlrpc_request,
2031                                                      rq_set_chain);
2032                                 cfs_spin_lock(&req->rq_lock);
2033                                 req->rq_invalid_rqset = 1;
2034                                 cfs_spin_unlock(&req->rq_lock);
2035                         }
2036                 }
2037         } while (rc != 0 || cfs_atomic_read(&set->set_remaining) != 0);
2038
2039         LASSERT(cfs_atomic_read(&set->set_remaining) == 0);
2040
2041         rc = 0;
2042         cfs_list_for_each(tmp, &set->set_requests) {
2043                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_set_chain);
2044
2045                 LASSERT(req->rq_phase == RQ_PHASE_COMPLETE);
2046                 if (req->rq_status != 0)
2047                         rc = req->rq_status;
2048         }
2049
2050         if (set->set_interpret != NULL) {
2051                 int (*interpreter)(struct ptlrpc_request_set *set,void *,int) =
2052                         set->set_interpret;
2053                 rc = interpreter (set, set->set_arg, rc);
2054         } else {
2055                 struct ptlrpc_set_cbdata *cbdata, *n;
2056                 int err;
2057
2058                 cfs_list_for_each_entry_safe(cbdata, n,
2059                                          &set->set_cblist, psc_item) {
2060                         cfs_list_del_init(&cbdata->psc_item);
2061                         err = cbdata->psc_interpret(set, cbdata->psc_data, rc);
2062                         if (err && !rc)
2063                                 rc = err;
2064                         OBD_FREE_PTR(cbdata);
2065                 }
2066         }
2067
2068         RETURN(rc);
2069 }
2070
2071 /**
2072  * Helper fuction for request freeing.
2073  * Called when request count reached zero and request needs to be freed.
2074  * Removes request from all sorts of sending/replay lists it might be on,
2075  * frees network buffers if any are present.
2076  * If \a locked is set, that means caller is already holding import imp_lock
2077  * and so we no longer need to reobtain it (for certain lists manipulations)
2078  */
2079 static void __ptlrpc_free_req(struct ptlrpc_request *request, int locked)
2080 {
2081         ENTRY;
2082         if (request == NULL) {
2083                 EXIT;
2084                 return;
2085         }
2086
2087         LASSERTF(!request->rq_receiving_reply, "req %p\n", request);
2088         LASSERTF(request->rq_rqbd == NULL, "req %p\n",request);/* client-side */
2089         LASSERTF(cfs_list_empty(&request->rq_list), "req %p\n", request);
2090         LASSERTF(cfs_list_empty(&request->rq_set_chain), "req %p\n", request);
2091         LASSERTF(cfs_list_empty(&request->rq_exp_list), "req %p\n", request);
2092         LASSERTF(!request->rq_replay, "req %p\n", request);
2093
2094         req_capsule_fini(&request->rq_pill);
2095
2096         /* We must take it off the imp_replay_list first.  Otherwise, we'll set
2097          * request->rq_reqmsg to NULL while osc_close is dereferencing it. */
2098         if (request->rq_import != NULL) {
2099                 if (!locked)
2100                         cfs_spin_lock(&request->rq_import->imp_lock);
2101                 cfs_list_del_init(&request->rq_replay_list);
2102                 if (!locked)
2103                         cfs_spin_unlock(&request->rq_import->imp_lock);
2104         }
2105         LASSERTF(cfs_list_empty(&request->rq_replay_list), "req %p\n", request);
2106
2107         if (cfs_atomic_read(&request->rq_refcount) != 0) {
2108                 DEBUG_REQ(D_ERROR, request,
2109                           "freeing request with nonzero refcount");
2110                 LBUG();
2111         }
2112
2113         if (request->rq_repbuf != NULL)
2114                 sptlrpc_cli_free_repbuf(request);
2115         if (request->rq_export != NULL) {
2116                 class_export_put(request->rq_export);
2117                 request->rq_export = NULL;
2118         }
2119         if (request->rq_import != NULL) {
2120                 class_import_put(request->rq_import);
2121                 request->rq_import = NULL;
2122         }
2123         if (request->rq_bulk != NULL)
2124                 ptlrpc_free_bulk(request->rq_bulk);
2125
2126         if (request->rq_reqbuf != NULL || request->rq_clrbuf != NULL)
2127                 sptlrpc_cli_free_reqbuf(request);
2128
2129         if (request->rq_cli_ctx)
2130                 sptlrpc_req_put_ctx(request, !locked);
2131
2132         if (request->rq_pool)
2133                 __ptlrpc_free_req_to_pool(request);
2134         else
2135                 OBD_FREE(request, sizeof(*request));
2136         EXIT;
2137 }
2138
2139 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked);
2140 /**
2141  * Drop one request reference. Must be called with import imp_lock held.
2142  * When reference count drops to zero, reuqest is freed.
2143  */
2144 void ptlrpc_req_finished_with_imp_lock(struct ptlrpc_request *request)
2145 {
2146         LASSERT_SPIN_LOCKED(&request->rq_import->imp_lock);
2147         (void)__ptlrpc_req_finished(request, 1);
2148 }
2149
2150 /**
2151  * Helper function
2152  * Drops one reference count for request \a request.
2153  * \a locked set indicates that caller holds import imp_lock.
2154  * Frees the request whe reference count reaches zero.
2155  */
2156 static int __ptlrpc_req_finished(struct ptlrpc_request *request, int locked)
2157 {
2158         ENTRY;
2159         if (request == NULL)
2160                 RETURN(1);
2161
2162         if (request == LP_POISON ||
2163             request->rq_reqmsg == LP_POISON) {
2164                 CERROR("dereferencing freed request (bug 575)\n");
2165                 LBUG();
2166                 RETURN(1);
2167         }
2168
2169         DEBUG_REQ(D_INFO, request, "refcount now %u",
2170                   cfs_atomic_read(&request->rq_refcount) - 1);
2171
2172         if (cfs_atomic_dec_and_test(&request->rq_refcount)) {
2173                 __ptlrpc_free_req(request, locked);
2174                 RETURN(1);
2175         }
2176
2177         RETURN(0);
2178 }
2179
2180 /**
2181  * Drops one reference count for a request.
2182  */
2183 void ptlrpc_req_finished(struct ptlrpc_request *request)
2184 {
2185         __ptlrpc_req_finished(request, 0);
2186 }
2187
2188 /**
2189  * Returns xid of a \a request
2190  */
2191 __u64 ptlrpc_req_xid(struct ptlrpc_request *request)
2192 {
2193         return request->rq_xid;
2194 }
2195 EXPORT_SYMBOL(ptlrpc_req_xid);
2196
2197 /**
2198  * Disengage the client's reply buffer from the network
2199  * NB does _NOT_ unregister any client-side bulk.
2200  * IDEMPOTENT, but _not_ safe against concurrent callers.
2201  * The request owner (i.e. the thread doing the I/O) must call...
2202  * Returns 0 on success or 1 if unregistering cannot be made.
2203  */
2204 int ptlrpc_unregister_reply(struct ptlrpc_request *request, int async)
2205 {
2206         int                rc;
2207         cfs_waitq_t       *wq;
2208         struct l_wait_info lwi;
2209
2210         /*
2211          * Might sleep.
2212          */
2213         LASSERT(!cfs_in_interrupt());
2214
2215         /*
2216          * Let's setup deadline for reply unlink.
2217          */
2218         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK) &&
2219             async && request->rq_reply_deadline == 0)
2220                 request->rq_reply_deadline = cfs_time_current_sec()+LONG_UNLINK;
2221
2222         /*
2223          * Nothing left to do.
2224          */
2225         if (!ptlrpc_client_recv_or_unlink(request))
2226                 RETURN(1);
2227
2228         LNetMDUnlink(request->rq_reply_md_h);
2229
2230         /*
2231          * Let's check it once again.
2232          */
2233         if (!ptlrpc_client_recv_or_unlink(request))
2234                 RETURN(1);
2235
2236         /*
2237          * Move to "Unregistering" phase as reply was not unlinked yet.
2238          */
2239         ptlrpc_rqphase_move(request, RQ_PHASE_UNREGISTERING);
2240
2241         /*
2242          * Do not wait for unlink to finish.
2243          */
2244         if (async)
2245                 RETURN(0);
2246
2247         /*
2248          * We have to l_wait_event() whatever the result, to give liblustre
2249          * a chance to run reply_in_callback(), and to make sure we've
2250          * unlinked before returning a req to the pool.
2251          */
2252         if (request->rq_set != NULL)
2253                 wq = &request->rq_set->set_waitq;
2254         else
2255                 wq = &request->rq_reply_waitq;
2256
2257         for (;;) {
2258                 /* Network access will complete in finite time but the HUGE
2259                  * timeout lets us CWARN for visibility of sluggish NALs */
2260                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
2261                                            cfs_time_seconds(1), NULL, NULL);
2262                 rc = l_wait_event(*wq, !ptlrpc_client_recv_or_unlink(request),
2263                                   &lwi);
2264                 if (rc == 0) {
2265                         ptlrpc_rqphase_move(request, request->rq_next_phase);
2266                         RETURN(1);
2267                 }
2268
2269                 LASSERT(rc == -ETIMEDOUT);
2270                 DEBUG_REQ(D_WARNING, request, "Unexpectedly long timeout "
2271                           "rvcng=%d unlnk=%d", request->rq_receiving_reply,
2272                           request->rq_must_unlink);
2273         }
2274         RETURN(0);
2275 }
2276
2277 /**
2278  * Iterates through replay_list on import and prunes
2279  * all requests have transno smaller than last_committed for the
2280  * import and don't have rq_replay set.
2281  * Since requests are sorted in transno order, stops when meetign first
2282  * transno bigger than last_committed.
2283  * caller must hold imp->imp_lock
2284  */
2285 void ptlrpc_free_committed(struct obd_import *imp)
2286 {
2287         cfs_list_t *tmp, *saved;
2288         struct ptlrpc_request *req;
2289         struct ptlrpc_request *last_req = NULL; /* temporary fire escape */
2290         ENTRY;
2291
2292         LASSERT(imp != NULL);
2293
2294         LASSERT_SPIN_LOCKED(&imp->imp_lock);
2295
2296
2297         if (imp->imp_peer_committed_transno == imp->imp_last_transno_checked &&
2298             imp->imp_generation == imp->imp_last_generation_checked) {
2299                 CDEBUG(D_INFO, "%s: skip recheck: last_committed "LPU64"\n",
2300                        imp->imp_obd->obd_name, imp->imp_peer_committed_transno);
2301                 EXIT;
2302                 return;
2303         }
2304         CDEBUG(D_RPCTRACE, "%s: committing for last_committed "LPU64" gen %d\n",
2305                imp->imp_obd->obd_name, imp->imp_peer_committed_transno,
2306                imp->imp_generation);
2307         imp->imp_last_transno_checked = imp->imp_peer_committed_transno;
2308         imp->imp_last_generation_checked = imp->imp_generation;
2309
2310         cfs_list_for_each_safe(tmp, saved, &imp->imp_replay_list) {
2311                 req = cfs_list_entry(tmp, struct ptlrpc_request,
2312                                      rq_replay_list);
2313
2314                 /* XXX ok to remove when 1357 resolved - rread 05/29/03  */
2315                 LASSERT(req != last_req);
2316                 last_req = req;
2317
2318                 if (req->rq_transno == 0) {
2319                         DEBUG_REQ(D_EMERG, req, "zero transno during replay");
2320                         LBUG();
2321                 }
2322                 if (req->rq_import_generation < imp->imp_generation) {
2323                         DEBUG_REQ(D_RPCTRACE, req, "free request with old gen");
2324                         GOTO(free_req, 0);
2325                 }
2326
2327                 if (req->rq_replay) {
2328                         DEBUG_REQ(D_RPCTRACE, req, "keeping (FL_REPLAY)");
2329                         continue;
2330                 }
2331
2332                 /* not yet committed */
2333                 if (req->rq_transno > imp->imp_peer_committed_transno) {
2334                         DEBUG_REQ(D_RPCTRACE, req, "stopping search");
2335                         break;
2336                 }
2337
2338                 DEBUG_REQ(D_INFO, req, "commit (last_committed "LPU64")",
2339                           imp->imp_peer_committed_transno);
2340 free_req:
2341                 cfs_spin_lock(&req->rq_lock);
2342                 req->rq_replay = 0;
2343                 cfs_spin_unlock(&req->rq_lock);
2344                 if (req->rq_commit_cb != NULL)
2345                         req->rq_commit_cb(req);
2346                 cfs_list_del_init(&req->rq_replay_list);
2347                 __ptlrpc_req_finished(req, 1);
2348         }
2349
2350         EXIT;
2351         return;
2352 }
2353
2354 void ptlrpc_cleanup_client(struct obd_import *imp)
2355 {
2356         ENTRY;
2357         EXIT;
2358         return;
2359 }
2360
2361 /**
2362  * Schedule previously sent request for resend.
2363  * For bulk requests we assign new xid (to avoid problems with
2364  * lost replies and therefore several transfers landing into same buffer
2365  * from different sending attempts).
2366  */
2367 void ptlrpc_resend_req(struct ptlrpc_request *req)
2368 {
2369         DEBUG_REQ(D_HA, req, "going to resend");
2370         lustre_msg_set_handle(req->rq_reqmsg, &(struct lustre_handle){ 0 });
2371         req->rq_status = -EAGAIN;
2372
2373         cfs_spin_lock(&req->rq_lock);
2374         req->rq_resend = 1;
2375         req->rq_net_err = 0;
2376         req->rq_timedout = 0;
2377         if (req->rq_bulk) {
2378                 __u64 old_xid = req->rq_xid;
2379
2380                 /* ensure previous bulk fails */
2381                 req->rq_xid = ptlrpc_next_xid();
2382                 CDEBUG(D_HA, "resend bulk old x"LPU64" new x"LPU64"\n",
2383                        old_xid, req->rq_xid);
2384         }
2385         ptlrpc_client_wake_req(req);
2386         cfs_spin_unlock(&req->rq_lock);
2387 }
2388
2389 /* XXX: this function and rq_status are currently unused */
2390 void ptlrpc_restart_req(struct ptlrpc_request *req)
2391 {
2392         DEBUG_REQ(D_HA, req, "restarting (possibly-)completed request");
2393         req->rq_status = -ERESTARTSYS;
2394
2395         cfs_spin_lock(&req->rq_lock);
2396         req->rq_restart = 1;
2397         req->rq_timedout = 0;
2398         ptlrpc_client_wake_req(req);
2399         cfs_spin_unlock(&req->rq_lock);
2400 }
2401
2402 /**
2403  * Grab additional reference on a request \a req
2404  */
2405 struct ptlrpc_request *ptlrpc_request_addref(struct ptlrpc_request *req)
2406 {
2407         ENTRY;
2408         cfs_atomic_inc(&req->rq_refcount);
2409         RETURN(req);
2410 }
2411
2412 /**
2413  * Add a request to import replay_list.
2414  * Must be called under imp_lock
2415  */
2416 void ptlrpc_retain_replayable_request(struct ptlrpc_request *req,
2417                                       struct obd_import *imp)
2418 {
2419         cfs_list_t *tmp;
2420
2421         LASSERT_SPIN_LOCKED(&imp->imp_lock);
2422
2423         if (req->rq_transno == 0) {
2424                 DEBUG_REQ(D_EMERG, req, "saving request with zero transno");
2425                 LBUG();
2426         }
2427
2428         /* clear this for new requests that were resent as well
2429            as resent replayed requests. */
2430         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
2431
2432         /* don't re-add requests that have been replayed */
2433         if (!cfs_list_empty(&req->rq_replay_list))
2434                 return;
2435
2436         lustre_msg_add_flags(req->rq_reqmsg, MSG_REPLAY);
2437
2438         LASSERT(imp->imp_replayable);
2439         /* Balanced in ptlrpc_free_committed, usually. */
2440         ptlrpc_request_addref(req);
2441         cfs_list_for_each_prev(tmp, &imp->imp_replay_list) {
2442                 struct ptlrpc_request *iter =
2443                         cfs_list_entry(tmp, struct ptlrpc_request,
2444                                        rq_replay_list);
2445
2446                 /* We may have duplicate transnos if we create and then
2447                  * open a file, or for closes retained if to match creating
2448                  * opens, so use req->rq_xid as a secondary key.
2449                  * (See bugs 684, 685, and 428.)
2450                  * XXX no longer needed, but all opens need transnos!
2451                  */
2452                 if (iter->rq_transno > req->rq_transno)
2453                         continue;
2454
2455                 if (iter->rq_transno == req->rq_transno) {
2456                         LASSERT(iter->rq_xid != req->rq_xid);
2457                         if (iter->rq_xid > req->rq_xid)
2458                                 continue;
2459                 }
2460
2461                 cfs_list_add(&req->rq_replay_list, &iter->rq_replay_list);
2462                 return;
2463         }
2464
2465         cfs_list_add(&req->rq_replay_list, &imp->imp_replay_list);
2466 }
2467
2468 /**
2469  * Send request and wait until it completes.
2470  * Returns request processing status.
2471  */
2472 int ptlrpc_queue_wait(struct ptlrpc_request *req)
2473 {
2474         struct ptlrpc_request_set *set;
2475         int rc;
2476         ENTRY;
2477
2478         LASSERT(req->rq_set == NULL);
2479         LASSERT(!req->rq_receiving_reply);
2480
2481         set = ptlrpc_prep_set();
2482         if (set == NULL) {
2483                 CERROR("Unable to allocate ptlrpc set.");
2484                 RETURN(-ENOMEM);
2485         }
2486
2487         /* for distributed debugging */
2488         lustre_msg_set_status(req->rq_reqmsg, cfs_curproc_pid());
2489
2490         /* add a ref for the set (see comment in ptlrpc_set_add_req) */
2491         ptlrpc_request_addref(req);
2492         ptlrpc_set_add_req(set, req);
2493         rc = ptlrpc_set_wait(set);
2494         ptlrpc_set_destroy(set);
2495
2496         RETURN(rc);
2497 }
2498
2499 struct ptlrpc_replay_async_args {
2500         int praa_old_state;
2501         int praa_old_status;
2502 };
2503
2504 /**
2505  * Callback used for replayed requests reply processing.
2506  * In case of succesful reply calls registeresd request replay callback.
2507  * In case of error restart replay process.
2508  */
2509 static int ptlrpc_replay_interpret(const struct lu_env *env,
2510                                    struct ptlrpc_request *req,
2511                                    void * data, int rc)
2512 {
2513         struct ptlrpc_replay_async_args *aa = data;
2514         struct obd_import *imp = req->rq_import;
2515
2516         ENTRY;
2517         cfs_atomic_dec(&imp->imp_replay_inflight);
2518
2519         if (!ptlrpc_client_replied(req)) {
2520                 CERROR("request replay timed out, restarting recovery\n");
2521                 GOTO(out, rc = -ETIMEDOUT);
2522         }
2523
2524         if (lustre_msg_get_type(req->rq_repmsg) == PTL_RPC_MSG_ERR &&
2525             (lustre_msg_get_status(req->rq_repmsg) == -ENOTCONN ||
2526              lustre_msg_get_status(req->rq_repmsg) == -ENODEV))
2527                 GOTO(out, rc = lustre_msg_get_status(req->rq_repmsg));
2528
2529         /** VBR: check version failure */
2530         if (lustre_msg_get_status(req->rq_repmsg) == -EOVERFLOW) {
2531                 /** replay was failed due to version mismatch */
2532                 DEBUG_REQ(D_WARNING, req, "Version mismatch during replay\n");
2533                 cfs_spin_lock(&imp->imp_lock);
2534                 imp->imp_vbr_failed = 1;
2535                 imp->imp_no_lock_replay = 1;
2536                 cfs_spin_unlock(&imp->imp_lock);
2537                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
2538         } else {
2539                 /** The transno had better not change over replay. */
2540                 LASSERTF(lustre_msg_get_transno(req->rq_reqmsg) ==
2541                          lustre_msg_get_transno(req->rq_repmsg) ||
2542                          lustre_msg_get_transno(req->rq_repmsg) == 0,
2543                          LPX64"/"LPX64"\n",
2544                          lustre_msg_get_transno(req->rq_reqmsg),
2545                          lustre_msg_get_transno(req->rq_repmsg));
2546         }
2547
2548         cfs_spin_lock(&imp->imp_lock);
2549         /** if replays by version then gap was occur on server, no trust to locks */
2550         if (lustre_msg_get_flags(req->rq_repmsg) & MSG_VERSION_REPLAY)
2551                 imp->imp_no_lock_replay = 1;
2552         imp->imp_last_replay_transno = lustre_msg_get_transno(req->rq_reqmsg);
2553         cfs_spin_unlock(&imp->imp_lock);
2554         LASSERT(imp->imp_last_replay_transno);
2555
2556         /* transaction number shouldn't be bigger than the latest replayed */
2557         if (req->rq_transno > lustre_msg_get_transno(req->rq_reqmsg)) {
2558                 DEBUG_REQ(D_ERROR, req,
2559                           "Reported transno "LPU64" is bigger than the "
2560                           "replayed one: "LPU64, req->rq_transno,
2561                           lustre_msg_get_transno(req->rq_reqmsg));
2562                 GOTO(out, rc = -EINVAL);
2563         }
2564
2565         DEBUG_REQ(D_HA, req, "got rep");
2566
2567         /* let the callback do fixups, possibly including in the request */
2568         if (req->rq_replay_cb)
2569                 req->rq_replay_cb(req);
2570
2571         if (ptlrpc_client_replied(req) &&
2572             lustre_msg_get_status(req->rq_repmsg) != aa->praa_old_status) {
2573                 DEBUG_REQ(D_ERROR, req, "status %d, old was %d",
2574                           lustre_msg_get_status(req->rq_repmsg),
2575                           aa->praa_old_status);
2576         } else {
2577                 /* Put it back for re-replay. */
2578                 lustre_msg_set_status(req->rq_repmsg, aa->praa_old_status);
2579         }
2580
2581         /*
2582          * Errors while replay can set transno to 0, but
2583          * imp_last_replay_transno shouldn't be set to 0 anyway
2584          */
2585         if (req->rq_transno == 0)
2586                 CERROR("Transno is 0 during replay!\n");
2587
2588         /* continue with recovery */
2589         rc = ptlrpc_import_recovery_state_machine(imp);
2590  out:
2591         req->rq_send_state = aa->praa_old_state;
2592
2593         if (rc != 0)
2594                 /* this replay failed, so restart recovery */
2595                 ptlrpc_connect_import(imp);
2596
2597         RETURN(rc);
2598 }
2599
2600 /**
2601  * Prepares and queues request for replay.
2602  * Adds it to ptlrpcd queue for actual sending.
2603  * Returns 0 on success.
2604  */
2605 int ptlrpc_replay_req(struct ptlrpc_request *req)
2606 {
2607         struct ptlrpc_replay_async_args *aa;
2608         ENTRY;
2609
2610         LASSERT(req->rq_import->imp_state == LUSTRE_IMP_REPLAY);
2611
2612         LASSERT (sizeof (*aa) <= sizeof (req->rq_async_args));
2613         aa = ptlrpc_req_async_args(req);
2614         memset(aa, 0, sizeof *aa);
2615
2616         /* Prepare request to be resent with ptlrpcd */
2617         aa->praa_old_state = req->rq_send_state;
2618         req->rq_send_state = LUSTRE_IMP_REPLAY;
2619         req->rq_phase = RQ_PHASE_NEW;
2620         req->rq_next_phase = RQ_PHASE_UNDEFINED;
2621         if (req->rq_repmsg)
2622                 aa->praa_old_status = lustre_msg_get_status(req->rq_repmsg);
2623         req->rq_status = 0;
2624         req->rq_interpret_reply = ptlrpc_replay_interpret;
2625         /* Readjust the timeout for current conditions */
2626         ptlrpc_at_set_req_timeout(req);
2627
2628         /* Tell server the net_latency, so the server can calculate how long
2629          * it should wait for next replay */
2630         lustre_msg_set_service_time(req->rq_reqmsg,
2631                                     ptlrpc_at_get_net_latency(req));
2632         DEBUG_REQ(D_HA, req, "REPLAY");
2633
2634         cfs_atomic_inc(&req->rq_import->imp_replay_inflight);
2635         ptlrpc_request_addref(req); /* ptlrpcd needs a ref */
2636
2637         ptlrpcd_add_req(req, PDL_POLICY_LOCAL, -1);
2638         RETURN(0);
2639 }
2640
2641 /**
2642  * Aborts all in-flight request on import \a imp sending and delayed lists
2643  */
2644 void ptlrpc_abort_inflight(struct obd_import *imp)
2645 {
2646         cfs_list_t *tmp, *n;
2647         ENTRY;
2648
2649         /* Make sure that no new requests get processed for this import.
2650          * ptlrpc_{queue,set}_wait must (and does) hold imp_lock while testing
2651          * this flag and then putting requests on sending_list or delayed_list.
2652          */
2653         cfs_spin_lock(&imp->imp_lock);
2654
2655         /* XXX locking?  Maybe we should remove each request with the list
2656          * locked?  Also, how do we know if the requests on the list are
2657          * being freed at this time?
2658          */
2659         cfs_list_for_each_safe(tmp, n, &imp->imp_sending_list) {
2660                 struct ptlrpc_request *req =
2661                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2662
2663                 DEBUG_REQ(D_RPCTRACE, req, "inflight");
2664
2665                 cfs_spin_lock (&req->rq_lock);
2666                 if (req->rq_import_generation < imp->imp_generation) {
2667                         req->rq_err = 1;
2668                         req->rq_status = -EINTR;
2669                         ptlrpc_client_wake_req(req);
2670                 }
2671                 cfs_spin_unlock (&req->rq_lock);
2672         }
2673
2674         cfs_list_for_each_safe(tmp, n, &imp->imp_delayed_list) {
2675                 struct ptlrpc_request *req =
2676                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2677
2678                 DEBUG_REQ(D_RPCTRACE, req, "aborting waiting req");
2679
2680                 cfs_spin_lock (&req->rq_lock);
2681                 if (req->rq_import_generation < imp->imp_generation) {
2682                         req->rq_err = 1;
2683                         req->rq_status = -EINTR;
2684                         ptlrpc_client_wake_req(req);
2685                 }
2686                 cfs_spin_unlock (&req->rq_lock);
2687         }
2688
2689         /* Last chance to free reqs left on the replay list, but we
2690          * will still leak reqs that haven't committed.  */
2691         if (imp->imp_replayable)
2692                 ptlrpc_free_committed(imp);
2693
2694         cfs_spin_unlock(&imp->imp_lock);
2695
2696         EXIT;
2697 }
2698
2699 /**
2700  * Abort all uncompleted requests in request set \a set
2701  */
2702 void ptlrpc_abort_set(struct ptlrpc_request_set *set)
2703 {
2704         cfs_list_t *tmp, *pos;
2705
2706         LASSERT(set != NULL);
2707
2708         cfs_list_for_each_safe(pos, tmp, &set->set_requests) {
2709                 struct ptlrpc_request *req =
2710                         cfs_list_entry(pos, struct ptlrpc_request,
2711                                        rq_set_chain);
2712
2713                 cfs_spin_lock(&req->rq_lock);
2714                 if (req->rq_phase != RQ_PHASE_RPC) {
2715                         cfs_spin_unlock(&req->rq_lock);
2716                         continue;
2717                 }
2718
2719                 req->rq_err = 1;
2720                 req->rq_status = -EINTR;
2721                 ptlrpc_client_wake_req(req);
2722                 cfs_spin_unlock(&req->rq_lock);
2723         }
2724 }
2725
2726 static __u64 ptlrpc_last_xid;
2727 static cfs_spinlock_t ptlrpc_last_xid_lock;
2728
2729 /**
2730  * Initialize the XID for the node.  This is common among all requests on
2731  * this node, and only requires the property that it is monotonically
2732  * increasing.  It does not need to be sequential.  Since this is also used
2733  * as the RDMA match bits, it is important that a single client NOT have
2734  * the same match bits for two different in-flight requests, hence we do
2735  * NOT want to have an XID per target or similar.
2736  *
2737  * To avoid an unlikely collision between match bits after a client reboot
2738  * (which would deliver old data into the wrong RDMA buffer) initialize
2739  * the XID based on the current time, assuming a maximum RPC rate of 1M RPC/s.
2740  * If the time is clearly incorrect, we instead use a 62-bit random number.
2741  * In the worst case the random number will overflow 1M RPCs per second in
2742  * 9133 years, or permutations thereof.
2743  */
2744 #define YEAR_2004 (1ULL << 30)
2745 void ptlrpc_init_xid(void)
2746 {
2747         time_t now = cfs_time_current_sec();
2748
2749         cfs_spin_lock_init(&ptlrpc_last_xid_lock);
2750         if (now < YEAR_2004) {
2751                 cfs_get_random_bytes(&ptlrpc_last_xid, sizeof(ptlrpc_last_xid));
2752                 ptlrpc_last_xid >>= 2;
2753                 ptlrpc_last_xid |= (1ULL << 61);
2754         } else {
2755                 ptlrpc_last_xid = (__u64)now << 20;
2756         }
2757 }
2758
2759 /**
2760  * Increase xid and returns resultng new value to the caller.
2761  */
2762 __u64 ptlrpc_next_xid(void)
2763 {
2764         __u64 tmp;
2765         cfs_spin_lock(&ptlrpc_last_xid_lock);
2766         tmp = ++ptlrpc_last_xid;
2767         cfs_spin_unlock(&ptlrpc_last_xid_lock);
2768         return tmp;
2769 }
2770
2771 /**
2772  * Get a glimpse at what next xid value might have been.
2773  * Returns possible next xid.
2774  */
2775 __u64 ptlrpc_sample_next_xid(void)
2776 {
2777 #if BITS_PER_LONG == 32
2778         /* need to avoid possible word tearing on 32-bit systems */
2779         __u64 tmp;
2780         cfs_spin_lock(&ptlrpc_last_xid_lock);
2781         tmp = ptlrpc_last_xid + 1;
2782         cfs_spin_unlock(&ptlrpc_last_xid_lock);
2783         return tmp;
2784 #else
2785         /* No need to lock, since returned value is racy anyways */
2786         return ptlrpc_last_xid + 1;
2787 #endif
2788 }
2789 EXPORT_SYMBOL(ptlrpc_sample_next_xid);
2790
2791 /**
2792  * Functions for operating ptlrpc workers.
2793  *
2794  * A ptlrpc work is a function which will be running inside ptlrpc context.
2795  * The callback shouldn't sleep otherwise it will block that ptlrpcd thread.
2796  *
2797  * 1. after a work is created, it can be used many times, that is:
2798  *         handler = ptlrpcd_alloc_work();
2799  *         ptlrpcd_queue_work();
2800  *
2801  *    queue it again when necessary:
2802  *         ptlrpcd_queue_work();
2803  *         ptlrpcd_destroy_work();
2804  * 2. ptlrpcd_queue_work() can be called by multiple processes meanwhile, but
2805  *    it will only be queued once in any time. Also as its name implies, it may
2806  *    have delay before it really runs by ptlrpcd thread.
2807  */
2808 struct ptlrpc_work_async_args {
2809         __u64   magic;
2810         int   (*cb)(const struct lu_env *, void *);
2811         void   *cbdata;
2812 };
2813
2814 #define PTLRPC_WORK_MAGIC 0x6655436b676f4f44ULL /* magic code */
2815
2816 static int work_interpreter(const struct lu_env *env,
2817                             struct ptlrpc_request *req, void *data, int rc)
2818 {
2819         struct ptlrpc_work_async_args *arg = data;
2820
2821         LASSERT(arg->magic == PTLRPC_WORK_MAGIC);
2822         LASSERT(arg->cb != NULL);
2823
2824         return arg->cb(env, arg->cbdata);
2825 }
2826
2827 /**
2828  * Create a work for ptlrpc.
2829  */
2830 void *ptlrpcd_alloc_work(struct obd_import *imp,
2831                          int (*cb)(const struct lu_env *, void *), void *cbdata)
2832 {
2833         struct ptlrpc_request         *req = NULL;
2834         struct ptlrpc_work_async_args *args;
2835         ENTRY;
2836
2837         cfs_might_sleep();
2838
2839         if (cb == NULL)
2840                 RETURN(ERR_PTR(-EINVAL));
2841
2842         /* copy some code from deprecated fakereq. */
2843         OBD_ALLOC_PTR(req);
2844         if (req == NULL) {
2845                 CERROR("ptlrpc: run out of memory!\n");
2846                 RETURN(ERR_PTR(-ENOMEM));
2847         }
2848
2849         req->rq_send_state = LUSTRE_IMP_FULL;
2850         req->rq_type = PTL_RPC_MSG_REQUEST;
2851         req->rq_import = class_import_get(imp);
2852         req->rq_export = NULL;
2853         req->rq_interpret_reply = work_interpreter;
2854         /* don't want reply */
2855         req->rq_receiving_reply = 0;
2856         req->rq_must_unlink = 0;
2857         req->rq_no_delay = req->rq_no_resend = 1;
2858
2859         cfs_spin_lock_init(&req->rq_lock);
2860         CFS_INIT_LIST_HEAD(&req->rq_list);
2861         CFS_INIT_LIST_HEAD(&req->rq_replay_list);
2862         CFS_INIT_LIST_HEAD(&req->rq_set_chain);
2863         CFS_INIT_LIST_HEAD(&req->rq_history_list);
2864         CFS_INIT_LIST_HEAD(&req->rq_exp_list);
2865         cfs_waitq_init(&req->rq_reply_waitq);
2866         cfs_waitq_init(&req->rq_set_waitq);
2867         cfs_atomic_set(&req->rq_refcount, 1);
2868
2869         CLASSERT (sizeof(*args) <= sizeof(req->rq_async_args));
2870         args = ptlrpc_req_async_args(req);
2871         args->magic  = PTLRPC_WORK_MAGIC;
2872         args->cb     = cb;
2873         args->cbdata = cbdata;
2874
2875         RETURN(req);
2876 }
2877 EXPORT_SYMBOL(ptlrpcd_alloc_work);
2878
2879 void ptlrpcd_destroy_work(void *handler)
2880 {
2881         struct ptlrpc_request *req = handler;
2882
2883         if (req)
2884                 ptlrpc_req_finished(req);
2885 }
2886 EXPORT_SYMBOL(ptlrpcd_destroy_work);
2887
2888 int ptlrpcd_queue_work(void *handler)
2889 {
2890         struct ptlrpc_request *req = handler;
2891
2892         /*
2893          * Check if the req is already being queued.
2894          *
2895          * Here comes a trick: it lacks a way of checking if a req is being
2896          * processed reliably in ptlrpc. Here I have to use refcount of req
2897          * for this purpose. This is okay because the caller should use this
2898          * req as opaque data. - Jinshan
2899          */
2900         LASSERT(cfs_atomic_read(&req->rq_refcount) > 0);
2901         if (cfs_atomic_read(&req->rq_refcount) > 1)
2902                 return -EBUSY;
2903
2904         if (cfs_atomic_inc_return(&req->rq_refcount) > 2) { /* race */
2905                 cfs_atomic_dec(&req->rq_refcount);
2906                 return -EBUSY;
2907         }
2908
2909         /* re-initialize the req */
2910         req->rq_timeout        = obd_timeout;
2911         req->rq_sent           = cfs_time_current_sec();
2912         req->rq_deadline       = req->rq_sent + req->rq_timeout;
2913         req->rq_reply_deadline = req->rq_deadline;
2914         req->rq_phase          = RQ_PHASE_INTERPRET;
2915         req->rq_next_phase     = RQ_PHASE_COMPLETE;
2916         req->rq_xid            = ptlrpc_next_xid();
2917         req->rq_import_generation = req->rq_import->imp_generation;
2918
2919         ptlrpcd_add_req(req, PDL_POLICY_ROUND, -1);
2920         return 0;
2921 }
2922 EXPORT_SYMBOL(ptlrpcd_queue_work);