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