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