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