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