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