Whamcloud - gitweb
8338095a43bb1a4cf08ed07441f71958ef87eac8
[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, time64_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         time64_t now = ktime_get_real_seconds();
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 = NULL;
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         exp = NULL;
1114
1115         if (rc != 0)
1116                 GOTO(out, rc);
1117
1118         obd_import_event(imp->imp_obd, imp, IMP_EVENT_OCD);
1119
1120         if (aa->pcaa_initial_connect) {
1121                 spin_lock(&imp->imp_lock);
1122                 if (msg_flags & MSG_CONNECT_REPLAYABLE) {
1123                         imp->imp_replayable = 1;
1124                         spin_unlock(&imp->imp_lock);
1125                         CDEBUG(D_HA, "connected to replayable target: %s\n",
1126                                obd2cli_tgt(imp->imp_obd));
1127                 } else {
1128                         imp->imp_replayable = 0;
1129                         spin_unlock(&imp->imp_lock);
1130                 }
1131
1132                 /* if applies, adjust the imp->imp_msg_magic here
1133                  * according to reply flags */
1134
1135                 imp->imp_remote_handle =
1136                                 *lustre_msg_get_handle(request->rq_repmsg);
1137
1138                 /* Initial connects are allowed for clients with non-random
1139                  * uuids when servers are in recovery.  Simply signal the
1140                  * servers replay is complete and wait in REPLAY_WAIT. */
1141                 if (msg_flags & MSG_CONNECT_RECOVERING) {
1142                         CDEBUG(D_HA, "connect to %s during recovery\n",
1143                                obd2cli_tgt(imp->imp_obd));
1144                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1145                 } else {
1146                         IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1147                         ptlrpc_activate_import(imp);
1148                 }
1149
1150                 GOTO(finish, rc = 0);
1151         }
1152
1153         /* Determine what recovery state to move the import to. */
1154         if (MSG_CONNECT_RECONNECT & msg_flags) {
1155                 memset(&old_hdl, 0, sizeof(old_hdl));
1156                 if (!memcmp(&old_hdl, lustre_msg_get_handle(request->rq_repmsg),
1157                             sizeof (old_hdl))) {
1158                         LCONSOLE_WARN("Reconnect to %s (at @%s) failed due "
1159                                       "bad handle %#llx\n",
1160                                       obd2cli_tgt(imp->imp_obd),
1161                                       imp->imp_connection->c_remote_uuid.uuid,
1162                                       imp->imp_dlm_handle.cookie);
1163                         GOTO(out, rc = -ENOTCONN);
1164                 }
1165
1166                 if (memcmp(&imp->imp_remote_handle,
1167                            lustre_msg_get_handle(request->rq_repmsg),
1168                            sizeof(imp->imp_remote_handle))) {
1169                         int level = msg_flags & MSG_CONNECT_RECOVERING ?
1170                                 D_HA : D_WARNING;
1171
1172                         /* Bug 16611/14775: if server handle have changed,
1173                          * that means some sort of disconnection happened.
1174                          * If the server is not in recovery, that also means it
1175                          * already erased all of our state because of previous
1176                          * eviction. If it is in recovery - we are safe to
1177                          * participate since we can reestablish all of our state
1178                          * with server again */
1179                         if ((MSG_CONNECT_RECOVERING & msg_flags)) {
1180                                 CDEBUG(level,"%s@%s changed server handle from "
1181                                        "%#llx to %#llx"
1182                                        " but is still in recovery\n",
1183                                        obd2cli_tgt(imp->imp_obd),
1184                                        imp->imp_connection->c_remote_uuid.uuid,
1185                                        imp->imp_remote_handle.cookie,
1186                                        lustre_msg_get_handle(
1187                                        request->rq_repmsg)->cookie);
1188                         } else {
1189                                 LCONSOLE_WARN("Evicted from %s (at %s) "
1190                                               "after server handle changed from "
1191                                               "%#llx to %#llx\n",
1192                                               obd2cli_tgt(imp->imp_obd),
1193                                               imp->imp_connection-> \
1194                                               c_remote_uuid.uuid,
1195                                               imp->imp_remote_handle.cookie,
1196                                               lustre_msg_get_handle(
1197                                               request->rq_repmsg)->cookie);
1198                         }
1199
1200
1201                         imp->imp_remote_handle =
1202                                      *lustre_msg_get_handle(request->rq_repmsg);
1203
1204                         if (!(MSG_CONNECT_RECOVERING & msg_flags)) {
1205                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1206                                 GOTO(finish, rc = 0);
1207                         }
1208
1209                 } else {
1210                         CDEBUG(D_HA, "reconnected to %s@%s after partition\n",
1211                                obd2cli_tgt(imp->imp_obd),
1212                                imp->imp_connection->c_remote_uuid.uuid);
1213                 }
1214
1215                 if (imp->imp_invalid) {
1216                         CDEBUG(D_HA, "%s: reconnected but import is invalid; "
1217                                "marking evicted\n", imp->imp_obd->obd_name);
1218                         IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1219                 } else if (MSG_CONNECT_RECOVERING & msg_flags) {
1220                         CDEBUG(D_HA, "%s: reconnected to %s during replay\n",
1221                                imp->imp_obd->obd_name,
1222                                obd2cli_tgt(imp->imp_obd));
1223
1224                         spin_lock(&imp->imp_lock);
1225                         imp->imp_resend_replay = 1;
1226                         spin_unlock(&imp->imp_lock);
1227
1228                         IMPORT_SET_STATE(imp, imp->imp_replay_state);
1229                 } else {
1230                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1231                 }
1232         } else if ((MSG_CONNECT_RECOVERING & msg_flags) && !imp->imp_invalid) {
1233                 LASSERT(imp->imp_replayable);
1234                 imp->imp_remote_handle =
1235                                 *lustre_msg_get_handle(request->rq_repmsg);
1236                 imp->imp_last_replay_transno = 0;
1237                 imp->imp_replay_cursor = &imp->imp_committed_list;
1238                 IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY);
1239         } else {
1240                 DEBUG_REQ(D_HA, request, "%s: evicting (reconnect/recover flags"
1241                           " not set: %x)", imp->imp_obd->obd_name, msg_flags);
1242                 imp->imp_remote_handle =
1243                                 *lustre_msg_get_handle(request->rq_repmsg);
1244                 IMPORT_SET_STATE(imp, LUSTRE_IMP_EVICTED);
1245         }
1246
1247         /* Sanity checks for a reconnected import. */
1248         if (!(imp->imp_replayable) != !(msg_flags & MSG_CONNECT_REPLAYABLE)) {
1249                 CERROR("imp_replayable flag does not match server "
1250                        "after reconnect. We should LBUG right here.\n");
1251         }
1252
1253         if (lustre_msg_get_last_committed(request->rq_repmsg) > 0 &&
1254             lustre_msg_get_last_committed(request->rq_repmsg) <
1255             aa->pcaa_peer_committed) {
1256                 CERROR("%s went back in time (transno %lld"
1257                        " was previously committed, server now claims %lld"
1258                        ")!  See https://bugzilla.lustre.org/show_bug.cgi?"
1259                        "id=9646\n",
1260                        obd2cli_tgt(imp->imp_obd), aa->pcaa_peer_committed,
1261                        lustre_msg_get_last_committed(request->rq_repmsg));
1262         }
1263
1264 finish:
1265         ptlrpc_prepare_replay(imp);
1266         rc = ptlrpc_import_recovery_state_machine(imp);
1267         if (rc == -ENOTCONN) {
1268                 CDEBUG(D_HA, "evicted/aborted by %s@%s during recovery;"
1269                        "invalidating and reconnecting\n",
1270                        obd2cli_tgt(imp->imp_obd),
1271                        imp->imp_connection->c_remote_uuid.uuid);
1272                 ptlrpc_connect_import(imp);
1273                 spin_lock(&imp->imp_lock);
1274                 imp->imp_connected = 0;
1275                 imp->imp_connect_tried = 1;
1276                 spin_unlock(&imp->imp_lock);
1277                 RETURN(0);
1278         }
1279
1280 out:
1281         spin_lock(&imp->imp_lock);
1282         imp->imp_connected = 0;
1283         imp->imp_connect_tried = 1;
1284         spin_unlock(&imp->imp_lock);
1285
1286         if (exp != NULL)
1287                 class_export_put(exp);
1288
1289         if (rc != 0) {
1290                 IMPORT_SET_STATE(imp, LUSTRE_IMP_DISCON);
1291                 if (rc == -EACCES) {
1292                         /*
1293                          * Give up trying to reconnect
1294                          * EACCES means client has no permission for connection
1295                          */
1296                         imp->imp_obd->obd_no_recov = 1;
1297                         ptlrpc_deactivate_import(imp);
1298                 }
1299
1300                 if (rc == -EPROTO) {
1301                         struct obd_connect_data *ocd;
1302
1303                         /* reply message might not be ready */
1304                         if (request->rq_repmsg == NULL)
1305                                 RETURN(-EPROTO);
1306
1307                         ocd = req_capsule_server_get(&request->rq_pill,
1308                                                      &RMF_CONNECT_DATA);
1309                         if (ocd &&
1310                             (ocd->ocd_connect_flags & OBD_CONNECT_VERSION) &&
1311                             (ocd->ocd_version != LUSTRE_VERSION_CODE)) {
1312                            /* Actually servers are only supposed to refuse
1313                               connection from liblustre clients, so we should
1314                               never see this from VFS context */
1315                                 LCONSOLE_ERROR_MSG(0x16a, "Server %s version "
1316                                         "(%d.%d.%d.%d)"
1317                                         " refused connection from this client "
1318                                         "with an incompatible version (%s).  "
1319                                         "Client must be recompiled\n",
1320                                         obd2cli_tgt(imp->imp_obd),
1321                                         OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
1322                                         OBD_OCD_VERSION_MINOR(ocd->ocd_version),
1323                                         OBD_OCD_VERSION_PATCH(ocd->ocd_version),
1324                                         OBD_OCD_VERSION_FIX(ocd->ocd_version),
1325                                         LUSTRE_VERSION_STRING);
1326                                 ptlrpc_deactivate_import(imp);
1327                                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CLOSED);
1328                         }
1329                         RETURN(-EPROTO);
1330                 }
1331
1332                 ptlrpc_maybe_ping_import_soon(imp);
1333
1334                 CDEBUG(D_HA, "recovery of %s on %s failed (%d)\n",
1335                        obd2cli_tgt(imp->imp_obd),
1336                        (char *)imp->imp_connection->c_remote_uuid.uuid, rc);
1337         }
1338
1339         wake_up_all(&imp->imp_recovery_waitq);
1340         RETURN(rc);
1341 }
1342
1343 /**
1344  * interpret callback for "completed replay" RPCs.
1345  * \see signal_completed_replay
1346  */
1347 static int completed_replay_interpret(const struct lu_env *env,
1348                                       struct ptlrpc_request *req,
1349                                       void * data, int rc)
1350 {
1351         ENTRY;
1352         atomic_dec(&req->rq_import->imp_replay_inflight);
1353         if (req->rq_status == 0 &&
1354             !req->rq_import->imp_vbr_failed) {
1355                 ptlrpc_import_recovery_state_machine(req->rq_import);
1356         } else {
1357                 if (req->rq_import->imp_vbr_failed) {
1358                         CDEBUG(D_WARNING,
1359                                "%s: version recovery fails, reconnecting\n",
1360                                req->rq_import->imp_obd->obd_name);
1361                 } else {
1362                         CDEBUG(D_HA, "%s: LAST_REPLAY message error: %d, "
1363                                      "reconnecting\n",
1364                                req->rq_import->imp_obd->obd_name,
1365                                req->rq_status);
1366                 }
1367                 ptlrpc_connect_import(req->rq_import);
1368         }
1369
1370         RETURN(0);
1371 }
1372
1373 /**
1374  * Let server know that we have no requests to replay anymore.
1375  * Achieved by just sending a PING request
1376  */
1377 static int signal_completed_replay(struct obd_import *imp)
1378 {
1379         struct ptlrpc_request *req;
1380         ENTRY;
1381
1382         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_FINISH_REPLAY)))
1383                 RETURN(0);
1384
1385         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1386         atomic_inc(&imp->imp_replay_inflight);
1387
1388         req = ptlrpc_request_alloc_pack(imp, &RQF_OBD_PING, LUSTRE_OBD_VERSION,
1389                                         OBD_PING);
1390         if (req == NULL) {
1391                 atomic_dec(&imp->imp_replay_inflight);
1392                 RETURN(-ENOMEM);
1393         }
1394
1395         ptlrpc_request_set_replen(req);
1396         req->rq_send_state = LUSTRE_IMP_REPLAY_WAIT;
1397         lustre_msg_add_flags(req->rq_reqmsg,
1398                              MSG_LOCK_REPLAY_DONE | MSG_REQ_REPLAY_DONE);
1399         if (AT_OFF)
1400                 req->rq_timeout *= 3;
1401         req->rq_interpret_reply = completed_replay_interpret;
1402
1403         ptlrpcd_add_req(req);
1404         RETURN(0);
1405 }
1406
1407 /**
1408  * In kernel code all import invalidation happens in its own
1409  * separate thread, so that whatever application happened to encounter
1410  * a problem could still be killed or otherwise continue
1411  */
1412 static int ptlrpc_invalidate_import_thread(void *data)
1413 {
1414         struct obd_import *imp = data;
1415
1416         ENTRY;
1417
1418         unshare_fs_struct();
1419
1420         CDEBUG(D_HA, "thread invalidate import %s to %s@%s\n",
1421                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1422                imp->imp_connection->c_remote_uuid.uuid);
1423
1424         ptlrpc_invalidate_import(imp);
1425
1426         if (obd_dump_on_eviction) {
1427                 CERROR("dump the log upon eviction\n");
1428                 libcfs_debug_dumplog();
1429         }
1430
1431         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1432         ptlrpc_import_recovery_state_machine(imp);
1433
1434         class_import_put(imp);
1435         RETURN(0);
1436 }
1437
1438 /**
1439  * This is the state machine for client-side recovery on import.
1440  *
1441  * Typicaly we have two possibly paths. If we came to server and it is not
1442  * in recovery, we just enter IMP_EVICTED state, invalidate our import
1443  * state and reconnect from scratch.
1444  * If we came to server that is in recovery, we enter IMP_REPLAY import state.
1445  * We go through our list of requests to replay and send them to server one by
1446  * one.
1447  * After sending all request from the list we change import state to
1448  * IMP_REPLAY_LOCKS and re-request all the locks we believe we have from server
1449  * and also all the locks we don't yet have and wait for server to grant us.
1450  * After that we send a special "replay completed" request and change import
1451  * state to IMP_REPLAY_WAIT.
1452  * Upon receiving reply to that "replay completed" RPC we enter IMP_RECOVER
1453  * state and resend all requests from sending list.
1454  * After that we promote import to FULL state and send all delayed requests
1455  * and import is fully operational after that.
1456  *
1457  */
1458 int ptlrpc_import_recovery_state_machine(struct obd_import *imp)
1459 {
1460         int rc = 0;
1461         int inflight;
1462         char *target_start;
1463         int target_len;
1464
1465         ENTRY;
1466         if (imp->imp_state == LUSTRE_IMP_EVICTED) {
1467                 deuuidify(obd2cli_tgt(imp->imp_obd), NULL,
1468                           &target_start, &target_len);
1469                 /* Don't care about MGC eviction */
1470                 if (strcmp(imp->imp_obd->obd_type->typ_name,
1471                            LUSTRE_MGC_NAME) != 0) {
1472                         LCONSOLE_ERROR_MSG(0x167, "%s: This client was evicted "
1473                                            "by %.*s; in progress operations "
1474                                            "using this service will fail.\n",
1475                                            imp->imp_obd->obd_name, target_len,
1476                                            target_start);
1477                 }
1478                 CDEBUG(D_HA, "evicted from %s@%s; invalidating\n",
1479                        obd2cli_tgt(imp->imp_obd),
1480                        imp->imp_connection->c_remote_uuid.uuid);
1481                 /* reset vbr_failed flag upon eviction */
1482                 spin_lock(&imp->imp_lock);
1483                 imp->imp_vbr_failed = 0;
1484                 spin_unlock(&imp->imp_lock);
1485
1486                 {
1487                 struct task_struct *task;
1488                 /* bug 17802:  XXX client_disconnect_export vs connect request
1489                  * race. if client is evicted at this time then we start
1490                  * invalidate thread without reference to import and import can
1491                  * be freed at same time. */
1492                 class_import_get(imp);
1493                 task = kthread_run(ptlrpc_invalidate_import_thread, imp,
1494                                      "ll_imp_inval");
1495                 if (IS_ERR(task)) {
1496                         class_import_put(imp);
1497                         CERROR("error starting invalidate thread: %d\n", rc);
1498                         rc = PTR_ERR(task);
1499                 } else {
1500                         rc = 0;
1501                 }
1502                 RETURN(rc);
1503                 }
1504         }
1505
1506         if (imp->imp_state == LUSTRE_IMP_REPLAY) {
1507                 CDEBUG(D_HA, "replay requested by %s\n",
1508                        obd2cli_tgt(imp->imp_obd));
1509                 rc = ptlrpc_replay_next(imp, &inflight);
1510                 if (inflight == 0 &&
1511                     atomic_read(&imp->imp_replay_inflight) == 0) {
1512                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_LOCKS);
1513                         rc = ldlm_replay_locks(imp);
1514                         if (rc)
1515                                 GOTO(out, rc);
1516                 }
1517                 rc = 0;
1518         }
1519
1520         if (imp->imp_state == LUSTRE_IMP_REPLAY_LOCKS) {
1521                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1522                         IMPORT_SET_STATE(imp, LUSTRE_IMP_REPLAY_WAIT);
1523                         rc = signal_completed_replay(imp);
1524                         if (rc)
1525                                 GOTO(out, rc);
1526                 }
1527         }
1528
1529         if (imp->imp_state == LUSTRE_IMP_REPLAY_WAIT) {
1530                 if (atomic_read(&imp->imp_replay_inflight) == 0) {
1531                         IMPORT_SET_STATE(imp, LUSTRE_IMP_RECOVER);
1532                 }
1533         }
1534
1535         if (imp->imp_state == LUSTRE_IMP_RECOVER) {
1536                 struct ptlrpc_connection *conn = imp->imp_connection;
1537
1538                 rc = ptlrpc_resend(imp);
1539                 if (rc)
1540                         GOTO(out, rc);
1541                 IMPORT_SET_STATE(imp, LUSTRE_IMP_FULL);
1542                 ptlrpc_activate_import(imp);
1543
1544                 LCONSOLE_INFO("%s: Connection restored to %s (at %s)\n",
1545                               imp->imp_obd->obd_name,
1546                               obd_uuid2str(&conn->c_remote_uuid),
1547                               libcfs_nid2str(imp->imp_connection->c_peer.nid));
1548         }
1549
1550         if (imp->imp_state == LUSTRE_IMP_FULL) {
1551                 wake_up_all(&imp->imp_recovery_waitq);
1552                 ptlrpc_wake_delayed(imp);
1553         }
1554
1555 out:
1556         RETURN(rc);
1557 }
1558
1559 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose)
1560 {
1561         struct ptlrpc_request *req;
1562         int rq_opc, rc = 0;
1563         ENTRY;
1564
1565         if (imp->imp_obd->obd_force)
1566                 GOTO(set_state, rc);
1567
1568         switch (imp->imp_connect_op) {
1569         case OST_CONNECT:
1570                 rq_opc = OST_DISCONNECT;
1571                 break;
1572         case MDS_CONNECT:
1573                 rq_opc = MDS_DISCONNECT;
1574                 break;
1575         case MGS_CONNECT:
1576                 rq_opc = MGS_DISCONNECT;
1577                 break;
1578         default:
1579                 rc = -EINVAL;
1580                 CERROR("%s: don't know how to disconnect from %s "
1581                        "(connect_op %d): rc = %d\n",
1582                        imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
1583                        imp->imp_connect_op, rc);
1584                 RETURN(rc);
1585         }
1586
1587         if (ptlrpc_import_in_recovery(imp)) {
1588                 struct l_wait_info lwi;
1589                 cfs_duration_t timeout;
1590
1591                 if (AT_OFF) {
1592                         if (imp->imp_server_timeout)
1593                                 timeout = cfs_time_seconds(obd_timeout / 2);
1594                         else
1595                                 timeout = cfs_time_seconds(obd_timeout);
1596                 } else {
1597                         int idx = import_at_get_index(imp,
1598                                 imp->imp_client->cli_request_portal);
1599                         timeout = cfs_time_seconds(
1600                                 at_get(&imp->imp_at.iat_service_estimate[idx]));
1601                 }
1602
1603                 lwi = LWI_TIMEOUT_INTR(cfs_timeout_cap(timeout),
1604                                        back_to_sleep, LWI_ON_SIGNAL_NOOP, NULL);
1605                 rc = l_wait_event(imp->imp_recovery_waitq,
1606                                   !ptlrpc_import_in_recovery(imp), &lwi);
1607
1608         }
1609
1610         spin_lock(&imp->imp_lock);
1611         if (imp->imp_state != LUSTRE_IMP_FULL)
1612                 GOTO(out, rc);
1613         spin_unlock(&imp->imp_lock);
1614
1615         req = ptlrpc_request_alloc_pack(imp, &RQF_MDS_DISCONNECT,
1616                                         LUSTRE_OBD_VERSION, rq_opc);
1617         if (req) {
1618                 /* We are disconnecting, do not retry a failed DISCONNECT rpc if
1619                  * it fails.  We can get through the above with a down server
1620                  * if the client doesn't know the server is gone yet. */
1621                 req->rq_no_resend = 1;
1622
1623                 /* We want client umounts to happen quickly, no matter the
1624                    server state... */
1625                 req->rq_timeout = min_t(int, req->rq_timeout,
1626                                         INITIAL_CONNECT_TIMEOUT);
1627
1628                 IMPORT_SET_STATE(imp, LUSTRE_IMP_CONNECTING);
1629                 req->rq_send_state =  LUSTRE_IMP_CONNECTING;
1630                 ptlrpc_request_set_replen(req);
1631                 rc = ptlrpc_queue_wait(req);
1632                 ptlrpc_req_finished(req);
1633         }
1634
1635 set_state:
1636         spin_lock(&imp->imp_lock);
1637 out:
1638         if (noclose)
1639                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_DISCON);
1640         else
1641                 IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1642         memset(&imp->imp_remote_handle, 0, sizeof(imp->imp_remote_handle));
1643         spin_unlock(&imp->imp_lock);
1644
1645         if (rc == -ETIMEDOUT || rc == -ENOTCONN || rc == -ESHUTDOWN)
1646                 rc = 0;
1647         RETURN(rc);
1648 }
1649 EXPORT_SYMBOL(ptlrpc_disconnect_import);
1650
1651 void ptlrpc_cleanup_imp(struct obd_import *imp)
1652 {
1653         ENTRY;
1654
1655         spin_lock(&imp->imp_lock);
1656         IMPORT_SET_STATE_NOLOCK(imp, LUSTRE_IMP_CLOSED);
1657         imp->imp_generation++;
1658         spin_unlock(&imp->imp_lock);
1659         ptlrpc_abort_inflight(imp);
1660
1661         EXIT;
1662 }
1663
1664 /* Adaptive Timeout utils */
1665 extern unsigned int at_min, at_max, at_history;
1666
1667 /* Update at_current with the specified value (bounded by at_min and at_max),
1668  * as well as the AT history "bins".
1669  *  - Bin into timeslices using AT_BINS bins.
1670  *  - This gives us a max of the last at_history seconds without the storage,
1671  *    but still smoothing out a return to normalcy from a slow response.
1672  *  - (E.g. remember the maximum latency in each minute of the last 4 minutes.)
1673  */
1674 int at_measured(struct adaptive_timeout *at, unsigned int val)
1675 {
1676         unsigned int old = at->at_current;
1677         time64_t now = ktime_get_real_seconds();
1678         long binlimit = max_t(long, at_history / AT_BINS, 1);
1679
1680         LASSERT(at);
1681         CDEBUG(D_OTHER, "add %u to %p time=%lu v=%u (%u %u %u %u)\n",
1682                val, at, (long)(now - at->at_binstart), at->at_current,
1683                at->at_hist[0], at->at_hist[1], at->at_hist[2], at->at_hist[3]);
1684
1685         if (val == 0)
1686                 /* 0's don't count, because we never want our timeout to
1687                    drop to 0, and because 0 could mean an error */
1688                 return 0;
1689
1690         spin_lock(&at->at_lock);
1691
1692         if (unlikely(at->at_binstart == 0)) {
1693                 /* Special case to remove default from history */
1694                 at->at_current = val;
1695                 at->at_worst_ever = val;
1696                 at->at_worst_time = now;
1697                 at->at_hist[0] = val;
1698                 at->at_binstart = now;
1699         } else if (now - at->at_binstart < binlimit ) {
1700                 /* in bin 0 */
1701                 at->at_hist[0] = max(val, at->at_hist[0]);
1702                 at->at_current = max(val, at->at_current);
1703         } else {
1704                 int i, shift;
1705                 unsigned int maxv = val;
1706
1707                 /* move bins over */
1708                 shift = (u32)(now - at->at_binstart) / binlimit;
1709                 LASSERT(shift > 0);
1710                 for(i = AT_BINS - 1; i >= 0; i--) {
1711                         if (i >= shift) {
1712                                 at->at_hist[i] = at->at_hist[i - shift];
1713                                 maxv = max(maxv, at->at_hist[i]);
1714                         } else {
1715                                 at->at_hist[i] = 0;
1716                         }
1717                 }
1718                 at->at_hist[0] = val;
1719                 at->at_current = maxv;
1720                 at->at_binstart += shift * binlimit;
1721         }
1722
1723         if (at->at_current > at->at_worst_ever) {
1724                 at->at_worst_ever = at->at_current;
1725                 at->at_worst_time = now;
1726         }
1727
1728         if (at->at_flags & AT_FLG_NOHIST)
1729                 /* Only keep last reported val; keeping the rest of the history
1730                    for proc only */
1731                 at->at_current = val;
1732
1733         if (at_max > 0)
1734                 at->at_current =  min(at->at_current, at_max);
1735         at->at_current =  max(at->at_current, at_min);
1736
1737         if (at->at_current != old)
1738                 CDEBUG(D_OTHER, "AT %p change: old=%u new=%u delta=%d "
1739                        "(val=%u) hist %u %u %u %u\n", at,
1740                        old, at->at_current, at->at_current - old, val,
1741                        at->at_hist[0], at->at_hist[1], at->at_hist[2],
1742                        at->at_hist[3]);
1743
1744         /* if we changed, report the old value */
1745         old = (at->at_current != old) ? old : 0;
1746
1747         spin_unlock(&at->at_lock);
1748         return old;
1749 }
1750
1751 /* Find the imp_at index for a given portal; assign if space available */
1752 int import_at_get_index(struct obd_import *imp, int portal)
1753 {
1754         struct imp_at *at = &imp->imp_at;
1755         int i;
1756
1757         for (i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1758                 if (at->iat_portal[i] == portal)
1759                         return i;
1760                 if (at->iat_portal[i] == 0)
1761                         /* unused */
1762                         break;
1763         }
1764
1765         /* Not found in list, add it under a lock */
1766         spin_lock(&imp->imp_lock);
1767
1768         /* Check unused under lock */
1769         for (; i < IMP_AT_MAX_PORTALS; i++) {
1770                 if (at->iat_portal[i] == portal)
1771                         goto out;
1772                 if (at->iat_portal[i] == 0)
1773                         /* unused */
1774                         break;
1775         }
1776
1777         /* Not enough portals? */
1778         LASSERT(i < IMP_AT_MAX_PORTALS);
1779
1780         at->iat_portal[i] = portal;
1781 out:
1782         spin_unlock(&imp->imp_lock);
1783         return i;
1784 }