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