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