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