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