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