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