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