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