Whamcloud - gitweb
LU-10756 ptlrpc: change IMPORT_SET_* macros into real functions
[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_del(&imp->imp_conn_current->oic_item);
827         list_add(&imp->imp_conn_current->oic_item,
828                  &imp->imp_conn_list);
829         imp->imp_last_success_conn =
830                 imp->imp_conn_current->oic_last_attempt;
831
832         spin_unlock(&imp->imp_lock);
833
834         if (!warned && (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
835             (ocd->ocd_version > LUSTRE_VERSION_CODE +
836                                 LUSTRE_VERSION_OFFSET_WARN ||
837              ocd->ocd_version < LUSTRE_VERSION_CODE -
838                                 LUSTRE_VERSION_OFFSET_WARN)) {
839                 /* Sigh, some compilers do not like #ifdef in the middle
840                    of macro arguments */
841                 const char *older = "older than client. "
842                                     "Consider upgrading server";
843                 const char *newer = "newer than client. "
844                                     "Consider upgrading client";
845
846                 LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
847                               "is much %s (%s)\n",
848                               obd2cli_tgt(imp->imp_obd),
849                               OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
850                               OBD_OCD_VERSION_MINOR(ocd->ocd_version),
851                               OBD_OCD_VERSION_PATCH(ocd->ocd_version),
852                               OBD_OCD_VERSION_FIX(ocd->ocd_version),
853                               ocd->ocd_version > LUSTRE_VERSION_CODE ?
854                               newer : older, LUSTRE_VERSION_STRING);
855                 warned = true;
856         }
857
858         if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
859                 /* We sent to the server ocd_cksum_types with bits set
860                  * for algorithms we understand. The server masked off
861                  * the checksum types it doesn't support */
862                 if ((ocd->ocd_cksum_types &
863                      obd_cksum_types_supported_client()) == 0) {
864                         LCONSOLE_ERROR("The negotiation of the checksum "
865                                        "alogrithm to use with server %s "
866                                        "failed (%x/%x)\n",
867                                        obd2cli_tgt(imp->imp_obd),
868                                        ocd->ocd_cksum_types,
869                                        obd_cksum_types_supported_client());
870                         return -EPROTO;
871                 } else {
872                         cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
873                 }
874         } else {
875                 /* The server does not support OBD_CONNECT_CKSUM.
876                  * Enforce ADLER for backward compatibility*/
877                 cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
878         }
879         cli->cl_cksum_type = obd_cksum_type_select(imp->imp_obd->obd_name,
880                                                    cli->cl_supp_cksum_types);
881
882         if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE)
883                 cli->cl_max_pages_per_rpc =
884                         min(ocd->ocd_brw_size >> PAGE_SHIFT,
885                             cli->cl_max_pages_per_rpc);
886         else if (imp->imp_connect_op == MDS_CONNECT ||
887                  imp->imp_connect_op == MGS_CONNECT)
888                 cli->cl_max_pages_per_rpc = 1;
889
890         LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
891                 (cli->cl_max_pages_per_rpc > 0));
892
893         client_adjust_max_dirty(cli);
894
895         /* Update client max modify RPCs in flight with value returned
896          * by the server */
897         if (ocd->ocd_connect_flags & OBD_CONNECT_MULTIMODRPCS)
898                 cli->cl_max_mod_rpcs_in_flight = min(
899                                         cli->cl_max_mod_rpcs_in_flight,
900                                         ocd->ocd_maxmodrpcs);
901         else
902                 cli->cl_max_mod_rpcs_in_flight = 1;
903
904         /* Reset ns_connect_flags only for initial connect. It might be
905          * changed in while using FS and if we reset it in reconnect
906          * this leads to losing user settings done before such as
907          * disable lru_resize, etc. */
908         if (old_connect_flags != exp_connect_flags(exp) || init_connect) {
909                 struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
910                 __u64 changed_flags;
911
912                 changed_flags =
913                         ns->ns_connect_flags ^ ns->ns_orig_connect_flags;
914                 CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
915                              "flags: %#llx\n", imp->imp_obd->obd_name,
916                              ocd->ocd_connect_flags);
917                 ns->ns_connect_flags = (ns->ns_connect_flags & changed_flags) |
918                                       (ocd->ocd_connect_flags & ~changed_flags);
919                 ns->ns_orig_connect_flags = ocd->ocd_connect_flags;
920         }
921
922         if (ocd->ocd_connect_flags & OBD_CONNECT_AT)
923                 /* We need a per-message support flag, because
924                  * a. we don't know if the incoming connect reply
925                  *    supports AT or not (in reply_in_callback)
926                  *    until we unpack it.
927                  * b. failovered server means export and flags are gone
928                  *    (in ptlrpc_send_reply).
929                  *    Can only be set when we know AT is supported at
930                  *    both ends */
931                 imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
932         else
933                 imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
934
935         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
936
937         return 0;
938 }
939
940 /**
941  * Add all replay requests back to unreplied list before start replay,
942  * so that we can make sure the known replied XID is always increased
943  * only even if when replaying requests.
944  */
945 static void ptlrpc_prepare_replay(struct obd_import *imp)
946 {
947         struct ptlrpc_request *req;
948
949         if (imp->imp_state != LUSTRE_IMP_REPLAY ||
950             imp->imp_resend_replay)
951                 return;
952
953         /* If the server was restart during repaly, the requests may
954          * have been added to the unreplied list in former replay. */
955         spin_lock(&imp->imp_lock);
956
957         list_for_each_entry(req, &imp->imp_committed_list, rq_replay_list) {
958                 if (list_empty(&req->rq_unreplied_list))
959                         ptlrpc_add_unreplied(req);
960         }
961
962         list_for_each_entry(req, &imp->imp_replay_list, rq_replay_list) {
963                 if (list_empty(&req->rq_unreplied_list))
964                         ptlrpc_add_unreplied(req);
965         }
966
967         imp->imp_known_replied_xid = ptlrpc_known_replied_xid(imp);
968         spin_unlock(&imp->imp_lock);
969 }
970
971 /**
972  * interpret_reply callback for connect RPCs.
973  * Looks into returned status of connect operation and decides
974  * what to do with the import - i.e enter recovery, promote it to
975  * full state for normal operations of disconnect it due to an error.
976  */
977 static int ptlrpc_connect_interpret(const struct lu_env *env,
978                                     struct ptlrpc_request *request,
979                                     void *data, int rc)
980 {
981         struct ptlrpc_connect_async_args *aa = data;
982         struct obd_import *imp = request->rq_import;
983         struct lustre_handle old_hdl;
984         __u64 old_connect_flags;
985         int msg_flags;
986         struct obd_connect_data *ocd;
987         struct obd_export *exp = NULL;
988         int ret;
989         ENTRY;
990
991         spin_lock(&imp->imp_lock);
992         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
993                 imp->imp_connect_tried = 1;
994                 spin_unlock(&imp->imp_lock);
995                 RETURN(0);
996         }
997
998         imp->imp_connect_error = rc;
999         if (rc) {
1000                 struct ptlrpc_request *free_req;
1001                 struct ptlrpc_request *tmp;
1002
1003                 /* abort all delayed requests initiated connection */
1004                 list_for_each_entry_safe(free_req, tmp, &imp->imp_delayed_list,
1005                                          rq_list) {
1006                         spin_lock(&free_req->rq_lock);
1007                         if (free_req->rq_no_resend) {
1008                                 free_req->rq_err = 1;
1009                                 free_req->rq_status = -EIO;
1010                                 ptlrpc_client_wake_req(free_req);
1011                         }
1012                         spin_unlock(&free_req->rq_lock);
1013                 }
1014
1015                 /* if this reconnect to busy export - not need select new target
1016                  * for connecting*/
1017                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
1018                 spin_unlock(&imp->imp_lock);
1019                 ptlrpc_maybe_ping_import_soon(imp);
1020                 GOTO(out, rc);
1021         }
1022
1023         /* LU-7558: indicate that we are interpretting connect reply,
1024          * pltrpc_connect_import() will not try to reconnect until
1025          * interpret will finish. */
1026         imp->imp_connected = 1;
1027         spin_unlock(&imp->imp_lock);
1028
1029         LASSERT(imp->imp_conn_current);
1030
1031         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
1032
1033         ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
1034                                    RCL_SERVER);
1035         /* server replied obd_connect_data is always bigger */
1036         ocd = req_capsule_server_sized_get(&request->rq_pill,
1037                                            &RMF_CONNECT_DATA, ret);
1038
1039         if (ocd == NULL) {
1040                 CERROR("%s: no connect data from server\n",
1041                        imp->imp_obd->obd_name);
1042                 rc = -EPROTO;
1043                 GOTO(out, rc);
1044         }
1045
1046         spin_lock(&imp->imp_lock);
1047
1048         /* All imports are pingable */
1049         imp->imp_pingable = 1;
1050         imp->imp_force_reconnect = 0;
1051         imp->imp_force_verify = 0;
1052
1053         imp->imp_connect_data = *ocd;
1054
1055         CDEBUG(D_HA, "%s: connect to target with instance %u\n",
1056                imp->imp_obd->obd_name, ocd->ocd_instance);
1057         exp = class_conn2export(&imp->imp_dlm_handle);
1058
1059         spin_unlock(&imp->imp_lock);
1060
1061         if (!exp) {
1062                 /* This could happen if export is cleaned during the
1063                    connect attempt */
1064                 CERROR("%s: missing export after connect\n",
1065                        imp->imp_obd->obd_name);
1066                 GOTO(out, rc = -ENODEV);
1067         }
1068
1069         /* check that server granted subset of flags we asked for. */
1070         if ((ocd->ocd_connect_flags & imp->imp_connect_flags_orig) !=
1071             ocd->ocd_connect_flags) {
1072                 CERROR("%s: Server didn't grant requested subset of flags: "
1073                        "asked=%#llx granted=%#llx\n",
1074                        imp->imp_obd->obd_name, imp->imp_connect_flags_orig,
1075                        ocd->ocd_connect_flags);
1076                 GOTO(out, rc = -EPROTO);
1077         }
1078
1079         if ((ocd->ocd_connect_flags2 & imp->imp_connect_flags2_orig) !=
1080             ocd->ocd_connect_flags2) {
1081                 CERROR("%s: Server didn't grant requested subset of flags2: "
1082                        "asked=%#llx granted=%#llx\n",
1083                        imp->imp_obd->obd_name, imp->imp_connect_flags2_orig,
1084                        ocd->ocd_connect_flags2);
1085                 GOTO(out, rc = -EPROTO);
1086         }
1087
1088         if (!(imp->imp_connect_flags_orig & OBD_CONNECT_LIGHTWEIGHT) &&
1089             (imp->imp_connect_flags_orig & OBD_CONNECT_MDS_MDS) &&
1090             (imp->imp_connect_flags_orig & OBD_CONNECT_FID) &&
1091             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION)) {
1092                 __u32 major = OBD_OCD_VERSION_MAJOR(ocd->ocd_version);
1093                 __u32 minor = OBD_OCD_VERSION_MINOR(ocd->ocd_version);
1094                 __u32 patch = OBD_OCD_VERSION_PATCH(ocd->ocd_version);
1095
1096                 /* We do not support the MDT-MDT interoperations with
1097                  * different version MDT because of protocol changes. */
1098                 if (unlikely(major != LUSTRE_MAJOR ||
1099                              minor != LUSTRE_MINOR ||
1100                              abs(patch - LUSTRE_PATCH) > 3)) {
1101                         LCONSOLE_WARN("%s: import %p (%u.%u.%u.%u) tried the "
1102                                       "connection to different version MDT "
1103                                       "(%d.%d.%d.%d) %s\n",
1104                                       imp->imp_obd->obd_name, imp, LUSTRE_MAJOR,
1105                                       LUSTRE_MINOR, LUSTRE_PATCH, LUSTRE_FIX,
1106                                       major, minor, patch,
1107                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1108                                       imp->imp_connection->c_remote_uuid.uuid);
1109
1110                         GOTO(out, rc = -EPROTO);
1111                 }
1112         }
1113
1114         old_connect_flags = exp_connect_flags(exp);
1115         exp->exp_connect_data = *ocd;
1116         imp->imp_obd->obd_self_export->exp_connect_data = *ocd;
1117
1118         /* The net statistics after (re-)connect is not valid anymore,
1119          * because may reflect other routing, etc. */
1120         at_reinit(&imp->imp_at.iat_net_latency, 0, 0);
1121         ptlrpc_at_adj_net_latency(request,
1122                         lustre_msg_get_service_time(request->rq_repmsg));
1123
1124         /* Import flags should be updated before waking import at FULL state */
1125         rc = ptlrpc_connect_set_flags(imp, ocd, old_connect_flags, exp,
1126                                       aa->pcaa_initial_connect);
1127         class_export_put(exp);
1128         exp = NULL;
1129
1130         if (rc != 0)
1131                 GOTO(out, rc);
1132
1133         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1134
1135         if (aa->pcaa_initial_connect) {
1136                 spin_lock(&imp->imp_lock);
1137                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
1138                         imp->imp_replayable = 1;
1139                         spin_unlock(&imp->imp_lock);
1140                         CDEBUG(D_HA, "connected to replayable target: %s\n",
1141                                obd2cli_tgt(imp->imp_obd));
1142                 } else {
1143                         imp->imp_replayable = 0;
1144                         spin_unlock(&imp->imp_lock);
1145                 }
1146
1147                 /* if applies, adjust the imp->imp_msg_magic here
1148                  * according to reply flags */
1149
1150                 imp->imp_remote_handle =
1151                                 *lustre_msg_get_handle(request->rq_repmsg);
1152
1153                 /* Initial connects are allowed for clients with non-random
1154                  * uuids when servers are in recovery.  Simply signal the
1155                  * servers replay is complete and wait in REPLAY_WAIT. */
1156                 if (msg_flags & MSG_CONNECT_RECOVERING) {
1157                         CDEBUG(D_HA, "connect to %s during recovery\n",
1158                                obd2cli_tgt(imp->imp_obd));
1159                         import_set_state(imp, LUSTRE_IMP_REPLAY_LOCKS);
1160                 } else {
1161                         import_set_state(imp, LUSTRE_IMP_FULL);
1162                         ptlrpc_activate_import(imp);
1163                 }
1164
1165                 GOTO(finish, rc = 0);
1166         }
1167
1168         /* Determine what recovery state to move the import to. */
1169         if (MSG_CONNECT_RECONNECT & msg_flags) {
1170                 memset(&old_hdl, 0, sizeof(old_hdl));
1171                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
1172                             sizeof (old_hdl))) {
1173                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
1174                                       "bad handle %#llx\n",
1175                                       obd2cli_tgt(imp->imp_obd),
1176                                       imp->imp_connection->c_remote_uuid.uuid,
1177                                       imp->imp_dlm_handle.cookie);
1178                         GOTO(out, rc = -ENOTCONN);
1179                 }
1180
1181                 if (memcmp(&imp->imp_remote_handle,
1182                            lustre_msg_get_handle(request->rq_repmsg),
1183                            sizeof(imp->imp_remote_handle))) {
1184                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
1185                                 D_HA : D_WARNING;
1186
1187                         /* Bug 16611/14775: if server handle have changed,
1188                          * that means some sort of disconnection happened.
1189                          * If the server is not in recovery, that also means it
1190                          * already erased all of our state because of previous
1191                          * eviction. If it is in recovery - we are safe to
1192                          * participate since we can reestablish all of our state
1193                          * with server again */
1194                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
1195                                 CDEBUG(level,"%s@%s changed server handle from "
1196                                        "%#llx to %#llx"
1197                                        " but is still in recovery\n",
1198                                        obd2cli_tgt(imp->imp_obd),
1199                                        imp->imp_connection->c_remote_uuid.uuid,
1200                                        imp->imp_remote_handle.cookie,
1201                                        lustre_msg_get_handle(
1202                                        request->rq_repmsg)->cookie);
1203                         } else {
1204                                 LCONSOLE_WARN("Evicted from %s (at %s) "
1205                                               "after server handle changed from "
1206                                               "%#llx to %#llx\n",
1207                                               obd2cli_tgt(imp->imp_obd),
1208                                               imp->imp_connection-> \
1209                                               c_remote_uuid.uuid,
1210                                               imp->imp_remote_handle.cookie,
1211                                               lustre_msg_get_handle(
1212                                               request->rq_repmsg)->cookie);
1213                         }
1214
1215
1216                         imp->imp_remote_handle =
1217                                      *lustre_msg_get_handle(request->rq_repmsg);
1218
1219                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
1220                                 import_set_state(imp, LUSTRE_IMP_EVICTED);
1221                                 GOTO(finish, rc = 0);
1222                         }
1223
1224                 } else {
1225                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
1226                                obd2cli_tgt(imp->imp_obd),
1227                                imp->imp_connection->c_remote_uuid.uuid);
1228                 }
1229
1230                 if (imp->imp_invalid) {
1231                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
1232                                "marking evicted\n", imp->imp_obd->obd_name);
1233                         import_set_state(imp, LUSTRE_IMP_EVICTED);
1234                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
1235                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
1236                                imp->imp_obd->obd_name,
1237                                obd2cli_tgt(imp->imp_obd));
1238
1239                         spin_lock(&imp->imp_lock);
1240                         imp->imp_resend_replay = 1;
1241                         spin_unlock(&imp->imp_lock);
1242
1243                         import_set_state(imp, imp->imp_replay_state);
1244                 } else {
1245                         import_set_state(imp, LUSTRE_IMP_RECOVER);
1246                 }
1247         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
1248                 LASSERT(imp->imp_replayable);
1249                 imp->imp_remote_handle =
1250                                 *lustre_msg_get_handle(request->rq_repmsg);
1251                 imp->imp_last_replay_transno = 0;
1252                 imp->imp_replay_cursor = &imp->imp_committed_list;
1253                 import_set_state(imp, LUSTRE_IMP_REPLAY);
1254         } else if ((ocd->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) != 0 &&
1255                    !imp->imp_invalid) {
1256
1257                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_INVALIDATE);
1258                 DEBUG_REQ(D_HA, request, "%s: lwp recover",
1259                           imp->imp_obd->obd_name);
1260                 imp->imp_remote_handle =
1261                         *lustre_msg_get_handle(request->rq_repmsg);
1262                 import_set_state(imp, LUSTRE_IMP_RECOVER);
1263         } else {
1264                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
1265                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
1266                 imp->imp_remote_handle =
1267                                 *lustre_msg_get_handle(request->rq_repmsg);
1268                 import_set_state(imp, LUSTRE_IMP_EVICTED);
1269         }
1270
1271         /* Sanity checks for a reconnected import. */
1272         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
1273                 CERROR("imp_replayable flag does not match server "
1274                        "after reconnect. We should LBUG right here.\n");
1275         }
1276
1277         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
1278             lustre_msg_get_last_committed(request->rq_repmsg) <
1279             aa->pcaa_peer_committed) {
1280                 CERROR("%s went back in time (transno %lld"
1281                        " was previously committed, server now claims %lld"
1282                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
1283                        "id=9646\n",
1284                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
1285                        lustre_msg_get_last_committed(request->rq_repmsg));
1286         }
1287
1288 finish:
1289         ptlrpc_prepare_replay(imp);
1290         rc = ptlrpc_import_recovery_state_machine(imp);
1291         if (rc == -ENOTCONN) {
1292                 CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
1293                        "invalidating and reconnecting\n",
1294                        obd2cli_tgt(imp->imp_obd),
1295                        imp->imp_connection->c_remote_uuid.uuid);
1296                 ptlrpc_connect_import(imp);
1297                 spin_lock(&imp->imp_lock);
1298                 imp->imp_connected = 0;
1299                 imp->imp_connect_tried = 1;
1300                 spin_unlock(&imp->imp_lock);
1301                 RETURN(0);
1302         }
1303
1304 out:
1305         spin_lock(&imp->imp_lock);
1306         imp->imp_connected = 0;
1307         imp->imp_connect_tried = 1;
1308         spin_unlock(&imp->imp_lock);
1309
1310         if (exp != NULL)
1311                 class_export_put(exp);
1312
1313         if (rc != 0) {
1314                 import_set_state(imp, LUSTRE_IMP_DISCON);
1315                 if (rc == -EACCES) {
1316                         /*
1317                          * Give up trying to reconnect
1318                          * EACCES means client has no permission for connection
1319                          */
1320                         imp->imp_obd->obd_no_recov = 1;
1321                         ptlrpc_deactivate_import(imp);
1322                 }
1323
1324                 if (rc == -EPROTO) {
1325                         struct obd_connect_data *ocd;
1326
1327                         /* reply message might not be ready */
1328                         if (request->rq_repmsg == NULL)
1329                                 RETURN(-EPROTO);
1330
1331                         ocd = req_capsule_server_get(&request->rq_pill,
1332                                                      &RMF_CONNECT_DATA);
1333                         /* Servers are not supposed to refuse connections from
1334                          * clients based on version, only connection feature
1335                          * flags.  We should never see this from llite, but it
1336                          * may be useful for debugging in the future. */
1337                         if (ocd &&
1338                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1339                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1340                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1341                                         "(%d.%d.%d.%d)"
1342                                         " refused connection from this client "
1343                                         "with an incompatible version (%s).  "
1344                                         "Client must be recompiled\n",
1345                                         obd2cli_tgt(imp->imp_obd),
1346                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1347                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1348                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1349                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1350                                         LUSTRE_VERSION_STRING);
1351                                 ptlrpc_deactivate_import(imp);
1352                                 import_set_state(imp, LUSTRE_IMP_CLOSED);
1353                         }
1354                         RETURN(-EPROTO);
1355                 }
1356
1357                 ptlrpc_maybe_ping_import_soon(imp);
1358
1359                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1360                        obd2cli_tgt(imp->imp_obd),
1361                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1362         }
1363
1364         wake_up_all(&imp->imp_recovery_waitq);
1365         RETURN(rc);
1366 }
1367
1368 /**
1369  * interpret callback for "completed replay" RPCs.
1370  * \see signal_completed_replay
1371  */
1372 static int completed_replay_interpret(const struct lu_env *env,
1373                                       struct ptlrpc_request *req,
1374                                       void *args, int rc)
1375 {
1376         ENTRY;
1377         atomic_dec(&req->rq_import->imp_replay_inflight);
1378         if (req->rq_status == 0 && !req->rq_import->imp_vbr_failed) {
1379                 ptlrpc_import_recovery_state_machine(req->rq_import);
1380         } else {
1381                 if (req->rq_import->imp_vbr_failed) {
1382                         CDEBUG(D_WARNING,
1383                                "%s: version recovery fails, reconnecting\n",
1384                                req->rq_import->imp_obd->obd_name);
1385                 } else {
1386                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1387                                      "reconnecting\n",
1388                                req->rq_import->imp_obd->obd_name,
1389                                req->rq_status);
1390                 }
1391                 ptlrpc_connect_import(req->rq_import);
1392         }
1393
1394         RETURN(0);
1395 }
1396
1397 /**
1398  * Let server know that we have no requests to replay anymore.
1399  * Achieved by just sending a PING request
1400  */
1401 static int signal_completed_replay(struct obd_import *imp)
1402 {
1403         struct ptlrpc_request *req;
1404         ENTRY;
1405
1406         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1407                 RETURN(0);
1408
1409         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1410         atomic_inc(&imp->imp_replay_inflight);
1411
1412         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1413                                         OBD_PING);
1414         if (req == NULL) {
1415                 atomic_dec(&imp->imp_replay_inflight);
1416                 RETURN(-ENOMEM);
1417         }
1418
1419         ptlrpc_request_set_replen(req);
1420         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1421         lustre_msg_add_flags(req->rq_reqmsg,
1422                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1423         if (AT_OFF)
1424                 req->rq_timeout *= 3;
1425         req->rq_interpret_reply = completed_replay_interpret;
1426
1427         ptlrpcd_add_req(req);
1428         RETURN(0);
1429 }
1430
1431 /**
1432  * In kernel code all import invalidation happens in its own
1433  * separate thread, so that whatever application happened to encounter
1434  * a problem could still be killed or otherwise continue
1435  */
1436 static int ptlrpc_invalidate_import_thread(void *data)
1437 {
1438         struct obd_import *imp = data;
1439
1440         ENTRY;
1441
1442         unshare_fs_struct();
1443
1444         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1445                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1446                imp->imp_connection->c_remote_uuid.uuid);
1447
1448         ptlrpc_invalidate_import(imp);
1449
1450         if (obd_dump_on_eviction) {
1451                 CERROR("dump the log upon eviction\n");
1452                 libcfs_debug_dumplog();
1453         }
1454
1455         import_set_state(imp, LUSTRE_IMP_RECOVER);
1456         ptlrpc_import_recovery_state_machine(imp);
1457
1458         class_import_put(imp);
1459         RETURN(0);
1460 }
1461
1462 /**
1463  * This is the state machine for client-side recovery on import.
1464  *
1465  * Typicaly we have two possibly paths. If we came to server and it is not
1466  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1467  * state and reconnect from scratch.
1468  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1469  * We go through our list of requests to replay and send them to server one by
1470  * one.
1471  * After sending all request from the list we change import state to
1472  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1473  * and also all the locks we don't yet have and wait for server to grant us.
1474  * After that we send a special "replay completed" request and change import
1475  * state to IMP_REPLAY_WAIT.
1476  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1477  * state and resend all requests from sending list.
1478  * After that we promote import to FULL state and send all delayed requests
1479  * and import is fully operational after that.
1480  *
1481  */
1482 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1483 {
1484         int rc = 0;
1485         int inflight;
1486         char *target_start;
1487         int target_len;
1488
1489         ENTRY;
1490         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1491                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1492                           &target_start, &target_len);
1493                 /* Don't care about MGC eviction */
1494                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1495                            LUSTRE_MGC_NAME) != 0) {
1496                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted "
1497                                            "by %.*s; in progress operations "
1498                                            "using this service will fail.\n",
1499                                            imp->imp_obd->obd_name, target_len,
1500                                            target_start);
1501                         LASSERTF(!obd_lbug_on_eviction, "LBUG upon eviction");
1502                 }
1503                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1504                        obd2cli_tgt(imp->imp_obd),
1505                        imp->imp_connection->c_remote_uuid.uuid);
1506                 /* reset vbr_failed flag upon eviction */
1507                 spin_lock(&imp->imp_lock);
1508                 imp->imp_vbr_failed = 0;
1509                 spin_unlock(&imp->imp_lock);
1510
1511                 {
1512                 struct task_struct *task;
1513                 /* bug 17802:  XXX client_disconnect_export vs connect request
1514                  * race. if client is evicted at this time then we start
1515                  * invalidate thread without reference to import and import can
1516                  * be freed at same time. */
1517                 class_import_get(imp);
1518                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1519                                      "ll_imp_inval");
1520                 if (IS_ERR(task)) {
1521                         class_import_put(imp);
1522                         CERROR("error starting invalidate thread: %d\n", rc);
1523                         rc = PTR_ERR(task);
1524                 } else {
1525                         rc = 0;
1526                 }
1527                 RETURN(rc);
1528                 }
1529         }
1530
1531         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1532                 CDEBUG(D_HA, "replay requested by %s\n",
1533                        obd2cli_tgt(imp->imp_obd));
1534                 rc = ptlrpc_replay_next(imp, &inflight);
1535                 if (inflight == 0 &&
1536                     atomic_read(&imp->imp_replay_inflight) == 0) {
1537                         import_set_state(imp, LUSTRE_IMP_REPLAY_LOCKS);
1538                         rc = ldlm_replay_locks(imp);
1539                         if (rc)
1540                                 GOTO(out, rc);
1541                 }
1542                 rc = 0;
1543         }
1544
1545         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1546                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1547                         import_set_state(imp, LUSTRE_IMP_REPLAY_WAIT);
1548                         rc = signal_completed_replay(imp);
1549                         if (rc)
1550                                 GOTO(out, rc);
1551                 }
1552         }
1553
1554         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1555                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1556                         import_set_state(imp, LUSTRE_IMP_RECOVER);
1557                 }
1558         }
1559
1560         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1561                 struct ptlrpc_connection *conn = imp->imp_connection;
1562
1563                 rc = ptlrpc_resend(imp);
1564                 if (rc)
1565                         GOTO(out, rc);
1566                 import_set_state(imp, LUSTRE_IMP_FULL);
1567                 ptlrpc_activate_import(imp);
1568
1569                 LCONSOLE_INFO("%s: Connection restored to %s (at %s)\n",
1570                               imp->imp_obd->obd_name,
1571                               obd_uuid2str(&conn->c_remote_uuid),
1572                               obd_import_nid2str(imp));
1573         }
1574
1575         if (imp->imp_state == LUSTRE_IMP_FULL) {
1576                 wake_up_all(&imp->imp_recovery_waitq);
1577                 ptlrpc_wake_delayed(imp);
1578         }
1579
1580 out:
1581         RETURN(rc);
1582 }
1583
1584 static struct ptlrpc_request *ptlrpc_disconnect_prep_req(struct obd_import *imp)
1585 {
1586         struct ptlrpc_request *req;
1587         int rq_opc, rc = 0;
1588         ENTRY;
1589
1590         switch (imp->imp_connect_op) {
1591         case OST_CONNECT:
1592                 rq_opc = OST_DISCONNECT;
1593                 break;
1594         case MDS_CONNECT:
1595                 rq_opc = MDS_DISCONNECT;
1596                 break;
1597         case MGS_CONNECT:
1598                 rq_opc = MGS_DISCONNECT;
1599                 break;
1600         default:
1601                 rc = -EINVAL;
1602                 CERROR("%s: don't know how to disconnect from %s "
1603                        "(connect_op %d): rc = %d\n",
1604                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1605                        imp->imp_connect_op, rc);
1606                 RETURN(ERR_PTR(rc));
1607         }
1608
1609         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1610                                         LUSTRE_OBD_VERSION, rq_opc);
1611         if (req == NULL)
1612                 RETURN(NULL);
1613
1614         /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1615          * it fails.  We can get through the above with a down server
1616          * if the client doesn't know the server is gone yet. */
1617         req->rq_no_resend = 1;
1618
1619         /* We want client umounts to happen quickly, no matter the
1620            server state... */
1621         req->rq_timeout = min_t(int, req->rq_timeout,
1622                                 INITIAL_CONNECT_TIMEOUT);
1623
1624         import_set_state(imp, LUSTRE_IMP_CONNECTING);
1625         req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1626         ptlrpc_request_set_replen(req);
1627
1628         RETURN(req);
1629 }
1630
1631 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1632 {
1633         struct ptlrpc_request *req;
1634         int rc = 0;
1635         ENTRY;
1636
1637         if (imp->imp_obd->obd_force)
1638                 GOTO(set_state, rc);
1639
1640         /* probably the import has been disconnected already being idle */
1641         spin_lock(&imp->imp_lock);
1642         if (imp->imp_state == LUSTRE_IMP_IDLE)
1643                 GOTO(out, rc);
1644         spin_unlock(&imp->imp_lock);
1645
1646         if (ptlrpc_import_in_recovery(imp)) {
1647                 struct l_wait_info lwi;
1648                 long timeout_jiffies;
1649                 time64_t timeout;
1650
1651                 if (AT_OFF) {
1652                         if (imp->imp_server_timeout)
1653                                 timeout = obd_timeout >> 1;
1654                         else
1655                                 timeout = obd_timeout;
1656                 } else {
1657                         u32 req_portal;
1658                         int idx;
1659
1660                         req_portal = imp->imp_client->cli_request_portal;
1661                         idx = import_at_get_index(imp, req_portal);
1662                         timeout = at_get(&imp->imp_at.iat_service_estimate[idx]);
1663                 }
1664
1665                 timeout_jiffies = cfs_time_seconds(timeout);
1666                 lwi = LWI_TIMEOUT_INTR(max_t(long, timeout_jiffies, 1),
1667                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1668                 rc = l_wait_event(imp->imp_recovery_waitq,
1669                                   !ptlrpc_import_in_recovery(imp), &lwi);
1670
1671         }
1672
1673         spin_lock(&imp->imp_lock);
1674         if (imp->imp_state != LUSTRE_IMP_FULL)
1675                 GOTO(out, rc);
1676         spin_unlock(&imp->imp_lock);
1677
1678         req = ptlrpc_disconnect_prep_req(imp);
1679         if (IS_ERR(req))
1680                 GOTO(set_state, rc = PTR_ERR(req));
1681         rc = ptlrpc_queue_wait(req);
1682         ptlrpc_req_finished(req);
1683
1684 set_state:
1685         spin_lock(&imp->imp_lock);
1686 out:
1687         if (noclose)
1688                 import_set_state_nolock(imp, LUSTRE_IMP_DISCON);
1689         else
1690                 import_set_state_nolock(imp, LUSTRE_IMP_CLOSED);
1691         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1692         spin_unlock(&imp->imp_lock);
1693
1694         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1695                 rc = 0;
1696         RETURN(rc);
1697 }
1698 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1699
1700 static void ptlrpc_reset_reqs_generation(struct obd_import *imp)
1701 {
1702         struct ptlrpc_request *old, *tmp;
1703
1704         /* tag all resendable requests generated before disconnection
1705          * notice this code is part of disconnect-at-idle path only */
1706         list_for_each_entry_safe(old, tmp, &imp->imp_delayed_list,
1707                         rq_list) {
1708                 spin_lock(&old->rq_lock);
1709                 if (old->rq_import_generation == imp->imp_generation - 1 &&
1710                     !old->rq_no_resend)
1711                         old->rq_import_generation = imp->imp_generation;
1712                 spin_unlock(&old->rq_lock);
1713         }
1714 }
1715
1716 static int ptlrpc_disconnect_idle_interpret(const struct lu_env *env,
1717                                             struct ptlrpc_request *req,
1718                                             void *args, int rc)
1719 {
1720         struct obd_import *imp = req->rq_import;
1721         int connect = 0;
1722
1723         DEBUG_REQ(D_HA, req, "inflight=%d, refcount=%d: rc = %d ",
1724                   atomic_read(&imp->imp_inflight),
1725                   atomic_read(&imp->imp_refcount), rc);
1726
1727         spin_lock(&imp->imp_lock);
1728         /* DISCONNECT reply can be late and another connection can just
1729          * be initiated. so we have to abort disconnection. */
1730         if (req->rq_import_generation == imp->imp_generation &&
1731             imp->imp_state != LUSTRE_IMP_CLOSED) {
1732                 LASSERTF(imp->imp_state == LUSTRE_IMP_CONNECTING,
1733                          "%s\n", ptlrpc_import_state_name(imp->imp_state));
1734                 imp->imp_state = LUSTRE_IMP_IDLE;
1735                 memset(&imp->imp_remote_handle, 0,
1736                        sizeof(imp->imp_remote_handle));
1737                 /* take our DISCONNECT into account */
1738                 if (atomic_read(&imp->imp_inflight) > 1) {
1739                         imp->imp_generation++;
1740                         imp->imp_initiated_at = imp->imp_generation;
1741                         import_set_state_nolock(imp, LUSTRE_IMP_NEW);
1742                         ptlrpc_reset_reqs_generation(imp);
1743                         connect = 1;
1744                 }
1745         }
1746         spin_unlock(&imp->imp_lock);
1747
1748         if (connect) {
1749                 rc = ptlrpc_connect_import(imp);
1750                 if (rc >= 0)
1751                         ptlrpc_pinger_add_import(imp);
1752         }
1753
1754         return 0;
1755 }
1756
1757 int ptlrpc_disconnect_and_idle_import(struct obd_import *imp)
1758 {
1759         struct ptlrpc_request *req;
1760         ENTRY;
1761
1762         if (imp->imp_obd->obd_force)
1763                 RETURN(0);
1764
1765         if (ptlrpc_import_in_recovery(imp))
1766                 RETURN(0);
1767
1768         spin_lock(&imp->imp_lock);
1769         if (imp->imp_state != LUSTRE_IMP_FULL) {
1770                 spin_unlock(&imp->imp_lock);
1771                 RETURN(0);
1772         }
1773         spin_unlock(&imp->imp_lock);
1774
1775         req = ptlrpc_disconnect_prep_req(imp);
1776         if (IS_ERR(req))
1777                 RETURN(PTR_ERR(req));
1778
1779         CDEBUG_LIMIT(imp->imp_idle_debug, "%s: disconnect after %llus idle\n",
1780                      imp->imp_obd->obd_name,
1781                      ktime_get_real_seconds() - imp->imp_last_reply_time);
1782         req->rq_interpret_reply = ptlrpc_disconnect_idle_interpret;
1783         ptlrpcd_add_req(req);
1784
1785         RETURN(0);
1786 }
1787 EXPORT_SYMBOL(ptlrpc_disconnect_and_idle_import);
1788
1789 void ptlrpc_cleanup_imp(struct obd_import *imp)
1790 {
1791         ENTRY;
1792
1793         spin_lock(&imp->imp_lock);
1794         import_set_state_nolock(imp, LUSTRE_IMP_CLOSED);
1795         imp->imp_generation++;
1796         spin_unlock(&imp->imp_lock);
1797         ptlrpc_abort_inflight(imp);
1798
1799         EXIT;
1800 }
1801
1802 /* Adaptive Timeout utils */
1803
1804 /* Update at_current with the specified value (bounded by at_min and at_max),
1805  * as well as the AT history "bins".
1806  *  - Bin into timeslices using AT_BINS bins.
1807  *  - This gives us a max of the last at_history seconds without the storage,
1808  *    but still smoothing out a return to normalcy from a slow response.
1809  *  - (E.g. remember the maximum latency in each minute of the last 4 minutes.)
1810  */
1811 int at_measured(struct adaptive_timeout *at, unsigned int val)
1812 {
1813         unsigned int old = at->at_current;
1814         time64_t now = ktime_get_real_seconds();
1815         long binlimit = max_t(long, at_history / AT_BINS, 1);
1816
1817         LASSERT(at);
1818         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1819                val, at, (long)(now - at->at_binstart), at->at_current,
1820                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1821
1822         if (val == 0)
1823                 /* 0's don't count, because we never want our timeout to
1824                    drop to 0, and because 0 could mean an error */
1825                 return 0;
1826
1827         spin_lock(&at->at_lock);
1828
1829         if (unlikely(at->at_binstart == 0)) {
1830                 /* Special case to remove default from history */
1831                 at->at_current = val;
1832                 at->at_worst_ever = val;
1833                 at->at_worst_time = now;
1834                 at->at_hist[0] = val;
1835                 at->at_binstart = now;
1836         } else if (now - at->at_binstart < binlimit ) {
1837                 /* in bin 0 */
1838                 at->at_hist[0] = max(val, at->at_hist[0]);
1839                 at->at_current = max(val, at->at_current);
1840         } else {
1841                 int i, shift;
1842                 unsigned int maxv = val;
1843
1844                 /* move bins over */
1845                 shift = (u32)(now - at->at_binstart) / binlimit;
1846                 LASSERT(shift > 0);
1847                 for(i = AT_BINS - 1; i >= 0; i--) {
1848                         if (i >= shift) {
1849                                 at->at_hist[i] = at->at_hist[i - shift];
1850                                 maxv = max(maxv, at->at_hist[i]);
1851                         } else {
1852                                 at->at_hist[i] = 0;
1853                         }
1854                 }
1855                 at->at_hist[0] = val;
1856                 at->at_current = maxv;
1857                 at->at_binstart += shift * binlimit;
1858         }
1859
1860         if (at->at_current > at->at_worst_ever) {
1861                 at->at_worst_ever = at->at_current;
1862                 at->at_worst_time = now;
1863         }
1864
1865         if (at->at_flags & AT_FLG_NOHIST)
1866                 /* Only keep last reported val; keeping the rest of the history
1867                    for proc only */
1868                 at->at_current = val;
1869
1870         if (at_max > 0)
1871                 at->at_current =  min(at->at_current, at_max);
1872         at->at_current =  max(at->at_current, at_min);
1873
1874         if (at->at_current != old)
1875                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1876                        "(val=%u) hist %u %u %u %u\n", at,
1877                        old, at->at_current, at->at_current - old, val,
1878                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1879                        at->at_hist[3]);
1880
1881         /* if we changed, report the old value */
1882         old = (at->at_current != old) ? old : 0;
1883
1884         spin_unlock(&at->at_lock);
1885         return old;
1886 }
1887
1888 /* Find the imp_at index for a given portal; assign if space available */
1889 int import_at_get_index(struct obd_import *imp, int portal)
1890 {
1891         struct imp_at *at = &imp->imp_at;
1892         int i;
1893
1894         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1895                 if (at->iat_portal[i] == portal)
1896                         return i;
1897                 if (at->iat_portal[i] == 0)
1898                         /* unused */
1899                         break;
1900         }
1901
1902         /* Not found in list, add it under a lock */
1903         spin_lock(&imp->imp_lock);
1904
1905         /* Check unused under lock */
1906         for (; i < IMP_AT_MAX_PORTALS; i++) {
1907                 if (at->iat_portal[i] == portal)
1908                         goto out;
1909                 if (at->iat_portal[i] == 0)
1910                         /* unused */
1911                         break;
1912         }
1913
1914         /* Not enough portals? */
1915         LASSERT(i < IMP_AT_MAX_PORTALS);
1916
1917         at->iat_portal[i] = portal;
1918 out:
1919         spin_unlock(&imp->imp_lock);
1920         return i;
1921 }