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