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