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