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