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