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