Whamcloud - gitweb
4d37048fe07a14e7d634772cdb2f091a976c1151
[fs/lustre-release.git] / lustre / ldlm / ldlm_lib.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) 2010, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31
32 /**
33  * This file deals with various client/target related logic including recovery.
34  *
35  * TODO: This code more logically belongs in the ptlrpc module than in ldlm and
36  * should be moved.
37  */
38
39 #define DEBUG_SUBSYSTEM S_LDLM
40
41 #include <cl_object.h>
42 #include <linux/jiffies.h>
43 #include <linux/kernel.h>
44 #include <linux/kthread.h>
45 #include <libcfs/libcfs.h>
46 #include <obd.h>
47 #include <obd_class.h>
48 #include <lustre_dlm.h>
49 #include <lustre_net.h>
50 #include <lustre_sec.h>
51 #include "ldlm_internal.h"
52
53 /*
54  * @priority: If non-zero, move the selected connection to the list head.
55  * @create: If zero, only search in existing connections.
56  */
57 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
58                            int priority, int create)
59 {
60         struct ptlrpc_connection *ptlrpc_conn;
61         struct obd_import_conn *imp_conn = NULL, *item;
62         lnet_nid_t nid4refnet = LNET_NID_ANY;
63         int rc = 0;
64
65         ENTRY;
66
67         if (!create && !priority) {
68                 CDEBUG(D_HA, "Nothing to do\n");
69                 RETURN(-EINVAL);
70         }
71
72         if (imp->imp_connection &&
73             imp->imp_connection->c_remote_uuid.uuid[0] == 0)
74                 /* nid4refnet is used to restrict network connections */
75                 nid4refnet = imp->imp_connection->c_self;
76         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid, nid4refnet);
77         if (!ptlrpc_conn) {
78                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
79                 RETURN(-ENOENT);
80         }
81
82         if (create) {
83                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
84                 if (!imp_conn)
85                         GOTO(out_put, rc = -ENOMEM);
86         }
87
88         spin_lock(&imp->imp_lock);
89         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
90                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
91                         if (priority) {
92                                 list_move(&item->oic_item,
93                                           &imp->imp_conn_list);
94                                 item->oic_last_attempt = 0;
95                         }
96                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
97                                imp, imp->imp_obd->obd_name, uuid->uuid,
98                                (priority ? ", moved to head" : ""));
99                         spin_unlock(&imp->imp_lock);
100                         GOTO(out_free, rc = 0);
101                 }
102         }
103         /* No existing import connection found for \a uuid. */
104         if (create) {
105                 imp_conn->oic_conn = ptlrpc_conn;
106                 imp_conn->oic_uuid = *uuid;
107                 imp_conn->oic_last_attempt = 0;
108                 if (priority)
109                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
110                 else
111                         list_add_tail(&imp_conn->oic_item,
112                                       &imp->imp_conn_list);
113                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
114                        imp, imp->imp_obd->obd_name, uuid->uuid,
115                        (priority ? "head" : "tail"));
116         } else {
117                 spin_unlock(&imp->imp_lock);
118                 GOTO(out_free, rc = -ENOENT);
119         }
120
121         spin_unlock(&imp->imp_lock);
122         RETURN(0);
123 out_free:
124         if (imp_conn)
125                 OBD_FREE(imp_conn, sizeof(*imp_conn));
126 out_put:
127         ptlrpc_connection_put(ptlrpc_conn);
128         RETURN(rc);
129 }
130
131 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
132 {
133         return import_set_conn(imp, uuid, 1, 0);
134 }
135
136 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
137                            int priority)
138 {
139         return import_set_conn(imp, uuid, priority, 1);
140 }
141 EXPORT_SYMBOL(client_import_add_conn);
142
143 int client_import_dyn_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
144                                lnet_nid_t prim_nid, int priority)
145 {
146         struct ptlrpc_connection *ptlrpc_conn;
147         int rc;
148
149         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid, prim_nid);
150         if (!ptlrpc_conn) {
151                 const char *str_uuid = obd_uuid2str(uuid);
152
153                 rc = class_add_uuid(str_uuid, prim_nid);
154                 if (rc) {
155                         CERROR("%s: failed to add UUID '%s': rc = %d\n",
156                                imp->imp_obd->obd_name, str_uuid, rc);
157                         return rc;
158                 }
159         }
160         return import_set_conn(imp, uuid, priority, 1);
161 }
162 EXPORT_SYMBOL(client_import_dyn_add_conn);
163
164 int client_import_add_nids_to_conn(struct obd_import *imp, lnet_nid_t *nids,
165                                    int nid_count, struct obd_uuid *uuid)
166 {
167         struct obd_import_conn *conn;
168         int rc = -ENOENT;
169
170         ENTRY;
171         if (nid_count <= 0 || !nids)
172                 return rc;
173
174         spin_lock(&imp->imp_lock);
175         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
176                 if (class_check_uuid(&conn->oic_uuid, nids[0])) {
177                         *uuid = conn->oic_uuid;
178                         rc = class_add_nids_to_uuid(&conn->oic_uuid, nids,
179                                                     nid_count);
180                         break;
181                 }
182         }
183         spin_unlock(&imp->imp_lock);
184         RETURN(rc);
185 }
186 EXPORT_SYMBOL(client_import_add_nids_to_conn);
187
188 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
189 {
190         struct obd_import_conn *imp_conn;
191         struct obd_export *dlmexp;
192         int rc = -ENOENT;
193
194         ENTRY;
195
196         spin_lock(&imp->imp_lock);
197         if (list_empty(&imp->imp_conn_list)) {
198                 LASSERT(!imp->imp_connection);
199                 GOTO(out, rc);
200         }
201
202         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
203                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
204                         continue;
205                 LASSERT(imp_conn->oic_conn);
206
207                 if (imp_conn == imp->imp_conn_current) {
208                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
209
210                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
211                             imp->imp_state != LUSTRE_IMP_DISCON) {
212                                 CERROR("can't remove current connection\n");
213                                 GOTO(out, rc = -EBUSY);
214                         }
215
216                         ptlrpc_connection_put(imp->imp_connection);
217                         imp->imp_connection = NULL;
218
219                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
220                         if (dlmexp && dlmexp->exp_connection) {
221                                 LASSERT(dlmexp->exp_connection ==
222                                         imp_conn->oic_conn);
223                                 ptlrpc_connection_put(dlmexp->exp_connection);
224                                 dlmexp->exp_connection = NULL;
225                         }
226
227                         if (dlmexp != NULL)
228                                 class_export_put(dlmexp);
229                 }
230
231                 list_del(&imp_conn->oic_item);
232                 ptlrpc_connection_put(imp_conn->oic_conn);
233                 OBD_FREE(imp_conn, sizeof(*imp_conn));
234                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
235                        imp, imp->imp_obd->obd_name, uuid->uuid);
236                 rc = 0;
237                 break;
238         }
239 out:
240         spin_unlock(&imp->imp_lock);
241         if (rc == -ENOENT)
242                 CERROR("connection %s not found\n", uuid->uuid);
243         RETURN(rc);
244 }
245 EXPORT_SYMBOL(client_import_del_conn);
246
247 /**
248  * Find conn UUID by peer NID. \a peer is a server NID. This function is used
249  * to find a conn uuid of \a imp which can reach \a peer.
250  */
251 int client_import_find_conn(struct obd_import *imp, lnet_nid_t peer,
252                             struct obd_uuid *uuid)
253 {
254         struct obd_import_conn *conn;
255         int rc = -ENOENT;
256
257         ENTRY;
258
259         spin_lock(&imp->imp_lock);
260         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
261                 /* Check if conn UUID does have this peer NID. */
262                 if (class_check_uuid(&conn->oic_uuid, peer)) {
263                         *uuid = conn->oic_uuid;
264                         rc = 0;
265                         break;
266                 }
267         }
268         spin_unlock(&imp->imp_lock);
269         RETURN(rc);
270 }
271 EXPORT_SYMBOL(client_import_find_conn);
272
273 void client_destroy_import(struct obd_import *imp)
274 {
275         /*
276          * Drop security policy instance after all RPCs have finished/aborted
277          * to let all busy contexts be released.
278          */
279         class_import_get(imp);
280         class_destroy_import(imp);
281         sptlrpc_import_sec_put(imp);
282         class_import_put(imp);
283 }
284 EXPORT_SYMBOL(client_destroy_import);
285
286 /**
287  * Check whether or not the OSC is on MDT.
288  * In the config log,
289  * osc on MDT
290  *      setup 0:{fsname}-OSTxxxx-osc[-MDTxxxx] 1:lustre-OST0000_UUID 2:NID
291  * osc on client
292  *      setup 0:{fsname}-OSTxxxx-osc 1:lustre-OST0000_UUID 2:NID
293  *
294  **/
295 static int osc_on_mdt(char *obdname)
296 {
297         char *ptr;
298
299         ptr = strrchr(obdname, '-');
300         if (ptr == NULL)
301                 return 0;
302
303         if (strncmp(ptr + 1, "MDT", 3) == 0)
304                 return 1;
305
306         return 0;
307 }
308
309 /*
310  * Configure an RPC client OBD device.
311  *
312  * lcfg parameters:
313  * 1 - client UUID
314  * 2 - server UUID
315  * 3 - inactive-on-startup
316  * 4 - restrictive net
317  */
318 int client_obd_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
319 {
320         struct client_obd *cli = &obd->u.cli;
321         struct obd_import *imp;
322         struct obd_uuid server_uuid;
323         int rq_portal, rp_portal, connect_op;
324         const char *name = obd->obd_type->typ_name;
325         enum ldlm_ns_type ns_type = LDLM_NS_TYPE_UNKNOWN;
326         char *cli_name = lustre_cfg_buf(lcfg, 0);
327         struct ptlrpc_connection fake_conn = { .c_self = 0,
328                                                .c_remote_uuid.uuid[0] = 0 };
329         int rc;
330
331         ENTRY;
332
333         /*
334          * In a more perfect world, we would hang a ptlrpc_client off of
335          * obd_type and just use the values from there.
336          */
337         if (!strcmp(name, LUSTRE_OSC_NAME)) {
338                 rq_portal = OST_REQUEST_PORTAL;
339                 rp_portal = OSC_REPLY_PORTAL;
340                 connect_op = OST_CONNECT;
341                 cli->cl_sp_me = LUSTRE_SP_CLI;
342                 cli->cl_sp_to = LUSTRE_SP_OST;
343                 ns_type = LDLM_NS_TYPE_OSC;
344         } else if (!strcmp(name, LUSTRE_MDC_NAME) ||
345                    !strcmp(name, LUSTRE_LWP_NAME)) {
346                 rq_portal = MDS_REQUEST_PORTAL;
347                 rp_portal = MDC_REPLY_PORTAL;
348                 connect_op = MDS_CONNECT;
349                 if (is_lwp_on_ost(cli_name))
350                         cli->cl_sp_me = LUSTRE_SP_OST;
351                 else if (is_lwp_on_mdt(cli_name))
352                         cli->cl_sp_me = LUSTRE_SP_MDT;
353                 else
354                         cli->cl_sp_me = LUSTRE_SP_CLI;
355                 cli->cl_sp_to = LUSTRE_SP_MDT;
356                 ns_type = LDLM_NS_TYPE_MDC;
357         } else if (!strcmp(name, LUSTRE_OSP_NAME)) {
358                 if (strstr(lustre_cfg_buf(lcfg, 1), "OST") == NULL) {
359                         /* OSP_on_MDT for other MDTs */
360                         connect_op = MDS_CONNECT;
361                         cli->cl_sp_to = LUSTRE_SP_MDT;
362                         ns_type = LDLM_NS_TYPE_MDC;
363                         rq_portal = OUT_PORTAL;
364                 } else {
365                         /* OSP on MDT for OST */
366                         connect_op = OST_CONNECT;
367                         cli->cl_sp_to = LUSTRE_SP_OST;
368                         ns_type = LDLM_NS_TYPE_OSC;
369                         rq_portal = OST_REQUEST_PORTAL;
370                 }
371                 rp_portal = OSC_REPLY_PORTAL;
372                 cli->cl_sp_me = LUSTRE_SP_MDT;
373         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
374                 rq_portal = MGS_REQUEST_PORTAL;
375                 rp_portal = MGC_REPLY_PORTAL;
376                 connect_op = MGS_CONNECT;
377                 cli->cl_sp_me = LUSTRE_SP_MGC;
378                 cli->cl_sp_to = LUSTRE_SP_MGS;
379                 cli->cl_flvr_mgc.sf_rpc = SPTLRPC_FLVR_INVALID;
380                 ns_type = LDLM_NS_TYPE_MGC;
381         } else {
382                 CERROR("unknown client OBD type \"%s\", can't setup\n",
383                        name);
384                 RETURN(-EINVAL);
385         }
386
387         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
388                 CERROR("requires a TARGET UUID\n");
389                 RETURN(-EINVAL);
390         }
391
392         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
393                 CERROR("client UUID must be less than 38 characters\n");
394                 RETURN(-EINVAL);
395         }
396
397         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
398                 CERROR("setup requires a SERVER UUID\n");
399                 RETURN(-EINVAL);
400         }
401
402         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
403                 CERROR("target UUID must be less than 38 characters\n");
404                 RETURN(-EINVAL);
405         }
406
407         init_rwsem(&cli->cl_sem);
408         mutex_init(&cli->cl_mgc_mutex);
409         cli->cl_seq = NULL;
410         init_rwsem(&cli->cl_seq_rwsem);
411         cli->cl_conn_count = 0;
412         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
413                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
414                      sizeof(server_uuid)));
415
416         cli->cl_dirty_pages = 0;
417         cli->cl_dirty_max_pages = 0;
418         cli->cl_avail_grant = 0;
419         /* FIXME: Should limit this for the sum of all cl_dirty_max_pages. */
420         /*
421          * cl_dirty_max_pages may be changed at connect time in
422          * ptlrpc_connect_interpret().
423          */
424         client_adjust_max_dirty(cli);
425         init_waitqueue_head(&cli->cl_cache_waiters);
426         INIT_LIST_HEAD(&cli->cl_loi_ready_list);
427         INIT_LIST_HEAD(&cli->cl_loi_hp_ready_list);
428         INIT_LIST_HEAD(&cli->cl_loi_write_list);
429         INIT_LIST_HEAD(&cli->cl_loi_read_list);
430         spin_lock_init(&cli->cl_loi_list_lock);
431         atomic_set(&cli->cl_pending_w_pages, 0);
432         atomic_set(&cli->cl_pending_r_pages, 0);
433         cli->cl_r_in_flight = 0;
434         cli->cl_w_in_flight = 0;
435
436         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
437         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
438         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
439         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
440         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
441         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
442
443         /* lru for osc. */
444         INIT_LIST_HEAD(&cli->cl_lru_osc);
445         atomic_set(&cli->cl_lru_shrinkers, 0);
446         atomic_long_set(&cli->cl_lru_busy, 0);
447         atomic_long_set(&cli->cl_lru_in_list, 0);
448         INIT_LIST_HEAD(&cli->cl_lru_list);
449         spin_lock_init(&cli->cl_lru_list_lock);
450         atomic_long_set(&cli->cl_unstable_count, 0);
451         INIT_LIST_HEAD(&cli->cl_shrink_list);
452         INIT_LIST_HEAD(&cli->cl_grant_chain);
453
454         INIT_LIST_HEAD(&cli->cl_flight_waiters);
455         cli->cl_rpcs_in_flight = 0;
456
457         init_waitqueue_head(&cli->cl_destroy_waitq);
458         atomic_set(&cli->cl_destroy_in_flight, 0);
459
460
461         cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
462         cli->cl_preferred_cksum_type = 0;
463 #ifdef ENABLE_CHECKSUM
464         /* Turn on checksumming by default. */
465         cli->cl_checksum = 1;
466         /*
467          * The supported checksum types will be worked out at connect time
468          * Set cl_chksum* to CRC32 for now to avoid returning screwed info
469          * through procfs.
470          */
471         cli->cl_cksum_type = cli->cl_supp_cksum_types;
472 #endif
473         atomic_set(&cli->cl_resends, OSC_DEFAULT_RESENDS);
474
475         /*
476          * Set it to possible maximum size. It may be reduced by ocd_brw_size
477          * from OFD after connecting.
478          */
479         cli->cl_max_pages_per_rpc = PTLRPC_MAX_BRW_PAGES;
480
481         cli->cl_max_short_io_bytes = OBD_DEF_SHORT_IO_BYTES;
482
483         /*
484          * set cl_chunkbits default value to PAGE_SHIFT,
485          * it will be updated at OSC connection time.
486          */
487         cli->cl_chunkbits = PAGE_SHIFT;
488
489         if (!strcmp(name, LUSTRE_MDC_NAME)) {
490                 cli->cl_max_rpcs_in_flight = OBD_MAX_RIF_DEFAULT;
491         } else if (cfs_totalram_pages() >> (20 - PAGE_SHIFT) <= 128 /* MB */) {
492                 cli->cl_max_rpcs_in_flight = 2;
493         } else if (cfs_totalram_pages() >> (20 - PAGE_SHIFT) <= 256 /* MB */) {
494                 cli->cl_max_rpcs_in_flight = 3;
495         } else if (cfs_totalram_pages() >> (20 - PAGE_SHIFT) <= 512 /* MB */) {
496                 cli->cl_max_rpcs_in_flight = 4;
497         } else {
498                 if (osc_on_mdt(obd->obd_name))
499                         cli->cl_max_rpcs_in_flight = OBD_MAX_RIF_MAX;
500                 else
501                         cli->cl_max_rpcs_in_flight = OBD_MAX_RIF_DEFAULT;
502         }
503
504         spin_lock_init(&cli->cl_mod_rpcs_lock);
505         spin_lock_init(&cli->cl_mod_rpcs_hist.oh_lock);
506         cli->cl_max_mod_rpcs_in_flight = 0;
507         cli->cl_mod_rpcs_in_flight = 0;
508         cli->cl_close_rpcs_in_flight = 0;
509         init_waitqueue_head(&cli->cl_mod_rpcs_waitq);
510         cli->cl_mod_tag_bitmap = NULL;
511
512         INIT_LIST_HEAD(&cli->cl_chg_dev_linkage);
513
514         if (connect_op == MDS_CONNECT) {
515                 cli->cl_max_mod_rpcs_in_flight = cli->cl_max_rpcs_in_flight - 1;
516                 OBD_ALLOC(cli->cl_mod_tag_bitmap,
517                           BITS_TO_LONGS(OBD_MAX_RIF_MAX) * sizeof(long));
518                 if (cli->cl_mod_tag_bitmap == NULL)
519                         GOTO(err, rc = -ENOMEM);
520         }
521
522         rc = ldlm_get_ref();
523         if (rc) {
524                 CERROR("ldlm_get_ref failed: %d\n", rc);
525                 GOTO(err, rc);
526         }
527
528         ptlrpc_init_client(rq_portal, rp_portal, name,
529                            &obd->obd_ldlm_client);
530
531         imp = class_new_import(obd);
532         if (imp == NULL)
533                 GOTO(err_ldlm, rc = -ENOENT);
534         imp->imp_client = &obd->obd_ldlm_client;
535         imp->imp_connect_op = connect_op;
536         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
537                LUSTRE_CFG_BUFLEN(lcfg, 1));
538         class_import_put(imp);
539
540         if (lustre_cfg_buf(lcfg, 4)) {
541                 __u32 refnet = libcfs_str2net(lustre_cfg_string(lcfg, 4));
542
543                 if (refnet == LNET_NET_ANY) {
544                         rc = -EINVAL;
545                         CERROR("%s: bad mount option 'network=%s': rc = %d\n",
546                                obd->obd_name, lustre_cfg_string(lcfg, 4),
547                                rc);
548                         GOTO(err_import, rc);
549                 }
550                 fake_conn.c_self = LNET_MKNID(refnet, 0);
551                 imp->imp_connection = &fake_conn;
552         }
553
554         rc = client_import_add_conn(imp, &server_uuid, 1);
555         if (rc) {
556                 CERROR("can't add initial connection\n");
557                 GOTO(err_import, rc);
558         }
559         imp->imp_connection = NULL;
560
561         cli->cl_import = imp;
562         /* cli->cl_max_mds_easize updated by mdc_init_ea_size() */
563         cli->cl_max_mds_easize = sizeof(struct lov_mds_md_v3);
564
565         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
566                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
567                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
568                                name, obd->obd_name,
569                                cli->cl_target_uuid.uuid);
570                         spin_lock(&imp->imp_lock);
571                         imp->imp_deactive = 1;
572                         spin_unlock(&imp->imp_lock);
573                 }
574         }
575
576         obd->obd_namespace = ldlm_namespace_new(obd, obd->obd_name,
577                                                 LDLM_NAMESPACE_CLIENT,
578                                                 LDLM_NAMESPACE_GREEDY,
579                                                 ns_type);
580         if (IS_ERR(obd->obd_namespace)) {
581                 rc = PTR_ERR(obd->obd_namespace);
582                 CERROR("%s: unable to create client namespace: rc = %d\n",
583                        obd->obd_name, rc);
584                 obd->obd_namespace = NULL;
585                 GOTO(err_import, rc);
586         }
587
588         RETURN(rc);
589
590 err_import:
591         class_destroy_import(imp);
592 err_ldlm:
593         ldlm_put_ref();
594 err:
595         if (cli->cl_mod_tag_bitmap != NULL)
596                 OBD_FREE(cli->cl_mod_tag_bitmap,
597                          BITS_TO_LONGS(OBD_MAX_RIF_MAX) * sizeof(long));
598         cli->cl_mod_tag_bitmap = NULL;
599
600         RETURN(rc);
601 }
602 EXPORT_SYMBOL(client_obd_setup);
603
604 int client_obd_cleanup(struct obd_device *obd)
605 {
606         struct client_obd *cli = &obd->u.cli;
607
608         ENTRY;
609
610         ldlm_namespace_free_post(obd->obd_namespace);
611         obd->obd_namespace = NULL;
612
613         obd_cleanup_client_import(obd);
614         LASSERT(obd->u.cli.cl_import == NULL);
615
616         ldlm_put_ref();
617
618         if (cli->cl_mod_tag_bitmap != NULL)
619                 OBD_FREE(cli->cl_mod_tag_bitmap,
620                          BITS_TO_LONGS(OBD_MAX_RIF_MAX) * sizeof(long));
621         cli->cl_mod_tag_bitmap = NULL;
622
623         RETURN(0);
624 }
625 EXPORT_SYMBOL(client_obd_cleanup);
626
627 /* ->o_connect() method for client side (OSC and MDC and MGC) */
628 int client_connect_import(const struct lu_env *env,
629                           struct obd_export **exp,
630                           struct obd_device *obd, struct obd_uuid *cluuid,
631                           struct obd_connect_data *data, void *localdata)
632 {
633         struct client_obd *cli = &obd->u.cli;
634         struct obd_import *imp = cli->cl_import;
635         struct obd_connect_data *ocd;
636         struct lustre_handle conn = { 0 };
637         int rc;
638
639         ENTRY;
640
641         *exp = NULL;
642         down_write(&cli->cl_sem);
643         if (cli->cl_conn_count > 0)
644                 GOTO(out_sem, rc = -EALREADY);
645
646         rc = class_connect(&conn, obd, cluuid);
647         if (rc)
648                 GOTO(out_sem, rc);
649
650         cli->cl_conn_count++;
651         *exp = class_conn2export(&conn);
652
653         LASSERT(obd->obd_namespace);
654
655         imp->imp_dlm_handle = conn;
656         rc = ptlrpc_init_import(imp);
657         if (rc != 0)
658                 GOTO(out_ldlm, rc);
659
660         ocd = &imp->imp_connect_data;
661         if (data) {
662                 *ocd = *data;
663                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
664                 imp->imp_connect_flags2_orig = data->ocd_connect_flags2;
665         }
666
667         rc = ptlrpc_connect_import(imp);
668         if (rc != 0) {
669                 LASSERT(imp->imp_state == LUSTRE_IMP_DISCON);
670                 GOTO(out_ldlm, rc);
671         }
672         LASSERT(*exp != NULL && (*exp)->exp_connection);
673
674         if (data) {
675                 LASSERTF((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
676                          ocd->ocd_connect_flags, "old %#llx, new %#llx\n",
677                          data->ocd_connect_flags, ocd->ocd_connect_flags);
678                 data->ocd_connect_flags = ocd->ocd_connect_flags;
679                 data->ocd_connect_flags2 = ocd->ocd_connect_flags2;
680         }
681
682         ptlrpc_pinger_add_import(imp);
683
684         EXIT;
685
686         if (rc) {
687 out_ldlm:
688                 cli->cl_conn_count--;
689                 class_disconnect(*exp);
690                 *exp = NULL;
691         }
692 out_sem:
693         up_write(&cli->cl_sem);
694
695         if (!rc && localdata) {
696                 LASSERT(cli->cl_cache == NULL); /* only once */
697                 cli->cl_cache = (struct cl_client_cache *)localdata;
698                 cl_cache_incref(cli->cl_cache);
699                 cli->cl_lru_left = &cli->cl_cache->ccc_lru_left;
700
701                 /* add this osc into entity list */
702                 LASSERT(list_empty(&cli->cl_lru_osc));
703                 spin_lock(&cli->cl_cache->ccc_lru_lock);
704                 list_add(&cli->cl_lru_osc, &cli->cl_cache->ccc_lru);
705                 spin_unlock(&cli->cl_cache->ccc_lru_lock);
706         }
707
708         return rc;
709 }
710 EXPORT_SYMBOL(client_connect_import);
711
712 int client_disconnect_export(struct obd_export *exp)
713 {
714         struct obd_device *obd = class_exp2obd(exp);
715         struct client_obd *cli;
716         struct obd_import *imp;
717         int rc = 0, err;
718
719         ENTRY;
720
721         if (!obd) {
722                 CERROR("invalid export for disconnect: exp %p cookie %#llx\n",
723                        exp, exp ? exp->exp_handle.h_cookie : -1);
724                 RETURN(-EINVAL);
725         }
726
727         cli = &obd->u.cli;
728         imp = cli->cl_import;
729
730         down_write(&cli->cl_sem);
731         CDEBUG(D_INFO, "disconnect %s - %zu\n", obd->obd_name,
732                 cli->cl_conn_count);
733
734         if (cli->cl_conn_count == 0) {
735                 CERROR("disconnecting disconnected device (%s)\n",
736                        obd->obd_name);
737                 GOTO(out_disconnect, rc = -EINVAL);
738         }
739
740         cli->cl_conn_count--;
741         if (cli->cl_conn_count != 0)
742                 GOTO(out_disconnect, rc = 0);
743
744         /*
745          * Mark import deactivated now, so we don't try to reconnect if any
746          * of the cleanup RPCs fails (e.g. LDLM cancel, etc).  We don't
747          * fully deactivate the import, or that would drop all requests.
748          */
749         spin_lock(&imp->imp_lock);
750         imp->imp_deactive = 1;
751         spin_unlock(&imp->imp_lock);
752
753         /*
754          * Some non-replayable imports (MDS's OSCs) are pinged, so just
755          * delete it regardless.  (It's safe to delete an import that was
756          * never added.)
757          */
758         (void)ptlrpc_pinger_del_import(imp);
759
760         if (obd->obd_namespace != NULL) {
761                 /* obd_force == local only */
762                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
763                                        obd->obd_force ? LCF_LOCAL : 0, NULL);
764                 ldlm_namespace_free_prior(obd->obd_namespace, imp,
765                                           obd->obd_force);
766         }
767
768         /*
769          * There's no need to hold sem while disconnecting an import,
770          * and it may actually cause deadlock in GSS.
771          */
772         up_write(&cli->cl_sem);
773         rc = ptlrpc_disconnect_import(imp, 0);
774         down_write(&cli->cl_sem);
775
776         ptlrpc_invalidate_import(imp);
777
778         EXIT;
779
780 out_disconnect:
781         /*
782          * Use server style - class_disconnect should be always called for
783          * o_disconnect.
784          */
785         err = class_disconnect(exp);
786         if (!rc && err)
787                 rc = err;
788
789         up_write(&cli->cl_sem);
790
791         RETURN(rc);
792 }
793 EXPORT_SYMBOL(client_disconnect_export);
794
795 #ifdef HAVE_SERVER_SUPPORT
796 int server_disconnect_export(struct obd_export *exp)
797 {
798         int rc;
799
800         ENTRY;
801
802         /* Disconnect early so that clients can't keep using export. */
803         rc = class_disconnect(exp);
804         /* Close import to avoid sending any requests. */
805         if (exp->exp_imp_reverse)
806                 ptlrpc_cleanup_imp(exp->exp_imp_reverse);
807
808         ldlm_bl_thread_wakeup();
809
810         /* complete all outstanding replies */
811         spin_lock(&exp->exp_lock);
812         while (!list_empty(&exp->exp_outstanding_replies)) {
813                 struct ptlrpc_reply_state *rs =
814                         list_entry(exp->exp_outstanding_replies.next,
815                                        struct ptlrpc_reply_state, rs_exp_list);
816                 struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
817
818                 spin_lock(&svcpt->scp_rep_lock);
819
820                 list_del_init(&rs->rs_exp_list);
821
822                 spin_lock(&rs->rs_lock);
823                 /* clear rs_convert_lock to make sure rs is handled and put */
824                 rs->rs_convert_lock = 0;
825                 ptlrpc_schedule_difficult_reply(rs);
826                 spin_unlock(&rs->rs_lock);
827
828                 spin_unlock(&svcpt->scp_rep_lock);
829         }
830         spin_unlock(&exp->exp_lock);
831
832         RETURN(rc);
833 }
834 EXPORT_SYMBOL(server_disconnect_export);
835
836 static inline int target_check_recovery_timer(struct obd_device *target)
837 {
838         ktime_t remaining;
839         s64 timeout;
840
841         if (!target->obd_recovering || target->obd_recovery_start == 0)
842                 return 0;
843
844         remaining = hrtimer_get_remaining(&target->obd_recovery_timer);
845         timeout = ktime_divns(remaining, NSEC_PER_SEC);
846         if (timeout > -30)
847                 return 0;
848
849         /* the recovery timer should expire, but it isn't triggered,
850          * it's better to abort the recovery of this target to speed up
851          * the recovery of the whole cluster. */
852         spin_lock(&target->obd_dev_lock);
853         if (target->obd_recovering) {
854                 CERROR("%s: Aborting recovery\n", target->obd_name);
855                 target->obd_abort_recovery = 1;
856                 wake_up(&target->obd_next_transno_waitq);
857         }
858         spin_unlock(&target->obd_dev_lock);
859         return 0;
860 }
861
862 /*
863  * --------------------------------------------------------------------------
864  * from old lib/target.c
865  * --------------------------------------------------------------------------
866  */
867 static int target_handle_reconnect(struct lustre_handle *conn,
868                                    struct obd_export *exp,
869                                    struct obd_uuid *cluuid)
870 {
871         struct obd_device *target;
872         struct lustre_handle *hdl;
873         ktime_t remaining;
874         s64 timeout;
875         int rc = 0;
876
877         ENTRY;
878         hdl = &exp->exp_imp_reverse->imp_remote_handle;
879         if (!exp->exp_connection || !lustre_handle_is_used(hdl)) {
880                 conn->cookie = exp->exp_handle.h_cookie;
881                 CDEBUG(D_HA,
882                        "connect export for UUID '%s' at %p, cookie %#llx\n",
883                        cluuid->uuid, exp, conn->cookie);
884                 RETURN(0);
885         }
886
887         target = exp->exp_obd;
888
889         /* Might be a re-connect after a partition. */
890         if (memcmp(&conn->cookie, &hdl->cookie, sizeof(conn->cookie))) {
891                 LCONSOLE_WARN("%s: already connected client %s (at %s) with handle %#llx. Rejecting client with the same UUID trying to reconnect with handle %#llx\n",
892                               target->obd_name,
893                               obd_uuid2str(&exp->exp_client_uuid),
894                               obd_export_nid2str(exp),
895                               hdl->cookie, conn->cookie);
896                 memset(conn, 0, sizeof(*conn));
897                 /*
898                  * target_handle_connect() treats EALREADY and
899                  * -EALREADY differently.  -EALREADY is an error
900                  * (same UUID, different handle).
901                  */
902                 RETURN(-EALREADY);
903         }
904
905         if (!target->obd_recovering) {
906                 LCONSOLE_WARN("%s: Client %s (at %s) reconnecting\n",
907                         target->obd_name, obd_uuid2str(&exp->exp_client_uuid),
908                         obd_export_nid2str(exp));
909                 GOTO(out_already, rc);
910         }
911
912         remaining = hrtimer_get_remaining(&target->obd_recovery_timer);
913         timeout = ktime_divns(remaining, NSEC_PER_SEC);
914         if (timeout > 0) {
915                 LCONSOLE_WARN("%s: Client %s (at %s) reconnected, waiting for %d clients in recovery for %lld:%.02lld\n",
916                               target->obd_name,
917                               obd_uuid2str(&exp->exp_client_uuid),
918                               obd_export_nid2str(exp),
919                               atomic_read(&target->obd_max_recoverable_clients),
920                               timeout / 60, timeout % 60);
921         } else {
922                 struct target_distribute_txn_data *tdtd;
923                 int size = 0;
924                 int count = 0;
925                 char *buf = NULL;
926
927                 target_check_recovery_timer(target);
928
929                 tdtd = class_exp2tgt(exp)->lut_tdtd;
930                 if (tdtd && tdtd->tdtd_show_update_logs_retrievers)
931                         buf = tdtd->tdtd_show_update_logs_retrievers(
932                                 tdtd->tdtd_show_retrievers_cbdata,
933                                 &size, &count);
934
935                 if (count > 0)
936                         LCONSOLE_WARN("%s: Client %s (at %s) reconnecting, waiting for %d MDTs (%s) in recovery for %lld:%.02lld. Please wait until all MDTs recovered or you may force MDT evicition via 'lctl --device %s abort_recovery.\n",
937                                       target->obd_name,
938                                       obd_uuid2str(&exp->exp_client_uuid),
939                                       obd_export_nid2str(exp), count,
940                                       buf ? buf : "unknown (not enough RAM)",
941                                       (abs(timeout) + target->obd_recovery_timeout) / 60,
942                                       (abs(timeout) + target->obd_recovery_timeout) % 60,
943                                       target->obd_name);
944                 else
945                         LCONSOLE_WARN("%s: Recovery already passed deadline %lld:%.02lld. If you do not want to wait more, you may force taget eviction via 'lctl --device %s abort_recovery.\n",
946                                       target->obd_name, abs(timeout) / 60,
947                                       abs(timeout) % 60, target->obd_name);
948
949                 if (buf != NULL)
950                         OBD_FREE(buf, size);
951         }
952
953 out_already:
954         conn->cookie = exp->exp_handle.h_cookie;
955         /*
956          * target_handle_connect() treats EALREADY and
957          * -EALREADY differently.  EALREADY means we are
958          * doing a valid reconnect from the same client.
959          */
960         RETURN(EALREADY);
961 }
962
963 static void
964 check_and_start_recovery_timer(struct obd_device *obd,
965                                struct ptlrpc_request *req, int new_client);
966
967 /**
968  * update flags for import during reconnect process
969  */
970 static int rev_import_flags_update(struct obd_import *revimp,
971                                    struct ptlrpc_request *req)
972 {
973         int rc;
974         struct obd_connect_data *data;
975
976         data = req_capsule_client_get(&req->rq_pill, &RMF_CONNECT_DATA);
977
978         if (data->ocd_connect_flags & OBD_CONNECT_AT)
979                 revimp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
980         else
981                 revimp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
982
983         revimp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
984
985         revimp->imp_connect_data = *data;
986         rc = sptlrpc_import_sec_adapt(revimp, req->rq_svc_ctx, &req->rq_flvr);
987         if (rc) {
988                 CERROR("%s: cannot get reverse import %s security: rc = %d\n",
989                         revimp->imp_client->cli_name,
990                         libcfs_id2str(req->rq_peer), rc);
991                 return rc;
992         }
993
994         return 0;
995 }
996
997 /**
998  * Allocate a new reverse import for an export.
999  *
1000  * \retval -errno in case error hit
1001  * \retval 0 if reverse import correctly init
1002  **/
1003 int rev_import_init(struct obd_export *export)
1004 {
1005         struct obd_device *obd = export->exp_obd;
1006         struct obd_import *revimp;
1007
1008         LASSERT(export->exp_imp_reverse == NULL);
1009
1010         revimp = class_new_import(obd);
1011         if (revimp == NULL)
1012                 return -ENOMEM;
1013
1014         revimp->imp_remote_handle.cookie = 0ULL;
1015         revimp->imp_client = &obd->obd_ldlm_client;
1016         revimp->imp_dlm_fake = 1;
1017
1018         /* it is safe to connect import in new state as no sends possible */
1019         spin_lock(&export->exp_lock);
1020         export->exp_imp_reverse = revimp;
1021         spin_unlock(&export->exp_lock);
1022         class_import_put(revimp);
1023
1024         return 0;
1025 }
1026 EXPORT_SYMBOL(rev_import_init);
1027
1028 /**
1029  * Handle reconnect for an export.
1030  *
1031  * \param exp export to handle reconnect process
1032  * \param req client reconnect request
1033  *
1034  * \retval -rc in case securitfy flavor can't be changed
1035  * \retval 0 in case none problems
1036  */
1037 static int rev_import_reconnect(struct obd_export *exp,
1038                                 struct ptlrpc_request *req)
1039 {
1040         struct obd_import *revimp = exp->exp_imp_reverse;
1041         struct lustre_handle *lh;
1042         int rc;
1043
1044         /* avoid sending a request until import flags are changed */
1045         ptlrpc_import_enter_resend(revimp);
1046
1047         ptlrpc_connection_put(revimp->imp_connection);
1048
1049         /*
1050          * client from recovery don't have a handle so we need to take from
1051          * request. it may produce situation when wrong client connected
1052          * to recovery as we trust a client uuid
1053          */
1054         lh = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
1055         revimp->imp_remote_handle = *lh;
1056
1057         /*
1058          * unknown versions will be caught in
1059          * ptlrpc_handle_server_req_in->lustre_unpack_msg()
1060          */
1061         revimp->imp_msg_magic = req->rq_reqmsg->lm_magic;
1062
1063         revimp->imp_connection = ptlrpc_connection_addref(exp->exp_connection);
1064
1065         rc = rev_import_flags_update(revimp, req);
1066         if (rc != 0) {
1067                 /*
1068                  * it is safe to still be in RECOVERY phase as we are not able
1069                  * to setup correct security flavor so requests are not able to
1070                  * be delivered correctly
1071                  */
1072                 return rc;
1073         }
1074
1075         /* resend all rpc's via new connection */
1076         return ptlrpc_import_recovery_state_machine(revimp);
1077 }
1078
1079 int target_handle_connect(struct ptlrpc_request *req)
1080 {
1081         struct obd_device *target = NULL;
1082         struct obd_export *export = NULL;
1083         /*
1084          * connect handle - filled from target_handle_reconnect in
1085          * reconnect case
1086          */
1087         struct lustre_handle conn;
1088         struct lustre_handle *tmp;
1089         struct obd_uuid cluuid;
1090         char *str;
1091         int rc = 0;
1092         char *target_start;
1093         int target_len;
1094         bool mds_conn = false, lw_client = false, initial_conn = false;
1095         bool mds_mds_conn = false;
1096         bool new_mds_mds_conn = false;
1097         struct obd_connect_data *data, *tmpdata;
1098         int size, tmpsize;
1099         lnet_nid_t *client_nid = NULL;
1100         struct ptlrpc_connection *pcon = NULL;
1101
1102         ENTRY;
1103
1104         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
1105
1106         str = req_capsule_client_get(&req->rq_pill, &RMF_TGTUUID);
1107         if (str == NULL) {
1108                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
1109                 GOTO(out, rc = -EINVAL);
1110         }
1111
1112         target = class_dev_by_str(str);
1113         if (!target) {
1114                 deuuidify(str, NULL, &target_start, &target_len);
1115                 LCONSOLE_ERROR_MSG(0x137,
1116                                    "%s: not available for connect from %s (no target). If you are running an HA pair check that the target is mounted on the other server.\n",
1117                                    str, libcfs_nid2str(req->rq_peer.nid));
1118                 GOTO(out, rc = -ENODEV);
1119         }
1120
1121         spin_lock(&target->obd_dev_lock);
1122
1123         target->obd_conn_inprogress++;
1124
1125         if (target->obd_stopping || !target->obd_set_up) {
1126                 spin_unlock(&target->obd_dev_lock);
1127
1128                 deuuidify(str, NULL, &target_start, &target_len);
1129                 LCONSOLE_INFO("%.*s: Not available for connect from %s (%s)\n",
1130                               target_len, target_start,
1131                               libcfs_nid2str(req->rq_peer.nid),
1132                               (target->obd_stopping ?
1133                                "stopping" : "not set up"));
1134                 GOTO(out, rc = -ENODEV);
1135         }
1136
1137         if (target->obd_no_conn) {
1138                 spin_unlock(&target->obd_dev_lock);
1139
1140                 CDEBUG(D_INFO,
1141                        "%s: Temporarily refusing client connection from %s\n",
1142                        target->obd_name, libcfs_nid2str(req->rq_peer.nid));
1143                 GOTO(out, rc = -EAGAIN);
1144         }
1145
1146         spin_unlock(&target->obd_dev_lock);
1147
1148         str = req_capsule_client_get(&req->rq_pill, &RMF_CLUUID);
1149         if (str == NULL) {
1150                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
1151                 GOTO(out, rc = -EINVAL);
1152         }
1153
1154         obd_str2uuid(&cluuid, str);
1155
1156         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
1157         if (tmp == NULL)
1158                 GOTO(out, rc = -EPROTO);
1159
1160         conn = *tmp;
1161
1162         size = req_capsule_get_size(&req->rq_pill, &RMF_CONNECT_DATA,
1163                                     RCL_CLIENT);
1164         if (size < 0 || size > 8 * sizeof(struct obd_connect_data))
1165                 GOTO(out, rc = -EPROTO);
1166         data = req_capsule_client_get(&req->rq_pill, &RMF_CONNECT_DATA);
1167         if (!data)
1168                 GOTO(out, rc = -EPROTO);
1169
1170         rc = req_capsule_server_pack(&req->rq_pill);
1171         if (rc)
1172                 GOTO(out, rc);
1173
1174 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
1175         /*
1176          * Don't allow clients to connect that are using old 1.8 format
1177          * protocol conventions (LUSTRE_MSG_MAGIC_v1, !MSGHDR_CKSUM_INCOMPAT18,
1178          * ldlm_flock_policy_wire format, MDT_ATTR_xTIME_SET, etc).  The
1179          * FULL20 flag should be set on all connections since 2.0, but no
1180          * longer affects behaviour.
1181          *
1182          * Later this check will be disabled and the flag can be retired
1183          * completely once interop with 3.0 is no longer needed.
1184          */
1185         if (!(data->ocd_connect_flags & OBD_CONNECT_FULL20))
1186                 GOTO(out, rc = -EPROTO);
1187
1188         /*
1189          * Don't allow liblustre clients to connect.
1190          * - testing was disabled in v2_2_50_0-61-g6a75d65
1191          * - building was disabled in v2_5_58_0-28-g7277179
1192          * - client code was deleted in v2_6_50_0-101-gcdfbc72,
1193          * - clients were refused connect for version difference > 0.0.1.32
1194          */
1195         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
1196                 DEBUG_REQ(D_WARNING, req, "Refusing libclient connection");
1197                 GOTO(out, rc = -EPROTO);
1198         }
1199 #endif
1200
1201         /*
1202          * Note: lw_client is needed in MDS-MDS failover during update log
1203          * processing, so we needs to allow lw_client to be connected at
1204          * anytime, instead of only the initial connection
1205          */
1206         lw_client = (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) != 0;
1207
1208         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL) {
1209                 initial_conn = true;
1210                 mds_conn = (data->ocd_connect_flags & OBD_CONNECT_MDS) != 0;
1211                 mds_mds_conn = (data->ocd_connect_flags &
1212                                 OBD_CONNECT_MDS_MDS) != 0;
1213
1214                 /*
1215                  * OBD_CONNECT_MNE_SWAB is removed at 2.14
1216                  * Checking OBD_CONNECT_FID can be removed in the future.
1217                  *
1218                  * Via check OBD_CONNECT_FID, we can distinguish whether
1219                  * the OBD_CONNECT_MDS_MDS/OBD_CONNECT_MNE_SWAB is from
1220                  * MGC or MDT, since MGC does not use OBD_CONNECT_FID.
1221                  */
1222                 if (!lw_client &&
1223                     (data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
1224                     (data->ocd_connect_flags & OBD_CONNECT_FID) &&
1225                     (data->ocd_connect_flags & OBD_CONNECT_VERSION)) {
1226                         __u32 major = OBD_OCD_VERSION_MAJOR(data->ocd_version);
1227                         __u32 minor = OBD_OCD_VERSION_MINOR(data->ocd_version);
1228                         __u32 patch = OBD_OCD_VERSION_PATCH(data->ocd_version);
1229
1230                         /*
1231                          * We do not support the MDT-MDT interoperations with
1232                          * different version MDT because of protocol changes.
1233                          */
1234                         if (unlikely(major != LUSTRE_MAJOR ||
1235                                      minor != LUSTRE_MINOR ||
1236                                      abs(patch - LUSTRE_PATCH) > 3)) {
1237                                 LCONSOLE_WARN("%s (%u.%u.%u.%u) refused the connection from different version MDT (%d.%d.%d.%d) %s %s\n",
1238                                               target->obd_name, LUSTRE_MAJOR,
1239                                               LUSTRE_MINOR, LUSTRE_PATCH,
1240                                               LUSTRE_FIX, major, minor, patch,
1241                                               OBD_OCD_VERSION_FIX(data->ocd_version),
1242                                               libcfs_nid2str(req->rq_peer.nid),
1243                                               str);
1244                                 GOTO(out, rc = -EPROTO);
1245                         }
1246                 }
1247         }
1248
1249         /* lctl gets a backstage, all-access pass. */
1250         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
1251                 goto dont_check_exports;
1252
1253         export = obd_uuid_lookup(target, &cluuid);
1254         if (!export)
1255                 goto no_export;
1256
1257         /* We've found an export in the hash. */
1258
1259         spin_lock(&export->exp_lock);
1260
1261         if (export->exp_connecting) { /* b=9635, et. al. */
1262                 spin_unlock(&export->exp_lock);
1263                 LCONSOLE_WARN("%s: Export %p already connecting from %s\n",
1264                               export->exp_obd->obd_name, export,
1265                               libcfs_nid2str(req->rq_peer.nid));
1266                 class_export_put(export);
1267                 export = NULL;
1268                 rc = -EALREADY;
1269         } else if ((mds_conn || (lw_client && initial_conn) ||
1270                    data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
1271                    export->exp_connection != NULL) {
1272                 spin_unlock(&export->exp_lock);
1273                 if (req->rq_peer.nid != export->exp_connection->c_peer.nid) {
1274                         /* MDS or LWP reconnected after failover. */
1275                         LCONSOLE_WARN("%s: Received %s connection from %s, removing former export from %s\n",
1276                                       target->obd_name,
1277                                       mds_conn ? "MDS" : "LWP",
1278                                       libcfs_nid2str(req->rq_peer.nid),
1279                                       libcfs_nid2str(export->exp_connection->c_peer.nid));
1280                 } else {
1281                         /* New MDS connection from the same NID. */
1282                         LCONSOLE_WARN("%s: Received new %s connection from %s, removing former export from same NID\n",
1283                                       target->obd_name,
1284                                       mds_conn ? "MDS" : "LWP",
1285                                       libcfs_nid2str(req->rq_peer.nid));
1286                 }
1287
1288                 if (req->rq_peer.nid == export->exp_connection->c_peer.nid &&
1289                     data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) {
1290                         /*
1291                          * Because exports between MDTs will always be
1292                          * kept, let's do not fail such export if they
1293                          * come from the same NID, otherwise it might
1294                          * cause eviction between MDTs, which might
1295                          * cause namespace inconsistency
1296                          */
1297                         spin_lock(&export->exp_lock);
1298                         export->exp_connecting = 1;
1299                         export->exp_conn_cnt = 0;
1300                         spin_unlock(&export->exp_lock);
1301                         conn.cookie = export->exp_handle.h_cookie;
1302                         rc = EALREADY;
1303                 } else {
1304                         class_fail_export(export);
1305                         class_export_put(export);
1306                         export = NULL;
1307                         rc = 0;
1308                 }
1309         } else if (export->exp_connection != NULL && initial_conn &&
1310                    req->rq_peer.nid != export->exp_connection->c_peer.nid) {
1311                 spin_unlock(&export->exp_lock);
1312                 /* In MDS failover we have static UUID but NID can change. */
1313                 LCONSOLE_WARN("%s: Client %s seen on new nid %s when existing nid %s is already connected\n",
1314                               target->obd_name, cluuid.uuid,
1315                               libcfs_nid2str(req->rq_peer.nid),
1316                               libcfs_nid2str(
1317                                         export->exp_connection->c_peer.nid));
1318                 rc = -EALREADY;
1319                 class_export_put(export);
1320                 export = NULL;
1321         } else if (OBD_FAIL_PRECHECK(OBD_FAIL_TGT_RECOVERY_CONNECT) &&
1322                    !lw_client) {
1323                 spin_unlock(&export->exp_lock);
1324                 rc = -EAGAIN;
1325         } else {
1326                 export->exp_connecting = 1;
1327                 spin_unlock(&export->exp_lock);
1328                 LASSERT(export->exp_obd == target);
1329
1330                 rc = target_handle_reconnect(&conn, export, &cluuid);
1331         }
1332
1333         /* If we found an export, we already unlocked. */
1334         if (!export) {
1335 no_export:
1336                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
1337         } else if (req->rq_export == NULL &&
1338                    atomic_read(&export->exp_rpc_count) > 0) {
1339                 LCONSOLE_WARN("%s: Client %s (at %s) refused connection, still busy with %d references\n",
1340                               target->obd_name, cluuid.uuid,
1341                               libcfs_nid2str(req->rq_peer.nid),
1342                               refcount_read(&export->exp_handle.h_ref));
1343                         GOTO(out, rc = -EBUSY);
1344         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1 &&
1345                    rc != EALREADY) {
1346                 if (!strstr(cluuid.uuid, "mdt"))
1347                         LCONSOLE_WARN("%s: Rejecting reconnect from the known client %s (at %s) because it is indicating it is a new client\n",
1348                                       target->obd_name, cluuid.uuid,
1349                                       libcfs_nid2str(req->rq_peer.nid));
1350                 GOTO(out, rc = -EALREADY);
1351         } else {
1352                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
1353         }
1354
1355         if (rc < 0)
1356                 GOTO(out, rc);
1357
1358         CDEBUG(D_HA, "%s: connection from %s@%s %st%llu exp %p cur %lld last %lld\n",
1359                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
1360                target->obd_recovering ? "recovering/" : "", data->ocd_transno,
1361                export, ktime_get_seconds(),
1362                export ? export->exp_last_request_time : 0);
1363
1364         /*
1365          * If this is the first time a client connects, reset the recovery
1366          * timer. Discard lightweight connections which might be local.
1367          */
1368         if (!lw_client && rc == 0 && target->obd_recovering)
1369                 check_and_start_recovery_timer(target, req, export == NULL);
1370
1371         /*
1372          * We want to handle EALREADY but *not* -EALREADY from
1373          * target_handle_reconnect(), return reconnection state in a flag.
1374          */
1375         if (rc == EALREADY) {
1376                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
1377                 rc = 0;
1378         } else {
1379                 LASSERT(rc == 0);
1380         }
1381
1382         /* Tell the client if we support replayable requests. */
1383         if (target->obd_replayable)
1384                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
1385         client_nid = &req->rq_peer.nid;
1386
1387         if (export == NULL) {
1388                 /* allow lightweight connections during recovery */
1389                 /*
1390                  * allow "new" MDT to be connected during recovery, since we
1391                  * need retrieve recovery update records from it
1392                  */
1393                 if (target->obd_recovering && !lw_client && !mds_mds_conn) {
1394                         struct hrtimer *timer = &target->obd_recovery_timer;
1395                         ktime_t remaining;
1396                         s64 timeout, left;
1397                         int in_progress;
1398                         int connected;
1399                         int known;
1400                         int stale;
1401                         char *msg;
1402
1403                         connected = atomic_read(&target->obd_connected_clients);
1404                         in_progress = atomic_read(&target->obd_lock_replay_clients);
1405                         known =
1406                            atomic_read(&target->obd_max_recoverable_clients);
1407                         stale = target->obd_stale_clients;
1408                         remaining = hrtimer_get_remaining(timer);
1409                         left = ktime_divns(remaining, NSEC_PER_SEC);
1410
1411                         if (ktime_to_ns(remaining) > 0) {
1412                                 msg = "to recover in";
1413                                 timeout = left;
1414                         } else {
1415                                 msg = "already passed deadline";
1416                                 timeout = -left;
1417
1418                                 target_check_recovery_timer(target);
1419                         }
1420
1421                         LCONSOLE_WARN("%s: Denying connection for new client %s (at %s), waiting for %d known clients (%d recovered, %d in progress, and %d evicted) %s %lld:%.02lld\n",
1422                                       target->obd_name, cluuid.uuid,
1423                                       libcfs_nid2str(req->rq_peer.nid), known,
1424                                       connected - in_progress, in_progress,
1425                                       stale, msg, timeout / 60, timeout % 60);
1426                         rc = -EBUSY;
1427                 } else {
1428 dont_check_exports:
1429                         rc = obd_connect(req->rq_svc_thread->t_env,
1430                                          &export, target, &cluuid, data,
1431                                          client_nid);
1432                         if (mds_conn && OBD_FAIL_CHECK(OBD_FAIL_TGT_RCVG_FLAG))
1433                                 lustre_msg_add_op_flags(req->rq_repmsg,
1434                                                         MSG_CONNECT_RECOVERING);
1435                         if (rc == 0) {
1436                                 conn.cookie = export->exp_handle.h_cookie;
1437                                 rc = rev_import_init(export);
1438                         }
1439
1440                         if (mds_mds_conn)
1441                                 new_mds_mds_conn = true;
1442                 }
1443         } else {
1444                 rc = obd_reconnect(req->rq_svc_thread->t_env,
1445                                    export, target, &cluuid, data, client_nid);
1446         }
1447         if (rc)
1448                 GOTO(out, rc);
1449
1450         LASSERT(target->u.obt.obt_magic == OBT_MAGIC);
1451         data->ocd_instance = target->u.obt.obt_instance;
1452
1453         /*
1454          * Return only the parts of obd_connect_data that we understand, so the
1455          * client knows that we don't understand the rest.
1456          */
1457         if (data) {
1458                 tmpsize = req_capsule_get_size(&req->rq_pill, &RMF_CONNECT_DATA,
1459                                                RCL_SERVER);
1460                 tmpdata = req_capsule_server_get(&req->rq_pill,
1461                                                  &RMF_CONNECT_DATA);
1462                 /*
1463                  * Don't use struct assignment here, because the client reply
1464                  * buffer may be smaller/larger than the local struct
1465                  * obd_connect_data.
1466                  */
1467                 memcpy(tmpdata, data, min(tmpsize, size));
1468         }
1469
1470         /*
1471          * If the client and the server are the same node, we will already
1472          * have an export that really points to the client's DLM export,
1473          * because we have a shared handles table.
1474          *
1475          * XXX this will go away when shaver stops sending the "connect" handle
1476          * in the real "remote handle" field of the request --phik 24 Apr 2003
1477          */
1478         ptlrpc_request_change_export(req, export);
1479
1480         pcon = ptlrpc_connection_get(req->rq_peer, req->rq_self, &cluuid);
1481         if (pcon == NULL)
1482                 GOTO(out, rc = -ENOTCONN);
1483
1484         spin_lock(&export->exp_lock);
1485
1486         if (export->exp_disconnected) {
1487                 spin_unlock(&export->exp_lock);
1488                 GOTO(out, rc = -ENODEV);
1489         }
1490         if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
1491                 spin_unlock(&export->exp_lock);
1492                 CDEBUG(D_RPCTRACE,
1493                        "%s: %s already connected at greater or equal conn_cnt: %d >= %d\n",
1494                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
1495                        export->exp_conn_cnt,
1496                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
1497
1498                 GOTO(out, rc = -EALREADY);
1499         }
1500         LASSERT(lustre_msg_get_conn_cnt(req->rq_reqmsg) > 0);
1501         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
1502
1503         /* Check to see if connection came from another NID. */
1504         if (export->exp_connection != NULL &&
1505             export->exp_connection->c_peer.nid != req->rq_peer.nid) {
1506                 obd_nid_del(export->exp_obd, export);
1507                 ptlrpc_connection_put(export->exp_connection);
1508                 export->exp_connection = NULL;
1509         }
1510
1511         if (export->exp_connection == NULL) {
1512                 export->exp_connection = pcon;
1513                 pcon = NULL;
1514         }
1515         obd_nid_add(export->exp_obd, export);
1516
1517         spin_unlock(&export->exp_lock);
1518
1519         lustre_msg_set_handle(req->rq_repmsg, &conn);
1520
1521         rc = rev_import_reconnect(export, req);
1522         if (rc != 0)
1523                 GOTO(out, rc);
1524
1525         if (target->obd_recovering && !export->exp_in_recovery && !lw_client) {
1526                 int has_transno;
1527                 __u64 transno = data->ocd_transno;
1528
1529                 spin_lock(&export->exp_lock);
1530                 /*
1531                  * possible race with class_disconnect_stale_exports,
1532                  * export may be already in the eviction process
1533                  */
1534                 if (export->exp_failed) {
1535                         spin_unlock(&export->exp_lock);
1536                         GOTO(out, rc = -ENODEV);
1537                 }
1538                 export->exp_in_recovery = 1;
1539                 export->exp_req_replay_needed = 1;
1540                 export->exp_lock_replay_needed = 1;
1541                 spin_unlock(&export->exp_lock);
1542
1543                 has_transno = !!(lustre_msg_get_op_flags(req->rq_reqmsg) &
1544                                  MSG_CONNECT_TRANSNO);
1545                 if (has_transno && transno == 0)
1546                         CWARN("Connect with zero transno!\n");
1547
1548                 if (has_transno && transno > 0 &&
1549                     transno < target->obd_next_recovery_transno &&
1550                     transno > target->obd_last_committed) {
1551                         /* Another way is to use cmpxchg() to be lock-free. */
1552                         spin_lock(&target->obd_recovery_task_lock);
1553                         if (transno < target->obd_next_recovery_transno)
1554                                 target->obd_next_recovery_transno = transno;
1555                         spin_unlock(&target->obd_recovery_task_lock);
1556                 }
1557
1558                 atomic_inc(&target->obd_req_replay_clients);
1559                 atomic_inc(&target->obd_lock_replay_clients);
1560                 /*
1561                  * Note: MDS-MDS connection is allowed to be connected during
1562                  * recovery, no matter if the exports needs to be recoveried.
1563                  * Because we need retrieve updates logs from all other MDTs.
1564                  * So if the MDS-MDS export is new, obd_max_recoverable_clients
1565                  * also needs to be increased to match other recovery checking
1566                  * condition.
1567                  */
1568                 if (new_mds_mds_conn)
1569                         atomic_inc(&target->obd_max_recoverable_clients);
1570
1571                 if (atomic_inc_return(&target->obd_connected_clients) ==
1572                     atomic_read(&target->obd_max_recoverable_clients))
1573                         wake_up(&target->obd_next_transno_waitq);
1574         }
1575
1576         /* Tell the client we're in recovery, when client is involved in it. */
1577         if (target->obd_recovering && !lw_client)
1578                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
1579
1580 out:
1581         if (export) {
1582                 spin_lock(&export->exp_lock);
1583                 export->exp_connecting = 0;
1584                 spin_unlock(&export->exp_lock);
1585
1586                 class_export_put(export);
1587         }
1588         if (target != NULL) {
1589                 spin_lock(&target->obd_dev_lock);
1590                 target->obd_conn_inprogress--;
1591                 spin_unlock(&target->obd_dev_lock);
1592                 class_decref(target, "find", current);
1593         }
1594         if (pcon)
1595                 ptlrpc_connection_put(pcon);
1596         req->rq_status = rc;
1597         RETURN(rc);
1598 }
1599
1600 int target_handle_disconnect(struct ptlrpc_request *req)
1601 {
1602         int rc;
1603
1604         ENTRY;
1605
1606         rc = req_capsule_server_pack(&req->rq_pill);
1607         if (rc)
1608                 RETURN(rc);
1609
1610         /* In case of target disconnect, updating sec ctx immediately is
1611          * required in order to record latest sequence number used.
1612          * Sequence is normally updated on export destroy, but this event
1613          * can occur too late, ie after a new target connect request has
1614          * been processed.
1615          * Maintaining correct sequence when client connection becomes idle
1616          * ensures that GSS does not erroneously consider requests as replays.
1617          */
1618         rc = sptlrpc_export_update_ctx(req->rq_export);
1619         if (rc)
1620                 RETURN(rc);
1621
1622         /* Keep the rq_export around so we can send the reply. */
1623         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1624
1625         RETURN(0);
1626 }
1627
1628 void target_destroy_export(struct obd_export *exp)
1629 {
1630         struct obd_import *imp = NULL;
1631         /*
1632          * exports created from last_rcvd data, and "fake"
1633          * exports created by lctl don't have an import
1634          */
1635         spin_lock(&exp->exp_lock);
1636         if (exp->exp_imp_reverse != NULL) {
1637                 imp = exp->exp_imp_reverse;
1638                 exp->exp_imp_reverse = NULL;
1639         }
1640         spin_unlock(&exp->exp_lock);
1641         if (imp != NULL)
1642                 client_destroy_import(imp);
1643
1644         LASSERT_ATOMIC_ZERO(&exp->exp_locks_count);
1645         LASSERT_ATOMIC_ZERO(&exp->exp_rpc_count);
1646         LASSERT_ATOMIC_ZERO(&exp->exp_cb_count);
1647         LASSERT_ATOMIC_ZERO(&exp->exp_replay_count);
1648 }
1649 EXPORT_SYMBOL(target_destroy_export);
1650
1651 /*
1652  * Recovery functions
1653  */
1654 static void target_request_copy_get(struct ptlrpc_request *req)
1655 {
1656         class_export_rpc_inc(req->rq_export);
1657         LASSERT(list_empty(&req->rq_list));
1658         INIT_LIST_HEAD(&req->rq_replay_list);
1659
1660         /* Increase refcount to keep request in queue. */
1661         atomic_inc(&req->rq_refcount);
1662         /* Let export know it has replays to be handled. */
1663         atomic_inc(&req->rq_export->exp_replay_count);
1664 }
1665
1666 static void target_request_copy_put(struct ptlrpc_request *req)
1667 {
1668         LASSERT(list_empty(&req->rq_replay_list));
1669         LASSERT_ATOMIC_POS(&req->rq_export->exp_replay_count);
1670
1671         atomic_dec(&req->rq_export->exp_replay_count);
1672         class_export_rpc_dec(req->rq_export);
1673         ptlrpc_server_drop_request(req);
1674 }
1675
1676 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1677 {
1678         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1679         struct obd_export *exp = req->rq_export;
1680         struct ptlrpc_request *reqiter;
1681         struct ptlrpc_request *dup_req = NULL;
1682         int dup = 0;
1683
1684         LASSERT(exp);
1685
1686         spin_lock(&exp->exp_lock);
1687         list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1688                             rq_replay_list) {
1689                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1690                         dup_req = reqiter;
1691                         dup = 1;
1692                         break;
1693                 }
1694         }
1695
1696         if (dup) {
1697                 /* We expect it with RESENT and REPLAY flags. */
1698                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1699                     (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1700                         CERROR("invalid flags %x of resent replay\n",
1701                                lustre_msg_get_flags(req->rq_reqmsg));
1702
1703                 if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1704                         __u32 new_conn;
1705
1706                         new_conn = lustre_msg_get_conn_cnt(req->rq_reqmsg);
1707                         if (new_conn >
1708                             lustre_msg_get_conn_cnt(dup_req->rq_reqmsg))
1709                                 lustre_msg_set_conn_cnt(dup_req->rq_reqmsg,
1710                                                         new_conn);
1711                 }
1712         } else {
1713                 list_add_tail(&req->rq_replay_list,
1714                               &exp->exp_req_replay_queue);
1715         }
1716
1717         spin_unlock(&exp->exp_lock);
1718         return dup;
1719 }
1720
1721 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1722 {
1723         LASSERT(!list_empty(&req->rq_replay_list));
1724         LASSERT(req->rq_export);
1725
1726         spin_lock(&req->rq_export->exp_lock);
1727         list_del_init(&req->rq_replay_list);
1728         spin_unlock(&req->rq_export->exp_lock);
1729 }
1730
1731 static void target_finish_recovery(struct lu_target *lut)
1732 {
1733         struct obd_device *obd = lut->lut_obd;
1734
1735         ENTRY;
1736
1737         /* Only log a recovery message when recovery has occurred. */
1738         if (obd->obd_recovery_start) {
1739                 time64_t now = ktime_get_seconds();
1740                 time64_t elapsed_time;
1741
1742                 elapsed_time = max_t(time64_t, now - obd->obd_recovery_start,
1743                                      1);
1744                 LCONSOLE_INFO("%s: Recovery over after %lld:%.02lld, of %d clients %d recovered and %d %s evicted.\n",
1745                               obd->obd_name, elapsed_time / 60,
1746                               elapsed_time % 60,
1747                               atomic_read(&obd->obd_max_recoverable_clients),
1748                               atomic_read(&obd->obd_connected_clients),
1749                               obd->obd_stale_clients,
1750                               obd->obd_stale_clients == 1 ? "was" : "were");
1751                 if (obd->obd_stale_clients && do_dump_on_eviction(obd))
1752                         libcfs_debug_dumplog();
1753         }
1754
1755         ldlm_reprocess_recovery_done(obd->obd_namespace);
1756         spin_lock(&obd->obd_recovery_task_lock);
1757         if (!list_empty(&obd->obd_req_replay_queue) ||
1758             !list_empty(&obd->obd_lock_replay_queue) ||
1759             !list_empty(&obd->obd_final_req_queue)) {
1760                 CERROR("%s: Recovery queues ( %s%s%s) are not empty\n",
1761                        obd->obd_name,
1762                        list_empty(&obd->obd_req_replay_queue) ? "" : "req ",
1763                        list_empty(&obd->obd_lock_replay_queue) ? \
1764                                   "" : "lock ",
1765                        list_empty(&obd->obd_final_req_queue) ? \
1766                                   "" : "final ");
1767                 spin_unlock(&obd->obd_recovery_task_lock);
1768                 LBUG();
1769         }
1770         spin_unlock(&obd->obd_recovery_task_lock);
1771
1772         obd->obd_recovery_end = ktime_get_seconds();
1773
1774         /* When recovery finished, cleanup orphans on MDS and OST. */
1775         if (obd->obd_type && OBP(obd, postrecov)) {
1776                 int rc = OBP(obd, postrecov)(obd);
1777
1778                 if (rc < 0)
1779                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1780                                       obd->obd_name, rc);
1781         }
1782         EXIT;
1783 }
1784
1785 static void abort_req_replay_queue(struct obd_device *obd)
1786 {
1787         struct ptlrpc_request *req, *n;
1788         LIST_HEAD(abort_list);
1789
1790         spin_lock(&obd->obd_recovery_task_lock);
1791         list_splice_init(&obd->obd_req_replay_queue, &abort_list);
1792         spin_unlock(&obd->obd_recovery_task_lock);
1793         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1794                 DEBUG_REQ(D_WARNING, req, "aborted:");
1795                 req->rq_status = -ENOTCONN;
1796                 if (ptlrpc_error(req)) {
1797                         DEBUG_REQ(D_ERROR, req,
1798                                   "failed abort_req_reply; skipping");
1799                 }
1800                 target_exp_dequeue_req_replay(req);
1801                 target_request_copy_put(req);
1802         }
1803 }
1804
1805 static void abort_lock_replay_queue(struct obd_device *obd)
1806 {
1807         struct ptlrpc_request *req, *n;
1808         LIST_HEAD(abort_list);
1809
1810         spin_lock(&obd->obd_recovery_task_lock);
1811         list_splice_init(&obd->obd_lock_replay_queue, &abort_list);
1812         spin_unlock(&obd->obd_recovery_task_lock);
1813         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1814                 DEBUG_REQ(D_ERROR, req, "aborted:");
1815                 req->rq_status = -ENOTCONN;
1816                 if (ptlrpc_error(req)) {
1817                         DEBUG_REQ(D_ERROR, req,
1818                                   "failed abort_lock_reply; skipping");
1819                 }
1820                 target_request_copy_put(req);
1821         }
1822 }
1823
1824 /*
1825  * Called from a cleanup function if the device is being cleaned up
1826  * forcefully.  The exports should all have been disconnected already,
1827  * the only thing left to do is
1828  * - clear the recovery flags
1829  * - cancel the timer
1830  * - free queued requests and replies, but don't send replies
1831  * Because the obd_stopping flag is set, no new requests should be received.
1832  */
1833 void target_cleanup_recovery(struct obd_device *obd)
1834 {
1835         struct ptlrpc_request *req, *n;
1836         LIST_HEAD(clean_list);
1837
1838         spin_lock(&obd->obd_dev_lock);
1839         if (!obd->obd_recovering) {
1840                 spin_unlock(&obd->obd_dev_lock);
1841                 EXIT;
1842                 return;
1843         }
1844         obd->obd_recovering = obd->obd_abort_recovery = 0;
1845         spin_unlock(&obd->obd_dev_lock);
1846
1847         spin_lock(&obd->obd_recovery_task_lock);
1848         target_cancel_recovery_timer(obd);
1849         list_splice_init(&obd->obd_req_replay_queue, &clean_list);
1850         spin_unlock(&obd->obd_recovery_task_lock);
1851
1852         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1853                 LASSERT(req->rq_reply_state == NULL);
1854                 target_exp_dequeue_req_replay(req);
1855                 target_request_copy_put(req);
1856         }
1857
1858         spin_lock(&obd->obd_recovery_task_lock);
1859         list_splice_init(&obd->obd_lock_replay_queue, &clean_list);
1860         list_splice_init(&obd->obd_final_req_queue, &clean_list);
1861         spin_unlock(&obd->obd_recovery_task_lock);
1862
1863         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1864                 LASSERT(req->rq_reply_state == NULL);
1865                 target_request_copy_put(req);
1866         }
1867
1868         EXIT;
1869 }
1870 EXPORT_SYMBOL(target_cleanup_recovery);
1871
1872 /* obd_recovery_task_lock should be held */
1873 void target_cancel_recovery_timer(struct obd_device *obd)
1874 {
1875         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1876         hrtimer_cancel(&obd->obd_recovery_timer);
1877 }
1878
1879 static void target_start_recovery_timer(struct obd_device *obd)
1880 {
1881         ktime_t delay;
1882
1883         if (obd->obd_recovery_start != 0)
1884                 return;
1885
1886         spin_lock(&obd->obd_dev_lock);
1887         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1888                 spin_unlock(&obd->obd_dev_lock);
1889                 return;
1890         }
1891
1892         LASSERT(obd->obd_recovery_timeout != 0);
1893
1894         if (obd->obd_recovery_start != 0) {
1895                 spin_unlock(&obd->obd_dev_lock);
1896                 return;
1897         }
1898
1899         obd->obd_recovery_start = ktime_get_seconds();
1900         delay = ktime_set(obd->obd_recovery_start +
1901                           obd->obd_recovery_timeout, 0);
1902         hrtimer_start(&obd->obd_recovery_timer, delay, HRTIMER_MODE_ABS);
1903         spin_unlock(&obd->obd_dev_lock);
1904
1905         LCONSOLE_WARN("%s: Will be in recovery for at least %u:%02u, or until %d client%s reconnect%s\n",
1906                       obd->obd_name,
1907                       obd->obd_recovery_timeout / 60,
1908                       obd->obd_recovery_timeout % 60,
1909                       atomic_read(&obd->obd_max_recoverable_clients),
1910                       (atomic_read(&obd->obd_max_recoverable_clients) == 1) ?
1911                       "" : "s",
1912                       (atomic_read(&obd->obd_max_recoverable_clients) == 1) ?
1913                       "s" : "");
1914 }
1915
1916 /**
1917  * extend recovery window.
1918  *
1919  * if @extend is true, extend recovery window to have @dr_timeout remaining
1920  * at least; otherwise, make sure the recovery timeout value is not less
1921  * than @dr_timeout.
1922  */
1923 static void extend_recovery_timer(struct obd_device *obd, timeout_t dr_timeout,
1924                                   bool extend)
1925 {
1926         ktime_t left_ns;
1927         timeout_t timeout;
1928         timeout_t left;
1929
1930         spin_lock(&obd->obd_dev_lock);
1931         if (!obd->obd_recovering || obd->obd_abort_recovery ||
1932             obd->obd_stopping) {
1933                 spin_unlock(&obd->obd_dev_lock);
1934                 return;
1935         }
1936         LASSERT(obd->obd_recovery_start != 0);
1937
1938         left_ns = hrtimer_get_remaining(&obd->obd_recovery_timer);
1939         left = ktime_divns(left_ns, NSEC_PER_SEC);
1940
1941         if (extend) {
1942                 timeout = obd->obd_recovery_timeout;
1943                 /* dr_timeout will happen after the hrtimer has expired.
1944                  * Add the excess time to the soft recovery timeout without
1945                  * exceeding the hard recovery timeout.
1946                  */
1947                 if (dr_timeout > left) {
1948                         timeout += dr_timeout - left;
1949                         timeout = min_t(timeout_t, obd->obd_recovery_time_hard,
1950                                         timeout);
1951                 }
1952         } else {
1953                 timeout = clamp_t(timeout_t, dr_timeout,
1954                                   obd->obd_recovery_timeout,
1955                                   obd->obd_recovery_time_hard);
1956         }
1957
1958         if (timeout == obd->obd_recovery_time_hard)
1959                 CWARN("%s: extended recovery timer reached hard limit: %d, extend: %d\n",
1960                       obd->obd_name, timeout, extend);
1961
1962         if (obd->obd_recovery_timeout < timeout) {
1963                 ktime_t end, now;
1964
1965                 obd->obd_recovery_timeout = timeout;
1966                 end = ktime_set(obd->obd_recovery_start + timeout, 0);
1967                 now = ktime_set(ktime_get_seconds(), 0);
1968                 left_ns = ktime_sub(end, now);
1969                 hrtimer_start(&obd->obd_recovery_timer, end, HRTIMER_MODE_ABS);
1970                 left = ktime_divns(left_ns, NSEC_PER_SEC);
1971         }
1972         spin_unlock(&obd->obd_dev_lock);
1973
1974         CDEBUG(D_HA, "%s: recovery timer will expire in %d seconds\n",
1975                 obd->obd_name, left);
1976 }
1977
1978 /* Reset the timer with each new client connection */
1979 /*
1980  * This timer is actually reconnect_timer, which is for making sure
1981  * the total recovery window is at least as big as my reconnect
1982  * attempt timing. So the initial recovery time_out will be set to
1983  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1984  * from client is bigger than this, then the recovery time_out will
1985  * be extended to make sure the client could be reconnected, in the
1986  * process, the timeout from the new client should be ignored.
1987  */
1988 static void
1989 check_and_start_recovery_timer(struct obd_device *obd,
1990                                struct ptlrpc_request *req,
1991                                int new_client)
1992 {
1993         timeout_t service_timeout = lustre_msg_get_service_timeout(req->rq_reqmsg);
1994         struct obd_device_target *obt = &obd->u.obt;
1995
1996         if (!new_client && service_timeout)
1997                 /*
1998                  * Teach server about old server's estimates, as first guess
1999                  * at how long new requests will take.
2000                  */
2001                 at_measured(&req->rq_rqbd->rqbd_svcpt->scp_at_estimate,
2002                             service_timeout);
2003
2004         target_start_recovery_timer(obd);
2005
2006         /*
2007          * Convert the service time to RPC timeout,
2008          * and reuse service_timeout to limit stack usage.
2009          */
2010         service_timeout = at_est2timeout(service_timeout);
2011
2012         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_SLUGGISH_NET) &&
2013             service_timeout < at_extra)
2014                 service_timeout = at_extra;
2015
2016         /*
2017          * We expect other clients to timeout within service_timeout, then try
2018          * to reconnect, then try the failover server.  The max delay between
2019          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL.
2020          */
2021         service_timeout += 2 * INITIAL_CONNECT_TIMEOUT;
2022
2023         LASSERT(obt->obt_magic == OBT_MAGIC);
2024         service_timeout += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
2025         if (service_timeout > obd->obd_recovery_timeout && !new_client)
2026                 extend_recovery_timer(obd, service_timeout, false);
2027 }
2028
2029 /** Health checking routines */
2030 static inline int exp_connect_healthy(struct obd_export *exp)
2031 {
2032         return exp->exp_in_recovery;
2033 }
2034
2035 /** if export done req_replay or has replay in queue */
2036 static inline int exp_req_replay_healthy(struct obd_export *exp)
2037 {
2038         return (!exp->exp_req_replay_needed ||
2039                 atomic_read(&exp->exp_replay_count) > 0);
2040 }
2041
2042
2043 static inline int exp_req_replay_healthy_or_from_mdt(struct obd_export *exp)
2044 {
2045         return (exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) ||
2046                exp_req_replay_healthy(exp);
2047 }
2048
2049 /** if export done lock_replay or has replay in queue */
2050 static inline int exp_lock_replay_healthy(struct obd_export *exp)
2051 {
2052         return (!exp->exp_lock_replay_needed ||
2053                 atomic_read(&exp->exp_replay_count) > 0);
2054 }
2055
2056 static inline int exp_vbr_healthy(struct obd_export *exp)
2057 {
2058         return !exp->exp_vbr_failed;
2059 }
2060
2061 static inline int exp_finished(struct obd_export *exp)
2062 {
2063         return exp->exp_in_recovery && !exp->exp_lock_replay_needed;
2064 }
2065
2066 static inline int exp_finished_or_from_mdt(struct obd_export *exp)
2067 {
2068         return (exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) ||
2069                 exp_finished(exp);
2070 }
2071
2072 static int check_for_next_transno(struct lu_target *lut)
2073 {
2074         struct ptlrpc_request *req = NULL;
2075         struct obd_device *obd = lut->lut_obd;
2076         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2077         int wake_up = 0, connected, completed, queue_len;
2078         __u64 req_transno = 0;
2079         __u64 update_transno = 0;
2080         __u64 next_transno = 0;
2081
2082         ENTRY;
2083
2084         spin_lock(&obd->obd_recovery_task_lock);
2085         if (!list_empty(&obd->obd_req_replay_queue)) {
2086                 req = list_entry(obd->obd_req_replay_queue.next,
2087                                      struct ptlrpc_request, rq_list);
2088                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
2089         }
2090
2091         if (!obd->obd_abort_recov_mdt && tdtd)
2092                 update_transno = distribute_txn_get_next_transno(tdtd);
2093
2094         connected = atomic_read(&obd->obd_connected_clients);
2095         completed = connected - atomic_read(&obd->obd_req_replay_clients);
2096         queue_len = obd->obd_requests_queued_for_recovery;
2097         next_transno = obd->obd_next_recovery_transno;
2098
2099         CDEBUG(D_HA,
2100                "max: %d, connected: %d, completed: %d, queue_len: %d, req_transno: %llu, next_transno: %llu\n",
2101                atomic_read(&obd->obd_max_recoverable_clients),
2102                connected, completed,
2103                queue_len, req_transno, next_transno);
2104
2105         if (obd->obd_abort_recovery) {
2106                 CDEBUG(D_HA, "waking for aborted recovery\n");
2107                 wake_up = 1;
2108         } else if (obd->obd_recovery_expired) {
2109                 CDEBUG(D_HA, "waking for expired recovery\n");
2110                 wake_up = 1;
2111         } else if (!obd->obd_abort_recov_mdt && tdtd && req &&
2112                    is_req_replayed_by_update(req)) {
2113                 LASSERTF(req_transno < next_transno,
2114                          "req_transno %llu next_transno%llu\n", req_transno,
2115                          next_transno);
2116                 CDEBUG(D_HA, "waking for duplicate req (%llu)\n",
2117                        req_transno);
2118                 wake_up = 1;
2119         } else if (req_transno == next_transno ||
2120                    (update_transno != 0 && update_transno <= next_transno)) {
2121                 CDEBUG(D_HA, "waking for next (%lld)\n", next_transno);
2122                 wake_up = 1;
2123         } else if (queue_len > 0 &&
2124                    queue_len == atomic_read(&obd->obd_req_replay_clients)) {
2125                 /** handle gaps occured due to lost reply or VBR */
2126                 LASSERTF(req_transno >= next_transno,
2127                          "req_transno: %llu, next_transno: %llu\n",
2128                          req_transno, next_transno);
2129                 CDEBUG(D_HA,
2130                        "%s: waking for gap in transno, VBR is %s (skip: %lld, ql: %d, comp: %d, conn: %d, next: %lld, next_update %lld last_committed: %lld)\n",
2131                        obd->obd_name, obd->obd_version_recov ? "ON" : "OFF",
2132                        next_transno, queue_len, completed, connected,
2133                        req_transno, update_transno, obd->obd_last_committed);
2134                 obd->obd_next_recovery_transno = req_transno;
2135                 wake_up = 1;
2136         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
2137                 CDEBUG(D_HA, "waking for completed recovery\n");
2138                 wake_up = 1;
2139         } else if (OBD_FAIL_CHECK(OBD_FAIL_MDS_RECOVERY_ACCEPTS_GAPS)) {
2140                 CDEBUG(D_HA,
2141                        "accepting transno gaps is explicitly allowed by fail_lock, waking up (%lld)\n",
2142                        next_transno);
2143                 obd->obd_next_recovery_transno = req_transno;
2144                 wake_up = 1;
2145         }
2146         spin_unlock(&obd->obd_recovery_task_lock);
2147         return wake_up;
2148 }
2149
2150 static int check_for_next_lock(struct lu_target *lut)
2151 {
2152         struct obd_device *obd = lut->lut_obd;
2153         int wake_up = 0;
2154
2155         spin_lock(&obd->obd_recovery_task_lock);
2156         if (!list_empty(&obd->obd_lock_replay_queue)) {
2157                 CDEBUG(D_HA, "waking for next lock\n");
2158                 wake_up = 1;
2159         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
2160                 CDEBUG(D_HA, "waking for completed lock replay\n");
2161                 wake_up = 1;
2162         } else if (obd->obd_abort_recovery) {
2163                 CDEBUG(D_HA, "waking for aborted recovery\n");
2164                 wake_up = 1;
2165         } else if (obd->obd_recovery_expired) {
2166                 CDEBUG(D_HA, "waking for expired recovery\n");
2167                 wake_up = 1;
2168         }
2169         spin_unlock(&obd->obd_recovery_task_lock);
2170
2171         return wake_up;
2172 }
2173
2174 static int check_update_llog(struct lu_target *lut)
2175 {
2176         struct obd_device *obd = lut->lut_obd;
2177         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2178
2179         if (obd->obd_abort_recovery) {
2180                 CDEBUG(D_HA, "waking for aborted recovery\n");
2181                 return 1;
2182         }
2183
2184         if (atomic_read(&tdtd->tdtd_recovery_threads_count) == 0) {
2185                 CDEBUG(D_HA, "waking for completion of reading update log\n");
2186                 return 1;
2187         }
2188
2189         return 0;
2190 }
2191
2192 /**
2193  * wait for recovery events,
2194  * check its status with help of check_routine
2195  * evict dead clients via health_check
2196  */
2197 static int target_recovery_overseer(struct lu_target *lut,
2198                                     int (*check_routine)(struct lu_target *),
2199                                     int (*health_check)(struct obd_export *))
2200 {
2201         struct obd_device *obd = lut->lut_obd;
2202         struct target_distribute_txn_data *tdtd;
2203         time64_t last = 0;
2204         time64_t now;
2205 repeat:
2206         if (obd->obd_recovering && obd->obd_recovery_start == 0) {
2207                 now = ktime_get_seconds();
2208                 if (now - last > 600) {
2209                         LCONSOLE_INFO("%s: in recovery but waiting for the first client to connect\n",
2210                                       obd->obd_name);
2211                         last = now;
2212                 }
2213         }
2214         if (obd->obd_recovery_start != 0 && ktime_get_seconds() >=
2215               (obd->obd_recovery_start + obd->obd_recovery_time_hard)) {
2216                 __u64 next_update_transno = 0;
2217
2218                 /*
2219                  * Only abort the recovery if there are no update recovery
2220                  * left in the queue
2221                  */
2222                 spin_lock(&obd->obd_recovery_task_lock);
2223                 if (!obd->obd_abort_recov_mdt && lut->lut_tdtd) {
2224                         next_update_transno =
2225                                 distribute_txn_get_next_transno(lut->lut_tdtd);
2226
2227                         tdtd = lut->lut_tdtd;
2228                         /*
2229                          * If next_update_transno == 0, it probably because
2230                          * updatelog retrieve threads did not get any records
2231                          * yet, let's wait those threads stopped
2232                          */
2233                         if (next_update_transno == 0) {
2234                                 spin_unlock(&obd->obd_recovery_task_lock);
2235
2236                                 while (wait_event_timeout(
2237                                         tdtd->tdtd_recovery_threads_waitq,
2238                                         check_update_llog(lut),
2239                                         cfs_time_seconds(60)) == 0);
2240
2241                                 spin_lock(&obd->obd_recovery_task_lock);
2242                                 next_update_transno =
2243                                         distribute_txn_get_next_transno(tdtd);
2244                         }
2245                 }
2246
2247                 if (next_update_transno != 0 && !obd->obd_abort_recovery) {
2248                         obd->obd_next_recovery_transno = next_update_transno;
2249                         spin_unlock(&obd->obd_recovery_task_lock);
2250                         /*
2251                          * Disconnect unfinished exports from clients, and
2252                          * keep connection from MDT to make sure the update
2253                          * recovery will still keep trying until some one
2254                          * manually abort the recovery
2255                          */
2256                         class_disconnect_stale_exports(obd,
2257                                                 exp_finished_or_from_mdt);
2258                         /* Abort all of replay & replay lock req from clients */
2259                         abort_req_replay_queue(obd);
2260                         abort_lock_replay_queue(obd);
2261                         CDEBUG(D_HA,
2262                                "%s: there are still update replay (%#llx)in the queue.\n",
2263                                obd->obd_name, next_update_transno);
2264                 } else {
2265                         obd->obd_abort_recovery = 1;
2266                         spin_unlock(&obd->obd_recovery_task_lock);
2267                         CWARN("%s recovery is aborted by hard timeout\n",
2268                               obd->obd_name);
2269                 }
2270         }
2271
2272         while (wait_event_timeout(obd->obd_next_transno_waitq,
2273                                   check_routine(lut),
2274                                   cfs_time_seconds(60)) == 0)
2275                 ; /* wait indefinitely for event, but don't trigger watchdog */
2276
2277         if (obd->obd_abort_recovery) {
2278                 CWARN("recovery is aborted, evict exports in recovery\n");
2279                 if (lut->lut_tdtd != NULL) {
2280                         tdtd = lut->lut_tdtd;
2281                         /*
2282                          * Let's wait all of the update log recovery thread
2283                          * finished
2284                          */
2285                         wait_event_idle(
2286                                 tdtd->tdtd_recovery_threads_waitq,
2287                                 atomic_read(&tdtd->tdtd_recovery_threads_count)
2288                                 == 0);
2289                         /* Then abort the update recovery list */
2290                         dtrq_list_destroy(lut->lut_tdtd);
2291                 }
2292
2293                 /** evict exports which didn't finish recovery yet */
2294                 class_disconnect_stale_exports(obd, exp_finished);
2295                 return 1;
2296         } else if (obd->obd_recovery_expired) {
2297                 obd->obd_recovery_expired = 0;
2298
2299                 /** If some clients died being recovered, evict them */
2300                 LCONSOLE_WARN("%s: recovery is timed out, evict stale exports\n",
2301                               obd->obd_name);
2302                 /** evict cexports with no replay in queue, they are stalled */
2303                 class_disconnect_stale_exports(obd, health_check);
2304
2305                 /** continue with VBR */
2306                 spin_lock(&obd->obd_dev_lock);
2307                 obd->obd_version_recov = 1;
2308                 spin_unlock(&obd->obd_dev_lock);
2309                 /**
2310                  * reset timer, recovery will proceed with versions now,
2311                  * timeout is set just to handle reconnection delays
2312                  */
2313                 extend_recovery_timer(obd, RECONNECT_DELAY_MAX, true);
2314                 /**
2315                  * Wait for recovery events again, after evicting bad clients
2316                  */
2317                 goto repeat;
2318         }
2319         return 0;
2320 }
2321
2322 static struct ptlrpc_request *target_next_replay_lock(struct lu_target *lut)
2323 {
2324         struct obd_device *obd = lut->lut_obd;
2325         struct ptlrpc_request *req = NULL;
2326
2327         CDEBUG(D_HA, "Waiting for lock\n");
2328         if (target_recovery_overseer(lut, check_for_next_lock,
2329                                      exp_lock_replay_healthy))
2330                 abort_lock_replay_queue(obd);
2331
2332         spin_lock(&obd->obd_recovery_task_lock);
2333         if (!list_empty(&obd->obd_lock_replay_queue)) {
2334                 req = list_entry(obd->obd_lock_replay_queue.next,
2335                                      struct ptlrpc_request, rq_list);
2336                 list_del_init(&req->rq_list);
2337                 spin_unlock(&obd->obd_recovery_task_lock);
2338         } else {
2339                 spin_unlock(&obd->obd_recovery_task_lock);
2340                 LASSERT(list_empty(&obd->obd_lock_replay_queue));
2341                 LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
2342                 /** evict exports failed VBR */
2343                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
2344         }
2345         return req;
2346 }
2347
2348 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
2349 {
2350         struct ptlrpc_request *req = NULL;
2351
2352         spin_lock(&obd->obd_recovery_task_lock);
2353         if (!list_empty(&obd->obd_final_req_queue)) {
2354                 req = list_entry(obd->obd_final_req_queue.next,
2355                                      struct ptlrpc_request, rq_list);
2356                 list_del_init(&req->rq_list);
2357                 spin_unlock(&obd->obd_recovery_task_lock);
2358                 if (req->rq_export->exp_in_recovery) {
2359                         spin_lock(&req->rq_export->exp_lock);
2360                         req->rq_export->exp_in_recovery = 0;
2361                         spin_unlock(&req->rq_export->exp_lock);
2362                 }
2363         } else {
2364                 spin_unlock(&obd->obd_recovery_task_lock);
2365         }
2366         return req;
2367 }
2368
2369 static void handle_recovery_req(struct ptlrpc_thread *thread,
2370                                 struct ptlrpc_request *req,
2371                                 svc_handler_t handler)
2372 {
2373         ENTRY;
2374
2375         /**
2376          * export can be evicted during recovery, no need to handle replays for
2377          * it after that, discard such request silently
2378          */
2379         if (req->rq_export->exp_disconnected)
2380                 RETURN_EXIT;
2381
2382         req->rq_session.lc_thread = thread;
2383         req->rq_svc_thread = thread;
2384         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
2385
2386         /* thread context */
2387         lu_context_enter(&thread->t_env->le_ctx);
2388         (void)handler(req);
2389         lu_context_exit(&thread->t_env->le_ctx);
2390
2391         req->rq_svc_thread->t_env->le_ses = NULL;
2392
2393         /* don't reset timer for final stage */
2394         if (!exp_finished(req->rq_export)) {
2395                 timeout_t timeout = obd_timeout;
2396
2397                 /**
2398                  * Add request @timeout to the recovery time so next request from
2399                  * this client may come in recovery time
2400                  */
2401                 if (!AT_OFF) {
2402                         struct ptlrpc_service_part *svcpt;
2403                         timeout_t est_timeout;
2404
2405                         svcpt = req->rq_rqbd->rqbd_svcpt;
2406                         /*
2407                          * If the server sent early reply for this request,
2408                          * the client will recalculate the timeout according to
2409                          * current server estimate service time, so we will
2410                          * use the maxium timeout here for waiting the client
2411                          * sending the next req
2412                          */
2413                         est_timeout = at_get(&svcpt->scp_at_estimate);
2414                         timeout = max_t(timeout_t, at_est2timeout(est_timeout),
2415                                         lustre_msg_get_timeout(req->rq_reqmsg));
2416                         /*
2417                          * Add 2 net_latency, one for balance rq_deadline
2418                          * (see ptl_send_rpc), one for resend the req to server,
2419                          * Note: client will pack net_latency in replay req
2420                          * (see ptlrpc_replay_req)
2421                          */
2422                         timeout += 2 * lustre_msg_get_service_timeout(req->rq_reqmsg);
2423                 }
2424                 extend_recovery_timer(class_exp2obd(req->rq_export), timeout,
2425                                       true);
2426         }
2427         EXIT;
2428 }
2429
2430 /** Checking routines for recovery */
2431 static int check_for_recovery_ready(struct lu_target *lut)
2432 {
2433         struct obd_device *obd = lut->lut_obd;
2434         unsigned int clnts = atomic_read(&obd->obd_connected_clients);
2435
2436         CDEBUG(D_HA,
2437                "connected %d stale %d max_recoverable_clients %d abort %d expired %d\n",
2438                clnts, obd->obd_stale_clients,
2439                atomic_read(&obd->obd_max_recoverable_clients),
2440                obd->obd_abort_recovery, obd->obd_recovery_expired);
2441
2442         if (!obd->obd_abort_recovery && !obd->obd_recovery_expired) {
2443                 LASSERT(clnts <=
2444                         atomic_read(&obd->obd_max_recoverable_clients));
2445                 if (clnts + obd->obd_stale_clients <
2446                     atomic_read(&obd->obd_max_recoverable_clients))
2447                         return 0;
2448         }
2449
2450         if (!obd->obd_abort_recov_mdt && lut->lut_tdtd != NULL) {
2451                 if (!lut->lut_tdtd->tdtd_replay_ready &&
2452                     !obd->obd_abort_recovery && !obd->obd_stopping) {
2453                         /*
2454                          * Let's extend recovery timer, in case the recovery
2455                          * timer expired, and some clients got evicted
2456                          */
2457                         extend_recovery_timer(obd, obd->obd_recovery_timeout,
2458                                               true);
2459                         CDEBUG(D_HA,
2460                                "%s update recovery is not ready, extend recovery %d\n",
2461                                obd->obd_name, obd->obd_recovery_timeout);
2462                         return 0;
2463                 }
2464         }
2465
2466         return 1;
2467 }
2468
2469 enum {
2470         REQUEST_RECOVERY = 1,
2471         UPDATE_RECOVERY = 2,
2472 };
2473
2474 static __u64 get_next_replay_req_transno(struct obd_device *obd)
2475 {
2476         __u64 transno = 0;
2477
2478         if (!list_empty(&obd->obd_req_replay_queue)) {
2479                 struct ptlrpc_request *req;
2480
2481                 req = list_entry(obd->obd_req_replay_queue.next,
2482                                  struct ptlrpc_request, rq_list);
2483                 transno = lustre_msg_get_transno(req->rq_reqmsg);
2484         }
2485
2486         return transno;
2487 }
2488
2489 static __u64 get_next_transno(struct lu_target *lut, int *type)
2490 {
2491         struct obd_device *obd = lut->lut_obd;
2492         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2493         __u64 transno = 0;
2494         __u64 update_transno;
2495
2496         ENTRY;
2497
2498         transno = get_next_replay_req_transno(obd);
2499         if (type != NULL)
2500                 *type = REQUEST_RECOVERY;
2501
2502         if (!tdtd || obd->obd_abort_recov_mdt)
2503                 RETURN(transno);
2504
2505         update_transno = distribute_txn_get_next_transno(tdtd);
2506         if (transno == 0 || (transno >= update_transno &&
2507                              update_transno != 0)) {
2508                 transno = update_transno;
2509                 if (type != NULL)
2510                         *type = UPDATE_RECOVERY;
2511         }
2512
2513         RETURN(transno);
2514 }
2515
2516 /**
2517  * drop duplicate replay request
2518  *
2519  * Because the operation has been replayed by update recovery, the request
2520  * with the same transno will be dropped and also notify the client to send
2521  * next replay request.
2522  *
2523  * \param[in] env       execution environment
2524  * \param[in] obd       failover obd device
2525  * \param[in] req       request to be dropped
2526  */
2527 static void drop_duplicate_replay_req(struct lu_env *env,
2528                                       struct obd_device *obd,
2529                                       struct ptlrpc_request *req)
2530 {
2531         DEBUG_REQ(D_HA, req,
2532                   "remove t%lld from %s because duplicate update records found",
2533                   lustre_msg_get_transno(req->rq_reqmsg),
2534                   libcfs_nid2str(req->rq_peer.nid));
2535
2536         /*
2537          * Right now, only for MDS reint operation update replay and
2538          * normal request replay can have the same transno
2539          */
2540         if (lustre_msg_get_opc(req->rq_reqmsg) == MDS_REINT) {
2541                 req_capsule_set(&req->rq_pill, &RQF_MDS_REINT);
2542                 req->rq_status = req_capsule_server_pack(&req->rq_pill);
2543                 if (likely(req->rq_export))
2544                         target_committed_to_req(req);
2545                 lustre_msg_set_transno(req->rq_repmsg, req->rq_transno);
2546                 target_send_reply(req, req->rq_status, 0);
2547         } else {
2548                 DEBUG_REQ(D_ERROR, req, "wrong opc from %s",
2549                 libcfs_nid2str(req->rq_peer.nid));
2550         }
2551         target_exp_dequeue_req_replay(req);
2552         target_request_copy_put(req);
2553         obd->obd_replayed_requests++;
2554 }
2555
2556 #define WATCHDOG_TIMEOUT (obd_timeout * 10)
2557
2558 static void replay_request_or_update(struct lu_env *env,
2559                                      struct lu_target *lut,
2560                                      struct target_recovery_data *trd,
2561                                      struct ptlrpc_thread *thread)
2562 {
2563         struct obd_device *obd = lut->lut_obd;
2564         struct ptlrpc_request *req = NULL;
2565         int type;
2566         __u64 transno;
2567
2568         ENTRY;
2569
2570         CDEBUG(D_HA, "Waiting for transno %lld\n",
2571                obd->obd_next_recovery_transno);
2572
2573         /* Replay all of request and update by transno */
2574         do {
2575                 struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2576
2577                 CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_DELAY2, cfs_fail_val);
2578
2579                 /**
2580                  * It is needed to extend recovery window above
2581                  *  recovery_time_soft. Extending is possible only in the
2582                  *  end of recovery window (see more details in
2583                  *  handle_recovery_req()).
2584                  */
2585                 CFS_FAIL_TIMEOUT_MS(OBD_FAIL_TGT_REPLAY_DELAY, 300);
2586
2587                 if (target_recovery_overseer(lut, check_for_next_transno,
2588                                         exp_req_replay_healthy_or_from_mdt)) {
2589                         abort_req_replay_queue(obd);
2590                         abort_lock_replay_queue(obd);
2591                         goto abort;
2592                 }
2593
2594                 spin_lock(&obd->obd_recovery_task_lock);
2595                 transno = get_next_transno(lut, &type);
2596                 if (type == REQUEST_RECOVERY && transno != 0) {
2597                         /*
2598                          * Drop replay request from client side, if the
2599                          * replay has been executed by update with the
2600                          * same transno
2601                          */
2602                         req = list_entry(obd->obd_req_replay_queue.next,
2603                                         struct ptlrpc_request, rq_list);
2604
2605                         list_del_init(&req->rq_list);
2606                         obd->obd_requests_queued_for_recovery--;
2607                         spin_unlock(&obd->obd_recovery_task_lock);
2608
2609                         /*
2610                          * Let's check if the request has been redone by
2611                          * update replay
2612                          */
2613                         if (is_req_replayed_by_update(req)) {
2614                                 struct distribute_txn_replay_req *dtrq;
2615
2616                                 dtrq = distribute_txn_lookup_finish_list(tdtd,
2617                                                                       transno);
2618                                 LASSERT(dtrq != NULL);
2619                                 spin_lock(&tdtd->tdtd_replay_list_lock);
2620                                 list_del_init(&dtrq->dtrq_list);
2621                                 spin_unlock(&tdtd->tdtd_replay_list_lock);
2622                                 dtrq_destroy(dtrq);
2623
2624                                 drop_duplicate_replay_req(env, obd, req);
2625
2626                                 continue;
2627                         }
2628
2629                         LASSERT(trd->trd_processing_task == current->pid);
2630                         DEBUG_REQ(D_HA, req, "processing x%llu t%lld from %s",
2631                                   req->rq_xid,
2632                                   lustre_msg_get_transno(req->rq_reqmsg),
2633                                   libcfs_nid2str(req->rq_peer.nid));
2634
2635                         ptlrpc_watchdog_init(&thread->t_watchdog,
2636                                              WATCHDOG_TIMEOUT);
2637                         handle_recovery_req(thread, req,
2638                                             trd->trd_recovery_handler);
2639                         ptlrpc_watchdog_disable(&thread->t_watchdog);
2640
2641                         /**
2642                          * bz18031: increase next_recovery_transno before
2643                          * target_request_copy_put() will drop exp_rpc reference
2644                          */
2645                         spin_lock(&obd->obd_recovery_task_lock);
2646                         obd->obd_next_recovery_transno++;
2647                         spin_unlock(&obd->obd_recovery_task_lock);
2648                         target_exp_dequeue_req_replay(req);
2649                         target_request_copy_put(req);
2650                         obd->obd_replayed_requests++;
2651                 } else if (type == UPDATE_RECOVERY && transno != 0) {
2652                         struct distribute_txn_replay_req *dtrq;
2653                         int rc;
2654
2655                         spin_unlock(&obd->obd_recovery_task_lock);
2656
2657                         LASSERT(tdtd != NULL);
2658                         dtrq = distribute_txn_get_next_req(tdtd);
2659                         lu_context_enter(&thread->t_env->le_ctx);
2660                         ptlrpc_watchdog_init(&thread->t_watchdog,
2661                                              WATCHDOG_TIMEOUT);
2662                         rc = tdtd->tdtd_replay_handler(env, tdtd, dtrq);
2663                         ptlrpc_watchdog_disable(&thread->t_watchdog);
2664                         lu_context_exit(&thread->t_env->le_ctx);
2665                         extend_recovery_timer(obd, obd_timeout, true);
2666
2667                         if (rc == 0 && dtrq->dtrq_xid != 0) {
2668                                 CDEBUG(D_HA,
2669                                        "Move x%llu t%llu to finish list\n",
2670                                        dtrq->dtrq_xid,
2671                                        dtrq->dtrq_master_transno);
2672
2673                                 /* Add it to the replay finish list */
2674                                 spin_lock(&tdtd->tdtd_replay_list_lock);
2675                                 list_add(&dtrq->dtrq_list,
2676                                          &tdtd->tdtd_replay_finish_list);
2677                                 spin_unlock(&tdtd->tdtd_replay_list_lock);
2678
2679                                 spin_lock(&obd->obd_recovery_task_lock);
2680                                 if (transno == obd->obd_next_recovery_transno)
2681                                         obd->obd_next_recovery_transno++;
2682                                 else if (transno >
2683                                          obd->obd_next_recovery_transno)
2684                                         obd->obd_next_recovery_transno =
2685                                                                 transno + 1;
2686                                 spin_unlock(&obd->obd_recovery_task_lock);
2687                         } else {
2688                                 dtrq_destroy(dtrq);
2689                         }
2690                 } else {
2691                         spin_unlock(&obd->obd_recovery_task_lock);
2692 abort:
2693                         LASSERT(list_empty(&obd->obd_req_replay_queue));
2694                         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
2695                         /** evict exports failed VBR */
2696                         class_disconnect_stale_exports(obd, exp_vbr_healthy);
2697                         break;
2698                 }
2699         } while (1);
2700 }
2701
2702 static int target_recovery_thread(void *arg)
2703 {
2704         struct lu_target *lut = arg;
2705         struct obd_device *obd = lut->lut_obd;
2706         struct ptlrpc_request *req;
2707         struct target_recovery_data *trd = &obd->obd_recovery_data;
2708         unsigned long delta;
2709         struct lu_env *env;
2710         struct ptlrpc_thread *thread = NULL;
2711         int rc = 0;
2712
2713         ENTRY;
2714         OBD_ALLOC_PTR(thread);
2715         if (thread == NULL)
2716                 RETURN(-ENOMEM);
2717
2718         OBD_ALLOC_PTR(env);
2719         if (env == NULL)
2720                 GOTO(out_thread, rc = -ENOMEM);
2721         rc = lu_env_add(env);
2722         if (rc)
2723                 GOTO(out_env, rc);
2724
2725         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD);
2726         if (rc)
2727                 GOTO(out_env_remove, rc);
2728
2729         thread->t_env = env;
2730         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
2731         thread->t_task = current;
2732         env->le_ctx.lc_thread = thread;
2733         tgt_io_thread_init(thread); /* init thread_big_cache for IO requests */
2734
2735         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
2736                current->pid);
2737         trd->trd_processing_task = current->pid;
2738
2739         spin_lock(&obd->obd_dev_lock);
2740         obd->obd_recovering = 1;
2741         spin_unlock(&obd->obd_dev_lock);
2742         complete(&trd->trd_starting);
2743
2744         /* first of all, we have to know the first transno to replay */
2745         if (target_recovery_overseer(lut, check_for_recovery_ready,
2746                                      exp_connect_healthy)) {
2747                 abort_req_replay_queue(obd);
2748                 abort_lock_replay_queue(obd);
2749                 if (lut->lut_tdtd != NULL)
2750                         dtrq_list_destroy(lut->lut_tdtd);
2751         }
2752
2753         /* next stage: replay requests or update */
2754         delta = jiffies;
2755         CDEBUG(D_INFO, "1: request replay stage - %d clients from t%llu\n",
2756                atomic_read(&obd->obd_req_replay_clients),
2757                obd->obd_next_recovery_transno);
2758         replay_request_or_update(env, lut, trd, thread);
2759
2760         /**
2761          * The second stage: replay locks
2762          */
2763         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
2764                atomic_read(&obd->obd_lock_replay_clients));
2765         while ((req = target_next_replay_lock(lut))) {
2766                 LASSERT(trd->trd_processing_task == current->pid);
2767                 DEBUG_REQ(D_HA, req, "processing lock from %s:",
2768                           libcfs_nid2str(req->rq_peer.nid));
2769                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_LOCK_REPLAY)) {
2770                         req->rq_status = -ENODEV;
2771                         target_request_copy_put(req);
2772                         continue;
2773                 }
2774                 handle_recovery_req(thread, req,
2775                                     trd->trd_recovery_handler);
2776                 target_request_copy_put(req);
2777                 obd->obd_replayed_locks++;
2778         }
2779
2780         /**
2781          * The third stage: reply on final pings, at this moment all clients
2782          * must have request in final queue
2783          */
2784         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_RECONNECT, cfs_fail_val);
2785         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
2786         /** Update server last boot epoch */
2787         tgt_boot_epoch_update(lut);
2788         /*
2789          * We drop recoverying flag to forward all new requests
2790          * to regular mds_handle() since now
2791          */
2792         spin_lock(&obd->obd_dev_lock);
2793         obd->obd_recovering = obd->obd_abort_recovery = 0;
2794         spin_unlock(&obd->obd_dev_lock);
2795         spin_lock(&obd->obd_recovery_task_lock);
2796         target_cancel_recovery_timer(obd);
2797         spin_unlock(&obd->obd_recovery_task_lock);
2798         while ((req = target_next_final_ping(obd))) {
2799                 LASSERT(trd->trd_processing_task == current->pid);
2800                 DEBUG_REQ(D_HA, req, "processing final ping from %s:",
2801                           libcfs_nid2str(req->rq_peer.nid));
2802                 handle_recovery_req(thread, req,
2803                                     trd->trd_recovery_handler);
2804                 /*
2805                  * Because the waiting client can not send ping to server,
2806                  * so we need refresh the last_request_time, to avoid the
2807                  * export is being evicted
2808                  */
2809                 ptlrpc_update_export_timer(req->rq_export, 0);
2810                 target_request_copy_put(req);
2811         }
2812
2813         delta = jiffies_to_msecs(jiffies - delta) / MSEC_PER_SEC;
2814         CDEBUG(D_INFO, "4: recovery completed in %lus - %d/%d reqs/locks\n",
2815                delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
2816         if (delta > OBD_RECOVERY_TIME_SOFT) {
2817                 CWARN("too long recovery - read logs\n");
2818                 libcfs_debug_dumplog();
2819         }
2820
2821         target_finish_recovery(lut);
2822         lu_context_fini(&env->le_ctx);
2823         trd->trd_processing_task = 0;
2824         complete_all(&trd->trd_finishing);
2825         tgt_io_thread_done(thread);
2826 out_env_remove:
2827         lu_env_remove(env);
2828 out_env:
2829         OBD_FREE_PTR(env);
2830 out_thread:
2831         OBD_FREE_PTR(thread);
2832         RETURN(rc);
2833 }
2834
2835 static int target_start_recovery_thread(struct lu_target *lut,
2836                                         svc_handler_t handler)
2837 {
2838         struct obd_device *obd = lut->lut_obd;
2839         int rc = 0;
2840         struct target_recovery_data *trd = &obd->obd_recovery_data;
2841         int index;
2842
2843         memset(trd, 0, sizeof(*trd));
2844         init_completion(&trd->trd_starting);
2845         init_completion(&trd->trd_finishing);
2846         trd->trd_recovery_handler = handler;
2847
2848         rc = server_name2index(obd->obd_name, &index, NULL);
2849         if (rc < 0)
2850                 return rc;
2851
2852         if (!IS_ERR(kthread_run(target_recovery_thread,
2853                                 lut, "tgt_recover_%d", index))) {
2854                 wait_for_completion(&trd->trd_starting);
2855                 LASSERT(obd->obd_recovering != 0);
2856         } else {
2857                 rc = -ECHILD;
2858         }
2859
2860         return rc;
2861 }
2862
2863 void target_stop_recovery_thread(struct obd_device *obd)
2864 {
2865         if (obd->obd_recovery_data.trd_processing_task > 0) {
2866                 struct target_recovery_data *trd = &obd->obd_recovery_data;
2867                 /** recovery can be done but postrecovery is not yet */
2868                 spin_lock(&obd->obd_dev_lock);
2869                 if (obd->obd_recovering) {
2870                         CERROR("%s: Aborting recovery\n", obd->obd_name);
2871                         obd->obd_abort_recovery = 1;
2872                         wake_up(&obd->obd_next_transno_waitq);
2873                 }
2874                 spin_unlock(&obd->obd_dev_lock);
2875                 wait_for_completion(&trd->trd_finishing);
2876         }
2877 }
2878 EXPORT_SYMBOL(target_stop_recovery_thread);
2879
2880 void target_recovery_fini(struct obd_device *obd)
2881 {
2882         class_disconnect_exports(obd);
2883         target_stop_recovery_thread(obd);
2884         target_cleanup_recovery(obd);
2885 }
2886 EXPORT_SYMBOL(target_recovery_fini);
2887
2888 static enum hrtimer_restart target_recovery_expired(struct hrtimer *timer)
2889 {
2890         struct obd_device *obd = container_of(timer, struct obd_device,
2891                                               obd_recovery_timer);
2892
2893         CDEBUG(D_HA,
2894                "%s: recovery timed out; %d clients are still in recovery after %llu seconds (%d clients connected)\n",
2895                obd->obd_name, atomic_read(&obd->obd_lock_replay_clients),
2896                ktime_get_seconds() - obd->obd_recovery_start,
2897                atomic_read(&obd->obd_connected_clients));
2898
2899         obd->obd_recovery_expired = 1;
2900         wake_up(&obd->obd_next_transno_waitq);
2901         return HRTIMER_NORESTART;
2902 }
2903
2904 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
2905 {
2906         struct obd_device *obd = lut->lut_obd;
2907
2908         if (lut->lut_bottom->dd_rdonly)
2909                 return;
2910
2911         if (atomic_read(&obd->obd_max_recoverable_clients) == 0) {
2912                 /** Update server last boot epoch */
2913                 tgt_boot_epoch_update(lut);
2914                 return;
2915         }
2916
2917         CDEBUG(D_HA, "RECOVERY: service %s, %d recoverable clients, "
2918                "last_transno %llu\n", obd->obd_name,
2919                atomic_read(&obd->obd_max_recoverable_clients),
2920                obd->obd_last_committed);
2921         LASSERT(obd->obd_stopping == 0);
2922         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
2923         obd->obd_recovery_start = 0;
2924         obd->obd_recovery_end = 0;
2925
2926         hrtimer_init(&obd->obd_recovery_timer, CLOCK_MONOTONIC,
2927                      HRTIMER_MODE_ABS);
2928         obd->obd_recovery_timer.function = &target_recovery_expired;
2929         target_start_recovery_thread(lut, handler);
2930 }
2931 EXPORT_SYMBOL(target_recovery_init);
2932
2933 static int target_process_req_flags(struct obd_device *obd,
2934                                     struct ptlrpc_request *req)
2935 {
2936         struct obd_export *exp = req->rq_export;
2937
2938         LASSERT(exp != NULL);
2939         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2940                 /* client declares he's ready to replay locks */
2941                 spin_lock(&exp->exp_lock);
2942                 if (exp->exp_req_replay_needed) {
2943                         exp->exp_req_replay_needed = 0;
2944                         spin_unlock(&exp->exp_lock);
2945
2946                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
2947                         atomic_dec(&obd->obd_req_replay_clients);
2948                 } else {
2949                         spin_unlock(&exp->exp_lock);
2950                 }
2951         }
2952         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2953                 /*
2954                  * client declares he's ready to complete recovery
2955                  * so, we put the request on th final queue
2956                  */
2957                 spin_lock(&exp->exp_lock);
2958                 if (exp->exp_lock_replay_needed) {
2959                         exp->exp_lock_replay_needed = 0;
2960                         spin_unlock(&exp->exp_lock);
2961
2962                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
2963                         atomic_dec(&obd->obd_lock_replay_clients);
2964                 } else {
2965                         spin_unlock(&exp->exp_lock);
2966                 }
2967         }
2968         return 0;
2969 }
2970
2971 int target_queue_recovery_request(struct ptlrpc_request *req,
2972                                   struct obd_device *obd)
2973 {
2974         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
2975         struct ptlrpc_request *reqiter;
2976         int inserted = 0;
2977
2978         ENTRY;
2979
2980         if (obd->obd_recovery_data.trd_processing_task == current->pid) {
2981                 /* Processing the queue right now, don't re-add. */
2982                 RETURN(1);
2983         }
2984
2985         target_process_req_flags(obd, req);
2986
2987         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2988                 if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_TGT_RECOVERY_REQ_RACE))) {
2989                         if (cfs_fail_val == 1) {
2990                                 cfs_race_state = 1;
2991                                 cfs_fail_val = 0;
2992                                 wake_up(&cfs_race_waitq);
2993
2994                                 schedule_timeout_interruptible(
2995                                         cfs_time_seconds(1));
2996                         }
2997                 }
2998
2999                 /*
3000                  * client declares he's ready to complete recovery
3001                  * so, we put the request on th final queue
3002                  */
3003                 target_request_copy_get(req);
3004                 DEBUG_REQ(D_HA, req, "queue final req");
3005                 wake_up(&obd->obd_next_transno_waitq);
3006                 spin_lock(&obd->obd_recovery_task_lock);
3007                 if (obd->obd_recovering) {
3008                         struct ptlrpc_request *tmp;
3009                         struct ptlrpc_request *duplicate = NULL;
3010
3011                         if (likely(!req->rq_export->exp_replay_done)) {
3012                                 req->rq_export->exp_replay_done = 1;
3013                                 list_add_tail(&req->rq_list,
3014                                               &obd->obd_final_req_queue);
3015                                 spin_unlock(&obd->obd_recovery_task_lock);
3016                                 RETURN(0);
3017                         }
3018
3019                         /*
3020                          * XXX O(n), but only happens if final ping is
3021                          * timed out, probably reorganize the list as
3022                          * a hash list later
3023                          */
3024                         list_for_each_entry_safe(reqiter, tmp,
3025                                                  &obd->obd_final_req_queue,
3026                                                  rq_list) {
3027                                 if (reqiter->rq_export == req->rq_export) {
3028                                         list_del_init(&reqiter->rq_list);
3029                                         duplicate = reqiter;
3030                                         break;
3031                                 }
3032                         }
3033
3034                         list_add_tail(&req->rq_list,
3035                                       &obd->obd_final_req_queue);
3036                         req->rq_export->exp_replay_done = 1;
3037                         spin_unlock(&obd->obd_recovery_task_lock);
3038
3039                         if (duplicate != NULL) {
3040                                 DEBUG_REQ(D_HA, duplicate,
3041                                           "put prev final req");
3042                                 target_request_copy_put(duplicate);
3043                         }
3044                         RETURN(0);
3045                 } else {
3046                         spin_unlock(&obd->obd_recovery_task_lock);
3047                         target_request_copy_put(req);
3048                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
3049                 }
3050         }
3051         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
3052                 /* client declares he's ready to replay locks */
3053                 target_request_copy_get(req);
3054                 DEBUG_REQ(D_HA, req, "queue lock replay req");
3055                 wake_up(&obd->obd_next_transno_waitq);
3056                 spin_lock(&obd->obd_recovery_task_lock);
3057                 LASSERT(obd->obd_recovering);
3058                 /* usually due to recovery abort */
3059                 if (!req->rq_export->exp_in_recovery) {
3060                         spin_unlock(&obd->obd_recovery_task_lock);
3061                         target_request_copy_put(req);
3062                         RETURN(-ENOTCONN);
3063                 }
3064                 LASSERT(req->rq_export->exp_lock_replay_needed);
3065                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
3066                 spin_unlock(&obd->obd_recovery_task_lock);
3067                 RETURN(0);
3068         }
3069
3070         /*
3071          * CAVEAT EMPTOR: The incoming request message has been swabbed
3072          * (i.e. buflens etc are in my own byte order), but type-dependent
3073          * buffers (eg mdt_body, ost_body etc) have NOT been swabbed.
3074          */
3075
3076         if (!transno) {
3077                 INIT_LIST_HEAD(&req->rq_list);
3078                 DEBUG_REQ(D_HA, req, "not queueing");
3079                 RETURN(1);
3080         }
3081
3082         /*
3083          * If we're processing the queue, we want don't want to queue this
3084          * message.
3085          *
3086          * Also, if this request has a transno less than the one we're waiting
3087          * for, we should process it now.  It could (and currently always will)
3088          * be an open request for a descriptor that was opened some time ago.
3089          *
3090          * Also, a resent, replayed request that has already been
3091          * handled will pass through here and be processed immediately.
3092          */
3093         CDEBUG(D_HA,
3094                "Next recovery transno: %llu, current: %llu, replaying\n",
3095                obd->obd_next_recovery_transno, transno);
3096
3097         /*
3098          * If the request has been replayed by update replay, then sends this
3099          * request to the recovery thread (replay_request_or_update()), where
3100          * it will be handled
3101          */
3102         spin_lock(&obd->obd_recovery_task_lock);
3103         if (transno < obd->obd_next_recovery_transno &&
3104             !is_req_replayed_by_update(req)) {
3105                 /* Processing the queue right now, don't re-add. */
3106                 LASSERT(list_empty(&req->rq_list));
3107                 spin_unlock(&obd->obd_recovery_task_lock);
3108                 RETURN(1);
3109         }
3110         spin_unlock(&obd->obd_recovery_task_lock);
3111
3112         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
3113                 RETURN(0);
3114
3115         target_request_copy_get(req);
3116         if (!req->rq_export->exp_in_recovery) {
3117                 target_request_copy_put(req);
3118                 RETURN(-ENOTCONN);
3119         }
3120         LASSERT(req->rq_export->exp_req_replay_needed);
3121
3122         if (target_exp_enqueue_req_replay(req)) {
3123                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
3124                 target_request_copy_put(req);
3125                 RETURN(0);
3126         }
3127
3128         /* XXX O(n^2) */
3129         spin_lock(&obd->obd_recovery_task_lock);
3130         LASSERT(obd->obd_recovering);
3131         list_for_each_entry(reqiter, &obd->obd_req_replay_queue, rq_list) {
3132                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
3133                         list_add_tail(&req->rq_list, &reqiter->rq_list);
3134                         inserted = 1;
3135                         goto added;
3136                 }
3137
3138                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
3139                              transno)) {
3140                         DEBUG_REQ(D_ERROR, req,
3141                                   "dropping replay: transno has been claimed by another client");
3142                         spin_unlock(&obd->obd_recovery_task_lock);
3143                         target_exp_dequeue_req_replay(req);
3144                         target_request_copy_put(req);
3145                         RETURN(0);
3146                 }
3147         }
3148 added:
3149         if (!inserted)
3150                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
3151
3152         obd->obd_requests_queued_for_recovery++;
3153         spin_unlock(&obd->obd_recovery_task_lock);
3154         wake_up(&obd->obd_next_transno_waitq);
3155         RETURN(0);
3156 }
3157
3158 void target_committed_to_req(struct ptlrpc_request *req)
3159 {
3160         struct obd_export *exp = req->rq_export;
3161
3162         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
3163                 lustre_msg_set_last_committed(req->rq_repmsg,
3164                                               exp->exp_last_committed);
3165         else
3166                 DEBUG_REQ(D_IOCTL, req,
3167                           "not sending last_committed update (%d/%d)",
3168                           exp->exp_obd->obd_no_transno,
3169                           req->rq_repmsg == NULL);
3170
3171         CDEBUG(D_INFO, "last_committed %llu, transno %llu, xid %llu\n",
3172                exp->exp_last_committed, req->rq_transno, req->rq_xid);
3173 }
3174
31