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