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