Whamcloud - gitweb
b=19854
[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  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #ifndef EXPORT_SYMTAB
38 # define EXPORT_SYMTAB
39 #endif
40 #define DEBUG_SUBSYSTEM S_LDLM
41
42 #ifdef __KERNEL__
43 # include <libcfs/libcfs.h>
44 #else
45 # include <liblustre.h>
46 #endif
47 #include <obd.h>
48 #include <lustre_mds.h>
49 #include <lustre_dlm.h>
50 #include <lustre_net.h>
51 #include "ldlm_internal.h"
52
53 /* @priority: if non-zero, move the selected to the list head
54  * @create: if zero, only search in existed connections
55  */
56 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
57                            int priority, int create)
58 {
59         struct ptlrpc_connection *ptlrpc_conn;
60         struct obd_import_conn *imp_conn = NULL, *item;
61         int rc = 0;
62         ENTRY;
63
64         if (!create && !priority) {
65                 CDEBUG(D_HA, "Nothing to do\n");
66                 RETURN(-EINVAL);
67         }
68
69         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
70         if (!ptlrpc_conn) {
71                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
72                 RETURN (-ENOENT);
73         }
74
75         if (create) {
76                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
77                 if (!imp_conn) {
78                         GOTO(out_put, rc = -ENOMEM);
79                 }
80         }
81
82         spin_lock(&imp->imp_lock);
83         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
84                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
85                         if (priority) {
86                                 list_del(&item->oic_item);
87                                 list_add(&item->oic_item, &imp->imp_conn_list);
88                                 item->oic_last_attempt = 0;
89                         }
90                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
91                                imp, imp->imp_obd->obd_name, uuid->uuid,
92                                (priority ? ", moved to head" : ""));
93                         spin_unlock(&imp->imp_lock);
94                         GOTO(out_free, rc = 0);
95                 }
96         }
97         /* not found */
98         if (create) {
99                 imp_conn->oic_conn = ptlrpc_conn;
100                 imp_conn->oic_uuid = *uuid;
101                 imp_conn->oic_last_attempt = 0;
102                 if (priority)
103                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
104                 else
105                         list_add_tail(&imp_conn->oic_item, &imp->imp_conn_list);
106                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
107                        imp, imp->imp_obd->obd_name, uuid->uuid,
108                        (priority ? "head" : "tail"));
109         } else {
110                 spin_unlock(&imp->imp_lock);
111                 GOTO(out_free, rc = -ENOENT);
112
113         }
114
115         spin_unlock(&imp->imp_lock);
116         RETURN(0);
117 out_free:
118         if (imp_conn)
119                 OBD_FREE(imp_conn, sizeof(*imp_conn));
120 out_put:
121         ptlrpc_connection_put(ptlrpc_conn);
122         RETURN(rc);
123 }
124
125 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
126 {
127         return import_set_conn(imp, uuid, 1, 0);
128 }
129
130 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
131                            int priority)
132 {
133         return import_set_conn(imp, uuid, priority, 1);
134 }
135
136 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
137 {
138         struct obd_import_conn *imp_conn;
139         struct obd_export *dlmexp;
140         int rc = -ENOENT;
141         ENTRY;
142
143         spin_lock(&imp->imp_lock);
144         if (list_empty(&imp->imp_conn_list)) {
145                 LASSERT(!imp->imp_connection);
146                 GOTO(out, rc);
147         }
148
149         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
150                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
151                         continue;
152                 LASSERT(imp_conn->oic_conn);
153
154                 /* is current conn? */
155                 if (imp_conn == imp->imp_conn_current) {
156                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
157
158                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
159                             imp->imp_state != LUSTRE_IMP_DISCON) {
160                                 CERROR("can't remove current connection\n");
161                                 GOTO(out, rc = -EBUSY);
162                         }
163
164                         ptlrpc_connection_put(imp->imp_connection);
165                         imp->imp_connection = NULL;
166
167                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
168                         if (dlmexp && dlmexp->exp_connection) {
169                                 LASSERT(dlmexp->exp_connection ==
170                                         imp_conn->oic_conn);
171                                 ptlrpc_connection_put(dlmexp->exp_connection);
172                                 dlmexp->exp_connection = NULL;
173                         }
174                 }
175
176                 list_del(&imp_conn->oic_item);
177                 ptlrpc_connection_put(imp_conn->oic_conn);
178                 OBD_FREE(imp_conn, sizeof(*imp_conn));
179                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
180                        imp, imp->imp_obd->obd_name, uuid->uuid);
181                 rc = 0;
182                 break;
183         }
184 out:
185         spin_unlock(&imp->imp_lock);
186         if (rc == -ENOENT)
187                 CERROR("connection %s not found\n", uuid->uuid);
188         RETURN(rc);
189 }
190
191 /* configure an RPC client OBD device
192  *
193  * lcfg parameters:
194  * 1 - client UUID
195  * 2 - server UUID
196  * 3 - inactive-on-startup
197  */
198 int client_obd_setup(struct obd_device *obddev, obd_count len, void *buf)
199 {
200         struct lustre_cfg* lcfg = buf;
201         struct client_obd *cli = &obddev->u.cli;
202         struct obd_import *imp;
203         struct obd_uuid server_uuid;
204         int rq_portal, rp_portal, connect_op;
205         char *name = obddev->obd_type->typ_name;
206         int rc;
207         ENTRY;
208
209         /* In a more perfect world, we would hang a ptlrpc_client off of
210          * obd_type and just use the values from there. */
211         if (!strcmp(name, LUSTRE_OSC_NAME)) {
212                 rq_portal = OST_REQUEST_PORTAL;
213                 rp_portal = OSC_REPLY_PORTAL;
214                 connect_op = OST_CONNECT;
215         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
216                 rq_portal = MDS_REQUEST_PORTAL;
217                 rp_portal = MDC_REPLY_PORTAL;
218                 connect_op = MDS_CONNECT;
219         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
220                 rq_portal = MGS_REQUEST_PORTAL;
221                 rp_portal = MGC_REPLY_PORTAL;
222                 connect_op = MGS_CONNECT;
223         } else {
224                 CERROR("unknown client OBD type \"%s\", can't setup\n",
225                        name);
226                 RETURN(-EINVAL);
227         }
228
229         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
230                 CERROR("requires a TARGET UUID\n");
231                 RETURN(-EINVAL);
232         }
233
234         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
235                 CERROR("client UUID must be less than 38 characters\n");
236                 RETURN(-EINVAL);
237         }
238
239         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
240                 CERROR("setup requires a SERVER UUID\n");
241                 RETURN(-EINVAL);
242         }
243
244         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
245                 CERROR("target UUID must be less than 38 characters\n");
246                 RETURN(-EINVAL);
247         }
248
249         init_rwsem(&cli->cl_sem);
250         sema_init(&cli->cl_mgc_sem, 1);
251         cli->cl_conn_count = 0;
252         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
253                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
254                      sizeof(server_uuid)));
255
256         cli->cl_dirty = 0;
257         cli->cl_avail_grant = 0;
258         /* FIXME: should limit this for the sum of all cl_dirty_max */
259         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
260         if (cli->cl_dirty_max >> CFS_PAGE_SHIFT > num_physpages / 8)
261                 cli->cl_dirty_max = num_physpages << (CFS_PAGE_SHIFT - 3);
262         CFS_INIT_LIST_HEAD(&cli->cl_cache_waiters);
263         CFS_INIT_LIST_HEAD(&cli->cl_loi_ready_list);
264         CFS_INIT_LIST_HEAD(&cli->cl_loi_hp_ready_list);
265         CFS_INIT_LIST_HEAD(&cli->cl_loi_write_list);
266         CFS_INIT_LIST_HEAD(&cli->cl_loi_read_list);
267         client_obd_list_lock_init(&cli->cl_loi_list_lock);
268         cli->cl_r_in_flight = 0;
269         cli->cl_w_in_flight = 0;
270         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
271         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
272         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
273         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
274         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
275         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
276         cfs_waitq_init(&cli->cl_destroy_waitq);
277         atomic_set(&cli->cl_destroy_in_flight, 0);
278 #ifdef ENABLE_CHECKSUM
279         /* Turn on checksumming by default. */
280         cli->cl_checksum = 1;
281         /*
282          * The supported checksum types will be worked out at connect time
283          * Set cl_chksum* to CRC32 for now to avoid returning screwed info
284          * through procfs.
285          */
286         cli->cl_cksum_type = cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
287 #endif
288         atomic_set(&cli->cl_resends, OSC_DEFAULT_RESENDS);
289         atomic_set(&cli->cl_quota_resends, CLIENT_QUOTA_DEFAULT_RESENDS);
290
291         /* This value may be changed at connect time in
292            ptlrpc_connect_interpret. */
293         cli->cl_max_pages_per_rpc = min((int)PTLRPC_MAX_BRW_PAGES,
294                                         (int)(1024 * 1024 >> CFS_PAGE_SHIFT));
295
296         if (!strcmp(name, LUSTRE_MDC_NAME)) {
297                 cli->cl_max_rpcs_in_flight = MDC_MAX_RIF_DEFAULT;
298         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 128 /* MB */) {
299                 cli->cl_max_rpcs_in_flight = 2;
300         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 256 /* MB */) {
301                 cli->cl_max_rpcs_in_flight = 3;
302         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 512 /* MB */) {
303                 cli->cl_max_rpcs_in_flight = 4;
304         } else {
305                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
306         }
307         rc = ldlm_get_ref();
308         if (rc) {
309                 CERROR("ldlm_get_ref failed: %d\n", rc);
310                 GOTO(err, rc);
311         }
312
313         ptlrpc_init_client(rq_portal, rp_portal, name,
314                            &obddev->obd_ldlm_client);
315
316         imp = class_new_import(obddev);
317         if (imp == NULL)
318                 GOTO(err_ldlm, rc = -ENOENT);
319         imp->imp_client = &obddev->obd_ldlm_client;
320         imp->imp_connect_op = connect_op;
321         imp->imp_initial_recov = 1;
322         imp->imp_initial_recov_bk = 0;
323         CFS_INIT_LIST_HEAD(&imp->imp_pinger_chain);
324         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
325                LUSTRE_CFG_BUFLEN(lcfg, 1));
326         class_import_put(imp);
327
328         rc = client_import_add_conn(imp, &server_uuid, 1);
329         if (rc) {
330                 CERROR("can't add initial connection\n");
331                 GOTO(err_import, rc);
332         }
333
334         cli->cl_import = imp;
335         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
336         cli->cl_max_mds_easize = sizeof(struct lov_mds_md_v3);
337         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
338
339         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
340                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
341                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
342                                name, obddev->obd_name,
343                                cli->cl_target_uuid.uuid);
344                         spin_lock(&imp->imp_lock);
345                         imp->imp_deactive = 1;
346                         spin_unlock(&imp->imp_lock);
347                 }
348         }
349
350         obddev->obd_namespace = ldlm_namespace_new(obddev, obddev->obd_name,
351                                                    LDLM_NAMESPACE_CLIENT,
352                                                    LDLM_NAMESPACE_GREEDY);
353         if (obddev->obd_namespace == NULL) {
354                 CERROR("Unable to create client namespace - %s\n",
355                        obddev->obd_name);
356                 GOTO(err_import, rc = -ENOMEM);
357         }
358
359         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
360
361         RETURN(rc);
362
363 err_import:
364         class_destroy_import(imp);
365 err_ldlm:
366         ldlm_put_ref();
367 err:
368         RETURN(rc);
369
370 }
371
372 int client_obd_cleanup(struct obd_device *obddev)
373 {
374         ENTRY;
375
376         ldlm_namespace_free_post(obddev->obd_namespace);
377         obddev->obd_namespace = NULL;
378
379         ldlm_put_ref();
380         RETURN(0);
381 }
382
383 /* ->o_connect() method for client side (OSC and MDC and MGC) */
384 int client_connect_import(struct lustre_handle *dlm_handle,
385                           struct obd_device *obd, struct obd_uuid *cluuid,
386                           struct obd_connect_data *data, void *localdata)
387 {
388         struct client_obd *cli = &obd->u.cli;
389         struct obd_import *imp = cli->cl_import;
390         struct obd_export **exp = localdata;
391         struct obd_connect_data *ocd;
392         int rc;
393         ENTRY;
394
395         down_write(&cli->cl_sem);
396         CDEBUG(D_INFO, "connect %s - %d\n", obd->obd_name,
397                cli->cl_conn_count);
398
399         if (cli->cl_conn_count > 0)
400                 GOTO(out_sem, rc = -EALREADY);
401
402         rc = class_connect(dlm_handle, obd, cluuid);
403         if (rc)
404                 GOTO(out_sem, rc);
405
406         cli->cl_conn_count++;
407         *exp = class_conn2export(dlm_handle);
408
409         LASSERT(obd->obd_namespace);
410
411         imp->imp_dlm_handle = *dlm_handle;
412         rc = ptlrpc_init_import(imp);
413         if (rc != 0)
414                 GOTO(out_ldlm, rc);
415
416         ocd = &imp->imp_connect_data;
417         if (data) {
418                 *ocd = *data;
419                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
420         }
421
422         rc = ptlrpc_connect_import(imp, NULL);
423         if (rc != 0) {
424                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
425                 GOTO(out_ldlm, rc);
426         }
427         LASSERT((*exp)->exp_connection);
428
429         if (data) {
430                 LASSERT((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
431                         ocd->ocd_connect_flags);
432                 data->ocd_connect_flags = ocd->ocd_connect_flags;
433         }
434
435         ptlrpc_pinger_add_import(imp);
436         EXIT;
437
438         if (rc) {
439 out_ldlm:
440                 cli->cl_conn_count--;
441                 class_disconnect(*exp);
442                 *exp = NULL;
443         }
444 out_sem:
445         up_write(&cli->cl_sem);
446         return rc;
447 }
448
449 int client_disconnect_export(struct obd_export *exp)
450 {
451         struct obd_device *obd = class_exp2obd(exp);
452         struct client_obd *cli;
453         struct obd_import *imp;
454         int rc = 0, err;
455         ENTRY;
456
457         if (!obd) {
458                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
459                        exp, exp ? exp->exp_handle.h_cookie : -1);
460                 RETURN(-EINVAL);
461         }
462
463         cli = &obd->u.cli;
464         imp = cli->cl_import;
465
466         down_write(&cli->cl_sem);
467         CDEBUG(D_INFO, "disconnect %s - %d\n", obd->obd_name,
468                cli->cl_conn_count);
469
470         if (!cli->cl_conn_count) {
471                 CERROR("disconnecting disconnected device (%s)\n",
472                        obd->obd_name);
473                 GOTO(out_disconnect, rc = -EINVAL);
474         }
475
476         cli->cl_conn_count--;
477         if (cli->cl_conn_count)
478                 GOTO(out_disconnect, rc = 0);
479
480         /* Mark import deactivated now, so we don't try to reconnect if any
481          * of the cleanup RPCs fails (e.g. ldlm cancel, etc).  We don't
482          * fully deactivate the import, or that would drop all requests. */
483         spin_lock(&imp->imp_lock);
484         imp->imp_deactive = 1;
485         spin_unlock(&imp->imp_lock);
486
487         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
488          * delete it regardless.  (It's safe to delete an import that was
489          * never added.) */
490         (void)ptlrpc_pinger_del_import(imp);
491
492         if (obd->obd_namespace != NULL) {
493                 /* obd_force == local only */
494                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
495                                        obd->obd_force ? LDLM_FL_LOCAL_ONLY:0,
496                                        NULL);
497                 ldlm_namespace_free_prior(obd->obd_namespace, imp,
498                                           obd->obd_force);
499         }
500
501         rc = ptlrpc_disconnect_import(imp, 0);
502
503         ptlrpc_invalidate_import(imp);
504
505         if (imp->imp_rq_pool) {
506                 ptlrpc_free_rq_pool(imp->imp_rq_pool);
507                 imp->imp_rq_pool = NULL;
508         }
509         class_destroy_import(imp);
510         cli->cl_import = NULL;
511
512         EXIT;
513
514  out_disconnect:
515         /* use server style - class_disconnect should be always called for
516          * o_disconnect */
517         err = class_disconnect(exp);
518         if (!rc && err)
519                 rc = err;
520         up_write(&cli->cl_sem);
521
522         RETURN(rc);
523 }
524
525 /* --------------------------------------------------------------------------
526  * from old lib/target.c
527  * -------------------------------------------------------------------------- */
528
529 static int target_handle_reconnect(struct lustre_handle *conn,
530                                    struct obd_export *exp,
531                                    struct obd_uuid *cluuid)
532 {
533         ENTRY;
534         if (exp->exp_connection && exp->exp_imp_reverse) {
535                 struct lustre_handle *hdl;
536                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
537                 /* Might be a re-connect after a partition. */
538                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
539                         CWARN("%s: %s reconnecting\n", exp->exp_obd->obd_name,
540                               cluuid->uuid);
541                         conn->cookie = exp->exp_handle.h_cookie;
542                         /* target_handle_connect() treats EALREADY and
543                          * -EALREADY differently.  EALREADY means we are
544                          * doing a valid reconnect from the same client. */
545                         RETURN(EALREADY);
546                 } else {
547                         CERROR("%s reconnecting from %s, "
548                                "handle mismatch (ours "LPX64", theirs "
549                                LPX64")\n", cluuid->uuid,
550                                exp->exp_connection->c_remote_uuid.uuid,
551                                hdl->cookie, conn->cookie);
552                         memset(conn, 0, sizeof *conn);
553                         /* target_handle_connect() treats EALREADY and
554                          * -EALREADY differently.  -EALREADY is an error
555                          * (same UUID, different handle). */
556                         RETURN(-EALREADY);
557                 }
558         }
559
560         conn->cookie = exp->exp_handle.h_cookie;
561         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
562                cluuid->uuid, exp, conn->cookie);
563         RETURN(0);
564 }
565
566 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
567                           int error)
568 {
569         struct obd_export *exp = cb_data;
570
571         CDEBUG(D_RPCTRACE, "%s: committing for initial connect of %s\n",
572                obd->obd_name, exp->exp_client_uuid.uuid);
573
574         spin_lock(&exp->exp_lock);
575         exp->exp_need_sync = 0;
576         spin_unlock(&exp->exp_lock);
577 }
578 EXPORT_SYMBOL(target_client_add_cb);
579
580 static void
581 target_start_and_reset_recovery_timer(struct obd_device *obd,
582                                       svc_handler_t handler,
583                                       struct ptlrpc_request *req,
584                                       int new_client);
585 void target_stop_recovery(void *, int);
586 static void reset_recovery_timer(struct obd_device *obd, int duration,
587                                  int extend);
588 int target_recovery_check_and_stop(struct obd_device *obd)
589 {
590         int abort_recovery = 0;
591
592         spin_lock_bh(&obd->obd_processing_task_lock);
593         abort_recovery = obd->obd_abort_recovery;
594         obd->obd_abort_recovery = 0;
595         spin_unlock_bh(&obd->obd_processing_task_lock);
596         if (!abort_recovery)
597                 return 0;
598         /** check is fs version-capable */
599         if (target_fs_version_capable(obd)) {
600                 class_handle_stale_exports(obd);
601         } else {
602                 CWARN("Versions are not supported by ldiskfs, VBR is OFF\n");
603                 class_disconnect_stale_exports(obd, exp_flags_from_obd(obd));
604         }
605         /* VBR: no clients are remained to replay, stop recovery */
606         spin_lock_bh(&obd->obd_processing_task_lock);
607         if (obd->obd_recovering && obd->obd_recoverable_clients == 0) {
608                 spin_unlock_bh(&obd->obd_processing_task_lock);
609                 target_stop_recovery(obd, 0);
610                 return 1;
611         }
612         /* always check versions now */
613         obd->obd_version_recov = 1;
614         spin_unlock_bh(&obd->obd_processing_task_lock);
615         /* reset timer, recovery will proceed with versions now */
616         reset_recovery_timer(obd, OBD_RECOVERY_TIME_SOFT, 1);
617         return 0;
618 }
619 EXPORT_SYMBOL(target_recovery_check_and_stop);
620
621 int target_handle_connect(struct ptlrpc_request *req, svc_handler_t handler)
622 {
623         struct obd_device *target, *targref = NULL;
624         struct obd_export *export = NULL;
625         struct obd_import *revimp;
626         struct lustre_handle conn;
627         struct obd_uuid tgtuuid;
628         struct obd_uuid cluuid;
629         struct obd_uuid remote_uuid;
630         char *str, *tmp;
631         int rc = 0;
632         struct obd_connect_data *data;
633         __u32 size[2] = { sizeof(struct ptlrpc_body), sizeof(*data) };
634         lnet_nid_t *client_nid = NULL;
635         int mds_conn = 0;
636         ENTRY;
637
638         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
639
640         lustre_set_req_swabbed(req, REQ_REC_OFF);
641         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF, sizeof(tgtuuid)-1);
642         if (str == NULL) {
643                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
644                 GOTO(out, rc = -EINVAL);
645         }
646
647         obd_str2uuid (&tgtuuid, str);
648         target = class_uuid2obd(&tgtuuid);
649         /* COMPAT_146 */
650         /* old (pre 1.6) lustre_process_log tries to connect to mdsname
651            (eg. mdsA) instead of uuid. */
652         if (!target) {
653                 snprintf((char *)tgtuuid.uuid, sizeof(tgtuuid), "%s_UUID", str);
654                 target = class_uuid2obd(&tgtuuid);
655         }
656         if (!target)
657                 target = class_name2obd(str);
658         /* end COMPAT_146 */
659
660         if (!target || target->obd_stopping || !target->obd_set_up) {
661                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
662                                    " for connect (%s)\n", str,
663                                    !target ? "no target" :
664                                    (target->obd_stopping ? "stopping" :
665                                    "not set up"));
666                 GOTO(out, rc = -ENODEV);
667         }
668
669         if (target->obd_no_conn) {
670                 LCONSOLE_WARN("%s: temporarily refusing client connection "
671                               "from %s\n", target->obd_name,
672                               libcfs_nid2str(req->rq_peer.nid));
673                 GOTO(out, rc = -EAGAIN);
674         }
675
676         /* Make sure the target isn't cleaned up while we're here. Yes,
677            there's still a race between the above check and our incref here.
678            Really, class_uuid2obd should take the ref. */
679         targref = class_incref(target);
680
681         lustre_set_req_swabbed(req, REQ_REC_OFF + 1);
682         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF + 1,
683                                 sizeof(cluuid) - 1);
684         if (str == NULL) {
685                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
686                 GOTO(out, rc = -EINVAL);
687         }
688
689         obd_str2uuid (&cluuid, str);
690
691         /* XXX extract a nettype and format accordingly */
692         switch (sizeof(lnet_nid_t)) {
693                 /* NB the casts only avoid compiler warnings */
694         case 8:
695                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
696                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
697                 break;
698         case 4:
699                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
700                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
701                 break;
702         default:
703                 LBUG();
704         }
705
706         target_recovery_check_and_stop(target);
707
708         tmp = lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn);
709         if (tmp == NULL)
710                 GOTO(out, rc = -EPROTO);
711
712         memcpy(&conn, tmp, sizeof conn);
713
714         data = lustre_swab_reqbuf(req, REQ_REC_OFF + 3, sizeof(*data),
715                                   lustre_swab_connect);
716         rc = lustre_pack_reply(req, 2, size, NULL);
717         if (rc)
718                 GOTO(out, rc);
719
720         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
721                 if (!data) {
722                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
723                                   "libclient connection attempt");
724                         GOTO(out, rc = -EPROTO);
725                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
726                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
727                            data->ocd_version > LUSTRE_VERSION_CODE +
728                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
729                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
730                                   "libclient connection attempt",
731                                   data->ocd_version < LUSTRE_VERSION_CODE ?
732                                   "old" : "new",
733                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
734                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
735                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
736                                   OBD_OCD_VERSION_FIX(data->ocd_version));
737                         data = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
738                                               offsetof(typeof(*data),
739                                                        ocd_version) +
740                                               sizeof(data->ocd_version));
741                         if (data) {
742                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
743                                 data->ocd_version = LUSTRE_VERSION_CODE;
744                         }
745                         GOTO(out, rc = -EPROTO);
746                 }
747         }
748
749         if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL) &&
750             (data->ocd_connect_flags & OBD_CONNECT_MDS))
751                 mds_conn = 1;
752
753         /* lctl gets a backstage, all-access pass. */
754         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
755                 goto dont_check_exports;
756
757         export = lustre_hash_lookup(target->obd_uuid_hash, &cluuid);
758         if (!export)
759                 goto no_export;
760
761         /* we've found an export in the hash */
762         if (export->exp_connecting) {
763                 /* bug 9635, et. al. */
764                 CWARN("%s: exp %p already connecting\n",
765                       export->exp_obd->obd_name, export);
766                 class_export_put(export);
767                 export = NULL;
768                 rc = -EALREADY;
769         } else if (mds_conn && export->exp_connection) {
770                 if (req->rq_peer.nid != export->exp_connection->c_peer.nid)
771                         /* mds reconnected after failover */
772                         CWARN("%s: received MDS connection from NID %s,"
773                               " removing former export from NID %s\n",
774                             target->obd_name, libcfs_nid2str(req->rq_peer.nid),
775                             libcfs_nid2str(export->exp_connection->c_peer.nid));
776                 else
777                         /* new mds connection from the same nid */
778                         CWARN("%s: received new MDS connection from NID %s,"
779                               " removing former export from same NID\n",
780                             target->obd_name, libcfs_nid2str(req->rq_peer.nid));
781                 class_fail_export(export);
782                 class_export_put(export);
783                 export = NULL;
784                 rc = 0;
785         } else if (export->exp_connection &&
786                    req->rq_peer.nid != export->exp_connection->c_peer.nid &&
787                    (lustre_msg_get_op_flags(req->rq_reqmsg) &
788                     MSG_CONNECT_INITIAL)) {
789                 CWARN("%s: cookie %s seen on new NID %s when "
790                       "existing NID %s is already connected\n",
791                       target->obd_name, cluuid.uuid,
792                       libcfs_nid2str(req->rq_peer.nid),
793                       libcfs_nid2str(export->exp_connection->c_peer.nid));
794                 rc = -EALREADY;
795                 class_export_put(export);
796                 export = NULL;
797         } else if (export->exp_failed) { /* bug 11327 */
798                 CDEBUG(D_HA, "%s: exp %p evict in progress - new cookie needed "
799                       "for connect\n", export->exp_obd->obd_name, export);
800                 class_export_put(export);
801                 export = NULL;
802                 rc = -ENODEV;
803         } else if (export->exp_delayed &&
804                    !(data && data->ocd_connect_flags & OBD_CONNECT_VBR)) {
805                 class_fail_export(export);
806                 class_export_put(export);
807                 export = NULL;
808                 GOTO(out, rc = -ENODEV);
809         } else {
810                 spin_lock(&export->exp_lock);
811                 export->exp_connecting = 1;
812                 spin_unlock(&export->exp_lock);
813                 class_export_put(export);
814                 LASSERT(export->exp_obd == target);
815
816                 rc = target_handle_reconnect(&conn, export, &cluuid);
817         }
818
819         /* If we found an export, we already unlocked. */
820         if (!export) {
821 no_export:
822                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
823         } else if (req->rq_export == NULL &&
824                    atomic_read(&export->exp_rpc_count) > 0) {
825                 CWARN("%s: refuse connection from %s/%s to 0x%p; still busy "
826                       "with %d references\n", target->obd_name, cluuid.uuid,
827                       libcfs_nid2str(req->rq_peer.nid),
828                       export, atomic_read(&export->exp_refcount));
829                 GOTO(out, rc = -EBUSY);
830         } else if (req->rq_export != NULL &&
831                    atomic_read(&export->exp_rpc_count) > 1) {
832                 /* the current connect rpc has increased exp_rpc_count */
833                 CWARN("%s: refuse reconnection from %s@%s to 0x%p; still busy "
834                       "with %d active RPCs\n", target->obd_name, cluuid.uuid,
835                       libcfs_nid2str(req->rq_peer.nid),
836                       export, atomic_read(&export->exp_rpc_count) - 1);
837                 spin_lock(&export->exp_lock);
838                 if (req->rq_export->exp_conn_cnt <
839                     lustre_msg_get_conn_cnt(req->rq_reqmsg))
840                         /* try to abort active requests */
841                         req->rq_export->exp_abort_active_req = 1;
842                 spin_unlock(&export->exp_lock);
843                 GOTO(out, rc = -EBUSY);
844         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1) {
845                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
846                        "cookies not random?\n", target->obd_name,
847                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
848                 GOTO(out, rc = -EALREADY);
849         } else if (export->exp_delayed && target->obd_recovering) {
850                 /* VBR: don't allow delayed connection during recovery */
851                 CWARN("%s: NID %s (%s) export was already marked as delayed "
852                       "and will wait for end of recovery\n", target->obd_name,
853                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
854                 GOTO(out, rc = -EBUSY);
855         } else {
856                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
857         }
858
859         if (rc < 0)
860                 GOTO(out, rc);
861
862         /* Tell the client if we're in recovery. */
863         if (target->obd_recovering) {
864                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
865                 /* If this is the first time a client connects,
866                    reset the recovery timer */
867                 if (rc == 0)
868                         target_start_and_reset_recovery_timer(target, handler,
869                                                               req, !export);
870         }
871
872         /* We want to handle EALREADY but *not* -EALREADY from
873          * target_handle_reconnect(), return reconnection state in a flag */
874         if (rc == EALREADY) {
875                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
876                 rc = 0;
877         } else {
878                 LASSERT(rc == 0);
879         }
880
881         /* Tell the client if we support replayable requests */
882         if (target->obd_replayable)
883                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
884         client_nid = &req->rq_peer.nid;
885
886         /* VBR: for delayed connections we start recovery */
887         if (export && export->exp_delayed && !export->exp_in_recovery) {
888                 LASSERT(!target->obd_recovering);
889                 LASSERT(data && data->ocd_connect_flags & OBD_CONNECT_VBR);
890                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_DELAYED |
891                                         MSG_CONNECT_RECOVERING);
892                 spin_lock_bh(&target->obd_processing_task_lock);
893                 target->obd_version_recov = 1;
894                 spin_unlock_bh(&target->obd_processing_task_lock);
895                 target_start_and_reset_recovery_timer(target, handler, req, 1);
896         }
897
898         if (export == NULL) {
899                 if (target->obd_recovering) {
900                         CERROR("%s: denying connection for new client %s (%s): "
901                                "%d clients in recovery for %lds\n",
902                                target->obd_name,
903                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
904                                target->obd_recoverable_clients,
905                                cfs_duration_sec(cfs_time_sub(cfs_timer_deadline(&target->obd_recovery_timer),
906                                                              cfs_time_current())));
907                         rc = -EBUSY;
908                 } else {
909  dont_check_exports:
910                         rc = obd_connect(&conn, target, &cluuid, data,
911                                          client_nid);
912                 }
913         } else {
914                 rc = obd_reconnect(export, target, &cluuid, data, client_nid);
915         }
916
917         if (rc)
918                 GOTO(out, rc);
919
920         /* Return only the parts of obd_connect_data that we understand, so the
921          * client knows that we don't understand the rest. */
922         if (data)
923                 memcpy(lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
924                                       sizeof(*data)),
925                        data, sizeof(*data));
926
927         /* If all else goes well, this is our RPC return code. */
928         req->rq_status = 0;
929
930         lustre_msg_set_handle(req->rq_repmsg, &conn);
931
932         /* ownership of this export ref transfers to the request AFTER we
933          * drop any previous reference the request had, but we don't want
934          * that to go to zero before we get our new export reference. */
935         export = class_conn2export(&conn);
936         if (!export) {
937                 DEBUG_REQ(D_ERROR, req, "Missing export!");
938                 GOTO(out, rc = -ENODEV);
939         }
940
941         /* If the client and the server are the same node, we will already
942          * have an export that really points to the client's DLM export,
943          * because we have a shared handles table.
944          *
945          * XXX this will go away when shaver stops sending the "connect" handle
946          * in the real "remote handle" field of the request --phik 24 Apr 2003
947          */
948         if (req->rq_export != NULL)
949                 class_export_put(req->rq_export);
950
951         req->rq_export = export;
952
953         spin_lock(&export->exp_lock);
954         if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
955                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
956                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
957                        export->exp_conn_cnt,
958                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
959
960                 spin_unlock(&export->exp_lock);
961                 GOTO(out, rc = -EALREADY);
962         }
963         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
964         export->exp_abort_active_req = 0;
965
966         /* request from liblustre?  Don't evict it for not pinging. */
967         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
968                 export->exp_libclient = 1;
969                 spin_unlock(&export->exp_lock);
970
971                 spin_lock(&target->obd_dev_lock);
972                 list_del_init(&export->exp_obd_chain_timed);
973                 spin_unlock(&target->obd_dev_lock);
974         } else {
975                 spin_unlock(&export->exp_lock);
976         }
977
978         if (export->exp_connection != NULL) {
979                 /* Check to see if connection came from another NID */
980                 if ((export->exp_connection->c_peer.nid != req->rq_peer.nid) &&
981                     !hlist_unhashed(&export->exp_nid_hash))
982                         lustre_hash_del(export->exp_obd->obd_nid_hash,
983                                         &export->exp_connection->c_peer.nid,
984                                         &export->exp_nid_hash);
985
986                 ptlrpc_connection_put(export->exp_connection);
987         }
988
989         export->exp_connection = ptlrpc_connection_get(req->rq_peer,
990                                                        req->rq_self,
991                                                        &remote_uuid);
992
993         if (hlist_unhashed(&export->exp_nid_hash)) {
994                 lustre_hash_add_unique(export->exp_obd->obd_nid_hash,
995                                        &export->exp_connection->c_peer.nid,
996                                        &export->exp_nid_hash);
997         }
998
999         if (lustre_msg_get_op_flags(req->rq_repmsg) & MSG_CONNECT_RECONNECT) {
1000                 revimp = class_import_get(export->exp_imp_reverse);
1001                 ptlrpc_connection_put(revimp->imp_connection);
1002                 revimp->imp_connection = NULL;
1003                 GOTO(set_flags, rc = 0);
1004         }
1005
1006         if (target->obd_recovering && !export->exp_in_recovery) {
1007                 spin_lock(&export->exp_lock);
1008                 export->exp_in_recovery = 1;
1009                 spin_unlock(&export->exp_lock);
1010                 target->obd_connected_clients++;
1011         }
1012         memcpy(&conn,
1013                lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn),
1014                sizeof conn);
1015
1016         if (export->exp_imp_reverse != NULL)
1017                 class_destroy_import(export->exp_imp_reverse);
1018         revimp = export->exp_imp_reverse = class_new_import(target);
1019         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
1020         revimp->imp_remote_handle = conn;
1021         revimp->imp_dlm_fake = 1;
1022         revimp->imp_state = LUSTRE_IMP_FULL;
1023
1024 set_flags:
1025         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
1026         if (req->rq_reqmsg->lm_magic == LUSTRE_MSG_MAGIC_V1 &&
1027             lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_NEXT_VER) {
1028                 revimp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
1029                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_NEXT_VER);
1030         } else {
1031                 /* unknown versions will be caught in
1032                  * ptlrpc_handle_server_req_in->lustre_unpack_msg() */
1033                 revimp->imp_msg_magic = req->rq_reqmsg->lm_magic;
1034         }
1035
1036         if (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1) {
1037                 if (export->exp_connect_flags & OBD_CONNECT_AT)
1038                         revimp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1039                 else
1040                         revimp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1041         }
1042
1043         class_import_put(revimp);
1044 out:
1045         if (export) {
1046                 spin_lock(&export->exp_lock);
1047                 export->exp_connecting = 0;
1048                 spin_unlock(&export->exp_lock);
1049         }
1050         if (targref)
1051                 class_decref(targref);
1052         if (rc)
1053                 req->rq_status = rc;
1054         RETURN(rc);
1055 }
1056
1057 int target_handle_disconnect(struct ptlrpc_request *req)
1058 {
1059         int rc;
1060         ENTRY;
1061
1062         rc = lustre_pack_reply(req, 1, NULL, NULL);
1063         if (rc)
1064                 RETURN(rc);
1065
1066         /* keep the rq_export around so we can send the reply */
1067         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1068         RETURN(0);
1069 }
1070
1071 void target_destroy_export(struct obd_export *exp)
1072 {
1073         /* exports created from last_rcvd data, and "fake"
1074            exports created by lctl don't have an import */
1075         if (exp->exp_imp_reverse != NULL)
1076                 class_destroy_import(exp->exp_imp_reverse);
1077
1078         /* We cancel locks at disconnect time, but this will catch any locks
1079          * granted in a race with recovery-induced disconnect. */
1080         if (exp->exp_obd->obd_namespace != NULL)
1081                 ldlm_cancel_locks_for_export(exp);
1082 }
1083
1084 /*
1085  * Recovery functions
1086  */
1087
1088 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1089 {
1090         __u64                  transno = lustre_msg_get_transno(req->rq_reqmsg);
1091         struct obd_export     *exp = req->rq_export;
1092         struct ptlrpc_request *reqiter;
1093         int                    dup = 0;
1094
1095         LASSERT(exp);
1096
1097         spin_lock(&exp->exp_lock);
1098         list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1099                             rq_replay_list) {
1100                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1101                         dup = 1;
1102                         break;
1103                 }
1104         }
1105
1106         if (dup) {
1107                 /* we expect it with RESENT and REPLAY flags */
1108                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1109                      (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1110                         CERROR("invalid flags %x of resent replay\n",
1111                                lustre_msg_get_flags(req->rq_reqmsg));
1112         } else {
1113                 list_add_tail(&req->rq_replay_list, &exp->exp_req_replay_queue);
1114         }
1115
1116         spin_unlock(&exp->exp_lock);
1117         return dup;
1118 }
1119
1120 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1121 {
1122         LASSERT(!list_empty(&req->rq_replay_list));
1123         LASSERT(req->rq_export);
1124
1125         spin_lock(&req->rq_export->exp_lock);
1126         list_del_init(&req->rq_replay_list);
1127         spin_unlock(&req->rq_export->exp_lock);
1128 }
1129
1130 static void target_release_saved_req(struct ptlrpc_request *req)
1131 {
1132         ptlrpc_req_drop_rs(req);
1133         class_export_put(req->rq_export);
1134         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1135         OBD_FREE(req, sizeof *req);
1136 }
1137
1138 static void target_send_delayed_replies(struct obd_device *obd)
1139 {
1140         int max_clients = obd->obd_max_recoverable_clients;
1141         struct ptlrpc_request *req, *tmp;
1142         time_t elapsed_time = max_t(time_t, 1, cfs_time_current_sec() -
1143                                     obd->obd_recovery_start);
1144
1145         LCONSOLE_INFO("%s: Recovery period over after %d:%.02d, of %d clients "
1146                       "%d recovered and %d %s evicted.\n", obd->obd_name,
1147                       (int)elapsed_time/60, (int)elapsed_time%60, max_clients,
1148                       obd->obd_connected_clients,
1149                       obd->obd_stale_clients,
1150                       obd->obd_stale_clients == 1 ? "was" : "were");
1151
1152         LCONSOLE_INFO("%s: sending delayed replies to recovered clients\n",
1153                       obd->obd_name);
1154
1155         list_for_each_entry_safe(req, tmp, &obd->obd_delayed_reply_queue,
1156                                  rq_list) {
1157                 list_del_init(&req->rq_list);
1158                 DEBUG_REQ(D_HA, req, "delayed:");
1159                 ptlrpc_reply(req);
1160                 target_release_saved_req(req);
1161         }
1162         obd->obd_recovery_end = cfs_time_current_sec();
1163 }
1164
1165 static void target_finish_recovery(struct obd_device *obd)
1166 {
1167         OBD_RACE(OBD_FAIL_TGT_REPLAY_DELAY);
1168
1169         ldlm_reprocess_all_ns(obd->obd_namespace);
1170         spin_lock_bh(&obd->obd_processing_task_lock);
1171         if (list_empty(&obd->obd_recovery_queue)) {
1172                 obd->obd_recovery_thread = NULL;
1173                 obd->obd_processing_task = 0;
1174         } else {
1175                 spin_unlock_bh(&obd->obd_processing_task_lock);
1176                 CERROR("%s: Recovery queue isn't empty\n", obd->obd_name);
1177                 LBUG();
1178         }
1179         spin_unlock_bh(&obd->obd_processing_task_lock);
1180                 ;
1181         /* when recovery finished, cleanup orphans on mds and ost */
1182         if (OBT(obd) && OBP(obd, postrecov)) {
1183                 int rc = OBP(obd, postrecov)(obd);
1184                 if (rc < 0)
1185                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1186                                       obd->obd_name, rc);
1187         }
1188         target_send_delayed_replies(obd);
1189 }
1190
1191 static void abort_recovery_queue(struct obd_device *obd)
1192 {
1193         struct ptlrpc_request *req, *n;
1194         struct list_head abort_list;
1195         int rc;
1196
1197         CFS_INIT_LIST_HEAD(&abort_list);
1198         spin_lock_bh(&obd->obd_processing_task_lock);
1199         list_splice_init(&obd->obd_recovery_queue, &abort_list);
1200         spin_unlock_bh(&obd->obd_processing_task_lock);
1201         /* process abort list unlocked */
1202         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1203                 target_exp_dequeue_req_replay(req);
1204                 list_del_init(&req->rq_list);
1205                 DEBUG_REQ(D_ERROR, req, "aborted:");
1206                 req->rq_status = -ENOTCONN;
1207                 req->rq_type = PTL_RPC_MSG_ERR;
1208                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1209                 if (rc == 0)
1210                         ptlrpc_reply(req);
1211                 else
1212                         DEBUG_REQ(D_ERROR, req,
1213                                   "packing failed for abort-reply; skipping");
1214
1215                 LASSERT(req->rq_copy);
1216                 class_export_rpc_put(req->rq_export);
1217                 target_release_saved_req(req);
1218         }
1219 }
1220
1221 /* Called from a cleanup function if the device is being cleaned up
1222    forcefully.  The exports should all have been disconnected already,
1223    the only thing left to do is
1224      - clear the recovery flags
1225      - cancel the timer
1226      - free queued requests and replies, but don't send replies
1227    Because the obd_stopping flag is set, no new requests should be received.
1228
1229 */
1230 void target_cleanup_recovery(struct obd_device *obd)
1231 {
1232         struct list_head *tmp, *n;
1233         struct ptlrpc_request *req;
1234         struct list_head clean_list;
1235         ENTRY;
1236
1237         LASSERT(obd->obd_stopping);
1238
1239         spin_lock_bh(&obd->obd_processing_task_lock);
1240         if (!obd->obd_recovering) {
1241                 spin_unlock_bh(&obd->obd_processing_task_lock);
1242                 EXIT;
1243                 return;
1244         }
1245         obd->obd_recovering = obd->obd_abort_recovery = 0;
1246         target_cancel_recovery_timer(obd);
1247         spin_unlock_bh(&obd->obd_processing_task_lock);
1248
1249         list_for_each_safe(tmp, n, &obd->obd_delayed_reply_queue) {
1250                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1251                 list_del(&req->rq_list);
1252                 target_release_saved_req(req);
1253         }
1254
1255         CFS_INIT_LIST_HEAD(&clean_list);
1256         spin_lock_bh(&obd->obd_processing_task_lock);
1257         list_splice_init(&obd->obd_recovery_queue, &clean_list);
1258         spin_unlock_bh(&obd->obd_processing_task_lock);
1259         list_for_each_safe(tmp, n, &clean_list) {
1260                 req = list_entry(tmp, struct ptlrpc_request, rq_list);
1261                 target_exp_dequeue_req_replay(req);
1262                 list_del_init(&req->rq_list);
1263
1264                 LASSERT(req->rq_copy);
1265                 class_export_rpc_put(req->rq_export);
1266                 target_release_saved_req(req);
1267         }
1268         EXIT;
1269 }
1270
1271 void target_stop_recovery(void *data, int abort)
1272 {
1273         struct obd_device *obd = data;
1274         enum obd_option flags;
1275         ENTRY;
1276
1277         spin_lock_bh(&obd->obd_processing_task_lock);
1278         if (!obd->obd_recovering) {
1279                 spin_unlock_bh(&obd->obd_processing_task_lock);
1280                 EXIT;
1281                 return;
1282         }
1283         flags = exp_flags_from_obd(obd) | OBD_OPT_ABORT_RECOV;
1284         obd->obd_recovering = 0;
1285         obd->obd_abort_recovery = 0;
1286         obd->obd_processing_task = 0;
1287         if (abort == 0)
1288                 LASSERT(obd->obd_recoverable_clients == 0);
1289
1290         target_cancel_recovery_timer(obd);
1291         spin_unlock_bh(&obd->obd_processing_task_lock);
1292
1293         if (abort) {
1294                 LCONSOLE_WARN("%s: recovery is aborted by administrative "
1295                               "request; %d clients are not recovered "
1296                               "(%d clients did)\n", obd->obd_name,
1297                               obd->obd_recoverable_clients,
1298                               obd->obd_connected_clients);
1299                 class_disconnect_stale_exports(obd, flags);
1300         }
1301         abort_recovery_queue(obd);
1302         target_finish_recovery(obd);
1303         CDEBUG(D_HA, "%s: recovery complete\n", obd_uuid2str(&obd->obd_uuid));
1304         EXIT;
1305 }
1306
1307 void target_abort_recovery(void *data)
1308 {
1309         target_stop_recovery(data, 1);
1310 }
1311
1312 static void reset_recovery_timer(struct obd_device *, int, int);
1313 static void target_recovery_expired(unsigned long castmeharder)
1314 {
1315         struct obd_device *obd = (struct obd_device *)castmeharder;
1316         CDEBUG(D_HA, "%s: recovery period over; %d clients never reconnected "
1317                "after %lds (%d clients did)\n", obd->obd_name,
1318                obd->obd_recoverable_clients,
1319                cfs_time_current_sec() - obd->obd_recovery_start,
1320                obd->obd_connected_clients);
1321
1322         spin_lock_bh(&obd->obd_processing_task_lock);
1323         obd->obd_abort_recovery = 1;
1324         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1325         spin_unlock_bh(&obd->obd_processing_task_lock);
1326 }
1327
1328 /* obd_processing_task_lock should be held */
1329 void target_cancel_recovery_timer(struct obd_device *obd)
1330 {
1331         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1332         cfs_timer_disarm(&obd->obd_recovery_timer);
1333 }
1334
1335 /* extend = 1 means require at least "duration" seconds left in the timer,
1336    extend = 0 means set the total duration (start_recovery_timer) */
1337 static void reset_recovery_timer(struct obd_device *obd, int duration,
1338                                  int extend)
1339 {
1340         cfs_time_t now = cfs_time_current_sec();
1341         cfs_duration_t left;
1342
1343         spin_lock_bh(&obd->obd_processing_task_lock);
1344         if (!obd->obd_recovering) {
1345                 spin_unlock_bh(&obd->obd_processing_task_lock);
1346                 return;
1347         }
1348
1349         left = cfs_time_sub(obd->obd_recovery_end, now);
1350
1351         if (extend && (duration > left))
1352                 obd->obd_recovery_timeout += duration - left;
1353         else if (!extend && (duration > obd->obd_recovery_timeout))
1354                 /* Track the client's largest expected replay time */
1355                 obd->obd_recovery_timeout = duration;
1356
1357         /* Hard limit of obd_recovery_time_hard which should not happen */
1358         if(obd->obd_recovery_timeout > obd->obd_recovery_time_hard)
1359                 obd->obd_recovery_timeout = obd->obd_recovery_time_hard;
1360
1361         obd->obd_recovery_end = obd->obd_recovery_start +
1362                                 obd->obd_recovery_timeout;
1363         if (cfs_time_before(now, obd->obd_recovery_end)) {
1364                 left = cfs_time_sub(obd->obd_recovery_end, now);
1365                 cfs_timer_arm(&obd->obd_recovery_timer, cfs_time_shift(left));
1366         }
1367         spin_unlock_bh(&obd->obd_processing_task_lock);
1368         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n",
1369                obd->obd_name, (unsigned)left);
1370 }
1371
1372 static void check_and_start_recovery_timer(struct obd_device *obd,
1373                                            svc_handler_t handler)
1374 {
1375         spin_lock_bh(&obd->obd_processing_task_lock);
1376         if (obd->obd_recovery_handler) {
1377                 spin_unlock_bh(&obd->obd_processing_task_lock);
1378                 return;
1379         }
1380         CDEBUG(D_HA, "%s: starting recovery timer\n", obd->obd_name);
1381         obd->obd_recovery_start = cfs_time_current_sec();
1382         obd->obd_recovery_handler = handler;
1383         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1384         spin_unlock_bh(&obd->obd_processing_task_lock);
1385
1386         reset_recovery_timer(obd, obd->obd_recovery_timeout, 0);
1387 }
1388
1389 /* Reset the timer with each new client connection */
1390 /*
1391  * This timer is actually reconnect_timer, which is for making sure
1392  * the total recovery window is at least as big as my reconnect
1393  * attempt timing. So the initial recovery time_out will be set to
1394  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1395  * from client is bigger than this, then the recovery time_out will
1396  * be extend to make sure the client could be reconnected, in the
1397  * process, the timeout from the new client should be ignored.
1398  */
1399
1400 static void
1401 target_start_and_reset_recovery_timer(struct obd_device *obd,
1402                                       svc_handler_t handler,
1403                                       struct ptlrpc_request *req,
1404                                       int new_client)
1405 {
1406         int service_time = lustre_msg_get_service_time(req->rq_reqmsg);
1407
1408         if (!new_client && service_time)
1409                 /* Teach server about old server's estimates, as first guess
1410                    at how long new requests will take. */
1411                 at_add(&req->rq_rqbd->rqbd_service->srv_at_estimate,
1412                        service_time);
1413
1414         check_and_start_recovery_timer(obd, handler);
1415
1416         /* convert the service time to rpc timeout,
1417          * reuse service_time to limit stack usage */
1418         service_time = at_est2timeout(service_time);
1419
1420         /* We expect other clients to timeout within service_time, then try
1421          * to reconnect, then try the failover server.  The max delay between
1422          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL */
1423         service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC +
1424                              INITIAL_CONNECT_TIMEOUT);
1425         if (service_time > obd->obd_recovery_timeout && !new_client)
1426                 reset_recovery_timer(obd, service_time, 0);
1427 }
1428
1429 static int check_for_next_transno(struct obd_device *obd)
1430 {
1431         struct ptlrpc_request *req;
1432         int wake_up = 0, connected, completed, queue_len, max;
1433         __u64 next_transno, req_transno;
1434
1435         spin_lock_bh(&obd->obd_processing_task_lock);
1436         req = list_entry(obd->obd_recovery_queue.next,
1437                          struct ptlrpc_request, rq_list);
1438         max = obd->obd_max_recoverable_clients;
1439         req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1440         connected = obd->obd_connected_clients;
1441         completed = max - obd->obd_recoverable_clients -
1442                     obd->obd_delayed_clients;
1443         queue_len = obd->obd_requests_queued_for_recovery;
1444         next_transno = obd->obd_next_recovery_transno;
1445
1446         CDEBUG(D_HA,"max: %d, connected: %d, delayed %d, completed: %d, "
1447                "queue_len: %d, req_transno: "LPU64", next_transno: "LPU64"\n",
1448                max, connected, obd->obd_delayed_clients, completed, queue_len,
1449                req_transno, next_transno);
1450         if (obd->obd_abort_recovery) {
1451                 CDEBUG(D_HA, "waking for aborted recovery\n");
1452                 wake_up = 1;
1453         } else if (!obd->obd_recovering) {
1454                 CDEBUG(D_HA, "waking for completed recovery (?)\n");
1455                 wake_up = 1;
1456         } else if (req_transno == next_transno) {
1457                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1458                 wake_up = 1;
1459         } else if (queue_len == obd->obd_recoverable_clients) {
1460                 CDEBUG(D_ERROR,
1461                        "waking for skipped transno (skip: "LPD64
1462                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1463                        next_transno, queue_len, completed, max, req_transno);
1464                 obd->obd_next_recovery_transno = req_transno;
1465                 wake_up = 1;
1466         }
1467         spin_unlock_bh(&obd->obd_processing_task_lock);
1468         LASSERT(lustre_msg_get_transno(req->rq_reqmsg) >= next_transno);
1469         return wake_up;
1470 }
1471
1472 static void process_recovery_queue(struct obd_device *obd)
1473 {
1474         struct ptlrpc_request *req;
1475         struct l_wait_info lwi = { 0 };
1476         ENTRY;
1477
1478         for (;;) {
1479                 spin_lock_bh(&obd->obd_processing_task_lock);
1480                 LASSERT(obd->obd_processing_task == cfs_curproc_pid());
1481                 req = list_entry(obd->obd_recovery_queue.next,
1482                                  struct ptlrpc_request, rq_list);
1483
1484                 if (lustre_msg_get_transno(req->rq_reqmsg) !=
1485                     obd->obd_next_recovery_transno) {
1486                         spin_unlock_bh(&obd->obd_processing_task_lock);
1487                         CDEBUG(D_HA, "Waiting for transno "LPD64" (1st is "
1488                                LPD64", x"LPU64")\n",
1489                                obd->obd_next_recovery_transno,
1490                                lustre_msg_get_transno(req->rq_reqmsg),
1491                                req->rq_xid);
1492                         l_wait_event(obd->obd_next_transno_waitq,
1493                                      check_for_next_transno(obd), &lwi);
1494                         if (target_recovery_check_and_stop(obd))
1495                                 return;
1496                         continue;
1497                 }
1498                 list_del_init(&req->rq_list);
1499                 LASSERT(obd->obd_recovery_thread);
1500                 /* replace request initial thread with current one, bug #18221 */
1501                 req->rq_svc_thread = obd->obd_recovery_thread;
1502                 obd->obd_requests_queued_for_recovery--;
1503                 spin_unlock_bh(&obd->obd_processing_task_lock);
1504
1505                 DEBUG_REQ(D_HA, req, "processing: ");
1506                 (void)obd->obd_recovery_handler(req);
1507                 obd->obd_replayed_requests++;
1508                 /* Extend the recovery timer enough to complete the next
1509                  * replayed rpc */
1510                 reset_recovery_timer(obd, AT_OFF ? obd_timeout :
1511                        at_get(&req->rq_rqbd->rqbd_service->srv_at_estimate), 1);
1512                 /* bug 1580: decide how to properly sync() in recovery */
1513                 //mds_fsync_super(obd->u.obt.obt_sb);
1514                 spin_lock_bh(&obd->obd_processing_task_lock);
1515                 obd->obd_next_recovery_transno++;
1516                 spin_unlock_bh(&obd->obd_processing_task_lock);
1517                 target_exp_dequeue_req_replay(req);
1518
1519                 LASSERT(req->rq_copy);
1520                 class_export_rpc_put(req->rq_export);
1521
1522                 class_export_put(req->rq_export);
1523                 ptlrpc_req_drop_rs(req);
1524                 OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1525                 OBD_FREE(req, sizeof *req);
1526                 OBD_RACE(OBD_FAIL_TGT_REPLAY_DELAY);
1527                 spin_lock_bh(&obd->obd_processing_task_lock);
1528                 if (list_empty(&obd->obd_recovery_queue)) {
1529                         obd->obd_processing_task = 0;
1530                         obd->obd_recovery_thread = NULL;
1531                         spin_unlock_bh(&obd->obd_processing_task_lock);
1532                         break;
1533                 }
1534                 spin_unlock_bh(&obd->obd_processing_task_lock);
1535         }
1536         EXIT;
1537 }
1538
1539 int target_queue_recovery_request(struct ptlrpc_request *req,
1540                                   struct obd_device *obd)
1541 {
1542         struct list_head *tmp;
1543         int inserted = 0;
1544         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1545         struct ptlrpc_request *saved_req, *orig_req;
1546         struct lustre_msg *reqmsg;
1547         int rc = 0;
1548
1549         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1550          * (i.e. buflens etc are in my own byte order), but type-dependent
1551          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1552
1553         if (!transno) {
1554                 CFS_INIT_LIST_HEAD(&req->rq_list);
1555                 DEBUG_REQ(D_HA, req, "not queueing");
1556                 return 1;
1557         }
1558
1559         /* XXX If I were a real man, these LBUGs would be sane cleanups. */
1560         /* XXX just like the request-dup code in queue_final_reply */
1561         OBD_ALLOC(saved_req, sizeof *saved_req);
1562         if (!saved_req)
1563                 LBUG();
1564         OBD_ALLOC(reqmsg, req->rq_reqlen);
1565         if (!reqmsg)
1566                 LBUG();
1567
1568         spin_lock_bh(&obd->obd_processing_task_lock);
1569
1570         /* If we're processing the queue, we want don't want to queue this
1571          * message.
1572          *
1573          * Also, if this request has a transno less than the one we're waiting
1574          * for, we should process it now.  It could (and currently always will)
1575          * be an open request for a descriptor that was opened some time ago.
1576          *
1577          * Also, a resent, replayed request that has already been
1578          * handled will pass through here and be processed immediately.
1579          */
1580         if (obd->obd_processing_task == cfs_curproc_pid() ||
1581             transno < obd->obd_next_recovery_transno) {
1582                 /* Processing the queue right now, don't re-add. */
1583                 LASSERT(list_empty(&req->rq_list));
1584                 spin_unlock_bh(&obd->obd_processing_task_lock);
1585                 GOTO(err_free, rc = 1);
1586         }
1587
1588         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))) {
1589                 spin_unlock_bh(&obd->obd_processing_task_lock);
1590                 GOTO(err_free, rc = 0);
1591         }
1592
1593         memcpy(saved_req, req, sizeof *req);
1594         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1595         orig_req = req;
1596         req = saved_req;
1597         req->rq_reqmsg = reqmsg;
1598         class_export_get(req->rq_export);
1599         CFS_INIT_LIST_HEAD(&req->rq_list);
1600         CFS_INIT_LIST_HEAD(&req->rq_replay_list);
1601
1602         if (target_exp_enqueue_req_replay(req)) {
1603                 spin_unlock_bh(&obd->obd_processing_task_lock);
1604                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1605                 GOTO(err_exp, rc = 0);
1606         }
1607
1608         /* XXX O(n^2) */
1609         list_for_each(tmp, &obd->obd_recovery_queue) {
1610                 struct ptlrpc_request *reqiter =
1611                         list_entry(tmp, struct ptlrpc_request, rq_list);
1612
1613                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1614                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1615                         inserted = 1;
1616                         break;
1617                 }
1618
1619                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
1620                              transno)) {
1621                         spin_unlock_bh(&obd->obd_processing_task_lock);
1622                         DEBUG_REQ(D_ERROR, req, "dropping replay: transno "
1623                                   "has been claimed by another client");
1624                         target_exp_dequeue_req_replay(req);
1625                         GOTO(err_exp, rc = 0);
1626                 }
1627         }
1628
1629         if (!inserted) {
1630                 list_add_tail(&req->rq_list, &obd->obd_recovery_queue);
1631         }
1632
1633         obd->obd_requests_queued_for_recovery++;
1634         orig_req->rq_copy_queued = 1;
1635         req->rq_copy = 1;
1636
1637         if (obd->obd_processing_task != 0) {
1638                 /* Someone else is processing this queue, we'll leave it to
1639                  * them.
1640                  */
1641                 cfs_waitq_signal(&obd->obd_next_transno_waitq);
1642                 spin_unlock_bh(&obd->obd_processing_task_lock);
1643                 return 0;
1644         }
1645
1646         /* Nobody is processing, and we know there's (at least) one to process
1647          * now, so we'll do the honours.
1648          */
1649         obd->obd_processing_task = cfs_curproc_pid();
1650         /* save thread that handle recovery queue */
1651         obd->obd_recovery_thread = req->rq_svc_thread;
1652         spin_unlock_bh(&obd->obd_processing_task_lock);
1653
1654         process_recovery_queue(obd);
1655         return 0;
1656
1657 err_exp:
1658         class_export_put(req->rq_export);
1659 err_free:
1660         OBD_FREE(reqmsg, req->rq_reqlen);
1661         OBD_FREE(saved_req, sizeof(*saved_req));
1662         return rc;
1663 }
1664
1665 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1666 {
1667         return req->rq_export->exp_obd;
1668 }
1669
1670 int target_queue_last_replay_reply(struct ptlrpc_request *req, int rc)
1671 {
1672         struct obd_device *obd = target_req2obd(req);
1673         struct ptlrpc_request *saved_req;
1674         struct lustre_msg *reqmsg;
1675         struct obd_export *exp = req->rq_export;
1676         int recovery_done = 0, delayed_done = 0;
1677
1678         LASSERT ((rc == 0) == req->rq_packed_final);
1679
1680         if (!req->rq_packed_final) {
1681                 /* Just like ptlrpc_error, but without the sending. */
1682                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1683                 if (rc)
1684                         return rc;
1685                 req->rq_type = PTL_RPC_MSG_ERR;
1686         }
1687
1688         LASSERT(!req->rq_reply_state->rs_difficult);
1689         LASSERT(list_empty(&req->rq_list));
1690         /* XXX a bit like the request-dup code in queue_recovery_request */
1691         OBD_ALLOC(saved_req, sizeof *saved_req);
1692         if (!saved_req)
1693                 return -ENOMEM;
1694         OBD_ALLOC(reqmsg, req->rq_reqlen);
1695         if (!reqmsg) {
1696                 OBD_FREE(saved_req, sizeof *req);
1697                 return -ENOMEM;
1698         }
1699         *saved_req = *req;
1700         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1701
1702         /* Don't race cleanup */
1703         spin_lock_bh(&obd->obd_processing_task_lock);
1704         if (obd->obd_stopping) {
1705                 spin_unlock_bh(&obd->obd_processing_task_lock);
1706                 goto out_noconn;
1707         }
1708
1709         if (!exp->exp_vbr_failed) {
1710                 ptlrpc_rs_addref(req->rq_reply_state);  /* +1 ref for saved reply */
1711                 req = saved_req;
1712                 req->rq_reqmsg = reqmsg;
1713                 CFS_INIT_LIST_HEAD(&req->rq_list);
1714                 CFS_INIT_LIST_HEAD(&req->rq_replay_list);
1715                 class_export_get(exp);
1716                 list_add(&req->rq_list, &obd->obd_delayed_reply_queue);
1717         }
1718
1719         /* only count the first "replay over" request from each
1720            export */
1721         if (exp->exp_replay_needed) {
1722                 spin_lock(&exp->exp_lock);
1723                 exp->exp_replay_needed = 0;
1724                 spin_unlock(&exp->exp_lock);
1725
1726                 if (!exp->exp_delayed) {
1727                         --obd->obd_recoverable_clients;
1728                 } else {
1729                         spin_lock(&exp->exp_lock);
1730                         exp->exp_delayed = 0;
1731                         spin_unlock(&exp->exp_lock);
1732                         delayed_done = 1;
1733                         if (obd->obd_delayed_clients == 0) {
1734                                 spin_unlock_bh(&obd->obd_processing_task_lock);
1735                                 LBUG();
1736                         }
1737                         --obd->obd_delayed_clients;
1738                 }
1739         }
1740         recovery_done = (obd->obd_recoverable_clients == 0);
1741         spin_unlock_bh(&obd->obd_processing_task_lock);
1742
1743         if (delayed_done) {
1744                 /* start pinging export */
1745                 spin_lock(&obd->obd_dev_lock);
1746                 list_add_tail(&exp->exp_obd_chain_timed,
1747                               &obd->obd_exports_timed);
1748                 list_move_tail(&exp->exp_obd_chain, &obd->obd_exports);
1749                 spin_unlock(&obd->obd_dev_lock);
1750                 target_send_delayed_replies(obd);
1751         }
1752
1753         OBD_RACE(OBD_FAIL_LDLM_RECOV_CLIENTS);
1754         if (recovery_done) {
1755                 spin_lock_bh(&obd->obd_processing_task_lock);
1756                 obd->obd_recovering = 0;
1757                 obd->obd_version_recov = 0;
1758                 obd->obd_abort_recovery = 0;
1759                 target_cancel_recovery_timer(obd);
1760                 spin_unlock_bh(&obd->obd_processing_task_lock);
1761
1762                 if (!delayed_done)
1763                         target_finish_recovery(obd);
1764                 CDEBUG(D_HA, "%s: recovery complete\n",
1765                        obd_uuid2str(&obd->obd_uuid));
1766         } else {
1767                 CWARN("%s: %d recoverable clients remain\n",
1768                       obd->obd_name, obd->obd_recoverable_clients);
1769                 cfs_waitq_signal(&obd->obd_next_transno_waitq);
1770         }
1771
1772         /* VBR: disconnect export with failed recovery */
1773         if (exp->exp_vbr_failed) {
1774                 CWARN("%s: disconnect export %s\n", obd->obd_name,
1775                       exp->exp_client_uuid.uuid);
1776                 class_fail_export(exp);
1777                 OBD_FREE(reqmsg, req->rq_reqlen);
1778                 OBD_FREE(saved_req, sizeof *req);
1779                 req->rq_status = 0;
1780                 ptlrpc_send_reply(req, 0);
1781         }
1782
1783         return 1;
1784
1785 out_noconn:
1786         OBD_FREE(reqmsg, req->rq_reqlen);
1787         OBD_FREE(saved_req, sizeof *req);
1788         req->rq_status = -ENOTCONN;
1789         /* rv is ignored anyhow */
1790         return -ENOTCONN;
1791 }
1792
1793 int target_handle_reply(struct ptlrpc_request *req, int rc, int fail)
1794 {
1795         struct obd_device *obd = NULL;
1796
1797         if (req->rq_export)
1798                 obd = target_req2obd(req);
1799
1800         /* handle replay reply for version recovery */
1801         if (obd && obd->obd_version_recov &&
1802             (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
1803                 LASSERT(req->rq_repmsg);
1804                 lustre_msg_add_flags(req->rq_repmsg, MSG_VERSION_REPLAY);
1805         }
1806
1807         /* handle last replay */
1808         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LAST_REPLAY) {
1809                 if (obd &&
1810                     lustre_msg_get_flags(req->rq_reqmsg) & MSG_DELAY_REPLAY) {
1811                         DEBUG_REQ(D_HA, req,
1812                                   "delayed LAST_REPLAY, queuing reply");
1813                         rc = target_queue_last_replay_reply(req, rc);
1814                         LASSERT(req->rq_export->exp_delayed == 0);
1815                         return rc;
1816                 }
1817
1818                 if (obd && obd->obd_recovering) { /* normal recovery */
1819                         DEBUG_REQ(D_HA, req, "LAST_REPLAY, queuing reply");
1820                         rc = target_queue_last_replay_reply(req, rc);
1821                         return rc;
1822                 }
1823
1824                 /* Lost a race with recovery; let the error path DTRT. */
1825                 rc = req->rq_status = -ENOTCONN;
1826         }
1827         target_send_reply(req, rc, fail);
1828         return 0;
1829 }
1830
1831 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1832 {
1833         LASSERT(exp != NULL);
1834         return &exp->exp_obd->obd_namespace->ns_pool;
1835 }
1836
1837 int target_pack_pool_reply(struct ptlrpc_request *req)
1838 {
1839         struct obd_device *obd;
1840         ENTRY;
1841
1842         /*
1843          * Check that we still have all structures alive as this may
1844          * be some late rpc in shutdown time.
1845          */
1846         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
1847                      !exp_connect_lru_resize(req->rq_export))) {
1848                 lustre_msg_set_slv(req->rq_repmsg, 0);
1849                 lustre_msg_set_limit(req->rq_repmsg, 0);
1850                 RETURN(0);
1851         }
1852
1853         /*
1854          * OBD is alive here as export is alive, which we checked above.
1855          */
1856         obd = req->rq_export->exp_obd;
1857
1858         read_lock(&obd->obd_pool_lock);
1859         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
1860         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
1861         read_unlock(&obd->obd_pool_lock);
1862
1863         RETURN(0);
1864 }
1865
1866 int
1867 target_send_reply_msg (struct ptlrpc_request *req, int rc, int fail_id)
1868 {
1869         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1870                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1871                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1872                 return (-ECOMM);
1873         }
1874
1875         if (rc) {
1876                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1877                 req->rq_status = rc;
1878                 return (ptlrpc_send_error(req, 1));
1879         } else {
1880                 DEBUG_REQ(D_NET, req, "sending reply");
1881         }
1882
1883         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
1884 }
1885
1886 void
1887 target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1888 {
1889         int                        netrc;
1890         struct ptlrpc_reply_state *rs;
1891         struct obd_device         *obd;
1892         struct obd_export         *exp;
1893         struct ptlrpc_service     *svc;
1894
1895         svc = req->rq_rqbd->rqbd_service;
1896         rs = req->rq_reply_state;
1897         if (rs == NULL || !rs->rs_difficult) {
1898                 /* no notifiers */
1899                 target_send_reply_msg (req, rc, fail_id);
1900                 return;
1901         }
1902
1903         /* must be an export if locks saved */
1904         LASSERT (req->rq_export != NULL);
1905         /* req/reply consistent */
1906         LASSERT (rs->rs_service == svc);
1907
1908         /* "fresh" reply */
1909         LASSERT (!rs->rs_scheduled);
1910         LASSERT (!rs->rs_scheduled_ever);
1911         LASSERT (!rs->rs_handled);
1912         LASSERT (!rs->rs_on_net);
1913         LASSERT (rs->rs_export == NULL);
1914         LASSERT (list_empty(&rs->rs_obd_list));
1915         LASSERT (list_empty(&rs->rs_exp_list));
1916
1917         exp = class_export_get(req->rq_export);
1918         obd = exp->exp_obd;
1919
1920         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1921         rs->rs_scheduled = 1;
1922         rs->rs_on_net    = 1;
1923         rs->rs_xid       = req->rq_xid;
1924         rs->rs_transno   = req->rq_transno;
1925         rs->rs_export    = exp;
1926
1927         spin_lock(&exp->exp_uncommitted_replies_lock);
1928
1929         /* VBR: use exp_last_committed */
1930         if (rs->rs_transno > exp->exp_last_committed) {
1931                 /* not committed already */
1932                 list_add_tail (&rs->rs_obd_list,
1933                                &exp->exp_uncommitted_replies);
1934         }
1935
1936         spin_unlock (&exp->exp_uncommitted_replies_lock);
1937         spin_lock (&exp->exp_lock);
1938
1939         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1940
1941         spin_unlock(&exp->exp_lock);
1942
1943         netrc = target_send_reply_msg (req, rc, fail_id);
1944
1945         spin_lock(&svc->srv_lock);
1946
1947         svc->srv_n_difficult_replies++;
1948
1949         if (netrc != 0) {
1950                 /* error sending: reply is off the net.  Also we need +1
1951                  * reply ref until ptlrpc_server_handle_reply() is done
1952                  * with the reply state (if the send was successful, there
1953                  * would have been +1 ref for the net, which
1954                  * reply_out_callback leaves alone) */
1955                 rs->rs_on_net = 0;
1956                 ptlrpc_rs_addref(rs);
1957                 atomic_inc (&svc->srv_outstanding_replies);
1958         }
1959
1960         if (!rs->rs_on_net ||                   /* some notifier */
1961             list_empty(&rs->rs_exp_list) ||     /* completed already */
1962             list_empty(&rs->rs_obd_list)) {
1963                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1964                 cfs_waitq_signal (&svc->srv_waitq);
1965         } else {
1966                 list_add (&rs->rs_list, &svc->srv_active_replies);
1967                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1968         }
1969
1970         spin_unlock(&svc->srv_lock);
1971 }
1972
1973 int target_handle_ping(struct ptlrpc_request *req)
1974 {
1975         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LAST_REPLAY &&
1976             req->rq_export->exp_in_recovery) {
1977                 spin_lock(&req->rq_export->exp_lock);
1978                 req->rq_export->exp_in_recovery = 0;
1979                 spin_unlock(&req->rq_export->exp_lock);
1980         }
1981         obd_ping(req->rq_export);
1982         return lustre_pack_reply(req, 1, NULL, NULL);
1983 }
1984
1985 void target_committed_to_req(struct ptlrpc_request *req)
1986 {
1987         struct obd_export *exp = req->rq_export;
1988         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL) {
1989                 lustre_msg_set_last_committed(req->rq_repmsg,
1990                                               exp->exp_last_committed);
1991         } else {
1992                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
1993                           "%d)", exp->exp_obd->obd_no_transno,
1994                           req->rq_repmsg == NULL);
1995         }
1996         CDEBUG(D_INFO, "last_committed x"LPU64", this req x"LPU64"\n",
1997                exp->exp_obd->obd_last_committed, req->rq_xid);
1998 }
1999
2000 EXPORT_SYMBOL(target_committed_to_req);
2001
2002 int target_handle_qc_callback(struct ptlrpc_request *req)
2003 {
2004         struct obd_quotactl *oqctl;
2005         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2006
2007         oqctl = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*oqctl),
2008                                    lustre_swab_obd_quotactl);
2009         if (oqctl == NULL) {
2010                 CERROR("Can't unpack obd_quatactl\n");
2011                 RETURN(-EPROTO);
2012         }
2013
2014         cli->cl_qchk_stat = oqctl->qc_stat;
2015
2016         return 0;
2017 }
2018
2019 #ifdef HAVE_QUOTA_SUPPORT
2020 int target_handle_dqacq_callback(struct ptlrpc_request *req)
2021 {
2022 #ifdef __KERNEL__
2023         struct obd_device *obd = req->rq_export->exp_obd;
2024         struct obd_device *master_obd;
2025         struct lustre_quota_ctxt *qctxt;
2026         struct qunit_data *qdata = NULL;
2027         int rc = 0;
2028         int repsize[2] = { sizeof(struct ptlrpc_body), 0 };
2029         ENTRY;
2030
2031         if (OBD_FAIL_CHECK_ONCE(OBD_FAIL_MDS_DROP_QUOTA_REQ))
2032                 RETURN(rc);
2033
2034         repsize[1] = quota_get_qunit_data_size(req->rq_export->
2035                                                exp_connect_flags);
2036
2037         rc = lustre_pack_reply(req, 2, repsize, NULL);
2038         if (rc)
2039                 RETURN(rc);
2040
2041         LASSERT(req->rq_export);
2042
2043         /* there are three forms of qunit(historic causes), so we need to
2044          * adjust qunits from slaves to the same form here */
2045         OBD_ALLOC(qdata, sizeof(struct qunit_data));
2046         if (!qdata)
2047                 RETURN(-ENOMEM);
2048         rc = quota_get_qdata(req, qdata, QUOTA_REQUEST, QUOTA_EXPORT);
2049         if (rc < 0) {
2050                 CDEBUG(D_ERROR, "Can't unpack qunit_data(rc: %d)\n", rc);
2051                 GOTO(out, rc);
2052         }
2053
2054         /* we use the observer */
2055         if (!obd->obd_observer || !obd->obd_observer->obd_observer) {
2056                 CERROR("Can't find the observer, it is recovering\n");
2057                 req->rq_status = -EAGAIN;
2058                 GOTO(send_reply, rc = -EAGAIN);
2059         }
2060
2061         master_obd = obd->obd_observer->obd_observer;
2062         qctxt = &master_obd->u.obt.obt_qctxt;
2063
2064         if (!qctxt->lqc_setup) {
2065                 /* quota_type has not been processed yet, return EAGAIN
2066                  * until we know whether or not quotas are supposed to
2067                  * be enabled */
2068                 CDEBUG(D_QUOTA, "quota_type not processed yet, return "
2069                                 "-EAGAIN\n");
2070                 req->rq_status = -EAGAIN;
2071                 rc = ptlrpc_reply(req);
2072                 GOTO(out, rc);
2073         }
2074
2075         LASSERT(qctxt->lqc_handler);
2076         rc = qctxt->lqc_handler(master_obd, qdata,
2077                                 lustre_msg_get_opc(req->rq_reqmsg));
2078         if (rc && rc != -EDQUOT)
2079                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2080                        "dqacq failed! (rc:%d)\n", rc);
2081         req->rq_status = rc;
2082
2083         /* there are three forms of qunit(historic causes), so we need to
2084          * adjust the same form to different forms slaves needed */
2085         rc = quota_copy_qdata(req, qdata, QUOTA_REPLY, QUOTA_EXPORT);
2086         if (rc < 0) {
2087                 CDEBUG(D_ERROR, "Can't pack qunit_data(rc: %d)\n", rc);
2088                 GOTO(out, rc);
2089         }
2090
2091         /* Block the quota req. b=14840 */
2092         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_BLOCK_QUOTA_REQ, obd_timeout);
2093  send_reply:
2094         rc = ptlrpc_reply(req);
2095 out:
2096         OBD_FREE(qdata, sizeof(struct qunit_data));
2097         RETURN(rc);
2098 #else
2099         return 0;
2100 #endif /* !__KERNEL__ */
2101 }
2102 #endif /* HAVE_QUOTA_SUPPORT */
2103
2104 ldlm_mode_t lck_compat_array[] = {
2105         [LCK_EX] LCK_COMPAT_EX,
2106         [LCK_PW] LCK_COMPAT_PW,
2107         [LCK_PR] LCK_COMPAT_PR,
2108         [LCK_CW] LCK_COMPAT_CW,
2109         [LCK_CR] LCK_COMPAT_CR,
2110         [LCK_NL] LCK_COMPAT_NL,
2111         [LCK_GROUP] LCK_COMPAT_GROUP
2112 };