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