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