Whamcloud - gitweb
LU-5396 all: use NULL instead of 0
[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
905         /* lctl gets a backstage, all-access pass. */
906         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
907                 goto dont_check_exports;
908
909         export = cfs_hash_lookup(target->obd_uuid_hash, &cluuid);
910         if (!export)
911                 goto no_export;
912
913         /* We've found an export in the hash. */
914
915         spin_lock(&export->exp_lock);
916
917         if (export->exp_connecting) { /* bug 9635, et. al. */
918                 spin_unlock(&export->exp_lock);
919                 LCONSOLE_WARN("%s: Export %p already connecting from %s\n",
920                               export->exp_obd->obd_name, export,
921                               libcfs_nid2str(req->rq_peer.nid));
922                 class_export_put(export);
923                 export = NULL;
924                 rc = -EALREADY;
925         } else if ((mds_conn || lw_client) && export->exp_connection != NULL) {
926                 spin_unlock(&export->exp_lock);
927                 if (req->rq_peer.nid != export->exp_connection->c_peer.nid)
928                         /* MDS or LWP reconnected after failover. */
929                         LCONSOLE_WARN("%s: Received %s connection from "
930                             "%s, removing former export from %s\n",
931                             target->obd_name, mds_conn ? "MDS" : "LWP",
932                             libcfs_nid2str(req->rq_peer.nid),
933                             libcfs_nid2str(export->exp_connection->c_peer.nid));
934                 else
935                         /* New MDS connection from the same NID. */
936                         LCONSOLE_WARN("%s: Received new %s connection from "
937                                 "%s, removing former export from same NID\n",
938                                 target->obd_name, mds_conn ? "MDS" : "LWP",
939                                 libcfs_nid2str(req->rq_peer.nid));
940                 class_fail_export(export);
941                 class_export_put(export);
942                 export = NULL;
943                 rc = 0;
944         } else if (export->exp_connection != NULL &&
945                    req->rq_peer.nid != export->exp_connection->c_peer.nid &&
946                    (lustre_msg_get_op_flags(req->rq_reqmsg) &
947                     MSG_CONNECT_INITIAL)) {
948                 spin_unlock(&export->exp_lock);
949                 /* In MDS failover we have static UUID but NID can change. */
950                 LCONSOLE_WARN("%s: Client %s seen on new nid %s when "
951                               "existing nid %s is already connected\n",
952                               target->obd_name, cluuid.uuid,
953                               libcfs_nid2str(req->rq_peer.nid),
954                               libcfs_nid2str(
955                                       export->exp_connection->c_peer.nid));
956                 rc = -EALREADY;
957                 class_export_put(export);
958                 export = NULL;
959         } else {
960                 export->exp_connecting = 1;
961                 spin_unlock(&export->exp_lock);
962                 LASSERT(export->exp_obd == target);
963
964                 rc = target_handle_reconnect(&conn, export, &cluuid);
965         }
966
967         /* If we found an export, we already unlocked. */
968         if (!export) {
969 no_export:
970                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
971         } else if (req->rq_export == NULL &&
972                    atomic_read(&export->exp_rpc_count) > 0) {
973                 LCONSOLE_WARN("%s: Client %s (at %s) refused connection, "
974                               "still busy with %d references\n",
975                               target->obd_name, cluuid.uuid,
976                               libcfs_nid2str(req->rq_peer.nid),
977                               atomic_read(&export->exp_refcount));
978                 GOTO(out, rc = -EBUSY);
979         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1) {
980                 if (!strstr(cluuid.uuid, "mdt"))
981                         LCONSOLE_WARN("%s: Rejecting reconnect from the "
982                                       "known client %s (at %s) because it "
983                                       "is indicating it is a new client",
984                                       target->obd_name, cluuid.uuid,
985                                       libcfs_nid2str(req->rq_peer.nid));
986                 GOTO(out, rc = -EALREADY);
987         } else {
988                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
989         }
990
991         if (rc < 0) {
992                 GOTO(out, rc);
993         }
994
995         CDEBUG(D_HA, "%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
996                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
997               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
998               export, (long)cfs_time_current_sec(),
999               export ? (long)export->exp_last_request_time : 0);
1000
1001         /* If this is the first time a client connects, reset the recovery
1002          * timer. Discard lightweight connections which might be local. */
1003         if (!lw_client && rc == 0 && target->obd_recovering)
1004                 check_and_start_recovery_timer(target, req, export == NULL);
1005
1006         /* We want to handle EALREADY but *not* -EALREADY from
1007          * target_handle_reconnect(), return reconnection state in a flag. */
1008         if (rc == EALREADY) {
1009                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
1010                 rc = 0;
1011         } else {
1012                 LASSERT(rc == 0);
1013         }
1014
1015         /* Tell the client if we support replayable requests. */
1016         if (target->obd_replayable)
1017                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
1018         client_nid = &req->rq_peer.nid;
1019
1020         if (export == NULL) {
1021                 /* allow lightweight connections during recovery */
1022                 if (target->obd_recovering && !lw_client) {
1023                         cfs_time_t t;
1024                         int     c; /* connected */
1025                         int     i; /* in progress */
1026                         int     k; /* known */
1027                         int     s; /* stale/evicted */
1028
1029                         c = atomic_read(&target->obd_connected_clients);
1030                         i = atomic_read(&target->obd_lock_replay_clients);
1031                         k = target->obd_max_recoverable_clients;
1032                         s = target->obd_stale_clients;
1033                         t = cfs_timer_deadline(&target->obd_recovery_timer);
1034                         t = cfs_time_sub(t, cfs_time_current());
1035                         t = cfs_duration_sec(t);
1036                         LCONSOLE_WARN("%s: Denying connection for new client "
1037                                       "%s (at %s), waiting for all %d known "
1038                                       "clients (%d recovered, %d in progress, "
1039                                       "and %d evicted) to recover in %d:%.02d\n",
1040                                       target->obd_name, cluuid.uuid,
1041                                       libcfs_nid2str(req->rq_peer.nid), k,
1042                                       c - i, i, s, (int)t / 60,
1043                                       (int)t % 60);
1044                         rc = -EBUSY;
1045                 } else {
1046 dont_check_exports:
1047                         rc = obd_connect(req->rq_svc_thread->t_env,
1048                                          &export, target, &cluuid, data,
1049                                          client_nid);
1050                         if (mds_conn && OBD_FAIL_CHECK(OBD_FAIL_TGT_RCVG_FLAG))
1051                                 lustre_msg_add_op_flags(req->rq_repmsg,
1052                                                 MSG_CONNECT_RECOVERING);
1053                         if (rc == 0)
1054                                 conn.cookie = export->exp_handle.h_cookie;
1055                 }
1056         } else {
1057                 rc = obd_reconnect(req->rq_svc_thread->t_env,
1058                                    export, target, &cluuid, data, client_nid);
1059         }
1060         if (rc)
1061                 GOTO(out, rc);
1062
1063         LASSERT(target->u.obt.obt_magic == OBT_MAGIC);
1064         data->ocd_instance = target->u.obt.obt_instance;
1065
1066         /* Return only the parts of obd_connect_data that we understand, so the
1067          * client knows that we don't understand the rest. */
1068         if (data) {
1069                 tmpsize = req_capsule_get_size(&req->rq_pill, &RMF_CONNECT_DATA,
1070                                                RCL_SERVER);
1071                 tmpdata = req_capsule_server_get(&req->rq_pill,
1072                                                  &RMF_CONNECT_DATA);
1073                 /* Don't use struct assignment here, because the client reply
1074                  * buffer may be smaller/larger than the local struct
1075                  * obd_connect_data. */
1076                 memcpy(tmpdata, data, min(tmpsize, size));
1077         }
1078
1079         /* If all else goes well, this is our RPC return code. */
1080         req->rq_status = 0;
1081
1082         lustre_msg_set_handle(req->rq_repmsg, &conn);
1083
1084         /* If the client and the server are the same node, we will already
1085          * have an export that really points to the client's DLM export,
1086          * because we have a shared handles table.
1087          *
1088          * XXX this will go away when shaver stops sending the "connect" handle
1089          * in the real "remote handle" field of the request --phik 24 Apr 2003
1090          */
1091         ptlrpc_request_change_export(req, export);
1092
1093         spin_lock(&export->exp_lock);
1094         if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
1095                 spin_unlock(&export->exp_lock);
1096                 CDEBUG(D_RPCTRACE, "%s: %s already connected at greater "
1097                        "or equal conn_cnt: %d >= %d\n",
1098                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
1099                        export->exp_conn_cnt,
1100                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
1101
1102                 GOTO(out, rc = -EALREADY);
1103         }
1104         LASSERT(lustre_msg_get_conn_cnt(req->rq_reqmsg) > 0);
1105         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
1106
1107         /* Don't evict liblustre clients for not pinging. */
1108         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
1109                 export->exp_libclient = 1;
1110                 spin_unlock(&export->exp_lock);
1111
1112                 spin_lock(&target->obd_dev_lock);
1113                 list_del_init(&export->exp_obd_chain_timed);
1114                 spin_unlock(&target->obd_dev_lock);
1115         } else {
1116                 spin_unlock(&export->exp_lock);
1117         }
1118
1119         if (export->exp_connection != NULL) {
1120                 /* Check to see if connection came from another NID. */
1121                 if ((export->exp_connection->c_peer.nid != req->rq_peer.nid) &&
1122                     !hlist_unhashed(&export->exp_nid_hash))
1123                         cfs_hash_del(export->exp_obd->obd_nid_hash,
1124                                      &export->exp_connection->c_peer.nid,
1125                                      &export->exp_nid_hash);
1126
1127                 ptlrpc_connection_put(export->exp_connection);
1128         }
1129
1130         export->exp_connection = ptlrpc_connection_get(req->rq_peer,
1131                                                        req->rq_self,
1132                                                        &remote_uuid);
1133         if (hlist_unhashed(&export->exp_nid_hash)) {
1134                 cfs_hash_add(export->exp_obd->obd_nid_hash,
1135                              &export->exp_connection->c_peer.nid,
1136                              &export->exp_nid_hash);
1137         }
1138
1139         if (target->obd_recovering && !export->exp_in_recovery && !lw_client) {
1140                 int has_transno;
1141                 __u64 transno = data->ocd_transno;
1142
1143                 spin_lock(&export->exp_lock);
1144                 /* possible race with class_disconnect_stale_exports,
1145                  * export may be already in the eviction process */
1146                 if (export->exp_failed) {
1147                         spin_unlock(&export->exp_lock);
1148                         GOTO(out, rc = -ENODEV);
1149                 }
1150                 export->exp_in_recovery = 1;
1151                 export->exp_req_replay_needed = 1;
1152                 export->exp_lock_replay_needed = 1;
1153                 spin_unlock(&export->exp_lock);
1154
1155                 has_transno = !!(lustre_msg_get_op_flags(req->rq_reqmsg) &
1156                                  MSG_CONNECT_TRANSNO);
1157                 if (has_transno && transno == 0)
1158                         CWARN("Connect with zero transno!\n");
1159
1160                 if (has_transno && transno > 0 &&
1161                     transno < target->obd_next_recovery_transno &&
1162                     transno > target->obd_last_committed) {
1163                         /* Another way is to use cmpxchg() to be lock-free. */
1164                         spin_lock(&target->obd_recovery_task_lock);
1165                         if (transno < target->obd_next_recovery_transno)
1166                                 target->obd_next_recovery_transno = transno;
1167                         spin_unlock(&target->obd_recovery_task_lock);
1168                 }
1169
1170                 atomic_inc(&target->obd_req_replay_clients);
1171                 atomic_inc(&target->obd_lock_replay_clients);
1172                 if (atomic_inc_return(&target->obd_connected_clients) ==
1173                     target->obd_max_recoverable_clients)
1174                         wake_up(&target->obd_next_transno_waitq);
1175         }
1176
1177         /* Tell the client we're in recovery, when client is involved in it. */
1178         if (target->obd_recovering && !lw_client)
1179                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
1180
1181         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
1182         conn = *tmp;
1183
1184         /* Return -ENOTCONN in case of errors to let client reconnect. */
1185         revimp = class_new_import(target);
1186         if (revimp == NULL) {
1187                 CERROR("fail to alloc new reverse import.\n");
1188                 GOTO(out, rc = -ENOTCONN);
1189         }
1190
1191         spin_lock(&export->exp_lock);
1192         if (export->exp_imp_reverse != NULL)
1193                 /* destroyed import can be still referenced in ctxt */
1194                 tmp_imp = export->exp_imp_reverse;
1195         export->exp_imp_reverse = revimp;
1196         spin_unlock(&export->exp_lock);
1197
1198         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
1199         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
1200         revimp->imp_remote_handle = conn;
1201         revimp->imp_dlm_fake = 1;
1202         revimp->imp_state = LUSTRE_IMP_FULL;
1203
1204         /* Unknown versions will be caught in
1205          * ptlrpc_handle_server_req_in->lustre_unpack_msg(). */
1206         revimp->imp_msg_magic = req->rq_reqmsg->lm_magic;
1207
1208         if ((data->ocd_connect_flags & OBD_CONNECT_AT) &&
1209             (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1))
1210                 revimp->imp_msghdr_flags |= MSGHDR_AT_SUPPORT;
1211         else
1212                 revimp->imp_msghdr_flags &= ~MSGHDR_AT_SUPPORT;
1213
1214         if ((data->ocd_connect_flags & OBD_CONNECT_FULL20) &&
1215             (revimp->imp_msg_magic != LUSTRE_MSG_MAGIC_V1))
1216                 revimp->imp_msghdr_flags |= MSGHDR_CKSUM_INCOMPAT18;
1217         else
1218                 revimp->imp_msghdr_flags &= ~MSGHDR_CKSUM_INCOMPAT18;
1219
1220         rc = sptlrpc_import_sec_adapt(revimp, req->rq_svc_ctx, &req->rq_flvr);
1221         if (rc) {
1222                 CERROR("Failed to get sec for reverse import: %d\n", rc);
1223                 spin_lock(&export->exp_lock);
1224                 export->exp_imp_reverse = NULL;
1225                 spin_unlock(&export->exp_lock);
1226                 class_destroy_import(revimp);
1227         }
1228
1229         class_import_put(revimp);
1230
1231 out:
1232         if (tmp_imp != NULL)
1233                 client_destroy_import(tmp_imp);
1234         if (export) {
1235                 spin_lock(&export->exp_lock);
1236                 export->exp_connecting = 0;
1237                 spin_unlock(&export->exp_lock);
1238
1239                 class_export_put(export);
1240         }
1241         if (targref) {
1242                 spin_lock(&target->obd_dev_lock);
1243                 target->obd_conn_inprogress--;
1244                 spin_unlock(&target->obd_dev_lock);
1245
1246                 class_decref(targref, __func__, current);
1247         }
1248         if (rc)
1249                 req->rq_status = rc;
1250         RETURN(rc);
1251 }
1252 EXPORT_SYMBOL(target_handle_connect);
1253
1254 int target_handle_disconnect(struct ptlrpc_request *req)
1255 {
1256         int rc;
1257         ENTRY;
1258
1259         rc = req_capsule_server_pack(&req->rq_pill);
1260         if (rc)
1261                 RETURN(rc);
1262
1263         /* Keep the rq_export around so we can send the reply. */
1264         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1265
1266         RETURN(0);
1267 }
1268 EXPORT_SYMBOL(target_handle_disconnect);
1269
1270 void target_destroy_export(struct obd_export *exp)
1271 {
1272         struct obd_import       *imp = NULL;
1273         /* exports created from last_rcvd data, and "fake"
1274            exports created by lctl don't have an import */
1275         spin_lock(&exp->exp_lock);
1276         if (exp->exp_imp_reverse != NULL) {
1277                 imp = exp->exp_imp_reverse;
1278                 exp->exp_imp_reverse = NULL;
1279         }
1280         spin_unlock(&exp->exp_lock);
1281         if (imp != NULL)
1282                 client_destroy_import(imp);
1283
1284         LASSERT_ATOMIC_ZERO(&exp->exp_locks_count);
1285         LASSERT_ATOMIC_ZERO(&exp->exp_rpc_count);
1286         LASSERT_ATOMIC_ZERO(&exp->exp_cb_count);
1287         LASSERT_ATOMIC_ZERO(&exp->exp_replay_count);
1288 }
1289 EXPORT_SYMBOL(target_destroy_export);
1290
1291 /*
1292  * Recovery functions
1293  */
1294 static void target_request_copy_get(struct ptlrpc_request *req)
1295 {
1296         class_export_rpc_inc(req->rq_export);
1297         LASSERT(list_empty(&req->rq_list));
1298         INIT_LIST_HEAD(&req->rq_replay_list);
1299
1300         /* Increase refcount to keep request in queue. */
1301         atomic_inc(&req->rq_refcount);
1302         /* Let export know it has replays to be handled. */
1303         atomic_inc(&req->rq_export->exp_replay_count);
1304 }
1305
1306 static void target_request_copy_put(struct ptlrpc_request *req)
1307 {
1308         LASSERT(list_empty(&req->rq_replay_list));
1309         LASSERT_ATOMIC_POS(&req->rq_export->exp_replay_count);
1310
1311         atomic_dec(&req->rq_export->exp_replay_count);
1312         class_export_rpc_dec(req->rq_export);
1313         ptlrpc_server_drop_request(req);
1314 }
1315
1316 static int target_exp_enqueue_req_replay(struct ptlrpc_request *req)
1317 {
1318         __u64                  transno = lustre_msg_get_transno(req->rq_reqmsg);
1319         struct obd_export     *exp = req->rq_export;
1320         struct ptlrpc_request *reqiter;
1321         int                    dup = 0;
1322
1323         LASSERT(exp);
1324
1325         spin_lock(&exp->exp_lock);
1326         list_for_each_entry(reqiter, &exp->exp_req_replay_queue,
1327                                 rq_replay_list) {
1328                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) == transno) {
1329                         dup = 1;
1330                         break;
1331                 }
1332         }
1333
1334         if (dup) {
1335                 /* We expect it with RESENT and REPLAY flags. */
1336                 if ((lustre_msg_get_flags(req->rq_reqmsg) &
1337                      (MSG_RESENT | MSG_REPLAY)) != (MSG_RESENT | MSG_REPLAY))
1338                         CERROR("invalid flags %x of resent replay\n",
1339                                lustre_msg_get_flags(req->rq_reqmsg));
1340         } else {
1341                 list_add_tail(&req->rq_replay_list,
1342                                   &exp->exp_req_replay_queue);
1343         }
1344
1345         spin_unlock(&exp->exp_lock);
1346         return dup;
1347 }
1348
1349 static void target_exp_dequeue_req_replay(struct ptlrpc_request *req)
1350 {
1351         LASSERT(!list_empty(&req->rq_replay_list));
1352         LASSERT(req->rq_export);
1353
1354         spin_lock(&req->rq_export->exp_lock);
1355         list_del_init(&req->rq_replay_list);
1356         spin_unlock(&req->rq_export->exp_lock);
1357 }
1358
1359 static void target_finish_recovery(struct obd_device *obd)
1360 {
1361         ENTRY;
1362
1363         /* Only log a recovery message when recovery has occurred. */
1364         if (obd->obd_recovery_start) {
1365                 time_t elapsed_time = max_t(time_t, 1, cfs_time_current_sec() -
1366                                         obd->obd_recovery_start);
1367                 LCONSOLE_INFO("%s: Recovery over after %d:%.02d, of %d clients "
1368                         "%d recovered and %d %s evicted.\n", obd->obd_name,
1369                         (int)elapsed_time / 60, (int)elapsed_time % 60,
1370                         obd->obd_max_recoverable_clients,
1371                         atomic_read(&obd->obd_connected_clients),
1372                         obd->obd_stale_clients,
1373                         obd->obd_stale_clients == 1 ? "was" : "were");
1374         }
1375
1376         ldlm_reprocess_all_ns(obd->obd_namespace);
1377         spin_lock(&obd->obd_recovery_task_lock);
1378         if (!list_empty(&obd->obd_req_replay_queue) ||
1379             !list_empty(&obd->obd_lock_replay_queue) ||
1380             !list_empty(&obd->obd_final_req_queue)) {
1381                 CERROR("%s: Recovery queues ( %s%s%s) are not empty\n",
1382                        obd->obd_name,
1383                        list_empty(&obd->obd_req_replay_queue) ? "" : "req ",
1384                        list_empty(&obd->obd_lock_replay_queue) ? \
1385                                "" : "lock ",
1386                        list_empty(&obd->obd_final_req_queue) ? \
1387                                "" : "final ");
1388                 spin_unlock(&obd->obd_recovery_task_lock);
1389                 LBUG();
1390         }
1391         spin_unlock(&obd->obd_recovery_task_lock);
1392
1393         obd->obd_recovery_end = cfs_time_current_sec();
1394
1395         /* When recovery finished, cleanup orphans on MDS and OST. */
1396         if (OBT(obd) && OBP(obd, postrecov)) {
1397                 int rc = OBP(obd, postrecov)(obd);
1398                 if (rc < 0)
1399                         LCONSOLE_WARN("%s: Post recovery failed, rc %d\n",
1400                                       obd->obd_name, rc);
1401         }
1402         EXIT;
1403 }
1404
1405 static void abort_req_replay_queue(struct obd_device *obd)
1406 {
1407         struct ptlrpc_request *req, *n;
1408         struct list_head abort_list;
1409
1410         INIT_LIST_HEAD(&abort_list);
1411         spin_lock(&obd->obd_recovery_task_lock);
1412         list_splice_init(&obd->obd_req_replay_queue, &abort_list);
1413         spin_unlock(&obd->obd_recovery_task_lock);
1414         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1415                 DEBUG_REQ(D_WARNING, req, "aborted:");
1416                 req->rq_status = -ENOTCONN;
1417                 if (ptlrpc_error(req)) {
1418                         DEBUG_REQ(D_ERROR, req,
1419                                   "failed abort_req_reply; skipping");
1420                 }
1421                 target_exp_dequeue_req_replay(req);
1422                 target_request_copy_put(req);
1423         }
1424 }
1425
1426 static void abort_lock_replay_queue(struct obd_device *obd)
1427 {
1428         struct ptlrpc_request *req, *n;
1429         struct list_head abort_list;
1430
1431         INIT_LIST_HEAD(&abort_list);
1432         spin_lock(&obd->obd_recovery_task_lock);
1433         list_splice_init(&obd->obd_lock_replay_queue, &abort_list);
1434         spin_unlock(&obd->obd_recovery_task_lock);
1435         list_for_each_entry_safe(req, n, &abort_list, rq_list) {
1436                 DEBUG_REQ(D_ERROR, req, "aborted:");
1437                 req->rq_status = -ENOTCONN;
1438                 if (ptlrpc_error(req)) {
1439                         DEBUG_REQ(D_ERROR, req,
1440                                   "failed abort_lock_reply; skipping");
1441                 }
1442                 target_request_copy_put(req);
1443         }
1444 }
1445
1446 /* Called from a cleanup function if the device is being cleaned up
1447    forcefully.  The exports should all have been disconnected already,
1448    the only thing left to do is
1449      - clear the recovery flags
1450      - cancel the timer
1451      - free queued requests and replies, but don't send replies
1452    Because the obd_stopping flag is set, no new requests should be received.
1453
1454 */
1455 void target_cleanup_recovery(struct obd_device *obd)
1456 {
1457         struct ptlrpc_request *req, *n;
1458         struct list_head clean_list;
1459         ENTRY;
1460
1461         INIT_LIST_HEAD(&clean_list);
1462         spin_lock(&obd->obd_dev_lock);
1463         if (!obd->obd_recovering) {
1464                 spin_unlock(&obd->obd_dev_lock);
1465                 EXIT;
1466                 return;
1467         }
1468         obd->obd_recovering = obd->obd_abort_recovery = 0;
1469         spin_unlock(&obd->obd_dev_lock);
1470
1471         spin_lock(&obd->obd_recovery_task_lock);
1472         target_cancel_recovery_timer(obd);
1473         list_splice_init(&obd->obd_req_replay_queue, &clean_list);
1474         spin_unlock(&obd->obd_recovery_task_lock);
1475
1476         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1477                 LASSERT(req->rq_reply_state == NULL);
1478                 target_exp_dequeue_req_replay(req);
1479                 target_request_copy_put(req);
1480         }
1481
1482         spin_lock(&obd->obd_recovery_task_lock);
1483         list_splice_init(&obd->obd_lock_replay_queue, &clean_list);
1484         list_splice_init(&obd->obd_final_req_queue, &clean_list);
1485         spin_unlock(&obd->obd_recovery_task_lock);
1486
1487         list_for_each_entry_safe(req, n, &clean_list, rq_list) {
1488                 LASSERT(req->rq_reply_state == NULL);
1489                 target_request_copy_put(req);
1490         }
1491
1492         EXIT;
1493 }
1494 EXPORT_SYMBOL(target_cleanup_recovery);
1495
1496 /* obd_recovery_task_lock should be held */
1497 void target_cancel_recovery_timer(struct obd_device *obd)
1498 {
1499         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1500         cfs_timer_disarm(&obd->obd_recovery_timer);
1501 }
1502 EXPORT_SYMBOL(target_cancel_recovery_timer);
1503
1504 static void target_start_recovery_timer(struct obd_device *obd)
1505 {
1506         if (obd->obd_recovery_start != 0)
1507                 return;
1508
1509         spin_lock(&obd->obd_dev_lock);
1510         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1511                 spin_unlock(&obd->obd_dev_lock);
1512                 return;
1513         }
1514
1515         LASSERT(obd->obd_recovery_timeout != 0);
1516
1517         if (obd->obd_recovery_start != 0) {
1518                 spin_unlock(&obd->obd_dev_lock);
1519                 return;
1520         }
1521
1522         cfs_timer_arm(&obd->obd_recovery_timer,
1523                       cfs_time_shift(obd->obd_recovery_timeout));
1524         obd->obd_recovery_start = cfs_time_current_sec();
1525         spin_unlock(&obd->obd_dev_lock);
1526
1527         LCONSOLE_WARN("%s: Will be in recovery for at least %d:%.02d, "
1528                       "or until %d client%s reconnect%s\n",
1529                       obd->obd_name,
1530                       obd->obd_recovery_timeout / 60,
1531                       obd->obd_recovery_timeout % 60,
1532                       obd->obd_max_recoverable_clients,
1533                       (obd->obd_max_recoverable_clients == 1) ? "" : "s",
1534                       (obd->obd_max_recoverable_clients == 1) ? "s": "");
1535 }
1536
1537 /**
1538  * extend recovery window.
1539  *
1540  * if @extend is true, extend recovery window to have @drt remaining at least;
1541  * otherwise, make sure the recovery timeout value is not less than @drt.
1542  */
1543 static void extend_recovery_timer(struct obd_device *obd, int drt, bool extend)
1544 {
1545         cfs_time_t now;
1546         cfs_time_t end;
1547         cfs_duration_t left;
1548         int to;
1549
1550         spin_lock(&obd->obd_dev_lock);
1551         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1552                 spin_unlock(&obd->obd_dev_lock);
1553                 return;
1554         }
1555         LASSERT(obd->obd_recovery_start != 0);
1556
1557         now  = cfs_time_current_sec();
1558         to   = obd->obd_recovery_timeout;
1559         end  = obd->obd_recovery_start + to;
1560         left = cfs_time_sub(end, now);
1561
1562         if (extend && (drt > left)) {
1563                 to += drt - left;
1564         } else if (!extend && (drt > to)) {
1565                 to = drt;
1566         }
1567
1568         if (to > obd->obd_recovery_time_hard)
1569                 to = obd->obd_recovery_time_hard;
1570         if (obd->obd_recovery_timeout < to) {
1571                 obd->obd_recovery_timeout = to;
1572                 end = obd->obd_recovery_start + to;
1573                 cfs_timer_arm(&obd->obd_recovery_timer,
1574                                 cfs_time_shift(end - now));
1575         }
1576         spin_unlock(&obd->obd_dev_lock);
1577
1578         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n",
1579                 obd->obd_name, (unsigned)cfs_time_sub(end, now));
1580 }
1581
1582 /* Reset the timer with each new client connection */
1583 /*
1584  * This timer is actually reconnect_timer, which is for making sure
1585  * the total recovery window is at least as big as my reconnect
1586  * attempt timing. So the initial recovery time_out will be set to
1587  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1588  * from client is bigger than this, then the recovery time_out will
1589  * be extended to make sure the client could be reconnected, in the
1590  * process, the timeout from the new client should be ignored.
1591  */
1592
1593 static void
1594 check_and_start_recovery_timer(struct obd_device *obd,
1595                                struct ptlrpc_request *req,
1596                                int new_client)
1597 {
1598         int service_time = lustre_msg_get_service_time(req->rq_reqmsg);
1599         struct obd_device_target *obt = &obd->u.obt;
1600
1601         if (!new_client && service_time)
1602                 /* Teach server about old server's estimates, as first guess
1603                  * at how long new requests will take. */
1604                 at_measured(&req->rq_rqbd->rqbd_svcpt->scp_at_estimate,
1605                             service_time);
1606
1607         target_start_recovery_timer(obd);
1608
1609         /* Convert the service time to RPC timeout,
1610          * and reuse service_time to limit stack usage. */
1611         service_time = at_est2timeout(service_time);
1612
1613         /* We expect other clients to timeout within service_time, then try
1614          * to reconnect, then try the failover server.  The max delay between
1615          * connect attempts is SWITCH_MAX + SWITCH_INC + INITIAL. */
1616         service_time += 2 * INITIAL_CONNECT_TIMEOUT;
1617
1618         LASSERT(obt->obt_magic == OBT_MAGIC);
1619         service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
1620         if (service_time > obd->obd_recovery_timeout && !new_client)
1621                 extend_recovery_timer(obd, service_time, false);
1622 }
1623
1624 /** Health checking routines */
1625 static inline int exp_connect_healthy(struct obd_export *exp)
1626 {
1627         return (exp->exp_in_recovery);
1628 }
1629
1630 /** if export done req_replay or has replay in queue */
1631 static inline int exp_req_replay_healthy(struct obd_export *exp)
1632 {
1633         return (!exp->exp_req_replay_needed ||
1634                 atomic_read(&exp->exp_replay_count) > 0);
1635 }
1636 /** if export done lock_replay or has replay in queue */
1637 static inline int exp_lock_replay_healthy(struct obd_export *exp)
1638 {
1639         return (!exp->exp_lock_replay_needed ||
1640                 atomic_read(&exp->exp_replay_count) > 0);
1641 }
1642
1643 static inline int exp_vbr_healthy(struct obd_export *exp)
1644 {
1645         return (!exp->exp_vbr_failed);
1646 }
1647
1648 static inline int exp_finished(struct obd_export *exp)
1649 {
1650         return (exp->exp_in_recovery && !exp->exp_lock_replay_needed);
1651 }
1652
1653 /** Checking routines for recovery */
1654 static int check_for_clients(struct obd_device *obd)
1655 {
1656         unsigned int clnts = atomic_read(&obd->obd_connected_clients);
1657
1658         if (obd->obd_abort_recovery || obd->obd_recovery_expired)
1659                 return 1;
1660         LASSERT(clnts <= obd->obd_max_recoverable_clients);
1661         return (clnts + obd->obd_stale_clients ==
1662                 obd->obd_max_recoverable_clients);
1663 }
1664
1665 static int check_for_next_transno(struct obd_device *obd)
1666 {
1667         struct ptlrpc_request *req = NULL;
1668         int wake_up = 0, connected, completed, queue_len;
1669         __u64 next_transno, req_transno;
1670         ENTRY;
1671
1672         spin_lock(&obd->obd_recovery_task_lock);
1673         if (!list_empty(&obd->obd_req_replay_queue)) {
1674                 req = list_entry(obd->obd_req_replay_queue.next,
1675                                      struct ptlrpc_request, rq_list);
1676                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1677         } else {
1678                 req_transno = 0;
1679         }
1680
1681         connected = atomic_read(&obd->obd_connected_clients);
1682         completed = connected - atomic_read(&obd->obd_req_replay_clients);
1683         queue_len = obd->obd_requests_queued_for_recovery;
1684         next_transno = obd->obd_next_recovery_transno;
1685
1686         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1687                "req_transno: "LPU64", next_transno: "LPU64"\n",
1688                obd->obd_max_recoverable_clients, connected, completed,
1689                queue_len, req_transno, next_transno);
1690
1691         if (obd->obd_abort_recovery) {
1692                 CDEBUG(D_HA, "waking for aborted recovery\n");
1693                 wake_up = 1;
1694         } else if (obd->obd_recovery_expired) {
1695                 CDEBUG(D_HA, "waking for expired recovery\n");
1696                 wake_up = 1;
1697         } else if (req_transno == next_transno) {
1698                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1699                 wake_up = 1;
1700         } else if (queue_len > 0 &&
1701                    queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1702                 int d_lvl = D_HA;
1703                 /** handle gaps occured due to lost reply or VBR */
1704                 LASSERTF(req_transno >= next_transno,
1705                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1706                          req_transno, next_transno);
1707                 if (req_transno > obd->obd_last_committed &&
1708                     !obd->obd_version_recov)
1709                         d_lvl = D_ERROR;
1710                 CDEBUG(d_lvl,
1711                        "%s: waking for gap in transno, VBR is %s (skip: "
1712                        LPD64", ql: %d, comp: %d, conn: %d, next: "LPD64
1713                        ", last_committed: "LPD64")\n",
1714                        obd->obd_name, obd->obd_version_recov ? "ON" : "OFF",
1715                        next_transno, queue_len, completed, connected,
1716                        req_transno, obd->obd_last_committed);
1717                 obd->obd_next_recovery_transno = req_transno;
1718                 wake_up = 1;
1719         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1720                 CDEBUG(D_HA, "waking for completed recovery\n");
1721                 wake_up = 1;
1722         } else if (OBD_FAIL_CHECK(OBD_FAIL_MDS_RECOVERY_ACCEPTS_GAPS)) {
1723                 CDEBUG(D_HA, "accepting transno gaps is explicitly allowed"
1724                        " by fail_lock, waking up ("LPD64")\n", next_transno);
1725                 obd->obd_next_recovery_transno = req_transno;
1726                 wake_up = 1;
1727         }
1728         spin_unlock(&obd->obd_recovery_task_lock);
1729         return wake_up;
1730 }
1731
1732 static int check_for_next_lock(struct obd_device *obd)
1733 {
1734         int wake_up = 0;
1735
1736         spin_lock(&obd->obd_recovery_task_lock);
1737         if (!list_empty(&obd->obd_lock_replay_queue)) {
1738                 CDEBUG(D_HA, "waking for next lock\n");
1739                 wake_up = 1;
1740         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1741                 CDEBUG(D_HA, "waking for completed lock replay\n");
1742                 wake_up = 1;
1743         } else if (obd->obd_abort_recovery) {
1744                 CDEBUG(D_HA, "waking for aborted recovery\n");
1745                 wake_up = 1;
1746         } else if (obd->obd_recovery_expired) {
1747                 CDEBUG(D_HA, "waking for expired recovery\n");
1748                 wake_up = 1;
1749         }
1750         spin_unlock(&obd->obd_recovery_task_lock);
1751
1752         return wake_up;
1753 }
1754
1755 /**
1756  * wait for recovery events,
1757  * check its status with help of check_routine
1758  * evict dead clients via health_check
1759  */
1760 static int target_recovery_overseer(struct obd_device *obd,
1761                                     int (*check_routine)(struct obd_device *),
1762                                     int (*health_check)(struct obd_export *))
1763 {
1764 repeat:
1765         if ((obd->obd_recovery_start != 0) && (cfs_time_current_sec() >=
1766               (obd->obd_recovery_start + obd->obd_recovery_time_hard))) {
1767                 CWARN("recovery is aborted by hard timeout\n");
1768                 obd->obd_abort_recovery = 1;
1769         }
1770
1771         wait_event(obd->obd_next_transno_waitq, check_routine(obd));
1772         if (obd->obd_abort_recovery) {
1773                 CWARN("recovery is aborted, evict exports in recovery\n");
1774                 /** evict exports which didn't finish recovery yet */
1775                 class_disconnect_stale_exports(obd, exp_finished);
1776                 return 1;
1777         } else if (obd->obd_recovery_expired) {
1778                 obd->obd_recovery_expired = 0;
1779                 /** If some clients died being recovered, evict them */
1780                 LCONSOLE_WARN("%s: recovery is timed out, "
1781                               "evict stale exports\n", obd->obd_name);
1782                 /** evict cexports with no replay in queue, they are stalled */
1783                 class_disconnect_stale_exports(obd, health_check);
1784                 /** continue with VBR */
1785                 spin_lock(&obd->obd_dev_lock);
1786                 obd->obd_version_recov = 1;
1787                 spin_unlock(&obd->obd_dev_lock);
1788                 /**
1789                  * reset timer, recovery will proceed with versions now,
1790                  * timeout is set just to handle reconnection delays
1791                  */
1792                 extend_recovery_timer(obd, RECONNECT_DELAY_MAX, true);
1793                 /** Wait for recovery events again, after evicting bad clients */
1794                 goto repeat;
1795         }
1796         return 0;
1797 }
1798
1799 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1800 {
1801         struct ptlrpc_request *req = NULL;
1802         ENTRY;
1803
1804         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1805                 obd->obd_next_recovery_transno);
1806
1807         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_DELAY2, cfs_fail_val);
1808         /** It is needed to extend recovery window above recovery_time_soft.
1809          *  Extending is possible only in the end of recovery window
1810          *  (see more details in handle_recovery_req).
1811          */
1812         CFS_FAIL_TIMEOUT_MS(OBD_FAIL_TGT_REPLAY_DELAY, 300);
1813
1814         if (target_recovery_overseer(obd, check_for_next_transno,
1815                                      exp_req_replay_healthy)) {
1816                 abort_req_replay_queue(obd);
1817                 abort_lock_replay_queue(obd);
1818         }
1819
1820         spin_lock(&obd->obd_recovery_task_lock);
1821         if (!list_empty(&obd->obd_req_replay_queue)) {
1822                 req = list_entry(obd->obd_req_replay_queue.next,
1823                                      struct ptlrpc_request, rq_list);
1824                 list_del_init(&req->rq_list);
1825                 obd->obd_requests_queued_for_recovery--;
1826                 spin_unlock(&obd->obd_recovery_task_lock);
1827         } else {
1828                 spin_unlock(&obd->obd_recovery_task_lock);
1829                 LASSERT(list_empty(&obd->obd_req_replay_queue));
1830                 LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1831                 /** evict exports failed VBR */
1832                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1833         }
1834         RETURN(req);
1835 }
1836
1837 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1838 {
1839         struct ptlrpc_request *req = NULL;
1840
1841         CDEBUG(D_HA, "Waiting for lock\n");
1842         if (target_recovery_overseer(obd, check_for_next_lock,
1843                                      exp_lock_replay_healthy))
1844                 abort_lock_replay_queue(obd);
1845
1846         spin_lock(&obd->obd_recovery_task_lock);
1847         if (!list_empty(&obd->obd_lock_replay_queue)) {
1848                 req = list_entry(obd->obd_lock_replay_queue.next,
1849                                      struct ptlrpc_request, rq_list);
1850                 list_del_init(&req->rq_list);
1851                 spin_unlock(&obd->obd_recovery_task_lock);
1852         } else {
1853                 spin_unlock(&obd->obd_recovery_task_lock);
1854                 LASSERT(list_empty(&obd->obd_lock_replay_queue));
1855                 LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1856                 /** evict exports failed VBR */
1857                 class_disconnect_stale_exports(obd, exp_vbr_healthy);
1858         }
1859         return req;
1860 }
1861
1862 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1863 {
1864         struct ptlrpc_request *req = NULL;
1865
1866         spin_lock(&obd->obd_recovery_task_lock);
1867         if (!list_empty(&obd->obd_final_req_queue)) {
1868                 req = list_entry(obd->obd_final_req_queue.next,
1869                                      struct ptlrpc_request, rq_list);
1870                 list_del_init(&req->rq_list);
1871                 spin_unlock(&obd->obd_recovery_task_lock);
1872                 if (req->rq_export->exp_in_recovery) {
1873                         spin_lock(&req->rq_export->exp_lock);
1874                         req->rq_export->exp_in_recovery = 0;
1875                         spin_unlock(&req->rq_export->exp_lock);
1876                 }
1877         } else {
1878                 spin_unlock(&obd->obd_recovery_task_lock);
1879         }
1880         return req;
1881 }
1882
1883 static void handle_recovery_req(struct ptlrpc_thread *thread,
1884                                 struct ptlrpc_request *req,
1885                                 svc_handler_t handler)
1886 {
1887         ENTRY;
1888
1889         /**
1890          * export can be evicted during recovery, no need to handle replays for
1891          * it after that, discard such request silently
1892          */
1893         if (req->rq_export->exp_disconnected)
1894                 RETURN_EXIT;
1895
1896         req->rq_session.lc_thread = thread;
1897         req->rq_svc_thread = thread;
1898         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1899
1900         /* thread context */
1901         lu_context_enter(&thread->t_env->le_ctx);
1902         (void)handler(req);
1903         lu_context_exit(&thread->t_env->le_ctx);
1904
1905         /* don't reset timer for final stage */
1906         if (!exp_finished(req->rq_export)) {
1907                 int to = obd_timeout;
1908
1909                 /**
1910                  * Add request timeout to the recovery time so next request from
1911                  * this client may come in recovery time
1912                  */
1913                 if (!AT_OFF) {
1914                         struct ptlrpc_service_part *svcpt;
1915
1916                         svcpt = req->rq_rqbd->rqbd_svcpt;
1917                         /* If the server sent early reply for this request,
1918                          * the client will recalculate the timeout according to
1919                          * current server estimate service time, so we will
1920                          * use the maxium timeout here for waiting the client
1921                          * sending the next req */
1922                         to = max((int)at_est2timeout(
1923                                  at_get(&svcpt->scp_at_estimate)),
1924                                  (int)lustre_msg_get_timeout(req->rq_reqmsg));
1925                         /* Add 2 net_latency, one for balance rq_deadline
1926                          * (see ptl_send_rpc), one for resend the req to server,
1927                          * Note: client will pack net_latency in replay req
1928                          * (see ptlrpc_replay_req) */
1929                         to += 2 * lustre_msg_get_service_time(req->rq_reqmsg);
1930                 }
1931                 extend_recovery_timer(class_exp2obd(req->rq_export), to, true);
1932         }
1933         EXIT;
1934 }
1935
1936 static int target_recovery_thread(void *arg)
1937 {
1938         struct lu_target *lut = arg;
1939         struct obd_device *obd = lut->lut_obd;
1940         struct ptlrpc_request *req;
1941         struct target_recovery_data *trd = &obd->obd_recovery_data;
1942         unsigned long delta;
1943         struct lu_env *env;
1944         struct ptlrpc_thread *thread = NULL;
1945         int rc = 0;
1946         ENTRY;
1947
1948         unshare_fs_struct();
1949         OBD_ALLOC_PTR(thread);
1950         if (thread == NULL)
1951                 RETURN(-ENOMEM);
1952
1953         OBD_ALLOC_PTR(env);
1954         if (env == NULL) {
1955                 OBD_FREE_PTR(thread);
1956                 RETURN(-ENOMEM);
1957         }
1958
1959         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD);
1960         if (rc) {
1961                 OBD_FREE_PTR(thread);
1962                 OBD_FREE_PTR(env);
1963                 RETURN(rc);
1964         }
1965
1966         thread->t_env = env;
1967         thread->t_id = -1; /* force filter_iobuf_get/put to use local buffers */
1968         env->le_ctx.lc_thread = thread;
1969         tgt_io_thread_init(thread); /* init thread_big_cache for IO requests */
1970         thread->t_watchdog = NULL;
1971
1972         CDEBUG(D_HA, "%s: started recovery thread pid %d\n", obd->obd_name,
1973                current_pid());
1974         trd->trd_processing_task = current_pid();
1975
1976         spin_lock(&obd->obd_dev_lock);
1977         obd->obd_recovering = 1;
1978         spin_unlock(&obd->obd_dev_lock);
1979         complete(&trd->trd_starting);
1980
1981         /* first of all, we have to know the first transno to replay */
1982         if (target_recovery_overseer(obd, check_for_clients,
1983                                      exp_connect_healthy)) {
1984                 abort_req_replay_queue(obd);
1985                 abort_lock_replay_queue(obd);
1986         }
1987
1988         /* next stage: replay requests */
1989         delta = jiffies;
1990         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1991                atomic_read(&obd->obd_req_replay_clients),
1992                obd->obd_next_recovery_transno);
1993         while ((req = target_next_replay_req(obd))) {
1994                 LASSERT(trd->trd_processing_task == current_pid());
1995                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1996                           lustre_msg_get_transno(req->rq_reqmsg),
1997                           libcfs_nid2str(req->rq_peer.nid));
1998                 handle_recovery_req(thread, req,
1999                                     trd->trd_recovery_handler);
2000                 /**
2001                  * bz18031: increase next_recovery_transno before
2002                  * target_request_copy_put() will drop exp_rpc reference
2003                  */
2004                 spin_lock(&obd->obd_recovery_task_lock);
2005                 obd->obd_next_recovery_transno++;
2006                 spin_unlock(&obd->obd_recovery_task_lock);
2007                 target_exp_dequeue_req_replay(req);
2008                 target_request_copy_put(req);
2009                 obd->obd_replayed_requests++;
2010         }
2011
2012         /**
2013          * The second stage: replay locks
2014          */
2015         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
2016                atomic_read(&obd->obd_lock_replay_clients));
2017         while ((req = target_next_replay_lock(obd))) {
2018                 LASSERT(trd->trd_processing_task == current_pid());
2019                 DEBUG_REQ(D_HA, req, "processing lock from %s: ",
2020                           libcfs_nid2str(req->rq_peer.nid));
2021                 handle_recovery_req(thread, req,
2022                                     trd->trd_recovery_handler);
2023                 target_request_copy_put(req);
2024                 obd->obd_replayed_locks++;
2025         }
2026
2027         /**
2028          * The third stage: reply on final pings, at this moment all clients
2029          * must have request in final queue
2030          */
2031         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLAY_RECONNECT, cfs_fail_val);
2032         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
2033         /** Update server last boot epoch */
2034         tgt_boot_epoch_update(lut);
2035         /* We drop recoverying flag to forward all new requests
2036          * to regular mds_handle() since now */
2037         spin_lock(&obd->obd_dev_lock);
2038         obd->obd_recovering = obd->obd_abort_recovery = 0;
2039         spin_unlock(&obd->obd_dev_lock);
2040         spin_lock(&obd->obd_recovery_task_lock);
2041         target_cancel_recovery_timer(obd);
2042         spin_unlock(&obd->obd_recovery_task_lock);
2043         while ((req = target_next_final_ping(obd))) {
2044                 LASSERT(trd->trd_processing_task == current_pid());
2045                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
2046                           libcfs_nid2str(req->rq_peer.nid));
2047                 handle_recovery_req(thread, req,
2048                                     trd->trd_recovery_handler);
2049                 /* Because the waiting client can not send ping to server,
2050                  * so we need refresh the last_request_time, to avoid the
2051                  * export is being evicted */
2052                 ptlrpc_update_export_timer(req->rq_export, 0);
2053                 target_request_copy_put(req);
2054         }
2055
2056         delta = jiffies_to_msecs(jiffies - delta) / MSEC_PER_SEC;
2057         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
2058               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
2059         if (delta > OBD_RECOVERY_TIME_SOFT) {
2060                 CWARN("too long recovery - read logs\n");
2061                 libcfs_debug_dumplog();
2062         }
2063
2064         target_finish_recovery(obd);
2065
2066         lu_context_fini(&env->le_ctx);
2067         trd->trd_processing_task = 0;
2068         complete(&trd->trd_finishing);
2069
2070         tgt_io_thread_done(thread);
2071         OBD_FREE_PTR(thread);
2072         OBD_FREE_PTR(env);
2073         RETURN(rc);
2074 }
2075
2076 static int target_start_recovery_thread(struct lu_target *lut,
2077                                         svc_handler_t handler)
2078 {
2079         struct obd_device *obd = lut->lut_obd;
2080         int rc = 0;
2081         struct target_recovery_data *trd = &obd->obd_recovery_data;
2082
2083         memset(trd, 0, sizeof(*trd));
2084         init_completion(&trd->trd_starting);
2085         init_completion(&trd->trd_finishing);
2086         trd->trd_recovery_handler = handler;
2087
2088         if (!IS_ERR(kthread_run(target_recovery_thread,
2089                                 lut, "tgt_recov"))) {
2090                 wait_for_completion(&trd->trd_starting);
2091                 LASSERT(obd->obd_recovering != 0);
2092         } else {
2093                 rc = -ECHILD;
2094         }
2095
2096         return rc;
2097 }
2098
2099 void target_stop_recovery_thread(struct obd_device *obd)
2100 {
2101         if (obd->obd_recovery_data.trd_processing_task > 0) {
2102                 struct target_recovery_data *trd = &obd->obd_recovery_data;
2103                 /** recovery can be done but postrecovery is not yet */
2104                 spin_lock(&obd->obd_dev_lock);
2105                 if (obd->obd_recovering) {
2106                         CERROR("%s: Aborting recovery\n", obd->obd_name);
2107                         obd->obd_abort_recovery = 1;
2108                         wake_up(&obd->obd_next_transno_waitq);
2109                 }
2110                 spin_unlock(&obd->obd_dev_lock);
2111                 wait_for_completion(&trd->trd_finishing);
2112         }
2113 }
2114 EXPORT_SYMBOL(target_stop_recovery_thread);
2115
2116 void target_recovery_fini(struct obd_device *obd)
2117 {
2118         class_disconnect_exports(obd);
2119         target_stop_recovery_thread(obd);
2120         target_cleanup_recovery(obd);
2121 }
2122 EXPORT_SYMBOL(target_recovery_fini);
2123
2124 static void target_recovery_expired(unsigned long castmeharder)
2125 {
2126         struct obd_device *obd = (struct obd_device *)castmeharder;
2127         CDEBUG(D_HA, "%s: recovery timed out; %d clients are still in recovery"
2128                " after %lds (%d clients connected)\n",
2129                obd->obd_name, atomic_read(&obd->obd_lock_replay_clients),
2130                cfs_time_current_sec()- obd->obd_recovery_start,
2131                atomic_read(&obd->obd_connected_clients));
2132
2133         obd->obd_recovery_expired = 1;
2134         wake_up(&obd->obd_next_transno_waitq);
2135 }
2136
2137 void target_recovery_init(struct lu_target *lut, svc_handler_t handler)
2138 {
2139         struct obd_device *obd = lut->lut_obd;
2140         if (obd->obd_max_recoverable_clients == 0) {
2141                 /** Update server last boot epoch */
2142                 tgt_boot_epoch_update(lut);
2143                 return;
2144         }
2145
2146         CDEBUG(D_HA, "RECOVERY: service %s, %d recoverable clients, "
2147                "last_transno "LPU64"\n", obd->obd_name,
2148                obd->obd_max_recoverable_clients, obd->obd_last_committed);
2149         LASSERT(obd->obd_stopping == 0);
2150         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
2151         obd->obd_recovery_start = 0;
2152         obd->obd_recovery_end = 0;
2153
2154         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
2155         target_start_recovery_thread(lut, handler);
2156 }
2157 EXPORT_SYMBOL(target_recovery_init);
2158
2159
2160 static int target_process_req_flags(struct obd_device *obd,
2161                                     struct ptlrpc_request *req)
2162 {
2163         struct obd_export *exp = req->rq_export;
2164         LASSERT(exp != NULL);
2165         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2166                 /* client declares he's ready to replay locks */
2167                 spin_lock(&exp->exp_lock);
2168                 if (exp->exp_req_replay_needed) {
2169                         exp->exp_req_replay_needed = 0;
2170                         spin_unlock(&exp->exp_lock);
2171
2172                         LASSERT_ATOMIC_POS(&obd->obd_req_replay_clients);
2173                         atomic_dec(&obd->obd_req_replay_clients);
2174                 } else {
2175                         spin_unlock(&exp->exp_lock);
2176                 }
2177         }
2178         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2179                 /* client declares he's ready to complete recovery
2180                  * so, we put the request on th final queue */
2181                 spin_lock(&exp->exp_lock);
2182                 if (exp->exp_lock_replay_needed) {
2183                         exp->exp_lock_replay_needed = 0;
2184                         spin_unlock(&exp->exp_lock);
2185
2186                         LASSERT_ATOMIC_POS(&obd->obd_lock_replay_clients);
2187                         atomic_dec(&obd->obd_lock_replay_clients);
2188                 } else {
2189                         spin_unlock(&exp->exp_lock);
2190                 }
2191         }
2192         return 0;
2193 }
2194
2195 int target_queue_recovery_request(struct ptlrpc_request *req,
2196                                   struct obd_device *obd)
2197 {
2198         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
2199         struct ptlrpc_request *reqiter;
2200         int inserted = 0;
2201         ENTRY;
2202
2203         if (obd->obd_recovery_data.trd_processing_task == current_pid()) {
2204                 /* Processing the queue right now, don't re-add. */
2205                 RETURN(1);
2206         }
2207
2208         target_process_req_flags(obd, req);
2209
2210         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
2211                 /* client declares he's ready to complete recovery
2212                  * so, we put the request on th final queue */
2213                 target_request_copy_get(req);
2214                 DEBUG_REQ(D_HA, req, "queue final req");
2215                 wake_up(&obd->obd_next_transno_waitq);
2216                 spin_lock(&obd->obd_recovery_task_lock);
2217                 if (obd->obd_recovering) {
2218                         list_add_tail(&req->rq_list,
2219                                           &obd->obd_final_req_queue);
2220                 } else {
2221                         spin_unlock(&obd->obd_recovery_task_lock);
2222                         target_request_copy_put(req);
2223                         RETURN(obd->obd_stopping ? -ENOTCONN : 1);
2224                 }
2225                 spin_unlock(&obd->obd_recovery_task_lock);
2226                 RETURN(0);
2227         }
2228         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
2229                 /* client declares he's ready to replay locks */
2230                 target_request_copy_get(req);
2231                 DEBUG_REQ(D_HA, req, "queue lock replay req");
2232                 wake_up(&obd->obd_next_transno_waitq);
2233                 spin_lock(&obd->obd_recovery_task_lock);
2234                 LASSERT(obd->obd_recovering);
2235                 /* usually due to recovery abort */
2236                 if (!req->rq_export->exp_in_recovery) {
2237                         spin_unlock(&obd->obd_recovery_task_lock);
2238                         target_request_copy_put(req);
2239                         RETURN(-ENOTCONN);
2240                 }
2241                 LASSERT(req->rq_export->exp_lock_replay_needed);
2242                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
2243                 spin_unlock(&obd->obd_recovery_task_lock);
2244                 RETURN(0);
2245         }
2246
2247         /* CAVEAT EMPTOR: The incoming request message has been swabbed
2248          * (i.e. buflens etc are in my own byte order), but type-dependent
2249          * buffers (eg mdt_body, ost_body etc) have NOT been swabbed. */
2250
2251         if (!transno) {
2252                 INIT_LIST_HEAD(&req->rq_list);
2253                 DEBUG_REQ(D_HA, req, "not queueing");
2254                 RETURN(1);
2255         }
2256
2257         /* If we're processing the queue, we want don't want to queue this
2258          * message.
2259          *
2260          * Also, if this request has a transno less than the one we're waiting
2261          * for, we should process it now.  It could (and currently always will)
2262          * be an open request for a descriptor that was opened some time ago.
2263          *
2264          * Also, a resent, replayed request that has already been
2265          * handled will pass through here and be processed immediately.
2266          */
2267         CDEBUG(D_HA, "Next recovery transno: "LPU64
2268                ", current: "LPU64", replaying\n",
2269                obd->obd_next_recovery_transno, transno);
2270         spin_lock(&obd->obd_recovery_task_lock);
2271         if (transno < obd->obd_next_recovery_transno) {
2272                 /* Processing the queue right now, don't re-add. */
2273                 LASSERT(list_empty(&req->rq_list));
2274                 spin_unlock(&obd->obd_recovery_task_lock);
2275                 RETURN(1);
2276         }
2277         spin_unlock(&obd->obd_recovery_task_lock);
2278
2279         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
2280                 RETURN(0);
2281
2282         target_request_copy_get(req);
2283         if (!req->rq_export->exp_in_recovery) {
2284                 target_request_copy_put(req);
2285                 RETURN(-ENOTCONN);
2286         }
2287         LASSERT(req->rq_export->exp_req_replay_needed);
2288
2289         if (target_exp_enqueue_req_replay(req)) {
2290                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
2291                 target_request_copy_put(req);
2292                 RETURN(0);
2293         }
2294
2295         /* XXX O(n^2) */
2296         spin_lock(&obd->obd_recovery_task_lock);
2297         LASSERT(obd->obd_recovering);
2298         list_for_each_entry(reqiter, &obd->obd_req_replay_queue, rq_list) {
2299                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
2300                         list_add_tail(&req->rq_list, &reqiter->rq_list);
2301                         inserted = 1;
2302                         goto added;
2303                 }
2304
2305                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
2306                              transno)) {
2307                         DEBUG_REQ(D_ERROR, req, "dropping replay: transno "
2308                                   "has been claimed by another client");
2309                         spin_unlock(&obd->obd_recovery_task_lock);
2310                         target_exp_dequeue_req_replay(req);
2311                         target_request_copy_put(req);
2312                         RETURN(0);
2313                 }
2314         }
2315 added:
2316         if (!inserted)
2317                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
2318
2319         obd->obd_requests_queued_for_recovery++;
2320         spin_unlock(&obd->obd_recovery_task_lock);
2321         wake_up(&obd->obd_next_transno_waitq);
2322         RETURN(0);
2323 }
2324 EXPORT_SYMBOL(target_queue_recovery_request);
2325
2326 int target_handle_ping(struct ptlrpc_request *req)
2327 {
2328         obd_ping(req->rq_svc_thread->t_env, req->rq_export);
2329         return req_capsule_server_pack(&req->rq_pill);
2330 }
2331 EXPORT_SYMBOL(target_handle_ping);
2332
2333 void target_committed_to_req(struct ptlrpc_request *req)
2334 {
2335         struct obd_export *exp = req->rq_export;
2336
2337         if (!exp->exp_obd->obd_no_transno && req->rq_repmsg != NULL)
2338                 lustre_msg_set_last_committed(req->rq_repmsg,
2339                                               exp->exp_last_committed);
2340         else
2341                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
2342                           "%d)", exp->exp_obd->obd_no_transno,
2343                           req->rq_repmsg == NULL);
2344
2345         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
2346                exp->exp_last_committed, req->rq_transno, req->rq_xid);
2347 }
2348 EXPORT_SYMBOL(target_committed_to_req);
2349
2350 #endif /* HAVE_SERVER_SUPPORT */
2351
2352 /**
2353  * Packs current SLV and Limit into \a req.
2354  */
2355 int target_pack_pool_reply(struct ptlrpc_request *req)
2356 {
2357         struct obd_device *obd;
2358         ENTRY;
2359
2360         /* Check that we still have all structures alive as this may
2361          * be some late RPC at shutdown time. */
2362         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
2363                      !exp_connect_lru_resize(req->rq_export))) {
2364                 lustre_msg_set_slv(req->rq_repmsg, 0);
2365                 lustre_msg_set_limit(req->rq_repmsg, 0);
2366                 RETURN(0);
2367         }
2368
2369         /* OBD is alive here as export is alive, which we checked above. */
2370         obd = req->rq_export->exp_obd;
2371
2372         read_lock(&obd->obd_pool_lock);
2373         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
2374         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
2375         read_unlock(&obd->obd_pool_lock);
2376
2377         RETURN(0);
2378 }
2379 EXPORT_SYMBOL(target_pack_pool_reply);
2380
2381 static int target_send_reply_msg(struct ptlrpc_request *req,
2382                                  int rc, int fail_id)
2383 {
2384         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
2385                 DEBUG_REQ(D_ERROR, req, "dropping reply");
2386                 return (-ECOMM);
2387         }
2388
2389         if (unlikely(rc)) {
2390                 DEBUG_REQ(D_NET, req, "processing error (%d)", rc);
2391                 req->rq_status = rc;
2392                 return (ptlrpc_send_error(req, 1));
2393         } else {
2394                 DEBUG_REQ(D_NET, req, "sending reply");
2395         }
2396
2397         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
2398 }
2399
2400 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
2401 {
2402         struct ptlrpc_service_part *svcpt;
2403         int                        netrc;
2404         struct ptlrpc_reply_state *rs;
2405         struct obd_export         *exp;
2406         ENTRY;
2407
2408         if (req->rq_no_reply) {
2409                 EXIT;
2410                 return;
2411         }
2412
2413         svcpt = req->rq_rqbd->rqbd_svcpt;
2414         rs = req->rq_reply_state;
2415         if (rs == NULL || !rs->rs_difficult) {
2416                 /* no notifiers */
2417                 target_send_reply_msg (req, rc, fail_id);
2418                 EXIT;
2419                 return;
2420         }
2421
2422         /* must be an export if locks saved */
2423         LASSERT(req->rq_export != NULL);
2424         /* req/reply consistent */
2425         LASSERT(rs->rs_svcpt == svcpt);
2426
2427         /* "fresh" reply */
2428         LASSERT(!rs->rs_scheduled);
2429         LASSERT(!rs->rs_scheduled_ever);
2430         LASSERT(!rs->rs_handled);
2431         LASSERT(!rs->rs_on_net);
2432         LASSERT(rs->rs_export == NULL);
2433         LASSERT(list_empty(&rs->rs_obd_list));
2434         LASSERT(list_empty(&rs->rs_exp_list));
2435
2436         exp = class_export_get(req->rq_export);
2437
2438         /* disable reply scheduling while I'm setting up */
2439         rs->rs_scheduled = 1;
2440         rs->rs_on_net    = 1;
2441         rs->rs_xid       = req->rq_xid;
2442         rs->rs_transno   = req->rq_transno;
2443         rs->rs_export    = exp;
2444         rs->rs_opc       = lustre_msg_get_opc(req->rq_reqmsg);
2445
2446         spin_lock(&exp->exp_uncommitted_replies_lock);
2447         CDEBUG(D_NET, "rs transno = "LPU64", last committed = "LPU64"\n",
2448                rs->rs_transno, exp->exp_last_committed);
2449         if (rs->rs_transno > exp->exp_last_committed) {
2450                 /* not committed already */
2451                 list_add_tail(&rs->rs_obd_list,
2452                                   &exp->exp_uncommitted_replies);
2453         }
2454         spin_unlock(&exp->exp_uncommitted_replies_lock);
2455
2456         spin_lock(&exp->exp_lock);
2457         list_add_tail(&rs->rs_exp_list, &exp->exp_outstanding_replies);
2458         spin_unlock(&exp->exp_lock);
2459
2460         netrc = target_send_reply_msg(req, rc, fail_id);
2461
2462         spin_lock(&svcpt->scp_rep_lock);
2463
2464         atomic_inc(&svcpt->scp_nreps_difficult);
2465
2466         if (netrc != 0) {
2467                 /* error sending: reply is off the net.  Also we need +1
2468                  * reply ref until ptlrpc_handle_rs() is done
2469                  * with the reply state (if the send was successful, there
2470                  * would have been +1 ref for the net, which
2471                  * reply_out_callback leaves alone) */
2472                 rs->rs_on_net = 0;
2473                 ptlrpc_rs_addref(rs);
2474         }
2475
2476         spin_lock(&rs->rs_lock);
2477         if (rs->rs_transno <= exp->exp_last_committed ||
2478             (!rs->rs_on_net && !rs->rs_no_ack) ||
2479             list_empty(&rs->rs_exp_list) ||     /* completed already */
2480             list_empty(&rs->rs_obd_list)) {
2481                 CDEBUG(D_HA, "Schedule reply immediately\n");
2482                 ptlrpc_dispatch_difficult_reply(rs);
2483         } else {
2484                 list_add(&rs->rs_list, &svcpt->scp_rep_active);
2485                 rs->rs_scheduled = 0;   /* allow notifier to schedule */
2486         }
2487         spin_unlock(&rs->rs_lock);
2488         spin_unlock(&svcpt->scp_rep_lock);
2489         EXIT;
2490 }
2491 EXPORT_SYMBOL(target_send_reply);
2492
2493 ldlm_mode_t lck_compat_array[] = {
2494         [LCK_EX]    = LCK_COMPAT_EX,
2495         [LCK_PW]    = LCK_COMPAT_PW,
2496         [LCK_PR]    = LCK_COMPAT_PR,
2497         [LCK_CW]    = LCK_COMPAT_CW,
2498         [LCK_CR]    = LCK_COMPAT_CR,
2499         [LCK_NL]    = LCK_COMPAT_NL,
2500         [LCK_GROUP] = LCK_COMPAT_GROUP,
2501         [LCK_COS]   = LCK_COMPAT_COS,
2502 };
2503
2504 /**
2505  * Rather arbitrary mapping from LDLM error codes to errno values. This should
2506  * not escape to the user level.
2507  */
2508 int ldlm_error2errno(ldlm_error_t error)
2509 {
2510         int result;
2511
2512         switch (error) {
2513         case ELDLM_OK:
2514         case ELDLM_LOCK_MATCHED:
2515                 result = 0;
2516                 break;
2517         case ELDLM_LOCK_CHANGED:
2518                 result = -ESTALE;
2519                 break;
2520         case ELDLM_LOCK_ABORTED:
2521                 result = -ENAVAIL;
2522                 break;
2523         case ELDLM_LOCK_REPLACED:
2524                 result = -ESRCH;
2525                 break;
2526         case ELDLM_NO_LOCK_DATA:
2527                 result = -ENOENT;
2528                 break;
2529         case ELDLM_NAMESPACE_EXISTS:
2530                 result = -EEXIST;
2531                 break;
2532         case ELDLM_BAD_NAMESPACE:
2533                 result = -EBADF;
2534                 break;
2535         default:
2536                 if (((int)error) < 0)  /* cast to signed type */
2537                         result = error; /* as ldlm_error_t can be unsigned */
2538                 else {
2539                         CERROR("Invalid DLM result code: %d\n", error);
2540                         result = -EPROTO;
2541                 }
2542         }
2543         return result;
2544 }
2545 EXPORT_SYMBOL(ldlm_error2errno);
2546
2547 /**
2548  * Dual to ldlm_error2errno(): maps errno values back to ldlm_error_t.
2549  */
2550 ldlm_error_t ldlm_errno2error(int err_no)
2551 {
2552         int error;
2553
2554         switch (err_no) {
2555         case 0:
2556                 error = ELDLM_OK;
2557                 break;
2558         case -ESTALE:
2559                 error = ELDLM_LOCK_CHANGED;
2560                 break;
2561         case -ENAVAIL:
2562                 error = ELDLM_LOCK_ABORTED;
2563                 break;
2564         case -ESRCH:
2565                 error = ELDLM_LOCK_REPLACED;
2566                 break;
2567         case -ENOENT:
2568                 error = ELDLM_NO_LOCK_DATA;
2569                 break;
2570         case -EEXIST:
2571                 error = ELDLM_NAMESPACE_EXISTS;
2572                 break;
2573         case -EBADF:
2574                 error = ELDLM_BAD_NAMESPACE;
2575                 break;
2576         default:
2577                 error = err_no;
2578         }
2579         return error;
2580 }
2581 EXPORT_SYMBOL(ldlm_errno2error);
2582
2583 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2584 void ldlm_dump_export_locks(struct obd_export *exp)
2585 {
2586         spin_lock(&exp->exp_locks_list_guard);
2587         if (!list_empty(&exp->exp_locks_list)) {
2588                 struct ldlm_lock *lock;
2589
2590                 CERROR("dumping locks for export %p,"
2591                        "ignore if the unmount doesn't hang\n", exp);
2592                 list_for_each_entry(lock, &exp->exp_locks_list,
2593                                         l_exp_refs_link)
2594                         LDLM_ERROR(lock, "lock:");
2595         }
2596         spin_unlock(&exp->exp_locks_list_guard);
2597 }
2598 #endif
2599
2600 #ifdef HAVE_SERVER_SUPPORT
2601 static int target_bulk_timeout(void *data)
2602 {
2603         ENTRY;
2604         /* We don't fail the connection here, because having the export
2605          * killed makes the (vital) call to commitrw very sad.
2606          */
2607         RETURN(1);
2608 }
2609
2610 static inline char *bulk2type(struct ptlrpc_bulk_desc *desc)
2611 {
2612         return desc->bd_type == BULK_GET_SINK ? "GET" : "PUT";
2613 }
2614
2615 int target_bulk_io(struct obd_export *exp, struct ptlrpc_bulk_desc *desc,
2616                    struct l_wait_info *lwi)
2617 {
2618         struct ptlrpc_request   *req = desc->bd_req;
2619         time_t                   start = cfs_time_current_sec();
2620         time_t                   deadline;
2621         int                      rc = 0;
2622
2623         ENTRY;
2624
2625         /* If there is eviction in progress, wait for it to finish. */
2626         if (unlikely(atomic_read(&exp->exp_obd->obd_evict_inprogress))) {
2627                 *lwi = LWI_INTR(NULL, NULL);
2628                 rc = l_wait_event(exp->exp_obd->obd_evict_inprogress_waitq,
2629                                   !atomic_read(&exp->exp_obd->
2630                                                    obd_evict_inprogress),
2631                                   lwi);
2632         }
2633
2634         /* Check if client was evicted or reconnected already. */
2635         if (exp->exp_failed ||
2636             exp->exp_conn_cnt > lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
2637                 rc = -ENOTCONN;
2638         } else {
2639                 if (desc->bd_type == BULK_PUT_SINK)
2640                         rc = sptlrpc_svc_wrap_bulk(req, desc);
2641                 if (rc == 0)
2642                         rc = ptlrpc_start_bulk_transfer(desc);
2643         }
2644
2645         if (rc < 0) {
2646                 DEBUG_REQ(D_ERROR, req, "bulk %s failed: rc %d",
2647                           bulk2type(desc), rc);
2648                 RETURN(rc);
2649         }
2650
2651         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
2652                 ptlrpc_abort_bulk(desc);
2653                 RETURN(0);
2654         }
2655
2656         /* limit actual bulk transfer to bulk_timeout seconds */
2657         deadline = start + bulk_timeout;
2658         if (deadline > req->rq_deadline)
2659                 deadline = req->rq_deadline;
2660
2661         do {
2662                 long timeoutl = deadline - cfs_time_current_sec();
2663                 cfs_duration_t timeout = timeoutl <= 0 ?
2664                                          CFS_TICK : cfs_time_seconds(timeoutl);
2665                 time_t  rq_deadline;
2666
2667                 *lwi = LWI_TIMEOUT_INTERVAL(timeout, cfs_time_seconds(1),
2668                                             target_bulk_timeout, desc);
2669                 rc = l_wait_event(desc->bd_waitq,
2670                                   !ptlrpc_server_bulk_active(desc) ||
2671                                   exp->exp_failed ||
2672                                   exp->exp_conn_cnt >
2673                                   lustre_msg_get_conn_cnt(req->rq_reqmsg),
2674                                   lwi);
2675                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
2676                 /* Wait again if we changed rq_deadline. */
2677                 rq_deadline = ACCESS_ONCE(req->rq_deadline);
2678                 deadline = start + bulk_timeout;
2679                 if (deadline > rq_deadline)
2680                         deadline = rq_deadline;
2681         } while ((rc == -ETIMEDOUT) &&
2682                  (deadline > cfs_time_current_sec()));
2683
2684         if (rc == -ETIMEDOUT) {
2685                 DEBUG_REQ(D_ERROR, req, "timeout on bulk %s after %ld%+lds",
2686                           bulk2type(desc), deadline - start,
2687                           cfs_time_current_sec() - deadline);
2688                 ptlrpc_abort_bulk(desc);
2689         } else if (exp->exp_failed) {
2690                 DEBUG_REQ(D_ERROR, req, "Eviction on bulk %s",
2691                           bulk2type(desc));
2692                 rc = -ENOTCONN;
2693                 ptlrpc_abort_bulk(desc);
2694         } else if (exp->exp_conn_cnt >
2695                    lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
2696                 DEBUG_REQ(D_ERROR, req, "Reconnect on bulk %s",
2697                           bulk2type(desc));
2698                 /* We don't reply anyway. */
2699                 rc = -ETIMEDOUT;
2700                 ptlrpc_abort_bulk(desc);
2701         } else if (desc->bd_failure ||
2702                    desc->bd_nob_transferred != desc->bd_nob) {
2703                 DEBUG_REQ(D_ERROR, req, "%s bulk %s %d(%d)",
2704                           desc->bd_failure ? "network error on" : "truncated",
2705                           bulk2type(desc), desc->bd_nob_transferred,
2706                           desc->bd_nob);
2707                 /* XXX Should this be a different errno? */
2708                 rc = -ETIMEDOUT;
2709         } else if (desc->bd_type == BULK_GET_SINK) {
2710                 rc = sptlrpc_svc_unwrap_bulk(req, desc);
2711         }
2712
2713         RETURN(rc);
2714 }
2715 EXPORT_SYMBOL(target_bulk_io);
2716
2717 #endif /* HAVE_SERVER_SUPPORT */