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