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