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