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