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