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