Whamcloud - gitweb
e50a11dade2393f6c374d47738190a9467fdcfc0
[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_measured(&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         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
671
672         rc = obd_reconnect(NULL, imp->imp_obd->obd_self_export, obd,
673                            &obd->obd_uuid, &imp->imp_connect_data, NULL);
674         if (rc)
675                 GOTO(out, rc);
676
677         request = ptlrpc_request_alloc(imp, &RQF_MDS_CONNECT);
678         if (request == NULL)
679                 GOTO(out, rc = -ENOMEM);
680
681         rc = ptlrpc_request_bufs_pack(request, LUSTRE_OBD_VERSION,
682                                       imp->imp_connect_op, bufs, NULL);
683         if (rc) {
684                 ptlrpc_request_free(request);
685                 GOTO(out, rc);
686         }
687
688         /* Report the rpc service time to the server so that it knows how long
689          * to wait for clients to join recovery */
690         lustre_msg_set_service_time(request->rq_reqmsg,
691                                     at_timeout2est(request->rq_timeout));
692
693         /* The amount of time we give the server to process the connect req.
694          * import_select_connection will increase the net latency on
695          * repeated reconnect attempts to cover slow networks.
696          * We override/ignore the server rpc completion estimate here,
697          * which may be large if this is a reconnect attempt */
698         request->rq_timeout = INITIAL_CONNECT_TIMEOUT;
699         lustre_msg_set_timeout(request->rq_reqmsg, request->rq_timeout);
700
701 #ifndef __KERNEL__
702         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_LIBCLIENT);
703 #endif
704         lustre_msg_add_op_flags(request->rq_reqmsg, MSG_CONNECT_NEXT_VER);
705
706         request->rq_no_resend = request->rq_no_delay = 1;
707         request->rq_send_state = LUSTRE_IMP_CONNECTING;
708         /* Allow a slightly larger reply for future growth compatibility */
709         req_capsule_set_size(&request->rq_pill, &RMF_CONNECT_DATA, RCL_SERVER,
710                              sizeof(struct obd_connect_data)+16*sizeof(__u64));
711         ptlrpc_request_set_replen(request);
712         request->rq_interpret_reply = ptlrpc_connect_interpret;
713
714         CLASSERT(sizeof (*aa) <= sizeof (request->rq_async_args));
715         aa = ptlrpc_req_async_args(request);
716         memset(aa, 0, sizeof *aa);
717
718         aa->pcaa_peer_committed = committed_before_reconnect;
719         aa->pcaa_initial_connect = initial_connect;
720
721         if (aa->pcaa_initial_connect) {
722                 cfs_spin_lock(&imp->imp_lock);
723                 imp->imp_replayable = 1;
724                 cfs_spin_unlock(&imp->imp_lock);
725                 lustre_msg_add_op_flags(request->rq_reqmsg,
726                                         MSG_CONNECT_INITIAL);
727         }
728
729         if (set_transno)
730                 lustre_msg_add_op_flags(request->rq_reqmsg,
731                                         MSG_CONNECT_TRANSNO);
732
733         DEBUG_REQ(D_RPCTRACE, request, "(re)connect request (timeout %d)",
734                   request->rq_timeout);
735         ptlrpcd_add_req(request, PSCOPE_OTHER);
736         rc = 0;
737 out:
738         if (rc != 0) {
739                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
740         }
741
742         RETURN(rc);
743 }
744 EXPORT_SYMBOL(ptlrpc_connect_import);
745
746 static void ptlrpc_maybe_ping_import_soon(struct obd_import *imp)
747 {
748 #ifdef __KERNEL__
749         struct obd_import_conn *imp_conn;
750 #endif
751         int wake_pinger = 0;
752
753         ENTRY;
754
755         cfs_spin_lock(&imp->imp_lock);
756         if (cfs_list_empty(&imp->imp_conn_list))
757                 GOTO(unlock, 0);
758
759 #ifdef __KERNEL__
760         imp_conn = cfs_list_entry(imp->imp_conn_list.prev,
761                                   struct obd_import_conn,
762                                   oic_item);
763
764         /* XXX: When the failover node is the primary node, it is possible
765          * to have two identical connections in imp_conn_list. We must
766          * compare not conn's pointers but NIDs, otherwise we can defeat
767          * connection throttling. (See bug 14774.) */
768         if (imp->imp_conn_current->oic_conn->c_peer.nid !=
769                                 imp_conn->oic_conn->c_peer.nid) {
770                 ptlrpc_ping_import_soon(imp);
771                 wake_pinger = 1;
772         }
773 #else
774         /* liblustre has no pinger thread, so we wakeup pinger anyway */
775         wake_pinger = 1;
776 #endif
777
778  unlock:
779         cfs_spin_unlock(&imp->imp_lock);
780
781         if (wake_pinger)
782                 ptlrpc_pinger_wake_up();
783
784         EXIT;
785 }
786
787 static int ptlrpc_busy_reconnect(int rc)
788 {
789         return (rc == -EBUSY) || (rc == -EAGAIN);
790 }
791
792
793 static int ptlrpc_connect_interpret(const struct lu_env *env,
794                                     struct ptlrpc_request *request,
795                                     void *data, int rc)
796 {
797         struct ptlrpc_connect_async_args *aa = data;
798         struct obd_import *imp = request->rq_import;
799         struct client_obd *cli = &imp->imp_obd->u.cli;
800         struct lustre_handle old_hdl;
801         __u64 old_connect_flags;
802         int msg_flags;
803         ENTRY;
804
805         cfs_spin_lock(&imp->imp_lock);
806         if (imp->imp_state == LUSTRE_IMP_CLOSED) {
807                 cfs_spin_unlock(&imp->imp_lock);
808                 RETURN(0);
809         }
810
811         if (rc) {
812                 /* if this reconnect to busy export - not need select new target
813                  * for connecting*/
814                 imp->imp_force_reconnect = ptlrpc_busy_reconnect(rc);
815                 cfs_spin_unlock(&imp->imp_lock);
816                 GOTO(out, rc);
817         }
818
819         LASSERT(imp->imp_conn_current);
820
821         msg_flags = lustre_msg_get_op_flags(request->rq_repmsg);
822
823         /* All imports are pingable */
824         imp->imp_pingable = 1;
825         imp->imp_force_reconnect = 0;
826
827         if (aa->pcaa_initial_connect) {
828                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
829                         imp->imp_replayable = 1;
830                         cfs_spin_unlock(&imp->imp_lock);
831                         CDEBUG(D_HA, "connected to replayable target: %s\n",
832                                obd2cli_tgt(imp->imp_obd));
833                 } else {
834                         imp->imp_replayable = 0;
835                         cfs_spin_unlock(&imp->imp_lock);
836                 }
837
838                 /* if applies, adjust the imp->imp_msg_magic here
839                  * according to reply flags */
840
841                 imp->imp_remote_handle =
842                                 *lustre_msg_get_handle(request->rq_repmsg);
843
844                 /* Initial connects are allowed for clients with non-random
845                  * uuids when servers are in recovery.  Simply signal the
846                  * servers replay is complete and wait in REPLAY_WAIT. */
847                 if (msg_flags & MSG_CONNECT_RECOVERING) {
848                         CDEBUG(D_HA, "connect to %s during recovery\n",
849                                obd2cli_tgt(imp->imp_obd));
850                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
851                 } else {
852                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
853                         ptlrpc_activate_import(imp);
854                 }
855
856                 GOTO(finish, rc = 0);
857         } else {
858                 cfs_spin_unlock(&imp->imp_lock);
859         }
860
861         /* Determine what recovery state to move the import to. */
862         if (MSG_CONNECT_RECONNECT & msg_flags) {
863                 memset(&old_hdl, 0, sizeof(old_hdl));
864                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
865                             sizeof (old_hdl))) {
866                         CERROR("%s@%s didn't like our handle "LPX64
867                                ", failed\n", obd2cli_tgt(imp->imp_obd),
868                                imp->imp_connection->c_remote_uuid.uuid,
869                                imp->imp_dlm_handle.cookie);
870                         GOTO(out, rc = -ENOTCONN);
871                 }
872
873                 if (memcmp(&imp->imp_remote_handle,
874                            lustre_msg_get_handle(request->rq_repmsg),
875                            sizeof(imp->imp_remote_handle))) {
876                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
877                                 D_HA : D_WARNING;
878
879                         /* Bug 16611/14775: if server handle have changed,
880                          * that means some sort of disconnection happened.
881                          * If the server is not in recovery, that also means it
882                          * already erased all of our state because of previous
883                          * eviction. If it is in recovery - we are safe to
884                          * participate since we can reestablish all of our state
885                          * with server again */
886                         CDEBUG(level,"%s@%s changed server handle from "
887                                      LPX64" to "LPX64"%s\n",
888                                      obd2cli_tgt(imp->imp_obd),
889                                      imp->imp_connection->c_remote_uuid.uuid,
890                                      imp->imp_remote_handle.cookie,
891                                      lustre_msg_get_handle(request->rq_repmsg)->
892                                                                         cookie,
893                                      (MSG_CONNECT_RECOVERING & msg_flags) ?
894                                          " but is still in recovery" : "");
895
896                         imp->imp_remote_handle =
897                                      *lustre_msg_get_handle(request->rq_repmsg);
898
899                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
900                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
901                                 GOTO(finish, rc = 0);
902                         }
903
904                 } else {
905                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
906                                obd2cli_tgt(imp->imp_obd),
907                                imp->imp_connection->c_remote_uuid.uuid);
908                 }
909
910                 if (imp->imp_invalid) {
911                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
912                                "marking evicted\n", imp->imp_obd->obd_name);
913                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
914                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
915                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
916                                imp->imp_obd->obd_name,
917                                obd2cli_tgt(imp->imp_obd));
918
919                         cfs_spin_lock(&imp->imp_lock);
920                         imp->imp_resend_replay = 1;
921                         cfs_spin_unlock(&imp->imp_lock);
922
923                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
924                 } else {
925                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
926                 }
927         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
928                 LASSERT(imp->imp_replayable);
929                 imp->imp_remote_handle =
930                                 *lustre_msg_get_handle(request->rq_repmsg);
931                 imp->imp_last_replay_transno = 0;
932                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
933         } else {
934                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
935                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
936                 imp->imp_remote_handle =
937                                 *lustre_msg_get_handle(request->rq_repmsg);
938                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
939         }
940
941         /* Sanity checks for a reconnected import. */
942         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
943                 CERROR("imp_replayable flag does not match server "
944                        "after reconnect. We should LBUG right here.\n");
945         }
946
947         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
948             lustre_msg_get_last_committed(request->rq_repmsg) <
949             aa->pcaa_peer_committed) {
950                 CERROR("%s went back in time (transno "LPD64
951                        " was previously committed, server now claims "LPD64
952                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
953                        "id=9646\n",
954                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
955                        lustre_msg_get_last_committed(request->rq_repmsg));
956         }
957
958 finish:
959         rc = ptlrpc_import_recovery_state_machine(imp);
960         if (rc != 0) {
961                 if (rc == -ENOTCONN) {
962                         CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
963                                "invalidating and reconnecting\n",
964                                obd2cli_tgt(imp->imp_obd),
965                                imp->imp_connection->c_remote_uuid.uuid);
966                         ptlrpc_connect_import(imp, NULL);
967                         RETURN(0);
968                 }
969         } else {
970                 struct obd_connect_data *ocd;
971                 struct obd_export *exp;
972                 int ret;
973                 ret = req_capsule_get_size(&request->rq_pill, &RMF_CONNECT_DATA,
974                                            RCL_SERVER);
975                 /* server replied obd_connect_data is always bigger */
976                 ocd = req_capsule_server_sized_get(&request->rq_pill,
977                                                    &RMF_CONNECT_DATA, ret);
978
979                 cfs_spin_lock(&imp->imp_lock);
980                 cfs_list_del(&imp->imp_conn_current->oic_item);
981                 cfs_list_add(&imp->imp_conn_current->oic_item,
982                              &imp->imp_conn_list);
983                 imp->imp_last_success_conn =
984                         imp->imp_conn_current->oic_last_attempt;
985
986                 if (ocd == NULL) {
987                         cfs_spin_unlock(&imp->imp_lock);
988                         CERROR("Wrong connect data from server\n");
989                         rc = -EPROTO;
990                         GOTO(out, rc);
991                 }
992
993                 imp->imp_connect_data = *ocd;
994
995                 exp = class_conn2export(&imp->imp_dlm_handle);
996                 cfs_spin_unlock(&imp->imp_lock);
997
998                 /* check that server granted subset of flags we asked for. */
999                 LASSERTF((ocd->ocd_connect_flags &
1000                           imp->imp_connect_flags_orig) ==
1001                          ocd->ocd_connect_flags, LPX64" != "LPX64,
1002                          imp->imp_connect_flags_orig, ocd->ocd_connect_flags);
1003
1004                 if (!exp) {
1005                         /* This could happen if export is cleaned during the
1006                            connect attempt */
1007                         CERROR("Missing export for %s\n",
1008                                imp->imp_obd->obd_name);
1009                         GOTO(out, rc = -ENODEV);
1010                 }
1011                 old_connect_flags = exp->exp_connect_flags;
1012                 exp->exp_connect_flags = ocd->ocd_connect_flags;
1013                 imp->imp_obd->obd_self_export->exp_connect_flags =
1014                                                         ocd->ocd_connect_flags;
1015                 class_export_put(exp);
1016
1017                 obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1018
1019                 if (!ocd->ocd_ibits_known &&
1020                     ocd->ocd_connect_flags & OBD_CONNECT_IBITS)
1021                         CERROR("Inodebits aware server returned zero compatible"
1022                                " bits?\n");
1023
1024                 if ((ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1025                     (ocd->ocd_version > LUSTRE_VERSION_CODE +
1026                                         LUSTRE_VERSION_OFFSET_WARN ||
1027                      ocd->ocd_version < LUSTRE_VERSION_CODE -
1028                                         LUSTRE_VERSION_OFFSET_WARN)) {
1029                         /* Sigh, some compilers do not like #ifdef in the middle
1030                            of macro arguments */
1031 #ifdef __KERNEL__
1032                         const char *older =
1033                                 "older. Consider upgrading this client";
1034 #else
1035                         const char *older =
1036                                 "older. Consider recompiling this application";
1037 #endif
1038                         const char *newer = "newer than client version";
1039
1040                         LCONSOLE_WARN("Server %s version (%d.%d.%d.%d) "
1041                                       "is much %s (%s)\n",
1042                                       obd2cli_tgt(imp->imp_obd),
1043                                       OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1044                                       OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1045                                       OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1046                                       OBD_OCD_VERSION_FIX(ocd->ocd_version),
1047                                       ocd->ocd_version > LUSTRE_VERSION_CODE ?
1048                                       newer : older, LUSTRE_VERSION_STRING);
1049                 }
1050
1051                 if (ocd->ocd_connect_flags & OBD_CONNECT_CKSUM) {
1052                         /* We sent to the server ocd_cksum_types with bits set
1053                          * for algorithms we understand. The server masked off
1054                          * the checksum types it doesn't support */
1055                         if ((ocd->ocd_cksum_types & OBD_CKSUM_ALL) == 0) {
1056                                 LCONSOLE_WARN("The negotiation of the checksum "
1057                                               "alogrithm to use with server %s "
1058                                               "failed (%x/%x), disabling "
1059                                               "checksums\n",
1060                                               obd2cli_tgt(imp->imp_obd),
1061                                               ocd->ocd_cksum_types,
1062                                               OBD_CKSUM_ALL);
1063                                 cli->cl_checksum = 0;
1064                                 cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
1065                                 cli->cl_cksum_type = OBD_CKSUM_CRC32;
1066                         } else {
1067                                 cli->cl_supp_cksum_types = ocd->ocd_cksum_types;
1068
1069                                 if (ocd->ocd_cksum_types & OSC_DEFAULT_CKSUM)
1070                                         cli->cl_cksum_type = OSC_DEFAULT_CKSUM;
1071                                 else if (ocd->ocd_cksum_types & OBD_CKSUM_ADLER)
1072                                         cli->cl_cksum_type = OBD_CKSUM_ADLER;
1073                                 else
1074                                         cli->cl_cksum_type = OBD_CKSUM_CRC32;
1075                         }
1076                 } else {
1077                         /* The server does not support OBD_CONNECT_CKSUM.
1078                          * Enforce CRC32 for backward compatibility*/
1079                         cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
1080                         cli->cl_cksum_type = OBD_CKSUM_CRC32;
1081                 }
1082
1083                 if (ocd->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
1084                         cli->cl_max_pages_per_rpc =
1085                                 ocd->ocd_brw_size >> CFS_PAGE_SHIFT;
1086                 }
1087
1088                 /* Reset ns_connect_flags only for initial connect. It might be
1089                  * changed in while using FS and if we reset it in reconnect
1090                  * this leads to losing user settings done before such as
1091                  * disable lru_resize, etc. */
1092                 if (old_connect_flags != exp->exp_connect_flags ||
1093                     aa->pcaa_initial_connect) {
1094                         CDEBUG(D_HA, "%s: Resetting ns_connect_flags to server "
1095                                "flags: "LPX64"\n", imp->imp_obd->obd_name,
1096                               ocd->ocd_connect_flags);
1097                         imp->imp_obd->obd_namespace->ns_connect_flags =
1098                                 ocd->ocd_connect_flags;
1099                         imp->imp_obd->obd_namespace->ns_orig_connect_flags =
1100                                 ocd->ocd_connect_flags;
1101                 }
1102
1103                 if ((ocd->ocd_connect_flags & OBD_CONNECT_AT) &&
1104                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1105                         /* We need a per-message support flag, because
1106                            a. we don't know if the incoming connect reply
1107                               supports AT or not (in reply_in_callback)
1108                               until we unpack it.
1109                            b. failovered server means export and flags are gone
1110                               (in ptlrpc_send_reply).
1111                            Can only be set when we know AT is supported at
1112                            both ends */
1113                         imp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1114                 else
1115                         imp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1116
1117                 if ((ocd->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1118                     (imp->imp_msg_magic == LUSTRE_MSG_MAGIC_V2))
1119                         imp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1120                 else
1121                         imp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1122
1123                 LASSERT((cli->cl_max_pages_per_rpc <= PTLRPC_MAX_BRW_PAGES) &&
1124                         (cli->cl_max_pages_per_rpc > 0));
1125         }
1126
1127 out:
1128         if (rc != 0) {
1129                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1130                 cfs_spin_lock(&imp->imp_lock);
1131                 if (aa->pcaa_initial_connect && !imp->imp_initial_recov &&
1132                     (request->rq_import_generation == imp->imp_generation))
1133                         ptlrpc_deactivate_and_unlock_import(imp);
1134                 else
1135                         cfs_spin_unlock(&imp->imp_lock);
1136
1137                 if ((imp->imp_recon_bk && imp->imp_last_recon) ||
1138                     (rc == -EACCES)) {
1139                         /*
1140                          * Give up trying to reconnect
1141                          * EACCES means client has no permission for connection
1142                          */
1143                         imp->imp_obd->obd_no_recov = 1;
1144                         ptlrpc_deactivate_import(imp);
1145                 }
1146
1147                 if (rc == -EPROTO) {
1148                         struct obd_connect_data *ocd;
1149
1150                         /* reply message might not be ready */
1151                         if (request->rq_repmsg == NULL)
1152                                 RETURN(-EPROTO);
1153
1154                         ocd = req_capsule_server_get(&request->rq_pill,
1155                                                      &RMF_CONNECT_DATA);
1156                         if (ocd &&
1157                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1158                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1159                            /* Actually servers are only supposed to refuse
1160                               connection from liblustre clients, so we should
1161                               never see this from VFS context */
1162                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1163                                         "(%d.%d.%d.%d)"
1164                                         " refused connection from this client "
1165                                         "with an incompatible version (%s).  "
1166                                         "Client must be recompiled\n",
1167                                         obd2cli_tgt(imp->imp_obd),
1168                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1169                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1170                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1171                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1172                                         LUSTRE_VERSION_STRING);
1173                                 ptlrpc_deactivate_import(imp);
1174                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1175                         }
1176                         RETURN(-EPROTO);
1177                 }
1178
1179                 ptlrpc_maybe_ping_import_soon(imp);
1180
1181                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1182                        obd2cli_tgt(imp->imp_obd),
1183                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1184         }
1185
1186         cfs_spin_lock(&imp->imp_lock);
1187         imp->imp_last_recon = 0;
1188         cfs_spin_unlock(&imp->imp_lock);
1189
1190         cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1191         RETURN(rc);
1192 }
1193
1194 static int completed_replay_interpret(const struct lu_env *env,
1195                                       struct ptlrpc_request *req,
1196                                       void * data, int rc)
1197 {
1198         ENTRY;
1199         cfs_atomic_dec(&req->rq_import->imp_replay_inflight);
1200         if (req->rq_status == 0 &&
1201             !req->rq_import->imp_vbr_failed) {
1202                 ptlrpc_import_recovery_state_machine(req->rq_import);
1203         } else {
1204                 if (req->rq_import->imp_vbr_failed) {
1205                         CDEBUG(D_WARNING,
1206                                "%s: version recovery fails, reconnecting\n",
1207                                req->rq_import->imp_obd->obd_name);
1208                 } else {
1209                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1210                                      "reconnecting\n",
1211                                req->rq_import->imp_obd->obd_name,
1212                                req->rq_status);
1213                 }
1214                 ptlrpc_connect_import(req->rq_import, NULL);
1215         }
1216
1217         RETURN(0);
1218 }
1219
1220 static int signal_completed_replay(struct obd_import *imp)
1221 {
1222         struct ptlrpc_request *req;
1223         ENTRY;
1224
1225         LASSERT(cfs_atomic_read(&imp->imp_replay_inflight) == 0);
1226         cfs_atomic_inc(&imp->imp_replay_inflight);
1227
1228         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1229                                         OBD_PING);
1230         if (req == NULL) {
1231                 cfs_atomic_dec(&imp->imp_replay_inflight);
1232                 RETURN(-ENOMEM);
1233         }
1234
1235         ptlrpc_request_set_replen(req);
1236         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1237         lustre_msg_add_flags(req->rq_reqmsg,
1238                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1239         if (AT_OFF)
1240                 req->rq_timeout *= 3;
1241         req->rq_interpret_reply = completed_replay_interpret;
1242
1243         ptlrpcd_add_req(req, PSCOPE_OTHER);
1244         RETURN(0);
1245 }
1246
1247 #ifdef __KERNEL__
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 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1276 {
1277         int rc = 0;
1278         int inflight;
1279         char *target_start;
1280         int target_len;
1281
1282         ENTRY;
1283         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1284                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1285                           &target_start, &target_len);
1286                 /* Don't care about MGC eviction */
1287                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1288                            LUSTRE_MGC_NAME) != 0) {
1289                         LCONSOLE_ERROR_MSG(0x167, "This client was evicted by "
1290                                            "%.*s; in progress operations using "
1291                                            "this service will fail.\n",
1292                                            target_len, target_start);
1293                 }
1294                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1295                        obd2cli_tgt(imp->imp_obd),
1296                        imp->imp_connection->c_remote_uuid.uuid);
1297                 /* reset vbr_failed flag upon eviction */
1298                 cfs_spin_lock(&imp->imp_lock);
1299                 imp->imp_vbr_failed = 0;
1300                 cfs_spin_unlock(&imp->imp_lock);
1301
1302 #ifdef __KERNEL__
1303                 /* bug 17802:  XXX client_disconnect_export vs connect request
1304                  * race. if client will evicted at this time, we start
1305                  * invalidate thread without reference to import and import can
1306                  * be freed at same time. */
1307                 class_import_get(imp);
1308                 rc = cfs_kernel_thread(ptlrpc_invalidate_import_thread, imp,
1309                                        CLONE_VM | CLONE_FILES);
1310                 if (rc < 0) {
1311                         class_import_put(imp);
1312                         CERROR("error starting invalidate thread: %d\n", rc);
1313                 } else {
1314                         rc = 0;
1315                 }
1316                 RETURN(rc);
1317 #else
1318                 ptlrpc_invalidate_import(imp);
1319
1320                 IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1321 #endif
1322         }
1323
1324         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1325                 CDEBUG(D_HA, "replay requested by %s\n",
1326                        obd2cli_tgt(imp->imp_obd));
1327                 rc = ptlrpc_replay_next(imp, &inflight);
1328                 if (inflight == 0 &&
1329                     cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1330                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1331                         rc = ldlm_replay_locks(imp);
1332                         if (rc)
1333                                 GOTO(out, rc);
1334                 }
1335                 rc = 0;
1336         }
1337
1338         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1339                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1340                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1341                         rc = signal_completed_replay(imp);
1342                         if (rc)
1343                                 GOTO(out, rc);
1344                 }
1345
1346         }
1347
1348         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1349                 if (cfs_atomic_read(&imp->imp_replay_inflight) == 0) {
1350                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1351                 }
1352         }
1353
1354         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1355                 CDEBUG(D_HA, "reconnected to %s@%s\n",
1356                        obd2cli_tgt(imp->imp_obd),
1357                        imp->imp_connection->c_remote_uuid.uuid);
1358
1359                 rc = ptlrpc_resend(imp);
1360                 if (rc)
1361                         GOTO(out, rc);
1362                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1363                 ptlrpc_activate_import(imp);
1364
1365                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1366                           &target_start, &target_len);
1367                 LCONSOLE_INFO("%s: Connection restored to service %.*s "
1368                               "using nid %s.\n", imp->imp_obd->obd_name,
1369                               target_len, target_start,
1370                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1371         }
1372
1373         if (imp->imp_state == LUSTRE_IMP_FULL) {
1374                 cfs_waitq_broadcast(&imp->imp_recovery_waitq);
1375                 ptlrpc_wake_delayed(imp);
1376         }
1377
1378 out:
1379         RETURN(rc);
1380 }
1381
1382 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1383 {
1384         struct ptlrpc_request *req;
1385         int rq_opc, rc = 0;
1386         int nowait = imp->imp_obd->obd_force;
1387         ENTRY;
1388
1389         if (nowait)
1390                 GOTO(set_state, rc);
1391
1392         switch (imp->imp_connect_op) {
1393         case OST_CONNECT: rq_opc = OST_DISCONNECT; break;
1394         case MDS_CONNECT: rq_opc = MDS_DISCONNECT; break;
1395         case MGS_CONNECT: rq_opc = MGS_DISCONNECT; break;
1396         default:
1397                 CERROR("don't know how to disconnect from %s (connect_op %d)\n",
1398                        obd2cli_tgt(imp->imp_obd), imp->imp_connect_op);
1399                 RETURN(-EINVAL);
1400         }
1401
1402         if (ptlrpc_import_in_recovery(imp)) {
1403                 struct l_wait_info lwi;
1404                 cfs_duration_t timeout;
1405
1406
1407                 if (AT_OFF) {
1408                         if (imp->imp_server_timeout)
1409                                 timeout = cfs_time_seconds(obd_timeout / 2);
1410                         else
1411                                 timeout = cfs_time_seconds(obd_timeout);
1412                 } else {
1413                         int idx = import_at_get_index(imp,
1414                                 imp->imp_client->cli_request_portal);
1415                         timeout = cfs_time_seconds(
1416                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1417                 }
1418
1419                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1420                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1421                 rc = l_wait_event(imp->imp_recovery_waitq,
1422                                   !ptlrpc_import_in_recovery(imp), &lwi);
1423
1424         }
1425
1426         cfs_spin_lock(&imp->imp_lock);
1427         if (imp->imp_state != LUSTRE_IMP_FULL)
1428                 GOTO(out, 0);
1429
1430         cfs_spin_unlock(&imp->imp_lock);
1431
1432         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1433                                         LUSTRE_OBD_VERSION, rq_opc);
1434         if (req) {
1435                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1436                  * it fails.  We can get through the above with a down server
1437                  * if the client doesn't know the server is gone yet. */
1438                 req->rq_no_resend = 1;
1439
1440 #ifndef CRAY_XT3
1441                 /* We want client umounts to happen quickly, no matter the
1442                    server state... */
1443                 req->rq_timeout = min_t(int, req->rq_timeout,
1444                                         INITIAL_CONNECT_TIMEOUT);
1445 #else
1446                 /* ... but we always want liblustre clients to nicely
1447                    disconnect, so only use the adaptive value. */
1448                 if (AT_OFF)
1449                         req->rq_timeout = obd_timeout / 3;
1450 #endif
1451
1452                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1453                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1454                 ptlrpc_request_set_replen(req);
1455                 rc = ptlrpc_queue_wait(req);
1456                 ptlrpc_req_finished(req);
1457         }
1458
1459 set_state:
1460         cfs_spin_lock(&imp->imp_lock);
1461 out:
1462         if (noclose)
1463                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1464         else
1465                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1466         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1467         /* Try all connections in the future - bz 12758 */
1468         imp->imp_last_recon = 0;
1469         cfs_spin_unlock(&imp->imp_lock);
1470
1471         RETURN(rc);
1472 }
1473
1474 void ptlrpc_cleanup_imp(struct obd_import *imp)
1475 {
1476         ENTRY;
1477
1478         cfs_spin_lock(&imp->imp_lock);
1479         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1480         imp->imp_generation++;
1481         cfs_spin_unlock(&imp->imp_lock);
1482         ptlrpc_abort_inflight(imp);
1483
1484         EXIT;
1485 }
1486
1487 /* Adaptive Timeout utils */
1488 extern unsigned int at_min, at_max, at_history;
1489
1490 /* Bin into timeslices using AT_BINS bins.
1491    This gives us a max of the last binlimit*AT_BINS secs without the storage,
1492    but still smoothing out a return to normalcy from a slow response.
1493    (E.g. remember the maximum latency in each minute of the last 4 minutes.) */
1494 int at_measured(struct adaptive_timeout *at, unsigned int val)
1495 {
1496         unsigned int old = at->at_current;
1497         time_t now = cfs_time_current_sec();
1498         time_t binlimit = max_t(time_t, at_history / AT_BINS, 1);
1499
1500         LASSERT(at);
1501         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1502                val, at, now - at->at_binstart, at->at_current,
1503                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1504
1505         if (val == 0)
1506                 /* 0's don't count, because we never want our timeout to
1507                    drop to 0, and because 0 could mean an error */
1508                 return 0;
1509
1510         cfs_spin_lock(&at->at_lock);
1511
1512         if (unlikely(at->at_binstart == 0)) {
1513                 /* Special case to remove default from history */
1514                 at->at_current = val;
1515                 at->at_worst_ever = val;
1516                 at->at_worst_time = now;
1517                 at->at_hist[0] = val;
1518                 at->at_binstart = now;
1519         } else if (now - at->at_binstart < binlimit ) {
1520                 /* in bin 0 */
1521                 at->at_hist[0] = max(val, at->at_hist[0]);
1522                 at->at_current = max(val, at->at_current);
1523         } else {
1524                 int i, shift;
1525                 unsigned int maxv = val;
1526                 /* move bins over */
1527                 shift = (now - at->at_binstart) / binlimit;
1528                 LASSERT(shift > 0);
1529                 for(i = AT_BINS - 1; i >= 0; i--) {
1530                         if (i >= shift) {
1531                                 at->at_hist[i] = at->at_hist[i - shift];
1532                                 maxv = max(maxv, at->at_hist[i]);
1533                         } else {
1534                                 at->at_hist[i] = 0;
1535                         }
1536                 }
1537                 at->at_hist[0] = val;
1538                 at->at_current = maxv;
1539                 at->at_binstart += shift * binlimit;
1540         }
1541
1542         if (at->at_current > at->at_worst_ever) {
1543                 at->at_worst_ever = at->at_current;
1544                 at->at_worst_time = now;
1545         }
1546
1547         if (at->at_flags & AT_FLG_NOHIST)
1548                 /* Only keep last reported val; keeping the rest of the history
1549                    for proc only */
1550                 at->at_current = val;
1551
1552         if (at_max > 0)
1553                 at->at_current =  min(at->at_current, at_max);
1554         at->at_current =  max(at->at_current, at_min);
1555
1556         if (at->at_current != old)
1557                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1558                        "(val=%u) hist %u %u %u %u\n", at,
1559                        old, at->at_current, at->at_current - old, val,
1560                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1561                        at->at_hist[3]);
1562
1563         /* if we changed, report the old value */
1564         old = (at->at_current != old) ? old : 0;
1565
1566         cfs_spin_unlock(&at->at_lock);
1567         return old;
1568 }
1569
1570 /* Find the imp_at index for a given portal; assign if space available */
1571 int import_at_get_index(struct obd_import *imp, int portal)
1572 {
1573         struct imp_at *at = &imp->imp_at;
1574         int i;
1575
1576         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1577                 if (at->iat_portal[i] == portal)
1578                         return i;
1579                 if (at->iat_portal[i] == 0)
1580                         /* unused */
1581                         break;
1582         }
1583
1584         /* Not found in list, add it under a lock */
1585         cfs_spin_lock(&imp->imp_lock);
1586
1587         /* Check unused under lock */
1588         for (; i < IMP_AT_MAX_PORTALS; i++) {
1589                 if (at->iat_portal[i] == portal)
1590                         goto out;
1591                 if (at->iat_portal[i] == 0)
1592                         /* unused */
1593                         break;
1594         }
1595
1596         /* Not enough portals? */
1597         LASSERT(i < IMP_AT_MAX_PORTALS);
1598
1599         at->iat_portal[i] = portal;
1600 out:
1601         cfs_spin_unlock(&imp->imp_lock);
1602         return i;
1603 }