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