Whamcloud - gitweb
bb2d2aa14a2ce3892f20bad9d0c2cb98bad5faff
[fs/lustre-release.git] / lustre / ldlm / ldlm_request.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (C) 2002, 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 #define DEBUG_SUBSYSTEM S_LDLM
26 #ifndef __KERNEL__
27 #include <signal.h>
28 #include <liblustre.h>
29 #endif
30
31 #include <lustre_dlm.h>
32 #include <obd_class.h>
33 #include <obd.h>
34
35 #include "ldlm_internal.h"
36
37 static void interrupted_completion_wait(void *data)
38 {
39 }
40
41 struct lock_wait_data {
42         struct ldlm_lock *lwd_lock;
43         __u32             lwd_conn_cnt;
44 };
45
46 int ldlm_expired_completion_wait(void *data)
47 {
48         struct lock_wait_data *lwd = data;
49         struct ldlm_lock *lock = lwd->lwd_lock;
50         struct obd_import *imp;
51         struct obd_device *obd;
52
53         ENTRY;
54         if (lock->l_conn_export == NULL) {
55                 static cfs_time_t next_dump = 0, last_dump = 0;
56
57                 LDLM_ERROR(lock, "lock timed out (enqueued at %lu, %lus ago); "
58                            "not entering recovery in server code, just going "
59                            "back to sleep", lock->l_enqueued_time.tv_sec,
60                            CURRENT_SECONDS - lock->l_enqueued_time.tv_sec);
61                 if (cfs_time_after(cfs_time_current(), next_dump)) {
62                         last_dump = next_dump;
63                         next_dump = cfs_time_shift(300);
64                         ldlm_namespace_dump(D_DLMTRACE,
65                                             lock->l_resource->lr_namespace);
66                         if (last_dump == 0)
67                                 libcfs_debug_dumplog();
68                 }
69                 RETURN(0);
70         }
71
72         obd = lock->l_conn_export->exp_obd;
73         imp = obd->u.cli.cl_import;
74         ptlrpc_fail_import(imp, lwd->lwd_conn_cnt);
75         LDLM_ERROR(lock, "lock timed out (enqueued at %lu, %lus ago), entering "
76                    "recovery for %s@%s", lock->l_enqueued_time.tv_sec,
77                    CURRENT_SECONDS - lock->l_enqueued_time.tv_sec,
78                    obd2cli_tgt(obd), imp->imp_connection->c_remote_uuid.uuid);
79
80         RETURN(0);
81 }
82
83 int ldlm_completion_ast(struct ldlm_lock *lock, int flags, void *data)
84 {
85         /* XXX ALLOCATE - 160 bytes */
86         struct lock_wait_data lwd;
87         struct obd_device *obd;
88         struct obd_import *imp = NULL;
89         struct l_wait_info lwi;
90         int rc = 0;
91         ENTRY;
92
93         if (flags == LDLM_FL_WAIT_NOREPROC) {
94                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
95                 goto noreproc;
96         }
97
98         if (!(flags & (LDLM_FL_BLOCK_WAIT | LDLM_FL_BLOCK_GRANTED |
99                        LDLM_FL_BLOCK_CONV))) {
100                 cfs_waitq_signal(&lock->l_waitq);
101                 RETURN(0);
102         }
103
104         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, "
105                    "sleeping");
106         ldlm_lock_dump(D_OTHER, lock, 0);
107         ldlm_reprocess_all(lock->l_resource);
108
109 noreproc:
110
111         obd = class_exp2obd(lock->l_conn_export);
112
113         /* if this is a local lock, then there is no import */
114         if (obd != NULL)
115                 imp = obd->u.cli.cl_import;
116
117         lwd.lwd_lock = lock;
118
119         if (lock->l_flags & LDLM_FL_NO_TIMEOUT) {
120                 LDLM_DEBUG(lock, "waiting indefinitely because of NO_TIMEOUT");
121                 lwi = LWI_INTR(interrupted_completion_wait, &lwd);
122         } else {
123                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(obd_timeout),
124                                        ldlm_expired_completion_wait,
125                                        interrupted_completion_wait, &lwd);
126         }
127
128         if (imp != NULL) {
129                 spin_lock(&imp->imp_lock);
130                 lwd.lwd_conn_cnt = imp->imp_conn_cnt;
131                 spin_unlock(&imp->imp_lock);
132         }
133
134         /* Go to sleep until the lock is granted or cancelled. */
135         rc = l_wait_event(lock->l_waitq,
136                           ((lock->l_req_mode == lock->l_granted_mode) ||
137                            (lock->l_flags & LDLM_FL_FAILED)), &lwi);
138
139         if (lock->l_destroyed || lock->l_flags & LDLM_FL_FAILED) {
140                 LDLM_DEBUG(lock, "client-side enqueue waking up: destroyed");
141                 RETURN(-EIO);
142         }
143
144         if (rc) {
145                 LDLM_DEBUG(lock, "client-side enqueue waking up: failed (%d)",
146                            rc);
147                 RETURN(rc);
148         }
149
150         LDLM_DEBUG(lock, "client-side enqueue waking up: granted");
151         RETURN(0);
152 }
153
154 /*
155  * ->l_blocking_ast() callback for LDLM locks acquired by server-side OBDs.
156  */
157 int ldlm_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
158                       void *data, int flag)
159 {
160         int do_ast;
161         ENTRY;
162
163         if (flag == LDLM_CB_CANCELING) {
164                 /* Don't need to do anything here. */
165                 RETURN(0);
166         }
167
168         lock_res_and_lock(lock);
169         /* Get this: if ldlm_blocking_ast is racing with intent_policy, such
170          * that ldlm_blocking_ast is called just before intent_policy method
171          * takes the ns_lock, then by the time we get the lock, we might not
172          * be the correct blocking function anymore.  So check, and return
173          * early, if so. */
174         if (lock->l_blocking_ast != ldlm_blocking_ast) {
175                 unlock_res_and_lock(lock);
176                 RETURN(0);
177         }
178
179         lock->l_flags |= LDLM_FL_CBPENDING;
180         do_ast = (!lock->l_readers && !lock->l_writers);
181         unlock_res_and_lock(lock);
182
183         if (do_ast) {
184                 struct lustre_handle lockh;
185                 int rc;
186
187                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
188                 ldlm_lock2handle(lock, &lockh);
189                 rc = ldlm_cli_cancel(&lockh);
190                 if (rc < 0)
191                         CERROR("ldlm_cli_cancel: %d\n", rc);
192         } else {
193                 LDLM_DEBUG(lock, "Lock still has references, will be "
194                            "cancelled later");
195         }
196         RETURN(0);
197 }
198
199 /*
200  * ->l_glimpse_ast() for DLM extent locks acquired on the server-side. See
201  * comment in filter_intent_policy() on why you may need this.
202  */
203 int ldlm_glimpse_ast(struct ldlm_lock *lock, void *reqp)
204 {
205         /*
206          * Returning -ELDLM_NO_LOCK_DATA actually works, but the reason for
207          * that is rather subtle: with OST-side locking, it may so happen that
208          * _all_ extent locks are held by the OST. If client wants to obtain
209          * current file size it calls ll{,u}_glimpse_size(), and (as locks are
210          * on the server), dummy glimpse callback fires and does
211          * nothing. Client still receives correct file size due to the
212          * following fragment in filter_intent_policy():
213          *
214          * rc = l->l_glimpse_ast(l, NULL); // this will update the LVB
215          * if (rc != 0 && res->lr_namespace->ns_lvbo &&
216          *     res->lr_namespace->ns_lvbo->lvbo_update) {
217          *         res->lr_namespace->ns_lvbo->lvbo_update(res, NULL, 0, 1);
218          * }
219          *
220          * that is, after glimpse_ast() fails, filter_lvbo_update() runs, and
221          * returns correct file size to the client.
222          */
223         return -ELDLM_NO_LOCK_DATA;
224 }
225
226 int ldlm_cli_enqueue_local(struct ldlm_namespace *ns, struct ldlm_res_id res_id,
227                            ldlm_type_t type, ldlm_policy_data_t *policy,
228                            ldlm_mode_t mode, int *flags,
229                            ldlm_blocking_callback blocking,
230                            ldlm_completion_callback completion,
231                            ldlm_glimpse_callback glimpse,
232                            void *data, __u32 lvb_len, void *lvb_swabber,
233                            struct lustre_handle *lockh)
234 {
235         struct ldlm_lock *lock;
236         int err;
237         ENTRY;
238
239         LASSERT(!(*flags & LDLM_FL_REPLAY));
240         if (ns->ns_client) {
241                 CERROR("Trying to enqueue local lock in a shadow namespace\n");
242                 LBUG();
243         }
244
245         lock = ldlm_lock_create(ns, res_id, type, mode, blocking,
246                                 completion, glimpse, data, lvb_len);
247         if (!lock)
248                 GOTO(out_nolock, err = -ENOMEM);
249         LDLM_DEBUG(lock, "client-side local enqueue handler, new lock created");
250
251         ldlm_lock_addref_internal(lock, mode);
252         ldlm_lock2handle(lock, lockh);
253         lock_res_and_lock(lock);
254         lock->l_flags |= LDLM_FL_LOCAL;
255         if (*flags & LDLM_FL_ATOMIC_CB)
256                 lock->l_flags |= LDLM_FL_ATOMIC_CB;
257         lock->l_lvb_swabber = lvb_swabber;
258         unlock_res_and_lock(lock);
259         if (policy != NULL)
260                 lock->l_policy_data = *policy;
261         if (type == LDLM_EXTENT)
262                 lock->l_req_extent = policy->l_extent;
263
264         err = ldlm_lock_enqueue(ns, &lock, policy, flags);
265         if (err != ELDLM_OK)
266                 GOTO(out, err);
267
268         if (policy != NULL)
269                 *policy = lock->l_policy_data;
270         if ((*flags) & LDLM_FL_LOCK_CHANGED)
271                 res_id = lock->l_resource->lr_name;
272
273         LDLM_DEBUG_NOLOCK("client-side local enqueue handler END (lock %p)",
274                           lock);
275
276         if (lock->l_completion_ast)
277                 lock->l_completion_ast(lock, *flags, NULL);
278
279         LDLM_DEBUG(lock, "client-side local enqueue END");
280         EXIT;
281  out:
282         LDLM_LOCK_PUT(lock);
283  out_nolock:
284         return err;
285 }
286
287 static void failed_lock_cleanup(struct ldlm_namespace *ns,
288                                 struct ldlm_lock *lock,
289                                 struct lustre_handle *lockh, int mode)
290 {
291         /* Set a flag to prevent us from sending a CANCEL (bug 407) */
292         lock_res_and_lock(lock);
293         lock->l_flags |= LDLM_FL_LOCAL_ONLY;
294         unlock_res_and_lock(lock);
295         LDLM_DEBUG(lock, "setting FL_LOCAL_ONLY");
296
297         ldlm_lock_decref_and_cancel(lockh, mode);
298
299         /* XXX - HACK because we shouldn't call ldlm_lock_destroy()
300          *       from llite/file.c/ll_file_flock(). */
301         if (lock->l_resource->lr_type == LDLM_FLOCK) {
302                 ldlm_lock_destroy(lock);
303         }
304 }
305
306 int ldlm_cli_enqueue_fini(struct obd_export *exp, struct ptlrpc_request *req,
307                           ldlm_type_t type, __u8 with_policy, ldlm_mode_t mode,
308                           int *flags, void *lvb, __u32 lvb_len,
309                           void *lvb_swabber, struct lustre_handle *lockh,int rc)
310 {
311         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
312         int is_replay = *flags & LDLM_FL_REPLAY;
313         struct ldlm_lock *lock;
314         struct ldlm_reply *reply;
315         int cleanup_phase = 1;
316         ENTRY;
317
318         lock = ldlm_handle2lock(lockh);
319         /* ldlm_cli_enqueue is holding a reference on this lock. */
320         if (!lock) {
321                 LASSERT(type == LDLM_FLOCK);
322                 RETURN(-ENOLCK);
323         }
324
325         if (rc != ELDLM_OK) {
326                 LASSERT(!is_replay);
327                 LDLM_DEBUG(lock, "client-side enqueue END (%s)",
328                            rc == ELDLM_LOCK_ABORTED ? "ABORTED" : "FAILED");
329                 if (rc == ELDLM_LOCK_ABORTED) {
330                         /* Before we return, swab the reply */
331                         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF,
332                                                    sizeof(*reply),
333                                                    lustre_swab_ldlm_reply);
334                         if (reply == NULL) {
335                                 CERROR("Can't unpack ldlm_reply\n");
336                                 rc = -EPROTO;
337                         }
338                         if (lvb_len) {
339                                 void *tmplvb;
340                                 tmplvb = lustre_swab_repbuf(req,
341                                                             DLM_REPLY_REC_OFF,
342                                                             lvb_len,
343                                                             lvb_swabber);
344                                 if (tmplvb == NULL)
345                                         GOTO(cleanup, rc = -EPROTO);
346                                 if (lvb != NULL)
347                                         memcpy(lvb, tmplvb, lvb_len);
348                         }
349                 }
350                 GOTO(cleanup, rc);
351         }
352
353         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
354                                    lustre_swab_ldlm_reply);
355         if (reply == NULL) {
356                 CERROR("Can't unpack ldlm_reply\n");
357                 GOTO(cleanup, rc = -EPROTO);
358         }
359
360         /* lock enqueued on the server */
361         cleanup_phase = 0;
362
363         lock_res_and_lock(lock);
364         lock->l_remote_handle = reply->lock_handle;
365         *flags = reply->lock_flags;
366         lock->l_flags |= reply->lock_flags & LDLM_INHERIT_FLAGS;
367         /* move NO_TIMEOUT flag to the lock to force ldlm_lock_match()
368          * to wait with no timeout as well */
369         lock->l_flags |= reply->lock_flags & LDLM_FL_NO_TIMEOUT;
370         unlock_res_and_lock(lock);
371
372         CDEBUG(D_INFO, "local: %p, remote cookie: "LPX64", flags: 0x%x\n",
373                lock, reply->lock_handle.cookie, *flags);
374
375         /* If enqueue returned a blocked lock but the completion handler has
376          * already run, then it fixed up the resource and we don't need to do it
377          * again. */
378         if ((*flags) & LDLM_FL_LOCK_CHANGED) {
379                 int newmode = reply->lock_desc.l_req_mode;
380                 LASSERT(!is_replay);
381                 if (newmode && newmode != lock->l_req_mode) {
382                         LDLM_DEBUG(lock, "server returned different mode %s",
383                                    ldlm_lockname[newmode]);
384                         lock->l_req_mode = newmode;
385                 }
386
387                 if (reply->lock_desc.l_resource.lr_name.name[0] !=
388                     lock->l_resource->lr_name.name[0]) {
389                         CDEBUG(D_INFO, "remote intent success, locking %ld "
390                                "instead of %ld\n",
391                               (long)reply->lock_desc.l_resource.lr_name.name[0],
392                                (long)lock->l_resource->lr_name.name[0]);
393
394                         ldlm_lock_change_resource(ns, lock,
395                                            reply->lock_desc.l_resource.lr_name);
396                         if (lock->l_resource == NULL) {
397                                 LBUG();
398                                 GOTO(cleanup, rc = -ENOMEM);
399                         }
400                         LDLM_DEBUG(lock, "client-side enqueue, new resource");
401                 }
402                 if (with_policy)
403                         if (!(type == LDLM_IBITS && !(exp->exp_connect_flags &
404                                                     OBD_CONNECT_IBITS)))
405                                 lock->l_policy_data =
406                                                  reply->lock_desc.l_policy_data;
407                 if (type != LDLM_PLAIN)
408                         LDLM_DEBUG(lock,"client-side enqueue, new policy data");
409         }
410
411         if ((*flags) & LDLM_FL_AST_SENT ||
412             /* Cancel extent locks as soon as possible on a liblustre client,
413              * because it cannot handle asynchronous ASTs robustly (see
414              * bug 7311). */
415             (LIBLUSTRE_CLIENT && type == LDLM_EXTENT)) {
416                 lock_res_and_lock(lock);
417                 lock->l_flags |= LDLM_FL_CBPENDING;
418                 unlock_res_and_lock(lock);
419                 LDLM_DEBUG(lock, "enqueue reply includes blocking AST");
420         }
421
422         /* If the lock has already been granted by a completion AST, don't
423          * clobber the LVB with an older one. */
424         if (lvb_len && (lock->l_req_mode != lock->l_granted_mode)) {
425                 void *tmplvb;
426                 tmplvb = lustre_swab_repbuf(req, DLM_REPLY_REC_OFF, lvb_len,
427                                             lvb_swabber);
428                 if (tmplvb == NULL)
429                         GOTO(cleanup, rc = -EPROTO);
430                 memcpy(lock->l_lvb_data, tmplvb, lvb_len);
431         }
432
433         if (!is_replay) {
434                 rc = ldlm_lock_enqueue(ns, &lock, NULL, flags);
435                 if (lock->l_completion_ast != NULL) {
436                         int err = lock->l_completion_ast(lock, *flags, NULL);
437                         if (!rc)
438                                 rc = err;
439                         if (rc && type != LDLM_FLOCK) /* bug 9425, bug 10250 */
440                                 cleanup_phase = 1;
441                 }
442         }
443
444         if (lvb_len && lvb != NULL) {
445                 /* Copy the LVB here, and not earlier, because the completion
446                  * AST (if any) can override what we got in the reply */
447                 memcpy(lvb, lock->l_lvb_data, lvb_len);
448         }
449
450         LDLM_DEBUG(lock, "client-side enqueue END");
451         EXIT;
452 cleanup:
453         if (cleanup_phase == 1 && rc)
454                 failed_lock_cleanup(ns, lock, lockh, mode);
455         /* Put lock 2 times, the second reference is held by ldlm_cli_enqueue */
456         LDLM_LOCK_PUT(lock);
457         LDLM_LOCK_PUT(lock);
458         return rc;
459 }
460
461 /* PAGE_SIZE-512 is to allow TCP/IP and LNET headers to fit into
462  * a single page on the send/receive side. XXX: 512 should be changed
463  * to more adequate value. */
464 #define ldlm_req_handles_avail(exp, size, bufcount, off)                \
465 ({                                                                      \
466         int _avail = min_t(int, LDLM_MAXREQSIZE, PAGE_SIZE - 512);      \
467         int _s = size[DLM_LOCKREQ_OFF];                                 \
468         size[DLM_LOCKREQ_OFF] = sizeof(struct ldlm_request);            \
469         _avail -= lustre_msg_size(class_exp2cliimp(exp)->imp_msg_magic, \
470                                   bufcount, size);                      \
471         _avail /= sizeof(struct lustre_handle);                         \
472         _avail += LDLM_LOCKREQ_HANDLES - off;                           \
473         size[DLM_LOCKREQ_OFF] = _s;                                     \
474         _avail;                                                         \
475 })
476
477 /* Cancel lru locks and pack them into the enqueue request. Pack there the given
478  * @count locks in @cancels. */
479 struct ptlrpc_request *ldlm_prep_enqueue_req(struct obd_export *exp,
480                                              int bufcount, int *size,
481                                              struct list_head *cancels,
482                                              int count)
483 {
484         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
485         struct ldlm_request *dlm = NULL;
486         struct ptlrpc_request *req;
487         CFS_LIST_HEAD(head);
488         ENTRY;
489         
490         if (cancels == NULL)
491                 cancels = &head;
492         if (exp_connect_cancelset(exp)) {
493                 /* Estimate the amount of free space in the request. */
494                 int avail = ldlm_req_handles_avail(exp, size, bufcount,
495                                                    LDLM_ENQUEUE_CANCEL_OFF);
496                 LASSERT(avail >= count);
497
498                 /* Cancel lru locks here _only_ if the server supports 
499                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
500                  * rpc right on enqueue, what will make it slower, vs. 
501                  * asynchronous rpc in blocking thread. */
502                 count += ldlm_cancel_lru_local(ns, cancels, 1, avail - count,
503                                                LDLM_CANCEL_AGED);
504                 size[DLM_LOCKREQ_OFF] =
505                         ldlm_request_bufsize(count, LDLM_ENQUEUE);
506         }
507         req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_DLM_VERSION,
508                               LDLM_ENQUEUE, bufcount, size, NULL);
509         if (exp_connect_cancelset(exp) && req) {
510                 dlm = lustre_msg_buf(req->rq_reqmsg,
511                                      DLM_LOCKREQ_OFF, sizeof(*dlm));
512                 /* Skip first lock handler in ldlm_request_pack(), this method
513                  * will incrment @lock_count according to the lock handle amount
514                  * actually written to the buffer. */
515                 dlm->lock_count = LDLM_ENQUEUE_CANCEL_OFF;
516                 ldlm_cli_cancel_list(cancels, count, req, DLM_LOCKREQ_OFF);
517         } else {
518                 ldlm_lock_list_put(cancels, l_bl_ast, count);
519         }
520         RETURN(req);
521 }
522
523 /* If a request has some specific initialisation it is passed in @reqp,
524  * otherwise it is created in ldlm_cli_enqueue.
525  *
526  * Supports sync and async requests, pass @async flag accordingly. If a
527  * request was created in ldlm_cli_enqueue and it is the async request,
528  * pass it to the caller in @reqp. */
529 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
530                      struct ldlm_enqueue_info *einfo, struct ldlm_res_id res_id,
531                      ldlm_policy_data_t *policy, int *flags,
532                      void *lvb, __u32 lvb_len, void *lvb_swabber,
533                      struct lustre_handle *lockh, int async)
534 {
535         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
536         struct ldlm_lock *lock;
537         struct ldlm_request *body;
538         struct ldlm_reply *reply;
539         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
540                         [DLM_LOCKREQ_OFF]     = sizeof(*body),
541                         [DLM_REPLY_REC_OFF]   = lvb_len };
542         int is_replay = *flags & LDLM_FL_REPLAY;
543         int req_passed_in = 1, rc, err;
544         struct ptlrpc_request *req;
545         ENTRY;
546
547         LASSERT(exp != NULL);
548
549         /* If we're replaying this lock, just check some invariants.
550          * If we're creating a new lock, get everything all setup nice. */
551         if (is_replay) {
552                 lock = ldlm_handle2lock(lockh);
553                 LASSERT(lock != NULL);
554                 LDLM_DEBUG(lock, "client-side enqueue START");
555                 LASSERT(exp == lock->l_conn_export);
556         } else {
557                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
558                                         einfo->ei_mode, einfo->ei_cb_bl,
559                                         einfo->ei_cb_cp, einfo->ei_cb_gl,
560                                         einfo->ei_cbdata, lvb_len);
561                 if (lock == NULL)
562                         RETURN(-ENOMEM);
563                 /* for the local lock, add the reference */
564                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
565                 ldlm_lock2handle(lock, lockh);
566                 lock->l_lvb_swabber = lvb_swabber;
567                 if (policy != NULL) {
568                         /* INODEBITS_INTEROP: If the server does not support
569                          * inodebits, we will request a plain lock in the
570                          * descriptor (ldlm_lock2desc() below) but use an
571                          * inodebits lock internally with both bits set.
572                          */
573                         if (einfo->ei_type == LDLM_IBITS &&
574                             !(exp->exp_connect_flags & OBD_CONNECT_IBITS))
575                                 lock->l_policy_data.l_inodebits.bits =
576                                         MDS_INODELOCK_LOOKUP |
577                                         MDS_INODELOCK_UPDATE;
578                         else
579                                 lock->l_policy_data = *policy;
580                 }
581
582                 if (einfo->ei_type == LDLM_EXTENT)
583                         lock->l_req_extent = policy->l_extent;
584                 LDLM_DEBUG(lock, "client-side enqueue START");
585         }
586
587         /* lock not sent to server yet */
588
589         if (reqp == NULL || *reqp == NULL) {
590                 req = ldlm_prep_enqueue_req(exp, 2, size, NULL, 0);
591                 if (req == NULL) {
592                         failed_lock_cleanup(ns, lock, lockh, einfo->ei_mode);
593                         LDLM_LOCK_PUT(lock);
594                         RETURN(-ENOMEM);
595                 }
596                 req_passed_in = 0;
597                 if (reqp)
598                         *reqp = req;
599         } else {
600                 req = *reqp;
601                 LASSERTF(lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF) >=
602                          sizeof(*body), "buflen[%d] = %d, not "LPSZ"\n",
603                          DLM_LOCKREQ_OFF,
604                          lustre_msg_buflen(req->rq_reqmsg, DLM_LOCKREQ_OFF),
605                          sizeof(*body));
606         }
607
608         lock->l_conn_export = exp;
609         lock->l_export = NULL;
610         lock->l_blocking_ast = einfo->ei_cb_bl;
611
612         /* Dump lock data into the request buffer */
613         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
614         ldlm_lock2desc(lock, &body->lock_desc);
615         body->lock_flags = *flags;
616         body->lock_handle[0] = *lockh;
617
618         /* Continue as normal. */
619         if (!req_passed_in) {
620                 size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
621                 ptlrpc_req_set_repsize(req, 2 + (lvb_len > 0), size);
622         }
623
624         /*
625          * Liblustre client doesn't get extent locks, except for O_APPEND case
626          * where [0, OBD_OBJECT_EOF] lock is taken, or truncate, where
627          * [i_size, OBD_OBJECT_EOF] lock is taken.
628          */
629         LASSERT(ergo(LIBLUSTRE_CLIENT, einfo->ei_type != LDLM_EXTENT ||
630                      policy->l_extent.end == OBD_OBJECT_EOF));
631
632         if (async) {
633                 LASSERT(reqp != NULL);
634                 RETURN(0);
635         }
636
637         LDLM_DEBUG(lock, "sending request");
638         rc = ptlrpc_queue_wait(req);
639         err = ldlm_cli_enqueue_fini(exp, req, einfo->ei_type, policy ? 1 : 0,
640                                     einfo->ei_mode, flags, lvb, lvb_len,
641                                     lvb_swabber, lockh, rc);
642
643         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
644          * one reference that we took */
645         if (err == -ENOLCK)
646                 LDLM_LOCK_PUT(lock);
647         else
648                 rc = err;
649
650         if (!req_passed_in && req != NULL) {
651                 ptlrpc_req_finished(req);
652                 if (reqp)
653                         *reqp = NULL;
654         }
655
656         RETURN(rc);
657 }
658
659 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
660                                   int *flags)
661 {
662         struct ldlm_resource *res;
663         int rc;
664         ENTRY;
665         if (lock->l_resource->lr_namespace->ns_client) {
666                 CERROR("Trying to cancel local lock\n");
667                 LBUG();
668         }
669         LDLM_DEBUG(lock, "client-side local convert");
670
671         res = ldlm_lock_convert(lock, new_mode, flags);
672         if (res) {
673                 ldlm_reprocess_all(res);
674                 rc = 0;
675         } else {
676                 rc = EDEADLOCK;
677         }
678         LDLM_DEBUG(lock, "client-side local convert handler END");
679         LDLM_LOCK_PUT(lock);
680         RETURN(rc);
681 }
682
683 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
684  * conversion of locks which are on the waiting or converting queue */
685 /* Caller of this code is supposed to take care of lock readers/writers
686    accounting */
687 int ldlm_cli_convert(struct lustre_handle *lockh, int new_mode, int *flags)
688 {
689         struct ldlm_request *body;
690         struct ldlm_reply *reply;
691         struct ldlm_lock *lock;
692         struct ldlm_resource *res;
693         struct ptlrpc_request *req;
694         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
695                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
696         int rc;
697         ENTRY;
698
699         lock = ldlm_handle2lock(lockh);
700         if (!lock) {
701                 LBUG();
702                 RETURN(-EINVAL);
703         }
704         *flags = 0;
705
706         if (lock->l_conn_export == NULL)
707                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
708
709         LDLM_DEBUG(lock, "client-side convert");
710
711         req = ptlrpc_prep_req(class_exp2cliimp(lock->l_conn_export),
712                               LUSTRE_DLM_VERSION, LDLM_CONVERT, 2, size, NULL);
713         if (!req)
714                 GOTO(out, rc = -ENOMEM);
715
716         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
717         body->lock_handle[0] = lock->l_remote_handle;
718
719         body->lock_desc.l_req_mode = new_mode;
720         body->lock_flags = *flags;
721
722         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
723         ptlrpc_req_set_repsize(req, 2, size);
724
725         rc = ptlrpc_queue_wait(req);
726         if (rc != ELDLM_OK)
727                 GOTO(out, rc);
728
729         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
730                                    lustre_swab_ldlm_reply);
731         if (reply == NULL) {
732                 CERROR ("Can't unpack ldlm_reply\n");
733                 GOTO (out, rc = -EPROTO);
734         }
735
736         if (req->rq_status)
737                 GOTO(out, rc = req->rq_status);
738
739         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
740         if (res != NULL) {
741                 ldlm_reprocess_all(res);
742                 /* Go to sleep until the lock is granted. */
743                 /* FIXME: or cancelled. */
744                 if (lock->l_completion_ast) {
745                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
746                                                     NULL);
747                         if (rc)
748                                 GOTO(out, rc);
749                 }
750         } else {
751                 rc = EDEADLOCK;
752         }
753         EXIT;
754  out:
755         LDLM_LOCK_PUT(lock);
756         ptlrpc_req_finished(req);
757         return rc;
758 }
759
760 /* Cancel locks locally.
761  * Returns:
762  * LDLM_FL_LOCAL_ONLY if tere is no need in a CANCEL rpc to the server;
763  * LDLM_FL_CANCELING otherwise;
764  * LDLM_FL_BL_AST if there is a need in a separate CANCEL rpc. */
765 static int ldlm_cli_cancel_local(struct ldlm_lock *lock)
766 {
767         int rc = LDLM_FL_LOCAL_ONLY;
768         ENTRY;
769         
770         if (lock->l_conn_export) {
771                 int local_only;
772
773                 LDLM_DEBUG(lock, "client-side cancel");
774                 /* Set this flag to prevent others from getting new references*/
775                 lock_res_and_lock(lock);
776                 lock->l_flags |= LDLM_FL_CBPENDING;
777                 local_only = (lock->l_flags &
778                               (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
779                 ldlm_cancel_callback(lock);
780                 rc = (lock->l_flags & LDLM_FL_BL_AST) ?
781                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
782                 unlock_res_and_lock(lock);
783
784                 if (local_only) {
785                         CDEBUG(D_DLMTRACE, "not sending request (at caller's "
786                                "instruction)\n");
787                         rc = LDLM_FL_LOCAL_ONLY;
788                 }
789                 ldlm_lock_cancel(lock);
790         } else {
791                 if (lock->l_resource->lr_namespace->ns_client) {
792                         LDLM_ERROR(lock, "Trying to cancel local lock");
793                         LBUG();
794                 }
795                 LDLM_DEBUG(lock, "server-side local cancel");
796                 ldlm_lock_cancel(lock);
797                 ldlm_reprocess_all(lock->l_resource);
798                 LDLM_DEBUG(lock, "server-side local cancel handler END");
799         }
800
801         RETURN(rc);
802 }
803
804 /* Pack @count locks in @head into ldlm_request buffer at the offset @off,
805    of the request @req. */
806 static void ldlm_cancel_pack(struct ptlrpc_request *req, int off,
807                              struct list_head *head, int count)
808 {
809         struct ldlm_request *dlm;
810         struct ldlm_lock *lock;
811         int max, packed = 0;
812         ENTRY;
813
814         dlm = lustre_msg_buf(req->rq_reqmsg, off, sizeof(*dlm));
815         LASSERT(dlm != NULL);
816
817         /* Check the room in the request buffer. */
818         max = lustre_msg_buflen(req->rq_reqmsg, off) - 
819                 sizeof(struct ldlm_request);
820         max /= sizeof(struct lustre_handle);
821         max += LDLM_LOCKREQ_HANDLES;
822         LASSERT(max >= dlm->lock_count + count);
823
824         /* XXX: it would be better to pack lock handles grouped by resource.
825          * so that the server cancel would call filter_lvbo_update() less
826          * frequently. */
827         list_for_each_entry(lock, head, l_bl_ast) {
828                 if (!count--)
829                         break;
830                 LASSERT(lock->l_conn_export);
831                 /* Pack the lock handle to the given request buffer. */
832                 LDLM_DEBUG(lock, "packing");
833                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
834                 packed++;
835         }
836         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
837         EXIT;
838 }
839
840 /* Prepare and send a batched cancel rpc, it will include count lock handles
841  * of locks given in @head. */
842 int ldlm_cli_cancel_req(struct obd_export *exp,
843                         struct list_head *cancels, int count)
844 {
845         struct ptlrpc_request *req = NULL;
846         struct ldlm_request *body;
847         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
848                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
849         struct obd_import *imp;
850         int free, sent = 0;
851         int rc = 0;
852         ENTRY;
853
854         LASSERT(exp != NULL);
855         LASSERT(count > 0);
856
857         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
858                 RETURN(count);
859
860         free = ldlm_req_handles_avail(exp, size, 2, 0);
861         if (count > free)
862                 count = free;
863         
864         size[DLM_LOCKREQ_OFF] = ldlm_request_bufsize(count, LDLM_CANCEL);
865         while (1) {
866                 imp = class_exp2cliimp(exp);
867                 if (imp == NULL || imp->imp_invalid) {
868                         CDEBUG(D_DLMTRACE,
869                                "skipping cancel on invalid import %p\n", imp);
870                         break;
871                 }
872
873                 req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_CANCEL, 2,
874                                       size, NULL);
875                 if (!req)
876                         GOTO(out, rc = -ENOMEM);
877
878                 req->rq_no_resend = 1;
879
880                 /* XXX FIXME bug 249 */
881                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
882                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
883
884                 body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF,
885                                       sizeof(*body));
886                 ldlm_cancel_pack(req, DLM_LOCKREQ_OFF, cancels, count);
887
888                 ptlrpc_req_set_repsize(req, 1, NULL);
889                 rc = ptlrpc_queue_wait(req);
890
891                 if (rc == ESTALE) {
892                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
893                                "out of sync -- not fatal\n",
894                                libcfs_nid2str(req->rq_import->
895                                               imp_connection->c_peer.nid));
896                 } else if (rc == -ETIMEDOUT) {
897                         ptlrpc_req_finished(req);
898                         continue;
899                 } else if (rc != ELDLM_OK) {
900                         CERROR("Got rc %d from cancel RPC: canceling "
901                                "anyway\n", rc);
902                         break;
903                 }
904                 sent = count;
905                 break;
906         }
907         
908         ptlrpc_req_finished(req);
909         EXIT;
910 out:
911         return sent ? sent : rc;
912 }
913
914 int ldlm_cli_cancel(struct lustre_handle *lockh)
915 {
916         struct ldlm_lock *lock;
917         CFS_LIST_HEAD(head);
918         int rc = 0;
919         ENTRY;
920
921         /* concurrent cancels on the same handle can happen */
922         lock = __ldlm_handle2lock(lockh, LDLM_FL_CANCELING);
923         if (lock == NULL) {
924                 LDLM_DEBUG_NOLOCK("lock is already being destroyed\n");
925                 RETURN(0);
926         }
927         
928         rc = ldlm_cli_cancel_local(lock);
929         if (rc < 0 || rc == LDLM_FL_LOCAL_ONLY)
930                 GOTO(out, rc);
931
932         list_add(&lock->l_bl_ast, &head);
933         rc = ldlm_cli_cancel_req(lock->l_conn_export, &head, 1);
934         EXIT;
935  out:
936         LDLM_LOCK_PUT(lock);
937         return rc < 0 ? rc : 0;
938 }
939
940 /* - Free space in lru for @count new locks,
941  *   redundant unused locks are canceled locally;
942  * - also cancel locally unused aged locks;
943  * - do not cancel more than @max locks;
944  * - GET the found locks and add them into the @cancels list.
945  *
946  * A client lock can be added to the l_bl_ast list only when it is
947  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
948  * There are the following use cases: ldlm_cancel_resource_local(),
949  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
950  * flag properly. As any attempt to cancel a lock rely on this flag,
951  * l_bl_ast list is accessed later without any special locking. */
952 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
953                           int count, int max, int flags)
954 {
955         cfs_time_t cur = cfs_time_current();
956         struct ldlm_lock *lock, *next;
957         int rc, added = 0, left;
958         ENTRY;
959
960         spin_lock(&ns->ns_unused_lock);
961         count += ns->ns_nr_unused - ns->ns_max_unused;
962         while (!list_empty(&ns->ns_unused_list)) {
963                 if (max && added >= max)
964                         break;
965
966                 list_for_each_entry(lock, &ns->ns_unused_list, l_lru) {
967                         /* somebody is already doing CANCEL or there is a
968                          * blocking request will send cancel. */
969                         if (!(lock->l_flags & LDLM_FL_CANCELING) &&
970                             !(lock->l_flags & LDLM_FL_BL_AST))
971                                 break;
972                 }
973                 if (&lock->l_lru == &ns->ns_unused_list)
974                         break;
975
976                 if ((added >= count) && 
977                     (!(flags & LDLM_CANCEL_AGED) ||
978                      cfs_time_before_64(cur, (__u64)ns->ns_max_age +
979                                         lock->l_last_used)))
980                         break;
981
982                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
983                 spin_unlock(&ns->ns_unused_lock);
984
985                 lock_res_and_lock(lock);
986                 /* Check flags again under the lock. */
987                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
988                     (lock->l_flags & LDLM_FL_BL_AST) ||
989                     (ldlm_lock_remove_from_lru(lock) == 0)) {
990                         /* other thread is removing lock from lru or
991                          * somebody is already doing CANCEL or
992                          * there is a blocking request which will send
993                          * cancel by itseft. */
994                         unlock_res_and_lock(lock);
995                         LDLM_LOCK_PUT(lock);
996                         spin_lock(&ns->ns_unused_lock);
997                         continue;
998                 }
999                 LASSERT(!lock->l_readers && !lock->l_writers);
1000
1001                 /* If we have chosen to canecl this lock voluntarily, we better
1002                    send cancel notification to server, so that it frees
1003                    appropriate state. This might lead to a race where while
1004                    we are doing cancel here, server is also silently
1005                    cancelling this lock. */
1006                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1007
1008                 /* Setting the CBPENDING flag is a little misleading, but
1009                  * prevents an important race; namely, once CBPENDING is set,
1010                  * the lock can accumulate no more readers/writers.  Since
1011                  * readers and writers are already zero here, ldlm_lock_decref
1012                  * won't see this flag and call l_blocking_ast */
1013                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1014                 /* We can't re-add to l_lru as it confuses the refcounting in
1015                  * ldlm_lock_remove_from_lru() if an AST arrives after we drop
1016                  * ns_lock below. We use l_bl_ast and can't use l_pending_chain
1017                  * as it is used both on server and client nevertheles bug 5666
1018                  * says it is used only on server. --umka */
1019
1020                 LASSERT(list_empty(&lock->l_bl_ast));
1021                 list_add(&lock->l_bl_ast, cancels);
1022                 unlock_res_and_lock(lock);
1023                 spin_lock(&ns->ns_unused_lock);
1024                 added++;
1025         }
1026         spin_unlock(&ns->ns_unused_lock);
1027
1028         /* Handle only @added inserted locks. */
1029         left = added;
1030         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1031                 if (left-- == 0)
1032                         break;
1033
1034                 rc = ldlm_cli_cancel_local(lock);
1035                 if (rc == LDLM_FL_BL_AST) {
1036                         CFS_LIST_HEAD(head);
1037
1038                         LDLM_DEBUG(lock, "Cancel lock separately");
1039                         list_del_init(&lock->l_bl_ast);
1040                         list_add(&lock->l_bl_ast, &head);
1041                         ldlm_cli_cancel_req(lock->l_conn_export, &head, 1);
1042                         rc = LDLM_FL_LOCAL_ONLY;
1043                 }
1044                 if (rc == LDLM_FL_LOCAL_ONLY) {
1045                         /* CANCEL RPC should not be sent to server. */
1046                         list_del_init(&lock->l_bl_ast);
1047                         LDLM_LOCK_PUT(lock);
1048                         added--;
1049                 }
1050
1051         } 
1052         RETURN(added);
1053 }
1054
1055 /* when called with LDLM_ASYNC the blocking callback will be handled
1056  * in a thread and this function will return after the thread has been
1057  * asked to call the callback.  when called with LDLM_SYNC the blocking
1058  * callback will be performed in this function. */
1059 int ldlm_cancel_lru(struct ldlm_namespace *ns, ldlm_sync_t sync)
1060 {
1061         CFS_LIST_HEAD(cancels);
1062         int count, rc;
1063         ENTRY;
1064
1065 #ifndef __KERNEL__
1066         sync = LDLM_SYNC; /* force to be sync in user space */
1067 #endif
1068         count = ldlm_cancel_lru_local(ns, &cancels, 0, 0, 0);
1069         if (sync == LDLM_ASYNC) {
1070                 struct ldlm_lock *lock, *next;
1071                 list_for_each_entry_safe(lock, next, &cancels, l_bl_ast) {
1072                         /* Remove from the list to allow blocking thread to
1073                          * re-use l_bl_ast. */
1074                         list_del_init(&lock->l_bl_ast);
1075                         rc = ldlm_bl_to_thread(ns, NULL, lock,
1076                                                LDLM_FL_CANCELING);
1077                         if (rc)
1078                                 list_add_tail(&lock->l_bl_ast, &next->l_bl_ast);
1079                 }
1080         }
1081
1082         /* If some locks are left in the list in ASYNC mode, or
1083          * this is SYNC mode, cancel the list. */
1084         ldlm_cli_cancel_list(&cancels, count, NULL, DLM_LOCKREQ_OFF);
1085         RETURN(0);
1086 }
1087
1088 /* Find and cancel locally unused locks found on resource, matched to the
1089  * given policy, mode. GET the found locks and add them into the @cancels
1090  * list. */
1091 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1092                                struct list_head *cancels,
1093                                ldlm_policy_data_t *policy,
1094                                ldlm_mode_t mode, int lock_flags,
1095                                int flags, void *opaque)
1096 {
1097         struct ldlm_lock *lock, *next;
1098         int count = 0, left;
1099         ENTRY;
1100
1101         lock_res(res);
1102         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1103                 if (opaque != NULL && lock->l_ast_data != opaque) {
1104                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1105                                    lock->l_ast_data, opaque);
1106                         //LBUG();
1107                         continue;
1108                 }
1109
1110                 if (lock->l_readers || lock->l_writers) {
1111                         if (flags & LDLM_FL_WARN) {
1112                                 LDLM_ERROR(lock, "lock in use");
1113                                 //LBUG();
1114                         }
1115                         continue;
1116                 }
1117
1118                 /* If somebody is already doing CANCEL, or blocking ast came,
1119                  * skip this lock. */
1120                 if (lock->l_flags & LDLM_FL_BL_AST || 
1121                     lock->l_flags & LDLM_FL_CANCELING)
1122                         continue;
1123
1124                 if (lockmode_compat(lock->l_granted_mode, mode))
1125                         continue;
1126
1127                 /* If policy is given and this is IBITS lock, add to list only
1128                  * those locks that match by policy. */
1129                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1130                     !(lock->l_policy_data.l_inodebits.bits &
1131                       policy->l_inodebits.bits))
1132                         continue;
1133
1134                 /* See CBPENDING comment in ldlm_cancel_lru */
1135                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1136                         lock_flags;
1137
1138                 LASSERT(list_empty(&lock->l_bl_ast));
1139                 list_add(&lock->l_bl_ast, cancels);
1140                 LDLM_LOCK_GET(lock);
1141                 count++;
1142         }
1143         unlock_res(res);
1144
1145         /* Handle only @count inserted locks. */
1146         left = count;
1147         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1148                 int rc = LDLM_FL_LOCAL_ONLY;
1149
1150                 if (left-- == 0)
1151                         break;
1152                 if (flags & LDLM_FL_LOCAL_ONLY)
1153                         ldlm_lock_cancel(lock);
1154                 else
1155                         rc = ldlm_cli_cancel_local(lock);
1156
1157                 if (rc == LDLM_FL_BL_AST) {
1158                         CFS_LIST_HEAD(head);
1159
1160                         LDLM_DEBUG(lock, "Cancel lock separately");
1161                         list_del_init(&lock->l_bl_ast);
1162                         list_add(&lock->l_bl_ast, &head);
1163                         ldlm_cli_cancel_req(lock->l_conn_export, &head, 1);
1164                         rc = LDLM_FL_LOCAL_ONLY;
1165                 }
1166                 if (rc == LDLM_FL_LOCAL_ONLY) {
1167                         /* CANCEL RPC should not be sent to server. */
1168                         list_del_init(&lock->l_bl_ast);
1169                         LDLM_LOCK_PUT(lock);
1170                         count--;
1171                 }
1172         }
1173         RETURN(count);
1174 }
1175
1176 /* If @req is NULL, send CANCEL request to server with handles of locks 
1177  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests 
1178  * separately per lock.
1179  * If @req is not NULL, put handles of locks in @cancels into the request 
1180  * buffer at the offset @off.
1181  * Destroy @cancels at the end. */
1182 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1183                          struct ptlrpc_request *req, int off)
1184 {
1185         struct ldlm_lock *lock;
1186         int res = 0;
1187         ENTRY;
1188
1189         if (list_empty(cancels) || count == 0)
1190                 RETURN(0);
1191         
1192         while (count) {
1193                 LASSERT(!list_empty(cancels));
1194                 lock = list_entry(cancels->next, struct ldlm_lock, l_bl_ast);
1195                 LASSERT(lock->l_conn_export);
1196
1197                 if (exp_connect_cancelset(lock->l_conn_export)) {
1198                         res = count;
1199                         if (req)
1200                                 ldlm_cancel_pack(req, off, cancels, count);
1201                         else
1202                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1203                                                           cancels, count);
1204                 } else {
1205                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1206                                                   cancels, 1);
1207                 }
1208
1209                 if (res < 0) {
1210                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1211                         res = count;
1212                 }
1213                 
1214                 count -= res;
1215                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1216         }
1217         LASSERT(list_empty(cancels));
1218         RETURN(0);
1219 }
1220
1221 static int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1222                                            struct ldlm_res_id res_id,
1223                                            int flags, void *opaque)
1224 {
1225         struct ldlm_resource *res;
1226         CFS_LIST_HEAD(cancels);
1227         int count;
1228         int rc;
1229         ENTRY;
1230
1231         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1232         if (res == NULL) {
1233                 /* This is not a problem. */
1234                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id.name[0]);
1235                 RETURN(0);
1236         }
1237
1238         count = ldlm_cancel_resource_local(res, &cancels, NULL, LCK_MINMODE,
1239                                            0, flags, opaque);
1240         rc = ldlm_cli_cancel_list(&cancels, count, NULL, DLM_LOCKREQ_OFF);
1241         if (rc != ELDLM_OK)
1242                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1243
1244         ldlm_resource_putref(res);
1245         RETURN(0);
1246 }
1247
1248 static inline int have_no_nsresource(struct ldlm_namespace *ns)
1249 {
1250         int no_resource = 0;
1251
1252         spin_lock(&ns->ns_hash_lock);
1253         if (ns->ns_resources == 0)
1254                 no_resource = 1;
1255         spin_unlock(&ns->ns_hash_lock);
1256
1257         RETURN(no_resource);
1258 }
1259
1260 /* Cancel all locks on a namespace (or a specific resource, if given)
1261  * that have 0 readers/writers.
1262  *
1263  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
1264  * to notify the server. */
1265 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1266                            struct ldlm_res_id *res_id, int flags, void *opaque)
1267 {
1268         int i;
1269         ENTRY;
1270
1271         if (ns == NULL)
1272                 RETURN(ELDLM_OK);
1273
1274         if (res_id)
1275                 RETURN(ldlm_cli_cancel_unused_resource(ns, *res_id, flags,
1276                                                        opaque));
1277
1278         spin_lock(&ns->ns_hash_lock);
1279         for (i = 0; i < RES_HASH_SIZE; i++) {
1280                 struct list_head *tmp;
1281                 tmp = ns->ns_hash[i].next;
1282                 while (tmp != &(ns->ns_hash[i])) {
1283                         struct ldlm_resource *res;
1284                         int rc;
1285
1286                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1287                         ldlm_resource_getref(res);
1288                         spin_unlock(&ns->ns_hash_lock);
1289
1290                         rc = ldlm_cli_cancel_unused_resource(ns, res->lr_name,
1291                                                              flags, opaque);
1292
1293                         if (rc)
1294                                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1295                                        res->lr_name.name[0], rc);
1296
1297                         spin_lock(&ns->ns_hash_lock);
1298                         tmp = tmp->next;
1299                         ldlm_resource_putref_locked(res);
1300                 }
1301         }
1302         spin_unlock(&ns->ns_hash_lock);
1303
1304         RETURN(ELDLM_OK);
1305 }
1306
1307 /* join/split resource locks to/from lru list */
1308 int ldlm_cli_join_lru(struct ldlm_namespace *ns,
1309                       struct ldlm_res_id *res_id, int join)
1310 {
1311         struct ldlm_resource *res;
1312         struct ldlm_lock *lock, *n;
1313         int count = 0;
1314         ENTRY;
1315
1316         LASSERT(ns->ns_client == LDLM_NAMESPACE_CLIENT);
1317
1318         res = ldlm_resource_get(ns, NULL, *res_id, LDLM_EXTENT, 0);
1319         if (res == NULL)
1320                 RETURN(count);
1321         LASSERT(res->lr_type == LDLM_EXTENT);
1322
1323         lock_res(res);
1324         if (!join)
1325                 goto split;
1326
1327         list_for_each_entry_safe (lock, n, &res->lr_granted, l_res_link) {
1328                 if (list_empty(&lock->l_lru) &&
1329                     !lock->l_readers && !lock->l_writers &&
1330                     !(lock->l_flags & LDLM_FL_LOCAL) &&
1331                     !(lock->l_flags & LDLM_FL_CBPENDING)) {
1332                         lock->l_last_used = cfs_time_current();
1333                         spin_lock(&ns->ns_unused_lock);
1334                         LASSERT(ns->ns_nr_unused >= 0);
1335                         list_add_tail(&lock->l_lru, &ns->ns_unused_list);
1336                         ns->ns_nr_unused++;
1337                         spin_unlock(&ns->ns_unused_lock);
1338                         lock->l_flags &= ~LDLM_FL_NO_LRU;
1339                         LDLM_DEBUG(lock, "join lock to lru");
1340                         count++;
1341                 }
1342         }
1343         goto unlock;
1344 split:
1345         spin_lock(&ns->ns_unused_lock);
1346         list_for_each_entry_safe (lock, n, &ns->ns_unused_list, l_lru) {
1347                 if (lock->l_resource == res) {
1348                         ldlm_lock_remove_from_lru_nolock(lock);
1349                         lock->l_flags |= LDLM_FL_NO_LRU;
1350                         LDLM_DEBUG(lock, "split lock from lru");
1351                         count++;
1352                 }
1353         }
1354         spin_unlock(&ns->ns_unused_lock);
1355 unlock:
1356         unlock_res(res);
1357         ldlm_resource_putref(res);
1358         RETURN(count);
1359 }
1360
1361 /* Lock iterators. */
1362
1363 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1364                           void *closure)
1365 {
1366         struct list_head *tmp, *next;
1367         struct ldlm_lock *lock;
1368         int rc = LDLM_ITER_CONTINUE;
1369
1370         ENTRY;
1371
1372         if (!res)
1373                 RETURN(LDLM_ITER_CONTINUE);
1374
1375         lock_res(res);
1376         list_for_each_safe(tmp, next, &res->lr_granted) {
1377                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1378
1379                 if (iter(lock, closure) == LDLM_ITER_STOP)
1380                         GOTO(out, rc = LDLM_ITER_STOP);
1381         }
1382
1383         list_for_each_safe(tmp, next, &res->lr_converting) {
1384                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1385
1386                 if (iter(lock, closure) == LDLM_ITER_STOP)
1387                         GOTO(out, rc = LDLM_ITER_STOP);
1388         }
1389
1390         list_for_each_safe(tmp, next, &res->lr_waiting) {
1391                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1392
1393                 if (iter(lock, closure) == LDLM_ITER_STOP)
1394                         GOTO(out, rc = LDLM_ITER_STOP);
1395         }
1396  out:
1397         unlock_res(res);
1398         RETURN(rc);
1399 }
1400
1401 struct iter_helper_data {
1402         ldlm_iterator_t iter;
1403         void *closure;
1404 };
1405
1406 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1407 {
1408         struct iter_helper_data *helper = closure;
1409         return helper->iter(lock, helper->closure);
1410 }
1411
1412 static int ldlm_res_iter_helper(struct ldlm_resource *res, void *closure)
1413 {
1414         return ldlm_resource_foreach(res, ldlm_iter_helper, closure);
1415 }
1416
1417 int ldlm_namespace_foreach(struct ldlm_namespace *ns, ldlm_iterator_t iter,
1418                            void *closure)
1419 {
1420         struct iter_helper_data helper = { iter: iter, closure: closure };
1421         return ldlm_namespace_foreach_res(ns, ldlm_res_iter_helper, &helper);
1422 }
1423
1424 int ldlm_namespace_foreach_res(struct ldlm_namespace *ns,
1425                                ldlm_res_iterator_t iter, void *closure)
1426 {
1427         int i, rc = LDLM_ITER_CONTINUE;
1428         struct ldlm_resource *res;
1429         struct list_head *tmp;
1430
1431         ENTRY;
1432         spin_lock(&ns->ns_hash_lock);
1433         for (i = 0; i < RES_HASH_SIZE; i++) {
1434                 tmp = ns->ns_hash[i].next;
1435                 while (tmp != &(ns->ns_hash[i])) {
1436                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1437                         ldlm_resource_getref(res);
1438                         spin_unlock(&ns->ns_hash_lock);
1439
1440                         rc = iter(res, closure);
1441
1442                         spin_lock(&ns->ns_hash_lock);
1443                         tmp = tmp->next;
1444                         ldlm_resource_putref_locked(res);
1445                         if (rc == LDLM_ITER_STOP)
1446                                 GOTO(out, rc);
1447                 }
1448         }
1449  out:
1450         spin_unlock(&ns->ns_hash_lock);
1451         RETURN(rc);
1452 }
1453
1454 /* non-blocking function to manipulate a lock whose cb_data is being put away.*/
1455 void ldlm_resource_iterate(struct ldlm_namespace *ns, struct ldlm_res_id *res_id,
1456                            ldlm_iterator_t iter, void *data)
1457 {
1458         struct ldlm_resource *res;
1459         ENTRY;
1460
1461         if (ns == NULL) {
1462                 CERROR("must pass in namespace\n");
1463                 LBUG();
1464         }
1465
1466         res = ldlm_resource_get(ns, NULL, *res_id, 0, 0);
1467         if (res == NULL) {
1468                 EXIT;
1469                 return;
1470         }
1471
1472         ldlm_resource_foreach(res, iter, data);
1473         ldlm_resource_putref(res);
1474         EXIT;
1475 }
1476
1477 /* Lock replay */
1478
1479 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
1480 {
1481         struct list_head *list = closure;
1482
1483         /* we use l_pending_chain here, because it's unused on clients. */
1484         LASSERTF(list_empty(&lock->l_pending_chain),"lock %p next %p prev %p\n",
1485                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
1486         /* bug 9573: don't replay locks left after eviction */
1487         if (!(lock->l_flags & LDLM_FL_FAILED))
1488                 list_add(&lock->l_pending_chain, list);
1489         return LDLM_ITER_CONTINUE;
1490 }
1491
1492 static int replay_lock_interpret(struct ptlrpc_request *req,
1493                                     void * data, int rc)
1494 {
1495         struct ldlm_lock *lock;
1496         struct ldlm_reply *reply;
1497
1498         ENTRY;
1499         atomic_dec(&req->rq_import->imp_replay_inflight);
1500         if (rc != ELDLM_OK)
1501                 GOTO(out, rc);
1502
1503         lock = req->rq_async_args.pointer_arg[0];
1504         LASSERT(lock != NULL);
1505
1506         reply = lustre_swab_repbuf(req, DLM_LOCKREPLY_OFF, sizeof(*reply),
1507                                    lustre_swab_ldlm_reply);
1508         if (reply == NULL) {
1509                 CERROR("Can't unpack ldlm_reply\n");
1510                 GOTO (out, rc = -EPROTO);
1511         }
1512
1513         lock->l_remote_handle = reply->lock_handle;
1514         LDLM_DEBUG(lock, "replayed lock:");
1515         ptlrpc_import_recovery_state_machine(req->rq_import);
1516  out:
1517         if (rc != ELDLM_OK)
1518                 ptlrpc_connect_import(req->rq_import, NULL);
1519
1520
1521         RETURN(rc);
1522 }
1523
1524 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
1525 {
1526         struct ptlrpc_request *req;
1527         struct ldlm_request *body;
1528         struct ldlm_reply *reply;
1529         int buffers = 2;
1530         int size[3] = { sizeof(struct ptlrpc_body) };
1531         int flags;
1532         ENTRY;
1533
1534         /* If this is reply-less callback lock, we cannot replay it, since
1535          * server might have long dropped it, but notification of that event was
1536          * lost by network. (and server granted conflicting lock already) */
1537         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1538                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
1539                 ldlm_lock_cancel(lock);
1540                 RETURN(0);
1541         }
1542         /*
1543          * If granted mode matches the requested mode, this lock is granted.
1544          *
1545          * If they differ, but we have a granted mode, then we were granted
1546          * one mode and now want another: ergo, converting.
1547          *
1548          * If we haven't been granted anything and are on a resource list,
1549          * then we're blocked/waiting.
1550          *
1551          * If we haven't been granted anything and we're NOT on a resource list,
1552          * then we haven't got a reply yet and don't have a known disposition.
1553          * This happens whenever a lock enqueue is the request that triggers
1554          * recovery.
1555          */
1556         if (lock->l_granted_mode == lock->l_req_mode)
1557                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
1558         else if (lock->l_granted_mode)
1559                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
1560         else if (!list_empty(&lock->l_res_link))
1561                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
1562         else
1563                 flags = LDLM_FL_REPLAY;
1564
1565         size[DLM_LOCKREQ_OFF] = sizeof(*body);
1566         req = ptlrpc_prep_req(imp, LUSTRE_DLM_VERSION, LDLM_ENQUEUE, 2, size,
1567                               NULL);
1568         if (!req)
1569                 RETURN(-ENOMEM);
1570
1571         /* We're part of recovery, so don't wait for it. */
1572         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
1573
1574         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
1575         ldlm_lock2desc(lock, &body->lock_desc);
1576         body->lock_flags = flags;
1577
1578         ldlm_lock2handle(lock, &body->lock_handle[0]);
1579         size[DLM_LOCKREPLY_OFF] = sizeof(*reply);
1580         if (lock->l_lvb_len != 0) {
1581                 buffers = 3;
1582                 size[DLM_REPLY_REC_OFF] = lock->l_lvb_len;
1583         }
1584         ptlrpc_req_set_repsize(req, buffers, size);
1585
1586         LDLM_DEBUG(lock, "replaying lock:");
1587
1588         atomic_inc(&req->rq_import->imp_replay_inflight);
1589         req->rq_async_args.pointer_arg[0] = lock;
1590         req->rq_interpret_reply = replay_lock_interpret;
1591         ptlrpcd_add_req(req);
1592
1593         RETURN(0);
1594 }
1595
1596 int ldlm_replay_locks(struct obd_import *imp)
1597 {
1598         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
1599         struct list_head list;
1600         struct ldlm_lock *lock, *next;
1601         int rc = 0;
1602
1603         ENTRY;
1604         CFS_INIT_LIST_HEAD(&list);
1605
1606         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
1607
1608         /* ensure this doesn't fall to 0 before all have been queued */
1609         atomic_inc(&imp->imp_replay_inflight);
1610
1611         (void)ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
1612
1613         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
1614                 list_del_init(&lock->l_pending_chain);
1615                 if (rc)
1616                         continue; /* or try to do the rest? */
1617                 rc = replay_one_lock(imp, lock);
1618         }
1619
1620         atomic_dec(&imp->imp_replay_inflight);
1621
1622         RETURN(rc);
1623 }