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