Whamcloud - gitweb
ORNL-27: Cancel on completion lock on the MGS
[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, NULL);
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 static void
676 target_start_and_reset_recovery_timer(struct obd_device *obd,
677                                       struct ptlrpc_request *req,
678                                       int new_client);
679
680 int target_handle_connect(struct ptlrpc_request *req)
681 {
682         struct obd_device *target, *targref = NULL;
683         struct obd_export *export = NULL;
684         struct obd_import *revimp;
685         struct lustre_handle conn;
686         struct lustre_handle *tmp;
687         struct obd_uuid tgtuuid;
688         struct obd_uuid cluuid;
689         struct obd_uuid remote_uuid;
690         char *str;
691         int rc = 0;
692         int mds_conn = 0;
693         struct obd_connect_data *data, *tmpdata;
694         int size, tmpsize;
695         lnet_nid_t *client_nid = NULL;
696         ENTRY;
697
698         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
699
700         str = req_capsule_client_get(&req->rq_pill, &RMF_TGTUUID);
701         if (str == NULL) {
702                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
703                 GOTO(out, rc = -EINVAL);
704         }
705
706         obd_str2uuid(&tgtuuid, str);
707         target = class_uuid2obd(&tgtuuid);
708         if (!target)
709                 target = class_name2obd(str);
710
711         if (!target || target->obd_stopping || !target->obd_set_up) {
712                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
713                                    "for connect (%s)\n", str,
714                                    !target ? "no target" :
715                                    (target->obd_stopping ? "stopping" :
716                                    "not set up"));
717                 GOTO(out, rc = -ENODEV);
718         }
719
720         if (target->obd_no_conn) {
721                 LCONSOLE_WARN("%s: temporarily refusing client connection "
722                               "from %s\n", target->obd_name,
723                               libcfs_nid2str(req->rq_peer.nid));
724                 GOTO(out, rc = -EAGAIN);
725         }
726
727         /* Make sure the target isn't cleaned up while we're here. Yes,
728            there's still a race between the above check and our incref here.
729            Really, class_uuid2obd should take the ref. */
730         targref = class_incref(target, __FUNCTION__, cfs_current());
731
732
733         str = req_capsule_client_get(&req->rq_pill, &RMF_CLUUID);
734         if (str == NULL) {
735                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
736                 GOTO(out, rc = -EINVAL);
737         }
738
739         obd_str2uuid(&cluuid, str);
740
741         /* XXX extract a nettype and format accordingly */
742         switch (sizeof(lnet_nid_t)) {
743                 /* NB the casts only avoid compiler warnings */
744         case 8:
745                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
746                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
747                 break;
748         case 4:
749                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
750                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
751                 break;
752         default:
753                 LBUG();
754         }
755
756         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
757         if (tmp == NULL)
758                 GOTO(out, rc = -EPROTO);
759
760         conn = *tmp;
761
762         size = req_capsule_get_size(&req->rq_pill, &RMF_CONNECT_DATA,
763                                     RCL_CLIENT);
764         data = req_capsule_client_get(&req->rq_pill, &RMF_CONNECT_DATA);
765         if (!data)
766                 GOTO(out, rc = -EPROTO);
767
768         rc = req_capsule_server_pack(&req->rq_pill);
769         if (rc)
770                 GOTO(out, rc);
771
772         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
773                 if (!data) {
774                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
775                                   "libclient connection attempt");
776                         GOTO(out, rc = -EPROTO);
777                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
778                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
779                            data->ocd_version > LUSTRE_VERSION_CODE +
780                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
781                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
782                                   "libclient connection attempt",
783                                   data->ocd_version < LUSTRE_VERSION_CODE ?
784                                   "old" : "new",
785                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
786                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
787                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
788                                   OBD_OCD_VERSION_FIX(data->ocd_version));
789                         data = req_capsule_server_sized_get(&req->rq_pill,
790                                                         &RMF_CONNECT_DATA,
791                                     offsetof(typeof(*data), ocd_version) +
792                                              sizeof(data->ocd_version));
793                         if (data) {
794                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
795                                 data->ocd_version = LUSTRE_VERSION_CODE;
796                         }
797                         GOTO(out, rc = -EPROTO);
798                 }
799         }
800
801         if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL) &&
802             (data->ocd_connect_flags & OBD_CONNECT_MDS))
803                 mds_conn = 1;
804
805         /* lctl gets a backstage, all-access pass. */
806         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
807                 goto dont_check_exports;
808
809         export = cfs_hash_lookup(target->obd_uuid_hash, &cluuid);
810         if (!export)
811                 goto no_export;
812
813         /* we've found an export in the hash */
814         if (export->exp_connecting) { /* bug 9635, et. al. */
815                 CWARN("%s: exp %p already connecting\n",
816                       export->exp_obd->obd_name, export);
817                 class_export_put(export);
818                 export = NULL;
819                 rc = -EALREADY;
820         } else if (mds_conn && export->exp_connection) {
821                 if (req->rq_peer.nid != export->exp_connection->c_peer.nid)
822                         /* mds reconnected after failover */
823                         CWARN("%s: received MDS connection from NID %s,"
824                               " removing former export from NID %s\n",
825                             target->obd_name, libcfs_nid2str(req->rq_peer.nid),
826                             libcfs_nid2str(export->exp_connection->c_peer.nid));
827                 else
828                         /* new mds connection from the same nid */
829                         CWARN("%s: received new MDS connection from NID %s,"
830                               " removing former export from same NID\n",
831                             target->obd_name, libcfs_nid2str(req->rq_peer.nid));
832                 class_fail_export(export);
833                 class_export_put(export);
834                 export = NULL;
835                 rc = 0;
836         } else if (export->exp_connection != NULL &&
837                    req->rq_peer.nid != export->exp_connection->c_peer.nid &&
838                    (lustre_msg_get_op_flags(req->rq_reqmsg) &
839                     MSG_CONNECT_INITIAL)) {
840                 /* in mds failover we have static uuid but nid can be
841                  * changed*/
842                 CWARN("%s: cookie %s seen on new NID %s when "
843                       "existing NID %s is already connected\n",
844                       target->obd_name, cluuid.uuid,
845                       libcfs_nid2str(req->rq_peer.nid),
846                       libcfs_nid2str(export->exp_connection->c_peer.nid));
847                 rc = -EALREADY;
848                 class_export_put(export);
849                 export = NULL;
850         } else {
851                 cfs_spin_lock(&export->exp_lock);
852                 export->exp_connecting = 1;
853                 cfs_spin_unlock(&export->exp_lock);
854                 class_export_put(export);
855                 LASSERT(export->exp_obd == target);
856
857                 rc = target_handle_reconnect(&conn, export, &cluuid);
858         }
859
860         /* If we found an export, we already unlocked. */
861         if (!export) {
862 no_export:
863                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
864         } else if (req->rq_export == NULL &&
865                    cfs_atomic_read(&export->exp_rpc_count) > 0) {
866                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
867                       target->obd_name, cluuid.uuid,
868                       libcfs_nid2str(req->rq_peer.nid),
869                       export, cfs_atomic_read(&export->exp_refcount));
870                 GOTO(out, rc = -EBUSY);
871         } else if (req->rq_export != NULL &&
872                    (cfs_atomic_read(&export->exp_rpc_count) > 1)) {
873                 /* the current connect rpc has increased exp_rpc_count */
874                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
875                       target->obd_name, cluuid.uuid,
876                       libcfs_nid2str(req->rq_peer.nid),
877                       export, cfs_atomic_read(&export->exp_rpc_count) - 1);
878                 cfs_spin_lock(&export->exp_lock);
879                 if (req->rq_export->exp_conn_cnt <
880                     lustre_msg_get_conn_cnt(req->rq_reqmsg))
881                         /* try to abort active requests */
882                         req->rq_export->exp_abort_active_req = 1;
883                 cfs_spin_unlock(&export->exp_lock);
884                 GOTO(out, rc = -EBUSY);
885         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1) {
886                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
887                        "cookies not random?\n", target->obd_name,
888                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
889                 GOTO(out, rc = -EALREADY);
890         } else {
891                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
892         }
893
894         if (rc < 0) {
895                 GOTO(out, rc);
896         }
897
898         CWARN("%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
899                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
900               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
901               export, (long)cfs_time_current_sec(),
902               export ? (long)export->exp_last_request_time : 0);
903
904         /* If this is the first time a client connects,
905          * reset the recovery timer */
906         if (rc == 0 && target->obd_recovering)
907                 target_start_and_reset_recovery_timer(target, req, !export);
908
909         /* We want to handle EALREADY but *not* -EALREADY from
910          * target_handle_reconnect(), return reconnection state in a flag */
911         if (rc == EALREADY) {
912                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
913                 rc = 0;
914         } else {
915                 LASSERT(rc == 0);
916         }
917
918         /* Tell the client if we support replayable requests */
919         if (target->obd_replayable)
920                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
921         client_nid = &req->rq_peer.nid;
922
923         if (export == NULL) {
924                 if (target->obd_recovering) {
925                         cfs_time_t t;
926
927                         t = cfs_timer_deadline(&target->obd_recovery_timer);
928                         t = cfs_time_sub(t, cfs_time_current());
929                         CERROR("%s: denying connection for new client %s (%s): "
930                                "%d clients in recovery for "CFS_TIME_T"s\n",
931                                target->obd_name,
932                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
933                                cfs_atomic_read(&target-> \
934                                                obd_lock_replay_clients),
935                                cfs_duration_sec(t));
936                         rc = -EBUSY;
937                 } else {
938 dont_check_exports:
939                         rc = obd_connect(req->rq_svc_thread->t_env,
940                                          &export, target, &cluuid, data,
941                                          client_nid);
942                         if (rc == 0)
943                                 conn.cookie = export->exp_handle.h_cookie;
944                 }
945         } else {
946                 rc = obd_reconnect(req->rq_svc_thread->t_env,
947                                    export, target, &cluuid, data, client_nid);
948                 if (rc == 0)
949                         /* prevous done via class_conn2export */
950                         class_export_get(export);
951         }
952         if (rc)
953                 GOTO(out, rc);
954
955         LASSERT(target->u.obt.obt_magic == OBT_MAGIC);
956         data->ocd_instance = target->u.obt.obt_instance;
957
958         /* Return only the parts of obd_connect_data that we understand, so the
959          * client knows that we don't understand the rest. */
960         if (data) {
961                 tmpsize = req_capsule_get_size(&req->rq_pill, &RMF_CONNECT_DATA,
962                                                RCL_SERVER);
963                 tmpdata = req_capsule_server_get(&req->rq_pill,
964                                                  &RMF_CONNECT_DATA);
965                 /* Don't use struct assignment here, because the client reply
966                  * buffer may be smaller/larger than the local struct
967                  * obd_connect_data. */
968                 memcpy(tmpdata, data, min(tmpsize, size));
969         }
970
971         /* If all else goes well, this is our RPC return code. */
972         req->rq_status = 0;
973
974         lustre_msg_set_handle(req->rq_repmsg, &conn);
975
976         /* If the client and the server are the same node, we will already
977          * have an export that really points to the client's DLM export,
978          * because we have a shared handles table.
979          *
980          * XXX this will go away when shaver stops sending the "connect" handle
981          * in the real "remote handle" field of the request --phik 24 Apr 2003
982          */
983         if (req->rq_export != NULL)
984                 class_export_put(req->rq_export);
985
986         req->rq_export = export;
987
988         cfs_spin_lock(&export->exp_lock);
989         if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
990                 cfs_spin_unlock(&export->exp_lock);
991                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
992                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
993                        export->exp_conn_cnt,
994                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
995
996                 GOTO(out, rc = -EALREADY);
997         }
998         LASSERT(lustre_msg_get_conn_cnt(req->rq_reqmsg) > 0);
999         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
1000         export->exp_abort_active_req = 0;
1001
1002         /* request from liblustre?  Don't evict it for not pinging. */
1003         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
1004                 export->exp_libclient = 1;
1005                 cfs_spin_unlock(&export->exp_lock);
1006
1007                 cfs_spin_lock(&target->obd_dev_lock);
1008                 cfs_list_del_init(&export->exp_obd_chain_timed);
1009                 cfs_spin_unlock(&target->obd_dev_lock);
1010         } else {
1011                 cfs_spin_unlock(&export->exp_lock);
1012         }
1013
1014         if (export->exp_connection != NULL) {
1015                 /* Check to see if connection came from another NID */
1016                 if ((export->exp_connection->c_peer.nid != req->rq_peer.nid) &&
1017                     !cfs_hlist_unhashed(&export->exp_nid_hash))
1018                         cfs_hash_del(export->exp_obd->obd_nid_hash,
1019                                      &export->exp_connection->c_peer.nid,
1020                                      &export->exp_nid_hash);
1021
1022                 ptlrpc_connection_put(export->exp_connection);
1023         }
1024
1025         export->exp_connection = ptlrpc_connection_get(req->rq_peer,
1026                                                        req->rq_self,
1027                                                        &remote_uuid);
1028         if (cfs_hlist_unhashed(&export->exp_nid_hash)) {
1029                 cfs_hash_add(export->exp_obd->obd_nid_hash,
1030                              &export->exp_connection->c_peer.nid,
1031                              &export->exp_nid_hash);
1032         }
1033
1034         cfs_spin_lock(&target->obd_recovery_task_lock);
1035         if (target->obd_recovering && !export->exp_in_recovery) {
1036                 cfs_spin_lock(&export->exp_lock);
1037                 export->exp_in_recovery = 1;
1038                 export->exp_req_replay_needed = 1;
1039                 export->exp_lock_replay_needed = 1;
1040                 cfs_spin_unlock(&export->exp_lock);
1041                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
1042                      && (data->ocd_transno == 0))
1043                         CWARN("Connect with zero transno!\n");
1044
1045                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
1046                      && data->ocd_transno < target->obd_next_recovery_transno &&
1047                      data->ocd_transno > target->obd_last_committed)
1048                         target->obd_next_recovery_transno = data->ocd_transno;
1049                 target->obd_connected_clients++;
1050                 cfs_atomic_inc(&target->obd_req_replay_clients);
1051                 cfs_atomic_inc(&target->obd_lock_replay_clients);
1052                 if (target->obd_connected_clients ==
1053                     target->obd_max_recoverable_clients)
1054                         cfs_waitq_signal(&target->obd_next_transno_waitq);
1055         }
1056         cfs_spin_unlock(&target->obd_recovery_task_lock);
1057
1058         /* Tell the client we're in recovery, when client is involved in it. */
1059         if (target->obd_recovering)
1060                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
1061
1062         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
1063         conn = *tmp;
1064
1065         if (export->exp_imp_reverse != NULL) {
1066                 /* destroyed import can be still referenced in ctxt */
1067                 obd_set_info_async(export, sizeof(KEY_REVIMP_UPD),
1068                                    KEY_REVIMP_UPD, 0, NULL, NULL);
1069
1070                 client_destroy_import(export->exp_imp_reverse);
1071         }
1072
1073         /* for the rest part, we return -ENOTCONN in case of errors
1074          * in order to let client initialize connection again.
1075          */
1076         revimp = export->exp_imp_reverse = class_new_import(target);
1077         if (!revimp) {
1078                 CERROR("fail to alloc new reverse import.\n");
1079                 GOTO(out, rc = -ENOTCONN);
1080         }
1081
1082         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
1083         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
1084         revimp->imp_remote_handle = conn;
1085         revimp->imp_dlm_fake = 1;
1086         revimp->imp_state = LUSTRE_IMP_FULL;
1087
1088         /* unknown versions will be caught in
1089          * ptlrpc_handle_server_req_in->lustre_unpack_msg() */
1090         revimp->imp_msg_magic = req->rq_reqmsg->lm_magic;
1091
1092         if ((export->exp_connect_flags & OBD_CONNECT_AT) &&
1093             (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1))
1094                 revimp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1095         else
1096                 revimp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1097
1098         if ((export->exp_connect_flags & OBD_CONNECT_FULL20) &&
1099             (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1))
1100                 revimp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1101         else
1102                 revimp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1103
1104         rc = sptlrpc_import_sec_adapt(revimp, req->rq_svc_ctx, &req->rq_flvr);
1105         if (rc) {
1106                 CERROR("Failed to get sec for reverse import: %d\n", rc);
1107                 export->exp_imp_reverse = NULL;
1108                 class_destroy_import(revimp);
1109         }
1110
1111         class_import_put(revimp);
1112 out:
1113         if (export) {
1114                 cfs_spin_lock(&export->exp_lock);
1115                 export->exp_connecting = 0;
1116                 cfs_spin_unlock(&export->exp_lock);
1117         }
1118         if (targref)
1119                 class_decref(targref, __FUNCTION__, cfs_current());
1120         if (rc)
1121                 req->rq_status = rc;
1122         RETURN(rc);
1123 }
1124
1125 int target_handle_disconnect(struct ptlrpc_request *req)
1126 {
1127         int rc;
1128         ENTRY;
1129
1130         rc = req_capsule_server_pack(&req->rq_pill);
1131         if (rc)
1132                 RETURN(rc);
1133
1134         /* keep the rq_export around so we can send the reply */
1135         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1136
1137         RETURN(0);
1138 }
1139
1140 void target_destroy_export(struct obd_export *exp)
1141 {
1142         /* exports created from last_rcvd data, and "fake"
1143            exports created by lctl don't have an import */
1144         if (exp->exp_imp_reverse != NULL)
1145                 client_destroy_import(exp->exp_imp_reverse);
1146
1147         LASSERT_ATOMIC_ZERO(&exp->exp_locks_count);
1148         LASSERT_ATOMIC_ZERO(&exp->exp_rpc_count);
1149         LASSERT_ATOMIC_ZERO(&exp->exp_cb_count);
1150         LASSERT_ATOMIC_ZERO(&exp->exp_replay_count);
1151 }
1152
1153 /*
1154  * Recovery functions
1155  */
1156 static void target_request_copy_get(struct ptlrpc_request *req)
1157 {
1158         class_export_rpc_get(req->rq_export);
1159         LASSERT(cfs_list_empty(&req->rq_list));
1160         CFS_INIT_LIST_HEAD(&req->rq_replay_list);
1161
1162         /* increase refcount to keep request in queue */
1163         cfs_atomic_inc(&req->rq_refcount);
1164         /** let export know it has replays to be handled */
1165         cfs_atomic_inc(&req->rq_export->exp_replay_count);
1166 }
1167
1168 static void target_request_copy_put(struct ptlrpc_request *req)
1169 {
1170         LASSERT(cfs_list_empty(&req->rq_replay_list));
1171         LASSERT_ATOMIC_POS(&req->rq_export->exp_replay_count);
1172
1173         cfs_atomic_dec(&req->rq_export->exp_replay_count);
1174         class_export_rpc_put(req->rq_export);
1175         ptlrpc_server_drop_request(req);
1176 }
1177
1178 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1179 {
1180         __u64                  transno = lustre_msg_get_transno(req->rq_reqmsg);
1181         struct obd_export     *exp = req->rq_export;
1182         struct ptlrpc_request *reqiter;
1183         int                    dup = 0;
1184
1185         LASSERT(exp);
1186
1187         cfs_spin_lock(&exp->exp_lock);
1188         cfs_list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1189                                 rq_replay_list) {
1190                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1191                         dup = 1;
1192                         break;
1193                 }
1194         }
1195
1196         if (dup) {
1197                 /* we expect it with RESENT and REPLAY flags */
1198                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1199                      (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1200                         CERROR("invalid flags %x of resent replay\n",
1201                                lustre_msg_get_flags(req->rq_reqmsg));
1202         } else {
1203                 cfs_list_add_tail(&req->rq_replay_list,
1204                                   &exp->exp_req_replay_queue);
1205         }
1206
1207         cfs_spin_unlock(&exp->exp_lock);
1208         return dup;
1209 }
1210
1211 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1212 {
1213         LASSERT(!cfs_list_empty(&req->rq_replay_list));
1214         LASSERT(req->rq_export);
1215
1216         cfs_spin_lock(&req->rq_export->exp_lock);
1217         cfs_list_del_init(&req->rq_replay_list);
1218         cfs_spin_unlock(&req->rq_export->exp_lock);
1219 }
1220
1221 #ifdef __KERNEL__
1222 static void target_finish_recovery(struct obd_device *obd)
1223 {
1224         time_t elapsed_time = max_t(time_t, 1, cfs_time_current_sec() -
1225                                     obd->obd_recovery_start);
1226         ENTRY;
1227
1228         LCONSOLE_INFO("%s: Recovery over after %d:%.02d, of %d clients "
1229                       "%d recovered and %d %s evicted.\n", obd->obd_name,
1230                       (int)elapsed_time / 60, (int)elapsed_time % 60,
1231                       obd->obd_max_recoverable_clients,
1232                       obd->obd_connected_clients, obd->obd_stale_clients,
1233                       obd->obd_stale_clients == 1 ? "was" : "were");
1234
1235         ldlm_reprocess_all_ns(obd->obd_namespace);
1236         cfs_spin_lock(&obd->obd_recovery_task_lock);
1237         if (!cfs_list_empty(&obd->obd_req_replay_queue) ||
1238             !cfs_list_empty(&obd->obd_lock_replay_queue) ||
1239             !cfs_list_empty(&obd->obd_final_req_queue)) {
1240                 CERROR("%s: Recovery queues ( %s%s%s) are not empty\n",
1241                        obd->obd_name,
1242                        cfs_list_empty(&obd->obd_req_replay_queue) ? "" : "req ",
1243                        cfs_list_empty(&obd->obd_lock_replay_queue) ? \
1244                                "" : "lock ",
1245                        cfs_list_empty(&obd->obd_final_req_queue) ? \
1246                                "" : "final ");
1247                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1248                 LBUG();
1249         }
1250         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1251
1252         obd->obd_recovery_end = cfs_time_current_sec();
1253
1254         /* when recovery finished, cleanup orphans on mds and ost */
1255         if (OBT(obd) && OBP(obd, postrecov)) {
1256                 int rc = OBP(obd, postrecov)(obd);
1257                 if (rc < 0)
1258                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1259                                       obd->obd_name, rc);
1260         }
1261         EXIT;
1262 }
1263
1264 static void abort_req_replay_queue(struct obd_device *obd)
1265 {
1266         struct ptlrpc_request *req, *n;
1267         cfs_list_t abort_list;
1268
1269         CFS_INIT_LIST_HEAD(&abort_list);
1270         cfs_spin_lock(&obd->obd_recovery_task_lock);
1271         cfs_list_splice_init(&obd->obd_req_replay_queue, &abort_list);
1272         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1273         cfs_list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1274                 DEBUG_REQ(D_WARNING, req, "aborted:");
1275                 req->rq_status = -ENOTCONN;
1276                 if (ptlrpc_error(req)) {
1277                         DEBUG_REQ(D_ERROR, req,
1278                                   "failed abort_req_reply; skipping");
1279                 }
1280                 target_exp_dequeue_req_replay(req);
1281                 target_request_copy_put(req);
1282         }
1283 }
1284
1285 static void abort_lock_replay_queue(struct obd_device *obd)
1286 {
1287         struct ptlrpc_request *req, *n;
1288         cfs_list_t abort_list;
1289
1290         CFS_INIT_LIST_HEAD(&abort_list);
1291         cfs_spin_lock(&obd->obd_recovery_task_lock);
1292         cfs_list_splice_init(&obd->obd_lock_replay_queue, &abort_list);
1293         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1294         cfs_list_for_each_entry_safe(req, n, &abort_list, rq_list){
1295                 DEBUG_REQ(D_ERROR, req, "aborted:");
1296                 req->rq_status = -ENOTCONN;
1297                 if (ptlrpc_error(req)) {
1298                         DEBUG_REQ(D_ERROR, req,
1299                                   "failed abort_lock_reply; skipping");
1300                 }
1301                 target_request_copy_put(req);
1302         }
1303 }
1304 #endif
1305
1306 /* Called from a cleanup function if the device is being cleaned up
1307    forcefully.  The exports should all have been disconnected already,
1308    the only thing left to do is
1309      - clear the recovery flags
1310      - cancel the timer
1311      - free queued requests and replies, but don't send replies
1312    Because the obd_stopping flag is set, no new requests should be received.
1313
1314 */
1315 void target_cleanup_recovery(struct obd_device *obd)
1316 {
1317         struct ptlrpc_request *req, *n;
1318         cfs_list_t clean_list;
1319         ENTRY;
1320
1321         CFS_INIT_LIST_HEAD(&clean_list);
1322         cfs_spin_lock(&obd->obd_dev_lock);
1323         if (!obd->obd_recovering) {
1324                 cfs_spin_unlock(&obd->obd_dev_lock);
1325                 EXIT;
1326                 return;
1327         }
1328         obd->obd_recovering = obd->obd_abort_recovery = 0;
1329         cfs_spin_unlock(&obd->obd_dev_lock);
1330
1331         cfs_spin_lock(&obd->obd_recovery_task_lock);
1332         target_cancel_recovery_timer(obd);
1333         cfs_list_splice_init(&obd->obd_req_replay_queue, &clean_list);
1334         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1335
1336         cfs_list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1337                 LASSERT(req->rq_reply_state == 0);
1338                 target_exp_dequeue_req_replay(req);
1339                 target_request_copy_put(req);
1340         }
1341
1342         cfs_spin_lock(&obd->obd_recovery_task_lock);
1343         cfs_list_splice_init(&obd->obd_lock_replay_queue, &clean_list);
1344         cfs_list_splice_init(&obd->obd_final_req_queue, &clean_list);
1345         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1346
1347         cfs_list_for_each_entry_safe(req, n, &clean_list, rq_list){
1348                 LASSERT(req->rq_reply_state == 0);
1349                 target_request_copy_put(req);
1350         }
1351
1352         EXIT;
1353 }
1354
1355 /* obd_recovery_task_lock should be held */
1356 void target_cancel_recovery_timer(struct obd_device *obd)
1357 {
1358         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1359         cfs_timer_disarm(&obd->obd_recovery_timer);
1360 }
1361
1362 /* extend = 1 means require at least "duration" seconds left in the timer,
1363    extend = 0 means set the total duration (start_recovery_timer) */
1364 static void reset_recovery_timer(struct obd_device *obd, int duration,
1365                                  int extend)
1366 {
1367         cfs_time_t now = cfs_time_current_sec();
1368         cfs_duration_t left;
1369
1370         cfs_spin_lock(&obd->obd_recovery_task_lock);
1371         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1372                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1373                 return;
1374         }
1375
1376         left = cfs_time_sub(obd->obd_recovery_end, now);
1377
1378         if (extend && (duration > left))
1379                 obd->obd_recovery_timeout += duration - left;
1380         else if (!extend && (duration > obd->obd_recovery_timeout))
1381                 /* Track the client's largest expected replay time */
1382                 obd->obd_recovery_timeout = duration;
1383
1384         /* Hard limit of obd_recovery_time_hard which should not happen */
1385         if (obd->obd_recovery_timeout > obd->obd_recovery_time_hard)
1386                 obd->obd_recovery_timeout = obd->obd_recovery_time_hard;
1387
1388         obd->obd_recovery_end = obd->obd_recovery_start +
1389                                 obd->obd_recovery_timeout;
1390         if (!cfs_timer_is_armed(&obd->obd_recovery_timer) ||
1391             cfs_time_before(now, obd->obd_recovery_end)) {
1392                 left = cfs_time_sub(obd->obd_recovery_end, now);
1393                 cfs_timer_arm(&obd->obd_recovery_timer, cfs_time_shift(left));
1394         }
1395         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1396         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n",
1397                obd->obd_name, (unsigned)left);
1398 }
1399
1400 static void check_and_start_recovery_timer(struct obd_device *obd)
1401 {
1402         cfs_spin_lock(&obd->obd_recovery_task_lock);
1403         if (cfs_timer_is_armed(&obd->obd_recovery_timer)) {
1404                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1405                 return;
1406         }
1407         CDEBUG(D_HA, "%s: starting recovery timer\n", obd->obd_name);
1408         obd->obd_recovery_start = cfs_time_current_sec();
1409         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1410
1411         reset_recovery_timer(obd, obd->obd_recovery_timeout, 0);
1412 }
1413
1414 /* Reset the timer with each new client connection */
1415 /*
1416  * This timer is actually reconnect_timer, which is for making sure
1417  * the total recovery window is at least as big as my reconnect
1418  * attempt timing. So the initial recovery time_out will be set to
1419  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1420  * from client is bigger than this, then the recovery time_out will
1421  * be extended to make sure the client could be reconnected, in the
1422  * process, the timeout from the new client should be ignored.
1423  */
1424
1425 static void
1426 target_start_and_reset_recovery_timer(struct obd_device *obd,
1427                                       struct ptlrpc_request *req,
1428                                       int new_client)
1429 {
1430         int service_time = lustre_msg_get_service_time(req->rq_reqmsg);
1431
1432         if (!new_client && service_time)
1433                 /* Teach server about old server's estimates, as first guess
1434                  * at how long new requests will take. */
1435                 at_measured(&req->rq_rqbd->rqbd_service->srv_at_estimate,
1436                             service_time);
1437
1438         check_and_start_recovery_timer(obd);
1439
1440         /* convert the service time to rpc timeout,
1441          * reuse service_time to limit stack usage */
1442         service_time = at_est2timeout(service_time);
1443
1444         /* We expect other clients to timeout within service_time, then try
1445          * to reconnect, then try the failover server.  The max delay between
1446          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL */
1447         service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
1448                              INITIAL_CONNECT_TIMEOUT);
1449         if (service_time > obd->obd_recovery_timeout && !new_client)
1450                 reset_recovery_timer(obd, service_time, 0);
1451 }
1452
1453 #ifdef __KERNEL__
1454
1455 /** Health checking routines */
1456 static inline int exp_connect_healthy(struct obd_export *exp)
1457 {
1458         return (exp->exp_in_recovery);
1459 }
1460
1461 /** if export done req_replay or has replay in queue */
1462 static inline int exp_req_replay_healthy(struct obd_export *exp)
1463 {
1464         return (!exp->exp_req_replay_needed ||
1465                 cfs_atomic_read(&exp->exp_replay_count) > 0);
1466 }
1467 /** if export done lock_replay or has replay in queue */
1468 static inline int exp_lock_replay_healthy(struct obd_export *exp)
1469 {
1470         return (!exp->exp_lock_replay_needed ||
1471                 cfs_atomic_read(&exp->exp_replay_count) > 0);
1472 }
1473
1474 static inline int exp_vbr_healthy(struct obd_export *exp)
1475 {
1476         return (!exp->exp_vbr_failed);
1477 }
1478
1479 static inline int exp_finished(struct obd_export *exp)
1480 {
1481         return (exp->exp_in_recovery && !exp->exp_lock_replay_needed);
1482 }
1483
1484 /** Checking routines for recovery */
1485 static int check_for_clients(struct obd_device *obd)
1486 {
1487         if (obd->obd_abort_recovery || obd->obd_recovery_expired)
1488                 return 1;
1489         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1490         if (obd->obd_no_conn == 0 &&
1491             obd->obd_connected_clients + obd->obd_stale_clients ==
1492             obd->obd_max_recoverable_clients)
1493                 return 1;
1494         return 0;
1495 }
1496
1497 static int check_for_next_transno(struct obd_device *obd)
1498 {
1499         struct ptlrpc_request *req = NULL;
1500         int wake_up = 0, connected, completed, queue_len;
1501         __u64 next_transno, req_transno;
1502         ENTRY;
1503
1504         cfs_spin_lock(&obd->obd_recovery_task_lock);
1505         if (!cfs_list_empty(&obd->obd_req_replay_queue)) {
1506                 req = cfs_list_entry(obd->obd_req_replay_queue.next,
1507                                      struct ptlrpc_request, rq_list);
1508                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1509         } else {
1510                 req_transno = 0;
1511         }
1512
1513         connected = obd->obd_connected_clients;
1514         completed = connected - cfs_atomic_read(&obd->obd_req_replay_clients);
1515         queue_len = obd->obd_requests_queued_for_recovery;
1516         next_transno = obd->obd_next_recovery_transno;
1517
1518         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1519                "req_transno: "LPU64", next_transno: "LPU64"\n",
1520                obd->obd_max_recoverable_clients, connected, completed,
1521                queue_len, req_transno, next_transno);
1522
1523         if (obd->obd_abort_recovery) {
1524                 CDEBUG(D_HA, "waking for aborted recovery\n");
1525                 wake_up = 1;
1526         } else if (obd->obd_recovery_expired) {
1527                 CDEBUG(D_HA, "waking for expired recovery\n");
1528                 wake_up = 1;
1529         } else if (cfs_atomic_read(&obd->obd_req_replay_clients) == 0) {
1530                 CDEBUG(D_HA, "waking for completed recovery\n");
1531                 wake_up = 1;
1532         } else if (req_transno == next_transno) {
1533                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1534                 wake_up = 1;
1535         } else if (queue_len == cfs_atomic_read(&obd->obd_req_replay_clients)) {
1536                 int d_lvl = D_HA;
1537                 /** handle gaps occured due to lost reply or VBR */
1538                 LASSERTF(req_transno >= next_transno,
1539                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1540                          req_transno, next_transno);
1541                 if (req_transno > obd->obd_last_committed &&
1542                     !obd->obd_version_recov)
1543                         d_lvl = D_ERROR;
1544                 CDEBUG(d_lvl,
1545                        "%s: waking for gap in transno, VBR is %s (skip: "
1546                        LPD64", ql: %d, comp: %d, conn: %d, next: "LPD64
1547                        ", last_committed: "LPD64")\n",
1548                        obd->obd_name, obd->obd_version_recov ? "ON" : "OFF",
1549                        next_transno, queue_len, completed, connected,
1550                        req_transno, obd->obd_last_committed);
1551                 obd->obd_next_recovery_transno = req_transno;
1552                 wake_up = 1;
1553         } else if (OBD_FAIL_CHECK(OBD_FAIL_MDS_RECOVERY_ACCEPTS_GAPS)) {
1554                 CDEBUG(D_HA, "accepting transno gaps is explicitly allowed"
1555                        " by fail_lock, waking up ("LPD64")\n", next_transno);
1556                 obd->obd_next_recovery_transno = req_transno;
1557                 wake_up = 1;
1558         }
1559         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1560         return wake_up;
1561 }
1562
1563 static int check_for_next_lock(struct obd_device *obd)
1564 {
1565         int wake_up = 0;
1566
1567         cfs_spin_lock(&obd->obd_recovery_task_lock);
1568         if (!cfs_list_empty(&obd->obd_lock_replay_queue)) {
1569                 CDEBUG(D_HA, "waking for next lock\n");
1570                 wake_up = 1;
1571         } else if (cfs_atomic_read(&obd->obd_lock_replay_clients) == 0) {
1572                 CDEBUG(D_HA, "waking for completed lock replay\n");
1573                 wake_up = 1;
1574         } else if (obd->obd_abort_recovery) {
1575                 CDEBUG(D_HA, "waking for aborted recovery\n");
1576                 wake_up = 1;
1577         } else if (obd->obd_recovery_expired) {
1578                 CDEBUG(D_HA, "waking for expired recovery\n");
1579                 wake_up = 1;
1580         }
1581         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1582
1583         return wake_up;
1584 }
1585
1586 /**
1587  * wait for recovery events,
1588  * check its status with help of check_routine
1589  * evict dead clients via health_check
1590  */
1591 static int target_recovery_overseer(struct obd_device *obd,
1592                                     int (*check_routine)(struct obd_device *),
1593                                     int (*health_check)(struct obd_export *))
1594 {
1595 repeat:
1596         cfs_wait_event(obd->obd_next_transno_waitq, check_routine(obd));
1597         if (obd->obd_abort_recovery) {
1598                 CWARN("recovery is aborted, evict exports in recovery\n");
1599                 /** evict exports which didn't finish recovery yet */
1600                 class_disconnect_stale_exports(obd, exp_finished);
1601                 return 1;
1602         } else if (obd->obd_recovery_expired) {
1603                 obd->obd_recovery_expired = 0;
1604                 /** If some clients died being recovered, evict them */
1605                 CDEBUG(D_WARNING,
1606                        "recovery is timed out, evict stale exports\n");
1607                 /** evict cexports with no replay in queue, they are stalled */
1608                 class_disconnect_stale_exports(obd, health_check);
1609                 /** continue with VBR */
1610                 cfs_spin_lock(&obd->obd_dev_lock);
1611                 obd->obd_version_recov = 1;
1612                 cfs_spin_unlock(&obd->obd_dev_lock);
1613                 /**
1614                  * reset timer, recovery will proceed with versions now,
1615                  * timeout is set just to handle reconnection delays
1616                  */
1617                 reset_recovery_timer(obd, RECONNECT_DELAY_MAX, 1);
1618                 /** Wait for recovery events again, after evicting bad clients */
1619                 goto repeat;
1620         }
1621         return 0;
1622 }
1623
1624 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1625 {
1626         struct ptlrpc_request *req = NULL;
1627         ENTRY;
1628
1629         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1630                obd->obd_next_recovery_transno);
1631
1632         if (target_recovery_overseer(obd, check_for_next_transno,
1633                                      exp_req_replay_healthy)) {
1634                 abort_req_replay_queue(obd);
1635                 abort_lock_replay_queue(obd);
1636         }
1637
1638         cfs_spin_lock(&obd->obd_recovery_task_lock);
1639         if (!cfs_list_empty(&obd->obd_req_replay_queue)) {
1640                 req = cfs_list_entry(obd->obd_req_replay_queue.next,
1641                                      struct ptlrpc_request, rq_list);
1642                 cfs_list_del_init(&req->rq_list);
1643                 obd->obd_requests_queued_for_recovery--;
1644                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1645         } else {
1646                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1647                 LASSERT(cfs_list_empty(&obd->obd_req_replay_queue));
1648                 LASSERT(cfs_atomic_read(&obd->obd_req_replay_clients) == 0);
1649                 /** evict exports failed VBR */
1650                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1651         }
1652         RETURN(req);
1653 }
1654
1655 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1656 {
1657         struct ptlrpc_request *req = NULL;
1658
1659         CDEBUG(D_HA, "Waiting for lock\n");
1660         if (target_recovery_overseer(obd, check_for_next_lock,
1661                                      exp_lock_replay_healthy))
1662                 abort_lock_replay_queue(obd);
1663
1664         cfs_spin_lock(&obd->obd_recovery_task_lock);
1665         if (!cfs_list_empty(&obd->obd_lock_replay_queue)) {
1666                 req = cfs_list_entry(obd->obd_lock_replay_queue.next,
1667                                      struct ptlrpc_request, rq_list);
1668                 cfs_list_del_init(&req->rq_list);
1669                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1670         } else {
1671                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1672                 LASSERT(cfs_list_empty(&obd->obd_lock_replay_queue));
1673                 LASSERT(cfs_atomic_read(&obd->obd_lock_replay_clients) == 0);
1674                 /** evict exports failed VBR */
1675                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1676         }
1677         return req;
1678 }
1679
1680 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1681 {
1682         struct ptlrpc_request *req = NULL;
1683
1684         cfs_spin_lock(&obd->obd_recovery_task_lock);
1685         if (!cfs_list_empty(&obd->obd_final_req_queue)) {
1686                 req = cfs_list_entry(obd->obd_final_req_queue.next,
1687                                      struct ptlrpc_request, rq_list);
1688                 cfs_list_del_init(&req->rq_list);
1689                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1690                 if (req->rq_export->exp_in_recovery) {
1691                         cfs_spin_lock(&req->rq_export->exp_lock);
1692                         req->rq_export->exp_in_recovery = 0;
1693                         cfs_spin_unlock(&req->rq_export->exp_lock);
1694                 }
1695         } else {
1696                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1697         }
1698         return req;
1699 }
1700
1701 static int handle_recovery_req(struct ptlrpc_thread *thread,
1702                                struct ptlrpc_request *req,
1703                                svc_handler_t handler)
1704 {
1705         int rc;
1706         ENTRY;
1707
1708         /**
1709          * export can be evicted during recovery, no need to handle replays for
1710          * it after that, discard such request silently
1711          */
1712         if (req->rq_export->exp_disconnected)
1713                 GOTO(reqcopy_put, rc = 0);
1714
1715         rc = lu_context_init(&req->rq_recov_session, LCT_SESSION);
1716         if (rc) {
1717                 CERROR("Failure to initialize session: %d\n", rc);
1718                 GOTO(reqcopy_put, rc);
1719         }
1720
1721         req->rq_recov_session.lc_thread = thread;
1722         lu_context_enter(&req->rq_recov_session);
1723         req->rq_svc_thread = thread;
1724         req->rq_svc_thread->t_env->le_ses = &req->rq_recov_session;
1725
1726         /* thread context */
1727         lu_context_enter(&thread->t_env->le_ctx);
1728         (void)handler(req);
1729         lu_context_exit(&thread->t_env->le_ctx);
1730
1731         lu_context_exit(&req->rq_recov_session);
1732         lu_context_fini(&req->rq_recov_session);
1733         /* don't reset timer for final stage */
1734         if (!exp_finished(req->rq_export)) {
1735                 /**
1736                  * Add request timeout to the recovery time so next request from
1737                  * this client may come in recovery time
1738                  */
1739                  reset_recovery_timer(class_exp2obd(req->rq_export),
1740                                       AT_OFF ? obd_timeout :
1741                                       lustre_msg_get_timeout(req->rq_reqmsg), 1);
1742         }
1743 reqcopy_put:
1744         RETURN(rc);
1745 }
1746
1747 static int target_recovery_thread(void *arg)
1748 {
1749         struct lu_target *lut = arg;
1750         struct obd_device *obd = lut->lut_obd;
1751         struct ptlrpc_request *req;
1752         struct target_recovery_data *trd = &obd->obd_recovery_data;
1753         unsigned long delta;
1754         unsigned long flags;
1755         struct lu_env env;
1756         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1757         int rc = 0;
1758         ENTRY;
1759
1760         cfs_daemonize_ctxt("tgt_recov");
1761
1762         SIGNAL_MASK_LOCK(current, flags);
1763         sigfillset(&current->blocked);
1764         RECALC_SIGPENDING;
1765         SIGNAL_MASK_UNLOCK(current, flags);
1766
1767         rc = lu_context_init(&env.le_ctx, LCT_MD_THREAD);
1768         if (rc)
1769                 RETURN(rc);
1770
1771         thread->t_env = &env;
1772         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
1773         env.le_ctx.lc_thread = thread;
1774         thread->t_data = NULL;
1775
1776         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
1777                cfs_curproc_pid());
1778         trd->trd_processing_task = cfs_curproc_pid();
1779
1780         cfs_spin_lock(&obd->obd_dev_lock);
1781         obd->obd_recovering = 1;
1782         cfs_spin_unlock(&obd->obd_dev_lock);
1783         cfs_complete(&trd->trd_starting);
1784
1785         /* first of all, we have to know the first transno to replay */
1786         if (target_recovery_overseer(obd, check_for_clients,
1787                                      exp_connect_healthy)) {
1788                 abort_req_replay_queue(obd);
1789                 abort_lock_replay_queue(obd);
1790         }
1791
1792         /* next stage: replay requests */
1793         delta = jiffies;
1794         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1795                cfs_atomic_read(&obd->obd_req_replay_clients),
1796                obd->obd_next_recovery_transno);
1797         while ((req = target_next_replay_req(obd))) {
1798                 LASSERT(trd->trd_processing_task == cfs_curproc_pid());
1799                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1800                           lustre_msg_get_transno(req->rq_reqmsg),
1801                           libcfs_nid2str(req->rq_peer.nid));
1802                 handle_recovery_req(thread, req,
1803                                     trd->trd_recovery_handler);
1804                 /**
1805                  * bz18031: increase next_recovery_transno before
1806                  * target_request_copy_put() will drop exp_rpc reference
1807                  */
1808                 cfs_spin_lock(&obd->obd_recovery_task_lock);
1809                 obd->obd_next_recovery_transno++;
1810                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
1811                 target_exp_dequeue_req_replay(req);
1812                 target_request_copy_put(req);
1813                 obd->obd_replayed_requests++;
1814         }
1815
1816         /**
1817          * The second stage: replay locks
1818          */
1819         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1820                cfs_atomic_read(&obd->obd_lock_replay_clients));
1821         while ((req = target_next_replay_lock(obd))) {
1822                 LASSERT(trd->trd_processing_task == cfs_curproc_pid());
1823                 DEBUG_REQ(D_HA, req, "processing lock from %s: ",
1824                           libcfs_nid2str(req->rq_peer.nid));
1825                 handle_recovery_req(thread, req,
1826                                     trd->trd_recovery_handler);
1827                 target_request_copy_put(req);
1828                 obd->obd_replayed_locks++;
1829         }
1830
1831         /**
1832          * The third stage: reply on final pings, at this moment all clients
1833          * must have request in final queue
1834          */
1835         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1836         /** Update server last boot epoch */
1837         lut_boot_epoch_update(lut);
1838         /* We drop recoverying flag to forward all new requests
1839          * to regular mds_handle() since now */
1840         cfs_spin_lock(&obd->obd_dev_lock);
1841         obd->obd_recovering = obd->obd_abort_recovery = 0;
1842         cfs_spin_unlock(&obd->obd_dev_lock);
1843         cfs_spin_lock(&obd->obd_recovery_task_lock);
1844         target_cancel_recovery_timer(obd);
1845         cfs_spin_unlock(&obd->obd_recovery_task_lock);
1846         while ((req = target_next_final_ping(obd))) {
1847                 LASSERT(trd->trd_processing_task == cfs_curproc_pid());
1848                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1849                           libcfs_nid2str(req->rq_peer.nid));
1850                 handle_recovery_req(thread, req,
1851                                     trd->trd_recovery_handler);
1852                 target_request_copy_put(req);
1853         }
1854
1855         delta = (jiffies - delta) / CFS_HZ;
1856         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1857               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1858         if (delta > OBD_RECOVERY_TIME_SOFT) {
1859                 CWARN("too long recovery - read logs\n");
1860                 libcfs_debug_dumplog();
1861         }
1862
1863         target_finish_recovery(obd);
1864
1865         lu_context_fini(&env.le_ctx);
1866         trd->trd_processing_task = 0;
1867         cfs_complete(&trd->trd_finishing);
1868         RETURN(rc);
1869 }
1870
1871 static int target_start_recovery_thread(struct lu_target *lut,
1872                                         svc_handler_t handler)
1873 {
1874         struct obd_device *obd = lut->lut_obd;
1875         int rc = 0;
1876         struct target_recovery_data *trd = &obd->obd_recovery_data;
1877
1878         memset(trd, 0, sizeof(*trd));
1879         cfs_init_completion(&trd->trd_starting);
1880         cfs_init_completion(&trd->trd_finishing);
1881         trd->trd_recovery_handler = handler;
1882
1883         if (cfs_create_thread(target_recovery_thread, lut, 0) > 0) {
1884                 cfs_wait_for_completion(&trd->trd_starting);
1885                 LASSERT(obd->obd_recovering != 0);
1886         } else
1887                 rc = -ECHILD;
1888
1889         return rc;
1890 }
1891
1892 void target_stop_recovery_thread(struct obd_device *obd)
1893 {
1894         if (obd->obd_recovery_data.trd_processing_task > 0) {
1895                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1896                 /** recovery can be done but postrecovery is not yet */
1897                 cfs_spin_lock(&obd->obd_dev_lock);
1898                 if (obd->obd_recovering) {
1899                         CERROR("%s: Aborting recovery\n", obd->obd_name);
1900                         obd->obd_abort_recovery = 1;
1901                         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1902                 }
1903                 cfs_spin_unlock(&obd->obd_dev_lock);
1904                 cfs_wait_for_completion(&trd->trd_finishing);
1905         }
1906 }
1907
1908 void target_recovery_fini(struct obd_device *obd)
1909 {
1910         class_disconnect_exports(obd);
1911         target_stop_recovery_thread(obd);
1912         target_cleanup_recovery(obd);
1913 }
1914 EXPORT_SYMBOL(target_recovery_fini);
1915
1916 static void target_recovery_expired(unsigned long castmeharder)
1917 {
1918         struct obd_device *obd = (struct obd_device *)castmeharder;
1919         CDEBUG(D_HA, "%s: recovery timed out; %d clients are still in recovery"
1920                " after %lds (%d clients connected)\n",
1921                obd->obd_name, cfs_atomic_read(&obd->obd_lock_replay_clients),
1922                cfs_time_current_sec()- obd->obd_recovery_start,
1923                obd->obd_connected_clients);
1924
1925         obd->obd_recovery_expired = 1;
1926         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1927 }
1928
1929 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
1930 {
1931         struct obd_device *obd = lut->lut_obd;
1932         if (obd->obd_max_recoverable_clients == 0) {
1933                 /** Update server last boot epoch */
1934                 lut_boot_epoch_update(lut);
1935                 return;
1936         }
1937
1938         CWARN("RECOVERY: service %s, %d recoverable clients, "
1939               "last_transno "LPU64"\n", obd->obd_name,
1940               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1941         LASSERT(obd->obd_stopping == 0);
1942         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1943         obd->obd_recovery_start = 0;
1944         obd->obd_recovery_end = 0;
1945
1946         /* both values can be get from mount data already */
1947         if (obd->obd_recovery_timeout == 0)
1948                 obd->obd_recovery_timeout = OBD_RECOVERY_TIME_SOFT;
1949         if (obd->obd_recovery_time_hard == 0)
1950                 obd->obd_recovery_time_hard = OBD_RECOVERY_TIME_HARD;
1951         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1952         target_start_recovery_thread(lut, handler);
1953 }
1954 EXPORT_SYMBOL(target_recovery_init);
1955
1956 #endif
1957
1958 static int target_process_req_flags(struct obd_device *obd,
1959                                     struct ptlrpc_request *req)
1960 {
1961         struct obd_export *exp = req->rq_export;
1962         LASSERT(exp != NULL);
1963         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1964                 /* client declares he's ready to replay locks */
1965                 cfs_spin_lock(&exp->exp_lock);
1966                 if (exp->exp_req_replay_needed) {
1967                         exp->exp_req_replay_needed = 0;
1968                         cfs_spin_unlock(&exp->exp_lock);
1969
1970                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
1971                         cfs_atomic_dec(&obd->obd_req_replay_clients);
1972                 } else {
1973                         cfs_spin_unlock(&exp->exp_lock);
1974                 }
1975         }
1976         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1977                 /* client declares he's ready to complete recovery
1978                  * so, we put the request on th final queue */
1979                 cfs_spin_lock(&exp->exp_lock);
1980                 if (exp->exp_lock_replay_needed) {
1981                         exp->exp_lock_replay_needed = 0;
1982                         cfs_spin_unlock(&exp->exp_lock);
1983
1984                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
1985                         cfs_atomic_dec(&obd->obd_lock_replay_clients);
1986                 } else {
1987                         cfs_spin_unlock(&exp->exp_lock);
1988                 }
1989         }
1990         return 0;
1991 }
1992
1993 int target_queue_recovery_request(struct ptlrpc_request *req,
1994                                   struct obd_device *obd)
1995 {
1996         cfs_list_t *tmp;
1997         int inserted = 0;
1998         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1999         ENTRY;
2000
2001         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
2002                 /* Processing the queue right now, don't re-add. */
2003                 RETURN(1);
2004         }
2005
2006         target_process_req_flags(obd, req);
2007
2008         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2009                 /* client declares he's ready to complete recovery
2010                  * so, we put the request on th final queue */
2011                 target_request_copy_get(req);
2012                 DEBUG_REQ(D_HA, req, "queue final req");
2013                 cfs_waitq_signal(&obd->obd_next_transno_waitq);
2014                 cfs_spin_lock(&obd->obd_recovery_task_lock);
2015                 if (obd->obd_recovering) {
2016                         cfs_list_add_tail(&req->rq_list,
2017                                           &obd->obd_final_req_queue);
2018                 } else {
2019                         cfs_spin_unlock(&obd->obd_recovery_task_lock);
2020                         target_request_copy_put(req);
2021                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
2022                 }
2023                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
2024                 RETURN(0);
2025         }
2026         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2027                 /* client declares he's ready to replay locks */
2028                 target_request_copy_get(req);
2029                 DEBUG_REQ(D_HA, req, "queue lock replay req");
2030                 cfs_waitq_signal(&obd->obd_next_transno_waitq);
2031                 cfs_spin_lock(&obd->obd_recovery_task_lock);
2032                 LASSERT(obd->obd_recovering);
2033                 /* usually due to recovery abort */
2034                 if (!req->rq_export->exp_in_recovery) {
2035                         cfs_spin_unlock(&obd->obd_recovery_task_lock);
2036                         target_request_copy_put(req);
2037                         RETURN(-ENOTCONN);
2038                 }
2039                 LASSERT(req->rq_export->exp_lock_replay_needed);
2040                 cfs_list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
2041                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
2042                 RETURN(0);
2043         }
2044
2045         /* CAVEAT EMPTOR: The incoming request message has been swabbed
2046          * (i.e. buflens etc are in my own byte order), but type-dependent
2047          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
2048
2049         if (!transno) {
2050                 CFS_INIT_LIST_HEAD(&req->rq_list);
2051                 DEBUG_REQ(D_HA, req, "not queueing");
2052                 RETURN(1);
2053         }
2054
2055         /* If we're processing the queue, we want don't want to queue this
2056          * message.
2057          *
2058          * Also, if this request has a transno less than the one we're waiting
2059          * for, we should process it now.  It could (and currently always will)
2060          * be an open request for a descriptor that was opened some time ago.
2061          *
2062          * Also, a resent, replayed request that has already been
2063          * handled will pass through here and be processed immediately.
2064          */
2065         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying\n",
2066               obd->obd_next_recovery_transno, transno);
2067         cfs_spin_lock(&obd->obd_recovery_task_lock);
2068         if (transno < obd->obd_next_recovery_transno) {
2069                 /* Processing the queue right now, don't re-add. */
2070                 LASSERT(cfs_list_empty(&req->rq_list));
2071                 cfs_spin_unlock(&obd->obd_recovery_task_lock);
2072                 RETURN(1);
2073         }
2074         cfs_spin_unlock(&obd->obd_recovery_task_lock);
2075
2076         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
2077                 RETURN(0);
2078
2079         target_request_copy_get(req);
2080         if (!req->rq_export->exp_in_recovery) {
2081                 target_request_copy_put(req);
2082                 RETURN(-ENOTCONN);
2083         }
2084         LASSERT(req->rq_export->exp_req_replay_needed);
2085
2086         if (target_exp_enqueue_req_replay(req)) {
2087                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
2088                 target_request_copy_put(req);
2089                 RETURN(0);
2090         }
2091
2092         /* XXX O(n^2) */
2093         cfs_spin_lock(&obd->obd_recovery_task_lock);
2094         LASSERT(obd->obd_recovering);
2095         cfs_list_for_each(tmp, &obd->obd_req_replay_queue) {
2096                 struct ptlrpc_request *reqiter =
2097                         cfs_list_entry(tmp, struct ptlrpc_request, rq_list);
2098
2099                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
2100                         cfs_list_add_tail(&req->rq_list, &reqiter->rq_list);
2101                         inserted = 1;
2102                         break;
2103                 }
2104
2105                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
2106                              transno)) {
2107                         DEBUG_REQ(D_ERROR, req, "dropping replay: transno "
2108                                   "has been claimed by another client");
2109                         cfs_spin_unlock(&obd->obd_recovery_task_lock);
2110                         target_exp_dequeue_req_replay(req);
2111                         target_request_copy_put(req);
2112                         RETURN(0);
2113                 }
2114         }
2115
2116         if (!inserted)
2117                 cfs_list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
2118
2119         obd->obd_requests_queued_for_recovery++;
2120         cfs_spin_unlock(&obd->obd_recovery_task_lock);
2121         cfs_waitq_signal(&obd->obd_next_transno_waitq);
2122         RETURN(0);
2123 }
2124
2125 /**
2126  * Packs current SLV and Limit into \a req.
2127  */
2128 int target_pack_pool_reply(struct ptlrpc_request *req)
2129 {
2130         struct obd_device *obd;
2131         ENTRY;
2132
2133         /*
2134          * Check that we still have all structures alive as this may
2135          * be some late rpc in shutdown time.
2136          */
2137         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
2138                      !exp_connect_lru_resize(req->rq_export))) {
2139                 lustre_msg_set_slv(req->rq_repmsg, 0);
2140                 lustre_msg_set_limit(req->rq_repmsg, 0);
2141                 RETURN(0);
2142         }
2143
2144         /*
2145          * OBD is alive here as export is alive, which we checked above.
2146          */
2147         obd = req->rq_export->exp_obd;
2148
2149         cfs_read_lock(&obd->obd_pool_lock);
2150         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
2151         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
2152         cfs_read_unlock(&obd->obd_pool_lock);
2153
2154         RETURN(0);
2155 }
2156
2157 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
2158 {
2159         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
2160                 DEBUG_REQ(D_ERROR, req, "dropping reply");
2161                 return (-ECOMM);
2162         }
2163
2164         if (unlikely(rc)) {
2165                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
2166                 req->rq_status = rc;
2167                 return (ptlrpc_send_error(req, 1));
2168         } else {
2169                 DEBUG_REQ(D_NET, req, "sending reply");
2170         }
2171
2172         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
2173 }
2174
2175 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
2176 {
2177         int                        netrc;
2178         struct ptlrpc_reply_state *rs;
2179         struct obd_device         *obd;
2180         struct obd_export         *exp;
2181         struct ptlrpc_service     *svc;
2182         ENTRY;
2183
2184         if (req->rq_no_reply) {
2185                 EXIT;
2186                 return;
2187         }
2188
2189         svc = req->rq_rqbd->rqbd_service;
2190         rs = req->rq_reply_state;
2191         if (rs == NULL || !rs->rs_difficult) {
2192                 /* no notifiers */
2193                 target_send_reply_msg (req, rc, fail_id);
2194                 EXIT;
2195                 return;
2196         }
2197
2198         /* must be an export if locks saved */
2199         LASSERT (req->rq_export != NULL);
2200         /* req/reply consistent */
2201         LASSERT (rs->rs_service == svc);
2202
2203         /* "fresh" reply */
2204         LASSERT (!rs->rs_scheduled);
2205         LASSERT (!rs->rs_scheduled_ever);
2206         LASSERT (!rs->rs_handled);
2207         LASSERT (!rs->rs_on_net);
2208         LASSERT (rs->rs_export == NULL);
2209         LASSERT (cfs_list_empty(&rs->rs_obd_list));
2210         LASSERT (cfs_list_empty(&rs->rs_exp_list));
2211
2212         exp = class_export_get (req->rq_export);
2213         obd = exp->exp_obd;
2214
2215         /* disable reply scheduling while I'm setting up */
2216         rs->rs_scheduled = 1;
2217         rs->rs_on_net    = 1;
2218         rs->rs_xid       = req->rq_xid;
2219         rs->rs_transno   = req->rq_transno;
2220         rs->rs_export    = exp;
2221         rs->rs_opc       = lustre_msg_get_opc(rs->rs_msg);
2222
2223         cfs_spin_lock(&exp->exp_uncommitted_replies_lock);
2224         CDEBUG(D_NET, "rs transno = "LPU64", last committed = "LPU64"\n",
2225                rs->rs_transno, exp->exp_last_committed);
2226         if (rs->rs_transno > exp->exp_last_committed) {
2227                 /* not committed already */
2228                 cfs_list_add_tail(&rs->rs_obd_list,
2229                                   &exp->exp_uncommitted_replies);
2230         }
2231         cfs_spin_unlock (&exp->exp_uncommitted_replies_lock);
2232
2233         cfs_spin_lock(&exp->exp_lock);
2234         cfs_list_add_tail(&rs->rs_exp_list, &exp->exp_outstanding_replies);
2235         cfs_spin_unlock(&exp->exp_lock);
2236
2237         netrc = target_send_reply_msg (req, rc, fail_id);
2238
2239         cfs_spin_lock(&svc->srv_rs_lock);
2240
2241         cfs_atomic_inc(&svc->srv_n_difficult_replies);
2242
2243         if (netrc != 0) {
2244                 /* error sending: reply is off the net.  Also we need +1
2245                  * reply ref until ptlrpc_handle_rs() is done
2246                  * with the reply state (if the send was successful, there
2247                  * would have been +1 ref for the net, which
2248                  * reply_out_callback leaves alone) */
2249                 rs->rs_on_net = 0;
2250                 ptlrpc_rs_addref(rs);
2251         }
2252
2253         cfs_spin_lock(&rs->rs_lock);
2254         if (rs->rs_transno <= exp->exp_last_committed ||
2255             (!rs->rs_on_net && !rs->rs_no_ack) ||
2256              cfs_list_empty(&rs->rs_exp_list) ||     /* completed already */
2257              cfs_list_empty(&rs->rs_obd_list)) {
2258                 CDEBUG(D_HA, "Schedule reply immediately\n");
2259                 ptlrpc_dispatch_difficult_reply(rs);
2260         } else {
2261                 cfs_list_add (&rs->rs_list, &svc->srv_active_replies);
2262                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
2263         }
2264         cfs_spin_unlock(&rs->rs_lock);
2265         cfs_spin_unlock(&svc->srv_rs_lock);
2266         EXIT;
2267 }
2268
2269 int target_handle_ping(struct ptlrpc_request *req)
2270 {
2271         obd_ping(req->rq_export);
2272         return req_capsule_server_pack(&req->rq_pill);
2273 }
2274
2275 void target_committed_to_req(struct ptlrpc_request *req)
2276 {
2277         struct obd_export *exp = req->rq_export;
2278
2279         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
2280                 lustre_msg_set_last_committed(req->rq_repmsg,
2281                                               exp->exp_last_committed);
2282         else
2283                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
2284                           "%d)", exp->exp_obd->obd_no_transno,
2285                           req->rq_repmsg == NULL);
2286
2287         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
2288                exp->exp_last_committed, req->rq_transno, req->rq_xid);
2289 }
2290 EXPORT_SYMBOL(target_committed_to_req);
2291
2292 int target_handle_qc_callback(struct ptlrpc_request *req)
2293 {
2294         struct obd_quotactl *oqctl;
2295         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2296
2297         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2298         if (oqctl == NULL) {
2299                 CERROR("Can't unpack obd_quotactl\n");
2300                 RETURN(-EPROTO);
2301         }
2302
2303         cli->cl_qchk_stat = oqctl->qc_stat;
2304
2305         return 0;
2306 }
2307
2308 #ifdef HAVE_QUOTA_SUPPORT
2309 int target_handle_dqacq_callback(struct ptlrpc_request *req)
2310 {
2311 #ifdef __KERNEL__
2312         struct obd_device *obd = req->rq_export->exp_obd;
2313         struct obd_device *master_obd = NULL, *lov_obd = NULL;
2314         struct obd_device_target *obt;
2315         struct lustre_quota_ctxt *qctxt;
2316         struct qunit_data *qdata = NULL;
2317         int rc = 0;
2318         ENTRY;
2319
2320         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_DROP_QUOTA_REQ))
2321                 RETURN(rc);
2322
2323         rc = req_capsule_server_pack(&req->rq_pill);
2324         if (rc) {
2325                 CERROR("packing reply failed!: rc = %d\n", rc);
2326                 RETURN(rc);
2327         }
2328
2329         LASSERT(req->rq_export);
2330
2331         qdata = quota_get_qdata(req, QUOTA_REQUEST, QUOTA_EXPORT);
2332         if (IS_ERR(qdata)) {
2333                 rc = PTR_ERR(qdata);
2334                 CDEBUG(D_ERROR, "Can't unpack qunit_data(rc: %d)\n", rc);
2335                 req->rq_status = rc;
2336                 GOTO(out, rc);
2337         }
2338
2339         /* we use the observer */
2340         if (obd_pin_observer(obd, &lov_obd) ||
2341             obd_pin_observer(lov_obd, &master_obd)) {
2342                 CERROR("Can't find the observer, it is recovering\n");
2343                 req->rq_status = -EAGAIN;
2344                 GOTO(out, rc);
2345         }
2346
2347         obt = &master_obd->u.obt;
2348         qctxt = &obt->obt_qctxt;
2349
2350         if (!qctxt->lqc_setup || !qctxt->lqc_valid) {
2351                 /* quota_type has not been processed yet, return EAGAIN
2352                  * until we know whether or not quotas are supposed to
2353                  * be enabled */
2354                 CDEBUG(D_QUOTA, "quota_type not processed yet, return "
2355                        "-EAGAIN\n");
2356                 req->rq_status = -EAGAIN;
2357                 GOTO(out, rc);
2358         }
2359
2360         cfs_down_read(&obt->obt_rwsem);
2361         if (qctxt->lqc_lqs_hash == NULL) {
2362                 cfs_up_read(&obt->obt_rwsem);
2363                 /* quota_type has not been processed yet, return EAGAIN
2364                  * until we know whether or not quotas are supposed to
2365                  * be enabled */
2366                 CDEBUG(D_QUOTA, "quota_ctxt is not ready yet, return "
2367                        "-EAGAIN\n");
2368                 req->rq_status = -EAGAIN;
2369                 GOTO(out, rc);
2370         }
2371
2372         LASSERT(qctxt->lqc_handler);
2373         rc = qctxt->lqc_handler(master_obd, qdata,
2374                                 lustre_msg_get_opc(req->rq_reqmsg));
2375         cfs_up_read(&obt->obt_rwsem);
2376         if (rc && rc != -EDQUOT)
2377                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2378                        "dqacq/dqrel failed! (rc:%d)\n", rc);
2379         req->rq_status = rc;
2380
2381         rc = quota_copy_qdata(req, qdata, QUOTA_REPLY, QUOTA_EXPORT);
2382         if (rc < 0) {
2383                 CERROR("Can't pack qunit_data(rc: %d)\n", rc);
2384                 GOTO(out, rc);
2385         }
2386
2387         /* Block the quota req. b=14840 */
2388         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_BLOCK_QUOTA_REQ, obd_timeout);
2389         EXIT;
2390
2391 out:
2392         if (master_obd)
2393                 obd_unpin_observer(lov_obd);
2394         if (lov_obd)
2395                 obd_unpin_observer(obd);
2396
2397         rc = ptlrpc_reply(req);
2398         return rc;
2399 #else
2400         return 0;
2401 #endif /* !__KERNEL__ */
2402 }
2403 #endif /* HAVE_QUOTA_SUPPORT */
2404
2405 ldlm_mode_t lck_compat_array[] = {
2406         [LCK_EX] LCK_COMPAT_EX,
2407         [LCK_PW] LCK_COMPAT_PW,
2408         [LCK_PR] LCK_COMPAT_PR,
2409         [LCK_CW] LCK_COMPAT_CW,
2410         [LCK_CR] LCK_COMPAT_CR,
2411         [LCK_NL] LCK_COMPAT_NL,
2412         [LCK_GROUP] LCK_COMPAT_GROUP,
2413         [LCK_COS] LCK_COMPAT_COS,
2414 };
2415
2416 /**
2417  * Rather arbitrary mapping from LDLM error codes to errno values. This should
2418  * not escape to the user level.
2419  */
2420 int ldlm_error2errno(ldlm_error_t error)
2421 {
2422         int result;
2423
2424         switch (error) {
2425         case ELDLM_OK:
2426                 result = 0;
2427                 break;
2428         case ELDLM_LOCK_CHANGED:
2429                 result = -ESTALE;
2430                 break;
2431         case ELDLM_LOCK_ABORTED:
2432                 result = -ENAVAIL;
2433                 break;
2434         case ELDLM_LOCK_REPLACED:
2435                 result = -ESRCH;
2436                 break;
2437         case ELDLM_NO_LOCK_DATA:
2438                 result = -ENOENT;
2439                 break;
2440         case ELDLM_NAMESPACE_EXISTS:
2441                 result = -EEXIST;
2442                 break;
2443         case ELDLM_BAD_NAMESPACE:
2444                 result = -EBADF;
2445                 break;
2446         default:
2447                 if (((int)error) < 0)  /* cast to signed type */
2448                         result = error; /* as ldlm_error_t can be unsigned */
2449                 else {
2450                         CERROR("Invalid DLM result code: %d\n", error);
2451                         result = -EPROTO;
2452                 }
2453         }
2454         return result;
2455 }
2456 EXPORT_SYMBOL(ldlm_error2errno);
2457
2458 /**
2459  * Dual to ldlm_error2errno(): maps errno values back to ldlm_error_t.
2460  */
2461 ldlm_error_t ldlm_errno2error(int err_no)
2462 {
2463         int error;
2464
2465         switch (err_no) {
2466         case 0:
2467                 error = ELDLM_OK;
2468                 break;
2469         case -ESTALE:
2470                 error = ELDLM_LOCK_CHANGED;
2471                 break;
2472         case -ENAVAIL:
2473                 error = ELDLM_LOCK_ABORTED;
2474                 break;
2475         case -ESRCH:
2476                 error = ELDLM_LOCK_REPLACED;
2477                 break;
2478         case -ENOENT:
2479                 error = ELDLM_NO_LOCK_DATA;
2480                 break;
2481         case -EEXIST:
2482                 error = ELDLM_NAMESPACE_EXISTS;
2483                 break;
2484         case -EBADF:
2485                 error = ELDLM_BAD_NAMESPACE;
2486                 break;
2487         default:
2488                 error = err_no;
2489         }
2490         return error;
2491 }
2492 EXPORT_SYMBOL(ldlm_errno2error);
2493
2494 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2495 void ldlm_dump_export_locks(struct obd_export *exp)
2496 {
2497         cfs_spin_lock(&exp->exp_locks_list_guard);
2498         if (!cfs_list_empty(&exp->exp_locks_list)) {
2499             struct ldlm_lock *lock;
2500
2501             CERROR("dumping locks for export %p,"
2502                    "ignore if the unmount doesn't hang\n", exp);
2503             cfs_list_for_each_entry(lock, &exp->exp_locks_list, l_exp_refs_link)
2504                 ldlm_lock_dump(D_ERROR, lock, 0);
2505         }
2506         cfs_spin_unlock(&exp->exp_locks_list_guard);
2507 }
2508 #endif
2509
2510 static int target_bulk_timeout(void *data)
2511 {
2512         ENTRY;
2513         /* We don't fail the connection here, because having the export
2514          * killed makes the (vital) call to commitrw very sad.
2515          */
2516         RETURN(1);
2517 }
2518
2519 static inline char *bulk2type(struct ptlrpc_bulk_desc *desc)
2520 {
2521         return desc->bd_type == BULK_GET_SINK ? "GET" : "PUT";
2522 }
2523
2524 int target_bulk_io(struct obd_export *exp, struct ptlrpc_bulk_desc *desc,
2525                    struct l_wait_info *lwi)
2526 {
2527         struct ptlrpc_request *req = desc->bd_req;
2528         int rc = 0;
2529         ENTRY;
2530
2531         /* Check if there is eviction in progress, and if so, wait for
2532          * it to finish */
2533         if (unlikely(cfs_atomic_read(&exp->exp_obd->obd_evict_inprogress))) {
2534                 *lwi = LWI_INTR(NULL, NULL);
2535                 rc = l_wait_event(exp->exp_obd->obd_evict_inprogress_waitq,
2536                                   !cfs_atomic_read(&exp->exp_obd->
2537                                                    obd_evict_inprogress),
2538                                   lwi);
2539         }
2540
2541         /* Check if client was evicted or tried to reconnect already */
2542         if (exp->exp_failed || exp->exp_abort_active_req) {
2543                 rc = -ENOTCONN;
2544         } else {
2545                 if (desc->bd_type == BULK_PUT_SINK)
2546                         rc = sptlrpc_svc_wrap_bulk(req, desc);
2547                 if (rc == 0)
2548                         rc = ptlrpc_start_bulk_transfer(desc);
2549         }
2550
2551         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
2552                 ptlrpc_abort_bulk(desc);
2553         } else if (rc == 0) {
2554                 time_t start = cfs_time_current_sec();
2555                 do {
2556                         long timeoutl = req->rq_deadline - cfs_time_current_sec();
2557                         cfs_duration_t timeout = timeoutl <= 0 ?
2558                                 CFS_TICK : cfs_time_seconds(timeoutl);
2559                         *lwi = LWI_TIMEOUT_INTERVAL(timeout,
2560                                                     cfs_time_seconds(1),
2561                                                    target_bulk_timeout,
2562                                                    desc);
2563                         rc = l_wait_event(desc->bd_waitq,
2564                                           !ptlrpc_server_bulk_active(desc) ||
2565                                           exp->exp_failed ||
2566                                           exp->exp_abort_active_req,
2567                                           lwi);
2568                         LASSERT(rc == 0 || rc == -ETIMEDOUT);
2569                         /* Wait again if we changed deadline */
2570                 } while ((rc == -ETIMEDOUT) &&
2571                          (req->rq_deadline > cfs_time_current_sec()));
2572
2573                 if (rc == -ETIMEDOUT) {
2574                         DEBUG_REQ(D_ERROR, req,
2575                                   "timeout on bulk %s after %ld%+lds",
2576                                   bulk2type(desc),
2577                                   req->rq_deadline - start,
2578                                   cfs_time_current_sec() -
2579                                   req->rq_deadline);
2580                         ptlrpc_abort_bulk(desc);
2581                 } else if (exp->exp_failed) {
2582                         DEBUG_REQ(D_ERROR, req, "Eviction on bulk %s",
2583                                   bulk2type(desc));
2584                         rc = -ENOTCONN;
2585                         ptlrpc_abort_bulk(desc);
2586                 } else if (exp->exp_abort_active_req) {
2587                         DEBUG_REQ(D_ERROR, req, "Reconnect on bulk %s",
2588                                   bulk2type(desc));
2589                         /* we don't reply anyway */
2590                         rc = -ETIMEDOUT;
2591                         ptlrpc_abort_bulk(desc);
2592                 } else if (!desc->bd_success ||
2593                            desc->bd_nob_transferred != desc->bd_nob) {
2594                         DEBUG_REQ(D_ERROR, req, "%s bulk %s %d(%d)",
2595                                   desc->bd_success ?
2596                                   "truncated" : "network error on",
2597                                   bulk2type(desc),
2598                                   desc->bd_nob_transferred,
2599                                   desc->bd_nob);
2600                         /* XXX should this be a different errno? */
2601                         rc = -ETIMEDOUT;
2602                 } else if (desc->bd_type == BULK_GET_SINK) {
2603                         rc = sptlrpc_svc_unwrap_bulk(req, desc);
2604                 }
2605         } else {
2606                 DEBUG_REQ(D_ERROR, req, "bulk %s failed: rc %d",
2607                           bulk2type(desc), rc);
2608         }
2609
2610         RETURN(rc);
2611 }
2612 EXPORT_SYMBOL(target_bulk_io);