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