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