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