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