Whamcloud - gitweb
f04e56fb8c5de3f33b8f47bd590f68d3d90e4bb0
[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_measured(&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         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
671
672         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
673                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
674         if (rc)
675                 GOTO(out, rc);
676
677         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
678         if (request == NULL)
679                 GOTO(out, rc = -ENOMEM);
680
681         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
682                                       imp->imp_connect_op, bufs, NULL);
683         if (rc) {
684                 ptlrpc_request_free(request);
685                 GOTO(out, rc);
686         }
687
688         /* Report the rpc service time to the server so that it knows how long
689          * to wait for clients to join recovery */
690         lustre_msg_set_service_time(request->rq_reqmsg,
691                                     at_timeout2est(request->rq_timeout));
692
693         /* The amount of time we give the server to process the connect req.
694          * import_select_connection will increase the net latency on
695          * repeated reconnect attempts to cover slow networks.
696          * We override/ignore the server rpc completion estimate here,
697          * which may be large if this is a reconnect attempt */
698         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
699         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
700
701 #ifndef __KERNEL__
702         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_LIBCLIENT);
703 #endif
704         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
705
706         request->rq_no_resend = request->rq_no_delay = 1;
707         request->rq_send_state = LUSTRE_IMP_CONNECTING;
708         /* Allow a slightly larger reply for future growth compatibility */
709         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
710                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
711         ptlrpc_request_set_replen(request);
712         request->rq_interpret_reply = ptlrpc_connect_interpret;
713
714         CLASSERT(sizeof (*aa) <= sizeof (request->rq_async_args));
715         aa = ptlrpc_req_async_args(request);
716         memset(aa, 0, sizeof *aa);
717
718         aa->pcaa_peer_committed = committed_before_reconnect;
719         aa->pcaa_initial_connect = initial_connect;
720
721         if (aa->pcaa_initial_connect) {
722                 cfs_spin_lock(&imp->imp_lock);
723                 imp->imp_replayable = 1;
724                 cfs_spin_unlock(&imp->imp_lock);
725                 lustre_msg_add_op_flags(request->rq_reqmsg,
726                                         MSG_CONNECT_INITIAL);
727         }
728
729         if (set_transno)
730                 lustre_msg_add_op_flags(request->rq_reqmsg,
731                                         MSG_CONNECT_TRANSNO);
732
733         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %d)",
734                   request->rq_timeout);
735         ptlrpcd_add_req(request, PSCOPE_OTHER);
736         rc = 0;
737 out:
738         if (rc != 0) {
739                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
740         }
741
742         RETURN(rc);
743 }
744 EXPORT_SYMBOL(ptlrpc_connect_import);
745
746 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
747 {
748 #ifdef __KERNEL__
749         struct obd_import_conn *imp_conn;
750 #endif
751         int wake_pinger = 0;
752
753         ENTRY;
754
755         cfs_spin_lock(&imp->imp_lock);
756         if (cfs_list_empty(&imp->imp_conn_list))
757                 GOTO(unlock, 0);
758
759 #ifdef __KERNEL__
760         imp_conn = cfs_list_entry(imp->imp_conn_list.prev,
761                                   struct obd_import_conn,
762                                   oic_item);
763
764         /* XXX: When the failover node is the primary node, it is possible
765          * to have two identical connections in imp_conn_list. We must
766          * compare not conn's pointers but NIDs, otherwise we can defeat
767          * connection throttling. (See bug 14774.) */
768         if (imp->imp_conn_current->oic_conn->c_peer.nid !=
769                                 imp_conn->oic_conn->c_peer.nid) {
770                 ptlrpc_ping_import_soon(imp);
771                 wake_pinger = 1;
772         }
773 #else
774         /* liblustre has no pinger thread, so we wakeup pinger anyway */
775         wake_pinger = 1;
776 #endif
777
778  unlock:
779         cfs_spin_unlock(&imp->imp_lock);
780
781         if (wake_pinger)
782                 ptlrpc_pinger_wake_up();
783
784         EXIT;
785 }
786
787 static int ptlrpc_busy_reconnect(int rc)
788 {
789         return (rc == -EBUSY) || (rc == -EAGAIN);
790 }
791
792
793 static int ptlrpc_connect_interpret(const struct lu_env *env,
794                                     struct ptlrpc_request *request,
795                                     void *data, int rc)
796 {
797         struct ptlrpc_connect_async_args *aa = data;
798         struct obd_import *imp = request->rq_import;
799         struct client_obd *cli = &imp->imp_obd->u.cli;
800         struct lustre_handle old_hdl;
801         __u64 old_connect_flags;
802         int msg_flags;
803         ENTRY;
804
805         cfs_spin_lock(&imp->imp_lock);
806         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
807                 cfs_spin_unlock(&imp->imp_lock);
808                 RETURN(0);
809         }
810
811         if (rc) {
812                 /* if this reconnect to busy export - not need select new target
813                  * for connecting*/
814                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
815                 cfs_spin_unlock(&imp->imp_lock);
816                 GOTO(out, rc);
817         }
818
819         LASSERT(imp->imp_conn_current);
820
821         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
822
823         /* All imports are pingable */
824         imp->imp_pingable = 1;
825         imp->imp_force_reconnect = 0;
826
827         if (aa->pcaa_initial_connect) {
828                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
829                         imp->imp_replayable = 1;
830                         cfs_spin_unlock(&imp->imp_lock);
831                         CDEBUG(D_HA, "connected to replayable target: %s\n",
832                                obd2cli_tgt(imp->imp_obd));
833                 } else {
834                         imp->imp_replayable = 0;
835                         cfs_spin_unlock(&imp->imp_lock);
836                 }
837
838                 /* if applies, adjust the imp->imp_msg_magic here
839                  * according to reply flags */
840
841                 imp->imp_remote_handle =
842                                 *lustre_msg_get_handle(request->rq_repmsg);
843
844                 /* Initial connects are allowed for clients with non-random
845                  * uuids when servers are in recovery.  Simply signal the
846                  * servers replay is complete and wait in REPLAY_WAIT. */
847                 if (msg_flags & MSG_CONNECT_RECOVERING) {
848                         CDEBUG(D_HA, "connect to %s during recovery\n",
849                                obd2cli_tgt(imp->imp_obd));
850                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
851                 } else {
852                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
853                         ptlrpc_activate_import(imp);
854                 }
855
856                 GOTO(finish, rc = 0);
857         } else {
858                 cfs_spin_unlock(&imp->imp_lock);
859         }
860
861         /* Determine what recovery state to move the import to. */
862         if (MSG_CONNECT_RECONNECT & msg_flags) {
863                 memset(&old_hdl, 0, sizeof(old_hdl));
864                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
865                             sizeof (old_hdl))) {
866                         CERROR("%s@%s didn't like our handle "LPX64
867                                ", failed\n", obd2cli_tgt(imp->imp_obd),
868                                imp->imp_connection->c_remote_uuid.uuid,
869                                imp->imp_dlm_handle.cookie);
870                         GOTO(out, rc = -ENOTCONN);
871                 }
872
873                 if (memcmp(&imp->imp_remote_handle,
874                            lustre_msg_get_handle(request->rq_repmsg),
875                            sizeof(imp->imp_remote_handle))) {
876                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
877                                 D_HA : D_WARNING;
878
879                         /* Bug 16611/14775: if server handle have changed,
880                          * that means some sort of disconnection happened.
881                          * If the server is not in recovery, that also means it
882                          * already erased all of our state because of previous
883                          * eviction. If it is in recovery - we are safe to
884                          * participate since we can reestablish all of our state
885                          * with server again */
886                         CDEBUG(level,"%s@%s changed server handle from "
887                                      LPX64" to "LPX64"%s\n",
888                                      obd2cli_tgt(imp->imp_obd),
889                                      imp->imp_connection->c_remote_uuid.uuid,
890                                      imp->imp_remote_handle.cookie,
891                                      lustre_msg_get_handle(request->rq_repmsg)->
892                                                                         cookie,
893                                      (MSG_CONNECT_RECOVERING & msg_flags) ?
894                                          " but is still in recovery" : "");
895
896                         imp->imp_remote_handle =
897                                      *lustre_msg_get_handle(request->rq_repmsg);
898
899                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
900                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
901                                 GOTO(finish, rc = 0);
902                         }
903
904                 } else {
905                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
906                                obd2cli_tgt(imp->imp_obd),
907                                imp->imp_connection->c_remote_uuid.uuid);
908                 }
909
910                 if (imp->imp_invalid) {
911                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
912                                "marking evicted\n", imp->imp_obd->obd_name);
913                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
914                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
915                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
916                                imp->imp_obd->obd_name,
917                                obd2cli_tgt(imp->imp_obd));
918
919                         cfs_spin_lock(&imp->imp_lock);
920                         imp->imp_resend_replay = 1;
921                         cfs_spin_unlock(&imp->imp_lock);
922
923                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
924                 } else {
925                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
926                 }
927         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
928                 LASSERT(imp->imp_replayable);
929                 imp->imp_remote_handle =
930                                 *lustre_msg_get_handle(request->rq_repmsg);
931                 imp->imp_last_replay_transno = 0;
932                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
933         } else {
934                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
935                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
936                 imp->imp_remote_handle =
937                                 *lustre_msg_get_handle(request->rq_repmsg);
938                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
939         }
940
941         /* Sanity checks for a reconnected import. */
942         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
943                 CERROR("imp_replayable flag does not match server "
944                        "after reconnect. We should LBUG right here.\n");
945         }
946
947         if (lustre_msg_get_last_committed(request->rq_repmsg) <
948             aa->pcaa_peer_committed) {
949                 CERROR("%s went back in time (transno "LPD64
950                        " was previously committed, server now claims "LPD64
951                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
952                        "id=9646\n",
953                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
954                        lustre_msg_get_last_committed(request->rq_repmsg));
955         }
956
957 finish:
958         rc = ptlrpc_import_recovery_state_machine(imp);
959         if (rc != 0) {
960                 if (rc == -ENOTCONN) {
961                         CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
962                                "invalidating and reconnecting\n",
963                                obd2cli_tgt(imp->imp_obd),
964                                imp->imp_connection->c_remote_uuid.uuid);
965                         ptlrpc_connect_import(imp, NULL);
966                         RETURN(0);
967                 }
968         } else {
969                 struct obd_connect_data *ocd;
970                 struct obd_export *exp;
971                 int ret;
972                 ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
973                                            RCL_SERVER);
974                 /* server replied obd_connect_data is always bigger */
975                 ocd = req_capsule_server_sized_get(&request->rq_pill,
976                                                    &RMF_CONNECT_DATA, ret);
977
978                 cfs_spin_lock(&imp->imp_lock);
979                 cfs_list_del(&imp->imp_conn_current->oic_item);
980                 cfs_list_add(&imp->imp_conn_current->oic_item,
981                              &imp->imp_conn_list);
982                 imp->imp_last_success_conn =
983                         imp->imp_conn_current->oic_last_attempt;
984
985                 if (ocd == NULL) {
986                         cfs_spin_unlock(&imp->imp_lock);
987                         CERROR("Wrong connect data from server\n");
988                         rc = -EPROTO;
989                         GOTO(out, rc);
990                 }
991
992                 imp->imp_connect_data = *ocd;
993
994                 exp = class_conn2export(&imp->imp_dlm_handle);
995                 cfs_spin_unlock(&imp->imp_lock);
996
997                 /* check that server granted subset of flags we asked for. */
998                 LASSERTF((ocd->ocd_connect_flags &
999                           imp->imp_connect_flags_orig) ==
1000                          ocd->ocd_connect_flags, LPX64" != "LPX64,
1001                          imp->imp_connect_flags_orig, ocd->ocd_connect_flags);
1002
1003                 if (!exp) {
1004                         /* This could happen if export is cleaned during the
1005                            connect attempt */
1006                         CERROR("Missing export for %s\n",
1007                                imp->imp_obd->obd_name);
1008                         GOTO(out, rc = -ENODEV);
1009                 }
1010                 old_connect_flags = exp->exp_connect_flags;
1011                 exp->exp_connect_flags = ocd->ocd_connect_flags;
1012                 imp->imp_obd->obd_self_export->exp_connect_flags =
1013                                                         ocd->ocd_connect_flags;
1014                 class_export_put(exp);
1015
1016                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1017
1018                 if (!ocd->ocd_ibits_known &&
1019                     ocd->ocd_connect_flags & OBD_CONNECT_IBITS)
1020                         CERROR("Inodebits aware server returned zero compatible"
1021                                " bits?\n");
1022
1023                 if ((ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1024                     (ocd->ocd_version > LUSTRE_VERSION_CODE +
1025                                         LUSTRE_VERSION_OFFSET_WARN ||
1026                      ocd->ocd_version < LUSTRE_VERSION_CODE -
1027                                         LUSTRE_VERSION_OFFSET_WARN)) {
1028                         /* Sigh, some compilers do not like #ifdef in the middle
1029                            of macro arguments */
1030 #ifdef __KERNEL__
1031                         const char *older =
1032                                 "older. Consider upgrading this client";
1033 #else
1034                         const char *older =
1035                                 "older. Consider recompiling this application";
1036 #endif
1037                         const char *newer = "newer than client version";
1038
1039                         LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
1040                                       "is much %s (%s)\n",
1041                                       obd2cli_tgt(imp->imp_obd),
1042                                       OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1043                                       OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1044                                       OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1045                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1046                                       ocd->ocd_version > LUSTRE_VERSION_CODE ?
1047                                       newer : older, LUSTRE_VERSION_STRING);
1048                 }
1049
1050                 if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
1051                         /* We sent to the server ocd_cksum_types with bits set
1052                          * for algorithms we understand. The server masked off
1053                          * the checksum types it doesn't support */
1054                         if ((ocd->ocd_cksum_types & OBD_CKSUM_ALL) == 0) {
1055                                 LCONSOLE_WARN("The negotiation of the checksum "
1056                                               "alogrithm to use with server %s "
1057                                               "failed (%x/%x), disabling "
1058                                               "checksums\n",
1059                                               obd2cli_tgt(imp->imp_obd),
1060                                               ocd->ocd_cksum_types,
1061                                               OBD_CKSUM_ALL);
1062                                 cli->cl_checksum = 0;
1063                                 cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
1064                                 cli->cl_cksum_type = OBD_CKSUM_CRC32;
1065                         } else {
1066                                 cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
1067
1068                                 if (ocd->ocd_cksum_types & OSC_DEFAULT_CKSUM)
1069                                         cli->cl_cksum_type = OSC_DEFAULT_CKSUM;
1070                                 else if (ocd->ocd_cksum_types & OBD_CKSUM_ADLER)
1071                                         cli->cl_cksum_type = OBD_CKSUM_ADLER;
1072                                 else
1073                                         cli->cl_cksum_type = OBD_CKSUM_CRC32;
1074                         }
1075                 } else {
1076                         /* The server does not support OBD_CONNECT_CKSUM.
1077                          * Enforce CRC32 for backward compatibility*/
1078                         cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
1079                         cli->cl_cksum_type = OBD_CKSUM_CRC32;
1080                 }
1081
1082                 if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
1083                         cli->cl_max_pages_per_rpc =
1084                                 ocd->ocd_brw_size >> CFS_PAGE_SHIFT;
1085                 }
1086
1087                 /* Reset ns_connect_flags only for initial connect. It might be
1088                  * changed in while using FS and if we reset it in reconnect
1089                  * this leads to losing user settings done before such as
1090                  * disable lru_resize, etc. */
1091                 if (old_connect_flags != exp->exp_connect_flags ||
1092                     aa->pcaa_initial_connect) {
1093                         CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
1094                                "flags: "LPX64"\n", imp->imp_obd->obd_name,
1095                               ocd->ocd_connect_flags);
1096                         imp->imp_obd->obd_namespace->ns_connect_flags =
1097                                 ocd->ocd_connect_flags;
1098                         imp->imp_obd->obd_namespace->ns_orig_connect_flags =
1099                                 ocd->ocd_connect_flags;
1100                 }
1101
1102                 if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
1103                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1104                         /* We need a per-message support flag, because
1105                            a. we don't know if the incoming connect reply
1106                               supports AT or not (in reply_in_callback)
1107                               until we unpack it.
1108                            b. failovered server means export and flags are gone
1109                               (in ptlrpc_send_reply).
1110                            Can only be set when we know AT is supported at
1111                            both ends */
1112                         imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1113                 else
1114                         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1115
1116                 if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1117                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1118                         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1119                 else
1120                         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1121
1122                 LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
1123                         (cli->cl_max_pages_per_rpc > 0));
1124         }
1125
1126 out:
1127         if (rc != 0) {
1128                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1129                 cfs_spin_lock(&imp->imp_lock);
1130                 if (aa->pcaa_initial_connect && !imp->imp_initial_recov &&
1131                     (request->rq_import_generation == imp->imp_generation))
1132                         ptlrpc_deactivate_and_unlock_import(imp);
1133                 else
1134                         cfs_spin_unlock(&imp->imp_lock);
1135
1136                 if ((imp->imp_recon_bk && imp->imp_last_recon) ||
1137                     (rc == -EACCES)) {
1138                         /*
1139                          * Give up trying to reconnect
1140                          * EACCES means client has no permission for connection
1141                          */
1142                         imp->imp_obd->obd_no_recov = 1;
1143                         ptlrpc_deactivate_import(imp);
1144                 }
1145
1146                 if (rc == -EPROTO) {
1147                         struct obd_connect_data *ocd;
1148
1149                         /* reply message might not be ready */
1150                         if (request->rq_repmsg == NULL)
1151                                 RETURN(-EPROTO);
1152
1153                         ocd = req_capsule_server_get(&request->rq_pill,
1154                                                      &RMF_CONNECT_DATA);
1155                         if (ocd &&
1156                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1157                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1158                            /* Actually servers are only supposed to refuse
1159                               connection from liblustre clients, so we should
1160                               never see this from VFS context */
1161                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1162                                         "(%d.%d.%d.%d)"
1163                                         " refused connection from this client "
1164                                         "with an incompatible version (%s).  "
1165                                         "Client must be recompiled\n",
1166                                         obd2cli_tgt(imp->imp_obd),
1167                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1168                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1169                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1170                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1171                                         LUSTRE_VERSION_STRING);
1172                                 ptlrpc_deactivate_import(imp);
1173                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1174                         }
1175                         RETURN(-EPROTO);
1176                 }
1177
1178                 ptlrpc_maybe_ping_import_soon(imp);
1179
1180                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1181                        obd2cli_tgt(imp->imp_obd),
1182                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1183         }
1184
1185         cfs_spin_lock(&imp->imp_lock);
1186         imp->imp_last_recon = 0;
1187         cfs_spin_unlock(&imp->imp_lock);
1188
1189         cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1190         RETURN(rc);
1191 }
1192
1193 static int completed_replay_interpret(const struct lu_env *env,
1194                                       struct ptlrpc_request *req,
1195                                       void * data, int rc)
1196 {
1197         ENTRY;
1198         cfs_atomic_dec(&req->rq_import->imp_replay_inflight);
1199         if (req->rq_status == 0 &&
1200             !req->rq_import->imp_vbr_failed) {
1201                 ptlrpc_import_recovery_state_machine(req->rq_import);
1202         } else {
1203                 if (req->rq_import->imp_vbr_failed) {
1204                         CDEBUG(D_WARNING,
1205                                "%s: version recovery fails, reconnecting\n",
1206                                req->rq_import->imp_obd->obd_name);
1207                 } else {
1208                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1209                                      "reconnecting\n",
1210                                req->rq_import->imp_obd->obd_name,
1211                                req->rq_status);
1212                 }
1213                 ptlrpc_connect_import(req->rq_import, NULL);
1214         }
1215
1216         RETURN(0);
1217 }
1218
1219 static int signal_completed_replay(struct obd_import *imp)
1220 {
1221         struct ptlrpc_request *req;
1222         ENTRY;
1223
1224         LASSERT(cfs_atomic_read(&imp->imp_replay_inflight) == 0);
1225         cfs_atomic_inc(&imp->imp_replay_inflight);
1226
1227         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1228                                         OBD_PING);
1229         if (req == NULL) {
1230                 cfs_atomic_dec(&imp->imp_replay_inflight);
1231                 RETURN(-ENOMEM);
1232         }
1233
1234         ptlrpc_request_set_replen(req);
1235         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1236         lustre_msg_add_flags(req->rq_reqmsg,
1237                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1238         if (AT_OFF)
1239                 req->rq_timeout *= 3;
1240         req->rq_interpret_reply = completed_replay_interpret;
1241
1242         ptlrpcd_add_req(req, PSCOPE_OTHER);
1243         RETURN(0);
1244 }
1245
1246 #ifdef __KERNEL__
1247 static int ptlrpc_invalidate_import_thread(void *data)
1248 {
1249         struct obd_import *imp = data;
1250
1251         ENTRY;
1252
1253         cfs_daemonize_ctxt("ll_imp_inval");
1254
1255         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1256                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1257                imp->imp_connection->c_remote_uuid.uuid);
1258
1259         ptlrpc_invalidate_import(imp);
1260
1261         if (obd_dump_on_eviction) {
1262                 CERROR("dump the log upon eviction\n");
1263                 libcfs_debug_dumplog();
1264         }
1265
1266         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1267         ptlrpc_import_recovery_state_machine(imp);
1268
1269         class_import_put(imp);
1270         RETURN(0);
1271 }
1272 #endif
1273
1274 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1275 {
1276         int rc = 0;
1277         int inflight;
1278         char *target_start;
1279         int target_len;
1280
1281         ENTRY;
1282         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1283                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1284                           &target_start, &target_len);
1285                 /* Don't care about MGC eviction */
1286                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1287                            LUSTRE_MGC_NAME) != 0) {
1288                         LCONSOLE_ERROR_MSG(0x167, "This client was evicted by "
1289                                            "%.*s; in progress operations using "
1290                                            "this service will fail.\n",
1291                                            target_len, target_start);
1292                 }
1293                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1294                        obd2cli_tgt(imp->imp_obd),
1295                        imp->imp_connection->c_remote_uuid.uuid);
1296                 /* reset vbr_failed flag upon eviction */
1297                 cfs_spin_lock(&imp->imp_lock);
1298                 imp->imp_vbr_failed = 0;
1299                 cfs_spin_unlock(&imp->imp_lock);
1300
1301 #ifdef __KERNEL__
1302                 /* bug 17802:  XXX client_disconnect_export vs connect request
1303                  * race. if client will evicted at this time, we start
1304                  * invalidate thread without reference to import and import can
1305                  * be freed at same time. */
1306                 class_import_get(imp);
1307                 rc = cfs_kernel_thread(ptlrpc_invalidate_import_thread, imp,
1308                                        CLONE_VM | CLONE_FILES);
1309                 if (rc < 0) {
1310                         class_import_put(imp);
1311                         CERROR("error starting invalidate thread: %d\n", rc);
1312                 } else {
1313                         rc = 0;
1314                 }
1315                 RETURN(rc);
1316 #else
1317                 ptlrpc_invalidate_import(imp);
1318
1319                 IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1320 #endif
1321         }
1322
1323         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1324                 CDEBUG(D_HA, "replay requested by %s\n",
1325                        obd2cli_tgt(imp->imp_obd));
1326                 rc = ptlrpc_replay_next(imp, &inflight);
1327                 if (inflight == 0 &&
1328                     cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1329                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1330                         rc = ldlm_replay_locks(imp);
1331                         if (rc)
1332                                 GOTO(out, rc);
1333                 }
1334                 rc = 0;
1335         }
1336
1337         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1338                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1339                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1340                         rc = signal_completed_replay(imp);
1341                         if (rc)
1342                                 GOTO(out, rc);
1343                 }
1344
1345         }
1346
1347         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1348                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1349                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1350                 }
1351         }
1352
1353         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1354                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1355                        obd2cli_tgt(imp->imp_obd),
1356                        imp->imp_connection->c_remote_uuid.uuid);
1357
1358                 rc = ptlrpc_resend(imp);
1359                 if (rc)
1360                         GOTO(out, rc);
1361                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1362                 ptlrpc_activate_import(imp);
1363
1364                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1365                           &target_start, &target_len);
1366                 LCONSOLE_INFO("%s: Connection restored to service %.*s "
1367                               "using nid %s.\n", imp->imp_obd->obd_name,
1368                               target_len, target_start,
1369                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1370         }
1371
1372         if (imp->imp_state == LUSTRE_IMP_FULL) {
1373                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1374                 ptlrpc_wake_delayed(imp);
1375         }
1376
1377 out:
1378         RETURN(rc);
1379 }
1380
1381 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1382 {
1383         struct ptlrpc_request *req;
1384         int rq_opc, rc = 0;
1385         int nowait = imp->imp_obd->obd_force;
1386         ENTRY;
1387
1388         if (nowait)
1389                 GOTO(set_state, rc);
1390
1391         switch (imp->imp_connect_op) {
1392         case OST_CONNECT: rq_opc = OST_DISCONNECT; break;
1393         case MDS_CONNECT: rq_opc = MDS_DISCONNECT; break;
1394         case MGS_CONNECT: rq_opc = MGS_DISCONNECT; break;
1395         default:
1396                 CERROR("don't know how to disconnect from %s (connect_op %d)\n",
1397                        obd2cli_tgt(imp->imp_obd), imp->imp_connect_op);
1398                 RETURN(-EINVAL);
1399         }
1400
1401         if (ptlrpc_import_in_recovery(imp)) {
1402                 struct l_wait_info lwi;
1403                 cfs_duration_t timeout;
1404
1405
1406                 if (AT_OFF) {
1407                         if (imp->imp_server_timeout)
1408                                 timeout = cfs_time_seconds(obd_timeout / 2);
1409                         else
1410                                 timeout = cfs_time_seconds(obd_timeout);
1411                 } else {
1412                         int idx = import_at_get_index(imp,
1413                                 imp->imp_client->cli_request_portal);
1414                         timeout = cfs_time_seconds(
1415                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1416                 }
1417
1418                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1419                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1420                 rc = l_wait_event(imp->imp_recovery_waitq,
1421                                   !ptlrpc_import_in_recovery(imp), &lwi);
1422
1423         }
1424
1425         cfs_spin_lock(&imp->imp_lock);
1426         if (imp->imp_state != LUSTRE_IMP_FULL)
1427                 GOTO(out, 0);
1428
1429         cfs_spin_unlock(&imp->imp_lock);
1430
1431         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1432                                         LUSTRE_OBD_VERSION, rq_opc);
1433         if (req) {
1434                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1435                  * it fails.  We can get through the above with a down server
1436                  * if the client doesn't know the server is gone yet. */
1437                 req->rq_no_resend = 1;
1438
1439 #ifndef CRAY_XT3
1440                 /* We want client umounts to happen quickly, no matter the
1441                    server state... */
1442                 req->rq_timeout = min_t(int, req->rq_timeout,
1443                                         INITIAL_CONNECT_TIMEOUT);
1444 #else
1445                 /* ... but we always want liblustre clients to nicely
1446                    disconnect, so only use the adaptive value. */
1447                 if (AT_OFF)
1448                         req->rq_timeout = obd_timeout / 3;
1449 #endif
1450
1451                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1452                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1453                 ptlrpc_request_set_replen(req);
1454                 rc = ptlrpc_queue_wait(req);
1455                 ptlrpc_req_finished(req);
1456         }
1457
1458 set_state:
1459         cfs_spin_lock(&imp->imp_lock);
1460 out:
1461         if (noclose)
1462                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1463         else
1464                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1465         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1466         /* Try all connections in the future - bz 12758 */
1467         imp->imp_last_recon = 0;
1468         cfs_spin_unlock(&imp->imp_lock);
1469
1470         RETURN(rc);
1471 }
1472
1473 void ptlrpc_cleanup_imp(struct obd_import *imp)
1474 {
1475         ENTRY;
1476
1477         cfs_spin_lock(&imp->imp_lock);
1478         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1479         imp->imp_generation++;
1480         cfs_spin_unlock(&imp->imp_lock);
1481         ptlrpc_abort_inflight(imp);
1482
1483         EXIT;
1484 }
1485
1486 /* Adaptive Timeout utils */
1487 extern unsigned int at_min, at_max, at_history;
1488
1489 /* Bin into timeslices using AT_BINS bins.
1490    This gives us a max of the last binlimit*AT_BINS secs without the storage,
1491    but still smoothing out a return to normalcy from a slow response.
1492    (E.g. remember the maximum latency in each minute of the last 4 minutes.) */
1493 int at_measured(struct adaptive_timeout *at, unsigned int val)
1494 {
1495         unsigned int old = at->at_current;
1496         time_t now = cfs_time_current_sec();
1497         time_t binlimit = max_t(time_t, at_history / AT_BINS, 1);
1498
1499         LASSERT(at);
1500         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1501                val, at, now - at->at_binstart, at->at_current,
1502                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1503
1504         if (val == 0)
1505                 /* 0's don't count, because we never want our timeout to
1506                    drop to 0, and because 0 could mean an error */
1507                 return 0;
1508
1509         cfs_spin_lock(&at->at_lock);
1510
1511         if (unlikely(at->at_binstart == 0)) {
1512                 /* Special case to remove default from history */
1513                 at->at_current = val;
1514                 at->at_worst_ever = val;
1515                 at->at_worst_time = now;
1516                 at->at_hist[0] = val;
1517                 at->at_binstart = now;
1518         } else if (now - at->at_binstart < binlimit ) {
1519                 /* in bin 0 */
1520                 at->at_hist[0] = max(val, at->at_hist[0]);
1521                 at->at_current = max(val, at->at_current);
1522         } else {
1523                 int i, shift;
1524                 unsigned int maxv = val;
1525                 /* move bins over */
1526                 shift = (now - at->at_binstart) / binlimit;
1527                 LASSERT(shift > 0);
1528                 for(i = AT_BINS - 1; i >= 0; i--) {
1529                         if (i >= shift) {
1530                                 at->at_hist[i] = at->at_hist[i - shift];
1531                                 maxv = max(maxv, at->at_hist[i]);
1532                         } else {
1533                                 at->at_hist[i] = 0;
1534                         }
1535                 }
1536                 at->at_hist[0] = val;
1537                 at->at_current = maxv;
1538                 at->at_binstart += shift * binlimit;
1539         }
1540
1541         if (at->at_current > at->at_worst_ever) {
1542                 at->at_worst_ever = at->at_current;
1543                 at->at_worst_time = now;
1544         }
1545
1546         if (at->at_flags & AT_FLG_NOHIST)
1547                 /* Only keep last reported val; keeping the rest of the history
1548                    for proc only */
1549                 at->at_current = val;
1550
1551         if (at_max > 0)
1552                 at->at_current =  min(at->at_current, at_max);
1553         at->at_current =  max(at->at_current, at_min);
1554
1555         if (at->at_current != old)
1556                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1557                        "(val=%u) hist %u %u %u %u\n", at,
1558                        old, at->at_current, at->at_current - old, val,
1559                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1560                        at->at_hist[3]);
1561
1562         /* if we changed, report the old value */
1563         old = (at->at_current != old) ? old : 0;
1564
1565         cfs_spin_unlock(&at->at_lock);
1566         return old;
1567 }
1568
1569 /* Find the imp_at index for a given portal; assign if space available */
1570 int import_at_get_index(struct obd_import *imp, int portal)
1571 {
1572         struct imp_at *at = &imp->imp_at;
1573         int i;
1574
1575         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1576                 if (at->iat_portal[i] == portal)
1577                         return i;
1578                 if (at->iat_portal[i] == 0)
1579                         /* unused */
1580                         break;
1581         }
1582
1583         /* Not found in list, add it under a lock */
1584         cfs_spin_lock(&imp->imp_lock);
1585
1586         /* Check unused under lock */
1587         for (; i < IMP_AT_MAX_PORTALS; i++) {
1588                 if (at->iat_portal[i] == portal)
1589                         goto out;
1590                 if (at->iat_portal[i] == 0)
1591                         /* unused */
1592                         break;
1593         }
1594
1595         /* Not enough portals? */
1596         LASSERT(i < IMP_AT_MAX_PORTALS);
1597
1598         at->iat_portal[i] = portal;
1599 out:
1600         cfs_spin_unlock(&imp->imp_lock);
1601         return i;
1602 }