Whamcloud - gitweb
LU-10360 mgc: Use IR for client->MDS/OST connections
[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_timeout < obd->obd_recovery_time_hard) {
2271                 obd->obd_recovery_expired = 0;
2272
2273                 /** If some clients died being recovered, evict them */
2274                 LCONSOLE_WARN("%s: recovery is timed out, evict stale exports\n",
2275                               obd->obd_name);
2276                 /** evict cexports with no replay in queue, they are stalled */
2277                 class_disconnect_stale_exports(obd, health_check);
2278
2279                 /** continue with VBR */
2280                 spin_lock(&obd->obd_dev_lock);
2281                 obd->obd_version_recov = 1;
2282                 spin_unlock(&obd->obd_dev_lock);
2283                 /**
2284                  * reset timer, recovery will proceed with versions now,
2285                  * timeout is set just to handle reconnection delays
2286                  */
2287                 extend_recovery_timer(obd, RECONNECT_DELAY_MAX, true);
2288                 /**
2289                  * Wait for recovery events again, after evicting bad clients
2290                  */
2291                 goto repeat;
2292         }
2293         return 0;
2294 }
2295
2296 static struct ptlrpc_request *target_next_replay_lock(struct lu_target *lut)
2297 {
2298         struct obd_device *obd = lut->lut_obd;
2299         struct ptlrpc_request *req = NULL;
2300
2301         CDEBUG(D_HA, "Waiting for lock\n");
2302         if (target_recovery_overseer(lut, check_for_next_lock,
2303                                      exp_lock_replay_healthy))
2304                 abort_lock_replay_queue(obd);
2305
2306         spin_lock(&obd->obd_recovery_task_lock);
2307         if (!list_empty(&obd->obd_lock_replay_queue)) {
2308                 req = list_entry(obd->obd_lock_replay_queue.next,
2309                                      struct ptlrpc_request, rq_list);
2310                 list_del_init(&req->rq_list);
2311                 spin_unlock(&obd->obd_recovery_task_lock);
2312         } else {
2313                 spin_unlock(&obd->obd_recovery_task_lock);
2314                 LASSERT(list_empty(&obd->obd_lock_replay_queue));
2315                 LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
2316                 /** evict exports failed VBR */
2317                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
2318         }
2319         return req;
2320 }
2321
2322 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
2323 {
2324         struct ptlrpc_request *req = NULL;
2325
2326         spin_lock(&obd->obd_recovery_task_lock);
2327         if (!list_empty(&obd->obd_final_req_queue)) {
2328                 req = list_entry(obd->obd_final_req_queue.next,
2329                                      struct ptlrpc_request, rq_list);
2330                 list_del_init(&req->rq_list);
2331                 spin_unlock(&obd->obd_recovery_task_lock);
2332                 if (req->rq_export->exp_in_recovery) {
2333                         spin_lock(&req->rq_export->exp_lock);
2334                         req->rq_export->exp_in_recovery = 0;
2335                         spin_unlock(&req->rq_export->exp_lock);
2336                 }
2337         } else {
2338                 spin_unlock(&obd->obd_recovery_task_lock);
2339         }
2340         return req;
2341 }
2342
2343 static void handle_recovery_req(struct ptlrpc_thread *thread,
2344                                 struct ptlrpc_request *req,
2345                                 svc_handler_t handler)
2346 {
2347         ENTRY;
2348
2349         /**
2350          * export can be evicted during recovery, no need to handle replays for
2351          * it after that, discard such request silently
2352          */
2353         if (req->rq_export->exp_disconnected)
2354                 RETURN_EXIT;
2355
2356         req->rq_session.lc_thread = thread;
2357         req->rq_svc_thread = thread;
2358         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
2359
2360         /* thread context */
2361         lu_context_enter(&thread->t_env->le_ctx);
2362         (void)handler(req);
2363         lu_context_exit(&thread->t_env->le_ctx);
2364
2365         req->rq_svc_thread->t_env->le_ses = NULL;
2366
2367         /* don't reset timer for final stage */
2368         if (!exp_finished(req->rq_export)) {
2369                 timeout_t timeout = obd_timeout;
2370
2371                 /**
2372                  * Add request @timeout to the recovery time so next request from
2373                  * this client may come in recovery time
2374                  */
2375                 if (!AT_OFF) {
2376                         struct ptlrpc_service_part *svcpt;
2377                         timeout_t est_timeout;
2378
2379                         svcpt = req->rq_rqbd->rqbd_svcpt;
2380                         /*
2381                          * If the server sent early reply for this request,
2382                          * the client will recalculate the timeout according to
2383                          * current server estimate service time, so we will
2384                          * use the maxium timeout here for waiting the client
2385                          * sending the next req
2386                          */
2387                         est_timeout = at_get(&svcpt->scp_at_estimate);
2388                         timeout = max_t(timeout_t, at_est2timeout(est_timeout),
2389                                         lustre_msg_get_timeout(req->rq_reqmsg));
2390                         /*
2391                          * Add 2 net_latency, one for balance rq_deadline
2392                          * (see ptl_send_rpc), one for resend the req to server,
2393                          * Note: client will pack net_latency in replay req
2394                          * (see ptlrpc_replay_req)
2395                          */
2396                         timeout += 2 * lustre_msg_get_service_timeout(req->rq_reqmsg);
2397                 }
2398                 extend_recovery_timer(class_exp2obd(req->rq_export), timeout,
2399                                       true);
2400         }
2401         EXIT;
2402 }
2403
2404 /** Checking routines for recovery */
2405 static int check_for_recovery_ready(struct lu_target *lut)
2406 {
2407         struct obd_device *obd = lut->lut_obd;
2408         unsigned int clnts = atomic_read(&obd->obd_connected_clients);
2409
2410         CDEBUG(D_HA,
2411                "connected %d stale %d max_recoverable_clients %d abort %d expired %d\n",
2412                clnts, obd->obd_stale_clients,
2413                atomic_read(&obd->obd_max_recoverable_clients),
2414                obd->obd_abort_recovery, obd->obd_recovery_expired);
2415
2416         if (!obd->obd_abort_recovery && !obd->obd_recovery_expired) {
2417                 LASSERT(clnts <=
2418                         atomic_read(&obd->obd_max_recoverable_clients));
2419                 if (clnts + obd->obd_stale_clients <
2420                     atomic_read(&obd->obd_max_recoverable_clients))
2421                         return 0;
2422         }
2423
2424         if (lut->lut_tdtd != NULL) {
2425                 if (!lut->lut_tdtd->tdtd_replay_ready &&
2426                     !obd->obd_abort_recovery && !obd->obd_stopping) {
2427                         /*
2428                          * Let's extend recovery timer, in case the recovery
2429                          * timer expired, and some clients got evicted
2430                          */
2431                         extend_recovery_timer(obd, obd->obd_recovery_timeout,
2432                                               true);
2433                         CDEBUG(D_HA,
2434                                "%s update recovery is not ready, extend recovery %d\n",
2435                                obd->obd_name, obd->obd_recovery_timeout);
2436                         return 0;
2437                 }
2438         }
2439
2440         return 1;
2441 }
2442
2443 enum {
2444         REQUEST_RECOVERY = 1,
2445         UPDATE_RECOVERY = 2,
2446 };
2447
2448 static __u64 get_next_replay_req_transno(struct obd_device *obd)
2449 {
2450         __u64 transno = 0;
2451
2452         if (!list_empty(&obd->obd_req_replay_queue)) {
2453                 struct ptlrpc_request *req;
2454
2455                 req = list_entry(obd->obd_req_replay_queue.next,
2456                                  struct ptlrpc_request, rq_list);
2457                 transno = lustre_msg_get_transno(req->rq_reqmsg);
2458         }
2459
2460         return transno;
2461 }
2462
2463 static __u64 get_next_transno(struct lu_target *lut, int *type)
2464 {
2465         struct obd_device *obd = lut->lut_obd;
2466         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2467         __u64 transno = 0;
2468         __u64 update_transno;
2469
2470         ENTRY;
2471
2472         transno = get_next_replay_req_transno(obd);
2473         if (type != NULL)
2474                 *type = REQUEST_RECOVERY;
2475
2476         if (tdtd == NULL)
2477                 RETURN(transno);
2478
2479         update_transno = distribute_txn_get_next_transno(tdtd);
2480         if (transno == 0 || (transno >= update_transno &&
2481                              update_transno != 0)) {
2482                 transno = update_transno;
2483                 if (type != NULL)
2484                         *type = UPDATE_RECOVERY;
2485         }
2486
2487         RETURN(transno);
2488 }
2489
2490 /**
2491  * drop duplicate replay request
2492  *
2493  * Because the operation has been replayed by update recovery, the request
2494  * with the same transno will be dropped and also notify the client to send
2495  * next replay request.
2496  *
2497  * \param[in] env       execution environment
2498  * \param[in] obd       failover obd device
2499  * \param[in] req       request to be dropped
2500  */
2501 static void drop_duplicate_replay_req(struct lu_env *env,
2502                                       struct obd_device *obd,
2503                                       struct ptlrpc_request *req)
2504 {
2505         DEBUG_REQ(D_HA, req,
2506                   "remove t%lld from %s because duplicate update records found",
2507                   lustre_msg_get_transno(req->rq_reqmsg),
2508                   libcfs_nid2str(req->rq_peer.nid));
2509
2510         /*
2511          * Right now, only for MDS reint operation update replay and
2512          * normal request replay can have the same transno
2513          */
2514         if (lustre_msg_get_opc(req->rq_reqmsg) == MDS_REINT) {
2515                 req_capsule_set(&req->rq_pill, &RQF_MDS_REINT);
2516                 req->rq_status = req_capsule_server_pack(&req->rq_pill);
2517                 if (likely(req->rq_export))
2518                         target_committed_to_req(req);
2519                 lustre_msg_set_transno(req->rq_repmsg, req->rq_transno);
2520                 target_send_reply(req, req->rq_status, 0);
2521         } else {
2522                 DEBUG_REQ(D_ERROR, req, "wrong opc from %s",
2523                 libcfs_nid2str(req->rq_peer.nid));
2524         }
2525         target_exp_dequeue_req_replay(req);
2526         target_request_copy_put(req);
2527         obd->obd_replayed_requests++;
2528 }
2529
2530 #define WATCHDOG_TIMEOUT (obd_timeout * 10)
2531
2532 static void replay_request_or_update(struct lu_env *env,
2533                                      struct lu_target *lut,
2534                                      struct target_recovery_data *trd,
2535                                      struct ptlrpc_thread *thread)
2536 {
2537         struct obd_device *obd = lut->lut_obd;
2538         struct ptlrpc_request *req = NULL;
2539         int type;
2540         __u64 transno;
2541
2542         ENTRY;
2543
2544         CDEBUG(D_HA, "Waiting for transno %lld\n",
2545                obd->obd_next_recovery_transno);
2546
2547         /* Replay all of request and update by transno */
2548         do {
2549                 struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2550
2551                 CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_DELAY2, cfs_fail_val);
2552
2553                 /**
2554                  * It is needed to extend recovery window above
2555                  *  recovery_time_soft. Extending is possible only in the
2556                  *  end of recovery window (see more details in
2557                  *  handle_recovery_req()).
2558                  */
2559                 CFS_FAIL_TIMEOUT_MS(OBD_FAIL_TGT_REPLAY_DELAY, 300);
2560
2561                 if (target_recovery_overseer(lut, check_for_next_transno,
2562                                         exp_req_replay_healthy_or_from_mdt)) {
2563                         abort_req_replay_queue(obd);
2564                         abort_lock_replay_queue(obd);
2565                         goto abort;
2566                 }
2567
2568                 spin_lock(&obd->obd_recovery_task_lock);
2569                 transno = get_next_transno(lut, &type);
2570                 if (type == REQUEST_RECOVERY && transno != 0) {
2571                         /*
2572                          * Drop replay request from client side, if the
2573                          * replay has been executed by update with the
2574                          * same transno
2575                          */
2576                         req = list_entry(obd->obd_req_replay_queue.next,
2577                                         struct ptlrpc_request, rq_list);
2578
2579                         list_del_init(&req->rq_list);
2580                         obd->obd_requests_queued_for_recovery--;
2581                         spin_unlock(&obd->obd_recovery_task_lock);
2582
2583                         /*
2584                          * Let's check if the request has been redone by
2585                          * update replay
2586                          */
2587                         if (is_req_replayed_by_update(req)) {
2588                                 struct distribute_txn_replay_req *dtrq;
2589
2590                                 dtrq = distribute_txn_lookup_finish_list(tdtd,
2591                                                                       transno);
2592                                 LASSERT(dtrq != NULL);
2593                                 spin_lock(&tdtd->tdtd_replay_list_lock);
2594                                 list_del_init(&dtrq->dtrq_list);
2595                                 spin_unlock(&tdtd->tdtd_replay_list_lock);
2596                                 dtrq_destroy(dtrq);
2597
2598                                 drop_duplicate_replay_req(env, obd, req);
2599
2600                                 continue;
2601                         }
2602
2603                         LASSERT(trd->trd_processing_task == current->pid);
2604                         DEBUG_REQ(D_HA, req, "processing x%llu t%lld from %s",
2605                                   req->rq_xid,
2606                                   lustre_msg_get_transno(req->rq_reqmsg),
2607                                   libcfs_nid2str(req->rq_peer.nid));
2608
2609                         ptlrpc_watchdog_init(&thread->t_watchdog,
2610                                              WATCHDOG_TIMEOUT);
2611                         handle_recovery_req(thread, req,
2612                                             trd->trd_recovery_handler);
2613                         ptlrpc_watchdog_disable(&thread->t_watchdog);
2614
2615                         /**
2616                          * bz18031: increase next_recovery_transno before
2617                          * target_request_copy_put() will drop exp_rpc reference
2618                          */
2619                         spin_lock(&obd->obd_recovery_task_lock);
2620                         obd->obd_next_recovery_transno++;
2621                         spin_unlock(&obd->obd_recovery_task_lock);
2622                         target_exp_dequeue_req_replay(req);
2623                         target_request_copy_put(req);
2624                         obd->obd_replayed_requests++;
2625                 } else if (type == UPDATE_RECOVERY && transno != 0) {
2626                         struct distribute_txn_replay_req *dtrq;
2627                         int rc;
2628
2629                         spin_unlock(&obd->obd_recovery_task_lock);
2630
2631                         LASSERT(tdtd != NULL);
2632                         dtrq = distribute_txn_get_next_req(tdtd);
2633                         lu_context_enter(&thread->t_env->le_ctx);
2634                         ptlrpc_watchdog_init(&thread->t_watchdog,
2635                                              WATCHDOG_TIMEOUT);
2636                         rc = tdtd->tdtd_replay_handler(env, tdtd, dtrq);
2637                         ptlrpc_watchdog_disable(&thread->t_watchdog);
2638                         lu_context_exit(&thread->t_env->le_ctx);
2639                         extend_recovery_timer(obd, obd_timeout, true);
2640
2641                         if (rc == 0 && dtrq->dtrq_xid != 0) {
2642                                 CDEBUG(D_HA,
2643                                        "Move x%llu t%llu to finish list\n",
2644                                        dtrq->dtrq_xid,
2645                                        dtrq->dtrq_master_transno);
2646
2647                                 /* Add it to the replay finish list */
2648                                 spin_lock(&tdtd->tdtd_replay_list_lock);
2649                                 list_add(&dtrq->dtrq_list,
2650                                          &tdtd->tdtd_replay_finish_list);
2651                                 spin_unlock(&tdtd->tdtd_replay_list_lock);
2652
2653                                 spin_lock(&obd->obd_recovery_task_lock);
2654                                 if (transno == obd->obd_next_recovery_transno)
2655                                         obd->obd_next_recovery_transno++;
2656                                 else if (transno >
2657                                          obd->obd_next_recovery_transno)
2658                                         obd->obd_next_recovery_transno =
2659                                                                 transno + 1;
2660                                 spin_unlock(&obd->obd_recovery_task_lock);
2661                         } else {
2662                                 dtrq_destroy(dtrq);
2663                         }
2664                 } else {
2665                         spin_unlock(&obd->obd_recovery_task_lock);
2666 abort:
2667                         LASSERT(list_empty(&obd->obd_req_replay_queue));
2668                         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
2669                         /** evict exports failed VBR */
2670                         class_disconnect_stale_exports(obd, exp_vbr_healthy);
2671                         break;
2672                 }
2673         } while (1);
2674 }
2675
2676 static int target_recovery_thread(void *arg)
2677 {
2678         struct lu_target *lut = arg;
2679         struct obd_device *obd = lut->lut_obd;
2680         struct ptlrpc_request *req;
2681         struct target_recovery_data *trd = &obd->obd_recovery_data;
2682         unsigned long delta;
2683         struct lu_env *env;
2684         struct ptlrpc_thread *thread = NULL;
2685         int rc = 0;
2686
2687         ENTRY;
2688         OBD_ALLOC_PTR(thread);
2689         if (thread == NULL)
2690                 RETURN(-ENOMEM);
2691
2692         OBD_ALLOC_PTR(env);
2693         if (env == NULL)
2694                 GOTO(out_thread, rc = -ENOMEM);
2695         rc = lu_env_add(env);
2696         if (rc)
2697                 GOTO(out_env, rc);
2698
2699         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD);
2700         if (rc)
2701                 GOTO(out_env_remove, rc);
2702
2703         thread->t_env = env;
2704         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
2705         env->le_ctx.lc_thread = thread;
2706         tgt_io_thread_init(thread); /* init thread_big_cache for IO requests */
2707
2708         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
2709                current->pid);
2710         trd->trd_processing_task = current->pid;
2711
2712         spin_lock(&obd->obd_dev_lock);
2713         obd->obd_recovering = 1;
2714         spin_unlock(&obd->obd_dev_lock);
2715         complete(&trd->trd_starting);
2716
2717         /* first of all, we have to know the first transno to replay */
2718         if (target_recovery_overseer(lut, check_for_recovery_ready,
2719                                      exp_connect_healthy)) {
2720                 abort_req_replay_queue(obd);
2721                 abort_lock_replay_queue(obd);
2722                 if (lut->lut_tdtd != NULL)
2723                         dtrq_list_destroy(lut->lut_tdtd);
2724         }
2725
2726         /* next stage: replay requests or update */
2727         delta = jiffies;
2728         CDEBUG(D_INFO, "1: request replay stage - %d clients from t%llu\n",
2729                atomic_read(&obd->obd_req_replay_clients),
2730                obd->obd_next_recovery_transno);
2731         replay_request_or_update(env, lut, trd, thread);
2732
2733         /**
2734          * The second stage: replay locks
2735          */
2736         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
2737                atomic_read(&obd->obd_lock_replay_clients));
2738         while ((req = target_next_replay_lock(lut))) {
2739                 LASSERT(trd->trd_processing_task == current->pid);
2740                 DEBUG_REQ(D_HA, req, "processing lock from %s:",
2741                           libcfs_nid2str(req->rq_peer.nid));
2742                 handle_recovery_req(thread, req,
2743                                     trd->trd_recovery_handler);
2744                 target_request_copy_put(req);
2745                 obd->obd_replayed_locks++;
2746         }
2747
2748         /**
2749          * The third stage: reply on final pings, at this moment all clients
2750          * must have request in final queue
2751          */
2752         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_RECONNECT, cfs_fail_val);
2753         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
2754         /** Update server last boot epoch */
2755         tgt_boot_epoch_update(lut);
2756         /*
2757          * We drop recoverying flag to forward all new requests
2758          * to regular mds_handle() since now
2759          */
2760         spin_lock(&obd->obd_dev_lock);
2761         obd->obd_recovering = obd->obd_abort_recovery = 0;
2762         spin_unlock(&obd->obd_dev_lock);
2763         spin_lock(&obd->obd_recovery_task_lock);
2764         target_cancel_recovery_timer(obd);
2765         spin_unlock(&obd->obd_recovery_task_lock);
2766         while ((req = target_next_final_ping(obd))) {
2767                 LASSERT(trd->trd_processing_task == current->pid);
2768                 DEBUG_REQ(D_HA, req, "processing final ping from %s:",
2769                           libcfs_nid2str(req->rq_peer.nid));
2770                 handle_recovery_req(thread, req,
2771                                     trd->trd_recovery_handler);
2772                 /*
2773                  * Because the waiting client can not send ping to server,
2774                  * so we need refresh the last_request_time, to avoid the
2775                  * export is being evicted
2776                  */
2777                 ptlrpc_update_export_timer(req->rq_export, 0);
2778                 target_request_copy_put(req);
2779         }
2780
2781         delta = jiffies_to_msecs(jiffies - delta) / MSEC_PER_SEC;
2782         CDEBUG(D_INFO, "4: recovery completed in %lus - %d/%d reqs/locks\n",
2783                delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
2784         if (delta > OBD_RECOVERY_TIME_SOFT) {
2785                 CWARN("too long recovery - read logs\n");
2786                 libcfs_debug_dumplog();
2787         }
2788
2789         target_finish_recovery(lut);
2790         lu_context_fini(&env->le_ctx);
2791         trd->trd_processing_task = 0;
2792         complete_all(&trd->trd_finishing);
2793         tgt_io_thread_done(thread);
2794 out_env_remove:
2795         lu_env_remove(env);
2796 out_env:
2797         OBD_FREE_PTR(env);
2798 out_thread:
2799         OBD_FREE_PTR(thread);
2800         RETURN(rc);
2801 }
2802
2803 static int target_start_recovery_thread(struct lu_target *lut,
2804                                         svc_handler_t handler)
2805 {
2806         struct obd_device *obd = lut->lut_obd;
2807         int rc = 0;
2808         struct target_recovery_data *trd = &obd->obd_recovery_data;
2809         int index;
2810
2811         memset(trd, 0, sizeof(*trd));
2812         init_completion(&trd->trd_starting);
2813         init_completion(&trd->trd_finishing);
2814         trd->trd_recovery_handler = handler;
2815
2816         rc = server_name2index(obd->obd_name, &index, NULL);
2817         if (rc < 0)
2818                 return rc;
2819
2820         if (!IS_ERR(kthread_run(target_recovery_thread,
2821                                 lut, "tgt_recover_%d", index))) {
2822                 wait_for_completion(&trd->trd_starting);
2823                 LASSERT(obd->obd_recovering != 0);
2824         } else {
2825                 rc = -ECHILD;
2826         }
2827
2828         return rc;
2829 }
2830
2831 void target_stop_recovery_thread(struct obd_device *obd)
2832 {
2833         if (obd->obd_recovery_data.trd_processing_task > 0) {
2834                 struct target_recovery_data *trd = &obd->obd_recovery_data;
2835                 /** recovery can be done but postrecovery is not yet */
2836                 spin_lock(&obd->obd_dev_lock);
2837                 if (obd->obd_recovering) {
2838                         CERROR("%s: Aborting recovery\n", obd->obd_name);
2839                         obd->obd_abort_recovery = 1;
2840                         wake_up(&obd->obd_next_transno_waitq);
2841                 }
2842                 spin_unlock(&obd->obd_dev_lock);
2843                 wait_for_completion(&trd->trd_finishing);
2844         }
2845 }
2846 EXPORT_SYMBOL(target_stop_recovery_thread);
2847
2848 void target_recovery_fini(struct obd_device *obd)
2849 {
2850         class_disconnect_exports(obd);
2851         target_stop_recovery_thread(obd);
2852         target_cleanup_recovery(obd);
2853 }
2854 EXPORT_SYMBOL(target_recovery_fini);
2855
2856 static enum hrtimer_restart target_recovery_expired(struct hrtimer *timer)
2857 {
2858         struct obd_device *obd = container_of(timer, struct obd_device,
2859                                               obd_recovery_timer);
2860
2861         CDEBUG(D_HA,
2862                "%s: recovery timed out; %d clients are still in recovery after %llu seconds (%d clients connected)\n",
2863                obd->obd_name, atomic_read(&obd->obd_lock_replay_clients),
2864                ktime_get_seconds() - obd->obd_recovery_start,
2865                atomic_read(&obd->obd_connected_clients));
2866
2867         obd->obd_recovery_expired = 1;
2868         wake_up(&obd->obd_next_transno_waitq);
2869         return HRTIMER_NORESTART;
2870 }
2871
2872 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
2873 {
2874         struct obd_device *obd = lut->lut_obd;
2875
2876         if (lut->lut_bottom->dd_rdonly)
2877                 return;
2878
2879         if (atomic_read(&obd->obd_max_recoverable_clients) == 0) {
2880                 /** Update server last boot epoch */
2881                 tgt_boot_epoch_update(lut);
2882                 return;
2883         }
2884
2885         CDEBUG(D_HA, "RECOVERY: service %s, %d recoverable clients, "
2886                "last_transno %llu\n", obd->obd_name,
2887                atomic_read(&obd->obd_max_recoverable_clients),
2888                obd->obd_last_committed);
2889         LASSERT(obd->obd_stopping == 0);
2890         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
2891         obd->obd_recovery_start = 0;
2892         obd->obd_recovery_end = 0;
2893
2894         hrtimer_init(&obd->obd_recovery_timer, CLOCK_MONOTONIC,
2895                      HRTIMER_MODE_ABS);
2896         obd->obd_recovery_timer.function = &target_recovery_expired;
2897         target_start_recovery_thread(lut, handler);
2898 }
2899 EXPORT_SYMBOL(target_recovery_init);
2900
2901 static int target_process_req_flags(struct obd_device *obd,
2902                                     struct ptlrpc_request *req)
2903 {
2904         struct obd_export *exp = req->rq_export;
2905
2906         LASSERT(exp != NULL);
2907         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2908                 /* client declares he's ready to replay locks */
2909                 spin_lock(&exp->exp_lock);
2910                 if (exp->exp_req_replay_needed) {
2911                         exp->exp_req_replay_needed = 0;
2912                         spin_unlock(&exp->exp_lock);
2913
2914                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
2915                         atomic_dec(&obd->obd_req_replay_clients);
2916                 } else {
2917                         spin_unlock(&exp->exp_lock);
2918                 }
2919         }
2920         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2921                 /*
2922                  * client declares he's ready to complete recovery
2923                  * so, we put the request on th final queue
2924                  */
2925                 spin_lock(&exp->exp_lock);
2926                 if (exp->exp_lock_replay_needed) {
2927                         exp->exp_lock_replay_needed = 0;
2928                         spin_unlock(&exp->exp_lock);
2929
2930                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
2931                         atomic_dec(&obd->obd_lock_replay_clients);
2932                 } else {
2933                         spin_unlock(&exp->exp_lock);
2934                 }
2935         }
2936         return 0;
2937 }
2938
2939 int target_queue_recovery_request(struct ptlrpc_request *req,
2940                                   struct obd_device *obd)
2941 {
2942         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
2943         struct ptlrpc_request *reqiter;
2944         int inserted = 0;
2945
2946         ENTRY;
2947
2948         if (obd->obd_recovery_data.trd_processing_task == current->pid) {
2949                 /* Processing the queue right now, don't re-add. */
2950                 RETURN(1);
2951         }
2952
2953         target_process_req_flags(obd, req);
2954
2955         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2956                 if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_TGT_RECOVERY_REQ_RACE))) {
2957                         if (cfs_fail_val == 1) {
2958                                 cfs_race_state = 1;
2959                                 cfs_fail_val = 0;
2960                                 wake_up(&cfs_race_waitq);
2961
2962                                 schedule_timeout_interruptible(
2963                                         cfs_time_seconds(1));
2964                         }
2965                 }
2966
2967                 /*
2968                  * client declares he's ready to complete recovery
2969                  * so, we put the request on th final queue
2970                  */
2971                 target_request_copy_get(req);
2972                 DEBUG_REQ(D_HA, req, "queue final req");
2973                 wake_up(&obd->obd_next_transno_waitq);
2974                 spin_lock(&obd->obd_recovery_task_lock);
2975                 if (obd->obd_recovering) {
2976                         struct ptlrpc_request *tmp;
2977                         struct ptlrpc_request *duplicate = NULL;
2978
2979                         if (likely(!req->rq_export->exp_replay_done)) {
2980                                 req->rq_export->exp_replay_done = 1;
2981                                 list_add_tail(&req->rq_list,
2982                                               &obd->obd_final_req_queue);
2983                                 spin_unlock(&obd->obd_recovery_task_lock);
2984                                 RETURN(0);
2985                         }
2986
2987                         /*
2988                          * XXX O(n), but only happens if final ping is
2989                          * timed out, probably reorganize the list as
2990                          * a hash list later
2991                          */
2992                         list_for_each_entry_safe(reqiter, tmp,
2993                                                  &obd->obd_final_req_queue,
2994                                                  rq_list) {
2995                                 if (reqiter->rq_export == req->rq_export) {
2996                                         list_del_init(&reqiter->rq_list);
2997                                         duplicate = reqiter;
2998                                         break;
2999                                 }
3000                         }
3001
3002                         list_add_tail(&req->rq_list,
3003                                       &obd->obd_final_req_queue);
3004                         req->rq_export->exp_replay_done = 1;
3005                         spin_unlock(&obd->obd_recovery_task_lock);
3006
3007                         if (duplicate != NULL) {
3008                                 DEBUG_REQ(D_HA, duplicate,
3009                                           "put prev final req");
3010                                 target_request_copy_put(duplicate);
3011                         }
3012                         RETURN(0);
3013                 } else {
3014                         spin_unlock(&obd->obd_recovery_task_lock);
3015                         target_request_copy_put(req);
3016                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
3017                 }
3018         }
3019         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
3020                 /* client declares he's ready to replay locks */
3021                 target_request_copy_get(req);
3022                 DEBUG_REQ(D_HA, req, "queue lock replay req");
3023                 wake_up(&obd->obd_next_transno_waitq);
3024                 spin_lock(&obd->obd_recovery_task_lock);
3025                 LASSERT(obd->obd_recovering);
3026                 /* usually due to recovery abort */
3027                 if (!req->rq_export->exp_in_recovery) {
3028                         spin_unlock(&obd->obd_recovery_task_lock);
3029                         target_request_copy_put(req);
3030                         RETURN(-ENOTCONN);
3031                 }
3032                 LASSERT(req->rq_export->exp_lock_replay_needed);
3033                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
3034                 spin_unlock(&obd->obd_recovery_task_lock);
3035                 RETURN(0);
3036         }
3037
3038         /*
3039          * CAVEAT EMPTOR: The incoming request message has been swabbed
3040          * (i.e. buflens etc are in my own byte order), but type-dependent
3041          * buffers (eg mdt_body, ost_body etc) have NOT been swabbed.
3042          */
3043
3044         if (!transno) {
3045                 INIT_LIST_HEAD(&req->rq_list);
3046                 DEBUG_REQ(D_HA, req, "not queueing");
3047                 RETURN(1);
3048         }
3049
3050         /*
3051          * If we're processing the queue, we want don't want to queue this
3052          * message.
3053          *
3054          * Also, if this request has a transno less than the one we're waiting
3055          * for, we should process it now.  It could (and currently always will)
3056          * be an open request for a descriptor that was opened some time ago.
3057          *
3058          * Also, a resent, replayed request that has already been
3059          * handled will pass through here and be processed immediately.
3060          */
3061         CDEBUG(D_HA,
3062                "Next recovery transno: %llu, current: %llu, replaying\n",
3063                obd->obd_next_recovery_transno, transno);
3064
3065         /*
3066          * If the request has been replayed by update replay, then sends this
3067          * request to the recovery thread (replay_request_or_update()), where
3068          * it will be handled
3069          */
3070         spin_lock(&obd->obd_recovery_task_lock);
3071         if (transno < obd->obd_next_recovery_transno &&
3072             !is_req_replayed_by_update(req)) {
3073                 /* Processing the queue right now, don't re-add. */
3074                 LASSERT(list_empty(&req->rq_list));
3075                 spin_unlock(&obd->obd_recovery_task_lock);
3076                 RETURN(1);
3077         }
3078         spin_unlock(&obd->obd_recovery_task_lock);
3079
3080         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
3081                 RETURN(0);
3082
3083         target_request_copy_get(req);
3084         if (!req->rq_export->exp_in_recovery) {
3085                 target_request_copy_put(req);
3086                 RETURN(-ENOTCONN);
3087         }
3088         LASSERT(req->rq_export->exp_req_replay_needed);
3089
3090         if (target_exp_enqueue_req_replay(req)) {
3091                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
3092                 target_request_copy_put(req);
3093                 RETURN(0);
3094         }
3095
3096         /* XXX O(n^2) */
3097         spin_lock(&obd->obd_recovery_task_lock);
3098         LASSERT(obd->obd_recovering);
3099         list_for_each_entry(reqiter, &obd->obd_req_replay_queue, rq_list) {
3100                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
3101                         list_add_tail(&req->rq_list, &reqiter->rq_list);
3102                         inserted = 1;
3103                         goto added;
3104                 }
3105
3106                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
3107                              transno)) {
3108                         DEBUG_REQ(D_ERROR, req,
3109                                   "dropping replay: transno has been claimed by another client");
3110                         spin_unlock(&obd->obd_recovery_task_lock);
3111                         target_exp_dequeue_req_replay(req);
3112                         target_request_copy_put(req);
3113                         RETURN(0);
3114                 }
3115         }
3116 added:
3117         if (!inserted)
3118                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
3119
3120         obd->obd_requests_queued_for_recovery++;
3121         spin_unlock(&obd->obd_recovery_task_lock);
3122         wake_up(&obd->obd_next_transno_waitq);
3123         RETURN(0);
3124 }
3125
3126 void target_committed_to_req(struct ptlrpc_request *req)
3127 {
3128         struct obd_export *exp = req->rq_export;
3129
3130         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
3131                 lustre_msg_set_last_committed(req->rq_repmsg,
3132                                               exp->exp_last_committed);
3133         else
3134                 DEBUG_REQ(D_IOCTL, req,
3135                           "not sending last_committed update (%d/%d)",
3136                           exp->exp_obd->obd_no_transno,
3137                           req->rq_repmsg == NULL);
3138
3139         CDEBUG(D_INFO, "last_committed %llu, transno %llu, xid %llu\n",
3140                exp->exp_last_committed, req->rq_transno, req->rq_xid);
3141 }
3142
3143 #endif /* HAVE_SERVER_SUPPORT */
3144
3145 /**
3146  * Packs current SLV and Limit into \a req.
3147  */
3148 int target_pack_pool_reply(struct ptlrpc_request *req)
3149 {
3150         struct obd_device *obd;
3151
3152         ENTRY;
3153
3154         /*
3155          * Check that we still have all structures alive as this may
3156          * be some late RPC at shutdown time.
3157          */
3158         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
3159                      !exp_connect_lru_resize(req->rq_export))) {
3160                 lustre_msg_set_slv(req->rq_repmsg, 0);
3161                 lustre_msg_set_limit(req->rq_repmsg, 0);
3162                 RETURN(0);
3163         }
3164
3165         /* OBD is alive here as export is alive, which we checked above. */
3166         obd = req->rq_export->exp_obd;
3167
3168         read_lock(&obd->obd_pool_lock);
3169         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
3170         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
3171         read_unlock(&obd->obd_pool_lock);
3172
3173         RETURN(0);
3174 }
3175
3176 static int target_send_reply_msg(struct ptlrpc_request *req,
3177                                  int rc, int fail_id)
3178 {
3179         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
3180                 DEBUG_REQ(D_ERROR, req, "dropping reply");
3181                 return -ECOMM;
3182         }
3183         /*
3184          * We can have a null rq_reqmsg in the event of bad signature or
3185          * no context when unwrapping
3186          */
3187         if (req->rq_reqmsg &&
3188             unlikely(lustre_msg_get_opc(req->rq_reqmsg) == MDS_REINT &&
3189             OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_MULTI_NET_REP)))
3190                 return -ECOMM;
3191
3192         if (unlikely(rc)) {
3193                 DEBUG_REQ(D_NET, req, "processing error (%d)", rc);
3194                 req->rq_status = rc;
3195                 return ptlrpc_send_error(req, 1);
3196         }
3197         DEBUG_REQ(D_NET, req, "sending reply");
3198
3199         return ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT);
3200 }
3201
3202 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
3203 {
3204         struct ptlrpc_service_part *svcpt;
3205         int netrc;
3206         struct ptlrpc_reply_state *rs;
3207         struct obd_export *exp;
3208
3209         ENTRY;
3210
3211         if (req->rq_no_reply) {
3212                 EXIT;
3213                 return;
3214         }
3215
3216         svcpt = req->rq_rqbd->rqbd_svcpt;
3217         rs = req->rq_reply_state;
3218         if (rs == NULL || !rs->rs_difficult) {
3219                 /* no notifiers */
3220                 target_send_reply_msg(req, rc, fail_id);
3221                 EXIT;
3222                 return;
3223         }
3224
3225         /* must be an export if locks saved */
3226         LASSERT(req->rq_export != NULL);
3227         /* req/reply consistent */
3228         LASSERT(rs->rs_svcpt == svcpt);
3229
3230         /* "fresh" reply */
3231         LASSERT(!rs->rs_scheduled);
3232         LASSERT(!rs->rs_scheduled_ever);
3233         LASSERT(!rs->rs_handled);
3234         LASSERT(!rs->rs_on_net);
3235         LASSERT(rs->rs_export == NULL);
3236         LASSERT(list_empty(&rs->rs_obd_list));
3237         LASSERT(list_empty(&rs->rs_exp_list));
3238
3239         exp = class_export_get(req->rq_export);
3240
3241         /* disable reply scheduling while I'm setting up */
3242         rs->rs_scheduled = 1;
3243         rs->rs_on_net    = 1;
3244         rs->rs_xid       = req->rq_xid;
3245         rs->rs_transno   = req->rq_transno;
3246         rs->rs_export    = exp;
3247         rs->rs_opc       = lustre_msg_get_opc(req->rq_reqmsg);
3248
3249         spin_lock(&exp->exp_uncommitted_replies_lock);
3250         CDEBUG(D_NET, "rs transno = %llu, last committed = %llu\n",
3251                rs->rs_transno, exp->exp_last_committed);
3252         if (rs->rs_transno > exp->exp_last_committed) {
3253                 /* not committed already */
3254                 list_add_tail(&rs->rs_obd_list,
3255                                   &exp->exp_uncommitted_replies);
3256         }
3257         spin_unlock(&exp->exp_uncommitted_replies_lock);
3258
3259         spin_lock(&exp->exp_lock);
3260         list_add_tail(&rs->rs_exp_list, &exp->exp_outstanding_replies);
3261         spin_unlock(&exp->exp_lock);
3262
3263         netrc = target_send_reply_msg(req, rc, fail_id);
3264
3265         spin_lock(&svcpt->scp_rep_lock);
3266
3267         atomic_inc(&svcpt->scp_nreps_difficult);
3268
3269         if (netrc != 0) {
3270                 /*
3271                  * error sending: reply is off the net.  Also we need +1
3272                  * reply ref until ptlrpc_handle_rs() is done
3273                  * with the reply state (if the send was successful, there
3274                  * would have been +1 ref for the net, which
3275                  * reply_out_callback leaves alone)
3276                  */
3277                 rs->rs_on_net = 0;
3278                 ptlrpc_rs_addref(rs);
3279         }
3280
3281         spin_lock(&rs->rs_lock);
3282         if (rs->rs_transno <= exp->exp_last_committed ||
3283             (!rs->rs_on_net && !rs->rs_no_ack) ||
3284             list_empty(&rs->rs_exp_list) ||     /* completed already */
3285             list_empty(&rs->rs_obd_list)) {
3286                 CDEBUG(D_HA, "Schedule reply immediately\n");
3287                 ptlrpc_dispatch_difficult_reply(rs);
3288         } else {
3289                 list_add(&rs->rs_list, &svcpt->scp_rep_active);
3290                 rs->rs_scheduled = 0;   /* allow notifier to schedule */
3291         }
3292         spin_unlock(&rs->rs_lock);
3293         spin_unlock(&svcpt->scp_rep_lock);
3294         EXIT;
3295 }
3296
3297 enum ldlm_mode lck_compat_array[] = {
3298         [LCK_EX]    = LCK_COMPAT_EX,
3299         [LCK_PW]    = LCK_COMPAT_PW,
3300         [LCK_PR]    = LCK_COMPAT_PR,
3301         [LCK_CW]    = LCK_COMPAT_CW,
3302         [LCK_CR]    = LCK_COMPAT_CR,
3303         [LCK_NL]    = LCK_COMPAT_NL,
3304         [LCK_GROUP] = LCK_COMPAT_GROUP,
3305         [LCK_COS]   = LCK_COMPAT_COS,
3306 };
3307
3308 /**
3309  * Rather arbitrary mapping from LDLM error codes to errno values. This should
3310  * not escape to the user level.
3311  */
3312 int ldlm_error2errno(enum ldlm_error error)
3313 {
3314         int result;
3315
3316         switch (error) {
3317         case ELDLM_OK:
3318         case ELDLM_LOCK_MATCHED:
3319                 result = 0;
3320                 break;
3321         case ELDLM_LOCK_CHANGED:
3322                 result = -ESTALE;
3323                 break;
3324         case ELDLM_LOCK_ABORTED:
3325                 result = -ENAVAIL;
3326                 break;
3327         case ELDLM_LOCK_REPLACED:
3328                 result = -ESRCH;
3329                 break;
3330         case ELDLM_NO_LOCK_DATA:
3331                 result = -ENOENT;
3332                 break;
3333         case ELDLM_NAMESPACE_EXISTS:
3334                 result = -EEXIST;
3335                 break;
3336         case ELDLM_BAD_NAMESPACE:
3337                 result = -EBADF;
3338                 break;
3339         default:
3340                 if (((int)error) < 0) { /* cast to signed type */
3341                         result = error; /* as ldlm_error can be unsigned */
3342                 } else {
3343                         CERROR("Invalid DLM result code: %d\n", error);
3344                         result = -EPROTO;
3345                 }
3346         }
3347         return result;
3348 }
3349 EXPORT_SYMBOL(ldlm_error2errno);
3350
3351 /**
3352  * Dual to ldlm_error2errno(): maps errno values back to enum ldlm_error.
3353  */
3354 enum ldlm_error ldlm_errno2error(int err_no)
3355 {
3356         int error;
3357
3358         switch (err_no) {
3359         case 0:
3360                 error = ELDLM_OK;
3361                 break;
3362         case -ESTALE:
3363                 error = ELDLM_LOCK_CHANGED;
3364                 break;
3365         case -ENAVAIL:
3366                 error = ELDLM_LOCK_ABORTED;
3367                 break;
3368         case -ESRCH:
3369                 error = ELDLM_LOCK_REPLACED;
3370                 break;
3371         case -ENOENT:
3372                 error = ELDLM_NO_LOCK_DATA;
3373                 break;
3374         case -EEXIST:
3375                 error = ELDLM_NAMESPACE_EXISTS;
3376                 break;
3377         case -EBADF:
3378                 error = ELDLM_BAD_NAMESPACE;
3379                 break;
3380         default:
3381                 error = err_no;
3382         }
3383         return error;
3384 }
3385
3386 #if LUSTRE_TRACKS_LOCK_EXP_REFS
3387 void ldlm_dump_export_locks(struct obd_export *exp)
3388 {
3389         spin_lock(&exp->exp_locks_list_guard);
3390         if (!list_empty(&exp->exp_locks_list)) {
3391                 struct ldlm_lock *lock;
3392
3393                 CERROR("dumping locks for export %p, ignore if the unmount doesn't hang\n",
3394                        exp);
3395                 list_for_each_entry(lock, &exp->exp_locks_list,
3396                                         l_exp_refs_link)
3397                         LDLM_ERROR(lock, "lock:");
3398         }
3399         spin_unlock(&exp->exp_locks_list_guard);
3400 }
3401 #endif
3402
3403 #ifdef HAVE_SERVER_SUPPORT
3404 static inline const char *bulk2type(struct ptlrpc_request *req)
3405 {
3406         if (req->rq_bulk_read)
3407                 return "READ";
3408         if (req->rq_bulk_write)
3409                 return "WRITE";
3410         return "UNKNOWN";
3411 }
3412
3413 int target_bulk_io(struct obd_export *exp, struct ptlrpc_bulk_desc *desc)
3414 {
3415         struct ptlrpc_request *req = desc->bd_req;
3416         time64_t start = ktime_get_seconds();
3417         time64_t deadline;
3418         int rc = 0;
3419
3420         ENTRY;
3421
3422         /* If there is eviction in progress, wait for it to finish. */
3423         wait_event_idle(
3424                 exp->exp_obd->obd_evict_inprogress_waitq,
3425                 !atomic_read(&exp->exp_obd->obd_evict_inprogress));
3426
3427         /* Check if client was evicted or reconnected already. */
3428         if (exp->exp_failed ||
3429             exp->exp_conn_cnt > lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
3430                 rc = -ENOTCONN;
3431         } else {
3432                 if (req->rq_bulk_read)
3433                         rc = sptlrpc_svc_wrap_bulk(req, desc);
3434
3435                 if (OCD_HAS_FLAG(&exp->exp_connect_data, BULK_MBITS))
3436                         req->rq_mbits = lustre_msg_get_mbits(req->rq_reqmsg);
3437                 else /* old version, bulk matchbits is rq_xid */
3438                         req->rq_mbits = req->rq_xid;
3439
3440                 if (rc == 0)
3441                         rc = ptlrpc_start_bulk_transfer(desc);
3442         }
3443
3444         if (rc < 0) {
3445                 DEBUG_REQ(D_ERROR, req, "bulk %s failed: rc = %d",
3446                           bulk2type(req), rc);
3447                 RETURN(rc);
3448         }
3449
3450         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
3451                 ptlrpc_abort_bulk(desc);
3452                 RETURN(0);
3453         }
3454
3455         /* limit actual bulk transfer to bulk_timeout seconds */
3456         deadline = start + bulk_timeout;
3457         if (deadline > req->rq_deadline)
3458                 deadline = req->rq_deadline;
3459
3460         do {
3461                 time64_t timeoutl = deadline - ktime_get_seconds();
3462                 time64_t rq_deadline;
3463
3464                 while (timeoutl >= 0 &&
3465                        wait_event_idle_timeout(
3466                                desc->bd_waitq,
3467                                !ptlrpc_server_bulk_active(desc) ||
3468                                exp->exp_failed ||
3469                                exp->exp_conn_cnt >
3470                                lustre_msg_get_conn_cnt(req->rq_reqmsg),
3471                                timeoutl ? cfs_time_seconds(1) : 1) == 0)
3472                         timeoutl -= 1;
3473                 rc = timeoutl < 0 ? -ETIMEDOUT : 0;
3474
3475                 /* Wait again if we changed rq_deadline. */
3476                 rq_deadline = READ_ONCE(req->rq_deadline);
3477                 deadline = start + bulk_timeout;
3478                 if (deadline > rq_deadline)
3479                         deadline = rq_deadline;
3480         } while (rc == -ETIMEDOUT &&
3481                  deadline > ktime_get_seconds());
3482
3483         if (rc == -ETIMEDOUT) {
3484                 DEBUG_REQ(D_ERROR, req, "timeout on bulk %s after %lld%+llds",
3485                           bulk2type(req), deadline - start,
3486                           ktime_get_real_seconds() - deadline);
3487                 ptlrpc_abort_bulk(desc);
3488         } else if (exp->exp_failed) {
3489                 DEBUG_REQ(D_ERROR, req, "Eviction on bulk %s",
3490                           bulk2type(req));
3491                 rc = -ENOTCONN;
3492                 ptlrpc_abort_bulk(desc);
3493         } else if (exp->exp_conn_cnt >
3494                    lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
3495                 DEBUG_REQ(D_ERROR, req, "Reconnect on bulk %s",
3496                           bulk2type(req));
3497                 /* We don't reply anyway. */
3498                 rc = -ETIMEDOUT;
3499                 ptlrpc_abort_bulk(desc);
3500         } else if (desc->bd_failure) {
3501                 DEBUG_REQ(D_ERROR, req, "network error on bulk %s",
3502                           bulk2type(req));
3503                 /* XXX should this be a different errno? */
3504                 rc = -ETIMEDOUT;
3505         } else {
3506                 if (req->rq_bulk_write)
3507                         rc = sptlrpc_svc_unwrap_bulk(req, desc);
3508                 if (rc == 0 && desc->bd_nob_transferred != desc->bd_nob) {
3509                         DEBUG_REQ(D_ERROR, req, "truncated bulk %s %d(%d)",
3510                                   bulk2type(req), desc->bd_nob_transferred,
3511                                   desc->bd_nob);
3512                         /* XXX should this be a different errno? */
3513                         rc = -ETIMEDOUT;
3514                 }
3515         }
3516
3517         RETURN(rc);
3518 }
3519 EXPORT_SYMBOL(target_bulk_io);
3520
3521 #endif /* HAVE_SERVER_SUPPORT */