Whamcloud - gitweb
LU-793 ptlrpc: allow client to reconnect with RPC in progress
[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 (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1) {
980                 if (!strstr(cluuid.uuid, "mdt"))
981                         LCONSOLE_WARN("%s: Rejecting reconnect from the "
982                                       "known client %s (at %s) because it "
983                                       "is indicating it is a new client",
984                                       target->obd_name, cluuid.uuid,
985                                       libcfs_nid2str(req->rq_peer.nid));
986                 GOTO(out, rc = -EALREADY);
987         } else {
988                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
989         }
990
991         if (rc < 0) {
992                 GOTO(out, rc);
993         }
994
995         CDEBUG(D_HA, "%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
996                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
997               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
998               export, (long)cfs_time_current_sec(),
999               export ? (long)export->exp_last_request_time : 0);
1000
1001         /* If this is the first time a client connects, reset the recovery
1002          * timer. Discard lightweight connections which might be local. */
1003         if (!lw_client && rc == 0 && target->obd_recovering)
1004                 check_and_start_recovery_timer(target, req, export == NULL);
1005
1006         /* We want to handle EALREADY but *not* -EALREADY from
1007          * target_handle_reconnect(), return reconnection state in a flag. */
1008         if (rc == EALREADY) {
1009                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
1010                 rc = 0;
1011         } else {
1012                 LASSERT(rc == 0);
1013         }
1014
1015         /* Tell the client if we support replayable requests. */
1016         if (target->obd_replayable)
1017                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
1018         client_nid = &req->rq_peer.nid;
1019
1020         if (export == NULL) {
1021                 /* allow lightweight connections during recovery */
1022                 if (target->obd_recovering && !lw_client) {
1023                         cfs_time_t t;
1024                         int     c; /* connected */
1025                         int     i; /* in progress */
1026                         int     k; /* known */
1027                         int     s; /* stale/evicted */
1028
1029                         c = cfs_atomic_read(&target->obd_connected_clients);
1030                         i = cfs_atomic_read(&target->obd_lock_replay_clients);
1031                         k = target->obd_max_recoverable_clients;
1032                         s = target->obd_stale_clients;
1033                         t = cfs_timer_deadline(&target->obd_recovery_timer);
1034                         t = cfs_time_sub(t, cfs_time_current());
1035                         t = cfs_duration_sec(t);
1036                         LCONSOLE_WARN("%s: Denying connection for new client "
1037                                       "%s (at %s), waiting for all %d known "
1038                                       "clients (%d recovered, %d in progress, "
1039                                       "and %d evicted) to recover in %d:%.02d\n",
1040                                       target->obd_name, cluuid.uuid,
1041                                       libcfs_nid2str(req->rq_peer.nid), k,
1042                                       c - i, i, s, (int)t / 60,
1043                                       (int)t % 60);
1044                         rc = -EBUSY;
1045                 } else {
1046 dont_check_exports:
1047                         rc = obd_connect(req->rq_svc_thread->t_env,
1048                                          &export, target, &cluuid, data,
1049                                          client_nid);
1050                         if (mds_conn && OBD_FAIL_CHECK(OBD_FAIL_TGT_RCVG_FLAG))
1051                                 lustre_msg_add_op_flags(req->rq_repmsg,
1052                                                 MSG_CONNECT_RECOVERING);
1053                         if (rc == 0)
1054                                 conn.cookie = export->exp_handle.h_cookie;
1055                 }
1056         } else {
1057                 rc = obd_reconnect(req->rq_svc_thread->t_env,
1058                                    export, target, &cluuid, data, client_nid);
1059         }
1060         if (rc)
1061                 GOTO(out, rc);
1062
1063 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 6, 50, 0)
1064         /* 2.2.0 clients always swab nidtbl entries due to a bug, so server
1065          * will do the swabbing for if the client is using the same endianness.
1066          *
1067          * This fixup is version-limited, because we don't want to carry the
1068          * OBD_CONNECT_MNE_SWAB flag around forever, just so long as we need
1069          * interop with unpatched 2.2 clients.  For newer clients, servers
1070          * will never do MNE swabbing, let the client handle that.  LU-1644 */
1071         export->exp_need_mne_swab = !ptlrpc_req_need_swab(req) &&
1072                         !(data->ocd_connect_flags & OBD_CONNECT_MNE_SWAB);
1073 #else
1074 #warning "LU-1644: Remove old OBD_CONNECT_MNE_SWAB fixup and exp_need_mne_swab"
1075 #endif
1076
1077         LASSERT(target->u.obt.obt_magic == OBT_MAGIC);
1078         data->ocd_instance = target->u.obt.obt_instance;
1079
1080         /* Return only the parts of obd_connect_data that we understand, so the
1081          * client knows that we don't understand the rest. */
1082         if (data) {
1083                 tmpsize = req_capsule_get_size(&req->rq_pill, &RMF_CONNECT_DATA,
1084                                                RCL_SERVER);
1085                 tmpdata = req_capsule_server_get(&req->rq_pill,
1086                                                  &RMF_CONNECT_DATA);
1087                 /* Don't use struct assignment here, because the client reply
1088                  * buffer may be smaller/larger than the local struct
1089                  * obd_connect_data. */
1090                 memcpy(tmpdata, data, min(tmpsize, size));
1091         }
1092
1093         /* If all else goes well, this is our RPC return code. */
1094         req->rq_status = 0;
1095
1096         lustre_msg_set_handle(req->rq_repmsg, &conn);
1097
1098         /* If the client and the server are the same node, we will already
1099          * have an export that really points to the client's DLM export,
1100          * because we have a shared handles table.
1101          *
1102          * XXX this will go away when shaver stops sending the "connect" handle
1103          * in the real "remote handle" field of the request --phik 24 Apr 2003
1104          */
1105         ptlrpc_request_change_export(req, export);
1106
1107         spin_lock(&export->exp_lock);
1108         if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
1109                 spin_unlock(&export->exp_lock);
1110                 CDEBUG(D_RPCTRACE, "%s: %s already connected at greater "
1111                        "or equal conn_cnt: %d >= %d\n",
1112                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
1113                        export->exp_conn_cnt,
1114                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
1115
1116                 GOTO(out, rc = -EALREADY);
1117         }
1118         LASSERT(lustre_msg_get_conn_cnt(req->rq_reqmsg) > 0);
1119         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
1120
1121         /* Don't evict liblustre clients for not pinging. */
1122         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
1123                 export->exp_libclient = 1;
1124                 spin_unlock(&export->exp_lock);
1125
1126                 spin_lock(&target->obd_dev_lock);
1127                 cfs_list_del_init(&export->exp_obd_chain_timed);
1128                 spin_unlock(&target->obd_dev_lock);
1129         } else {
1130                 spin_unlock(&export->exp_lock);
1131         }
1132
1133         if (export->exp_connection != NULL) {
1134                 /* Check to see if connection came from another NID. */
1135                 if ((export->exp_connection->c_peer.nid != req->rq_peer.nid) &&
1136                     !cfs_hlist_unhashed(&export->exp_nid_hash))
1137                         cfs_hash_del(export->exp_obd->obd_nid_hash,
1138                                      &export->exp_connection->c_peer.nid,
1139                                      &export->exp_nid_hash);
1140
1141                 ptlrpc_connection_put(export->exp_connection);
1142         }
1143
1144         export->exp_connection = ptlrpc_connection_get(req->rq_peer,
1145                                                        req->rq_self,
1146                                                        &remote_uuid);
1147         if (cfs_hlist_unhashed(&export->exp_nid_hash)) {
1148                 cfs_hash_add(export->exp_obd->obd_nid_hash,
1149                              &export->exp_connection->c_peer.nid,
1150                              &export->exp_nid_hash);
1151         }
1152
1153         if (target->obd_recovering && !export->exp_in_recovery && !lw_client) {
1154                 int has_transno;
1155                 __u64 transno = data->ocd_transno;
1156
1157                 spin_lock(&export->exp_lock);
1158                 /* possible race with class_disconnect_stale_exports,
1159                  * export may be already in the eviction process */
1160                 if (export->exp_failed) {
1161                         spin_unlock(&export->exp_lock);
1162                         GOTO(out, rc = -ENODEV);
1163                 }
1164                 export->exp_in_recovery = 1;
1165                 export->exp_req_replay_needed = 1;
1166                 export->exp_lock_replay_needed = 1;
1167                 spin_unlock(&export->exp_lock);
1168
1169                 has_transno = !!(lustre_msg_get_op_flags(req->rq_reqmsg) &
1170                                  MSG_CONNECT_TRANSNO);
1171                 if (has_transno && transno == 0)
1172                         CWARN("Connect with zero transno!\n");
1173
1174                 if (has_transno && transno > 0 &&
1175                     transno < target->obd_next_recovery_transno &&
1176                     transno > target->obd_last_committed) {
1177                         /* Another way is to use cmpxchg() to be lock-free. */
1178                         spin_lock(&target->obd_recovery_task_lock);
1179                         if (transno < target->obd_next_recovery_transno)
1180                                 target->obd_next_recovery_transno = transno;
1181                         spin_unlock(&target->obd_recovery_task_lock);
1182                 }
1183
1184                 cfs_atomic_inc(&target->obd_req_replay_clients);
1185                 cfs_atomic_inc(&target->obd_lock_replay_clients);
1186                 if (cfs_atomic_inc_return(&target->obd_connected_clients) ==
1187                     target->obd_max_recoverable_clients)
1188                         wake_up(&target->obd_next_transno_waitq);
1189         }
1190
1191         /* Tell the client we're in recovery, when client is involved in it. */
1192         if (target->obd_recovering && !lw_client)
1193                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
1194
1195         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
1196         conn = *tmp;
1197
1198         /* Return -ENOTCONN in case of errors to let client reconnect. */
1199         revimp = class_new_import(target);
1200         if (revimp == NULL) {
1201                 CERROR("fail to alloc new reverse import.\n");
1202                 GOTO(out, rc = -ENOTCONN);
1203         }
1204
1205         spin_lock(&export->exp_lock);
1206         if (export->exp_imp_reverse != NULL)
1207                 /* destroyed import can be still referenced in ctxt */
1208                 tmp_imp = export->exp_imp_reverse;
1209         export->exp_imp_reverse = revimp;
1210         spin_unlock(&export->exp_lock);
1211
1212         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
1213         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
1214         revimp->imp_remote_handle = conn;
1215         revimp->imp_dlm_fake = 1;
1216         revimp->imp_state = LUSTRE_IMP_FULL;
1217
1218         /* Unknown versions will be caught in
1219          * ptlrpc_handle_server_req_in->lustre_unpack_msg(). */
1220         revimp->imp_msg_magic = req->rq_reqmsg->lm_magic;
1221
1222         if ((data->ocd_connect_flags & OBD_CONNECT_AT) &&
1223             (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1))
1224                 revimp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1225         else
1226                 revimp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1227
1228         if ((data->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1229             (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1))
1230                 revimp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1231         else
1232                 revimp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1233
1234         rc = sptlrpc_import_sec_adapt(revimp, req->rq_svc_ctx, &req->rq_flvr);
1235         if (rc) {
1236                 CERROR("Failed to get sec for reverse import: %d\n", rc);
1237                 spin_lock(&export->exp_lock);
1238                 export->exp_imp_reverse = NULL;
1239                 spin_unlock(&export->exp_lock);
1240                 class_destroy_import(revimp);
1241         }
1242
1243         class_import_put(revimp);
1244
1245 out:
1246         if (tmp_imp != NULL)
1247                 client_destroy_import(tmp_imp);
1248         if (export) {
1249                 spin_lock(&export->exp_lock);
1250                 export->exp_connecting = 0;
1251                 spin_unlock(&export->exp_lock);
1252
1253                 class_export_put(export);
1254         }
1255         if (targref) {
1256                 spin_lock(&target->obd_dev_lock);
1257                 target->obd_conn_inprogress--;
1258                 spin_unlock(&target->obd_dev_lock);
1259
1260                 class_decref(targref, __func__, current);
1261         }
1262         if (rc)
1263                 req->rq_status = rc;
1264         RETURN(rc);
1265 }
1266 EXPORT_SYMBOL(target_handle_connect);
1267
1268 int target_handle_disconnect(struct ptlrpc_request *req)
1269 {
1270         int rc;
1271         ENTRY;
1272
1273         rc = req_capsule_server_pack(&req->rq_pill);
1274         if (rc)
1275                 RETURN(rc);
1276
1277         /* Keep the rq_export around so we can send the reply. */
1278         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1279
1280         RETURN(0);
1281 }
1282 EXPORT_SYMBOL(target_handle_disconnect);
1283
1284 void target_destroy_export(struct obd_export *exp)
1285 {
1286         struct obd_import       *imp = NULL;
1287         /* exports created from last_rcvd data, and "fake"
1288            exports created by lctl don't have an import */
1289         spin_lock(&exp->exp_lock);
1290         if (exp->exp_imp_reverse != NULL) {
1291                 imp = exp->exp_imp_reverse;
1292                 exp->exp_imp_reverse = NULL;
1293         }
1294         spin_unlock(&exp->exp_lock);
1295         if (imp != NULL)
1296                 client_destroy_import(imp);
1297
1298         LASSERT_ATOMIC_ZERO(&exp->exp_locks_count);
1299         LASSERT_ATOMIC_ZERO(&exp->exp_rpc_count);
1300         LASSERT_ATOMIC_ZERO(&exp->exp_cb_count);
1301         LASSERT_ATOMIC_ZERO(&exp->exp_replay_count);
1302 }
1303 EXPORT_SYMBOL(target_destroy_export);
1304
1305 /*
1306  * Recovery functions
1307  */
1308 static void target_request_copy_get(struct ptlrpc_request *req)
1309 {
1310         class_export_rpc_inc(req->rq_export);
1311         LASSERT(cfs_list_empty(&req->rq_list));
1312         CFS_INIT_LIST_HEAD(&req->rq_replay_list);
1313
1314         /* Increase refcount to keep request in queue. */
1315         cfs_atomic_inc(&req->rq_refcount);
1316         /* Let export know it has replays to be handled. */
1317         cfs_atomic_inc(&req->rq_export->exp_replay_count);
1318 }
1319
1320 static void target_request_copy_put(struct ptlrpc_request *req)
1321 {
1322         LASSERT(cfs_list_empty(&req->rq_replay_list));
1323         LASSERT_ATOMIC_POS(&req->rq_export->exp_replay_count);
1324
1325         cfs_atomic_dec(&req->rq_export->exp_replay_count);
1326         class_export_rpc_dec(req->rq_export);
1327         ptlrpc_server_drop_request(req);
1328 }
1329
1330 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1331 {
1332         __u64                  transno = lustre_msg_get_transno(req->rq_reqmsg);
1333         struct obd_export     *exp = req->rq_export;
1334         struct ptlrpc_request *reqiter;
1335         int                    dup = 0;
1336
1337         LASSERT(exp);
1338
1339         spin_lock(&exp->exp_lock);
1340         cfs_list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1341                                 rq_replay_list) {
1342                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1343                         dup = 1;
1344                         break;
1345                 }
1346         }
1347
1348         if (dup) {
1349                 /* We expect it with RESENT and REPLAY flags. */
1350                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1351                      (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1352                         CERROR("invalid flags %x of resent replay\n",
1353                                lustre_msg_get_flags(req->rq_reqmsg));
1354         } else {
1355                 cfs_list_add_tail(&req->rq_replay_list,
1356                                   &exp->exp_req_replay_queue);
1357         }
1358
1359         spin_unlock(&exp->exp_lock);
1360         return dup;
1361 }
1362
1363 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1364 {
1365         LASSERT(!cfs_list_empty(&req->rq_replay_list));
1366         LASSERT(req->rq_export);
1367
1368         spin_lock(&req->rq_export->exp_lock);
1369         cfs_list_del_init(&req->rq_replay_list);
1370         spin_unlock(&req->rq_export->exp_lock);
1371 }
1372
1373 #ifdef __KERNEL__
1374 static void target_finish_recovery(struct obd_device *obd)
1375 {
1376         ENTRY;
1377
1378         /* Only log a recovery message when recovery has occurred. */
1379         if (obd->obd_recovery_start) {
1380                 time_t elapsed_time = max_t(time_t, 1, cfs_time_current_sec() -
1381                                         obd->obd_recovery_start);
1382                 LCONSOLE_INFO("%s: Recovery over after %d:%.02d, of %d clients "
1383                         "%d recovered and %d %s evicted.\n", obd->obd_name,
1384                         (int)elapsed_time / 60, (int)elapsed_time % 60,
1385                         obd->obd_max_recoverable_clients,
1386                         cfs_atomic_read(&obd->obd_connected_clients),
1387                         obd->obd_stale_clients,
1388                         obd->obd_stale_clients == 1 ? "was" : "were");
1389         }
1390
1391         ldlm_reprocess_all_ns(obd->obd_namespace);
1392         spin_lock(&obd->obd_recovery_task_lock);
1393         if (!cfs_list_empty(&obd->obd_req_replay_queue) ||
1394             !cfs_list_empty(&obd->obd_lock_replay_queue) ||
1395             !cfs_list_empty(&obd->obd_final_req_queue)) {
1396                 CERROR("%s: Recovery queues ( %s%s%s) are not empty\n",
1397                        obd->obd_name,
1398                        cfs_list_empty(&obd->obd_req_replay_queue) ? "" : "req ",
1399                        cfs_list_empty(&obd->obd_lock_replay_queue) ? \
1400                                "" : "lock ",
1401                        cfs_list_empty(&obd->obd_final_req_queue) ? \
1402                                "" : "final ");
1403                 spin_unlock(&obd->obd_recovery_task_lock);
1404                 LBUG();
1405         }
1406         spin_unlock(&obd->obd_recovery_task_lock);
1407
1408         obd->obd_recovery_end = cfs_time_current_sec();
1409
1410         /* When recovery finished, cleanup orphans on MDS and OST. */
1411         if (OBT(obd) && OBP(obd, postrecov)) {
1412                 int rc = OBP(obd, postrecov)(obd);
1413                 if (rc < 0)
1414                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1415                                       obd->obd_name, rc);
1416         }
1417         EXIT;
1418 }
1419
1420 static void abort_req_replay_queue(struct obd_device *obd)
1421 {
1422         struct ptlrpc_request *req, *n;
1423         cfs_list_t abort_list;
1424
1425         CFS_INIT_LIST_HEAD(&abort_list);
1426         spin_lock(&obd->obd_recovery_task_lock);
1427         cfs_list_splice_init(&obd->obd_req_replay_queue, &abort_list);
1428         spin_unlock(&obd->obd_recovery_task_lock);
1429         cfs_list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1430                 DEBUG_REQ(D_WARNING, req, "aborted:");
1431                 req->rq_status = -ENOTCONN;
1432                 if (ptlrpc_error(req)) {
1433                         DEBUG_REQ(D_ERROR, req,
1434                                   "failed abort_req_reply; skipping");
1435                 }
1436                 target_exp_dequeue_req_replay(req);
1437                 target_request_copy_put(req);
1438         }
1439 }
1440
1441 static void abort_lock_replay_queue(struct obd_device *obd)
1442 {
1443         struct ptlrpc_request *req, *n;
1444         cfs_list_t abort_list;
1445
1446         CFS_INIT_LIST_HEAD(&abort_list);
1447         spin_lock(&obd->obd_recovery_task_lock);
1448         cfs_list_splice_init(&obd->obd_lock_replay_queue, &abort_list);
1449         spin_unlock(&obd->obd_recovery_task_lock);
1450         cfs_list_for_each_entry_safe(req, n, &abort_list, rq_list){
1451                 DEBUG_REQ(D_ERROR, req, "aborted:");
1452                 req->rq_status = -ENOTCONN;
1453                 if (ptlrpc_error(req)) {
1454                         DEBUG_REQ(D_ERROR, req,
1455                                   "failed abort_lock_reply; skipping");
1456                 }
1457                 target_request_copy_put(req);
1458         }
1459 }
1460
1461 /* Called from a cleanup function if the device is being cleaned up
1462    forcefully.  The exports should all have been disconnected already,
1463    the only thing left to do is
1464      - clear the recovery flags
1465      - cancel the timer
1466      - free queued requests and replies, but don't send replies
1467    Because the obd_stopping flag is set, no new requests should be received.
1468
1469 */
1470 void target_cleanup_recovery(struct obd_device *obd)
1471 {
1472         struct ptlrpc_request *req, *n;
1473         cfs_list_t clean_list;
1474         ENTRY;
1475
1476         CFS_INIT_LIST_HEAD(&clean_list);
1477         spin_lock(&obd->obd_dev_lock);
1478         if (!obd->obd_recovering) {
1479                 spin_unlock(&obd->obd_dev_lock);
1480                 EXIT;
1481                 return;
1482         }
1483         obd->obd_recovering = obd->obd_abort_recovery = 0;
1484         spin_unlock(&obd->obd_dev_lock);
1485
1486         spin_lock(&obd->obd_recovery_task_lock);
1487         target_cancel_recovery_timer(obd);
1488         cfs_list_splice_init(&obd->obd_req_replay_queue, &clean_list);
1489         spin_unlock(&obd->obd_recovery_task_lock);
1490
1491         cfs_list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1492                 LASSERT(req->rq_reply_state == 0);
1493                 target_exp_dequeue_req_replay(req);
1494                 target_request_copy_put(req);
1495         }
1496
1497         spin_lock(&obd->obd_recovery_task_lock);
1498         cfs_list_splice_init(&obd->obd_lock_replay_queue, &clean_list);
1499         cfs_list_splice_init(&obd->obd_final_req_queue, &clean_list);
1500         spin_unlock(&obd->obd_recovery_task_lock);
1501
1502         cfs_list_for_each_entry_safe(req, n, &clean_list, rq_list){
1503                 LASSERT(req->rq_reply_state == 0);
1504                 target_request_copy_put(req);
1505         }
1506
1507         EXIT;
1508 }
1509 EXPORT_SYMBOL(target_cleanup_recovery);
1510
1511 /* obd_recovery_task_lock should be held */
1512 void target_cancel_recovery_timer(struct obd_device *obd)
1513 {
1514         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1515         cfs_timer_disarm(&obd->obd_recovery_timer);
1516 }
1517 EXPORT_SYMBOL(target_cancel_recovery_timer);
1518
1519 static void target_start_recovery_timer(struct obd_device *obd)
1520 {
1521         if (obd->obd_recovery_start != 0)
1522                 return;
1523
1524         spin_lock(&obd->obd_dev_lock);
1525         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1526                 spin_unlock(&obd->obd_dev_lock);
1527                 return;
1528         }
1529
1530         LASSERT(obd->obd_recovery_timeout != 0);
1531
1532         if (obd->obd_recovery_start != 0) {
1533                 spin_unlock(&obd->obd_dev_lock);
1534                 return;
1535         }
1536
1537         cfs_timer_arm(&obd->obd_recovery_timer,
1538                       cfs_time_shift(obd->obd_recovery_timeout));
1539         obd->obd_recovery_start = cfs_time_current_sec();
1540         spin_unlock(&obd->obd_dev_lock);
1541
1542         LCONSOLE_WARN("%s: Will be in recovery for at least %d:%.02d, "
1543                       "or until %d client%s reconnect%s\n",
1544                       obd->obd_name,
1545                       obd->obd_recovery_timeout / 60,
1546                       obd->obd_recovery_timeout % 60,
1547                       obd->obd_max_recoverable_clients,
1548                       (obd->obd_max_recoverable_clients == 1) ? "" : "s",
1549                       (obd->obd_max_recoverable_clients == 1) ? "s": "");
1550 }
1551
1552 /**
1553  * extend recovery window.
1554  *
1555  * if @extend is true, extend recovery window to have @drt remaining at least;
1556  * otherwise, make sure the recovery timeout value is not less than @drt.
1557  */
1558 static void extend_recovery_timer(struct obd_device *obd, int drt, bool extend)
1559 {
1560         cfs_time_t now;
1561         cfs_time_t end;
1562         cfs_duration_t left;
1563         int to;
1564
1565         spin_lock(&obd->obd_dev_lock);
1566         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1567                 spin_unlock(&obd->obd_dev_lock);
1568                 return;
1569         }
1570         LASSERT(obd->obd_recovery_start != 0);
1571
1572         now  = cfs_time_current_sec();
1573         to   = obd->obd_recovery_timeout;
1574         end  = obd->obd_recovery_start + to;
1575         left = cfs_time_sub(end, now);
1576
1577         if (extend && (drt > left)) {
1578                 to += drt - left;
1579         } else if (!extend && (drt > to)) {
1580                 to = drt;
1581                 /* reduce drt by already passed time */
1582                 drt -= obd->obd_recovery_timeout - left;
1583         }
1584
1585         if (to > obd->obd_recovery_time_hard)
1586                 to = obd->obd_recovery_time_hard;
1587         if (obd->obd_recovery_timeout < to ||
1588             obd->obd_recovery_timeout == obd->obd_recovery_time_hard) {
1589                 obd->obd_recovery_timeout = to;
1590                 cfs_timer_arm(&obd->obd_recovery_timer,
1591                               cfs_time_shift(drt));
1592         }
1593         spin_unlock(&obd->obd_dev_lock);
1594
1595         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n",
1596                obd->obd_name, (unsigned)drt);
1597 }
1598
1599 /* Reset the timer with each new client connection */
1600 /*
1601  * This timer is actually reconnect_timer, which is for making sure
1602  * the total recovery window is at least as big as my reconnect
1603  * attempt timing. So the initial recovery time_out will be set to
1604  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1605  * from client is bigger than this, then the recovery time_out will
1606  * be extended to make sure the client could be reconnected, in the
1607  * process, the timeout from the new client should be ignored.
1608  */
1609
1610 static void
1611 check_and_start_recovery_timer(struct obd_device *obd,
1612                                struct ptlrpc_request *req,
1613                                int new_client)
1614 {
1615         int service_time = lustre_msg_get_service_time(req->rq_reqmsg);
1616         struct obd_device_target *obt = &obd->u.obt;
1617
1618         if (!new_client && service_time)
1619                 /* Teach server about old server's estimates, as first guess
1620                  * at how long new requests will take. */
1621                 at_measured(&req->rq_rqbd->rqbd_svcpt->scp_at_estimate,
1622                             service_time);
1623
1624         target_start_recovery_timer(obd);
1625
1626         /* Convert the service time to RPC timeout,
1627          * and reuse service_time to limit stack usage. */
1628         service_time = at_est2timeout(service_time);
1629
1630         /* We expect other clients to timeout within service_time, then try
1631          * to reconnect, then try the failover server.  The max delay between
1632          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL. */
1633         service_time += 2 * INITIAL_CONNECT_TIMEOUT;
1634
1635         LASSERT(obt->obt_magic == OBT_MAGIC);
1636         service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
1637         if (service_time > obd->obd_recovery_timeout && !new_client)
1638                 extend_recovery_timer(obd, service_time, false);
1639 }
1640
1641 /** Health checking routines */
1642 static inline int exp_connect_healthy(struct obd_export *exp)
1643 {
1644         return (exp->exp_in_recovery);
1645 }
1646
1647 /** if export done req_replay or has replay in queue */
1648 static inline int exp_req_replay_healthy(struct obd_export *exp)
1649 {
1650         return (!exp->exp_req_replay_needed ||
1651                 cfs_atomic_read(&exp->exp_replay_count) > 0);
1652 }
1653 /** if export done lock_replay or has replay in queue */
1654 static inline int exp_lock_replay_healthy(struct obd_export *exp)
1655 {
1656         return (!exp->exp_lock_replay_needed ||
1657                 cfs_atomic_read(&exp->exp_replay_count) > 0);
1658 }
1659
1660 static inline int exp_vbr_healthy(struct obd_export *exp)
1661 {
1662         return (!exp->exp_vbr_failed);
1663 }
1664
1665 static inline int exp_finished(struct obd_export *exp)
1666 {
1667         return (exp->exp_in_recovery && !exp->exp_lock_replay_needed);
1668 }
1669
1670 /** Checking routines for recovery */
1671 static int check_for_clients(struct obd_device *obd)
1672 {
1673         unsigned int clnts = cfs_atomic_read(&obd->obd_connected_clients);
1674
1675         if (obd->obd_abort_recovery || obd->obd_recovery_expired)
1676                 return 1;
1677         LASSERT(clnts <= obd->obd_max_recoverable_clients);
1678         return (clnts + obd->obd_stale_clients ==
1679                 obd->obd_max_recoverable_clients);
1680 }
1681
1682 static int check_for_next_transno(struct obd_device *obd)
1683 {
1684         struct ptlrpc_request *req = NULL;
1685         int wake_up = 0, connected, completed, queue_len;
1686         __u64 next_transno, req_transno;
1687         ENTRY;
1688
1689         spin_lock(&obd->obd_recovery_task_lock);
1690         if (!cfs_list_empty(&obd->obd_req_replay_queue)) {
1691                 req = cfs_list_entry(obd->obd_req_replay_queue.next,
1692                                      struct ptlrpc_request, rq_list);
1693                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1694         } else {
1695                 req_transno = 0;
1696         }
1697
1698         connected = cfs_atomic_read(&obd->obd_connected_clients);
1699         completed = connected - cfs_atomic_read(&obd->obd_req_replay_clients);
1700         queue_len = obd->obd_requests_queued_for_recovery;
1701         next_transno = obd->obd_next_recovery_transno;
1702
1703         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1704                "req_transno: "LPU64", next_transno: "LPU64"\n",
1705                obd->obd_max_recoverable_clients, connected, completed,
1706                queue_len, req_transno, next_transno);
1707
1708         if (obd->obd_abort_recovery) {
1709                 CDEBUG(D_HA, "waking for aborted recovery\n");
1710                 wake_up = 1;
1711         } else if (obd->obd_recovery_expired) {
1712                 CDEBUG(D_HA, "waking for expired recovery\n");
1713                 wake_up = 1;
1714         } else if (req_transno == next_transno) {
1715                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1716                 wake_up = 1;
1717         } else if (queue_len > 0 &&
1718                    queue_len == cfs_atomic_read(&obd->obd_req_replay_clients)) {
1719                 int d_lvl = D_HA;
1720                 /** handle gaps occured due to lost reply or VBR */
1721                 LASSERTF(req_transno >= next_transno,
1722                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1723                          req_transno, next_transno);
1724                 if (req_transno > obd->obd_last_committed &&
1725                     !obd->obd_version_recov)
1726                         d_lvl = D_ERROR;
1727                 CDEBUG(d_lvl,
1728                        "%s: waking for gap in transno, VBR is %s (skip: "
1729                        LPD64", ql: %d, comp: %d, conn: %d, next: "LPD64
1730                        ", last_committed: "LPD64")\n",
1731                        obd->obd_name, obd->obd_version_recov ? "ON" : "OFF",
1732                        next_transno, queue_len, completed, connected,
1733                        req_transno, obd->obd_last_committed);
1734                 obd->obd_next_recovery_transno = req_transno;
1735                 wake_up = 1;
1736         } else if (cfs_atomic_read(&obd->obd_req_replay_clients) == 0) {
1737                 CDEBUG(D_HA, "waking for completed recovery\n");
1738                 wake_up = 1;
1739         } else if (OBD_FAIL_CHECK(OBD_FAIL_MDS_RECOVERY_ACCEPTS_GAPS)) {
1740                 CDEBUG(D_HA, "accepting transno gaps is explicitly allowed"
1741                        " by fail_lock, waking up ("LPD64")\n", next_transno);
1742                 obd->obd_next_recovery_transno = req_transno;
1743                 wake_up = 1;
1744         }
1745         spin_unlock(&obd->obd_recovery_task_lock);
1746         return wake_up;
1747 }
1748
1749 static int check_for_next_lock(struct obd_device *obd)
1750 {
1751         int wake_up = 0;
1752
1753         spin_lock(&obd->obd_recovery_task_lock);
1754         if (!cfs_list_empty(&obd->obd_lock_replay_queue)) {
1755                 CDEBUG(D_HA, "waking for next lock\n");
1756                 wake_up = 1;
1757         } else if (cfs_atomic_read(&obd->obd_lock_replay_clients) == 0) {
1758                 CDEBUG(D_HA, "waking for completed lock replay\n");
1759                 wake_up = 1;
1760         } else if (obd->obd_abort_recovery) {
1761                 CDEBUG(D_HA, "waking for aborted recovery\n");
1762                 wake_up = 1;
1763         } else if (obd->obd_recovery_expired) {
1764                 CDEBUG(D_HA, "waking for expired recovery\n");
1765                 wake_up = 1;
1766         }
1767         spin_unlock(&obd->obd_recovery_task_lock);
1768
1769         return wake_up;
1770 }
1771
1772 /**
1773  * wait for recovery events,
1774  * check its status with help of check_routine
1775  * evict dead clients via health_check
1776  */
1777 static int target_recovery_overseer(struct obd_device *obd,
1778                                     int (*check_routine)(struct obd_device *),
1779                                     int (*health_check)(struct obd_export *))
1780 {
1781 repeat:
1782         wait_event(obd->obd_next_transno_waitq, check_routine(obd));
1783         if (obd->obd_abort_recovery) {
1784                 CWARN("recovery is aborted, evict exports in recovery\n");
1785                 /** evict exports which didn't finish recovery yet */
1786                 class_disconnect_stale_exports(obd, exp_finished);
1787                 return 1;
1788         } else if (obd->obd_recovery_expired) {
1789                 obd->obd_recovery_expired = 0;
1790                 /** If some clients died being recovered, evict them */
1791                 LCONSOLE_WARN("%s: recovery is timed out, "
1792                               "evict stale exports\n", obd->obd_name);
1793                 /** evict cexports with no replay in queue, they are stalled */
1794                 class_disconnect_stale_exports(obd, health_check);
1795                 /** continue with VBR */
1796                 spin_lock(&obd->obd_dev_lock);
1797                 obd->obd_version_recov = 1;
1798                 spin_unlock(&obd->obd_dev_lock);
1799                 /**
1800                  * reset timer, recovery will proceed with versions now,
1801                  * timeout is set just to handle reconnection delays
1802                  */
1803                 extend_recovery_timer(obd, RECONNECT_DELAY_MAX, true);
1804                 /** Wait for recovery events again, after evicting bad clients */
1805                 goto repeat;
1806         }
1807         return 0;
1808 }
1809
1810 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1811 {
1812         struct ptlrpc_request *req = NULL;
1813         ENTRY;
1814
1815         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1816                obd->obd_next_recovery_transno);
1817
1818         if (target_recovery_overseer(obd, check_for_next_transno,
1819                                      exp_req_replay_healthy)) {
1820                 abort_req_replay_queue(obd);
1821                 abort_lock_replay_queue(obd);
1822         }
1823
1824         spin_lock(&obd->obd_recovery_task_lock);
1825         if (!cfs_list_empty(&obd->obd_req_replay_queue)) {
1826                 req = cfs_list_entry(obd->obd_req_replay_queue.next,
1827                                      struct ptlrpc_request, rq_list);
1828                 cfs_list_del_init(&req->rq_list);
1829                 obd->obd_requests_queued_for_recovery--;
1830                 spin_unlock(&obd->obd_recovery_task_lock);
1831         } else {
1832                 spin_unlock(&obd->obd_recovery_task_lock);
1833                 LASSERT(cfs_list_empty(&obd->obd_req_replay_queue));
1834                 LASSERT(cfs_atomic_read(&obd->obd_req_replay_clients) == 0);
1835                 /** evict exports failed VBR */
1836                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1837         }
1838         RETURN(req);
1839 }
1840
1841 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1842 {
1843         struct ptlrpc_request *req = NULL;
1844
1845         CDEBUG(D_HA, "Waiting for lock\n");
1846         if (target_recovery_overseer(obd, check_for_next_lock,
1847                                      exp_lock_replay_healthy))
1848                 abort_lock_replay_queue(obd);
1849
1850         spin_lock(&obd->obd_recovery_task_lock);
1851         if (!cfs_list_empty(&obd->obd_lock_replay_queue)) {
1852                 req = cfs_list_entry(obd->obd_lock_replay_queue.next,
1853                                      struct ptlrpc_request, rq_list);
1854                 cfs_list_del_init(&req->rq_list);
1855                 spin_unlock(&obd->obd_recovery_task_lock);
1856         } else {
1857                 spin_unlock(&obd->obd_recovery_task_lock);
1858                 LASSERT(cfs_list_empty(&obd->obd_lock_replay_queue));
1859                 LASSERT(cfs_atomic_read(&obd->obd_lock_replay_clients) == 0);
1860                 /** evict exports failed VBR */
1861                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1862         }
1863         return req;
1864 }
1865
1866 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1867 {
1868         struct ptlrpc_request *req = NULL;
1869
1870         spin_lock(&obd->obd_recovery_task_lock);
1871         if (!cfs_list_empty(&obd->obd_final_req_queue)) {
1872                 req = cfs_list_entry(obd->obd_final_req_queue.next,
1873                                      struct ptlrpc_request, rq_list);
1874                 cfs_list_del_init(&req->rq_list);
1875                 spin_unlock(&obd->obd_recovery_task_lock);
1876                 if (req->rq_export->exp_in_recovery) {
1877                         spin_lock(&req->rq_export->exp_lock);
1878                         req->rq_export->exp_in_recovery = 0;
1879                         spin_unlock(&req->rq_export->exp_lock);
1880                 }
1881         } else {
1882                 spin_unlock(&obd->obd_recovery_task_lock);
1883         }
1884         return req;
1885 }
1886
1887 static int handle_recovery_req(struct ptlrpc_thread *thread,
1888                                struct ptlrpc_request *req,
1889                                svc_handler_t handler)
1890 {
1891         int rc;
1892         ENTRY;
1893
1894         /**
1895          * export can be evicted during recovery, no need to handle replays for
1896          * it after that, discard such request silently
1897          */
1898         if (req->rq_export->exp_disconnected)
1899                 GOTO(reqcopy_put, rc = 0);
1900
1901         rc = lu_context_init(&req->rq_recov_session, LCT_SERVER_SESSION);
1902         if (rc) {
1903                 CERROR("Failure to initialize session: %d\n", rc);
1904                 GOTO(reqcopy_put, rc);
1905         }
1906
1907         req->rq_recov_session.lc_thread = thread;
1908         lu_context_enter(&req->rq_recov_session);
1909         req->rq_svc_thread = thread;
1910         req->rq_svc_thread->t_env->le_ses = &req->rq_recov_session;
1911
1912         /* thread context */
1913         lu_context_enter(&thread->t_env->le_ctx);
1914         (void)handler(req);
1915         lu_context_exit(&thread->t_env->le_ctx);
1916
1917         lu_context_exit(&req->rq_recov_session);
1918         lu_context_fini(&req->rq_recov_session);
1919         /* don't reset timer for final stage */
1920         if (!exp_finished(req->rq_export)) {
1921                 int to = obd_timeout;
1922
1923                 /**
1924                  * Add request timeout to the recovery time so next request from
1925                  * this client may come in recovery time
1926                  */
1927                 if (!AT_OFF) {
1928                         struct ptlrpc_service_part *svcpt;
1929
1930                         svcpt = req->rq_rqbd->rqbd_svcpt;
1931                         /* If the server sent early reply for this request,
1932                          * the client will recalculate the timeout according to
1933                          * current server estimate service time, so we will
1934                          * use the maxium timeout here for waiting the client
1935                          * sending the next req */
1936                         to = max((int)at_est2timeout(
1937                                  at_get(&svcpt->scp_at_estimate)),
1938                                  (int)lustre_msg_get_timeout(req->rq_reqmsg));
1939                         /* Add 2 net_latency, one for balance rq_deadline
1940                          * (see ptl_send_rpc), one for resend the req to server,
1941                          * Note: client will pack net_latency in replay req
1942                          * (see ptlrpc_replay_req) */
1943                         to += 2 * lustre_msg_get_service_time(req->rq_reqmsg);
1944                 }
1945                 extend_recovery_timer(class_exp2obd(req->rq_export), to, true);
1946         }
1947 reqcopy_put:
1948         RETURN(rc);
1949 }
1950
1951 static int target_recovery_thread(void *arg)
1952 {
1953         struct lu_target *lut = arg;
1954         struct obd_device *obd = lut->lut_obd;
1955         struct ptlrpc_request *req;
1956         struct target_recovery_data *trd = &obd->obd_recovery_data;
1957         unsigned long delta;
1958         struct lu_env *env;
1959         struct ptlrpc_thread *thread = NULL;
1960         int rc = 0;
1961         ENTRY;
1962
1963         unshare_fs_struct();
1964         OBD_ALLOC_PTR(thread);
1965         if (thread == NULL)
1966                 RETURN(-ENOMEM);
1967
1968         OBD_ALLOC_PTR(env);
1969         if (env == NULL) {
1970                 OBD_FREE_PTR(thread);
1971                 RETURN(-ENOMEM);
1972         }
1973
1974         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD);
1975         if (rc) {
1976                 OBD_FREE_PTR(thread);
1977                 OBD_FREE_PTR(env);
1978                 RETURN(rc);
1979         }
1980
1981         thread->t_env = env;
1982         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
1983         env->le_ctx.lc_thread = thread;
1984         tgt_io_thread_init(thread); /* init thread_big_cache for IO requests */
1985         thread->t_watchdog = NULL;
1986
1987         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
1988                current_pid());
1989         trd->trd_processing_task = current_pid();
1990
1991         spin_lock(&obd->obd_dev_lock);
1992         obd->obd_recovering = 1;
1993         spin_unlock(&obd->obd_dev_lock);
1994         complete(&trd->trd_starting);
1995
1996         /* first of all, we have to know the first transno to replay */
1997         if (target_recovery_overseer(obd, check_for_clients,
1998                                      exp_connect_healthy)) {
1999                 abort_req_replay_queue(obd);
2000                 abort_lock_replay_queue(obd);
2001         }
2002
2003         /* next stage: replay requests */
2004         delta = jiffies;
2005         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
2006                cfs_atomic_read(&obd->obd_req_replay_clients),
2007                obd->obd_next_recovery_transno);
2008         while ((req = target_next_replay_req(obd))) {
2009                 LASSERT(trd->trd_processing_task == current_pid());
2010                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
2011                           lustre_msg_get_transno(req->rq_reqmsg),
2012                           libcfs_nid2str(req->rq_peer.nid));
2013                 handle_recovery_req(thread, req,
2014                                     trd->trd_recovery_handler);
2015                 /**
2016                  * bz18031: increase next_recovery_transno before
2017                  * target_request_copy_put() will drop exp_rpc reference
2018                  */
2019                 spin_lock(&obd->obd_recovery_task_lock);
2020                 obd->obd_next_recovery_transno++;
2021                 spin_unlock(&obd->obd_recovery_task_lock);
2022                 target_exp_dequeue_req_replay(req);
2023                 target_request_copy_put(req);
2024                 obd->obd_replayed_requests++;
2025         }
2026
2027         /**
2028          * The second stage: replay locks
2029          */
2030         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
2031                cfs_atomic_read(&obd->obd_lock_replay_clients));
2032         while ((req = target_next_replay_lock(obd))) {
2033                 LASSERT(trd->trd_processing_task == current_pid());
2034                 DEBUG_REQ(D_HA, req, "processing lock from %s: ",
2035                           libcfs_nid2str(req->rq_peer.nid));
2036                 handle_recovery_req(thread, req,
2037                                     trd->trd_recovery_handler);
2038                 target_request_copy_put(req);
2039                 obd->obd_replayed_locks++;
2040         }
2041
2042         /**
2043          * The third stage: reply on final pings, at this moment all clients
2044          * must have request in final queue
2045          */
2046         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
2047         /** Update server last boot epoch */
2048         tgt_boot_epoch_update(lut);
2049         /* We drop recoverying flag to forward all new requests
2050          * to regular mds_handle() since now */
2051         spin_lock(&obd->obd_dev_lock);
2052         obd->obd_recovering = obd->obd_abort_recovery = 0;
2053         spin_unlock(&obd->obd_dev_lock);
2054         spin_lock(&obd->obd_recovery_task_lock);
2055         target_cancel_recovery_timer(obd);
2056         spin_unlock(&obd->obd_recovery_task_lock);
2057         while ((req = target_next_final_ping(obd))) {
2058                 LASSERT(trd->trd_processing_task == current_pid());
2059                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
2060                           libcfs_nid2str(req->rq_peer.nid));
2061                 handle_recovery_req(thread, req,
2062                                     trd->trd_recovery_handler);
2063                 target_request_copy_put(req);
2064         }
2065
2066         delta = (jiffies - delta) / HZ;
2067         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
2068               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
2069         if (delta > OBD_RECOVERY_TIME_SOFT) {
2070                 CWARN("too long recovery - read logs\n");
2071                 libcfs_debug_dumplog();
2072         }
2073
2074         target_finish_recovery(obd);
2075
2076         lu_context_fini(&env->le_ctx);
2077         trd->trd_processing_task = 0;
2078         complete(&trd->trd_finishing);
2079
2080         tgt_io_thread_done(thread);
2081         OBD_FREE_PTR(thread);
2082         OBD_FREE_PTR(env);
2083         RETURN(rc);
2084 }
2085
2086 static int target_start_recovery_thread(struct lu_target *lut,
2087                                         svc_handler_t handler)
2088 {
2089         struct obd_device *obd = lut->lut_obd;
2090         int rc = 0;
2091         struct target_recovery_data *trd = &obd->obd_recovery_data;
2092
2093         memset(trd, 0, sizeof(*trd));
2094         init_completion(&trd->trd_starting);
2095         init_completion(&trd->trd_finishing);
2096         trd->trd_recovery_handler = handler;
2097
2098         if (!IS_ERR(kthread_run(target_recovery_thread,
2099                                 lut, "tgt_recov"))) {
2100                 wait_for_completion(&trd->trd_starting);
2101                 LASSERT(obd->obd_recovering != 0);
2102         } else {
2103                 rc = -ECHILD;
2104         }
2105
2106         return rc;
2107 }
2108
2109 void target_stop_recovery_thread(struct obd_device *obd)
2110 {
2111         if (obd->obd_recovery_data.trd_processing_task > 0) {
2112                 struct target_recovery_data *trd = &obd->obd_recovery_data;
2113                 /** recovery can be done but postrecovery is not yet */
2114                 spin_lock(&obd->obd_dev_lock);
2115                 if (obd->obd_recovering) {
2116                         CERROR("%s: Aborting recovery\n", obd->obd_name);
2117                         obd->obd_abort_recovery = 1;
2118                         wake_up(&obd->obd_next_transno_waitq);
2119                 }
2120                 spin_unlock(&obd->obd_dev_lock);
2121                 wait_for_completion(&trd->trd_finishing);
2122         }
2123 }
2124 EXPORT_SYMBOL(target_stop_recovery_thread);
2125
2126 void target_recovery_fini(struct obd_device *obd)
2127 {
2128         class_disconnect_exports(obd);
2129         target_stop_recovery_thread(obd);
2130         target_cleanup_recovery(obd);
2131 }
2132 EXPORT_SYMBOL(target_recovery_fini);
2133
2134 static void target_recovery_expired(unsigned long castmeharder)
2135 {
2136         struct obd_device *obd = (struct obd_device *)castmeharder;
2137         CDEBUG(D_HA, "%s: recovery timed out; %d clients are still in recovery"
2138                " after %lds (%d clients connected)\n",
2139                obd->obd_name, cfs_atomic_read(&obd->obd_lock_replay_clients),
2140                cfs_time_current_sec()- obd->obd_recovery_start,
2141                cfs_atomic_read(&obd->obd_connected_clients));
2142
2143         obd->obd_recovery_expired = 1;
2144         wake_up(&obd->obd_next_transno_waitq);
2145 }
2146
2147 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
2148 {
2149         struct obd_device *obd = lut->lut_obd;
2150         if (obd->obd_max_recoverable_clients == 0) {
2151                 /** Update server last boot epoch */
2152                 tgt_boot_epoch_update(lut);
2153                 return;
2154         }
2155
2156         CDEBUG(D_HA, "RECOVERY: service %s, %d recoverable clients, "
2157                "last_transno "LPU64"\n", obd->obd_name,
2158                obd->obd_max_recoverable_clients, obd->obd_last_committed);
2159         LASSERT(obd->obd_stopping == 0);
2160         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
2161         obd->obd_recovery_start = 0;
2162         obd->obd_recovery_end = 0;
2163
2164         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
2165         target_start_recovery_thread(lut, handler);
2166 }
2167 EXPORT_SYMBOL(target_recovery_init);
2168
2169 #endif /* __KERNEL__ */
2170
2171 static int target_process_req_flags(struct obd_device *obd,
2172                                     struct ptlrpc_request *req)
2173 {
2174         struct obd_export *exp = req->rq_export;
2175         LASSERT(exp != NULL);
2176         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2177                 /* client declares he's ready to replay locks */
2178                 spin_lock(&exp->exp_lock);
2179                 if (exp->exp_req_replay_needed) {
2180                         exp->exp_req_replay_needed = 0;
2181                         spin_unlock(&exp->exp_lock);
2182
2183                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
2184                         cfs_atomic_dec(&obd->obd_req_replay_clients);
2185                 } else {
2186                         spin_unlock(&exp->exp_lock);
2187                 }
2188         }
2189         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2190                 /* client declares he's ready to complete recovery
2191                  * so, we put the request on th final queue */
2192                 spin_lock(&exp->exp_lock);
2193                 if (exp->exp_lock_replay_needed) {
2194                         exp->exp_lock_replay_needed = 0;
2195                         spin_unlock(&exp->exp_lock);
2196
2197                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
2198                         cfs_atomic_dec(&obd->obd_lock_replay_clients);
2199                 } else {
2200                         spin_unlock(&exp->exp_lock);
2201                 }
2202         }
2203         return 0;
2204 }
2205
2206 int target_queue_recovery_request(struct ptlrpc_request *req,
2207                                   struct obd_device *obd)
2208 {
2209         cfs_list_t *tmp;
2210         int inserted = 0;
2211         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
2212         ENTRY;
2213
2214         if (obd->obd_recovery_data.trd_processing_task == current_pid()) {
2215                 /* Processing the queue right now, don't re-add. */
2216                 RETURN(1);
2217         }
2218
2219         target_process_req_flags(obd, req);
2220
2221         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2222                 /* client declares he's ready to complete recovery
2223                  * so, we put the request on th final queue */
2224                 target_request_copy_get(req);
2225                 DEBUG_REQ(D_HA, req, "queue final req");
2226                 wake_up(&obd->obd_next_transno_waitq);
2227                 spin_lock(&obd->obd_recovery_task_lock);
2228                 if (obd->obd_recovering) {
2229                         cfs_list_add_tail(&req->rq_list,
2230                                           &obd->obd_final_req_queue);
2231                 } else {
2232                         spin_unlock(&obd->obd_recovery_task_lock);
2233                         target_request_copy_put(req);
2234                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
2235                 }
2236                 spin_unlock(&obd->obd_recovery_task_lock);
2237                 RETURN(0);
2238         }
2239         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2240                 /* client declares he's ready to replay locks */
2241                 target_request_copy_get(req);
2242                 DEBUG_REQ(D_HA, req, "queue lock replay req");
2243                 wake_up(&obd->obd_next_transno_waitq);
2244                 spin_lock(&obd->obd_recovery_task_lock);
2245                 LASSERT(obd->obd_recovering);
2246                 /* usually due to recovery abort */
2247                 if (!req->rq_export->exp_in_recovery) {
2248                         spin_unlock(&obd->obd_recovery_task_lock);
2249                         target_request_copy_put(req);
2250                         RETURN(-ENOTCONN);
2251                 }
2252                 LASSERT(req->rq_export->exp_lock_replay_needed);
2253                 cfs_list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
2254                 spin_unlock(&obd->obd_recovery_task_lock);
2255                 RETURN(0);
2256         }
2257
2258         /* CAVEAT EMPTOR: The incoming request message has been swabbed
2259          * (i.e. buflens etc are in my own byte order), but type-dependent
2260          * buffers (eg mdt_body, ost_body etc) have NOT been swabbed. */
2261
2262         if (!transno) {
2263                 CFS_INIT_LIST_HEAD(&req->rq_list);
2264                 DEBUG_REQ(D_HA, req, "not queueing");
2265                 RETURN(1);
2266         }
2267
2268         /* If we're processing the queue, we want don't want to queue this
2269          * message.
2270          *
2271          * Also, if this request has a transno less than the one we're waiting
2272          * for, we should process it now.  It could (and currently always will)
2273          * be an open request for a descriptor that was opened some time ago.
2274          *
2275          * Also, a resent, replayed request that has already been
2276          * handled will pass through here and be processed immediately.
2277          */
2278         CDEBUG(D_HA, "Next recovery transno: "LPU64
2279                ", current: "LPU64", replaying\n",
2280                obd->obd_next_recovery_transno, transno);
2281         spin_lock(&obd->obd_recovery_task_lock);
2282         if (transno < obd->obd_next_recovery_transno) {
2283                 /* Processing the queue right now, don't re-add. */
2284                 LASSERT(cfs_list_empty(&req->rq_list));
2285                 spin_unlock(&obd->obd_recovery_task_lock);
2286                 RETURN(1);
2287         }
2288         spin_unlock(&obd->obd_recovery_task_lock);
2289
2290         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
2291                 RETURN(0);
2292
2293         target_request_copy_get(req);
2294         if (!req->rq_export->exp_in_recovery) {
2295                 target_request_copy_put(req);
2296                 RETURN(-ENOTCONN);
2297         }
2298         LASSERT(req->rq_export->exp_req_replay_needed);
2299
2300         if (target_exp_enqueue_req_replay(req)) {
2301                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
2302                 target_request_copy_put(req);
2303                 RETURN(0);
2304         }
2305
2306         /* XXX O(n^2) */
2307         spin_lock(&obd->obd_recovery_task_lock);
2308         LASSERT(obd->obd_recovering);
2309         cfs_list_for_each(tmp, &obd->obd_req_replay_queue) {
2310                 struct ptlrpc_request *reqiter =
2311                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2312
2313                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
2314                         cfs_list_add_tail(&req->rq_list, &reqiter->rq_list);
2315                         inserted = 1;
2316                         break;
2317                 }
2318
2319                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
2320                              transno)) {
2321                         DEBUG_REQ(D_ERROR, req, "dropping replay: transno "
2322                                   "has been claimed by another client");
2323                         spin_unlock(&obd->obd_recovery_task_lock);
2324                         target_exp_dequeue_req_replay(req);
2325                         target_request_copy_put(req);
2326                         RETURN(0);
2327                 }
2328         }
2329
2330         if (!inserted)
2331                 cfs_list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
2332
2333         obd->obd_requests_queued_for_recovery++;
2334         spin_unlock(&obd->obd_recovery_task_lock);
2335         wake_up(&obd->obd_next_transno_waitq);
2336         RETURN(0);
2337 }
2338 EXPORT_SYMBOL(target_queue_recovery_request);
2339
2340 int target_handle_ping(struct ptlrpc_request *req)
2341 {
2342         obd_ping(req->rq_svc_thread->t_env, req->rq_export);
2343         return req_capsule_server_pack(&req->rq_pill);
2344 }
2345 EXPORT_SYMBOL(target_handle_ping);
2346
2347 void target_committed_to_req(struct ptlrpc_request *req)
2348 {
2349         struct obd_export *exp = req->rq_export;
2350
2351         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
2352                 lustre_msg_set_last_committed(req->rq_repmsg,
2353                                               exp->exp_last_committed);
2354         else
2355                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
2356                           "%d)", exp->exp_obd->obd_no_transno,
2357                           req->rq_repmsg == NULL);
2358
2359         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
2360                exp->exp_last_committed, req->rq_transno, req->rq_xid);
2361 }
2362 EXPORT_SYMBOL(target_committed_to_req);
2363
2364 #endif /* HAVE_SERVER_SUPPORT */
2365
2366 /**
2367  * Packs current SLV and Limit into \a req.
2368  */
2369 int target_pack_pool_reply(struct ptlrpc_request *req)
2370 {
2371         struct obd_device *obd;
2372         ENTRY;
2373
2374         /* Check that we still have all structures alive as this may
2375          * be some late RPC at shutdown time. */
2376         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
2377                      !exp_connect_lru_resize(req->rq_export))) {
2378                 lustre_msg_set_slv(req->rq_repmsg, 0);
2379                 lustre_msg_set_limit(req->rq_repmsg, 0);
2380                 RETURN(0);
2381         }
2382
2383         /* OBD is alive here as export is alive, which we checked above. */
2384         obd = req->rq_export->exp_obd;
2385
2386         read_lock(&obd->obd_pool_lock);
2387         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
2388         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
2389         read_unlock(&obd->obd_pool_lock);
2390
2391         RETURN(0);
2392 }
2393 EXPORT_SYMBOL(target_pack_pool_reply);
2394
2395 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
2396 {
2397         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
2398                 DEBUG_REQ(D_ERROR, req, "dropping reply");
2399                 return (-ECOMM);
2400         }
2401
2402         if (unlikely(rc)) {
2403                 DEBUG_REQ(D_NET, req, "processing error (%d)", rc);
2404                 req->rq_status = rc;
2405                 return (ptlrpc_send_error(req, 1));
2406         } else {
2407                 DEBUG_REQ(D_NET, req, "sending reply");
2408         }
2409
2410         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
2411 }
2412
2413 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
2414 {
2415         struct ptlrpc_service_part *svcpt;
2416         int                        netrc;
2417         struct ptlrpc_reply_state *rs;
2418         struct obd_export         *exp;
2419         ENTRY;
2420
2421         if (req->rq_no_reply) {
2422                 EXIT;
2423                 return;
2424         }
2425
2426         svcpt = req->rq_rqbd->rqbd_svcpt;
2427         rs = req->rq_reply_state;
2428         if (rs == NULL || !rs->rs_difficult) {
2429                 /* no notifiers */
2430                 target_send_reply_msg (req, rc, fail_id);
2431                 EXIT;
2432                 return;
2433         }
2434
2435         /* must be an export if locks saved */
2436         LASSERT (req->rq_export != NULL);
2437         /* req/reply consistent */
2438         LASSERT(rs->rs_svcpt == svcpt);
2439
2440         /* "fresh" reply */
2441         LASSERT (!rs->rs_scheduled);
2442         LASSERT (!rs->rs_scheduled_ever);
2443         LASSERT (!rs->rs_handled);
2444         LASSERT (!rs->rs_on_net);
2445         LASSERT (rs->rs_export == NULL);
2446         LASSERT (cfs_list_empty(&rs->rs_obd_list));
2447         LASSERT (cfs_list_empty(&rs->rs_exp_list));
2448
2449         exp = class_export_get (req->rq_export);
2450
2451         /* disable reply scheduling while I'm setting up */
2452         rs->rs_scheduled = 1;
2453         rs->rs_on_net    = 1;
2454         rs->rs_xid       = req->rq_xid;
2455         rs->rs_transno   = req->rq_transno;
2456         rs->rs_export    = exp;
2457         rs->rs_opc       = lustre_msg_get_opc(req->rq_reqmsg);
2458
2459         spin_lock(&exp->exp_uncommitted_replies_lock);
2460         CDEBUG(D_NET, "rs transno = "LPU64", last committed = "LPU64"\n",
2461                rs->rs_transno, exp->exp_last_committed);
2462         if (rs->rs_transno > exp->exp_last_committed) {
2463                 /* not committed already */
2464                 cfs_list_add_tail(&rs->rs_obd_list,
2465                                   &exp->exp_uncommitted_replies);
2466         }
2467         spin_unlock(&exp->exp_uncommitted_replies_lock);
2468
2469         spin_lock(&exp->exp_lock);
2470         cfs_list_add_tail(&rs->rs_exp_list, &exp->exp_outstanding_replies);
2471         spin_unlock(&exp->exp_lock);
2472
2473         netrc = target_send_reply_msg(req, rc, fail_id);
2474
2475         spin_lock(&svcpt->scp_rep_lock);
2476
2477         cfs_atomic_inc(&svcpt->scp_nreps_difficult);
2478
2479         if (netrc != 0) {
2480                 /* error sending: reply is off the net.  Also we need +1
2481                  * reply ref until ptlrpc_handle_rs() is done
2482                  * with the reply state (if the send was successful, there
2483                  * would have been +1 ref for the net, which
2484                  * reply_out_callback leaves alone) */
2485                 rs->rs_on_net = 0;
2486                 ptlrpc_rs_addref(rs);
2487         }
2488
2489         spin_lock(&rs->rs_lock);
2490         if (rs->rs_transno <= exp->exp_last_committed ||
2491             (!rs->rs_on_net && !rs->rs_no_ack) ||
2492             cfs_list_empty(&rs->rs_exp_list) ||     /* completed already */
2493             cfs_list_empty(&rs->rs_obd_list)) {
2494                 CDEBUG(D_HA, "Schedule reply immediately\n");
2495                 ptlrpc_dispatch_difficult_reply(rs);
2496         } else {
2497                 cfs_list_add(&rs->rs_list, &svcpt->scp_rep_active);
2498                 rs->rs_scheduled = 0;   /* allow notifier to schedule */
2499         }
2500         spin_unlock(&rs->rs_lock);
2501         spin_unlock(&svcpt->scp_rep_lock);
2502         EXIT;
2503 }
2504 EXPORT_SYMBOL(target_send_reply);
2505
2506 ldlm_mode_t lck_compat_array[] = {
2507         [LCK_EX] LCK_COMPAT_EX,
2508         [LCK_PW] LCK_COMPAT_PW,
2509         [LCK_PR] LCK_COMPAT_PR,
2510         [LCK_CW] LCK_COMPAT_CW,
2511         [LCK_CR] LCK_COMPAT_CR,
2512         [LCK_NL] LCK_COMPAT_NL,
2513         [LCK_GROUP] LCK_COMPAT_GROUP,
2514         [LCK_COS] LCK_COMPAT_COS,
2515 };
2516
2517 /**
2518  * Rather arbitrary mapping from LDLM error codes to errno values. This should
2519  * not escape to the user level.
2520  */
2521 int ldlm_error2errno(ldlm_error_t error)
2522 {
2523         int result;
2524
2525         switch (error) {
2526         case ELDLM_OK:
2527                 result = 0;
2528                 break;
2529         case ELDLM_LOCK_CHANGED:
2530                 result = -ESTALE;
2531                 break;
2532         case ELDLM_LOCK_ABORTED:
2533                 result = -ENAVAIL;
2534                 break;
2535         case ELDLM_LOCK_REPLACED:
2536                 result = -ESRCH;
2537                 break;
2538         case ELDLM_NO_LOCK_DATA:
2539                 result = -ENOENT;
2540                 break;
2541         case ELDLM_NAMESPACE_EXISTS:
2542                 result = -EEXIST;
2543                 break;
2544         case ELDLM_BAD_NAMESPACE:
2545                 result = -EBADF;
2546                 break;
2547         default:
2548                 if (((int)error) < 0)  /* cast to signed type */
2549                         result = error; /* as ldlm_error_t can be unsigned */
2550                 else {
2551                         CERROR("Invalid DLM result code: %d\n", error);
2552                         result = -EPROTO;
2553                 }
2554         }
2555         return result;
2556 }
2557 EXPORT_SYMBOL(ldlm_error2errno);
2558
2559 /**
2560  * Dual to ldlm_error2errno(): maps errno values back to ldlm_error_t.
2561  */
2562 ldlm_error_t ldlm_errno2error(int err_no)
2563 {
2564         int error;
2565
2566         switch (err_no) {
2567         case 0:
2568                 error = ELDLM_OK;
2569                 break;
2570         case -ESTALE:
2571                 error = ELDLM_LOCK_CHANGED;
2572                 break;
2573         case -ENAVAIL:
2574                 error = ELDLM_LOCK_ABORTED;
2575                 break;
2576         case -ESRCH:
2577                 error = ELDLM_LOCK_REPLACED;
2578                 break;
2579         case -ENOENT:
2580                 error = ELDLM_NO_LOCK_DATA;
2581                 break;
2582         case -EEXIST:
2583                 error = ELDLM_NAMESPACE_EXISTS;
2584                 break;
2585         case -EBADF:
2586                 error = ELDLM_BAD_NAMESPACE;
2587                 break;
2588         default:
2589                 error = err_no;
2590         }
2591         return error;
2592 }
2593 EXPORT_SYMBOL(ldlm_errno2error);
2594
2595 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2596 void ldlm_dump_export_locks(struct obd_export *exp)
2597 {
2598         spin_lock(&exp->exp_locks_list_guard);
2599         if (!cfs_list_empty(&exp->exp_locks_list)) {
2600                 struct ldlm_lock *lock;
2601
2602                 CERROR("dumping locks for export %p,"
2603                        "ignore if the unmount doesn't hang\n", exp);
2604                 cfs_list_for_each_entry(lock, &exp->exp_locks_list,
2605                                         l_exp_refs_link)
2606                         LDLM_ERROR(lock, "lock:");
2607         }
2608         spin_unlock(&exp->exp_locks_list_guard);
2609 }
2610 #endif
2611
2612 #ifdef HAVE_SERVER_SUPPORT
2613 static int target_bulk_timeout(void *data)
2614 {
2615         ENTRY;
2616         /* We don't fail the connection here, because having the export
2617          * killed makes the (vital) call to commitrw very sad.
2618          */
2619         RETURN(1);
2620 }
2621
2622 static inline char *bulk2type(struct ptlrpc_bulk_desc *desc)
2623 {
2624         return desc->bd_type == BULK_GET_SINK ? "GET" : "PUT";
2625 }
2626
2627 int target_bulk_io(struct obd_export *exp, struct ptlrpc_bulk_desc *desc,
2628                    struct l_wait_info *lwi)
2629 {
2630         struct ptlrpc_request   *req = desc->bd_req;
2631         time_t                   start = cfs_time_current_sec();
2632         int                      rc = 0;
2633
2634         ENTRY;
2635
2636         /* If there is eviction in progress, wait for it to finish. */
2637         if (unlikely(cfs_atomic_read(&exp->exp_obd->obd_evict_inprogress))) {
2638                 *lwi = LWI_INTR(NULL, NULL);
2639                 rc = l_wait_event(exp->exp_obd->obd_evict_inprogress_waitq,
2640                                   !cfs_atomic_read(&exp->exp_obd->
2641                                                    obd_evict_inprogress),
2642                                   lwi);
2643         }
2644
2645         /* Check if client was evicted or reconnected already. */
2646         if (exp->exp_failed ||
2647             exp->exp_conn_cnt > lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
2648                 rc = -ENOTCONN;
2649         } else {
2650                 if (desc->bd_type == BULK_PUT_SINK)
2651                         rc = sptlrpc_svc_wrap_bulk(req, desc);
2652                 if (rc == 0)
2653                         rc = ptlrpc_start_bulk_transfer(desc);
2654         }
2655
2656         if (rc < 0) {
2657                 DEBUG_REQ(D_ERROR, req, "bulk %s failed: rc %d",
2658                           bulk2type(desc), rc);
2659                 RETURN(rc);
2660         }
2661
2662         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
2663                 ptlrpc_abort_bulk(desc);
2664                 RETURN(0);
2665         }
2666
2667         do {
2668                 long timeoutl = req->rq_deadline - cfs_time_current_sec();
2669                 cfs_duration_t timeout = timeoutl <= 0 ?
2670                                          CFS_TICK : cfs_time_seconds(timeoutl);
2671
2672                 *lwi = LWI_TIMEOUT_INTERVAL(timeout, cfs_time_seconds(1),
2673                                             target_bulk_timeout, desc);
2674                 rc = l_wait_event(desc->bd_waitq,
2675                                   !ptlrpc_server_bulk_active(desc) ||
2676                                   exp->exp_failed ||
2677                                   exp->exp_conn_cnt >
2678                                   lustre_msg_get_conn_cnt(req->rq_reqmsg),
2679                                   lwi);
2680                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
2681                 /* Wait again if we changed deadline. */
2682         } while ((rc == -ETIMEDOUT) &&
2683                  (req->rq_deadline > cfs_time_current_sec()));
2684
2685         if (rc == -ETIMEDOUT) {
2686                 DEBUG_REQ(D_ERROR, req, "timeout on bulk %s after %ld%+lds",
2687                           bulk2type(desc), req->rq_deadline - start,
2688                           cfs_time_current_sec() - req->rq_deadline);
2689                 ptlrpc_abort_bulk(desc);
2690         } else if (exp->exp_failed) {
2691                 DEBUG_REQ(D_ERROR, req, "Eviction on bulk %s",
2692                           bulk2type(desc));
2693                 rc = -ENOTCONN;
2694                 ptlrpc_abort_bulk(desc);
2695         } else if (exp->exp_conn_cnt >
2696                    lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
2697                 DEBUG_REQ(D_ERROR, req, "Reconnect on bulk %s",
2698                           bulk2type(desc));
2699                 /* We don't reply anyway. */
2700                 rc = -ETIMEDOUT;
2701                 ptlrpc_abort_bulk(desc);
2702         } else if (desc->bd_failure ||
2703                    desc->bd_nob_transferred != desc->bd_nob) {
2704                 DEBUG_REQ(D_ERROR, req, "%s bulk %s %d(%d)",
2705                           desc->bd_failure ? "network error on" : "truncated",
2706                           bulk2type(desc), desc->bd_nob_transferred,
2707                           desc->bd_nob);
2708                 /* XXX Should this be a different errno? */
2709                 rc = -ETIMEDOUT;
2710         } else if (desc->bd_type == BULK_GET_SINK) {
2711                 rc = sptlrpc_svc_unwrap_bulk(req, desc);
2712         }
2713
2714         RETURN(rc);
2715 }
2716 EXPORT_SYMBOL(target_bulk_io);
2717
2718 #endif /* HAVE_SERVER_SUPPORT */