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