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