Whamcloud - gitweb
LU-6068 misc: update Intel copyright messages 2014
[fs/lustre-release.git] / lustre / ptlrpc / import.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ptlrpc/import.c
37  *
38  * Author: Mike Shaver <shaver@clusterfs.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_RPC
42
43 #include <obd_support.h>
44 #include <lustre_ha.h>
45 #include <lustre_net.h>
46 #include <lustre_import.h>
47 #include <lustre_export.h>
48 #include <obd.h>
49 #include <obd_cksum.h>
50 #include <obd_class.h>
51
52 #include "ptlrpc_internal.h"
53
54 struct ptlrpc_connect_async_args {
55          __u64 pcaa_peer_committed;
56         int pcaa_initial_connect;
57 };
58
59 /**
60  * Updates import \a imp current state to provided \a state value
61  * Helper function. Must be called under imp_lock.
62  */
63 static void __import_set_state(struct obd_import *imp,
64                                enum lustre_imp_state state)
65 {
66         switch (state) {
67         case LUSTRE_IMP_CLOSED:
68         case LUSTRE_IMP_NEW:
69         case LUSTRE_IMP_DISCON:
70         case LUSTRE_IMP_CONNECTING:
71                 break;
72         case LUSTRE_IMP_REPLAY_WAIT:
73                 imp->imp_replay_state = LUSTRE_IMP_REPLAY_LOCKS;
74                 break;
75         default:
76                 imp->imp_replay_state = LUSTRE_IMP_REPLAY;
77         }
78         imp->imp_state = state;
79         imp->imp_state_hist[imp->imp_state_hist_idx].ish_state = state;
80         imp->imp_state_hist[imp->imp_state_hist_idx].ish_time =
81                 cfs_time_current_sec();
82         imp->imp_state_hist_idx = (imp->imp_state_hist_idx + 1) %
83                 IMP_STATE_HIST_LEN;
84 }
85
86 /* A CLOSED import should remain so. */
87 #define IMPORT_SET_STATE_NOLOCK(imp, state)                                    \
88 do {                                                                           \
89         if (imp->imp_state != LUSTRE_IMP_CLOSED) {                             \
90                CDEBUG(D_HA, "%p %s: changing import state from %s to %s\n",    \
91                       imp, obd2cli_tgt(imp->imp_obd),                          \
92                       ptlrpc_import_state_name(imp->imp_state),                \
93                       ptlrpc_import_state_name(state));                        \
94                __import_set_state(imp, state);                                 \
95         }                                                                      \
96 } while(0)
97
98 #define IMPORT_SET_STATE(imp, state)                                    \
99 do {                                                                    \
100         spin_lock(&imp->imp_lock);                                      \
101         IMPORT_SET_STATE_NOLOCK(imp, state);                            \
102         spin_unlock(&imp->imp_lock);                                    \
103 } while(0)
104
105
106 static int ptlrpc_connect_interpret(const struct lu_env *env,
107                                     struct ptlrpc_request *request,
108                                     void * data, int rc);
109 int ptlrpc_import_recovery_state_machine(struct obd_import *imp);
110
111 /* Only this function is allowed to change the import state when it is
112  * CLOSED. I would rather refcount the import and free it after
113  * disconnection like we do with exports. To do that, the client_obd
114  * will need to save the peer info somewhere other than in the import,
115  * though. */
116 int ptlrpc_init_import(struct obd_import *imp)
117 {
118         spin_lock(&imp->imp_lock);
119
120         imp->imp_generation++;
121         imp->imp_state =  LUSTRE_IMP_NEW;
122
123         spin_unlock(&imp->imp_lock);
124
125         return 0;
126 }
127 EXPORT_SYMBOL(ptlrpc_init_import);
128
129 #define UUID_STR "_UUID"
130 void deuuidify(char *uuid, const char *prefix, char **uuid_start, int *uuid_len)
131 {
132         *uuid_start = !prefix || strncmp(uuid, prefix, strlen(prefix))
133                 ? uuid : uuid + strlen(prefix);
134
135         *uuid_len = strlen(*uuid_start);
136
137         if (*uuid_len < strlen(UUID_STR))
138                 return;
139
140         if (!strncmp(*uuid_start + *uuid_len - strlen(UUID_STR),
141                     UUID_STR, strlen(UUID_STR)))
142                 *uuid_len -= strlen(UUID_STR);
143 }
144 EXPORT_SYMBOL(deuuidify);
145
146 /**
147  * Returns true if import was FULL, false if import was already not
148  * connected.
149  * @imp - import to be disconnected
150  * @conn_cnt - connection count (epoch) of the request that timed out
151  *             and caused the disconnection.  In some cases, multiple
152  *             inflight requests can fail to a single target (e.g. OST
153  *             bulk requests) and if one has already caused a reconnection
154  *             (increasing the import->conn_cnt) the older failure should
155  *             not also cause a reconnection.  If zero it forces a reconnect.
156  */
157 int ptlrpc_set_import_discon(struct obd_import *imp, __u32 conn_cnt)
158 {
159         int rc = 0;
160
161         spin_lock(&imp->imp_lock);
162
163         if (imp->imp_state == LUSTRE_IMP_FULL &&
164             (conn_cnt == 0 || conn_cnt == imp->imp_conn_cnt)) {
165                 char *target_start;
166                 int   target_len;
167
168                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
169                           &target_start, &target_len);
170
171                 if (imp->imp_replayable) {
172                         LCONSOLE_WARN("%s: Connection to %.*s (at %s) was "
173                                "lost; in progress operations using this "
174                                "service will wait for recovery to complete\n",
175                                imp->imp_obd->obd_name, target_len, target_start,
176                                libcfs_nid2str(imp->imp_connection->c_peer.nid));
177                 } else {
178                         LCONSOLE_ERROR_MSG(0x166, "%s: Connection to "
179                                "%.*s (at %s) was lost; in progress "
180                                "operations using this service will fail\n",
181                                imp->imp_obd->obd_name,
182                                target_len, target_start,
183                                libcfs_nid2str(imp->imp_connection->c_peer.nid));
184                 }
185                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
186                 spin_unlock(&imp->imp_lock);
187
188                 if (obd_dump_on_timeout)
189                         libcfs_debug_dumplog();
190
191                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_DISCON);
192                 rc = 1;
193         } else {
194                 spin_unlock(&imp->imp_lock);
195                 CDEBUG(D_HA, "%s: import %p already %s (conn %u, was %u): %s\n",
196                        imp->imp_client->cli_name, imp,
197                        (imp->imp_state == LUSTRE_IMP_FULL &&
198                         imp->imp_conn_cnt > conn_cnt) ?
199                        "reconnected" : "not connected", imp->imp_conn_cnt,
200                        conn_cnt, ptlrpc_import_state_name(imp->imp_state));
201         }
202
203         return rc;
204 }
205
206 /* Must be called with imp_lock held! */
207 static void ptlrpc_deactivate_and_unlock_import(struct obd_import *imp)
208 {
209         ENTRY;
210         assert_spin_locked(&imp->imp_lock);
211
212         CDEBUG(D_HA, "setting import %s INVALID\n", obd2cli_tgt(imp->imp_obd));
213         imp->imp_invalid = 1;
214         imp->imp_generation++;
215         spin_unlock(&imp->imp_lock);
216
217         ptlrpc_abort_inflight(imp);
218         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INACTIVE);
219
220         EXIT;
221 }
222
223 /*
224  * This acts as a barrier; all existing requests are rejected, and
225  * no new requests will be accepted until the import is valid again.
226  */
227 void ptlrpc_deactivate_import(struct obd_import *imp)
228 {
229         spin_lock(&imp->imp_lock);
230         ptlrpc_deactivate_and_unlock_import(imp);
231 }
232 EXPORT_SYMBOL(ptlrpc_deactivate_import);
233
234 static unsigned int
235 ptlrpc_inflight_deadline(struct ptlrpc_request *req, time_t now)
236 {
237         long dl;
238
239         if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
240               (req->rq_phase == RQ_PHASE_BULK) ||
241               (req->rq_phase == RQ_PHASE_NEW)))
242                 return 0;
243
244         if (req->rq_timedout)
245                 return 0;
246
247         if (req->rq_phase == RQ_PHASE_NEW)
248                 dl = req->rq_sent;
249         else
250                 dl = req->rq_deadline;
251
252         if (dl <= now)
253                 return 0;
254
255         return dl - now;
256 }
257
258 static unsigned int ptlrpc_inflight_timeout(struct obd_import *imp)
259 {
260         time_t now = cfs_time_current_sec();
261         struct list_head *tmp, *n;
262         struct ptlrpc_request *req;
263         unsigned int timeout = 0;
264
265         spin_lock(&imp->imp_lock);
266         list_for_each_safe(tmp, n, &imp->imp_sending_list) {
267                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
268                 timeout = max(ptlrpc_inflight_deadline(req, now), timeout);
269         }
270         spin_unlock(&imp->imp_lock);
271         return timeout;
272 }
273
274 /**
275  * This function will invalidate the import, if necessary, then block
276  * for all the RPC completions, and finally notify the obd to
277  * invalidate its state (ie cancel locks, clear pending requests,
278  * etc).
279  */
280 void ptlrpc_invalidate_import(struct obd_import *imp)
281 {
282         struct list_head *tmp, *n;
283         struct ptlrpc_request *req;
284         struct l_wait_info lwi;
285         unsigned int timeout;
286         int rc;
287
288         atomic_inc(&imp->imp_inval_count);
289
290         if (!imp->imp_invalid || imp->imp_obd->obd_no_recov)
291                 ptlrpc_deactivate_import(imp);
292
293         CFS_FAIL_TIMEOUT(OBD_FAIL_MGS_CONNECT_NET, 3 * cfs_fail_val / 2);
294         LASSERT(imp->imp_invalid);
295
296         /* Wait forever until inflight == 0. We really can't do it another
297          * way because in some cases we need to wait for very long reply
298          * unlink. We can't do anything before that because there is really
299          * no guarantee that some rdma transfer is not in progress right now. */
300         do {
301                 /* Calculate max timeout for waiting on rpcs to error
302                  * out. Use obd_timeout if calculated value is smaller
303                  * than it. */
304                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
305                         timeout = ptlrpc_inflight_timeout(imp);
306                         timeout += timeout / 3;
307
308                         if (timeout == 0)
309                                 timeout = obd_timeout;
310                 } else {
311                         /* decrease the interval to increase race condition */
312                         timeout = 1;
313                 }
314
315                 CDEBUG(D_RPCTRACE,"Sleeping %d sec for inflight to error out\n",
316                        timeout);
317
318                 /* Wait for all requests to error out and call completion
319                  * callbacks. Cap it at obd_timeout -- these should all
320                  * have been locally cancelled by ptlrpc_abort_inflight. */
321                 lwi = LWI_TIMEOUT_INTERVAL(
322                         cfs_timeout_cap(cfs_time_seconds(timeout)),
323                         (timeout > 1)?cfs_time_seconds(1):cfs_time_seconds(1)/2,
324                         NULL, NULL);
325                 rc = l_wait_event(imp->imp_recovery_waitq,
326                                   (atomic_read(&imp->imp_inflight) == 0),
327                                   &lwi);
328                 if (rc) {
329                         const char *cli_tgt = obd2cli_tgt(imp->imp_obd);
330
331                         CERROR("%s: rc = %d waiting for callback (%d != 0)\n",
332                                cli_tgt, rc, atomic_read(&imp->imp_inflight));
333
334                         spin_lock(&imp->imp_lock);
335                         if (atomic_read(&imp->imp_inflight) == 0) {
336                                 int count = atomic_read(&imp->imp_unregistering);
337
338                                 /* We know that "unregistering" rpcs only can
339                                  * survive in sending or delaying lists (they
340                                  * maybe waiting for long reply unlink in
341                                  * sluggish nets). Let's check this. If there
342                                  * is no inflight and unregistering != 0, this
343                                  * is bug. */
344                                 LASSERTF(count == 0, "Some RPCs are still "
345                                          "unregistering: %d\n", count);
346
347                                 /* Let's save one loop as soon as inflight have
348                                  * dropped to zero. No new inflights possible at
349                                  * this point. */
350                                 rc = 0;
351                         } else {
352                                 list_for_each_safe(tmp, n,
353                                                    &imp->imp_sending_list) {
354                                         req = list_entry(tmp,
355                                                          struct ptlrpc_request,
356                                                          rq_list);
357                                         DEBUG_REQ(D_ERROR, req,
358                                                   "still on sending list");
359                                 }
360                                 list_for_each_safe(tmp, n,
361                                                    &imp->imp_delayed_list) {
362                                         req = list_entry(tmp,
363                                                          struct ptlrpc_request,
364                                                          rq_list);
365                                         DEBUG_REQ(D_ERROR, req,
366                                                   "still on delayed list");
367                                 }
368
369                                 CERROR("%s: RPCs in \"%s\" phase found (%d). "
370                                        "Network is sluggish? Waiting them "
371                                        "to error out.\n", cli_tgt,
372                                        ptlrpc_phase2str(RQ_PHASE_UNREGISTERING),
373                                        atomic_read(&imp->imp_unregistering));
374                         }
375                         spin_unlock(&imp->imp_lock);
376                 }
377         } while (rc != 0);
378
379         /*
380          * Let's additionally check that no new rpcs added to import in
381          * "invalidate" state.
382          */
383         LASSERT(atomic_read(&imp->imp_inflight) == 0);
384         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INVALIDATE);
385         sptlrpc_import_flush_all_ctx(imp);
386
387         atomic_dec(&imp->imp_inval_count);
388         wake_up_all(&imp->imp_recovery_waitq);
389 }
390 EXPORT_SYMBOL(ptlrpc_invalidate_import);
391
392 /* unset imp_invalid */
393 void ptlrpc_activate_import(struct obd_import *imp)
394 {
395         struct obd_device *obd = imp->imp_obd;
396
397         spin_lock(&imp->imp_lock);
398         if (imp->imp_deactive != 0) {
399                 spin_unlock(&imp->imp_lock);
400                 return;
401         }
402
403         imp->imp_invalid = 0;
404         spin_unlock(&imp->imp_lock);
405         obd_import_event(obd, imp, IMP_EVENT_ACTIVE);
406 }
407 EXPORT_SYMBOL(ptlrpc_activate_import);
408
409 static void ptlrpc_pinger_force(struct obd_import *imp)
410 {
411         CDEBUG(D_HA, "%s: waking up pinger s:%s\n", obd2cli_tgt(imp->imp_obd),
412                ptlrpc_import_state_name(imp->imp_state));
413
414         spin_lock(&imp->imp_lock);
415         imp->imp_force_verify = 1;
416         spin_unlock(&imp->imp_lock);
417
418         if (imp->imp_state != LUSTRE_IMP_CONNECTING)
419                 ptlrpc_pinger_wake_up();
420 }
421
422 void ptlrpc_fail_import(struct obd_import *imp, __u32 conn_cnt)
423 {
424         ENTRY;
425
426         LASSERT(!imp->imp_dlm_fake);
427
428         if (ptlrpc_set_import_discon(imp, conn_cnt)) {
429                 if (!imp->imp_replayable) {
430                         CDEBUG(D_HA, "import %s@%s for %s not replayable, "
431                                "auto-deactivating\n",
432                                obd2cli_tgt(imp->imp_obd),
433                                imp->imp_connection->c_remote_uuid.uuid,
434                                imp->imp_obd->obd_name);
435                         ptlrpc_deactivate_import(imp);
436                 }
437
438                 ptlrpc_pinger_force(imp);
439         }
440         EXIT;
441 }
442 EXPORT_SYMBOL(ptlrpc_fail_import);
443
444 int ptlrpc_reconnect_import(struct obd_import *imp)
445 {
446 #ifdef ENABLE_PINGER
447         struct l_wait_info lwi;
448         int secs = cfs_time_seconds(obd_timeout);
449         int rc;
450
451         ptlrpc_pinger_force(imp);
452
453         CDEBUG(D_HA, "%s: recovery started, waiting %u seconds\n",
454                obd2cli_tgt(imp->imp_obd), secs);
455
456         lwi = LWI_TIMEOUT(secs, NULL, NULL);
457         rc = l_wait_event(imp->imp_recovery_waitq,
458                           !ptlrpc_import_in_recovery(imp), &lwi);
459         CDEBUG(D_HA, "%s: recovery finished s:%s\n", obd2cli_tgt(imp->imp_obd),
460                ptlrpc_import_state_name(imp->imp_state));
461         return rc;
462 #else
463         ptlrpc_set_import_discon(imp, 0);
464         /* Force a new connect attempt */
465         ptlrpc_invalidate_import(imp);
466         /* Do a fresh connect next time by zeroing the handle */
467         ptlrpc_disconnect_import(imp, 1);
468         /* Wait for all invalidate calls to finish */
469         if (atomic_read(&imp->imp_inval_count) > 0) {
470                 struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
471                 int rc;
472
473                 rc = l_wait_event(imp->imp_recovery_waitq,
474                                   (atomic_read(&imp->imp_inval_count) == 0),
475                                   &lwi);
476                 if (rc)
477                         CERROR("Interrupted, inval=%d\n",
478                                atomic_read(&imp->imp_inval_count));
479         }
480
481         /* Allow reconnect attempts */
482         imp->imp_obd->obd_no_recov = 0;
483         /* Remove 'invalid' flag */
484         ptlrpc_activate_import(imp);
485         /* Attempt a new connect */
486         ptlrpc_recover_import(imp, NULL, 0);
487         return 0;
488 #endif
489 }
490 EXPORT_SYMBOL(ptlrpc_reconnect_import);
491
492 /**
493  * Connection on import \a imp is changed to another one (if more than one is
494  * present). We typically chose connection that we have not tried to connect to
495  * the longest
496  */
497 static int import_select_connection(struct obd_import *imp)
498 {
499         struct obd_import_conn *imp_conn = NULL, *conn;
500         struct obd_export *dlmexp;
501         char *target_start;
502         int target_len, tried_all = 1;
503         ENTRY;
504
505         spin_lock(&imp->imp_lock);
506
507         if (list_empty(&imp->imp_conn_list)) {
508                 CERROR("%s: no connections available\n",
509                        imp->imp_obd->obd_name);
510                 spin_unlock(&imp->imp_lock);
511                 RETURN(-EINVAL);
512         }
513
514         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
515                 CDEBUG(D_HA, "%s: connect to NID %s last attempt "LPU64"\n",
516                        imp->imp_obd->obd_name,
517                        libcfs_nid2str(conn->oic_conn->c_peer.nid),
518                        conn->oic_last_attempt);
519
520                 /* If we have not tried this connection since
521                    the last successful attempt, go with this one */
522                 if ((conn->oic_last_attempt == 0) ||
523                     cfs_time_beforeq_64(conn->oic_last_attempt,
524                                        imp->imp_last_success_conn)) {
525                         imp_conn = conn;
526                         tried_all = 0;
527                         break;
528                 }
529
530                 /* If all of the connections have already been tried
531                    since the last successful connection; just choose the
532                    least recently used */
533                 if (!imp_conn)
534                         imp_conn = conn;
535                 else if (cfs_time_before_64(conn->oic_last_attempt,
536                                             imp_conn->oic_last_attempt))
537                         imp_conn = conn;
538         }
539
540         /* if not found, simply choose the current one */
541         if (!imp_conn || imp->imp_force_reconnect) {
542                 LASSERT(imp->imp_conn_current);
543                 imp_conn = imp->imp_conn_current;
544                 tried_all = 0;
545         }
546         LASSERT(imp_conn->oic_conn);
547
548         /* If we've tried everything, and we're back to the beginning of the
549            list, increase our timeout and try again. It will be reset when
550            we do finally connect. (FIXME: really we should wait for all network
551            state associated with the last connection attempt to drain before
552            trying to reconnect on it.) */
553         if (tried_all && (imp->imp_conn_list.next == &imp_conn->oic_item)) {
554                 struct adaptive_timeout *at = &imp->imp_at.iat_net_latency;
555                 if (at_get(at) < CONNECTION_SWITCH_MAX) {
556                         at_measured(at, at_get(at) + CONNECTION_SWITCH_INC);
557                         if (at_get(at) > CONNECTION_SWITCH_MAX)
558                                 at_reset(at, CONNECTION_SWITCH_MAX);
559                 }
560                 LASSERT(imp_conn->oic_last_attempt);
561                 CDEBUG(D_HA, "%s: tried all connections, increasing latency "
562                         "to %ds\n", imp->imp_obd->obd_name, at_get(at));
563         }
564
565         imp_conn->oic_last_attempt = cfs_time_current_64();
566
567         /* switch connection, don't mind if it's same as the current one */
568         if (imp->imp_connection)
569                 ptlrpc_connection_put(imp->imp_connection);
570         imp->imp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
571
572         dlmexp =  class_conn2export(&imp->imp_dlm_handle);
573         LASSERT(dlmexp != NULL);
574         if (dlmexp->exp_connection)
575                 ptlrpc_connection_put(dlmexp->exp_connection);
576         dlmexp->exp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
577         class_export_put(dlmexp);
578
579         if (imp->imp_conn_current != imp_conn) {
580                 if (imp->imp_conn_current) {
581                         deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
582                                   &target_start, &target_len);
583
584                         CDEBUG(D_HA, "%s: Connection changing to"
585                                " %.*s (at %s)\n",
586                                imp->imp_obd->obd_name,
587                                target_len, target_start,
588                                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
589                 }
590
591                 imp->imp_conn_current = imp_conn;
592         }
593
594         CDEBUG(D_HA, "%s: import %p using connection %s/%s\n",
595                imp->imp_obd->obd_name, imp, imp_conn->oic_uuid.uuid,
596                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
597
598         spin_unlock(&imp->imp_lock);
599
600         RETURN(0);
601 }
602
603 /*
604  * must be called under imp_lock
605  */
606 static int ptlrpc_first_transno(struct obd_import *imp, __u64 *transno)
607 {
608         struct ptlrpc_request   *req;
609         struct list_head        *tmp;
610
611         /* The requests in committed_list always have smaller transnos than
612          * the requests in replay_list */
613         if (!list_empty(&imp->imp_committed_list)) {
614                 tmp = imp->imp_committed_list.next;
615                 req = list_entry(tmp, struct ptlrpc_request, rq_replay_list);
616                 *transno = req->rq_transno;
617                 if (req->rq_transno == 0) {
618                         DEBUG_REQ(D_ERROR, req, "zero transno in committed_list");
619                         LBUG();
620                 }
621                 return 1;
622         }
623         if (!list_empty(&imp->imp_replay_list)) {
624                 tmp = imp->imp_replay_list.next;
625                 req = list_entry(tmp, struct ptlrpc_request, rq_replay_list);
626                 *transno = req->rq_transno;
627                 if (req->rq_transno == 0) {
628                         DEBUG_REQ(D_ERROR, req, "zero transno in replay_list");
629                         LBUG();
630                 }
631                 return 1;
632         }
633         return 0;
634 }
635
636 /**
637  * Attempt to (re)connect import \a imp. This includes all preparations,
638  * initializing CONNECT RPC request and passing it to ptlrpcd for
639  * actual sending.
640  * Returns 0 on success or error code.
641  */
642 int ptlrpc_connect_import(struct obd_import *imp)
643 {
644         struct obd_device *obd = imp->imp_obd;
645         int initial_connect = 0;
646         int set_transno = 0;
647         __u64 committed_before_reconnect = 0;
648         struct ptlrpc_request *request;
649         char *bufs[] = { NULL,
650                          obd2cli_tgt(imp->imp_obd),
651                          obd->obd_uuid.uuid,
652                          (char *)&imp->imp_dlm_handle,
653                          (char *)&imp->imp_connect_data };
654         struct ptlrpc_connect_async_args *aa;
655         int rc;
656         ENTRY;
657
658         spin_lock(&imp->imp_lock);
659         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
660                 spin_unlock(&imp->imp_lock);
661                 CERROR("can't connect to a closed import\n");
662                 RETURN(-EINVAL);
663         } else if (imp->imp_state == LUSTRE_IMP_FULL) {
664                 spin_unlock(&imp->imp_lock);
665                 CERROR("already connected\n");
666                 RETURN(0);
667         } else if (imp->imp_state == LUSTRE_IMP_CONNECTING) {
668                 spin_unlock(&imp->imp_lock);
669                 CERROR("already connecting\n");
670                 RETURN(-EALREADY);
671         }
672
673         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CONNECTING);
674
675         imp->imp_conn_cnt++;
676         imp->imp_resend_replay = 0;
677
678         if (!lustre_handle_is_used(&imp->imp_remote_handle))
679                 initial_connect = 1;
680         else
681                 committed_before_reconnect = imp->imp_peer_committed_transno;
682
683         set_transno = ptlrpc_first_transno(imp,
684                                            &imp->imp_connect_data.ocd_transno);
685         spin_unlock(&imp->imp_lock);
686
687         rc = import_select_connection(imp);
688         if (rc)
689                 GOTO(out, rc);
690
691         rc = sptlrpc_import_sec_adapt(imp, NULL, 0);
692         if (rc)
693                 GOTO(out, rc);
694
695         /* Reset connect flags to the originally requested flags, in case
696          * the server is updated on-the-fly we will get the new features. */
697         imp->imp_connect_data.ocd_connect_flags = imp->imp_connect_flags_orig;
698         /* Reset ocd_version each time so the server knows the exact versions */
699         imp->imp_connect_data.ocd_version = LUSTRE_VERSION_CODE;
700         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
701         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
702
703         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
704                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
705         if (rc)
706                 GOTO(out, rc);
707
708         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
709         if (request == NULL)
710                 GOTO(out, rc = -ENOMEM);
711
712         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
713                                       imp->imp_connect_op, bufs, NULL);
714         if (rc) {
715                 ptlrpc_request_free(request);
716                 GOTO(out, rc);
717         }
718
719         /* Report the rpc service time to the server so that it knows how long
720          * to wait for clients to join recovery */
721         lustre_msg_set_service_time(request->rq_reqmsg,
722                                     at_timeout2est(request->rq_timeout));
723
724         /* The amount of time we give the server to process the connect req.
725          * import_select_connection will increase the net latency on
726          * repeated reconnect attempts to cover slow networks.
727          * We override/ignore the server rpc completion estimate here,
728          * which may be large if this is a reconnect attempt */
729         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
730         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
731
732         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
733
734         request->rq_no_resend = request->rq_no_delay = 1;
735         request->rq_send_state = LUSTRE_IMP_CONNECTING;
736         /* Allow a slightly larger reply for future growth compatibility */
737         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
738                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
739         ptlrpc_request_set_replen(request);
740         request->rq_interpret_reply = ptlrpc_connect_interpret;
741
742         CLASSERT(sizeof (*aa) <= sizeof (request->rq_async_args));
743         aa = ptlrpc_req_async_args(request);
744         memset(aa, 0, sizeof *aa);
745
746         aa->pcaa_peer_committed = committed_before_reconnect;
747         aa->pcaa_initial_connect = initial_connect;
748
749         if (aa->pcaa_initial_connect) {
750                 spin_lock(&imp->imp_lock);
751                 imp->imp_replayable = 1;
752                 spin_unlock(&imp->imp_lock);
753                 lustre_msg_add_op_flags(request->rq_reqmsg,
754                                         MSG_CONNECT_INITIAL);
755         }
756
757         if (set_transno)
758                 lustre_msg_add_op_flags(request->rq_reqmsg,
759                                         MSG_CONNECT_TRANSNO);
760
761         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %d)",
762                   request->rq_timeout);
763         ptlrpcd_add_req(request, PDL_POLICY_ROUND, -1);
764         rc = 0;
765 out:
766         if (rc != 0) {
767                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
768         }
769
770         RETURN(rc);
771 }
772 EXPORT_SYMBOL(ptlrpc_connect_import);
773
774 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
775 {
776         int force_verify;
777
778         spin_lock(&imp->imp_lock);
779         force_verify = imp->imp_force_verify != 0;
780         spin_unlock(&imp->imp_lock);
781
782         if (force_verify)
783                 ptlrpc_pinger_wake_up();
784 }
785
786 static int ptlrpc_busy_reconnect(int rc)
787 {
788         return (rc == -EBUSY) || (rc == -EAGAIN);
789 }
790
791 static int ptlrpc_connect_set_flags(struct obd_import *imp,
792                                      struct obd_connect_data *ocd,
793                                      __u64 old_connect_flags,
794                                      struct obd_export *exp, int init_connect)
795 {
796         static bool warned;
797         struct client_obd *cli = &imp->imp_obd->u.cli;
798
799         if ((imp->imp_connect_flags_orig & OBD_CONNECT_IBITS) &&
800             !(ocd->ocd_connect_flags & OBD_CONNECT_IBITS)) {
801                 LCONSOLE_WARN("%s: MDS %s does not support ibits "
802                               "lock, either very old or invalid: "
803                               "requested "LPX64", replied "LPX64"\n",
804                               imp->imp_obd->obd_name,
805                               imp->imp_connection->c_remote_uuid.uuid,
806                               imp->imp_connect_flags_orig,
807                               ocd->ocd_connect_flags);
808                 return -EPROTO;
809         }
810
811         spin_lock(&imp->imp_lock);
812         list_del(&imp->imp_conn_current->oic_item);
813         list_add(&imp->imp_conn_current->oic_item,
814                  &imp->imp_conn_list);
815         imp->imp_last_success_conn =
816                 imp->imp_conn_current->oic_last_attempt;
817
818         spin_unlock(&imp->imp_lock);
819
820
821         if (!warned && (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
822             (ocd->ocd_version > LUSTRE_VERSION_CODE +
823                                 LUSTRE_VERSION_OFFSET_WARN ||
824              ocd->ocd_version < LUSTRE_VERSION_CODE -
825                                 LUSTRE_VERSION_OFFSET_WARN)) {
826                 /* Sigh, some compilers do not like #ifdef in the middle
827                    of macro arguments */
828                 const char *older = "older than client. "
829                                     "Consider upgrading server";
830                 const char *newer = "newer than client. "
831                                     "Consider recompiling application";
832
833                 LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
834                               "is much %s (%s)\n",
835                               obd2cli_tgt(imp->imp_obd),
836                               OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
837                               OBD_OCD_VERSION_MINOR(ocd->ocd_version),
838                               OBD_OCD_VERSION_PATCH(ocd->ocd_version),
839                               OBD_OCD_VERSION_FIX(ocd->ocd_version),
840                               ocd->ocd_version > LUSTRE_VERSION_CODE ?
841                               newer : older, LUSTRE_VERSION_STRING);
842                 warned = true;
843         }
844
845 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
846         /* Check if server has LU-1252 fix applied to not always swab
847          * the IR MNE entries. Do this only once per connection.  This
848          * fixup is version-limited, because we don't want to carry the
849          * OBD_CONNECT_MNE_SWAB flag around forever, just so long as we
850          * need interop with unpatched 2.2 servers.  For newer servers,
851          * the client will do MNE swabbing only as needed.  LU-1644 */
852         if (unlikely((ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
853                      !(ocd->ocd_connect_flags & OBD_CONNECT_MNE_SWAB) &&
854                      OBD_OCD_VERSION_MAJOR(ocd->ocd_version) == 2 &&
855                      OBD_OCD_VERSION_MINOR(ocd->ocd_version) == 2 &&
856                      OBD_OCD_VERSION_PATCH(ocd->ocd_version) < 55 &&
857                      strcmp(imp->imp_obd->obd_type->typ_name,
858                             LUSTRE_MGC_NAME) == 0))
859                 imp->imp_need_mne_swab = 1;
860         else /* clear if server was upgraded since last connect */
861                 imp->imp_need_mne_swab = 0;
862 #endif
863
864         if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
865                 /* We sent to the server ocd_cksum_types with bits set
866                  * for algorithms we understand. The server masked off
867                  * the checksum types it doesn't support */
868                 if ((ocd->ocd_cksum_types &
869                      cksum_types_supported_client()) == 0) {
870                         LCONSOLE_WARN("The negotiation of the checksum "
871                                       "alogrithm to use with server %s "
872                                       "failed (%x/%x), disabling "
873                                       "checksums\n",
874                                       obd2cli_tgt(imp->imp_obd),
875                                       ocd->ocd_cksum_types,
876                                       cksum_types_supported_client());
877                         cli->cl_checksum = 0;
878                         cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
879                 } else {
880                         cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
881                 }
882         } else {
883                 /* The server does not support OBD_CONNECT_CKSUM.
884                  * Enforce ADLER for backward compatibility*/
885                 cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
886         }
887         cli->cl_cksum_type = cksum_type_select(cli->cl_supp_cksum_types);
888
889         if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE)
890                 cli->cl_max_pages_per_rpc =
891                         min(ocd->ocd_brw_size >> PAGE_CACHE_SHIFT,
892                             cli->cl_max_pages_per_rpc);
893         else if (imp->imp_connect_op == MDS_CONNECT ||
894                  imp->imp_connect_op == MGS_CONNECT)
895                 cli->cl_max_pages_per_rpc = 1;
896
897         LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
898                 (cli->cl_max_pages_per_rpc > 0));
899
900         client_adjust_max_dirty(cli);
901
902
903         /* Reset ns_connect_flags only for initial connect. It might be
904          * changed in while using FS and if we reset it in reconnect
905          * this leads to losing user settings done before such as
906          * disable lru_resize, etc. */
907         if (old_connect_flags != exp_connect_flags(exp) || init_connect) {
908                 CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
909                              "flags: "LPX64"\n", imp->imp_obd->obd_name,
910                              ocd->ocd_connect_flags);
911                 imp->imp_obd->obd_namespace->ns_connect_flags =
912                         ocd->ocd_connect_flags;
913                 imp->imp_obd->obd_namespace->ns_orig_connect_flags =
914                         ocd->ocd_connect_flags;
915         }
916
917         if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
918                 (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
919                 /* We need a per-message support flag, because
920                  * a. we don't know if the incoming connect reply
921                  *    supports AT or not (in reply_in_callback)
922                  *    until we unpack it.
923                  * b. failovered server means export and flags are gone
924                  *    (in ptlrpc_send_reply).
925                  *    Can only be set when we know AT is supported at
926                  *    both ends */
927                 imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
928         else
929                 imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
930
931         if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
932             (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
933                 imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
934         else
935                 imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
936
937         return 0;
938 }
939
940 /**
941  * interpret_reply callback for connect RPCs.
942  * Looks into returned status of connect operation and decides
943  * what to do with the import - i.e enter recovery, promote it to
944  * full state for normal operations of disconnect it due to an error.
945  */
946 static int ptlrpc_connect_interpret(const struct lu_env *env,
947                                     struct ptlrpc_request *request,
948                                     void *data, int rc)
949 {
950         struct ptlrpc_connect_async_args *aa = data;
951         struct obd_import *imp = request->rq_import;
952         struct lustre_handle old_hdl;
953         __u64 old_connect_flags;
954         int msg_flags;
955         struct obd_connect_data *ocd;
956         struct obd_export *exp;
957         int ret;
958         ENTRY;
959
960         spin_lock(&imp->imp_lock);
961         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
962                 imp->imp_connect_tried = 1;
963                 spin_unlock(&imp->imp_lock);
964                 RETURN(0);
965         }
966
967         if (rc) {
968                 /* if this reconnect to busy export - not need select new target
969                  * for connecting*/
970                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
971                 spin_unlock(&imp->imp_lock);
972                 ptlrpc_maybe_ping_import_soon(imp);
973                 GOTO(out, rc);
974         }
975         spin_unlock(&imp->imp_lock);
976
977         LASSERT(imp->imp_conn_current);
978
979         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
980
981         ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
982                                    RCL_SERVER);
983         /* server replied obd_connect_data is always bigger */
984         ocd = req_capsule_server_sized_get(&request->rq_pill,
985                                            &RMF_CONNECT_DATA, ret);
986
987         if (ocd == NULL) {
988                 CERROR("%s: no connect data from server\n",
989                        imp->imp_obd->obd_name);
990                 rc = -EPROTO;
991                 GOTO(out, rc);
992         }
993
994         spin_lock(&imp->imp_lock);
995
996         /* All imports are pingable */
997         imp->imp_pingable = 1;
998         imp->imp_force_reconnect = 0;
999         imp->imp_force_verify = 0;
1000
1001         imp->imp_connect_data = *ocd;
1002
1003         CDEBUG(D_HA, "%s: connect to target with instance %u\n",
1004                imp->imp_obd->obd_name, ocd->ocd_instance);
1005         exp = class_conn2export(&imp->imp_dlm_handle);
1006
1007         spin_unlock(&imp->imp_lock);
1008
1009         /* check that server granted subset of flags we asked for. */
1010         if ((ocd->ocd_connect_flags & imp->imp_connect_flags_orig) !=
1011             ocd->ocd_connect_flags) {
1012                 CERROR("%s: Server didn't granted asked subset of flags: "
1013                        "asked="LPX64" grranted="LPX64"\n",
1014                        imp->imp_obd->obd_name,imp->imp_connect_flags_orig,
1015                        ocd->ocd_connect_flags);
1016                 GOTO(out, rc = -EPROTO);
1017         }
1018
1019         if (!exp) {
1020                 /* This could happen if export is cleaned during the
1021                    connect attempt */
1022                 CERROR("%s: missing export after connect\n",
1023                        imp->imp_obd->obd_name);
1024                 GOTO(out, rc = -ENODEV);
1025         }
1026         old_connect_flags = exp_connect_flags(exp);
1027         exp->exp_connect_data = *ocd;
1028         imp->imp_obd->obd_self_export->exp_connect_data = *ocd;
1029
1030         /* The net statistics after (re-)connect is not valid anymore,
1031          * because may reflect other routing, etc. */
1032         at_init(&imp->imp_at.iat_net_latency, 0, 0);
1033         ptlrpc_at_adj_net_latency(request,
1034                         lustre_msg_get_service_time(request->rq_repmsg));
1035
1036         /* Import flags should be updated before waking import at FULL state */
1037         rc = ptlrpc_connect_set_flags(imp, ocd, old_connect_flags, exp,
1038                                  aa->pcaa_initial_connect);
1039         class_export_put(exp);
1040         if (rc != 0)
1041                 GOTO(out, rc);
1042
1043         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1044
1045         if (aa->pcaa_initial_connect) {
1046                 spin_lock(&imp->imp_lock);
1047                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
1048                         imp->imp_replayable = 1;
1049                         spin_unlock(&imp->imp_lock);
1050                         CDEBUG(D_HA, "connected to replayable target: %s\n",
1051                                obd2cli_tgt(imp->imp_obd));
1052                 } else {
1053                         imp->imp_replayable = 0;
1054                         spin_unlock(&imp->imp_lock);
1055                 }
1056
1057                 /* if applies, adjust the imp->imp_msg_magic here
1058                  * according to reply flags */
1059
1060                 imp->imp_remote_handle =
1061                                 *lustre_msg_get_handle(request->rq_repmsg);
1062
1063                 /* Initial connects are allowed for clients with non-random
1064                  * uuids when servers are in recovery.  Simply signal the
1065                  * servers replay is complete and wait in REPLAY_WAIT. */
1066                 if (msg_flags & MSG_CONNECT_RECOVERING) {
1067                         CDEBUG(D_HA, "connect to %s during recovery\n",
1068                                obd2cli_tgt(imp->imp_obd));
1069                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1070                 } else {
1071                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1072                         ptlrpc_activate_import(imp);
1073                 }
1074
1075                 GOTO(finish, rc = 0);
1076         }
1077
1078         /* Determine what recovery state to move the import to. */
1079         if (MSG_CONNECT_RECONNECT & msg_flags) {
1080                 memset(&old_hdl, 0, sizeof(old_hdl));
1081                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
1082                             sizeof (old_hdl))) {
1083                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
1084                                       "bad handle "LPX64"\n",
1085                                       obd2cli_tgt(imp->imp_obd),
1086                                       imp->imp_connection->c_remote_uuid.uuid,
1087                                       imp->imp_dlm_handle.cookie);
1088                         GOTO(out, rc = -ENOTCONN);
1089                 }
1090
1091                 if (memcmp(&imp->imp_remote_handle,
1092                            lustre_msg_get_handle(request->rq_repmsg),
1093                            sizeof(imp->imp_remote_handle))) {
1094                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
1095                                 D_HA : D_WARNING;
1096
1097                         /* Bug 16611/14775: if server handle have changed,
1098                          * that means some sort of disconnection happened.
1099                          * If the server is not in recovery, that also means it
1100                          * already erased all of our state because of previous
1101                          * eviction. If it is in recovery - we are safe to
1102                          * participate since we can reestablish all of our state
1103                          * with server again */
1104                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
1105                                 CDEBUG(level,"%s@%s changed server handle from "
1106                                        LPX64" to "LPX64
1107                                        " but is still in recovery\n",
1108                                        obd2cli_tgt(imp->imp_obd),
1109                                        imp->imp_connection->c_remote_uuid.uuid,
1110                                        imp->imp_remote_handle.cookie,
1111                                        lustre_msg_get_handle(
1112                                        request->rq_repmsg)->cookie);
1113                         } else {
1114                                 LCONSOLE_WARN("Evicted from %s (at %s) "
1115                                               "after server handle changed from "
1116                                               LPX64" to "LPX64"\n",
1117                                               obd2cli_tgt(imp->imp_obd),
1118                                               imp->imp_connection-> \
1119                                               c_remote_uuid.uuid,
1120                                               imp->imp_remote_handle.cookie,
1121                                               lustre_msg_get_handle(
1122                                               request->rq_repmsg)->cookie);
1123                         }
1124
1125
1126                         imp->imp_remote_handle =
1127                                      *lustre_msg_get_handle(request->rq_repmsg);
1128
1129                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
1130                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1131                                 GOTO(finish, rc = 0);
1132                         }
1133
1134                 } else {
1135                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
1136                                obd2cli_tgt(imp->imp_obd),
1137                                imp->imp_connection->c_remote_uuid.uuid);
1138                 }
1139
1140                 if (imp->imp_invalid) {
1141                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
1142                                "marking evicted\n", imp->imp_obd->obd_name);
1143                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1144                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
1145                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
1146                                imp->imp_obd->obd_name,
1147                                obd2cli_tgt(imp->imp_obd));
1148
1149                         spin_lock(&imp->imp_lock);
1150                         imp->imp_resend_replay = 1;
1151                         spin_unlock(&imp->imp_lock);
1152
1153                         IMPORT_SET_STATE(imp, imp->imp_replay_state);
1154                 } else {
1155                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1156                 }
1157         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
1158                 LASSERT(imp->imp_replayable);
1159                 imp->imp_remote_handle =
1160                                 *lustre_msg_get_handle(request->rq_repmsg);
1161                 imp->imp_last_replay_transno = 0;
1162                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
1163         } else {
1164                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
1165                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
1166                 imp->imp_remote_handle =
1167                                 *lustre_msg_get_handle(request->rq_repmsg);
1168                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1169         }
1170
1171         /* Sanity checks for a reconnected import. */
1172         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
1173                 CERROR("imp_replayable flag does not match server "
1174                        "after reconnect. We should LBUG right here.\n");
1175         }
1176
1177         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
1178             lustre_msg_get_last_committed(request->rq_repmsg) <
1179             aa->pcaa_peer_committed) {
1180                 CERROR("%s went back in time (transno "LPD64
1181                        " was previously committed, server now claims "LPD64
1182                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
1183                        "id=9646\n",
1184                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
1185                        lustre_msg_get_last_committed(request->rq_repmsg));
1186         }
1187
1188 finish:
1189         rc = ptlrpc_import_recovery_state_machine(imp);
1190         if (rc == -ENOTCONN) {
1191                 CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
1192                        "invalidating and reconnecting\n",
1193                        obd2cli_tgt(imp->imp_obd),
1194                        imp->imp_connection->c_remote_uuid.uuid);
1195                 ptlrpc_connect_import(imp);
1196                 imp->imp_connect_tried = 1;
1197                 RETURN(0);
1198         }
1199
1200 out:
1201         imp->imp_connect_tried = 1;
1202
1203         if (rc != 0) {
1204                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1205                 if (rc == -EACCES) {
1206                         /*
1207                          * Give up trying to reconnect
1208                          * EACCES means client has no permission for connection
1209                          */
1210                         imp->imp_obd->obd_no_recov = 1;
1211                         ptlrpc_deactivate_import(imp);
1212                 }
1213
1214                 if (rc == -EPROTO) {
1215                         struct obd_connect_data *ocd;
1216
1217                         /* reply message might not be ready */
1218                         if (request->rq_repmsg == NULL)
1219                                 RETURN(-EPROTO);
1220
1221                         ocd = req_capsule_server_get(&request->rq_pill,
1222                                                      &RMF_CONNECT_DATA);
1223                         if (ocd &&
1224                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1225                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1226                            /* Actually servers are only supposed to refuse
1227                               connection from liblustre clients, so we should
1228                               never see this from VFS context */
1229                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1230                                         "(%d.%d.%d.%d)"
1231                                         " refused connection from this client "
1232                                         "with an incompatible version (%s).  "
1233                                         "Client must be recompiled\n",
1234                                         obd2cli_tgt(imp->imp_obd),
1235                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1236                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1237                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1238                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1239                                         LUSTRE_VERSION_STRING);
1240                                 ptlrpc_deactivate_import(imp);
1241                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1242                         }
1243                         RETURN(-EPROTO);
1244                 }
1245
1246                 ptlrpc_maybe_ping_import_soon(imp);
1247
1248                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1249                        obd2cli_tgt(imp->imp_obd),
1250                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1251         }
1252
1253         wake_up_all(&imp->imp_recovery_waitq);
1254         RETURN(rc);
1255 }
1256
1257 /**
1258  * interpret callback for "completed replay" RPCs.
1259  * \see signal_completed_replay
1260  */
1261 static int completed_replay_interpret(const struct lu_env *env,
1262                                       struct ptlrpc_request *req,
1263                                       void * data, int rc)
1264 {
1265         ENTRY;
1266         atomic_dec(&req->rq_import->imp_replay_inflight);
1267         if (req->rq_status == 0 &&
1268             !req->rq_import->imp_vbr_failed) {
1269                 ptlrpc_import_recovery_state_machine(req->rq_import);
1270         } else {
1271                 if (req->rq_import->imp_vbr_failed) {
1272                         CDEBUG(D_WARNING,
1273                                "%s: version recovery fails, reconnecting\n",
1274                                req->rq_import->imp_obd->obd_name);
1275                 } else {
1276                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1277                                      "reconnecting\n",
1278                                req->rq_import->imp_obd->obd_name,
1279                                req->rq_status);
1280                 }
1281                 ptlrpc_connect_import(req->rq_import);
1282         }
1283
1284         RETURN(0);
1285 }
1286
1287 /**
1288  * Let server know that we have no requests to replay anymore.
1289  * Achieved by just sending a PING request
1290  */
1291 static int signal_completed_replay(struct obd_import *imp)
1292 {
1293         struct ptlrpc_request *req;
1294         ENTRY;
1295
1296         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1297                 RETURN(0);
1298
1299         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1300         atomic_inc(&imp->imp_replay_inflight);
1301
1302         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1303                                         OBD_PING);
1304         if (req == NULL) {
1305                 atomic_dec(&imp->imp_replay_inflight);
1306                 RETURN(-ENOMEM);
1307         }
1308
1309         ptlrpc_request_set_replen(req);
1310         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1311         lustre_msg_add_flags(req->rq_reqmsg,
1312                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1313         if (AT_OFF)
1314                 req->rq_timeout *= 3;
1315         req->rq_interpret_reply = completed_replay_interpret;
1316
1317         ptlrpcd_add_req(req, PDL_POLICY_ROUND, -1);
1318         RETURN(0);
1319 }
1320
1321 /**
1322  * In kernel code all import invalidation happens in its own
1323  * separate thread, so that whatever application happened to encounter
1324  * a problem could still be killed or otherwise continue
1325  */
1326 static int ptlrpc_invalidate_import_thread(void *data)
1327 {
1328         struct obd_import *imp = data;
1329
1330         ENTRY;
1331
1332         unshare_fs_struct();
1333
1334         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1335                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1336                imp->imp_connection->c_remote_uuid.uuid);
1337
1338         ptlrpc_invalidate_import(imp);
1339
1340         if (obd_dump_on_eviction) {
1341                 CERROR("dump the log upon eviction\n");
1342                 libcfs_debug_dumplog();
1343         }
1344
1345         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1346         ptlrpc_import_recovery_state_machine(imp);
1347
1348         class_import_put(imp);
1349         RETURN(0);
1350 }
1351
1352 /**
1353  * This is the state machine for client-side recovery on import.
1354  *
1355  * Typicaly we have two possibly paths. If we came to server and it is not
1356  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1357  * state and reconnect from scratch.
1358  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1359  * We go through our list of requests to replay and send them to server one by
1360  * one.
1361  * After sending all request from the list we change import state to
1362  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1363  * and also all the locks we don't yet have and wait for server to grant us.
1364  * After that we send a special "replay completed" request and change import
1365  * state to IMP_REPLAY_WAIT.
1366  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1367  * state and resend all requests from sending list.
1368  * After that we promote import to FULL state and send all delayed requests
1369  * and import is fully operational after that.
1370  *
1371  */
1372 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1373 {
1374         int rc = 0;
1375         int inflight;
1376         char *target_start;
1377         int target_len;
1378
1379         ENTRY;
1380         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1381                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1382                           &target_start, &target_len);
1383                 /* Don't care about MGC eviction */
1384                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1385                            LUSTRE_MGC_NAME) != 0) {
1386                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted "
1387                                            "by %.*s; in progress operations "
1388                                            "using this service will fail.\n",
1389                                            imp->imp_obd->obd_name, target_len,
1390                                            target_start);
1391                 }
1392                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1393                        obd2cli_tgt(imp->imp_obd),
1394                        imp->imp_connection->c_remote_uuid.uuid);
1395                 /* reset vbr_failed flag upon eviction */
1396                 spin_lock(&imp->imp_lock);
1397                 imp->imp_vbr_failed = 0;
1398                 spin_unlock(&imp->imp_lock);
1399
1400                 {
1401                 struct task_struct *task;
1402                 /* bug 17802:  XXX client_disconnect_export vs connect request
1403                  * race. if client will evicted at this time, we start
1404                  * invalidate thread without reference to import and import can
1405                  * be freed at same time. */
1406                 class_import_get(imp);
1407                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1408                                      "ll_imp_inval");
1409                 if (IS_ERR(task)) {
1410                         class_import_put(imp);
1411                         CERROR("error starting invalidate thread: %d\n", rc);
1412                         rc = PTR_ERR(task);
1413                 } else {
1414                         rc = 0;
1415                 }
1416                 RETURN(rc);
1417                 }
1418         }
1419
1420         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1421                 CDEBUG(D_HA, "replay requested by %s\n",
1422                        obd2cli_tgt(imp->imp_obd));
1423                 rc = ptlrpc_replay_next(imp, &inflight);
1424                 if (inflight == 0 &&
1425                     atomic_read(&imp->imp_replay_inflight) == 0) {
1426                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1427                         rc = ldlm_replay_locks(imp);
1428                         if (rc)
1429                                 GOTO(out, rc);
1430                 }
1431                 rc = 0;
1432         }
1433
1434         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1435                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1436                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1437                         rc = signal_completed_replay(imp);
1438                         if (rc)
1439                                 GOTO(out, rc);
1440                 }
1441         }
1442
1443         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1444                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1445                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1446                 }
1447         }
1448
1449         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1450                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1451                        obd2cli_tgt(imp->imp_obd),
1452                        imp->imp_connection->c_remote_uuid.uuid);
1453
1454                 rc = ptlrpc_resend(imp);
1455                 if (rc)
1456                         GOTO(out, rc);
1457                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1458                 ptlrpc_activate_import(imp);
1459
1460                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1461                           &target_start, &target_len);
1462                 LCONSOLE_INFO("%s: Connection restored to %.*s (at %s)\n",
1463                               imp->imp_obd->obd_name,
1464                               target_len, target_start,
1465                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1466         }
1467
1468         if (imp->imp_state == LUSTRE_IMP_FULL) {
1469                 wake_up_all(&imp->imp_recovery_waitq);
1470                 ptlrpc_wake_delayed(imp);
1471         }
1472
1473 out:
1474         RETURN(rc);
1475 }
1476
1477 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1478 {
1479         struct ptlrpc_request *req;
1480         int rq_opc, rc = 0;
1481         ENTRY;
1482
1483         if (imp->imp_obd->obd_force)
1484                 GOTO(set_state, rc);
1485
1486         switch (imp->imp_connect_op) {
1487         case OST_CONNECT:
1488                 rq_opc = OST_DISCONNECT;
1489                 break;
1490         case MDS_CONNECT:
1491                 rq_opc = MDS_DISCONNECT;
1492                 break;
1493         case MGS_CONNECT:
1494                 rq_opc = MGS_DISCONNECT;
1495                 break;
1496         default:
1497                 rc = -EINVAL;
1498                 CERROR("%s: don't know how to disconnect from %s "
1499                        "(connect_op %d): rc = %d\n",
1500                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1501                        imp->imp_connect_op, rc);
1502                 RETURN(rc);
1503         }
1504
1505         if (ptlrpc_import_in_recovery(imp)) {
1506                 struct l_wait_info lwi;
1507                 cfs_duration_t timeout;
1508
1509                 if (AT_OFF) {
1510                         if (imp->imp_server_timeout)
1511                                 timeout = cfs_time_seconds(obd_timeout / 2);
1512                         else
1513                                 timeout = cfs_time_seconds(obd_timeout);
1514                 } else {
1515                         int idx = import_at_get_index(imp,
1516                                 imp->imp_client->cli_request_portal);
1517                         timeout = cfs_time_seconds(
1518                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1519                 }
1520
1521                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1522                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1523                 rc = l_wait_event(imp->imp_recovery_waitq,
1524                                   !ptlrpc_import_in_recovery(imp), &lwi);
1525
1526         }
1527
1528         spin_lock(&imp->imp_lock);
1529         if (imp->imp_state != LUSTRE_IMP_FULL)
1530                 GOTO(out, rc);
1531         spin_unlock(&imp->imp_lock);
1532
1533         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1534                                         LUSTRE_OBD_VERSION, rq_opc);
1535         if (req) {
1536                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1537                  * it fails.  We can get through the above with a down server
1538                  * if the client doesn't know the server is gone yet. */
1539                 req->rq_no_resend = 1;
1540
1541                 /* We want client umounts to happen quickly, no matter the
1542                    server state... */
1543                 req->rq_timeout = min_t(int, req->rq_timeout,
1544                                         INITIAL_CONNECT_TIMEOUT);
1545
1546                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1547                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1548                 ptlrpc_request_set_replen(req);
1549                 rc = ptlrpc_queue_wait(req);
1550                 ptlrpc_req_finished(req);
1551         }
1552
1553 set_state:
1554         spin_lock(&imp->imp_lock);
1555 out:
1556         if (noclose)
1557                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1558         else
1559                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1560         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1561         spin_unlock(&imp->imp_lock);
1562
1563         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1564                 rc = 0;
1565         RETURN(rc);
1566 }
1567 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1568
1569 void ptlrpc_cleanup_imp(struct obd_import *imp)
1570 {
1571         ENTRY;
1572
1573         spin_lock(&imp->imp_lock);
1574         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1575         imp->imp_generation++;
1576         spin_unlock(&imp->imp_lock);
1577         ptlrpc_abort_inflight(imp);
1578
1579         EXIT;
1580 }
1581 EXPORT_SYMBOL(ptlrpc_cleanup_imp);
1582
1583 /* Adaptive Timeout utils */
1584 extern unsigned int at_min, at_max, at_history;
1585
1586 /* Update at_current with the specified value (bounded by at_min and at_max),
1587  * as well as the AT history "bins".
1588  *  - Bin into timeslices using AT_BINS bins.
1589  *  - This gives us a max of the last at_history seconds without the storage,
1590  *    but still smoothing out a return to normalcy from a slow response.
1591  *  - (E.g. remember the maximum latency in each minute of the last 4 minutes.)
1592  */
1593 int at_measured(struct adaptive_timeout *at, unsigned int val)
1594 {
1595         unsigned int old = at->at_current;
1596         time_t now = cfs_time_current_sec();
1597         time_t binlimit = max_t(time_t, at_history / AT_BINS, 1);
1598
1599         LASSERT(at);
1600         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1601                val, at, now - at->at_binstart, at->at_current,
1602                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1603
1604         if (val == 0)
1605                 /* 0's don't count, because we never want our timeout to
1606                    drop to 0, and because 0 could mean an error */
1607                 return 0;
1608
1609         spin_lock(&at->at_lock);
1610
1611         if (unlikely(at->at_binstart == 0)) {
1612                 /* Special case to remove default from history */
1613                 at->at_current = val;
1614                 at->at_worst_ever = val;
1615                 at->at_worst_time = now;
1616                 at->at_hist[0] = val;
1617                 at->at_binstart = now;
1618         } else if (now - at->at_binstart < binlimit ) {
1619                 /* in bin 0 */
1620                 at->at_hist[0] = max(val, at->at_hist[0]);
1621                 at->at_current = max(val, at->at_current);
1622         } else {
1623                 int i, shift;
1624                 unsigned int maxv = val;
1625                 /* move bins over */
1626                 shift = (now - at->at_binstart) / binlimit;
1627                 LASSERT(shift > 0);
1628                 for(i = AT_BINS - 1; i >= 0; i--) {
1629                         if (i >= shift) {
1630                                 at->at_hist[i] = at->at_hist[i - shift];
1631                                 maxv = max(maxv, at->at_hist[i]);
1632                         } else {
1633                                 at->at_hist[i] = 0;
1634                         }
1635                 }
1636                 at->at_hist[0] = val;
1637                 at->at_current = maxv;
1638                 at->at_binstart += shift * binlimit;
1639         }
1640
1641         if (at->at_current > at->at_worst_ever) {
1642                 at->at_worst_ever = at->at_current;
1643                 at->at_worst_time = now;
1644         }
1645
1646         if (at->at_flags & AT_FLG_NOHIST)
1647                 /* Only keep last reported val; keeping the rest of the history
1648                    for proc only */
1649                 at->at_current = val;
1650
1651         if (at_max > 0)
1652                 at->at_current =  min(at->at_current, at_max);
1653         at->at_current =  max(at->at_current, at_min);
1654
1655         if (at->at_current != old)
1656                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1657                        "(val=%u) hist %u %u %u %u\n", at,
1658                        old, at->at_current, at->at_current - old, val,
1659                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1660                        at->at_hist[3]);
1661
1662         /* if we changed, report the old value */
1663         old = (at->at_current != old) ? old : 0;
1664
1665         spin_unlock(&at->at_lock);
1666         return old;
1667 }
1668
1669 /* Find the imp_at index for a given portal; assign if space available */
1670 int import_at_get_index(struct obd_import *imp, int portal)
1671 {
1672         struct imp_at *at = &imp->imp_at;
1673         int i;
1674
1675         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1676                 if (at->iat_portal[i] == portal)
1677                         return i;
1678                 if (at->iat_portal[i] == 0)
1679                         /* unused */
1680                         break;
1681         }
1682
1683         /* Not found in list, add it under a lock */
1684         spin_lock(&imp->imp_lock);
1685
1686         /* Check unused under lock */
1687         for (; i < IMP_AT_MAX_PORTALS; i++) {
1688                 if (at->iat_portal[i] == portal)
1689                         goto out;
1690                 if (at->iat_portal[i] == 0)
1691                         /* unused */
1692                         break;
1693         }
1694
1695         /* Not enough portals? */
1696         LASSERT(i < IMP_AT_MAX_PORTALS);
1697
1698         at->iat_portal[i] = portal;
1699 out:
1700         spin_unlock(&imp->imp_lock);
1701         return i;
1702 }