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