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