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