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