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