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