Whamcloud - gitweb
LU-12616 obclass: fix MDS start/stop race
[fs/lustre-release.git] / lustre / ptlrpc / import.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/ptlrpc/import.c
33  *
34  * Author: Mike Shaver <shaver@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_RPC
38
39 #include <linux/kthread.h>
40 #include <linux/delay.h>
41 #include <obd_support.h>
42 #include <lustre_ha.h>
43 #include <lustre_net.h>
44 #include <lustre_import.h>
45 #include <lustre_export.h>
46 #include <obd.h>
47 #include <obd_cksum.h>
48 #include <obd_class.h>
49
50 #include "ptlrpc_internal.h"
51
52 struct ptlrpc_connect_async_args {
53          __u64 pcaa_peer_committed;
54         int pcaa_initial_connect;
55 };
56
57 /**
58  * Updates import \a imp current state to provided \a state value
59  * Helper function.
60  */
61 static void import_set_state_nolock(struct obd_import *imp,
62                                     enum lustre_imp_state state)
63 {
64         switch (state) {
65         case LUSTRE_IMP_CLOSED:
66         case LUSTRE_IMP_NEW:
67         case LUSTRE_IMP_DISCON:
68         case LUSTRE_IMP_CONNECTING:
69                 break;
70         case LUSTRE_IMP_REPLAY_WAIT:
71                 imp->imp_replay_state = LUSTRE_IMP_REPLAY_LOCKS;
72                 break;
73         default:
74                 imp->imp_replay_state = LUSTRE_IMP_REPLAY;
75                 break;
76         }
77
78         /* A CLOSED import should remain so. */
79         if (state == LUSTRE_IMP_CLOSED)
80                 return;
81
82         if (imp->imp_state != LUSTRE_IMP_NEW) {
83                 CDEBUG(D_HA, "%p %s: changing import state from %s to %s\n",
84                        imp, obd2cli_tgt(imp->imp_obd),
85                        ptlrpc_import_state_name(imp->imp_state),
86                        ptlrpc_import_state_name(state));
87         }
88
89         imp->imp_state = state;
90         imp->imp_state_hist[imp->imp_state_hist_idx].ish_state = state;
91         imp->imp_state_hist[imp->imp_state_hist_idx].ish_time =
92                 ktime_get_real_seconds();
93         imp->imp_state_hist_idx = (imp->imp_state_hist_idx + 1) %
94                 IMP_STATE_HIST_LEN;
95 }
96
97 static void import_set_state(struct obd_import *imp,
98                              enum lustre_imp_state new_state)
99 {
100         spin_lock(&imp->imp_lock);
101         import_set_state_nolock(imp, new_state);
102         spin_unlock(&imp->imp_lock);
103 }
104
105 void ptlrpc_import_enter_resend(struct obd_import *imp)
106 {
107         import_set_state(imp, LUSTRE_IMP_RECOVER);
108 }
109 EXPORT_SYMBOL(ptlrpc_import_enter_resend);
110
111
112 static int ptlrpc_connect_interpret(const struct lu_env *env,
113                                     struct ptlrpc_request *request,
114                                     void *args, int rc);
115 int ptlrpc_import_recovery_state_machine(struct obd_import *imp);
116
117 /* Only this function is allowed to change the import state when it is
118  * CLOSED. I would rather refcount the import and free it after
119  * disconnection like we do with exports. To do that, the client_obd
120  * will need to save the peer info somewhere other than in the import,
121  * though. */
122 int ptlrpc_init_import(struct obd_import *imp)
123 {
124         spin_lock(&imp->imp_lock);
125
126         imp->imp_generation++;
127         imp->imp_state =  LUSTRE_IMP_NEW;
128
129         spin_unlock(&imp->imp_lock);
130
131         return 0;
132 }
133 EXPORT_SYMBOL(ptlrpc_init_import);
134
135 #define UUID_STR "_UUID"
136 void deuuidify(char *uuid, const char *prefix, char **uuid_start, int *uuid_len)
137 {
138         *uuid_start = !prefix || strncmp(uuid, prefix, strlen(prefix))
139                 ? uuid : uuid + strlen(prefix);
140
141         *uuid_len = strlen(*uuid_start);
142
143         if (*uuid_len < strlen(UUID_STR))
144                 return;
145
146         if (!strncmp(*uuid_start + *uuid_len - strlen(UUID_STR),
147                     UUID_STR, strlen(UUID_STR)))
148                 *uuid_len -= strlen(UUID_STR);
149 }
150
151 /* Must be called with imp_lock held! */
152 static void ptlrpc_deactivate_import_nolock(struct obd_import *imp)
153 {
154         ENTRY;
155
156         assert_spin_locked(&imp->imp_lock);
157         CDEBUG(D_HA, "setting import %s INVALID\n", obd2cli_tgt(imp->imp_obd));
158         imp->imp_invalid = 1;
159         imp->imp_generation++;
160
161         ptlrpc_abort_inflight(imp);
162
163         EXIT;
164 }
165
166 /**
167  * Returns true if import was FULL, false if import was already not
168  * connected.
169  * @imp - import to be disconnected
170  * @conn_cnt - connection count (epoch) of the request that timed out
171  *             and caused the disconnection.  In some cases, multiple
172  *             inflight requests can fail to a single target (e.g. OST
173  *             bulk requests) and if one has already caused a reconnection
174  *             (increasing the import->conn_cnt) the older failure should
175  *             not also cause a reconnection.  If zero it forces a reconnect.
176  * @invalid - set import invalid flag
177  */
178 int ptlrpc_set_import_discon(struct obd_import *imp,
179                              __u32 conn_cnt, bool invalid)
180 {
181         int rc = 0;
182
183         spin_lock(&imp->imp_lock);
184
185         if (imp->imp_state == LUSTRE_IMP_FULL &&
186             (conn_cnt == 0 || conn_cnt == imp->imp_conn_cnt)) {
187                 char *target_start;
188                 int   target_len;
189                 bool  inact = false;
190
191                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
192                           &target_start, &target_len);
193
194                 import_set_state_nolock(imp, LUSTRE_IMP_DISCON);
195                 if (imp->imp_replayable) {
196                         LCONSOLE_WARN("%s: Connection to %.*s (at %s) was "
197                                "lost; in progress operations using this "
198                                "service will wait for recovery to complete\n",
199                                imp->imp_obd->obd_name, target_len, target_start,
200                                obd_import_nid2str(imp));
201                 } else {
202                         LCONSOLE_ERROR_MSG(0x166, "%s: Connection to "
203                                "%.*s (at %s) was lost; in progress "
204                                "operations using this service will fail\n",
205                                imp->imp_obd->obd_name, target_len, target_start,
206                                obd_import_nid2str(imp));
207                         if (invalid) {
208                                 CDEBUG(D_HA, "import %s@%s for %s not "
209                                        "replayable, auto-deactivating\n",
210                                        obd2cli_tgt(imp->imp_obd),
211                                        imp->imp_connection->c_remote_uuid.uuid,
212                                        imp->imp_obd->obd_name);
213                                 ptlrpc_deactivate_import_nolock(imp);
214                                 inact = true;
215                         }
216                 }
217                 spin_unlock(&imp->imp_lock);
218
219                 if (obd_dump_on_timeout)
220                         libcfs_debug_dumplog();
221
222                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_DISCON);
223
224                 if (inact)
225                         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INACTIVE);
226                 rc = 1;
227         } else {
228                 spin_unlock(&imp->imp_lock);
229                 CDEBUG(D_HA, "%s: import %p already %s (conn %u, was %u): %s\n",
230                        imp->imp_client->cli_name, imp,
231                        (imp->imp_state == LUSTRE_IMP_FULL &&
232                         imp->imp_conn_cnt > conn_cnt) ?
233                        "reconnected" : "not connected", imp->imp_conn_cnt,
234                        conn_cnt, ptlrpc_import_state_name(imp->imp_state));
235         }
236
237         return rc;
238 }
239
240 /*
241  * This acts as a barrier; all existing requests are rejected, and
242  * no new requests will be accepted until the import is valid again.
243  */
244 void ptlrpc_deactivate_import(struct obd_import *imp)
245 {
246         spin_lock(&imp->imp_lock);
247         ptlrpc_deactivate_import_nolock(imp);
248         spin_unlock(&imp->imp_lock);
249
250         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INACTIVE);
251 }
252 EXPORT_SYMBOL(ptlrpc_deactivate_import);
253
254 static time64_t ptlrpc_inflight_deadline(struct ptlrpc_request *req,
255                                          time64_t now)
256 {
257         time64_t dl;
258
259         if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
260               (req->rq_phase == RQ_PHASE_BULK) ||
261               (req->rq_phase == RQ_PHASE_NEW)))
262                 return 0;
263
264         if (req->rq_timedout)
265                 return 0;
266
267         if (req->rq_phase == RQ_PHASE_NEW)
268                 dl = req->rq_sent;
269         else
270                 dl = req->rq_deadline;
271
272         if (dl <= now)
273                 return 0;
274
275         return dl - now;
276 }
277
278 static time64_t ptlrpc_inflight_timeout(struct obd_import *imp)
279 {
280         time64_t now = ktime_get_real_seconds();
281         struct list_head *tmp, *n;
282         struct ptlrpc_request *req;
283         time64_t timeout = 0;
284
285         spin_lock(&imp->imp_lock);
286         list_for_each_safe(tmp, n, &imp->imp_sending_list) {
287                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
288                 timeout = max(ptlrpc_inflight_deadline(req, now), timeout);
289         }
290         spin_unlock(&imp->imp_lock);
291         return timeout;
292 }
293
294 /**
295  * This function will invalidate the import, if necessary, then block
296  * for all the RPC completions, and finally notify the obd to
297  * invalidate its state (ie cancel locks, clear pending requests,
298  * etc).
299  */
300 void ptlrpc_invalidate_import(struct obd_import *imp)
301 {
302         struct list_head *tmp, *n;
303         struct ptlrpc_request *req;
304         struct l_wait_info lwi;
305         time64_t timeout;
306         int rc;
307
308         atomic_inc(&imp->imp_inval_count);
309
310         if (!imp->imp_invalid || imp->imp_obd->obd_no_recov)
311                 ptlrpc_deactivate_import(imp);
312
313         if (OBD_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CONNECT_RACE)) {
314                 OBD_RACE(OBD_FAIL_PTLRPC_CONNECT_RACE);
315                 msleep(10 * MSEC_PER_SEC);
316         }
317         CFS_FAIL_TIMEOUT(OBD_FAIL_MGS_CONNECT_NET, 3 * cfs_fail_val / 2);
318         LASSERT(imp->imp_invalid);
319
320         /* Wait forever until inflight == 0. We really can't do it another
321          * way because in some cases we need to wait for very long reply
322          * unlink. We can't do anything before that because there is really
323          * no guarantee that some rdma transfer is not in progress right now. */
324         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 /**
660  * Attempt to (re)connect import \a imp. This includes all preparations,
661  * initializing CONNECT RPC request and passing it to ptlrpcd for
662  * actual sending.
663  * Returns 0 on success or error code.
664  */
665 int ptlrpc_connect_import(struct obd_import *imp)
666 {
667         struct obd_device *obd = imp->imp_obd;
668         int initial_connect = 0;
669         int set_transno = 0;
670         __u64 committed_before_reconnect = 0;
671         struct ptlrpc_request *request;
672         struct obd_connect_data ocd;
673         char *bufs[] = { NULL,
674                          obd2cli_tgt(imp->imp_obd),
675                          obd->obd_uuid.uuid,
676                          (char *)&imp->imp_dlm_handle,
677                          (char *)&ocd,
678                          NULL };
679         struct ptlrpc_connect_async_args *aa;
680         int rc;
681         ENTRY;
682
683         spin_lock(&imp->imp_lock);
684         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
685                 spin_unlock(&imp->imp_lock);
686                 CERROR("can't connect to a closed import\n");
687                 RETURN(-EINVAL);
688         } else if (imp->imp_state == LUSTRE_IMP_FULL) {
689                 spin_unlock(&imp->imp_lock);
690                 CERROR("already connected\n");
691                 RETURN(0);
692         } else if (imp->imp_state == LUSTRE_IMP_CONNECTING ||
693                    imp->imp_state == LUSTRE_IMP_EVICTED ||
694                    imp->imp_connected) {
695                 spin_unlock(&imp->imp_lock);
696                 CERROR("already connecting\n");
697                 RETURN(-EALREADY);
698         }
699
700         import_set_state_nolock(imp, LUSTRE_IMP_CONNECTING);
701
702         imp->imp_conn_cnt++;
703         imp->imp_resend_replay = 0;
704
705         if (!lustre_handle_is_used(&imp->imp_remote_handle))
706                 initial_connect = 1;
707         else
708                 committed_before_reconnect = imp->imp_peer_committed_transno;
709
710         set_transno = ptlrpc_first_transno(imp,
711                                            &imp->imp_connect_data.ocd_transno);
712         spin_unlock(&imp->imp_lock);
713
714         rc = import_select_connection(imp);
715         if (rc)
716                 GOTO(out, rc);
717
718         rc = sptlrpc_import_sec_adapt(imp, NULL, NULL);
719         if (rc)
720                 GOTO(out, rc);
721
722         /* Reset connect flags to the originally requested flags, in case
723          * the server is updated on-the-fly we will get the new features. */
724         ocd = imp->imp_connect_data;
725         ocd.ocd_connect_flags = imp->imp_connect_flags_orig;
726         ocd.ocd_connect_flags2 = imp->imp_connect_flags2_orig;
727         /* Reset ocd_version each time so the server knows the exact versions */
728         ocd.ocd_version = LUSTRE_VERSION_CODE;
729         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
730         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
731
732         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
733                            &obd->obd_uuid, &ocd, NULL);
734         if (rc)
735                 GOTO(out, rc);
736
737         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
738         if (request == NULL)
739                 GOTO(out, rc = -ENOMEM);
740
741         /* get SELinux policy info if any */
742         rc = sptlrpc_get_sepol(request);
743         if (rc < 0) {
744                 ptlrpc_request_free(request);
745                 GOTO(out, rc);
746         }
747
748         bufs[5] = request->rq_sepol;
749
750         req_capsule_set_size(&request->rq_pill, &RMF_SELINUX_POL, RCL_CLIENT,
751                              strlen(request->rq_sepol) ?
752                              strlen(request->rq_sepol) + 1 : 0);
753
754         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
755                                       imp->imp_connect_op, bufs, NULL);
756         if (rc) {
757                 ptlrpc_request_free(request);
758                 GOTO(out, rc);
759         }
760
761         /* Report the rpc service time to the server so that it knows how long
762          * to wait for clients to join recovery */
763         lustre_msg_set_service_time(request->rq_reqmsg,
764                                     at_timeout2est(request->rq_timeout));
765
766         /* The amount of time we give the server to process the connect req.
767          * import_select_connection will increase the net latency on
768          * repeated reconnect attempts to cover slow networks.
769          * We override/ignore the server rpc completion estimate here,
770          * which may be large if this is a reconnect attempt */
771         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
772         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
773
774         request->rq_no_resend = request->rq_no_delay = 1;
775         request->rq_send_state = LUSTRE_IMP_CONNECTING;
776         /* Allow a slightly larger reply for future growth compatibility */
777         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
778                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
779         ptlrpc_request_set_replen(request);
780         request->rq_interpret_reply = ptlrpc_connect_interpret;
781
782         CLASSERT(sizeof(*aa) <= sizeof(request->rq_async_args));
783         aa = ptlrpc_req_async_args(request);
784         memset(aa, 0, sizeof *aa);
785
786         aa->pcaa_peer_committed = committed_before_reconnect;
787         aa->pcaa_initial_connect = initial_connect;
788
789         if (aa->pcaa_initial_connect) {
790                 spin_lock(&imp->imp_lock);
791                 imp->imp_replayable = 1;
792                 spin_unlock(&imp->imp_lock);
793                 lustre_msg_add_op_flags(request->rq_reqmsg,
794                                         MSG_CONNECT_INITIAL);
795         }
796
797         if (set_transno)
798                 lustre_msg_add_op_flags(request->rq_reqmsg,
799                                         MSG_CONNECT_TRANSNO);
800
801         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %ld)",
802                   request->rq_timeout);
803         ptlrpcd_add_req(request);
804         rc = 0;
805 out:
806         if (rc != 0)
807                 import_set_state(imp, LUSTRE_IMP_DISCON);
808
809         RETURN(rc);
810 }
811 EXPORT_SYMBOL(ptlrpc_connect_import);
812
813 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
814 {
815         int force_verify;
816
817         spin_lock(&imp->imp_lock);
818         force_verify = imp->imp_force_verify != 0;
819         spin_unlock(&imp->imp_lock);
820
821         if (force_verify)
822                 ptlrpc_pinger_wake_up();
823 }
824
825 static int ptlrpc_busy_reconnect(int rc)
826 {
827         return (rc == -EBUSY) || (rc == -EAGAIN);
828 }
829
830 static int ptlrpc_connect_set_flags(struct obd_import *imp,
831                                     struct obd_connect_data *ocd,
832                                     __u64 old_connect_flags,
833                                     struct obd_export *exp, int init_connect)
834 {
835         static bool warned;
836         struct client_obd *cli = &imp->imp_obd->u.cli;
837
838         spin_lock(&imp->imp_lock);
839         list_move(&imp->imp_conn_current->oic_item,
840                   &imp->imp_conn_list);
841         imp->imp_last_success_conn =
842                 imp->imp_conn_current->oic_last_attempt;
843
844         spin_unlock(&imp->imp_lock);
845
846         if (!warned && (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
847             (ocd->ocd_version > LUSTRE_VERSION_CODE +
848                                 LUSTRE_VERSION_OFFSET_WARN ||
849              ocd->ocd_version < LUSTRE_VERSION_CODE -
850                                 LUSTRE_VERSION_OFFSET_WARN)) {
851                 /* Sigh, some compilers do not like #ifdef in the middle
852                    of macro arguments */
853                 const char *older = "older than client. "
854                                     "Consider upgrading server";
855                 const char *newer = "newer than client. "
856                                     "Consider upgrading client";
857
858                 LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
859                               "is much %s (%s)\n",
860                               obd2cli_tgt(imp->imp_obd),
861                               OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
862                               OBD_OCD_VERSION_MINOR(ocd->ocd_version),
863                               OBD_OCD_VERSION_PATCH(ocd->ocd_version),
864                               OBD_OCD_VERSION_FIX(ocd->ocd_version),
865                               ocd->ocd_version > LUSTRE_VERSION_CODE ?
866                               newer : older, LUSTRE_VERSION_STRING);
867                 warned = true;
868         }
869
870         if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
871                 /* We sent to the server ocd_cksum_types with bits set
872                  * for algorithms we understand. The server masked off
873                  * the checksum types it doesn't support */
874                 if ((ocd->ocd_cksum_types &
875                      obd_cksum_types_supported_client()) == 0) {
876                         LCONSOLE_ERROR("The negotiation of the checksum "
877                                        "alogrithm to use with server %s "
878                                        "failed (%x/%x)\n",
879                                        obd2cli_tgt(imp->imp_obd),
880                                        ocd->ocd_cksum_types,
881                                        obd_cksum_types_supported_client());
882                         return -EPROTO;
883                 } else {
884                         cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
885                 }
886         } else {
887                 /* The server does not support OBD_CONNECT_CKSUM.
888                  * Enforce ADLER for backward compatibility*/
889                 cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
890         }
891         cli->cl_cksum_type = obd_cksum_type_select(imp->imp_obd->obd_name,
892                                                   cli->cl_supp_cksum_types,
893                                                   cli->cl_preferred_cksum_type);
894
895         if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE)
896                 cli->cl_max_pages_per_rpc =
897                         min(ocd->ocd_brw_size >> PAGE_SHIFT,
898                             cli->cl_max_pages_per_rpc);
899         else if (imp->imp_connect_op == MDS_CONNECT ||
900                  imp->imp_connect_op == MGS_CONNECT)
901                 cli->cl_max_pages_per_rpc = 1;
902
903         LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
904                 (cli->cl_max_pages_per_rpc > 0));
905
906         client_adjust_max_dirty(cli);
907
908         /* Update client max modify RPCs in flight with value returned
909          * by the server */
910         if (ocd->ocd_connect_flags & OBD_CONNECT_MULTIMODRPCS)
911                 cli->cl_max_mod_rpcs_in_flight = min(
912                                         cli->cl_max_mod_rpcs_in_flight,
913                                         ocd->ocd_maxmodrpcs);
914         else
915                 cli->cl_max_mod_rpcs_in_flight = 1;
916
917         /* Reset ns_connect_flags only for initial connect. It might be
918          * changed in while using FS and if we reset it in reconnect
919          * this leads to losing user settings done before such as
920          * disable lru_resize, etc. */
921         if (old_connect_flags != exp_connect_flags(exp) || init_connect) {
922                 struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
923                 __u64 changed_flags;
924
925                 changed_flags =
926                         ns->ns_connect_flags ^ ns->ns_orig_connect_flags;
927                 CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
928                              "flags: %#llx\n", imp->imp_obd->obd_name,
929                              ocd->ocd_connect_flags);
930                 ns->ns_connect_flags = (ns->ns_connect_flags & changed_flags) |
931                                       (ocd->ocd_connect_flags & ~changed_flags);
932                 ns->ns_orig_connect_flags = ocd->ocd_connect_flags;
933         }
934
935         if (ocd->ocd_connect_flags & OBD_CONNECT_AT)
936                 /* We need a per-message support flag, because
937                  * a. we don't know if the incoming connect reply
938                  *    supports AT or not (in reply_in_callback)
939                  *    until we unpack it.
940                  * b. failovered server means export and flags are gone
941                  *    (in ptlrpc_send_reply).
942                  *    Can only be set when we know AT is supported at
943                  *    both ends */
944                 imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
945         else
946                 imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
947
948         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
949
950         return 0;
951 }
952
953 /**
954  * Add all replay requests back to unreplied list before start replay,
955  * so that we can make sure the known replied XID is always increased
956  * only even if when replaying requests.
957  */
958 static void ptlrpc_prepare_replay(struct obd_import *imp)
959 {
960         struct ptlrpc_request *req;
961
962         if (imp->imp_state != LUSTRE_IMP_REPLAY ||
963             imp->imp_resend_replay)
964                 return;
965
966         /* If the server was restart during repaly, the requests may
967          * have been added to the unreplied list in former replay. */
968         spin_lock(&imp->imp_lock);
969
970         list_for_each_entry(req, &imp->imp_committed_list, rq_replay_list) {
971                 if (list_empty(&req->rq_unreplied_list))
972                         ptlrpc_add_unreplied(req);
973         }
974
975         list_for_each_entry(req, &imp->imp_replay_list, rq_replay_list) {
976                 if (list_empty(&req->rq_unreplied_list))
977                         ptlrpc_add_unreplied(req);
978         }
979
980         imp->imp_known_replied_xid = ptlrpc_known_replied_xid(imp);
981         spin_unlock(&imp->imp_lock);
982 }
983
984 /**
985  * interpret_reply callback for connect RPCs.
986  * Looks into returned status of connect operation and decides
987  * what to do with the import - i.e enter recovery, promote it to
988  * full state for normal operations of disconnect it due to an error.
989  */
990 static int ptlrpc_connect_interpret(const struct lu_env *env,
991                                     struct ptlrpc_request *request,
992                                     void *data, int rc)
993 {
994         struct ptlrpc_connect_async_args *aa = data;
995         struct obd_import *imp = request->rq_import;
996         struct lustre_handle old_hdl;
997         __u64 old_connect_flags;
998         int msg_flags;
999         struct obd_connect_data *ocd;
1000         struct obd_export *exp = NULL;
1001         int ret;
1002         ENTRY;
1003
1004         spin_lock(&imp->imp_lock);
1005         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
1006                 imp->imp_connect_tried = 1;
1007                 spin_unlock(&imp->imp_lock);
1008                 RETURN(0);
1009         }
1010
1011         imp->imp_connect_error = rc;
1012         if (rc) {
1013                 struct ptlrpc_request *free_req;
1014                 struct ptlrpc_request *tmp;
1015
1016                 /* abort all delayed requests initiated connection */
1017                 list_for_each_entry_safe(free_req, tmp, &imp->imp_delayed_list,
1018                                          rq_list) {
1019                         spin_lock(&free_req->rq_lock);
1020                         if (free_req->rq_no_resend) {
1021                                 free_req->rq_err = 1;
1022                                 free_req->rq_status = -EIO;
1023                                 ptlrpc_client_wake_req(free_req);
1024                         }
1025                         spin_unlock(&free_req->rq_lock);
1026                 }
1027
1028                 /* if this reconnect to busy export - not need select new target
1029                  * for connecting*/
1030                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
1031                 spin_unlock(&imp->imp_lock);
1032                 ptlrpc_maybe_ping_import_soon(imp);
1033                 GOTO(out, rc);
1034         }
1035
1036         /* LU-7558: indicate that we are interpretting connect reply,
1037          * pltrpc_connect_import() will not try to reconnect until
1038          * interpret will finish. */
1039         imp->imp_connected = 1;
1040         spin_unlock(&imp->imp_lock);
1041
1042         LASSERT(imp->imp_conn_current);
1043
1044         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
1045
1046         ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
1047                                    RCL_SERVER);
1048         /* server replied obd_connect_data is always bigger */
1049         ocd = req_capsule_server_sized_get(&request->rq_pill,
1050                                            &RMF_CONNECT_DATA, ret);
1051
1052         if (ocd == NULL) {
1053                 CERROR("%s: no connect data from server\n",
1054                        imp->imp_obd->obd_name);
1055                 rc = -EPROTO;
1056                 GOTO(out, rc);
1057         }
1058
1059         spin_lock(&imp->imp_lock);
1060
1061         /* All imports are pingable */
1062         imp->imp_pingable = 1;
1063         imp->imp_force_reconnect = 0;
1064         imp->imp_force_verify = 0;
1065
1066         imp->imp_connect_data = *ocd;
1067
1068         CDEBUG(D_HA, "%s: connect to target with instance %u\n",
1069                imp->imp_obd->obd_name, ocd->ocd_instance);
1070         exp = class_conn2export(&imp->imp_dlm_handle);
1071
1072         spin_unlock(&imp->imp_lock);
1073
1074         if (!exp) {
1075                 /* This could happen if export is cleaned during the
1076                    connect attempt */
1077                 CERROR("%s: missing export after connect\n",
1078                        imp->imp_obd->obd_name);
1079                 GOTO(out, rc = -ENODEV);
1080         }
1081
1082         /* check that server granted subset of flags we asked for. */
1083         if ((ocd->ocd_connect_flags & imp->imp_connect_flags_orig) !=
1084             ocd->ocd_connect_flags) {
1085                 CERROR("%s: Server didn't grant requested subset of flags: "
1086                        "asked=%#llx granted=%#llx\n",
1087                        imp->imp_obd->obd_name, imp->imp_connect_flags_orig,
1088                        ocd->ocd_connect_flags);
1089                 GOTO(out, rc = -EPROTO);
1090         }
1091
1092         if ((ocd->ocd_connect_flags2 & imp->imp_connect_flags2_orig) !=
1093             ocd->ocd_connect_flags2) {
1094                 CERROR("%s: Server didn't grant requested subset of flags2: "
1095                        "asked=%#llx granted=%#llx\n",
1096                        imp->imp_obd->obd_name, imp->imp_connect_flags2_orig,
1097                        ocd->ocd_connect_flags2);
1098                 GOTO(out, rc = -EPROTO);
1099         }
1100
1101         if (!(imp->imp_connect_flags_orig & OBD_CONNECT_LIGHTWEIGHT) &&
1102             (imp->imp_connect_flags_orig & OBD_CONNECT_MDS_MDS) &&
1103             (imp->imp_connect_flags_orig & OBD_CONNECT_FID) &&
1104             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION)) {
1105                 __u32 major = OBD_OCD_VERSION_MAJOR(ocd->ocd_version);
1106                 __u32 minor = OBD_OCD_VERSION_MINOR(ocd->ocd_version);
1107                 __u32 patch = OBD_OCD_VERSION_PATCH(ocd->ocd_version);
1108
1109                 /* We do not support the MDT-MDT interoperations with
1110                  * different version MDT because of protocol changes. */
1111                 if (unlikely(major != LUSTRE_MAJOR ||
1112                              minor != LUSTRE_MINOR ||
1113                              abs(patch - LUSTRE_PATCH) > 3)) {
1114                         LCONSOLE_WARN("%s: import %p (%u.%u.%u.%u) tried the "
1115                                       "connection to different version MDT "
1116                                       "(%d.%d.%d.%d) %s\n",
1117                                       imp->imp_obd->obd_name, imp, LUSTRE_MAJOR,
1118                                       LUSTRE_MINOR, LUSTRE_PATCH, LUSTRE_FIX,
1119                                       major, minor, patch,
1120                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1121                                       imp->imp_connection->c_remote_uuid.uuid);
1122
1123                         GOTO(out, rc = -EPROTO);
1124                 }
1125         }
1126
1127         old_connect_flags = exp_connect_flags(exp);
1128         exp->exp_connect_data = *ocd;
1129         imp->imp_obd->obd_self_export->exp_connect_data = *ocd;
1130
1131         /* The net statistics after (re-)connect is not valid anymore,
1132          * because may reflect other routing, etc. */
1133         at_reinit(&imp->imp_at.iat_net_latency, 0, 0);
1134         ptlrpc_at_adj_net_latency(request,
1135                         lustre_msg_get_service_time(request->rq_repmsg));
1136
1137         /* Import flags should be updated before waking import at FULL state */
1138         rc = ptlrpc_connect_set_flags(imp, ocd, old_connect_flags, exp,
1139                                       aa->pcaa_initial_connect);
1140         class_export_put(exp);
1141         exp = NULL;
1142
1143         if (rc != 0)
1144                 GOTO(out, rc);
1145
1146         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1147
1148         if (aa->pcaa_initial_connect) {
1149                 spin_lock(&imp->imp_lock);
1150                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
1151                         imp->imp_replayable = 1;
1152                         CDEBUG(D_HA, "connected to replayable target: %s\n",
1153                                obd2cli_tgt(imp->imp_obd));
1154                 } else {
1155                         imp->imp_replayable = 0;
1156                 }
1157
1158                 /* if applies, adjust the imp->imp_msg_magic here
1159                  * according to reply flags */
1160
1161                 imp->imp_remote_handle =
1162                                 *lustre_msg_get_handle(request->rq_repmsg);
1163
1164                 /* Initial connects are allowed for clients with non-random
1165                  * uuids when servers are in recovery.  Simply signal the
1166                  * servers replay is complete and wait in REPLAY_WAIT. */
1167                 if (msg_flags & MSG_CONNECT_RECOVERING) {
1168                         CDEBUG(D_HA, "connect to %s during recovery\n",
1169                                obd2cli_tgt(imp->imp_obd));
1170                         import_set_state_nolock(imp, LUSTRE_IMP_REPLAY_LOCKS);
1171                         spin_unlock(&imp->imp_lock);
1172                 } else {
1173                         spin_unlock(&imp->imp_lock);
1174                         ptlrpc_activate_import(imp, true);
1175                 }
1176
1177                 GOTO(finish, rc = 0);
1178         }
1179
1180         /* Determine what recovery state to move the import to. */
1181         if (MSG_CONNECT_RECONNECT & msg_flags) {
1182                 memset(&old_hdl, 0, sizeof(old_hdl));
1183                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
1184                             sizeof (old_hdl))) {
1185                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
1186                                       "bad handle %#llx\n",
1187                                       obd2cli_tgt(imp->imp_obd),
1188                                       imp->imp_connection->c_remote_uuid.uuid,
1189                                       imp->imp_dlm_handle.cookie);
1190                         GOTO(out, rc = -ENOTCONN);
1191                 }
1192
1193                 if (memcmp(&imp->imp_remote_handle,
1194                            lustre_msg_get_handle(request->rq_repmsg),
1195                            sizeof(imp->imp_remote_handle))) {
1196                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
1197                                 D_HA : D_WARNING;
1198
1199                         /* Bug 16611/14775: if server handle have changed,
1200                          * that means some sort of disconnection happened.
1201                          * If the server is not in recovery, that also means it
1202                          * already erased all of our state because of previous
1203                          * eviction. If it is in recovery - we are safe to
1204                          * participate since we can reestablish all of our state
1205                          * with server again */
1206                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
1207                                 CDEBUG(level,"%s@%s changed server handle from "
1208                                        "%#llx to %#llx"
1209                                        " but is still in recovery\n",
1210                                        obd2cli_tgt(imp->imp_obd),
1211                                        imp->imp_connection->c_remote_uuid.uuid,
1212                                        imp->imp_remote_handle.cookie,
1213                                        lustre_msg_get_handle(
1214                                        request->rq_repmsg)->cookie);
1215                         } else {
1216                                 LCONSOLE_WARN("Evicted from %s (at %s) "
1217                                               "after server handle changed from "
1218                                               "%#llx to %#llx\n",
1219                                               obd2cli_tgt(imp->imp_obd),
1220                                               imp->imp_connection-> \
1221                                               c_remote_uuid.uuid,
1222                                               imp->imp_remote_handle.cookie,
1223                                               lustre_msg_get_handle(
1224                                               request->rq_repmsg)->cookie);
1225                         }
1226
1227
1228                         imp->imp_remote_handle =
1229                                      *lustre_msg_get_handle(request->rq_repmsg);
1230
1231                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
1232                                 import_set_state(imp, LUSTRE_IMP_EVICTED);
1233                                 GOTO(finish, rc = 0);
1234                         }
1235
1236                 } else {
1237                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
1238                                obd2cli_tgt(imp->imp_obd),
1239                                imp->imp_connection->c_remote_uuid.uuid);
1240                 }
1241
1242                 if (imp->imp_invalid) {
1243                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
1244                                "marking evicted\n", imp->imp_obd->obd_name);
1245                         import_set_state(imp, LUSTRE_IMP_EVICTED);
1246                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
1247                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
1248                                imp->imp_obd->obd_name,
1249                                obd2cli_tgt(imp->imp_obd));
1250
1251                         spin_lock(&imp->imp_lock);
1252                         imp->imp_resend_replay = 1;
1253                         spin_unlock(&imp->imp_lock);
1254
1255                         import_set_state(imp, imp->imp_replay_state);
1256                 } else {
1257                         import_set_state(imp, LUSTRE_IMP_RECOVER);
1258                 }
1259         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
1260                 LASSERT(imp->imp_replayable);
1261                 imp->imp_remote_handle =
1262                                 *lustre_msg_get_handle(request->rq_repmsg);
1263                 imp->imp_last_replay_transno = 0;
1264                 imp->imp_replay_cursor = &imp->imp_committed_list;
1265                 import_set_state(imp, LUSTRE_IMP_REPLAY);
1266         } else if ((ocd->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) != 0 &&
1267                    !imp->imp_invalid) {
1268
1269                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_INVALIDATE);
1270                 DEBUG_REQ(D_HA, request, "%s: lwp recover",
1271                           imp->imp_obd->obd_name);
1272                 imp->imp_remote_handle =
1273                         *lustre_msg_get_handle(request->rq_repmsg);
1274                 import_set_state(imp, LUSTRE_IMP_RECOVER);
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 *args, int rc)
1398 {
1399         ENTRY;
1400         atomic_dec(&req->rq_import->imp_replay_inflight);
1401         if (req->rq_status == 0 && !req->rq_import->imp_vbr_failed) {
1402                 ptlrpc_import_recovery_state_machine(req->rq_import);
1403         } else {
1404                 if (req->rq_import->imp_vbr_failed) {
1405                         CDEBUG(D_WARNING,
1406                                "%s: version recovery fails, reconnecting\n",
1407                                req->rq_import->imp_obd->obd_name);
1408                 } else {
1409                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1410                                      "reconnecting\n",
1411                                req->rq_import->imp_obd->obd_name,
1412                                req->rq_status);
1413                 }
1414                 ptlrpc_connect_import(req->rq_import);
1415         }
1416
1417         RETURN(0);
1418 }
1419
1420 /**
1421  * Let server know that we have no requests to replay anymore.
1422  * Achieved by just sending a PING request
1423  */
1424 static int signal_completed_replay(struct obd_import *imp)
1425 {
1426         struct ptlrpc_request *req;
1427         ENTRY;
1428
1429         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1430                 RETURN(0);
1431
1432         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1433         atomic_inc(&imp->imp_replay_inflight);
1434
1435         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1436                                         OBD_PING);
1437         if (req == NULL) {
1438                 atomic_dec(&imp->imp_replay_inflight);
1439                 RETURN(-ENOMEM);
1440         }
1441
1442         ptlrpc_request_set_replen(req);
1443         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1444         lustre_msg_add_flags(req->rq_reqmsg,
1445                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1446         if (AT_OFF)
1447                 req->rq_timeout *= 3;
1448         req->rq_interpret_reply = completed_replay_interpret;
1449
1450         ptlrpcd_add_req(req);
1451         RETURN(0);
1452 }
1453
1454 /**
1455  * In kernel code all import invalidation happens in its own
1456  * separate thread, so that whatever application happened to encounter
1457  * a problem could still be killed or otherwise continue
1458  */
1459 static int ptlrpc_invalidate_import_thread(void *data)
1460 {
1461         struct obd_import *imp = data;
1462
1463         ENTRY;
1464
1465         unshare_fs_struct();
1466
1467         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1468                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1469                imp->imp_connection->c_remote_uuid.uuid);
1470
1471         ptlrpc_invalidate_import(imp);
1472
1473         if (obd_dump_on_eviction) {
1474                 CERROR("dump the log upon eviction\n");
1475                 libcfs_debug_dumplog();
1476         }
1477
1478         import_set_state(imp, LUSTRE_IMP_RECOVER);
1479         ptlrpc_import_recovery_state_machine(imp);
1480
1481         class_import_put(imp);
1482         RETURN(0);
1483 }
1484
1485 /**
1486  * This is the state machine for client-side recovery on import.
1487  *
1488  * Typicaly we have two possibly paths. If we came to server and it is not
1489  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1490  * state and reconnect from scratch.
1491  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1492  * We go through our list of requests to replay and send them to server one by
1493  * one.
1494  * After sending all request from the list we change import state to
1495  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1496  * and also all the locks we don't yet have and wait for server to grant us.
1497  * After that we send a special "replay completed" request and change import
1498  * state to IMP_REPLAY_WAIT.
1499  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1500  * state and resend all requests from sending list.
1501  * After that we promote import to FULL state and send all delayed requests
1502  * and import is fully operational after that.
1503  *
1504  */
1505 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1506 {
1507         int rc = 0;
1508         int inflight;
1509         char *target_start;
1510         int target_len;
1511
1512         ENTRY;
1513         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1514                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1515                           &target_start, &target_len);
1516                 /* Don't care about MGC eviction */
1517                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1518                            LUSTRE_MGC_NAME) != 0) {
1519                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted "
1520                                            "by %.*s; in progress operations "
1521                                            "using this service will fail.\n",
1522                                            imp->imp_obd->obd_name, target_len,
1523                                            target_start);
1524                         LASSERTF(!obd_lbug_on_eviction, "LBUG upon eviction");
1525                 }
1526                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1527                        obd2cli_tgt(imp->imp_obd),
1528                        imp->imp_connection->c_remote_uuid.uuid);
1529                 /* reset vbr_failed flag upon eviction */
1530                 spin_lock(&imp->imp_lock);
1531                 imp->imp_vbr_failed = 0;
1532                 spin_unlock(&imp->imp_lock);
1533
1534                 {
1535                 struct task_struct *task;
1536                 /* bug 17802:  XXX client_disconnect_export vs connect request
1537                  * race. if client is evicted at this time then we start
1538                  * invalidate thread without reference to import and import can
1539                  * be freed at same time. */
1540                 class_import_get(imp);
1541                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1542                                      "ll_imp_inval");
1543                 if (IS_ERR(task)) {
1544                         class_import_put(imp);
1545                         CERROR("error starting invalidate thread: %d\n", rc);
1546                         rc = PTR_ERR(task);
1547                 } else {
1548                         rc = 0;
1549                 }
1550                 RETURN(rc);
1551                 }
1552         }
1553
1554         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1555                 CDEBUG(D_HA, "replay requested by %s\n",
1556                        obd2cli_tgt(imp->imp_obd));
1557                 rc = ptlrpc_replay_next(imp, &inflight);
1558                 if (inflight == 0 &&
1559                     atomic_read(&imp->imp_replay_inflight) == 0) {
1560                         import_set_state(imp, LUSTRE_IMP_REPLAY_LOCKS);
1561                         rc = ldlm_replay_locks(imp);
1562                         if (rc)
1563                                 GOTO(out, rc);
1564                 }
1565                 rc = 0;
1566         }
1567
1568         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1569                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1570                         import_set_state(imp, LUSTRE_IMP_REPLAY_WAIT);
1571                         rc = signal_completed_replay(imp);
1572                         if (rc)
1573                                 GOTO(out, rc);
1574                 }
1575         }
1576
1577         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1578                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1579                         import_set_state(imp, LUSTRE_IMP_RECOVER);
1580                 }
1581         }
1582
1583         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1584                 struct ptlrpc_connection *conn = imp->imp_connection;
1585
1586                 rc = ptlrpc_resend(imp);
1587                 if (rc)
1588                         GOTO(out, rc);
1589                 ptlrpc_activate_import(imp, true);
1590
1591                 LCONSOLE_INFO("%s: Connection restored to %s (at %s)\n",
1592                               imp->imp_obd->obd_name,
1593                               obd_uuid2str(&conn->c_remote_uuid),
1594                               obd_import_nid2str(imp));
1595         }
1596
1597         if (imp->imp_state == LUSTRE_IMP_FULL) {
1598                 wake_up_all(&imp->imp_recovery_waitq);
1599                 ptlrpc_wake_delayed(imp);
1600         }
1601
1602 out:
1603         RETURN(rc);
1604 }
1605
1606 static struct ptlrpc_request *ptlrpc_disconnect_prep_req(struct obd_import *imp)
1607 {
1608         struct ptlrpc_request *req;
1609         int rq_opc, rc = 0;
1610         ENTRY;
1611
1612         switch (imp->imp_connect_op) {
1613         case OST_CONNECT:
1614                 rq_opc = OST_DISCONNECT;
1615                 break;
1616         case MDS_CONNECT:
1617                 rq_opc = MDS_DISCONNECT;
1618                 break;
1619         case MGS_CONNECT:
1620                 rq_opc = MGS_DISCONNECT;
1621                 break;
1622         default:
1623                 rc = -EINVAL;
1624                 CERROR("%s: don't know how to disconnect from %s "
1625                        "(connect_op %d): rc = %d\n",
1626                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1627                        imp->imp_connect_op, rc);
1628                 RETURN(ERR_PTR(rc));
1629         }
1630
1631         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1632                                         LUSTRE_OBD_VERSION, rq_opc);
1633         if (req == NULL)
1634                 RETURN(NULL);
1635
1636         /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1637          * it fails.  We can get through the above with a down server
1638          * if the client doesn't know the server is gone yet. */
1639         req->rq_no_resend = 1;
1640
1641         /* We want client umounts to happen quickly, no matter the
1642            server state... */
1643         req->rq_timeout = min_t(int, req->rq_timeout,
1644                                 INITIAL_CONNECT_TIMEOUT);
1645
1646         import_set_state(imp, LUSTRE_IMP_CONNECTING);
1647         req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1648         ptlrpc_request_set_replen(req);
1649
1650         RETURN(req);
1651 }
1652
1653 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1654 {
1655         struct ptlrpc_request *req;
1656         int rc = 0;
1657         ENTRY;
1658
1659         if (imp->imp_obd->obd_force)
1660                 GOTO(set_state, rc);
1661
1662         /* probably the import has been disconnected already being idle */
1663         spin_lock(&imp->imp_lock);
1664         if (imp->imp_state == LUSTRE_IMP_IDLE)
1665                 GOTO(out, rc);
1666         spin_unlock(&imp->imp_lock);
1667
1668         if (ptlrpc_import_in_recovery(imp)) {
1669                 struct l_wait_info lwi;
1670                 long timeout_jiffies;
1671                 time64_t timeout;
1672
1673                 if (AT_OFF) {
1674                         if (imp->imp_server_timeout)
1675                                 timeout = obd_timeout >> 1;
1676                         else
1677                                 timeout = obd_timeout;
1678                 } else {
1679                         u32 req_portal;
1680                         int idx;
1681
1682                         req_portal = imp->imp_client->cli_request_portal;
1683                         idx = import_at_get_index(imp, req_portal);
1684                         timeout = at_get(&imp->imp_at.iat_service_estimate[idx]);
1685                 }
1686
1687                 timeout_jiffies = cfs_time_seconds(timeout);
1688                 lwi = LWI_TIMEOUT_INTR(max_t(long, timeout_jiffies, 1),
1689                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1690                 rc = l_wait_event(imp->imp_recovery_waitq,
1691                                   !ptlrpc_import_in_recovery(imp), &lwi);
1692
1693         }
1694
1695         spin_lock(&imp->imp_lock);
1696         if (imp->imp_state != LUSTRE_IMP_FULL)
1697                 GOTO(out, rc);
1698         spin_unlock(&imp->imp_lock);
1699
1700         req = ptlrpc_disconnect_prep_req(imp);
1701         if (IS_ERR(req))
1702                 GOTO(set_state, rc = PTR_ERR(req));
1703         rc = ptlrpc_queue_wait(req);
1704         ptlrpc_req_finished(req);
1705
1706 set_state:
1707         spin_lock(&imp->imp_lock);
1708 out:
1709         if (noclose)
1710                 import_set_state_nolock(imp, LUSTRE_IMP_DISCON);
1711         else
1712                 import_set_state_nolock(imp, LUSTRE_IMP_CLOSED);
1713         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1714         spin_unlock(&imp->imp_lock);
1715
1716         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1717                 rc = 0;
1718         RETURN(rc);
1719 }
1720 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1721
1722 static void ptlrpc_reset_reqs_generation(struct obd_import *imp)
1723 {
1724         struct ptlrpc_request *old, *tmp;
1725
1726         /* tag all resendable requests generated before disconnection
1727          * notice this code is part of disconnect-at-idle path only */
1728         list_for_each_entry_safe(old, tmp, &imp->imp_delayed_list,
1729                         rq_list) {
1730                 spin_lock(&old->rq_lock);
1731                 if (old->rq_import_generation == imp->imp_generation - 1 &&
1732                     !old->rq_no_resend)
1733                         old->rq_import_generation = imp->imp_generation;
1734                 spin_unlock(&old->rq_lock);
1735         }
1736 }
1737
1738 static int ptlrpc_disconnect_idle_interpret(const struct lu_env *env,
1739                                             struct ptlrpc_request *req,
1740                                             void *args, int rc)
1741 {
1742         struct obd_import *imp = req->rq_import;
1743         int connect = 0;
1744
1745         DEBUG_REQ(D_HA, req, "inflight=%d, refcount=%d: rc = %d ",
1746                   atomic_read(&imp->imp_inflight),
1747                   atomic_read(&imp->imp_refcount), rc);
1748
1749         spin_lock(&imp->imp_lock);
1750         /* DISCONNECT reply can be late and another connection can just
1751          * be initiated. so we have to abort disconnection. */
1752         if (req->rq_import_generation == imp->imp_generation &&
1753             imp->imp_state != LUSTRE_IMP_CLOSED) {
1754                 LASSERTF(imp->imp_state == LUSTRE_IMP_CONNECTING,
1755                          "%s\n", ptlrpc_import_state_name(imp->imp_state));
1756                 imp->imp_state = LUSTRE_IMP_IDLE;
1757                 memset(&imp->imp_remote_handle, 0,
1758                        sizeof(imp->imp_remote_handle));
1759                 /* take our DISCONNECT into account */
1760                 if (atomic_read(&imp->imp_inflight) > 1) {
1761                         imp->imp_generation++;
1762                         imp->imp_initiated_at = imp->imp_generation;
1763                         import_set_state_nolock(imp, LUSTRE_IMP_NEW);
1764                         ptlrpc_reset_reqs_generation(imp);
1765                         connect = 1;
1766                 }
1767         }
1768         spin_unlock(&imp->imp_lock);
1769
1770         if (connect) {
1771                 rc = ptlrpc_connect_import(imp);
1772                 if (rc >= 0)
1773                         ptlrpc_pinger_add_import(imp);
1774         }
1775
1776         return 0;
1777 }
1778
1779 int ptlrpc_disconnect_and_idle_import(struct obd_import *imp)
1780 {
1781         struct ptlrpc_request *req;
1782         ENTRY;
1783
1784         if (imp->imp_obd->obd_force)
1785                 RETURN(0);
1786
1787         if (ptlrpc_import_in_recovery(imp))
1788                 RETURN(0);
1789
1790         spin_lock(&imp->imp_lock);
1791         if (imp->imp_state != LUSTRE_IMP_FULL) {
1792                 spin_unlock(&imp->imp_lock);
1793                 RETURN(0);
1794         }
1795         spin_unlock(&imp->imp_lock);
1796
1797         req = ptlrpc_disconnect_prep_req(imp);
1798         if (IS_ERR(req))
1799                 RETURN(PTR_ERR(req));
1800
1801         CDEBUG_LIMIT(imp->imp_idle_debug, "%s: disconnect after %llus idle\n",
1802                      imp->imp_obd->obd_name,
1803                      ktime_get_real_seconds() - imp->imp_last_reply_time);
1804         req->rq_interpret_reply = ptlrpc_disconnect_idle_interpret;
1805         ptlrpcd_add_req(req);
1806
1807         RETURN(0);
1808 }
1809 EXPORT_SYMBOL(ptlrpc_disconnect_and_idle_import);
1810
1811 void ptlrpc_cleanup_imp(struct obd_import *imp)
1812 {
1813         ENTRY;
1814
1815         spin_lock(&imp->imp_lock);
1816
1817         import_set_state_nolock(imp, LUSTRE_IMP_CLOSED);
1818         imp->imp_generation++;
1819         ptlrpc_abort_inflight(imp);
1820
1821         spin_unlock(&imp->imp_lock);
1822
1823         EXIT;
1824 }
1825
1826 /* Adaptive Timeout utils */
1827
1828 /* Update at_current with the specified value (bounded by at_min and at_max),
1829  * as well as the AT history "bins".
1830  *  - Bin into timeslices using AT_BINS bins.
1831  *  - This gives us a max of the last at_history seconds without the storage,
1832  *    but still smoothing out a return to normalcy from a slow response.
1833  *  - (E.g. remember the maximum latency in each minute of the last 4 minutes.)
1834  */
1835 int at_measured(struct adaptive_timeout *at, unsigned int val)
1836 {
1837         unsigned int old = at->at_current;
1838         time64_t now = ktime_get_real_seconds();
1839         long binlimit = max_t(long, at_history / AT_BINS, 1);
1840
1841         LASSERT(at);
1842         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1843                val, at, (long)(now - at->at_binstart), at->at_current,
1844                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1845
1846         if (val == 0)
1847                 /* 0's don't count, because we never want our timeout to
1848                    drop to 0, and because 0 could mean an error */
1849                 return 0;
1850
1851         spin_lock(&at->at_lock);
1852
1853         if (unlikely(at->at_binstart == 0)) {
1854                 /* Special case to remove default from history */
1855                 at->at_current = val;
1856                 at->at_worst_ever = val;
1857                 at->at_worst_time = now;
1858                 at->at_hist[0] = val;
1859                 at->at_binstart = now;
1860         } else if (now - at->at_binstart < binlimit ) {
1861                 /* in bin 0 */
1862                 at->at_hist[0] = max(val, at->at_hist[0]);
1863                 at->at_current = max(val, at->at_current);
1864         } else {
1865                 int i, shift;
1866                 unsigned int maxv = val;
1867
1868                 /* move bins over */
1869                 shift = (u32)(now - at->at_binstart) / binlimit;
1870                 LASSERT(shift > 0);
1871                 for(i = AT_BINS - 1; i >= 0; i--) {
1872                         if (i >= shift) {
1873                                 at->at_hist[i] = at->at_hist[i - shift];
1874                                 maxv = max(maxv, at->at_hist[i]);
1875                         } else {
1876                                 at->at_hist[i] = 0;
1877                         }
1878                 }
1879                 at->at_hist[0] = val;
1880                 at->at_current = maxv;
1881                 at->at_binstart += shift * binlimit;
1882         }
1883
1884         if (at->at_current > at->at_worst_ever) {
1885                 at->at_worst_ever = at->at_current;
1886                 at->at_worst_time = now;
1887         }
1888
1889         if (at->at_flags & AT_FLG_NOHIST)
1890                 /* Only keep last reported val; keeping the rest of the history
1891                    for proc only */
1892                 at->at_current = val;
1893
1894         if (at_max > 0)
1895                 at->at_current =  min(at->at_current, at_max);
1896         at->at_current =  max(at->at_current, at_min);
1897
1898         if (at->at_current != old)
1899                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1900                        "(val=%u) hist %u %u %u %u\n", at,
1901                        old, at->at_current, at->at_current - old, val,
1902                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1903                        at->at_hist[3]);
1904
1905         /* if we changed, report the old value */
1906         old = (at->at_current != old) ? old : 0;
1907
1908         spin_unlock(&at->at_lock);
1909         return old;
1910 }
1911
1912 /* Find the imp_at index for a given portal; assign if space available */
1913 int import_at_get_index(struct obd_import *imp, int portal)
1914 {
1915         struct imp_at *at = &imp->imp_at;
1916         int i;
1917
1918         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1919                 if (at->iat_portal[i] == portal)
1920                         return i;
1921                 if (at->iat_portal[i] == 0)
1922                         /* unused */
1923                         break;
1924         }
1925
1926         /* Not found in list, add it under a lock */
1927         spin_lock(&imp->imp_lock);
1928
1929         /* Check unused under lock */
1930         for (; i < IMP_AT_MAX_PORTALS; i++) {
1931                 if (at->iat_portal[i] == portal)
1932                         goto out;
1933                 if (at->iat_portal[i] == 0)
1934                         /* unused */
1935                         break;
1936         }
1937
1938         /* Not enough portals? */
1939         LASSERT(i < IMP_AT_MAX_PORTALS);
1940
1941         at->iat_portal[i] = portal;
1942 out:
1943         spin_unlock(&imp->imp_lock);
1944         return i;
1945 }