Whamcloud - gitweb
Branch HEAD
[fs/lustre-release.git] / lustre / ldlm / ldlm_lib.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (c) 2003 Cluster File Systems, Inc.
5  *
6  *   This file is part of the Lustre file system, http://www.lustre.org
7  *   Lustre is a trademark of Cluster File Systems, Inc.
8  *
9  *   You may have signed or agreed to another license before downloading
10  *   this software.  If so, you are bound by the terms and conditions
11  *   of that agreement, and the following does not apply to you.  See the
12  *   LICENSE file included with this distribution for more information.
13  *
14  *   If you did not agree to a different license, then this copy of Lustre
15  *   is open source software; you can redistribute it and/or modify it
16  *   under the terms of version 2 of the GNU General Public License as
17  *   published by the Free Software Foundation.
18  *
19  *   In either case, Lustre is distributed in the hope that it will be
20  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
21  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   license text for more details.
23  */
24
25 #ifndef EXPORT_SYMTAB
26 # define EXPORT_SYMTAB
27 #endif
28 #define DEBUG_SUBSYSTEM S_LDLM
29
30 #ifdef __KERNEL__
31 # include <libcfs/libcfs.h>
32 #else
33 # include <liblustre.h>
34 #endif
35 #include <obd.h>
36 #include <lustre_mds.h>
37 #include <lustre_dlm.h>
38 #include <lustre_net.h>
39 #include <lustre_sec.h>
40 #include "ldlm_internal.h"
41
42
43 /* @priority: if non-zero, move the selected to the list head
44  * @create: if zero, only search in existed connections
45  */
46 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
47                            int priority, int create)
48 {
49         struct ptlrpc_connection *ptlrpc_conn;
50         struct obd_import_conn *imp_conn = NULL, *item;
51         int rc = 0;
52         ENTRY;
53
54         if (!create && !priority) {
55                 CDEBUG(D_HA, "Nothing to do\n");
56                 RETURN(-EINVAL);
57         }
58
59         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
60         if (!ptlrpc_conn) {
61                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
62                 RETURN (-ENOENT);
63         }
64
65         if (create) {
66                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
67                 if (!imp_conn) {
68                         GOTO(out_put, rc = -ENOMEM);
69                 }
70         }
71
72         spin_lock(&imp->imp_lock);
73         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
74                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
75                         if (priority) {
76                                 list_del(&item->oic_item);
77                                 list_add(&item->oic_item, &imp->imp_conn_list);
78                                 item->oic_last_attempt = 0;
79                         }
80                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
81                                imp, imp->imp_obd->obd_name, uuid->uuid,
82                                (priority ? ", moved to head" : ""));
83                         spin_unlock(&imp->imp_lock);
84                         GOTO(out_free, rc = 0);
85                 }
86         }
87         /* not found */
88         if (create) {
89                 imp_conn->oic_conn = ptlrpc_conn;
90                 imp_conn->oic_uuid = *uuid;
91                 item->oic_last_attempt = 0;
92                 if (priority)
93                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
94                 else
95                         list_add_tail(&imp_conn->oic_item, &imp->imp_conn_list);
96                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
97                        imp, imp->imp_obd->obd_name, uuid->uuid,
98                        (priority ? "head" : "tail"));
99         } else {
100                 spin_unlock(&imp->imp_lock);
101                 GOTO(out_free, rc = -ENOENT);
102         }
103
104         spin_unlock(&imp->imp_lock);
105         RETURN(0);
106 out_free:
107         if (imp_conn)
108                 OBD_FREE(imp_conn, sizeof(*imp_conn));
109 out_put:
110         ptlrpc_put_connection(ptlrpc_conn);
111         RETURN(rc);
112 }
113
114 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
115 {
116         return import_set_conn(imp, uuid, 1, 0);
117 }
118
119 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
120                            int priority)
121 {
122         return import_set_conn(imp, uuid, priority, 1);
123 }
124
125 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
126 {
127         struct obd_import_conn *imp_conn;
128         struct obd_export *dlmexp;
129         int rc = -ENOENT;
130         ENTRY;
131
132         spin_lock(&imp->imp_lock);
133         if (list_empty(&imp->imp_conn_list)) {
134                 LASSERT(!imp->imp_connection);
135                 GOTO(out, rc);
136         }
137
138         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
139                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
140                         continue;
141                 LASSERT(imp_conn->oic_conn);
142
143                 /* is current conn? */
144                 if (imp_conn == imp->imp_conn_current) {
145                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
146
147                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
148                             imp->imp_state != LUSTRE_IMP_DISCON) {
149                                 CERROR("can't remove current connection\n");
150                                 GOTO(out, rc = -EBUSY);
151                         }
152
153                         ptlrpc_put_connection(imp->imp_connection);
154                         imp->imp_connection = NULL;
155
156                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
157                         if (dlmexp && dlmexp->exp_connection) {
158                                 LASSERT(dlmexp->exp_connection ==
159                                         imp_conn->oic_conn);
160                                 ptlrpc_put_connection(dlmexp->exp_connection);
161                                 dlmexp->exp_connection = NULL;
162                         }
163                 }
164
165                 list_del(&imp_conn->oic_item);
166                 ptlrpc_put_connection(imp_conn->oic_conn);
167                 OBD_FREE(imp_conn, sizeof(*imp_conn));
168                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
169                        imp, imp->imp_obd->obd_name, uuid->uuid);
170                 rc = 0;
171                 break;
172         }
173 out:
174         spin_unlock(&imp->imp_lock);
175         if (rc == -ENOENT)
176                 CERROR("connection %s not found\n", uuid->uuid);
177         RETURN(rc);
178 }
179
180 static void destroy_import(struct obd_import *imp)
181 {
182         /* drop security policy instance after all rpc finished/aborted
183          * to let all busy contexts be released. */
184         class_import_get(imp);
185         class_destroy_import(imp);
186         sptlrpc_import_sec_put(imp);
187         class_import_put(imp);
188 }
189
190 /* configure an RPC client OBD device
191  *
192  * lcfg parameters:
193  * 1 - client UUID
194  * 2 - server UUID
195  * 3 - inactive-on-startup
196  */
197 int client_obd_setup(struct obd_device *obddev, struct lustre_cfg *lcfg)
198 {
199         struct client_obd *cli = &obddev->u.cli;
200         struct obd_import *imp;
201         struct obd_uuid server_uuid;
202         int rq_portal, rp_portal, connect_op;
203         char *name = obddev->obd_type->typ_name;
204         int rc;
205         ENTRY;
206
207         /* In a more perfect world, we would hang a ptlrpc_client off of
208          * obd_type and just use the values from there. */
209         if (!strcmp(name, LUSTRE_OSC_NAME)) {
210                 rq_portal = OST_REQUEST_PORTAL;
211                 rp_portal = OSC_REPLY_PORTAL;
212                 connect_op = OST_CONNECT;
213         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
214                 rq_portal = MDS_REQUEST_PORTAL;
215                 rp_portal = MDC_REPLY_PORTAL;
216                 connect_op = MDS_CONNECT;
217         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
218                 rq_portal = MGS_REQUEST_PORTAL;
219                 rp_portal = MGC_REPLY_PORTAL;
220                 connect_op = MGS_CONNECT;
221         } else {
222                 CERROR("unknown client OBD type \"%s\", can't setup\n",
223                        name);
224                 RETURN(-EINVAL);
225         }
226
227         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
228                 CERROR("requires a TARGET UUID\n");
229                 RETURN(-EINVAL);
230         }
231
232         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
233                 CERROR("client UUID must be less than 38 characters\n");
234                 RETURN(-EINVAL);
235         }
236
237         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
238                 CERROR("setup requires a SERVER UUID\n");
239                 RETURN(-EINVAL);
240         }
241
242         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
243                 CERROR("target UUID must be less than 38 characters\n");
244                 RETURN(-EINVAL);
245         }
246
247         sema_init(&cli->cl_sem, 1);
248         sema_init(&cli->cl_mgc_sem, 1);
249         sptlrpc_rule_set_init(&cli->cl_sptlrpc_rset);
250         cli->cl_sec_part = LUSTRE_SP_ANY;
251         cli->cl_conn_count = 0;
252         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
253                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
254                      sizeof(server_uuid)));
255
256         cli->cl_dirty = 0;
257         cli->cl_avail_grant = 0;
258         /* FIXME: should limit this for the sum of all cl_dirty_max */
259         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
260         if (cli->cl_dirty_max >> CFS_PAGE_SHIFT > num_physpages / 8)
261                 cli->cl_dirty_max = num_physpages << (CFS_PAGE_SHIFT - 3);
262         CFS_INIT_LIST_HEAD(&cli->cl_cache_waiters);
263         CFS_INIT_LIST_HEAD(&cli->cl_loi_ready_list);
264         CFS_INIT_LIST_HEAD(&cli->cl_loi_write_list);
265         CFS_INIT_LIST_HEAD(&cli->cl_loi_read_list);
266         client_obd_list_lock_init(&cli->cl_loi_list_lock);
267         cli->cl_r_in_flight = 0;
268         cli->cl_w_in_flight = 0;
269
270         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
271         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
272         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
273         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
274         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
275         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
276         cfs_waitq_init(&cli->cl_destroy_waitq);
277         atomic_set(&cli->cl_destroy_in_flight, 0);
278 #ifdef ENABLE_CHECKSUM
279         /* Turn on checksumming by default. */
280         cli->cl_checksum = 1;
281         /*
282          * The supported checksum types will be worked out at connect time
283          * Set cl_chksum* to CRC32 for now to avoid returning screwed info
284          * through procfs.
285          */
286         cli->cl_cksum_type = cli->cl_supp_cksum_types = OBD_CKSUM_CRC32;
287 #endif
288         atomic_set(&cli->cl_resends, OSC_DEFAULT_RESENDS);
289
290         /* This value may be changed at connect time in
291            ptlrpc_connect_interpret. */
292         cli->cl_max_pages_per_rpc = min((int)PTLRPC_MAX_BRW_PAGES,
293                                         (int)(1024 * 1024 >> CFS_PAGE_SHIFT));
294
295         if (!strcmp(name, LUSTRE_MDC_NAME)) {
296                 cli->cl_max_rpcs_in_flight = MDC_MAX_RIF_DEFAULT;
297         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 128 /* MB */) {
298                 cli->cl_max_rpcs_in_flight = 2;
299         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 256 /* MB */) {
300                 cli->cl_max_rpcs_in_flight = 3;
301         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 512 /* MB */) {
302                 cli->cl_max_rpcs_in_flight = 4;
303         } else {
304                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
305         }
306
307         rc = ldlm_get_ref();
308         if (rc) {
309                 CERROR("ldlm_get_ref failed: %d\n", rc);
310                 GOTO(err, rc);
311         }
312
313         ptlrpc_init_client(rq_portal, rp_portal, name,
314                            &obddev->obd_ldlm_client);
315
316         imp = class_new_import(obddev);
317         if (imp == NULL)
318                 GOTO(err_ldlm, rc = -ENOENT);
319         imp->imp_client = &obddev->obd_ldlm_client;
320         imp->imp_connect_op = connect_op;
321         imp->imp_initial_recov = 1;
322         imp->imp_initial_recov_bk = 0;
323         CFS_INIT_LIST_HEAD(&imp->imp_pinger_chain);
324         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
325                LUSTRE_CFG_BUFLEN(lcfg, 1));
326         class_import_put(imp);
327
328         rc = client_import_add_conn(imp, &server_uuid, 1);
329         if (rc) {
330                 CERROR("can't add initial connection\n");
331                 GOTO(err_import, rc);
332         }
333
334         cli->cl_import = imp;
335         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
336         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
337         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
338
339         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
340                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
341                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
342                                name, obddev->obd_name,
343                                cli->cl_target_uuid.uuid);
344                         spin_lock(&imp->imp_lock);
345                         imp->imp_invalid = 1;
346                         spin_unlock(&imp->imp_lock);
347                 }
348         }
349
350         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
351
352         RETURN(rc);
353
354 err_import:
355         class_destroy_import(imp);
356 err_ldlm:
357         ldlm_put_ref(0);
358 err:
359         RETURN(rc);
360
361 }
362
363 int client_obd_cleanup(struct obd_device *obddev)
364 {
365         ENTRY;
366         sptlrpc_rule_set_free(&obddev->u.cli.cl_sptlrpc_rset);
367         ldlm_put_ref(obddev->obd_force);
368         RETURN(0);
369 }
370
371 /* ->o_connect() method for client side (OSC and MDC and MGC) */
372 int client_connect_import(const struct lu_env *env,
373                           struct lustre_handle *dlm_handle,
374                           struct obd_device *obd, struct obd_uuid *cluuid,
375                           struct obd_connect_data *data)
376 {
377         struct client_obd *cli = &obd->u.cli;
378         struct obd_import *imp = cli->cl_import;
379         struct obd_export *exp;
380         struct obd_connect_data *ocd;
381         struct ldlm_namespace *to_be_freed = NULL;
382         int rc;
383         ENTRY;
384
385         mutex_down(&cli->cl_sem);
386         rc = class_connect(dlm_handle, obd, cluuid);
387         if (rc)
388                 GOTO(out_sem, rc);
389
390         cli->cl_conn_count++;
391         if (cli->cl_conn_count > 1)
392                 GOTO(out_sem, rc);
393         exp = class_conn2export(dlm_handle);
394
395         if (obd->obd_namespace != NULL)
396                 CERROR("already have namespace!\n");
397         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
398                                                 LDLM_NAMESPACE_CLIENT,
399                                                 LDLM_NAMESPACE_GREEDY);
400         if (obd->obd_namespace == NULL)
401                 GOTO(out_disco, rc = -ENOMEM);
402
403         imp->imp_dlm_handle = *dlm_handle;
404         rc = ptlrpc_init_import(imp);
405         if (rc != 0)
406                 GOTO(out_ldlm, rc);
407
408         ocd = &imp->imp_connect_data;
409         if (data) {
410                 *ocd = *data;
411                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
412         }
413
414         rc = ptlrpc_connect_import(imp, NULL);
415         if (rc != 0) {
416                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
417                 GOTO(out_ldlm, rc);
418         }
419         LASSERT(exp->exp_connection);
420
421         if (data) {
422                 LASSERTF((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
423                          ocd->ocd_connect_flags, "old "LPX64", new "LPX64"\n",
424                          data->ocd_connect_flags, ocd->ocd_connect_flags);
425                 data->ocd_connect_flags = ocd->ocd_connect_flags;
426         }
427
428         ptlrpc_pinger_add_import(imp);
429
430         EXIT;
431
432         if (rc) {
433 out_ldlm:
434                 ldlm_namespace_free_prior(obd->obd_namespace);
435                 to_be_freed = obd->obd_namespace;
436                 obd->obd_namespace = NULL;
437 out_disco:
438                 cli->cl_conn_count--;
439                 class_disconnect(exp);
440         } else {
441                 class_export_put(exp);
442         }
443 out_sem:
444         mutex_up(&cli->cl_sem);
445         if (to_be_freed)
446                 ldlm_namespace_free_post(to_be_freed, 1);
447
448         return rc;
449 }
450
451 int client_disconnect_export(struct obd_export *exp)
452 {
453         struct obd_device *obd = class_exp2obd(exp);
454         struct client_obd *cli;
455         struct obd_import *imp;
456         int rc = 0, err;
457         struct ldlm_namespace *to_be_freed = NULL;
458         ENTRY;
459
460         if (!obd) {
461                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
462                        exp, exp ? exp->exp_handle.h_cookie : -1);
463                 RETURN(-EINVAL);
464         }
465
466         cli = &obd->u.cli;
467         imp = cli->cl_import;
468
469         mutex_down(&cli->cl_sem);
470         if (!cli->cl_conn_count) {
471                 CERROR("disconnecting disconnected device (%s)\n",
472                        obd->obd_name);
473                 GOTO(out_sem, rc = -EINVAL);
474         }
475
476         cli->cl_conn_count--;
477         if (cli->cl_conn_count)
478                 GOTO(out_no_disconnect, rc = 0);
479
480         /* Mark import deactivated now, so we don't try to reconnect if any
481          * of the cleanup RPCs fails (e.g. ldlm cancel, etc).  We don't
482          * fully deactivate the import, or that would drop all requests. */
483         spin_lock(&imp->imp_lock);
484         imp->imp_deactive = 1;
485         spin_unlock(&imp->imp_lock);
486
487         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
488          * delete it regardless.  (It's safe to delete an import that was
489          * never added.) */
490         (void)ptlrpc_pinger_del_import(imp);
491
492         if (obd->obd_namespace != NULL) {
493                 /* obd_force == local only */
494                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
495                                        obd->obd_force ? LDLM_FL_LOCAL_ONLY:0,
496                                        NULL);
497                 ldlm_namespace_free_prior(obd->obd_namespace);
498                 to_be_freed = obd->obd_namespace;
499         }
500
501         rc = ptlrpc_disconnect_import(imp, 0);
502
503         ptlrpc_invalidate_import(imp);
504         /* set obd_namespace to NULL only after invalidate, because we can have
505          * some connect requests in flight, and his need store a connect flags
506          * in obd_namespace. bug 14260 */
507         obd->obd_namespace = NULL;
508
509         ptlrpc_free_rq_pool(imp->imp_rq_pool);
510         destroy_import(imp);
511         cli->cl_import = NULL;
512
513         EXIT;
514  out_no_disconnect:
515         err = class_disconnect(exp);
516         if (!rc && err)
517                 rc = err;
518  out_sem:
519         mutex_up(&cli->cl_sem);
520         if (to_be_freed)
521                 ldlm_namespace_free_post(to_be_freed, obd->obd_force);
522
523         RETURN(rc);
524 }
525
526 /* --------------------------------------------------------------------------
527  * from old lib/target.c
528  * -------------------------------------------------------------------------- */
529
530 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
531                             struct obd_uuid *cluuid, int initial_conn)
532 {
533         ENTRY;
534         if (exp->exp_connection && exp->exp_imp_reverse && !initial_conn) {
535                 struct lustre_handle *hdl;
536                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
537                 /* Might be a re-connect after a partition. */
538                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
539                         CWARN("%s: %s reconnecting\n", exp->exp_obd->obd_name,
540                               cluuid->uuid);
541                         conn->cookie = exp->exp_handle.h_cookie;
542                         /* target_handle_connect() treats EALREADY and
543                          * -EALREADY differently.  EALREADY means we are
544                          * doing a valid reconnect from the same client. */
545                         RETURN(EALREADY);
546                 } else {
547                         CERROR("%s reconnecting from %s, "
548                                "handle mismatch (ours "LPX64", theirs "
549                                LPX64")\n", cluuid->uuid,
550                                exp->exp_connection->c_remote_uuid.uuid,
551                                hdl->cookie, conn->cookie);
552                         memset(conn, 0, sizeof *conn);
553                         /* target_handle_connect() treats EALREADY and
554                          * -EALREADY differently.  -EALREADY is an error
555                          * (same UUID, different handle). */
556                         RETURN(-EALREADY);
557                 }
558         }
559
560         conn->cookie = exp->exp_handle.h_cookie;
561         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
562                cluuid->uuid, exp, conn->cookie);
563         RETURN(0);
564 }
565
566 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
567                           int error)
568 {
569         struct obd_export *exp = cb_data;
570
571         CDEBUG(D_RPCTRACE, "%s: committing for initial connect of %s\n",
572                obd->obd_name, exp->exp_client_uuid.uuid);
573
574         spin_lock(&exp->exp_lock);
575         exp->exp_need_sync = 0;
576         spin_unlock(&exp->exp_lock);
577 }
578 EXPORT_SYMBOL(target_client_add_cb);
579
580 int target_handle_connect(struct ptlrpc_request *req)
581 {
582         struct obd_device *target, *targref = NULL;
583         struct obd_export *export = NULL;
584         struct obd_import *revimp;
585         struct lustre_handle conn;
586         struct lustre_handle *tmp;
587         struct obd_uuid tgtuuid;
588         struct obd_uuid cluuid;
589         struct obd_uuid remote_uuid;
590         char *str;
591         int rc = 0;
592         int initial_conn = 0;
593         struct obd_connect_data *data, *tmpdata;
594         ENTRY;
595
596         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
597
598         str = req_capsule_client_get(&req->rq_pill, &RMF_TGTUUID);
599         if (str == NULL) {
600                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
601                 GOTO(out, rc = -EINVAL);
602         }
603
604         obd_str2uuid(&tgtuuid, str);
605         target = class_uuid2obd(&tgtuuid);
606         if (!target)
607                 target = class_name2obd(str);
608
609         if (!target || target->obd_stopping || !target->obd_set_up) {
610                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
611                                    " for connect (%s)\n", str,
612                                    !target ? "no target" :
613                                    (target->obd_stopping ? "stopping" :
614                                    "not set up"));
615                 GOTO(out, rc = -ENODEV);
616         }
617
618         if (target->obd_no_conn) {
619                 LCONSOLE_WARN("%s: temporarily refusing client connection "
620                               "from %s\n", target->obd_name,
621                               libcfs_nid2str(req->rq_peer.nid));
622                 GOTO(out, rc = -EAGAIN);
623         }
624
625         /* Make sure the target isn't cleaned up while we're here. Yes,
626            there's still a race between the above check and our incref here.
627            Really, class_uuid2obd should take the ref. */
628         targref = class_incref(target);
629
630
631         str = req_capsule_client_get(&req->rq_pill, &RMF_CLUUID);
632         if (str == NULL) {
633                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
634                 GOTO(out, rc = -EINVAL);
635         }
636
637         obd_str2uuid(&cluuid, str);
638
639         /* XXX extract a nettype and format accordingly */
640         switch (sizeof(lnet_nid_t)) {
641                 /* NB the casts only avoid compiler warnings */
642         case 8:
643                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
644                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
645                 break;
646         case 4:
647                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
648                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
649                 break;
650         default:
651                 LBUG();
652         }
653
654         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
655         if (tmp == NULL)
656                 GOTO(out, rc = -EPROTO);
657
658         conn = *tmp;
659
660         data = req_capsule_client_get(&req->rq_pill, &RMF_CONNECT_DATA);
661         if (!data)
662                 GOTO(out, rc = -EPROTO);
663
664         rc = req_capsule_server_pack(&req->rq_pill);
665         if (rc)
666                 GOTO(out, rc);
667
668         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
669                 if (!data) {
670                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
671                                   "libclient connection attempt");
672                         GOTO(out, rc = -EPROTO);
673                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
674                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
675                            data->ocd_version > LUSTRE_VERSION_CODE +
676                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
677                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
678                                   "libclient connection attempt",
679                                   data->ocd_version < LUSTRE_VERSION_CODE ?
680                                   "old" : "new",
681                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
682                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
683                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
684                                   OBD_OCD_VERSION_FIX(data->ocd_version));
685                         data = req_capsule_server_sized_get(&req->rq_pill,
686                                                         &RMF_CONNECT_DATA,
687                                     offsetof(typeof(*data), ocd_version) +
688                                              sizeof(data->ocd_version));
689                         if (data) {
690                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
691                                 data->ocd_version = LUSTRE_VERSION_CODE;
692                         }
693                         GOTO(out, rc = -EPROTO);
694                 }
695         }
696
697         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
698                 initial_conn = 1;
699
700         /* lctl gets a backstage, all-access pass. */
701         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
702                 goto dont_check_exports;
703
704         spin_lock(&target->obd_dev_lock);
705         export = lustre_hash_get_object_by_key(target->obd_uuid_hash_body, &cluuid);
706
707         if (export != NULL && export->exp_connecting) { /* bug 9635, et. al. */
708                 CWARN("%s: exp %p already connecting\n",
709                       export->exp_obd->obd_name, export);
710                 class_export_put(export);
711                 export = NULL;
712                 rc = -EALREADY;
713         } else if (export != NULL && export->exp_connection != NULL &&
714                    req->rq_peer.nid != export->exp_connection->c_peer.nid) {
715                 /* make darn sure this is coming from the same peer
716                  * if the UUIDs matched */
717                   CWARN("%s: cookie %s seen on new NID %s when "
718                           "existing NID %s is already connected\n",
719                         target->obd_name, cluuid.uuid,
720                   libcfs_nid2str(req->rq_peer.nid),
721                   libcfs_nid2str(export->exp_connection->c_peer.nid));
722                   class_export_put(export);
723                   export = NULL;
724                   rc = -EALREADY;
725         } else if (export != NULL) {
726                 spin_lock(&export->exp_lock);
727                 export->exp_connecting = 1;
728                 spin_unlock(&export->exp_lock);
729                 class_export_put(export);
730                 spin_unlock(&target->obd_dev_lock);
731                 LASSERT(export->exp_obd == target);
732
733                 rc = target_handle_reconnect(&conn, export, &cluuid, initial_conn);
734         }
735
736         /* If we found an export, we already unlocked. */
737         if (!export) {
738                 spin_unlock(&target->obd_dev_lock);
739                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
740         } else if (req->rq_export == NULL &&
741                    atomic_read(&export->exp_rpc_count) > 0) {
742                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
743                       target->obd_name, cluuid.uuid,
744                       libcfs_nid2str(req->rq_peer.nid),
745                       export, atomic_read(&export->exp_refcount));
746                 GOTO(out, rc = -EBUSY);
747         } else if (req->rq_export != NULL &&
748                    (atomic_read(&export->exp_rpc_count) > 1)) {
749                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
750                       target->obd_name, cluuid.uuid,
751                       libcfs_nid2str(req->rq_peer.nid),
752                       export, atomic_read(&export->exp_rpc_count));
753                 GOTO(out, rc = -EBUSY);
754         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1 &&
755                    !initial_conn) {
756                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
757                        "cookies not random?\n", target->obd_name,
758                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
759                 GOTO(out, rc = -EALREADY);
760         } else {
761                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
762                 if (req->rq_export == NULL && initial_conn)
763                        export->exp_last_request_time =
764                                max(export->exp_last_request_time,
765                                    (time_t)CURRENT_SECONDS);
766         }
767
768         /* We want to handle EALREADY but *not* -EALREADY from
769          * target_handle_reconnect(), return reconnection state in a flag */
770         if (rc == EALREADY) {
771                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
772                 rc = 0;
773         } else if (rc) {
774                 GOTO(out, rc);
775         }
776         /* Tell the client if we're in recovery. */
777         /* If this is the first client, start the recovery timer */
778         CWARN("%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
779                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
780               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
781               export, (long)CURRENT_SECONDS,
782               export ? (long)export->exp_last_request_time : 0);
783
784
785         if (target->obd_recovering) {
786                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
787                 target_start_recovery_timer(target);
788         }
789
790         /* Tell the client if we support replayable requests */
791         if (target->obd_replayable)
792                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
793
794         if (export == NULL) {
795                 if (target->obd_recovering) {
796                         cfs_time_t t;
797
798                         t = cfs_timer_deadline(&target->obd_recovery_timer);
799                         t = cfs_time_sub(t, cfs_time_current());
800                         CERROR("%s: denying connection for new client %s (%s): "
801                                "%d clients in recovery for %lds\n",
802                                target->obd_name,
803                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
804                                target->obd_recoverable_clients,
805                                cfs_duration_sec(t));
806                         rc = -EBUSY;
807                 } else {
808 dont_check_exports:
809                         rc = obd_connect(req->rq_svc_thread->t_env,
810                                          &conn, target, &cluuid, data);
811                 }
812         } else {
813                 rc = obd_reconnect(req->rq_svc_thread->t_env,
814                                    export, target, &cluuid, data);
815         }
816         if (rc)
817                 GOTO(out, rc);
818         /* Return only the parts of obd_connect_data that we understand, so the
819          * client knows that we don't understand the rest. */
820         if (data) {
821                  tmpdata = req_capsule_server_get(&req->rq_pill,
822                                                   &RMF_CONNECT_DATA);
823                   //data->ocd_connect_flags &= OBD_CONNECT_SUPPORTED;
824                  *tmpdata = *data;
825         }
826                   
827         /* If all else goes well, this is our RPC return code. */
828         req->rq_status = 0;
829
830         lustre_msg_set_handle(req->rq_repmsg, &conn);
831
832         /* ownership of this export ref transfers to the request AFTER we
833          * drop any previous reference the request had, but we don't want
834          * that to go to zero before we get our new export reference. */
835         export = class_conn2export(&conn);
836         if (!export) {
837                 DEBUG_REQ(D_ERROR, req, "Missing export!");
838                 GOTO(out, rc = -ENODEV);
839         }
840
841         /* If the client and the server are the same node, we will already
842          * have an export that really points to the client's DLM export,
843          * because we have a shared handles table.
844          *
845          * XXX this will go away when shaver stops sending the "connect" handle
846          * in the real "remote handle" field of the request --phik 24 Apr 2003
847          */
848         if (req->rq_export != NULL)
849                 class_export_put(req->rq_export);
850
851         req->rq_export = export;
852
853         spin_lock(&export->exp_lock);
854         if (initial_conn) {
855                 lustre_msg_set_conn_cnt(req->rq_repmsg, export->exp_conn_cnt + 1);
856         } else if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
857                 spin_unlock(&export->exp_lock);
858                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
859                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
860                        export->exp_conn_cnt,
861                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
862
863                 GOTO(out, rc = -EALREADY);
864         }
865         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
866
867         /* request from liblustre?  Don't evict it for not pinging. */
868         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
869                 export->exp_libclient = 1;
870                 spin_unlock(&export->exp_lock);
871
872                 spin_lock(&target->obd_dev_lock);
873                 list_del_init(&export->exp_obd_chain_timed);
874                 spin_unlock(&target->obd_dev_lock);
875         } else {
876                 spin_unlock(&export->exp_lock);
877         }
878
879         if (export->exp_connection != NULL)
880                 ptlrpc_put_connection(export->exp_connection);
881         export->exp_connection = ptlrpc_get_connection(req->rq_peer,
882                                                        req->rq_self,
883                                                        &remote_uuid);
884
885         spin_lock(&target->obd_dev_lock);
886         /* Export might be hashed already, e.g. if this is reconnect */
887         if (hlist_unhashed(&export->exp_nid_hash))
888                 lustre_hash_additem(export->exp_obd->obd_nid_hash_body,
889                                     &export->exp_connection->c_peer.nid,
890                                     &export->exp_nid_hash);
891         spin_unlock(&target->obd_dev_lock);
892
893         spin_lock_bh(&target->obd_processing_task_lock);
894         if (target->obd_recovering && !export->exp_in_recovery) {
895                 spin_lock(&export->exp_lock);
896                 export->exp_in_recovery = 1;
897                 export->exp_req_replay_needed = 1;
898                 export->exp_lock_replay_needed = 1;
899                 spin_unlock(&export->exp_lock);
900                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
901                      && (data->ocd_transno == 0))
902                         CWARN("Connect with zero transno!\n");
903
904                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
905                      && data->ocd_transno < target->obd_next_recovery_transno)
906                         target->obd_next_recovery_transno = data->ocd_transno;
907                 target->obd_connected_clients++;
908                 /* each connected client is counted as recoverable */
909                 target->obd_recoverable_clients++;
910                 atomic_inc(&target->obd_req_replay_clients);
911                 atomic_inc(&target->obd_lock_replay_clients);
912                 if (target->obd_connected_clients ==
913                     target->obd_max_recoverable_clients)
914                         wake_up(&target->obd_next_transno_waitq);
915         }
916         spin_unlock_bh(&target->obd_processing_task_lock);
917         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
918         conn = *tmp;
919
920         if (export->exp_imp_reverse != NULL) {
921                 /* destroyed import can be still referenced in ctxt */
922                 obd_set_info_async(export, strlen(KEY_REVIMP_UPD),
923                                    KEY_REVIMP_UPD, 0, NULL, NULL);
924
925                 /* in some recovery senarios, previous ctx init rpc handled
926                  * in sptlrpc_target_export_check() might be used to install
927                  * a reverse ctx in this reverse import, and later OBD_CONNECT
928                  * using the same gss ctx could reach here and following new
929                  * reverse import. note all reverse ctx in new/old import are
930                  * actually based on the same gss ctx. so we invalidate ctx
931                  * here before destroy import, otherwise flush old import will
932                  * lead to remote reverse ctx be destroied, thus the reverse
933                  * ctx of new import will lost its peer.
934                  * there might be a better way to deal with this???
935                  */
936                 sptlrpc_import_inval_all_ctx(export->exp_imp_reverse);
937
938                 destroy_import(export->exp_imp_reverse);
939         }
940
941         /* for the rest part, we return -ENOTCONN in case of errors
942          * in order to let client initialize connection again.
943          */
944         revimp = export->exp_imp_reverse = class_new_import(target);
945         if (!revimp) {
946                 CERROR("fail to alloc new reverse import.\n");
947                 GOTO(out, rc = -ENOTCONN);
948         }
949
950         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
951         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
952         revimp->imp_remote_handle = conn;
953         revimp->imp_dlm_fake = 1;
954         revimp->imp_state = LUSTRE_IMP_FULL;
955
956         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_NEXT_VER) {
957                 revimp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
958                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_NEXT_VER);
959         }
960
961         rc = sptlrpc_import_sec_adapt(revimp, req->rq_svc_ctx,
962                                       req->rq_flvr.sf_rpc);
963         if (rc) {
964                 CERROR("Failed to get sec for reverse import: %d\n", rc);
965                 export->exp_imp_reverse = NULL;
966                 class_destroy_import(revimp);
967         }
968
969         class_import_put(revimp);
970 out:
971         if (export) {
972                 spin_lock(&export->exp_lock);
973                 export->exp_connecting = 0;
974                 spin_unlock(&export->exp_lock);
975         }
976         if (targref)
977                 class_decref(targref);
978         if (rc)
979                 req->rq_status = rc;
980         RETURN(rc);
981 }
982
983 int target_handle_disconnect(struct ptlrpc_request *req)
984 {
985         int rc;
986         ENTRY;
987
988         rc = req_capsule_server_pack(&req->rq_pill);
989         if (rc)
990                 RETURN(rc);
991
992         /* keep the rq_export around so we can send the reply */
993         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
994
995         RETURN(0);
996 }
997
998 void target_destroy_export(struct obd_export *exp)
999 {
1000         /* exports created from last_rcvd data, and "fake"
1001            exports created by lctl don't have an import */
1002         if (exp->exp_imp_reverse != NULL)
1003                 destroy_import(exp->exp_imp_reverse);
1004
1005         /* We cancel locks at disconnect time, but this will catch any locks
1006          * granted in a race with recovery-induced disconnect. */
1007         if (exp->exp_obd->obd_namespace != NULL)
1008                 ldlm_cancel_locks_for_export(exp);
1009 }
1010
1011 /*
1012  * Recovery functions
1013  */
1014
1015 struct ptlrpc_request *ptlrpc_clone_req( struct ptlrpc_request *orig_req)
1016 {
1017         struct ptlrpc_request *copy_req;
1018         struct lustre_msg *copy_reqmsg;
1019         struct ptlrpc_user_desc *udesc = NULL;
1020
1021         OBD_ALLOC_PTR(copy_req);
1022         if (!copy_req)
1023                 return NULL;
1024         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
1025         if (!copy_reqmsg){
1026                 OBD_FREE_PTR(copy_req);
1027                 return NULL;
1028         }
1029
1030         if (orig_req->rq_user_desc) {
1031                 int ngroups = orig_req->rq_user_desc->pud_ngroups;
1032
1033                 OBD_ALLOC(udesc, sptlrpc_user_desc_size(ngroups));
1034                 if (!udesc) {
1035                         OBD_FREE(copy_reqmsg, orig_req->rq_reqlen);
1036                         OBD_FREE_PTR(copy_req);
1037                         return NULL;
1038                 }
1039                 memcpy(udesc, orig_req->rq_user_desc,
1040                        sptlrpc_user_desc_size(ngroups));
1041         }
1042
1043         *copy_req = *orig_req;
1044         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
1045         copy_req->rq_reqmsg = copy_reqmsg;
1046         copy_req->rq_user_desc = udesc;
1047
1048         class_export_get(copy_req->rq_export);
1049         CFS_INIT_LIST_HEAD(&copy_req->rq_list);
1050         sptlrpc_svc_ctx_addref(copy_req);
1051
1052         if (copy_req->rq_reply_state) {
1053                 /* the copied req takes over the reply state */
1054                 orig_req->rq_reply_state = NULL;
1055                 /* to catch further access */
1056                 orig_req->rq_repmsg = NULL;
1057                 orig_req->rq_replen = 0;
1058         }
1059
1060         return copy_req;
1061 }
1062
1063 void ptlrpc_free_clone( struct ptlrpc_request *req)
1064 {
1065         if (req->rq_reply_state) {
1066                 ptlrpc_rs_decref(req->rq_reply_state);
1067                 req->rq_reply_state = NULL;
1068         }
1069
1070         sptlrpc_svc_ctx_decref(req);
1071         class_export_put(req->rq_export);
1072         list_del(&req->rq_list);
1073
1074         if (req->rq_user_desc) {
1075                 int ngroups = req->rq_user_desc->pud_ngroups;
1076                 OBD_FREE(req->rq_user_desc, sptlrpc_user_desc_size(ngroups));
1077         }
1078         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1079         OBD_FREE_PTR(req);
1080 }
1081
1082 #ifdef __KERNEL__
1083 static void target_finish_recovery(struct obd_device *obd)
1084 {
1085         ENTRY;
1086         LCONSOLE_INFO("%s: sending delayed replies to recovered clients\n",
1087                       obd->obd_name);
1088
1089         ldlm_reprocess_all_ns(obd->obd_namespace);
1090
1091         /* when recovery finished, cleanup orphans on mds and ost */
1092         if (OBT(obd) && OBP(obd, postrecov)) {
1093                 int rc = OBP(obd, postrecov)(obd);
1094                 LCONSOLE_WARN("%s: recovery %s: rc %d\n", obd->obd_name,
1095                               rc < 0 ? "failed" : "complete", rc);
1096         }
1097
1098         obd->obd_recovery_end = CURRENT_SECONDS;
1099         EXIT;
1100 }
1101
1102 static void abort_req_replay_queue(struct obd_device *obd)
1103 {
1104         struct ptlrpc_request *req, *n;
1105
1106         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1107                 DEBUG_REQ(D_WARNING, req, "aborted:");
1108                 req->rq_status = -ENOTCONN;
1109                 if (ptlrpc_error(req)) {
1110                         DEBUG_REQ(D_ERROR, req,
1111                                   "failed abort_req_reply; skipping");
1112                 }
1113                 ptlrpc_free_clone(req);
1114         }
1115 }
1116
1117 static void abort_lock_replay_queue(struct obd_device *obd)
1118 {
1119         struct ptlrpc_request *req, *n;
1120
1121         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1122                 DEBUG_REQ(D_ERROR, req, "aborted:");
1123                 req->rq_status = -ENOTCONN;
1124                 if (ptlrpc_error(req)) {
1125                         DEBUG_REQ(D_ERROR, req,
1126                                   "failed abort_lock_reply; skipping");
1127                 }
1128                 ptlrpc_free_clone(req);
1129         }
1130 }
1131 #endif
1132
1133 /* Called from a cleanup function if the device is being cleaned up
1134    forcefully.  The exports should all have been disconnected already,
1135    the only thing left to do is
1136      - clear the recovery flags
1137      - cancel the timer
1138      - free queued requests and replies, but don't send replies
1139    Because the obd_stopping flag is set, no new requests should be received.
1140
1141 */
1142 void target_cleanup_recovery(struct obd_device *obd)
1143 {
1144         struct ptlrpc_request *req, *n;
1145         ENTRY;
1146
1147         LASSERT(obd->obd_stopping);
1148
1149         spin_lock_bh(&obd->obd_processing_task_lock);
1150         if (!obd->obd_recovering) {
1151                 spin_unlock_bh(&obd->obd_processing_task_lock);
1152                 EXIT;
1153                 return;
1154         }
1155         obd->obd_recovering = obd->obd_abort_recovery = 0;
1156         target_cancel_recovery_timer(obd);
1157         spin_unlock_bh(&obd->obd_processing_task_lock);
1158
1159         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1160                 LASSERT (req->rq_reply_state == 0);
1161                 ptlrpc_free_clone(req);
1162         }
1163         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1164                 LASSERT (req->rq_reply_state == 0);
1165                 ptlrpc_free_clone(req);
1166         }
1167         list_for_each_entry_safe(req, n, &obd->obd_final_req_queue, rq_list) {
1168                 LASSERT (req->rq_reply_state == 0);
1169                 ptlrpc_free_clone(req);
1170         }
1171
1172         EXIT;
1173 }
1174
1175 static void target_recovery_expired(unsigned long castmeharder)
1176 {
1177         struct obd_device *obd = (struct obd_device *)castmeharder;
1178         CERROR("%s: recovery timed out, aborting\n", obd->obd_name);
1179         spin_lock_bh(&obd->obd_processing_task_lock);
1180         if (obd->obd_recovering)
1181                 obd->obd_abort_recovery = 1;
1182         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1183         spin_unlock_bh(&obd->obd_processing_task_lock);
1184 }
1185
1186
1187 /* obd_processing_task_lock should be held */
1188 void target_cancel_recovery_timer(struct obd_device *obd)
1189 {
1190         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1191         cfs_timer_disarm(&obd->obd_recovery_timer);
1192 }
1193
1194 static void reset_recovery_timer(struct obd_device *obd)
1195 {
1196         time_t timeout_shift = OBD_RECOVERY_TIMEOUT;
1197         spin_lock_bh(&obd->obd_processing_task_lock);
1198         if (!obd->obd_recovering) {
1199                 spin_unlock_bh(&obd->obd_processing_task_lock);
1200                 return;
1201         }
1202         if (cfs_time_current_sec() + OBD_RECOVERY_TIMEOUT > 
1203             obd->obd_recovery_start + obd->obd_recovery_max_time)
1204                 timeout_shift = obd->obd_recovery_start + 
1205                         obd->obd_recovery_max_time - cfs_time_current_sec();
1206         cfs_timer_arm(&obd->obd_recovery_timer, cfs_time_shift(timeout_shift));
1207         spin_unlock_bh(&obd->obd_processing_task_lock);
1208         CDEBUG(D_HA, "%s: timer will expire in %u seconds\n", obd->obd_name,
1209                (unsigned int)timeout_shift);
1210         /* Only used for lprocfs_status */
1211         obd->obd_recovery_end = CURRENT_SECONDS + timeout_shift;
1212 }
1213
1214
1215 /* Only start it the first time called */
1216 void target_start_recovery_timer(struct obd_device *obd)
1217 {
1218         spin_lock_bh(&obd->obd_processing_task_lock);
1219         if (obd->obd_recovery_handler
1220             || timer_pending((struct timer_list *)&obd->obd_recovery_timer)) {
1221                 spin_unlock_bh(&obd->obd_processing_task_lock);
1222                 return;
1223         }
1224         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1225               OBD_RECOVERY_TIMEOUT);
1226         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1227         spin_unlock_bh(&obd->obd_processing_task_lock);
1228
1229         reset_recovery_timer(obd);
1230 }
1231
1232 #ifdef __KERNEL__
1233 static int check_for_next_transno(struct obd_device *obd)
1234 {
1235         struct ptlrpc_request *req = NULL;
1236         int wake_up = 0, connected, completed, queue_len, max;
1237         __u64 next_transno, req_transno;
1238         ENTRY;
1239         spin_lock_bh(&obd->obd_processing_task_lock);
1240
1241         if (!list_empty(&obd->obd_req_replay_queue)) {
1242                 req = list_entry(obd->obd_req_replay_queue.next,
1243                                  struct ptlrpc_request, rq_list);
1244                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1245         } else {
1246                 req_transno = 0;
1247         }
1248
1249         max = obd->obd_max_recoverable_clients;
1250         connected = obd->obd_connected_clients;
1251         completed = connected - obd->obd_recoverable_clients;
1252         queue_len = obd->obd_requests_queued_for_recovery;
1253         next_transno = obd->obd_next_recovery_transno;
1254
1255         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1256                "req_transno: "LPU64", next_transno: "LPU64"\n",
1257                max, connected, completed, queue_len, req_transno, next_transno);
1258
1259         if (obd->obd_abort_recovery) {
1260                 CDEBUG(D_HA, "waking for aborted recovery\n");
1261                 wake_up = 1;
1262         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1263                 CDEBUG(D_HA, "waking for completed recovery\n");
1264                 wake_up = 1;
1265         } else if (req_transno == next_transno) {
1266                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1267                 wake_up = 1;
1268         } else if (queue_len + completed == max) {
1269                 /* handle gaps occured due to lost reply. It is allowed gaps
1270                  * because all clients are connected and there will be resend
1271                  * for missed transaction */
1272                 LASSERTF(req_transno >= next_transno,
1273                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1274                          req_transno, next_transno);
1275
1276                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1277                        "waking for skipped transno (skip: "LPD64
1278                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1279                        next_transno, queue_len, completed, connected, req_transno);
1280                 obd->obd_next_recovery_transno = req_transno;
1281                 wake_up = 1;
1282         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1283                 /* some clients haven't connected in time, but we can try
1284                  * to replay requests that demand on already committed ones
1285                  * also, we can replay first non-committed transation */
1286                 LASSERT(req_transno != 0);
1287                 if (req_transno == obd->obd_last_committed + 1) {
1288                         obd->obd_next_recovery_transno = req_transno;
1289                 } else if (req_transno > obd->obd_last_committed) {
1290                         /* can't continue recovery: have no needed transno */
1291                         obd->obd_abort_recovery = 1;
1292                         CDEBUG(D_ERROR, "abort due to missed clients. max: %d, "
1293                                "connected: %d, completed: %d, queue_len: %d, "
1294                                "req_transno: "LPU64", next_transno: "LPU64"\n",
1295                                max, connected, completed, queue_len,
1296                                req_transno, next_transno);
1297                 }
1298                 wake_up = 1;
1299         }
1300
1301         spin_unlock_bh(&obd->obd_processing_task_lock);
1302         return wake_up;
1303 }
1304
1305 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1306 {
1307         struct l_wait_info lwi = { 0 };
1308         struct ptlrpc_request *req;
1309
1310         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1311                obd->obd_next_recovery_transno);
1312         l_wait_event(obd->obd_next_transno_waitq,
1313                      check_for_next_transno(obd), &lwi);
1314
1315         spin_lock_bh(&obd->obd_processing_task_lock);
1316         if (obd->obd_abort_recovery) {
1317                 req = NULL;
1318         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1319                 req = list_entry(obd->obd_req_replay_queue.next,
1320                                  struct ptlrpc_request, rq_list);
1321                 list_del_init(&req->rq_list);
1322                 obd->obd_requests_queued_for_recovery--;
1323         } else {
1324                 req = NULL;
1325         }
1326         spin_unlock_bh(&obd->obd_processing_task_lock);
1327         RETURN(req);
1328 }
1329
1330 static int check_for_next_lock(struct obd_device *obd)
1331 {
1332         struct ptlrpc_request *req = NULL;
1333         int wake_up = 0;
1334
1335         spin_lock_bh(&obd->obd_processing_task_lock);
1336         if (!list_empty(&obd->obd_lock_replay_queue)) {
1337                 req = list_entry(obd->obd_lock_replay_queue.next,
1338                                  struct ptlrpc_request, rq_list);
1339                 CDEBUG(D_HA, "waking for next lock\n");
1340                 wake_up = 1;
1341         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1342                 CDEBUG(D_HA, "waking for completed lock replay\n");
1343                 wake_up = 1;
1344         } else if (obd->obd_abort_recovery) {
1345                 CDEBUG(D_HA, "waking for aborted recovery\n");
1346                 wake_up = 1;
1347         }
1348         spin_unlock_bh(&obd->obd_processing_task_lock);
1349
1350         return wake_up;
1351 }
1352
1353 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1354 {
1355         struct l_wait_info lwi = { 0 };
1356         struct ptlrpc_request *req;
1357
1358         CDEBUG(D_HA, "Waiting for lock\n");
1359         l_wait_event(obd->obd_next_transno_waitq,
1360                      check_for_next_lock(obd), &lwi);
1361
1362         spin_lock_bh(&obd->obd_processing_task_lock);
1363         if (obd->obd_abort_recovery) {
1364                 req = NULL;
1365         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1366                 req = list_entry(obd->obd_lock_replay_queue.next,
1367                                  struct ptlrpc_request, rq_list);
1368                 list_del_init(&req->rq_list);
1369         } else {
1370                 req = NULL;
1371         }
1372         spin_unlock_bh(&obd->obd_processing_task_lock);
1373         return req;
1374 }
1375
1376 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1377 {
1378         struct ptlrpc_request *req;
1379
1380         spin_lock_bh(&obd->obd_processing_task_lock);
1381         if (!list_empty(&obd->obd_final_req_queue)) {
1382                 req = list_entry(obd->obd_final_req_queue.next,
1383                                  struct ptlrpc_request, rq_list);
1384                 list_del_init(&req->rq_list);
1385         } else {
1386                 req = NULL;
1387         }
1388         spin_unlock_bh(&obd->obd_processing_task_lock);
1389         return req;
1390 }
1391
1392 static inline int req_replay_done(struct obd_export *exp)
1393 {
1394         return (exp->exp_req_replay_needed == 0);
1395 }
1396
1397 static inline int lock_replay_done(struct obd_export *exp)
1398 {
1399         return (exp->exp_lock_replay_needed == 0);
1400 }
1401
1402 static inline int connect_done(struct obd_export *exp)
1403 {
1404         return (exp->exp_in_recovery != 0);
1405 }
1406
1407 static int check_for_clients(struct obd_device *obd)
1408 {
1409         if (obd->obd_abort_recovery)
1410                 return 1;
1411         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1412         if (obd->obd_no_conn == 0 &&
1413             obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1414                 return 1;
1415         return 0;
1416 }
1417
1418 static int handle_recovery_req(struct ptlrpc_thread *thread,
1419                                struct ptlrpc_request *req,
1420                                svc_handler_t handler)
1421 {
1422         int rc;
1423         ENTRY;
1424
1425         rc = lu_context_init(&req->rq_session, LCT_SESSION);
1426         if (rc) {
1427                 CERROR("Failure to initialize session: %d\n", rc);
1428                 return rc;
1429         }
1430         req->rq_session.lc_thread = thread;
1431         lu_context_enter(&req->rq_session);
1432         req->rq_svc_thread = thread;
1433         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1434
1435         /* thread context */
1436         lu_context_enter(&thread->t_env->le_ctx);
1437         (void)handler(req);
1438         lu_context_exit(&thread->t_env->le_ctx);
1439
1440         lu_context_exit(&req->rq_session);
1441         lu_context_fini(&req->rq_session);
1442         /* don't reset timer for final stage */
1443         if (!req_replay_done(req->rq_export) ||
1444             !lock_replay_done(req->rq_export))
1445                 reset_recovery_timer(class_exp2obd(req->rq_export));
1446         ptlrpc_free_clone(req);
1447         RETURN(0);
1448 }
1449
1450 static int target_recovery_thread(void *arg)
1451 {
1452         struct obd_device *obd = arg;
1453         struct ptlrpc_request *req;
1454         struct target_recovery_data *trd = &obd->obd_recovery_data;
1455         struct l_wait_info lwi = { 0 };
1456         unsigned long delta;
1457         unsigned long flags;
1458         struct lu_env env;
1459         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1460         __u32 recov_ctx_tags = LCT_MD_THREAD;
1461         int rc = 0;
1462         ENTRY;
1463
1464         cfs_daemonize("tgt_recov");
1465
1466         SIGNAL_MASK_LOCK(current, flags);
1467         sigfillset(&current->blocked);
1468         RECALC_SIGPENDING;
1469         SIGNAL_MASK_UNLOCK(current, flags);
1470
1471         rc = lu_context_init(&env.le_ctx, recov_ctx_tags);
1472         if (rc)
1473                 RETURN(rc);
1474
1475         thread->t_env = &env;
1476         env.le_ctx.lc_thread = thread;
1477
1478         CERROR("%s: started recovery thread pid %d\n", obd->obd_name,
1479                current->pid);
1480         trd->trd_processing_task = current->pid;
1481
1482         obd->obd_recovering = 1;
1483         complete(&trd->trd_starting);
1484
1485         /* first of all, we have to know the first transno to replay */
1486         obd->obd_abort_recovery = 0;
1487         l_wait_event(obd->obd_next_transno_waitq,
1488                      check_for_clients(obd), &lwi);
1489
1490         spin_lock_bh(&obd->obd_processing_task_lock);
1491         target_cancel_recovery_timer(obd);
1492         spin_unlock_bh(&obd->obd_processing_task_lock);
1493
1494         /* If some clients haven't connected in time, evict them */
1495         if (obd->obd_abort_recovery) {
1496                 CWARN("Some clients haven't connect in time (%d/%d),"
1497                        "evict them\n", obd->obd_connected_clients,
1498                        obd->obd_max_recoverable_clients);
1499                 obd->obd_abort_recovery = obd->obd_stopping;
1500                 class_disconnect_stale_exports(obd, connect_done);
1501         }
1502         /* next stage: replay requests */
1503         delta = jiffies;
1504         obd->obd_req_replaying = 1;
1505         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1506               atomic_read(&obd->obd_req_replay_clients),
1507               obd->obd_next_recovery_transno);
1508         while ((req = target_next_replay_req(obd))) {
1509                 LASSERT(trd->trd_processing_task == current->pid);
1510                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1511                           lustre_msg_get_transno(req->rq_reqmsg),
1512                           libcfs_nid2str(req->rq_peer.nid));
1513                 handle_recovery_req(thread, req,
1514                                     trd->trd_recovery_handler);
1515                 obd->obd_replayed_requests++;
1516                 spin_lock_bh(&obd->obd_processing_task_lock);
1517                 obd->obd_next_recovery_transno++;
1518                 spin_unlock_bh(&obd->obd_processing_task_lock);
1519         }
1520
1521         spin_lock_bh(&obd->obd_processing_task_lock);
1522         target_cancel_recovery_timer(obd);
1523         spin_unlock_bh(&obd->obd_processing_task_lock);
1524
1525         /* If some clients haven't replayed requests in time, evict them */
1526         if (obd->obd_abort_recovery) {
1527                 CDEBUG(D_ERROR, "req replay timed out, aborting ...\n");
1528                 obd->obd_abort_recovery = obd->obd_stopping;
1529                 class_disconnect_stale_exports(obd, req_replay_done);
1530                 abort_req_replay_queue(obd);
1531         }
1532         /* The second stage: replay locks */
1533         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1534                atomic_read(&obd->obd_lock_replay_clients));
1535         while ((req = target_next_replay_lock(obd))) {
1536                 LASSERT(trd->trd_processing_task == current->pid);
1537                 DEBUG_REQ(D_HA|D_WARNING, req, "processing lock from %s: ",
1538                           libcfs_nid2str(req->rq_peer.nid));
1539                 handle_recovery_req(thread, req,
1540                                     trd->trd_recovery_handler);
1541                 obd->obd_replayed_locks++;
1542         }
1543
1544         spin_lock_bh(&obd->obd_processing_task_lock);
1545         target_cancel_recovery_timer(obd);
1546         spin_unlock_bh(&obd->obd_processing_task_lock);
1547         /* If some clients haven't replayed requests in time, evict them */
1548         if (obd->obd_abort_recovery) {
1549                 int stale;
1550                 CERROR("lock replay timed out, aborting ...\n");
1551                 obd->obd_abort_recovery = obd->obd_stopping;
1552                 stale = class_disconnect_stale_exports(obd, lock_replay_done);
1553                 abort_lock_replay_queue(obd);
1554         }
1555
1556         /* We drop recoverying flag to forward all new requests
1557          * to regular mds_handle() since now */
1558         spin_lock_bh(&obd->obd_processing_task_lock);
1559         obd->obd_recovering = obd->obd_abort_recovery = 0;
1560         spin_unlock_bh(&obd->obd_processing_task_lock);
1561         /* The third stage: reply on final pings */
1562         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1563         while ((req = target_next_final_ping(obd))) {
1564                 LASSERT(trd->trd_processing_task == current->pid);
1565                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1566                           libcfs_nid2str(req->rq_peer.nid));
1567                 handle_recovery_req(thread, req,
1568                                     trd->trd_recovery_handler);
1569         }
1570
1571         delta = (jiffies - delta) / HZ;
1572         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1573               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1574         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1575         LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1576         if (delta > obd_timeout * 2) {
1577                 CWARN("too long recovery - read logs\n");
1578                 libcfs_debug_dumplog();
1579         }
1580
1581         target_finish_recovery(obd);
1582
1583         lu_context_fini(&env.le_ctx);
1584         trd->trd_processing_task = 0;
1585         complete(&trd->trd_finishing);
1586         RETURN(rc);
1587 }
1588
1589 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1590 {
1591         int rc = 0;
1592         struct target_recovery_data *trd = &obd->obd_recovery_data;
1593
1594         memset(trd, 0, sizeof(*trd));
1595         init_completion(&trd->trd_starting);
1596         init_completion(&trd->trd_finishing);
1597         trd->trd_recovery_handler = handler;
1598
1599         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1600                 wait_for_completion(&trd->trd_starting);
1601                 LASSERT(obd->obd_recovering != 0);
1602         } else
1603                 rc = -ECHILD;
1604
1605         return rc;
1606 }
1607
1608 void target_stop_recovery_thread(struct obd_device *obd)
1609 {
1610         spin_lock_bh(&obd->obd_processing_task_lock);
1611         if (obd->obd_recovery_data.trd_processing_task > 0) {
1612                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1613                 CERROR("%s: Aborting recovery\n", obd->obd_name);
1614                 obd->obd_abort_recovery = 1;
1615                 wake_up(&obd->obd_next_transno_waitq);
1616                 spin_unlock_bh(&obd->obd_processing_task_lock);
1617                 wait_for_completion(&trd->trd_finishing);
1618         } else {
1619                 spin_unlock_bh(&obd->obd_processing_task_lock);
1620         }
1621 }
1622
1623 void target_recovery_fini(struct obd_device *obd)
1624 {
1625         class_disconnect_exports(obd);
1626         target_stop_recovery_thread(obd);
1627         target_cleanup_recovery(obd);
1628 }
1629 EXPORT_SYMBOL(target_recovery_fini);
1630
1631 void target_recovery_init(struct obd_device *obd, svc_handler_t handler)
1632 {
1633         if (obd->obd_max_recoverable_clients == 0)
1634                 return;
1635
1636         CWARN("RECOVERY: service %s, %d recoverable clients, "
1637               "last_transno "LPU64"\n", obd->obd_name,
1638               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1639         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1640         target_start_recovery_thread(obd, handler);
1641         obd->obd_recovery_start = CURRENT_SECONDS;
1642         /* Only used for lprocfs_status */
1643         obd->obd_recovery_end = obd->obd_recovery_start + OBD_RECOVERY_TIMEOUT;
1644         /* bz13079: this should be set to desired value for ost but not for mds */
1645         obd->obd_recovery_max_time = OBD_RECOVERY_MAX_TIME;
1646 }
1647 EXPORT_SYMBOL(target_recovery_init);
1648
1649 #endif
1650
1651 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1652 {
1653         struct obd_export *exp = req->rq_export;
1654         LASSERT(exp != NULL);
1655         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1656                 /* client declares he's ready to replay locks */
1657                 spin_lock_bh(&obd->obd_processing_task_lock);
1658                 if (exp->exp_req_replay_needed) {
1659                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1660                         spin_lock(&exp->exp_lock);
1661                         exp->exp_req_replay_needed = 0;
1662                         spin_unlock(&exp->exp_lock);
1663                         atomic_dec(&obd->obd_req_replay_clients);
1664                         LASSERT(obd->obd_recoverable_clients > 0);
1665                         obd->obd_recoverable_clients--;
1666                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1667                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1668                         wake_up(&obd->obd_next_transno_waitq);
1669                 }
1670                 spin_unlock_bh(&obd->obd_processing_task_lock);
1671         }
1672         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1673                 /* client declares he's ready to complete recovery
1674                  * so, we put the request on th final queue */
1675                 spin_lock_bh(&obd->obd_processing_task_lock);
1676                 if (exp->exp_lock_replay_needed) {
1677                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1678                         spin_lock(&exp->exp_lock);
1679                         exp->exp_lock_replay_needed = 0;
1680                         spin_unlock(&exp->exp_lock);
1681                         atomic_dec(&obd->obd_lock_replay_clients);
1682                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1683                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1684                         wake_up(&obd->obd_next_transno_waitq);
1685                 }
1686                 spin_unlock_bh(&obd->obd_processing_task_lock);
1687         }
1688
1689         return 0;
1690 }
1691
1692 int target_queue_recovery_request(struct ptlrpc_request *req,
1693                                   struct obd_device *obd)
1694 {
1695         struct list_head *tmp;
1696         int inserted = 0;
1697         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1698
1699         ENTRY;
1700
1701         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
1702                 /* Processing the queue right now, don't re-add. */
1703                 RETURN(1);
1704         }
1705
1706         target_process_req_flags(obd, req);
1707
1708         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1709                 /* client declares he's ready to complete recovery
1710                  * so, we put the request on th final queue */
1711                 req = ptlrpc_clone_req(req);
1712                 if (req == NULL)
1713                         RETURN(-ENOMEM);
1714                 DEBUG_REQ(D_HA, req, "queue final req");
1715                 spin_lock_bh(&obd->obd_processing_task_lock);
1716                 if (obd->obd_recovering)
1717                         list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1718                 else {
1719                         spin_unlock_bh(&obd->obd_processing_task_lock);
1720                         ptlrpc_free_clone(req);
1721                         if (obd->obd_stopping) {
1722                                 RETURN(-ENOTCONN);
1723                         } else {
1724                                 RETURN(1);
1725                         }
1726                 }
1727                 spin_unlock_bh(&obd->obd_processing_task_lock);
1728                 RETURN(0);
1729         }
1730         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1731                 /* client declares he's ready to replay locks */
1732                 req = ptlrpc_clone_req(req);
1733                 if (req == NULL)
1734                         RETURN(-ENOMEM);
1735                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1736                 spin_lock_bh(&obd->obd_processing_task_lock);
1737                 LASSERT(obd->obd_recovering);
1738                 /* usually due to recovery abort */
1739                 if (!req->rq_export->exp_in_recovery) {
1740                         spin_unlock_bh(&obd->obd_processing_task_lock);
1741                         ptlrpc_free_clone(req);
1742                         RETURN(-ENOTCONN);
1743                 }
1744                 LASSERT(req->rq_export->exp_lock_replay_needed);
1745                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1746                 spin_unlock_bh(&obd->obd_processing_task_lock);
1747                 wake_up(&obd->obd_next_transno_waitq);
1748                 RETURN(0);
1749         }
1750
1751         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1752          * (i.e. buflens etc are in my own byte order), but type-dependent
1753          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1754
1755         if (!transno) {
1756                 CFS_INIT_LIST_HEAD(&req->rq_list);
1757                 DEBUG_REQ(D_HA, req, "not queueing");
1758                 RETURN(1);
1759         }
1760
1761         spin_lock_bh(&obd->obd_processing_task_lock);
1762
1763         /* If we're processing the queue, we want don't want to queue this
1764          * message.
1765          *
1766          * Also, if this request has a transno less than the one we're waiting
1767          * for, we should process it now.  It could (and currently always will)
1768          * be an open request for a descriptor that was opened some time ago.
1769          *
1770          * Also, a resent, replayed request that has already been
1771          * handled will pass through here and be processed immediately.
1772          */
1773         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying: %i\n",
1774               obd->obd_next_recovery_transno, transno, obd->obd_req_replaying);
1775         if (transno < obd->obd_next_recovery_transno && obd->obd_req_replaying) {
1776                 /* Processing the queue right now, don't re-add. */
1777                 LASSERT(list_empty(&req->rq_list));
1778                 spin_unlock_bh(&obd->obd_processing_task_lock);
1779                 RETURN(1);
1780         }
1781         spin_unlock_bh(&obd->obd_processing_task_lock);
1782
1783         /* A resent, replayed request that is still on the queue; just drop it.
1784            The queued request will handle this. */
1785         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT|MSG_REPLAY)) ==
1786             (MSG_RESENT | MSG_REPLAY)) {
1787                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1788                 RETURN(0);
1789         }
1790
1791         req = ptlrpc_clone_req(req);
1792         if (req == NULL)
1793                 RETURN(-ENOMEM);
1794
1795         spin_lock_bh(&obd->obd_processing_task_lock);
1796         LASSERT(obd->obd_recovering);
1797         if (!req->rq_export->exp_in_recovery) {
1798                 spin_unlock_bh(&obd->obd_processing_task_lock);
1799                 ptlrpc_free_clone(req);
1800                 RETURN(-ENOTCONN);
1801         }
1802         LASSERT(req->rq_export->exp_req_replay_needed);
1803
1804         /* XXX O(n^2) */
1805         list_for_each(tmp, &obd->obd_req_replay_queue) {
1806                 struct ptlrpc_request *reqiter =
1807                         list_entry(tmp, struct ptlrpc_request, rq_list);
1808
1809                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1810                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1811                         inserted = 1;
1812                         break;
1813                 }
1814         }
1815
1816         if (!inserted)
1817                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1818
1819         obd->obd_requests_queued_for_recovery++;
1820         wake_up(&obd->obd_next_transno_waitq);
1821         spin_unlock_bh(&obd->obd_processing_task_lock);
1822         RETURN(0);
1823
1824 }
1825
1826 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1827 {
1828         return req->rq_export->exp_obd;
1829 }
1830
1831 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1832 {
1833         LASSERT(exp != NULL);
1834         return &exp->exp_obd->obd_namespace->ns_pool;
1835 }
1836
1837 int target_pack_pool_reply(struct ptlrpc_request *req)
1838 {
1839         struct ldlm_pool *pl;
1840         ENTRY;
1841    
1842         if (!req->rq_export || !req->rq_export->exp_obd ||
1843             !exp_connect_lru_resize(req->rq_export)) {
1844                 lustre_msg_set_slv(req->rq_repmsg, 0);
1845                 lustre_msg_set_limit(req->rq_repmsg, 0);
1846                 RETURN(0);
1847         }
1848
1849         pl = ldlm_exp2pl(req->rq_export);
1850
1851         spin_lock(&pl->pl_lock);
1852         LASSERT(ldlm_pool_get_slv(pl) != 0 && ldlm_pool_get_limit(pl) != 0);
1853         lustre_msg_set_slv(req->rq_repmsg, ldlm_pool_get_slv(pl));
1854         lustre_msg_set_limit(req->rq_repmsg, ldlm_pool_get_limit(pl));
1855         spin_unlock(&pl->pl_lock);
1856
1857         RETURN(0);
1858 }
1859
1860 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
1861 {
1862         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
1863                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1864                 return (-ECOMM);
1865         }
1866
1867         if (unlikely(rc)) {
1868                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1869                 req->rq_status = rc;
1870                 return (ptlrpc_error(req));
1871         } else {
1872                 DEBUG_REQ(D_NET, req, "sending reply");
1873         }
1874
1875         return (ptlrpc_send_reply(req, 1));
1876 }
1877
1878 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1879 {
1880         int                        netrc;
1881         struct ptlrpc_reply_state *rs;
1882         struct obd_device         *obd;
1883         struct obd_export         *exp;
1884         struct ptlrpc_service     *svc;
1885
1886         if (req->rq_no_reply)
1887                 return;
1888
1889         svc = req->rq_rqbd->rqbd_service;
1890         rs = req->rq_reply_state;
1891         if (rs == NULL || !rs->rs_difficult) {
1892                 /* no notifiers */
1893                 target_send_reply_msg (req, rc, fail_id);
1894                 return;
1895         }
1896
1897         /* must be an export if locks saved */
1898         LASSERT (req->rq_export != NULL);
1899         /* req/reply consistent */
1900         LASSERT (rs->rs_service == svc);
1901
1902         /* "fresh" reply */
1903         LASSERT (!rs->rs_scheduled);
1904         LASSERT (!rs->rs_scheduled_ever);
1905         LASSERT (!rs->rs_handled);
1906         LASSERT (!rs->rs_on_net);
1907         LASSERT (rs->rs_export == NULL);
1908         LASSERT (list_empty(&rs->rs_obd_list));
1909         LASSERT (list_empty(&rs->rs_exp_list));
1910
1911         exp = class_export_get (req->rq_export);
1912         obd = exp->exp_obd;
1913
1914         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1915         rs->rs_scheduled = 1;
1916         rs->rs_on_net    = 1;
1917         rs->rs_xid       = req->rq_xid;
1918         rs->rs_transno   = req->rq_transno;
1919         rs->rs_export    = exp;
1920
1921         spin_lock(&obd->obd_uncommitted_replies_lock);
1922
1923         if (rs->rs_transno > obd->obd_last_committed) {
1924                 /* not committed already */
1925                 list_add_tail (&rs->rs_obd_list,
1926                                &obd->obd_uncommitted_replies);
1927         }
1928
1929         spin_unlock (&obd->obd_uncommitted_replies_lock);
1930         spin_lock (&exp->exp_lock);
1931
1932         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1933
1934         spin_unlock(&exp->exp_lock);
1935
1936         netrc = target_send_reply_msg (req, rc, fail_id);
1937
1938         spin_lock(&svc->srv_lock);
1939
1940         svc->srv_n_difficult_replies++;
1941
1942         if (netrc != 0) {
1943                 /* error sending: reply is off the net.  Also we need +1
1944                  * reply ref until ptlrpc_server_handle_reply() is done
1945                  * with the reply state (if the send was successful, there
1946                  * would have been +1 ref for the net, which
1947                  * reply_out_callback leaves alone) */
1948                 rs->rs_on_net = 0;
1949                 ptlrpc_rs_addref(rs);
1950                 atomic_inc (&svc->srv_outstanding_replies);
1951         }
1952
1953         if (!rs->rs_on_net ||                   /* some notifier */
1954             list_empty(&rs->rs_exp_list) ||     /* completed already */
1955             list_empty(&rs->rs_obd_list)) {
1956                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1957                 cfs_waitq_signal (&svc->srv_waitq);
1958         } else {
1959                 list_add (&rs->rs_list, &svc->srv_active_replies);
1960                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1961         }
1962
1963         spin_unlock(&svc->srv_lock);
1964 }
1965
1966 int target_handle_ping(struct ptlrpc_request *req)
1967 {
1968         obd_ping(req->rq_export);
1969         return req_capsule_server_pack(&req->rq_pill);
1970 }
1971
1972 void target_committed_to_req(struct ptlrpc_request *req)
1973 {
1974         struct obd_device *obd;
1975
1976         if (req == NULL || req->rq_export == NULL)
1977                 return;
1978
1979         obd = req->rq_export->exp_obd;
1980         if (obd == NULL)
1981                 return;
1982
1983         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1984                 lustre_msg_set_last_committed(req->rq_repmsg,
1985                                               obd->obd_last_committed);
1986         else
1987                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update");
1988
1989         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
1990                obd->obd_last_committed, req->rq_transno, req->rq_xid);
1991 }
1992
1993 EXPORT_SYMBOL(target_committed_to_req);
1994
1995 #ifdef HAVE_QUOTA_SUPPORT
1996 int target_handle_qc_callback(struct ptlrpc_request *req)
1997 {
1998         struct obd_quotactl *oqctl;
1999         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2000
2001         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2002         if (oqctl == NULL)
2003                 RETURN(-EPROTO);
2004
2005         cli->cl_qchk_stat = oqctl->qc_stat;
2006
2007         return 0;
2008 }
2009
2010 int target_handle_dqacq_callback(struct ptlrpc_request *req)
2011 {
2012 #ifdef __KERNEL__
2013         struct obd_device *obd = req->rq_export->exp_obd;
2014         struct obd_device *master_obd;
2015         struct lustre_quota_ctxt *qctxt;
2016         struct qunit_data *qdata;
2017         void* rep;
2018         struct qunit_data_old *qdata_old;
2019         int rc = 0;
2020         ENTRY;
2021
2022         rc = req_capsule_server_pack(&req->rq_pill);
2023         if (rc) {
2024                 CERROR("packing reply failed!: rc = %d\n", rc);
2025                 RETURN(rc);
2026         }
2027
2028         LASSERT(req->rq_export);
2029
2030         /* fixed for bug10707 */
2031         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2032             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2033                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
2034                 rep = req_capsule_server_get(&req->rq_pill,
2035                                              &RMF_QUNIT_DATA);
2036                 LASSERT(rep);
2037                 qdata = req_capsule_client_swab_get(&req->rq_pill,
2038                                                     &RMF_QUNIT_DATA,
2039                                           (void*)lustre_swab_qdata);
2040         } else {
2041                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
2042                 rep = req_capsule_server_get(&req->rq_pill, &RMF_QUNIT_DATA);
2043                 LASSERT(rep);
2044                 qdata_old = req_capsule_client_swab_get(&req->rq_pill,
2045                                                         &RMF_QUNIT_DATA,
2046                                            (void*)lustre_swab_qdata_old);
2047                 qdata = lustre_quota_old_to_new(qdata_old);
2048         }
2049
2050         if (qdata == NULL)
2051                 RETURN(-EPROTO);
2052
2053         /* we use the observer */
2054         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
2055         master_obd = obd->obd_observer->obd_observer;
2056         qctxt = &master_obd->u.obt.obt_qctxt;
2057
2058         LASSERT(qctxt->lqc_handler);
2059         rc = qctxt->lqc_handler(master_obd, qdata,
2060                                 lustre_msg_get_opc(req->rq_reqmsg));
2061         if (rc && rc != -EDQUOT)
2062                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2063                        "dqacq failed! (rc:%d)\n", rc);
2064
2065         /* the qd_count might be changed in lqc_handler */
2066         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2067             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2068                 memcpy(rep, qdata, sizeof(*qdata));
2069         } else {
2070                 qdata_old = lustre_quota_new_to_old(qdata);
2071                 memcpy(rep, qdata_old, sizeof(*qdata_old));
2072         }
2073         req->rq_status = rc;
2074         rc = ptlrpc_reply(req);
2075
2076         RETURN(rc);
2077 #else
2078         return 0;
2079 #endif /* !__KERNEL__ */
2080 }
2081 #endif /* HAVE_QUOTA_SUPPORT */
2082
2083 ldlm_mode_t lck_compat_array[] = {
2084         [LCK_EX] LCK_COMPAT_EX,
2085         [LCK_PW] LCK_COMPAT_PW,
2086         [LCK_PR] LCK_COMPAT_PR,
2087         [LCK_CW] LCK_COMPAT_CW,
2088         [LCK_CR] LCK_COMPAT_CR,
2089         [LCK_NL] LCK_COMPAT_NL,
2090         [LCK_GROUP] LCK_COMPAT_GROUP
2091 };