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