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