Whamcloud - gitweb
5df9591ee0b0c3d4ba54483c9af3c63aa3f2f13f
[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 EXPORT_SYMBOL(ptlrpc_deactivate_import);
225
226 static unsigned int
227 ptlrpc_inflight_deadline(struct ptlrpc_request *req, time_t now)
228 {
229         long dl;
230
231         if (!(((req->rq_phase == RQ_PHASE_RPC) && !req->rq_waiting) ||
232               (req->rq_phase == RQ_PHASE_BULK) ||
233               (req->rq_phase == RQ_PHASE_NEW)))
234                 return 0;
235
236         if (req->rq_timedout)
237                 return 0;
238
239         if (req->rq_phase == RQ_PHASE_NEW)
240                 dl = req->rq_sent;
241         else
242                 dl = req->rq_deadline;
243
244         if (dl <= now)
245                 return 0;
246
247         return dl - now;
248 }
249
250 static unsigned int ptlrpc_inflight_timeout(struct obd_import *imp)
251 {
252         time_t now = cfs_time_current_sec();
253         cfs_list_t *tmp, *n;
254         struct ptlrpc_request *req;
255         unsigned int timeout = 0;
256
257         cfs_spin_lock(&imp->imp_lock);
258         cfs_list_for_each_safe(tmp, n, &imp->imp_sending_list) {
259                 req = cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
260                 timeout = max(ptlrpc_inflight_deadline(req, now), timeout);
261         }
262         cfs_spin_unlock(&imp->imp_lock);
263         return timeout;
264 }
265
266 /**
267  * This function will invalidate the import, if necessary, then block
268  * for all the RPC completions, and finally notify the obd to
269  * invalidate its state (ie cancel locks, clear pending requests,
270  * etc).
271  */
272 void ptlrpc_invalidate_import(struct obd_import *imp)
273 {
274         cfs_list_t *tmp, *n;
275         struct ptlrpc_request *req;
276         struct l_wait_info lwi;
277         unsigned int timeout;
278         int rc;
279
280         cfs_atomic_inc(&imp->imp_inval_count);
281
282         if (!imp->imp_invalid || imp->imp_obd->obd_no_recov)
283                 ptlrpc_deactivate_import(imp);
284
285         LASSERT(imp->imp_invalid);
286
287         /* Wait forever until inflight == 0. We really can't do it another
288          * way because in some cases we need to wait for very long reply
289          * unlink. We can't do anything before that because there is really
290          * no guarantee that some rdma transfer is not in progress right now. */
291         do {
292                 /* Calculate max timeout for waiting on rpcs to error
293                  * out. Use obd_timeout if calculated value is smaller
294                  * than it. */
295                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_LONG_REPL_UNLINK)) {
296                         timeout = ptlrpc_inflight_timeout(imp);
297                         timeout += timeout / 3;
298
299                         if (timeout == 0)
300                                 timeout = obd_timeout;
301                 } else {
302                         /* decrease the interval to increase race condition */
303                         timeout = 1;
304                 }
305
306                 CDEBUG(D_RPCTRACE,"Sleeping %d sec for inflight to error out\n",
307                        timeout);
308
309                 /* Wait for all requests to error out and call completion
310                  * callbacks. Cap it at obd_timeout -- these should all
311                  * have been locally cancelled by ptlrpc_abort_inflight. */
312                 lwi = LWI_TIMEOUT_INTERVAL(
313                         cfs_timeout_cap(cfs_time_seconds(timeout)),
314                         (timeout > 1)?cfs_time_seconds(1):cfs_time_seconds(1)/2,
315                         NULL, NULL);
316                 rc = l_wait_event(imp->imp_recovery_waitq,
317                                   (cfs_atomic_read(&imp->imp_inflight) == 0),
318                                   &lwi);
319                 if (rc) {
320                         const char *cli_tgt = obd2cli_tgt(imp->imp_obd);
321
322                         CERROR("%s: rc = %d waiting for callback (%d != 0)\n",
323                                cli_tgt, rc,
324                                cfs_atomic_read(&imp->imp_inflight));
325
326                         cfs_spin_lock(&imp->imp_lock);
327                         if (cfs_atomic_read(&imp->imp_inflight) == 0) {
328                                 int count = cfs_atomic_read(&imp->imp_unregistering);
329
330                                 /* We know that "unregistering" rpcs only can
331                                  * survive in sending or delaying lists (they
332                                  * maybe waiting for long reply unlink in
333                                  * sluggish nets). Let's check this. If there
334                                  * is no inflight and unregistering != 0, this
335                                  * is bug. */
336                                 LASSERTF(count == 0, "Some RPCs are still "
337                                          "unregistering: %d\n", count);
338
339                                 /* Let's save one loop as soon as inflight have
340                                  * dropped to zero. No new inflights possible at
341                                  * this point. */
342                                 rc = 0;
343                         } else {
344                                 cfs_list_for_each_safe(tmp, n,
345                                                        &imp->imp_sending_list) {
346                                         req = cfs_list_entry(tmp,
347                                                              struct ptlrpc_request,
348                                                              rq_list);
349                                         DEBUG_REQ(D_ERROR, req,
350                                                   "still on sending list");
351                                 }
352                                 cfs_list_for_each_safe(tmp, n,
353                                                        &imp->imp_delayed_list) {
354                                         req = cfs_list_entry(tmp,
355                                                              struct ptlrpc_request,
356                                                              rq_list);
357                                         DEBUG_REQ(D_ERROR, req,
358                                                   "still on delayed list");
359                                 }
360
361                                 CERROR("%s: RPCs in \"%s\" phase found (%d). "
362                                        "Network is sluggish? Waiting them "
363                                        "to error out.\n", cli_tgt,
364                                        ptlrpc_phase2str(RQ_PHASE_UNREGISTERING),
365                                        cfs_atomic_read(&imp->
366                                                        imp_unregistering));
367                         }
368                         cfs_spin_unlock(&imp->imp_lock);
369                   }
370         } while (rc != 0);
371
372         /*
373          * Let's additionally check that no new rpcs added to import in
374          * "invalidate" state.
375          */
376         LASSERT(cfs_atomic_read(&imp->imp_inflight) == 0);
377         obd_import_event(imp->imp_obd, imp, IMP_EVENT_INVALIDATE);
378         sptlrpc_import_flush_all_ctx(imp);
379
380         cfs_atomic_dec(&imp->imp_inval_count);
381         cfs_waitq_broadcast(&imp->imp_recovery_waitq);
382 }
383 EXPORT_SYMBOL(ptlrpc_invalidate_import);
384
385 /* unset imp_invalid */
386 void ptlrpc_activate_import(struct obd_import *imp)
387 {
388         struct obd_device *obd = imp->imp_obd;
389
390         cfs_spin_lock(&imp->imp_lock);
391         imp->imp_invalid = 0;
392         ptlrpc_activate_timeouts(imp);
393         cfs_spin_unlock(&imp->imp_lock);
394         obd_import_event(obd, imp, IMP_EVENT_ACTIVE);
395 }
396 EXPORT_SYMBOL(ptlrpc_activate_import);
397
398 void ptlrpc_fail_import(struct obd_import *imp, __u32 conn_cnt)
399 {
400         ENTRY;
401
402         LASSERT(!imp->imp_dlm_fake);
403
404         if (ptlrpc_set_import_discon(imp, conn_cnt)) {
405                 if (!imp->imp_replayable) {
406                         CDEBUG(D_HA, "import %s@%s for %s not replayable, "
407                                "auto-deactivating\n",
408                                obd2cli_tgt(imp->imp_obd),
409                                imp->imp_connection->c_remote_uuid.uuid,
410                                imp->imp_obd->obd_name);
411                         ptlrpc_deactivate_import(imp);
412                 }
413
414                 CDEBUG(D_HA, "%s: waking up pinger\n",
415                        obd2cli_tgt(imp->imp_obd));
416
417                 cfs_spin_lock(&imp->imp_lock);
418                 imp->imp_force_verify = 1;
419                 cfs_spin_unlock(&imp->imp_lock);
420
421                 ptlrpc_pinger_wake_up();
422         }
423         EXIT;
424 }
425 EXPORT_SYMBOL(ptlrpc_fail_import);
426
427 int ptlrpc_reconnect_import(struct obd_import *imp)
428 {
429         ptlrpc_set_import_discon(imp, 0);
430         /* Force a new connect attempt */
431         ptlrpc_invalidate_import(imp);
432         /* Do a fresh connect next time by zeroing the handle */
433         ptlrpc_disconnect_import(imp, 1);
434         /* Wait for all invalidate calls to finish */
435         if (cfs_atomic_read(&imp->imp_inval_count) > 0) {
436                 int rc;
437                 struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
438                 rc = l_wait_event(imp->imp_recovery_waitq,
439                                   (cfs_atomic_read(&imp->imp_inval_count) == 0),
440                                   &lwi);
441                 if (rc)
442                         CERROR("Interrupted, inval=%d\n",
443                                cfs_atomic_read(&imp->imp_inval_count));
444         }
445
446         /* Allow reconnect attempts */
447         imp->imp_obd->obd_no_recov = 0;
448         /* Remove 'invalid' flag */
449         ptlrpc_activate_import(imp);
450         /* Attempt a new connect */
451         ptlrpc_recover_import(imp, NULL, 0);
452         return 0;
453 }
454 EXPORT_SYMBOL(ptlrpc_reconnect_import);
455
456 /**
457  * Connection on import \a imp is changed to another one (if more than one is
458  * present). We typically chose connection that we have not tried to connect to
459  * the longest
460  */
461 static int import_select_connection(struct obd_import *imp)
462 {
463         struct obd_import_conn *imp_conn = NULL, *conn;
464         struct obd_export *dlmexp;
465         char *target_start;
466         int target_len, tried_all = 1;
467         ENTRY;
468
469         cfs_spin_lock(&imp->imp_lock);
470
471         if (cfs_list_empty(&imp->imp_conn_list)) {
472                 CERROR("%s: no connections available\n",
473                         imp->imp_obd->obd_name);
474                 cfs_spin_unlock(&imp->imp_lock);
475                 RETURN(-EINVAL);
476         }
477
478         cfs_list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
479                 CDEBUG(D_HA, "%s: connect to NID %s last attempt "LPU64"\n",
480                        imp->imp_obd->obd_name,
481                        libcfs_nid2str(conn->oic_conn->c_peer.nid),
482                        conn->oic_last_attempt);
483
484                 /* If we have not tried this connection since
485                    the last successful attempt, go with this one */
486                 if ((conn->oic_last_attempt == 0) ||
487                     cfs_time_beforeq_64(conn->oic_last_attempt,
488                                        imp->imp_last_success_conn)) {
489                         imp_conn = conn;
490                         tried_all = 0;
491                         break;
492                 }
493
494                 /* If all of the connections have already been tried
495                    since the last successful connection; just choose the
496                    least recently used */
497                 if (!imp_conn)
498                         imp_conn = conn;
499                 else if (cfs_time_before_64(conn->oic_last_attempt,
500                                             imp_conn->oic_last_attempt))
501                         imp_conn = conn;
502         }
503
504         /* if not found, simply choose the current one */
505         if (!imp_conn || imp->imp_force_reconnect) {
506                 LASSERT(imp->imp_conn_current);
507                 imp_conn = imp->imp_conn_current;
508                 tried_all = 0;
509         }
510         LASSERT(imp_conn->oic_conn);
511
512         /* If we've tried everything, and we're back to the beginning of the
513            list, increase our timeout and try again. It will be reset when
514            we do finally connect. (FIXME: really we should wait for all network
515            state associated with the last connection attempt to drain before
516            trying to reconnect on it.) */
517         if (tried_all && (imp->imp_conn_list.next == &imp_conn->oic_item)) {
518                 struct adaptive_timeout *at = &imp->imp_at.iat_net_latency;
519                 if (at_get(at) < CONNECTION_SWITCH_MAX) {
520                         at_measured(at, at_get(at) + CONNECTION_SWITCH_INC);
521                         if (at_get(at) > CONNECTION_SWITCH_MAX)
522                                 at_reset(at, CONNECTION_SWITCH_MAX);
523                 }
524                 LASSERT(imp_conn->oic_last_attempt);
525                 CDEBUG(D_HA, "%s: tried all connections, increasing latency "
526                         "to %ds\n", imp->imp_obd->obd_name, at_get(at));
527         }
528
529         imp_conn->oic_last_attempt = cfs_time_current_64();
530
531         /* switch connection, don't mind if it's same as the current one */
532         if (imp->imp_connection)
533                 ptlrpc_connection_put(imp->imp_connection);
534         imp->imp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
535
536         dlmexp =  class_conn2export(&imp->imp_dlm_handle);
537         LASSERT(dlmexp != NULL);
538         if (dlmexp->exp_connection)
539                 ptlrpc_connection_put(dlmexp->exp_connection);
540         dlmexp->exp_connection = ptlrpc_connection_addref(imp_conn->oic_conn);
541         class_export_put(dlmexp);
542
543         if (imp->imp_conn_current != imp_conn) {
544                 if (imp->imp_conn_current) {
545                         deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
546                                   &target_start, &target_len);
547
548                         CDEBUG(D_HA, "%s: Connection changing to"
549                                " %.*s (at %s)\n",
550                                imp->imp_obd->obd_name,
551                                target_len, target_start,
552                                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
553                 }
554
555                 imp->imp_conn_current = imp_conn;
556         }
557
558         CDEBUG(D_HA, "%s: import %p using connection %s/%s\n",
559                imp->imp_obd->obd_name, imp, imp_conn->oic_uuid.uuid,
560                libcfs_nid2str(imp_conn->oic_conn->c_peer.nid));
561
562         cfs_spin_unlock(&imp->imp_lock);
563
564         RETURN(0);
565 }
566
567 /*
568  * must be called under imp_lock
569  */
570 static int ptlrpc_first_transno(struct obd_import *imp, __u64 *transno)
571 {
572         struct ptlrpc_request *req;
573         cfs_list_t *tmp;
574
575         if (cfs_list_empty(&imp->imp_replay_list))
576                 return 0;
577         tmp = imp->imp_replay_list.next;
578         req = cfs_list_entry(tmp, struct ptlrpc_request, rq_replay_list);
579         *transno = req->rq_transno;
580         if (req->rq_transno == 0) {
581                 DEBUG_REQ(D_ERROR, req, "zero transno in replay");
582                 LBUG();
583         }
584
585         return 1;
586 }
587
588 /**
589  * Attempt to (re)connect import \a imp. This includes all preparations,
590  * initializing CONNECT RPC request and passing it to ptlrpcd for
591  * actual sending.
592  * Returns 0 on success or error code.
593  */
594 int ptlrpc_connect_import(struct obd_import *imp)
595 {
596         struct obd_device *obd = imp->imp_obd;
597         int initial_connect = 0;
598         int set_transno = 0;
599         __u64 committed_before_reconnect = 0;
600         struct ptlrpc_request *request;
601         char *bufs[] = { NULL,
602                          obd2cli_tgt(imp->imp_obd),
603                          obd->obd_uuid.uuid,
604                          (char *)&imp->imp_dlm_handle,
605                          (char *)&imp->imp_connect_data };
606         struct ptlrpc_connect_async_args *aa;
607         int rc;
608         ENTRY;
609
610         cfs_spin_lock(&imp->imp_lock);
611         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
612                 cfs_spin_unlock(&imp->imp_lock);
613                 CERROR("can't connect to a closed import\n");
614                 RETURN(-EINVAL);
615         } else if (imp->imp_state == LUSTRE_IMP_FULL) {
616                 cfs_spin_unlock(&imp->imp_lock);
617                 CERROR("already connected\n");
618                 RETURN(0);
619         } else if (imp->imp_state == LUSTRE_IMP_CONNECTING) {
620                 cfs_spin_unlock(&imp->imp_lock);
621                 CERROR("already connecting\n");
622                 RETURN(-EALREADY);
623         }
624
625         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CONNECTING);
626
627         imp->imp_conn_cnt++;
628         imp->imp_resend_replay = 0;
629
630         if (!lustre_handle_is_used(&imp->imp_remote_handle))
631                 initial_connect = 1;
632         else
633                 committed_before_reconnect = imp->imp_peer_committed_transno;
634
635         set_transno = ptlrpc_first_transno(imp,
636                                            &imp->imp_connect_data.ocd_transno);
637         cfs_spin_unlock(&imp->imp_lock);
638
639         rc = import_select_connection(imp);
640         if (rc)
641                 GOTO(out, rc);
642
643         rc = sptlrpc_import_sec_adapt(imp, NULL, 0);
644         if (rc)
645                 GOTO(out, rc);
646
647         /* Reset connect flags to the originally requested flags, in case
648          * the server is updated on-the-fly we will get the new features. */
649         imp->imp_connect_data.ocd_connect_flags = imp->imp_connect_flags_orig;
650         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
651         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
652
653         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
654                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
655         if (rc)
656                 GOTO(out, rc);
657
658         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
659         if (request == NULL)
660                 GOTO(out, rc = -ENOMEM);
661
662         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
663                                       imp->imp_connect_op, bufs, NULL);
664         if (rc) {
665                 ptlrpc_request_free(request);
666                 GOTO(out, rc);
667         }
668
669         /* Report the rpc service time to the server so that it knows how long
670          * to wait for clients to join recovery */
671         lustre_msg_set_service_time(request->rq_reqmsg,
672                                     at_timeout2est(request->rq_timeout));
673
674         /* The amount of time we give the server to process the connect req.
675          * import_select_connection will increase the net latency on
676          * repeated reconnect attempts to cover slow networks.
677          * We override/ignore the server rpc completion estimate here,
678          * which may be large if this is a reconnect attempt */
679         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
680         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
681
682 #ifndef __KERNEL__
683         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_LIBCLIENT);
684 #endif
685         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
686
687         request->rq_no_resend = request->rq_no_delay = 1;
688         request->rq_send_state = LUSTRE_IMP_CONNECTING;
689         /* Allow a slightly larger reply for future growth compatibility */
690         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
691                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
692         ptlrpc_request_set_replen(request);
693         request->rq_interpret_reply = ptlrpc_connect_interpret;
694
695         CLASSERT(sizeof (*aa) <= sizeof (request->rq_async_args));
696         aa = ptlrpc_req_async_args(request);
697         memset(aa, 0, sizeof *aa);
698
699         aa->pcaa_peer_committed = committed_before_reconnect;
700         aa->pcaa_initial_connect = initial_connect;
701
702         if (aa->pcaa_initial_connect) {
703                 cfs_spin_lock(&imp->imp_lock);
704                 imp->imp_replayable = 1;
705                 cfs_spin_unlock(&imp->imp_lock);
706                 lustre_msg_add_op_flags(request->rq_reqmsg,
707                                         MSG_CONNECT_INITIAL);
708         }
709
710         if (set_transno)
711                 lustre_msg_add_op_flags(request->rq_reqmsg,
712                                         MSG_CONNECT_TRANSNO);
713
714         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %d)",
715                   request->rq_timeout);
716         ptlrpcd_add_req(request, PDL_POLICY_ROUND, -1);
717         rc = 0;
718 out:
719         if (rc != 0) {
720                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
721         }
722
723         RETURN(rc);
724 }
725 EXPORT_SYMBOL(ptlrpc_connect_import);
726
727 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
728 {
729 #ifdef __KERNEL__
730         int force_verify;
731
732         cfs_spin_lock(&imp->imp_lock);
733         force_verify = imp->imp_force_verify != 0;
734         cfs_spin_unlock(&imp->imp_lock);
735
736         if (force_verify)
737                 ptlrpc_pinger_wake_up();
738 #else
739         /* liblustre has no pinger thread, so we wakeup pinger anyway */
740         ptlrpc_pinger_wake_up();
741 #endif
742 }
743
744 static int ptlrpc_busy_reconnect(int rc)
745 {
746         return (rc == -EBUSY) || (rc == -EAGAIN);
747 }
748
749 /**
750  * interpret_reply callback for connect RPCs.
751  * Looks into returned status of connect operation and decides
752  * what to do with the import - i.e enter recovery, promote it to
753  * full state for normal operations of disconnect it due to an error.
754  */
755 static int ptlrpc_connect_interpret(const struct lu_env *env,
756                                     struct ptlrpc_request *request,
757                                     void *data, int rc)
758 {
759         struct ptlrpc_connect_async_args *aa = data;
760         struct obd_import *imp = request->rq_import;
761         struct client_obd *cli = &imp->imp_obd->u.cli;
762         struct lustre_handle old_hdl;
763         __u64 old_connect_flags;
764         int msg_flags;
765         ENTRY;
766
767         cfs_spin_lock(&imp->imp_lock);
768         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
769                 cfs_spin_unlock(&imp->imp_lock);
770                 RETURN(0);
771         }
772
773         if (rc) {
774                 /* if this reconnect to busy export - not need select new target
775                  * for connecting*/
776                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
777                 cfs_spin_unlock(&imp->imp_lock);
778                 ptlrpc_maybe_ping_import_soon(imp);
779                 GOTO(out, rc);
780         }
781
782         LASSERT(imp->imp_conn_current);
783
784         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
785
786         /* All imports are pingable */
787         imp->imp_pingable = 1;
788         imp->imp_force_reconnect = 0;
789         imp->imp_force_verify = 0;
790
791         if (aa->pcaa_initial_connect) {
792                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
793                         imp->imp_replayable = 1;
794                         cfs_spin_unlock(&imp->imp_lock);
795                         CDEBUG(D_HA, "connected to replayable target: %s\n",
796                                obd2cli_tgt(imp->imp_obd));
797                 } else {
798                         imp->imp_replayable = 0;
799                         cfs_spin_unlock(&imp->imp_lock);
800                 }
801
802                 /* if applies, adjust the imp->imp_msg_magic here
803                  * according to reply flags */
804
805                 imp->imp_remote_handle =
806                                 *lustre_msg_get_handle(request->rq_repmsg);
807
808                 /* Initial connects are allowed for clients with non-random
809                  * uuids when servers are in recovery.  Simply signal the
810                  * servers replay is complete and wait in REPLAY_WAIT. */
811                 if (msg_flags & MSG_CONNECT_RECOVERING) {
812                         CDEBUG(D_HA, "connect to %s during recovery\n",
813                                obd2cli_tgt(imp->imp_obd));
814                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
815                 } else {
816                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
817                         ptlrpc_activate_import(imp);
818                 }
819
820                 GOTO(finish, rc = 0);
821         } else {
822                 cfs_spin_unlock(&imp->imp_lock);
823         }
824
825         /* Determine what recovery state to move the import to. */
826         if (MSG_CONNECT_RECONNECT & msg_flags) {
827                 memset(&old_hdl, 0, sizeof(old_hdl));
828                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
829                             sizeof (old_hdl))) {
830                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
831                                       "bad handle "LPX64"\n",
832                                       obd2cli_tgt(imp->imp_obd),
833                                       imp->imp_connection->c_remote_uuid.uuid,
834                                       imp->imp_dlm_handle.cookie);
835                         GOTO(out, rc = -ENOTCONN);
836                 }
837
838                 if (memcmp(&imp->imp_remote_handle,
839                            lustre_msg_get_handle(request->rq_repmsg),
840                            sizeof(imp->imp_remote_handle))) {
841                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
842                                 D_HA : D_WARNING;
843
844                         /* Bug 16611/14775: if server handle have changed,
845                          * that means some sort of disconnection happened.
846                          * If the server is not in recovery, that also means it
847                          * already erased all of our state because of previous
848                          * eviction. If it is in recovery - we are safe to
849                          * participate since we can reestablish all of our state
850                          * with server again */
851                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
852                                 CDEBUG(level,"%s@%s changed server handle from "
853                                        LPX64" to "LPX64
854                                        " but is still in recovery\n",
855                                        obd2cli_tgt(imp->imp_obd),
856                                        imp->imp_connection->c_remote_uuid.uuid,
857                                        imp->imp_remote_handle.cookie,
858                                        lustre_msg_get_handle(
859                                        request->rq_repmsg)->cookie);
860                         } else {
861                                 LCONSOLE_WARN("Evicted from %s (at %s) "
862                                               "after server handle changed from "
863                                               LPX64" to "LPX64"\n",
864                                               obd2cli_tgt(imp->imp_obd),
865                                               imp->imp_connection-> \
866                                               c_remote_uuid.uuid,
867                                               imp->imp_remote_handle.cookie,
868                                               lustre_msg_get_handle(
869                                               request->rq_repmsg)->cookie);
870                         }
871
872
873                         imp->imp_remote_handle =
874                                      *lustre_msg_get_handle(request->rq_repmsg);
875
876                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
877                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
878                                 GOTO(finish, rc = 0);
879                         }
880
881                 } else {
882                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
883                                obd2cli_tgt(imp->imp_obd),
884                                imp->imp_connection->c_remote_uuid.uuid);
885                 }
886
887                 if (imp->imp_invalid) {
888                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
889                                "marking evicted\n", imp->imp_obd->obd_name);
890                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
891                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
892                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
893                                imp->imp_obd->obd_name,
894                                obd2cli_tgt(imp->imp_obd));
895
896                         cfs_spin_lock(&imp->imp_lock);
897                         imp->imp_resend_replay = 1;
898                         cfs_spin_unlock(&imp->imp_lock);
899
900                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
901                 } else {
902                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
903                 }
904         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
905                 LASSERT(imp->imp_replayable);
906                 imp->imp_remote_handle =
907                                 *lustre_msg_get_handle(request->rq_repmsg);
908                 imp->imp_last_replay_transno = 0;
909                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
910         } else {
911                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
912                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
913                 imp->imp_remote_handle =
914                                 *lustre_msg_get_handle(request->rq_repmsg);
915                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
916         }
917
918         /* Sanity checks for a reconnected import. */
919         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
920                 CERROR("imp_replayable flag does not match server "
921                        "after reconnect. We should LBUG right here.\n");
922         }
923
924         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
925             lustre_msg_get_last_committed(request->rq_repmsg) <
926             aa->pcaa_peer_committed) {
927                 CERROR("%s went back in time (transno "LPD64
928                        " was previously committed, server now claims "LPD64
929                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
930                        "id=9646\n",
931                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
932                        lustre_msg_get_last_committed(request->rq_repmsg));
933         }
934
935 finish:
936         rc = ptlrpc_import_recovery_state_machine(imp);
937         if (rc != 0) {
938                 if (rc == -ENOTCONN) {
939                         CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
940                                "invalidating and reconnecting\n",
941                                obd2cli_tgt(imp->imp_obd),
942                                imp->imp_connection->c_remote_uuid.uuid);
943                         ptlrpc_connect_import(imp);
944                         RETURN(0);
945                 }
946         } else {
947                 struct obd_connect_data *ocd;
948                 struct obd_export *exp;
949                 int ret;
950                 ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
951                                            RCL_SERVER);
952                 /* server replied obd_connect_data is always bigger */
953                 ocd = req_capsule_server_sized_get(&request->rq_pill,
954                                                    &RMF_CONNECT_DATA, ret);
955
956                 cfs_spin_lock(&imp->imp_lock);
957                 cfs_list_del(&imp->imp_conn_current->oic_item);
958                 cfs_list_add(&imp->imp_conn_current->oic_item,
959                              &imp->imp_conn_list);
960                 imp->imp_last_success_conn =
961                         imp->imp_conn_current->oic_last_attempt;
962
963                 if (ocd == NULL) {
964                         cfs_spin_unlock(&imp->imp_lock);
965                         CERROR("Wrong connect data from server\n");
966                         rc = -EPROTO;
967                         GOTO(out, rc);
968                 }
969
970                 imp->imp_connect_data = *ocd;
971                 CDEBUG(D_HA, "obd %s to target with inst %u\n",
972                        imp->imp_obd->obd_name, ocd->ocd_instance);
973
974                 exp = class_conn2export(&imp->imp_dlm_handle);
975                 cfs_spin_unlock(&imp->imp_lock);
976
977                 /* check that server granted subset of flags we asked for. */
978                 LASSERTF((ocd->ocd_connect_flags &
979                           imp->imp_connect_flags_orig) ==
980                          ocd->ocd_connect_flags, LPX64" != "LPX64,
981                          imp->imp_connect_flags_orig, ocd->ocd_connect_flags);
982
983                 if (!exp) {
984                         /* This could happen if export is cleaned during the
985                            connect attempt */
986                         CERROR("Missing export for %s\n",
987                                imp->imp_obd->obd_name);
988                         GOTO(out, rc = -ENODEV);
989                 }
990                 old_connect_flags = exp->exp_connect_flags;
991                 exp->exp_connect_flags = ocd->ocd_connect_flags;
992                 imp->imp_obd->obd_self_export->exp_connect_flags =
993                                                         ocd->ocd_connect_flags;
994                 class_export_put(exp);
995
996                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
997
998                 if (!ocd->ocd_ibits_known &&
999                     ocd->ocd_connect_flags & OBD_CONNECT_IBITS)
1000                         CERROR("Inodebits aware server returned zero compatible"
1001                                " bits?\n");
1002
1003                 if ((ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1004                     (ocd->ocd_version > LUSTRE_VERSION_CODE +
1005                                         LUSTRE_VERSION_OFFSET_WARN ||
1006                      ocd->ocd_version < LUSTRE_VERSION_CODE -
1007                                         LUSTRE_VERSION_OFFSET_WARN)) {
1008                         /* Sigh, some compilers do not like #ifdef in the middle
1009                            of macro arguments */
1010 #ifdef __KERNEL__
1011                         const char *older = "older. Consider upgrading server "
1012                                             "or downgrading client";
1013 #else
1014                         const char *older = "older. Consider recompiling this "
1015                                             "application";
1016 #endif
1017                         const char *newer = "newer than client version. "
1018                                             "Consider upgrading client";
1019
1020                         LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
1021                                       "is much %s (%s)\n",
1022                                       obd2cli_tgt(imp->imp_obd),
1023                                       OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1024                                       OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1025                                       OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1026                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1027                                       ocd->ocd_version > LUSTRE_VERSION_CODE ?
1028                                       newer : older, LUSTRE_VERSION_STRING);
1029                 }
1030
1031                 if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
1032                         /* We sent to the server ocd_cksum_types with bits set
1033                          * for algorithms we understand. The server masked off
1034                          * the checksum types it doesn't support */
1035                         if ((ocd->ocd_cksum_types &
1036                              cksum_types_supported_client()) == 0) {
1037                                 LCONSOLE_WARN("The negotiation of the checksum "
1038                                               "alogrithm to use with server %s "
1039                                               "failed (%x/%x), disabling "
1040                                               "checksums\n",
1041                                               obd2cli_tgt(imp->imp_obd),
1042                                               ocd->ocd_cksum_types,
1043                                               cksum_types_supported_client());
1044                                 cli->cl_checksum = 0;
1045                                 cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
1046                         } else {
1047                                 cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
1048                         }
1049                 } else {
1050                         /* The server does not support OBD_CONNECT_CKSUM.
1051                          * Enforce ADLER for backward compatibility*/
1052                         cli->cl_supp_cksum_types = OBD_CKSUM_ADLER;
1053                 }
1054                 cli->cl_cksum_type =cksum_type_select(cli->cl_supp_cksum_types);
1055
1056                 if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE)
1057                         cli->cl_max_pages_per_rpc =
1058                                 ocd->ocd_brw_size >> CFS_PAGE_SHIFT;
1059                 else if (imp->imp_connect_op == MDS_CONNECT ||
1060                          imp->imp_connect_op == MGS_CONNECT)
1061                         cli->cl_max_pages_per_rpc = 1;
1062
1063                 /* Reset ns_connect_flags only for initial connect. It might be
1064                  * changed in while using FS and if we reset it in reconnect
1065                  * this leads to losing user settings done before such as
1066                  * disable lru_resize, etc. */
1067                 if (old_connect_flags != exp->exp_connect_flags ||
1068                     aa->pcaa_initial_connect) {
1069                         CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
1070                                "flags: "LPX64"\n", imp->imp_obd->obd_name,
1071                               ocd->ocd_connect_flags);
1072                         imp->imp_obd->obd_namespace->ns_connect_flags =
1073                                 ocd->ocd_connect_flags;
1074                         imp->imp_obd->obd_namespace->ns_orig_connect_flags =
1075                                 ocd->ocd_connect_flags;
1076                 }
1077
1078                 if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
1079                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1080                         /* We need a per-message support flag, because
1081                            a. we don't know if the incoming connect reply
1082                               supports AT or not (in reply_in_callback)
1083                               until we unpack it.
1084                            b. failovered server means export and flags are gone
1085                               (in ptlrpc_send_reply).
1086                            Can only be set when we know AT is supported at
1087                            both ends */
1088                         imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1089                 else
1090                         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1091
1092                 if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1093                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1094                         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1095                 else
1096                         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1097
1098                 LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
1099                         (cli->cl_max_pages_per_rpc > 0));
1100         }
1101
1102 out:
1103         if (rc != 0) {
1104                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1105                 if (rc == -EACCES) {
1106                         /*
1107                          * Give up trying to reconnect
1108                          * EACCES means client has no permission for connection
1109                          */
1110                         imp->imp_obd->obd_no_recov = 1;
1111                         ptlrpc_deactivate_import(imp);
1112                 }
1113
1114                 if (rc == -EPROTO) {
1115                         struct obd_connect_data *ocd;
1116
1117                         /* reply message might not be ready */
1118                         if (request->rq_repmsg == NULL)
1119                                 RETURN(-EPROTO);
1120
1121                         ocd = req_capsule_server_get(&request->rq_pill,
1122                                                      &RMF_CONNECT_DATA);
1123                         if (ocd &&
1124                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1125                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1126                            /* Actually servers are only supposed to refuse
1127                               connection from liblustre clients, so we should
1128                               never see this from VFS context */
1129                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1130                                         "(%d.%d.%d.%d)"
1131                                         " refused connection from this client "
1132                                         "with an incompatible version (%s).  "
1133                                         "Client must be recompiled\n",
1134                                         obd2cli_tgt(imp->imp_obd),
1135                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1136                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1137                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1138                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1139                                         LUSTRE_VERSION_STRING);
1140                                 ptlrpc_deactivate_import(imp);
1141                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1142                         }
1143                         RETURN(-EPROTO);
1144                 }
1145
1146                 ptlrpc_maybe_ping_import_soon(imp);
1147
1148                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1149                        obd2cli_tgt(imp->imp_obd),
1150                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1151         }
1152
1153         cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1154         RETURN(rc);
1155 }
1156
1157 /**
1158  * interpret callback for "completed replay" RPCs.
1159  * \see signal_completed_replay
1160  */
1161 static int completed_replay_interpret(const struct lu_env *env,
1162                                       struct ptlrpc_request *req,
1163                                       void * data, int rc)
1164 {
1165         ENTRY;
1166         cfs_atomic_dec(&req->rq_import->imp_replay_inflight);
1167         if (req->rq_status == 0 &&
1168             !req->rq_import->imp_vbr_failed) {
1169                 ptlrpc_import_recovery_state_machine(req->rq_import);
1170         } else {
1171                 if (req->rq_import->imp_vbr_failed) {
1172                         CDEBUG(D_WARNING,
1173                                "%s: version recovery fails, reconnecting\n",
1174                                req->rq_import->imp_obd->obd_name);
1175                 } else {
1176                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1177                                      "reconnecting\n",
1178                                req->rq_import->imp_obd->obd_name,
1179                                req->rq_status);
1180                 }
1181                 ptlrpc_connect_import(req->rq_import);
1182         }
1183
1184         RETURN(0);
1185 }
1186
1187 /**
1188  * Let server know that we have no requests to replay anymore.
1189  * Achieved by just sending a PING request
1190  */
1191 static int signal_completed_replay(struct obd_import *imp)
1192 {
1193         struct ptlrpc_request *req;
1194         ENTRY;
1195
1196         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1197                 RETURN(0);
1198
1199         LASSERT(cfs_atomic_read(&imp->imp_replay_inflight) == 0);
1200         cfs_atomic_inc(&imp->imp_replay_inflight);
1201
1202         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1203                                         OBD_PING);
1204         if (req == NULL) {
1205                 cfs_atomic_dec(&imp->imp_replay_inflight);
1206                 RETURN(-ENOMEM);
1207         }
1208
1209         ptlrpc_request_set_replen(req);
1210         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1211         lustre_msg_add_flags(req->rq_reqmsg,
1212                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1213         if (AT_OFF)
1214                 req->rq_timeout *= 3;
1215         req->rq_interpret_reply = completed_replay_interpret;
1216
1217         ptlrpcd_add_req(req, PDL_POLICY_ROUND, -1);
1218         RETURN(0);
1219 }
1220
1221 #ifdef __KERNEL__
1222 /**
1223  * In kernel code all import invalidation happens in its own
1224  * separate thread, so that whatever application happened to encounter
1225  * a problem could still be killed or otherwise continue
1226  */
1227 static int ptlrpc_invalidate_import_thread(void *data)
1228 {
1229         struct obd_import *imp = data;
1230
1231         ENTRY;
1232
1233         cfs_daemonize_ctxt("ll_imp_inval");
1234
1235         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1236                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1237                imp->imp_connection->c_remote_uuid.uuid);
1238
1239         ptlrpc_invalidate_import(imp);
1240
1241         if (obd_dump_on_eviction) {
1242                 CERROR("dump the log upon eviction\n");
1243                 libcfs_debug_dumplog();
1244         }
1245
1246         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1247         ptlrpc_import_recovery_state_machine(imp);
1248
1249         class_import_put(imp);
1250         RETURN(0);
1251 }
1252 #endif
1253
1254 /**
1255  * This is the state machine for client-side recovery on import.
1256  *
1257  * Typicaly we have two possibly paths. If we came to server and it is not
1258  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1259  * state and reconnect from scratch.
1260  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1261  * We go through our list of requests to replay and send them to server one by
1262  * one.
1263  * After sending all request from the list we change import state to
1264  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1265  * and also all the locks we don't yet have and wait for server to grant us.
1266  * After that we send a special "replay completed" request and change import
1267  * state to IMP_REPLAY_WAIT.
1268  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1269  * state and resend all requests from sending list.
1270  * After that we promote import to FULL state and send all delayed requests
1271  * and import is fully operational after that.
1272  *
1273  */
1274 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1275 {
1276         int rc = 0;
1277         int inflight;
1278         char *target_start;
1279         int target_len;
1280
1281         ENTRY;
1282         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1283                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1284                           &target_start, &target_len);
1285                 /* Don't care about MGC eviction */
1286                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1287                            LUSTRE_MGC_NAME) != 0) {
1288                         LCONSOLE_ERROR_MSG(0x167, "This client was evicted by "
1289                                            "%.*s; in progress operations using "
1290                                            "this service will fail.\n",
1291                                            target_len, target_start);
1292                 }
1293                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1294                        obd2cli_tgt(imp->imp_obd),
1295                        imp->imp_connection->c_remote_uuid.uuid);
1296                 /* reset vbr_failed flag upon eviction */
1297                 cfs_spin_lock(&imp->imp_lock);
1298                 imp->imp_vbr_failed = 0;
1299                 cfs_spin_unlock(&imp->imp_lock);
1300
1301 #ifdef __KERNEL__
1302                 /* bug 17802:  XXX client_disconnect_export vs connect request
1303                  * race. if client will evicted at this time, we start
1304                  * invalidate thread without reference to import and import can
1305                  * be freed at same time. */
1306                 class_import_get(imp);
1307                 rc = cfs_create_thread(ptlrpc_invalidate_import_thread, imp,
1308                                        CFS_DAEMON_FLAGS);
1309                 if (rc < 0) {
1310                         class_import_put(imp);
1311                         CERROR("error starting invalidate thread: %d\n", rc);
1312                 } else {
1313                         rc = 0;
1314                 }
1315                 RETURN(rc);
1316 #else
1317                 ptlrpc_invalidate_import(imp);
1318
1319                 IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1320 #endif
1321         }
1322
1323         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1324                 CDEBUG(D_HA, "replay requested by %s\n",
1325                        obd2cli_tgt(imp->imp_obd));
1326                 rc = ptlrpc_replay_next(imp, &inflight);
1327                 if (inflight == 0 &&
1328                     cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1329                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1330                         rc = ldlm_replay_locks(imp);
1331                         if (rc)
1332                                 GOTO(out, rc);
1333                 }
1334                 rc = 0;
1335         }
1336
1337         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1338                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1339                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1340                         rc = signal_completed_replay(imp);
1341                         if (rc)
1342                                 GOTO(out, rc);
1343                 }
1344
1345         }
1346
1347         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1348                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1349                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1350                 }
1351         }
1352
1353         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1354                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1355                        obd2cli_tgt(imp->imp_obd),
1356                        imp->imp_connection->c_remote_uuid.uuid);
1357
1358                 rc = ptlrpc_resend(imp);
1359                 if (rc)
1360                         GOTO(out, rc);
1361                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1362                 ptlrpc_activate_import(imp);
1363
1364                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1365                           &target_start, &target_len);
1366                 LCONSOLE_INFO("%s: Connection restored to %.*s (at %s)\n",
1367                               imp->imp_obd->obd_name,
1368                               target_len, target_start,
1369                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1370         }
1371
1372         if (imp->imp_state == LUSTRE_IMP_FULL) {
1373                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1374                 ptlrpc_wake_delayed(imp);
1375         }
1376
1377 out:
1378         RETURN(rc);
1379 }
1380
1381 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1382 {
1383         struct ptlrpc_request *req;
1384         int rq_opc, rc = 0;
1385         int nowait = imp->imp_obd->obd_force;
1386         ENTRY;
1387
1388         if (nowait)
1389                 GOTO(set_state, rc);
1390
1391         switch (imp->imp_connect_op) {
1392         case OST_CONNECT: rq_opc = OST_DISCONNECT; break;
1393         case MDS_CONNECT: rq_opc = MDS_DISCONNECT; break;
1394         case MGS_CONNECT: rq_opc = MGS_DISCONNECT; break;
1395         default:
1396                 CERROR("don't know how to disconnect from %s (connect_op %d)\n",
1397                        obd2cli_tgt(imp->imp_obd), imp->imp_connect_op);
1398                 RETURN(-EINVAL);
1399         }
1400
1401         if (ptlrpc_import_in_recovery(imp)) {
1402                 struct l_wait_info lwi;
1403                 cfs_duration_t timeout;
1404
1405
1406                 if (AT_OFF) {
1407                         if (imp->imp_server_timeout)
1408                                 timeout = cfs_time_seconds(obd_timeout / 2);
1409                         else
1410                                 timeout = cfs_time_seconds(obd_timeout);
1411                 } else {
1412                         int idx = import_at_get_index(imp,
1413                                 imp->imp_client->cli_request_portal);
1414                         timeout = cfs_time_seconds(
1415                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1416                 }
1417
1418                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1419                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1420                 rc = l_wait_event(imp->imp_recovery_waitq,
1421                                   !ptlrpc_import_in_recovery(imp), &lwi);
1422
1423         }
1424
1425         cfs_spin_lock(&imp->imp_lock);
1426         if (imp->imp_state != LUSTRE_IMP_FULL)
1427                 GOTO(out, 0);
1428
1429         cfs_spin_unlock(&imp->imp_lock);
1430
1431         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1432                                         LUSTRE_OBD_VERSION, rq_opc);
1433         if (req) {
1434                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1435                  * it fails.  We can get through the above with a down server
1436                  * if the client doesn't know the server is gone yet. */
1437                 req->rq_no_resend = 1;
1438
1439                 /* We want client umounts to happen quickly, no matter the
1440                    server state... */
1441                 req->rq_timeout = min_t(int, req->rq_timeout,
1442                                         INITIAL_CONNECT_TIMEOUT);
1443
1444                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1445                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1446                 ptlrpc_request_set_replen(req);
1447                 rc = ptlrpc_queue_wait(req);
1448                 ptlrpc_req_finished(req);
1449         }
1450
1451 set_state:
1452         cfs_spin_lock(&imp->imp_lock);
1453 out:
1454         if (noclose)
1455                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1456         else
1457                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1458         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1459         cfs_spin_unlock(&imp->imp_lock);
1460
1461         RETURN(rc);
1462 }
1463 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1464
1465 void ptlrpc_cleanup_imp(struct obd_import *imp)
1466 {
1467         ENTRY;
1468
1469         cfs_spin_lock(&imp->imp_lock);
1470         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1471         imp->imp_generation++;
1472         cfs_spin_unlock(&imp->imp_lock);
1473         ptlrpc_abort_inflight(imp);
1474
1475         EXIT;
1476 }
1477 EXPORT_SYMBOL(ptlrpc_cleanup_imp);
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 }