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