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