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