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