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