Whamcloud - gitweb
LU-1347 build: remove the vim/emacs modelines
[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, Whamcloud, Inc.
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         cfs_spin_lock(&imp->imp_lock);          \
92         IMPORT_SET_STATE_NOLOCK(imp, state);    \
93         cfs_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         cfs_spin_lock(&imp->imp_lock);
110
111         imp->imp_generation++;
112         imp->imp_state =  LUSTRE_IMP_NEW;
113
114         cfs_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         cfs_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                 ptlrpc_deactivate_timeouts(imp);
177                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
178                 cfs_spin_unlock(&imp->imp_lock);
179
180                 if (obd_dump_on_timeout)
181                         libcfs_debug_dumplog();
182
183                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_DISCON);
184                 rc = 1;
185         } else {
186                 cfs_spin_unlock(&imp->imp_lock);
187                 CDEBUG(D_HA, "%s: import %p already %s (conn %u, was %u): %s\n",
188                        imp->imp_client->cli_name, imp,
189                        (imp->imp_state == LUSTRE_IMP_FULL &&
190                         imp->imp_conn_cnt > conn_cnt) ?
191                        "reconnected" : "not connected", imp->imp_conn_cnt,
192                        conn_cnt, ptlrpc_import_state_name(imp->imp_state));
193         }
194
195         return rc;
196 }
197
198 /* Must be called with imp_lock held! */
199 static void ptlrpc_deactivate_and_unlock_import(struct obd_import *imp)
200 {
201         ENTRY;
202         LASSERT_SPIN_LOCKED(&imp->imp_lock);
203
204         CDEBUG(D_HA, "setting import %s INVALID\n", obd2cli_tgt(imp->imp_obd));
205         imp->imp_invalid = 1;
206         imp->imp_generation++;
207         cfs_spin_unlock(&imp->imp_lock);
208
209         ptlrpc_abort_inflight(imp);
210         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INACTIVE);
211
212         EXIT;
213 }
214
215 /*
216  * This acts as a barrier; all existing requests are rejected, and
217  * no new requests will be accepted until the import is valid again.
218  */
219 void ptlrpc_deactivate_import(struct obd_import *imp)
220 {
221         cfs_spin_lock(&imp->imp_lock);
222         ptlrpc_deactivate_and_unlock_import(imp);
223 }
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         cfs_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         cfs_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                         cfs_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                         cfs_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         cfs_waitq_broadcast(&imp->imp_recovery_waitq);
381 }
382
383 /* unset imp_invalid */
384 void ptlrpc_activate_import(struct obd_import *imp)
385 {
386         struct obd_device *obd = imp->imp_obd;
387
388         cfs_spin_lock(&imp->imp_lock);
389         imp->imp_invalid = 0;
390         ptlrpc_activate_timeouts(imp);
391         cfs_spin_unlock(&imp->imp_lock);
392         obd_import_event(obd, imp, IMP_EVENT_ACTIVE);
393 }
394
395 void ptlrpc_fail_import(struct obd_import *imp, __u32 conn_cnt)
396 {
397         ENTRY;
398
399         LASSERT(!imp->imp_dlm_fake);
400
401         if (ptlrpc_set_import_discon(imp, conn_cnt)) {
402                 if (!imp->imp_replayable) {
403                         CDEBUG(D_HA, "import %s@%s for %s not replayable, "
404                                "auto-deactivating\n",
405                                obd2cli_tgt(imp->imp_obd),
406                                imp->imp_connection->c_remote_uuid.uuid,
407                                imp->imp_obd->obd_name);
408                         ptlrpc_deactivate_import(imp);
409                 }
410
411                 CDEBUG(D_HA, "%s: waking up pinger\n",
412                        obd2cli_tgt(imp->imp_obd));
413
414                 cfs_spin_lock(&imp->imp_lock);
415                 imp->imp_force_verify = 1;
416                 cfs_spin_unlock(&imp->imp_lock);
417
418                 ptlrpc_pinger_wake_up();
419         }
420         EXIT;
421 }
422
423 int ptlrpc_reconnect_import(struct obd_import *imp)
424 {
425         ptlrpc_set_import_discon(imp, 0);
426         /* Force a new connect attempt */
427         ptlrpc_invalidate_import(imp);
428         /* Do a fresh connect next time by zeroing the handle */
429         ptlrpc_disconnect_import(imp, 1);
430         /* Wait for all invalidate calls to finish */
431         if (cfs_atomic_read(&imp->imp_inval_count) > 0) {
432                 int rc;
433                 struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
434                 rc = l_wait_event(imp->imp_recovery_waitq,
435                                   (cfs_atomic_read(&imp->imp_inval_count) == 0),
436                                   &lwi);
437                 if (rc)
438                         CERROR("Interrupted, inval=%d\n",
439                                cfs_atomic_read(&imp->imp_inval_count));
440         }
441
442         /* Allow reconnect attempts */
443         imp->imp_obd->obd_no_recov = 0;
444         /* Remove 'invalid' flag */
445         ptlrpc_activate_import(imp);
446         /* Attempt a new connect */
447         ptlrpc_recover_import(imp, NULL, 0);
448         return 0;
449 }
450 EXPORT_SYMBOL(ptlrpc_reconnect_import);
451
452 /**
453  * Connection on import \a imp is changed to another one (if more than one is
454  * present). We typically chose connection that we have not tried to connect to
455  * the longest
456  */
457 static int import_select_connection(struct obd_import *imp)
458 {
459         struct obd_import_conn *imp_conn = NULL, *conn;
460         struct obd_export *dlmexp;
461         char *target_start;
462         int target_len, tried_all = 1;
463         ENTRY;
464
465         cfs_spin_lock(&imp->imp_lock);
466
467         if (cfs_list_empty(&imp->imp_conn_list)) {
468                 CERROR("%s: no connections available\n",
469                         imp->imp_obd->obd_name);
470                 cfs_spin_unlock(&imp->imp_lock);
471                 RETURN(-EINVAL);
472         }
473
474         cfs_list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
475                 CDEBUG(D_HA, "%s: connect to NID %s last attempt "LPU64"\n",
476                        imp->imp_obd->obd_name,
477                        libcfs_nid2str(conn->oic_conn->c_peer.nid),
478                        conn->oic_last_attempt);
479
480                 /* If we have not tried this connection since
481                    the last successful attempt, go with this one */
482                 if ((conn->oic_last_attempt == 0) ||
483                     cfs_time_beforeq_64(conn->oic_last_attempt,
484                                        imp->imp_last_success_conn)) {
485                         imp_conn = conn;
486                         tried_all = 0;
487                         break;
488                 }
489
490                 /* If all of the connections have already been tried
491                    since the last successful connection; just choose the
492                    least recently used */
493                 if (!imp_conn)
494                         imp_conn = conn;
495                 else if (cfs_time_before_64(conn->oic_last_attempt,
496                                             imp_conn->oic_last_attempt))
497                         imp_conn = conn;
498         }
499
500         /* if not found, simply choose the current one */
501         if (!imp_conn || imp->imp_force_reconnect) {
502                 LASSERT(imp->imp_conn_current);
503                 imp_conn = imp->imp_conn_current;
504                 tried_all = 0;
505         }
506         LASSERT(imp_conn->oic_conn);
507
508         /* If we've tried everything, and we're back to the beginning of the
509            list, increase our timeout and try again. It will be reset when
510            we do finally connect. (FIXME: really we should wait for all network
511            state associated with the last connection attempt to drain before
512            trying to reconnect on it.) */
513         if (tried_all && (imp->imp_conn_list.next == &imp_conn->oic_item)) {
514                 if (at_get(&imp->imp_at.iat_net_latency) <
515                     CONNECTION_SWITCH_MAX) {
516                         at_measured(&imp->imp_at.iat_net_latency,
517                                     at_get(&imp->imp_at.iat_net_latency) +
518                                     CONNECTION_SWITCH_INC);
519                 }
520                 LASSERT(imp_conn->oic_last_attempt);
521                 CDEBUG(D_HA, "%s: tried all connections, increasing latency "
522                        "to %ds\n", imp->imp_obd->obd_name,
523                        at_get(&imp->imp_at.iat_net_latency));
524         }
525
526         imp_conn->oic_last_attempt = cfs_time_current_64();
527
528         /* switch connection, don't mind if it's same as the current one */
529         if (imp->imp_connection)
530                 ptlrpc_connection_put(imp->imp_connection);
531         imp->imp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
532
533         dlmexp =  class_conn2export(&imp->imp_dlm_handle);
534         LASSERT(dlmexp != NULL);
535         if (dlmexp->exp_connection)
536                 ptlrpc_connection_put(dlmexp->exp_connection);
537         dlmexp->exp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
538         class_export_put(dlmexp);
539
540         if (imp->imp_conn_current != imp_conn) {
541                 if (imp->imp_conn_current) {
542                         deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
543                                   &target_start, &target_len);
544
545                         CDEBUG(D_HA, "%s: Connection changing to"
546                                " %.*s (at %s)\n",
547                                imp->imp_obd->obd_name,
548                                target_len, target_start,
549                                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
550                 }
551
552                 imp->imp_conn_current = imp_conn;
553         }
554
555         CDEBUG(D_HA, "%s: import %p using connection %s/%s\n",
556                imp->imp_obd->obd_name, imp, imp_conn->oic_uuid.uuid,
557                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
558
559         cfs_spin_unlock(&imp->imp_lock);
560
561         RETURN(0);
562 }
563
564 /*
565  * must be called under imp_lock
566  */
567 static int ptlrpc_first_transno(struct obd_import *imp, __u64 *transno)
568 {
569         struct ptlrpc_request *req;
570         cfs_list_t *tmp;
571
572         if (cfs_list_empty(&imp->imp_replay_list))
573                 return 0;
574         tmp = imp->imp_replay_list.next;
575         req = cfs_list_entry(tmp, struct ptlrpc_request, rq_replay_list);
576         *transno = req->rq_transno;
577         if (req->rq_transno == 0) {
578                 DEBUG_REQ(D_ERROR, req, "zero transno in replay");
579                 LBUG();
580         }
581
582         return 1;
583 }
584
585 /**
586  * Attempt to (re)connect import \a imp. This includes all preparations,
587  * initializing CONNECT RPC request and passing it to ptlrpcd for
588  * actual sending.
589  * Returns 0 on success or error code.
590  */
591 int ptlrpc_connect_import(struct obd_import *imp)
592 {
593         struct obd_device *obd = imp->imp_obd;
594         int initial_connect = 0;
595         int set_transno = 0;
596         __u64 committed_before_reconnect = 0;
597         struct ptlrpc_request *request;
598         char *bufs[] = { NULL,
599                          obd2cli_tgt(imp->imp_obd),
600                          obd->obd_uuid.uuid,
601                          (char *)&imp->imp_dlm_handle,
602                          (char *)&imp->imp_connect_data };
603         struct ptlrpc_connect_async_args *aa;
604         int rc;
605         ENTRY;
606
607         cfs_spin_lock(&imp->imp_lock);
608         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
609                 cfs_spin_unlock(&imp->imp_lock);
610                 CERROR("can't connect to a closed import\n");
611                 RETURN(-EINVAL);
612         } else if (imp->imp_state == LUSTRE_IMP_FULL) {
613                 cfs_spin_unlock(&imp->imp_lock);
614                 CERROR("already connected\n");
615                 RETURN(0);
616         } else if (imp->imp_state == LUSTRE_IMP_CONNECTING) {
617                 cfs_spin_unlock(&imp->imp_lock);
618                 CERROR("already connecting\n");
619                 RETURN(-EALREADY);
620         }
621
622         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CONNECTING);
623
624         imp->imp_conn_cnt++;
625         imp->imp_resend_replay = 0;
626
627         if (!lustre_handle_is_used(&imp->imp_remote_handle))
628                 initial_connect = 1;
629         else
630                 committed_before_reconnect = imp->imp_peer_committed_transno;
631
632         set_transno = ptlrpc_first_transno(imp,
633                                            &imp->imp_connect_data.ocd_transno);
634         cfs_spin_unlock(&imp->imp_lock);
635
636         rc = import_select_connection(imp);
637         if (rc)
638                 GOTO(out, rc);
639
640         rc = sptlrpc_import_sec_adapt(imp, NULL, 0);
641         if (rc)
642                 GOTO(out, rc);
643
644         /* Reset connect flags to the originally requested flags, in case
645          * the server is updated on-the-fly we will get the new features. */
646         imp->imp_connect_data.ocd_connect_flags = imp->imp_connect_flags_orig;
647         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
648         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
649
650         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
651                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
652         if (rc)
653                 GOTO(out, rc);
654
655         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
656         if (request == NULL)
657                 GOTO(out, rc = -ENOMEM);
658
659         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
660                                       imp->imp_connect_op, bufs, NULL);
661         if (rc) {
662                 ptlrpc_request_free(request);
663                 GOTO(out, rc);
664         }
665
666         /* Report the rpc service time to the server so that it knows how long
667          * to wait for clients to join recovery */
668         lustre_msg_set_service_time(request->rq_reqmsg,
669                                     at_timeout2est(request->rq_timeout));
670
671         /* The amount of time we give the server to process the connect req.
672          * import_select_connection will increase the net latency on
673          * repeated reconnect attempts to cover slow networks.
674          * We override/ignore the server rpc completion estimate here,
675          * which may be large if this is a reconnect attempt */
676         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
677         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
678
679 #ifndef __KERNEL__
680         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_LIBCLIENT);
681 #endif
682         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
683
684         request->rq_no_resend = request->rq_no_delay = 1;
685         request->rq_send_state = LUSTRE_IMP_CONNECTING;
686         /* Allow a slightly larger reply for future growth compatibility */
687         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
688                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
689         ptlrpc_request_set_replen(request);
690         request->rq_interpret_reply = ptlrpc_connect_interpret;
691
692         CLASSERT(sizeof (*aa) <= sizeof (request->rq_async_args));
693         aa = ptlrpc_req_async_args(request);
694         memset(aa, 0, sizeof *aa);
695
696         aa->pcaa_peer_committed = committed_before_reconnect;
697         aa->pcaa_initial_connect = initial_connect;
698
699         if (aa->pcaa_initial_connect) {
700                 cfs_spin_lock(&imp->imp_lock);
701                 imp->imp_replayable = 1;
702                 cfs_spin_unlock(&imp->imp_lock);
703                 lustre_msg_add_op_flags(request->rq_reqmsg,
704                                         MSG_CONNECT_INITIAL);
705         }
706
707         if (set_transno)
708                 lustre_msg_add_op_flags(request->rq_reqmsg,
709                                         MSG_CONNECT_TRANSNO);
710
711         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %d)",
712                   request->rq_timeout);
713         ptlrpcd_add_req(request, PDL_POLICY_ROUND, -1);
714         rc = 0;
715 out:
716         if (rc != 0) {
717                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
718         }
719
720         RETURN(rc);
721 }
722 EXPORT_SYMBOL(ptlrpc_connect_import);
723
724 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
725 {
726 #ifdef __KERNEL__
727         int force_verify;
728
729         cfs_spin_lock(&imp->imp_lock);
730         force_verify = imp->imp_force_verify != 0;
731         cfs_spin_unlock(&imp->imp_lock);
732
733         if (force_verify)
734                 ptlrpc_pinger_wake_up();
735 #else
736         /* liblustre has no pinger thread, so we wakeup pinger anyway */
737         ptlrpc_pinger_wake_up();
738 #endif
739 }
740
741 static int ptlrpc_busy_reconnect(int rc)
742 {
743         return (rc == -EBUSY) || (rc == -EAGAIN);
744 }
745
746 /**
747  * interpret_reply callback for connect RPCs.
748  * Looks into returned status of connect operation and decides
749  * what to do with the import - i.e enter recovery, promote it to
750  * full state for normal operations of disconnect it due to an error.
751  */
752 static int ptlrpc_connect_interpret(const struct lu_env *env,
753                                     struct ptlrpc_request *request,
754                                     void *data, int rc)
755 {
756         struct ptlrpc_connect_async_args *aa = data;
757         struct obd_import *imp = request->rq_import;
758         struct client_obd *cli = &imp->imp_obd->u.cli;
759         struct lustre_handle old_hdl;
760         __u64 old_connect_flags;
761         int msg_flags;
762         ENTRY;
763
764         cfs_spin_lock(&imp->imp_lock);
765         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
766                 cfs_spin_unlock(&imp->imp_lock);
767                 RETURN(0);
768         }
769
770         if (rc) {
771                 /* if this reconnect to busy export - not need select new target
772                  * for connecting*/
773                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
774                 cfs_spin_unlock(&imp->imp_lock);
775                 GOTO(out, rc);
776         }
777
778         LASSERT(imp->imp_conn_current);
779
780         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
781
782         /* All imports are pingable */
783         imp->imp_pingable = 1;
784         imp->imp_force_reconnect = 0;
785         imp->imp_force_verify = 0;
786
787         if (aa->pcaa_initial_connect) {
788                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
789                         imp->imp_replayable = 1;
790                         cfs_spin_unlock(&imp->imp_lock);
791                         CDEBUG(D_HA, "connected to replayable target: %s\n",
792                                obd2cli_tgt(imp->imp_obd));
793                 } else {
794                         imp->imp_replayable = 0;
795                         cfs_spin_unlock(&imp->imp_lock);
796                 }
797
798                 /* if applies, adjust the imp->imp_msg_magic here
799                  * according to reply flags */
800
801                 imp->imp_remote_handle =
802                                 *lustre_msg_get_handle(request->rq_repmsg);
803
804                 /* Initial connects are allowed for clients with non-random
805                  * uuids when servers are in recovery.  Simply signal the
806                  * servers replay is complete and wait in REPLAY_WAIT. */
807                 if (msg_flags & MSG_CONNECT_RECOVERING) {
808                         CDEBUG(D_HA, "connect to %s during recovery\n",
809                                obd2cli_tgt(imp->imp_obd));
810                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
811                 } else {
812                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
813                         ptlrpc_activate_import(imp);
814                 }
815
816                 GOTO(finish, rc = 0);
817         } else {
818                 cfs_spin_unlock(&imp->imp_lock);
819         }
820
821         /* Determine what recovery state to move the import to. */
822         if (MSG_CONNECT_RECONNECT & msg_flags) {
823                 memset(&old_hdl, 0, sizeof(old_hdl));
824                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
825                             sizeof (old_hdl))) {
826                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
827                                       "bad handle "LPX64"\n",
828                                       obd2cli_tgt(imp->imp_obd),
829                                       imp->imp_connection->c_remote_uuid.uuid,
830                                       imp->imp_dlm_handle.cookie);
831                         GOTO(out, rc = -ENOTCONN);
832                 }
833
834                 if (memcmp(&imp->imp_remote_handle,
835                            lustre_msg_get_handle(request->rq_repmsg),
836                            sizeof(imp->imp_remote_handle))) {
837                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
838                                 D_HA : D_WARNING;
839
840                         /* Bug 16611/14775: if server handle have changed,
841                          * that means some sort of disconnection happened.
842                          * If the server is not in recovery, that also means it
843                          * already erased all of our state because of previous
844                          * eviction. If it is in recovery - we are safe to
845                          * participate since we can reestablish all of our state
846                          * with server again */
847                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
848                                 CDEBUG(level,"%s@%s changed server handle from "
849                                        LPX64" to "LPX64
850                                        " but is still in recovery\n",
851                                        obd2cli_tgt(imp->imp_obd),
852                                        imp->imp_connection->c_remote_uuid.uuid,
853                                        imp->imp_remote_handle.cookie,
854                                        lustre_msg_get_handle(
855                                        request->rq_repmsg)->cookie);
856                         } else {
857                                 LCONSOLE_WARN("Evicted from %s (at %s) "
858                                               "after server handle changed from "
859                                               LPX64" to "LPX64"\n",
860                                               obd2cli_tgt(imp->imp_obd),
861                                               imp->imp_connection-> \
862                                               c_remote_uuid.uuid,
863                                               imp->imp_remote_handle.cookie,
864                                               lustre_msg_get_handle(
865                                               request->rq_repmsg)->cookie);
866                         }
867
868
869                         imp->imp_remote_handle =
870                                      *lustre_msg_get_handle(request->rq_repmsg);
871
872                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
873                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
874                                 GOTO(finish, rc = 0);
875                         }
876
877                 } else {
878                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
879                                obd2cli_tgt(imp->imp_obd),
880                                imp->imp_connection->c_remote_uuid.uuid);
881                 }
882
883                 if (imp->imp_invalid) {
884                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
885                                "marking evicted\n", imp->imp_obd->obd_name);
886                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
887                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
888                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
889                                imp->imp_obd->obd_name,
890                                obd2cli_tgt(imp->imp_obd));
891
892                         cfs_spin_lock(&imp->imp_lock);
893                         imp->imp_resend_replay = 1;
894                         cfs_spin_unlock(&imp->imp_lock);
895
896                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
897                 } else {
898                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
899                 }
900         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
901                 LASSERT(imp->imp_replayable);
902                 imp->imp_remote_handle =
903                                 *lustre_msg_get_handle(request->rq_repmsg);
904                 imp->imp_last_replay_transno = 0;
905                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
906         } else {
907                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
908                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
909                 imp->imp_remote_handle =
910                                 *lustre_msg_get_handle(request->rq_repmsg);
911                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
912         }
913
914         /* Sanity checks for a reconnected import. */
915         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
916                 CERROR("imp_replayable flag does not match server "
917                        "after reconnect. We should LBUG right here.\n");
918         }
919
920         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
921             lustre_msg_get_last_committed(request->rq_repmsg) <
922             aa->pcaa_peer_committed) {
923                 CERROR("%s went back in time (transno "LPD64
924                        " was previously committed, server now claims "LPD64
925                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
926                        "id=9646\n",
927                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
928                        lustre_msg_get_last_committed(request->rq_repmsg));
929         }
930
931 finish:
932         rc = ptlrpc_import_recovery_state_machine(imp);
933         if (rc != 0) {
934                 if (rc == -ENOTCONN) {
935                         CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
936                                "invalidating and reconnecting\n",
937                                obd2cli_tgt(imp->imp_obd),
938                                imp->imp_connection->c_remote_uuid.uuid);
939                         ptlrpc_connect_import(imp);
940                         RETURN(0);
941                 }
942         } else {
943                 struct obd_connect_data *ocd;
944                 struct obd_export *exp;
945                 int ret;
946                 ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
947                                            RCL_SERVER);
948                 /* server replied obd_connect_data is always bigger */
949                 ocd = req_capsule_server_sized_get(&request->rq_pill,
950                                                    &RMF_CONNECT_DATA, ret);
951
952                 cfs_spin_lock(&imp->imp_lock);
953                 cfs_list_del(&imp->imp_conn_current->oic_item);
954                 cfs_list_add(&imp->imp_conn_current->oic_item,
955                              &imp->imp_conn_list);
956                 imp->imp_last_success_conn =
957                         imp->imp_conn_current->oic_last_attempt;
958
959                 if (ocd == NULL) {
960                         cfs_spin_unlock(&imp->imp_lock);
961                         CERROR("Wrong connect data from server\n");
962                         rc = -EPROTO;
963                         GOTO(out, rc);
964                 }
965
966                 imp->imp_connect_data = *ocd;
967                 CDEBUG(D_HA, "obd %s to target with inst %u\n",
968                        imp->imp_obd->obd_name, ocd->ocd_instance);
969
970                 exp = class_conn2export(&imp->imp_dlm_handle);
971                 cfs_spin_unlock(&imp->imp_lock);
972
973                 /* check that server granted subset of flags we asked for. */
974                 LASSERTF((ocd->ocd_connect_flags &
975                           imp->imp_connect_flags_orig) ==
976                          ocd->ocd_connect_flags, LPX64" != "LPX64,
977                          imp->imp_connect_flags_orig, ocd->ocd_connect_flags);
978
979                 if (!exp) {
980                         /* This could happen if export is cleaned during the
981                            connect attempt */
982                         CERROR("Missing export for %s\n",
983                                imp->imp_obd->obd_name);
984                         GOTO(out, rc = -ENODEV);
985                 }
986                 old_connect_flags = exp->exp_connect_flags;
987                 exp->exp_connect_flags = ocd->ocd_connect_flags;
988                 imp->imp_obd->obd_self_export->exp_connect_flags =
989                                                         ocd->ocd_connect_flags;
990                 class_export_put(exp);
991
992                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
993
994                 if (!ocd->ocd_ibits_known &&
995                     ocd->ocd_connect_flags & OBD_CONNECT_IBITS)
996                         CERROR("Inodebits aware server returned zero compatible"
997                                " bits?\n");
998
999                 if ((ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1000                     (ocd->ocd_version > LUSTRE_VERSION_CODE +
1001                                         LUSTRE_VERSION_OFFSET_WARN ||
1002                      ocd->ocd_version < LUSTRE_VERSION_CODE -
1003                                         LUSTRE_VERSION_OFFSET_WARN)) {
1004                         /* Sigh, some compilers do not like #ifdef in the middle
1005                            of macro arguments */
1006 #ifdef __KERNEL__
1007                         const char *older = "older. Consider upgrading server "
1008                                             "or downgrading client";
1009 #else
1010                         const char *older = "older. Consider recompiling this "
1011                                             "application";
1012 #endif
1013                         const char *newer = "newer than client version. "
1014                                             "Consider upgrading client";
1015
1016                         LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
1017                                       "is much %s (%s)\n",
1018                                       obd2cli_tgt(imp->imp_obd),
1019                                       OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1020                                       OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1021                                       OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1022                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1023                                       ocd->ocd_version > LUSTRE_VERSION_CODE ?
1024                                       newer : older, LUSTRE_VERSION_STRING);
1025                 }
1026
1027                 if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
1028                         /* We sent to the server ocd_cksum_types with bits set
1029                          * for algorithms we understand. The server masked off
1030                          * the checksum types it doesn't support */
1031                         if ((ocd->ocd_cksum_types & cksum_types_supported()) == 0) {
1032                                 LCONSOLE_WARN("The negotiation of the checksum "
1033                                               "alogrithm to use with server %s "
1034                                               "failed (%x/%x), disabling "
1035                                               "checksums\n",
1036                                               obd2cli_tgt(imp->imp_obd),
1037                                               ocd->ocd_cksum_types,
1038                                               cksum_types_supported());
1039                                 cli->cl_checksum = 0;
1040                                 cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
1041                         } else {
1042                                 cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
1043                         }
1044                 } else {
1045                         /* The server does not support OBD_CONNECT_CKSUM.
1046                          * Enforce CRC32 for backward compatibility*/
1047                         cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
1048                 }
1049                 cli->cl_cksum_type =cksum_type_select(cli->cl_supp_cksum_types);
1050
1051                 if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE)
1052                         cli->cl_max_pages_per_rpc =
1053                                 ocd->ocd_brw_size >> CFS_PAGE_SHIFT;
1054                 else if (imp->imp_connect_op == MDS_CONNECT ||
1055                          imp->imp_connect_op == MGS_CONNECT)
1056                         cli->cl_max_pages_per_rpc = 1;
1057
1058                 /* Reset ns_connect_flags only for initial connect. It might be
1059                  * changed in while using FS and if we reset it in reconnect
1060                  * this leads to losing user settings done before such as
1061                  * disable lru_resize, etc. */
1062                 if (old_connect_flags != exp->exp_connect_flags ||
1063                     aa->pcaa_initial_connect) {
1064                         CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
1065                                "flags: "LPX64"\n", imp->imp_obd->obd_name,
1066                               ocd->ocd_connect_flags);
1067                         imp->imp_obd->obd_namespace->ns_connect_flags =
1068                                 ocd->ocd_connect_flags;
1069                         imp->imp_obd->obd_namespace->ns_orig_connect_flags =
1070                                 ocd->ocd_connect_flags;
1071                 }
1072
1073                 if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
1074                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1075                         /* We need a per-message support flag, because
1076                            a. we don't know if the incoming connect reply
1077                               supports AT or not (in reply_in_callback)
1078                               until we unpack it.
1079                            b. failovered server means export and flags are gone
1080                               (in ptlrpc_send_reply).
1081                            Can only be set when we know AT is supported at
1082                            both ends */
1083                         imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1084                 else
1085                         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1086
1087                 if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1088                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1089                         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1090                 else
1091                         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1092
1093                 LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
1094                         (cli->cl_max_pages_per_rpc > 0));
1095         }
1096
1097 out:
1098         if (rc != 0) {
1099                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1100                 if (rc == -EACCES) {
1101                         /*
1102                          * Give up trying to reconnect
1103                          * EACCES means client has no permission for connection
1104                          */
1105                         imp->imp_obd->obd_no_recov = 1;
1106                         ptlrpc_deactivate_import(imp);
1107                 }
1108
1109                 if (rc == -EPROTO) {
1110                         struct obd_connect_data *ocd;
1111
1112                         /* reply message might not be ready */
1113                         if (request->rq_repmsg == NULL)
1114                                 RETURN(-EPROTO);
1115
1116                         ocd = req_capsule_server_get(&request->rq_pill,
1117                                                      &RMF_CONNECT_DATA);
1118                         if (ocd &&
1119                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1120                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1121                            /* Actually servers are only supposed to refuse
1122                               connection from liblustre clients, so we should
1123                               never see this from VFS context */
1124                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1125                                         "(%d.%d.%d.%d)"
1126                                         " refused connection from this client "
1127                                         "with an incompatible version (%s).  "
1128                                         "Client must be recompiled\n",
1129                                         obd2cli_tgt(imp->imp_obd),
1130                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1131                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1132                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1133                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1134                                         LUSTRE_VERSION_STRING);
1135                                 ptlrpc_deactivate_import(imp);
1136                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1137                         }
1138                         RETURN(-EPROTO);
1139                 }
1140
1141                 ptlrpc_maybe_ping_import_soon(imp);
1142
1143                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1144                        obd2cli_tgt(imp->imp_obd),
1145                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1146         }
1147
1148         cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1149         RETURN(rc);
1150 }
1151
1152 /**
1153  * interpret callback for "completed replay" RPCs.
1154  * \see signal_completed_replay
1155  */
1156 static int completed_replay_interpret(const struct lu_env *env,
1157                                       struct ptlrpc_request *req,
1158                                       void * data, int rc)
1159 {
1160         ENTRY;
1161         cfs_atomic_dec(&req->rq_import->imp_replay_inflight);
1162         if (req->rq_status == 0 &&
1163             !req->rq_import->imp_vbr_failed) {
1164                 ptlrpc_import_recovery_state_machine(req->rq_import);
1165         } else {
1166                 if (req->rq_import->imp_vbr_failed) {
1167                         CDEBUG(D_WARNING,
1168                                "%s: version recovery fails, reconnecting\n",
1169                                req->rq_import->imp_obd->obd_name);
1170                 } else {
1171                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1172                                      "reconnecting\n",
1173                                req->rq_import->imp_obd->obd_name,
1174                                req->rq_status);
1175                 }
1176                 ptlrpc_connect_import(req->rq_import);
1177         }
1178
1179         RETURN(0);
1180 }
1181
1182 /**
1183  * Let server know that we have no requests to replay anymore.
1184  * Achieved by just sending a PING request
1185  */
1186 static int signal_completed_replay(struct obd_import *imp)
1187 {
1188         struct ptlrpc_request *req;
1189         ENTRY;
1190
1191         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1192                 RETURN(0);
1193
1194         LASSERT(cfs_atomic_read(&imp->imp_replay_inflight) == 0);
1195         cfs_atomic_inc(&imp->imp_replay_inflight);
1196
1197         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1198                                         OBD_PING);
1199         if (req == NULL) {
1200                 cfs_atomic_dec(&imp->imp_replay_inflight);
1201                 RETURN(-ENOMEM);
1202         }
1203
1204         ptlrpc_request_set_replen(req);
1205         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1206         lustre_msg_add_flags(req->rq_reqmsg,
1207                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1208         if (AT_OFF)
1209                 req->rq_timeout *= 3;
1210         req->rq_interpret_reply = completed_replay_interpret;
1211
1212         ptlrpcd_add_req(req, PDL_POLICY_ROUND, -1);
1213         RETURN(0);
1214 }
1215
1216 #ifdef __KERNEL__
1217 /**
1218  * In kernel code all import invalidation happens in its own
1219  * separate thread, so that whatever application happened to encounter
1220  * a problem could still be killed or otherwise continue
1221  */
1222 static int ptlrpc_invalidate_import_thread(void *data)
1223 {
1224         struct obd_import *imp = data;
1225
1226         ENTRY;
1227
1228         cfs_daemonize_ctxt("ll_imp_inval");
1229
1230         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1231                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1232                imp->imp_connection->c_remote_uuid.uuid);
1233
1234         ptlrpc_invalidate_import(imp);
1235
1236         if (obd_dump_on_eviction) {
1237                 CERROR("dump the log upon eviction\n");
1238                 libcfs_debug_dumplog();
1239         }
1240
1241         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1242         ptlrpc_import_recovery_state_machine(imp);
1243
1244         class_import_put(imp);
1245         RETURN(0);
1246 }
1247 #endif
1248
1249 /**
1250  * This is the state machine for client-side recovery on import.
1251  *
1252  * Typicaly we have two possibly paths. If we came to server and it is not
1253  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1254  * state and reconnect from scratch.
1255  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1256  * We go through our list of requests to replay and send them to server one by
1257  * one.
1258  * After sending all request from the list we change import state to
1259  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1260  * and also all the locks we don't yet have and wait for server to grant us.
1261  * After that we send a special "replay completed" request and change import
1262  * state to IMP_REPLAY_WAIT.
1263  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1264  * state and resend all requests from sending list.
1265  * After that we promote import to FULL state and send all delayed requests
1266  * and import is fully operational after that.
1267  *
1268  */
1269 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1270 {
1271         int rc = 0;
1272         int inflight;
1273         char *target_start;
1274         int target_len;
1275
1276         ENTRY;
1277         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1278                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1279                           &target_start, &target_len);
1280                 /* Don't care about MGC eviction */
1281                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1282                            LUSTRE_MGC_NAME) != 0) {
1283                         LCONSOLE_ERROR_MSG(0x167, "This client was evicted by "
1284                                            "%.*s; in progress operations using "
1285                                            "this service will fail.\n",
1286                                            target_len, target_start);
1287                 }
1288                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1289                        obd2cli_tgt(imp->imp_obd),
1290                        imp->imp_connection->c_remote_uuid.uuid);
1291                 /* reset vbr_failed flag upon eviction */
1292                 cfs_spin_lock(&imp->imp_lock);
1293                 imp->imp_vbr_failed = 0;
1294                 cfs_spin_unlock(&imp->imp_lock);
1295
1296 #ifdef __KERNEL__
1297                 /* bug 17802:  XXX client_disconnect_export vs connect request
1298                  * race. if client will evicted at this time, we start
1299                  * invalidate thread without reference to import and import can
1300                  * be freed at same time. */
1301                 class_import_get(imp);
1302                 rc = cfs_create_thread(ptlrpc_invalidate_import_thread, imp,
1303                                        CFS_DAEMON_FLAGS);
1304                 if (rc < 0) {
1305                         class_import_put(imp);
1306                         CERROR("error starting invalidate thread: %d\n", rc);
1307                 } else {
1308                         rc = 0;
1309                 }
1310                 RETURN(rc);
1311 #else
1312                 ptlrpc_invalidate_import(imp);
1313
1314                 IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1315 #endif
1316         }
1317
1318         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1319                 CDEBUG(D_HA, "replay requested by %s\n",
1320                        obd2cli_tgt(imp->imp_obd));
1321                 rc = ptlrpc_replay_next(imp, &inflight);
1322                 if (inflight == 0 &&
1323                     cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1324                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1325                         rc = ldlm_replay_locks(imp);
1326                         if (rc)
1327                                 GOTO(out, rc);
1328                 }
1329                 rc = 0;
1330         }
1331
1332         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1333                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1334                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1335                         rc = signal_completed_replay(imp);
1336                         if (rc)
1337                                 GOTO(out, rc);
1338                 }
1339
1340         }
1341
1342         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1343                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1344                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1345                 }
1346         }
1347
1348         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1349                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1350                        obd2cli_tgt(imp->imp_obd),
1351                        imp->imp_connection->c_remote_uuid.uuid);
1352
1353                 rc = ptlrpc_resend(imp);
1354                 if (rc)
1355                         GOTO(out, rc);
1356                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1357                 ptlrpc_activate_import(imp);
1358
1359                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1360                           &target_start, &target_len);
1361                 LCONSOLE_INFO("%s: Connection restored to %.*s (at %s)\n",
1362                               imp->imp_obd->obd_name,
1363                               target_len, target_start,
1364                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1365         }
1366
1367         if (imp->imp_state == LUSTRE_IMP_FULL) {
1368                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1369                 ptlrpc_wake_delayed(imp);
1370         }
1371
1372 out:
1373         RETURN(rc);
1374 }
1375
1376 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1377 {
1378         struct ptlrpc_request *req;
1379         int rq_opc, rc = 0;
1380         int nowait = imp->imp_obd->obd_force;
1381         ENTRY;
1382
1383         if (nowait)
1384                 GOTO(set_state, rc);
1385
1386         switch (imp->imp_connect_op) {
1387         case OST_CONNECT: rq_opc = OST_DISCONNECT; break;
1388         case MDS_CONNECT: rq_opc = MDS_DISCONNECT; break;
1389         case MGS_CONNECT: rq_opc = MGS_DISCONNECT; break;
1390         default:
1391                 CERROR("don't know how to disconnect from %s (connect_op %d)\n",
1392                        obd2cli_tgt(imp->imp_obd), imp->imp_connect_op);
1393                 RETURN(-EINVAL);
1394         }
1395
1396         if (ptlrpc_import_in_recovery(imp)) {
1397                 struct l_wait_info lwi;
1398                 cfs_duration_t timeout;
1399
1400
1401                 if (AT_OFF) {
1402                         if (imp->imp_server_timeout)
1403                                 timeout = cfs_time_seconds(obd_timeout / 2);
1404                         else
1405                                 timeout = cfs_time_seconds(obd_timeout);
1406                 } else {
1407                         int idx = import_at_get_index(imp,
1408                                 imp->imp_client->cli_request_portal);
1409                         timeout = cfs_time_seconds(
1410                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1411                 }
1412
1413                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1414                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1415                 rc = l_wait_event(imp->imp_recovery_waitq,
1416                                   !ptlrpc_import_in_recovery(imp), &lwi);
1417
1418         }
1419
1420         cfs_spin_lock(&imp->imp_lock);
1421         if (imp->imp_state != LUSTRE_IMP_FULL)
1422                 GOTO(out, 0);
1423
1424         cfs_spin_unlock(&imp->imp_lock);
1425
1426         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1427                                         LUSTRE_OBD_VERSION, rq_opc);
1428         if (req) {
1429                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1430                  * it fails.  We can get through the above with a down server
1431                  * if the client doesn't know the server is gone yet. */
1432                 req->rq_no_resend = 1;
1433
1434 #ifndef CRAY_XT3
1435                 /* We want client umounts to happen quickly, no matter the
1436                    server state... */
1437                 req->rq_timeout = min_t(int, req->rq_timeout,
1438                                         INITIAL_CONNECT_TIMEOUT);
1439 #else
1440                 /* ... but we always want liblustre clients to nicely
1441                    disconnect, so only use the adaptive value. */
1442                 if (AT_OFF)
1443                         req->rq_timeout = obd_timeout / 3;
1444 #endif
1445
1446                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1447                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1448                 ptlrpc_request_set_replen(req);
1449                 rc = ptlrpc_queue_wait(req);
1450                 ptlrpc_req_finished(req);
1451         }
1452
1453 set_state:
1454         cfs_spin_lock(&imp->imp_lock);
1455 out:
1456         if (noclose)
1457                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1458         else
1459                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1460         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1461         cfs_spin_unlock(&imp->imp_lock);
1462
1463         RETURN(rc);
1464 }
1465
1466 void ptlrpc_cleanup_imp(struct obd_import *imp)
1467 {
1468         ENTRY;
1469
1470         cfs_spin_lock(&imp->imp_lock);
1471         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1472         imp->imp_generation++;
1473         cfs_spin_unlock(&imp->imp_lock);
1474         ptlrpc_abort_inflight(imp);
1475
1476         EXIT;
1477 }
1478
1479 /* Adaptive Timeout utils */
1480 extern unsigned int at_min, at_max, at_history;
1481
1482 /* Bin into timeslices using AT_BINS bins.
1483    This gives us a max of the last binlimit*AT_BINS secs without the storage,
1484    but still smoothing out a return to normalcy from a slow response.
1485    (E.g. remember the maximum latency in each minute of the last 4 minutes.) */
1486 int at_measured(struct adaptive_timeout *at, unsigned int val)
1487 {
1488         unsigned int old = at->at_current;
1489         time_t now = cfs_time_current_sec();
1490         time_t binlimit = max_t(time_t, at_history / AT_BINS, 1);
1491
1492         LASSERT(at);
1493         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1494                val, at, now - at->at_binstart, at->at_current,
1495                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1496
1497         if (val == 0)
1498                 /* 0's don't count, because we never want our timeout to
1499                    drop to 0, and because 0 could mean an error */
1500                 return 0;
1501
1502         cfs_spin_lock(&at->at_lock);
1503
1504         if (unlikely(at->at_binstart == 0)) {
1505                 /* Special case to remove default from history */
1506                 at->at_current = val;
1507                 at->at_worst_ever = val;
1508                 at->at_worst_time = now;
1509                 at->at_hist[0] = val;
1510                 at->at_binstart = now;
1511         } else if (now - at->at_binstart < binlimit ) {
1512                 /* in bin 0 */
1513                 at->at_hist[0] = max(val, at->at_hist[0]);
1514                 at->at_current = max(val, at->at_current);
1515         } else {
1516                 int i, shift;
1517                 unsigned int maxv = val;
1518                 /* move bins over */
1519                 shift = (now - at->at_binstart) / binlimit;
1520                 LASSERT(shift > 0);
1521                 for(i = AT_BINS - 1; i >= 0; i--) {
1522                         if (i >= shift) {
1523                                 at->at_hist[i] = at->at_hist[i - shift];
1524                                 maxv = max(maxv, at->at_hist[i]);
1525                         } else {
1526                                 at->at_hist[i] = 0;
1527                         }
1528                 }
1529                 at->at_hist[0] = val;
1530                 at->at_current = maxv;
1531                 at->at_binstart += shift * binlimit;
1532         }
1533
1534         if (at->at_current > at->at_worst_ever) {
1535                 at->at_worst_ever = at->at_current;
1536                 at->at_worst_time = now;
1537         }
1538
1539         if (at->at_flags & AT_FLG_NOHIST)
1540                 /* Only keep last reported val; keeping the rest of the history
1541                    for proc only */
1542                 at->at_current = val;
1543
1544         if (at_max > 0)
1545                 at->at_current =  min(at->at_current, at_max);
1546         at->at_current =  max(at->at_current, at_min);
1547
1548         if (at->at_current != old)
1549                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1550                        "(val=%u) hist %u %u %u %u\n", at,
1551                        old, at->at_current, at->at_current - old, val,
1552                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1553                        at->at_hist[3]);
1554
1555         /* if we changed, report the old value */
1556         old = (at->at_current != old) ? old : 0;
1557
1558         cfs_spin_unlock(&at->at_lock);
1559         return old;
1560 }
1561
1562 /* Find the imp_at index for a given portal; assign if space available */
1563 int import_at_get_index(struct obd_import *imp, int portal)
1564 {
1565         struct imp_at *at = &imp->imp_at;
1566         int i;
1567
1568         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1569                 if (at->iat_portal[i] == portal)
1570                         return i;
1571                 if (at->iat_portal[i] == 0)
1572                         /* unused */
1573                         break;
1574         }
1575
1576         /* Not found in list, add it under a lock */
1577         cfs_spin_lock(&imp->imp_lock);
1578
1579         /* Check unused under lock */
1580         for (; i < IMP_AT_MAX_PORTALS; i++) {
1581                 if (at->iat_portal[i] == portal)
1582                         goto out;
1583                 if (at->iat_portal[i] == 0)
1584                         /* unused */
1585                         break;
1586         }
1587
1588         /* Not enough portals? */
1589         LASSERT(i < IMP_AT_MAX_PORTALS);
1590
1591         at->iat_portal[i] = portal;
1592 out:
1593         cfs_spin_unlock(&imp->imp_lock);
1594         return i;
1595 }