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