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