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