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