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