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