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