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