Whamcloud - gitweb
12ab2891122578680c702596cbb7f1f26efa540c
[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         time_t timeout_shift = OBD_RECOVERY_TIMEOUT;
1177         spin_lock_bh(&obd->obd_processing_task_lock);
1178         if (!obd->obd_recovering) {
1179                 spin_unlock_bh(&obd->obd_processing_task_lock);
1180                 return;
1181         }
1182         if (cfs_time_current_sec() + OBD_RECOVERY_TIMEOUT > 
1183             obd->obd_recovery_start + obd->obd_recovery_max_time)
1184                 timeout_shift = obd->obd_recovery_start + 
1185                         obd->obd_recovery_max_time - cfs_time_current_sec();
1186         cfs_timer_arm(&obd->obd_recovery_timer, cfs_time_shift(timeout_shift));
1187         spin_unlock_bh(&obd->obd_processing_task_lock);
1188         CDEBUG(D_HA, "%s: timer will expire in %u seconds\n", obd->obd_name,
1189                (unsigned int)timeout_shift);
1190         /* Only used for lprocfs_status */
1191         obd->obd_recovery_end = CURRENT_SECONDS + timeout_shift;
1192 }
1193
1194
1195 /* Only start it the first time called */
1196 void target_start_recovery_timer(struct obd_device *obd)
1197 {
1198         spin_lock_bh(&obd->obd_processing_task_lock);
1199         if (obd->obd_recovery_handler
1200             || timer_pending((struct timer_list *)&obd->obd_recovery_timer)) {
1201                 spin_unlock_bh(&obd->obd_processing_task_lock);
1202                 return;
1203         }
1204         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1205               OBD_RECOVERY_TIMEOUT);
1206         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1207         spin_unlock_bh(&obd->obd_processing_task_lock);
1208
1209         reset_recovery_timer(obd);
1210 }
1211
1212 #ifdef __KERNEL__
1213 static int check_for_next_transno(struct obd_device *obd)
1214 {
1215         struct ptlrpc_request *req = NULL;
1216         int wake_up = 0, connected, completed, queue_len, max;
1217         __u64 next_transno, req_transno;
1218         ENTRY;
1219         spin_lock_bh(&obd->obd_processing_task_lock);
1220
1221         if (!list_empty(&obd->obd_req_replay_queue)) {
1222                 req = list_entry(obd->obd_req_replay_queue.next,
1223                                  struct ptlrpc_request, rq_list);
1224                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1225         } else {
1226                 req_transno = 0;
1227         }
1228
1229         max = obd->obd_max_recoverable_clients;
1230         connected = obd->obd_connected_clients;
1231         completed = connected - obd->obd_recoverable_clients;
1232         queue_len = obd->obd_requests_queued_for_recovery;
1233         next_transno = obd->obd_next_recovery_transno;
1234
1235         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1236                "req_transno: "LPU64", next_transno: "LPU64"\n",
1237                max, connected, completed, queue_len, req_transno, next_transno);
1238
1239         if (obd->obd_abort_recovery) {
1240                 CDEBUG(D_HA, "waking for aborted recovery\n");
1241                 wake_up = 1;
1242         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1243                 CDEBUG(D_HA, "waking for completed recovery\n");
1244                 wake_up = 1;
1245         } else if (req_transno == next_transno) {
1246                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1247                 wake_up = 1;
1248         } else if (queue_len + completed == max) {
1249                 /* handle gaps occured due to lost reply. It is allowed gaps
1250                  * because all clients are connected and there will be resend
1251                  * for missed transaction */
1252                 LASSERTF(req_transno >= next_transno,
1253                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1254                          req_transno, next_transno);
1255
1256                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1257                        "waking for skipped transno (skip: "LPD64
1258                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1259                        next_transno, queue_len, completed, connected, req_transno);
1260                 obd->obd_next_recovery_transno = req_transno;
1261                 wake_up = 1;
1262         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1263                 /* some clients haven't connected in time, but we can try
1264                  * to replay requests that demand on already committed ones
1265                  * also, we can replay first non-committed transation */
1266                 LASSERT(req_transno != 0);
1267                 if (req_transno == obd->obd_last_committed + 1) {
1268                         obd->obd_next_recovery_transno = req_transno;
1269                 } else if (req_transno > obd->obd_last_committed) {
1270                         /* can't continue recovery: have no needed transno */
1271                         obd->obd_abort_recovery = 1;
1272                         CDEBUG(D_ERROR, "abort due to missed clients. max: %d, "
1273                                "connected: %d, completed: %d, queue_len: %d, "
1274                                "req_transno: "LPU64", next_transno: "LPU64"\n",
1275                                max, connected, completed, queue_len,
1276                                req_transno, next_transno);
1277                 }
1278                 wake_up = 1;
1279         }
1280
1281         spin_unlock_bh(&obd->obd_processing_task_lock);
1282         return wake_up;
1283 }
1284
1285 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1286 {
1287         struct l_wait_info lwi = { 0 };
1288         struct ptlrpc_request *req;
1289
1290         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1291                obd->obd_next_recovery_transno);
1292         l_wait_event(obd->obd_next_transno_waitq,
1293                      check_for_next_transno(obd), &lwi);
1294
1295         spin_lock_bh(&obd->obd_processing_task_lock);
1296         if (obd->obd_abort_recovery) {
1297                 req = NULL;
1298         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1299                 req = list_entry(obd->obd_req_replay_queue.next,
1300                                  struct ptlrpc_request, rq_list);
1301                 list_del_init(&req->rq_list);
1302                 obd->obd_requests_queued_for_recovery--;
1303         } else {
1304                 req = NULL;
1305         }
1306         spin_unlock_bh(&obd->obd_processing_task_lock);
1307         RETURN(req);
1308 }
1309
1310 static int check_for_next_lock(struct obd_device *obd)
1311 {
1312         struct ptlrpc_request *req = NULL;
1313         int wake_up = 0;
1314
1315         spin_lock_bh(&obd->obd_processing_task_lock);
1316         if (!list_empty(&obd->obd_lock_replay_queue)) {
1317                 req = list_entry(obd->obd_lock_replay_queue.next,
1318                                  struct ptlrpc_request, rq_list);
1319                 CDEBUG(D_HA, "waking for next lock\n");
1320                 wake_up = 1;
1321         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1322                 CDEBUG(D_HA, "waking for completed lock replay\n");
1323                 wake_up = 1;
1324         } else if (obd->obd_abort_recovery) {
1325                 CDEBUG(D_HA, "waking for aborted recovery\n");
1326                 wake_up = 1;
1327         }
1328         spin_unlock_bh(&obd->obd_processing_task_lock);
1329
1330         return wake_up;
1331 }
1332
1333 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1334 {
1335         struct l_wait_info lwi = { 0 };
1336         struct ptlrpc_request *req;
1337
1338         CDEBUG(D_HA, "Waiting for lock\n");
1339         l_wait_event(obd->obd_next_transno_waitq,
1340                      check_for_next_lock(obd), &lwi);
1341
1342         spin_lock_bh(&obd->obd_processing_task_lock);
1343         if (obd->obd_abort_recovery) {
1344                 req = NULL;
1345         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1346                 req = list_entry(obd->obd_lock_replay_queue.next,
1347                                  struct ptlrpc_request, rq_list);
1348                 list_del_init(&req->rq_list);
1349         } else {
1350                 req = NULL;
1351         }
1352         spin_unlock_bh(&obd->obd_processing_task_lock);
1353         return req;
1354 }
1355
1356 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1357 {
1358         struct ptlrpc_request *req;
1359
1360         spin_lock_bh(&obd->obd_processing_task_lock);
1361         if (!list_empty(&obd->obd_final_req_queue)) {
1362                 req = list_entry(obd->obd_final_req_queue.next,
1363                                  struct ptlrpc_request, rq_list);
1364                 list_del_init(&req->rq_list);
1365         } else {
1366                 req = NULL;
1367         }
1368         spin_unlock_bh(&obd->obd_processing_task_lock);
1369         return req;
1370 }
1371
1372 static inline int req_replay_done(struct obd_export *exp)
1373 {
1374         return (exp->exp_req_replay_needed == 0);
1375 }
1376
1377 static inline int lock_replay_done(struct obd_export *exp)
1378 {
1379         return (exp->exp_lock_replay_needed == 0);
1380 }
1381
1382 static inline int connect_done(struct obd_export *exp)
1383 {
1384         return (exp->exp_in_recovery != 0);
1385 }
1386
1387 static int check_for_clients(struct obd_device *obd)
1388 {
1389         if (obd->obd_abort_recovery)
1390                 return 1;
1391         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1392         if (obd->obd_no_conn == 0 &&
1393             obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1394                 return 1;
1395         return 0;
1396 }
1397
1398 static int handle_recovery_req(struct ptlrpc_thread *thread,
1399                                struct ptlrpc_request *req,
1400                                svc_handler_t handler)
1401 {
1402         int rc;
1403         ENTRY;
1404
1405         rc = lu_context_init(&req->rq_session, LCT_SESSION);
1406         if (rc) {
1407                 CERROR("Failure to initialize session: %d\n", rc);
1408                 return rc;
1409         }
1410         req->rq_session.lc_thread = thread;
1411         lu_context_enter(&req->rq_session);
1412         req->rq_svc_thread = thread;
1413         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1414
1415         (void)handler(req);
1416
1417         lu_context_exit(&req->rq_session);
1418         lu_context_fini(&req->rq_session);
1419         /* don't reset timer for final stage */
1420         if (!req_replay_done(req->rq_export) ||
1421             !lock_replay_done(req->rq_export))
1422                 reset_recovery_timer(class_exp2obd(req->rq_export));
1423         ptlrpc_free_clone(req);
1424         RETURN(0);
1425 }
1426
1427 static int target_recovery_thread(void *arg)
1428 {
1429         struct obd_device *obd = arg;
1430         struct ptlrpc_request *req;
1431         struct target_recovery_data *trd = &obd->obd_recovery_data;
1432         struct l_wait_info lwi = { 0 };
1433         unsigned long delta;
1434         unsigned long flags;
1435         struct lu_env env;
1436         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1437         __u32 recov_ctx_tags = LCT_MD_THREAD;
1438         int rc = 0;
1439         ENTRY;
1440
1441         cfs_daemonize("tgt_recov");
1442
1443         SIGNAL_MASK_LOCK(current, flags);
1444         sigfillset(&current->blocked);
1445         RECALC_SIGPENDING;
1446         SIGNAL_MASK_UNLOCK(current, flags);
1447
1448         rc = lu_context_init(&env.le_ctx, recov_ctx_tags);
1449         if (rc)
1450                 RETURN(rc);
1451
1452         thread->t_env = &env;
1453         env.le_ctx.lc_thread = thread;
1454
1455         CERROR("%s: started recovery thread pid %d\n", obd->obd_name,
1456                current->pid);
1457         trd->trd_processing_task = current->pid;
1458
1459         obd->obd_recovering = 1;
1460         complete(&trd->trd_starting);
1461
1462         /* first of all, we have to know the first transno to replay */
1463         obd->obd_abort_recovery = 0;
1464         l_wait_event(obd->obd_next_transno_waitq,
1465                      check_for_clients(obd), &lwi);
1466
1467         spin_lock_bh(&obd->obd_processing_task_lock);
1468         target_cancel_recovery_timer(obd);
1469         spin_unlock_bh(&obd->obd_processing_task_lock);
1470
1471         /* If some clients haven't connected in time, evict them */
1472         if (obd->obd_abort_recovery) {
1473                 CWARN("Some clients haven't connect in time (%d/%d),"
1474                        "evict them\n", obd->obd_connected_clients,
1475                        obd->obd_max_recoverable_clients);
1476                 obd->obd_abort_recovery = obd->obd_stopping;
1477                 class_disconnect_stale_exports(obd, connect_done);
1478         }
1479         /* next stage: replay requests */
1480         delta = jiffies;
1481         obd->obd_req_replaying = 1;
1482         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1483               atomic_read(&obd->obd_req_replay_clients),
1484               obd->obd_next_recovery_transno);
1485         while ((req = target_next_replay_req(obd))) {
1486                 LASSERT(trd->trd_processing_task == current->pid);
1487                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1488                           lustre_msg_get_transno(req->rq_reqmsg),
1489                           libcfs_nid2str(req->rq_peer.nid));
1490
1491                 handle_recovery_req(thread, req,
1492                                     trd->trd_recovery_handler);
1493                 obd->obd_replayed_requests++;
1494                 spin_lock_bh(&obd->obd_processing_task_lock);
1495                 obd->obd_next_recovery_transno++;
1496                 spin_unlock_bh(&obd->obd_processing_task_lock);
1497         }
1498
1499         spin_lock_bh(&obd->obd_processing_task_lock);
1500         target_cancel_recovery_timer(obd);
1501         spin_unlock_bh(&obd->obd_processing_task_lock);
1502
1503         /* If some clients haven't replayed requests in time, evict them */
1504         if (obd->obd_abort_recovery) {
1505                 CDEBUG(D_ERROR, "req replay timed out, aborting ...\n");
1506                 obd->obd_abort_recovery = obd->obd_stopping;
1507                 class_disconnect_stale_exports(obd, req_replay_done);
1508                 abort_req_replay_queue(obd);
1509         }
1510         /* The second stage: replay locks */
1511         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1512                atomic_read(&obd->obd_lock_replay_clients));
1513         while ((req = target_next_replay_lock(obd))) {
1514                 LASSERT(trd->trd_processing_task == current->pid);
1515                 DEBUG_REQ(D_HA|D_WARNING, req, "processing lock from %s: ",
1516                           libcfs_nid2str(req->rq_peer.nid));
1517                 handle_recovery_req(thread, req,
1518                                     trd->trd_recovery_handler);
1519                 obd->obd_replayed_locks++;
1520         }
1521
1522         spin_lock_bh(&obd->obd_processing_task_lock);
1523         target_cancel_recovery_timer(obd);
1524         spin_unlock_bh(&obd->obd_processing_task_lock);
1525         /* If some clients haven't replayed requests in time, evict them */
1526         if (obd->obd_abort_recovery) {
1527                 int stale;
1528                 CERROR("lock replay timed out, aborting ...\n");
1529                 obd->obd_abort_recovery = obd->obd_stopping;
1530                 stale = class_disconnect_stale_exports(obd, lock_replay_done);
1531                 abort_lock_replay_queue(obd);
1532         }
1533
1534         /* We drop recoverying flag to forward all new requests
1535          * to regular mds_handle() since now */
1536         spin_lock_bh(&obd->obd_processing_task_lock);
1537         obd->obd_recovering = obd->obd_abort_recovery = 0;
1538         spin_unlock_bh(&obd->obd_processing_task_lock);
1539         /* The third stage: reply on final pings */
1540         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1541         while ((req = target_next_final_ping(obd))) {
1542                 LASSERT(trd->trd_processing_task == current->pid);
1543                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1544                           libcfs_nid2str(req->rq_peer.nid));
1545                 handle_recovery_req(thread, req,
1546                                     trd->trd_recovery_handler);
1547         }
1548
1549         delta = (jiffies - delta) / HZ;
1550         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1551               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1552         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1553         LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1554         if (delta > obd_timeout * 2) {
1555                 CWARN("too long recovery - read logs\n");
1556                 libcfs_debug_dumplog();
1557         }
1558
1559         target_finish_recovery(obd);
1560
1561         lu_env_fini(&env);
1562         trd->trd_processing_task = 0;
1563         complete(&trd->trd_finishing);
1564         RETURN(rc);
1565 }
1566
1567 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1568 {
1569         int rc = 0;
1570         struct target_recovery_data *trd = &obd->obd_recovery_data;
1571
1572         memset(trd, 0, sizeof(*trd));
1573         init_completion(&trd->trd_starting);
1574         init_completion(&trd->trd_finishing);
1575         trd->trd_recovery_handler = handler;
1576
1577         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1578                 wait_for_completion(&trd->trd_starting);
1579                 LASSERT(obd->obd_recovering != 0);
1580         } else
1581                 rc = -ECHILD;
1582
1583         return rc;
1584 }
1585
1586 void target_stop_recovery_thread(struct obd_device *obd)
1587 {
1588         spin_lock_bh(&obd->obd_processing_task_lock);
1589         if (obd->obd_recovery_data.trd_processing_task > 0) {
1590                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1591                 CERROR("%s: Aborting recovery\n", obd->obd_name);
1592                 obd->obd_abort_recovery = 1;
1593                 wake_up(&obd->obd_next_transno_waitq);
1594                 spin_unlock_bh(&obd->obd_processing_task_lock);
1595                 wait_for_completion(&trd->trd_finishing);
1596         } else {
1597                 spin_unlock_bh(&obd->obd_processing_task_lock);
1598         }
1599 }
1600
1601 void target_recovery_fini(struct obd_device *obd)
1602 {
1603         class_disconnect_exports(obd);
1604         target_stop_recovery_thread(obd);
1605         target_cleanup_recovery(obd);
1606 }
1607 EXPORT_SYMBOL(target_recovery_fini);
1608
1609 void target_recovery_init(struct obd_device *obd, svc_handler_t handler)
1610 {
1611         if (obd->obd_max_recoverable_clients == 0)
1612                 return;
1613         
1614         CWARN("RECOVERY: service %s, %d recoverable clients, "
1615               "last_transno "LPU64"\n", obd->obd_name,
1616               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1617         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1618         target_start_recovery_thread(obd, handler);
1619         obd->obd_recovery_start = CURRENT_SECONDS;
1620         /* Only used for lprocfs_status */
1621         obd->obd_recovery_end = obd->obd_recovery_start + OBD_RECOVERY_TIMEOUT;
1622         /* bz13079: this should be set to desired value for ost but not for mds */
1623         obd->obd_recovery_max_time = OBD_RECOVERY_MAX_TIME;
1624 }
1625 EXPORT_SYMBOL(target_recovery_init);
1626
1627 #endif
1628
1629 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1630 {
1631         struct obd_export *exp = req->rq_export;
1632         LASSERT(exp != NULL);
1633         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1634                 /* client declares he's ready to replay locks */
1635                 spin_lock_bh(&obd->obd_processing_task_lock);
1636                 if (exp->exp_req_replay_needed) {
1637                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1638                         spin_lock(&exp->exp_lock);
1639                         exp->exp_req_replay_needed = 0;
1640                         spin_unlock(&exp->exp_lock);
1641                         atomic_dec(&obd->obd_req_replay_clients);
1642                         LASSERT(obd->obd_recoverable_clients > 0);
1643                         obd->obd_recoverable_clients--;
1644                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1645                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1646                         wake_up(&obd->obd_next_transno_waitq);
1647                 }
1648                 spin_unlock_bh(&obd->obd_processing_task_lock);
1649         }
1650         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1651                 /* client declares he's ready to complete recovery
1652                  * so, we put the request on th final queue */
1653                 spin_lock_bh(&obd->obd_processing_task_lock);
1654                 if (exp->exp_lock_replay_needed) {
1655                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1656                         spin_lock(&exp->exp_lock);
1657                         exp->exp_lock_replay_needed = 0;
1658                         spin_unlock(&exp->exp_lock);
1659                         atomic_dec(&obd->obd_lock_replay_clients);
1660                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1661                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1662                         wake_up(&obd->obd_next_transno_waitq);
1663                 }
1664                 spin_unlock_bh(&obd->obd_processing_task_lock);
1665         }
1666
1667         return 0;
1668 }
1669
1670 int target_queue_recovery_request(struct ptlrpc_request *req,
1671                                   struct obd_device *obd)
1672 {
1673         struct list_head *tmp;
1674         int inserted = 0;
1675         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1676
1677         ENTRY;
1678
1679         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
1680                 /* Processing the queue right now, don't re-add. */
1681                 RETURN(1);
1682         }
1683
1684         target_process_req_flags(obd, req);
1685
1686         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1687                 /* client declares he's ready to complete recovery
1688                  * so, we put the request on th final queue */
1689                 req = ptlrpc_clone_req(req);
1690                 if (req == NULL)
1691                         RETURN(-ENOMEM);
1692                 DEBUG_REQ(D_HA, req, "queue final req");
1693                 spin_lock_bh(&obd->obd_processing_task_lock);
1694                 if (obd->obd_recovering)
1695                         list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1696                 else {
1697                         spin_unlock_bh(&obd->obd_processing_task_lock);
1698                         ptlrpc_free_clone(req);
1699                         if (obd->obd_stopping) {
1700                                 RETURN(-ENOTCONN);
1701                         } else {
1702                                 RETURN(1);
1703                         }
1704                 }
1705                 spin_unlock_bh(&obd->obd_processing_task_lock);
1706                 RETURN(0);
1707         }
1708         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1709                 /* client declares he's ready to replay locks */
1710                 req = ptlrpc_clone_req(req);
1711                 if (req == NULL)
1712                         RETURN(-ENOMEM);
1713                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1714                 spin_lock_bh(&obd->obd_processing_task_lock);
1715                 LASSERT(obd->obd_recovering);
1716                 /* usually due to recovery abort */
1717                 if (!req->rq_export->exp_in_recovery) {
1718                         spin_unlock_bh(&obd->obd_processing_task_lock);
1719                         ptlrpc_free_clone(req);
1720                         RETURN(-ENOTCONN);
1721                 }
1722                 LASSERT(req->rq_export->exp_lock_replay_needed);
1723                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1724                 spin_unlock_bh(&obd->obd_processing_task_lock);
1725                 wake_up(&obd->obd_next_transno_waitq);
1726                 RETURN(0);
1727         }
1728
1729         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1730          * (i.e. buflens etc are in my own byte order), but type-dependent
1731          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1732
1733         if (!transno) {
1734                 CFS_INIT_LIST_HEAD(&req->rq_list);
1735                 DEBUG_REQ(D_HA, req, "not queueing");
1736                 RETURN(1);
1737         }
1738
1739         spin_lock_bh(&obd->obd_processing_task_lock);
1740
1741         /* If we're processing the queue, we want don't want to queue this
1742          * message.
1743          *
1744          * Also, if this request has a transno less than the one we're waiting
1745          * for, we should process it now.  It could (and currently always will)
1746          * be an open request for a descriptor that was opened some time ago.
1747          *
1748          * Also, a resent, replayed request that has already been
1749          * handled will pass through here and be processed immediately.
1750          */
1751         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying: %i\n",
1752               obd->obd_next_recovery_transno, transno, obd->obd_req_replaying);
1753         if (transno < obd->obd_next_recovery_transno && obd->obd_req_replaying) {
1754                 /* Processing the queue right now, don't re-add. */
1755                 LASSERT(list_empty(&req->rq_list));
1756                 spin_unlock_bh(&obd->obd_processing_task_lock);
1757                 RETURN(1);
1758         }
1759         spin_unlock_bh(&obd->obd_processing_task_lock);
1760
1761         /* A resent, replayed request that is still on the queue; just drop it.
1762            The queued request will handle this. */
1763         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT|MSG_REPLAY)) ==
1764             (MSG_RESENT | MSG_REPLAY)) {
1765                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1766                 RETURN(0);
1767         }
1768
1769         req = ptlrpc_clone_req(req);
1770         if (req == NULL)
1771                 RETURN(-ENOMEM);
1772
1773         spin_lock_bh(&obd->obd_processing_task_lock);
1774         LASSERT(obd->obd_recovering);
1775         if (!req->rq_export->exp_in_recovery) {
1776                 spin_unlock_bh(&obd->obd_processing_task_lock);
1777                 ptlrpc_free_clone(req);
1778                 RETURN(-ENOTCONN);
1779         }
1780         LASSERT(req->rq_export->exp_req_replay_needed);
1781
1782         /* XXX O(n^2) */
1783         list_for_each(tmp, &obd->obd_req_replay_queue) {
1784                 struct ptlrpc_request *reqiter =
1785                         list_entry(tmp, struct ptlrpc_request, rq_list);
1786
1787                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1788                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1789                         inserted = 1;
1790                         break;
1791                 }
1792         }
1793
1794         if (!inserted)
1795                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1796
1797         obd->obd_requests_queued_for_recovery++;
1798         wake_up(&obd->obd_next_transno_waitq);
1799         spin_unlock_bh(&obd->obd_processing_task_lock);
1800         RETURN(0);
1801
1802 }
1803
1804 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1805 {
1806         return req->rq_export->exp_obd;
1807 }
1808
1809 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1810 {
1811         LASSERT(exp != NULL);
1812         return &exp->exp_obd->obd_namespace->ns_pool;
1813 }
1814
1815 int target_pack_pool_reply(struct ptlrpc_request *req)
1816 {
1817         struct ldlm_pool *pl;
1818         ENTRY;
1819    
1820         if (!req->rq_export || !exp_connect_lru_resize(req->rq_export)) {
1821                 lustre_msg_set_slv(req->rq_repmsg, 0);
1822                 lustre_msg_set_limit(req->rq_repmsg, 0);
1823                 RETURN(0);
1824         }
1825  
1826         pl = ldlm_exp2pl(req->rq_export);
1827
1828         spin_lock(&pl->pl_lock);
1829         LASSERT(ldlm_pool_get_slv(pl) != 0 && ldlm_pool_get_limit(pl) != 0);
1830         lustre_msg_set_slv(req->rq_repmsg, ldlm_pool_get_slv(pl));
1831         lustre_msg_set_limit(req->rq_repmsg, ldlm_pool_get_limit(pl));
1832         spin_unlock(&pl->pl_lock);
1833
1834         RETURN(0);
1835 }
1836
1837 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
1838 {
1839         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
1840                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1841                 return (-ECOMM);
1842         }
1843
1844         if (unlikely(rc)) {
1845                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1846                 req->rq_status = rc;
1847                 return (ptlrpc_error(req));
1848         } else {
1849                 DEBUG_REQ(D_NET, req, "sending reply");
1850         }
1851
1852         return (ptlrpc_send_reply(req, 1));
1853 }
1854
1855 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1856 {
1857         int                        netrc;
1858         struct ptlrpc_reply_state *rs;
1859         struct obd_device         *obd;
1860         struct obd_export         *exp;
1861         struct ptlrpc_service     *svc;
1862
1863         if (req->rq_no_reply)
1864                 return;
1865
1866         svc = req->rq_rqbd->rqbd_service;
1867         rs = req->rq_reply_state;
1868         if (rs == NULL || !rs->rs_difficult) {
1869                 /* no notifiers */
1870                 target_send_reply_msg (req, rc, fail_id);
1871                 return;
1872         }
1873
1874         /* must be an export if locks saved */
1875         LASSERT (req->rq_export != NULL);
1876         /* req/reply consistent */
1877         LASSERT (rs->rs_service == svc);
1878
1879         /* "fresh" reply */
1880         LASSERT (!rs->rs_scheduled);
1881         LASSERT (!rs->rs_scheduled_ever);
1882         LASSERT (!rs->rs_handled);
1883         LASSERT (!rs->rs_on_net);
1884         LASSERT (rs->rs_export == NULL);
1885         LASSERT (list_empty(&rs->rs_obd_list));
1886         LASSERT (list_empty(&rs->rs_exp_list));
1887
1888         exp = class_export_get (req->rq_export);
1889         obd = exp->exp_obd;
1890
1891         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1892         rs->rs_scheduled = 1;
1893         rs->rs_on_net    = 1;
1894         rs->rs_xid       = req->rq_xid;
1895         rs->rs_transno   = req->rq_transno;
1896         rs->rs_export    = exp;
1897
1898         spin_lock(&obd->obd_uncommitted_replies_lock);
1899
1900         if (rs->rs_transno > obd->obd_last_committed) {
1901                 /* not committed already */
1902                 list_add_tail (&rs->rs_obd_list,
1903                                &obd->obd_uncommitted_replies);
1904         }
1905
1906         spin_unlock (&obd->obd_uncommitted_replies_lock);
1907         spin_lock (&exp->exp_lock);
1908
1909         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1910
1911         spin_unlock(&exp->exp_lock);
1912
1913         netrc = target_send_reply_msg (req, rc, fail_id);
1914
1915         spin_lock(&svc->srv_lock);
1916
1917         svc->srv_n_difficult_replies++;
1918
1919         if (netrc != 0) {
1920                 /* error sending: reply is off the net.  Also we need +1
1921                  * reply ref until ptlrpc_server_handle_reply() is done
1922                  * with the reply state (if the send was successful, there
1923                  * would have been +1 ref for the net, which
1924                  * reply_out_callback leaves alone) */
1925                 rs->rs_on_net = 0;
1926                 ptlrpc_rs_addref(rs);
1927                 atomic_inc (&svc->srv_outstanding_replies);
1928         }
1929
1930         if (!rs->rs_on_net ||                   /* some notifier */
1931             list_empty(&rs->rs_exp_list) ||     /* completed already */
1932             list_empty(&rs->rs_obd_list)) {
1933                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1934                 cfs_waitq_signal (&svc->srv_waitq);
1935         } else {
1936                 list_add (&rs->rs_list, &svc->srv_active_replies);
1937                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1938         }
1939
1940         spin_unlock(&svc->srv_lock);
1941 }
1942
1943 int target_handle_ping(struct ptlrpc_request *req)
1944 {
1945         obd_ping(req->rq_export);
1946         return lustre_pack_reply(req, 1, NULL, NULL);
1947 }
1948
1949 void target_committed_to_req(struct ptlrpc_request *req)
1950 {
1951         struct obd_device *obd;
1952
1953         if (req == NULL || req->rq_export == NULL)
1954                 return;
1955
1956         obd = req->rq_export->exp_obd;
1957         if (obd == NULL)
1958                 return;
1959
1960         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1961                 lustre_msg_set_last_committed(req->rq_repmsg,
1962                                               obd->obd_last_committed);
1963         else
1964                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update");
1965
1966         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
1967                obd->obd_last_committed, req->rq_transno, req->rq_xid);
1968 }
1969
1970 EXPORT_SYMBOL(target_committed_to_req);
1971
1972 #ifdef HAVE_QUOTA_SUPPORT
1973 int target_handle_qc_callback(struct ptlrpc_request *req)
1974 {
1975         struct obd_quotactl *oqctl;
1976         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
1977
1978         oqctl = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*oqctl),
1979                                    lustre_swab_obd_quotactl);
1980         if (oqctl == NULL) {
1981                 CERROR("Can't unpack obd_quotactl\n");
1982                 RETURN(-EPROTO);
1983         }
1984
1985         cli->cl_qchk_stat = oqctl->qc_stat;
1986
1987         return 0;
1988 }
1989
1990 int target_handle_dqacq_callback(struct ptlrpc_request *req)
1991 {
1992 #ifdef __KERNEL__
1993         struct obd_device *obd = req->rq_export->exp_obd;
1994         struct obd_device *master_obd;
1995         struct lustre_quota_ctxt *qctxt;
1996         struct qunit_data *qdata;
1997         void* rep;
1998         struct qunit_data_old *qdata_old;
1999         int rc = 0;
2000         int repsize[2] = { sizeof(struct ptlrpc_body),
2001                            sizeof(struct qunit_data) };
2002         ENTRY;
2003
2004         rc = lustre_pack_reply(req, 2, repsize, NULL);
2005         if (rc)
2006                 RETURN(rc);
2007
2008         LASSERT(req->rq_export);
2009
2010         /* fixed for bug10707 */
2011         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2012             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2013                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
2014                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
2015                                      sizeof(struct qunit_data));
2016                 LASSERT(rep);
2017                 qdata = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata),
2018                                            lustre_swab_qdata);
2019         } else {
2020                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
2021                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
2022                                      sizeof(struct qunit_data_old));
2023                 LASSERT(rep);
2024                 qdata_old = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata_old),
2025                                                lustre_swab_qdata_old);
2026                 qdata = lustre_quota_old_to_new(qdata_old);
2027         }
2028
2029         if (qdata == NULL) {
2030                 CERROR("Can't unpack qunit_data\n");
2031                 RETURN(-EPROTO);
2032         }
2033
2034         /* we use the observer */
2035         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
2036         master_obd = obd->obd_observer->obd_observer;
2037         qctxt = &master_obd->u.obt.obt_qctxt;
2038
2039         LASSERT(qctxt->lqc_handler);
2040         rc = qctxt->lqc_handler(master_obd, qdata,
2041                                 lustre_msg_get_opc(req->rq_reqmsg));
2042         if (rc && rc != -EDQUOT)
2043                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2044                        "dqacq failed! (rc:%d)\n", rc);
2045
2046         /* the qd_count might be changed in lqc_handler */
2047         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2048             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2049                 memcpy(rep,qdata,sizeof(*qdata));
2050         } else {
2051                 qdata_old = lustre_quota_new_to_old(qdata);
2052                 memcpy(rep,qdata_old,sizeof(*qdata_old));
2053         }
2054         req->rq_status = rc;
2055         rc = ptlrpc_reply(req);
2056
2057         RETURN(rc);
2058 #else
2059         return 0;
2060 #endif /* !__KERNEL__ */
2061 }
2062 #endif /* HAVE_QUOTA_SUPPORT */
2063
2064 ldlm_mode_t lck_compat_array[] = {
2065         [LCK_EX] LCK_COMPAT_EX,
2066         [LCK_PW] LCK_COMPAT_PW,
2067         [LCK_PR] LCK_COMPAT_PR,
2068         [LCK_CW] LCK_COMPAT_CW,
2069         [LCK_CR] LCK_COMPAT_CR,
2070         [LCK_NL] LCK_COMPAT_NL,
2071         [LCK_GROUP] LCK_COMPAT_GROUP
2072 };