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