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