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