Whamcloud - gitweb
LU-12956 ldlm: fix hrtimer using
[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_get_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_get_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_get_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         /* In case of target disconnect, updating sec ctx immediately is
1598          * required in order to record latest sequence number used.
1599          * Sequence is normally updated on export destroy, but this event
1600          * can occur too late, ie after a new target connect request has
1601          * been processed.
1602          * Maintaining correct sequence when client connection becomes idle
1603          * ensures that GSS does not erroneously consider requests as replays.
1604          */
1605         rc = sptlrpc_export_update_ctx(req->rq_export);
1606         if (rc)
1607                 RETURN(rc);
1608
1609         /* Keep the rq_export around so we can send the reply. */
1610         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1611
1612         RETURN(0);
1613 }
1614
1615 void target_destroy_export(struct obd_export *exp)
1616 {
1617         struct obd_import *imp = NULL;
1618         /*
1619          * exports created from last_rcvd data, and "fake"
1620          * exports created by lctl don't have an import
1621          */
1622         spin_lock(&exp->exp_lock);
1623         if (exp->exp_imp_reverse != NULL) {
1624                 imp = exp->exp_imp_reverse;
1625                 exp->exp_imp_reverse = NULL;
1626         }
1627         spin_unlock(&exp->exp_lock);
1628         if (imp != NULL)
1629                 client_destroy_import(imp);
1630
1631         LASSERT_ATOMIC_ZERO(&exp->exp_locks_count);
1632         LASSERT_ATOMIC_ZERO(&exp->exp_rpc_count);
1633         LASSERT_ATOMIC_ZERO(&exp->exp_cb_count);
1634         LASSERT_ATOMIC_ZERO(&exp->exp_replay_count);
1635 }
1636 EXPORT_SYMBOL(target_destroy_export);
1637
1638 /*
1639  * Recovery functions
1640  */
1641 static void target_request_copy_get(struct ptlrpc_request *req)
1642 {
1643         class_export_rpc_inc(req->rq_export);
1644         LASSERT(list_empty(&req->rq_list));
1645         INIT_LIST_HEAD(&req->rq_replay_list);
1646
1647         /* Increase refcount to keep request in queue. */
1648         atomic_inc(&req->rq_refcount);
1649         /* Let export know it has replays to be handled. */
1650         atomic_inc(&req->rq_export->exp_replay_count);
1651 }
1652
1653 static void target_request_copy_put(struct ptlrpc_request *req)
1654 {
1655         LASSERT(list_empty(&req->rq_replay_list));
1656         LASSERT_ATOMIC_POS(&req->rq_export->exp_replay_count);
1657
1658         atomic_dec(&req->rq_export->exp_replay_count);
1659         class_export_rpc_dec(req->rq_export);
1660         ptlrpc_server_drop_request(req);
1661 }
1662
1663 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1664 {
1665         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1666         struct obd_export *exp = req->rq_export;
1667         struct ptlrpc_request *reqiter;
1668         struct ptlrpc_request *dup_req = NULL;
1669         int dup = 0;
1670
1671         LASSERT(exp);
1672
1673         spin_lock(&exp->exp_lock);
1674         list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1675                             rq_replay_list) {
1676                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1677                         dup_req = reqiter;
1678                         dup = 1;
1679                         break;
1680                 }
1681         }
1682
1683         if (dup) {
1684                 /* We expect it with RESENT and REPLAY flags. */
1685                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1686                     (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1687                         CERROR("invalid flags %x of resent replay\n",
1688                                lustre_msg_get_flags(req->rq_reqmsg));
1689
1690                 if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1691                         __u32 new_conn;
1692
1693                         new_conn = lustre_msg_get_conn_cnt(req->rq_reqmsg);
1694                         if (new_conn >
1695                             lustre_msg_get_conn_cnt(dup_req->rq_reqmsg))
1696                                 lustre_msg_set_conn_cnt(dup_req->rq_reqmsg,
1697                                                         new_conn);
1698                 }
1699         } else {
1700                 list_add_tail(&req->rq_replay_list,
1701                               &exp->exp_req_replay_queue);
1702         }
1703
1704         spin_unlock(&exp->exp_lock);
1705         return dup;
1706 }
1707
1708 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1709 {
1710         LASSERT(!list_empty(&req->rq_replay_list));
1711         LASSERT(req->rq_export);
1712
1713         spin_lock(&req->rq_export->exp_lock);
1714         list_del_init(&req->rq_replay_list);
1715         spin_unlock(&req->rq_export->exp_lock);
1716 }
1717
1718 static void target_finish_recovery(struct lu_target *lut)
1719 {
1720         struct obd_device *obd = lut->lut_obd;
1721
1722         ENTRY;
1723
1724         /* Only log a recovery message when recovery has occurred. */
1725         if (obd->obd_recovery_start) {
1726                 time64_t now = ktime_get_seconds();
1727                 time64_t elapsed_time;
1728
1729                 elapsed_time = max_t(time64_t, now - obd->obd_recovery_start,
1730                                      1);
1731                 LCONSOLE_INFO("%s: Recovery over after %lld:%.02lld, of %d clients %d recovered and %d %s evicted.\n",
1732                               obd->obd_name, elapsed_time / 60,
1733                               elapsed_time % 60,
1734                               atomic_read(&obd->obd_max_recoverable_clients),
1735                               atomic_read(&obd->obd_connected_clients),
1736                               obd->obd_stale_clients,
1737                               obd->obd_stale_clients == 1 ? "was" : "were");
1738         }
1739
1740         ldlm_reprocess_recovery_done(obd->obd_namespace);
1741         spin_lock(&obd->obd_recovery_task_lock);
1742         if (!list_empty(&obd->obd_req_replay_queue) ||
1743             !list_empty(&obd->obd_lock_replay_queue) ||
1744             !list_empty(&obd->obd_final_req_queue)) {
1745                 CERROR("%s: Recovery queues ( %s%s%s) are not empty\n",
1746                        obd->obd_name,
1747                        list_empty(&obd->obd_req_replay_queue) ? "" : "req ",
1748                        list_empty(&obd->obd_lock_replay_queue) ? \
1749                                   "" : "lock ",
1750                        list_empty(&obd->obd_final_req_queue) ? \
1751                                   "" : "final ");
1752                 spin_unlock(&obd->obd_recovery_task_lock);
1753                 LBUG();
1754         }
1755         spin_unlock(&obd->obd_recovery_task_lock);
1756
1757         obd->obd_recovery_end = ktime_get_seconds();
1758
1759         /* When recovery finished, cleanup orphans on MDS and OST. */
1760         if (obd->obd_type && OBP(obd, postrecov)) {
1761                 int rc = OBP(obd, postrecov)(obd);
1762
1763                 if (rc < 0)
1764                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1765                                       obd->obd_name, rc);
1766         }
1767         EXIT;
1768 }
1769
1770 static void abort_req_replay_queue(struct obd_device *obd)
1771 {
1772         struct ptlrpc_request *req, *n;
1773         LIST_HEAD(abort_list);
1774
1775         spin_lock(&obd->obd_recovery_task_lock);
1776         list_splice_init(&obd->obd_req_replay_queue, &abort_list);
1777         spin_unlock(&obd->obd_recovery_task_lock);
1778         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1779                 DEBUG_REQ(D_WARNING, req, "aborted:");
1780                 req->rq_status = -ENOTCONN;
1781                 if (ptlrpc_error(req)) {
1782                         DEBUG_REQ(D_ERROR, req,
1783                                   "failed abort_req_reply; skipping");
1784                 }
1785                 target_exp_dequeue_req_replay(req);
1786                 target_request_copy_put(req);
1787         }
1788 }
1789
1790 static void abort_lock_replay_queue(struct obd_device *obd)
1791 {
1792         struct ptlrpc_request *req, *n;
1793         LIST_HEAD(abort_list);
1794
1795         spin_lock(&obd->obd_recovery_task_lock);
1796         list_splice_init(&obd->obd_lock_replay_queue, &abort_list);
1797         spin_unlock(&obd->obd_recovery_task_lock);
1798         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1799                 DEBUG_REQ(D_ERROR, req, "aborted:");
1800                 req->rq_status = -ENOTCONN;
1801                 if (ptlrpc_error(req)) {
1802                         DEBUG_REQ(D_ERROR, req,
1803                                   "failed abort_lock_reply; skipping");
1804                 }
1805                 target_request_copy_put(req);
1806         }
1807 }
1808
1809 /*
1810  * Called from a cleanup function if the device is being cleaned up
1811  * forcefully.  The exports should all have been disconnected already,
1812  * the only thing left to do is
1813  * - clear the recovery flags
1814  * - cancel the timer
1815  * - free queued requests and replies, but don't send replies
1816  * Because the obd_stopping flag is set, no new requests should be received.
1817  */
1818 void target_cleanup_recovery(struct obd_device *obd)
1819 {
1820         struct ptlrpc_request *req, *n;
1821         LIST_HEAD(clean_list);
1822
1823         spin_lock(&obd->obd_dev_lock);
1824         if (!obd->obd_recovering) {
1825                 spin_unlock(&obd->obd_dev_lock);
1826                 EXIT;
1827                 return;
1828         }
1829         obd->obd_recovering = obd->obd_abort_recovery = 0;
1830         spin_unlock(&obd->obd_dev_lock);
1831
1832         spin_lock(&obd->obd_recovery_task_lock);
1833         target_cancel_recovery_timer(obd);
1834         list_splice_init(&obd->obd_req_replay_queue, &clean_list);
1835         spin_unlock(&obd->obd_recovery_task_lock);
1836
1837         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1838                 LASSERT(req->rq_reply_state == NULL);
1839                 target_exp_dequeue_req_replay(req);
1840                 target_request_copy_put(req);
1841         }
1842
1843         spin_lock(&obd->obd_recovery_task_lock);
1844         list_splice_init(&obd->obd_lock_replay_queue, &clean_list);
1845         list_splice_init(&obd->obd_final_req_queue, &clean_list);
1846         spin_unlock(&obd->obd_recovery_task_lock);
1847
1848         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1849                 LASSERT(req->rq_reply_state == NULL);
1850                 target_request_copy_put(req);
1851         }
1852
1853         EXIT;
1854 }
1855 EXPORT_SYMBOL(target_cleanup_recovery);
1856
1857 /* obd_recovery_task_lock should be held */
1858 void target_cancel_recovery_timer(struct obd_device *obd)
1859 {
1860         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1861         hrtimer_cancel(&obd->obd_recovery_timer);
1862 }
1863
1864 static void target_start_recovery_timer(struct obd_device *obd)
1865 {
1866         ktime_t delay;
1867
1868         if (obd->obd_recovery_start != 0)
1869                 return;
1870
1871         spin_lock(&obd->obd_dev_lock);
1872         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1873                 spin_unlock(&obd->obd_dev_lock);
1874                 return;
1875         }
1876
1877         LASSERT(obd->obd_recovery_timeout != 0);
1878
1879         if (obd->obd_recovery_start != 0) {
1880                 spin_unlock(&obd->obd_dev_lock);
1881                 return;
1882         }
1883
1884         obd->obd_recovery_start = ktime_get_seconds();
1885         delay = ktime_set(obd->obd_recovery_start +
1886                           obd->obd_recovery_timeout, 0);
1887         hrtimer_start(&obd->obd_recovery_timer, delay, HRTIMER_MODE_ABS);
1888         spin_unlock(&obd->obd_dev_lock);
1889
1890         LCONSOLE_WARN("%s: Will be in recovery for at least %u:%02u, or until %d client%s reconnect%s\n",
1891                       obd->obd_name,
1892                       obd->obd_recovery_timeout / 60,
1893                       obd->obd_recovery_timeout % 60,
1894                       atomic_read(&obd->obd_max_recoverable_clients),
1895                       (atomic_read(&obd->obd_max_recoverable_clients) == 1) ?
1896                       "" : "s",
1897                       (atomic_read(&obd->obd_max_recoverable_clients) == 1) ?
1898                       "s" : "");
1899 }
1900
1901 /**
1902  * extend recovery window.
1903  *
1904  * if @extend is true, extend recovery window to have @dr_timeout remaining
1905  * at least; otherwise, make sure the recovery timeout value is not less
1906  * than @dr_timeout.
1907  */
1908 static void extend_recovery_timer(struct obd_device *obd, timeout_t dr_timeout,
1909                                   bool extend)
1910 {
1911         ktime_t left_ns;
1912         timeout_t timeout;
1913         timeout_t left;
1914
1915         spin_lock(&obd->obd_dev_lock);
1916         if (!obd->obd_recovering || obd->obd_abort_recovery ||
1917             obd->obd_stopping) {
1918                 spin_unlock(&obd->obd_dev_lock);
1919                 return;
1920         }
1921         LASSERT(obd->obd_recovery_start != 0);
1922
1923         left_ns = hrtimer_get_remaining(&obd->obd_recovery_timer);
1924         left = ktime_divns(left_ns, NSEC_PER_SEC);
1925
1926         if (extend) {
1927                 timeout = obd->obd_recovery_timeout;
1928                 /* dr_timeout will happen after the hrtimer has expired.
1929                  * Add the excess time to the soft recovery timeout without
1930                  * exceeding the hard recovery timeout.
1931                  */
1932                 if (dr_timeout > left) {
1933                         timeout += dr_timeout - left;
1934                         timeout = min_t(timeout_t, obd->obd_recovery_time_hard,
1935                                         timeout);
1936                 }
1937         } else {
1938                 timeout = clamp_t(timeout_t, dr_timeout,
1939                                   obd->obd_recovery_timeout,
1940                                   obd->obd_recovery_time_hard);
1941         }
1942
1943         if (timeout == obd->obd_recovery_time_hard)
1944                 CWARN("%s: extended recovery timer reached hard limit: %d, extend: %d\n",
1945                       obd->obd_name, timeout, extend);
1946
1947         if (obd->obd_recovery_timeout < timeout) {
1948                 ktime_t end, now;
1949
1950                 obd->obd_recovery_timeout = timeout;
1951                 end = ktime_set(obd->obd_recovery_start + timeout, 0);
1952                 now = ktime_set(ktime_get_seconds(), 0);
1953                 left_ns = ktime_sub(end, now);
1954                 hrtimer_start(&obd->obd_recovery_timer, end, HRTIMER_MODE_ABS);
1955                 left = ktime_divns(left_ns, NSEC_PER_SEC);
1956         }
1957         spin_unlock(&obd->obd_dev_lock);
1958
1959         CDEBUG(D_HA, "%s: recovery timer will expire in %d seconds\n",
1960                 obd->obd_name, left);
1961 }
1962
1963 /* Reset the timer with each new client connection */
1964 /*
1965  * This timer is actually reconnect_timer, which is for making sure
1966  * the total recovery window is at least as big as my reconnect
1967  * attempt timing. So the initial recovery time_out will be set to
1968  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1969  * from client is bigger than this, then the recovery time_out will
1970  * be extended to make sure the client could be reconnected, in the
1971  * process, the timeout from the new client should be ignored.
1972  */
1973 static void
1974 check_and_start_recovery_timer(struct obd_device *obd,
1975                                struct ptlrpc_request *req,
1976                                int new_client)
1977 {
1978         timeout_t service_timeout = lustre_msg_get_service_timeout(req->rq_reqmsg);
1979         struct obd_device_target *obt = &obd->u.obt;
1980
1981         if (!new_client && service_timeout)
1982                 /*
1983                  * Teach server about old server's estimates, as first guess
1984                  * at how long new requests will take.
1985                  */
1986                 at_measured(&req->rq_rqbd->rqbd_svcpt->scp_at_estimate,
1987                             service_timeout);
1988
1989         target_start_recovery_timer(obd);
1990
1991         /*
1992          * Convert the service time to RPC timeout,
1993          * and reuse service_timeout to limit stack usage.
1994          */
1995         service_timeout = at_est2timeout(service_timeout);
1996
1997         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_SLUGGISH_NET) &&
1998             service_timeout < at_extra)
1999                 service_timeout = at_extra;
2000
2001         /*
2002          * We expect other clients to timeout within service_timeout, then try
2003          * to reconnect, then try the failover server.  The max delay between
2004          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL.
2005          */
2006         service_timeout += 2 * INITIAL_CONNECT_TIMEOUT;
2007
2008         LASSERT(obt->obt_magic == OBT_MAGIC);
2009         service_timeout += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
2010         if (service_timeout > obd->obd_recovery_timeout && !new_client)
2011                 extend_recovery_timer(obd, service_timeout, false);
2012 }
2013
2014 /** Health checking routines */
2015 static inline int exp_connect_healthy(struct obd_export *exp)
2016 {
2017         return exp->exp_in_recovery;
2018 }
2019
2020 /** if export done req_replay or has replay in queue */
2021 static inline int exp_req_replay_healthy(struct obd_export *exp)
2022 {
2023         return (!exp->exp_req_replay_needed ||
2024                 atomic_read(&exp->exp_replay_count) > 0);
2025 }
2026
2027
2028 static inline int exp_req_replay_healthy_or_from_mdt(struct obd_export *exp)
2029 {
2030         return (exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) ||
2031                exp_req_replay_healthy(exp);
2032 }
2033
2034 /** if export done lock_replay or has replay in queue */
2035 static inline int exp_lock_replay_healthy(struct obd_export *exp)
2036 {
2037         return (!exp->exp_lock_replay_needed ||
2038                 atomic_read(&exp->exp_replay_count) > 0);
2039 }
2040
2041 static inline int exp_vbr_healthy(struct obd_export *exp)
2042 {
2043         return !exp->exp_vbr_failed;
2044 }
2045
2046 static inline int exp_finished(struct obd_export *exp)
2047 {
2048         return exp->exp_in_recovery && !exp->exp_lock_replay_needed;
2049 }
2050
2051 static inline int exp_finished_or_from_mdt(struct obd_export *exp)
2052 {
2053         return (exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) ||
2054                 exp_finished(exp);
2055 }
2056
2057 static int check_for_next_transno(struct lu_target *lut)
2058 {
2059         struct ptlrpc_request *req = NULL;
2060         struct obd_device *obd = lut->lut_obd;
2061         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2062         int wake_up = 0, connected, completed, queue_len;
2063         __u64 req_transno = 0;
2064         __u64 update_transno = 0;
2065         __u64 next_transno = 0;
2066
2067         ENTRY;
2068
2069         spin_lock(&obd->obd_recovery_task_lock);
2070         if (!list_empty(&obd->obd_req_replay_queue)) {
2071                 req = list_entry(obd->obd_req_replay_queue.next,
2072                                      struct ptlrpc_request, rq_list);
2073                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
2074         }
2075
2076         if (!obd->obd_abort_recov_mdt && tdtd)
2077                 update_transno = distribute_txn_get_next_transno(tdtd);
2078
2079         connected = atomic_read(&obd->obd_connected_clients);
2080         completed = connected - atomic_read(&obd->obd_req_replay_clients);
2081         queue_len = obd->obd_requests_queued_for_recovery;
2082         next_transno = obd->obd_next_recovery_transno;
2083
2084         CDEBUG(D_HA,
2085                "max: %d, connected: %d, completed: %d, queue_len: %d, req_transno: %llu, next_transno: %llu\n",
2086                atomic_read(&obd->obd_max_recoverable_clients),
2087                connected, completed,
2088                queue_len, req_transno, next_transno);
2089
2090         if (obd->obd_abort_recovery) {
2091                 CDEBUG(D_HA, "waking for aborted recovery\n");
2092                 wake_up = 1;
2093         } else if (obd->obd_recovery_expired) {
2094                 CDEBUG(D_HA, "waking for expired recovery\n");
2095                 wake_up = 1;
2096         } else if (!obd->obd_abort_recov_mdt && tdtd && req &&
2097                    is_req_replayed_by_update(req)) {
2098                 LASSERTF(req_transno < next_transno,
2099                          "req_transno %llu next_transno%llu\n", req_transno,
2100                          next_transno);
2101                 CDEBUG(D_HA, "waking for duplicate req (%llu)\n",
2102                        req_transno);
2103                 wake_up = 1;
2104         } else if (req_transno == next_transno ||
2105                    (update_transno != 0 && update_transno <= next_transno)) {
2106                 CDEBUG(D_HA, "waking for next (%lld)\n", next_transno);
2107                 wake_up = 1;
2108         } else if (queue_len > 0 &&
2109                    queue_len == atomic_read(&obd->obd_req_replay_clients)) {
2110                 /** handle gaps occured due to lost reply or VBR */
2111                 LASSERTF(req_transno >= next_transno,
2112                          "req_transno: %llu, next_transno: %llu\n",
2113                          req_transno, next_transno);
2114                 CDEBUG(D_HA,
2115                        "%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",
2116                        obd->obd_name, obd->obd_version_recov ? "ON" : "OFF",
2117                        next_transno, queue_len, completed, connected,
2118                        req_transno, update_transno, obd->obd_last_committed);
2119                 obd->obd_next_recovery_transno = req_transno;
2120                 wake_up = 1;
2121         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
2122                 CDEBUG(D_HA, "waking for completed recovery\n");
2123                 wake_up = 1;
2124         } else if (OBD_FAIL_CHECK(OBD_FAIL_MDS_RECOVERY_ACCEPTS_GAPS)) {
2125                 CDEBUG(D_HA,
2126                        "accepting transno gaps is explicitly allowed by fail_lock, waking up (%lld)\n",
2127                        next_transno);
2128                 obd->obd_next_recovery_transno = req_transno;
2129                 wake_up = 1;
2130         }
2131         spin_unlock(&obd->obd_recovery_task_lock);
2132         return wake_up;
2133 }
2134
2135 static int check_for_next_lock(struct lu_target *lut)
2136 {
2137         struct obd_device *obd = lut->lut_obd;
2138         int wake_up = 0;
2139
2140         spin_lock(&obd->obd_recovery_task_lock);
2141         if (!list_empty(&obd->obd_lock_replay_queue)) {
2142                 CDEBUG(D_HA, "waking for next lock\n");
2143                 wake_up = 1;
2144         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
2145                 CDEBUG(D_HA, "waking for completed lock replay\n");
2146                 wake_up = 1;
2147         } else if (obd->obd_abort_recovery) {
2148                 CDEBUG(D_HA, "waking for aborted recovery\n");
2149                 wake_up = 1;
2150         } else if (obd->obd_recovery_expired) {
2151                 CDEBUG(D_HA, "waking for expired recovery\n");
2152                 wake_up = 1;
2153         }
2154         spin_unlock(&obd->obd_recovery_task_lock);
2155
2156         return wake_up;
2157 }
2158
2159 static int check_update_llog(struct lu_target *lut)
2160 {
2161         struct obd_device *obd = lut->lut_obd;
2162         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2163
2164         if (obd->obd_abort_recovery) {
2165                 CDEBUG(D_HA, "waking for aborted recovery\n");
2166                 return 1;
2167         }
2168
2169         if (atomic_read(&tdtd->tdtd_recovery_threads_count) == 0) {
2170                 CDEBUG(D_HA, "waking for completion of reading update log\n");
2171                 return 1;
2172         }
2173
2174         return 0;
2175 }
2176
2177 /**
2178  * wait for recovery events,
2179  * check its status with help of check_routine
2180  * evict dead clients via health_check
2181  */
2182 static int target_recovery_overseer(struct lu_target *lut,
2183                                     int (*check_routine)(struct lu_target *),
2184                                     int (*health_check)(struct obd_export *))
2185 {
2186         struct obd_device *obd = lut->lut_obd;
2187         struct target_distribute_txn_data *tdtd;
2188         time64_t last = 0;
2189         time64_t now;
2190 repeat:
2191         if (obd->obd_recovering && obd->obd_recovery_start == 0) {
2192                 now = ktime_get_seconds();
2193                 if (now - last > 600) {
2194                         LCONSOLE_INFO("%s: in recovery but waiting for the first client to connect\n",
2195                                       obd->obd_name);
2196                         last = now;
2197                 }
2198         }
2199         if (obd->obd_recovery_start != 0 && ktime_get_seconds() >=
2200               (obd->obd_recovery_start + obd->obd_recovery_time_hard)) {
2201                 __u64 next_update_transno = 0;
2202
2203                 /*
2204                  * Only abort the recovery if there are no update recovery
2205                  * left in the queue
2206                  */
2207                 spin_lock(&obd->obd_recovery_task_lock);
2208                 if (!obd->obd_abort_recov_mdt && lut->lut_tdtd) {
2209                         next_update_transno =
2210                                 distribute_txn_get_next_transno(lut->lut_tdtd);
2211
2212                         tdtd = lut->lut_tdtd;
2213                         /*
2214                          * If next_update_transno == 0, it probably because
2215                          * updatelog retrieve threads did not get any records
2216                          * yet, let's wait those threads stopped
2217                          */
2218                         if (next_update_transno == 0) {
2219                                 spin_unlock(&obd->obd_recovery_task_lock);
2220
2221                                 while (wait_event_timeout(
2222                                         tdtd->tdtd_recovery_threads_waitq,
2223                                         check_update_llog(lut),
2224                                         cfs_time_seconds(60)) == 0);
2225
2226                                 spin_lock(&obd->obd_recovery_task_lock);
2227                                 next_update_transno =
2228                                         distribute_txn_get_next_transno(tdtd);
2229                         }
2230                 }
2231
2232                 if (next_update_transno != 0 && !obd->obd_abort_recovery) {
2233                         obd->obd_next_recovery_transno = next_update_transno;
2234                         spin_unlock(&obd->obd_recovery_task_lock);
2235                         /*
2236                          * Disconnect unfinished exports from clients, and
2237                          * keep connection from MDT to make sure the update
2238                          * recovery will still keep trying until some one
2239                          * manually abort the recovery
2240                          */
2241                         class_disconnect_stale_exports(obd,
2242                                                 exp_finished_or_from_mdt);
2243                         /* Abort all of replay & replay lock req from clients */
2244                         abort_req_replay_queue(obd);
2245                         abort_lock_replay_queue(obd);
2246                         CDEBUG(D_HA,
2247                                "%s: there are still update replay (%#llx)in the queue.\n",
2248                                obd->obd_name, next_update_transno);
2249                 } else {
2250                         obd->obd_abort_recovery = 1;
2251                         spin_unlock(&obd->obd_recovery_task_lock);
2252                         CWARN("%s recovery is aborted by hard timeout\n",
2253                               obd->obd_name);
2254                 }
2255         }
2256
2257         while (wait_event_timeout(obd->obd_next_transno_waitq,
2258                                   check_routine(lut),
2259                                   cfs_time_seconds(60)) == 0)
2260                 ; /* wait indefinitely for event, but don't trigger watchdog */
2261
2262         if (obd->obd_abort_recovery) {
2263                 CWARN("recovery is aborted, evict exports in recovery\n");
2264                 if (lut->lut_tdtd != NULL) {
2265                         tdtd = lut->lut_tdtd;
2266                         /*
2267                          * Let's wait all of the update log recovery thread
2268                          * finished
2269                          */
2270                         wait_event_idle(
2271                                 tdtd->tdtd_recovery_threads_waitq,
2272                                 atomic_read(&tdtd->tdtd_recovery_threads_count)
2273                                 == 0);
2274                         /* Then abort the update recovery list */
2275                         dtrq_list_destroy(lut->lut_tdtd);
2276                 }
2277
2278                 /** evict exports which didn't finish recovery yet */
2279                 class_disconnect_stale_exports(obd, exp_finished);
2280                 return 1;
2281         } else if (obd->obd_recovery_expired) {
2282                 obd->obd_recovery_expired = 0;
2283
2284                 /** If some clients died being recovered, evict them */
2285                 LCONSOLE_WARN("%s: recovery is timed out, evict stale exports\n",
2286                               obd->obd_name);
2287                 /** evict cexports with no replay in queue, they are stalled */
2288                 class_disconnect_stale_exports(obd, health_check);
2289
2290                 /** continue with VBR */
2291                 spin_lock(&obd->obd_dev_lock);
2292                 obd->obd_version_recov = 1;
2293                 spin_unlock(&obd->obd_dev_lock);
2294                 /**
2295                  * reset timer, recovery will proceed with versions now,
2296                  * timeout is set just to handle reconnection delays
2297                  */
2298                 extend_recovery_timer(obd, RECONNECT_DELAY_MAX, true);
2299                 /**
2300                  * Wait for recovery events again, after evicting bad clients
2301                  */
2302                 goto repeat;
2303         }
2304         return 0;
2305 }
2306
2307 static struct ptlrpc_request *target_next_replay_lock(struct lu_target *lut)
2308 {
2309         struct obd_device *obd = lut->lut_obd;
2310         struct ptlrpc_request *req = NULL;
2311
2312         CDEBUG(D_HA, "Waiting for lock\n");
2313         if (target_recovery_overseer(lut, check_for_next_lock,
2314                                      exp_lock_replay_healthy))
2315                 abort_lock_replay_queue(obd);
2316
2317         spin_lock(&obd->obd_recovery_task_lock);
2318         if (!list_empty(&obd->obd_lock_replay_queue)) {
2319                 req = list_entry(obd->obd_lock_replay_queue.next,
2320                                      struct ptlrpc_request, rq_list);
2321                 list_del_init(&req->rq_list);
2322                 spin_unlock(&obd->obd_recovery_task_lock);
2323         } else {
2324                 spin_unlock(&obd->obd_recovery_task_lock);
2325                 LASSERT(list_empty(&obd->obd_lock_replay_queue));
2326                 LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
2327                 /** evict exports failed VBR */
2328                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
2329         }
2330         return req;
2331 }
2332
2333 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
2334 {
2335         struct ptlrpc_request *req = NULL;
2336
2337         spin_lock(&obd->obd_recovery_task_lock);
2338         if (!list_empty(&obd->obd_final_req_queue)) {
2339                 req = list_entry(obd->obd_final_req_queue.next,
2340                                      struct ptlrpc_request, rq_list);
2341                 list_del_init(&req->rq_list);
2342                 spin_unlock(&obd->obd_recovery_task_lock);
2343                 if (req->rq_export->exp_in_recovery) {
2344                         spin_lock(&req->rq_export->exp_lock);
2345                         req->rq_export->exp_in_recovery = 0;
2346                         spin_unlock(&req->rq_export->exp_lock);
2347                 }
2348         } else {
2349                 spin_unlock(&obd->obd_recovery_task_lock);
2350         }
2351         return req;
2352 }
2353
2354 static void handle_recovery_req(struct ptlrpc_thread *thread,
2355                                 struct ptlrpc_request *req,
2356                                 svc_handler_t handler)
2357 {
2358         ENTRY;
2359
2360         /**
2361          * export can be evicted during recovery, no need to handle replays for
2362          * it after that, discard such request silently
2363          */
2364         if (req->rq_export->exp_disconnected)
2365                 RETURN_EXIT;
2366
2367         req->rq_session.lc_thread = thread;
2368         req->rq_svc_thread = thread;
2369         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
2370
2371         /* thread context */
2372         lu_context_enter(&thread->t_env->le_ctx);
2373         (void)handler(req);
2374         lu_context_exit(&thread->t_env->le_ctx);
2375
2376         req->rq_svc_thread->t_env->le_ses = NULL;
2377
2378         /* don't reset timer for final stage */
2379         if (!exp_finished(req->rq_export)) {
2380                 timeout_t timeout = obd_timeout;
2381
2382                 /**
2383                  * Add request @timeout to the recovery time so next request from
2384                  * this client may come in recovery time
2385                  */
2386                 if (!AT_OFF) {
2387                         struct ptlrpc_service_part *svcpt;
2388                         timeout_t est_timeout;
2389
2390                         svcpt = req->rq_rqbd->rqbd_svcpt;
2391                         /*
2392                          * If the server sent early reply for this request,
2393                          * the client will recalculate the timeout according to
2394                          * current server estimate service time, so we will
2395                          * use the maxium timeout here for waiting the client
2396                          * sending the next req
2397                          */
2398                         est_timeout = at_get(&svcpt->scp_at_estimate);
2399                         timeout = max_t(timeout_t, at_est2timeout(est_timeout),
2400                                         lustre_msg_get_timeout(req->rq_reqmsg));
2401                         /*
2402                          * Add 2 net_latency, one for balance rq_deadline
2403                          * (see ptl_send_rpc), one for resend the req to server,
2404                          * Note: client will pack net_latency in replay req
2405                          * (see ptlrpc_replay_req)
2406                          */
2407                         timeout += 2 * lustre_msg_get_service_timeout(req->rq_reqmsg);
2408                 }
2409                 extend_recovery_timer(class_exp2obd(req->rq_export), timeout,
2410                                       true);
2411         }
2412         EXIT;
2413 }
2414
2415 /** Checking routines for recovery */
2416 static int check_for_recovery_ready(struct lu_target *lut)
2417 {
2418         struct obd_device *obd = lut->lut_obd;
2419         unsigned int clnts = atomic_read(&obd->obd_connected_clients);
2420
2421         CDEBUG(D_HA,
2422                "connected %d stale %d max_recoverable_clients %d abort %d expired %d\n",
2423                clnts, obd->obd_stale_clients,
2424                atomic_read(&obd->obd_max_recoverable_clients),
2425                obd->obd_abort_recovery, obd->obd_recovery_expired);
2426
2427         if (!obd->obd_abort_recovery && !obd->obd_recovery_expired) {
2428                 LASSERT(clnts <=
2429                         atomic_read(&obd->obd_max_recoverable_clients));
2430                 if (clnts + obd->obd_stale_clients <
2431                     atomic_read(&obd->obd_max_recoverable_clients))
2432                         return 0;
2433         }
2434
2435         if (!obd->obd_abort_recov_mdt && lut->lut_tdtd != NULL) {
2436                 if (!lut->lut_tdtd->tdtd_replay_ready &&
2437                     !obd->obd_abort_recovery && !obd->obd_stopping) {
2438                         /*
2439                          * Let's extend recovery timer, in case the recovery
2440                          * timer expired, and some clients got evicted
2441                          */
2442                         extend_recovery_timer(obd, obd->obd_recovery_timeout,
2443                                               true);
2444                         CDEBUG(D_HA,
2445                                "%s update recovery is not ready, extend recovery %d\n",
2446                                obd->obd_name, obd->obd_recovery_timeout);
2447                         return 0;
2448                 }
2449         }
2450
2451         return 1;
2452 }
2453
2454 enum {
2455         REQUEST_RECOVERY = 1,
2456         UPDATE_RECOVERY = 2,
2457 };
2458
2459 static __u64 get_next_replay_req_transno(struct obd_device *obd)
2460 {
2461         __u64 transno = 0;
2462
2463         if (!list_empty(&obd->obd_req_replay_queue)) {
2464                 struct ptlrpc_request *req;
2465
2466                 req = list_entry(obd->obd_req_replay_queue.next,
2467                                  struct ptlrpc_request, rq_list);
2468                 transno = lustre_msg_get_transno(req->rq_reqmsg);
2469         }
2470
2471         return transno;
2472 }
2473
2474 static __u64 get_next_transno(struct lu_target *lut, int *type)
2475 {
2476         struct obd_device *obd = lut->lut_obd;
2477         struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2478         __u64 transno = 0;
2479         __u64 update_transno;
2480
2481         ENTRY;
2482
2483         transno = get_next_replay_req_transno(obd);
2484         if (type != NULL)
2485                 *type = REQUEST_RECOVERY;
2486
2487         if (!tdtd || obd->obd_abort_recov_mdt)
2488                 RETURN(transno);
2489
2490         update_transno = distribute_txn_get_next_transno(tdtd);
2491         if (transno == 0 || (transno >= update_transno &&
2492                              update_transno != 0)) {
2493                 transno = update_transno;
2494                 if (type != NULL)
2495                         *type = UPDATE_RECOVERY;
2496         }
2497
2498         RETURN(transno);
2499 }
2500
2501 /**
2502  * drop duplicate replay request
2503  *
2504  * Because the operation has been replayed by update recovery, the request
2505  * with the same transno will be dropped and also notify the client to send
2506  * next replay request.
2507  *
2508  * \param[in] env       execution environment
2509  * \param[in] obd       failover obd device
2510  * \param[in] req       request to be dropped
2511  */
2512 static void drop_duplicate_replay_req(struct lu_env *env,
2513                                       struct obd_device *obd,
2514                                       struct ptlrpc_request *req)
2515 {
2516         DEBUG_REQ(D_HA, req,
2517                   "remove t%lld from %s because duplicate update records found",
2518                   lustre_msg_get_transno(req->rq_reqmsg),
2519                   libcfs_nid2str(req->rq_peer.nid));
2520
2521         /*
2522          * Right now, only for MDS reint operation update replay and
2523          * normal request replay can have the same transno
2524          */
2525         if (lustre_msg_get_opc(req->rq_reqmsg) == MDS_REINT) {
2526                 req_capsule_set(&req->rq_pill, &RQF_MDS_REINT);
2527                 req->rq_status = req_capsule_server_pack(&req->rq_pill);
2528                 if (likely(req->rq_export))
2529                         target_committed_to_req(req);
2530                 lustre_msg_set_transno(req->rq_repmsg, req->rq_transno);
2531                 target_send_reply(req, req->rq_status, 0);
2532         } else {
2533                 DEBUG_REQ(D_ERROR, req, "wrong opc from %s",
2534                 libcfs_nid2str(req->rq_peer.nid));
2535         }
2536         target_exp_dequeue_req_replay(req);
2537         target_request_copy_put(req);
2538         obd->obd_replayed_requests++;
2539 }
2540
2541 #define WATCHDOG_TIMEOUT (obd_timeout * 10)
2542
2543 static void replay_request_or_update(struct lu_env *env,
2544                                      struct lu_target *lut,
2545                                      struct target_recovery_data *trd,
2546                                      struct ptlrpc_thread *thread)
2547 {
2548         struct obd_device *obd = lut->lut_obd;
2549         struct ptlrpc_request *req = NULL;
2550         int type;
2551         __u64 transno;
2552
2553         ENTRY;
2554
2555         CDEBUG(D_HA, "Waiting for transno %lld\n",
2556                obd->obd_next_recovery_transno);
2557
2558         /* Replay all of request and update by transno */
2559         do {
2560                 struct target_distribute_txn_data *tdtd = lut->lut_tdtd;
2561
2562                 CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_DELAY2, cfs_fail_val);
2563
2564                 /**
2565                  * It is needed to extend recovery window above
2566                  *  recovery_time_soft. Extending is possible only in the
2567                  *  end of recovery window (see more details in
2568                  *  handle_recovery_req()).
2569                  */
2570                 CFS_FAIL_TIMEOUT_MS(OBD_FAIL_TGT_REPLAY_DELAY, 300);
2571
2572                 if (target_recovery_overseer(lut, check_for_next_transno,
2573                                         exp_req_replay_healthy_or_from_mdt)) {
2574                         abort_req_replay_queue(obd);
2575                         abort_lock_replay_queue(obd);
2576                         goto abort;
2577                 }
2578
2579                 spin_lock(&obd->obd_recovery_task_lock);
2580                 transno = get_next_transno(lut, &type);
2581                 if (type == REQUEST_RECOVERY && transno != 0) {
2582                         /*
2583                          * Drop replay request from client side, if the
2584                          * replay has been executed by update with the
2585                          * same transno
2586                          */
2587                         req = list_entry(obd->obd_req_replay_queue.next,
2588                                         struct ptlrpc_request, rq_list);
2589
2590                         list_del_init(&req->rq_list);
2591                         obd->obd_requests_queued_for_recovery--;
2592                         spin_unlock(&obd->obd_recovery_task_lock);
2593
2594                         /*
2595                          * Let's check if the request has been redone by
2596                          * update replay
2597                          */
2598                         if (is_req_replayed_by_update(req)) {
2599                                 struct distribute_txn_replay_req *dtrq;
2600
2601                                 dtrq = distribute_txn_lookup_finish_list(tdtd,
2602                                                                       transno);
2603                                 LASSERT(dtrq != NULL);
2604                                 spin_lock(&tdtd->tdtd_replay_list_lock);
2605                                 list_del_init(&dtrq->dtrq_list);
2606                                 spin_unlock(&tdtd->tdtd_replay_list_lock);
2607                                 dtrq_destroy(dtrq);
2608
2609                                 drop_duplicate_replay_req(env, obd, req);
2610
2611                                 continue;
2612                         }
2613
2614                         LASSERT(trd->trd_processing_task == current->pid);
2615                         DEBUG_REQ(D_HA, req, "processing x%llu t%lld from %s",
2616                                   req->rq_xid,
2617                                   lustre_msg_get_transno(req->rq_reqmsg),
2618                                   libcfs_nid2str(req->rq_peer.nid));
2619
2620                         ptlrpc_watchdog_init(&thread->t_watchdog,
2621                                              WATCHDOG_TIMEOUT);
2622                         handle_recovery_req(thread, req,
2623                                             trd->trd_recovery_handler);
2624                         ptlrpc_watchdog_disable(&thread->t_watchdog);
2625
2626                         /**
2627                          * bz18031: increase next_recovery_transno before
2628                          * target_request_copy_put() will drop exp_rpc reference
2629                          */
2630                         spin_lock(&obd->obd_recovery_task_lock);
2631                         obd->obd_next_recovery_transno++;
2632                         spin_unlock(&obd->obd_recovery_task_lock);
2633                         target_exp_dequeue_req_replay(req);
2634                         target_request_copy_put(req);
2635                         obd->obd_replayed_requests++;
2636                 } else if (type == UPDATE_RECOVERY && transno != 0) {
2637                         struct distribute_txn_replay_req *dtrq;
2638                         int rc;
2639
2640                         spin_unlock(&obd->obd_recovery_task_lock);
2641
2642                         LASSERT(tdtd != NULL);
2643                         dtrq = distribute_txn_get_next_req(tdtd);
2644                         lu_context_enter(&thread->t_env->le_ctx);
2645                         ptlrpc_watchdog_init(&thread->t_watchdog,
2646                                              WATCHDOG_TIMEOUT);
2647                         rc = tdtd->tdtd_replay_handler(env, tdtd, dtrq);
2648                         ptlrpc_watchdog_disable(&thread->t_watchdog);
2649                         lu_context_exit(&thread->t_env->le_ctx);
2650                         extend_recovery_timer(obd, obd_timeout, true);
2651
2652                         if (rc == 0 && dtrq->dtrq_xid != 0) {
2653                                 CDEBUG(D_HA,
2654                                        "Move x%llu t%llu to finish list\n",
2655                                        dtrq->dtrq_xid,
2656                                        dtrq->dtrq_master_transno);
2657
2658                                 /* Add it to the replay finish list */
2659                                 spin_lock(&tdtd->tdtd_replay_list_lock);
2660                                 list_add(&dtrq->dtrq_list,
2661                                          &tdtd->tdtd_replay_finish_list);
2662                                 spin_unlock(&tdtd->tdtd_replay_list_lock);
2663
2664                                 spin_lock(&obd->obd_recovery_task_lock);
2665                                 if (transno == obd->obd_next_recovery_transno)
2666                                         obd->obd_next_recovery_transno++;
2667                                 else if (transno >
2668                                          obd->obd_next_recovery_transno)
2669                                         obd->obd_next_recovery_transno =
2670                                                                 transno + 1;
2671                                 spin_unlock(&obd->obd_recovery_task_lock);
2672                         } else {
2673                                 dtrq_destroy(dtrq);
2674                         }
2675                 } else {
2676                         spin_unlock(&obd->obd_recovery_task_lock);
2677 abort:
2678                         LASSERT(list_empty(&obd->obd_req_replay_queue));
2679                         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
2680                         /** evict exports failed VBR */
2681                         class_disconnect_stale_exports(obd, exp_vbr_healthy);
2682                         break;
2683                 }
2684         } while (1);
2685 }
2686
2687 static int target_recovery_thread(void *arg)
2688 {
2689         struct lu_target *lut = arg;
2690         struct obd_device *obd = lut->lut_obd;
2691         struct ptlrpc_request *req;
2692         struct target_recovery_data *trd = &obd->obd_recovery_data;
2693         unsigned long delta;
2694         struct lu_env *env;
2695         struct ptlrpc_thread *thread = NULL;
2696         int rc = 0;
2697
2698         ENTRY;
2699         OBD_ALLOC_PTR(thread);
2700         if (thread == NULL)
2701                 RETURN(-ENOMEM);
2702
2703         OBD_ALLOC_PTR(env);
2704         if (env == NULL)
2705                 GOTO(out_thread, rc = -ENOMEM);
2706         rc = lu_env_add(env);
2707         if (rc)
2708                 GOTO(out_env, rc);
2709
2710         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD);
2711         if (rc)
2712                 GOTO(out_env_remove, rc);
2713
2714         thread->t_env = env;
2715         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
2716         env->le_ctx.lc_thread = thread;
2717         tgt_io_thread_init(thread); /* init thread_big_cache for IO requests */
2718
2719         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
2720                current->pid);
2721         trd->trd_processing_task = current->pid;
2722
2723         spin_lock(&obd->obd_dev_lock);
2724         obd->obd_recovering = 1;
2725         spin_unlock(&obd->obd_dev_lock);
2726         complete(&trd->trd_starting);
2727
2728         /* first of all, we have to know the first transno to replay */
2729         if (target_recovery_overseer(lut, check_for_recovery_ready,
2730                                      exp_connect_healthy)) {
2731                 abort_req_replay_queue(obd);
2732                 abort_lock_replay_queue(obd);
2733                 if (lut->lut_tdtd != NULL)
2734                         dtrq_list_destroy(lut->lut_tdtd);
2735         }
2736
2737         /* next stage: replay requests or update */
2738         delta = jiffies;
2739         CDEBUG(D_INFO, "1: request replay stage - %d clients from t%llu\n",
2740                atomic_read(&obd->obd_req_replay_clients),
2741                obd->obd_next_recovery_transno);
2742         replay_request_or_update(env, lut, trd, thread);
2743
2744         /**
2745          * The second stage: replay locks
2746          */
2747         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
2748                atomic_read(&obd->obd_lock_replay_clients));
2749         while ((req = target_next_replay_lock(lut))) {
2750                 LASSERT(trd->trd_processing_task == current->pid);
2751                 DEBUG_REQ(D_HA, req, "processing lock from %s:",
2752                           libcfs_nid2str(req->rq_peer.nid));
2753                 handle_recovery_req(thread, req,
2754                                     trd->trd_recovery_handler);
2755                 target_request_copy_put(req);
2756                 obd->obd_replayed_locks++;
2757         }
2758
2759         /**
2760          * The third stage: reply on final pings, at this moment all clients
2761          * must have request in final queue
2762          */
2763         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_RECONNECT, cfs_fail_val);
2764         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
2765         /** Update server last boot epoch */
2766         tgt_boot_epoch_update(lut);
2767         /*
2768          * We drop recoverying flag to forward all new requests
2769          * to regular mds_handle() since now
2770          */
2771         spin_lock(&obd->obd_dev_lock);
2772         obd->obd_recovering = obd->obd_abort_recovery = 0;
2773         spin_unlock(&obd->obd_dev_lock);
2774         spin_lock(&obd->obd_recovery_task_lock);
2775         target_cancel_recovery_timer(obd);
2776         spin_unlock(&obd->obd_recovery_task_lock);
2777         while ((req = target_next_final_ping(obd))) {
2778                 LASSERT(trd->trd_processing_task == current->pid);
2779                 DEBUG_REQ(D_HA, req, "processing final ping from %s:",
2780                           libcfs_nid2str(req->rq_peer.nid));
2781                 handle_recovery_req(thread, req,
2782                                     trd->trd_recovery_handler);
2783                 /*
2784                  * Because the waiting client can not send ping to server,
2785                  * so we need refresh the last_request_time, to avoid the
2786                  * export is being evicted
2787                  */
2788                 ptlrpc_update_export_timer(req->rq_export, 0);
2789                 target_request_copy_put(req);
2790         }
2791
2792         delta = jiffies_to_msecs(jiffies - delta) / MSEC_PER_SEC;
2793         CDEBUG(D_INFO, "4: recovery completed in %lus - %d/%d reqs/locks\n",
2794                delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
2795         if (delta > OBD_RECOVERY_TIME_SOFT) {
2796                 CWARN("too long recovery - read logs\n");
2797                 libcfs_debug_dumplog();
2798         }
2799
2800         target_finish_recovery(lut);
2801         lu_context_fini(&env->le_ctx);
2802         trd->trd_processing_task = 0;
2803         complete_all(&trd->trd_finishing);
2804         tgt_io_thread_done(thread);
2805 out_env_remove:
2806         lu_env_remove(env);
2807 out_env:
2808         OBD_FREE_PTR(env);
2809 out_thread:
2810         OBD_FREE_PTR(thread);
2811         RETURN(rc);
2812 }
2813
2814 static int target_start_recovery_thread(struct lu_target *lut,
2815                                         svc_handler_t handler)
2816 {
2817         struct obd_device *obd = lut->lut_obd;
2818         int rc = 0;
2819         struct target_recovery_data *trd = &obd->obd_recovery_data;
2820         int index;
2821
2822         memset(trd, 0, sizeof(*trd));
2823         init_completion(&trd->trd_starting);
2824         init_completion(&trd->trd_finishing);
2825         trd->trd_recovery_handler = handler;
2826
2827         rc = server_name2index(obd->obd_name, &index, NULL);
2828         if (rc < 0)
2829                 return rc;
2830
2831         if (!IS_ERR(kthread_run(target_recovery_thread,
2832                                 lut, "tgt_recover_%d", index))) {
2833                 wait_for_completion(&trd->trd_starting);
2834                 LASSERT(obd->obd_recovering != 0);
2835         } else {
2836                 rc = -ECHILD;
2837         }
2838
2839         return rc;
2840 }
2841
2842 void target_stop_recovery_thread(struct obd_device *obd)
2843 {
2844         if (obd->obd_recovery_data.trd_processing_task > 0) {
2845                 struct target_recovery_data *trd = &obd->obd_recovery_data;
2846                 /** recovery can be done but postrecovery is not yet */
2847                 spin_lock(&obd->obd_dev_lock);
2848                 if (obd->obd_recovering) {
2849                         CERROR("%s: Aborting recovery\n", obd->obd_name);
2850                         obd->obd_abort_recovery = 1;
2851                         wake_up(&obd->obd_next_transno_waitq);
2852                 }
2853                 spin_unlock(&obd->obd_dev_lock);
2854                 wait_for_completion(&trd->trd_finishing);
2855         }
2856 }
2857 EXPORT_SYMBOL(target_stop_recovery_thread);
2858
2859 void target_recovery_fini(struct obd_device *obd)
2860 {
2861         class_disconnect_exports(obd);
2862         target_stop_recovery_thread(obd);
2863         target_cleanup_recovery(obd);
2864 }
2865 EXPORT_SYMBOL(target_recovery_fini);
2866
2867 static enum hrtimer_restart target_recovery_expired(struct hrtimer *timer)
2868 {
2869         struct obd_device *obd = container_of(timer, struct obd_device,
2870                                               obd_recovery_timer);
2871
2872         CDEBUG(D_HA,
2873                "%s: recovery timed out; %d clients are still in recovery after %llu seconds (%d clients connected)\n",
2874                obd->obd_name, atomic_read(&obd->obd_lock_replay_clients),
2875                ktime_get_seconds() - obd->obd_recovery_start,
2876                atomic_read(&obd->obd_connected_clients));
2877
2878         obd->obd_recovery_expired = 1;
2879         wake_up(&obd->obd_next_transno_waitq);
2880         return HRTIMER_NORESTART;
2881 }
2882
2883 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
2884 {
2885         struct obd_device *obd = lut->lut_obd;
2886
2887         if (lut->lut_bottom->dd_rdonly)
2888                 return;
2889
2890         if (atomic_read(&obd->obd_max_recoverable_clients) == 0) {
2891                 /** Update server last boot epoch */
2892                 tgt_boot_epoch_update(lut);
2893                 return;
2894         }
2895
2896         CDEBUG(D_HA, "RECOVERY: service %s, %d recoverable clients, "
2897                "last_transno %llu\n", obd->obd_name,
2898                atomic_read(&obd->obd_max_recoverable_clients),
2899                obd->obd_last_committed);
2900         LASSERT(obd->obd_stopping == 0);
2901         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
2902         obd->obd_recovery_start = 0;
2903         obd->obd_recovery_end = 0;
2904
2905         hrtimer_init(&obd->obd_recovery_timer, CLOCK_MONOTONIC,
2906                      HRTIMER_MODE_ABS);
2907         obd->obd_recovery_timer.function = &target_recovery_expired;
2908         target_start_recovery_thread(lut, handler);
2909 }
2910 EXPORT_SYMBOL(target_recovery_init);
2911
2912 static int target_process_req_flags(struct obd_device *obd,
2913                                     struct ptlrpc_request *req)
2914 {
2915         struct obd_export *exp = req->rq_export;
2916
2917         LASSERT(exp != NULL);
2918         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2919                 /* client declares he's ready to replay locks */
2920                 spin_lock(&exp->exp_lock);
2921                 if (exp->exp_req_replay_needed) {
2922                         exp->exp_req_replay_needed = 0;
2923                         spin_unlock(&exp->exp_lock);
2924
2925                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
2926                         atomic_dec(&obd->obd_req_replay_clients);
2927                 } else {
2928                         spin_unlock(&exp->exp_lock);
2929                 }
2930         }
2931         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2932                 /*
2933                  * client declares he's ready to complete recovery
2934                  * so, we put the request on th final queue
2935                  */
2936                 spin_lock(&exp->exp_lock);
2937                 if (exp->exp_lock_replay_needed) {
2938                         exp->exp_lock_replay_needed = 0;
2939                         spin_unlock(&exp->exp_lock);
2940
2941                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
2942                         atomic_dec(&obd->obd_lock_replay_clients);
2943                 } else {
2944                         spin_unlock(&exp->exp_lock);
2945                 }
2946         }
2947         return 0;
2948 }
2949
2950 int target_queue_recovery_request(struct ptlrpc_request *req,
2951                                   struct obd_device *obd)
2952 {
2953         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
2954         struct ptlrpc_request *reqiter;
2955         int inserted = 0;
2956
2957         ENTRY;
2958
2959         if (obd->obd_recovery_data.trd_processing_task == current->pid) {
2960                 /* Processing the queue right now, don't re-add. */
2961                 RETURN(1);
2962         }
2963
2964         target_process_req_flags(obd, req);
2965
2966         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2967                 if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_TGT_RECOVERY_REQ_RACE))) {
2968                         if (cfs_fail_val == 1) {
2969                                 cfs_race_state = 1;
2970                                 cfs_fail_val = 0;
2971                                 wake_up(&cfs_race_waitq);
2972
2973                                 schedule_timeout_interruptible(
2974                                         cfs_time_seconds(1));
2975                         }
2976                 }
2977
2978                 /*
2979                  * client declares he's ready to complete recovery
2980                  * so, we put the request on th final queue
2981                  */
2982                 target_request_copy_get(req);
2983                 DEBUG_REQ(D_HA, req, "queue final req");
2984                 wake_up(&obd->obd_next_transno_waitq);
2985                 spin_lock(&obd->obd_recovery_task_lock);
2986                 if (obd->obd_recovering) {
2987                         struct ptlrpc_request *tmp;
2988                         struct ptlrpc_request *duplicate = NULL;
2989
2990                         if (likely(!req->rq_export->exp_replay_done)) {
2991                                 req->rq_export->exp_replay_done = 1;
2992                                 list_add_tail(&req->rq_list,
2993                                               &obd->obd_final_req_queue);
2994                                 spin_unlock(&obd->obd_recovery_task_lock);
2995                                 RETURN(0);
2996                         }
2997
2998                         /*
2999                          * XXX O(n), but only happens if final ping is
3000                          * timed out, probably reorganize the list as
3001                          * a hash list later
3002                          */
3003                         list_for_each_entry_safe(reqiter, tmp,
3004                                                  &obd->obd_final_req_queue,
3005                                                  rq_list) {
3006                                 if (reqiter->rq_export == req->rq_export) {
3007                                         list_del_init(&reqiter->rq_list);
3008                                         duplicate = reqiter;
3009                                         break;
3010                                 }
3011                         }
3012
3013                         list_add_tail(&req->rq_list,
3014                                       &obd->obd_final_req_queue);
3015                         req->rq_export->exp_replay_done = 1;
3016                         spin_unlock(&obd->obd_recovery_task_lock);
3017
3018                         if (duplicate != NULL) {
3019                                 DEBUG_REQ(D_HA, duplicate,
3020                                           "put prev final req");
3021                                 target_request_copy_put(duplicate);
3022                         }
3023                         RETURN(0);
3024                 } else {
3025                         spin_unlock(&obd->obd_recovery_task_lock);
3026                         target_request_copy_put(req);
3027                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
3028                 }
3029         }
3030         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
3031                 /* client declares he's ready to replay locks */
3032                 target_request_copy_get(req);
3033                 DEBUG_REQ(D_HA, req, "queue lock replay req");
3034                 wake_up(&obd->obd_next_transno_waitq);
3035                 spin_lock(&obd->obd_recovery_task_lock);
3036                 LASSERT(obd->obd_recovering);
3037                 /* usually due to recovery abort */
3038                 if (!req->rq_export->exp_in_recovery) {
3039                         spin_unlock(&obd->obd_recovery_task_lock);
3040                         target_request_copy_put(req);
3041                         RETURN(-ENOTCONN);
3042                 }
3043                 LASSERT(req->rq_export->exp_lock_replay_needed);
3044                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
3045                 spin_unlock(&obd->obd_recovery_task_lock);
3046                 RETURN(0);
3047         }
3048
3049         /*
3050          * CAVEAT EMPTOR: The incoming request message has been swabbed
3051          * (i.e. buflens etc are in my own byte order), but type-dependent
3052          * buffers (eg mdt_body, ost_body etc) have NOT been swabbed.
3053          */
3054
3055         if (!transno) {
3056                 INIT_LIST_HEAD(&req->rq_list);
3057                 DEBUG_REQ(D_HA, req, "not queueing");
3058                 RETURN(1);
3059         }
3060
3061         /*
3062          * If we're processing the queue, we want don't want to queue this
3063          * message.
3064          *
3065          * Also, if this request has a transno less than the one we're waiting
3066          * for, we should process it now.  It could (and currently always will)
3067          * be an open request for a descriptor that was opened some time ago.
3068          *
3069          * Also, a resent, replayed request that has already been
3070          * handled will pass through here and be processed immediately.
3071          */
3072         CDEBUG(D_HA,
3073                "Next recovery transno: %llu, current: %llu, replaying\n",
3074                obd->obd_next_recovery_transno, transno);
3075
3076         /*
3077          * If the request has been replayed by update replay, then sends this
3078          * request to the recovery thread (replay_request_or_update()), where
3079          * it will be handled
3080          */
3081         spin_lock(&obd->obd_recovery_task_lock);
3082         if (transno < obd->obd_next_recovery_transno &&
3083             !is_req_replayed_by_update(req)) {
3084                 /* Processing the queue right now, don't re-add. */
3085                 LASSERT(list_empty(&req->rq_list));
3086                 spin_unlock(&obd->obd_recovery_task_lock);
3087                 RETURN(1);
3088         }
3089         spin_unlock(&obd->obd_recovery_task_lock);
3090
3091         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
3092                 RETURN(0);
3093
3094         target_request_copy_get(req);
3095         if (!req->rq_export->exp_in_recovery) {
3096                 target_request_copy_put(req);
3097                 RETURN(-ENOTCONN);
3098         }
3099         LASSERT(req->rq_export->exp_req_replay_needed);
3100
3101         if (target_exp_enqueue_req_replay(req)) {
3102                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
3103                 target_request_copy_put(req);
3104                 RETURN(0);
3105         }
3106
3107         /* XXX O(n^2) */
3108         spin_lock(&obd->obd_recovery_task_lock);
3109         LASSERT(obd->obd_recovering);
3110         list_for_each_entry(reqiter, &obd->obd_req_replay_queue, rq_list) {
3111                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
3112                         list_add_tail(&req->rq_list, &reqiter->rq_list);
3113                         inserted = 1;
3114                         goto added;
3115                 }
3116
3117                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
3118                              transno)) {
3119                         DEBUG_REQ(D_ERROR, req,
3120                                   "dropping replay: transno has been claimed by another client");
3121                         spin_unlock(&obd->obd_recovery_task_lock);
3122                         target_exp_dequeue_req_replay(req);
3123                         target_request_copy_put(req);
3124                         RETURN(0);
3125                 }
3126         }
3127 added:
3128         if (!inserted)
3129                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
3130
3131         obd->obd_requests_queued_for_recovery++;
3132         spin_unlock(&obd->obd_recovery_task_lock);
3133         wake_up(&obd->obd_next_transno_waitq);
3134         RETURN(0);
3135 }
3136
3137 void target_committed_to_req(struct ptlrpc_request *req)
3138 {
3139         struct obd_export *exp = req->rq_export;
3140
3141         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
3142                 lustre_msg_set_last_committed(req->rq_repmsg,
3143                                               exp->exp_last_committed);
3144         else
3145                 DEBUG_REQ(D_IOCTL, req,
3146                           "not sending last_committed update (%d/%d)",
3147                           exp->exp_obd->obd_no_transno,
3148                           req->rq_repmsg == NULL);
3149
3150         CDEBUG(D_INFO, "last_committed %llu, transno %llu, xid %llu\n",
3151                exp->exp_last_committed, req->rq_transno, req->rq_xid);
3152 }
3153
3154 #endif /* HAVE_SERVER_SUPPORT */
3155
3156 /**
3157  * Packs current SLV and Limit into \a req.
3158  */
3159 int target_pack_pool_reply(struct ptlrpc_request *req)
3160 {
3161         struct obd_device *obd;
3162
3163         ENTRY;
3164
3165         /*
3166          * Check that we still have all structures alive as this may
3167          * be some late RPC at shutdown time.
3168          */
3169         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
3170                      !exp_connect_lru_resize(req->rq_export))) {
3171                 lustre_msg_set_slv(req->rq_repmsg, 0);
3172                 lustre_msg_set_limit(req->rq_repmsg, 0);
3173                 RETURN(0);
3174         }
3175
3176         /* OBD is alive here as export is alive, which we checked above. */
3177         obd = req->rq_export->exp_obd;
3178
3179         read_lock(&obd->obd_pool_lock);
3180         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
3181         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
3182         read_unlock(&obd->obd_pool_lock);
3183
3184         RETURN(0);
3185 }
3186
3187 static int target_send_reply_msg(struct ptlrpc_request *req,
3188                                  int rc, int fail_id)
3189 {
3190         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
3191                 DEBUG_REQ(D_ERROR, req, "dropping reply");
3192                 return -ECOMM;
3193         }
3194         /*
3195          * We can have a null rq_reqmsg in the event of bad signature or
3196          * no context when unwrapping
3197          */
3198         if (req->rq_reqmsg &&
3199             unlikely(lustre_msg_get_opc(req->rq_reqmsg) == MDS_REINT &&
3200             OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_MULTI_NET_REP)))
3201                 return -ECOMM;
3202
3203         if (unlikely(rc)) {
3204                 DEBUG_REQ(D_NET, req, "processing error (%d)", rc);
3205                 req->rq_status = rc;
3206                 return ptlrpc_send_error(req, 1);
3207         }
3208         DEBUG_REQ(D_NET, req, "sending reply");
3209
3210         return ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT);
3211 }
3212
3213 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
3214 {
3215         struct ptlrpc_service_part *svcpt;
3216         int netrc;
3217         struct ptlrpc_reply_state *rs;
3218         struct obd_export *exp;
3219
3220         ENTRY;
3221
3222         if (req->rq_no_reply) {
3223                 EXIT;
3224                 return;
3225         }
3226
3227         svcpt = req->rq_rqbd->rqbd_svcpt;
3228         rs = req->rq_reply_state;
3229         if (rs == NULL || !rs->rs_difficult) {
3230                 /* no notifiers */
3231                 target_send_reply_msg(req, rc, fail_id);
3232                 EXIT;
3233                 return;
3234         }
3235
3236         /* must be an export if locks saved */
3237         LASSERT(req->rq_export != NULL);
3238         /* req/reply consistent */
3239         LASSERT(rs->rs_svcpt == svcpt);
3240
3241         /* "fresh" reply */
3242         LASSERT(!rs->rs_scheduled);
3243         LASSERT(!rs->rs_scheduled_ever);
3244         LASSERT(!rs->rs_handled);
3245         LASSERT(!rs->rs_on_net);
3246         LASSERT(rs->rs_export == NULL);
3247         LASSERT(list_empty(&rs->rs_obd_list));
3248         LASSERT(list_empty(&rs->rs_exp_list));
3249
3250         exp = class_export_get(req->rq_export);
3251
3252         /* disable reply scheduling while I'm setting up */
3253         rs->rs_scheduled = 1;
3254         rs->rs_on_net    = 1;
3255         rs->rs_xid       = req->rq_xid;
3256         rs->rs_transno   = req->rq_transno;
3257         rs->rs_export    = exp;
3258         rs->rs_opc       = lustre_msg_get_opc(req->rq_reqmsg);
3259
3260         spin_lock(&exp->exp_uncommitted_replies_lock);
3261         CDEBUG(D_NET, "rs transno = %llu, last committed = %llu\n",
3262                rs->rs_transno, exp->exp_last_committed);
3263         if (rs->rs_transno > exp->exp_last_committed) {
3264                 /* not committed already */
3265                 list_add_tail(&rs->rs_obd_list,
3266                                   &exp->exp_uncommitted_replies);
3267         }
3268         spin_unlock(&exp->exp_uncommitted_replies_lock);
3269
3270         spin_lock(&exp->exp_lock);
3271         list_add_tail(&rs->rs_exp_list, &exp->exp_outstanding_replies);
3272         spin_unlock(&exp->exp_lock);
3273
3274         netrc = target_send_reply_msg(req, rc, fail_id);
3275
3276         spin_lock(&svcpt->scp_rep_lock);
3277
3278         atomic_inc(&svcpt->scp_nreps_difficult);
3279
3280         if (netrc != 0) {
3281                 /*
3282                  * error sending: reply is off the net.  Also we need +1
3283                  * reply ref until ptlrpc_handle_rs() is done
3284                  * with the reply state (if the send was successful, there
3285                  * would have been +1 ref for the net, which
3286                  * reply_out_callback leaves alone)
3287                  */
3288                 rs->rs_on_net = 0;
3289                 ptlrpc_rs_addref(rs);
3290         }
3291
3292         spin_lock(&rs->rs_lock);
3293         if (rs->rs_transno <= exp->exp_last_committed ||
3294             (!rs->rs_on_net && !rs->rs_no_ack) ||
3295             list_empty(&rs->rs_exp_list) ||     /* completed already */
3296             list_empty(&rs->rs_obd_list)) {
3297                 CDEBUG(D_HA, "Schedule reply immediately\n");
3298                 ptlrpc_dispatch_difficult_reply(rs);
3299         } else {
3300                 list_add(&rs->rs_list, &svcpt->scp_rep_active);
3301                 rs->rs_scheduled = 0;   /* allow notifier to schedule */
3302         }
3303         spin_unlock(&rs->rs_lock);
3304         spin_unlock(&svcpt->scp_rep_lock);
3305         EXIT;
3306 }
3307
3308 enum ldlm_mode lck_compat_array[] = {
3309         [LCK_EX]    = LCK_COMPAT_EX,
3310         [LCK_PW]    = LCK_COMPAT_PW,
3311         [LCK_PR]    = LCK_COMPAT_PR,
3312         [LCK_CW]    = LCK_COMPAT_CW,
3313         [LCK_CR]    = LCK_COMPAT_CR,
3314         [LCK_NL]    = LCK_COMPAT_NL,
3315         [LCK_GROUP] = LCK_COMPAT_GROUP,
3316         [LCK_COS]   = LCK_COMPAT_COS,
3317 };
3318
3319 /**
3320  * Rather arbitrary mapping from LDLM error codes to errno values. This should
3321  * not escape to the user level.
3322  */
3323 int ldlm_error2errno(enum ldlm_error error)
3324 {
3325         int result;
3326
3327         switch (error) {
3328         case ELDLM_OK:
3329         case ELDLM_LOCK_MATCHED:
3330                 result = 0;
3331                 break;
3332         case ELDLM_LOCK_CHANGED:
3333                 result = -ESTALE;
3334                 break;
3335         case ELDLM_LOCK_ABORTED:
3336                 result = -ENAVAIL;
3337                 break;
3338         case ELDLM_LOCK_REPLACED:
3339                 result = -ESRCH;
3340                 break;
3341         case ELDLM_NO_LOCK_DATA:
3342                 result = -ENOENT;
3343                 break;
3344         case ELDLM_NAMESPACE_EXISTS:
3345                 result = -EEXIST;
3346                 break;
3347         case ELDLM_BAD_NAMESPACE:
3348                 result = -EBADF;
3349                 break;
3350         default:
3351                 if (((int)error) < 0) { /* cast to signed type */
3352                         result = error; /* as ldlm_error can be unsigned */
3353                 } else {
3354                         CERROR("Invalid DLM result code: %d\n", error);
3355                         result = -EPROTO;
3356                 }
3357         }
3358         return result;
3359 }
3360 EXPORT_SYMBOL(ldlm_error2errno);
3361
3362 /**
3363  * Dual to ldlm_error2errno(): maps errno values back to enum ldlm_error.
3364  */
3365 enum ldlm_error ldlm_errno2error(int err_no)
3366 {
3367         int error;
3368
3369         switch (err_no) {
3370         case 0:
3371                 error = ELDLM_OK;
3372                 break;
3373         case -ESTALE:
3374                 error = ELDLM_LOCK_CHANGED;
3375                 break;
3376         case -ENAVAIL:
3377                 error = ELDLM_LOCK_ABORTED;
3378                 break;
3379         case -ESRCH:
3380                 error = ELDLM_LOCK_REPLACED;
3381                 break;
3382         case -ENOENT:
3383                 error = ELDLM_NO_LOCK_DATA;
3384                 break;
3385         case -EEXIST:
3386                 error = ELDLM_NAMESPACE_EXISTS;
3387                 break;
3388         case -EBADF:
3389                 error = ELDLM_BAD_NAMESPACE;
3390                 break;
3391         default:
3392                 error = err_no;
3393         }
3394         return error;
3395 }
3396
3397 #if LUSTRE_TRACKS_LOCK_EXP_REFS
3398 void ldlm_dump_export_locks(struct obd_export *exp)
3399 {
3400         spin_lock(&exp->exp_locks_list_guard);
3401         if (!list_empty(&exp->exp_locks_list)) {
3402                 struct ldlm_lock *lock;
3403
3404                 CERROR("dumping locks for export %p, ignore if the unmount doesn't hang\n",
3405                        exp);
3406                 list_for_each_entry(lock, &exp->exp_locks_list,
3407                                         l_exp_refs_link)
3408                         LDLM_ERROR(lock, "lock:");
3409         }
3410         spin_unlock(&exp->exp_locks_list_guard);
3411 }
3412 #endif
3413
3414 #ifdef HAVE_SERVER_SUPPORT
3415 static inline const char *bulk2type(struct ptlrpc_request *req)
3416 {
3417         if (req->rq_bulk_read)
3418                 return "READ";
3419         if (req->rq_bulk_write)
3420                 return "WRITE";
3421         return "UNKNOWN";
3422 }
3423
3424 int target_bulk_io(struct obd_export *exp, struct ptlrpc_bulk_desc *desc)
3425 {
3426         struct ptlrpc_request *req = desc->bd_req;
3427         time64_t start = ktime_get_seconds();
3428         time64_t deadline;
3429         int rc = 0;
3430
3431         ENTRY;
3432
3433         /* If there is eviction in progress, wait for it to finish. */
3434         wait_event_idle(
3435                 exp->exp_obd->obd_evict_inprogress_waitq,
3436                 !atomic_read(&exp->exp_obd->obd_evict_inprogress));
3437
3438         /* Check if client was evicted or reconnected already. */
3439         if (exp->exp_failed ||
3440             exp->exp_conn_cnt > lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
3441                 rc = -ENOTCONN;
3442         } else {
3443                 if (req->rq_bulk_read)
3444                         rc = sptlrpc_svc_wrap_bulk(req, desc);
3445
3446                 if (OCD_HAS_FLAG(&exp->exp_connect_data, BULK_MBITS))
3447                         req->rq_mbits = lustre_msg_get_mbits(req->rq_reqmsg);
3448                 else /* old version, bulk matchbits is rq_xid */
3449                         req->rq_mbits = req->rq_xid;
3450
3451                 if (rc == 0)
3452                         rc = ptlrpc_start_bulk_transfer(desc);
3453         }
3454
3455         if (rc < 0) {
3456                 DEBUG_REQ(D_ERROR, req, "bulk %s failed: rc = %d",
3457                           bulk2type(req), rc);
3458                 RETURN(rc);
3459         }
3460
3461         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
3462                 ptlrpc_abort_bulk(desc);
3463                 RETURN(0);
3464         }
3465
3466         /* limit actual bulk transfer to bulk_timeout seconds */
3467         deadline = start + bulk_timeout;
3468         if (deadline > req->rq_deadline)
3469                 deadline = req->rq_deadline;
3470
3471         do {
3472                 time64_t timeoutl = deadline - ktime_get_seconds();
3473                 time64_t rq_deadline;
3474
3475                 while (timeoutl >= 0 &&
3476                        wait_event_idle_timeout(
3477                                desc->bd_waitq,
3478                                !ptlrpc_server_bulk_active(desc) ||
3479                                exp->exp_failed ||
3480                                exp->exp_conn_cnt >
3481                                lustre_msg_get_conn_cnt(req->rq_reqmsg),
3482                                timeoutl ? cfs_time_seconds(1) : 1) == 0)
3483                         timeoutl -= 1;
3484                 rc = timeoutl < 0 ? -ETIMEDOUT : 0;
3485
3486                 /* Wait again if we changed rq_deadline. */
3487                 rq_deadline = READ_ONCE(req->rq_deadline);
3488                 deadline = start + bulk_timeout;
3489                 if (deadline > rq_deadline)
3490                         deadline = rq_deadline;
3491         } while (rc == -ETIMEDOUT &&
3492                  deadline > ktime_get_seconds());
3493
3494         if (rc == -ETIMEDOUT) {
3495                 DEBUG_REQ(D_ERROR, req, "timeout on bulk %s after %lld%+llds",
3496                           bulk2type(req), deadline - start,
3497                           ktime_get_real_seconds() - deadline);
3498                 ptlrpc_abort_bulk(desc);
3499         } else if (exp->exp_failed) {
3500                 DEBUG_REQ(D_ERROR, req, "Eviction on bulk %s",
3501                           bulk2type(req));
3502                 rc = -ENOTCONN;
3503                 ptlrpc_abort_bulk(desc);
3504         } else if (exp->exp_conn_cnt >
3505                    lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
3506                 DEBUG_REQ(D_ERROR, req, "Reconnect on bulk %s",
3507                           bulk2type(req));
3508                 /* We don't reply anyway. */
3509                 rc = -ETIMEDOUT;
3510                 ptlrpc_abort_bulk(desc);
3511         } else if (desc->bd_failure) {
3512                 DEBUG_REQ(D_ERROR, req, "network error on bulk %s",
3513                           bulk2type(req));
3514                 /* XXX should this be a different errno? */
3515                 rc = -ETIMEDOUT;
3516         } else {
3517                 if (req->rq_bulk_write)
3518                         rc = sptlrpc_svc_unwrap_bulk(req, desc);
3519                 if (rc == 0 && desc->bd_nob_transferred != desc->bd_nob) {
3520                         DEBUG_REQ(D_ERROR, req, "truncated bulk %s %d(%d)",
3521                                   bulk2type(req), desc->bd_nob_transferred,
3522                                   desc->bd_nob);
3523                         /* XXX should this be a different errno? */
3524                         rc = -ETIMEDOUT;
3525                 }
3526         }
3527
3528         RETURN(rc);
3529 }
3530 EXPORT_SYMBOL(target_bulk_io);
3531
3532 #endif /* HAVE_SERVER_SUPPORT */