staging: lustre: ldlm: Fix overlong lines
[pandora-kernel.git] / drivers / staging / lustre / lustre / ldlm / ldlm_lock.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2010, 2012, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ldlm/ldlm_lock.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42 #define DEBUG_SUBSYSTEM S_LDLM
43
44 #include "../../include/linux/libcfs/libcfs.h"
45 #include "../include/lustre_intent.h"
46 #include "../include/obd_class.h"
47 #include "ldlm_internal.h"
48
49 /* lock types */
50 char *ldlm_lockname[] = {
51         [0]             = "--",
52         [LCK_EX]        = "EX",
53         [LCK_PW]        = "PW",
54         [LCK_PR]        = "PR",
55         [LCK_CW]        = "CW",
56         [LCK_CR]        = "CR",
57         [LCK_NL]        = "NL",
58         [LCK_GROUP]     = "GROUP",
59         [LCK_COS]       = "COS",
60 };
61 EXPORT_SYMBOL(ldlm_lockname);
62
63 char *ldlm_typename[] = {
64         [LDLM_PLAIN]    = "PLN",
65         [LDLM_EXTENT]   = "EXT",
66         [LDLM_FLOCK]    = "FLK",
67         [LDLM_IBITS]    = "IBT",
68 };
69 EXPORT_SYMBOL(ldlm_typename);
70
71 static ldlm_policy_wire_to_local_t ldlm_policy_wire18_to_local[] = {
72         [LDLM_PLAIN - LDLM_MIN_TYPE]    = ldlm_plain_policy_wire_to_local,
73         [LDLM_EXTENT - LDLM_MIN_TYPE]   = ldlm_extent_policy_wire_to_local,
74         [LDLM_FLOCK - LDLM_MIN_TYPE]    = ldlm_flock_policy_wire18_to_local,
75         [LDLM_IBITS - LDLM_MIN_TYPE]    = ldlm_ibits_policy_wire_to_local,
76 };
77
78 static ldlm_policy_wire_to_local_t ldlm_policy_wire21_to_local[] = {
79         [LDLM_PLAIN - LDLM_MIN_TYPE]    = ldlm_plain_policy_wire_to_local,
80         [LDLM_EXTENT - LDLM_MIN_TYPE]   = ldlm_extent_policy_wire_to_local,
81         [LDLM_FLOCK - LDLM_MIN_TYPE]    = ldlm_flock_policy_wire21_to_local,
82         [LDLM_IBITS - LDLM_MIN_TYPE]    = ldlm_ibits_policy_wire_to_local,
83 };
84
85 static ldlm_policy_local_to_wire_t ldlm_policy_local_to_wire[] = {
86         [LDLM_PLAIN - LDLM_MIN_TYPE]    = ldlm_plain_policy_local_to_wire,
87         [LDLM_EXTENT - LDLM_MIN_TYPE]   = ldlm_extent_policy_local_to_wire,
88         [LDLM_FLOCK - LDLM_MIN_TYPE]    = ldlm_flock_policy_local_to_wire,
89         [LDLM_IBITS - LDLM_MIN_TYPE]    = ldlm_ibits_policy_local_to_wire,
90 };
91
92 /**
93  * Converts lock policy from local format to on the wire lock_desc format
94  */
95 void ldlm_convert_policy_to_wire(ldlm_type_t type,
96                                  const ldlm_policy_data_t *lpolicy,
97                                  ldlm_wire_policy_data_t *wpolicy)
98 {
99         ldlm_policy_local_to_wire_t convert;
100
101         convert = ldlm_policy_local_to_wire[type - LDLM_MIN_TYPE];
102
103         convert(lpolicy, wpolicy);
104 }
105
106 /**
107  * Converts lock policy from on the wire lock_desc format to local format
108  */
109 void ldlm_convert_policy_to_local(struct obd_export *exp, ldlm_type_t type,
110                                   const ldlm_wire_policy_data_t *wpolicy,
111                                   ldlm_policy_data_t *lpolicy)
112 {
113         ldlm_policy_wire_to_local_t convert;
114         int new_client;
115
116         /** some badness for 2.0.0 clients, but 2.0.0 isn't supported */
117         new_client = (exp_connect_flags(exp) & OBD_CONNECT_FULL20) != 0;
118         if (new_client)
119                 convert = ldlm_policy_wire21_to_local[type - LDLM_MIN_TYPE];
120         else
121                 convert = ldlm_policy_wire18_to_local[type - LDLM_MIN_TYPE];
122
123         convert(wpolicy, lpolicy);
124 }
125
126 char *ldlm_it2str(int it)
127 {
128         switch (it) {
129         case IT_OPEN:
130                 return "open";
131         case IT_CREAT:
132                 return "creat";
133         case (IT_OPEN | IT_CREAT):
134                 return "open|creat";
135         case IT_READDIR:
136                 return "readdir";
137         case IT_GETATTR:
138                 return "getattr";
139         case IT_LOOKUP:
140                 return "lookup";
141         case IT_UNLINK:
142                 return "unlink";
143         case IT_GETXATTR:
144                 return "getxattr";
145         case IT_LAYOUT:
146                 return "layout";
147         default:
148                 CERROR("Unknown intent %d\n", it);
149                 return "UNKNOWN";
150         }
151 }
152 EXPORT_SYMBOL(ldlm_it2str);
153
154 extern struct kmem_cache *ldlm_lock_slab;
155
156
157 void ldlm_register_intent(struct ldlm_namespace *ns, ldlm_res_policy arg)
158 {
159         ns->ns_policy = arg;
160 }
161 EXPORT_SYMBOL(ldlm_register_intent);
162
163 /*
164  * REFCOUNTED LOCK OBJECTS
165  */
166
167
168 /**
169  * Get a reference on a lock.
170  *
171  * Lock refcounts, during creation:
172  *   - one special one for allocation, dec'd only once in destroy
173  *   - one for being a lock that's in-use
174  *   - one for the addref associated with a new lock
175  */
176 struct ldlm_lock *ldlm_lock_get(struct ldlm_lock *lock)
177 {
178         atomic_inc(&lock->l_refc);
179         return lock;
180 }
181 EXPORT_SYMBOL(ldlm_lock_get);
182
183 /**
184  * Release lock reference.
185  *
186  * Also frees the lock if it was last reference.
187  */
188 void ldlm_lock_put(struct ldlm_lock *lock)
189 {
190         LASSERT(lock->l_resource != LP_POISON);
191         LASSERT(atomic_read(&lock->l_refc) > 0);
192         if (atomic_dec_and_test(&lock->l_refc)) {
193                 struct ldlm_resource *res;
194
195                 LDLM_DEBUG(lock,
196                            "final lock_put on destroyed lock, freeing it.");
197
198                 res = lock->l_resource;
199                 LASSERT(lock->l_flags & LDLM_FL_DESTROYED);
200                 LASSERT(list_empty(&lock->l_res_link));
201                 LASSERT(list_empty(&lock->l_pending_chain));
202
203                 lprocfs_counter_decr(ldlm_res_to_ns(res)->ns_stats,
204                                      LDLM_NSS_LOCKS);
205                 lu_ref_del(&res->lr_reference, "lock", lock);
206                 ldlm_resource_putref(res);
207                 lock->l_resource = NULL;
208                 if (lock->l_export) {
209                         class_export_lock_put(lock->l_export, lock);
210                         lock->l_export = NULL;
211                 }
212
213                 if (lock->l_lvb_data != NULL)
214                         OBD_FREE(lock->l_lvb_data, lock->l_lvb_len);
215
216                 ldlm_interval_free(ldlm_interval_detach(lock));
217                 lu_ref_fini(&lock->l_reference);
218                 OBD_FREE_RCU(lock, sizeof(*lock), &lock->l_handle);
219         }
220 }
221 EXPORT_SYMBOL(ldlm_lock_put);
222
223 /**
224  * Removes LDLM lock \a lock from LRU. Assumes LRU is already locked.
225  */
226 int ldlm_lock_remove_from_lru_nolock(struct ldlm_lock *lock)
227 {
228         int rc = 0;
229
230         if (!list_empty(&lock->l_lru)) {
231                 struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
232
233                 LASSERT(lock->l_resource->lr_type != LDLM_FLOCK);
234                 list_del_init(&lock->l_lru);
235                 LASSERT(ns->ns_nr_unused > 0);
236                 ns->ns_nr_unused--;
237                 rc = 1;
238         }
239         return rc;
240 }
241
242 /**
243  * Removes LDLM lock \a lock from LRU. Obtains the LRU lock first.
244  */
245 int ldlm_lock_remove_from_lru(struct ldlm_lock *lock)
246 {
247         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
248         int rc;
249
250         if (lock->l_flags & LDLM_FL_NS_SRV) {
251                 LASSERT(list_empty(&lock->l_lru));
252                 return 0;
253         }
254
255         spin_lock(&ns->ns_lock);
256         rc = ldlm_lock_remove_from_lru_nolock(lock);
257         spin_unlock(&ns->ns_lock);
258         return rc;
259 }
260
261 /**
262  * Adds LDLM lock \a lock to namespace LRU. Assumes LRU is already locked.
263  */
264 void ldlm_lock_add_to_lru_nolock(struct ldlm_lock *lock)
265 {
266         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
267
268         lock->l_last_used = cfs_time_current();
269         LASSERT(list_empty(&lock->l_lru));
270         LASSERT(lock->l_resource->lr_type != LDLM_FLOCK);
271         list_add_tail(&lock->l_lru, &ns->ns_unused_list);
272         if (lock->l_flags & LDLM_FL_SKIPPED)
273                 lock->l_flags &= ~LDLM_FL_SKIPPED;
274         LASSERT(ns->ns_nr_unused >= 0);
275         ns->ns_nr_unused++;
276 }
277
278 /**
279  * Adds LDLM lock \a lock to namespace LRU. Obtains necessary LRU locks
280  * first.
281  */
282 void ldlm_lock_add_to_lru(struct ldlm_lock *lock)
283 {
284         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
285
286         spin_lock(&ns->ns_lock);
287         ldlm_lock_add_to_lru_nolock(lock);
288         spin_unlock(&ns->ns_lock);
289 }
290
291 /**
292  * Moves LDLM lock \a lock that is already in namespace LRU to the tail of
293  * the LRU. Performs necessary LRU locking
294  */
295 void ldlm_lock_touch_in_lru(struct ldlm_lock *lock)
296 {
297         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
298
299         if (lock->l_flags & LDLM_FL_NS_SRV) {
300                 LASSERT(list_empty(&lock->l_lru));
301                 return;
302         }
303
304         spin_lock(&ns->ns_lock);
305         if (!list_empty(&lock->l_lru)) {
306                 ldlm_lock_remove_from_lru_nolock(lock);
307                 ldlm_lock_add_to_lru_nolock(lock);
308         }
309         spin_unlock(&ns->ns_lock);
310 }
311
312 /**
313  * Helper to destroy a locked lock.
314  *
315  * Used by ldlm_lock_destroy and ldlm_lock_destroy_nolock
316  * Must be called with l_lock and lr_lock held.
317  *
318  * Does not actually free the lock data, but rather marks the lock as
319  * destroyed by setting l_destroyed field in the lock to 1.  Destroys a
320  * handle->lock association too, so that the lock can no longer be found
321  * and removes the lock from LRU list.  Actual lock freeing occurs when
322  * last lock reference goes away.
323  *
324  * Original comment (of some historical value):
325  * This used to have a 'strict' flag, which recovery would use to mark an
326  * in-use lock as needing-to-die.  Lest I am ever tempted to put it back, I
327  * shall explain why it's gone: with the new hash table scheme, once you call
328  * ldlm_lock_destroy, you can never drop your final references on this lock.
329  * Because it's not in the hash table anymore.  -phil
330  */
331 int ldlm_lock_destroy_internal(struct ldlm_lock *lock)
332 {
333         if (lock->l_readers || lock->l_writers) {
334                 LDLM_ERROR(lock, "lock still has references");
335                 LBUG();
336         }
337
338         if (!list_empty(&lock->l_res_link)) {
339                 LDLM_ERROR(lock, "lock still on resource");
340                 LBUG();
341         }
342
343         if (lock->l_flags & LDLM_FL_DESTROYED) {
344                 LASSERT(list_empty(&lock->l_lru));
345                 return 0;
346         }
347         lock->l_flags |= LDLM_FL_DESTROYED;
348
349         if (lock->l_export && lock->l_export->exp_lock_hash) {
350                 /* NB: it's safe to call cfs_hash_del() even lock isn't
351                  * in exp_lock_hash. */
352                 /* In the function below, .hs_keycmp resolves to
353                  * ldlm_export_lock_keycmp() */
354                 /* coverity[overrun-buffer-val] */
355                 cfs_hash_del(lock->l_export->exp_lock_hash,
356                              &lock->l_remote_handle, &lock->l_exp_hash);
357         }
358
359         ldlm_lock_remove_from_lru(lock);
360         class_handle_unhash(&lock->l_handle);
361
362 #if 0
363         /* Wake anyone waiting for this lock */
364         /* FIXME: I should probably add yet another flag, instead of using
365          * l_export to only call this on clients */
366         if (lock->l_export)
367                 class_export_put(lock->l_export);
368         lock->l_export = NULL;
369         if (lock->l_export && lock->l_completion_ast)
370                 lock->l_completion_ast(lock, 0);
371 #endif
372         return 1;
373 }
374
375 /**
376  * Destroys a LDLM lock \a lock. Performs necessary locking first.
377  */
378 void ldlm_lock_destroy(struct ldlm_lock *lock)
379 {
380         int first;
381
382         lock_res_and_lock(lock);
383         first = ldlm_lock_destroy_internal(lock);
384         unlock_res_and_lock(lock);
385
386         /* drop reference from hashtable only for first destroy */
387         if (first) {
388                 lu_ref_del(&lock->l_reference, "hash", lock);
389                 LDLM_LOCK_RELEASE(lock);
390         }
391 }
392
393 /**
394  * Destroys a LDLM lock \a lock that is already locked.
395  */
396 void ldlm_lock_destroy_nolock(struct ldlm_lock *lock)
397 {
398         int first;
399
400         first = ldlm_lock_destroy_internal(lock);
401         /* drop reference from hashtable only for first destroy */
402         if (first) {
403                 lu_ref_del(&lock->l_reference, "hash", lock);
404                 LDLM_LOCK_RELEASE(lock);
405         }
406 }
407
408 /* this is called by portals_handle2object with the handle lock taken */
409 static void lock_handle_addref(void *lock)
410 {
411         LDLM_LOCK_GET((struct ldlm_lock *)lock);
412 }
413
414 static void lock_handle_free(void *lock, int size)
415 {
416         LASSERT(size == sizeof(struct ldlm_lock));
417         OBD_SLAB_FREE(lock, ldlm_lock_slab, size);
418 }
419
420 struct portals_handle_ops lock_handle_ops = {
421         .hop_addref = lock_handle_addref,
422         .hop_free   = lock_handle_free,
423 };
424
425 /**
426  *
427  * Allocate and initialize new lock structure.
428  *
429  * usage: pass in a resource on which you have done ldlm_resource_get
430  *      new lock will take over the refcount.
431  * returns: lock with refcount 2 - one for current caller and one for remote
432  */
433 static struct ldlm_lock *ldlm_lock_new(struct ldlm_resource *resource)
434 {
435         struct ldlm_lock *lock;
436
437         if (resource == NULL)
438                 LBUG();
439
440         OBD_SLAB_ALLOC_PTR_GFP(lock, ldlm_lock_slab, GFP_NOFS);
441         if (lock == NULL)
442                 return NULL;
443
444         spin_lock_init(&lock->l_lock);
445         lock->l_resource = resource;
446         lu_ref_add(&resource->lr_reference, "lock", lock);
447
448         atomic_set(&lock->l_refc, 2);
449         INIT_LIST_HEAD(&lock->l_res_link);
450         INIT_LIST_HEAD(&lock->l_lru);
451         INIT_LIST_HEAD(&lock->l_pending_chain);
452         INIT_LIST_HEAD(&lock->l_bl_ast);
453         INIT_LIST_HEAD(&lock->l_cp_ast);
454         INIT_LIST_HEAD(&lock->l_rk_ast);
455         init_waitqueue_head(&lock->l_waitq);
456         lock->l_blocking_lock = NULL;
457         INIT_LIST_HEAD(&lock->l_sl_mode);
458         INIT_LIST_HEAD(&lock->l_sl_policy);
459         INIT_HLIST_NODE(&lock->l_exp_hash);
460         INIT_HLIST_NODE(&lock->l_exp_flock_hash);
461
462         lprocfs_counter_incr(ldlm_res_to_ns(resource)->ns_stats,
463                              LDLM_NSS_LOCKS);
464         INIT_LIST_HEAD(&lock->l_handle.h_link);
465         class_handle_hash(&lock->l_handle, &lock_handle_ops);
466
467         lu_ref_init(&lock->l_reference);
468         lu_ref_add(&lock->l_reference, "hash", lock);
469         lock->l_callback_timeout = 0;
470
471 #if LUSTRE_TRACKS_LOCK_EXP_REFS
472         INIT_LIST_HEAD(&lock->l_exp_refs_link);
473         lock->l_exp_refs_nr = 0;
474         lock->l_exp_refs_target = NULL;
475 #endif
476         INIT_LIST_HEAD(&lock->l_exp_list);
477
478         return lock;
479 }
480
481 /**
482  * Moves LDLM lock \a lock to another resource.
483  * This is used on client when server returns some other lock than requested
484  * (typically as a result of intent operation)
485  */
486 int ldlm_lock_change_resource(struct ldlm_namespace *ns, struct ldlm_lock *lock,
487                               const struct ldlm_res_id *new_resid)
488 {
489         struct ldlm_resource *oldres = lock->l_resource;
490         struct ldlm_resource *newres;
491         int type;
492
493         LASSERT(ns_is_client(ns));
494
495         lock_res_and_lock(lock);
496         if (memcmp(new_resid, &lock->l_resource->lr_name,
497                    sizeof(lock->l_resource->lr_name)) == 0) {
498                 /* Nothing to do */
499                 unlock_res_and_lock(lock);
500                 return 0;
501         }
502
503         LASSERT(new_resid->name[0] != 0);
504
505         /* This function assumes that the lock isn't on any lists */
506         LASSERT(list_empty(&lock->l_res_link));
507
508         type = oldres->lr_type;
509         unlock_res_and_lock(lock);
510
511         newres = ldlm_resource_get(ns, NULL, new_resid, type, 1);
512         if (newres == NULL)
513                 return -ENOMEM;
514
515         lu_ref_add(&newres->lr_reference, "lock", lock);
516         /*
517          * To flip the lock from the old to the new resource, lock, oldres and
518          * newres have to be locked. Resource spin-locks are nested within
519          * lock->l_lock, and are taken in the memory address order to avoid
520          * dead-locks.
521          */
522         spin_lock(&lock->l_lock);
523         oldres = lock->l_resource;
524         if (oldres < newres) {
525                 lock_res(oldres);
526                 lock_res_nested(newres, LRT_NEW);
527         } else {
528                 lock_res(newres);
529                 lock_res_nested(oldres, LRT_NEW);
530         }
531         LASSERT(memcmp(new_resid, &oldres->lr_name,
532                        sizeof(oldres->lr_name)) != 0);
533         lock->l_resource = newres;
534         unlock_res(oldres);
535         unlock_res_and_lock(lock);
536
537         /* ...and the flowers are still standing! */
538         lu_ref_del(&oldres->lr_reference, "lock", lock);
539         ldlm_resource_putref(oldres);
540
541         return 0;
542 }
543 EXPORT_SYMBOL(ldlm_lock_change_resource);
544
545 /** \defgroup ldlm_handles LDLM HANDLES
546  * Ways to get hold of locks without any addresses.
547  * @{
548  */
549
550 /**
551  * Fills in handle for LDLM lock \a lock into supplied \a lockh
552  * Does not take any references.
553  */
554 void ldlm_lock2handle(const struct ldlm_lock *lock, struct lustre_handle *lockh)
555 {
556         lockh->cookie = lock->l_handle.h_cookie;
557 }
558 EXPORT_SYMBOL(ldlm_lock2handle);
559
560 /**
561  * Obtain a lock reference by handle.
562  *
563  * if \a flags: atomically get the lock and set the flags.
564  *            Return NULL if flag already set
565  */
566 struct ldlm_lock *__ldlm_handle2lock(const struct lustre_handle *handle,
567                                      __u64 flags)
568 {
569         struct ldlm_lock *lock;
570
571         LASSERT(handle);
572
573         lock = class_handle2object(handle->cookie);
574         if (lock == NULL)
575                 return NULL;
576
577         /* It's unlikely but possible that someone marked the lock as
578          * destroyed after we did handle2object on it */
579         if (flags == 0 && ((lock->l_flags & LDLM_FL_DESTROYED)== 0)) {
580                 lu_ref_add(&lock->l_reference, "handle", current);
581                 return lock;
582         }
583
584         lock_res_and_lock(lock);
585
586         LASSERT(lock->l_resource != NULL);
587
588         lu_ref_add_atomic(&lock->l_reference, "handle", current);
589         if (unlikely(lock->l_flags & LDLM_FL_DESTROYED)) {
590                 unlock_res_and_lock(lock);
591                 CDEBUG(D_INFO, "lock already destroyed: lock %p\n", lock);
592                 LDLM_LOCK_PUT(lock);
593                 return NULL;
594         }
595
596         if (flags && (lock->l_flags & flags)) {
597                 unlock_res_and_lock(lock);
598                 LDLM_LOCK_PUT(lock);
599                 return NULL;
600         }
601
602         if (flags)
603                 lock->l_flags |= flags;
604
605         unlock_res_and_lock(lock);
606         return lock;
607 }
608 EXPORT_SYMBOL(__ldlm_handle2lock);
609 /** @} ldlm_handles */
610
611 /**
612  * Fill in "on the wire" representation for given LDLM lock into supplied
613  * lock descriptor \a desc structure.
614  */
615 void ldlm_lock2desc(struct ldlm_lock *lock, struct ldlm_lock_desc *desc)
616 {
617         ldlm_res2desc(lock->l_resource, &desc->l_resource);
618         desc->l_req_mode = lock->l_req_mode;
619         desc->l_granted_mode = lock->l_granted_mode;
620         ldlm_convert_policy_to_wire(lock->l_resource->lr_type,
621                                     &lock->l_policy_data,
622                                     &desc->l_policy_data);
623 }
624 EXPORT_SYMBOL(ldlm_lock2desc);
625
626 /**
627  * Add a lock to list of conflicting locks to send AST to.
628  *
629  * Only add if we have not sent a blocking AST to the lock yet.
630  */
631 void ldlm_add_bl_work_item(struct ldlm_lock *lock, struct ldlm_lock *new,
632                            struct list_head *work_list)
633 {
634         if ((lock->l_flags & LDLM_FL_AST_SENT) == 0) {
635                 LDLM_DEBUG(lock, "lock incompatible; sending blocking AST.");
636                 lock->l_flags |= LDLM_FL_AST_SENT;
637                 /* If the enqueuing client said so, tell the AST recipient to
638                  * discard dirty data, rather than writing back. */
639                 if (new->l_flags & LDLM_FL_AST_DISCARD_DATA)
640                         lock->l_flags |= LDLM_FL_DISCARD_DATA;
641                 LASSERT(list_empty(&lock->l_bl_ast));
642                 list_add(&lock->l_bl_ast, work_list);
643                 LDLM_LOCK_GET(lock);
644                 LASSERT(lock->l_blocking_lock == NULL);
645                 lock->l_blocking_lock = LDLM_LOCK_GET(new);
646         }
647 }
648
649 /**
650  * Add a lock to list of just granted locks to send completion AST to.
651  */
652 void ldlm_add_cp_work_item(struct ldlm_lock *lock, struct list_head *work_list)
653 {
654         if ((lock->l_flags & LDLM_FL_CP_REQD) == 0) {
655                 lock->l_flags |= LDLM_FL_CP_REQD;
656                 LDLM_DEBUG(lock, "lock granted; sending completion AST.");
657                 LASSERT(list_empty(&lock->l_cp_ast));
658                 list_add(&lock->l_cp_ast, work_list);
659                 LDLM_LOCK_GET(lock);
660         }
661 }
662
663 /**
664  * Aggregator function to add AST work items into a list. Determines
665  * what sort of an AST work needs to be done and calls the proper
666  * adding function.
667  * Must be called with lr_lock held.
668  */
669 void ldlm_add_ast_work_item(struct ldlm_lock *lock, struct ldlm_lock *new,
670                             struct list_head *work_list)
671 {
672         check_res_locked(lock->l_resource);
673         if (new)
674                 ldlm_add_bl_work_item(lock, new, work_list);
675         else
676                 ldlm_add_cp_work_item(lock, work_list);
677 }
678
679 /**
680  * Add specified reader/writer reference to LDLM lock with handle \a lockh.
681  * r/w reference type is determined by \a mode
682  * Calls ldlm_lock_addref_internal.
683  */
684 void ldlm_lock_addref(struct lustre_handle *lockh, __u32 mode)
685 {
686         struct ldlm_lock *lock;
687
688         lock = ldlm_handle2lock(lockh);
689         LASSERT(lock != NULL);
690         ldlm_lock_addref_internal(lock, mode);
691         LDLM_LOCK_PUT(lock);
692 }
693 EXPORT_SYMBOL(ldlm_lock_addref);
694
695 /**
696  * Helper function.
697  * Add specified reader/writer reference to LDLM lock \a lock.
698  * r/w reference type is determined by \a mode
699  * Removes lock from LRU if it is there.
700  * Assumes the LDLM lock is already locked.
701  */
702 void ldlm_lock_addref_internal_nolock(struct ldlm_lock *lock, __u32 mode)
703 {
704         ldlm_lock_remove_from_lru(lock);
705         if (mode & (LCK_NL | LCK_CR | LCK_PR)) {
706                 lock->l_readers++;
707                 lu_ref_add_atomic(&lock->l_reference, "reader", lock);
708         }
709         if (mode & (LCK_EX | LCK_CW | LCK_PW | LCK_GROUP | LCK_COS)) {
710                 lock->l_writers++;
711                 lu_ref_add_atomic(&lock->l_reference, "writer", lock);
712         }
713         LDLM_LOCK_GET(lock);
714         lu_ref_add_atomic(&lock->l_reference, "user", lock);
715         LDLM_DEBUG(lock, "ldlm_lock_addref(%s)", ldlm_lockname[mode]);
716 }
717
718 /**
719  * Attempts to add reader/writer reference to a lock with handle \a lockh, and
720  * fails if lock is already LDLM_FL_CBPENDING or destroyed.
721  *
722  * \retval 0 success, lock was addref-ed
723  *
724  * \retval -EAGAIN lock is being canceled.
725  */
726 int ldlm_lock_addref_try(struct lustre_handle *lockh, __u32 mode)
727 {
728         struct ldlm_lock *lock;
729         int            result;
730
731         result = -EAGAIN;
732         lock = ldlm_handle2lock(lockh);
733         if (lock != NULL) {
734                 lock_res_and_lock(lock);
735                 if (lock->l_readers != 0 || lock->l_writers != 0 ||
736                     !(lock->l_flags & LDLM_FL_CBPENDING)) {
737                         ldlm_lock_addref_internal_nolock(lock, mode);
738                         result = 0;
739                 }
740                 unlock_res_and_lock(lock);
741                 LDLM_LOCK_PUT(lock);
742         }
743         return result;
744 }
745 EXPORT_SYMBOL(ldlm_lock_addref_try);
746
747 /**
748  * Add specified reader/writer reference to LDLM lock \a lock.
749  * Locks LDLM lock and calls ldlm_lock_addref_internal_nolock to do the work.
750  * Only called for local locks.
751  */
752 void ldlm_lock_addref_internal(struct ldlm_lock *lock, __u32 mode)
753 {
754         lock_res_and_lock(lock);
755         ldlm_lock_addref_internal_nolock(lock, mode);
756         unlock_res_and_lock(lock);
757 }
758
759 /**
760  * Removes reader/writer reference for LDLM lock \a lock.
761  * Assumes LDLM lock is already locked.
762  * only called in ldlm_flock_destroy and for local locks.
763  * Does NOT add lock to LRU if no r/w references left to accommodate flock locks
764  * that cannot be placed in LRU.
765  */
766 void ldlm_lock_decref_internal_nolock(struct ldlm_lock *lock, __u32 mode)
767 {
768         LDLM_DEBUG(lock, "ldlm_lock_decref(%s)", ldlm_lockname[mode]);
769         if (mode & (LCK_NL | LCK_CR | LCK_PR)) {
770                 LASSERT(lock->l_readers > 0);
771                 lu_ref_del(&lock->l_reference, "reader", lock);
772                 lock->l_readers--;
773         }
774         if (mode & (LCK_EX | LCK_CW | LCK_PW | LCK_GROUP | LCK_COS)) {
775                 LASSERT(lock->l_writers > 0);
776                 lu_ref_del(&lock->l_reference, "writer", lock);
777                 lock->l_writers--;
778         }
779
780         lu_ref_del(&lock->l_reference, "user", lock);
781         LDLM_LOCK_RELEASE(lock);    /* matches the LDLM_LOCK_GET() in addref */
782 }
783
784 /**
785  * Removes reader/writer reference for LDLM lock \a lock.
786  * Locks LDLM lock first.
787  * If the lock is determined to be client lock on a client and r/w refcount
788  * drops to zero and the lock is not blocked, the lock is added to LRU lock
789  * on the namespace.
790  * For blocked LDLM locks if r/w count drops to zero, blocking_ast is called.
791  */
792 void ldlm_lock_decref_internal(struct ldlm_lock *lock, __u32 mode)
793 {
794         struct ldlm_namespace *ns;
795
796         lock_res_and_lock(lock);
797
798         ns = ldlm_lock_to_ns(lock);
799
800         ldlm_lock_decref_internal_nolock(lock, mode);
801
802         if (lock->l_flags & LDLM_FL_LOCAL &&
803             !lock->l_readers && !lock->l_writers) {
804                 /* If this is a local lock on a server namespace and this was
805                  * the last reference, cancel the lock. */
806                 CDEBUG(D_INFO, "forcing cancel of local lock\n");
807                 lock->l_flags |= LDLM_FL_CBPENDING;
808         }
809
810         if (!lock->l_readers && !lock->l_writers &&
811             (lock->l_flags & LDLM_FL_CBPENDING)) {
812                 /* If we received a blocked AST and this was the last reference,
813                  * run the callback. */
814                 if ((lock->l_flags & LDLM_FL_NS_SRV) && lock->l_export)
815                         CERROR("FL_CBPENDING set on non-local lock--just a warning\n");
816
817                 LDLM_DEBUG(lock, "final decref done on cbpending lock");
818
819                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
820                 ldlm_lock_remove_from_lru(lock);
821                 unlock_res_and_lock(lock);
822
823                 if (lock->l_flags & LDLM_FL_FAIL_LOC)
824                         OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
825
826                 if ((lock->l_flags & LDLM_FL_ATOMIC_CB) ||
827                     ldlm_bl_to_thread_lock(ns, NULL, lock) != 0)
828                         ldlm_handle_bl_callback(ns, NULL, lock);
829         } else if (ns_is_client(ns) &&
830                    !lock->l_readers && !lock->l_writers &&
831                    !(lock->l_flags & LDLM_FL_NO_LRU) &&
832                    !(lock->l_flags & LDLM_FL_BL_AST)) {
833
834                 LDLM_DEBUG(lock, "add lock into lru list");
835
836                 /* If this is a client-side namespace and this was the last
837                  * reference, put it on the LRU. */
838                 ldlm_lock_add_to_lru(lock);
839                 unlock_res_and_lock(lock);
840
841                 if (lock->l_flags & LDLM_FL_FAIL_LOC)
842                         OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
843
844                 /* Call ldlm_cancel_lru() only if EARLY_CANCEL and LRU RESIZE
845                  * are not supported by the server, otherwise, it is done on
846                  * enqueue. */
847                 if (!exp_connect_cancelset(lock->l_conn_export) &&
848                     !ns_connect_lru_resize(ns))
849                         ldlm_cancel_lru(ns, 0, LCF_ASYNC, 0);
850         } else {
851                 LDLM_DEBUG(lock, "do not add lock into lru list");
852                 unlock_res_and_lock(lock);
853         }
854 }
855
856 /**
857  * Decrease reader/writer refcount for LDLM lock with handle \a lockh
858  */
859 void ldlm_lock_decref(struct lustre_handle *lockh, __u32 mode)
860 {
861         struct ldlm_lock *lock = __ldlm_handle2lock(lockh, 0);
862
863         LASSERTF(lock != NULL, "Non-existing lock: %#llx\n", lockh->cookie);
864         ldlm_lock_decref_internal(lock, mode);
865         LDLM_LOCK_PUT(lock);
866 }
867 EXPORT_SYMBOL(ldlm_lock_decref);
868
869 /**
870  * Decrease reader/writer refcount for LDLM lock with handle
871  * \a lockh and mark it for subsequent cancellation once r/w refcount
872  * drops to zero instead of putting into LRU.
873  *
874  * Typical usage is for GROUP locks which we cannot allow to be cached.
875  */
876 void ldlm_lock_decref_and_cancel(struct lustre_handle *lockh, __u32 mode)
877 {
878         struct ldlm_lock *lock = __ldlm_handle2lock(lockh, 0);
879
880         LASSERT(lock != NULL);
881
882         LDLM_DEBUG(lock, "ldlm_lock_decref(%s)", ldlm_lockname[mode]);
883         lock_res_and_lock(lock);
884         lock->l_flags |= LDLM_FL_CBPENDING;
885         unlock_res_and_lock(lock);
886         ldlm_lock_decref_internal(lock, mode);
887         LDLM_LOCK_PUT(lock);
888 }
889 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
890
891 struct sl_insert_point {
892         struct list_head *res_link;
893         struct list_head *mode_link;
894         struct list_head *policy_link;
895 };
896
897 /**
898  * Finds a position to insert the new lock into granted lock list.
899  *
900  * Used for locks eligible for skiplist optimization.
901  *
902  * Parameters:
903  *      queue [input]:  the granted list where search acts on;
904  *      req [input]:    the lock whose position to be located;
905  *      prev [output]:  positions within 3 lists to insert @req to
906  * Return Value:
907  *      filled @prev
908  * NOTE: called by
909  *  - ldlm_grant_lock_with_skiplist
910  */
911 static void search_granted_lock(struct list_head *queue,
912                                 struct ldlm_lock *req,
913                                 struct sl_insert_point *prev)
914 {
915         struct list_head *tmp;
916         struct ldlm_lock *lock, *mode_end, *policy_end;
917
918         list_for_each(tmp, queue) {
919                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
920
921                 mode_end = list_entry(lock->l_sl_mode.prev,
922                                           struct ldlm_lock, l_sl_mode);
923
924                 if (lock->l_req_mode != req->l_req_mode) {
925                         /* jump to last lock of mode group */
926                         tmp = &mode_end->l_res_link;
927                         continue;
928                 }
929
930                 /* suitable mode group is found */
931                 if (lock->l_resource->lr_type == LDLM_PLAIN) {
932                         /* insert point is last lock of the mode group */
933                         prev->res_link = &mode_end->l_res_link;
934                         prev->mode_link = &mode_end->l_sl_mode;
935                         prev->policy_link = &req->l_sl_policy;
936                         return;
937                 } else if (lock->l_resource->lr_type == LDLM_IBITS) {
938                         for (;;) {
939                                 policy_end =
940                                         list_entry(lock->l_sl_policy.prev,
941                                                        struct ldlm_lock,
942                                                        l_sl_policy);
943
944                                 if (lock->l_policy_data.l_inodebits.bits ==
945                                     req->l_policy_data.l_inodebits.bits) {
946                                         /* insert point is last lock of
947                                          * the policy group */
948                                         prev->res_link =
949                                                 &policy_end->l_res_link;
950                                         prev->mode_link =
951                                                 &policy_end->l_sl_mode;
952                                         prev->policy_link =
953                                                 &policy_end->l_sl_policy;
954                                         return;
955                                 }
956
957                                 if (policy_end == mode_end)
958                                         /* done with mode group */
959                                         break;
960
961                                 /* go to next policy group within mode group */
962                                 tmp = policy_end->l_res_link.next;
963                                 lock = list_entry(tmp, struct ldlm_lock,
964                                                       l_res_link);
965                         }  /* loop over policy groups within the mode group */
966
967                         /* insert point is last lock of the mode group,
968                          * new policy group is started */
969                         prev->res_link = &mode_end->l_res_link;
970                         prev->mode_link = &mode_end->l_sl_mode;
971                         prev->policy_link = &req->l_sl_policy;
972                         return;
973                 } else {
974                         LDLM_ERROR(lock,
975                                    "is not LDLM_PLAIN or LDLM_IBITS lock");
976                         LBUG();
977                 }
978         }
979
980         /* insert point is last lock on the queue,
981          * new mode group and new policy group are started */
982         prev->res_link = queue->prev;
983         prev->mode_link = &req->l_sl_mode;
984         prev->policy_link = &req->l_sl_policy;
985         return;
986 }
987
988 /**
989  * Add a lock into resource granted list after a position described by
990  * \a prev.
991  */
992 static void ldlm_granted_list_add_lock(struct ldlm_lock *lock,
993                                        struct sl_insert_point *prev)
994 {
995         struct ldlm_resource *res = lock->l_resource;
996
997         check_res_locked(res);
998
999         ldlm_resource_dump(D_INFO, res);
1000         LDLM_DEBUG(lock, "About to add lock:");
1001
1002         if (lock->l_flags & LDLM_FL_DESTROYED) {
1003                 CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
1004                 return;
1005         }
1006
1007         LASSERT(list_empty(&lock->l_res_link));
1008         LASSERT(list_empty(&lock->l_sl_mode));
1009         LASSERT(list_empty(&lock->l_sl_policy));
1010
1011         /*
1012          * lock->link == prev->link means lock is first starting the group.
1013          * Don't re-add to itself to suppress kernel warnings.
1014          */
1015         if (&lock->l_res_link != prev->res_link)
1016                 list_add(&lock->l_res_link, prev->res_link);
1017         if (&lock->l_sl_mode != prev->mode_link)
1018                 list_add(&lock->l_sl_mode, prev->mode_link);
1019         if (&lock->l_sl_policy != prev->policy_link)
1020                 list_add(&lock->l_sl_policy, prev->policy_link);
1021 }
1022
1023 /**
1024  * Add a lock to granted list on a resource maintaining skiplist
1025  * correctness.
1026  */
1027 static void ldlm_grant_lock_with_skiplist(struct ldlm_lock *lock)
1028 {
1029         struct sl_insert_point prev;
1030
1031         LASSERT(lock->l_req_mode == lock->l_granted_mode);
1032
1033         search_granted_lock(&lock->l_resource->lr_granted, lock, &prev);
1034         ldlm_granted_list_add_lock(lock, &prev);
1035 }
1036
1037 /**
1038  * Perform lock granting bookkeeping.
1039  *
1040  * Includes putting the lock into granted list and updating lock mode.
1041  * NOTE: called by
1042  *  - ldlm_lock_enqueue
1043  *  - ldlm_reprocess_queue
1044  *  - ldlm_lock_convert
1045  *
1046  * must be called with lr_lock held
1047  */
1048 void ldlm_grant_lock(struct ldlm_lock *lock, struct list_head *work_list)
1049 {
1050         struct ldlm_resource *res = lock->l_resource;
1051
1052         check_res_locked(res);
1053
1054         lock->l_granted_mode = lock->l_req_mode;
1055         if (res->lr_type == LDLM_PLAIN || res->lr_type == LDLM_IBITS)
1056                 ldlm_grant_lock_with_skiplist(lock);
1057         else if (res->lr_type == LDLM_EXTENT)
1058                 ldlm_extent_add_lock(res, lock);
1059         else
1060                 ldlm_resource_add_lock(res, &res->lr_granted, lock);
1061
1062         if (lock->l_granted_mode < res->lr_most_restr)
1063                 res->lr_most_restr = lock->l_granted_mode;
1064
1065         if (work_list && lock->l_completion_ast != NULL)
1066                 ldlm_add_ast_work_item(lock, NULL, work_list);
1067
1068         ldlm_pool_add(&ldlm_res_to_ns(res)->ns_pool, lock);
1069 }
1070
1071 /**
1072  * Search for a lock with given properties in a queue.
1073  *
1074  * \retval a referenced lock or NULL.  See the flag descriptions below, in the
1075  * comment above ldlm_lock_match
1076  */
1077 static struct ldlm_lock *search_queue(struct list_head *queue,
1078                                       ldlm_mode_t *mode,
1079                                       ldlm_policy_data_t *policy,
1080                                       struct ldlm_lock *old_lock,
1081                                       __u64 flags, int unref)
1082 {
1083         struct ldlm_lock *lock;
1084         struct list_head       *tmp;
1085
1086         list_for_each(tmp, queue) {
1087                 ldlm_mode_t match;
1088
1089                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1090
1091                 if (lock == old_lock)
1092                         break;
1093
1094                 /* Check if this lock can be matched.
1095                  * Used by LU-2919(exclusive open) for open lease lock */
1096                 if (ldlm_is_excl(lock))
1097                         continue;
1098
1099                 /* llite sometimes wants to match locks that will be
1100                  * canceled when their users drop, but we allow it to match
1101                  * if it passes in CBPENDING and the lock still has users.
1102                  * this is generally only going to be used by children
1103                  * whose parents already hold a lock so forward progress
1104                  * can still happen. */
1105                 if (lock->l_flags & LDLM_FL_CBPENDING &&
1106                     !(flags & LDLM_FL_CBPENDING))
1107                         continue;
1108                 if (!unref && lock->l_flags & LDLM_FL_CBPENDING &&
1109                     lock->l_readers == 0 && lock->l_writers == 0)
1110                         continue;
1111
1112                 if (!(lock->l_req_mode & *mode))
1113                         continue;
1114                 match = lock->l_req_mode;
1115
1116                 if (lock->l_resource->lr_type == LDLM_EXTENT &&
1117                     (lock->l_policy_data.l_extent.start >
1118                      policy->l_extent.start ||
1119                      lock->l_policy_data.l_extent.end < policy->l_extent.end))
1120                         continue;
1121
1122                 if (unlikely(match == LCK_GROUP) &&
1123                     lock->l_resource->lr_type == LDLM_EXTENT &&
1124                     lock->l_policy_data.l_extent.gid != policy->l_extent.gid)
1125                         continue;
1126
1127                 /* We match if we have existing lock with same or wider set
1128                    of bits. */
1129                 if (lock->l_resource->lr_type == LDLM_IBITS &&
1130                      ((lock->l_policy_data.l_inodebits.bits &
1131                       policy->l_inodebits.bits) !=
1132                       policy->l_inodebits.bits))
1133                         continue;
1134
1135                 if (!unref && (lock->l_flags & LDLM_FL_GONE_MASK))
1136                         continue;
1137
1138                 if ((flags & LDLM_FL_LOCAL_ONLY) &&
1139                     !(lock->l_flags & LDLM_FL_LOCAL))
1140                         continue;
1141
1142                 if (flags & LDLM_FL_TEST_LOCK) {
1143                         LDLM_LOCK_GET(lock);
1144                         ldlm_lock_touch_in_lru(lock);
1145                 } else {
1146                         ldlm_lock_addref_internal_nolock(lock, match);
1147                 }
1148                 *mode = match;
1149                 return lock;
1150         }
1151
1152         return NULL;
1153 }
1154
1155 void ldlm_lock_fail_match_locked(struct ldlm_lock *lock)
1156 {
1157         if ((lock->l_flags & LDLM_FL_FAIL_NOTIFIED) == 0) {
1158                 lock->l_flags |= LDLM_FL_FAIL_NOTIFIED;
1159                 wake_up_all(&lock->l_waitq);
1160         }
1161 }
1162 EXPORT_SYMBOL(ldlm_lock_fail_match_locked);
1163
1164 void ldlm_lock_fail_match(struct ldlm_lock *lock)
1165 {
1166         lock_res_and_lock(lock);
1167         ldlm_lock_fail_match_locked(lock);
1168         unlock_res_and_lock(lock);
1169 }
1170 EXPORT_SYMBOL(ldlm_lock_fail_match);
1171
1172 /**
1173  * Mark lock as "matchable" by OST.
1174  *
1175  * Used to prevent certain races in LOV/OSC where the lock is granted, but LVB
1176  * is not yet valid.
1177  * Assumes LDLM lock is already locked.
1178  */
1179 void ldlm_lock_allow_match_locked(struct ldlm_lock *lock)
1180 {
1181         lock->l_flags |= LDLM_FL_LVB_READY;
1182         wake_up_all(&lock->l_waitq);
1183 }
1184 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
1185
1186 /**
1187  * Mark lock as "matchable" by OST.
1188  * Locks the lock and then \see ldlm_lock_allow_match_locked
1189  */
1190 void ldlm_lock_allow_match(struct ldlm_lock *lock)
1191 {
1192         lock_res_and_lock(lock);
1193         ldlm_lock_allow_match_locked(lock);
1194         unlock_res_and_lock(lock);
1195 }
1196 EXPORT_SYMBOL(ldlm_lock_allow_match);
1197
1198 /**
1199  * Attempt to find a lock with specified properties.
1200  *
1201  * Typically returns a reference to matched lock unless LDLM_FL_TEST_LOCK is
1202  * set in \a flags
1203  *
1204  * Can be called in two ways:
1205  *
1206  * If 'ns' is NULL, then lockh describes an existing lock that we want to look
1207  * for a duplicate of.
1208  *
1209  * Otherwise, all of the fields must be filled in, to match against.
1210  *
1211  * If 'flags' contains LDLM_FL_LOCAL_ONLY, then only match local locks on the
1212  *     server (ie, connh is NULL)
1213  * If 'flags' contains LDLM_FL_BLOCK_GRANTED, then only locks on the granted
1214  *     list will be considered
1215  * If 'flags' contains LDLM_FL_CBPENDING, then locks that have been marked
1216  *     to be canceled can still be matched as long as they still have reader
1217  *     or writer referneces
1218  * If 'flags' contains LDLM_FL_TEST_LOCK, then don't actually reference a lock,
1219  *     just tell us if we would have matched.
1220  *
1221  * \retval 1 if it finds an already-existing lock that is compatible; in this
1222  * case, lockh is filled in with a addref()ed lock
1223  *
1224  * We also check security context, and if that fails we simply return 0 (to
1225  * keep caller code unchanged), the context failure will be discovered by
1226  * caller sometime later.
1227  */
1228 ldlm_mode_t ldlm_lock_match(struct ldlm_namespace *ns, __u64 flags,
1229                             const struct ldlm_res_id *res_id, ldlm_type_t type,
1230                             ldlm_policy_data_t *policy, ldlm_mode_t mode,
1231                             struct lustre_handle *lockh, int unref)
1232 {
1233         struct ldlm_resource *res;
1234         struct ldlm_lock *lock, *old_lock = NULL;
1235         int rc = 0;
1236
1237         if (ns == NULL) {
1238                 old_lock = ldlm_handle2lock(lockh);
1239                 LASSERT(old_lock);
1240
1241                 ns = ldlm_lock_to_ns(old_lock);
1242                 res_id = &old_lock->l_resource->lr_name;
1243                 type = old_lock->l_resource->lr_type;
1244                 mode = old_lock->l_req_mode;
1245         }
1246
1247         res = ldlm_resource_get(ns, NULL, res_id, type, 0);
1248         if (res == NULL) {
1249                 LASSERT(old_lock == NULL);
1250                 return 0;
1251         }
1252
1253         LDLM_RESOURCE_ADDREF(res);
1254         lock_res(res);
1255
1256         lock = search_queue(&res->lr_granted, &mode, policy, old_lock,
1257                             flags, unref);
1258         if (lock != NULL) {
1259                 rc = 1;
1260                 goto out;
1261         }
1262         if (flags & LDLM_FL_BLOCK_GRANTED) {
1263                 rc = 0;
1264                 goto out;
1265         }
1266         lock = search_queue(&res->lr_converting, &mode, policy, old_lock,
1267                             flags, unref);
1268         if (lock != NULL) {
1269                 rc = 1;
1270                 goto out;
1271         }
1272         lock = search_queue(&res->lr_waiting, &mode, policy, old_lock,
1273                             flags, unref);
1274         if (lock != NULL) {
1275                 rc = 1;
1276                 goto out;
1277         }
1278
1279  out:
1280         unlock_res(res);
1281         LDLM_RESOURCE_DELREF(res);
1282         ldlm_resource_putref(res);
1283
1284         if (lock) {
1285                 ldlm_lock2handle(lock, lockh);
1286                 if ((flags & LDLM_FL_LVB_READY) &&
1287                     (!(lock->l_flags & LDLM_FL_LVB_READY))) {
1288                         __u64 wait_flags = LDLM_FL_LVB_READY |
1289                                 LDLM_FL_DESTROYED | LDLM_FL_FAIL_NOTIFIED;
1290                         struct l_wait_info lwi;
1291
1292                         if (lock->l_completion_ast) {
1293                                 int err = lock->l_completion_ast(lock,
1294                                                           LDLM_FL_WAIT_NOREPROC,
1295                                                                  NULL);
1296                                 if (err) {
1297                                         if (flags & LDLM_FL_TEST_LOCK)
1298                                                 LDLM_LOCK_RELEASE(lock);
1299                                         else
1300                                                 ldlm_lock_decref_internal(lock,
1301                                                                           mode);
1302                                         rc = 0;
1303                                         goto out2;
1304                                 }
1305                         }
1306
1307                         lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(obd_timeout),
1308                                                NULL, LWI_ON_SIGNAL_NOOP, NULL);
1309
1310                         /* XXX FIXME see comment on CAN_MATCH in lustre_dlm.h */
1311                         l_wait_event(lock->l_waitq,
1312                                      lock->l_flags & wait_flags,
1313                                      &lwi);
1314                         if (!(lock->l_flags & LDLM_FL_LVB_READY)) {
1315                                 if (flags & LDLM_FL_TEST_LOCK)
1316                                         LDLM_LOCK_RELEASE(lock);
1317                                 else
1318                                         ldlm_lock_decref_internal(lock, mode);
1319                                 rc = 0;
1320                         }
1321                 }
1322         }
1323  out2:
1324         if (rc) {
1325                 LDLM_DEBUG(lock, "matched (%llu %llu)",
1326                            (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1327                                 res_id->name[2] : policy->l_extent.start,
1328                            (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1329                                 res_id->name[3] : policy->l_extent.end);
1330
1331                 /* check user's security context */
1332                 if (lock->l_conn_export &&
1333                     sptlrpc_import_check_ctx(
1334                                 class_exp2cliimp(lock->l_conn_export))) {
1335                         if (!(flags & LDLM_FL_TEST_LOCK))
1336                                 ldlm_lock_decref_internal(lock, mode);
1337                         rc = 0;
1338                 }
1339
1340                 if (flags & LDLM_FL_TEST_LOCK)
1341                         LDLM_LOCK_RELEASE(lock);
1342
1343         } else if (!(flags & LDLM_FL_TEST_LOCK)) {/*less verbose for test-only*/
1344                 LDLM_DEBUG_NOLOCK("not matched ns %p type %u mode %u res %llu/%llu (%llu %llu)",
1345                                   ns, type, mode, res_id->name[0],
1346                                   res_id->name[1],
1347                                   (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1348                                         res_id->name[2] :policy->l_extent.start,
1349                                   (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1350                                         res_id->name[3] : policy->l_extent.end);
1351         }
1352         if (old_lock)
1353                 LDLM_LOCK_PUT(old_lock);
1354
1355         return rc ? mode : 0;
1356 }
1357 EXPORT_SYMBOL(ldlm_lock_match);
1358
1359 ldlm_mode_t ldlm_revalidate_lock_handle(struct lustre_handle *lockh,
1360                                         __u64 *bits)
1361 {
1362         struct ldlm_lock *lock;
1363         ldlm_mode_t mode = 0;
1364
1365         lock = ldlm_handle2lock(lockh);
1366         if (lock != NULL) {
1367                 lock_res_and_lock(lock);
1368                 if (lock->l_flags & LDLM_FL_GONE_MASK)
1369                         goto out;
1370
1371                 if (lock->l_flags & LDLM_FL_CBPENDING &&
1372                     lock->l_readers == 0 && lock->l_writers == 0)
1373                         goto out;
1374
1375                 if (bits)
1376                         *bits = lock->l_policy_data.l_inodebits.bits;
1377                 mode = lock->l_granted_mode;
1378                 ldlm_lock_addref_internal_nolock(lock, mode);
1379         }
1380
1381 out:
1382         if (lock != NULL) {
1383                 unlock_res_and_lock(lock);
1384                 LDLM_LOCK_PUT(lock);
1385         }
1386         return mode;
1387 }
1388 EXPORT_SYMBOL(ldlm_revalidate_lock_handle);
1389
1390 /** The caller must guarantee that the buffer is large enough. */
1391 int ldlm_fill_lvb(struct ldlm_lock *lock, struct req_capsule *pill,
1392                   enum req_location loc, void *data, int size)
1393 {
1394         void *lvb;
1395
1396         LASSERT(data != NULL);
1397         LASSERT(size >= 0);
1398
1399         switch (lock->l_lvb_type) {
1400         case LVB_T_OST:
1401                 if (size == sizeof(struct ost_lvb)) {
1402                         if (loc == RCL_CLIENT)
1403                                 lvb = req_capsule_client_swab_get(pill,
1404                                                 &RMF_DLM_LVB,
1405                                                 lustre_swab_ost_lvb);
1406                         else
1407                                 lvb = req_capsule_server_swab_get(pill,
1408                                                 &RMF_DLM_LVB,
1409                                                 lustre_swab_ost_lvb);
1410                         if (unlikely(lvb == NULL)) {
1411                                 LDLM_ERROR(lock, "no LVB");
1412                                 return -EPROTO;
1413                         }
1414
1415                         memcpy(data, lvb, size);
1416                 } else if (size == sizeof(struct ost_lvb_v1)) {
1417                         struct ost_lvb *olvb = data;
1418
1419                         if (loc == RCL_CLIENT)
1420                                 lvb = req_capsule_client_swab_get(pill,
1421                                                 &RMF_DLM_LVB,
1422                                                 lustre_swab_ost_lvb_v1);
1423                         else
1424                                 lvb = req_capsule_server_sized_swab_get(pill,
1425                                                 &RMF_DLM_LVB, size,
1426                                                 lustre_swab_ost_lvb_v1);
1427                         if (unlikely(lvb == NULL)) {
1428                                 LDLM_ERROR(lock, "no LVB");
1429                                 return -EPROTO;
1430                         }
1431
1432                         memcpy(data, lvb, size);
1433                         olvb->lvb_mtime_ns = 0;
1434                         olvb->lvb_atime_ns = 0;
1435                         olvb->lvb_ctime_ns = 0;
1436                 } else {
1437                         LDLM_ERROR(lock, "Replied unexpected ost LVB size %d",
1438                                    size);
1439                         return -EINVAL;
1440                 }
1441                 break;
1442         case LVB_T_LQUOTA:
1443                 if (size == sizeof(struct lquota_lvb)) {
1444                         if (loc == RCL_CLIENT)
1445                                 lvb = req_capsule_client_swab_get(pill,
1446                                                 &RMF_DLM_LVB,
1447                                                 lustre_swab_lquota_lvb);
1448                         else
1449                                 lvb = req_capsule_server_swab_get(pill,
1450                                                 &RMF_DLM_LVB,
1451                                                 lustre_swab_lquota_lvb);
1452                         if (unlikely(lvb == NULL)) {
1453                                 LDLM_ERROR(lock, "no LVB");
1454                                 return -EPROTO;
1455                         }
1456
1457                         memcpy(data, lvb, size);
1458                 } else {
1459                         LDLM_ERROR(lock,
1460                                    "Replied unexpected lquota LVB size %d",
1461                                    size);
1462                         return -EINVAL;
1463                 }
1464                 break;
1465         case LVB_T_LAYOUT:
1466                 if (size == 0)
1467                         break;
1468
1469                 if (loc == RCL_CLIENT)
1470                         lvb = req_capsule_client_get(pill, &RMF_DLM_LVB);
1471                 else
1472                         lvb = req_capsule_server_get(pill, &RMF_DLM_LVB);
1473                 if (unlikely(lvb == NULL)) {
1474                         LDLM_ERROR(lock, "no LVB");
1475                         return -EPROTO;
1476                 }
1477
1478                 memcpy(data, lvb, size);
1479                 break;
1480         default:
1481                 LDLM_ERROR(lock, "Unknown LVB type: %d\n", lock->l_lvb_type);
1482                 dump_stack();
1483                 return -EINVAL;
1484         }
1485
1486         return 0;
1487 }
1488
1489 /**
1490  * Create and fill in new LDLM lock with specified properties.
1491  * Returns a referenced lock
1492  */
1493 struct ldlm_lock *ldlm_lock_create(struct ldlm_namespace *ns,
1494                                    const struct ldlm_res_id *res_id,
1495                                    ldlm_type_t type,
1496                                    ldlm_mode_t mode,
1497                                    const struct ldlm_callback_suite *cbs,
1498                                    void *data, __u32 lvb_len,
1499                                    enum lvb_type lvb_type)
1500 {
1501         struct ldlm_lock *lock;
1502         struct ldlm_resource *res;
1503
1504         res = ldlm_resource_get(ns, NULL, res_id, type, 1);
1505         if (res == NULL)
1506                 return NULL;
1507
1508         lock = ldlm_lock_new(res);
1509
1510         if (lock == NULL)
1511                 return NULL;
1512
1513         lock->l_req_mode = mode;
1514         lock->l_ast_data = data;
1515         lock->l_pid = current_pid();
1516         if (ns_is_server(ns))
1517                 lock->l_flags |= LDLM_FL_NS_SRV;
1518         if (cbs) {
1519                 lock->l_blocking_ast = cbs->lcs_blocking;
1520                 lock->l_completion_ast = cbs->lcs_completion;
1521                 lock->l_glimpse_ast = cbs->lcs_glimpse;
1522         }
1523
1524         lock->l_tree_node = NULL;
1525         /* if this is the extent lock, allocate the interval tree node */
1526         if (type == LDLM_EXTENT) {
1527                 if (ldlm_interval_alloc(lock) == NULL)
1528                         goto out;
1529         }
1530
1531         if (lvb_len) {
1532                 lock->l_lvb_len = lvb_len;
1533                 OBD_ALLOC(lock->l_lvb_data, lvb_len);
1534                 if (lock->l_lvb_data == NULL)
1535                         goto out;
1536         }
1537
1538         lock->l_lvb_type = lvb_type;
1539         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_NEW_LOCK))
1540                 goto out;
1541
1542         return lock;
1543
1544 out:
1545         ldlm_lock_destroy(lock);
1546         LDLM_LOCK_RELEASE(lock);
1547         return NULL;
1548 }
1549
1550 /**
1551  * Enqueue (request) a lock.
1552  *
1553  * Does not block. As a result of enqueue the lock would be put
1554  * into granted or waiting list.
1555  *
1556  * If namespace has intent policy sent and the lock has LDLM_FL_HAS_INTENT flag
1557  * set, skip all the enqueueing and delegate lock processing to intent policy
1558  * function.
1559  */
1560 ldlm_error_t ldlm_lock_enqueue(struct ldlm_namespace *ns,
1561                                struct ldlm_lock **lockp,
1562                                void *cookie, __u64 *flags)
1563 {
1564         struct ldlm_lock *lock = *lockp;
1565         struct ldlm_resource *res = lock->l_resource;
1566         int local = ns_is_client(ldlm_res_to_ns(res));
1567         ldlm_error_t rc = ELDLM_OK;
1568         struct ldlm_interval *node = NULL;
1569
1570         lock->l_last_activity = get_seconds();
1571         /* policies are not executed on the client or during replay */
1572         if ((*flags & (LDLM_FL_HAS_INTENT|LDLM_FL_REPLAY)) == LDLM_FL_HAS_INTENT
1573             && !local && ns->ns_policy) {
1574                 rc = ns->ns_policy(ns, lockp, cookie, lock->l_req_mode, *flags,
1575                                    NULL);
1576                 if (rc == ELDLM_LOCK_REPLACED) {
1577                         /* The lock that was returned has already been granted,
1578                          * and placed into lockp.  If it's not the same as the
1579                          * one we passed in, then destroy the old one and our
1580                          * work here is done. */
1581                         if (lock != *lockp) {
1582                                 ldlm_lock_destroy(lock);
1583                                 LDLM_LOCK_RELEASE(lock);
1584                         }
1585                         *flags |= LDLM_FL_LOCK_CHANGED;
1586                         return 0;
1587                 } else if (rc != ELDLM_OK ||
1588                            (rc == ELDLM_OK && (*flags & LDLM_FL_INTENT_ONLY))) {
1589                         ldlm_lock_destroy(lock);
1590                         return rc;
1591                 }
1592         }
1593
1594         /* For a replaying lock, it might be already in granted list. So
1595          * unlinking the lock will cause the interval node to be freed, we
1596          * have to allocate the interval node early otherwise we can't regrant
1597          * this lock in the future. - jay */
1598         if (!local && (*flags & LDLM_FL_REPLAY) && res->lr_type == LDLM_EXTENT)
1599                 OBD_SLAB_ALLOC_PTR_GFP(node, ldlm_interval_slab, GFP_NOFS);
1600
1601         lock_res_and_lock(lock);
1602         if (local && lock->l_req_mode == lock->l_granted_mode) {
1603                 /* The server returned a blocked lock, but it was granted
1604                  * before we got a chance to actually enqueue it.  We don't
1605                  * need to do anything else. */
1606                 *flags &= ~(LDLM_FL_BLOCK_GRANTED |
1607                             LDLM_FL_BLOCK_CONV | LDLM_FL_BLOCK_WAIT);
1608                 goto out;
1609         }
1610
1611         ldlm_resource_unlink_lock(lock);
1612         if (res->lr_type == LDLM_EXTENT && lock->l_tree_node == NULL) {
1613                 if (node == NULL) {
1614                         ldlm_lock_destroy_nolock(lock);
1615                         rc = -ENOMEM;
1616                         goto out;
1617                 }
1618
1619                 INIT_LIST_HEAD(&node->li_group);
1620                 ldlm_interval_attach(node, lock);
1621                 node = NULL;
1622         }
1623
1624         /* Some flags from the enqueue want to make it into the AST, via the
1625          * lock's l_flags. */
1626         lock->l_flags |= *flags & LDLM_FL_AST_DISCARD_DATA;
1627
1628         /* This distinction between local lock trees is very important; a client
1629          * namespace only has information about locks taken by that client, and
1630          * thus doesn't have enough information to decide for itself if it can
1631          * be granted (below).  In this case, we do exactly what the server
1632          * tells us to do, as dictated by the 'flags'.
1633          *
1634          * We do exactly the same thing during recovery, when the server is
1635          * more or less trusting the clients not to lie.
1636          *
1637          * FIXME (bug 268): Detect obvious lies by checking compatibility in
1638          * granted/converting queues. */
1639         if (local) {
1640                 if (*flags & LDLM_FL_BLOCK_CONV)
1641                         ldlm_resource_add_lock(res, &res->lr_converting, lock);
1642                 else if (*flags & (LDLM_FL_BLOCK_WAIT | LDLM_FL_BLOCK_GRANTED))
1643                         ldlm_resource_add_lock(res, &res->lr_waiting, lock);
1644                 else
1645                         ldlm_grant_lock(lock, NULL);
1646                 goto out;
1647         } else {
1648                 CERROR("This is client-side-only module, cannot handle LDLM_NAMESPACE_SERVER resource type lock.\n");
1649                 LBUG();
1650         }
1651
1652 out:
1653         unlock_res_and_lock(lock);
1654         if (node)
1655                 OBD_SLAB_FREE(node, ldlm_interval_slab, sizeof(*node));
1656         return rc;
1657 }
1658
1659
1660 /**
1661  * Process a call to blocking AST callback for a lock in ast_work list
1662  */
1663 static int
1664 ldlm_work_bl_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
1665 {
1666         struct ldlm_cb_set_arg *arg = opaq;
1667         struct ldlm_lock_desc   d;
1668         int                  rc;
1669         struct ldlm_lock       *lock;
1670
1671         if (list_empty(arg->list))
1672                 return -ENOENT;
1673
1674         lock = list_entry(arg->list->next, struct ldlm_lock, l_bl_ast);
1675
1676         /* nobody should touch l_bl_ast */
1677         lock_res_and_lock(lock);
1678         list_del_init(&lock->l_bl_ast);
1679
1680         LASSERT(lock->l_flags & LDLM_FL_AST_SENT);
1681         LASSERT(lock->l_bl_ast_run == 0);
1682         LASSERT(lock->l_blocking_lock);
1683         lock->l_bl_ast_run++;
1684         unlock_res_and_lock(lock);
1685
1686         ldlm_lock2desc(lock->l_blocking_lock, &d);
1687
1688         rc = lock->l_blocking_ast(lock, &d, (void *)arg, LDLM_CB_BLOCKING);
1689         LDLM_LOCK_RELEASE(lock->l_blocking_lock);
1690         lock->l_blocking_lock = NULL;
1691         LDLM_LOCK_RELEASE(lock);
1692
1693         return rc;
1694 }
1695
1696 /**
1697  * Process a call to completion AST callback for a lock in ast_work list
1698  */
1699 static int
1700 ldlm_work_cp_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
1701 {
1702         struct ldlm_cb_set_arg  *arg = opaq;
1703         int                   rc = 0;
1704         struct ldlm_lock        *lock;
1705         ldlm_completion_callback completion_callback;
1706
1707         if (list_empty(arg->list))
1708                 return -ENOENT;
1709
1710         lock = list_entry(arg->list->next, struct ldlm_lock, l_cp_ast);
1711
1712         /* It's possible to receive a completion AST before we've set
1713          * the l_completion_ast pointer: either because the AST arrived
1714          * before the reply, or simply because there's a small race
1715          * window between receiving the reply and finishing the local
1716          * enqueue. (bug 842)
1717          *
1718          * This can't happen with the blocking_ast, however, because we
1719          * will never call the local blocking_ast until we drop our
1720          * reader/writer reference, which we won't do until we get the
1721          * reply and finish enqueueing. */
1722
1723         /* nobody should touch l_cp_ast */
1724         lock_res_and_lock(lock);
1725         list_del_init(&lock->l_cp_ast);
1726         LASSERT(lock->l_flags & LDLM_FL_CP_REQD);
1727         /* save l_completion_ast since it can be changed by
1728          * mds_intent_policy(), see bug 14225 */
1729         completion_callback = lock->l_completion_ast;
1730         lock->l_flags &= ~LDLM_FL_CP_REQD;
1731         unlock_res_and_lock(lock);
1732
1733         if (completion_callback != NULL)
1734                 rc = completion_callback(lock, 0, (void *)arg);
1735         LDLM_LOCK_RELEASE(lock);
1736
1737         return rc;
1738 }
1739
1740 /**
1741  * Process a call to revocation AST callback for a lock in ast_work list
1742  */
1743 static int
1744 ldlm_work_revoke_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
1745 {
1746         struct ldlm_cb_set_arg *arg = opaq;
1747         struct ldlm_lock_desc   desc;
1748         int                  rc;
1749         struct ldlm_lock       *lock;
1750
1751         if (list_empty(arg->list))
1752                 return -ENOENT;
1753
1754         lock = list_entry(arg->list->next, struct ldlm_lock, l_rk_ast);
1755         list_del_init(&lock->l_rk_ast);
1756
1757         /* the desc just pretend to exclusive */
1758         ldlm_lock2desc(lock, &desc);
1759         desc.l_req_mode = LCK_EX;
1760         desc.l_granted_mode = 0;
1761
1762         rc = lock->l_blocking_ast(lock, &desc, (void *)arg, LDLM_CB_BLOCKING);
1763         LDLM_LOCK_RELEASE(lock);
1764
1765         return rc;
1766 }
1767
1768 /**
1769  * Process a call to glimpse AST callback for a lock in ast_work list
1770  */
1771 int ldlm_work_gl_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
1772 {
1773         struct ldlm_cb_set_arg          *arg = opaq;
1774         struct ldlm_glimpse_work        *gl_work;
1775         struct ldlm_lock                *lock;
1776         int                              rc = 0;
1777
1778         if (list_empty(arg->list))
1779                 return -ENOENT;
1780
1781         gl_work = list_entry(arg->list->next, struct ldlm_glimpse_work,
1782                                  gl_list);
1783         list_del_init(&gl_work->gl_list);
1784
1785         lock = gl_work->gl_lock;
1786
1787         /* transfer the glimpse descriptor to ldlm_cb_set_arg */
1788         arg->gl_desc = gl_work->gl_desc;
1789
1790         /* invoke the actual glimpse callback */
1791         if (lock->l_glimpse_ast(lock, (void *)arg) == 0)
1792                 rc = 1;
1793
1794         LDLM_LOCK_RELEASE(lock);
1795
1796         if ((gl_work->gl_flags & LDLM_GL_WORK_NOFREE) == 0)
1797                 OBD_FREE_PTR(gl_work);
1798
1799         return rc;
1800 }
1801
1802 /**
1803  * Process list of locks in need of ASTs being sent.
1804  *
1805  * Used on server to send multiple ASTs together instead of sending one by
1806  * one.
1807  */
1808 int ldlm_run_ast_work(struct ldlm_namespace *ns, struct list_head *rpc_list,
1809                       ldlm_desc_ast_t ast_type)
1810 {
1811         struct ldlm_cb_set_arg *arg;
1812         set_producer_func       work_ast_lock;
1813         int                  rc;
1814
1815         if (list_empty(rpc_list))
1816                 return 0;
1817
1818         OBD_ALLOC_PTR(arg);
1819         if (arg == NULL)
1820                 return -ENOMEM;
1821
1822         atomic_set(&arg->restart, 0);
1823         arg->list = rpc_list;
1824
1825         switch (ast_type) {
1826                 case LDLM_WORK_BL_AST:
1827                         arg->type = LDLM_BL_CALLBACK;
1828                         work_ast_lock = ldlm_work_bl_ast_lock;
1829                         break;
1830                 case LDLM_WORK_CP_AST:
1831                         arg->type = LDLM_CP_CALLBACK;
1832                         work_ast_lock = ldlm_work_cp_ast_lock;
1833                         break;
1834                 case LDLM_WORK_REVOKE_AST:
1835                         arg->type = LDLM_BL_CALLBACK;
1836                         work_ast_lock = ldlm_work_revoke_ast_lock;
1837                         break;
1838                 case LDLM_WORK_GL_AST:
1839                         arg->type = LDLM_GL_CALLBACK;
1840                         work_ast_lock = ldlm_work_gl_ast_lock;
1841                         break;
1842                 default:
1843                         LBUG();
1844         }
1845
1846         /* We create a ptlrpc request set with flow control extension.
1847          * This request set will use the work_ast_lock function to produce new
1848          * requests and will send a new request each time one completes in order
1849          * to keep the number of requests in flight to ns_max_parallel_ast */
1850         arg->set = ptlrpc_prep_fcset(ns->ns_max_parallel_ast ? : UINT_MAX,
1851                                      work_ast_lock, arg);
1852         if (arg->set == NULL) {
1853                 rc = -ENOMEM;
1854                 goto out;
1855         }
1856
1857         ptlrpc_set_wait(arg->set);
1858         ptlrpc_set_destroy(arg->set);
1859
1860         rc = atomic_read(&arg->restart) ? -ERESTART : 0;
1861         goto out;
1862 out:
1863         OBD_FREE_PTR(arg);
1864         return rc;
1865 }
1866
1867 static int reprocess_one_queue(struct ldlm_resource *res, void *closure)
1868 {
1869         ldlm_reprocess_all(res);
1870         return LDLM_ITER_CONTINUE;
1871 }
1872
1873 static int ldlm_reprocess_res(struct cfs_hash *hs, struct cfs_hash_bd *bd,
1874                               struct hlist_node *hnode, void *arg)
1875 {
1876         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
1877         int    rc;
1878
1879         rc = reprocess_one_queue(res, arg);
1880
1881         return rc == LDLM_ITER_STOP;
1882 }
1883
1884 /**
1885  * Iterate through all resources on a namespace attempting to grant waiting
1886  * locks.
1887  */
1888 void ldlm_reprocess_all_ns(struct ldlm_namespace *ns)
1889 {
1890         if (ns != NULL) {
1891                 cfs_hash_for_each_nolock(ns->ns_rs_hash,
1892                                          ldlm_reprocess_res, NULL);
1893         }
1894 }
1895 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
1896
1897 /**
1898  * Try to grant all waiting locks on a resource.
1899  *
1900  * Calls ldlm_reprocess_queue on converting and waiting queues.
1901  *
1902  * Typically called after some resource locks are cancelled to see
1903  * if anything could be granted as a result of the cancellation.
1904  */
1905 void ldlm_reprocess_all(struct ldlm_resource *res)
1906 {
1907         LIST_HEAD(rpc_list);
1908
1909         if (!ns_is_client(ldlm_res_to_ns(res))) {
1910                 CERROR("This is client-side-only module, cannot handle LDLM_NAMESPACE_SERVER resource type lock.\n");
1911                 LBUG();
1912         }
1913 }
1914
1915 /**
1916  * Helper function to call blocking AST for LDLM lock \a lock in a
1917  * "cancelling" mode.
1918  */
1919 void ldlm_cancel_callback(struct ldlm_lock *lock)
1920 {
1921         check_res_locked(lock->l_resource);
1922         if (!(lock->l_flags & LDLM_FL_CANCEL)) {
1923                 lock->l_flags |= LDLM_FL_CANCEL;
1924                 if (lock->l_blocking_ast) {
1925                         unlock_res_and_lock(lock);
1926                         lock->l_blocking_ast(lock, NULL, lock->l_ast_data,
1927                                              LDLM_CB_CANCELING);
1928                         lock_res_and_lock(lock);
1929                 } else {
1930                         LDLM_DEBUG(lock, "no blocking ast");
1931                 }
1932         }
1933         lock->l_flags |= LDLM_FL_BL_DONE;
1934 }
1935
1936 /**
1937  * Remove skiplist-enabled LDLM lock \a req from granted list
1938  */
1939 void ldlm_unlink_lock_skiplist(struct ldlm_lock *req)
1940 {
1941         if (req->l_resource->lr_type != LDLM_PLAIN &&
1942             req->l_resource->lr_type != LDLM_IBITS)
1943                 return;
1944
1945         list_del_init(&req->l_sl_policy);
1946         list_del_init(&req->l_sl_mode);
1947 }
1948
1949 /**
1950  * Attempts to cancel LDLM lock \a lock that has no reader/writer references.
1951  */
1952 void ldlm_lock_cancel(struct ldlm_lock *lock)
1953 {
1954         struct ldlm_resource *res;
1955         struct ldlm_namespace *ns;
1956
1957         lock_res_and_lock(lock);
1958
1959         res = lock->l_resource;
1960         ns  = ldlm_res_to_ns(res);
1961
1962         /* Please do not, no matter how tempting, remove this LBUG without
1963          * talking to me first. -phik */
1964         if (lock->l_readers || lock->l_writers) {
1965                 LDLM_ERROR(lock, "lock still has references");
1966                 LBUG();
1967         }
1968
1969         if (lock->l_flags & LDLM_FL_WAITED)
1970                 ldlm_del_waiting_lock(lock);
1971
1972         /* Releases cancel callback. */
1973         ldlm_cancel_callback(lock);
1974
1975         /* Yes, second time, just in case it was added again while we were
1976          * running with no res lock in ldlm_cancel_callback */
1977         if (lock->l_flags & LDLM_FL_WAITED)
1978                 ldlm_del_waiting_lock(lock);
1979
1980         ldlm_resource_unlink_lock(lock);
1981         ldlm_lock_destroy_nolock(lock);
1982
1983         if (lock->l_granted_mode == lock->l_req_mode)
1984                 ldlm_pool_del(&ns->ns_pool, lock);
1985
1986         /* Make sure we will not be called again for same lock what is possible
1987          * if not to zero out lock->l_granted_mode */
1988         lock->l_granted_mode = LCK_MINMODE;
1989         unlock_res_and_lock(lock);
1990 }
1991 EXPORT_SYMBOL(ldlm_lock_cancel);
1992
1993 /**
1994  * Set opaque data into the lock that only makes sense to upper layer.
1995  */
1996 int ldlm_lock_set_data(struct lustre_handle *lockh, void *data)
1997 {
1998         struct ldlm_lock *lock = ldlm_handle2lock(lockh);
1999         int rc = -EINVAL;
2000
2001         if (lock) {
2002                 if (lock->l_ast_data == NULL)
2003                         lock->l_ast_data = data;
2004                 if (lock->l_ast_data == data)
2005                         rc = 0;
2006                 LDLM_LOCK_PUT(lock);
2007         }
2008         return rc;
2009 }
2010 EXPORT_SYMBOL(ldlm_lock_set_data);
2011
2012 struct export_cl_data {
2013         struct obd_export       *ecl_exp;
2014         int                     ecl_loop;
2015 };
2016
2017 /**
2018  * Iterator function for ldlm_cancel_locks_for_export.
2019  * Cancels passed locks.
2020  */
2021 int ldlm_cancel_locks_for_export_cb(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2022                                     struct hlist_node *hnode, void *data)
2023
2024 {
2025         struct export_cl_data   *ecl = (struct export_cl_data *)data;
2026         struct obd_export       *exp  = ecl->ecl_exp;
2027         struct ldlm_lock     *lock = cfs_hash_object(hs, hnode);
2028         struct ldlm_resource *res;
2029
2030         res = ldlm_resource_getref(lock->l_resource);
2031         LDLM_LOCK_GET(lock);
2032
2033         LDLM_DEBUG(lock, "export %p", exp);
2034         ldlm_res_lvbo_update(res, NULL, 1);
2035         ldlm_lock_cancel(lock);
2036         ldlm_reprocess_all(res);
2037         ldlm_resource_putref(res);
2038         LDLM_LOCK_RELEASE(lock);
2039
2040         ecl->ecl_loop++;
2041         if ((ecl->ecl_loop & -ecl->ecl_loop) == ecl->ecl_loop) {
2042                 CDEBUG(D_INFO,
2043                        "Cancel lock %p for export %p (loop %d), still have %d locks left on hash table.\n",
2044                        lock, exp, ecl->ecl_loop,
2045                        atomic_read(&hs->hs_count));
2046         }
2047
2048         return 0;
2049 }
2050
2051 /**
2052  * Cancel all locks for given export.
2053  *
2054  * Typically called on client disconnection/eviction
2055  */
2056 void ldlm_cancel_locks_for_export(struct obd_export *exp)
2057 {
2058         struct export_cl_data   ecl = {
2059                 .ecl_exp        = exp,
2060                 .ecl_loop       = 0,
2061         };
2062
2063         cfs_hash_for_each_empty(exp->exp_lock_hash,
2064                                 ldlm_cancel_locks_for_export_cb, &ecl);
2065 }
2066
2067 /**
2068  * Downgrade an exclusive lock.
2069  *
2070  * A fast variant of ldlm_lock_convert for conversion of exclusive
2071  * locks. The conversion is always successful.
2072  * Used by Commit on Sharing (COS) code.
2073  *
2074  * \param lock A lock to convert
2075  * \param new_mode new lock mode
2076  */
2077 void ldlm_lock_downgrade(struct ldlm_lock *lock, int new_mode)
2078 {
2079         LASSERT(lock->l_granted_mode & (LCK_PW | LCK_EX));
2080         LASSERT(new_mode == LCK_COS);
2081
2082         lock_res_and_lock(lock);
2083         ldlm_resource_unlink_lock(lock);
2084         /*
2085          * Remove the lock from pool as it will be added again in
2086          * ldlm_grant_lock() called below.
2087          */
2088         ldlm_pool_del(&ldlm_lock_to_ns(lock)->ns_pool, lock);
2089
2090         lock->l_req_mode = new_mode;
2091         ldlm_grant_lock(lock, NULL);
2092         unlock_res_and_lock(lock);
2093         ldlm_reprocess_all(lock->l_resource);
2094 }
2095 EXPORT_SYMBOL(ldlm_lock_downgrade);
2096
2097 /**
2098  * Attempt to convert already granted lock to a different mode.
2099  *
2100  * While lock conversion is not currently used, future client-side
2101  * optimizations could take advantage of it to avoid discarding cached
2102  * pages on a file.
2103  */
2104 struct ldlm_resource *ldlm_lock_convert(struct ldlm_lock *lock, int new_mode,
2105                                         __u32 *flags)
2106 {
2107         LIST_HEAD(rpc_list);
2108         struct ldlm_resource *res;
2109         struct ldlm_namespace *ns;
2110         int granted = 0;
2111         struct ldlm_interval *node;
2112
2113         /* Just return if mode is unchanged. */
2114         if (new_mode == lock->l_granted_mode) {
2115                 *flags |= LDLM_FL_BLOCK_GRANTED;
2116                 return lock->l_resource;
2117         }
2118
2119         /* I can't check the type of lock here because the bitlock of lock
2120          * is not held here, so do the allocation blindly. -jay */
2121         OBD_SLAB_ALLOC_PTR_GFP(node, ldlm_interval_slab, GFP_NOFS);
2122         if (node == NULL)
2123                 /* Actually, this causes EDEADLOCK to be returned */
2124                 return NULL;
2125
2126         LASSERTF((new_mode == LCK_PW && lock->l_granted_mode == LCK_PR),
2127                  "new_mode %u, granted %u\n", new_mode, lock->l_granted_mode);
2128
2129         lock_res_and_lock(lock);
2130
2131         res = lock->l_resource;
2132         ns  = ldlm_res_to_ns(res);
2133
2134         lock->l_req_mode = new_mode;
2135         if (res->lr_type == LDLM_PLAIN || res->lr_type == LDLM_IBITS) {
2136                 ldlm_resource_unlink_lock(lock);
2137         } else {
2138                 ldlm_resource_unlink_lock(lock);
2139                 if (res->lr_type == LDLM_EXTENT) {
2140                         /* FIXME: ugly code, I have to attach the lock to a
2141                          * interval node again since perhaps it will be granted
2142                          * soon */
2143                         INIT_LIST_HEAD(&node->li_group);
2144                         ldlm_interval_attach(node, lock);
2145                         node = NULL;
2146                 }
2147         }
2148
2149         /*
2150          * Remove old lock from the pool before adding the lock with new
2151          * mode below in ->policy()
2152          */
2153         ldlm_pool_del(&ns->ns_pool, lock);
2154
2155         /* If this is a local resource, put it on the appropriate list. */
2156         if (ns_is_client(ldlm_res_to_ns(res))) {
2157                 if (*flags & (LDLM_FL_BLOCK_CONV | LDLM_FL_BLOCK_GRANTED)) {
2158                         ldlm_resource_add_lock(res, &res->lr_converting, lock);
2159                 } else {
2160                         /* This should never happen, because of the way the
2161                          * server handles conversions. */
2162                         LDLM_ERROR(lock, "Erroneous flags %x on local lock\n",
2163                                    *flags);
2164                         LBUG();
2165
2166                         ldlm_grant_lock(lock, &rpc_list);
2167                         granted = 1;
2168                         /* FIXME: completion handling not with lr_lock held ! */
2169                         if (lock->l_completion_ast)
2170                                 lock->l_completion_ast(lock, 0, NULL);
2171                 }
2172         } else {
2173                 CERROR("This is client-side-only module, cannot handle LDLM_NAMESPACE_SERVER resource type lock.\n");
2174                 LBUG();
2175         }
2176         unlock_res_and_lock(lock);
2177
2178         if (granted)
2179                 ldlm_run_ast_work(ns, &rpc_list, LDLM_WORK_CP_AST);
2180         if (node)
2181                 OBD_SLAB_FREE(node, ldlm_interval_slab, sizeof(*node));
2182         return res;
2183 }
2184 EXPORT_SYMBOL(ldlm_lock_convert);
2185
2186 /**
2187  * Print lock with lock handle \a lockh description into debug log.
2188  *
2189  * Used when printing all locks on a resource for debug purposes.
2190  */
2191 void ldlm_lock_dump_handle(int level, struct lustre_handle *lockh)
2192 {
2193         struct ldlm_lock *lock;
2194
2195         if (!((libcfs_debug | D_ERROR) & level))
2196                 return;
2197
2198         lock = ldlm_handle2lock(lockh);
2199         if (lock == NULL)
2200                 return;
2201
2202         LDLM_DEBUG_LIMIT(level, lock, "###");
2203
2204         LDLM_LOCK_PUT(lock);
2205 }
2206 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2207
2208 /**
2209  * Print lock information with custom message into debug log.
2210  * Helper function.
2211  */
2212 void _ldlm_lock_debug(struct ldlm_lock *lock,
2213                       struct libcfs_debug_msg_data *msgdata,
2214                       const char *fmt, ...)
2215 {
2216         va_list args;
2217         struct obd_export *exp = lock->l_export;
2218         struct ldlm_resource *resource = lock->l_resource;
2219         char *nid = "local";
2220
2221         va_start(args, fmt);
2222
2223         if (exp && exp->exp_connection) {
2224                 nid = libcfs_nid2str(exp->exp_connection->c_peer.nid);
2225         } else if (exp && exp->exp_obd != NULL) {
2226                 struct obd_import *imp = exp->exp_obd->u.cli.cl_import;
2227
2228                 nid = libcfs_nid2str(imp->imp_connection->c_peer.nid);
2229         }
2230
2231         if (resource == NULL) {
2232                 libcfs_debug_vmsg2(msgdata, fmt, args,
2233                                    " ns: \?\? lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: \?\? rrc=\?\? type: \?\?\? flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lu lvb_type: %d\n",
2234                                    lock,
2235                                    lock->l_handle.h_cookie, atomic_read(&lock->l_refc),
2236                                    lock->l_readers, lock->l_writers,
2237                                    ldlm_lockname[lock->l_granted_mode],
2238                                    ldlm_lockname[lock->l_req_mode],
2239                                    lock->l_flags, nid, lock->l_remote_handle.cookie,
2240                                    exp ? atomic_read(&exp->exp_refcount) : -99,
2241                                    lock->l_pid, lock->l_callback_timeout, lock->l_lvb_type);
2242                 va_end(args);
2243                 return;
2244         }
2245
2246         switch (resource->lr_type) {
2247         case LDLM_EXTENT:
2248                 libcfs_debug_vmsg2(msgdata, fmt, args,
2249                                    " ns: %s lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: " DLDLMRES " rrc: %d type: %s [%llu->%llu] (req %llu->%llu) flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lu lvb_type: %d\n",
2250                                    ldlm_lock_to_ns_name(lock), lock,
2251                                    lock->l_handle.h_cookie, atomic_read(&lock->l_refc),
2252                                    lock->l_readers, lock->l_writers,
2253                                    ldlm_lockname[lock->l_granted_mode],
2254                                    ldlm_lockname[lock->l_req_mode],
2255                                    PLDLMRES(resource),
2256                                    atomic_read(&resource->lr_refcount),
2257                                    ldlm_typename[resource->lr_type],
2258                                    lock->l_policy_data.l_extent.start,
2259                                    lock->l_policy_data.l_extent.end,
2260                                    lock->l_req_extent.start, lock->l_req_extent.end,
2261                                    lock->l_flags, nid, lock->l_remote_handle.cookie,
2262                                    exp ? atomic_read(&exp->exp_refcount) : -99,
2263                                    lock->l_pid, lock->l_callback_timeout,
2264                                    lock->l_lvb_type);
2265                 break;
2266
2267         case LDLM_FLOCK:
2268                 libcfs_debug_vmsg2(msgdata, fmt, args,
2269                                    " ns: %s lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: " DLDLMRES " rrc: %d type: %s pid: %d [%llu->%llu] flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lu\n",
2270                                    ldlm_lock_to_ns_name(lock), lock,
2271                                    lock->l_handle.h_cookie, atomic_read(&lock->l_refc),
2272                                    lock->l_readers, lock->l_writers,
2273                                    ldlm_lockname[lock->l_granted_mode],
2274                                    ldlm_lockname[lock->l_req_mode],
2275                                    PLDLMRES(resource),
2276                                    atomic_read(&resource->lr_refcount),
2277                                    ldlm_typename[resource->lr_type],
2278                                    lock->l_policy_data.l_flock.pid,
2279                                    lock->l_policy_data.l_flock.start,
2280                                    lock->l_policy_data.l_flock.end,
2281                                    lock->l_flags, nid, lock->l_remote_handle.cookie,
2282                                    exp ? atomic_read(&exp->exp_refcount) : -99,
2283                                    lock->l_pid, lock->l_callback_timeout);
2284                 break;
2285
2286         case LDLM_IBITS:
2287                 libcfs_debug_vmsg2(msgdata, fmt, args,
2288                                    " ns: %s lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: " DLDLMRES " bits %#llx rrc: %d type: %s flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lu lvb_type: %d\n",
2289                                    ldlm_lock_to_ns_name(lock),
2290                                    lock, lock->l_handle.h_cookie,
2291                                    atomic_read(&lock->l_refc),
2292                                    lock->l_readers, lock->l_writers,
2293                                    ldlm_lockname[lock->l_granted_mode],
2294                                    ldlm_lockname[lock->l_req_mode],
2295                                    PLDLMRES(resource),
2296                                    lock->l_policy_data.l_inodebits.bits,
2297                                    atomic_read(&resource->lr_refcount),
2298                                    ldlm_typename[resource->lr_type],
2299                                    lock->l_flags, nid, lock->l_remote_handle.cookie,
2300                                    exp ? atomic_read(&exp->exp_refcount) : -99,
2301                                    lock->l_pid, lock->l_callback_timeout,
2302                                    lock->l_lvb_type);
2303                 break;
2304
2305         default:
2306                 libcfs_debug_vmsg2(msgdata, fmt, args,
2307                                    " ns: %s lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: " DLDLMRES " rrc: %d type: %s flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lu lvb_type: %d\n",
2308                                    ldlm_lock_to_ns_name(lock),
2309                                    lock, lock->l_handle.h_cookie,
2310                                    atomic_read(&lock->l_refc),
2311                                    lock->l_readers, lock->l_writers,
2312                                    ldlm_lockname[lock->l_granted_mode],
2313                                    ldlm_lockname[lock->l_req_mode],
2314                                    PLDLMRES(resource),
2315                                    atomic_read(&resource->lr_refcount),
2316                                    ldlm_typename[resource->lr_type],
2317                                    lock->l_flags, nid, lock->l_remote_handle.cookie,
2318                                    exp ? atomic_read(&exp->exp_refcount) : -99,
2319                                    lock->l_pid, lock->l_callback_timeout,
2320                                    lock->l_lvb_type);
2321                 break;
2322         }
2323         va_end(args);
2324 }
2325 EXPORT_SYMBOL(_ldlm_lock_debug);