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