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