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