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