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