Whamcloud - gitweb
1dcc9604464f82d8470a638d9b41084573b745fc
[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, void *localdata)
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         lnet_nid_t *client_nid = NULL;
595         ENTRY;
596
597         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
598
599         str = req_capsule_client_get(&req->rq_pill, &RMF_TGTUUID);
600         if (str == NULL) {
601                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
602                 GOTO(out, rc = -EINVAL);
603         }
604
605         obd_str2uuid(&tgtuuid, str);
606         target = class_uuid2obd(&tgtuuid);
607         if (!target)
608                 target = class_name2obd(str);
609
610         if (!target || target->obd_stopping || !target->obd_set_up) {
611                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
612                                    " for connect (%s)\n", str,
613                                    !target ? "no target" :
614                                    (target->obd_stopping ? "stopping" :
615                                    "not set up"));
616                 GOTO(out, rc = -ENODEV);
617         }
618
619         if (target->obd_no_conn) {
620                 LCONSOLE_WARN("%s: temporarily refusing client connection "
621                               "from %s\n", target->obd_name,
622                               libcfs_nid2str(req->rq_peer.nid));
623                 GOTO(out, rc = -EAGAIN);
624         }
625
626         /* Make sure the target isn't cleaned up while we're here. Yes,
627            there's still a race between the above check and our incref here.
628            Really, class_uuid2obd should take the ref. */
629         targref = class_incref(target);
630
631
632         str = req_capsule_client_get(&req->rq_pill, &RMF_CLUUID);
633         if (str == NULL) {
634                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
635                 GOTO(out, rc = -EINVAL);
636         }
637
638         obd_str2uuid(&cluuid, str);
639
640         /* XXX extract a nettype and format accordingly */
641         switch (sizeof(lnet_nid_t)) {
642                 /* NB the casts only avoid compiler warnings */
643         case 8:
644                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
645                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
646                 break;
647         case 4:
648                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
649                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
650                 break;
651         default:
652                 LBUG();
653         }
654
655         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
656         if (tmp == NULL)
657                 GOTO(out, rc = -EPROTO);
658
659         conn = *tmp;
660
661         data = req_capsule_client_get(&req->rq_pill, &RMF_CONNECT_DATA);
662         if (!data)
663                 GOTO(out, rc = -EPROTO);
664
665         rc = req_capsule_server_pack(&req->rq_pill);
666         if (rc)
667                 GOTO(out, rc);
668
669         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
670                 if (!data) {
671                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
672                                   "libclient connection attempt");
673                         GOTO(out, rc = -EPROTO);
674                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
675                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
676                            data->ocd_version > LUSTRE_VERSION_CODE +
677                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
678                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
679                                   "libclient connection attempt",
680                                   data->ocd_version < LUSTRE_VERSION_CODE ?
681                                   "old" : "new",
682                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
683                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
684                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
685                                   OBD_OCD_VERSION_FIX(data->ocd_version));
686                         data = req_capsule_server_sized_get(&req->rq_pill,
687                                                         &RMF_CONNECT_DATA,
688                                     offsetof(typeof(*data), ocd_version) +
689                                              sizeof(data->ocd_version));
690                         if (data) {
691                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
692                                 data->ocd_version = LUSTRE_VERSION_CODE;
693                         }
694                         GOTO(out, rc = -EPROTO);
695                 }
696         }
697
698         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
699                 initial_conn = 1;
700
701         /* lctl gets a backstage, all-access pass. */
702         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
703                 goto dont_check_exports;
704
705         spin_lock(&target->obd_dev_lock);
706         export = lustre_hash_get_object_by_key(target->obd_uuid_hash_body, &cluuid);
707
708         if (export != NULL && export->exp_connecting) { /* bug 9635, et. al. */
709                 CWARN("%s: exp %p already connecting\n",
710                       export->exp_obd->obd_name, export);
711                 class_export_put(export);
712                 export = NULL;
713                 rc = -EALREADY;
714         } else if (export != NULL && export->exp_connection != NULL &&
715                    req->rq_peer.nid != export->exp_connection->c_peer.nid) {
716                 /* make darn sure this is coming from the same peer
717                  * if the UUIDs matched */
718                   CWARN("%s: cookie %s seen on new NID %s when "
719                           "existing NID %s is already connected\n",
720                         target->obd_name, cluuid.uuid,
721                   libcfs_nid2str(req->rq_peer.nid),
722                   libcfs_nid2str(export->exp_connection->c_peer.nid));
723                   class_export_put(export);
724                   export = NULL;
725                   rc = -EALREADY;
726         } else if (export != NULL) {
727                 spin_lock(&export->exp_lock);
728                 export->exp_connecting = 1;
729                 spin_unlock(&export->exp_lock);
730                 class_export_put(export);
731                 spin_unlock(&target->obd_dev_lock);
732                 LASSERT(export->exp_obd == target);
733
734                 rc = target_handle_reconnect(&conn, export, &cluuid, initial_conn);
735         }
736
737         /* If we found an export, we already unlocked. */
738         if (!export) {
739                 spin_unlock(&target->obd_dev_lock);
740                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
741         } else if (req->rq_export == NULL &&
742                    atomic_read(&export->exp_rpc_count) > 0) {
743                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
744                       target->obd_name, cluuid.uuid,
745                       libcfs_nid2str(req->rq_peer.nid),
746                       export, atomic_read(&export->exp_refcount));
747                 GOTO(out, rc = -EBUSY);
748         } else if (req->rq_export != NULL &&
749                    (atomic_read(&export->exp_rpc_count) > 1)) {
750                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
751                       target->obd_name, cluuid.uuid,
752                       libcfs_nid2str(req->rq_peer.nid),
753                       export, atomic_read(&export->exp_rpc_count));
754                 GOTO(out, rc = -EBUSY);
755         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1 &&
756                    !initial_conn) {
757                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
758                        "cookies not random?\n", target->obd_name,
759                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
760                 GOTO(out, rc = -EALREADY);
761         } else {
762                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
763                 if (req->rq_export == NULL && initial_conn)
764                        export->exp_last_request_time =
765                                max(export->exp_last_request_time,
766                                    (time_t)CURRENT_SECONDS);
767         }
768
769         /* We want to handle EALREADY but *not* -EALREADY from
770          * target_handle_reconnect(), return reconnection state in a flag */
771         if (rc == EALREADY) {
772                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
773                 rc = 0;
774         } else if (rc) {
775                 GOTO(out, rc);
776         }
777         /* Tell the client if we're in recovery. */
778         /* If this is the first client, start the recovery timer */
779         CWARN("%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
780                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
781               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
782               export, (long)CURRENT_SECONDS,
783               export ? (long)export->exp_last_request_time : 0);
784
785
786         if (target->obd_recovering) {
787                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
788                 target_start_recovery_timer(target);
789         }
790
791         /* Tell the client if we support replayable requests */
792         if (target->obd_replayable)
793                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
794         client_nid = &req->rq_peer.nid;
795
796         if (export == NULL) {
797                 if (target->obd_recovering) {
798                         cfs_time_t t;
799
800                         t = cfs_timer_deadline(&target->obd_recovery_timer);
801                         t = cfs_time_sub(t, cfs_time_current());
802                         CERROR("%s: denying connection for new client %s (%s): "
803                                "%d clients in recovery for %lds\n",
804                                target->obd_name,
805                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
806                                target->obd_recoverable_clients,
807                                cfs_duration_sec(t));
808                         rc = -EBUSY;
809                 } else {
810 dont_check_exports:
811                         rc = obd_connect(req->rq_svc_thread->t_env,
812                                          &conn, target, &cluuid, data,
813                                          client_nid);
814                 }
815         } else {
816                 rc = obd_reconnect(req->rq_svc_thread->t_env,
817                                    export, target, &cluuid, data);
818         }
819         if (rc)
820                 GOTO(out, rc);
821         /* Return only the parts of obd_connect_data that we understand, so the
822          * client knows that we don't understand the rest. */
823         if (data) {
824                  tmpdata = req_capsule_server_get(&req->rq_pill,
825                                                   &RMF_CONNECT_DATA);
826                   //data->ocd_connect_flags &= OBD_CONNECT_SUPPORTED;
827                  *tmpdata = *data;
828         }
829                   
830         /* If all else goes well, this is our RPC return code. */
831         req->rq_status = 0;
832
833         lustre_msg_set_handle(req->rq_repmsg, &conn);
834
835         /* ownership of this export ref transfers to the request AFTER we
836          * drop any previous reference the request had, but we don't want
837          * that to go to zero before we get our new export reference. */
838         export = class_conn2export(&conn);
839         if (!export) {
840                 DEBUG_REQ(D_ERROR, req, "Missing export!");
841                 GOTO(out, rc = -ENODEV);
842         }
843
844         /* If the client and the server are the same node, we will already
845          * have an export that really points to the client's DLM export,
846          * because we have a shared handles table.
847          *
848          * XXX this will go away when shaver stops sending the "connect" handle
849          * in the real "remote handle" field of the request --phik 24 Apr 2003
850          */
851         if (req->rq_export != NULL)
852                 class_export_put(req->rq_export);
853
854         req->rq_export = export;
855
856         spin_lock(&export->exp_lock);
857         if (initial_conn) {
858                 lustre_msg_set_conn_cnt(req->rq_repmsg, export->exp_conn_cnt + 1);
859         } else if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
860                 spin_unlock(&export->exp_lock);
861                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
862                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
863                        export->exp_conn_cnt,
864                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
865
866                 GOTO(out, rc = -EALREADY);
867         }
868         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
869
870         /* request from liblustre?  Don't evict it for not pinging. */
871         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
872                 export->exp_libclient = 1;
873                 spin_unlock(&export->exp_lock);
874
875                 spin_lock(&target->obd_dev_lock);
876                 list_del_init(&export->exp_obd_chain_timed);
877                 spin_unlock(&target->obd_dev_lock);
878         } else {
879                 spin_unlock(&export->exp_lock);
880         }
881
882         if (export->exp_connection != NULL)
883                 ptlrpc_put_connection(export->exp_connection);
884         export->exp_connection = ptlrpc_get_connection(req->rq_peer,
885                                                        req->rq_self,
886                                                        &remote_uuid);
887
888         spin_lock(&target->obd_dev_lock);
889         /* Export might be hashed already, e.g. if this is reconnect */
890         if (hlist_unhashed(&export->exp_nid_hash))
891                 lustre_hash_additem(export->exp_obd->obd_nid_hash_body,
892                                     &export->exp_connection->c_peer.nid,
893                                     &export->exp_nid_hash);
894         spin_unlock(&target->obd_dev_lock);
895
896         spin_lock_bh(&target->obd_processing_task_lock);
897         if (target->obd_recovering && !export->exp_in_recovery) {
898                 spin_lock(&export->exp_lock);
899                 export->exp_in_recovery = 1;
900                 export->exp_req_replay_needed = 1;
901                 export->exp_lock_replay_needed = 1;
902                 spin_unlock(&export->exp_lock);
903                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
904                      && (data->ocd_transno == 0))
905                         CWARN("Connect with zero transno!\n");
906
907                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
908                      && data->ocd_transno < target->obd_next_recovery_transno)
909                         target->obd_next_recovery_transno = data->ocd_transno;
910                 target->obd_connected_clients++;
911                 /* each connected client is counted as recoverable */
912                 target->obd_recoverable_clients++;
913                 atomic_inc(&target->obd_req_replay_clients);
914                 atomic_inc(&target->obd_lock_replay_clients);
915                 if (target->obd_connected_clients ==
916                     target->obd_max_recoverable_clients)
917                         wake_up(&target->obd_next_transno_waitq);
918         }
919         spin_unlock_bh(&target->obd_processing_task_lock);
920         tmp = req_capsule_client_get(&req->rq_pill, &RMF_CONN);
921         conn = *tmp;
922
923         if (export->exp_imp_reverse != NULL) {
924                 /* destroyed import can be still referenced in ctxt */
925                 obd_set_info_async(export, strlen(KEY_REVIMP_UPD),
926                                    KEY_REVIMP_UPD, 0, NULL, NULL);
927
928                 /* in some recovery senarios, previous ctx init rpc handled
929                  * in sptlrpc_target_export_check() might be used to install
930                  * a reverse ctx in this reverse import, and later OBD_CONNECT
931                  * using the same gss ctx could reach here and following new
932                  * reverse import. note all reverse ctx in new/old import are
933                  * actually based on the same gss ctx. so we invalidate ctx
934                  * here before destroy import, otherwise flush old import will
935                  * lead to remote reverse ctx be destroied, thus the reverse
936                  * ctx of new import will lost its peer.
937                  * there might be a better way to deal with this???
938                  */
939                 sptlrpc_import_inval_all_ctx(export->exp_imp_reverse);
940
941                 destroy_import(export->exp_imp_reverse);
942         }
943
944         /* for the rest part, we return -ENOTCONN in case of errors
945          * in order to let client initialize connection again.
946          */
947         revimp = export->exp_imp_reverse = class_new_import(target);
948         if (!revimp) {
949                 CERROR("fail to alloc new reverse import.\n");
950                 GOTO(out, rc = -ENOTCONN);
951         }
952
953         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
954         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
955         revimp->imp_remote_handle = conn;
956         revimp->imp_dlm_fake = 1;
957         revimp->imp_state = LUSTRE_IMP_FULL;
958
959         if (req->rq_reqmsg->lm_magic == LUSTRE_MSG_MAGIC_V1 &&
960             lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_NEXT_VER) {
961                 revimp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
962                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_NEXT_VER);
963         } else {
964                 /* unknown magic has been filtered out by unpack */
965                 revimp->imp_msg_magic = req->rq_reqmsg->lm_magic;
966         }
967
968         rc = sptlrpc_import_sec_adapt(revimp, req->rq_svc_ctx,
969                                       req->rq_flvr.sf_rpc);
970         if (rc) {
971                 CERROR("Failed to get sec for reverse import: %d\n", rc);
972                 export->exp_imp_reverse = NULL;
973                 class_destroy_import(revimp);
974         }
975
976         class_import_put(revimp);
977 out:
978         if (export) {
979                 spin_lock(&export->exp_lock);
980                 export->exp_connecting = 0;
981                 spin_unlock(&export->exp_lock);
982         }
983         if (targref)
984                 class_decref(targref);
985         if (rc)
986                 req->rq_status = rc;
987         RETURN(rc);
988 }
989
990 int target_handle_disconnect(struct ptlrpc_request *req)
991 {
992         int rc;
993         ENTRY;
994
995         rc = req_capsule_server_pack(&req->rq_pill);
996         if (rc)
997                 RETURN(rc);
998
999         /* keep the rq_export around so we can send the reply */
1000         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
1001
1002         RETURN(0);
1003 }
1004
1005 void target_destroy_export(struct obd_export *exp)
1006 {
1007         /* exports created from last_rcvd data, and "fake"
1008            exports created by lctl don't have an import */
1009         if (exp->exp_imp_reverse != NULL)
1010                 destroy_import(exp->exp_imp_reverse);
1011
1012         /* We cancel locks at disconnect time, but this will catch any locks
1013          * granted in a race with recovery-induced disconnect. */
1014         if (exp->exp_obd->obd_namespace != NULL)
1015                 ldlm_cancel_locks_for_export(exp);
1016 }
1017
1018 /*
1019  * Recovery functions
1020  */
1021
1022 struct ptlrpc_request *ptlrpc_clone_req( struct ptlrpc_request *orig_req)
1023 {
1024         struct ptlrpc_request *copy_req;
1025         struct lustre_msg *copy_reqmsg;
1026         struct ptlrpc_user_desc *udesc = NULL;
1027
1028         OBD_ALLOC_PTR(copy_req);
1029         if (!copy_req)
1030                 return NULL;
1031         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
1032         if (!copy_reqmsg){
1033                 OBD_FREE_PTR(copy_req);
1034                 return NULL;
1035         }
1036
1037         if (orig_req->rq_user_desc) {
1038                 int ngroups = orig_req->rq_user_desc->pud_ngroups;
1039
1040                 OBD_ALLOC(udesc, sptlrpc_user_desc_size(ngroups));
1041                 if (!udesc) {
1042                         OBD_FREE(copy_reqmsg, orig_req->rq_reqlen);
1043                         OBD_FREE_PTR(copy_req);
1044                         return NULL;
1045                 }
1046                 memcpy(udesc, orig_req->rq_user_desc,
1047                        sptlrpc_user_desc_size(ngroups));
1048         }
1049
1050         *copy_req = *orig_req;
1051         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
1052         copy_req->rq_reqmsg = copy_reqmsg;
1053         copy_req->rq_user_desc = udesc;
1054
1055         class_export_get(copy_req->rq_export);
1056         CFS_INIT_LIST_HEAD(&copy_req->rq_list);
1057         sptlrpc_svc_ctx_addref(copy_req);
1058
1059         if (copy_req->rq_reply_state) {
1060                 /* the copied req takes over the reply state */
1061                 orig_req->rq_reply_state = NULL;
1062                 /* to catch further access */
1063                 orig_req->rq_repmsg = NULL;
1064                 orig_req->rq_replen = 0;
1065         }
1066
1067         return copy_req;
1068 }
1069
1070 void ptlrpc_free_clone( struct ptlrpc_request *req)
1071 {
1072         if (req->rq_reply_state) {
1073                 ptlrpc_rs_decref(req->rq_reply_state);
1074                 req->rq_reply_state = NULL;
1075         }
1076
1077         sptlrpc_svc_ctx_decref(req);
1078         class_export_put(req->rq_export);
1079         list_del(&req->rq_list);
1080
1081         if (req->rq_user_desc) {
1082                 int ngroups = req->rq_user_desc->pud_ngroups;
1083                 OBD_FREE(req->rq_user_desc, sptlrpc_user_desc_size(ngroups));
1084         }
1085         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1086         OBD_FREE_PTR(req);
1087 }
1088
1089 #ifdef __KERNEL__
1090 static void target_finish_recovery(struct obd_device *obd)
1091 {
1092         ENTRY;
1093         LCONSOLE_INFO("%s: sending delayed replies to recovered clients\n",
1094                       obd->obd_name);
1095
1096         ldlm_reprocess_all_ns(obd->obd_namespace);
1097
1098         /* when recovery finished, cleanup orphans on mds and ost */
1099         if (OBT(obd) && OBP(obd, postrecov)) {
1100                 int rc = OBP(obd, postrecov)(obd);
1101                 LCONSOLE_WARN("%s: recovery %s: rc %d\n", obd->obd_name,
1102                               rc < 0 ? "failed" : "complete", rc);
1103         }
1104
1105         obd->obd_recovery_end = CURRENT_SECONDS;
1106         EXIT;
1107 }
1108
1109 static void abort_req_replay_queue(struct obd_device *obd)
1110 {
1111         struct ptlrpc_request *req, *n;
1112
1113         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1114                 DEBUG_REQ(D_WARNING, req, "aborted:");
1115                 req->rq_status = -ENOTCONN;
1116                 if (ptlrpc_error(req)) {
1117                         DEBUG_REQ(D_ERROR, req,
1118                                   "failed abort_req_reply; skipping");
1119                 }
1120                 ptlrpc_free_clone(req);
1121         }
1122 }
1123
1124 static void abort_lock_replay_queue(struct obd_device *obd)
1125 {
1126         struct ptlrpc_request *req, *n;
1127
1128         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1129                 DEBUG_REQ(D_ERROR, req, "aborted:");
1130                 req->rq_status = -ENOTCONN;
1131                 if (ptlrpc_error(req)) {
1132                         DEBUG_REQ(D_ERROR, req,
1133                                   "failed abort_lock_reply; skipping");
1134                 }
1135                 ptlrpc_free_clone(req);
1136         }
1137 }
1138 #endif
1139
1140 /* Called from a cleanup function if the device is being cleaned up
1141    forcefully.  The exports should all have been disconnected already,
1142    the only thing left to do is
1143      - clear the recovery flags
1144      - cancel the timer
1145      - free queued requests and replies, but don't send replies
1146    Because the obd_stopping flag is set, no new requests should be received.
1147
1148 */
1149 void target_cleanup_recovery(struct obd_device *obd)
1150 {
1151         struct ptlrpc_request *req, *n;
1152         ENTRY;
1153
1154         LASSERT(obd->obd_stopping);
1155
1156         spin_lock_bh(&obd->obd_processing_task_lock);
1157         if (!obd->obd_recovering) {
1158                 spin_unlock_bh(&obd->obd_processing_task_lock);
1159                 EXIT;
1160                 return;
1161         }
1162         obd->obd_recovering = obd->obd_abort_recovery = 0;
1163         target_cancel_recovery_timer(obd);
1164         spin_unlock_bh(&obd->obd_processing_task_lock);
1165
1166         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1167                 LASSERT (req->rq_reply_state == 0);
1168                 ptlrpc_free_clone(req);
1169         }
1170         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1171                 LASSERT (req->rq_reply_state == 0);
1172                 ptlrpc_free_clone(req);
1173         }
1174         list_for_each_entry_safe(req, n, &obd->obd_final_req_queue, rq_list) {
1175                 LASSERT (req->rq_reply_state == 0);
1176                 ptlrpc_free_clone(req);
1177         }
1178
1179         EXIT;
1180 }
1181
1182 static void target_recovery_expired(unsigned long castmeharder)
1183 {
1184         struct obd_device *obd = (struct obd_device *)castmeharder;
1185         CERROR("%s: recovery timed out, aborting\n", obd->obd_name);
1186         spin_lock_bh(&obd->obd_processing_task_lock);
1187         if (obd->obd_recovering)
1188                 obd->obd_abort_recovery = 1;
1189         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1190         spin_unlock_bh(&obd->obd_processing_task_lock);
1191 }
1192
1193
1194 /* obd_processing_task_lock should be held */
1195 void target_cancel_recovery_timer(struct obd_device *obd)
1196 {
1197         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1198         cfs_timer_disarm(&obd->obd_recovery_timer);
1199 }
1200
1201 static void reset_recovery_timer(struct obd_device *obd)
1202 {
1203         time_t timeout_shift = OBD_RECOVERY_TIMEOUT;
1204         spin_lock_bh(&obd->obd_processing_task_lock);
1205         if (!obd->obd_recovering) {
1206                 spin_unlock_bh(&obd->obd_processing_task_lock);
1207                 return;
1208         }
1209         if (cfs_time_current_sec() + OBD_RECOVERY_TIMEOUT > 
1210             obd->obd_recovery_start + obd->obd_recovery_max_time)
1211                 timeout_shift = obd->obd_recovery_start + 
1212                         obd->obd_recovery_max_time - cfs_time_current_sec();
1213         cfs_timer_arm(&obd->obd_recovery_timer, cfs_time_shift(timeout_shift));
1214         spin_unlock_bh(&obd->obd_processing_task_lock);
1215         CDEBUG(D_HA, "%s: timer will expire in %u seconds\n", obd->obd_name,
1216                (unsigned int)timeout_shift);
1217         /* Only used for lprocfs_status */
1218         obd->obd_recovery_end = CURRENT_SECONDS + timeout_shift;
1219 }
1220
1221
1222 /* Only start it the first time called */
1223 void target_start_recovery_timer(struct obd_device *obd)
1224 {
1225         spin_lock_bh(&obd->obd_processing_task_lock);
1226         if (obd->obd_recovery_handler
1227             || timer_pending((struct timer_list *)&obd->obd_recovery_timer)) {
1228                 spin_unlock_bh(&obd->obd_processing_task_lock);
1229                 return;
1230         }
1231         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1232               OBD_RECOVERY_TIMEOUT);
1233         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1234         spin_unlock_bh(&obd->obd_processing_task_lock);
1235
1236         reset_recovery_timer(obd);
1237 }
1238
1239 #ifdef __KERNEL__
1240 static int check_for_next_transno(struct obd_device *obd)
1241 {
1242         struct ptlrpc_request *req = NULL;
1243         int wake_up = 0, connected, completed, queue_len, max;
1244         __u64 next_transno, req_transno;
1245         ENTRY;
1246         spin_lock_bh(&obd->obd_processing_task_lock);
1247
1248         if (!list_empty(&obd->obd_req_replay_queue)) {
1249                 req = list_entry(obd->obd_req_replay_queue.next,
1250                                  struct ptlrpc_request, rq_list);
1251                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1252         } else {
1253                 req_transno = 0;
1254         }
1255
1256         max = obd->obd_max_recoverable_clients;
1257         connected = obd->obd_connected_clients;
1258         completed = connected - obd->obd_recoverable_clients;
1259         queue_len = obd->obd_requests_queued_for_recovery;
1260         next_transno = obd->obd_next_recovery_transno;
1261
1262         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1263                "req_transno: "LPU64", next_transno: "LPU64"\n",
1264                max, connected, completed, queue_len, req_transno, next_transno);
1265
1266         if (obd->obd_abort_recovery) {
1267                 CDEBUG(D_HA, "waking for aborted recovery\n");
1268                 wake_up = 1;
1269         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1270                 CDEBUG(D_HA, "waking for completed recovery\n");
1271                 wake_up = 1;
1272         } else if (req_transno == next_transno) {
1273                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1274                 wake_up = 1;
1275         } else if (queue_len + completed == max) {
1276                 /* handle gaps occured due to lost reply. It is allowed gaps
1277                  * because all clients are connected and there will be resend
1278                  * for missed transaction */
1279                 LASSERTF(req_transno >= next_transno,
1280                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1281                          req_transno, next_transno);
1282
1283                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1284                        "waking for skipped transno (skip: "LPD64
1285                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1286                        next_transno, queue_len, completed, connected, req_transno);
1287                 obd->obd_next_recovery_transno = req_transno;
1288                 wake_up = 1;
1289         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1290                 /* some clients haven't connected in time, but we can try
1291                  * to replay requests that demand on already committed ones
1292                  * also, we can replay first non-committed transation */
1293                 LASSERT(req_transno != 0);
1294                 if (req_transno == obd->obd_last_committed + 1) {
1295                         obd->obd_next_recovery_transno = req_transno;
1296                 } else if (req_transno > obd->obd_last_committed) {
1297                         /* can't continue recovery: have no needed transno */
1298                         obd->obd_abort_recovery = 1;
1299                         CDEBUG(D_ERROR, "abort due to missed clients. max: %d, "
1300                                "connected: %d, completed: %d, queue_len: %d, "
1301                                "req_transno: "LPU64", next_transno: "LPU64"\n",
1302                                max, connected, completed, queue_len,
1303                                req_transno, next_transno);
1304                 }
1305                 wake_up = 1;
1306         }
1307
1308         spin_unlock_bh(&obd->obd_processing_task_lock);
1309         return wake_up;
1310 }
1311
1312 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1313 {
1314         struct l_wait_info lwi = { 0 };
1315         struct ptlrpc_request *req;
1316
1317         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1318                obd->obd_next_recovery_transno);
1319         l_wait_event(obd->obd_next_transno_waitq,
1320                      check_for_next_transno(obd), &lwi);
1321
1322         spin_lock_bh(&obd->obd_processing_task_lock);
1323         if (obd->obd_abort_recovery) {
1324                 req = NULL;
1325         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1326                 req = list_entry(obd->obd_req_replay_queue.next,
1327                                  struct ptlrpc_request, rq_list);
1328                 list_del_init(&req->rq_list);
1329                 obd->obd_requests_queued_for_recovery--;
1330         } else {
1331                 req = NULL;
1332         }
1333         spin_unlock_bh(&obd->obd_processing_task_lock);
1334         RETURN(req);
1335 }
1336
1337 static int check_for_next_lock(struct obd_device *obd)
1338 {
1339         struct ptlrpc_request *req = NULL;
1340         int wake_up = 0;
1341
1342         spin_lock_bh(&obd->obd_processing_task_lock);
1343         if (!list_empty(&obd->obd_lock_replay_queue)) {
1344                 req = list_entry(obd->obd_lock_replay_queue.next,
1345                                  struct ptlrpc_request, rq_list);
1346                 CDEBUG(D_HA, "waking for next lock\n");
1347                 wake_up = 1;
1348         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1349                 CDEBUG(D_HA, "waking for completed lock replay\n");
1350                 wake_up = 1;
1351         } else if (obd->obd_abort_recovery) {
1352                 CDEBUG(D_HA, "waking for aborted recovery\n");
1353                 wake_up = 1;
1354         }
1355         spin_unlock_bh(&obd->obd_processing_task_lock);
1356
1357         return wake_up;
1358 }
1359
1360 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1361 {
1362         struct l_wait_info lwi = { 0 };
1363         struct ptlrpc_request *req;
1364
1365         CDEBUG(D_HA, "Waiting for lock\n");
1366         l_wait_event(obd->obd_next_transno_waitq,
1367                      check_for_next_lock(obd), &lwi);
1368
1369         spin_lock_bh(&obd->obd_processing_task_lock);
1370         if (obd->obd_abort_recovery) {
1371                 req = NULL;
1372         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1373                 req = list_entry(obd->obd_lock_replay_queue.next,
1374                                  struct ptlrpc_request, rq_list);
1375                 list_del_init(&req->rq_list);
1376         } else {
1377                 req = NULL;
1378         }
1379         spin_unlock_bh(&obd->obd_processing_task_lock);
1380         return req;
1381 }
1382
1383 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1384 {
1385         struct ptlrpc_request *req;
1386
1387         spin_lock_bh(&obd->obd_processing_task_lock);
1388         if (!list_empty(&obd->obd_final_req_queue)) {
1389                 req = list_entry(obd->obd_final_req_queue.next,
1390                                  struct ptlrpc_request, rq_list);
1391                 list_del_init(&req->rq_list);
1392         } else {
1393                 req = NULL;
1394         }
1395         spin_unlock_bh(&obd->obd_processing_task_lock);
1396         return req;
1397 }
1398
1399 static inline int req_replay_done(struct obd_export *exp)
1400 {
1401         return (exp->exp_req_replay_needed == 0);
1402 }
1403
1404 static inline int lock_replay_done(struct obd_export *exp)
1405 {
1406         return (exp->exp_lock_replay_needed == 0);
1407 }
1408
1409 static inline int connect_done(struct obd_export *exp)
1410 {
1411         return (exp->exp_in_recovery != 0);
1412 }
1413
1414 static int check_for_clients(struct obd_device *obd)
1415 {
1416         if (obd->obd_abort_recovery)
1417                 return 1;
1418         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1419         if (obd->obd_no_conn == 0 &&
1420             obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1421                 return 1;
1422         return 0;
1423 }
1424
1425 static int handle_recovery_req(struct ptlrpc_thread *thread,
1426                                struct ptlrpc_request *req,
1427                                svc_handler_t handler)
1428 {
1429         int rc;
1430         ENTRY;
1431
1432         rc = lu_context_init(&req->rq_session, LCT_SESSION);
1433         if (rc) {
1434                 CERROR("Failure to initialize session: %d\n", rc);
1435                 return rc;
1436         }
1437         req->rq_session.lc_thread = thread;
1438         lu_context_enter(&req->rq_session);
1439         req->rq_svc_thread = thread;
1440         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1441
1442         /* thread context */
1443         lu_context_enter(&thread->t_env->le_ctx);
1444         (void)handler(req);
1445         lu_context_exit(&thread->t_env->le_ctx);
1446
1447         lu_context_exit(&req->rq_session);
1448         lu_context_fini(&req->rq_session);
1449         /* don't reset timer for final stage */
1450         if (!req_replay_done(req->rq_export) ||
1451             !lock_replay_done(req->rq_export))
1452                 reset_recovery_timer(class_exp2obd(req->rq_export));
1453         ptlrpc_free_clone(req);
1454         RETURN(0);
1455 }
1456
1457 static int target_recovery_thread(void *arg)
1458 {
1459         struct obd_device *obd = arg;
1460         struct ptlrpc_request *req;
1461         struct target_recovery_data *trd = &obd->obd_recovery_data;
1462         struct l_wait_info lwi = { 0 };
1463         unsigned long delta;
1464         unsigned long flags;
1465         struct lu_env env;
1466         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1467         __u32 recov_ctx_tags = LCT_MD_THREAD;
1468         int rc = 0;
1469         ENTRY;
1470
1471         cfs_daemonize("tgt_recov");
1472
1473         SIGNAL_MASK_LOCK(current, flags);
1474         sigfillset(&current->blocked);
1475         RECALC_SIGPENDING;
1476         SIGNAL_MASK_UNLOCK(current, flags);
1477
1478         rc = lu_context_init(&env.le_ctx, recov_ctx_tags);
1479         if (rc)
1480                 RETURN(rc);
1481
1482         thread->t_env = &env;
1483         env.le_ctx.lc_thread = thread;
1484
1485         CERROR("%s: started recovery thread pid %d\n", obd->obd_name,
1486                current->pid);
1487         trd->trd_processing_task = current->pid;
1488
1489         obd->obd_recovering = 1;
1490         complete(&trd->trd_starting);
1491
1492         /* first of all, we have to know the first transno to replay */
1493         obd->obd_abort_recovery = 0;
1494         l_wait_event(obd->obd_next_transno_waitq,
1495                      check_for_clients(obd), &lwi);
1496
1497         spin_lock_bh(&obd->obd_processing_task_lock);
1498         target_cancel_recovery_timer(obd);
1499         spin_unlock_bh(&obd->obd_processing_task_lock);
1500
1501         /* If some clients haven't connected in time, evict them */
1502         if (obd->obd_abort_recovery) {
1503                 CWARN("Some clients haven't connect in time (%d/%d),"
1504                        "evict them\n", obd->obd_connected_clients,
1505                        obd->obd_max_recoverable_clients);
1506                 obd->obd_abort_recovery = obd->obd_stopping;
1507                 class_disconnect_stale_exports(obd, connect_done);
1508         }
1509         /* next stage: replay requests */
1510         delta = jiffies;
1511         obd->obd_req_replaying = 1;
1512         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1513               atomic_read(&obd->obd_req_replay_clients),
1514               obd->obd_next_recovery_transno);
1515         while ((req = target_next_replay_req(obd))) {
1516                 LASSERT(trd->trd_processing_task == current->pid);
1517                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1518                           lustre_msg_get_transno(req->rq_reqmsg),
1519                           libcfs_nid2str(req->rq_peer.nid));
1520                 handle_recovery_req(thread, req,
1521                                     trd->trd_recovery_handler);
1522                 obd->obd_replayed_requests++;
1523                 spin_lock_bh(&obd->obd_processing_task_lock);
1524                 obd->obd_next_recovery_transno++;
1525                 spin_unlock_bh(&obd->obd_processing_task_lock);
1526         }
1527
1528         spin_lock_bh(&obd->obd_processing_task_lock);
1529         target_cancel_recovery_timer(obd);
1530         spin_unlock_bh(&obd->obd_processing_task_lock);
1531
1532         /* If some clients haven't replayed requests in time, evict them */
1533         if (obd->obd_abort_recovery) {
1534                 CDEBUG(D_ERROR, "req replay timed out, aborting ...\n");
1535                 obd->obd_abort_recovery = obd->obd_stopping;
1536                 class_disconnect_stale_exports(obd, req_replay_done);
1537                 abort_req_replay_queue(obd);
1538         }
1539         /* The second stage: replay locks */
1540         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1541                atomic_read(&obd->obd_lock_replay_clients));
1542         while ((req = target_next_replay_lock(obd))) {
1543                 LASSERT(trd->trd_processing_task == current->pid);
1544                 DEBUG_REQ(D_HA|D_WARNING, req, "processing lock from %s: ",
1545                           libcfs_nid2str(req->rq_peer.nid));
1546                 handle_recovery_req(thread, req,
1547                                     trd->trd_recovery_handler);
1548                 obd->obd_replayed_locks++;
1549         }
1550
1551         spin_lock_bh(&obd->obd_processing_task_lock);
1552         target_cancel_recovery_timer(obd);
1553         spin_unlock_bh(&obd->obd_processing_task_lock);
1554         /* If some clients haven't replayed requests in time, evict them */
1555         if (obd->obd_abort_recovery) {
1556                 int stale;
1557                 CERROR("lock replay timed out, aborting ...\n");
1558                 obd->obd_abort_recovery = obd->obd_stopping;
1559                 stale = class_disconnect_stale_exports(obd, lock_replay_done);
1560                 abort_lock_replay_queue(obd);
1561         }
1562
1563         /* We drop recoverying flag to forward all new requests
1564          * to regular mds_handle() since now */
1565         spin_lock_bh(&obd->obd_processing_task_lock);
1566         obd->obd_recovering = obd->obd_abort_recovery = 0;
1567         spin_unlock_bh(&obd->obd_processing_task_lock);
1568         /* The third stage: reply on final pings */
1569         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1570         while ((req = target_next_final_ping(obd))) {
1571                 LASSERT(trd->trd_processing_task == current->pid);
1572                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1573                           libcfs_nid2str(req->rq_peer.nid));
1574                 handle_recovery_req(thread, req,
1575                                     trd->trd_recovery_handler);
1576         }
1577
1578         delta = (jiffies - delta) / HZ;
1579         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1580               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1581         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1582         LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1583         if (delta > obd_timeout * 2) {
1584                 CWARN("too long recovery - read logs\n");
1585                 libcfs_debug_dumplog();
1586         }
1587
1588         target_finish_recovery(obd);
1589
1590         lu_context_fini(&env.le_ctx);
1591         trd->trd_processing_task = 0;
1592         complete(&trd->trd_finishing);
1593         RETURN(rc);
1594 }
1595
1596 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1597 {
1598         int rc = 0;
1599         struct target_recovery_data *trd = &obd->obd_recovery_data;
1600
1601         memset(trd, 0, sizeof(*trd));
1602         init_completion(&trd->trd_starting);
1603         init_completion(&trd->trd_finishing);
1604         trd->trd_recovery_handler = handler;
1605
1606         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1607                 wait_for_completion(&trd->trd_starting);
1608                 LASSERT(obd->obd_recovering != 0);
1609         } else
1610                 rc = -ECHILD;
1611
1612         return rc;
1613 }
1614
1615 void target_stop_recovery_thread(struct obd_device *obd)
1616 {
1617         spin_lock_bh(&obd->obd_processing_task_lock);
1618         if (obd->obd_recovery_data.trd_processing_task > 0) {
1619                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1620                 CERROR("%s: Aborting recovery\n", obd->obd_name);
1621                 obd->obd_abort_recovery = 1;
1622                 wake_up(&obd->obd_next_transno_waitq);
1623                 spin_unlock_bh(&obd->obd_processing_task_lock);
1624                 wait_for_completion(&trd->trd_finishing);
1625         } else {
1626                 spin_unlock_bh(&obd->obd_processing_task_lock);
1627         }
1628 }
1629
1630 void target_recovery_fini(struct obd_device *obd)
1631 {
1632         class_disconnect_exports(obd);
1633         target_stop_recovery_thread(obd);
1634         target_cleanup_recovery(obd);
1635 }
1636 EXPORT_SYMBOL(target_recovery_fini);
1637
1638 void target_recovery_init(struct obd_device *obd, svc_handler_t handler)
1639 {
1640         if (obd->obd_max_recoverable_clients == 0)
1641                 return;
1642
1643         CWARN("RECOVERY: service %s, %d recoverable clients, "
1644               "last_transno "LPU64"\n", obd->obd_name,
1645               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1646         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1647         target_start_recovery_thread(obd, handler);
1648         obd->obd_recovery_start = CURRENT_SECONDS;
1649         /* Only used for lprocfs_status */
1650         obd->obd_recovery_end = obd->obd_recovery_start + OBD_RECOVERY_TIMEOUT;
1651         /* bz13079: this should be set to desired value for ost but not for mds */
1652         obd->obd_recovery_max_time = OBD_RECOVERY_MAX_TIME;
1653 }
1654 EXPORT_SYMBOL(target_recovery_init);
1655
1656 #endif
1657
1658 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1659 {
1660         struct obd_export *exp = req->rq_export;
1661         LASSERT(exp != NULL);
1662         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1663                 /* client declares he's ready to replay locks */
1664                 spin_lock_bh(&obd->obd_processing_task_lock);
1665                 if (exp->exp_req_replay_needed) {
1666                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1667                         spin_lock(&exp->exp_lock);
1668                         exp->exp_req_replay_needed = 0;
1669                         spin_unlock(&exp->exp_lock);
1670                         atomic_dec(&obd->obd_req_replay_clients);
1671                         LASSERT(obd->obd_recoverable_clients > 0);
1672                         obd->obd_recoverable_clients--;
1673                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1674                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1675                         wake_up(&obd->obd_next_transno_waitq);
1676                 }
1677                 spin_unlock_bh(&obd->obd_processing_task_lock);
1678         }
1679         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1680                 /* client declares he's ready to complete recovery
1681                  * so, we put the request on th final queue */
1682                 spin_lock_bh(&obd->obd_processing_task_lock);
1683                 if (exp->exp_lock_replay_needed) {
1684                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1685                         spin_lock(&exp->exp_lock);
1686                         exp->exp_lock_replay_needed = 0;
1687                         spin_unlock(&exp->exp_lock);
1688                         atomic_dec(&obd->obd_lock_replay_clients);
1689                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1690                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1691                         wake_up(&obd->obd_next_transno_waitq);
1692                 }
1693                 spin_unlock_bh(&obd->obd_processing_task_lock);
1694         }
1695
1696         return 0;
1697 }
1698
1699 int target_queue_recovery_request(struct ptlrpc_request *req,
1700                                   struct obd_device *obd)
1701 {
1702         struct list_head *tmp;
1703         int inserted = 0;
1704         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1705
1706         ENTRY;
1707
1708         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
1709                 /* Processing the queue right now, don't re-add. */
1710                 RETURN(1);
1711         }
1712
1713         target_process_req_flags(obd, req);
1714
1715         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1716                 /* client declares he's ready to complete recovery
1717                  * so, we put the request on th final queue */
1718                 req = ptlrpc_clone_req(req);
1719                 if (req == NULL)
1720                         RETURN(-ENOMEM);
1721                 DEBUG_REQ(D_HA, req, "queue final req");
1722                 spin_lock_bh(&obd->obd_processing_task_lock);
1723                 if (obd->obd_recovering)
1724                         list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1725                 else {
1726                         spin_unlock_bh(&obd->obd_processing_task_lock);
1727                         ptlrpc_free_clone(req);
1728                         if (obd->obd_stopping) {
1729                                 RETURN(-ENOTCONN);
1730                         } else {
1731                                 RETURN(1);
1732                         }
1733                 }
1734                 spin_unlock_bh(&obd->obd_processing_task_lock);
1735                 RETURN(0);
1736         }
1737         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1738                 /* client declares he's ready to replay locks */
1739                 req = ptlrpc_clone_req(req);
1740                 if (req == NULL)
1741                         RETURN(-ENOMEM);
1742                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1743                 spin_lock_bh(&obd->obd_processing_task_lock);
1744                 LASSERT(obd->obd_recovering);
1745                 /* usually due to recovery abort */
1746                 if (!req->rq_export->exp_in_recovery) {
1747                         spin_unlock_bh(&obd->obd_processing_task_lock);
1748                         ptlrpc_free_clone(req);
1749                         RETURN(-ENOTCONN);
1750                 }
1751                 LASSERT(req->rq_export->exp_lock_replay_needed);
1752                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1753                 spin_unlock_bh(&obd->obd_processing_task_lock);
1754                 wake_up(&obd->obd_next_transno_waitq);
1755                 RETURN(0);
1756         }
1757
1758         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1759          * (i.e. buflens etc are in my own byte order), but type-dependent
1760          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1761
1762         if (!transno) {
1763                 CFS_INIT_LIST_HEAD(&req->rq_list);
1764                 DEBUG_REQ(D_HA, req, "not queueing");
1765                 RETURN(1);
1766         }
1767
1768         spin_lock_bh(&obd->obd_processing_task_lock);
1769
1770         /* If we're processing the queue, we want don't want to queue this
1771          * message.
1772          *
1773          * Also, if this request has a transno less than the one we're waiting
1774          * for, we should process it now.  It could (and currently always will)
1775          * be an open request for a descriptor that was opened some time ago.
1776          *
1777          * Also, a resent, replayed request that has already been
1778          * handled will pass through here and be processed immediately.
1779          */
1780         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying: %i\n",
1781               obd->obd_next_recovery_transno, transno, obd->obd_req_replaying);
1782         if (transno < obd->obd_next_recovery_transno && obd->obd_req_replaying) {
1783                 /* Processing the queue right now, don't re-add. */
1784                 LASSERT(list_empty(&req->rq_list));
1785                 spin_unlock_bh(&obd->obd_processing_task_lock);
1786                 RETURN(1);
1787         }
1788         spin_unlock_bh(&obd->obd_processing_task_lock);
1789
1790         /* A resent, replayed request that is still on the queue; just drop it.
1791            The queued request will handle this. */
1792         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT|MSG_REPLAY)) ==
1793             (MSG_RESENT | MSG_REPLAY)) {
1794                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1795                 RETURN(0);
1796         }
1797
1798         req = ptlrpc_clone_req(req);
1799         if (req == NULL)
1800                 RETURN(-ENOMEM);
1801
1802         spin_lock_bh(&obd->obd_processing_task_lock);
1803         LASSERT(obd->obd_recovering);
1804         if (!req->rq_export->exp_in_recovery) {
1805                 spin_unlock_bh(&obd->obd_processing_task_lock);
1806                 ptlrpc_free_clone(req);
1807                 RETURN(-ENOTCONN);
1808         }
1809         LASSERT(req->rq_export->exp_req_replay_needed);
1810
1811         /* XXX O(n^2) */
1812         list_for_each(tmp, &obd->obd_req_replay_queue) {
1813                 struct ptlrpc_request *reqiter =
1814                         list_entry(tmp, struct ptlrpc_request, rq_list);
1815
1816                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1817                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1818                         inserted = 1;
1819                         break;
1820                 }
1821         }
1822
1823         if (!inserted)
1824                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1825
1826         obd->obd_requests_queued_for_recovery++;
1827         wake_up(&obd->obd_next_transno_waitq);
1828         spin_unlock_bh(&obd->obd_processing_task_lock);
1829         RETURN(0);
1830
1831 }
1832
1833 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1834 {
1835         return req->rq_export->exp_obd;
1836 }
1837
1838 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1839 {
1840         LASSERT(exp != NULL);
1841         return &exp->exp_obd->obd_namespace->ns_pool;
1842 }
1843
1844 int target_pack_pool_reply(struct ptlrpc_request *req)
1845 {
1846         struct ldlm_pool *pl;
1847         ENTRY;
1848    
1849         if (!req->rq_export || !req->rq_export->exp_obd ||
1850             !exp_connect_lru_resize(req->rq_export)) {
1851                 lustre_msg_set_slv(req->rq_repmsg, 0);
1852                 lustre_msg_set_limit(req->rq_repmsg, 0);
1853                 RETURN(0);
1854         }
1855
1856         pl = ldlm_exp2pl(req->rq_export);
1857
1858         spin_lock(&pl->pl_lock);
1859         LASSERT(ldlm_pool_get_slv(pl) != 0 && ldlm_pool_get_limit(pl) != 0);
1860         lustre_msg_set_slv(req->rq_repmsg, ldlm_pool_get_slv(pl));
1861         lustre_msg_set_limit(req->rq_repmsg, ldlm_pool_get_limit(pl));
1862         spin_unlock(&pl->pl_lock);
1863
1864         RETURN(0);
1865 }
1866
1867 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
1868 {
1869         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
1870                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1871                 return (-ECOMM);
1872         }
1873
1874         if (unlikely(rc)) {
1875                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1876                 req->rq_status = rc;
1877                 return (ptlrpc_error(req));
1878         } else {
1879                 DEBUG_REQ(D_NET, req, "sending reply");
1880         }
1881
1882         return (ptlrpc_send_reply(req, 1));
1883 }
1884
1885 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1886 {
1887         int                        netrc;
1888         struct ptlrpc_reply_state *rs;
1889         struct obd_device         *obd;
1890         struct obd_export         *exp;
1891         struct ptlrpc_service     *svc;
1892
1893         if (req->rq_no_reply)
1894                 return;
1895
1896         svc = req->rq_rqbd->rqbd_service;
1897         rs = req->rq_reply_state;
1898         if (rs == NULL || !rs->rs_difficult) {
1899                 /* no notifiers */
1900                 target_send_reply_msg (req, rc, fail_id);
1901                 return;
1902         }
1903
1904         /* must be an export if locks saved */
1905         LASSERT (req->rq_export != NULL);
1906         /* req/reply consistent */
1907         LASSERT (rs->rs_service == svc);
1908
1909         /* "fresh" reply */
1910         LASSERT (!rs->rs_scheduled);
1911         LASSERT (!rs->rs_scheduled_ever);
1912         LASSERT (!rs->rs_handled);
1913         LASSERT (!rs->rs_on_net);
1914         LASSERT (rs->rs_export == NULL);
1915         LASSERT (list_empty(&rs->rs_obd_list));
1916         LASSERT (list_empty(&rs->rs_exp_list));
1917
1918         exp = class_export_get (req->rq_export);
1919         obd = exp->exp_obd;
1920
1921         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1922         rs->rs_scheduled = 1;
1923         rs->rs_on_net    = 1;
1924         rs->rs_xid       = req->rq_xid;
1925         rs->rs_transno   = req->rq_transno;
1926         rs->rs_export    = exp;
1927
1928         spin_lock(&obd->obd_uncommitted_replies_lock);
1929
1930         if (rs->rs_transno > obd->obd_last_committed) {
1931                 /* not committed already */
1932                 list_add_tail (&rs->rs_obd_list,
1933                                &obd->obd_uncommitted_replies);
1934         }
1935
1936         spin_unlock (&obd->obd_uncommitted_replies_lock);
1937         spin_lock (&exp->exp_lock);
1938
1939         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1940
1941         spin_unlock(&exp->exp_lock);
1942
1943         netrc = target_send_reply_msg (req, rc, fail_id);
1944
1945         spin_lock(&svc->srv_lock);
1946
1947         svc->srv_n_difficult_replies++;
1948
1949         if (netrc != 0) {
1950                 /* error sending: reply is off the net.  Also we need +1
1951                  * reply ref until ptlrpc_server_handle_reply() is done
1952                  * with the reply state (if the send was successful, there
1953                  * would have been +1 ref for the net, which
1954                  * reply_out_callback leaves alone) */
1955                 rs->rs_on_net = 0;
1956                 ptlrpc_rs_addref(rs);
1957                 atomic_inc (&svc->srv_outstanding_replies);
1958         }
1959
1960         if (!rs->rs_on_net ||                   /* some notifier */
1961             list_empty(&rs->rs_exp_list) ||     /* completed already */
1962             list_empty(&rs->rs_obd_list)) {
1963                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1964                 cfs_waitq_signal (&svc->srv_waitq);
1965         } else {
1966                 list_add (&rs->rs_list, &svc->srv_active_replies);
1967                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1968         }
1969
1970         spin_unlock(&svc->srv_lock);
1971 }
1972
1973 int target_handle_ping(struct ptlrpc_request *req)
1974 {
1975         obd_ping(req->rq_export);
1976         return req_capsule_server_pack(&req->rq_pill);
1977 }
1978
1979 void target_committed_to_req(struct ptlrpc_request *req)
1980 {
1981         struct obd_device *obd;
1982
1983         if (req == NULL || req->rq_export == NULL)
1984                 return;
1985
1986         obd = req->rq_export->exp_obd;
1987         if (obd == NULL)
1988                 return;
1989
1990         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1991                 lustre_msg_set_last_committed(req->rq_repmsg,
1992                                               obd->obd_last_committed);
1993         else
1994                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update");
1995
1996         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
1997                obd->obd_last_committed, req->rq_transno, req->rq_xid);
1998 }
1999
2000 EXPORT_SYMBOL(target_committed_to_req);
2001
2002 #ifdef HAVE_QUOTA_SUPPORT
2003 int target_handle_qc_callback(struct ptlrpc_request *req)
2004 {
2005         struct obd_quotactl *oqctl;
2006         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2007
2008         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2009         if (oqctl == NULL)
2010                 RETURN(-EPROTO);
2011
2012         cli->cl_qchk_stat = oqctl->qc_stat;
2013
2014         return 0;
2015 }
2016
2017 int target_handle_dqacq_callback(struct ptlrpc_request *req)
2018 {
2019 #ifdef __KERNEL__
2020         struct obd_device *obd = req->rq_export->exp_obd;
2021         struct obd_device *master_obd;
2022         struct lustre_quota_ctxt *qctxt;
2023         struct qunit_data *qdata;
2024         void* rep;
2025         struct qunit_data_old *qdata_old;
2026         int rc = 0;
2027         ENTRY;
2028
2029         rc = req_capsule_server_pack(&req->rq_pill);
2030         if (rc) {
2031                 CERROR("packing reply failed!: rc = %d\n", rc);
2032                 RETURN(rc);
2033         }
2034
2035         LASSERT(req->rq_export);
2036
2037         /* fixed for bug10707 */
2038         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2039             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2040                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
2041                 rep = req_capsule_server_get(&req->rq_pill,
2042                                              &RMF_QUNIT_DATA);
2043                 LASSERT(rep);
2044                 qdata = req_capsule_client_swab_get(&req->rq_pill,
2045                                                     &RMF_QUNIT_DATA,
2046                                           (void*)lustre_swab_qdata);
2047         } else {
2048                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
2049                 rep = req_capsule_server_get(&req->rq_pill, &RMF_QUNIT_DATA);
2050                 LASSERT(rep);
2051                 qdata_old = req_capsule_client_swab_get(&req->rq_pill,
2052                                                         &RMF_QUNIT_DATA,
2053                                            (void*)lustre_swab_qdata_old);
2054                 qdata = lustre_quota_old_to_new(qdata_old);
2055         }
2056
2057         if (qdata == NULL)
2058                 RETURN(-EPROTO);
2059
2060         /* we use the observer */
2061         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
2062         master_obd = obd->obd_observer->obd_observer;
2063         qctxt = &master_obd->u.obt.obt_qctxt;
2064
2065         LASSERT(qctxt->lqc_handler);
2066         rc = qctxt->lqc_handler(master_obd, qdata,
2067                                 lustre_msg_get_opc(req->rq_reqmsg));
2068         if (rc && rc != -EDQUOT)
2069                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2070                        "dqacq failed! (rc:%d)\n", rc);
2071
2072         /* the qd_count might be changed in lqc_handler */
2073         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2074             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2075                 memcpy(rep, qdata, sizeof(*qdata));
2076         } else {
2077                 qdata_old = lustre_quota_new_to_old(qdata);
2078                 memcpy(rep, qdata_old, sizeof(*qdata_old));
2079         }
2080         req->rq_status = rc;
2081         rc = ptlrpc_reply(req);
2082
2083         RETURN(rc);
2084 #else
2085         return 0;
2086 #endif /* !__KERNEL__ */
2087 }
2088 #endif /* HAVE_QUOTA_SUPPORT */
2089
2090 ldlm_mode_t lck_compat_array[] = {
2091         [LCK_EX] LCK_COMPAT_EX,
2092         [LCK_PW] LCK_COMPAT_PW,
2093         [LCK_PR] LCK_COMPAT_PR,
2094         [LCK_CW] LCK_COMPAT_CW,
2095         [LCK_CR] LCK_COMPAT_CR,
2096         [LCK_NL] LCK_COMPAT_NL,
2097         [LCK_GROUP] LCK_COMPAT_GROUP
2098 };