Whamcloud - gitweb
LU-4413 ptlrpc: don't try to recover no_recov connection
[fs/lustre-release.git] / 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, 2013, 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 #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         spin_lock(&imp->imp_lock);                                      \
92         IMPORT_SET_STATE_NOLOCK(imp, state);                            \
93         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         spin_lock(&imp->imp_lock);
110
111         imp->imp_generation++;
112         imp->imp_state =  LUSTRE_IMP_NEW;
113
114         spin_unlock(&imp->imp_lock);
115
116         return 0;
117 }
118 EXPORT_SYMBOL(ptlrpc_init_import);
119
120 #define UUID_STR "_UUID"
121 void deuuidify(char *uuid, const char *prefix, char **uuid_start, int *uuid_len)
122 {
123         *uuid_start = !prefix || strncmp(uuid, prefix, strlen(prefix))
124                 ? uuid : uuid + strlen(prefix);
125
126         *uuid_len = strlen(*uuid_start);
127
128         if (*uuid_len < strlen(UUID_STR))
129                 return;
130
131         if (!strncmp(*uuid_start + *uuid_len - strlen(UUID_STR),
132                     UUID_STR, strlen(UUID_STR)))
133                 *uuid_len -= strlen(UUID_STR);
134 }
135 EXPORT_SYMBOL(deuuidify);
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         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 %.*s (at %s) was "
164                                "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 "
170                                "%.*s (at %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                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
177                 spin_unlock(&imp->imp_lock);
178
179                 if (obd_dump_on_timeout)
180                         libcfs_debug_dumplog();
181
182                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_DISCON);
183                 rc = 1;
184         } else {
185                 spin_unlock(&imp->imp_lock);
186                 CDEBUG(D_HA, "%s: import %p already %s (conn %u, was %u): %s\n",
187                        imp->imp_client->cli_name, imp,
188                        (imp->imp_state == LUSTRE_IMP_FULL &&
189                         imp->imp_conn_cnt > conn_cnt) ?
190                        "reconnected" : "not connected", imp->imp_conn_cnt,
191                        conn_cnt, ptlrpc_import_state_name(imp->imp_state));
192         }
193
194         return rc;
195 }
196
197 /* Must be called with imp_lock held! */
198 static void ptlrpc_deactivate_and_unlock_import(struct obd_import *imp)
199 {
200         ENTRY;
201         LASSERT(spin_is_locked(&imp->imp_lock));
202
203         CDEBUG(D_HA, "setting import %s INVALID\n", obd2cli_tgt(imp->imp_obd));
204         imp->imp_invalid = 1;
205         imp->imp_generation++;
206         spin_unlock(&imp->imp_lock);
207
208         ptlrpc_abort_inflight(imp);
209         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INACTIVE);
210
211         EXIT;
212 }
213
214 /*
215  * This acts as a barrier; all existing requests are rejected, and
216  * no new requests will be accepted until the import is valid again.
217  */
218 void ptlrpc_deactivate_import(struct obd_import *imp)
219 {
220         spin_lock(&imp->imp_lock);
221         ptlrpc_deactivate_and_unlock_import(imp);
222 }
223 EXPORT_SYMBOL(ptlrpc_deactivate_import);
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         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         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                         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                         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         wake_up_all(&imp->imp_recovery_waitq);
381 }
382 EXPORT_SYMBOL(ptlrpc_invalidate_import);
383
384 /* unset imp_invalid */
385 void ptlrpc_activate_import(struct obd_import *imp)
386 {
387         struct obd_device *obd = imp->imp_obd;
388
389         spin_lock(&imp->imp_lock);
390         if (imp->imp_deactive != 0) {
391                 spin_unlock(&imp->imp_lock);
392                 return;
393         }
394
395         imp->imp_invalid = 0;
396         spin_unlock(&imp->imp_lock);
397         obd_import_event(obd, imp, IMP_EVENT_ACTIVE);
398 }
399 EXPORT_SYMBOL(ptlrpc_activate_import);
400
401 void ptlrpc_fail_import(struct obd_import *imp, __u32 conn_cnt)
402 {
403         ENTRY;
404
405         LASSERT(!imp->imp_dlm_fake);
406
407         if (ptlrpc_set_import_discon(imp, conn_cnt)) {
408                 if (!imp->imp_replayable) {
409                         CDEBUG(D_HA, "import %s@%s for %s not replayable, "
410                                "auto-deactivating\n",
411                                obd2cli_tgt(imp->imp_obd),
412                                imp->imp_connection->c_remote_uuid.uuid,
413                                imp->imp_obd->obd_name);
414                         ptlrpc_deactivate_import(imp);
415                 }
416
417                 CDEBUG(D_HA, "%s: waking up pinger\n",
418                        obd2cli_tgt(imp->imp_obd));
419
420                 spin_lock(&imp->imp_lock);
421                 imp->imp_force_verify = 1;
422                 spin_unlock(&imp->imp_lock);
423
424                 ptlrpc_pinger_wake_up();
425         }
426         EXIT;
427 }
428 EXPORT_SYMBOL(ptlrpc_fail_import);
429
430 int ptlrpc_reconnect_import(struct obd_import *imp)
431 {
432         ptlrpc_set_import_discon(imp, 0);
433         /* Force a new connect attempt */
434         ptlrpc_invalidate_import(imp);
435         /* Do a fresh connect next time by zeroing the handle */
436         ptlrpc_disconnect_import(imp, 1);
437         /* Wait for all invalidate calls to finish */
438         if (cfs_atomic_read(&imp->imp_inval_count) > 0) {
439                 int rc;
440                 struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
441                 rc = l_wait_event(imp->imp_recovery_waitq,
442                                   (cfs_atomic_read(&imp->imp_inval_count) == 0),
443                                   &lwi);
444                 if (rc)
445                         CERROR("Interrupted, inval=%d\n",
446                                cfs_atomic_read(&imp->imp_inval_count));
447         }
448
449         /* Allow reconnect attempts */
450         imp->imp_obd->obd_no_recov = 0;
451         /* Remove 'invalid' flag */
452         ptlrpc_activate_import(imp);
453         /* Attempt a new connect */
454         ptlrpc_recover_import(imp, NULL, 0);
455         return 0;
456 }
457 EXPORT_SYMBOL(ptlrpc_reconnect_import);
458
459 /**
460  * Connection on import \a imp is changed to another one (if more than one is
461  * present). We typically chose connection that we have not tried to connect to
462  * the longest
463  */
464 static int import_select_connection(struct obd_import *imp)
465 {
466         struct obd_import_conn *imp_conn = NULL, *conn;
467         struct obd_export *dlmexp;
468         char *target_start;
469         int target_len, tried_all = 1;
470         ENTRY;
471
472         spin_lock(&imp->imp_lock);
473
474         if (cfs_list_empty(&imp->imp_conn_list)) {
475                 CERROR("%s: no connections available\n",
476                        imp->imp_obd->obd_name);
477                 spin_unlock(&imp->imp_lock);
478                 RETURN(-EINVAL);
479         }
480
481         cfs_list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
482                 CDEBUG(D_HA, "%s: connect to NID %s last attempt "LPU64"\n",
483                        imp->imp_obd->obd_name,
484                        libcfs_nid2str(conn->oic_conn->c_peer.nid),
485                        conn->oic_last_attempt);
486
487                 /* If we have not tried this connection since
488                    the last successful attempt, go with this one */
489                 if ((conn->oic_last_attempt == 0) ||
490                     cfs_time_beforeq_64(conn->oic_last_attempt,
491                                        imp->imp_last_success_conn)) {
492                         imp_conn = conn;
493                         tried_all = 0;
494                         break;
495                 }
496
497                 /* If all of the connections have already been tried
498                    since the last successful connection; just choose the
499                    least recently used */
500                 if (!imp_conn)
501                         imp_conn = conn;
502                 else if (cfs_time_before_64(conn->oic_last_attempt,
503                                             imp_conn->oic_last_attempt))
504                         imp_conn = conn;
505         }
506
507         /* if not found, simply choose the current one */
508         if (!imp_conn || imp->imp_force_reconnect) {
509                 LASSERT(imp->imp_conn_current);
510                 imp_conn = imp->imp_conn_current;
511                 tried_all = 0;
512         }
513         LASSERT(imp_conn->oic_conn);
514
515         /* If we've tried everything, and we're back to the beginning of the
516            list, increase our timeout and try again. It will be reset when
517            we do finally connect. (FIXME: really we should wait for all network
518            state associated with the last connection attempt to drain before
519            trying to reconnect on it.) */
520         if (tried_all && (imp->imp_conn_list.next == &imp_conn->oic_item)) {
521                 struct adaptive_timeout *at = &imp->imp_at.iat_net_latency;
522                 if (at_get(at) < CONNECTION_SWITCH_MAX) {
523                         at_measured(at, at_get(at) + CONNECTION_SWITCH_INC);
524                         if (at_get(at) > CONNECTION_SWITCH_MAX)
525                                 at_reset(at, CONNECTION_SWITCH_MAX);
526                 }
527                 LASSERT(imp_conn->oic_last_attempt);
528                 CDEBUG(D_HA, "%s: tried all connections, increasing latency "
529                         "to %ds\n", imp->imp_obd->obd_name, at_get(at));
530         }
531
532         imp_conn->oic_last_attempt = cfs_time_current_64();
533
534         /* switch connection, don't mind if it's same as the current one */
535         if (imp->imp_connection)
536                 ptlrpc_connection_put(imp->imp_connection);
537         imp->imp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
538
539         dlmexp =  class_conn2export(&imp->imp_dlm_handle);
540         LASSERT(dlmexp != NULL);
541         if (dlmexp->exp_connection)
542                 ptlrpc_connection_put(dlmexp->exp_connection);
543         dlmexp->exp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
544         class_export_put(dlmexp);
545
546         if (imp->imp_conn_current != imp_conn) {
547                 if (imp->imp_conn_current) {
548                         deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
549                                   &target_start, &target_len);
550
551                         CDEBUG(D_HA, "%s: Connection changing to"
552                                " %.*s (at %s)\n",
553                                imp->imp_obd->obd_name,
554                                target_len, target_start,
555                                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
556                 }
557
558                 imp->imp_conn_current = imp_conn;
559         }
560
561         CDEBUG(D_HA, "%s: import %p using connection %s/%s\n",
562                imp->imp_obd->obd_name, imp, imp_conn->oic_uuid.uuid,
563                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
564
565         spin_unlock(&imp->imp_lock);
566
567         RETURN(0);
568 }
569
570 /*
571  * must be called under imp_lock
572  */
573 static int ptlrpc_first_transno(struct obd_import *imp, __u64 *transno)
574 {
575         struct ptlrpc_request   *req;
576         cfs_list_t              *tmp;
577
578         /* The requests in committed_list always have smaller transnos than
579          * the requests in replay_list */
580         if (!cfs_list_empty(&imp->imp_committed_list)) {
581                 tmp = imp->imp_committed_list.next;
582                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_replay_list);
583                 *transno = req->rq_transno;
584                 if (req->rq_transno == 0) {
585                         DEBUG_REQ(D_ERROR, req, "zero transno in committed_list");
586                         LBUG();
587                 }
588                 return 1;
589         }
590         if (!cfs_list_empty(&imp->imp_replay_list)) {
591                 tmp = imp->imp_replay_list.next;
592                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_replay_list);
593                 *transno = req->rq_transno;
594                 if (req->rq_transno == 0) {
595                         DEBUG_REQ(D_ERROR, req, "zero transno in replay_list");
596                         LBUG();
597                 }
598                 return 1;
599         }
600         return 0;
601 }
602
603 /**
604  * Attempt to (re)connect import \a imp. This includes all preparations,
605  * initializing CONNECT RPC request and passing it to ptlrpcd for
606  * actual sending.
607  * Returns 0 on success or error code.
608  */
609 int ptlrpc_connect_import(struct obd_import *imp)
610 {
611         struct obd_device *obd = imp->imp_obd;
612         int initial_connect = 0;
613         int set_transno = 0;
614         __u64 committed_before_reconnect = 0;
615         struct ptlrpc_request *request;
616         char *bufs[] = { NULL,
617                          obd2cli_tgt(imp->imp_obd),
618                          obd->obd_uuid.uuid,
619                          (char *)&imp->imp_dlm_handle,
620                          (char *)&imp->imp_connect_data };
621         struct ptlrpc_connect_async_args *aa;
622         int rc;
623         ENTRY;
624
625         spin_lock(&imp->imp_lock);
626         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
627                 spin_unlock(&imp->imp_lock);
628                 CERROR("can't connect to a closed import\n");
629                 RETURN(-EINVAL);
630         } else if (imp->imp_state == LUSTRE_IMP_FULL) {
631                 spin_unlock(&imp->imp_lock);
632                 CERROR("already connected\n");
633                 RETURN(0);
634         } else if (imp->imp_state == LUSTRE_IMP_CONNECTING) {
635                 spin_unlock(&imp->imp_lock);
636                 CERROR("already connecting\n");
637                 RETURN(-EALREADY);
638         }
639
640         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CONNECTING);
641
642         imp->imp_conn_cnt++;
643         imp->imp_resend_replay = 0;
644
645         if (!lustre_handle_is_used(&imp->imp_remote_handle))
646                 initial_connect = 1;
647         else
648                 committed_before_reconnect = imp->imp_peer_committed_transno;
649
650         set_transno = ptlrpc_first_transno(imp,
651                                            &imp->imp_connect_data.ocd_transno);
652         spin_unlock(&imp->imp_lock);
653
654         rc = import_select_connection(imp);
655         if (rc)
656                 GOTO(out, rc);
657
658         rc = sptlrpc_import_sec_adapt(imp, NULL, 0);
659         if (rc)
660                 GOTO(out, rc);
661
662         /* Reset connect flags to the originally requested flags, in case
663          * the server is updated on-the-fly we will get the new features. */
664         imp->imp_connect_data.ocd_connect_flags = imp->imp_connect_flags_orig;
665         /* Reset ocd_version each time so the server knows the exact versions */
666         imp->imp_connect_data.ocd_version = LUSTRE_VERSION_CODE;
667         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
668         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
669
670         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
671                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
672         if (rc)
673                 GOTO(out, rc);
674
675         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
676         if (request == NULL)
677                 GOTO(out, rc = -ENOMEM);
678
679         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
680                                       imp->imp_connect_op, bufs, NULL);
681         if (rc) {
682                 ptlrpc_request_free(request);
683                 GOTO(out, rc);
684         }
685
686         /* Report the rpc service time to the server so that it knows how long
687          * to wait for clients to join recovery */
688         lustre_msg_set_service_time(request->rq_reqmsg,
689                                     at_timeout2est(request->rq_timeout));
690
691         /* The amount of time we give the server to process the connect req.
692          * import_select_connection will increase the net latency on
693          * repeated reconnect attempts to cover slow networks.
694          * We override/ignore the server rpc completion estimate here,
695          * which may be large if this is a reconnect attempt */
696         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
697         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
698
699 #ifndef __KERNEL__
700         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_LIBCLIENT);
701 #endif
702         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
703
704         request->rq_no_resend = request->rq_no_delay = 1;
705         request->rq_send_state = LUSTRE_IMP_CONNECTING;
706         /* Allow a slightly larger reply for future growth compatibility */
707         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
708                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
709         ptlrpc_request_set_replen(request);
710         request->rq_interpret_reply = ptlrpc_connect_interpret;
711
712         CLASSERT(sizeof (*aa) <= sizeof (request->rq_async_args));
713         aa = ptlrpc_req_async_args(request);
714         memset(aa, 0, sizeof *aa);
715
716         aa->pcaa_peer_committed = committed_before_reconnect;
717         aa->pcaa_initial_connect = initial_connect;
718
719         if (aa->pcaa_initial_connect) {
720                 spin_lock(&imp->imp_lock);
721                 imp->imp_replayable = 1;
722                 spin_unlock(&imp->imp_lock);
723                 lustre_msg_add_op_flags(request->rq_reqmsg,
724                                         MSG_CONNECT_INITIAL);
725         }
726
727         if (set_transno)
728                 lustre_msg_add_op_flags(request->rq_reqmsg,
729                                         MSG_CONNECT_TRANSNO);
730
731         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %d)",
732                   request->rq_timeout);
733         ptlrpcd_add_req(request, PDL_POLICY_ROUND, -1);
734         rc = 0;
735 out:
736         if (rc != 0) {
737                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
738         }
739
740         RETURN(rc);
741 }
742 EXPORT_SYMBOL(ptlrpc_connect_import);
743
744 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
745 {
746 #ifdef __KERNEL__
747         int force_verify;
748
749         spin_lock(&imp->imp_lock);
750         force_verify = imp->imp_force_verify != 0;
751         spin_unlock(&imp->imp_lock);
752
753         if (force_verify)
754                 ptlrpc_pinger_wake_up();
755 #else
756         /* liblustre has no pinger thread, so we wakeup pinger anyway */
757         ptlrpc_pinger_wake_up();
758 #endif
759 }
760
761 static int ptlrpc_busy_reconnect(int rc)
762 {
763         return (rc == -EBUSY) || (rc == -EAGAIN);
764 }
765
766 /**
767  * interpret_reply callback for connect RPCs.
768  * Looks into returned status of connect operation and decides
769  * what to do with the import - i.e enter recovery, promote it to
770  * full state for normal operations of disconnect it due to an error.
771  */
772 static int ptlrpc_connect_interpret(const struct lu_env *env,
773                                     struct ptlrpc_request *request,
774                                     void *data, int rc)
775 {
776         struct ptlrpc_connect_async_args *aa = data;
777         struct obd_import *imp = request->rq_import;
778         struct client_obd *cli = &imp->imp_obd->u.cli;
779         struct lustre_handle old_hdl;
780         __u64 old_connect_flags;
781         int msg_flags;
782         struct obd_connect_data *ocd;
783         struct obd_export *exp;
784         int ret;
785         ENTRY;
786
787         spin_lock(&imp->imp_lock);
788         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
789                 imp->imp_connect_tried = 1;
790                 spin_unlock(&imp->imp_lock);
791                 RETURN(0);
792         }
793
794         if (rc) {
795                 /* if this reconnect to busy export - not need select new target
796                  * for connecting*/
797                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
798                 spin_unlock(&imp->imp_lock);
799                 ptlrpc_maybe_ping_import_soon(imp);
800                 GOTO(out, rc);
801         }
802         spin_unlock(&imp->imp_lock);
803
804         LASSERT(imp->imp_conn_current);
805
806         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
807
808         ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
809                                    RCL_SERVER);
810         /* server replied obd_connect_data is always bigger */
811         ocd = req_capsule_server_sized_get(&request->rq_pill,
812                                            &RMF_CONNECT_DATA, ret);
813
814         if (ocd == NULL) {
815                 CERROR("%s: no connect data from server\n",
816                        imp->imp_obd->obd_name);
817                 rc = -EPROTO;
818                 GOTO(out, rc);
819         }
820
821         spin_lock(&imp->imp_lock);
822
823         /* All imports are pingable */
824         imp->imp_pingable = 1;
825         imp->imp_force_reconnect = 0;
826         imp->imp_force_verify = 0;
827
828         imp->imp_connect_data = *ocd;
829
830         CDEBUG(D_HA, "%s: connect to target with instance %u\n",
831                imp->imp_obd->obd_name, ocd->ocd_instance);
832         exp = class_conn2export(&imp->imp_dlm_handle);
833
834         spin_unlock(&imp->imp_lock);
835
836         /* check that server granted subset of flags we asked for. */
837         if ((ocd->ocd_connect_flags & imp->imp_connect_flags_orig) !=
838             ocd->ocd_connect_flags) {
839                 CERROR("%s: Server didn't granted asked subset of flags: "
840                        "asked="LPX64" grranted="LPX64"\n",
841                        imp->imp_obd->obd_name,imp->imp_connect_flags_orig,
842                        ocd->ocd_connect_flags);
843                 GOTO(out, rc = -EPROTO);
844         }
845
846         if (!exp) {
847                 /* This could happen if export is cleaned during the
848                    connect attempt */
849                 CERROR("%s: missing export after connect\n",
850                        imp->imp_obd->obd_name);
851                 GOTO(out, rc = -ENODEV);
852         }
853         old_connect_flags = exp_connect_flags(exp);
854         exp->exp_connect_data = *ocd;
855         imp->imp_obd->obd_self_export->exp_connect_data = *ocd;
856         class_export_put(exp);
857
858         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
859
860         if (aa->pcaa_initial_connect) {
861                 spin_lock(&imp->imp_lock);
862                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
863                         imp->imp_replayable = 1;
864                         spin_unlock(&imp->imp_lock);
865                         CDEBUG(D_HA, "connected to replayable target: %s\n",
866                                obd2cli_tgt(imp->imp_obd));
867                 } else {
868                         imp->imp_replayable = 0;
869                         spin_unlock(&imp->imp_lock);
870                 }
871
872                 /* if applies, adjust the imp->imp_msg_magic here
873                  * according to reply flags */
874
875                 imp->imp_remote_handle =
876                                 *lustre_msg_get_handle(request->rq_repmsg);
877
878                 /* Initial connects are allowed for clients with non-random
879                  * uuids when servers are in recovery.  Simply signal the
880                  * servers replay is complete and wait in REPLAY_WAIT. */
881                 if (msg_flags & MSG_CONNECT_RECOVERING) {
882                         CDEBUG(D_HA, "connect to %s during recovery\n",
883                                obd2cli_tgt(imp->imp_obd));
884                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
885                 } else {
886                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
887                         ptlrpc_activate_import(imp);
888                 }
889
890                 GOTO(finish, rc = 0);
891         }
892
893         /* Determine what recovery state to move the import to. */
894         if (MSG_CONNECT_RECONNECT & msg_flags) {
895                 memset(&old_hdl, 0, sizeof(old_hdl));
896                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
897                             sizeof (old_hdl))) {
898                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
899                                       "bad handle "LPX64"\n",
900                                       obd2cli_tgt(imp->imp_obd),
901                                       imp->imp_connection->c_remote_uuid.uuid,
902                                       imp->imp_dlm_handle.cookie);
903                         GOTO(out, rc = -ENOTCONN);
904                 }
905
906                 if (memcmp(&imp->imp_remote_handle,
907                            lustre_msg_get_handle(request->rq_repmsg),
908                            sizeof(imp->imp_remote_handle))) {
909                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
910                                 D_HA : D_WARNING;
911
912                         /* Bug 16611/14775: if server handle have changed,
913                          * that means some sort of disconnection happened.
914                          * If the server is not in recovery, that also means it
915                          * already erased all of our state because of previous
916                          * eviction. If it is in recovery - we are safe to
917                          * participate since we can reestablish all of our state
918                          * with server again */
919                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
920                                 CDEBUG(level,"%s@%s changed server handle from "
921                                        LPX64" to "LPX64
922                                        " but is still in recovery\n",
923                                        obd2cli_tgt(imp->imp_obd),
924                                        imp->imp_connection->c_remote_uuid.uuid,
925                                        imp->imp_remote_handle.cookie,
926                                        lustre_msg_get_handle(
927                                        request->rq_repmsg)->cookie);
928                         } else {
929                                 LCONSOLE_WARN("Evicted from %s (at %s) "
930                                               "after server handle changed from "
931                                               LPX64" to "LPX64"\n",
932                                               obd2cli_tgt(imp->imp_obd),
933                                               imp->imp_connection-> \
934                                               c_remote_uuid.uuid,
935                                               imp->imp_remote_handle.cookie,
936                                               lustre_msg_get_handle(
937                                               request->rq_repmsg)->cookie);
938                         }
939
940
941                         imp->imp_remote_handle =
942                                      *lustre_msg_get_handle(request->rq_repmsg);
943
944                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
945                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
946                                 GOTO(finish, rc = 0);
947                         }
948
949                 } else {
950                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
951                                obd2cli_tgt(imp->imp_obd),
952                                imp->imp_connection->c_remote_uuid.uuid);
953                 }
954
955                 if (imp->imp_invalid) {
956                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
957                                "marking evicted\n", imp->imp_obd->obd_name);
958                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
959                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
960                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
961                                imp->imp_obd->obd_name,
962                                obd2cli_tgt(imp->imp_obd));
963
964                         spin_lock(&imp->imp_lock);
965                         imp->imp_resend_replay = 1;
966                         spin_unlock(&imp->imp_lock);
967
968                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
969                 } else {
970                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
971                 }
972         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
973                 LASSERT(imp->imp_replayable);
974                 imp->imp_remote_handle =
975                                 *lustre_msg_get_handle(request->rq_repmsg);
976                 imp->imp_last_replay_transno = 0;
977                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
978         } else {
979                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
980                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
981                 imp->imp_remote_handle =
982                                 *lustre_msg_get_handle(request->rq_repmsg);
983                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
984         }
985
986         /* Sanity checks for a reconnected import. */
987         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
988                 CERROR("imp_replayable flag does not match server "
989                        "after reconnect. We should LBUG right here.\n");
990         }
991
992         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
993             lustre_msg_get_last_committed(request->rq_repmsg) <
994             aa->pcaa_peer_committed) {
995                 CERROR("%s went back in time (transno "LPD64
996                        " was previously committed, server now claims "LPD64
997                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
998                        "id=9646\n",
999                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
1000                        lustre_msg_get_last_committed(request->rq_repmsg));
1001         }
1002
1003 finish:
1004         rc = ptlrpc_import_recovery_state_machine(imp);
1005         if (rc != 0) {
1006                 if (rc == -ENOTCONN) {
1007                         CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
1008                                "invalidating and reconnecting\n",
1009                                obd2cli_tgt(imp->imp_obd),
1010                                imp->imp_connection->c_remote_uuid.uuid);
1011                         ptlrpc_connect_import(imp);
1012                         imp->imp_connect_tried = 1;
1013                         RETURN(0);
1014                 }
1015         } else {
1016                 static bool warned;
1017
1018                 spin_lock(&imp->imp_lock);
1019                 cfs_list_del(&imp->imp_conn_current->oic_item);
1020                 cfs_list_add(&imp->imp_conn_current->oic_item,
1021                              &imp->imp_conn_list);
1022                 imp->imp_last_success_conn =
1023                         imp->imp_conn_current->oic_last_attempt;
1024
1025                 spin_unlock(&imp->imp_lock);
1026
1027                 if (!ocd->ocd_ibits_known &&
1028                     ocd->ocd_connect_flags & OBD_CONNECT_IBITS)
1029                         CERROR("Inodebits aware server returned zero compatible"
1030                                " bits?\n");
1031
1032                 if (!warned && (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1033                     (ocd->ocd_version > LUSTRE_VERSION_CODE +
1034                                         LUSTRE_VERSION_OFFSET_WARN ||
1035                      ocd->ocd_version < LUSTRE_VERSION_CODE -
1036                                         LUSTRE_VERSION_OFFSET_WARN)) {
1037                         /* Sigh, some compilers do not like #ifdef in the middle
1038                            of macro arguments */
1039                         const char *older = "older than client. "
1040                                             "Consider upgrading server";
1041 #ifdef __KERNEL__
1042                         const char *newer = "newer than client. "
1043                                             "Consider recompiling application";
1044 #else
1045                         const char *newer = "newer than client. "
1046                                             "Consider upgrading client";
1047 #endif
1048
1049                         LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
1050                                       "is much %s (%s)\n",
1051                                       obd2cli_tgt(imp->imp_obd),
1052                                       OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1053                                       OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1054                                       OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1055                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1056                                       ocd->ocd_version > LUSTRE_VERSION_CODE ?
1057                                       newer : older, LUSTRE_VERSION_STRING);
1058                         warned = true;
1059                 }
1060
1061 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 50, 0)
1062                 /* Check if server has LU-1252 fix applied to not always swab
1063                  * the IR MNE entries. Do this only once per connection.  This
1064                  * fixup is version-limited, because we don't want to carry the
1065                  * OBD_CONNECT_MNE_SWAB flag around forever, just so long as we
1066                  * need interop with unpatched 2.2 servers.  For newer servers,
1067                  * the client will do MNE swabbing only as needed.  LU-1644 */
1068                 if (unlikely((ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1069                              !(ocd->ocd_connect_flags & OBD_CONNECT_MNE_SWAB) &&
1070                              OBD_OCD_VERSION_MAJOR(ocd->ocd_version) == 2 &&
1071                              OBD_OCD_VERSION_MINOR(ocd->ocd_version) == 2 &&
1072                              OBD_OCD_VERSION_PATCH(ocd->ocd_version) < 55 &&
1073                              strcmp(imp->imp_obd->obd_type->typ_name,
1074                                     LUSTRE_MGC_NAME) == 0))
1075                         imp->imp_need_mne_swab = 1;
1076                 else /* clear if server was upgraded since last connect */
1077                         imp->imp_need_mne_swab = 0;
1078 #else
1079 #warning "LU-1644: Remove old OBD_CONNECT_MNE_SWAB fixup and imp_need_mne_swab"
1080 #endif
1081
1082                 if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
1083                         /* We sent to the server ocd_cksum_types with bits set
1084                          * for algorithms we understand. The server masked off
1085                          * the checksum types it doesn't support */
1086                         if ((ocd->ocd_cksum_types &
1087                              cksum_types_supported_client()) == 0) {
1088                                 LCONSOLE_WARN("The negotiation of the checksum "
1089                                               "alogrithm to use with server %s "
1090                                               "failed (%x/%x), disabling "
1091                                               "checksums\n",
1092                                               obd2cli_tgt(imp->imp_obd),
1093                                               ocd->ocd_cksum_types,
1094                                               cksum_types_supported_client());
1095                                 cli->cl_checksum = 0;
1096                                 cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
1097                         } else {
1098                                 cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
1099                         }
1100                 } else {
1101                         /* The server does not support OBD_CONNECT_CKSUM.
1102                          * Enforce ADLER for backward compatibility*/
1103                         cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
1104                 }
1105                 cli->cl_cksum_type =cksum_type_select(cli->cl_supp_cksum_types);
1106
1107                 if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE)
1108                         cli->cl_max_pages_per_rpc =
1109                                 min(ocd->ocd_brw_size >> PAGE_CACHE_SHIFT,
1110                                     cli->cl_max_pages_per_rpc);
1111                 else if (imp->imp_connect_op == MDS_CONNECT ||
1112                          imp->imp_connect_op == MGS_CONNECT)
1113                         cli->cl_max_pages_per_rpc = 1;
1114
1115                 /* Reset ns_connect_flags only for initial connect. It might be
1116                  * changed in while using FS and if we reset it in reconnect
1117                  * this leads to losing user settings done before such as
1118                  * disable lru_resize, etc. */
1119                 if (old_connect_flags != exp_connect_flags(exp) ||
1120                     aa->pcaa_initial_connect) {
1121                         CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
1122                                "flags: "LPX64"\n", imp->imp_obd->obd_name,
1123                               ocd->ocd_connect_flags);
1124                         imp->imp_obd->obd_namespace->ns_connect_flags =
1125                                 ocd->ocd_connect_flags;
1126                         imp->imp_obd->obd_namespace->ns_orig_connect_flags =
1127                                 ocd->ocd_connect_flags;
1128                 }
1129
1130                 if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
1131                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1132                         /* We need a per-message support flag, because
1133                            a. we don't know if the incoming connect reply
1134                               supports AT or not (in reply_in_callback)
1135                               until we unpack it.
1136                            b. failovered server means export and flags are gone
1137                               (in ptlrpc_send_reply).
1138                            Can only be set when we know AT is supported at
1139                            both ends */
1140                         imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1141                 else
1142                         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1143
1144                 if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1145                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1146                         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1147                 else
1148                         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1149
1150                 LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
1151                         (cli->cl_max_pages_per_rpc > 0));
1152         }
1153
1154 out:
1155         imp->imp_connect_tried = 1;
1156
1157         if (rc != 0) {
1158                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1159                 if (rc == -EACCES) {
1160                         /*
1161                          * Give up trying to reconnect
1162                          * EACCES means client has no permission for connection
1163                          */
1164                         imp->imp_obd->obd_no_recov = 1;
1165                         ptlrpc_deactivate_import(imp);
1166                 }
1167
1168                 if (rc == -EPROTO) {
1169                         struct obd_connect_data *ocd;
1170
1171                         /* reply message might not be ready */
1172                         if (request->rq_repmsg == NULL)
1173                                 RETURN(-EPROTO);
1174
1175                         ocd = req_capsule_server_get(&request->rq_pill,
1176                                                      &RMF_CONNECT_DATA);
1177                         if (ocd &&
1178                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1179                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1180                            /* Actually servers are only supposed to refuse
1181                               connection from liblustre clients, so we should
1182                               never see this from VFS context */
1183                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1184                                         "(%d.%d.%d.%d)"
1185                                         " refused connection from this client "
1186                                         "with an incompatible version (%s).  "
1187                                         "Client must be recompiled\n",
1188                                         obd2cli_tgt(imp->imp_obd),
1189                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1190                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1191                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1192                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1193                                         LUSTRE_VERSION_STRING);
1194                                 ptlrpc_deactivate_import(imp);
1195                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1196                         }
1197                         RETURN(-EPROTO);
1198                 }
1199
1200                 ptlrpc_maybe_ping_import_soon(imp);
1201
1202                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1203                        obd2cli_tgt(imp->imp_obd),
1204                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1205         }
1206
1207         wake_up_all(&imp->imp_recovery_waitq);
1208         RETURN(rc);
1209 }
1210
1211 /**
1212  * interpret callback for "completed replay" RPCs.
1213  * \see signal_completed_replay
1214  */
1215 static int completed_replay_interpret(const struct lu_env *env,
1216                                       struct ptlrpc_request *req,
1217                                       void * data, int rc)
1218 {
1219         ENTRY;
1220         cfs_atomic_dec(&req->rq_import->imp_replay_inflight);
1221         if (req->rq_status == 0 &&
1222             !req->rq_import->imp_vbr_failed) {
1223                 ptlrpc_import_recovery_state_machine(req->rq_import);
1224         } else {
1225                 if (req->rq_import->imp_vbr_failed) {
1226                         CDEBUG(D_WARNING,
1227                                "%s: version recovery fails, reconnecting\n",
1228                                req->rq_import->imp_obd->obd_name);
1229                 } else {
1230                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1231                                      "reconnecting\n",
1232                                req->rq_import->imp_obd->obd_name,
1233                                req->rq_status);
1234                 }
1235                 ptlrpc_connect_import(req->rq_import);
1236         }
1237
1238         RETURN(0);
1239 }
1240
1241 /**
1242  * Let server know that we have no requests to replay anymore.
1243  * Achieved by just sending a PING request
1244  */
1245 static int signal_completed_replay(struct obd_import *imp)
1246 {
1247         struct ptlrpc_request *req;
1248         ENTRY;
1249
1250         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1251                 RETURN(0);
1252
1253         LASSERT(cfs_atomic_read(&imp->imp_replay_inflight) == 0);
1254         cfs_atomic_inc(&imp->imp_replay_inflight);
1255
1256         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1257                                         OBD_PING);
1258         if (req == NULL) {
1259                 cfs_atomic_dec(&imp->imp_replay_inflight);
1260                 RETURN(-ENOMEM);
1261         }
1262
1263         ptlrpc_request_set_replen(req);
1264         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1265         lustre_msg_add_flags(req->rq_reqmsg,
1266                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1267         if (AT_OFF)
1268                 req->rq_timeout *= 3;
1269         req->rq_interpret_reply = completed_replay_interpret;
1270
1271         ptlrpcd_add_req(req, PDL_POLICY_ROUND, -1);
1272         RETURN(0);
1273 }
1274
1275 #ifdef __KERNEL__
1276 /**
1277  * In kernel code all import invalidation happens in its own
1278  * separate thread, so that whatever application happened to encounter
1279  * a problem could still be killed or otherwise continue
1280  */
1281 static int ptlrpc_invalidate_import_thread(void *data)
1282 {
1283         struct obd_import *imp = data;
1284
1285         ENTRY;
1286
1287         unshare_fs_struct();
1288
1289         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1290                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1291                imp->imp_connection->c_remote_uuid.uuid);
1292
1293         ptlrpc_invalidate_import(imp);
1294
1295         if (obd_dump_on_eviction) {
1296                 CERROR("dump the log upon eviction\n");
1297                 libcfs_debug_dumplog();
1298         }
1299
1300         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1301         ptlrpc_import_recovery_state_machine(imp);
1302
1303         class_import_put(imp);
1304         RETURN(0);
1305 }
1306 #endif
1307
1308 /**
1309  * This is the state machine for client-side recovery on import.
1310  *
1311  * Typicaly we have two possibly paths. If we came to server and it is not
1312  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1313  * state and reconnect from scratch.
1314  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1315  * We go through our list of requests to replay and send them to server one by
1316  * one.
1317  * After sending all request from the list we change import state to
1318  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1319  * and also all the locks we don't yet have and wait for server to grant us.
1320  * After that we send a special "replay completed" request and change import
1321  * state to IMP_REPLAY_WAIT.
1322  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1323  * state and resend all requests from sending list.
1324  * After that we promote import to FULL state and send all delayed requests
1325  * and import is fully operational after that.
1326  *
1327  */
1328 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1329 {
1330         int rc = 0;
1331         int inflight;
1332         char *target_start;
1333         int target_len;
1334
1335         ENTRY;
1336         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1337                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1338                           &target_start, &target_len);
1339                 /* Don't care about MGC eviction */
1340                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1341                            LUSTRE_MGC_NAME) != 0) {
1342                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted "
1343                                            "by %.*s; in progress operations "
1344                                            "using this service will fail.\n",
1345                                            imp->imp_obd->obd_name, target_len,
1346                                            target_start);
1347                 }
1348                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1349                        obd2cli_tgt(imp->imp_obd),
1350                        imp->imp_connection->c_remote_uuid.uuid);
1351                 /* reset vbr_failed flag upon eviction */
1352                 spin_lock(&imp->imp_lock);
1353                 imp->imp_vbr_failed = 0;
1354                 spin_unlock(&imp->imp_lock);
1355
1356 #ifdef __KERNEL__
1357                 {
1358                 struct task_struct *task;
1359                 /* bug 17802:  XXX client_disconnect_export vs connect request
1360                  * race. if client will evicted at this time, we start
1361                  * invalidate thread without reference to import and import can
1362                  * be freed at same time. */
1363                 class_import_get(imp);
1364                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1365                                      "ll_imp_inval");
1366                 if (IS_ERR(task)) {
1367                         class_import_put(imp);
1368                         CERROR("error starting invalidate thread: %d\n", rc);
1369                         rc = PTR_ERR(task);
1370                 } else {
1371                         rc = 0;
1372                 }
1373                 RETURN(rc);
1374                 }
1375 #else
1376                 ptlrpc_invalidate_import(imp);
1377
1378                 IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1379 #endif
1380         }
1381
1382         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1383                 CDEBUG(D_HA, "replay requested by %s\n",
1384                        obd2cli_tgt(imp->imp_obd));
1385                 rc = ptlrpc_replay_next(imp, &inflight);
1386                 if (inflight == 0 &&
1387                     cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1388                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1389                         rc = ldlm_replay_locks(imp);
1390                         if (rc)
1391                                 GOTO(out, rc);
1392                 }
1393                 rc = 0;
1394         }
1395
1396         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1397                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1398                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1399                         rc = signal_completed_replay(imp);
1400                         if (rc)
1401                                 GOTO(out, rc);
1402                 }
1403
1404         }
1405
1406         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1407                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1408                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1409                 }
1410         }
1411
1412         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1413                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1414                        obd2cli_tgt(imp->imp_obd),
1415                        imp->imp_connection->c_remote_uuid.uuid);
1416
1417                 rc = ptlrpc_resend(imp);
1418                 if (rc)
1419                         GOTO(out, rc);
1420                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1421                 ptlrpc_activate_import(imp);
1422
1423                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1424                           &target_start, &target_len);
1425                 LCONSOLE_INFO("%s: Connection restored to %.*s (at %s)\n",
1426                               imp->imp_obd->obd_name,
1427                               target_len, target_start,
1428                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1429         }
1430
1431         if (imp->imp_state == LUSTRE_IMP_FULL) {
1432                 wake_up_all(&imp->imp_recovery_waitq);
1433                 ptlrpc_wake_delayed(imp);
1434         }
1435
1436 out:
1437         RETURN(rc);
1438 }
1439
1440 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1441 {
1442         struct ptlrpc_request *req;
1443         int rq_opc, rc = 0;
1444         ENTRY;
1445
1446         if (imp->imp_obd->obd_force)
1447                 GOTO(set_state, rc);
1448
1449         switch (imp->imp_connect_op) {
1450         case OST_CONNECT:
1451                 rq_opc = OST_DISCONNECT;
1452                 break;
1453         case MDS_CONNECT:
1454                 rq_opc = MDS_DISCONNECT;
1455                 break;
1456         case MGS_CONNECT:
1457                 rq_opc = MGS_DISCONNECT;
1458                 break;
1459         default:
1460                 rc = -EINVAL;
1461                 CERROR("%s: don't know how to disconnect from %s "
1462                        "(connect_op %d): rc = %d\n",
1463                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1464                        imp->imp_connect_op, rc);
1465                 RETURN(rc);
1466         }
1467
1468         if (ptlrpc_import_in_recovery(imp)) {
1469                 struct l_wait_info lwi;
1470                 cfs_duration_t timeout;
1471
1472                 if (AT_OFF) {
1473                         if (imp->imp_server_timeout)
1474                                 timeout = cfs_time_seconds(obd_timeout / 2);
1475                         else
1476                                 timeout = cfs_time_seconds(obd_timeout);
1477                 } else {
1478                         int idx = import_at_get_index(imp,
1479                                 imp->imp_client->cli_request_portal);
1480                         timeout = cfs_time_seconds(
1481                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1482                 }
1483
1484                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1485                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1486                 rc = l_wait_event(imp->imp_recovery_waitq,
1487                                   !ptlrpc_import_in_recovery(imp), &lwi);
1488
1489         }
1490
1491         spin_lock(&imp->imp_lock);
1492         if (imp->imp_state != LUSTRE_IMP_FULL)
1493                 GOTO(out, rc);
1494         spin_unlock(&imp->imp_lock);
1495
1496         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1497                                         LUSTRE_OBD_VERSION, rq_opc);
1498         if (req) {
1499                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1500                  * it fails.  We can get through the above with a down server
1501                  * if the client doesn't know the server is gone yet. */
1502                 req->rq_no_resend = 1;
1503
1504                 /* We want client umounts to happen quickly, no matter the
1505                    server state... */
1506                 req->rq_timeout = min_t(int, req->rq_timeout,
1507                                         INITIAL_CONNECT_TIMEOUT);
1508
1509                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1510                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1511                 ptlrpc_request_set_replen(req);
1512                 rc = ptlrpc_queue_wait(req);
1513                 ptlrpc_req_finished(req);
1514         }
1515
1516 set_state:
1517         spin_lock(&imp->imp_lock);
1518 out:
1519         if (noclose)
1520                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1521         else
1522                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1523         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1524         spin_unlock(&imp->imp_lock);
1525
1526         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1527                 rc = 0;
1528         RETURN(rc);
1529 }
1530 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1531
1532 void ptlrpc_cleanup_imp(struct obd_import *imp)
1533 {
1534         ENTRY;
1535
1536         spin_lock(&imp->imp_lock);
1537         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1538         imp->imp_generation++;
1539         spin_unlock(&imp->imp_lock);
1540         ptlrpc_abort_inflight(imp);
1541
1542         EXIT;
1543 }
1544 EXPORT_SYMBOL(ptlrpc_cleanup_imp);
1545
1546 /* Adaptive Timeout utils */
1547 extern unsigned int at_min, at_max, at_history;
1548
1549 /* Bin into timeslices using AT_BINS bins.
1550    This gives us a max of the last binlimit*AT_BINS secs without the storage,
1551    but still smoothing out a return to normalcy from a slow response.
1552    (E.g. remember the maximum latency in each minute of the last 4 minutes.) */
1553 int at_measured(struct adaptive_timeout *at, unsigned int val)
1554 {
1555         unsigned int old = at->at_current;
1556         time_t now = cfs_time_current_sec();
1557         time_t binlimit = max_t(time_t, at_history / AT_BINS, 1);
1558
1559         LASSERT(at);
1560         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1561                val, at, now - at->at_binstart, at->at_current,
1562                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1563
1564         if (val == 0)
1565                 /* 0's don't count, because we never want our timeout to
1566                    drop to 0, and because 0 could mean an error */
1567                 return 0;
1568
1569         spin_lock(&at->at_lock);
1570
1571         if (unlikely(at->at_binstart == 0)) {
1572                 /* Special case to remove default from history */
1573                 at->at_current = val;
1574                 at->at_worst_ever = val;
1575                 at->at_worst_time = now;
1576                 at->at_hist[0] = val;
1577                 at->at_binstart = now;
1578         } else if (now - at->at_binstart < binlimit ) {
1579                 /* in bin 0 */
1580                 at->at_hist[0] = max(val, at->at_hist[0]);
1581                 at->at_current = max(val, at->at_current);
1582         } else {
1583                 int i, shift;
1584                 unsigned int maxv = val;
1585                 /* move bins over */
1586                 shift = (now - at->at_binstart) / binlimit;
1587                 LASSERT(shift > 0);
1588                 for(i = AT_BINS - 1; i >= 0; i--) {
1589                         if (i >= shift) {
1590                                 at->at_hist[i] = at->at_hist[i - shift];
1591                                 maxv = max(maxv, at->at_hist[i]);
1592                         } else {
1593                                 at->at_hist[i] = 0;
1594                         }
1595                 }
1596                 at->at_hist[0] = val;
1597                 at->at_current = maxv;
1598                 at->at_binstart += shift * binlimit;
1599         }
1600
1601         if (at->at_current > at->at_worst_ever) {
1602                 at->at_worst_ever = at->at_current;
1603                 at->at_worst_time = now;
1604         }
1605
1606         if (at->at_flags & AT_FLG_NOHIST)
1607                 /* Only keep last reported val; keeping the rest of the history
1608                    for proc only */
1609                 at->at_current = val;
1610
1611         if (at_max > 0)
1612                 at->at_current =  min(at->at_current, at_max);
1613         at->at_current =  max(at->at_current, at_min);
1614
1615         if (at->at_current != old)
1616                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1617                        "(val=%u) hist %u %u %u %u\n", at,
1618                        old, at->at_current, at->at_current - old, val,
1619                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1620                        at->at_hist[3]);
1621
1622         /* if we changed, report the old value */
1623         old = (at->at_current != old) ? old : 0;
1624
1625         spin_unlock(&at->at_lock);
1626         return old;
1627 }
1628
1629 /* Find the imp_at index for a given portal; assign if space available */
1630 int import_at_get_index(struct obd_import *imp, int portal)
1631 {
1632         struct imp_at *at = &imp->imp_at;
1633         int i;
1634
1635         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1636                 if (at->iat_portal[i] == portal)
1637                         return i;
1638                 if (at->iat_portal[i] == 0)
1639                         /* unused */
1640                         break;
1641         }
1642
1643         /* Not found in list, add it under a lock */
1644         spin_lock(&imp->imp_lock);
1645
1646         /* Check unused under lock */
1647         for (; i < IMP_AT_MAX_PORTALS; i++) {
1648                 if (at->iat_portal[i] == portal)
1649                         goto out;
1650                 if (at->iat_portal[i] == 0)
1651                         /* unused */
1652                         break;
1653         }
1654
1655         /* Not enough portals? */
1656         LASSERT(i < IMP_AT_MAX_PORTALS);
1657
1658         at->iat_portal[i] = portal;
1659 out:
1660         spin_unlock(&imp->imp_lock);
1661         return i;
1662 }