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