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