Whamcloud - gitweb
LU-6698 kernel: kernel update RHEL 6.6 [2.6.32-504.23.4.el6]
[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 <linux/kthread.h>
44 #include <obd_support.h>
45 #include <lustre_ha.h>
46 #include <lustre_net.h>
47 #include <lustre_import.h>
48 #include <lustre_export.h>
49 #include <obd.h>
50 #include <obd_cksum.h>
51 #include <obd_class.h>
52
53 #include "ptlrpc_internal.h"
54
55 struct ptlrpc_connect_async_args {
56          __u64 pcaa_peer_committed;
57         int pcaa_initial_connect;
58 };
59
60 /**
61  * Updates import \a imp current state to provided \a state value
62  * Helper function. Must be called under imp_lock.
63  */
64 static void __import_set_state(struct obd_import *imp,
65                                enum lustre_imp_state state)
66 {
67         switch (state) {
68         case LUSTRE_IMP_CLOSED:
69         case LUSTRE_IMP_NEW:
70         case LUSTRE_IMP_DISCON:
71         case LUSTRE_IMP_CONNECTING:
72                 break;
73         case LUSTRE_IMP_REPLAY_WAIT:
74                 imp->imp_replay_state = LUSTRE_IMP_REPLAY_LOCKS;
75                 break;
76         default:
77                 imp->imp_replay_state = LUSTRE_IMP_REPLAY;
78         }
79         imp->imp_state = state;
80         imp->imp_state_hist[imp->imp_state_hist_idx].ish_state = state;
81         imp->imp_state_hist[imp->imp_state_hist_idx].ish_time =
82                 cfs_time_current_sec();
83         imp->imp_state_hist_idx = (imp->imp_state_hist_idx + 1) %
84                 IMP_STATE_HIST_LEN;
85 }
86
87 /* A CLOSED import should remain so. */
88 #define IMPORT_SET_STATE_NOLOCK(imp, state)                                    \
89 do {                                                                           \
90         if (imp->imp_state != LUSTRE_IMP_CLOSED) {                             \
91                CDEBUG(D_HA, "%p %s: changing import state from %s to %s\n",    \
92                       imp, obd2cli_tgt(imp->imp_obd),                          \
93                       ptlrpc_import_state_name(imp->imp_state),                \
94                       ptlrpc_import_state_name(state));                        \
95                __import_set_state(imp, state);                                 \
96         }                                                                      \
97 } while(0)
98
99 #define IMPORT_SET_STATE(imp, state)                                    \
100 do {                                                                    \
101         spin_lock(&imp->imp_lock);                                      \
102         IMPORT_SET_STATE_NOLOCK(imp, state);                            \
103         spin_unlock(&imp->imp_lock);                                    \
104 } while(0)
105
106
107 static int ptlrpc_connect_interpret(const struct lu_env *env,
108                                     struct ptlrpc_request *request,
109                                     void * data, int rc);
110 int ptlrpc_import_recovery_state_machine(struct obd_import *imp);
111
112 /* Only this function is allowed to change the import state when it is
113  * CLOSED. I would rather refcount the import and free it after
114  * disconnection like we do with exports. To do that, the client_obd
115  * will need to save the peer info somewhere other than in the import,
116  * though. */
117 int ptlrpc_init_import(struct obd_import *imp)
118 {
119         spin_lock(&imp->imp_lock);
120
121         imp->imp_generation++;
122         imp->imp_state =  LUSTRE_IMP_NEW;
123
124         spin_unlock(&imp->imp_lock);
125
126         return 0;
127 }
128 EXPORT_SYMBOL(ptlrpc_init_import);
129
130 #define UUID_STR "_UUID"
131 void deuuidify(char *uuid, const char *prefix, char **uuid_start, int *uuid_len)
132 {
133         *uuid_start = !prefix || strncmp(uuid, prefix, strlen(prefix))
134                 ? uuid : uuid + strlen(prefix);
135
136         *uuid_len = strlen(*uuid_start);
137
138         if (*uuid_len < strlen(UUID_STR))
139                 return;
140
141         if (!strncmp(*uuid_start + *uuid_len - strlen(UUID_STR),
142                     UUID_STR, strlen(UUID_STR)))
143                 *uuid_len -= strlen(UUID_STR);
144 }
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 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 EXPORT_SYMBOL(ptlrpc_pinger_force);
422
423 void ptlrpc_fail_import(struct obd_import *imp, __u32 conn_cnt)
424 {
425         ENTRY;
426
427         LASSERT(!imp->imp_dlm_fake);
428
429         if (ptlrpc_set_import_discon(imp, conn_cnt)) {
430                 if (!imp->imp_replayable) {
431                         CDEBUG(D_HA, "import %s@%s for %s not replayable, "
432                                "auto-deactivating\n",
433                                obd2cli_tgt(imp->imp_obd),
434                                imp->imp_connection->c_remote_uuid.uuid,
435                                imp->imp_obd->obd_name);
436                         ptlrpc_deactivate_import(imp);
437                 }
438
439                 ptlrpc_pinger_force(imp);
440         }
441         EXIT;
442 }
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, NULL);
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         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         /* Update client max modify RPCs in flight with value returned
901          * by the server */
902         if (ocd->ocd_connect_flags & OBD_CONNECT_MULTIMODRPCS)
903                 cli->cl_max_mod_rpcs_in_flight = min(
904                                         cli->cl_max_mod_rpcs_in_flight,
905                                         ocd->ocd_maxmodrpcs);
906         else
907                 cli->cl_max_mod_rpcs_in_flight = 1;
908
909         /* Reset ns_connect_flags only for initial connect. It might be
910          * changed in while using FS and if we reset it in reconnect
911          * this leads to losing user settings done before such as
912          * disable lru_resize, etc. */
913         if (old_connect_flags != exp_connect_flags(exp) || init_connect) {
914                 CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
915                              "flags: "LPX64"\n", imp->imp_obd->obd_name,
916                              ocd->ocd_connect_flags);
917                 imp->imp_obd->obd_namespace->ns_connect_flags =
918                         ocd->ocd_connect_flags;
919                 imp->imp_obd->obd_namespace->ns_orig_connect_flags =
920                         ocd->ocd_connect_flags;
921         }
922
923         if (ocd->ocd_connect_flags & OBD_CONNECT_AT)
924                 /* We need a per-message support flag, because
925                  * a. we don't know if the incoming connect reply
926                  *    supports AT or not (in reply_in_callback)
927                  *    until we unpack it.
928                  * b. failovered server means export and flags are gone
929                  *    (in ptlrpc_send_reply).
930                  *    Can only be set when we know AT is supported at
931                  *    both ends */
932                 imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
933         else
934                 imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
935
936         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
937
938         return 0;
939 }
940
941 /**
942  * interpret_reply callback for connect RPCs.
943  * Looks into returned status of connect operation and decides
944  * what to do with the import - i.e enter recovery, promote it to
945  * full state for normal operations of disconnect it due to an error.
946  */
947 static int ptlrpc_connect_interpret(const struct lu_env *env,
948                                     struct ptlrpc_request *request,
949                                     void *data, int rc)
950 {
951         struct ptlrpc_connect_async_args *aa = data;
952         struct obd_import *imp = request->rq_import;
953         struct lustre_handle old_hdl;
954         __u64 old_connect_flags;
955         int msg_flags;
956         struct obd_connect_data *ocd;
957         struct obd_export *exp;
958         int ret;
959         ENTRY;
960
961         spin_lock(&imp->imp_lock);
962         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
963                 imp->imp_connect_tried = 1;
964                 spin_unlock(&imp->imp_lock);
965                 RETURN(0);
966         }
967
968         if (rc) {
969                 /* if this reconnect to busy export - not need select new target
970                  * for connecting*/
971                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
972                 spin_unlock(&imp->imp_lock);
973                 ptlrpc_maybe_ping_import_soon(imp);
974                 GOTO(out, rc);
975         }
976         spin_unlock(&imp->imp_lock);
977
978         LASSERT(imp->imp_conn_current);
979
980         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
981
982         ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
983                                    RCL_SERVER);
984         /* server replied obd_connect_data is always bigger */
985         ocd = req_capsule_server_sized_get(&request->rq_pill,
986                                            &RMF_CONNECT_DATA, ret);
987
988         if (ocd == NULL) {
989                 CERROR("%s: no connect data from server\n",
990                        imp->imp_obd->obd_name);
991                 rc = -EPROTO;
992                 GOTO(out, rc);
993         }
994
995         spin_lock(&imp->imp_lock);
996
997         /* All imports are pingable */
998         imp->imp_pingable = 1;
999         imp->imp_force_reconnect = 0;
1000         imp->imp_force_verify = 0;
1001
1002         imp->imp_connect_data = *ocd;
1003
1004         CDEBUG(D_HA, "%s: connect to target with instance %u\n",
1005                imp->imp_obd->obd_name, ocd->ocd_instance);
1006         exp = class_conn2export(&imp->imp_dlm_handle);
1007
1008         spin_unlock(&imp->imp_lock);
1009
1010         /* check that server granted subset of flags we asked for. */
1011         if ((ocd->ocd_connect_flags & imp->imp_connect_flags_orig) !=
1012             ocd->ocd_connect_flags) {
1013                 CERROR("%s: Server didn't granted asked subset of flags: "
1014                        "asked="LPX64" grranted="LPX64"\n",
1015                        imp->imp_obd->obd_name,imp->imp_connect_flags_orig,
1016                        ocd->ocd_connect_flags);
1017                 GOTO(out, rc = -EPROTO);
1018         }
1019
1020         if (!(imp->imp_connect_flags_orig & OBD_CONNECT_LIGHTWEIGHT) &&
1021             (imp->imp_connect_flags_orig & OBD_CONNECT_MDS_MDS) &&
1022             (imp->imp_connect_flags_orig & OBD_CONNECT_FID) &&
1023             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION)) {
1024                 __u32 major = OBD_OCD_VERSION_MAJOR(ocd->ocd_version);
1025                 __u32 minor = OBD_OCD_VERSION_MINOR(ocd->ocd_version);
1026                 __u32 patch = OBD_OCD_VERSION_PATCH(ocd->ocd_version);
1027
1028                 /* We do not support the MDT-MDT interoperations with
1029                  * different version MDT because of protocol changes. */
1030                 if (unlikely(major != LUSTRE_MAJOR ||
1031                              minor != LUSTRE_MINOR ||
1032                              abs(patch - LUSTRE_PATCH) > 3)) {
1033                         LCONSOLE_WARN("%s: import %p (%u.%u.%u.%u) tried the "
1034                                       "connection to different version MDT "
1035                                       "(%d.%d.%d.%d) %s\n",
1036                                       imp->imp_obd->obd_name, imp, LUSTRE_MAJOR,
1037                                       LUSTRE_MINOR, LUSTRE_PATCH, LUSTRE_FIX,
1038                                       major, minor, patch,
1039                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1040                                       imp->imp_connection->c_remote_uuid.uuid);
1041
1042                         GOTO(out, rc = -EPROTO);
1043                 }
1044         }
1045
1046         if (!exp) {
1047                 /* This could happen if export is cleaned during the
1048                    connect attempt */
1049                 CERROR("%s: missing export after connect\n",
1050                        imp->imp_obd->obd_name);
1051                 GOTO(out, rc = -ENODEV);
1052         }
1053         old_connect_flags = exp_connect_flags(exp);
1054         exp->exp_connect_data = *ocd;
1055         imp->imp_obd->obd_self_export->exp_connect_data = *ocd;
1056
1057         /* The net statistics after (re-)connect is not valid anymore,
1058          * because may reflect other routing, etc. */
1059         at_init(&imp->imp_at.iat_net_latency, 0, 0);
1060         ptlrpc_at_adj_net_latency(request,
1061                         lustre_msg_get_service_time(request->rq_repmsg));
1062
1063         /* Import flags should be updated before waking import at FULL state */
1064         rc = ptlrpc_connect_set_flags(imp, ocd, old_connect_flags, exp,
1065                                  aa->pcaa_initial_connect);
1066         class_export_put(exp);
1067         if (rc != 0)
1068                 GOTO(out, rc);
1069
1070         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1071
1072         if (aa->pcaa_initial_connect) {
1073                 spin_lock(&imp->imp_lock);
1074                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
1075                         imp->imp_replayable = 1;
1076                         spin_unlock(&imp->imp_lock);
1077                         CDEBUG(D_HA, "connected to replayable target: %s\n",
1078                                obd2cli_tgt(imp->imp_obd));
1079                 } else {
1080                         imp->imp_replayable = 0;
1081                         spin_unlock(&imp->imp_lock);
1082                 }
1083
1084                 /* if applies, adjust the imp->imp_msg_magic here
1085                  * according to reply flags */
1086
1087                 imp->imp_remote_handle =
1088                                 *lustre_msg_get_handle(request->rq_repmsg);
1089
1090                 /* Initial connects are allowed for clients with non-random
1091                  * uuids when servers are in recovery.  Simply signal the
1092                  * servers replay is complete and wait in REPLAY_WAIT. */
1093                 if (msg_flags & MSG_CONNECT_RECOVERING) {
1094                         CDEBUG(D_HA, "connect to %s during recovery\n",
1095                                obd2cli_tgt(imp->imp_obd));
1096                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1097                 } else {
1098                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1099                         ptlrpc_activate_import(imp);
1100                 }
1101
1102                 GOTO(finish, rc = 0);
1103         }
1104
1105         /* Determine what recovery state to move the import to. */
1106         if (MSG_CONNECT_RECONNECT & msg_flags) {
1107                 memset(&old_hdl, 0, sizeof(old_hdl));
1108                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
1109                             sizeof (old_hdl))) {
1110                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
1111                                       "bad handle "LPX64"\n",
1112                                       obd2cli_tgt(imp->imp_obd),
1113                                       imp->imp_connection->c_remote_uuid.uuid,
1114                                       imp->imp_dlm_handle.cookie);
1115                         GOTO(out, rc = -ENOTCONN);
1116                 }
1117
1118                 if (memcmp(&imp->imp_remote_handle,
1119                            lustre_msg_get_handle(request->rq_repmsg),
1120                            sizeof(imp->imp_remote_handle))) {
1121                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
1122                                 D_HA : D_WARNING;
1123
1124                         /* Bug 16611/14775: if server handle have changed,
1125                          * that means some sort of disconnection happened.
1126                          * If the server is not in recovery, that also means it
1127                          * already erased all of our state because of previous
1128                          * eviction. If it is in recovery - we are safe to
1129                          * participate since we can reestablish all of our state
1130                          * with server again */
1131                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
1132                                 CDEBUG(level,"%s@%s changed server handle from "
1133                                        LPX64" to "LPX64
1134                                        " but is still in recovery\n",
1135                                        obd2cli_tgt(imp->imp_obd),
1136                                        imp->imp_connection->c_remote_uuid.uuid,
1137                                        imp->imp_remote_handle.cookie,
1138                                        lustre_msg_get_handle(
1139                                        request->rq_repmsg)->cookie);
1140                         } else {
1141                                 LCONSOLE_WARN("Evicted from %s (at %s) "
1142                                               "after server handle changed from "
1143                                               LPX64" to "LPX64"\n",
1144                                               obd2cli_tgt(imp->imp_obd),
1145                                               imp->imp_connection-> \
1146                                               c_remote_uuid.uuid,
1147                                               imp->imp_remote_handle.cookie,
1148                                               lustre_msg_get_handle(
1149                                               request->rq_repmsg)->cookie);
1150                         }
1151
1152
1153                         imp->imp_remote_handle =
1154                                      *lustre_msg_get_handle(request->rq_repmsg);
1155
1156                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
1157                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1158                                 GOTO(finish, rc = 0);
1159                         }
1160
1161                 } else {
1162                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
1163                                obd2cli_tgt(imp->imp_obd),
1164                                imp->imp_connection->c_remote_uuid.uuid);
1165                 }
1166
1167                 if (imp->imp_invalid) {
1168                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
1169                                "marking evicted\n", imp->imp_obd->obd_name);
1170                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1171                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
1172                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
1173                                imp->imp_obd->obd_name,
1174                                obd2cli_tgt(imp->imp_obd));
1175
1176                         spin_lock(&imp->imp_lock);
1177                         imp->imp_resend_replay = 1;
1178                         spin_unlock(&imp->imp_lock);
1179
1180                         IMPORT_SET_STATE(imp, imp->imp_replay_state);
1181                 } else {
1182                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1183                 }
1184         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
1185                 LASSERT(imp->imp_replayable);
1186                 imp->imp_remote_handle =
1187                                 *lustre_msg_get_handle(request->rq_repmsg);
1188                 imp->imp_last_replay_transno = 0;
1189                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
1190         } else {
1191                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
1192                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
1193                 imp->imp_remote_handle =
1194                                 *lustre_msg_get_handle(request->rq_repmsg);
1195                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1196         }
1197
1198         /* Sanity checks for a reconnected import. */
1199         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
1200                 CERROR("imp_replayable flag does not match server "
1201                        "after reconnect. We should LBUG right here.\n");
1202         }
1203
1204         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
1205             lustre_msg_get_last_committed(request->rq_repmsg) <
1206             aa->pcaa_peer_committed) {
1207                 CERROR("%s went back in time (transno "LPD64
1208                        " was previously committed, server now claims "LPD64
1209                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
1210                        "id=9646\n",
1211                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
1212                        lustre_msg_get_last_committed(request->rq_repmsg));
1213         }
1214
1215 finish:
1216         rc = ptlrpc_import_recovery_state_machine(imp);
1217         if (rc == -ENOTCONN) {
1218                 CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
1219                        "invalidating and reconnecting\n",
1220                        obd2cli_tgt(imp->imp_obd),
1221                        imp->imp_connection->c_remote_uuid.uuid);
1222                 ptlrpc_connect_import(imp);
1223                 imp->imp_connect_tried = 1;
1224                 RETURN(0);
1225         }
1226
1227 out:
1228         imp->imp_connect_tried = 1;
1229
1230         if (rc != 0) {
1231                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1232                 if (rc == -EACCES) {
1233                         /*
1234                          * Give up trying to reconnect
1235                          * EACCES means client has no permission for connection
1236                          */
1237                         imp->imp_obd->obd_no_recov = 1;
1238                         ptlrpc_deactivate_import(imp);
1239                 }
1240
1241                 if (rc == -EPROTO) {
1242                         struct obd_connect_data *ocd;
1243
1244                         /* reply message might not be ready */
1245                         if (request->rq_repmsg == NULL)
1246                                 RETURN(-EPROTO);
1247
1248                         ocd = req_capsule_server_get(&request->rq_pill,
1249                                                      &RMF_CONNECT_DATA);
1250                         if (ocd &&
1251                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1252                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1253                            /* Actually servers are only supposed to refuse
1254                               connection from liblustre clients, so we should
1255                               never see this from VFS context */
1256                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1257                                         "(%d.%d.%d.%d)"
1258                                         " refused connection from this client "
1259                                         "with an incompatible version (%s).  "
1260                                         "Client must be recompiled\n",
1261                                         obd2cli_tgt(imp->imp_obd),
1262                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1263                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1264                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1265                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1266                                         LUSTRE_VERSION_STRING);
1267                                 ptlrpc_deactivate_import(imp);
1268                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1269                         }
1270                         RETURN(-EPROTO);
1271                 }
1272
1273                 ptlrpc_maybe_ping_import_soon(imp);
1274
1275                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1276                        obd2cli_tgt(imp->imp_obd),
1277                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1278         }
1279
1280         wake_up_all(&imp->imp_recovery_waitq);
1281         RETURN(rc);
1282 }
1283
1284 /**
1285  * interpret callback for "completed replay" RPCs.
1286  * \see signal_completed_replay
1287  */
1288 static int completed_replay_interpret(const struct lu_env *env,
1289                                       struct ptlrpc_request *req,
1290                                       void * data, int rc)
1291 {
1292         ENTRY;
1293         atomic_dec(&req->rq_import->imp_replay_inflight);
1294         if (req->rq_status == 0 &&
1295             !req->rq_import->imp_vbr_failed) {
1296                 ptlrpc_import_recovery_state_machine(req->rq_import);
1297         } else {
1298                 if (req->rq_import->imp_vbr_failed) {
1299                         CDEBUG(D_WARNING,
1300                                "%s: version recovery fails, reconnecting\n",
1301                                req->rq_import->imp_obd->obd_name);
1302                 } else {
1303                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1304                                      "reconnecting\n",
1305                                req->rq_import->imp_obd->obd_name,
1306                                req->rq_status);
1307                 }
1308                 ptlrpc_connect_import(req->rq_import);
1309         }
1310
1311         RETURN(0);
1312 }
1313
1314 /**
1315  * Let server know that we have no requests to replay anymore.
1316  * Achieved by just sending a PING request
1317  */
1318 static int signal_completed_replay(struct obd_import *imp)
1319 {
1320         struct ptlrpc_request *req;
1321         ENTRY;
1322
1323         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1324                 RETURN(0);
1325
1326         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1327         atomic_inc(&imp->imp_replay_inflight);
1328
1329         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1330                                         OBD_PING);
1331         if (req == NULL) {
1332                 atomic_dec(&imp->imp_replay_inflight);
1333                 RETURN(-ENOMEM);
1334         }
1335
1336         ptlrpc_request_set_replen(req);
1337         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1338         lustre_msg_add_flags(req->rq_reqmsg,
1339                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1340         if (AT_OFF)
1341                 req->rq_timeout *= 3;
1342         req->rq_interpret_reply = completed_replay_interpret;
1343
1344         ptlrpcd_add_req(req, PDL_POLICY_ROUND, -1);
1345         RETURN(0);
1346 }
1347
1348 /**
1349  * In kernel code all import invalidation happens in its own
1350  * separate thread, so that whatever application happened to encounter
1351  * a problem could still be killed or otherwise continue
1352  */
1353 static int ptlrpc_invalidate_import_thread(void *data)
1354 {
1355         struct obd_import *imp = data;
1356
1357         ENTRY;
1358
1359         unshare_fs_struct();
1360
1361         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1362                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1363                imp->imp_connection->c_remote_uuid.uuid);
1364
1365         ptlrpc_invalidate_import(imp);
1366
1367         if (obd_dump_on_eviction) {
1368                 CERROR("dump the log upon eviction\n");
1369                 libcfs_debug_dumplog();
1370         }
1371
1372         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1373         ptlrpc_import_recovery_state_machine(imp);
1374
1375         class_import_put(imp);
1376         RETURN(0);
1377 }
1378
1379 /**
1380  * This is the state machine for client-side recovery on import.
1381  *
1382  * Typicaly we have two possibly paths. If we came to server and it is not
1383  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1384  * state and reconnect from scratch.
1385  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1386  * We go through our list of requests to replay and send them to server one by
1387  * one.
1388  * After sending all request from the list we change import state to
1389  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1390  * and also all the locks we don't yet have and wait for server to grant us.
1391  * After that we send a special "replay completed" request and change import
1392  * state to IMP_REPLAY_WAIT.
1393  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1394  * state and resend all requests from sending list.
1395  * After that we promote import to FULL state and send all delayed requests
1396  * and import is fully operational after that.
1397  *
1398  */
1399 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1400 {
1401         int rc = 0;
1402         int inflight;
1403         char *target_start;
1404         int target_len;
1405
1406         ENTRY;
1407         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1408                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1409                           &target_start, &target_len);
1410                 /* Don't care about MGC eviction */
1411                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1412                            LUSTRE_MGC_NAME) != 0) {
1413                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted "
1414                                            "by %.*s; in progress operations "
1415                                            "using this service will fail.\n",
1416                                            imp->imp_obd->obd_name, target_len,
1417                                            target_start);
1418                 }
1419                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1420                        obd2cli_tgt(imp->imp_obd),
1421                        imp->imp_connection->c_remote_uuid.uuid);
1422                 /* reset vbr_failed flag upon eviction */
1423                 spin_lock(&imp->imp_lock);
1424                 imp->imp_vbr_failed = 0;
1425                 spin_unlock(&imp->imp_lock);
1426
1427                 {
1428                 struct task_struct *task;
1429                 /* bug 17802:  XXX client_disconnect_export vs connect request
1430                  * race. if client is evicted at this time then we start
1431                  * invalidate thread without reference to import and import can
1432                  * be freed at same time. */
1433                 class_import_get(imp);
1434                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1435                                      "ll_imp_inval");
1436                 if (IS_ERR(task)) {
1437                         class_import_put(imp);
1438                         CERROR("error starting invalidate thread: %d\n", rc);
1439                         rc = PTR_ERR(task);
1440                 } else {
1441                         rc = 0;
1442                 }
1443                 RETURN(rc);
1444                 }
1445         }
1446
1447         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1448                 CDEBUG(D_HA, "replay requested by %s\n",
1449                        obd2cli_tgt(imp->imp_obd));
1450                 rc = ptlrpc_replay_next(imp, &inflight);
1451                 if (inflight == 0 &&
1452                     atomic_read(&imp->imp_replay_inflight) == 0) {
1453                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1454                         rc = ldlm_replay_locks(imp);
1455                         if (rc)
1456                                 GOTO(out, rc);
1457                 }
1458                 rc = 0;
1459         }
1460
1461         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1462                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1463                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1464                         rc = signal_completed_replay(imp);
1465                         if (rc)
1466                                 GOTO(out, rc);
1467                 }
1468         }
1469
1470         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1471                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1472                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1473                 }
1474         }
1475
1476         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1477                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1478                        obd2cli_tgt(imp->imp_obd),
1479                        imp->imp_connection->c_remote_uuid.uuid);
1480
1481                 rc = ptlrpc_resend(imp);
1482                 if (rc)
1483                         GOTO(out, rc);
1484                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1485                 ptlrpc_activate_import(imp);
1486
1487                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1488                           &target_start, &target_len);
1489                 LCONSOLE_INFO("%s: Connection restored to %.*s (at %s)\n",
1490                               imp->imp_obd->obd_name,
1491                               target_len, target_start,
1492                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1493         }
1494
1495         if (imp->imp_state == LUSTRE_IMP_FULL) {
1496                 wake_up_all(&imp->imp_recovery_waitq);
1497                 ptlrpc_wake_delayed(imp);
1498         }
1499
1500 out:
1501         RETURN(rc);
1502 }
1503
1504 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1505 {
1506         struct ptlrpc_request *req;
1507         int rq_opc, rc = 0;
1508         ENTRY;
1509
1510         if (imp->imp_obd->obd_force)
1511                 GOTO(set_state, rc);
1512
1513         switch (imp->imp_connect_op) {
1514         case OST_CONNECT:
1515                 rq_opc = OST_DISCONNECT;
1516                 break;
1517         case MDS_CONNECT:
1518                 rq_opc = MDS_DISCONNECT;
1519                 break;
1520         case MGS_CONNECT:
1521                 rq_opc = MGS_DISCONNECT;
1522                 break;
1523         default:
1524                 rc = -EINVAL;
1525                 CERROR("%s: don't know how to disconnect from %s "
1526                        "(connect_op %d): rc = %d\n",
1527                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1528                        imp->imp_connect_op, rc);
1529                 RETURN(rc);
1530         }
1531
1532         if (ptlrpc_import_in_recovery(imp)) {
1533                 struct l_wait_info lwi;
1534                 cfs_duration_t timeout;
1535
1536                 if (AT_OFF) {
1537                         if (imp->imp_server_timeout)
1538                                 timeout = cfs_time_seconds(obd_timeout / 2);
1539                         else
1540                                 timeout = cfs_time_seconds(obd_timeout);
1541                 } else {
1542                         int idx = import_at_get_index(imp,
1543                                 imp->imp_client->cli_request_portal);
1544                         timeout = cfs_time_seconds(
1545                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1546                 }
1547
1548                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1549                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1550                 rc = l_wait_event(imp->imp_recovery_waitq,
1551                                   !ptlrpc_import_in_recovery(imp), &lwi);
1552
1553         }
1554
1555         spin_lock(&imp->imp_lock);
1556         if (imp->imp_state != LUSTRE_IMP_FULL)
1557                 GOTO(out, rc);
1558         spin_unlock(&imp->imp_lock);
1559
1560         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1561                                         LUSTRE_OBD_VERSION, rq_opc);
1562         if (req) {
1563                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1564                  * it fails.  We can get through the above with a down server
1565                  * if the client doesn't know the server is gone yet. */
1566                 req->rq_no_resend = 1;
1567
1568                 /* We want client umounts to happen quickly, no matter the
1569                    server state... */
1570                 req->rq_timeout = min_t(int, req->rq_timeout,
1571                                         INITIAL_CONNECT_TIMEOUT);
1572
1573                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1574                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1575                 ptlrpc_request_set_replen(req);
1576                 rc = ptlrpc_queue_wait(req);
1577                 ptlrpc_req_finished(req);
1578         }
1579
1580 set_state:
1581         spin_lock(&imp->imp_lock);
1582 out:
1583         if (noclose)
1584                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1585         else
1586                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1587         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1588         spin_unlock(&imp->imp_lock);
1589
1590         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1591                 rc = 0;
1592         RETURN(rc);
1593 }
1594 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1595
1596 void ptlrpc_cleanup_imp(struct obd_import *imp)
1597 {
1598         ENTRY;
1599
1600         spin_lock(&imp->imp_lock);
1601         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1602         imp->imp_generation++;
1603         spin_unlock(&imp->imp_lock);
1604         ptlrpc_abort_inflight(imp);
1605
1606         EXIT;
1607 }
1608
1609 /* Adaptive Timeout utils */
1610 extern unsigned int at_min, at_max, at_history;
1611
1612 /* Update at_current with the specified value (bounded by at_min and at_max),
1613  * as well as the AT history "bins".
1614  *  - Bin into timeslices using AT_BINS bins.
1615  *  - This gives us a max of the last at_history seconds without the storage,
1616  *    but still smoothing out a return to normalcy from a slow response.
1617  *  - (E.g. remember the maximum latency in each minute of the last 4 minutes.)
1618  */
1619 int at_measured(struct adaptive_timeout *at, unsigned int val)
1620 {
1621         unsigned int old = at->at_current;
1622         time_t now = cfs_time_current_sec();
1623         time_t binlimit = max_t(time_t, at_history / AT_BINS, 1);
1624
1625         LASSERT(at);
1626         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1627                val, at, now - at->at_binstart, at->at_current,
1628                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1629
1630         if (val == 0)
1631                 /* 0's don't count, because we never want our timeout to
1632                    drop to 0, and because 0 could mean an error */
1633                 return 0;
1634
1635         spin_lock(&at->at_lock);
1636
1637         if (unlikely(at->at_binstart == 0)) {
1638                 /* Special case to remove default from history */
1639                 at->at_current = val;
1640                 at->at_worst_ever = val;
1641                 at->at_worst_time = now;
1642                 at->at_hist[0] = val;
1643                 at->at_binstart = now;
1644         } else if (now - at->at_binstart < binlimit ) {
1645                 /* in bin 0 */
1646                 at->at_hist[0] = max(val, at->at_hist[0]);
1647                 at->at_current = max(val, at->at_current);
1648         } else {
1649                 int i, shift;
1650                 unsigned int maxv = val;
1651                 /* move bins over */
1652                 shift = (now - at->at_binstart) / binlimit;
1653                 LASSERT(shift > 0);
1654                 for(i = AT_BINS - 1; i >= 0; i--) {
1655                         if (i >= shift) {
1656                                 at->at_hist[i] = at->at_hist[i - shift];
1657                                 maxv = max(maxv, at->at_hist[i]);
1658                         } else {
1659                                 at->at_hist[i] = 0;
1660                         }
1661                 }
1662                 at->at_hist[0] = val;
1663                 at->at_current = maxv;
1664                 at->at_binstart += shift * binlimit;
1665         }
1666
1667         if (at->at_current > at->at_worst_ever) {
1668                 at->at_worst_ever = at->at_current;
1669                 at->at_worst_time = now;
1670         }
1671
1672         if (at->at_flags & AT_FLG_NOHIST)
1673                 /* Only keep last reported val; keeping the rest of the history
1674                    for proc only */
1675                 at->at_current = val;
1676
1677         if (at_max > 0)
1678                 at->at_current =  min(at->at_current, at_max);
1679         at->at_current =  max(at->at_current, at_min);
1680
1681         if (at->at_current != old)
1682                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1683                        "(val=%u) hist %u %u %u %u\n", at,
1684                        old, at->at_current, at->at_current - old, val,
1685                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1686                        at->at_hist[3]);
1687
1688         /* if we changed, report the old value */
1689         old = (at->at_current != old) ? old : 0;
1690
1691         spin_unlock(&at->at_lock);
1692         return old;
1693 }
1694
1695 /* Find the imp_at index for a given portal; assign if space available */
1696 int import_at_get_index(struct obd_import *imp, int portal)
1697 {
1698         struct imp_at *at = &imp->imp_at;
1699         int i;
1700
1701         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1702                 if (at->iat_portal[i] == portal)
1703                         return i;
1704                 if (at->iat_portal[i] == 0)
1705                         /* unused */
1706                         break;
1707         }
1708
1709         /* Not found in list, add it under a lock */
1710         spin_lock(&imp->imp_lock);
1711
1712         /* Check unused under lock */
1713         for (; i < IMP_AT_MAX_PORTALS; i++) {
1714                 if (at->iat_portal[i] == portal)
1715                         goto out;
1716                 if (at->iat_portal[i] == 0)
1717                         /* unused */
1718                         break;
1719         }
1720
1721         /* Not enough portals? */
1722         LASSERT(i < IMP_AT_MAX_PORTALS);
1723
1724         at->iat_portal[i] = portal;
1725 out:
1726         spin_unlock(&imp->imp_lock);
1727         return i;
1728 }