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