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