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