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