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