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