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