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