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