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