Whamcloud - gitweb
Instead of specifying each ldlm_lock call-back through separate parameter,
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_LDLM
38 #ifndef __KERNEL__
39 #include <signal.h>
40 #include <liblustre.h>
41 #endif
42
43 #include <lustre_dlm.h>
44 #include <obd_class.h>
45 #include <obd.h>
46
47 #include "ldlm_internal.h"
48
49 int ldlm_enqueue_min = OBD_TIMEOUT_DEFAULT;
50 CFS_MODULE_PARM(ldlm_enqueue_min, "i", int, 0644,
51                 "lock enqueue timeout minimum");
52
53 static void interrupted_completion_wait(void *data)
54 {
55 }
56
57 struct lock_wait_data {
58         struct ldlm_lock *lwd_lock;
59         __u32             lwd_conn_cnt;
60 };
61
62 struct ldlm_async_args {
63         struct lustre_handle lock_handle;
64 };
65
66 int ldlm_expired_completion_wait(void *data)
67 {
68         struct lock_wait_data *lwd = data;
69         struct ldlm_lock *lock = lwd->lwd_lock;
70         struct obd_import *imp;
71         struct obd_device *obd;
72
73         ENTRY;
74         if (lock->l_conn_export == NULL) {
75                 static cfs_time_t next_dump = 0, last_dump = 0;
76
77                 if (ptlrpc_check_suspend())
78                         RETURN(0);
79
80                 LDLM_ERROR(lock, "lock timed out (enqueued at "CFS_TIME_T", "
81                            CFS_DURATION_T"s ago); not entering recovery in "
82                            "server code, just going back to sleep",
83                            lock->l_enqueued_time.tv_sec,
84                            cfs_time_sub(cfs_time_current_sec(),
85                            lock->l_enqueued_time.tv_sec));
86                 if (cfs_time_after(cfs_time_current(), next_dump)) {
87                         last_dump = next_dump;
88                         next_dump = cfs_time_shift(300);
89                         ldlm_namespace_dump(D_DLMTRACE,
90                                             lock->l_resource->lr_namespace);
91                         if (last_dump == 0)
92                                 libcfs_debug_dumplog();
93                 }
94                 RETURN(0);
95         }
96
97         obd = lock->l_conn_export->exp_obd;
98         imp = obd->u.cli.cl_import;
99         ptlrpc_fail_import(imp, lwd->lwd_conn_cnt);
100         LDLM_ERROR(lock, "lock timed out (enqueued at "CFS_TIME_T", "
101                   CFS_DURATION_T"s ago), entering recovery for %s@%s",
102                   lock->l_enqueued_time.tv_sec,
103                   cfs_time_sub(cfs_time_current_sec(),
104                   lock->l_enqueued_time.tv_sec),
105                   obd2cli_tgt(obd), imp->imp_connection->c_remote_uuid.uuid);
106
107         RETURN(0);
108 }
109
110 /* We use the same basis for both server side and client side functions
111    from a single node. */
112 int ldlm_get_enq_timeout(struct ldlm_lock *lock)
113 {
114         int timeout = at_get(&lock->l_resource->lr_namespace->ns_at_estimate);
115         if (AT_OFF)
116                 return obd_timeout / 2;
117         /* Since these are non-updating timeouts, we should be conservative.
118            It would be nice to have some kind of "early reply" mechanism for
119            lock callbacks too... */
120         timeout = timeout + (timeout >> 1); /* 150% */
121         return max(timeout, ldlm_enqueue_min);
122 }
123
124 static int is_granted_or_cancelled(struct ldlm_lock *lock)
125 {
126         int ret = 0;
127
128         lock_res_and_lock(lock);
129         if (((lock->l_req_mode == lock->l_granted_mode) &&
130              !(lock->l_flags & LDLM_FL_CP_REQD)) ||
131             (lock->l_flags & LDLM_FL_FAILED))
132                 ret = 1;
133         unlock_res_and_lock(lock);
134
135         return ret;
136 }
137
138 int ldlm_completion_ast(struct ldlm_lock *lock, int flags, void *data)
139 {
140         /* XXX ALLOCATE - 160 bytes */
141         struct lock_wait_data lwd;
142         struct obd_device *obd;
143         struct obd_import *imp = NULL;
144         struct l_wait_info lwi;
145         __u32 timeout;
146         int rc = 0;
147         ENTRY;
148
149         if (flags == LDLM_FL_WAIT_NOREPROC) {
150                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
151                 goto noreproc;
152         }
153
154         if (!(flags & (LDLM_FL_BLOCK_WAIT | LDLM_FL_BLOCK_GRANTED |
155                        LDLM_FL_BLOCK_CONV))) {
156                 cfs_waitq_signal(&lock->l_waitq);
157                 RETURN(0);
158         }
159
160         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, "
161                    "sleeping");
162         ldlm_lock_dump(D_OTHER, lock, 0);
163         ldlm_reprocess_all(lock->l_resource);
164
165 noreproc:
166
167         obd = class_exp2obd(lock->l_conn_export);
168
169         /* if this is a local lock, then there is no import */
170         if (obd != NULL) {
171                 imp = obd->u.cli.cl_import;
172         }
173
174         /* Wait a long time for enqueue - server may have to callback a
175            lock from another client.  Server will evict the other client if it
176            doesn't respond reasonably, and then give us the lock. */
177         timeout = ldlm_get_enq_timeout(lock) * 2;
178
179         lwd.lwd_lock = lock;
180
181         if (lock->l_flags & LDLM_FL_NO_TIMEOUT) {
182                 LDLM_DEBUG(lock, "waiting indefinitely because of NO_TIMEOUT");
183                 lwi = LWI_INTR(interrupted_completion_wait, &lwd);
184         } else {
185                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(timeout),
186                                        ldlm_expired_completion_wait,
187                                        interrupted_completion_wait, &lwd);
188         }
189
190         if (imp != NULL) {
191                 spin_lock(&imp->imp_lock);
192                 lwd.lwd_conn_cnt = imp->imp_conn_cnt;
193                 spin_unlock(&imp->imp_lock);
194         }
195
196         /* Go to sleep until the lock is granted or cancelled. */
197         rc = l_wait_event(lock->l_waitq, is_granted_or_cancelled(lock), &lwi);
198
199         if (lock->l_destroyed || lock->l_flags & LDLM_FL_FAILED) {
200                 LDLM_DEBUG(lock, "client-side enqueue waking up: destroyed");
201                 RETURN(-EIO);
202         }
203
204         if (rc) {
205                 LDLM_DEBUG(lock, "client-side enqueue waking up: failed (%d)",
206                            rc);
207                 RETURN(rc);
208         }
209
210         LDLM_DEBUG(lock, "client-side enqueue waking up: granted after "
211                    CFS_DURATION_T"s",
212                    cfs_time_sub(cfs_time_current_sec(),
213                    lock->l_enqueued_time.tv_sec));
214
215         /* Update our time estimate */
216         at_add(&lock->l_resource->lr_namespace->ns_at_estimate,
217                cfs_time_current_sec() - lock->l_enqueued_time.tv_sec);
218
219         RETURN(0);
220 }
221
222 /*
223  * ->l_blocking_ast() callback for LDLM locks acquired by server-side OBDs.
224  */
225 int ldlm_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
226                       void *data, int flag)
227 {
228         int do_ast;
229         ENTRY;
230
231         if (flag == LDLM_CB_CANCELING) {
232                 /* Don't need to do anything here. */
233                 RETURN(0);
234         }
235
236         lock_res_and_lock(lock);
237         /* Get this: if ldlm_blocking_ast is racing with intent_policy, such
238          * that ldlm_blocking_ast is called just before intent_policy method
239          * takes the ns_lock, then by the time we get the lock, we might not
240          * be the correct blocking function anymore.  So check, and return
241          * early, if so. */
242         if (lock->l_blocking_ast != ldlm_blocking_ast) {
243                 unlock_res_and_lock(lock);
244                 RETURN(0);
245         }
246
247         lock->l_flags |= LDLM_FL_CBPENDING;
248         do_ast = (!lock->l_readers && !lock->l_writers);
249         unlock_res_and_lock(lock);
250
251         if (do_ast) {
252                 struct lustre_handle lockh;
253                 int rc;
254
255                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
256                 ldlm_lock2handle(lock, &lockh);
257                 rc = ldlm_cli_cancel(&lockh);
258                 if (rc < 0)
259                         CERROR("ldlm_cli_cancel: %d\n", rc);
260         } else {
261                 LDLM_DEBUG(lock, "Lock still has references, will be "
262                            "cancelled later");
263         }
264         RETURN(0);
265 }
266
267 /*
268  * ->l_glimpse_ast() for DLM extent locks acquired on the server-side. See
269  * comment in filter_intent_policy() on why you may need this.
270  */
271 int ldlm_glimpse_ast(struct ldlm_lock *lock, void *reqp)
272 {
273         /*
274          * Returning -ELDLM_NO_LOCK_DATA actually works, but the reason for
275          * that is rather subtle: with OST-side locking, it may so happen that
276          * _all_ extent locks are held by the OST. If client wants to obtain
277          * current file size it calls ll{,u}_glimpse_size(), and (as locks are
278          * on the server), dummy glimpse callback fires and does
279          * nothing. Client still receives correct file size due to the
280          * following fragment in filter_intent_policy():
281          *
282          * rc = l->l_glimpse_ast(l, NULL); // this will update the LVB
283          * if (rc != 0 && res->lr_namespace->ns_lvbo &&
284          *     res->lr_namespace->ns_lvbo->lvbo_update) {
285          *         res->lr_namespace->ns_lvbo->lvbo_update(res, NULL, 0, 1);
286          * }
287          *
288          * that is, after glimpse_ast() fails, filter_lvbo_update() runs, and
289          * returns correct file size to the client.
290          */
291         return -ELDLM_NO_LOCK_DATA;
292 }
293
294 int ldlm_cli_enqueue_local(struct ldlm_namespace *ns,
295                            const struct ldlm_res_id *res_id,
296                            ldlm_type_t type, ldlm_policy_data_t *policy,
297                            ldlm_mode_t mode, int *flags,
298                            ldlm_blocking_callback blocking,
299                            ldlm_completion_callback completion,
300                            ldlm_glimpse_callback glimpse,
301                            void *data, __u32 lvb_len, void *lvb_swabber,
302                            struct lustre_handle *lockh)
303 {
304         struct ldlm_lock *lock;
305         int err;
306         const struct ldlm_callback_suite cbs = { .lcs_completion = completion,
307                                                  .lcs_blocking   = blocking,
308                                                  .lcs_glimpse    = glimpse,
309         };
310         ENTRY;
311
312         LASSERT(!(*flags & LDLM_FL_REPLAY));
313         if (unlikely(ns_is_client(ns))) {
314                 CERROR("Trying to enqueue local lock in a shadow namespace\n");
315                 LBUG();
316         }
317
318         lock = ldlm_lock_create(ns, res_id, type, mode, &cbs, data, lvb_len);
319         if (unlikely(!lock))
320                 GOTO(out_nolock, err = -ENOMEM);
321         LDLM_DEBUG(lock, "client-side local enqueue handler, new lock created");
322
323         ldlm_lock_addref_internal(lock, mode);
324         ldlm_lock2handle(lock, lockh);
325         lock_res_and_lock(lock);
326         lock->l_flags |= LDLM_FL_LOCAL;
327         if (*flags & LDLM_FL_ATOMIC_CB)
328                 lock->l_flags |= LDLM_FL_ATOMIC_CB;
329         lock->l_lvb_swabber = lvb_swabber;
330         unlock_res_and_lock(lock);
331         if (policy != NULL)
332                 lock->l_policy_data = *policy;
333         if (type == LDLM_EXTENT)
334                 lock->l_req_extent = policy->l_extent;
335
336         err = ldlm_lock_enqueue(ns, &lock, policy, flags);
337         if (unlikely(err != ELDLM_OK))
338                 GOTO(out, err);
339
340         if (policy != NULL)
341                 *policy = lock->l_policy_data;
342
343         LDLM_DEBUG_NOLOCK("client-side local enqueue handler END (lock %p)",
344                           lock);
345
346         if (lock->l_completion_ast)
347                 lock->l_completion_ast(lock, *flags, NULL);
348
349         LDLM_DEBUG(lock, "client-side local enqueue END");
350         EXIT;
351  out:
352         LDLM_LOCK_PUT(lock);
353  out_nolock:
354         return err;
355 }
356
357 static void failed_lock_cleanup(struct ldlm_namespace *ns,
358                                 struct ldlm_lock *lock,
359                                 struct lustre_handle *lockh, int mode)
360 {
361         /* Set a flag to prevent us from sending a CANCEL (bug 407) */
362         lock_res_and_lock(lock);
363         lock->l_flags |= LDLM_FL_LOCAL_ONLY;
364         unlock_res_and_lock(lock);
365         LDLM_DEBUG(lock, "setting FL_LOCAL_ONLY");
366
367         ldlm_lock_decref_and_cancel(lockh, mode);
368
369         /* XXX - HACK because we shouldn't call ldlm_lock_destroy()
370          *       from llite/file.c/ll_file_flock(). */
371         if (lock->l_resource->lr_type == LDLM_FLOCK) {
372                 ldlm_lock_destroy(lock);
373         }
374 }
375
376 int ldlm_cli_enqueue_fini(struct obd_export *exp, struct ptlrpc_request *req,
377                           ldlm_type_t type, __u8 with_policy, ldlm_mode_t mode,
378                           int *flags, void *lvb, __u32 lvb_len,
379                           void *lvb_swabber, struct lustre_handle *lockh,int rc)
380 {
381         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
382         int is_replay = *flags & LDLM_FL_REPLAY;
383         struct lustre_handle old_hash_key;
384         struct ldlm_lock *lock;
385         struct ldlm_reply *reply;
386         int cleanup_phase = 1;
387         ENTRY;
388
389         lock = ldlm_handle2lock(lockh);
390         /* ldlm_cli_enqueue is holding a reference on this lock. */
391         if (!lock) {
392                 LASSERT(type == LDLM_FLOCK);
393                 RETURN(-ENOLCK);
394         }
395
396         if (rc != ELDLM_OK) {
397                 LASSERT(!is_replay);
398                 LDLM_DEBUG(lock, "client-side enqueue END (%s)",
399                            rc == ELDLM_LOCK_ABORTED ? "ABORTED" : "FAILED");
400                 if (rc == ELDLM_LOCK_ABORTED) {
401                         /* Before we return, swab the reply */
402                         reply = req_capsule_server_get(&req->rq_pill,
403                                                        &RMF_DLM_REP);
404                         if (reply == NULL)
405                                 rc = -EPROTO;
406                         if (lvb_len) {
407                                 struct ost_lvb *tmplvb;
408
409                                 req_capsule_set_size(&req->rq_pill,
410                                                      &RMF_DLM_LVB, RCL_SERVER,
411                                                      lvb_len);
412                             tmplvb = req_capsule_server_swab_get(&req->rq_pill,
413                                                                  &RMF_DLM_LVB,
414                                                                  lvb_swabber);
415                                 if (tmplvb == NULL)
416                                         GOTO(cleanup, rc = -EPROTO);
417                                 if (lvb != NULL)
418                                         memcpy(lvb, tmplvb, lvb_len);
419                         }
420                 }
421                 GOTO(cleanup, rc);
422         }
423
424         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
425         if (reply == NULL)
426                 GOTO(cleanup, rc = -EPROTO);
427
428         /* lock enqueued on the server */
429         cleanup_phase = 0;
430
431         lock_res_and_lock(lock);
432         old_hash_key = lock->l_remote_handle;
433         lock->l_remote_handle = reply->lock_handle;
434
435         /* Key change rehash lock in per-export hash with new key */
436         if (exp->exp_lock_hash)
437                 lustre_hash_rehash_key(exp->exp_lock_hash, &old_hash_key,
438                                        &lock->l_remote_handle,
439                                        &lock->l_exp_hash);
440
441         *flags = reply->lock_flags;
442         lock->l_flags |= reply->lock_flags & LDLM_INHERIT_FLAGS;
443         /* move NO_TIMEOUT flag to the lock to force ldlm_lock_match()
444          * to wait with no timeout as well */
445         lock->l_flags |= reply->lock_flags & LDLM_FL_NO_TIMEOUT;
446         unlock_res_and_lock(lock);
447
448         CDEBUG(D_INFO, "local: %p, remote cookie: "LPX64", flags: 0x%x\n",
449                lock, reply->lock_handle.cookie, *flags);
450
451         /* If enqueue returned a blocked lock but the completion handler has
452          * already run, then it fixed up the resource and we don't need to do it
453          * again. */
454         if ((*flags) & LDLM_FL_LOCK_CHANGED) {
455                 int newmode = reply->lock_desc.l_req_mode;
456                 LASSERT(!is_replay);
457                 if (newmode && newmode != lock->l_req_mode) {
458                         LDLM_DEBUG(lock, "server returned different mode %s",
459                                    ldlm_lockname[newmode]);
460                         lock->l_req_mode = newmode;
461                 }
462
463                 if (memcmp(reply->lock_desc.l_resource.lr_name.name,
464                           lock->l_resource->lr_name.name,
465                           sizeof(struct ldlm_res_id))) {
466                         CDEBUG(D_INFO, "remote intent success, locking "
467                                         "(%ld,%ld,%ld) instead of "
468                                         "(%ld,%ld,%ld)\n",
469                               (long)reply->lock_desc.l_resource.lr_name.name[0],
470                               (long)reply->lock_desc.l_resource.lr_name.name[1],
471                               (long)reply->lock_desc.l_resource.lr_name.name[2],
472                               (long)lock->l_resource->lr_name.name[0],
473                               (long)lock->l_resource->lr_name.name[1],
474                               (long)lock->l_resource->lr_name.name[2]);
475
476                         rc = ldlm_lock_change_resource(ns, lock,
477                                         &reply->lock_desc.l_resource.lr_name);
478                         if (rc || lock->l_resource == NULL)
479                                 GOTO(cleanup, rc = -ENOMEM);
480                         LDLM_DEBUG(lock, "client-side enqueue, new resource");
481                 }
482                 if (with_policy)
483                         if (!(type == LDLM_IBITS && !(exp->exp_connect_flags &
484                                                     OBD_CONNECT_IBITS)))
485                                 lock->l_policy_data =
486                                                  reply->lock_desc.l_policy_data;
487                 if (type != LDLM_PLAIN)
488                         LDLM_DEBUG(lock,"client-side enqueue, new policy data");
489         }
490
491         if ((*flags) & LDLM_FL_AST_SENT ||
492             /* Cancel extent locks as soon as possible on a liblustre client,
493              * because it cannot handle asynchronous ASTs robustly (see
494              * bug 7311). */
495             (LIBLUSTRE_CLIENT && type == LDLM_EXTENT)) {
496                 lock_res_and_lock(lock);
497                 lock->l_flags |= LDLM_FL_CBPENDING |  LDLM_FL_BL_AST;
498                 unlock_res_and_lock(lock);
499                 LDLM_DEBUG(lock, "enqueue reply includes blocking AST");
500         }
501
502         /* If the lock has already been granted by a completion AST, don't
503          * clobber the LVB with an older one. */
504         if (lvb_len && (lock->l_req_mode != lock->l_granted_mode)) {
505                 void *tmplvb;
506
507                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
508                                      lvb_len);
509                 tmplvb = req_capsule_server_swab_get(&req->rq_pill,
510                                                      &RMF_DLM_LVB,
511                                                      lvb_swabber);
512                 if (tmplvb == NULL)
513                         GOTO(cleanup, rc = -EPROTO);
514                 memcpy(lock->l_lvb_data, tmplvb, lvb_len);
515         }
516
517         if (!is_replay) {
518                 rc = ldlm_lock_enqueue(ns, &lock, NULL, flags);
519                 if (lock->l_completion_ast != NULL) {
520                         int err = lock->l_completion_ast(lock, *flags, NULL);
521                         if (!rc)
522                                 rc = err;
523                         if (rc && type != LDLM_FLOCK) /* bug 9425, bug 10250 */
524                                 cleanup_phase = 1;
525                 }
526         }
527
528         if (lvb_len && lvb != NULL) {
529                 /* Copy the LVB here, and not earlier, because the completion
530                  * AST (if any) can override what we got in the reply */
531                 memcpy(lvb, lock->l_lvb_data, lvb_len);
532         }
533
534         LDLM_DEBUG(lock, "client-side enqueue END");
535         EXIT;
536 cleanup:
537         if (cleanup_phase == 1 && rc)
538                 failed_lock_cleanup(ns, lock, lockh, mode);
539         /* Put lock 2 times, the second reference is held by ldlm_cli_enqueue */
540         LDLM_LOCK_PUT(lock);
541         LDLM_LOCK_PUT(lock);
542         return rc;
543 }
544
545 /* PAGE_SIZE-512 is to allow TCP/IP and LNET headers to fit into
546  * a single page on the send/receive side. XXX: 512 should be changed
547  * to more adequate value. */
548 static inline int ldlm_req_handles_avail(int req_size, int off)
549 {
550         int avail;
551
552         avail = min_t(int, LDLM_MAXREQSIZE, CFS_PAGE_SIZE - 512) - req_size;
553         avail /= sizeof(struct lustre_handle);
554         avail += LDLM_LOCKREQ_HANDLES - off;
555
556         return avail;
557 }
558
559 static inline int ldlm_capsule_handles_avail(struct req_capsule *pill,
560                                              enum req_location loc,
561                                              int off)
562 {
563         int size = req_capsule_msg_size(pill, loc);
564         return ldlm_req_handles_avail(size, off);
565 }
566
567 static inline int ldlm_format_handles_avail(struct obd_import *imp,
568                                             const struct req_format *fmt,
569                                             enum req_location loc, int off)
570 {
571         int size = req_capsule_fmt_size(imp->imp_msg_magic, fmt, loc);
572         return ldlm_req_handles_avail(size, off);
573 }
574
575 /* Cancel lru locks and pack them into the enqueue request. Pack there the given
576  * @count locks in @cancels. */
577 int ldlm_prep_elc_req(struct obd_export *exp, struct ptlrpc_request *req,
578                       int version, int opc, int canceloff,
579                       struct list_head *cancels, int count)
580 {
581         struct ldlm_namespace   *ns = exp->exp_obd->obd_namespace;
582         struct req_capsule      *pill = &req->rq_pill;
583         struct ldlm_request     *dlm = NULL;
584         int flags, avail, to_free, bufcount, pack = 0;
585         CFS_LIST_HEAD(head);
586         int rc;
587         ENTRY;
588
589         if (cancels == NULL)
590                 cancels = &head;
591         if (exp_connect_cancelset(exp)) {
592                 /* Estimate the amount of available space in the request. */
593                 bufcount = req_capsule_filled_sizes(pill, RCL_CLIENT);
594                 avail = ldlm_capsule_handles_avail(pill, RCL_CLIENT, canceloff);
595
596                 flags = ns_connect_lru_resize(ns) ? 
597                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
598                 to_free = !ns_connect_lru_resize(ns) &&
599                           opc == LDLM_ENQUEUE ? 1 : 0;
600
601                 /* Cancel lru locks here _only_ if the server supports 
602                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
603                  * rpc, what will make us slower. */
604                 if (avail > count)
605                         count += ldlm_cancel_lru_local(ns, cancels, to_free,
606                                                        avail - count, 0, flags);
607                 if (avail > count)
608                         pack = count;
609                 else
610                         pack = avail;
611                 req_capsule_set_size(pill, &RMF_DLM_REQ, RCL_CLIENT,
612                                      ldlm_request_bufsize(pack, opc));
613         }
614
615         rc = ptlrpc_request_pack(req, version, opc);
616         if (rc) {
617                 ldlm_lock_list_put(cancels, l_bl_ast, count);
618                 RETURN(rc);
619         }
620
621         if (exp_connect_cancelset(exp)) {
622                 if (canceloff) {
623                         dlm = req_capsule_client_get(pill, &RMF_DLM_REQ);
624                         LASSERT(dlm);
625                         /* Skip first lock handler in ldlm_request_pack(),
626                          * this method will incrment @lock_count according
627                          * to the lock handle amount actually written to
628                          * the buffer. */
629                         dlm->lock_count = canceloff;
630                 }
631                 /* Pack into the request @pack lock handles. */
632                 ldlm_cli_cancel_list(cancels, pack, req, 0);
633                 /* Prepare and send separate cancel rpc for others. */
634                 ldlm_cli_cancel_list(cancels, count - pack, NULL, 0);
635         } else {
636                 ldlm_lock_list_put(cancels, l_bl_ast, count);
637         }
638         RETURN(0);
639 }
640
641 int ldlm_prep_enqueue_req(struct obd_export *exp, struct ptlrpc_request *req,
642                           struct list_head *cancels, int count)
643 {
644         return ldlm_prep_elc_req(exp, req, LUSTRE_DLM_VERSION, LDLM_ENQUEUE,
645                                  LDLM_ENQUEUE_CANCEL_OFF, cancels, count);
646 }
647
648 /* If a request has some specific initialisation it is passed in @reqp,
649  * otherwise it is created in ldlm_cli_enqueue.
650  *
651  * Supports sync and async requests, pass @async flag accordingly. If a
652  * request was created in ldlm_cli_enqueue and it is the async request,
653  * pass it to the caller in @reqp. */
654 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
655                      struct ldlm_enqueue_info *einfo,
656                      const struct ldlm_res_id *res_id,
657                      ldlm_policy_data_t *policy, int *flags,
658                      void *lvb, __u32 lvb_len, void *lvb_swabber,
659                      struct lustre_handle *lockh, int async)
660 {
661         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
662         struct ldlm_lock      *lock;
663         struct ldlm_request   *body;
664         int                    is_replay = *flags & LDLM_FL_REPLAY;
665         int                    req_passed_in = 1;
666         int                    rc, err;
667         struct ptlrpc_request *req;
668         ENTRY;
669
670         LASSERT(exp != NULL);
671
672         /* If we're replaying this lock, just check some invariants.
673          * If we're creating a new lock, get everything all setup nice. */
674         if (is_replay) {
675                 lock = ldlm_handle2lock_long(lockh, 0);
676                 LASSERT(lock != NULL);
677                 LDLM_DEBUG(lock, "client-side enqueue START");
678                 LASSERT(exp == lock->l_conn_export);
679         } else {
680                 const struct ldlm_callback_suite cbs = {
681                         .lcs_completion = einfo->ei_cb_cp,
682                         .lcs_blocking   = einfo->ei_cb_bl,
683                         .lcs_glimpse    = einfo->ei_cb_gl,
684                         .lcs_weigh      = einfo->ei_cb_wg
685                 };
686                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
687                                         einfo->ei_mode, &cbs, einfo->ei_cbdata,
688                                         lvb_len);
689                 if (lock == NULL)
690                         RETURN(-ENOMEM);
691                 /* for the local lock, add the reference */
692                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
693                 ldlm_lock2handle(lock, lockh);
694                 lock->l_lvb_swabber = lvb_swabber;
695                 if (policy != NULL) {
696                         /* INODEBITS_INTEROP: If the server does not support
697                          * inodebits, we will request a plain lock in the
698                          * descriptor (ldlm_lock2desc() below) but use an
699                          * inodebits lock internally with both bits set.
700                          */
701                         if (einfo->ei_type == LDLM_IBITS &&
702                             !(exp->exp_connect_flags & OBD_CONNECT_IBITS))
703                                 lock->l_policy_data.l_inodebits.bits =
704                                         MDS_INODELOCK_LOOKUP |
705                                         MDS_INODELOCK_UPDATE;
706                         else
707                                 lock->l_policy_data = *policy;
708                 }
709
710                 if (einfo->ei_type == LDLM_EXTENT)
711                         lock->l_req_extent = policy->l_extent;
712                 LDLM_DEBUG(lock, "client-side enqueue START");
713         }
714
715         /* lock not sent to server yet */
716
717         if (reqp == NULL || *reqp == NULL) {
718                 req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
719                                                 &RQF_LDLM_ENQUEUE,
720                                                 LUSTRE_DLM_VERSION,
721                                                 LDLM_ENQUEUE);
722                 if (req == NULL) {
723                         failed_lock_cleanup(ns, lock, lockh, einfo->ei_mode);
724                         LDLM_LOCK_PUT(lock);
725                         RETURN(-ENOMEM);
726                 }
727                 req_passed_in = 0;
728                 if (reqp)
729                         *reqp = req;
730         } else {
731                 int len;
732
733                 req = *reqp;
734                 len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ,
735                                            RCL_CLIENT);
736                 LASSERTF(len >= sizeof(*body), "buflen[%d] = %d, not %d\n",
737                          DLM_LOCKREQ_OFF, len, (int)sizeof(*body));
738         }
739
740         lock->l_conn_export = exp;
741         lock->l_export = NULL;
742         lock->l_blocking_ast = einfo->ei_cb_bl;
743
744         /* Dump lock data into the request buffer */
745         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
746         ldlm_lock2desc(lock, &body->lock_desc);
747         body->lock_flags = *flags;
748         body->lock_handle[0] = *lockh;
749
750         /* Continue as normal. */
751         if (!req_passed_in) {
752                 if (lvb_len > 0) {
753                         req_capsule_extend(&req->rq_pill,
754                                            &RQF_LDLM_ENQUEUE_LVB);
755                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
756                                              RCL_SERVER, lvb_len);
757                 }
758                 ptlrpc_request_set_replen(req);
759         }
760
761         /*
762          * Liblustre client doesn't get extent locks, except for O_APPEND case
763          * where [0, OBD_OBJECT_EOF] lock is taken, or truncate, where
764          * [i_size, OBD_OBJECT_EOF] lock is taken.
765          */
766         LASSERT(ergo(LIBLUSTRE_CLIENT, einfo->ei_type != LDLM_EXTENT ||
767                      policy->l_extent.end == OBD_OBJECT_EOF));
768
769         if (async) {
770                 LASSERT(reqp != NULL);
771                 RETURN(0);
772         }
773
774         LDLM_DEBUG(lock, "sending request");
775         rc = ptlrpc_queue_wait(req);
776         err = ldlm_cli_enqueue_fini(exp, req, einfo->ei_type, policy ? 1 : 0,
777                                     einfo->ei_mode, flags, lvb, lvb_len,
778                                     lvb_swabber, lockh, rc);
779
780         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
781          * one reference that we took */
782         if (err == -ENOLCK)
783                 LDLM_LOCK_PUT(lock);
784         else
785                 rc = err;
786
787         if (!req_passed_in && req != NULL) {
788                 ptlrpc_req_finished(req);
789                 if (reqp)
790                         *reqp = NULL;
791         }
792
793         RETURN(rc);
794 }
795
796 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
797                                   __u32 *flags)
798 {
799         struct ldlm_resource *res;
800         int rc;
801         ENTRY;
802         if (ns_is_client(lock->l_resource->lr_namespace)) {
803                 CERROR("Trying to cancel local lock\n");
804                 LBUG();
805         }
806         LDLM_DEBUG(lock, "client-side local convert");
807
808         res = ldlm_lock_convert(lock, new_mode, flags);
809         if (res) {
810                 ldlm_reprocess_all(res);
811                 rc = 0;
812         } else {
813                 rc = EDEADLOCK;
814         }
815         LDLM_DEBUG(lock, "client-side local convert handler END");
816         LDLM_LOCK_PUT(lock);
817         RETURN(rc);
818 }
819
820 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
821  * conversion of locks which are on the waiting or converting queue */
822 /* Caller of this code is supposed to take care of lock readers/writers
823    accounting */
824 int ldlm_cli_convert(struct lustre_handle *lockh, int new_mode, __u32 *flags)
825 {
826         struct ldlm_request   *body;
827         struct ldlm_reply     *reply;
828         struct ldlm_lock      *lock;
829         struct ldlm_resource  *res;
830         struct ptlrpc_request *req;
831         int                    rc;
832         ENTRY;
833
834         lock = ldlm_handle2lock(lockh);
835         if (!lock) {
836                 LBUG();
837                 RETURN(-EINVAL);
838         }
839         *flags = 0;
840
841         if (lock->l_conn_export == NULL)
842                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
843
844         LDLM_DEBUG(lock, "client-side convert");
845
846         req = ptlrpc_request_alloc_pack(class_exp2cliimp(lock->l_conn_export),
847                                         &RQF_LDLM_CONVERT, LUSTRE_DLM_VERSION,
848                                         LDLM_CONVERT);
849         if (req == NULL) {
850                 LDLM_LOCK_PUT(lock);
851                 RETURN(-ENOMEM);
852         }
853
854         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
855         body->lock_handle[0] = lock->l_remote_handle;
856
857         body->lock_desc.l_req_mode = new_mode;
858         body->lock_flags = *flags;
859
860
861         ptlrpc_request_set_replen(req);
862         rc = ptlrpc_queue_wait(req);
863         if (rc != ELDLM_OK)
864                 GOTO(out, rc);
865
866         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
867         if (reply == NULL)
868                 GOTO(out, rc = -EPROTO);
869
870         if (req->rq_status)
871                 GOTO(out, rc = req->rq_status);
872
873         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
874         if (res != NULL) {
875                 ldlm_reprocess_all(res);
876                 /* Go to sleep until the lock is granted. */
877                 /* FIXME: or cancelled. */
878                 if (lock->l_completion_ast) {
879                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
880                                                     NULL);
881                         if (rc)
882                                 GOTO(out, rc);
883                 }
884         } else {
885                 rc = EDEADLOCK;
886         }
887         EXIT;
888  out:
889         LDLM_LOCK_PUT(lock);
890         ptlrpc_req_finished(req);
891         return rc;
892 }
893
894 /* Cancel locks locally.
895  * Returns:
896  * LDLM_FL_LOCAL_ONLY if tere is no need in a CANCEL rpc to the server;
897  * LDLM_FL_CANCELING otherwise;
898  * LDLM_FL_BL_AST if there is a need in a separate CANCEL rpc. */
899 static int ldlm_cli_cancel_local(struct ldlm_lock *lock)
900 {
901         int rc = LDLM_FL_LOCAL_ONLY;
902         ENTRY;
903         
904         if (lock->l_conn_export) {
905                 int local_only;
906
907                 LDLM_DEBUG(lock, "client-side cancel");
908                 /* Set this flag to prevent others from getting new references*/
909                 lock_res_and_lock(lock);
910                 lock->l_flags |= LDLM_FL_CBPENDING;
911                 local_only = (lock->l_flags &
912                               (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
913                 ldlm_cancel_callback(lock);
914                 rc = (lock->l_flags & LDLM_FL_BL_AST) ?
915                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
916                 unlock_res_and_lock(lock);
917
918                 if (local_only) {
919                         CDEBUG(D_DLMTRACE, "not sending request (at caller's "
920                                "instruction)\n");
921                         rc = LDLM_FL_LOCAL_ONLY;
922                 }
923                 ldlm_lock_cancel(lock);
924         } else {
925                 if (ns_is_client(lock->l_resource->lr_namespace)) {
926                         LDLM_ERROR(lock, "Trying to cancel local lock");
927                         LBUG();
928                 }
929                 LDLM_DEBUG(lock, "server-side local cancel");
930                 ldlm_lock_cancel(lock);
931                 ldlm_reprocess_all(lock->l_resource);
932                 LDLM_DEBUG(lock, "server-side local cancel handler END");
933         }
934
935         RETURN(rc);
936 }
937
938 /* Pack @count locks in @head into ldlm_request buffer at the offset @off,
939    of the request @req. */
940 static void ldlm_cancel_pack(struct ptlrpc_request *req,
941                              struct list_head *head, int count)
942 {
943         struct ldlm_request *dlm;
944         struct ldlm_lock *lock;
945         int max, packed = 0;
946         ENTRY;
947
948         dlm = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
949         LASSERT(dlm != NULL);
950
951         /* Check the room in the request buffer. */
952         max = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT) - 
953                 sizeof(struct ldlm_request);
954         max /= sizeof(struct lustre_handle);
955         max += LDLM_LOCKREQ_HANDLES;
956         LASSERT(max >= dlm->lock_count + count);
957
958         /* XXX: it would be better to pack lock handles grouped by resource.
959          * so that the server cancel would call filter_lvbo_update() less
960          * frequently. */
961         list_for_each_entry(lock, head, l_bl_ast) {
962                 if (!count--)
963                         break;
964                 LASSERT(lock->l_conn_export);
965                 /* Pack the lock handle to the given request buffer. */
966                 LDLM_DEBUG(lock, "packing");
967                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
968                 packed++;
969         }
970         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
971         EXIT;
972 }
973
974 /* Prepare and send a batched cancel rpc, it will include count lock handles
975  * of locks given in @head. */
976 int ldlm_cli_cancel_req(struct obd_export *exp, struct list_head *cancels,
977                         int count, int flags)
978 {
979         struct ptlrpc_request *req = NULL;
980         struct obd_import *imp;
981         int free, sent = 0;
982         int rc = 0;
983         ENTRY;
984
985         LASSERT(exp != NULL);
986         LASSERT(count > 0);
987
988         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL, obd_fail_val);
989
990         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
991                 RETURN(count);
992
993         free = ldlm_format_handles_avail(class_exp2cliimp(exp),
994                                          &RQF_LDLM_CANCEL, RCL_CLIENT, 0);
995         if (count > free)
996                 count = free;
997
998         while (1) {
999                 int bufcount;
1000
1001                 imp = class_exp2cliimp(exp);
1002                 if (imp == NULL || imp->imp_invalid) {
1003                         CDEBUG(D_DLMTRACE,
1004                                "skipping cancel on invalid import %p\n", imp);
1005                         RETURN(count);
1006                 }
1007
1008                 req = ptlrpc_request_alloc(imp, &RQF_LDLM_CANCEL);
1009                 if (req == NULL)
1010                         GOTO(out, rc = -ENOMEM);
1011
1012                 bufcount = req_capsule_filled_sizes(&req->rq_pill, RCL_CLIENT);
1013                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT,
1014                                      ldlm_request_bufsize(count, LDLM_CANCEL));
1015
1016                 rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CANCEL);
1017                 if (rc) {
1018                         ptlrpc_request_free(req);
1019                         GOTO(out, rc);
1020                 }
1021                 req->rq_no_resend = 1;
1022                 req->rq_no_delay = 1;
1023
1024                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1025                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1026                 ptlrpc_at_set_req_timeout(req);
1027
1028                 ldlm_cancel_pack(req, cancels, count);
1029
1030                 ptlrpc_request_set_replen(req);
1031                 if (flags & LDLM_FL_ASYNC) {
1032                         ptlrpcd_add_req(req);
1033                         sent = count;
1034                         GOTO(out, 0);
1035                 } else {
1036                         rc = ptlrpc_queue_wait(req);
1037                 }
1038                 if (rc == ESTALE) {
1039                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
1040                                "out of sync -- not fatal\n",
1041                                libcfs_nid2str(req->rq_import->
1042                                               imp_connection->c_peer.nid));
1043                         rc = 0;
1044                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
1045                            req->rq_import_generation == imp->imp_generation) {
1046                         ptlrpc_req_finished(req);
1047                         continue;
1048                 } else if (rc != ELDLM_OK) {
1049                         CERROR("Got rc %d from cancel RPC: canceling "
1050                                "anyway\n", rc);
1051                         break;
1052                 }
1053                 sent = count;
1054                 break;
1055         }
1056
1057         ptlrpc_req_finished(req);
1058         EXIT;
1059 out:
1060         return sent ? sent : rc;
1061 }
1062
1063 static inline struct ldlm_pool *ldlm_imp2pl(struct obd_import *imp)
1064 {
1065         LASSERT(imp != NULL);
1066         return &imp->imp_obd->obd_namespace->ns_pool;
1067 }
1068
1069 /**
1070  * Update client's obd pool related fields with new SLV and Limit from \a req.
1071  */
1072 int ldlm_cli_update_pool(struct ptlrpc_request *req)
1073 {
1074         struct obd_device *obd;
1075         __u64 old_slv, new_slv;
1076         __u32 new_limit;
1077         ENTRY;
1078     
1079         if (unlikely(!req->rq_import || !req->rq_import->imp_obd || 
1080                      !imp_connect_lru_resize(req->rq_import)))
1081         {
1082                 /* 
1083                  * Do nothing for corner cases. 
1084                  */
1085                 RETURN(0);
1086         }
1087
1088         /* 
1089          * In some cases RPC may contain slv and limit zeroed out. This is 
1090          * the case when server does not support lru resize feature. This is
1091          * also possible in some recovery cases when server side reqs have no
1092          * ref to obd export and thus access to server side namespace is no 
1093          * possible. 
1094          */
1095         if (lustre_msg_get_slv(req->rq_repmsg) == 0 || 
1096             lustre_msg_get_limit(req->rq_repmsg) == 0) {
1097                 DEBUG_REQ(D_HA, req, "Zero SLV or Limit found "
1098                           "(SLV: "LPU64", Limit: %u)", 
1099                           lustre_msg_get_slv(req->rq_repmsg), 
1100                           lustre_msg_get_limit(req->rq_repmsg));
1101                 RETURN(0);
1102         }
1103
1104         new_limit = lustre_msg_get_limit(req->rq_repmsg);
1105         new_slv = lustre_msg_get_slv(req->rq_repmsg);
1106         obd = req->rq_import->imp_obd;
1107
1108         /* 
1109          * Set new SLV and Limit to obd fields to make accessible for pool 
1110          * thread. We do not access obd_namespace and pool directly here
1111          * as there is no reliable way to make sure that they are still
1112          * alive in cleanup time. Evil races are possible which may cause
1113          * oops in that time. 
1114          */
1115         write_lock(&obd->obd_pool_lock);
1116         old_slv = obd->obd_pool_slv;
1117         obd->obd_pool_slv = new_slv;
1118         obd->obd_pool_limit = new_limit;
1119         write_unlock(&obd->obd_pool_lock);
1120
1121         RETURN(0);
1122 }
1123 EXPORT_SYMBOL(ldlm_cli_update_pool);
1124
1125 int ldlm_cli_cancel(struct lustre_handle *lockh)
1126 {
1127         struct obd_export *exp;
1128         int avail, flags, count = 1, rc = 0;
1129         struct ldlm_namespace *ns;
1130         struct ldlm_lock *lock;
1131         CFS_LIST_HEAD(cancels);
1132         ENTRY;
1133
1134         /* concurrent cancels on the same handle can happen */
1135         lock = __ldlm_handle2lock(lockh, LDLM_FL_CANCELING);
1136         if (lock == NULL) {
1137                 LDLM_DEBUG_NOLOCK("lock is already being destroyed\n");
1138                 RETURN(0);
1139         }
1140
1141         rc = ldlm_cli_cancel_local(lock);
1142         if (rc < 0 || rc == LDLM_FL_LOCAL_ONLY) {
1143                 LDLM_LOCK_PUT(lock);
1144                 RETURN(rc < 0 ? rc : 0);
1145         }
1146         /* Even if the lock is marked as LDLM_FL_BL_AST, this is a LDLM_CANCEL
1147          * rpc which goes to canceld portal, so we can cancel other lru locks
1148          * here and send them all as one LDLM_CANCEL rpc. */
1149         LASSERT(list_empty(&lock->l_bl_ast));
1150         list_add(&lock->l_bl_ast, &cancels);
1151
1152         exp = lock->l_conn_export;
1153         if (exp_connect_cancelset(exp)) {
1154                 avail = ldlm_format_handles_avail(class_exp2cliimp(exp),
1155                                                   &RQF_LDLM_CANCEL,
1156                                                   RCL_CLIENT, 0);
1157                 LASSERT(avail > 0);
1158
1159                 ns = lock->l_resource->lr_namespace;
1160                 flags = ns_connect_lru_resize(ns) ?
1161                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
1162                 count += ldlm_cancel_lru_local(ns, &cancels, 0, avail - 1,
1163                                                LDLM_FL_BL_AST, flags);
1164         }
1165         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1166         RETURN(0);
1167 }
1168
1169 /* XXX until we will have compound requests and can cut cancels from generic rpc
1170  * we need send cancels with LDLM_FL_BL_AST flag as separate rpc */
1171 static int ldlm_cancel_list(struct list_head *cancels, int count, int flags)
1172 {
1173         CFS_LIST_HEAD(head);
1174         struct ldlm_lock *lock, *next;
1175         int left = 0, bl_ast = 0, rc;
1176
1177         left = count;
1178         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1179                 if (left-- == 0)
1180                         break;
1181
1182                 if (flags & LDLM_FL_LOCAL_ONLY) {
1183                         rc = LDLM_FL_LOCAL_ONLY;
1184                         ldlm_lock_cancel(lock);
1185                 } else {
1186                         rc = ldlm_cli_cancel_local(lock);
1187                 }
1188                 if (!(flags & LDLM_FL_BL_AST) && (rc == LDLM_FL_BL_AST)) {
1189                         LDLM_DEBUG(lock, "Cancel lock separately");
1190                         list_del_init(&lock->l_bl_ast);
1191                         list_add(&lock->l_bl_ast, &head);
1192                         bl_ast ++;
1193                         continue;
1194                 }
1195                 if (rc == LDLM_FL_LOCAL_ONLY) {
1196                         /* CANCEL RPC should not be sent to server. */
1197                         list_del_init(&lock->l_bl_ast);
1198                         LDLM_LOCK_PUT(lock);
1199                         count--;
1200                 }
1201
1202         }
1203         if (bl_ast > 0) {
1204                 count -= bl_ast;
1205                 ldlm_cli_cancel_list(&head, bl_ast, NULL, 0);
1206         }
1207
1208         RETURN(count);
1209 }
1210
1211 /** 
1212  * Callback function for shrink policy. Makes decision whether to keep
1213  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1214  * \a added and number of locks to be preferably canceled \a count.
1215  *
1216  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1217  *
1218  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1219  */
1220 static ldlm_policy_res_t ldlm_cancel_shrink_policy(struct ldlm_namespace *ns,
1221                                                    struct ldlm_lock *lock,
1222                                                    int unused, int added, 
1223                                                    int count)
1224 {
1225         int lock_cost;
1226         __u64 page_nr;
1227
1228         /* 
1229          * Stop lru processing when we reached passed @count or checked all 
1230          * locks in lru. 
1231          */
1232         if (count && added >= count)
1233                 return LDLM_POLICY_KEEP_LOCK;
1234
1235         if (lock->l_resource->lr_type == LDLM_EXTENT) {
1236                 struct ldlm_extent *l_extent;
1237
1238                 /* 
1239                  * For all extent locks cost is 1 + number of pages in
1240                  * their extent. 
1241                  */
1242                 l_extent = &lock->l_policy_data.l_extent;
1243                 page_nr = (l_extent->end - l_extent->start);
1244                 do_div(page_nr, CFS_PAGE_SIZE);
1245
1246 #ifdef __KERNEL__
1247                 /* 
1248                  * XXX: In fact this is evil hack, we can't access inode
1249                  * here. For doing it right we need somehow to have number
1250                  * of covered by lock. This should be fixed later when 10718 
1251                  * is landed. 
1252                  */
1253                 if (lock->l_ast_data != NULL) {
1254                         struct inode *inode = lock->l_ast_data;
1255                         if (page_nr > inode->i_mapping->nrpages)
1256                                 page_nr = inode->i_mapping->nrpages;
1257                 }
1258 #endif
1259                 lock_cost = 1 + page_nr;
1260         } else {
1261                 /* 
1262                  * For all locks which are not extent ones cost is 1 
1263                  */
1264                 lock_cost = 1;
1265         }
1266
1267         /* 
1268          * Keep all expensive locks in lru for the memory pressure time
1269          * cancel policy. They anyways may be canceled by lru resize
1270          * pplicy if they have not small enough CLV. 
1271          */
1272         return lock_cost > ns->ns_shrink_thumb ? 
1273                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1274 }
1275
1276 /**
1277  * Callback function for lru-resize policy. Makes decision whether to keep
1278  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1279  * \a added and number of locks to be preferably canceled \a count.
1280  *
1281  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1282  *
1283  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1284  */
1285 static ldlm_policy_res_t ldlm_cancel_lrur_policy(struct ldlm_namespace *ns,
1286                                                  struct ldlm_lock *lock, 
1287                                                  int unused, int added, 
1288                                                  int count)
1289 {
1290         cfs_time_t cur = cfs_time_current();
1291         struct ldlm_pool *pl = &ns->ns_pool;
1292         __u64 slv, lvf, lv;
1293         cfs_time_t la;
1294
1295         /* 
1296          * Stop lru processing when we reached passed @count or checked all 
1297          * locks in lru.
1298          */
1299         if (count && added >= count)
1300                 return LDLM_POLICY_KEEP_LOCK;
1301
1302         slv = ldlm_pool_get_slv(pl);
1303         lvf = ldlm_pool_get_lvf(pl);
1304         la = cfs_duration_sec(cfs_time_sub(cur, 
1305                               lock->l_last_used));
1306
1307         /* 
1308          * Stop when slv is not yet come from server or lv is smaller than 
1309          * it is.
1310          */
1311         lv = lvf * la * unused;
1312         
1313         /* 
1314          * Inform pool about current CLV to see it via proc. 
1315          */
1316         ldlm_pool_set_clv(pl, lv);
1317         return (slv == 1 || lv < slv) ? 
1318                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1319 }
1320
1321 /**
1322  * Callback function for proc used policy. Makes decision whether to keep
1323  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1324  * \a added and number of locks to be preferably canceled \a count.
1325  *
1326  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1327  *
1328  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1329  */
1330 static ldlm_policy_res_t ldlm_cancel_passed_policy(struct ldlm_namespace *ns,
1331                                                    struct ldlm_lock *lock, 
1332                                                    int unused, int added,
1333                                                    int count)
1334 {
1335         /* 
1336          * Stop lru processing when we reached passed @count or checked all 
1337          * locks in lru. 
1338          */
1339         return (added >= count) ? 
1340                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1341 }
1342
1343 /**
1344  * Callback function for aged policy. Makes decision whether to keep
1345  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1346  * \a added and number of locks to be preferably canceled \a count.
1347  *
1348  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1349  *
1350  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1351  */
1352 static ldlm_policy_res_t ldlm_cancel_aged_policy(struct ldlm_namespace *ns,
1353                                                  struct ldlm_lock *lock, 
1354                                                  int unused, int added,
1355                                                  int count)
1356 {
1357         /* 
1358          * Stop lru processing if young lock is found and we reached passed 
1359          * @count. 
1360          */
1361         return ((added >= count) && 
1362                 cfs_time_before(cfs_time_current(),
1363                                 cfs_time_add(lock->l_last_used,
1364                                              ns->ns_max_age))) ? 
1365                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1366 }
1367
1368 /**
1369  * Callback function for default policy. Makes decision whether to keep
1370  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1371  * \a added and number of locks to be preferably canceled \a count.
1372  *
1373  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1374  *
1375  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1376  */
1377 static ldlm_policy_res_t ldlm_cancel_default_policy(struct ldlm_namespace *ns,
1378                                                     struct ldlm_lock *lock, 
1379                                                     int unused, int added,
1380                                                     int count)
1381 {
1382         /* 
1383          * Stop lru processing when we reached passed @count or checked all 
1384          * locks in lru. 
1385          */
1386         return (added >= count) ? 
1387                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1388 }
1389
1390 typedef ldlm_policy_res_t (*ldlm_cancel_lru_policy_t)(struct ldlm_namespace *, 
1391                                                       struct ldlm_lock *, int, 
1392                                                       int, int);
1393
1394 static ldlm_cancel_lru_policy_t
1395 ldlm_cancel_lru_policy(struct ldlm_namespace *ns, int flags)
1396 {
1397         if (ns_connect_lru_resize(ns)) {
1398                 if (flags & LDLM_CANCEL_SHRINK)
1399                         return ldlm_cancel_shrink_policy;
1400                 else if (flags & LDLM_CANCEL_LRUR)
1401                         return ldlm_cancel_lrur_policy;
1402                 else if (flags & LDLM_CANCEL_PASSED)
1403                         return ldlm_cancel_passed_policy;
1404         } else {
1405                 if (flags & LDLM_CANCEL_AGED)
1406                         return ldlm_cancel_aged_policy;
1407         }
1408         
1409         return ldlm_cancel_default_policy;
1410 }
1411  
1412 /* - Free space in lru for @count new locks,
1413  *   redundant unused locks are canceled locally;
1414  * - also cancel locally unused aged locks;
1415  * - do not cancel more than @max locks;
1416  * - GET the found locks and add them into the @cancels list.
1417  *
1418  * A client lock can be added to the l_bl_ast list only when it is
1419  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
1420  * There are the following use cases: ldlm_cancel_resource_local(),
1421  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
1422  * flag properly. As any attempt to cancel a lock rely on this flag,
1423  * l_bl_ast list is accessed later without any special locking.
1424  *
1425  * Calling policies for enabled lru resize:
1426  * ----------------------------------------
1427  * flags & LDLM_CANCEL_LRUR - use lru resize policy (SLV from server) to
1428  *                            cancel not more than @count locks;
1429  *
1430  * flags & LDLM_CANCEL_PASSED - cancel @count number of old locks (located at
1431  *                              the beginning of lru list);
1432  *
1433  * flags & LDLM_CANCEL_SHRINK - cancel not more than @count locks according to
1434  *                              memory pressre policy function;
1435  *
1436  * flags & LDLM_CANCEL_AGED -   cancel alocks according to "aged policy".
1437  */
1438 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
1439                           int count, int max, int cancel_flags, int flags)
1440 {
1441         ldlm_cancel_lru_policy_t pf;
1442         struct ldlm_lock *lock, *next;
1443         int added = 0, unused;
1444         ENTRY;
1445
1446         spin_lock(&ns->ns_unused_lock);
1447         unused = ns->ns_nr_unused;
1448
1449         if (!ns_connect_lru_resize(ns))
1450                 count += unused - ns->ns_max_unused;
1451
1452         pf = ldlm_cancel_lru_policy(ns, flags);
1453         LASSERT(pf != NULL);
1454         
1455         while (!list_empty(&ns->ns_unused_list)) {
1456                 /* For any flags, stop scanning if @max is reached. */
1457                 if (max && added >= max)
1458                         break;
1459
1460                 list_for_each_entry_safe(lock, next, &ns->ns_unused_list, l_lru){
1461                         /* No locks which got blocking requests. */
1462                         LASSERT(!(lock->l_flags & LDLM_FL_BL_AST));
1463
1464                         /* Somebody is already doing CANCEL. No need in this
1465                          * lock in lru, do not traverse it again. */
1466                         if (!(lock->l_flags & LDLM_FL_CANCELING))
1467                                 break;
1468
1469                         ldlm_lock_remove_from_lru_nolock(lock);
1470                 }
1471                 if (&lock->l_lru == &ns->ns_unused_list)
1472                         break;
1473
1474                 /* Pass the lock through the policy filter and see if it
1475                  * should stay in lru.
1476                  *
1477                  * Even for shrinker policy we stop scanning if
1478                  * we find a lock that should stay in the cache.
1479                  * We should take into account lock age anyway
1480                  * as new lock even if it is small of weight is
1481                  * valuable resource. 
1482                  *
1483                  * That is, for shrinker policy we drop only
1484                  * old locks, but additionally chose them by
1485                  * their weight. Big extent locks will stay in 
1486                  * the cache. */
1487                 if (pf(ns, lock, unused, added, count) == LDLM_POLICY_KEEP_LOCK)
1488                         break;
1489
1490                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
1491                 spin_unlock(&ns->ns_unused_lock);
1492
1493                 lock_res_and_lock(lock);
1494                 /* Check flags again under the lock. */
1495                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1496                     (ldlm_lock_remove_from_lru(lock) == 0)) {
1497                         /* other thread is removing lock from lru or
1498                          * somebody is already doing CANCEL or
1499                          * there is a blocking request which will send
1500                          * cancel by itseft or the lock is matched
1501                          * is already not unused. */
1502                         unlock_res_and_lock(lock);
1503                         LDLM_LOCK_PUT(lock);
1504                         spin_lock(&ns->ns_unused_lock);
1505                         continue;
1506                 }
1507                 LASSERT(!lock->l_readers && !lock->l_writers);
1508
1509                 /* If we have chosen to cancel this lock voluntarily, we
1510                  * better send cancel notification to server, so that it
1511                  * frees appropriate state. This might lead to a race 
1512                  * where while we are doing cancel here, server is also 
1513                  * silently cancelling this lock. */
1514                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1515
1516                 /* Setting the CBPENDING flag is a little misleading,
1517                  * but prevents an important race; namely, once
1518                  * CBPENDING is set, the lock can accumulate no more
1519                  * readers/writers. Since readers and writers are
1520                  * already zero here, ldlm_lock_decref() won't see
1521                  * this flag and call l_blocking_ast */
1522                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1523
1524                 /* We can't re-add to l_lru as it confuses the
1525                  * refcounting in ldlm_lock_remove_from_lru() if an AST
1526                  * arrives after we drop ns_lock below. We use l_bl_ast
1527                  * and can't use l_pending_chain as it is used both on
1528                  * server and client nevertheless bug 5666 says it is
1529                  * used only on server */
1530                 LASSERT(list_empty(&lock->l_bl_ast));
1531                 list_add(&lock->l_bl_ast, cancels);
1532                 unlock_res_and_lock(lock);
1533                 spin_lock(&ns->ns_unused_lock);
1534                 added++;
1535                 unused--;
1536         }
1537         spin_unlock(&ns->ns_unused_lock);
1538         RETURN(ldlm_cancel_list(cancels, added, cancel_flags));
1539 }
1540
1541 /* Returns number of locks which could be canceled next time when 
1542  * ldlm_cancel_lru() is called. Used from locks pool shrinker. */
1543 int ldlm_cancel_lru_estimate(struct ldlm_namespace *ns,
1544                              int count, int max, int flags)
1545 {
1546         ldlm_cancel_lru_policy_t pf;
1547         struct ldlm_lock *lock;
1548         int added = 0, unused;
1549         ENTRY;
1550
1551         pf = ldlm_cancel_lru_policy(ns, flags);
1552         LASSERT(pf != NULL);
1553         spin_lock(&ns->ns_unused_lock);
1554         unused = ns->ns_nr_unused;
1555
1556         list_for_each_entry(lock, &ns->ns_unused_list, l_lru) {
1557                 /* For any flags, stop scanning if @max is reached. */
1558                 if (max && added >= max)
1559                         break;
1560
1561                 /* Somebody is already doing CANCEL or there is a
1562                  * blocking request will send cancel. Let's not count 
1563                  * this lock. */
1564                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1565                     (lock->l_flags & LDLM_FL_BL_AST)) 
1566                         continue;
1567
1568                 /* Pass the lock through the policy filter and see if it
1569                  * should stay in lru. */
1570                 if (pf(ns, lock, unused, added, count) == LDLM_POLICY_KEEP_LOCK)
1571                         break;
1572
1573                 added++;
1574                 unused--;
1575         }
1576         spin_unlock(&ns->ns_unused_lock);
1577         RETURN(added);
1578 }
1579
1580 /* when called with LDLM_ASYNC the blocking callback will be handled
1581  * in a thread and this function will return after the thread has been
1582  * asked to call the callback.  when called with LDLM_SYNC the blocking
1583  * callback will be performed in this function. */
1584 int ldlm_cancel_lru(struct ldlm_namespace *ns, int nr, ldlm_sync_t sync, 
1585                     int flags)
1586 {
1587         CFS_LIST_HEAD(cancels);
1588         int count, rc;
1589         ENTRY;
1590
1591 #ifndef __KERNEL__
1592         sync = LDLM_SYNC; /* force to be sync in user space */
1593 #endif
1594         count = ldlm_cancel_lru_local(ns, &cancels, nr, 0, 0, flags);
1595         if (sync == LDLM_ASYNC) {
1596                 rc = ldlm_bl_to_thread_list(ns, NULL, &cancels, count);
1597                 if (rc == 0)
1598                         RETURN(count);
1599         }
1600
1601         /* If an error occured in ASYNC mode, or
1602          * this is SYNC mode, cancel the list. */
1603         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1604         RETURN(count);
1605 }
1606
1607 /* Find and cancel locally unused locks found on resource, matched to the
1608  * given policy, mode. GET the found locks and add them into the @cancels
1609  * list. */
1610 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1611                                struct list_head *cancels,
1612                                ldlm_policy_data_t *policy,
1613                                ldlm_mode_t mode, int lock_flags,
1614                                int cancel_flags, void *opaque)
1615 {
1616         struct ldlm_lock *lock;
1617         int count = 0;
1618         ENTRY;
1619
1620         lock_res(res);
1621         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1622                 if (opaque != NULL && lock->l_ast_data != opaque) {
1623                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1624                                    lock->l_ast_data, opaque);
1625                         //LBUG();
1626                         continue;
1627                 }
1628
1629                 if (lock->l_readers || lock->l_writers) {
1630                         if (cancel_flags & LDLM_FL_WARN) {
1631                                 LDLM_ERROR(lock, "lock in use");
1632                                 //LBUG();
1633                         }
1634                         continue;
1635                 }
1636
1637                 /* If somebody is already doing CANCEL, or blocking ast came,
1638                  * skip this lock. */
1639                 if (lock->l_flags & LDLM_FL_BL_AST || 
1640                     lock->l_flags & LDLM_FL_CANCELING)
1641                         continue;
1642
1643                 if (lockmode_compat(lock->l_granted_mode, mode))
1644                         continue;
1645
1646                 /* If policy is given and this is IBITS lock, add to list only
1647                  * those locks that match by policy. */
1648                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1649                     !(lock->l_policy_data.l_inodebits.bits &
1650                       policy->l_inodebits.bits))
1651                         continue;
1652
1653                 /* See CBPENDING comment in ldlm_cancel_lru */
1654                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1655                                  lock_flags;
1656
1657                 LASSERT(list_empty(&lock->l_bl_ast));
1658                 list_add(&lock->l_bl_ast, cancels);
1659                 LDLM_LOCK_GET(lock);
1660                 count++;
1661         }
1662         unlock_res(res);
1663
1664         RETURN(ldlm_cancel_list(cancels, count, cancel_flags));
1665 }
1666
1667 /* If @req is NULL, send CANCEL request to server with handles of locks 
1668  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests 
1669  * separately per lock.
1670  * If @req is not NULL, put handles of locks in @cancels into the request 
1671  * buffer at the offset @off.
1672  * Destroy @cancels at the end. */
1673 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1674                          struct ptlrpc_request *req, int flags)
1675 {
1676         struct ldlm_lock *lock;
1677         int res = 0;
1678         ENTRY;
1679
1680         if (list_empty(cancels) || count == 0)
1681                 RETURN(0);
1682         
1683         /* XXX: requests (both batched and not) could be sent in parallel. 
1684          * Usually it is enough to have just 1 RPC, but it is possible that
1685          * there are to many locks to be cancelled in LRU or on a resource.
1686          * It would also speed up the case when the server does not support
1687          * the feature. */
1688         while (count > 0) {
1689                 LASSERT(!list_empty(cancels));
1690                 lock = list_entry(cancels->next, struct ldlm_lock, l_bl_ast);
1691                 LASSERT(lock->l_conn_export);
1692
1693                 if (exp_connect_cancelset(lock->l_conn_export)) {
1694                         res = count;
1695                         if (req)
1696                                 ldlm_cancel_pack(req, cancels, count);
1697                         else
1698                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1699                                                           cancels, count,
1700                                                           flags);
1701                 } else {
1702                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1703                                                   cancels, 1, flags);
1704                 }
1705
1706                 if (res < 0) {
1707                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1708                         res = count;
1709                 }
1710
1711                 count -= res;
1712                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1713         }
1714         LASSERT(count == 0);
1715         RETURN(0);
1716 }
1717
1718 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1719                                     const struct ldlm_res_id *res_id,
1720                                     ldlm_policy_data_t *policy,
1721                                     ldlm_mode_t mode, int flags, void *opaque)
1722 {
1723         struct ldlm_resource *res;
1724         CFS_LIST_HEAD(cancels);
1725         int count;
1726         int rc;
1727         ENTRY;
1728
1729         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1730         if (res == NULL) {
1731                 /* This is not a problem. */
1732                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id->name[0]);
1733                 RETURN(0);
1734         }
1735
1736         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
1737                                            0, flags, opaque);
1738         rc = ldlm_cli_cancel_list(&cancels, count, NULL, flags);
1739         if (rc != ELDLM_OK)
1740                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1741
1742         ldlm_resource_putref(res);
1743         RETURN(0);
1744 }
1745
1746 static inline int have_no_nsresource(struct ldlm_namespace *ns)
1747 {
1748         int no_resource = 0;
1749
1750         spin_lock(&ns->ns_hash_lock);
1751         if (ns->ns_resources == 0)
1752                 no_resource = 1;
1753         spin_unlock(&ns->ns_hash_lock);
1754
1755         RETURN(no_resource);
1756 }
1757
1758 /* Cancel all locks on a namespace (or a specific resource, if given)
1759  * that have 0 readers/writers.
1760  *
1761  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
1762  * to notify the server. */
1763 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1764                            const struct ldlm_res_id *res_id,
1765                            int flags, void *opaque)
1766 {
1767         int i;
1768         ENTRY;
1769
1770         if (ns == NULL)
1771                 RETURN(ELDLM_OK);
1772
1773         if (res_id)
1774                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
1775                                                        LCK_MINMODE, flags,
1776                                                        opaque));
1777
1778         spin_lock(&ns->ns_hash_lock);
1779         for (i = 0; i < RES_HASH_SIZE; i++) {
1780                 struct list_head *tmp;
1781                 tmp = ns->ns_hash[i].next;
1782                 while (tmp != &(ns->ns_hash[i])) {
1783                         struct ldlm_resource *res;
1784                         int rc;
1785
1786                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1787                         ldlm_resource_getref(res);
1788                         spin_unlock(&ns->ns_hash_lock);
1789
1790                         rc = ldlm_cli_cancel_unused_resource(ns, &res->lr_name,
1791                                                              NULL, LCK_MINMODE,
1792                                                              flags, opaque);
1793
1794                         if (rc)
1795                                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1796                                        res->lr_name.name[0], rc);
1797
1798                         spin_lock(&ns->ns_hash_lock);
1799                         tmp = tmp->next;
1800                         ldlm_resource_putref_locked(res);
1801                 }
1802         }
1803         spin_unlock(&ns->ns_hash_lock);
1804
1805         RETURN(ELDLM_OK);
1806 }
1807
1808 /* join/split resource locks to/from lru list */
1809 int ldlm_cli_join_lru(struct ldlm_namespace *ns,
1810                       const struct ldlm_res_id *res_id, int join)
1811 {
1812         struct ldlm_resource *res;
1813         struct ldlm_lock *lock, *n;
1814         int count = 0;
1815         ENTRY;
1816
1817         LASSERT(ns_is_client(ns));
1818
1819         res = ldlm_resource_get(ns, NULL, res_id, LDLM_EXTENT, 0);
1820         if (res == NULL)
1821                 RETURN(count);
1822         LASSERT(res->lr_type == LDLM_EXTENT);
1823
1824         lock_res(res);
1825         if (!join)
1826                 goto split;
1827
1828         list_for_each_entry_safe (lock, n, &res->lr_granted, l_res_link) {
1829                 if (list_empty(&lock->l_lru) &&
1830                     !lock->l_readers && !lock->l_writers &&
1831                     !(lock->l_flags & LDLM_FL_LOCAL) &&
1832                     !(lock->l_flags & LDLM_FL_CBPENDING) &&
1833                     !(lock->l_flags & LDLM_FL_BL_AST)) {
1834                         ldlm_lock_add_to_lru(lock);
1835                         lock->l_flags &= ~LDLM_FL_NO_LRU;
1836                         LDLM_DEBUG(lock, "join lock to lru");
1837                         count++;
1838                 }
1839         }
1840         goto unlock;
1841 split:
1842         spin_lock(&ns->ns_unused_lock);
1843         list_for_each_entry_safe (lock, n, &ns->ns_unused_list, l_lru) {
1844                 if (lock->l_resource == res) {
1845                         ldlm_lock_remove_from_lru_nolock(lock);
1846                         lock->l_flags |= LDLM_FL_NO_LRU;
1847                         LDLM_DEBUG(lock, "split lock from lru");
1848                         count++;
1849                 }
1850         }
1851         spin_unlock(&ns->ns_unused_lock);
1852 unlock:
1853         unlock_res(res);
1854         ldlm_resource_putref(res);
1855         RETURN(count);
1856 }
1857
1858 /* Lock iterators. */
1859
1860 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1861                           void *closure)
1862 {
1863         struct list_head *tmp, *next;
1864         struct ldlm_lock *lock;
1865         int rc = LDLM_ITER_CONTINUE;
1866
1867         ENTRY;
1868
1869         if (!res)
1870                 RETURN(LDLM_ITER_CONTINUE);
1871
1872         lock_res(res);
1873         list_for_each_safe(tmp, next, &res->lr_granted) {
1874                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1875
1876                 if (iter(lock, closure) == LDLM_ITER_STOP)
1877                         GOTO(out, rc = LDLM_ITER_STOP);
1878         }
1879
1880         list_for_each_safe(tmp, next, &res->lr_converting) {
1881                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1882
1883                 if (iter(lock, closure) == LDLM_ITER_STOP)
1884                         GOTO(out, rc = LDLM_ITER_STOP);
1885         }
1886
1887         list_for_each_safe(tmp, next, &res->lr_waiting) {
1888                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1889
1890                 if (iter(lock, closure) == LDLM_ITER_STOP)
1891                         GOTO(out, rc = LDLM_ITER_STOP);
1892         }
1893  out:
1894         unlock_res(res);
1895         RETURN(rc);
1896 }
1897
1898 struct iter_helper_data {
1899         ldlm_iterator_t iter;
1900         void *closure;
1901 };
1902
1903 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1904 {
1905         struct iter_helper_data *helper = closure;
1906         return helper->iter(lock, helper->closure);
1907 }
1908
1909 static int ldlm_res_iter_helper(struct ldlm_resource *res, void *closure)
1910 {
1911         return ldlm_resource_foreach(res, ldlm_iter_helper, closure);
1912 }
1913
1914 int ldlm_namespace_foreach(struct ldlm_namespace *ns, ldlm_iterator_t iter,
1915                            void *closure)
1916 {
1917         struct iter_helper_data helper = { iter: iter, closure: closure };
1918         return ldlm_namespace_foreach_res(ns, ldlm_res_iter_helper, &helper);
1919 }
1920
1921 int ldlm_namespace_foreach_res(struct ldlm_namespace *ns,
1922                                ldlm_res_iterator_t iter, void *closure)
1923 {
1924         int i, rc = LDLM_ITER_CONTINUE;
1925         struct ldlm_resource *res;
1926         struct list_head *tmp;
1927
1928         ENTRY;
1929         spin_lock(&ns->ns_hash_lock);
1930         for (i = 0; i < RES_HASH_SIZE; i++) {
1931                 tmp = ns->ns_hash[i].next;
1932                 while (tmp != &(ns->ns_hash[i])) {
1933                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1934                         ldlm_resource_getref(res);
1935                         spin_unlock(&ns->ns_hash_lock);
1936
1937                         rc = iter(res, closure);
1938
1939                         spin_lock(&ns->ns_hash_lock);
1940                         tmp = tmp->next;
1941                         ldlm_resource_putref_locked(res);
1942                         if (rc == LDLM_ITER_STOP)
1943                                 GOTO(out, rc);
1944                 }
1945         }
1946  out:
1947         spin_unlock(&ns->ns_hash_lock);
1948         RETURN(rc);
1949 }
1950
1951 /* non-blocking function to manipulate a lock whose cb_data is being put away.*/
1952 void ldlm_resource_iterate(struct ldlm_namespace *ns,
1953                            const struct ldlm_res_id *res_id,
1954                            ldlm_iterator_t iter, void *data)
1955 {
1956         struct ldlm_resource *res;
1957         ENTRY;
1958
1959         if (ns == NULL) {
1960                 CERROR("must pass in namespace\n");
1961                 LBUG();
1962         }
1963
1964         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1965         if (res == NULL) {
1966                 EXIT;
1967                 return;
1968         }
1969
1970         ldlm_resource_foreach(res, iter, data);
1971         ldlm_resource_putref(res);
1972         EXIT;
1973 }
1974
1975 /* Lock replay */
1976
1977 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
1978 {
1979         struct list_head *list = closure;
1980
1981         /* we use l_pending_chain here, because it's unused on clients. */
1982         LASSERTF(list_empty(&lock->l_pending_chain),"lock %p next %p prev %p\n",
1983                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
1984         /* bug 9573: don't replay locks left after eviction */
1985         if (!(lock->l_flags & LDLM_FL_FAILED))
1986                 list_add(&lock->l_pending_chain, list);
1987         return LDLM_ITER_CONTINUE;
1988 }
1989
1990 static int replay_lock_interpret(struct ptlrpc_request *req,
1991                                  struct ldlm_async_args *aa, int rc)
1992 {
1993         struct lustre_handle  old_hash_key;
1994         struct ldlm_lock     *lock;
1995         struct ldlm_reply    *reply;
1996         struct obd_export    *exp;
1997
1998         ENTRY;
1999         atomic_dec(&req->rq_import->imp_replay_inflight);
2000         if (rc != ELDLM_OK)
2001                 GOTO(out, rc);
2002
2003
2004         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
2005         if (reply == NULL)
2006                 GOTO(out, rc = -EPROTO);
2007
2008         lock = ldlm_handle2lock(&aa->lock_handle);
2009         if (!lock) {
2010                 CERROR("received replay ack for unknown local cookie "LPX64
2011                        " remote cookie "LPX64 " from server %s id %s\n",
2012                        aa->lock_handle.cookie, reply->lock_handle.cookie,
2013                        req->rq_export->exp_client_uuid.uuid,
2014                        libcfs_id2str(req->rq_peer));
2015                 GOTO(out, rc = -ESTALE);
2016         }
2017
2018         old_hash_key = lock->l_remote_handle;
2019         lock->l_remote_handle = reply->lock_handle;
2020
2021         /* Key change rehash lock in per-export hash with new key */
2022         exp = req->rq_export;
2023         if (exp && exp->exp_lock_hash)
2024                 lustre_hash_rehash_key(exp->exp_lock_hash, &old_hash_key,
2025                                        &lock->l_remote_handle,
2026                                        &lock->l_exp_hash);
2027
2028         LDLM_DEBUG(lock, "replayed lock:");
2029         ptlrpc_import_recovery_state_machine(req->rq_import);
2030         LDLM_LOCK_PUT(lock);
2031 out:
2032         if (rc != ELDLM_OK)
2033                 ptlrpc_connect_import(req->rq_import, NULL);
2034
2035         RETURN(rc);
2036 }
2037
2038 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
2039 {
2040         struct ptlrpc_request *req;
2041         struct ldlm_async_args *aa;
2042         struct ldlm_request   *body;
2043         int flags;
2044         ENTRY;
2045
2046
2047         /* Bug 11974: Do not replay a lock which is actively being canceled */
2048         if (lock->l_flags & LDLM_FL_CANCELING) {
2049                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
2050                 RETURN(0);
2051         }
2052
2053         /* If this is reply-less callback lock, we cannot replay it, since
2054          * server might have long dropped it, but notification of that event was
2055          * lost by network. (and server granted conflicting lock already) */
2056         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
2057                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
2058                 ldlm_lock_cancel(lock);
2059                 RETURN(0);
2060         }
2061         /*
2062          * If granted mode matches the requested mode, this lock is granted.
2063          *
2064          * If they differ, but we have a granted mode, then we were granted
2065          * one mode and now want another: ergo, converting.
2066          *
2067          * If we haven't been granted anything and are on a resource list,
2068          * then we're blocked/waiting.
2069          *
2070          * If we haven't been granted anything and we're NOT on a resource list,
2071          * then we haven't got a reply yet and don't have a known disposition.
2072          * This happens whenever a lock enqueue is the request that triggers
2073          * recovery.
2074          */
2075         if (lock->l_granted_mode == lock->l_req_mode)
2076                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
2077         else if (lock->l_granted_mode)
2078                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
2079         else if (!list_empty(&lock->l_res_link))
2080                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
2081         else
2082                 flags = LDLM_FL_REPLAY;
2083
2084         req = ptlrpc_request_alloc_pack(imp, &RQF_LDLM_ENQUEUE,
2085                                         LUSTRE_DLM_VERSION, LDLM_ENQUEUE);
2086         if (req == NULL)
2087                 RETURN(-ENOMEM);
2088
2089         /* We're part of recovery, so don't wait for it. */
2090         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
2091
2092         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2093         ldlm_lock2desc(lock, &body->lock_desc);
2094         body->lock_flags = flags;
2095
2096         ldlm_lock2handle(lock, &body->lock_handle[0]);
2097         if (lock->l_lvb_len != 0) {
2098                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_ENQUEUE_LVB);
2099                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
2100                                      lock->l_lvb_len);
2101         }
2102         ptlrpc_request_set_replen(req);
2103         /* notify the server we've replayed all requests.
2104          * also, we mark the request to be put on a dedicated
2105          * queue to be processed after all request replayes.
2106          * bug 6063 */
2107         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
2108
2109         LDLM_DEBUG(lock, "replaying lock:");
2110
2111         atomic_inc(&req->rq_import->imp_replay_inflight);
2112         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2113         aa = ptlrpc_req_async_args(req);
2114         aa->lock_handle = body->lock_handle[0];
2115         req->rq_interpret_reply = replay_lock_interpret;
2116         ptlrpcd_add_req(req);
2117
2118         RETURN(0);
2119 }
2120
2121 int ldlm_replay_locks(struct obd_import *imp)
2122 {
2123         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
2124         CFS_LIST_HEAD(list);
2125         struct ldlm_lock *lock, *next;
2126         int rc = 0;
2127
2128         ENTRY;
2129
2130         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
2131
2132         /* ensure this doesn't fall to 0 before all have been queued */
2133         atomic_inc(&imp->imp_replay_inflight);
2134
2135         (void)ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
2136
2137         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
2138                 list_del_init(&lock->l_pending_chain);
2139                 if (rc)
2140                         continue; /* or try to do the rest? */
2141                 rc = replay_one_lock(imp, lock);
2142         }
2143
2144         atomic_dec(&imp->imp_replay_inflight);
2145
2146         RETURN(rc);
2147 }