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