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