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