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