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