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