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