Whamcloud - gitweb
14a0ac71d4b0a69afa46c5f834e2d444359c82f5
[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 <libcfs/libcfs.h>
47 #include <obd.h>
48 #include <obd_class.h>
49 #include <lustre_dlm.h>
50 #include <lustre_net.h>
51 #include <lustre_sec.h>
52 #include "ldlm_internal.h"
53
54 /* @priority: If non-zero, move the selected connection to the list head.
55  * @create: If zero, only search in existing connections.
56  */
57 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
58                            int priority, int create)
59 {
60         struct ptlrpc_connection *ptlrpc_conn;
61         struct obd_import_conn *imp_conn = NULL, *item;
62         int rc = 0;
63         ENTRY;
64
65         if (!create && !priority) {
66                 CDEBUG(D_HA, "Nothing to do\n");
67                 RETURN(-EINVAL);
68         }
69
70         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
71         if (!ptlrpc_conn) {
72                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
73                 RETURN (-ENOENT);
74         }
75
76         if (create) {
77                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
78                 if (!imp_conn) {
79                         GOTO(out_put, rc = -ENOMEM);
80                 }
81         }
82
83         spin_lock(&imp->imp_lock);
84         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
85                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
86                         if (priority) {
87                                 list_del(&item->oic_item);
88                                 list_add(&item->oic_item,
89                                              &imp->imp_conn_list);
90                                 item->oic_last_attempt = 0;
91                         }
92                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
93                                imp, imp->imp_obd->obd_name, uuid->uuid,
94                                (priority ? ", moved to head" : ""));
95                         spin_unlock(&imp->imp_lock);
96                         GOTO(out_free, rc = 0);
97                 }
98         }
99         /* No existing import connection found for \a uuid. */
100         if (create) {
101                 imp_conn->oic_conn = ptlrpc_conn;
102                 imp_conn->oic_uuid = *uuid;
103                 imp_conn->oic_last_attempt = 0;
104                 if (priority)
105                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
106                 else
107                         list_add_tail(&imp_conn->oic_item,
108                                           &imp->imp_conn_list);
109                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
110                        imp, imp->imp_obd->obd_name, uuid->uuid,
111                        (priority ? "head" : "tail"));
112         } else {
113                 spin_unlock(&imp->imp_lock);
114                 GOTO(out_free, rc = -ENOENT);
115         }
116
117         spin_unlock(&imp->imp_lock);
118         RETURN(0);
119 out_free:
120         if (imp_conn)
121                 OBD_FREE(imp_conn, sizeof(*imp_conn));
122 out_put:
123         ptlrpc_connection_put(ptlrpc_conn);
124         RETURN(rc);
125 }
126
127 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
128 {
129         return import_set_conn(imp, uuid, 1, 0);
130 }
131
132 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
133                            int priority)
134 {
135         return import_set_conn(imp, uuid, priority, 1);
136 }
137 EXPORT_SYMBOL(client_import_add_conn);
138
139 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
140 {
141         struct obd_import_conn *imp_conn;
142         struct obd_export *dlmexp;
143         int rc = -ENOENT;
144         ENTRY;
145
146         spin_lock(&imp->imp_lock);
147         if (list_empty(&imp->imp_conn_list)) {
148                 LASSERT(!imp->imp_connection);
149                 GOTO(out, rc);
150         }
151
152         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
153                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
154                         continue;
155                 LASSERT(imp_conn->oic_conn);
156
157                 if (imp_conn == imp->imp_conn_current) {
158                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
159
160                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
161                             imp->imp_state != LUSTRE_IMP_DISCON) {
162                                 CERROR("can't remove current connection\n");
163                                 GOTO(out, rc = -EBUSY);
164                         }
165
166                         ptlrpc_connection_put(imp->imp_connection);
167                         imp->imp_connection = NULL;
168
169                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
170                         if (dlmexp && dlmexp->exp_connection) {
171                                 LASSERT(dlmexp->exp_connection ==
172                                         imp_conn->oic_conn);
173                                 ptlrpc_connection_put(dlmexp->exp_connection);
174                                 dlmexp->exp_connection = NULL;
175                         }
176                 }
177
178                 list_del(&imp_conn->oic_item);
179                 ptlrpc_connection_put(imp_conn->oic_conn);
180                 OBD_FREE(imp_conn, sizeof(*imp_conn));
181                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
182                        imp, imp->imp_obd->obd_name, uuid->uuid);
183                 rc = 0;
184                 break;
185         }
186 out:
187         spin_unlock(&imp->imp_lock);
188         if (rc == -ENOENT)
189                 CERROR("connection %s not found\n", uuid->uuid);
190         RETURN(rc);
191 }
192 EXPORT_SYMBOL(client_import_del_conn);
193
194 /**
195  * Find conn UUID by peer NID. \a peer is a server NID. This function is used
196  * to find a conn uuid of \a imp which can reach \a peer.
197  */
198 int client_import_find_conn(struct obd_import *imp, lnet_nid_t peer,
199                             struct obd_uuid *uuid)
200 {
201         struct obd_import_conn *conn;
202         int rc = -ENOENT;
203         ENTRY;
204
205         spin_lock(&imp->imp_lock);
206         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
207                 /* Check if conn UUID does have this peer NID. */
208                 if (class_check_uuid(&conn->oic_uuid, peer)) {
209                         *uuid = conn->oic_uuid;
210                         rc = 0;
211                         break;
212                 }
213         }
214         spin_unlock(&imp->imp_lock);
215         RETURN(rc);
216 }
217 EXPORT_SYMBOL(client_import_find_conn);
218
219 void client_destroy_import(struct obd_import *imp)
220 {
221         /* Drop security policy instance after all RPCs have finished/aborted
222          * to let all busy contexts be released. */
223         class_import_get(imp);
224         class_destroy_import(imp);
225         sptlrpc_import_sec_put(imp);
226         class_import_put(imp);
227 }
228 EXPORT_SYMBOL(client_destroy_import);
229
230 /**
231  * Check whether or not the OSC is on MDT.
232  * In the config log,
233  * osc on MDT
234  *      setup 0:{fsname}-OSTxxxx-osc[-MDTxxxx] 1:lustre-OST0000_UUID 2:NID
235  * osc on client
236  *      setup 0:{fsname}-OSTxxxx-osc 1:lustre-OST0000_UUID 2:NID
237  *
238  **/
239 static int osc_on_mdt(char *obdname)
240 {
241         char *ptr;
242
243         ptr = strrchr(obdname, '-');
244         if (ptr == NULL)
245                 return 0;
246
247         if (strncmp(ptr + 1, "MDT", 3) == 0)
248                 return 1;
249
250         return 0;
251 }
252
253 /* Configure an RPC client OBD device.
254  *
255  * lcfg parameters:
256  * 1 - client UUID
257  * 2 - server UUID
258  * 3 - inactive-on-startup
259  */
260 int client_obd_setup(struct obd_device *obddev, struct lustre_cfg *lcfg)
261 {
262         struct client_obd *cli = &obddev->u.cli;
263         struct obd_import *imp;
264         struct obd_uuid server_uuid;
265         int rq_portal, rp_portal, connect_op;
266         char *name = obddev->obd_type->typ_name;
267         ldlm_ns_type_t ns_type = LDLM_NS_TYPE_UNKNOWN;
268         int rc;
269         ENTRY;
270
271         /* In a more perfect world, we would hang a ptlrpc_client off of
272          * obd_type and just use the values from there. */
273         if (!strcmp(name, LUSTRE_OSC_NAME)) {
274                 rq_portal = OST_REQUEST_PORTAL;
275                 rp_portal = OSC_REPLY_PORTAL;
276                 connect_op = OST_CONNECT;
277                 cli->cl_sp_me = LUSTRE_SP_CLI;
278                 cli->cl_sp_to = LUSTRE_SP_OST;
279                 ns_type = LDLM_NS_TYPE_OSC;
280         } else if (!strcmp(name, LUSTRE_MDC_NAME) ||
281                    !strcmp(name, LUSTRE_LWP_NAME)) {
282                 rq_portal = MDS_REQUEST_PORTAL;
283                 rp_portal = MDC_REPLY_PORTAL;
284                 connect_op = MDS_CONNECT;
285                 cli->cl_sp_me = LUSTRE_SP_CLI;
286                 cli->cl_sp_to = LUSTRE_SP_MDT;
287                 ns_type = LDLM_NS_TYPE_MDC;
288         } else if (!strcmp(name, LUSTRE_OSP_NAME)) {
289                 if (strstr(lustre_cfg_buf(lcfg, 1), "OST") == NULL) {
290                         /* OSP_on_MDT for other MDTs */
291                         connect_op = MDS_CONNECT;
292                         cli->cl_sp_to = LUSTRE_SP_MDT;
293                         ns_type = LDLM_NS_TYPE_MDC;
294                         rq_portal = OUT_PORTAL;
295                 } else {
296                         /* OSP on MDT for OST */
297                         connect_op = OST_CONNECT;
298                         cli->cl_sp_to = LUSTRE_SP_OST;
299                         ns_type = LDLM_NS_TYPE_OSC;
300                         rq_portal = OST_REQUEST_PORTAL;
301                 }
302                 rp_portal = OSC_REPLY_PORTAL;
303                 cli->cl_sp_me = LUSTRE_SP_CLI;
304         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
305                 rq_portal = MGS_REQUEST_PORTAL;
306                 rp_portal = MGC_REPLY_PORTAL;
307                 connect_op = MGS_CONNECT;
308                 cli->cl_sp_me = LUSTRE_SP_MGC;
309                 cli->cl_sp_to = LUSTRE_SP_MGS;
310                 cli->cl_flvr_mgc.sf_rpc = SPTLRPC_FLVR_INVALID;
311                 ns_type = LDLM_NS_TYPE_MGC;
312         } else {
313                 CERROR("unknown client OBD type \"%s\", can't setup\n",
314                        name);
315                 RETURN(-EINVAL);
316         }
317
318         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
319                 CERROR("requires a TARGET UUID\n");
320                 RETURN(-EINVAL);
321         }
322
323         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
324                 CERROR("client UUID must be less than 38 characters\n");
325                 RETURN(-EINVAL);
326         }
327
328         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
329                 CERROR("setup requires a SERVER UUID\n");
330                 RETURN(-EINVAL);
331         }
332
333         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
334                 CERROR("target UUID must be less than 38 characters\n");
335                 RETURN(-EINVAL);
336         }
337
338         init_rwsem(&cli->cl_sem);
339         mutex_init(&cli->cl_mgc_mutex);
340         cli->cl_conn_count = 0;
341         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
342                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
343                      sizeof(server_uuid)));
344
345         cli->cl_dirty_pages = 0;
346         cli->cl_avail_grant = 0;
347         /* FIXME: Should limit this for the sum of all cl_dirty_max_pages. */
348         /* cl_dirty_max_pages may be changed at connect time in
349          * ptlrpc_connect_interpret(). */
350         client_adjust_max_dirty(cli);
351         INIT_LIST_HEAD(&cli->cl_cache_waiters);
352         INIT_LIST_HEAD(&cli->cl_loi_ready_list);
353         INIT_LIST_HEAD(&cli->cl_loi_hp_ready_list);
354         INIT_LIST_HEAD(&cli->cl_loi_write_list);
355         INIT_LIST_HEAD(&cli->cl_loi_read_list);
356         spin_lock_init(&cli->cl_loi_list_lock);
357         atomic_set(&cli->cl_pending_w_pages, 0);
358         atomic_set(&cli->cl_pending_r_pages, 0);
359         cli->cl_r_in_flight = 0;
360         cli->cl_w_in_flight = 0;
361
362         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
363         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
364         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
365         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
366         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
367         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
368
369         /* lru for osc. */
370         INIT_LIST_HEAD(&cli->cl_lru_osc);
371         atomic_set(&cli->cl_lru_shrinkers, 0);
372         atomic_long_set(&cli->cl_lru_busy, 0);
373         atomic_long_set(&cli->cl_lru_in_list, 0);
374         INIT_LIST_HEAD(&cli->cl_lru_list);
375         spin_lock_init(&cli->cl_lru_list_lock);
376         atomic_long_set(&cli->cl_unstable_count, 0);
377
378         init_waitqueue_head(&cli->cl_destroy_waitq);
379         atomic_set(&cli->cl_destroy_in_flight, 0);
380 #ifdef ENABLE_CHECKSUM
381         /* Turn on checksumming by default. */
382         cli->cl_checksum = 1;
383         /*
384          * The supported checksum types will be worked out at connect time
385          * Set cl_chksum* to CRC32 for now to avoid returning screwed info
386          * through procfs.
387          */
388         cli->cl_cksum_type = cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
389 #endif
390         atomic_set(&cli->cl_resends, OSC_DEFAULT_RESENDS);
391
392         /* This value may be reduced at connect time in
393          * ptlrpc_connect_interpret() . We initialize it to only
394          * 1MB until we know what the performance looks like.
395          * In the future this should likely be increased. LU-1431 */
396         cli->cl_max_pages_per_rpc = min_t(int, PTLRPC_MAX_BRW_PAGES,
397                                           LNET_MTU >> PAGE_CACHE_SHIFT);
398
399         /* set cl_chunkbits default value to PAGE_CACHE_SHIFT,
400          * it will be updated at OSC connection time. */
401         cli->cl_chunkbits = PAGE_CACHE_SHIFT;
402
403         if (!strcmp(name, LUSTRE_MDC_NAME)) {
404                 cli->cl_max_rpcs_in_flight = OBD_MAX_RIF_DEFAULT;
405         } else if (totalram_pages >> (20 - PAGE_CACHE_SHIFT) <= 128 /* MB */) {
406                 cli->cl_max_rpcs_in_flight = 2;
407         } else if (totalram_pages >> (20 - PAGE_CACHE_SHIFT) <= 256 /* MB */) {
408                 cli->cl_max_rpcs_in_flight = 3;
409         } else if (totalram_pages >> (20 - PAGE_CACHE_SHIFT) <= 512 /* MB */) {
410                 cli->cl_max_rpcs_in_flight = 4;
411         } else {
412                 if (osc_on_mdt(obddev->obd_name))
413                         cli->cl_max_rpcs_in_flight = OBD_MAX_RIF_MAX;
414                 else
415                         cli->cl_max_rpcs_in_flight = OBD_MAX_RIF_DEFAULT;
416         }
417         rc = ldlm_get_ref();
418         if (rc) {
419                 CERROR("ldlm_get_ref failed: %d\n", rc);
420                 GOTO(err, rc);
421         }
422
423         ptlrpc_init_client(rq_portal, rp_portal, name,
424                            &obddev->obd_ldlm_client);
425
426         imp = class_new_import(obddev);
427         if (imp == NULL)
428                 GOTO(err_ldlm, rc = -ENOENT);
429         imp->imp_client = &obddev->obd_ldlm_client;
430         imp->imp_connect_op = connect_op;
431         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
432                LUSTRE_CFG_BUFLEN(lcfg, 1));
433         class_import_put(imp);
434
435         rc = client_import_add_conn(imp, &server_uuid, 1);
436         if (rc) {
437                 CERROR("can't add initial connection\n");
438                 GOTO(err_import, rc);
439         }
440
441         cli->cl_import = imp;
442         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
443         cli->cl_max_mds_easize = sizeof(struct lov_mds_md_v3);
444         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
445
446         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
447                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
448                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
449                                name, obddev->obd_name,
450                                cli->cl_target_uuid.uuid);
451                         spin_lock(&imp->imp_lock);
452                         imp->imp_deactive = 1;
453                         spin_unlock(&imp->imp_lock);
454                 }
455         }
456
457         obddev->obd_namespace = ldlm_namespace_new(obddev, obddev->obd_name,
458                                                    LDLM_NAMESPACE_CLIENT,
459                                                    LDLM_NAMESPACE_GREEDY,
460                                                    ns_type);
461         if (obddev->obd_namespace == NULL) {
462                 CERROR("Unable to create client namespace - %s\n",
463                        obddev->obd_name);
464                 GOTO(err_import, rc = -ENOMEM);
465         }
466
467         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
468
469         RETURN(rc);
470
471 err_import:
472         class_destroy_import(imp);
473 err_ldlm:
474         ldlm_put_ref();
475 err:
476         RETURN(rc);
477
478 }
479 EXPORT_SYMBOL(client_obd_setup);
480
481 int client_obd_cleanup(struct obd_device *obddev)
482 {
483         ENTRY;
484
485         ldlm_namespace_free_post(obddev->obd_namespace);
486         obddev->obd_namespace = NULL;
487
488         obd_cleanup_client_import(obddev);
489         LASSERT(obddev->u.cli.cl_import == NULL);
490
491         ldlm_put_ref();
492         RETURN(0);
493 }
494 EXPORT_SYMBOL(client_obd_cleanup);
495
496 /* ->o_connect() method for client side (OSC and MDC and MGC) */
497 int client_connect_import(const struct lu_env *env,
498                           struct obd_export **exp,
499                           struct obd_device *obd, struct obd_uuid *cluuid,
500                           struct obd_connect_data *data, void *localdata)
501 {
502         struct client_obd       *cli    = &obd->u.cli;
503         struct obd_import       *imp    = cli->cl_import;
504         struct obd_connect_data *ocd;
505         struct lustre_handle    conn    = { 0 };
506         int                     rc;
507         ENTRY;
508
509         *exp = NULL;
510         down_write(&cli->cl_sem);
511         if (cli->cl_conn_count > 0)
512                 GOTO(out_sem, rc = -EALREADY);
513
514         rc = class_connect(&conn, obd, cluuid);
515         if (rc)
516                 GOTO(out_sem, rc);
517
518         cli->cl_conn_count++;
519         *exp = class_conn2export(&conn);
520
521         LASSERT(obd->obd_namespace);
522
523         imp->imp_dlm_handle = conn;
524         rc = ptlrpc_init_import(imp);
525         if (rc != 0)
526                 GOTO(out_ldlm, rc);
527
528         ocd = &imp->imp_connect_data;
529         if (data) {
530                 *ocd = *data;
531                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
532         }
533
534         rc = ptlrpc_connect_import(imp);
535         if (rc != 0) {
536                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
537                 GOTO(out_ldlm, rc);
538         }
539         LASSERT(*exp != NULL && (*exp)->exp_connection);
540
541         if (data) {
542                 LASSERTF((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
543                          ocd->ocd_connect_flags, "old "LPX64", new "LPX64"\n",
544                          data->ocd_connect_flags, ocd->ocd_connect_flags);
545                 data->ocd_connect_flags = ocd->ocd_connect_flags;
546         }
547
548         ptlrpc_pinger_add_import(imp);
549
550         EXIT;
551
552         if (rc) {
553 out_ldlm:
554                 cli->cl_conn_count--;
555                 class_disconnect(*exp);
556                 *exp = NULL;
557         }
558 out_sem:
559         up_write(&cli->cl_sem);
560
561         return rc;
562 }
563 EXPORT_SYMBOL(client_connect_import);
564
565 int client_disconnect_export(struct obd_export *exp)
566 {
567         struct obd_device *obd = class_exp2obd(exp);
568         struct client_obd *cli;
569         struct obd_import *imp;
570         int rc = 0, err;
571         ENTRY;
572
573         if (!obd) {
574                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
575                        exp, exp ? exp->exp_handle.h_cookie : -1);
576                 RETURN(-EINVAL);
577         }
578
579         cli = &obd->u.cli;
580         imp = cli->cl_import;
581
582         down_write(&cli->cl_sem);
583         CDEBUG(D_INFO, "disconnect %s - %zu\n", obd->obd_name,
584                 cli->cl_conn_count);
585
586         if (cli->cl_conn_count == 0) {
587                 CERROR("disconnecting disconnected device (%s)\n",
588                        obd->obd_name);
589                 GOTO(out_disconnect, rc = -EINVAL);
590         }
591
592         cli->cl_conn_count--;
593         if (cli->cl_conn_count != 0)
594                 GOTO(out_disconnect, rc = 0);
595
596         /* Mark import deactivated now, so we don't try to reconnect if any
597          * of the cleanup RPCs fails (e.g. LDLM cancel, etc).  We don't
598          * fully deactivate the import, or that would drop all requests. */
599         spin_lock(&imp->imp_lock);
600         imp->imp_deactive = 1;
601         spin_unlock(&imp->imp_lock);
602
603         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
604          * delete it regardless.  (It's safe to delete an import that was
605          * never added.) */
606         (void)ptlrpc_pinger_del_import(imp);
607
608         if (obd->obd_namespace != NULL) {
609                 /* obd_force == local only */
610                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
611                                        obd->obd_force ? LCF_LOCAL : 0, NULL);
612                 ldlm_namespace_free_prior(obd->obd_namespace, imp, obd->obd_force);
613         }
614
615         /* There's no need to hold sem while disconnecting an import,
616          * and it may actually cause deadlock in GSS. */
617         up_write(&cli->cl_sem);
618         rc = ptlrpc_disconnect_import(imp, 0);
619         down_write(&cli->cl_sem);
620
621         ptlrpc_invalidate_import(imp);
622
623         EXIT;
624
625 out_disconnect:
626         /* Use server style - class_disconnect should be always called for
627          * o_disconnect. */
628         err = class_disconnect(exp);
629         if (!rc && err)
630                 rc = err;
631
632         up_write(&cli->cl_sem);
633
634         RETURN(rc);
635 }
636 EXPORT_SYMBOL(client_disconnect_export);
637
638 #ifdef HAVE_SERVER_SUPPORT
639 int server_disconnect_export(struct obd_export *exp)
640 {
641         int rc;
642         ENTRY;
643
644         /* Disconnect early so that clients can't keep using export. */
645         rc = class_disconnect(exp);
646         /* Close import to avoid sending any requests. */
647         if (exp->exp_imp_reverse)
648                 ptlrpc_cleanup_imp(exp->exp_imp_reverse);
649
650         if (exp->exp_obd->obd_namespace != NULL)
651                 ldlm_cancel_locks_for_export(exp);
652
653         /* complete all outstanding replies */
654         spin_lock(&exp->exp_lock);
655         while (!list_empty(&exp->exp_outstanding_replies)) {
656                 struct ptlrpc_reply_state *rs =
657                         list_entry(exp->exp_outstanding_replies.next,
658                                        struct ptlrpc_reply_state, rs_exp_list);
659                 struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
660
661                 spin_lock(&svcpt->scp_rep_lock);
662
663                 list_del_init(&rs->rs_exp_list);
664                 spin_lock(&rs->rs_lock);
665                 ptlrpc_schedule_difficult_reply(rs);
666                 spin_unlock(&rs->rs_lock);
667
668                 spin_unlock(&svcpt->scp_rep_lock);
669         }
670         spin_unlock(&exp->exp_lock);
671
672         RETURN(rc);
673 }
674 EXPORT_SYMBOL(server_disconnect_export);
675
676 /* --------------------------------------------------------------------------
677  * from old lib/target.c
678  * -------------------------------------------------------------------------- */
679
680 static int target_handle_reconnect(struct lustre_handle *conn,
681                                    struct obd_export *exp,
682                                    struct obd_uuid *cluuid)
683 {
684         ENTRY;
685
686         if (exp->exp_connection && exp->exp_imp_reverse) {
687                 struct lustre_handle *hdl;
688                 struct obd_device *target;
689
690                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
691                 target = exp->exp_obd;
692
693                 /* Might be a re-connect after a partition. */
694                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
695                         if (target->obd_recovering) {
696                                 int timeout = cfs_duration_sec(cfs_time_sub(
697                                         cfs_timer_deadline(
698                                         &target->obd_recovery_timer),
699                                         cfs_time_current()));
700
701                                 LCONSOLE_WARN("%s: Client %s (at %s) reconnect"
702                                         "ing, waiting for %d clients in recov"
703                                         "ery for %d:%.02d\n", target->obd_name,
704                                         obd_uuid2str(&exp->exp_client_uuid),
705                                         obd_export_nid2str(exp),
706                                         target->obd_max_recoverable_clients,
707                                         timeout / 60, timeout % 60);
708                         } else {
709                                 LCONSOLE_WARN("%s: Client %s (at %s) "
710                                         "reconnecting\n", target->obd_name,
711                                         obd_uuid2str(&exp->exp_client_uuid),
712                                         obd_export_nid2str(exp));
713                         }
714
715                         conn->cookie = exp->exp_handle.h_cookie;
716                         /* target_handle_connect() treats EALREADY and
717                          * -EALREADY differently.  EALREADY means we are
718                          * doing a valid reconnect from the same client. */
719                         RETURN(EALREADY);
720                 } else {
721                         LCONSOLE_WARN("%s: already connected client %s (at %s) "
722                                       "with handle "LPX64". Rejecting client "
723                                       "with the same UUID trying to reconnect "
724                                       "with handle "LPX64"\n", target->obd_name,
725                                       obd_uuid2str(&exp->exp_client_uuid),
726                                       obd_export_nid2str(exp),
727                                       hdl->cookie, conn->cookie);
728                         memset(conn, 0, sizeof *conn);
729                         /* target_handle_connect() treats EALREADY and
730                          * -EALREADY differently.  -EALREADY is an error
731                          * (same UUID, different handle). */
732                         RETURN(-EALREADY);
733                 }
734         }
735
736         conn->cookie = exp->exp_handle.h_cookie;
737         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
738                cluuid->uuid, exp, conn->cookie);
739         RETURN(0);
740 }
741
742 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
743                           int error)
744 {
745         struct obd_export *exp = cb_data;
746
747         CDEBUG(D_RPCTRACE, "%s: committing for initial connect of %s\n",
748                obd->obd_name, exp->exp_client_uuid.uuid);
749
750         spin_lock(&exp->exp_lock);
751         exp->exp_need_sync = 0;
752         spin_unlock(&exp->exp_lock);
753         class_export_cb_put(exp);
754 }
755 EXPORT_SYMBOL(target_client_add_cb);
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 EXPORT_SYMBOL(target_handle_connect);
1285
1286 int target_handle_disconnect(struct ptlrpc_request *req)
1287 {
1288         int rc;
1289         ENTRY;
1290
1291         rc = req_capsule_server_pack(&req->rq_pill);
1292         if (rc)
1293                 RETURN(rc);
1294
1295         /* Keep the rq_export around so we can send the reply. */
1296         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1297
1298         RETURN(0);
1299 }
1300 EXPORT_SYMBOL(target_handle_disconnect);
1301
1302 void target_destroy_export(struct obd_export *exp)
1303 {
1304         struct obd_import       *imp = NULL;
1305         /* exports created from last_rcvd data, and "fake"
1306            exports created by lctl don't have an import */
1307         spin_lock(&exp->exp_lock);
1308         if (exp->exp_imp_reverse != NULL) {
1309                 imp = exp->exp_imp_reverse;
1310                 exp->exp_imp_reverse = NULL;
1311         }
1312         spin_unlock(&exp->exp_lock);
1313         if (imp != NULL)
1314                 client_destroy_import(imp);
1315
1316         LASSERT_ATOMIC_ZERO(&exp->exp_locks_count);
1317         LASSERT_ATOMIC_ZERO(&exp->exp_rpc_count);
1318         LASSERT_ATOMIC_ZERO(&exp->exp_cb_count);
1319         LASSERT_ATOMIC_ZERO(&exp->exp_replay_count);
1320 }
1321 EXPORT_SYMBOL(target_destroy_export);
1322
1323 /*
1324  * Recovery functions
1325  */
1326 static void target_request_copy_get(struct ptlrpc_request *req)
1327 {
1328         class_export_rpc_inc(req->rq_export);
1329         LASSERT(list_empty(&req->rq_list));
1330         INIT_LIST_HEAD(&req->rq_replay_list);
1331
1332         /* Increase refcount to keep request in queue. */
1333         atomic_inc(&req->rq_refcount);
1334         /* Let export know it has replays to be handled. */
1335         atomic_inc(&req->rq_export->exp_replay_count);
1336 }
1337
1338 static void target_request_copy_put(struct ptlrpc_request *req)
1339 {
1340         LASSERT(list_empty(&req->rq_replay_list));
1341         LASSERT_ATOMIC_POS(&req->rq_export->exp_replay_count);
1342
1343         atomic_dec(&req->rq_export->exp_replay_count);
1344         class_export_rpc_dec(req->rq_export);
1345         ptlrpc_server_drop_request(req);
1346 }
1347
1348 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1349 {
1350         __u64                  transno = lustre_msg_get_transno(req->rq_reqmsg);
1351         struct obd_export     *exp = req->rq_export;
1352         struct ptlrpc_request *reqiter;
1353         int                    dup = 0;
1354
1355         LASSERT(exp);
1356
1357         spin_lock(&exp->exp_lock);
1358         list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1359                                 rq_replay_list) {
1360                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1361                         dup = 1;
1362                         break;
1363                 }
1364         }
1365
1366         if (dup) {
1367                 /* We expect it with RESENT and REPLAY flags. */
1368                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1369                      (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1370                         CERROR("invalid flags %x of resent replay\n",
1371                                lustre_msg_get_flags(req->rq_reqmsg));
1372         } else {
1373                 list_add_tail(&req->rq_replay_list,
1374                                   &exp->exp_req_replay_queue);
1375         }
1376
1377         spin_unlock(&exp->exp_lock);
1378         return dup;
1379 }
1380
1381 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1382 {
1383         LASSERT(!list_empty(&req->rq_replay_list));
1384         LASSERT(req->rq_export);
1385
1386         spin_lock(&req->rq_export->exp_lock);
1387         list_del_init(&req->rq_replay_list);
1388         spin_unlock(&req->rq_export->exp_lock);
1389 }
1390
1391 static void target_finish_recovery(struct obd_device *obd)
1392 {
1393         ENTRY;
1394
1395         /* Only log a recovery message when recovery has occurred. */
1396         if (obd->obd_recovery_start) {
1397                 time_t elapsed_time = max_t(time_t, 1, cfs_time_current_sec() -
1398                                         obd->obd_recovery_start);
1399                 LCONSOLE_INFO("%s: Recovery over after %d:%.02d, of %d clients "
1400                         "%d recovered and %d %s evicted.\n", obd->obd_name,
1401                         (int)elapsed_time / 60, (int)elapsed_time % 60,
1402                         obd->obd_max_recoverable_clients,
1403                         atomic_read(&obd->obd_connected_clients),
1404                         obd->obd_stale_clients,
1405                         obd->obd_stale_clients == 1 ? "was" : "were");
1406         }
1407
1408         ldlm_reprocess_all_ns(obd->obd_namespace);
1409         spin_lock(&obd->obd_recovery_task_lock);
1410         if (!list_empty(&obd->obd_req_replay_queue) ||
1411             !list_empty(&obd->obd_lock_replay_queue) ||
1412             !list_empty(&obd->obd_final_req_queue)) {
1413                 CERROR("%s: Recovery queues ( %s%s%s) are not empty\n",
1414                        obd->obd_name,
1415                        list_empty(&obd->obd_req_replay_queue) ? "" : "req ",
1416                        list_empty(&obd->obd_lock_replay_queue) ? \
1417                                "" : "lock ",
1418                        list_empty(&obd->obd_final_req_queue) ? \
1419                                "" : "final ");
1420                 spin_unlock(&obd->obd_recovery_task_lock);
1421                 LBUG();
1422         }
1423         spin_unlock(&obd->obd_recovery_task_lock);
1424
1425         obd->obd_recovery_end = cfs_time_current_sec();
1426
1427         /* When recovery finished, cleanup orphans on MDS and OST. */
1428         if (OBT(obd) && OBP(obd, postrecov)) {
1429                 int rc = OBP(obd, postrecov)(obd);
1430                 if (rc < 0)
1431                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1432                                       obd->obd_name, rc);
1433         }
1434         EXIT;
1435 }
1436
1437 static void abort_req_replay_queue(struct obd_device *obd)
1438 {
1439         struct ptlrpc_request *req, *n;
1440         struct list_head abort_list;
1441
1442         INIT_LIST_HEAD(&abort_list);
1443         spin_lock(&obd->obd_recovery_task_lock);
1444         list_splice_init(&obd->obd_req_replay_queue, &abort_list);
1445         spin_unlock(&obd->obd_recovery_task_lock);
1446         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1447                 DEBUG_REQ(D_WARNING, req, "aborted:");
1448                 req->rq_status = -ENOTCONN;
1449                 if (ptlrpc_error(req)) {
1450                         DEBUG_REQ(D_ERROR, req,
1451                                   "failed abort_req_reply; skipping");
1452                 }
1453                 target_exp_dequeue_req_replay(req);
1454                 target_request_copy_put(req);
1455         }
1456 }
1457
1458 static void abort_lock_replay_queue(struct obd_device *obd)
1459 {
1460         struct ptlrpc_request *req, *n;
1461         struct list_head abort_list;
1462
1463         INIT_LIST_HEAD(&abort_list);
1464         spin_lock(&obd->obd_recovery_task_lock);
1465         list_splice_init(&obd->obd_lock_replay_queue, &abort_list);
1466         spin_unlock(&obd->obd_recovery_task_lock);
1467         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1468                 DEBUG_REQ(D_ERROR, req, "aborted:");
1469                 req->rq_status = -ENOTCONN;
1470                 if (ptlrpc_error(req)) {
1471                         DEBUG_REQ(D_ERROR, req,
1472                                   "failed abort_lock_reply; skipping");
1473                 }
1474                 target_request_copy_put(req);
1475         }
1476 }
1477
1478 /* Called from a cleanup function if the device is being cleaned up
1479    forcefully.  The exports should all have been disconnected already,
1480    the only thing left to do is
1481      - clear the recovery flags
1482      - cancel the timer
1483      - free queued requests and replies, but don't send replies
1484    Because the obd_stopping flag is set, no new requests should be received.
1485
1486 */
1487 void target_cleanup_recovery(struct obd_device *obd)
1488 {
1489         struct ptlrpc_request *req, *n;
1490         struct list_head clean_list;
1491         ENTRY;
1492
1493         INIT_LIST_HEAD(&clean_list);
1494         spin_lock(&obd->obd_dev_lock);
1495         if (!obd->obd_recovering) {
1496                 spin_unlock(&obd->obd_dev_lock);
1497                 EXIT;
1498                 return;
1499         }
1500         obd->obd_recovering = obd->obd_abort_recovery = 0;
1501         spin_unlock(&obd->obd_dev_lock);
1502
1503         spin_lock(&obd->obd_recovery_task_lock);
1504         target_cancel_recovery_timer(obd);
1505         list_splice_init(&obd->obd_req_replay_queue, &clean_list);
1506         spin_unlock(&obd->obd_recovery_task_lock);
1507
1508         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1509                 LASSERT(req->rq_reply_state == NULL);
1510                 target_exp_dequeue_req_replay(req);
1511                 target_request_copy_put(req);
1512         }
1513
1514         spin_lock(&obd->obd_recovery_task_lock);
1515         list_splice_init(&obd->obd_lock_replay_queue, &clean_list);
1516         list_splice_init(&obd->obd_final_req_queue, &clean_list);
1517         spin_unlock(&obd->obd_recovery_task_lock);
1518
1519         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1520                 LASSERT(req->rq_reply_state == NULL);
1521                 target_request_copy_put(req);
1522         }
1523
1524         EXIT;
1525 }
1526 EXPORT_SYMBOL(target_cleanup_recovery);
1527
1528 /* obd_recovery_task_lock should be held */
1529 void target_cancel_recovery_timer(struct obd_device *obd)
1530 {
1531         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1532         cfs_timer_disarm(&obd->obd_recovery_timer);
1533 }
1534 EXPORT_SYMBOL(target_cancel_recovery_timer);
1535
1536 static void target_start_recovery_timer(struct obd_device *obd)
1537 {
1538         if (obd->obd_recovery_start != 0)
1539                 return;
1540
1541         spin_lock(&obd->obd_dev_lock);
1542         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1543                 spin_unlock(&obd->obd_dev_lock);
1544                 return;
1545         }
1546
1547         LASSERT(obd->obd_recovery_timeout != 0);
1548
1549         if (obd->obd_recovery_start != 0) {
1550                 spin_unlock(&obd->obd_dev_lock);
1551                 return;
1552         }
1553
1554         cfs_timer_arm(&obd->obd_recovery_timer,
1555                       cfs_time_shift(obd->obd_recovery_timeout));
1556         obd->obd_recovery_start = cfs_time_current_sec();
1557         spin_unlock(&obd->obd_dev_lock);
1558
1559         LCONSOLE_WARN("%s: Will be in recovery for at least %d:%.02d, "
1560                       "or until %d client%s reconnect%s\n",
1561                       obd->obd_name,
1562                       obd->obd_recovery_timeout / 60,
1563                       obd->obd_recovery_timeout % 60,
1564                       obd->obd_max_recoverable_clients,
1565                       (obd->obd_max_recoverable_clients == 1) ? "" : "s",
1566                       (obd->obd_max_recoverable_clients == 1) ? "s": "");
1567 }
1568
1569 /**
1570  * extend recovery window.
1571  *
1572  * if @extend is true, extend recovery window to have @drt remaining at least;
1573  * otherwise, make sure the recovery timeout value is not less than @drt.
1574  */
1575 static void extend_recovery_timer(struct obd_device *obd, int drt, bool extend)
1576 {
1577         cfs_time_t now;
1578         cfs_time_t end;
1579         cfs_duration_t left;
1580         int to;
1581
1582         spin_lock(&obd->obd_dev_lock);
1583         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1584                 spin_unlock(&obd->obd_dev_lock);
1585                 return;
1586         }
1587         LASSERT(obd->obd_recovery_start != 0);
1588
1589         now  = cfs_time_current_sec();
1590         to   = obd->obd_recovery_timeout;
1591         end  = obd->obd_recovery_start + to;
1592         left = cfs_time_sub(end, now);
1593
1594         if (extend && (drt > left)) {
1595                 to += drt - left;
1596         } else if (!extend && (drt > to)) {
1597                 to = drt;
1598         }
1599
1600         if (to > obd->obd_recovery_time_hard)
1601                 to = obd->obd_recovery_time_hard;
1602         if (obd->obd_recovery_timeout < to) {
1603                 obd->obd_recovery_timeout = to;
1604                 end = obd->obd_recovery_start + to;
1605                 cfs_timer_arm(&obd->obd_recovery_timer,
1606                                 cfs_time_shift(end - now));
1607         }
1608         spin_unlock(&obd->obd_dev_lock);
1609
1610         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n",
1611                 obd->obd_name, (unsigned)cfs_time_sub(end, now));
1612 }
1613
1614 /* Reset the timer with each new client connection */
1615 /*
1616  * This timer is actually reconnect_timer, which is for making sure
1617  * the total recovery window is at least as big as my reconnect
1618  * attempt timing. So the initial recovery time_out will be set to
1619  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1620  * from client is bigger than this, then the recovery time_out will
1621  * be extended to make sure the client could be reconnected, in the
1622  * process, the timeout from the new client should be ignored.
1623  */
1624
1625 static void
1626 check_and_start_recovery_timer(struct obd_device *obd,
1627                                struct ptlrpc_request *req,
1628                                int new_client)
1629 {
1630         int service_time = lustre_msg_get_service_time(req->rq_reqmsg);
1631         struct obd_device_target *obt = &obd->u.obt;
1632
1633         if (!new_client && service_time)
1634                 /* Teach server about old server's estimates, as first guess
1635                  * at how long new requests will take. */
1636                 at_measured(&req->rq_rqbd->rqbd_svcpt->scp_at_estimate,
1637                             service_time);
1638
1639         target_start_recovery_timer(obd);
1640
1641         /* Convert the service time to RPC timeout,
1642          * and reuse service_time to limit stack usage. */
1643         service_time = at_est2timeout(service_time);
1644
1645         /* We expect other clients to timeout within service_time, then try
1646          * to reconnect, then try the failover server.  The max delay between
1647          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL. */
1648         service_time += 2 * INITIAL_CONNECT_TIMEOUT;
1649
1650         LASSERT(obt->obt_magic == OBT_MAGIC);
1651         service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
1652         if (service_time > obd->obd_recovery_timeout && !new_client)
1653                 extend_recovery_timer(obd, service_time, false);
1654 }
1655
1656 /** Health checking routines */
1657 static inline int exp_connect_healthy(struct obd_export *exp)
1658 {
1659         return (exp->exp_in_recovery);
1660 }
1661
1662 /** if export done req_replay or has replay in queue */
1663 static inline int exp_req_replay_healthy(struct obd_export *exp)
1664 {
1665         return (!exp->exp_req_replay_needed ||
1666                 atomic_read(&exp->exp_replay_count) > 0);
1667 }
1668 /** if export done lock_replay or has replay in queue */
1669 static inline int exp_lock_replay_healthy(struct obd_export *exp)
1670 {
1671         return (!exp->exp_lock_replay_needed ||
1672                 atomic_read(&exp->exp_replay_count) > 0);
1673 }
1674
1675 static inline int exp_vbr_healthy(struct obd_export *exp)
1676 {
1677         return (!exp->exp_vbr_failed);
1678 }
1679
1680 static inline int exp_finished(struct obd_export *exp)
1681 {
1682         return (exp->exp_in_recovery && !exp->exp_lock_replay_needed);
1683 }
1684
1685 /** Checking routines for recovery */
1686 static int check_for_clients(struct obd_device *obd)
1687 {
1688         unsigned int clnts = atomic_read(&obd->obd_connected_clients);
1689
1690         if (obd->obd_abort_recovery || obd->obd_recovery_expired)
1691                 return 1;
1692         LASSERT(clnts <= obd->obd_max_recoverable_clients);
1693         return (clnts + obd->obd_stale_clients ==
1694                 obd->obd_max_recoverable_clients);
1695 }
1696
1697 static int check_for_next_transno(struct obd_device *obd)
1698 {
1699         struct ptlrpc_request *req = NULL;
1700         int wake_up = 0, connected, completed, queue_len;
1701         __u64 next_transno, req_transno;
1702         ENTRY;
1703
1704         spin_lock(&obd->obd_recovery_task_lock);
1705         if (!list_empty(&obd->obd_req_replay_queue)) {
1706                 req = list_entry(obd->obd_req_replay_queue.next,
1707                                      struct ptlrpc_request, rq_list);
1708                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1709         } else {
1710                 req_transno = 0;
1711         }
1712
1713         connected = atomic_read(&obd->obd_connected_clients);
1714         completed = connected - atomic_read(&obd->obd_req_replay_clients);
1715         queue_len = obd->obd_requests_queued_for_recovery;
1716         next_transno = obd->obd_next_recovery_transno;
1717
1718         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1719                "req_transno: "LPU64", next_transno: "LPU64"\n",
1720                obd->obd_max_recoverable_clients, connected, completed,
1721                queue_len, req_transno, next_transno);
1722
1723         if (obd->obd_abort_recovery) {
1724                 CDEBUG(D_HA, "waking for aborted recovery\n");
1725                 wake_up = 1;
1726         } else if (obd->obd_recovery_expired) {
1727                 CDEBUG(D_HA, "waking for expired recovery\n");
1728                 wake_up = 1;
1729         } else if (req_transno == next_transno) {
1730                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1731                 wake_up = 1;
1732         } else if (queue_len > 0 &&
1733                    queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1734                 int d_lvl = D_HA;
1735                 /** handle gaps occured due to lost reply or VBR */
1736                 LASSERTF(req_transno >= next_transno,
1737                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1738                          req_transno, next_transno);
1739                 if (req_transno > obd->obd_last_committed &&
1740                     !obd->obd_version_recov)
1741                         d_lvl = D_ERROR;
1742                 CDEBUG(d_lvl,
1743                        "%s: waking for gap in transno, VBR is %s (skip: "
1744                        LPD64", ql: %d, comp: %d, conn: %d, next: "LPD64
1745                        ", last_committed: "LPD64")\n",
1746                        obd->obd_name, obd->obd_version_recov ? "ON" : "OFF",
1747                        next_transno, queue_len, completed, connected,
1748                        req_transno, obd->obd_last_committed);
1749                 obd->obd_next_recovery_transno = req_transno;
1750                 wake_up = 1;
1751         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1752                 CDEBUG(D_HA, "waking for completed recovery\n");
1753                 wake_up = 1;
1754         } else if (OBD_FAIL_CHECK(OBD_FAIL_MDS_RECOVERY_ACCEPTS_GAPS)) {
1755                 CDEBUG(D_HA, "accepting transno gaps is explicitly allowed"
1756                        " by fail_lock, waking up ("LPD64")\n", next_transno);
1757                 obd->obd_next_recovery_transno = req_transno;
1758                 wake_up = 1;
1759         }
1760         spin_unlock(&obd->obd_recovery_task_lock);
1761         return wake_up;
1762 }
1763
1764 static int check_for_next_lock(struct obd_device *obd)
1765 {
1766         int wake_up = 0;
1767
1768         spin_lock(&obd->obd_recovery_task_lock);
1769         if (!list_empty(&obd->obd_lock_replay_queue)) {
1770                 CDEBUG(D_HA, "waking for next lock\n");
1771                 wake_up = 1;
1772         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1773                 CDEBUG(D_HA, "waking for completed lock replay\n");
1774                 wake_up = 1;
1775         } else if (obd->obd_abort_recovery) {
1776                 CDEBUG(D_HA, "waking for aborted recovery\n");
1777                 wake_up = 1;
1778         } else if (obd->obd_recovery_expired) {
1779                 CDEBUG(D_HA, "waking for expired recovery\n");
1780                 wake_up = 1;
1781         }
1782         spin_unlock(&obd->obd_recovery_task_lock);
1783
1784         return wake_up;
1785 }
1786
1787 /**
1788  * wait for recovery events,
1789  * check its status with help of check_routine
1790  * evict dead clients via health_check
1791  */
1792 static int target_recovery_overseer(struct obd_device *obd,
1793                                     int (*check_routine)(struct obd_device *),
1794                                     int (*health_check)(struct obd_export *))
1795 {
1796 repeat:
1797         if ((obd->obd_recovery_start != 0) && (cfs_time_current_sec() >=
1798               (obd->obd_recovery_start + obd->obd_recovery_time_hard))) {
1799                 CWARN("recovery is aborted by hard timeout\n");
1800                 obd->obd_abort_recovery = 1;
1801         }
1802
1803         while (wait_event_timeout(obd->obd_next_transno_waitq,
1804                                   check_routine(obd),
1805                                   msecs_to_jiffies(60 * MSEC_PER_SEC)) == 0)
1806                 /* wait indefinitely for event, but don't trigger watchdog */;
1807
1808         if (obd->obd_abort_recovery) {
1809                 CWARN("recovery is aborted, evict exports in recovery\n");
1810                 /** evict exports which didn't finish recovery yet */
1811                 class_disconnect_stale_exports(obd, exp_finished);
1812                 return 1;
1813         } else if (obd->obd_recovery_expired) {
1814                 obd->obd_recovery_expired = 0;
1815                 /** If some clients died being recovered, evict them */
1816                 LCONSOLE_WARN("%s: recovery is timed out, "
1817                               "evict stale exports\n", obd->obd_name);
1818                 /** evict cexports with no replay in queue, they are stalled */
1819                 class_disconnect_stale_exports(obd, health_check);
1820                 /** continue with VBR */
1821                 spin_lock(&obd->obd_dev_lock);
1822                 obd->obd_version_recov = 1;
1823                 spin_unlock(&obd->obd_dev_lock);
1824                 /**
1825                  * reset timer, recovery will proceed with versions now,
1826                  * timeout is set just to handle reconnection delays
1827                  */
1828                 extend_recovery_timer(obd, RECONNECT_DELAY_MAX, true);
1829                 /** Wait for recovery events again, after evicting bad clients */
1830                 goto repeat;
1831         }
1832         return 0;
1833 }
1834
1835 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1836 {
1837         struct ptlrpc_request *req = NULL;
1838         ENTRY;
1839
1840         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1841                 obd->obd_next_recovery_transno);
1842
1843         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_DELAY2, cfs_fail_val);
1844         /** It is needed to extend recovery window above recovery_time_soft.
1845          *  Extending is possible only in the end of recovery window
1846          *  (see more details in handle_recovery_req).
1847          */
1848         CFS_FAIL_TIMEOUT_MS(OBD_FAIL_TGT_REPLAY_DELAY, 300);
1849
1850         if (target_recovery_overseer(obd, check_for_next_transno,
1851                                      exp_req_replay_healthy)) {
1852                 abort_req_replay_queue(obd);
1853                 abort_lock_replay_queue(obd);
1854         }
1855
1856         spin_lock(&obd->obd_recovery_task_lock);
1857         if (!list_empty(&obd->obd_req_replay_queue)) {
1858                 req = list_entry(obd->obd_req_replay_queue.next,
1859                                      struct ptlrpc_request, rq_list);
1860                 list_del_init(&req->rq_list);
1861                 obd->obd_requests_queued_for_recovery--;
1862                 spin_unlock(&obd->obd_recovery_task_lock);
1863         } else {
1864                 spin_unlock(&obd->obd_recovery_task_lock);
1865                 LASSERT(list_empty(&obd->obd_req_replay_queue));
1866                 LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1867                 /** evict exports failed VBR */
1868                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1869         }
1870         RETURN(req);
1871 }
1872
1873 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1874 {
1875         struct ptlrpc_request *req = NULL;
1876
1877         CDEBUG(D_HA, "Waiting for lock\n");
1878         if (target_recovery_overseer(obd, check_for_next_lock,
1879                                      exp_lock_replay_healthy))
1880                 abort_lock_replay_queue(obd);
1881
1882         spin_lock(&obd->obd_recovery_task_lock);
1883         if (!list_empty(&obd->obd_lock_replay_queue)) {
1884                 req = list_entry(obd->obd_lock_replay_queue.next,
1885                                      struct ptlrpc_request, rq_list);
1886                 list_del_init(&req->rq_list);
1887                 spin_unlock(&obd->obd_recovery_task_lock);
1888         } else {
1889                 spin_unlock(&obd->obd_recovery_task_lock);
1890                 LASSERT(list_empty(&obd->obd_lock_replay_queue));
1891                 LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1892                 /** evict exports failed VBR */
1893                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1894         }
1895         return req;
1896 }
1897
1898 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1899 {
1900         struct ptlrpc_request *req = NULL;
1901
1902         spin_lock(&obd->obd_recovery_task_lock);
1903         if (!list_empty(&obd->obd_final_req_queue)) {
1904                 req = list_entry(obd->obd_final_req_queue.next,
1905                                      struct ptlrpc_request, rq_list);
1906                 list_del_init(&req->rq_list);
1907                 spin_unlock(&obd->obd_recovery_task_lock);
1908                 if (req->rq_export->exp_in_recovery) {
1909                         spin_lock(&req->rq_export->exp_lock);
1910                         req->rq_export->exp_in_recovery = 0;
1911                         spin_unlock(&req->rq_export->exp_lock);
1912                 }
1913         } else {
1914                 spin_unlock(&obd->obd_recovery_task_lock);
1915         }
1916         return req;
1917 }
1918
1919 static void handle_recovery_req(struct ptlrpc_thread *thread,
1920                                 struct ptlrpc_request *req,
1921                                 svc_handler_t handler)
1922 {
1923         ENTRY;
1924
1925         /**
1926          * export can be evicted during recovery, no need to handle replays for
1927          * it after that, discard such request silently
1928          */
1929         if (req->rq_export->exp_disconnected)
1930                 RETURN_EXIT;
1931
1932         req->rq_session.lc_thread = thread;
1933         req->rq_svc_thread = thread;
1934         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1935
1936         /* thread context */
1937         lu_context_enter(&thread->t_env->le_ctx);
1938         (void)handler(req);
1939         lu_context_exit(&thread->t_env->le_ctx);
1940
1941         /* don't reset timer for final stage */
1942         if (!exp_finished(req->rq_export)) {
1943                 int to = obd_timeout;
1944
1945                 /**
1946                  * Add request timeout to the recovery time so next request from
1947                  * this client may come in recovery time
1948                  */
1949                 if (!AT_OFF) {
1950                         struct ptlrpc_service_part *svcpt;
1951
1952                         svcpt = req->rq_rqbd->rqbd_svcpt;
1953                         /* If the server sent early reply for this request,
1954                          * the client will recalculate the timeout according to
1955                          * current server estimate service time, so we will
1956                          * use the maxium timeout here for waiting the client
1957                          * sending the next req */
1958                         to = max((int)at_est2timeout(
1959                                  at_get(&svcpt->scp_at_estimate)),
1960                                  (int)lustre_msg_get_timeout(req->rq_reqmsg));
1961                         /* Add 2 net_latency, one for balance rq_deadline
1962                          * (see ptl_send_rpc), one for resend the req to server,
1963                          * Note: client will pack net_latency in replay req
1964                          * (see ptlrpc_replay_req) */
1965                         to += 2 * lustre_msg_get_service_time(req->rq_reqmsg);
1966                 }
1967                 extend_recovery_timer(class_exp2obd(req->rq_export), to, true);
1968         }
1969         EXIT;
1970 }
1971
1972 static int target_recovery_thread(void *arg)
1973 {
1974         struct lu_target *lut = arg;
1975         struct obd_device *obd = lut->lut_obd;
1976         struct ptlrpc_request *req;
1977         struct target_recovery_data *trd = &obd->obd_recovery_data;
1978         unsigned long delta;
1979         struct lu_env *env;
1980         struct ptlrpc_thread *thread = NULL;
1981         int rc = 0;
1982         ENTRY;
1983
1984         unshare_fs_struct();
1985         OBD_ALLOC_PTR(thread);
1986         if (thread == NULL)
1987                 RETURN(-ENOMEM);
1988
1989         OBD_ALLOC_PTR(env);
1990         if (env == NULL) {
1991                 OBD_FREE_PTR(thread);
1992                 RETURN(-ENOMEM);
1993         }
1994
1995         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD);
1996         if (rc) {
1997                 OBD_FREE_PTR(thread);
1998                 OBD_FREE_PTR(env);
1999                 RETURN(rc);
2000         }
2001
2002         thread->t_env = env;
2003         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
2004         env->le_ctx.lc_thread = thread;
2005         tgt_io_thread_init(thread); /* init thread_big_cache for IO requests */
2006         thread->t_watchdog = NULL;
2007
2008         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
2009                current_pid());
2010         trd->trd_processing_task = current_pid();
2011
2012         spin_lock(&obd->obd_dev_lock);
2013         obd->obd_recovering = 1;
2014         spin_unlock(&obd->obd_dev_lock);
2015         complete(&trd->trd_starting);
2016
2017         /* first of all, we have to know the first transno to replay */
2018         if (target_recovery_overseer(obd, check_for_clients,
2019                                      exp_connect_healthy)) {
2020                 abort_req_replay_queue(obd);
2021                 abort_lock_replay_queue(obd);
2022         }
2023
2024         /* next stage: replay requests */
2025         delta = jiffies;
2026         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
2027                atomic_read(&obd->obd_req_replay_clients),
2028                obd->obd_next_recovery_transno);
2029         while ((req = target_next_replay_req(obd))) {
2030                 LASSERT(trd->trd_processing_task == current_pid());
2031                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
2032                           lustre_msg_get_transno(req->rq_reqmsg),
2033                           libcfs_nid2str(req->rq_peer.nid));
2034                 handle_recovery_req(thread, req,
2035                                     trd->trd_recovery_handler);
2036                 /**
2037                  * bz18031: increase next_recovery_transno before
2038                  * target_request_copy_put() will drop exp_rpc reference
2039                  */
2040                 spin_lock(&obd->obd_recovery_task_lock);
2041                 obd->obd_next_recovery_transno++;
2042                 spin_unlock(&obd->obd_recovery_task_lock);
2043                 target_exp_dequeue_req_replay(req);
2044                 target_request_copy_put(req);
2045                 obd->obd_replayed_requests++;
2046         }
2047
2048         /**
2049          * The second stage: replay locks
2050          */
2051         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
2052                atomic_read(&obd->obd_lock_replay_clients));
2053         while ((req = target_next_replay_lock(obd))) {
2054                 LASSERT(trd->trd_processing_task == current_pid());
2055                 DEBUG_REQ(D_HA, req, "processing lock from %s: ",
2056                           libcfs_nid2str(req->rq_peer.nid));
2057                 handle_recovery_req(thread, req,
2058                                     trd->trd_recovery_handler);
2059                 target_request_copy_put(req);
2060                 obd->obd_replayed_locks++;
2061         }
2062
2063         /**
2064          * The third stage: reply on final pings, at this moment all clients
2065          * must have request in final queue
2066          */
2067         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_RECONNECT, cfs_fail_val);
2068         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
2069         /** Update server last boot epoch */
2070         tgt_boot_epoch_update(lut);
2071         /* We drop recoverying flag to forward all new requests
2072          * to regular mds_handle() since now */
2073         spin_lock(&obd->obd_dev_lock);
2074         obd->obd_recovering = obd->obd_abort_recovery = 0;
2075         spin_unlock(&obd->obd_dev_lock);
2076         spin_lock(&obd->obd_recovery_task_lock);
2077         target_cancel_recovery_timer(obd);
2078         spin_unlock(&obd->obd_recovery_task_lock);
2079         while ((req = target_next_final_ping(obd))) {
2080                 LASSERT(trd->trd_processing_task == current_pid());
2081                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
2082                           libcfs_nid2str(req->rq_peer.nid));
2083                 handle_recovery_req(thread, req,
2084                                     trd->trd_recovery_handler);
2085                 /* Because the waiting client can not send ping to server,
2086                  * so we need refresh the last_request_time, to avoid the
2087                  * export is being evicted */
2088                 ptlrpc_update_export_timer(req->rq_export, 0);
2089                 target_request_copy_put(req);
2090         }
2091
2092         delta = jiffies_to_msecs(jiffies - delta) / MSEC_PER_SEC;
2093         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
2094               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
2095         if (delta > OBD_RECOVERY_TIME_SOFT) {
2096                 CWARN("too long recovery - read logs\n");
2097                 libcfs_debug_dumplog();
2098         }
2099
2100         target_finish_recovery(obd);
2101
2102         lu_context_fini(&env->le_ctx);
2103         trd->trd_processing_task = 0;
2104         complete(&trd->trd_finishing);
2105
2106         tgt_io_thread_done(thread);
2107         OBD_FREE_PTR(thread);
2108         OBD_FREE_PTR(env);
2109         RETURN(rc);
2110 }
2111
2112 static int target_start_recovery_thread(struct lu_target *lut,
2113                                         svc_handler_t handler)
2114 {
2115         struct obd_device *obd = lut->lut_obd;
2116         int rc = 0;
2117         struct target_recovery_data *trd = &obd->obd_recovery_data;
2118
2119         memset(trd, 0, sizeof(*trd));
2120         init_completion(&trd->trd_starting);
2121         init_completion(&trd->trd_finishing);
2122         trd->trd_recovery_handler = handler;
2123
2124         if (!IS_ERR(kthread_run(target_recovery_thread,
2125                                 lut, "tgt_recov"))) {
2126                 wait_for_completion(&trd->trd_starting);
2127                 LASSERT(obd->obd_recovering != 0);
2128         } else {
2129                 rc = -ECHILD;
2130         }
2131
2132         return rc;
2133 }
2134
2135 void target_stop_recovery_thread(struct obd_device *obd)
2136 {
2137         if (obd->obd_recovery_data.trd_processing_task > 0) {
2138                 struct target_recovery_data *trd = &obd->obd_recovery_data;
2139                 /** recovery can be done but postrecovery is not yet */
2140                 spin_lock(&obd->obd_dev_lock);
2141                 if (obd->obd_recovering) {
2142                         CERROR("%s: Aborting recovery\n", obd->obd_name);
2143                         obd->obd_abort_recovery = 1;
2144                         wake_up(&obd->obd_next_transno_waitq);
2145                 }
2146                 spin_unlock(&obd->obd_dev_lock);
2147                 wait_for_completion(&trd->trd_finishing);
2148         }
2149 }
2150 EXPORT_SYMBOL(target_stop_recovery_thread);
2151
2152 void target_recovery_fini(struct obd_device *obd)
2153 {
2154         class_disconnect_exports(obd);
2155         target_stop_recovery_thread(obd);
2156         target_cleanup_recovery(obd);
2157 }
2158 EXPORT_SYMBOL(target_recovery_fini);
2159
2160 static void target_recovery_expired(unsigned long castmeharder)
2161 {
2162         struct obd_device *obd = (struct obd_device *)castmeharder;
2163         CDEBUG(D_HA, "%s: recovery timed out; %d clients are still in recovery"
2164                " after %lds (%d clients connected)\n",
2165                obd->obd_name, atomic_read(&obd->obd_lock_replay_clients),
2166                cfs_time_current_sec()- obd->obd_recovery_start,
2167                atomic_read(&obd->obd_connected_clients));
2168
2169         obd->obd_recovery_expired = 1;
2170         wake_up(&obd->obd_next_transno_waitq);
2171 }
2172
2173 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
2174 {
2175         struct obd_device *obd = lut->lut_obd;
2176         if (obd->obd_max_recoverable_clients == 0) {
2177                 /** Update server last boot epoch */
2178                 tgt_boot_epoch_update(lut);
2179                 return;
2180         }
2181
2182         CDEBUG(D_HA, "RECOVERY: service %s, %d recoverable clients, "
2183                "last_transno "LPU64"\n", obd->obd_name,
2184                obd->obd_max_recoverable_clients, obd->obd_last_committed);
2185         LASSERT(obd->obd_stopping == 0);
2186         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
2187         obd->obd_recovery_start = 0;
2188         obd->obd_recovery_end = 0;
2189
2190         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
2191         target_start_recovery_thread(lut, handler);
2192 }
2193 EXPORT_SYMBOL(target_recovery_init);
2194
2195
2196 static int target_process_req_flags(struct obd_device *obd,
2197                                     struct ptlrpc_request *req)
2198 {
2199         struct obd_export *exp = req->rq_export;
2200         LASSERT(exp != NULL);
2201         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2202                 /* client declares he's ready to replay locks */
2203                 spin_lock(&exp->exp_lock);
2204                 if (exp->exp_req_replay_needed) {
2205                         exp->exp_req_replay_needed = 0;
2206                         spin_unlock(&exp->exp_lock);
2207
2208                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
2209                         atomic_dec(&obd->obd_req_replay_clients);
2210                 } else {
2211                         spin_unlock(&exp->exp_lock);
2212                 }
2213         }
2214         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2215                 /* client declares he's ready to complete recovery
2216                  * so, we put the request on th final queue */
2217                 spin_lock(&exp->exp_lock);
2218                 if (exp->exp_lock_replay_needed) {
2219                         exp->exp_lock_replay_needed = 0;
2220                         spin_unlock(&exp->exp_lock);
2221
2222                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
2223                         atomic_dec(&obd->obd_lock_replay_clients);
2224                 } else {
2225                         spin_unlock(&exp->exp_lock);
2226                 }
2227         }
2228         return 0;
2229 }
2230
2231 int target_queue_recovery_request(struct ptlrpc_request *req,
2232                                   struct obd_device *obd)
2233 {
2234         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
2235         struct ptlrpc_request *reqiter;
2236         int inserted = 0;
2237         ENTRY;
2238
2239         if (obd->obd_recovery_data.trd_processing_task == current_pid()) {
2240                 /* Processing the queue right now, don't re-add. */
2241                 RETURN(1);
2242         }
2243
2244         target_process_req_flags(obd, req);
2245
2246         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2247                 /* client declares he's ready to complete recovery
2248                  * so, we put the request on th final queue */
2249                 target_request_copy_get(req);
2250                 DEBUG_REQ(D_HA, req, "queue final req");
2251                 wake_up(&obd->obd_next_transno_waitq);
2252                 spin_lock(&obd->obd_recovery_task_lock);
2253                 if (obd->obd_recovering) {
2254                         list_add_tail(&req->rq_list,
2255                                           &obd->obd_final_req_queue);
2256                 } else {
2257                         spin_unlock(&obd->obd_recovery_task_lock);
2258                         target_request_copy_put(req);
2259                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
2260                 }
2261                 spin_unlock(&obd->obd_recovery_task_lock);
2262                 RETURN(0);
2263         }
2264         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2265                 /* client declares he's ready to replay locks */
2266                 target_request_copy_get(req);
2267                 DEBUG_REQ(D_HA, req, "queue lock replay req");
2268                 wake_up(&obd->obd_next_transno_waitq);
2269                 spin_lock(&obd->obd_recovery_task_lock);
2270                 LASSERT(obd->obd_recovering);
2271                 /* usually due to recovery abort */
2272                 if (!req->rq_export->exp_in_recovery) {
2273                         spin_unlock(&obd->obd_recovery_task_lock);
2274                         target_request_copy_put(req);
2275                         RETURN(-ENOTCONN);
2276                 }
2277                 LASSERT(req->rq_export->exp_lock_replay_needed);
2278                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
2279                 spin_unlock(&obd->obd_recovery_task_lock);
2280                 RETURN(0);
2281         }
2282
2283         /* CAVEAT EMPTOR: The incoming request message has been swabbed
2284          * (i.e. buflens etc are in my own byte order), but type-dependent
2285          * buffers (eg mdt_body, ost_body etc) have NOT been swabbed. */
2286
2287         if (!transno) {
2288                 INIT_LIST_HEAD(&req->rq_list);
2289                 DEBUG_REQ(D_HA, req, "not queueing");
2290                 RETURN(1);
2291         }
2292
2293         /* If we're processing the queue, we want don't want to queue this
2294          * message.
2295          *
2296          * Also, if this request has a transno less than the one we're waiting
2297          * for, we should process it now.  It could (and currently always will)
2298          * be an open request for a descriptor that was opened some time ago.
2299          *
2300          * Also, a resent, replayed request that has already been
2301          * handled will pass through here and be processed immediately.
2302          */
2303         CDEBUG(D_HA, "Next recovery transno: "LPU64
2304                ", current: "LPU64", replaying\n",
2305                obd->obd_next_recovery_transno, transno);
2306         spin_lock(&obd->obd_recovery_task_lock);
2307         if (transno < obd->obd_next_recovery_transno) {
2308                 /* Processing the queue right now, don't re-add. */
2309                 LASSERT(list_empty(&req->rq_list));
2310                 spin_unlock(&obd->obd_recovery_task_lock);
2311                 RETURN(1);
2312         }
2313         spin_unlock(&obd->obd_recovery_task_lock);
2314
2315         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
2316                 RETURN(0);
2317
2318         target_request_copy_get(req);
2319         if (!req->rq_export->exp_in_recovery) {
2320                 target_request_copy_put(req);
2321                 RETURN(-ENOTCONN);
2322         }
2323         LASSERT(req->rq_export->exp_req_replay_needed);
2324
2325         if (target_exp_enqueue_req_replay(req)) {
2326                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
2327                 target_request_copy_put(req);
2328                 RETURN(0);
2329         }
2330
2331         /* XXX O(n^2) */
2332         spin_lock(&obd->obd_recovery_task_lock);
2333         LASSERT(obd->obd_recovering);
2334         list_for_each_entry(reqiter, &obd->obd_req_replay_queue, rq_list) {
2335                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
2336                         list_add_tail(&req->rq_list, &reqiter->rq_list);
2337                         inserted = 1;
2338                         goto added;
2339                 }
2340
2341                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
2342                              transno)) {
2343                         DEBUG_REQ(D_ERROR, req, "dropping replay: transno "
2344                                   "has been claimed by another client");
2345                         spin_unlock(&obd->obd_recovery_task_lock);
2346                         target_exp_dequeue_req_replay(req);
2347                         target_request_copy_put(req);
2348                         RETURN(0);
2349                 }
2350         }
2351 added:
2352         if (!inserted)
2353                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
2354
2355         obd->obd_requests_queued_for_recovery++;
2356         spin_unlock(&obd->obd_recovery_task_lock);
2357         wake_up(&obd->obd_next_transno_waitq);
2358         RETURN(0);
2359 }
2360 EXPORT_SYMBOL(target_queue_recovery_request);
2361
2362 int target_handle_ping(struct ptlrpc_request *req)
2363 {
2364         obd_ping(req->rq_svc_thread->t_env, req->rq_export);
2365         return req_capsule_server_pack(&req->rq_pill);
2366 }
2367 EXPORT_SYMBOL(target_handle_ping);
2368
2369 void target_committed_to_req(struct ptlrpc_request *req)
2370 {
2371         struct obd_export *exp = req->rq_export;
2372
2373         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
2374                 lustre_msg_set_last_committed(req->rq_repmsg,
2375                                               exp->exp_last_committed);
2376         else
2377                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
2378                           "%d)", exp->exp_obd->obd_no_transno,
2379                           req->rq_repmsg == NULL);
2380
2381         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
2382                exp->exp_last_committed, req->rq_transno, req->rq_xid);
2383 }
2384 EXPORT_SYMBOL(target_committed_to_req);
2385
2386 #endif /* HAVE_SERVER_SUPPORT */
2387
2388 /**
2389  * Packs current SLV and Limit into \a req.
2390  */
2391 int target_pack_pool_reply(struct ptlrpc_request *req)
2392 {
2393         struct obd_device *obd;
2394         ENTRY;
2395
2396         /* Check that we still have all structures alive as this may
2397          * be some late RPC at shutdown time. */
2398         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
2399                      !exp_connect_lru_resize(req->rq_export))) {
2400                 lustre_msg_set_slv(req->rq_repmsg, 0);
2401                 lustre_msg_set_limit(req->rq_repmsg, 0);
2402                 RETURN(0);
2403         }
2404
2405         /* OBD is alive here as export is alive, which we checked above. */
2406         obd = req->rq_export->exp_obd;
2407
2408         read_lock(&obd->obd_pool_lock);
2409         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
2410         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
2411         read_unlock(&obd->obd_pool_lock);
2412
2413         RETURN(0);
2414 }
2415 EXPORT_SYMBOL(target_pack_pool_reply);
2416
2417 static int target_send_reply_msg(struct ptlrpc_request *req,
2418                                  int rc, int fail_id)
2419 {
2420         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
2421                 DEBUG_REQ(D_ERROR, req, "dropping reply");
2422                 return (-ECOMM);
2423         }
2424
2425         if (unlikely(rc)) {
2426                 DEBUG_REQ(D_NET, req, "processing error (%d)", rc);
2427                 req->rq_status = rc;
2428                 return (ptlrpc_send_error(req, 1));
2429         } else {
2430                 DEBUG_REQ(D_NET, req, "sending reply");
2431         }
2432
2433         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
2434 }
2435
2436 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
2437 {
2438         struct ptlrpc_service_part *svcpt;
2439         int                        netrc;
2440         struct ptlrpc_reply_state *rs;
2441         struct obd_export         *exp;
2442         ENTRY;
2443
2444         if (req->rq_no_reply) {
2445                 EXIT;
2446                 return;
2447         }
2448
2449         svcpt = req->rq_rqbd->rqbd_svcpt;
2450         rs = req->rq_reply_state;
2451         if (rs == NULL || !rs->rs_difficult) {
2452                 /* no notifiers */
2453                 target_send_reply_msg (req, rc, fail_id);
2454                 EXIT;
2455                 return;
2456         }
2457
2458         /* must be an export if locks saved */
2459         LASSERT(req->rq_export != NULL);
2460         /* req/reply consistent */
2461         LASSERT(rs->rs_svcpt == svcpt);
2462
2463         /* "fresh" reply */
2464         LASSERT(!rs->rs_scheduled);
2465         LASSERT(!rs->rs_scheduled_ever);
2466         LASSERT(!rs->rs_handled);
2467         LASSERT(!rs->rs_on_net);
2468         LASSERT(rs->rs_export == NULL);
2469         LASSERT(list_empty(&rs->rs_obd_list));
2470         LASSERT(list_empty(&rs->rs_exp_list));
2471
2472         exp = class_export_get(req->rq_export);
2473
2474         /* disable reply scheduling while I'm setting up */
2475         rs->rs_scheduled = 1;
2476         rs->rs_on_net    = 1;
2477         rs->rs_xid       = req->rq_xid;
2478         rs->rs_transno   = req->rq_transno;
2479         rs->rs_export    = exp;
2480         rs->rs_opc       = lustre_msg_get_opc(req->rq_reqmsg);
2481
2482         spin_lock(&exp->exp_uncommitted_replies_lock);
2483         CDEBUG(D_NET, "rs transno = "LPU64", last committed = "LPU64"\n",
2484                rs->rs_transno, exp->exp_last_committed);
2485         if (rs->rs_transno > exp->exp_last_committed) {
2486                 /* not committed already */
2487                 list_add_tail(&rs->rs_obd_list,
2488                                   &exp->exp_uncommitted_replies);
2489         }
2490         spin_unlock(&exp->exp_uncommitted_replies_lock);
2491
2492         spin_lock(&exp->exp_lock);
2493         list_add_tail(&rs->rs_exp_list, &exp->exp_outstanding_replies);
2494         spin_unlock(&exp->exp_lock);
2495
2496         netrc = target_send_reply_msg(req, rc, fail_id);
2497
2498         spin_lock(&svcpt->scp_rep_lock);
2499
2500         atomic_inc(&svcpt->scp_nreps_difficult);
2501
2502         if (netrc != 0) {
2503                 /* error sending: reply is off the net.  Also we need +1
2504                  * reply ref until ptlrpc_handle_rs() is done
2505                  * with the reply state (if the send was successful, there
2506                  * would have been +1 ref for the net, which
2507                  * reply_out_callback leaves alone) */
2508                 rs->rs_on_net = 0;
2509                 ptlrpc_rs_addref(rs);
2510         }
2511
2512         spin_lock(&rs->rs_lock);
2513         if (rs->rs_transno <= exp->exp_last_committed ||
2514             (!rs->rs_on_net && !rs->rs_no_ack) ||
2515             list_empty(&rs->rs_exp_list) ||     /* completed already */
2516             list_empty(&rs->rs_obd_list)) {
2517                 CDEBUG(D_HA, "Schedule reply immediately\n");
2518                 ptlrpc_dispatch_difficult_reply(rs);
2519         } else {
2520                 list_add(&rs->rs_list, &svcpt->scp_rep_active);
2521                 rs->rs_scheduled = 0;   /* allow notifier to schedule */
2522         }
2523         spin_unlock(&rs->rs_lock);
2524         spin_unlock(&svcpt->scp_rep_lock);
2525         EXIT;
2526 }
2527 EXPORT_SYMBOL(target_send_reply);
2528
2529 ldlm_mode_t lck_compat_array[] = {
2530         [LCK_EX]    = LCK_COMPAT_EX,
2531         [LCK_PW]    = LCK_COMPAT_PW,
2532         [LCK_PR]    = LCK_COMPAT_PR,
2533         [LCK_CW]    = LCK_COMPAT_CW,
2534         [LCK_CR]    = LCK_COMPAT_CR,
2535         [LCK_NL]    = LCK_COMPAT_NL,
2536         [LCK_GROUP] = LCK_COMPAT_GROUP,
2537         [LCK_COS]   = LCK_COMPAT_COS,
2538 };
2539
2540 /**
2541  * Rather arbitrary mapping from LDLM error codes to errno values. This should
2542  * not escape to the user level.
2543  */
2544 int ldlm_error2errno(ldlm_error_t error)
2545 {
2546         int result;
2547
2548         switch (error) {
2549         case ELDLM_OK:
2550         case ELDLM_LOCK_MATCHED:
2551                 result = 0;
2552                 break;
2553         case ELDLM_LOCK_CHANGED:
2554                 result = -ESTALE;
2555                 break;
2556         case ELDLM_LOCK_ABORTED:
2557                 result = -ENAVAIL;
2558                 break;
2559         case ELDLM_LOCK_REPLACED:
2560                 result = -ESRCH;
2561                 break;
2562         case ELDLM_NO_LOCK_DATA:
2563                 result = -ENOENT;
2564                 break;
2565         case ELDLM_NAMESPACE_EXISTS:
2566                 result = -EEXIST;
2567                 break;
2568         case ELDLM_BAD_NAMESPACE:
2569                 result = -EBADF;
2570                 break;
2571         default:
2572                 if (((int)error) < 0)  /* cast to signed type */
2573                         result = error; /* as ldlm_error_t can be unsigned */
2574                 else {
2575                         CERROR("Invalid DLM result code: %d\n", error);
2576                         result = -EPROTO;
2577                 }
2578         }
2579         return result;
2580 }
2581 EXPORT_SYMBOL(ldlm_error2errno);
2582
2583 /**
2584  * Dual to ldlm_error2errno(): maps errno values back to ldlm_error_t.
2585  */
2586 ldlm_error_t ldlm_errno2error(int err_no)
2587 {
2588         int error;
2589
2590         switch (err_no) {
2591         case 0:
2592                 error = ELDLM_OK;
2593                 break;
2594         case -ESTALE:
2595                 error = ELDLM_LOCK_CHANGED;
2596                 break;
2597         case -ENAVAIL:
2598                 error = ELDLM_LOCK_ABORTED;
2599                 break;
2600         case -ESRCH:
2601                 error = ELDLM_LOCK_REPLACED;
2602                 break;
2603         case -ENOENT:
2604                 error = ELDLM_NO_LOCK_DATA;
2605                 break;
2606         case -EEXIST:
2607                 error = ELDLM_NAMESPACE_EXISTS;
2608                 break;
2609         case -EBADF:
2610                 error = ELDLM_BAD_NAMESPACE;
2611                 break;
2612         default:
2613                 error = err_no;
2614         }
2615         return error;
2616 }
2617 EXPORT_SYMBOL(ldlm_errno2error);
2618
2619 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2620 void ldlm_dump_export_locks(struct obd_export *exp)
2621 {
2622         spin_lock(&exp->exp_locks_list_guard);
2623         if (!list_empty(&exp->exp_locks_list)) {
2624                 struct ldlm_lock *lock;
2625
2626                 CERROR("dumping locks for export %p,"
2627                        "ignore if the unmount doesn't hang\n", exp);
2628                 list_for_each_entry(lock, &exp->exp_locks_list,
2629                                         l_exp_refs_link)
2630                         LDLM_ERROR(lock, "lock:");
2631         }
2632         spin_unlock(&exp->exp_locks_list_guard);
2633 }
2634 #endif
2635
2636 #ifdef HAVE_SERVER_SUPPORT
2637 static int target_bulk_timeout(void *data)
2638 {
2639         ENTRY;
2640         /* We don't fail the connection here, because having the export
2641          * killed makes the (vital) call to commitrw very sad.
2642          */
2643         RETURN(1);
2644 }
2645
2646 static inline char *bulk2type(struct ptlrpc_bulk_desc *desc)
2647 {
2648         return desc->bd_type == BULK_GET_SINK ? "GET" : "PUT";
2649 }
2650
2651 int target_bulk_io(struct obd_export *exp, struct ptlrpc_bulk_desc *desc,
2652                    struct l_wait_info *lwi)
2653 {
2654         struct ptlrpc_request   *req = desc->bd_req;
2655         time_t                   start = cfs_time_current_sec();
2656         time_t                   deadline;
2657         int                      rc = 0;
2658
2659         ENTRY;
2660
2661         /* If there is eviction in progress, wait for it to finish. */
2662         if (unlikely(atomic_read(&exp->exp_obd->obd_evict_inprogress))) {
2663                 *lwi = LWI_INTR(NULL, NULL);
2664                 rc = l_wait_event(exp->exp_obd->obd_evict_inprogress_waitq,
2665                                   !atomic_read(&exp->exp_obd->
2666                                                    obd_evict_inprogress),
2667                                   lwi);
2668         }
2669
2670         /* Check if client was evicted or reconnected already. */
2671         if (exp->exp_failed ||
2672             exp->exp_conn_cnt > lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
2673                 rc = -ENOTCONN;
2674         } else {
2675                 if (desc->bd_type == BULK_PUT_SINK)
2676                         rc = sptlrpc_svc_wrap_bulk(req, desc);
2677                 if (rc == 0)
2678                         rc = ptlrpc_start_bulk_transfer(desc);
2679         }
2680
2681         if (rc < 0) {
2682                 DEBUG_REQ(D_ERROR, req, "bulk %s failed: rc %d",
2683                           bulk2type(desc), rc);
2684                 RETURN(rc);
2685         }
2686
2687         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
2688                 ptlrpc_abort_bulk(desc);
2689                 RETURN(0);
2690         }
2691
2692         /* limit actual bulk transfer to bulk_timeout seconds */
2693         deadline = start + bulk_timeout;
2694         if (deadline > req->rq_deadline)
2695                 deadline = req->rq_deadline;
2696
2697         do {
2698                 long timeoutl = deadline - cfs_time_current_sec();
2699                 cfs_duration_t timeout = timeoutl <= 0 ?
2700                                          CFS_TICK : cfs_time_seconds(timeoutl);
2701                 time_t  rq_deadline;
2702
2703                 *lwi = LWI_TIMEOUT_INTERVAL(timeout, cfs_time_seconds(1),
2704                                             target_bulk_timeout, desc);
2705                 rc = l_wait_event(desc->bd_waitq,
2706                                   !ptlrpc_server_bulk_active(desc) ||
2707                                   exp->exp_failed ||
2708                                   exp->exp_conn_cnt >
2709                                   lustre_msg_get_conn_cnt(req->rq_reqmsg),
2710                                   lwi);
2711                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
2712                 /* Wait again if we changed rq_deadline. */
2713                 rq_deadline = ACCESS_ONCE(req->rq_deadline);
2714                 deadline = start + bulk_timeout;
2715                 if (deadline > rq_deadline)
2716                         deadline = rq_deadline;
2717         } while ((rc == -ETIMEDOUT) &&
2718                  (deadline > cfs_time_current_sec()));
2719
2720         if (rc == -ETIMEDOUT) {
2721                 DEBUG_REQ(D_ERROR, req, "timeout on bulk %s after %ld%+lds",
2722                           bulk2type(desc), deadline - start,
2723                           cfs_time_current_sec() - deadline);
2724                 ptlrpc_abort_bulk(desc);
2725         } else if (exp->exp_failed) {
2726                 DEBUG_REQ(D_ERROR, req, "Eviction on bulk %s",
2727                           bulk2type(desc));
2728                 rc = -ENOTCONN;
2729                 ptlrpc_abort_bulk(desc);
2730         } else if (exp->exp_conn_cnt >
2731                    lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
2732                 DEBUG_REQ(D_ERROR, req, "Reconnect on bulk %s",
2733                           bulk2type(desc));
2734                 /* We don't reply anyway. */
2735                 rc = -ETIMEDOUT;
2736                 ptlrpc_abort_bulk(desc);
2737         } else if (desc->bd_failure ||
2738                    desc->bd_nob_transferred != desc->bd_nob) {
2739                 DEBUG_REQ(D_ERROR, req, "%s bulk %s %d(%d)",
2740                           desc->bd_failure ? "network error on" : "truncated",
2741                           bulk2type(desc), desc->bd_nob_transferred,
2742                           desc->bd_nob);
2743                 /* XXX Should this be a different errno? */
2744                 rc = -ETIMEDOUT;
2745         } else if (desc->bd_type == BULK_GET_SINK) {
2746                 rc = sptlrpc_svc_unwrap_bulk(req, desc);
2747         }
2748
2749         RETURN(rc);
2750 }
2751 EXPORT_SYMBOL(target_bulk_io);
2752
2753 #endif /* HAVE_SERVER_SUPPORT */