GNU Linux-libre 4.9.301-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 "../include/obd_support.h"
40 #include "../include/lustre_ha.h"
41 #include "../include/lustre_net.h"
42 #include "../include/lustre_import.h"
43 #include "../include/lustre_export.h"
44 #include "../include/obd.h"
45 #include "../include/obd_cksum.h"
46 #include "../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 static 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
412 void ptlrpc_fail_import(struct obd_import *imp, __u32 conn_cnt)
413 {
414         LASSERT(!imp->imp_dlm_fake);
415
416         if (ptlrpc_set_import_discon(imp, conn_cnt)) {
417                 if (!imp->imp_replayable) {
418                         CDEBUG(D_HA, "import %s@%s for %s not replayable, auto-deactivating\n",
419                                obd2cli_tgt(imp->imp_obd),
420                                imp->imp_connection->c_remote_uuid.uuid,
421                                imp->imp_obd->obd_name);
422                         ptlrpc_deactivate_import(imp);
423                 }
424
425                 ptlrpc_pinger_force(imp);
426         }
427 }
428
429 int ptlrpc_reconnect_import(struct obd_import *imp)
430 {
431         struct l_wait_info lwi;
432         int secs = cfs_time_seconds(obd_timeout);
433         int rc;
434
435         ptlrpc_pinger_force(imp);
436
437         CDEBUG(D_HA, "%s: recovery started, waiting %u seconds\n",
438                obd2cli_tgt(imp->imp_obd), secs);
439
440         lwi = LWI_TIMEOUT(secs, NULL, NULL);
441         rc = l_wait_event(imp->imp_recovery_waitq,
442                           !ptlrpc_import_in_recovery(imp), &lwi);
443         CDEBUG(D_HA, "%s: recovery finished s:%s\n", obd2cli_tgt(imp->imp_obd),
444                ptlrpc_import_state_name(imp->imp_state));
445         return rc;
446 }
447 EXPORT_SYMBOL(ptlrpc_reconnect_import);
448
449 /**
450  * Connection on import \a imp is changed to another one (if more than one is
451  * present). We typically chose connection that we have not tried to connect to
452  * the longest
453  */
454 static int import_select_connection(struct obd_import *imp)
455 {
456         struct obd_import_conn *imp_conn = NULL, *conn;
457         struct obd_export *dlmexp;
458         char *target_start;
459         int target_len, tried_all = 1;
460
461         spin_lock(&imp->imp_lock);
462
463         if (list_empty(&imp->imp_conn_list)) {
464                 CERROR("%s: no connections available\n",
465                        imp->imp_obd->obd_name);
466                 spin_unlock(&imp->imp_lock);
467                 return -EINVAL;
468         }
469
470         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
471                 CDEBUG(D_HA, "%s: connect to NID %s last attempt %llu\n",
472                        imp->imp_obd->obd_name,
473                        libcfs_nid2str(conn->oic_conn->c_peer.nid),
474                        conn->oic_last_attempt);
475
476                 /* If we have not tried this connection since
477                  * the last successful attempt, go with this one
478                  */
479                 if ((conn->oic_last_attempt == 0) ||
480                     cfs_time_beforeq_64(conn->oic_last_attempt,
481                                         imp->imp_last_success_conn)) {
482                         imp_conn = conn;
483                         tried_all = 0;
484                         break;
485                 }
486
487                 /* If all of the connections have already been tried
488                  * since the last successful connection; just choose the
489                  * least recently used
490                  */
491                 if (!imp_conn)
492                         imp_conn = conn;
493                 else if (cfs_time_before_64(conn->oic_last_attempt,
494                                             imp_conn->oic_last_attempt))
495                         imp_conn = conn;
496         }
497
498         /* if not found, simply choose the current one */
499         if (!imp_conn || imp->imp_force_reconnect) {
500                 LASSERT(imp->imp_conn_current);
501                 imp_conn = imp->imp_conn_current;
502                 tried_all = 0;
503         }
504         LASSERT(imp_conn->oic_conn);
505
506         /* If we've tried everything, and we're back to the beginning of the
507          * list, increase our timeout and try again. It will be reset when
508          * we do finally connect. (FIXME: really we should wait for all network
509          * state associated with the last connection attempt to drain before
510          * trying to reconnect on it.)
511          */
512         if (tried_all && (imp->imp_conn_list.next == &imp_conn->oic_item)) {
513                 struct adaptive_timeout *at = &imp->imp_at.iat_net_latency;
514
515                 if (at_get(at) < CONNECTION_SWITCH_MAX) {
516                         at_measured(at, at_get(at) + CONNECTION_SWITCH_INC);
517                         if (at_get(at) > CONNECTION_SWITCH_MAX)
518                                 at_reset(at, CONNECTION_SWITCH_MAX);
519                 }
520                 LASSERT(imp_conn->oic_last_attempt);
521                 CDEBUG(D_HA, "%s: tried all connections, increasing latency to %ds\n",
522                        imp->imp_obd->obd_name, at_get(at));
523         }
524
525         imp_conn->oic_last_attempt = cfs_time_current_64();
526
527         /* switch connection, don't mind if it's same as the current one */
528         ptlrpc_connection_put(imp->imp_connection);
529         imp->imp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
530
531         dlmexp = class_conn2export(&imp->imp_dlm_handle);
532         ptlrpc_connection_put(dlmexp->exp_connection);
533         dlmexp->exp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
534         class_export_put(dlmexp);
535
536         if (imp->imp_conn_current != imp_conn) {
537                 if (imp->imp_conn_current) {
538                         deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
539                                   &target_start, &target_len);
540
541                         CDEBUG(D_HA, "%s: Connection changing to %.*s (at %s)\n",
542                                imp->imp_obd->obd_name,
543                                target_len, target_start,
544                                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
545                 }
546
547                 imp->imp_conn_current = imp_conn;
548         }
549
550         CDEBUG(D_HA, "%s: import %p using connection %s/%s\n",
551                imp->imp_obd->obd_name, imp, imp_conn->oic_uuid.uuid,
552                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
553
554         spin_unlock(&imp->imp_lock);
555
556         return 0;
557 }
558
559 /*
560  * must be called under imp_lock
561  */
562 static int ptlrpc_first_transno(struct obd_import *imp, __u64 *transno)
563 {
564         struct ptlrpc_request *req;
565         struct list_head *tmp;
566
567         /* The requests in committed_list always have smaller transnos than
568          * the requests in replay_list
569          */
570         if (!list_empty(&imp->imp_committed_list)) {
571                 tmp = imp->imp_committed_list.next;
572                 req = list_entry(tmp, struct ptlrpc_request, rq_replay_list);
573                 *transno = req->rq_transno;
574                 if (req->rq_transno == 0) {
575                         DEBUG_REQ(D_ERROR, req,
576                                   "zero transno in committed_list");
577                         LBUG();
578                 }
579                 return 1;
580         }
581         if (!list_empty(&imp->imp_replay_list)) {
582                 tmp = imp->imp_replay_list.next;
583                 req = list_entry(tmp, struct ptlrpc_request, rq_replay_list);
584                 *transno = req->rq_transno;
585                 if (req->rq_transno == 0) {
586                         DEBUG_REQ(D_ERROR, req, "zero transno in replay_list");
587                         LBUG();
588                 }
589                 return 1;
590         }
591         return 0;
592 }
593
594 /**
595  * Attempt to (re)connect import \a imp. This includes all preparations,
596  * initializing CONNECT RPC request and passing it to ptlrpcd for
597  * actual sending.
598  * Returns 0 on success or error code.
599  */
600 int ptlrpc_connect_import(struct obd_import *imp)
601 {
602         struct obd_device *obd = imp->imp_obd;
603         int initial_connect = 0;
604         int set_transno = 0;
605         __u64 committed_before_reconnect = 0;
606         struct ptlrpc_request *request;
607         char *bufs[] = { NULL,
608                          obd2cli_tgt(imp->imp_obd),
609                          obd->obd_uuid.uuid,
610                          (char *)&imp->imp_dlm_handle,
611                          (char *)&imp->imp_connect_data };
612         struct ptlrpc_connect_async_args *aa;
613         int rc;
614
615         spin_lock(&imp->imp_lock);
616         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
617                 spin_unlock(&imp->imp_lock);
618                 CERROR("can't connect to a closed import\n");
619                 return -EINVAL;
620         } else if (imp->imp_state == LUSTRE_IMP_FULL) {
621                 spin_unlock(&imp->imp_lock);
622                 CERROR("already connected\n");
623                 return 0;
624         } else if (imp->imp_state == LUSTRE_IMP_CONNECTING) {
625                 spin_unlock(&imp->imp_lock);
626                 CERROR("already connecting\n");
627                 return -EALREADY;
628         }
629
630         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CONNECTING);
631
632         imp->imp_conn_cnt++;
633         imp->imp_resend_replay = 0;
634
635         if (!lustre_handle_is_used(&imp->imp_remote_handle))
636                 initial_connect = 1;
637         else
638                 committed_before_reconnect = imp->imp_peer_committed_transno;
639
640         set_transno = ptlrpc_first_transno(imp,
641                                            &imp->imp_connect_data.ocd_transno);
642         spin_unlock(&imp->imp_lock);
643
644         rc = import_select_connection(imp);
645         if (rc)
646                 goto out;
647
648         rc = sptlrpc_import_sec_adapt(imp, NULL, NULL);
649         if (rc)
650                 goto out;
651
652         /* Reset connect flags to the originally requested flags, in case
653          * the server is updated on-the-fly we will get the new features.
654          */
655         imp->imp_connect_data.ocd_connect_flags = imp->imp_connect_flags_orig;
656         /* Reset ocd_version each time so the server knows the exact versions */
657         imp->imp_connect_data.ocd_version = LUSTRE_VERSION_CODE;
658         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
659         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
660
661         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
662                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
663         if (rc)
664                 goto out;
665
666         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
667         if (!request) {
668                 rc = -ENOMEM;
669                 goto out;
670         }
671
672         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
673                                       imp->imp_connect_op, bufs, NULL);
674         if (rc) {
675                 ptlrpc_request_free(request);
676                 goto out;
677         }
678
679         /* Report the rpc service time to the server so that it knows how long
680          * to wait for clients to join recovery
681          */
682         lustre_msg_set_service_time(request->rq_reqmsg,
683                                     at_timeout2est(request->rq_timeout));
684
685         /* The amount of time we give the server to process the connect req.
686          * import_select_connection will increase the net latency on
687          * repeated reconnect attempts to cover slow networks.
688          * We override/ignore the server rpc completion estimate here,
689          * which may be large if this is a reconnect attempt
690          */
691         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
692         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
693
694         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
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         CLASSERT(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          * Reset ns_connect_flags only for initial connect. It might be
863          * changed in while using FS and if we reset it in reconnect
864          * this leads to losing user settings done before such as
865          * disable lru_resize, etc.
866          */
867         if (old_connect_flags != exp_connect_flags(exp) || init_connect) {
868                 CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server flags: %#llx\n",
869                        imp->imp_obd->obd_name, ocd->ocd_connect_flags);
870                 imp->imp_obd->obd_namespace->ns_connect_flags =
871                         ocd->ocd_connect_flags;
872                 imp->imp_obd->obd_namespace->ns_orig_connect_flags =
873                         ocd->ocd_connect_flags;
874         }
875
876         if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
877             (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
878                 /*
879                  * We need a per-message support flag, because
880                  * a. we don't know if the incoming connect reply
881                  *    supports AT or not (in reply_in_callback)
882                  *    until we unpack it.
883                  * b. failovered server means export and flags are gone
884                  *    (in ptlrpc_send_reply).
885                  *    Can only be set when we know AT is supported at
886                  *    both ends
887                  */
888                 imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
889         else
890                 imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
891
892         if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
893             (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
894                 imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
895         else
896                 imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
897
898         return 0;
899 }
900
901 /**
902  * interpret_reply callback for connect RPCs.
903  * Looks into returned status of connect operation and decides
904  * what to do with the import - i.e enter recovery, promote it to
905  * full state for normal operations of disconnect it due to an error.
906  */
907 static int ptlrpc_connect_interpret(const struct lu_env *env,
908                                     struct ptlrpc_request *request,
909                                     void *data, int rc)
910 {
911         struct ptlrpc_connect_async_args *aa = data;
912         struct obd_import *imp = request->rq_import;
913         struct lustre_handle old_hdl;
914         __u64 old_connect_flags;
915         int msg_flags;
916         struct obd_connect_data *ocd;
917         struct obd_export *exp;
918         int ret;
919
920         spin_lock(&imp->imp_lock);
921         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
922                 imp->imp_connect_tried = 1;
923                 spin_unlock(&imp->imp_lock);
924                 return 0;
925         }
926
927         if (rc) {
928                 /* if this reconnect to busy export - not need select new target
929                  * for connecting
930                  */
931                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
932                 spin_unlock(&imp->imp_lock);
933                 ptlrpc_maybe_ping_import_soon(imp);
934                 goto out;
935         }
936         spin_unlock(&imp->imp_lock);
937
938         LASSERT(imp->imp_conn_current);
939
940         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
941
942         ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
943                                    RCL_SERVER);
944         /* server replied obd_connect_data is always bigger */
945         ocd = req_capsule_server_sized_get(&request->rq_pill,
946                                            &RMF_CONNECT_DATA, ret);
947
948         if (!ocd) {
949                 CERROR("%s: no connect data from server\n",
950                        imp->imp_obd->obd_name);
951                 rc = -EPROTO;
952                 goto out;
953         }
954
955         spin_lock(&imp->imp_lock);
956
957         /* All imports are pingable */
958         imp->imp_pingable = 1;
959         imp->imp_force_reconnect = 0;
960         imp->imp_force_verify = 0;
961
962         imp->imp_connect_data = *ocd;
963
964         CDEBUG(D_HA, "%s: connect to target with instance %u\n",
965                imp->imp_obd->obd_name, ocd->ocd_instance);
966         exp = class_conn2export(&imp->imp_dlm_handle);
967
968         spin_unlock(&imp->imp_lock);
969
970         /* check that server granted subset of flags we asked for. */
971         if ((ocd->ocd_connect_flags & imp->imp_connect_flags_orig) !=
972             ocd->ocd_connect_flags) {
973                 CERROR("%s: Server didn't granted asked subset of flags: asked=%#llx grranted=%#llx\n",
974                        imp->imp_obd->obd_name, imp->imp_connect_flags_orig,
975                        ocd->ocd_connect_flags);
976                 rc = -EPROTO;
977                 goto out;
978         }
979
980         if (!exp) {
981                 /* This could happen if export is cleaned during the
982                  * connect attempt
983                  */
984                 CERROR("%s: missing export after connect\n",
985                        imp->imp_obd->obd_name);
986                 rc = -ENODEV;
987                 goto out;
988         }
989         old_connect_flags = exp_connect_flags(exp);
990         exp->exp_connect_data = *ocd;
991         imp->imp_obd->obd_self_export->exp_connect_data = *ocd;
992
993         /*
994          * The net statistics after (re-)connect is not valid anymore,
995          * because may reflect other routing, etc.
996          */
997         at_init(&imp->imp_at.iat_net_latency, 0, 0);
998         ptlrpc_at_adj_net_latency(request,
999                                   lustre_msg_get_service_time(request->rq_repmsg));
1000
1001         /* Import flags should be updated before waking import at FULL state */
1002         rc = ptlrpc_connect_set_flags(imp, ocd, old_connect_flags, exp,
1003                                       aa->pcaa_initial_connect);
1004         class_export_put(exp);
1005         if (rc)
1006                 goto out;
1007
1008         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1009
1010         if (aa->pcaa_initial_connect) {
1011                 spin_lock(&imp->imp_lock);
1012                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
1013                         imp->imp_replayable = 1;
1014                         spin_unlock(&imp->imp_lock);
1015                         CDEBUG(D_HA, "connected to replayable target: %s\n",
1016                                obd2cli_tgt(imp->imp_obd));
1017                 } else {
1018                         imp->imp_replayable = 0;
1019                         spin_unlock(&imp->imp_lock);
1020                 }
1021
1022                 /* if applies, adjust the imp->imp_msg_magic here
1023                  * according to reply flags
1024                  */
1025
1026                 imp->imp_remote_handle =
1027                                 *lustre_msg_get_handle(request->rq_repmsg);
1028
1029                 /* Initial connects are allowed for clients with non-random
1030                  * uuids when servers are in recovery.  Simply signal the
1031                  * servers replay is complete and wait in REPLAY_WAIT.
1032                  */
1033                 if (msg_flags & MSG_CONNECT_RECOVERING) {
1034                         CDEBUG(D_HA, "connect to %s during recovery\n",
1035                                obd2cli_tgt(imp->imp_obd));
1036                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1037                 } else {
1038                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1039                         ptlrpc_activate_import(imp);
1040                 }
1041
1042                 rc = 0;
1043                 goto finish;
1044         }
1045
1046         /* Determine what recovery state to move the import to. */
1047         if (msg_flags & MSG_CONNECT_RECONNECT) {
1048                 memset(&old_hdl, 0, sizeof(old_hdl));
1049                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
1050                             sizeof(old_hdl))) {
1051                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due bad handle %#llx\n",
1052                                       obd2cli_tgt(imp->imp_obd),
1053                                       imp->imp_connection->c_remote_uuid.uuid,
1054                                       imp->imp_dlm_handle.cookie);
1055                         rc = -ENOTCONN;
1056                         goto out;
1057                 }
1058
1059                 if (memcmp(&imp->imp_remote_handle,
1060                            lustre_msg_get_handle(request->rq_repmsg),
1061                            sizeof(imp->imp_remote_handle))) {
1062                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
1063                                 D_HA : D_WARNING;
1064
1065                         /* Bug 16611/14775: if server handle have changed,
1066                          * that means some sort of disconnection happened.
1067                          * If the server is not in recovery, that also means it
1068                          * already erased all of our state because of previous
1069                          * eviction. If it is in recovery - we are safe to
1070                          * participate since we can reestablish all of our state
1071                          * with server again
1072                          */
1073                         if ((msg_flags & MSG_CONNECT_RECOVERING)) {
1074                                 CDEBUG(level, "%s@%s changed server handle from %#llx to %#llx but is still in recovery\n",
1075                                        obd2cli_tgt(imp->imp_obd),
1076                                        imp->imp_connection->c_remote_uuid.uuid,
1077                                        imp->imp_remote_handle.cookie,
1078                                        lustre_msg_get_handle(
1079                                        request->rq_repmsg)->cookie);
1080                         } else {
1081                                 LCONSOLE_WARN("Evicted from %s (at %s) after server handle changed from %#llx to %#llx\n",
1082                                               obd2cli_tgt(imp->imp_obd),
1083                                               imp->imp_connection-> \
1084                                               c_remote_uuid.uuid,
1085                                               imp->imp_remote_handle.cookie,
1086                                               lustre_msg_get_handle(
1087                                                       request->rq_repmsg)->cookie);
1088                         }
1089
1090                         imp->imp_remote_handle =
1091                                      *lustre_msg_get_handle(request->rq_repmsg);
1092
1093                         if (!(msg_flags & MSG_CONNECT_RECOVERING)) {
1094                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1095                                 rc = 0;
1096                                 goto finish;
1097                         }
1098
1099                 } else {
1100                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
1101                                obd2cli_tgt(imp->imp_obd),
1102                                imp->imp_connection->c_remote_uuid.uuid);
1103                 }
1104
1105                 if (imp->imp_invalid) {
1106                         CDEBUG(D_HA, "%s: reconnected but import is invalid; marking evicted\n",
1107                                imp->imp_obd->obd_name);
1108                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1109                 } else if (msg_flags & MSG_CONNECT_RECOVERING) {
1110                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
1111                                imp->imp_obd->obd_name,
1112                                obd2cli_tgt(imp->imp_obd));
1113
1114                         spin_lock(&imp->imp_lock);
1115                         imp->imp_resend_replay = 1;
1116                         spin_unlock(&imp->imp_lock);
1117
1118                         IMPORT_SET_STATE(imp, imp->imp_replay_state);
1119                 } else {
1120                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1121                 }
1122         } else if ((msg_flags & MSG_CONNECT_RECOVERING) && !imp->imp_invalid) {
1123                 LASSERT(imp->imp_replayable);
1124                 imp->imp_remote_handle =
1125                                 *lustre_msg_get_handle(request->rq_repmsg);
1126                 imp->imp_last_replay_transno = 0;
1127                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
1128         } else {
1129                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags not set: %x)",
1130                           imp->imp_obd->obd_name, msg_flags);
1131                 imp->imp_remote_handle =
1132                                 *lustre_msg_get_handle(request->rq_repmsg);
1133                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1134         }
1135
1136         /* Sanity checks for a reconnected import. */
1137         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
1138                 CERROR("imp_replayable flag does not match server after reconnect. We should LBUG right here.\n");
1139         }
1140
1141         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
1142             lustre_msg_get_last_committed(request->rq_repmsg) <
1143             aa->pcaa_peer_committed) {
1144                 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",
1145                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
1146                        lustre_msg_get_last_committed(request->rq_repmsg));
1147         }
1148
1149 finish:
1150         rc = ptlrpc_import_recovery_state_machine(imp);
1151         if (rc == -ENOTCONN) {
1152                 CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery; invalidating and reconnecting\n",
1153                        obd2cli_tgt(imp->imp_obd),
1154                        imp->imp_connection->c_remote_uuid.uuid);
1155                 ptlrpc_connect_import(imp);
1156                 imp->imp_connect_tried = 1;
1157                 return 0;
1158         }
1159
1160 out:
1161         imp->imp_connect_tried = 1;
1162
1163         if (rc != 0) {
1164                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1165                 if (rc == -EACCES) {
1166                         /*
1167                          * Give up trying to reconnect
1168                          * EACCES means client has no permission for connection
1169                          */
1170                         imp->imp_obd->obd_no_recov = 1;
1171                         ptlrpc_deactivate_import(imp);
1172                 }
1173
1174                 if (rc == -EPROTO) {
1175                         struct obd_connect_data *ocd;
1176
1177                         /* reply message might not be ready */
1178                         if (!request->rq_repmsg)
1179                                 return -EPROTO;
1180
1181                         ocd = req_capsule_server_get(&request->rq_pill,
1182                                                      &RMF_CONNECT_DATA);
1183                         if (ocd &&
1184                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1185                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1186                                 /*
1187                                  * Actually servers are only supposed to refuse
1188                                  * connection from liblustre clients, so we
1189                                  * should never see this from VFS context
1190                                  */
1191                                 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",
1192                                                    obd2cli_tgt(imp->imp_obd),
1193                                                    OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1194                                                    OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1195                                                    OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1196                                                    OBD_OCD_VERSION_FIX(ocd->ocd_version),
1197                                                    LUSTRE_VERSION_STRING);
1198                                 ptlrpc_deactivate_import(imp);
1199                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1200                         }
1201                         return -EPROTO;
1202                 }
1203
1204                 ptlrpc_maybe_ping_import_soon(imp);
1205
1206                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1207                        obd2cli_tgt(imp->imp_obd),
1208                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1209         }
1210
1211         wake_up_all(&imp->imp_recovery_waitq);
1212         return rc;
1213 }
1214
1215 /**
1216  * interpret callback for "completed replay" RPCs.
1217  * \see signal_completed_replay
1218  */
1219 static int completed_replay_interpret(const struct lu_env *env,
1220                                       struct ptlrpc_request *req,
1221                                       void *data, int rc)
1222 {
1223         atomic_dec(&req->rq_import->imp_replay_inflight);
1224         if (req->rq_status == 0 &&
1225             !req->rq_import->imp_vbr_failed) {
1226                 ptlrpc_import_recovery_state_machine(req->rq_import);
1227         } else {
1228                 if (req->rq_import->imp_vbr_failed) {
1229                         CDEBUG(D_WARNING,
1230                                "%s: version recovery fails, reconnecting\n",
1231                                req->rq_import->imp_obd->obd_name);
1232                 } else {
1233                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, reconnecting\n",
1234                                req->rq_import->imp_obd->obd_name,
1235                                req->rq_status);
1236                 }
1237                 ptlrpc_connect_import(req->rq_import);
1238         }
1239
1240         return 0;
1241 }
1242
1243 /**
1244  * Let server know that we have no requests to replay anymore.
1245  * Achieved by just sending a PING request
1246  */
1247 static int signal_completed_replay(struct obd_import *imp)
1248 {
1249         struct ptlrpc_request *req;
1250
1251         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1252                 return 0;
1253
1254         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1255         atomic_inc(&imp->imp_replay_inflight);
1256
1257         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1258                                         OBD_PING);
1259         if (!req) {
1260                 atomic_dec(&imp->imp_replay_inflight);
1261                 return -ENOMEM;
1262         }
1263
1264         ptlrpc_request_set_replen(req);
1265         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1266         lustre_msg_add_flags(req->rq_reqmsg,
1267                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1268         if (AT_OFF)
1269                 req->rq_timeout *= 3;
1270         req->rq_interpret_reply = completed_replay_interpret;
1271
1272         ptlrpcd_add_req(req);
1273         return 0;
1274 }
1275
1276 /**
1277  * In kernel code all import invalidation happens in its own
1278  * separate thread, so that whatever application happened to encounter
1279  * a problem could still be killed or otherwise continue
1280  */
1281 static int ptlrpc_invalidate_import_thread(void *data)
1282 {
1283         struct obd_import *imp = data;
1284
1285         unshare_fs_struct();
1286
1287         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1288                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1289                imp->imp_connection->c_remote_uuid.uuid);
1290
1291         ptlrpc_invalidate_import(imp);
1292
1293         if (obd_dump_on_eviction) {
1294                 CERROR("dump the log upon eviction\n");
1295                 libcfs_debug_dumplog();
1296         }
1297
1298         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1299         ptlrpc_import_recovery_state_machine(imp);
1300
1301         class_import_put(imp);
1302         return 0;
1303 }
1304
1305 /**
1306  * This is the state machine for client-side recovery on import.
1307  *
1308  * Typically we have two possibly paths. If we came to server and it is not
1309  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1310  * state and reconnect from scratch.
1311  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1312  * We go through our list of requests to replay and send them to server one by
1313  * one.
1314  * After sending all request from the list we change import state to
1315  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1316  * and also all the locks we don't yet have and wait for server to grant us.
1317  * After that we send a special "replay completed" request and change import
1318  * state to IMP_REPLAY_WAIT.
1319  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1320  * state and resend all requests from sending list.
1321  * After that we promote import to FULL state and send all delayed requests
1322  * and import is fully operational after that.
1323  *
1324  */
1325 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1326 {
1327         int rc = 0;
1328         int inflight;
1329         char *target_start;
1330         int target_len;
1331
1332         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1333                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1334                           &target_start, &target_len);
1335                 /* Don't care about MGC eviction */
1336                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1337                            LUSTRE_MGC_NAME) != 0) {
1338                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted by %.*s; in progress operations using this service will fail.\n",
1339                                            imp->imp_obd->obd_name, target_len,
1340                                            target_start);
1341                 }
1342                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1343                        obd2cli_tgt(imp->imp_obd),
1344                        imp->imp_connection->c_remote_uuid.uuid);
1345                 /* reset vbr_failed flag upon eviction */
1346                 spin_lock(&imp->imp_lock);
1347                 imp->imp_vbr_failed = 0;
1348                 spin_unlock(&imp->imp_lock);
1349
1350                 {
1351                 struct task_struct *task;
1352                 /* bug 17802:  XXX client_disconnect_export vs connect request
1353                  * race. if client is evicted at this time, we start
1354                  * invalidate thread without reference to import and import can
1355                  * be freed at same time.
1356                  */
1357                 class_import_get(imp);
1358                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1359                                    "ll_imp_inval");
1360                 if (IS_ERR(task)) {
1361                         class_import_put(imp);
1362                         CERROR("error starting invalidate thread: %d\n", rc);
1363                         rc = PTR_ERR(task);
1364                 } else {
1365                         rc = 0;
1366                 }
1367                 return rc;
1368                 }
1369         }
1370
1371         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1372                 CDEBUG(D_HA, "replay requested by %s\n",
1373                        obd2cli_tgt(imp->imp_obd));
1374                 rc = ptlrpc_replay_next(imp, &inflight);
1375                 if (inflight == 0 &&
1376                     atomic_read(&imp->imp_replay_inflight) == 0) {
1377                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1378                         rc = ldlm_replay_locks(imp);
1379                         if (rc)
1380                                 goto out;
1381                 }
1382                 rc = 0;
1383         }
1384
1385         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1386                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1387                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1388                         rc = signal_completed_replay(imp);
1389                         if (rc)
1390                                 goto out;
1391                 }
1392         }
1393
1394         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1395                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1396                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1397                 }
1398         }
1399
1400         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1401                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1402                        obd2cli_tgt(imp->imp_obd),
1403                        imp->imp_connection->c_remote_uuid.uuid);
1404
1405                 rc = ptlrpc_resend(imp);
1406                 if (rc)
1407                         goto out;
1408                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1409                 ptlrpc_activate_import(imp);
1410
1411                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1412                           &target_start, &target_len);
1413                 LCONSOLE_INFO("%s: Connection restored to %.*s (at %s)\n",
1414                               imp->imp_obd->obd_name,
1415                               target_len, target_start,
1416                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1417         }
1418
1419         if (imp->imp_state == LUSTRE_IMP_FULL) {
1420                 wake_up_all(&imp->imp_recovery_waitq);
1421                 ptlrpc_wake_delayed(imp);
1422         }
1423
1424 out:
1425         return rc;
1426 }
1427
1428 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1429 {
1430         struct ptlrpc_request *req;
1431         int rq_opc, rc = 0;
1432
1433         if (imp->imp_obd->obd_force)
1434                 goto set_state;
1435
1436         switch (imp->imp_connect_op) {
1437         case OST_CONNECT:
1438                 rq_opc = OST_DISCONNECT;
1439                 break;
1440         case MDS_CONNECT:
1441                 rq_opc = MDS_DISCONNECT;
1442                 break;
1443         case MGS_CONNECT:
1444                 rq_opc = MGS_DISCONNECT;
1445                 break;
1446         default:
1447                 rc = -EINVAL;
1448                 CERROR("%s: don't know how to disconnect from %s (connect_op %d): rc = %d\n",
1449                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1450                        imp->imp_connect_op, rc);
1451                 return rc;
1452         }
1453
1454         if (ptlrpc_import_in_recovery(imp)) {
1455                 struct l_wait_info lwi;
1456                 long timeout;
1457
1458                 if (AT_OFF) {
1459                         if (imp->imp_server_timeout)
1460                                 timeout = cfs_time_seconds(obd_timeout / 2);
1461                         else
1462                                 timeout = cfs_time_seconds(obd_timeout);
1463                 } else {
1464                         int idx = import_at_get_index(imp,
1465                                 imp->imp_client->cli_request_portal);
1466                         timeout = cfs_time_seconds(
1467                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1468                 }
1469
1470                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1471                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1472                 rc = l_wait_event(imp->imp_recovery_waitq,
1473                                   !ptlrpc_import_in_recovery(imp), &lwi);
1474         }
1475
1476         spin_lock(&imp->imp_lock);
1477         if (imp->imp_state != LUSTRE_IMP_FULL)
1478                 goto out;
1479         spin_unlock(&imp->imp_lock);
1480
1481         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1482                                         LUSTRE_OBD_VERSION, rq_opc);
1483         if (req) {
1484                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1485                  * it fails.  We can get through the above with a down server
1486                  * if the client doesn't know the server is gone yet.
1487                  */
1488                 req->rq_no_resend = 1;
1489
1490                 /* We want client umounts to happen quickly, no matter the
1491                  * server state...
1492                  */
1493                 req->rq_timeout = min_t(int, req->rq_timeout,
1494                                         INITIAL_CONNECT_TIMEOUT);
1495
1496                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1497                 req->rq_send_state = LUSTRE_IMP_CONNECTING;
1498                 ptlrpc_request_set_replen(req);
1499                 rc = ptlrpc_queue_wait(req);
1500                 ptlrpc_req_finished(req);
1501         }
1502
1503 set_state:
1504         spin_lock(&imp->imp_lock);
1505 out:
1506         if (noclose)
1507                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1508         else
1509                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1510         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1511         spin_unlock(&imp->imp_lock);
1512
1513         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1514                 rc = 0;
1515
1516         return rc;
1517 }
1518 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1519
1520 /* Adaptive Timeout utils */
1521 extern unsigned int at_min, at_max, at_history;
1522
1523 /*
1524  *Update at_current with the specified value (bounded by at_min and at_max),
1525  * as well as the AT history "bins".
1526  *  - Bin into timeslices using AT_BINS bins.
1527  *  - This gives us a max of the last at_history seconds without the storage,
1528  *    but still smoothing out a return to normalcy from a slow response.
1529  *  - (E.g. remember the maximum latency in each minute of the last 4 minutes.)
1530  */
1531 int at_measured(struct adaptive_timeout *at, unsigned int val)
1532 {
1533         unsigned int old = at->at_current;
1534         time64_t now = ktime_get_real_seconds();
1535         long binlimit = max_t(long, at_history / AT_BINS, 1);
1536
1537         LASSERT(at);
1538         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1539                val, at, (long)(now - at->at_binstart), at->at_current,
1540                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1541
1542         if (val == 0)
1543                 /* 0's don't count, because we never want our timeout to
1544                  * drop to 0, and because 0 could mean an error
1545                  */
1546                 return 0;
1547
1548         spin_lock(&at->at_lock);
1549
1550         if (unlikely(at->at_binstart == 0)) {
1551                 /* Special case to remove default from history */
1552                 at->at_current = val;
1553                 at->at_worst_ever = val;
1554                 at->at_worst_time = now;
1555                 at->at_hist[0] = val;
1556                 at->at_binstart = now;
1557         } else if (now - at->at_binstart < binlimit) {
1558                 /* in bin 0 */
1559                 at->at_hist[0] = max(val, at->at_hist[0]);
1560                 at->at_current = max(val, at->at_current);
1561         } else {
1562                 int i, shift;
1563                 unsigned int maxv = val;
1564                 /* move bins over */
1565                 shift = (u32)(now - at->at_binstart) / binlimit;
1566                 LASSERT(shift > 0);
1567                 for (i = AT_BINS - 1; i >= 0; i--) {
1568                         if (i >= shift) {
1569                                 at->at_hist[i] = at->at_hist[i - shift];
1570                                 maxv = max(maxv, at->at_hist[i]);
1571                         } else {
1572                                 at->at_hist[i] = 0;
1573                         }
1574                 }
1575                 at->at_hist[0] = val;
1576                 at->at_current = maxv;
1577                 at->at_binstart += shift * binlimit;
1578         }
1579
1580         if (at->at_current > at->at_worst_ever) {
1581                 at->at_worst_ever = at->at_current;
1582                 at->at_worst_time = now;
1583         }
1584
1585         if (at->at_flags & AT_FLG_NOHIST)
1586                 /* Only keep last reported val; keeping the rest of the history
1587                  * for debugfs only
1588                  */
1589                 at->at_current = val;
1590
1591         if (at_max > 0)
1592                 at->at_current =  min(at->at_current, at_max);
1593         at->at_current =  max(at->at_current, at_min);
1594
1595         if (at->at_current != old)
1596                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d (val=%u) hist %u %u %u %u\n",
1597                        at,
1598                        old, at->at_current, at->at_current - old, val,
1599                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1600                        at->at_hist[3]);
1601
1602         /* if we changed, report the old value */
1603         old = (at->at_current != old) ? old : 0;
1604
1605         spin_unlock(&at->at_lock);
1606         return old;
1607 }
1608
1609 /* Find the imp_at index for a given portal; assign if space available */
1610 int import_at_get_index(struct obd_import *imp, int portal)
1611 {
1612         struct imp_at *at = &imp->imp_at;
1613         int i;
1614
1615         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1616                 if (at->iat_portal[i] == portal)
1617                         return i;
1618                 if (at->iat_portal[i] == 0)
1619                         /* unused */
1620                         break;
1621         }
1622
1623         /* Not found in list, add it under a lock */
1624         spin_lock(&imp->imp_lock);
1625
1626         /* Check unused under lock */
1627         for (; i < IMP_AT_MAX_PORTALS; i++) {
1628                 if (at->iat_portal[i] == portal)
1629                         goto out;
1630                 if (at->iat_portal[i] == 0)
1631                         /* unused */
1632                         break;
1633         }
1634
1635         /* Not enough portals? */
1636         LASSERT(i < IMP_AT_MAX_PORTALS);
1637
1638         at->iat_portal[i] = portal;
1639 out:
1640         spin_unlock(&imp->imp_lock);
1641         return i;
1642 }