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