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