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