Whamcloud - gitweb
LU-6142 lustre: use list_first/last_entry() for list heads
[fs/lustre-release.git] / 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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2010, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/ldlm/ldlm_lock.c
32  *
33  * Author: Peter Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_LDLM
38
39 #include <libcfs/libcfs.h>
40
41 #include <lustre_swab.h>
42 #include <obd_class.h>
43
44 #include "ldlm_internal.h"
45
46 struct kmem_cache *ldlm_glimpse_work_kmem;
47 EXPORT_SYMBOL(ldlm_glimpse_work_kmem);
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
70 static ldlm_policy_wire_to_local_t ldlm_policy_wire_to_local[] = {
71         [LDLM_PLAIN - LDLM_MIN_TYPE]  = ldlm_plain_policy_wire_to_local,
72         [LDLM_EXTENT - LDLM_MIN_TYPE] = ldlm_extent_policy_wire_to_local,
73         [LDLM_FLOCK - LDLM_MIN_TYPE]  = ldlm_flock_policy_wire_to_local,
74         [LDLM_IBITS - LDLM_MIN_TYPE]  = ldlm_ibits_policy_wire_to_local,
75 };
76
77 static ldlm_policy_local_to_wire_t ldlm_policy_local_to_wire[] = {
78         [LDLM_PLAIN - LDLM_MIN_TYPE]  = ldlm_plain_policy_local_to_wire,
79         [LDLM_EXTENT - LDLM_MIN_TYPE] = ldlm_extent_policy_local_to_wire,
80         [LDLM_FLOCK - LDLM_MIN_TYPE]  = ldlm_flock_policy_local_to_wire,
81         [LDLM_IBITS - LDLM_MIN_TYPE]  = ldlm_ibits_policy_local_to_wire,
82 };
83
84 /**
85  * Converts lock policy from local format to on the wire lock_desc format
86  */
87 void ldlm_convert_policy_to_wire(enum ldlm_type type,
88                                  const union ldlm_policy_data *lpolicy,
89                                  union ldlm_wire_policy_data *wpolicy)
90 {
91         ldlm_policy_local_to_wire_t convert;
92
93         convert = ldlm_policy_local_to_wire[type - LDLM_MIN_TYPE];
94
95         convert(lpolicy, wpolicy);
96 }
97
98 /**
99  * Converts lock policy from on the wire lock_desc format to local format
100  */
101 void ldlm_convert_policy_to_local(struct obd_export *exp, enum ldlm_type type,
102                                   const union ldlm_wire_policy_data *wpolicy,
103                                   union ldlm_policy_data *lpolicy)
104 {
105         ldlm_policy_wire_to_local_t convert;
106
107         convert = ldlm_policy_wire_to_local[type - LDLM_MIN_TYPE];
108
109         convert(wpolicy, lpolicy);
110 }
111
112 const char *ldlm_it2str(enum ldlm_intent_flags it)
113 {
114         switch (it) {
115         case IT_OPEN:
116                 return "open";
117         case IT_CREAT:
118                 return "creat";
119         case (IT_OPEN | IT_CREAT):
120                 return "open|creat";
121         case IT_READDIR:
122                 return "readdir";
123         case IT_GETATTR:
124                 return "getattr";
125         case IT_LOOKUP:
126                 return "lookup";
127         case IT_GETXATTR:
128                 return "getxattr";
129         case IT_LAYOUT:
130                 return "layout";
131         default:
132                 CERROR("Unknown intent 0x%08x\n", it);
133                 return "UNKNOWN";
134         }
135 }
136 EXPORT_SYMBOL(ldlm_it2str);
137
138 #ifdef HAVE_SERVER_SUPPORT
139 static ldlm_processing_policy ldlm_processing_policy_table[] = {
140         [LDLM_PLAIN]    = ldlm_process_plain_lock,
141         [LDLM_EXTENT]   = ldlm_process_extent_lock,
142         [LDLM_FLOCK]    = ldlm_process_flock_lock,
143         [LDLM_IBITS]    = ldlm_process_inodebits_lock,
144 };
145
146 ldlm_processing_policy ldlm_get_processing_policy(struct ldlm_resource *res)
147 {
148         return ldlm_processing_policy_table[res->lr_type];
149 }
150 EXPORT_SYMBOL(ldlm_get_processing_policy);
151
152 static ldlm_reprocessing_policy ldlm_reprocessing_policy_table[] = {
153         [LDLM_PLAIN]    = ldlm_reprocess_queue,
154         [LDLM_EXTENT]   = ldlm_reprocess_queue,
155         [LDLM_FLOCK]    = ldlm_reprocess_queue,
156         [LDLM_IBITS]    = ldlm_reprocess_inodebits_queue,
157 };
158
159 ldlm_reprocessing_policy ldlm_get_reprocessing_policy(struct ldlm_resource *res)
160 {
161         return ldlm_reprocessing_policy_table[res->lr_type];
162 }
163
164 #endif /* HAVE_SERVER_SUPPORT */
165
166 void ldlm_register_intent(struct ldlm_namespace *ns, ldlm_res_policy arg)
167 {
168         ns->ns_policy = arg;
169 }
170 EXPORT_SYMBOL(ldlm_register_intent);
171
172 /*
173  * REFCOUNTED LOCK OBJECTS
174  */
175
176
177 /**
178  * Get a reference on a lock.
179  *
180  * Lock refcounts, during creation:
181  *   - one special one for allocation, dec'd only once in destroy
182  *   - one for being a lock that's in-use
183  *   - one for the addref associated with a new lock
184  */
185 struct ldlm_lock *ldlm_lock_get(struct ldlm_lock *lock)
186 {
187         refcount_inc(&lock->l_handle.h_ref);
188         return lock;
189 }
190 EXPORT_SYMBOL(ldlm_lock_get);
191
192 static void lock_handle_free(struct rcu_head *rcu)
193 {
194         struct ldlm_lock *lock = container_of(rcu, struct ldlm_lock,
195                                               l_handle.h_rcu);
196
197         OBD_FREE_PRE(lock, sizeof(*lock), "slab-freed");
198         kmem_cache_free(ldlm_lock_slab, lock);
199 }
200
201 /**
202  * Release lock reference.
203  *
204  * Also frees the lock if it was last reference.
205  */
206 void ldlm_lock_put(struct ldlm_lock *lock)
207 {
208         ENTRY;
209
210         LASSERT(lock->l_resource != LP_POISON);
211         LASSERT(refcount_read(&lock->l_handle.h_ref) > 0);
212         if (refcount_dec_and_test(&lock->l_handle.h_ref)) {
213                 struct ldlm_resource *res;
214
215                 LDLM_DEBUG(lock,
216                            "final lock_put on destroyed lock, freeing it.");
217
218                 res = lock->l_resource;
219                 LASSERT(ldlm_is_destroyed(lock));
220                 LASSERT(list_empty(&lock->l_exp_list));
221                 LASSERT(list_empty(&lock->l_res_link));
222                 LASSERT(list_empty(&lock->l_pending_chain));
223
224                 lprocfs_counter_decr(ldlm_res_to_ns(res)->ns_stats,
225                                      LDLM_NSS_LOCKS);
226                 lu_ref_del(&res->lr_reference, "lock", lock);
227                 if (lock->l_export) {
228                         class_export_lock_put(lock->l_export, lock);
229                         lock->l_export = NULL;
230                 }
231
232                 if (lock->l_lvb_data != NULL)
233                         OBD_FREE_LARGE(lock->l_lvb_data, lock->l_lvb_len);
234
235                 if (res->lr_type == LDLM_EXTENT) {
236                         ldlm_interval_free(ldlm_interval_detach(lock));
237                 } else if (res->lr_type == LDLM_IBITS) {
238                         if (lock->l_ibits_node != NULL)
239                                 OBD_SLAB_FREE_PTR(lock->l_ibits_node,
240                                                   ldlm_inodebits_slab);
241                 }
242                 ldlm_resource_putref(res);
243                 lock->l_resource = NULL;
244                 lu_ref_fini(&lock->l_reference);
245                 call_rcu(&lock->l_handle.h_rcu, lock_handle_free);
246         }
247
248         EXIT;
249 }
250 EXPORT_SYMBOL(ldlm_lock_put);
251
252 /**
253  * Removes LDLM lock \a lock from LRU. Assumes LRU is already locked.
254  */
255 int ldlm_lock_remove_from_lru_nolock(struct ldlm_lock *lock)
256 {
257         int rc = 0;
258         if (!list_empty(&lock->l_lru)) {
259                 struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
260
261                 LASSERT(lock->l_resource->lr_type != LDLM_FLOCK);
262                 if (ns->ns_last_pos == &lock->l_lru)
263                         ns->ns_last_pos = lock->l_lru.prev;
264                 list_del_init(&lock->l_lru);
265                 LASSERT(ns->ns_nr_unused > 0);
266                 ns->ns_nr_unused--;
267                 rc = 1;
268         }
269         return rc;
270 }
271
272 /**
273  * Removes LDLM lock \a lock from LRU. Obtains the LRU lock first.
274  *
275  * If \a last_use is non-zero, it will remove the lock from LRU only if
276  * it matches lock's l_last_used.
277  *
278  * \retval 0 if \a last_use is set, the lock is not in LRU list or \a last_use
279  *           doesn't match lock's l_last_used;
280  *           otherwise, the lock hasn't been in the LRU list.
281  * \retval 1 the lock was in LRU list and removed.
282  */
283 int ldlm_lock_remove_from_lru_check(struct ldlm_lock *lock, ktime_t last_use)
284 {
285         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
286         int rc = 0;
287
288         ENTRY;
289         if (ldlm_is_ns_srv(lock)) {
290                 LASSERT(list_empty(&lock->l_lru));
291                 RETURN(0);
292         }
293
294         spin_lock(&ns->ns_lock);
295         if (!ktime_compare(last_use, ktime_set(0, 0)) ||
296             !ktime_compare(last_use, lock->l_last_used))
297                 rc = ldlm_lock_remove_from_lru_nolock(lock);
298         spin_unlock(&ns->ns_lock);
299
300         RETURN(rc);
301 }
302
303 /**
304  * Adds LDLM lock \a lock to namespace LRU. Assumes LRU is already locked.
305  */
306 void ldlm_lock_add_to_lru_nolock(struct ldlm_lock *lock)
307 {
308         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
309
310         lock->l_last_used = ktime_get();
311         LASSERT(list_empty(&lock->l_lru));
312         LASSERT(lock->l_resource->lr_type != LDLM_FLOCK);
313         list_add_tail(&lock->l_lru, &ns->ns_unused_list);
314         LASSERT(ns->ns_nr_unused >= 0);
315         ns->ns_nr_unused++;
316 }
317
318 /**
319  * Adds LDLM lock \a lock to namespace LRU. Obtains necessary LRU locks
320  * first.
321  */
322 static void ldlm_lock_add_to_lru(struct ldlm_lock *lock)
323 {
324         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
325
326         ENTRY;
327         spin_lock(&ns->ns_lock);
328         ldlm_lock_add_to_lru_nolock(lock);
329         spin_unlock(&ns->ns_lock);
330         EXIT;
331 }
332
333 /**
334  * Moves LDLM lock \a lock that is already in namespace LRU to the tail of
335  * the LRU. Performs necessary LRU locking
336  */
337 void ldlm_lock_touch_in_lru(struct ldlm_lock *lock)
338 {
339         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
340
341         ENTRY;
342         if (ldlm_is_ns_srv(lock)) {
343                 LASSERT(list_empty(&lock->l_lru));
344                 EXIT;
345                 return;
346         }
347
348         spin_lock(&ns->ns_lock);
349         if (!list_empty(&lock->l_lru)) {
350                 ldlm_lock_remove_from_lru_nolock(lock);
351                 ldlm_lock_add_to_lru_nolock(lock);
352         }
353         spin_unlock(&ns->ns_lock);
354         EXIT;
355 }
356
357 /**
358  * Helper to destroy a locked lock.
359  *
360  * Used by ldlm_lock_destroy and ldlm_lock_destroy_nolock
361  * Must be called with l_lock and lr_lock held.
362  *
363  * Does not actually free the lock data, but rather marks the lock as
364  * destroyed by setting l_destroyed field in the lock to 1.  Destroys a
365  * handle->lock association too, so that the lock can no longer be found
366  * and removes the lock from LRU list.  Actual lock freeing occurs when
367  * last lock reference goes away.
368  *
369  * Original comment (of some historical value):
370  * This used to have a 'strict' flag, which recovery would use to mark an
371  * in-use lock as needing-to-die.  Lest I am ever tempted to put it back, I
372  * shall explain why it's gone: with the new hash table scheme, once you call
373  * ldlm_lock_destroy, you can never drop your final references on this lock.
374  * Because it's not in the hash table anymore.  -phil
375  */
376 static int ldlm_lock_destroy_internal(struct ldlm_lock *lock)
377 {
378         ENTRY;
379
380         if (lock->l_readers || lock->l_writers) {
381                 LDLM_ERROR(lock, "lock still has references");
382                 LBUG();
383         }
384
385         if (!list_empty(&lock->l_res_link)) {
386                 LDLM_ERROR(lock, "lock still on resource");
387                 LBUG();
388         }
389
390         if (ldlm_is_destroyed(lock)) {
391                 LASSERT(list_empty(&lock->l_lru));
392                 EXIT;
393                 return 0;
394         }
395         ldlm_set_destroyed(lock);
396         wake_up(&lock->l_waitq);
397
398         if (lock->l_export && lock->l_export->exp_lock_hash) {
399                 /* NB: it's safe to call cfs_hash_del() even lock isn't
400                  * in exp_lock_hash. */
401                 /* In the function below, .hs_keycmp resolves to
402                  * ldlm_export_lock_keycmp() */
403                 /* coverity[overrun-buffer-val] */
404                 cfs_hash_del(lock->l_export->exp_lock_hash,
405                              &lock->l_remote_handle, &lock->l_exp_hash);
406         }
407
408         ldlm_lock_remove_from_lru(lock);
409         class_handle_unhash(&lock->l_handle);
410
411         EXIT;
412         return 1;
413 }
414
415 /**
416  * Destroys a LDLM lock \a lock. Performs necessary locking first.
417  */
418 void ldlm_lock_destroy(struct ldlm_lock *lock)
419 {
420         int first;
421         ENTRY;
422         lock_res_and_lock(lock);
423         first = ldlm_lock_destroy_internal(lock);
424         unlock_res_and_lock(lock);
425
426         /* drop reference from hashtable only for first destroy */
427         if (first) {
428                 lu_ref_del(&lock->l_reference, "hash", lock);
429                 LDLM_LOCK_RELEASE(lock);
430         }
431         EXIT;
432 }
433
434 /**
435  * Destroys a LDLM lock \a lock that is already locked.
436  */
437 void ldlm_lock_destroy_nolock(struct ldlm_lock *lock)
438 {
439         int first;
440         ENTRY;
441         first = ldlm_lock_destroy_internal(lock);
442         /* drop reference from hashtable only for first destroy */
443         if (first) {
444                 lu_ref_del(&lock->l_reference, "hash", lock);
445                 LDLM_LOCK_RELEASE(lock);
446         }
447         EXIT;
448 }
449
450 static const char lock_handle_owner[] = "ldlm";
451
452 /**
453  *
454  * Allocate and initialize new lock structure.
455  *
456  * usage: pass in a resource on which you have done ldlm_resource_get
457  *        new lock will take over the refcount.
458  * returns: lock with refcount 2 - one for current caller and one for remote
459  */
460 static struct ldlm_lock *ldlm_lock_new(struct ldlm_resource *resource)
461 {
462         struct ldlm_lock *lock;
463         ENTRY;
464
465         if (resource == NULL)
466                 LBUG();
467
468         OBD_SLAB_ALLOC_PTR_GFP(lock, ldlm_lock_slab, GFP_NOFS);
469         if (lock == NULL)
470                 RETURN(NULL);
471
472         RCU_INIT_POINTER(lock->l_resource, resource);
473         lu_ref_add(&resource->lr_reference, "lock", lock);
474
475         refcount_set(&lock->l_handle.h_ref, 2);
476         INIT_LIST_HEAD(&lock->l_res_link);
477         INIT_LIST_HEAD(&lock->l_lru);
478         INIT_LIST_HEAD(&lock->l_pending_chain);
479         INIT_LIST_HEAD(&lock->l_bl_ast);
480         INIT_LIST_HEAD(&lock->l_cp_ast);
481         INIT_LIST_HEAD(&lock->l_rk_ast);
482         init_waitqueue_head(&lock->l_waitq);
483         lock->l_blocking_lock = NULL;
484         INIT_LIST_HEAD(&lock->l_sl_mode);
485         INIT_LIST_HEAD(&lock->l_sl_policy);
486         INIT_HLIST_NODE(&lock->l_exp_hash);
487         INIT_HLIST_NODE(&lock->l_exp_flock_hash);
488
489         lprocfs_counter_incr(ldlm_res_to_ns(resource)->ns_stats,
490                              LDLM_NSS_LOCKS);
491         INIT_HLIST_NODE(&lock->l_handle.h_link);
492         class_handle_hash(&lock->l_handle, lock_handle_owner);
493
494         lu_ref_init(&lock->l_reference);
495         lu_ref_add(&lock->l_reference, "hash", lock);
496         lock->l_callback_timestamp = 0;
497         lock->l_activity = 0;
498
499 #if LUSTRE_TRACKS_LOCK_EXP_REFS
500         INIT_LIST_HEAD(&lock->l_exp_refs_link);
501         lock->l_exp_refs_nr = 0;
502         lock->l_exp_refs_target = NULL;
503 #endif
504         INIT_LIST_HEAD(&lock->l_exp_list);
505
506         RETURN(lock);
507 }
508
509 /**
510  * Moves LDLM lock \a lock to another resource.
511  * This is used on client when server returns some other lock than requested
512  * (typically as a result of intent operation)
513  */
514 int ldlm_lock_change_resource(struct ldlm_namespace *ns, struct ldlm_lock *lock,
515                               const struct ldlm_res_id *new_resid)
516 {
517         struct ldlm_resource *oldres;
518         struct ldlm_resource *newres;
519         int type;
520         ENTRY;
521
522         LASSERT(ns_is_client(ns));
523
524         oldres = lock_res_and_lock(lock);
525         if (memcmp(new_resid, &oldres->lr_name,
526                    sizeof(oldres->lr_name)) == 0) {
527                 /* Nothing to do */
528                 unlock_res_and_lock(lock);
529                 RETURN(0);
530         }
531
532         LASSERT(new_resid->name[0] != 0);
533
534         /* This function assumes that the lock isn't on any lists */
535         LASSERT(list_empty(&lock->l_res_link));
536
537         type = oldres->lr_type;
538         unlock_res_and_lock(lock);
539
540         newres = ldlm_resource_get(ns, new_resid, type, 1);
541         if (IS_ERR(newres))
542                 RETURN(PTR_ERR(newres));
543
544         lu_ref_add(&newres->lr_reference, "lock", lock);
545         /*
546          * To flip the lock from the old to the new resource, oldres
547          * and newres have to be locked. Resource spin-locks are taken
548          * in the memory address order to avoid dead-locks.
549          * As this is the only circumstance where ->l_resource
550          * can change, and this cannot race with itself, it is safe
551          * to access lock->l_resource without being careful about locking.
552          */
553         oldres = lock->l_resource;
554         if (oldres < newres) {
555                 lock_res(oldres);
556                 lock_res_nested(newres, LRT_NEW);
557         } else {
558                 lock_res(newres);
559                 lock_res_nested(oldres, LRT_NEW);
560         }
561         LASSERT(memcmp(new_resid, &oldres->lr_name,
562                        sizeof oldres->lr_name) != 0);
563         rcu_assign_pointer(lock->l_resource, newres);
564         unlock_res(oldres);
565         unlock_res(newres);
566
567         /* ...and the flowers are still standing! */
568         lu_ref_del(&oldres->lr_reference, "lock", lock);
569         ldlm_resource_putref(oldres);
570
571         RETURN(0);
572 }
573
574 /** \defgroup ldlm_handles LDLM HANDLES
575  * Ways to get hold of locks without any addresses.
576  * @{
577  */
578
579 /**
580  * Fills in handle for LDLM lock \a lock into supplied \a lockh
581  * Does not take any references.
582  */
583 void ldlm_lock2handle(const struct ldlm_lock *lock, struct lustre_handle *lockh)
584 {
585         lockh->cookie = lock->l_handle.h_cookie;
586 }
587 EXPORT_SYMBOL(ldlm_lock2handle);
588
589 /**
590  * Obtain a lock reference by handle.
591  *
592  * if \a flags: atomically get the lock and set the flags.
593  *              Return NULL if flag already set
594  */
595 struct ldlm_lock *__ldlm_handle2lock(const struct lustre_handle *handle,
596                                      __u64 flags)
597 {
598         struct ldlm_lock *lock;
599         ENTRY;
600
601         LASSERT(handle);
602
603         if (!lustre_handle_is_used(handle))
604                 RETURN(NULL);
605
606         lock = class_handle2object(handle->cookie, lock_handle_owner);
607         if (lock == NULL)
608                 RETURN(NULL);
609
610         if (lock->l_export != NULL && lock->l_export->exp_failed) {
611                 CDEBUG(D_INFO, "lock export failed: lock %p, exp %p\n",
612                        lock, lock->l_export);
613                 LDLM_LOCK_PUT(lock);
614                 RETURN(NULL);
615         }
616
617         /* It's unlikely but possible that someone marked the lock as
618          * destroyed after we did handle2object on it */
619         if ((flags == 0) && !ldlm_is_destroyed(lock)) {
620                 lu_ref_add_atomic(&lock->l_reference, "handle", lock);
621                 RETURN(lock);
622         }
623
624         lock_res_and_lock(lock);
625
626         LASSERT(lock->l_resource != NULL);
627
628         lu_ref_add_atomic(&lock->l_reference, "handle", lock);
629         if (unlikely(ldlm_is_destroyed(lock))) {
630                 unlock_res_and_lock(lock);
631                 CDEBUG(D_INFO, "lock already destroyed: lock %p\n", lock);
632                 LDLM_LOCK_PUT(lock);
633                 RETURN(NULL);
634         }
635
636         /* If we're setting flags, make sure none of them are already set. */
637         if (flags != 0) {
638                 if ((lock->l_flags & flags) != 0) {
639                         unlock_res_and_lock(lock);
640                         LDLM_LOCK_PUT(lock);
641                         RETURN(NULL);
642                 }
643
644                 lock->l_flags |= flags;
645         }
646
647         unlock_res_and_lock(lock);
648         RETURN(lock);
649 }
650 EXPORT_SYMBOL(__ldlm_handle2lock);
651 /** @} ldlm_handles */
652
653 /**
654  * Fill in "on the wire" representation for given LDLM lock into supplied
655  * lock descriptor \a desc structure.
656  */
657 void ldlm_lock2desc(struct ldlm_lock *lock, struct ldlm_lock_desc *desc)
658 {
659         ldlm_res2desc(lock->l_resource, &desc->l_resource);
660         desc->l_req_mode = lock->l_req_mode;
661         desc->l_granted_mode = lock->l_granted_mode;
662         ldlm_convert_policy_to_wire(lock->l_resource->lr_type,
663                                     &lock->l_policy_data,
664                                     &desc->l_policy_data);
665 }
666
667 /**
668  * Add a lock to list of conflicting locks to send AST to.
669  *
670  * Only add if we have not sent a blocking AST to the lock yet.
671  */
672 static void ldlm_add_bl_work_item(struct ldlm_lock *lock, struct ldlm_lock *new,
673                                   struct list_head *work_list)
674 {
675         if (!ldlm_is_ast_sent(lock)) {
676                 LDLM_DEBUG(lock, "lock incompatible; sending blocking AST.");
677                 ldlm_set_ast_sent(lock);
678                 /* If the enqueuing client said so, tell the AST recipient to
679                  * discard dirty data, rather than writing back. */
680                 if (ldlm_is_ast_discard_data(new))
681                         ldlm_set_discard_data(lock);
682
683                 /* Lock can be converted from a blocking state back to granted
684                  * after lock convert or COS downgrade but still be in an
685                  * older bl_list because it is controlled only by
686                  * ldlm_work_bl_ast_lock(), let it be processed there.
687                  */
688                 if (list_empty(&lock->l_bl_ast)) {
689                         list_add(&lock->l_bl_ast, work_list);
690                         LDLM_LOCK_GET(lock);
691                 }
692                 LASSERT(lock->l_blocking_lock == NULL);
693                 lock->l_blocking_lock = LDLM_LOCK_GET(new);
694         }
695 }
696
697 /**
698  * Add a lock to list of just granted locks to send completion AST to.
699  */
700 static void ldlm_add_cp_work_item(struct ldlm_lock *lock,
701                                   struct list_head *work_list)
702 {
703         if (!ldlm_is_cp_reqd(lock)) {
704                 ldlm_set_cp_reqd(lock);
705                 LDLM_DEBUG(lock, "lock granted; sending completion AST.");
706                 LASSERT(list_empty(&lock->l_cp_ast));
707                 list_add(&lock->l_cp_ast, work_list);
708                 LDLM_LOCK_GET(lock);
709         }
710 }
711
712 /**
713  * Aggregator function to add AST work items into a list. Determines
714  * what sort of an AST work needs to be done and calls the proper
715  * adding function.
716  * Must be called with lr_lock held.
717  */
718 void ldlm_add_ast_work_item(struct ldlm_lock *lock, struct ldlm_lock *new,
719                             struct list_head *work_list)
720 {
721         ENTRY;
722         check_res_locked(lock->l_resource);
723         if (new)
724                 ldlm_add_bl_work_item(lock, new, work_list);
725         else
726                 ldlm_add_cp_work_item(lock, work_list);
727         EXIT;
728 }
729
730 /**
731  * Add specified reader/writer reference to LDLM lock with handle \a lockh.
732  * r/w reference type is determined by \a mode
733  * Calls ldlm_lock_addref_internal.
734  */
735 void ldlm_lock_addref(const struct lustre_handle *lockh, enum ldlm_mode mode)
736 {
737         struct ldlm_lock *lock;
738
739         lock = ldlm_handle2lock(lockh);
740         LASSERTF(lock != NULL, "Non-existing lock: %#llx\n", lockh->cookie);
741         ldlm_lock_addref_internal(lock, mode);
742         LDLM_LOCK_PUT(lock);
743 }
744 EXPORT_SYMBOL(ldlm_lock_addref);
745
746 /**
747  * Helper function.
748  * Add specified reader/writer reference to LDLM lock \a lock.
749  * r/w reference type is determined by \a mode
750  * Removes lock from LRU if it is there.
751  * Assumes the LDLM lock is already locked.
752  */
753 void ldlm_lock_addref_internal_nolock(struct ldlm_lock *lock,
754                                       enum ldlm_mode mode)
755 {
756         ldlm_lock_remove_from_lru(lock);
757         if (mode & (LCK_NL | LCK_CR | LCK_PR)) {
758                 lock->l_readers++;
759                 lu_ref_add_atomic(&lock->l_reference, "reader", lock);
760         }
761         if (mode & (LCK_EX | LCK_CW | LCK_PW | LCK_GROUP | LCK_COS)) {
762                 lock->l_writers++;
763                 lu_ref_add_atomic(&lock->l_reference, "writer", lock);
764         }
765         LDLM_LOCK_GET(lock);
766         lu_ref_add_atomic(&lock->l_reference, "user", lock);
767         LDLM_DEBUG(lock, "ldlm_lock_addref(%s)", ldlm_lockname[mode]);
768 }
769
770 /**
771  * Attempts to add reader/writer reference to a lock with handle \a lockh, and
772  * fails if lock is already LDLM_FL_CBPENDING or destroyed.
773  *
774  * \retval 0 success, lock was addref-ed
775  *
776  * \retval -EAGAIN lock is being canceled.
777  */
778 int ldlm_lock_addref_try(const struct lustre_handle *lockh, enum ldlm_mode mode)
779 {
780         struct ldlm_lock *lock;
781         int               result;
782
783         result = -EAGAIN;
784         lock = ldlm_handle2lock(lockh);
785         if (lock != NULL) {
786                 lock_res_and_lock(lock);
787                 if (lock->l_readers != 0 || lock->l_writers != 0 ||
788                     !ldlm_is_cbpending(lock)) {
789                         ldlm_lock_addref_internal_nolock(lock, mode);
790                         result = 0;
791                 }
792                 unlock_res_and_lock(lock);
793                 LDLM_LOCK_PUT(lock);
794         }
795         return result;
796 }
797 EXPORT_SYMBOL(ldlm_lock_addref_try);
798
799 /**
800  * Add specified reader/writer reference to LDLM lock \a lock.
801  * Locks LDLM lock and calls ldlm_lock_addref_internal_nolock to do the work.
802  * Only called for local locks.
803  */
804 void ldlm_lock_addref_internal(struct ldlm_lock *lock, enum ldlm_mode mode)
805 {
806         lock_res_and_lock(lock);
807         ldlm_lock_addref_internal_nolock(lock, mode);
808         unlock_res_and_lock(lock);
809 }
810
811 /**
812  * Removes reader/writer reference for LDLM lock \a lock.
813  * Assumes LDLM lock is already locked.
814  * only called in ldlm_flock_destroy and for local locks.
815  * Does NOT add lock to LRU if no r/w references left to accomodate flock locks
816  * that cannot be placed in LRU.
817  */
818 void ldlm_lock_decref_internal_nolock(struct ldlm_lock *lock,
819                                       enum ldlm_mode mode)
820 {
821         LDLM_DEBUG(lock, "ldlm_lock_decref(%s)", ldlm_lockname[mode]);
822         if (mode & (LCK_NL | LCK_CR | LCK_PR)) {
823                 LASSERT(lock->l_readers > 0);
824                 lu_ref_del(&lock->l_reference, "reader", lock);
825                 lock->l_readers--;
826         }
827         if (mode & (LCK_EX | LCK_CW | LCK_PW | LCK_GROUP | LCK_COS)) {
828                 LASSERT(lock->l_writers > 0);
829                 lu_ref_del(&lock->l_reference, "writer", lock);
830                 lock->l_writers--;
831         }
832
833         lu_ref_del(&lock->l_reference, "user", lock);
834         LDLM_LOCK_RELEASE(lock);    /* matches the LDLM_LOCK_GET() in addref */
835 }
836
837 /**
838  * Removes reader/writer reference for LDLM lock \a lock.
839  * Locks LDLM lock first.
840  * If the lock is determined to be client lock on a client and r/w refcount
841  * drops to zero and the lock is not blocked, the lock is added to LRU lock
842  * on the namespace.
843  * For blocked LDLM locks if r/w count drops to zero, blocking_ast is called.
844  */
845 void ldlm_lock_decref_internal(struct ldlm_lock *lock, enum ldlm_mode mode)
846 {
847         struct ldlm_namespace *ns;
848
849         ENTRY;
850
851         lock_res_and_lock(lock);
852
853         ns = ldlm_lock_to_ns(lock);
854
855         ldlm_lock_decref_internal_nolock(lock, mode);
856
857         if ((ldlm_is_local(lock) || lock->l_req_mode == LCK_GROUP) &&
858             !lock->l_readers && !lock->l_writers) {
859                 /* If this is a local lock on a server namespace and this was
860                  * the last reference, cancel the lock.
861                  *
862                  * Group locks are special:
863                  * They must not go in LRU, but they are not called back
864                  * like non-group locks, instead they are manually released.
865                  * They have an l_writers reference which they keep until
866                  * they are manually released, so we remove them when they have
867                  * no more reader or writer references. - LU-6368 */
868                 ldlm_set_cbpending(lock);
869         }
870
871         if (!lock->l_readers && !lock->l_writers && ldlm_is_cbpending(lock)) {
872                 unsigned int mask = D_DLMTRACE;
873
874                 /* If we received a blocked AST and this was the last reference,
875                  * run the callback. */
876                 if (ldlm_is_ns_srv(lock) && lock->l_export)
877                         mask |= D_WARNING;
878                 LDLM_DEBUG_LIMIT(mask, lock,
879                                  "final decref done on %sCBPENDING lock",
880                                  mask & D_WARNING ? "non-local " : "");
881
882                 LDLM_LOCK_GET(lock); /* dropped by bl thread */
883                 ldlm_lock_remove_from_lru(lock);
884                 unlock_res_and_lock(lock);
885
886                 if (ldlm_is_fail_loc(lock))
887                         CFS_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
888
889                 if (ldlm_is_atomic_cb(lock) ||
890                     ldlm_bl_to_thread_lock(ns, NULL, lock) != 0)
891                         ldlm_handle_bl_callback(ns, NULL, lock);
892         } else if (ns_is_client(ns) &&
893                    !lock->l_readers && !lock->l_writers &&
894                    !ldlm_is_no_lru(lock) &&
895                    !ldlm_is_bl_ast(lock) &&
896                    !ldlm_is_converting(lock)) {
897
898                 /* If this is a client-side namespace and this was the last
899                  * reference, put it on the LRU.
900                  */
901                 ldlm_lock_add_to_lru(lock);
902                 unlock_res_and_lock(lock);
903                 LDLM_DEBUG(lock, "add lock into lru list");
904
905                 if (ldlm_is_fail_loc(lock))
906                         CFS_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
907
908                 ldlm_pool_recalc(&ns->ns_pool, true);
909         } else {
910                 LDLM_DEBUG(lock, "do not add lock into lru list");
911                 unlock_res_and_lock(lock);
912         }
913
914         EXIT;
915 }
916
917 /**
918  * Decrease reader/writer refcount for LDLM lock with handle \a lockh
919  */
920 void ldlm_lock_decref(const struct lustre_handle *lockh, enum ldlm_mode mode)
921 {
922         struct ldlm_lock *lock = __ldlm_handle2lock(lockh, 0);
923         LASSERTF(lock != NULL, "Non-existing lock: %#llx\n", lockh->cookie);
924         ldlm_lock_decref_internal(lock, mode);
925         LDLM_LOCK_PUT(lock);
926 }
927 EXPORT_SYMBOL(ldlm_lock_decref);
928
929 /**
930  * Decrease reader/writer refcount for LDLM lock with handle
931  * \a lockh and mark it for subsequent cancellation once r/w refcount
932  * drops to zero instead of putting into LRU.
933  *
934  */
935 void ldlm_lock_decref_and_cancel(const struct lustre_handle *lockh,
936                                  enum ldlm_mode mode)
937 {
938         struct ldlm_lock *lock = __ldlm_handle2lock(lockh, 0);
939         ENTRY;
940
941         LASSERT(lock != NULL);
942
943         LDLM_DEBUG(lock, "ldlm_lock_decref(%s)", ldlm_lockname[mode]);
944         lock_res_and_lock(lock);
945         ldlm_set_cbpending(lock);
946         unlock_res_and_lock(lock);
947         ldlm_lock_decref_internal(lock, mode);
948         LDLM_LOCK_PUT(lock);
949 }
950 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
951
952 struct sl_insert_point {
953         struct list_head *res_link;
954         struct list_head *mode_link;
955         struct list_head *policy_link;
956 };
957
958 /**
959  * Finds a position to insert the new lock into granted lock list.
960  *
961  * Used for locks eligible for skiplist optimization.
962  *
963  * Parameters:
964  *      queue [input]:  the granted list where search acts on;
965  *      req [input]:    the lock whose position to be located;
966  *      prev [output]:  positions within 3 lists to insert @req to
967  * Return Value:
968  *      filled @prev
969  * NOTE: called by
970  *  - ldlm_grant_lock_with_skiplist
971  */
972 static void search_granted_lock(struct list_head *queue,
973                                 struct ldlm_lock *req,
974                                 struct sl_insert_point *prev)
975 {
976         struct ldlm_lock *lock, *mode_end, *policy_end;
977
978         ENTRY;
979         list_for_each_entry(lock, queue, l_res_link) {
980                 mode_end = list_entry(lock->l_sl_mode.prev,
981                                       struct ldlm_lock, l_sl_mode);
982
983                 if (lock->l_req_mode != req->l_req_mode) {
984                         /* jump to last lock of mode group */
985                         lock = mode_end;
986                         continue;
987                 }
988
989                 /* suitable mode group is found */
990                 if (lock->l_resource->lr_type == LDLM_PLAIN) {
991                         /* insert point is last lock of the mode group */
992                         prev->res_link = &mode_end->l_res_link;
993                         prev->mode_link = &mode_end->l_sl_mode;
994                         prev->policy_link = &req->l_sl_policy;
995                         EXIT;
996                         return;
997                 } else if (lock->l_resource->lr_type == LDLM_IBITS) {
998                         for (;;) {
999                                 policy_end =
1000                                         list_entry(lock->l_sl_policy.prev,
1001                                                        struct ldlm_lock,
1002                                                        l_sl_policy);
1003
1004                                 if (lock->l_policy_data.l_inodebits.bits ==
1005                                     req->l_policy_data.l_inodebits.bits) {
1006                                         /* insert point is last lock of
1007                                          * the policy group */
1008                                         prev->res_link =
1009                                                 &policy_end->l_res_link;
1010                                         prev->mode_link =
1011                                                 &policy_end->l_sl_mode;
1012                                         prev->policy_link =
1013                                                 &policy_end->l_sl_policy;
1014                                         EXIT;
1015                                         return;
1016                                 }
1017
1018                                 if (policy_end == mode_end)
1019                                         /* done with mode group */
1020                                         break;
1021
1022                                 /* go to next policy group within mode group */
1023                                 lock = list_next_entry(policy_end, l_res_link);
1024                         }  /* loop over policy groups within the mode group */
1025
1026                         /* insert point is last lock of the mode group,
1027                          * new policy group is started */
1028                         prev->res_link = &mode_end->l_res_link;
1029                         prev->mode_link = &mode_end->l_sl_mode;
1030                         prev->policy_link = &req->l_sl_policy;
1031                         EXIT;
1032                         return;
1033                 } else {
1034                         LDLM_ERROR(lock,"is not LDLM_PLAIN or LDLM_IBITS lock");
1035                         LBUG();
1036                 }
1037         }
1038
1039         /* insert point is last lock on the queue,
1040          * new mode group and new policy group are started */
1041         prev->res_link = queue->prev;
1042         prev->mode_link = &req->l_sl_mode;
1043         prev->policy_link = &req->l_sl_policy;
1044         EXIT;
1045 }
1046
1047 /**
1048  * Add a lock into resource granted list after a position described by
1049  * \a prev.
1050  */
1051 static void ldlm_granted_list_add_lock(struct ldlm_lock *lock,
1052                                        struct sl_insert_point *prev)
1053 {
1054         struct ldlm_resource *res = lock->l_resource;
1055         ENTRY;
1056
1057         check_res_locked(res);
1058
1059         ldlm_resource_dump(D_INFO, res);
1060         LDLM_DEBUG(lock, "About to add lock:");
1061
1062         if (ldlm_is_destroyed(lock)) {
1063                 CDEBUG(D_OTHER, "Lock destroyed, not adding to resource\n");
1064                 return;
1065         }
1066
1067         LASSERT(list_empty(&lock->l_res_link));
1068         LASSERT(list_empty(&lock->l_sl_mode));
1069         LASSERT(list_empty(&lock->l_sl_policy));
1070
1071         /*
1072          * lock->link == prev->link means lock is first starting the group.
1073          * Don't re-add to itself to suppress kernel warnings.
1074          */
1075         if (&lock->l_res_link != prev->res_link)
1076                 list_add(&lock->l_res_link, prev->res_link);
1077         if (&lock->l_sl_mode != prev->mode_link)
1078                 list_add(&lock->l_sl_mode, prev->mode_link);
1079         if (&lock->l_sl_policy != prev->policy_link)
1080                 list_add(&lock->l_sl_policy, prev->policy_link);
1081
1082         EXIT;
1083 }
1084
1085 /**
1086  * Add a lock to granted list on a resource maintaining skiplist
1087  * correctness.
1088  */
1089 void ldlm_grant_lock_with_skiplist(struct ldlm_lock *lock)
1090 {
1091         struct sl_insert_point prev;
1092
1093         LASSERT(ldlm_is_granted(lock));
1094
1095         search_granted_lock(&lock->l_resource->lr_granted, lock, &prev);
1096         ldlm_granted_list_add_lock(lock, &prev);
1097 }
1098
1099 /**
1100  * Perform lock granting bookkeeping.
1101  *
1102  * Includes putting the lock into granted list and updating lock mode.
1103  * NOTE: called by
1104  *  - ldlm_lock_enqueue
1105  *  - ldlm_reprocess_queue
1106  *
1107  * must be called with lr_lock held
1108  */
1109 void ldlm_grant_lock(struct ldlm_lock *lock, struct list_head *work_list)
1110 {
1111         struct ldlm_resource *res = lock->l_resource;
1112         ENTRY;
1113
1114         check_res_locked(res);
1115
1116         lock->l_granted_mode = lock->l_req_mode;
1117
1118         if (work_list && lock->l_completion_ast != NULL)
1119                 ldlm_add_ast_work_item(lock, NULL, work_list);
1120
1121         if (res->lr_type == LDLM_PLAIN || res->lr_type == LDLM_IBITS)
1122                 ldlm_grant_lock_with_skiplist(lock);
1123         else if (res->lr_type == LDLM_EXTENT)
1124                 ldlm_extent_add_lock(res, lock);
1125         else if (res->lr_type == LDLM_FLOCK) {
1126                 /* We should not add locks to granted list in the following
1127                  * cases:
1128                  * - this is an UNLOCK but not a real lock;
1129                  * - this is a TEST lock;
1130                  * - this is a F_CANCELLK lock (async flock has req_mode == 0)
1131                  * - this is a deadlock (flock cannot be granted) */
1132                 if (lock->l_req_mode == 0 ||
1133                     lock->l_req_mode == LCK_NL ||
1134                     ldlm_is_test_lock(lock) ||
1135                     ldlm_is_flock_deadlock(lock))
1136                         RETURN_EXIT;
1137                 ldlm_resource_add_lock(res, &res->lr_granted, lock);
1138         } else {
1139                 LBUG();
1140         }
1141
1142         ldlm_pool_add(&ldlm_res_to_ns(res)->ns_pool, lock);
1143         EXIT;
1144 }
1145
1146 /**
1147  * Check if the given @lock meets the criteria for a match.
1148  * A reference on the lock is taken if matched.
1149  *
1150  * @lock        test-against this lock
1151  * @data        parameters
1152  *
1153  * RETURN       returns true if @lock matches @data, false otherwise
1154  */
1155 static bool lock_matches(struct ldlm_lock *lock, struct ldlm_match_data *data)
1156 {
1157         union ldlm_policy_data *lpol = &lock->l_policy_data;
1158         enum ldlm_mode match = LCK_MINMODE;
1159
1160         if (lock == data->lmd_old)
1161                 return true;
1162
1163         /* Check if this lock can be matched.
1164          * Used by LU-2919(exclusive open) for open lease lock */
1165         if (ldlm_is_excl(lock))
1166                 return false;
1167
1168         /* llite sometimes wants to match locks that will be
1169          * canceled when their users drop, but we allow it to match
1170          * if it passes in CBPENDING and the lock still has users.
1171          * this is generally only going to be used by children
1172          * whose parents already hold a lock so forward progress
1173          * can still happen. */
1174         if (ldlm_is_cbpending(lock) &&
1175             !(data->lmd_flags & LDLM_FL_CBPENDING) &&
1176             !(data->lmd_match & LDLM_MATCH_GROUP))
1177                 return false;
1178
1179         if (!(data->lmd_match & (LDLM_MATCH_UNREF | LDLM_MATCH_GROUP)) &&
1180             ldlm_is_cbpending(lock) &&
1181             lock->l_readers == 0 && lock->l_writers == 0)
1182                 return false;
1183
1184         if (!(lock->l_req_mode & *data->lmd_mode))
1185                 return false;
1186
1187         /* When we search for ast_data, we are not doing a traditional match,
1188          * so we don't worry about IBITS or extent matching.
1189          */
1190         if (data->lmd_match & (LDLM_MATCH_AST | LDLM_MATCH_AST_ANY)) {
1191                 if (!lock->l_ast_data)
1192                         return false;
1193
1194                 if (data->lmd_match & LDLM_MATCH_AST_ANY)
1195                         goto matched;
1196         }
1197
1198         match = lock->l_req_mode;
1199
1200         switch (lock->l_resource->lr_type) {
1201         case LDLM_EXTENT:
1202                 if (!(data->lmd_match & LDLM_MATCH_RIGHT) &&
1203                     (lpol->l_extent.start > data->lmd_policy->l_extent.start ||
1204                      lpol->l_extent.end < data->lmd_policy->l_extent.end))
1205                         return false;
1206
1207                 if (unlikely(match == LCK_GROUP) &&
1208                     data->lmd_policy->l_extent.gid != LDLM_GID_ANY &&
1209                     lpol->l_extent.gid != data->lmd_policy->l_extent.gid)
1210                         return false;
1211                 break;
1212         case LDLM_IBITS:
1213                 /* We match if we have existing lock with same or wider set
1214                    of bits. */
1215                 if ((lpol->l_inodebits.bits &
1216                      data->lmd_policy->l_inodebits.bits) !=
1217                     data->lmd_policy->l_inodebits.bits)
1218                         return false;
1219
1220                 if (unlikely(match == LCK_GROUP) &&
1221                     data->lmd_policy->l_inodebits.li_gid != LDLM_GID_ANY &&
1222                     lpol->l_inodebits.li_gid !=
1223                     data->lmd_policy->l_inodebits.li_gid)
1224                         return false;
1225                 break;
1226         default:
1227                 ;
1228         }
1229
1230         /* We match if we have existing lock with same or wider set
1231            of bits. */
1232         if (!(data->lmd_match & LDLM_MATCH_UNREF) && LDLM_HAVE_MASK(lock, GONE))
1233                 return false;
1234
1235         if (!equi(data->lmd_flags & LDLM_FL_LOCAL_ONLY, ldlm_is_local(lock)))
1236                 return false;
1237
1238         /* Filter locks by skipping flags */
1239         if (data->lmd_skip_flags & lock->l_flags)
1240                 return false;
1241
1242 matched:
1243         /**
1244          * In case the lock is a CBPENDING grouplock, just pin it and return,
1245          * we need to wait until it gets to DESTROYED.
1246          */
1247         if ((data->lmd_flags & LDLM_FL_TEST_LOCK) ||
1248             (ldlm_is_cbpending(lock) && (data->lmd_match & LDLM_MATCH_GROUP))) {
1249                 LDLM_LOCK_GET(lock);
1250                 ldlm_lock_touch_in_lru(lock);
1251         } else {
1252                 ldlm_lock_addref_internal_nolock(lock, match);
1253         }
1254
1255         *data->lmd_mode = match;
1256         data->lmd_lock = lock;
1257
1258         return true;
1259 }
1260
1261 static unsigned int itree_overlap_cb(struct interval_node *in, void *args)
1262 {
1263         struct ldlm_interval *node = to_ldlm_interval(in);
1264         struct ldlm_match_data *data = args;
1265         struct ldlm_lock *lock;
1266
1267         list_for_each_entry(lock, &node->li_group, l_sl_policy) {
1268                 if (lock_matches(lock, data))
1269                         return INTERVAL_ITER_STOP;
1270         }
1271         return INTERVAL_ITER_CONT;
1272 }
1273
1274 /**
1275  * Search for a lock with given parameters in interval trees.
1276  *
1277  * \param res      search for a lock in this resource
1278  * \param data     parameters
1279  *
1280  * \retval a referenced lock or NULL.
1281  */
1282 struct ldlm_lock *search_itree(struct ldlm_resource *res,
1283                                struct ldlm_match_data *data)
1284 {
1285         struct interval_node_extent ext = {
1286                 .start     = data->lmd_policy->l_extent.start,
1287                 .end       = data->lmd_policy->l_extent.end
1288         };
1289         int idx;
1290
1291         data->lmd_lock = NULL;
1292
1293         if (data->lmd_match & LDLM_MATCH_RIGHT)
1294                 ext.end = OBD_OBJECT_EOF;
1295
1296         for (idx = 0; idx < LCK_MODE_NUM; idx++) {
1297                 struct ldlm_interval_tree *tree = &res->lr_itree[idx];
1298
1299                 if (tree->lit_root == NULL)
1300                         continue;
1301
1302                 if (!(tree->lit_mode & *data->lmd_mode))
1303                         continue;
1304
1305                 interval_search(tree->lit_root, &ext,
1306                                 itree_overlap_cb, data);
1307                 if (data->lmd_lock)
1308                         return data->lmd_lock;
1309         }
1310
1311         return NULL;
1312 }
1313 EXPORT_SYMBOL(search_itree);
1314
1315
1316 /**
1317  * Search for a lock with given properties in a queue.
1318  *
1319  * \param queue    search for a lock in this queue
1320  * \param data     parameters
1321  *
1322  * \retval a referenced lock or NULL.
1323  */
1324 static struct ldlm_lock *search_queue(struct list_head *queue,
1325                                       struct ldlm_match_data *data)
1326 {
1327         struct ldlm_lock *lock;
1328
1329         data->lmd_lock = NULL;
1330
1331         list_for_each_entry(lock, queue, l_res_link)
1332                 if (lock_matches(lock, data))
1333                         return data->lmd_lock;
1334
1335         return NULL;
1336 }
1337
1338 void ldlm_lock_fail_match_locked(struct ldlm_lock *lock)
1339 {
1340         if ((lock->l_flags & LDLM_FL_FAIL_NOTIFIED) == 0) {
1341                 lock->l_flags |= LDLM_FL_FAIL_NOTIFIED;
1342                 wake_up(&lock->l_waitq);
1343         }
1344 }
1345 EXPORT_SYMBOL(ldlm_lock_fail_match_locked);
1346
1347 void ldlm_lock_fail_match(struct ldlm_lock *lock)
1348 {
1349         lock_res_and_lock(lock);
1350         ldlm_lock_fail_match_locked(lock);
1351         unlock_res_and_lock(lock);
1352 }
1353
1354 /**
1355  * Mark lock as "matchable" by OST.
1356  *
1357  * Used to prevent certain races in LOV/OSC where the lock is granted, but LVB
1358  * is not yet valid.
1359  * Assumes LDLM lock is already locked.
1360  */
1361 void ldlm_lock_allow_match_locked(struct ldlm_lock *lock)
1362 {
1363         ldlm_set_lvb_ready(lock);
1364         wake_up(&lock->l_waitq);
1365 }
1366 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
1367
1368 /**
1369  * Mark lock as "matchable" by OST.
1370  * Locks the lock and then \see ldlm_lock_allow_match_locked
1371  */
1372 void ldlm_lock_allow_match(struct ldlm_lock *lock)
1373 {
1374         lock_res_and_lock(lock);
1375         ldlm_lock_allow_match_locked(lock);
1376         unlock_res_and_lock(lock);
1377 }
1378 EXPORT_SYMBOL(ldlm_lock_allow_match);
1379
1380 /**
1381  * Attempt to find a lock with specified properties.
1382  *
1383  * Typically returns a reference to matched lock unless LDLM_FL_TEST_LOCK is
1384  * set in \a flags
1385  *
1386  * Can be called in two ways:
1387  *
1388  * If 'ns' is NULL, then lockh describes an existing lock that we want to look
1389  * for a duplicate of.
1390  *
1391  * Otherwise, all of the fields must be filled in, to match against.
1392  *
1393  * If 'flags' contains LDLM_FL_LOCAL_ONLY, then only match local locks on the
1394  *     server (ie, connh is NULL)
1395  * If 'flags' contains LDLM_FL_BLOCK_GRANTED, then only locks on the granted
1396  *     list will be considered
1397  * If 'flags' contains LDLM_FL_CBPENDING, then locks that have been marked
1398  *     to be canceled can still be matched as long as they still have reader
1399  *     or writer refernces
1400  * If 'flags' contains LDLM_FL_TEST_LOCK, then don't actually reference a lock,
1401  *     just tell us if we would have matched.
1402  *
1403  * \retval 1 if it finds an already-existing lock that is compatible; in this
1404  * case, lockh is filled in with a addref()ed lock
1405  *
1406  * We also check security context, and if that fails we simply return 0 (to
1407  * keep caller code unchanged), the context failure will be discovered by
1408  * caller sometime later.
1409  */
1410 enum ldlm_mode ldlm_lock_match_with_skip(struct ldlm_namespace *ns,
1411                                          __u64 flags, __u64 skip_flags,
1412                                          const struct ldlm_res_id *res_id,
1413                                          enum ldlm_type type,
1414                                          union ldlm_policy_data *policy,
1415                                          enum ldlm_mode mode,
1416                                          struct lustre_handle *lockh,
1417                                          enum ldlm_match_flags match_flags)
1418 {
1419         struct ldlm_match_data data = {
1420                 .lmd_old = NULL,
1421                 .lmd_lock = NULL,
1422                 .lmd_mode = &mode,
1423                 .lmd_policy = policy,
1424                 .lmd_flags = flags,
1425                 .lmd_skip_flags = skip_flags,
1426                 .lmd_match = match_flags,
1427         };
1428         struct ldlm_resource *res;
1429         struct ldlm_lock *lock;
1430         struct ldlm_lock *group_lock;
1431         int matched;
1432
1433         ENTRY;
1434
1435         if (ns == NULL) {
1436                 data.lmd_old = ldlm_handle2lock(lockh);
1437                 LASSERT(data.lmd_old != NULL);
1438
1439                 ns = ldlm_lock_to_ns(data.lmd_old);
1440                 res_id = &data.lmd_old->l_resource->lr_name;
1441                 type = data.lmd_old->l_resource->lr_type;
1442                 *data.lmd_mode = data.lmd_old->l_req_mode;
1443         }
1444
1445         res = ldlm_resource_get(ns, res_id, type, 0);
1446         if (IS_ERR(res)) {
1447                 LASSERT(data.lmd_old == NULL);
1448                 RETURN(0);
1449         }
1450
1451 repeat:
1452         group_lock = NULL;
1453         LDLM_RESOURCE_ADDREF(res);
1454         lock_res(res);
1455         if (res->lr_type == LDLM_EXTENT)
1456                 lock = search_itree(res, &data);
1457         else
1458                 lock = search_queue(&res->lr_granted, &data);
1459         if (!lock && !(flags & LDLM_FL_BLOCK_GRANTED))
1460                 lock = search_queue(&res->lr_waiting, &data);
1461         matched = lock ? mode : 0;
1462
1463         if (lock && ldlm_is_cbpending(lock) &&
1464             (data.lmd_match & LDLM_MATCH_GROUP))
1465                 group_lock = lock;
1466         unlock_res(res);
1467         LDLM_RESOURCE_DELREF(res);
1468
1469         if (group_lock) {
1470                 l_wait_event_abortable(group_lock->l_waitq,
1471                                        ldlm_is_destroyed(lock));
1472                 LDLM_LOCK_RELEASE(lock);
1473                 goto repeat;
1474         }
1475         ldlm_resource_putref(res);
1476
1477         if (lock) {
1478                 ldlm_lock2handle(lock, lockh);
1479                 if ((flags & LDLM_FL_LVB_READY) &&
1480                     (!ldlm_is_lvb_ready(lock))) {
1481                         __u64 wait_flags = LDLM_FL_LVB_READY |
1482                                 LDLM_FL_DESTROYED | LDLM_FL_FAIL_NOTIFIED;
1483
1484                         if (lock->l_completion_ast) {
1485                                 int err = lock->l_completion_ast(lock,
1486                                                         LDLM_FL_WAIT_NOREPROC,
1487                                                         NULL);
1488                                 if (err)
1489                                         GOTO(out_fail_match, matched = 0);
1490                         }
1491
1492                         wait_event_idle_timeout(
1493                                 lock->l_waitq,
1494                                 lock->l_flags & wait_flags,
1495                                 cfs_time_seconds(obd_timeout));
1496
1497                         if (!ldlm_is_lvb_ready(lock))
1498                                 GOTO(out_fail_match, matched = 0);
1499                 }
1500
1501                 /* check user's security context */
1502                 if (lock->l_conn_export &&
1503                     sptlrpc_import_check_ctx(
1504                                 class_exp2cliimp(lock->l_conn_export)))
1505                         GOTO(out_fail_match, matched = 0);
1506
1507                 LDLM_DEBUG(lock, "matched (%llu %llu)",
1508                            (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1509                            res_id->name[2] : policy->l_extent.start,
1510                            (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1511                            res_id->name[3] : policy->l_extent.end);
1512
1513 out_fail_match:
1514                 if (flags & LDLM_FL_TEST_LOCK)
1515                         LDLM_LOCK_RELEASE(lock);
1516                 else if (!matched)
1517                         ldlm_lock_decref_internal(lock, mode);
1518         }
1519
1520         /* less verbose for test-only */
1521         if (!matched && !(flags & LDLM_FL_TEST_LOCK)) {
1522                 LDLM_DEBUG_NOLOCK("not matched ns %p type %u mode %u res "
1523                                   "%llu/%llu (%llu %llu)", ns,
1524                                   type, mode, res_id->name[0], res_id->name[1],
1525                                   (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1526                                   res_id->name[2] : policy->l_extent.start,
1527                                   (type == LDLM_PLAIN || type == LDLM_IBITS) ?
1528                                   res_id->name[3] : policy->l_extent.end);
1529         }
1530         if (data.lmd_old != NULL)
1531                 LDLM_LOCK_PUT(data.lmd_old);
1532
1533         return matched;
1534 }
1535 EXPORT_SYMBOL(ldlm_lock_match_with_skip);
1536
1537 enum ldlm_mode ldlm_revalidate_lock_handle(const struct lustre_handle *lockh,
1538                                            __u64 *bits)
1539 {
1540         struct ldlm_lock *lock;
1541         enum ldlm_mode mode = 0;
1542         ENTRY;
1543
1544         lock = ldlm_handle2lock(lockh);
1545         if (lock != NULL) {
1546                 lock_res_and_lock(lock);
1547                 if (LDLM_HAVE_MASK(lock, GONE))
1548                         GOTO(out, mode);
1549
1550                 if (ldlm_is_cbpending(lock) &&
1551                     lock->l_readers == 0 && lock->l_writers == 0)
1552                         GOTO(out, mode);
1553
1554                 if (bits)
1555                         *bits = lock->l_policy_data.l_inodebits.bits;
1556                 mode = lock->l_granted_mode;
1557                 ldlm_lock_addref_internal_nolock(lock, mode);
1558         }
1559
1560         EXIT;
1561
1562 out:
1563         if (lock != NULL) {
1564                 unlock_res_and_lock(lock);
1565                 LDLM_LOCK_PUT(lock);
1566         }
1567         return mode;
1568 }
1569 EXPORT_SYMBOL(ldlm_revalidate_lock_handle);
1570
1571 /** The caller must guarantee that the buffer is large enough. */
1572 int ldlm_fill_lvb(struct ldlm_lock *lock, struct req_capsule *pill,
1573                   enum req_location loc, void *data, int size)
1574 {
1575         void *lvb;
1576         ENTRY;
1577
1578         LASSERT(data != NULL);
1579         LASSERT(size >= 0);
1580
1581         switch (lock->l_lvb_type) {
1582         case LVB_T_OST:
1583                 if (size == sizeof(struct ost_lvb)) {
1584                         if (loc == RCL_CLIENT)
1585                                 lvb = req_capsule_client_swab_get(pill,
1586                                                 &RMF_DLM_LVB,
1587                                                 lustre_swab_ost_lvb);
1588                         else
1589                                 lvb = req_capsule_server_swab_get(pill,
1590                                                 &RMF_DLM_LVB,
1591                                                 lustre_swab_ost_lvb);
1592                         if (unlikely(lvb == NULL)) {
1593                                 LDLM_ERROR(lock, "no LVB");
1594                                 RETURN(-EPROTO);
1595                         }
1596
1597                         memcpy(data, lvb, size);
1598                 } else if (size == sizeof(struct ost_lvb_v1)) {
1599                         struct ost_lvb *olvb = data;
1600
1601                         if (loc == RCL_CLIENT)
1602                                 lvb = req_capsule_client_swab_get(pill,
1603                                                 &RMF_DLM_LVB,
1604                                                 lustre_swab_ost_lvb_v1);
1605                         else
1606                                 lvb = req_capsule_server_sized_swab_get(pill,
1607                                                 &RMF_DLM_LVB, size,
1608                                                 lustre_swab_ost_lvb_v1);
1609                         if (unlikely(lvb == NULL)) {
1610                                 LDLM_ERROR(lock, "no LVB");
1611                                 RETURN(-EPROTO);
1612                         }
1613
1614                         memcpy(data, lvb, size);
1615                         olvb->lvb_mtime_ns = 0;
1616                         olvb->lvb_atime_ns = 0;
1617                         olvb->lvb_ctime_ns = 0;
1618                 } else {
1619                         LDLM_ERROR(lock, "Replied unexpected ost LVB size %d",
1620                                    size);
1621                         RETURN(-EINVAL);
1622                 }
1623                 break;
1624         case LVB_T_LQUOTA:
1625                 if (size == sizeof(struct lquota_lvb)) {
1626                         if (loc == RCL_CLIENT)
1627                                 lvb = req_capsule_client_swab_get(pill,
1628                                                 &RMF_DLM_LVB,
1629                                                 lustre_swab_lquota_lvb);
1630                         else
1631                                 lvb = req_capsule_server_swab_get(pill,
1632                                                 &RMF_DLM_LVB,
1633                                                 lustre_swab_lquota_lvb);
1634                         if (unlikely(lvb == NULL)) {
1635                                 LDLM_ERROR(lock, "no LVB");
1636                                 RETURN(-EPROTO);
1637                         }
1638
1639                         memcpy(data, lvb, size);
1640                 } else {
1641                         LDLM_ERROR(lock, "Replied unexpected lquota LVB size %d",
1642                                    size);
1643                         RETURN(-EINVAL);
1644                 }
1645                 break;
1646         case LVB_T_LAYOUT:
1647                 if (size == 0)
1648                         break;
1649
1650                 if (loc == RCL_CLIENT)
1651                         lvb = req_capsule_client_get(pill, &RMF_DLM_LVB);
1652                 else
1653                         lvb = req_capsule_server_get(pill, &RMF_DLM_LVB);
1654                 if (unlikely(lvb == NULL)) {
1655                         LDLM_ERROR(lock, "no LVB");
1656                         RETURN(-EPROTO);
1657                 }
1658
1659                 memcpy(data, lvb, size);
1660                 break;
1661         default:
1662                 LDLM_ERROR(lock, "Unknown LVB type: %d", lock->l_lvb_type);
1663                 libcfs_debug_dumpstack(NULL);
1664                 RETURN(-EINVAL);
1665         }
1666
1667         RETURN(0);
1668 }
1669
1670 /**
1671  * Create and fill in new LDLM lock with specified properties.
1672  * Returns a referenced lock
1673  */
1674 struct ldlm_lock *ldlm_lock_create(struct ldlm_namespace *ns,
1675                                    const struct ldlm_res_id *res_id,
1676                                    enum ldlm_type type,
1677                                    enum ldlm_mode mode,
1678                                    const struct ldlm_callback_suite *cbs,
1679                                    void *data, __u32 lvb_len,
1680                                    enum lvb_type lvb_type)
1681 {
1682         struct ldlm_lock        *lock;
1683         struct ldlm_resource    *res;
1684         int                     rc;
1685         ENTRY;
1686
1687         res = ldlm_resource_get(ns, res_id, type, 1);
1688         if (IS_ERR(res))
1689                 RETURN(ERR_CAST(res));
1690
1691         lock = ldlm_lock_new(res);
1692         if (!lock) {
1693                 ldlm_resource_putref(res);
1694                 RETURN(ERR_PTR(-ENOMEM));
1695         }
1696
1697         lock->l_req_mode = mode;
1698         lock->l_ast_data = data;
1699         lock->l_pid = current->pid;
1700         if (ns_is_server(ns))
1701                 ldlm_set_ns_srv(lock);
1702         if (cbs) {
1703                 lock->l_blocking_ast = cbs->lcs_blocking;
1704                 lock->l_completion_ast = cbs->lcs_completion;
1705                 lock->l_glimpse_ast = cbs->lcs_glimpse;
1706         }
1707
1708         switch (type) {
1709         case LDLM_EXTENT:
1710                 rc = ldlm_extent_alloc_lock(lock);
1711                 break;
1712         case LDLM_IBITS:
1713                 rc = ldlm_inodebits_alloc_lock(lock);
1714                 break;
1715         default:
1716                 rc = 0;
1717         }
1718         if (rc)
1719                 GOTO(out, rc);
1720
1721         if (lvb_len) {
1722                 lock->l_lvb_len = lvb_len;
1723                 OBD_ALLOC_LARGE(lock->l_lvb_data, lvb_len);
1724                 if (lock->l_lvb_data == NULL)
1725                         GOTO(out, rc = -ENOMEM);
1726         }
1727
1728         lock->l_lvb_type = lvb_type;
1729         if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_NEW_LOCK))
1730                 GOTO(out, rc = -ENOENT);
1731
1732         RETURN(lock);
1733
1734 out:
1735         ldlm_lock_destroy(lock);
1736         LDLM_LOCK_RELEASE(lock);
1737         RETURN(ERR_PTR(rc));
1738 }
1739
1740 #ifdef HAVE_SERVER_SUPPORT
1741 static enum ldlm_error ldlm_lock_enqueue_helper(struct ldlm_lock *lock,
1742                                              __u64 *flags)
1743 {
1744         struct ldlm_resource *res = lock->l_resource;
1745         enum ldlm_error rc = ELDLM_OK;
1746         LIST_HEAD(rpc_list);
1747         ldlm_processing_policy policy;
1748
1749         ENTRY;
1750
1751         policy = ldlm_get_processing_policy(res);
1752         policy(lock, flags, LDLM_PROCESS_ENQUEUE, &rc, &rpc_list);
1753         if (rc == ELDLM_OK && lock->l_granted_mode != lock->l_req_mode &&
1754             res->lr_type != LDLM_FLOCK)
1755                 rc = ldlm_handle_conflict_lock(lock, flags, &rpc_list);
1756
1757         if (!list_empty(&rpc_list))
1758                 ldlm_discard_bl_list(&rpc_list);
1759
1760         RETURN(rc);
1761 }
1762 #endif
1763
1764 /**
1765  * Enqueue (request) a lock.
1766  *
1767  * Does not block. As a result of enqueue the lock would be put
1768  * into granted or waiting list.
1769  *
1770  * If namespace has intent policy sent and the lock has LDLM_FL_HAS_INTENT flag
1771  * set, skip all the enqueueing and delegate lock processing to intent policy
1772  * function.
1773  */
1774 enum ldlm_error ldlm_lock_enqueue(const struct lu_env *env,
1775                                   struct ldlm_namespace *ns,
1776                                   struct ldlm_lock **lockp,
1777                                   void *cookie, __u64 *flags)
1778 {
1779         struct ldlm_lock *lock = *lockp;
1780         struct ldlm_resource *res;
1781         int local = ns_is_client(ns);
1782         enum ldlm_error rc = ELDLM_OK;
1783         struct ldlm_interval *node = NULL;
1784 #ifdef HAVE_SERVER_SUPPORT
1785         bool reconstruct = false;
1786 #endif
1787         ENTRY;
1788
1789         /* policies are not executed on the client or during replay */
1790         if ((*flags & (LDLM_FL_HAS_INTENT|LDLM_FL_REPLAY)) == LDLM_FL_HAS_INTENT
1791             && !local && ns->ns_policy) {
1792                 rc = ns->ns_policy(env, ns, lockp, cookie, lock->l_req_mode,
1793                                    *flags, NULL);
1794                 if (rc == ELDLM_LOCK_REPLACED) {
1795                         /* The lock that was returned has already been granted,
1796                          * and placed into lockp.  If it's not the same as the
1797                          * one we passed in, then destroy the old one and our
1798                          * work here is done. */
1799                         if (lock != *lockp) {
1800                                 ldlm_lock_destroy(lock);
1801                                 LDLM_LOCK_RELEASE(lock);
1802                         }
1803                         *flags |= LDLM_FL_LOCK_CHANGED;
1804                         RETURN(0);
1805                 } else if (rc != ELDLM_OK &&
1806                            ldlm_is_granted(lock)) {
1807                         LASSERT(*flags & LDLM_FL_RESENT);
1808                         /* It may happen that ns_policy returns an error in
1809                          * resend case, object may be unlinked or just some
1810                          * error occurs. It is unclear if lock reached the
1811                          * client in the original reply, just leave the lock on
1812                          * server, not returning it again to client. Due to
1813                          * LU-6529, the server will not OOM. */
1814                         RETURN(rc);
1815                 } else if (rc != ELDLM_OK ||
1816                            (rc == ELDLM_OK && (*flags & LDLM_FL_INTENT_ONLY))) {
1817                         ldlm_lock_destroy(lock);
1818                         RETURN(rc);
1819                 }
1820         }
1821
1822         if (*flags & LDLM_FL_RESENT) {
1823                 /* Reconstruct LDLM_FL_SRV_ENQ_MASK @flags for reply.
1824                  * Set LOCK_CHANGED always.
1825                  * Check if the lock is granted for BLOCK_GRANTED.
1826                  * Take NO_TIMEOUT from the lock as it is inherited through
1827                  * LDLM_FL_INHERIT_MASK */
1828                 *flags |= LDLM_FL_LOCK_CHANGED;
1829                 if (!ldlm_is_granted(lock))
1830                         *flags |= LDLM_FL_BLOCK_GRANTED;
1831                 *flags |= lock->l_flags & LDLM_FL_NO_TIMEOUT;
1832                 RETURN(ELDLM_OK);
1833         }
1834
1835 #ifdef HAVE_SERVER_SUPPORT
1836         /* For a replaying lock, it might be already in granted list. So
1837          * unlinking the lock will cause the interval node to be freed, we
1838          * have to allocate the interval node early otherwise we can't regrant
1839          * this lock in the future. - jay
1840          *
1841          * The only time the ldlm_resource changes for the ldlm_lock is when
1842          * ldlm_lock_change_resource() is called and that only happens for
1843          * the Lustre client case.
1844          */
1845         if (!local && (*flags & LDLM_FL_REPLAY) &&
1846             lock->l_resource->lr_type == LDLM_EXTENT)
1847                 OBD_SLAB_ALLOC_PTR_GFP(node, ldlm_interval_slab, GFP_NOFS);
1848
1849         reconstruct = !local && lock->l_resource->lr_type == LDLM_FLOCK &&
1850                       !(*flags & LDLM_FL_TEST_LOCK);
1851         if (reconstruct) {
1852                 rc = req_can_reconstruct(cookie, NULL);
1853                 if (rc != 0) {
1854                         if (rc == 1)
1855                                 rc = 0;
1856                         RETURN(rc);
1857                 }
1858         }
1859
1860         if (!local && lock->l_resource->lr_type == LDLM_FLOCK) {
1861                 struct ldlm_flock_node *fn = &lock->l_resource->lr_flock_node;
1862                 if (lock->l_req_mode == LCK_NL) {
1863                         atomic_inc(&fn->lfn_unlock_pending);
1864                         res = lock_res_and_lock(lock);
1865                         atomic_dec(&fn->lfn_unlock_pending);
1866                 } else {
1867                         res  = lock_res_and_lock(lock);
1868
1869                         while (atomic_read(&fn->lfn_unlock_pending)) {
1870                                 unlock_res_and_lock(lock);
1871                                 cond_resched();
1872                                 lock_res_and_lock(lock);
1873                         }
1874                 }
1875         } else
1876 #endif
1877         {
1878                 res = lock_res_and_lock(lock);
1879         }
1880         if (local && ldlm_is_granted(lock)) {
1881                 /* The server returned a blocked lock, but it was granted
1882                  * before we got a chance to actually enqueue it.  We don't
1883                  * need to do anything else. */
1884                 *flags &= ~LDLM_FL_BLOCKED_MASK;
1885                 GOTO(out, rc = ELDLM_OK);
1886         }
1887
1888         ldlm_resource_unlink_lock(lock);
1889         if (res->lr_type == LDLM_EXTENT && lock->l_tree_node == NULL) {
1890                 if (node == NULL) {
1891                         ldlm_lock_destroy_nolock(lock);
1892                         GOTO(out, rc = -ENOMEM);
1893                 }
1894
1895                 INIT_LIST_HEAD(&node->li_group);
1896                 ldlm_interval_attach(node, lock);
1897                 node = NULL;
1898         }
1899
1900         /* Some flags from the enqueue want to make it into the AST, via the
1901          * lock's l_flags. */
1902         if (*flags & LDLM_FL_AST_DISCARD_DATA)
1903                 ldlm_set_ast_discard_data(lock);
1904         if (*flags & LDLM_FL_TEST_LOCK)
1905                 ldlm_set_test_lock(lock);
1906         if (*flags & LDLM_FL_COS_INCOMPAT)
1907                 ldlm_set_cos_incompat(lock);
1908         if (*flags & LDLM_FL_COS_ENABLED)
1909                 ldlm_set_cos_enabled(lock);
1910
1911         /* This distinction between local lock trees is very important; a client
1912          * namespace only has information about locks taken by that client, and
1913          * thus doesn't have enough information to decide for itself if it can
1914          * be granted (below).  In this case, we do exactly what the server
1915          * tells us to do, as dictated by the 'flags'.
1916          *
1917          * We do exactly the same thing during recovery, when the server is
1918          * more or less trusting the clients not to lie.
1919          *
1920          * FIXME (bug 268): Detect obvious lies by checking compatibility in
1921          * granted queue. */
1922         if (local) {
1923                 if (*flags & (LDLM_FL_BLOCK_WAIT | LDLM_FL_BLOCK_GRANTED))
1924                         ldlm_resource_add_lock(res, &res->lr_waiting, lock);
1925                 else
1926                         ldlm_grant_lock(lock, NULL);
1927                 GOTO(out, rc = ELDLM_OK);
1928 #ifdef HAVE_SERVER_SUPPORT
1929         } else if (*flags & LDLM_FL_REPLAY) {
1930                 if (*flags & LDLM_FL_BLOCK_WAIT) {
1931                         ldlm_resource_add_lock(res, &res->lr_waiting, lock);
1932                         GOTO(out, rc = ELDLM_OK);
1933                 } else if (*flags & LDLM_FL_BLOCK_GRANTED) {
1934                         ldlm_grant_lock(lock, NULL);
1935                         GOTO(out, rc = ELDLM_OK);
1936                 }
1937                 /* If no flags, fall through to normal enqueue path. */
1938         }
1939
1940         rc = ldlm_lock_enqueue_helper(lock, flags);
1941         GOTO(out, rc);
1942 #else
1943         } else {
1944                 CERROR("This is client-side-only module, cannot handle "
1945                        "LDLM_NAMESPACE_SERVER resource type lock.\n");
1946                 LBUG();
1947         }
1948 #endif
1949
1950 out:
1951         unlock_res_and_lock(lock);
1952
1953 #ifdef HAVE_SERVER_SUPPORT
1954         if (reconstruct) {
1955                 struct ptlrpc_request *req = cookie;
1956
1957                 tgt_mk_reply_data(NULL, NULL,
1958                                   &req->rq_export->exp_target_data,
1959                                   req, 0, NULL, false, 0);
1960         }
1961 #endif
1962         if (node)
1963                 OBD_SLAB_FREE(node, ldlm_interval_slab, sizeof(*node));
1964         return rc;
1965 }
1966
1967 #ifdef HAVE_SERVER_SUPPORT
1968 /**
1969  * Iterate through all waiting locks on a given resource queue and attempt to
1970  * grant them.
1971  *
1972  * Must be called with resource lock held.
1973  */
1974 int ldlm_reprocess_queue(struct ldlm_resource *res, struct list_head *queue,
1975                          struct list_head *work_list,
1976                          enum ldlm_process_intention intention, __u64 hint)
1977 {
1978         struct list_head *tmp, *pos;
1979         ldlm_processing_policy policy;
1980         __u64 flags;
1981         int rc = LDLM_ITER_CONTINUE;
1982         enum ldlm_error err;
1983         LIST_HEAD(bl_ast_list);
1984
1985         ENTRY;
1986
1987         check_res_locked(res);
1988
1989         policy = ldlm_get_processing_policy(res);
1990         LASSERT(policy);
1991         LASSERT(intention == LDLM_PROCESS_RESCAN ||
1992                 intention == LDLM_PROCESS_RECOVERY);
1993
1994 restart:
1995         list_for_each_safe(tmp, pos, queue) {
1996                 struct ldlm_lock *pending;
1997                 LIST_HEAD(rpc_list);
1998
1999                 pending = list_entry(tmp, struct ldlm_lock, l_res_link);
2000
2001                 CDEBUG(D_INFO, "Reprocessing lock %p\n", pending);
2002
2003                 flags = 0;
2004                 rc = policy(pending, &flags, intention, &err, &rpc_list);
2005                 if (pending->l_granted_mode == pending->l_req_mode ||
2006                     res->lr_type == LDLM_FLOCK) {
2007                         list_splice(&rpc_list, work_list);
2008                 } else {
2009                         list_splice(&rpc_list, &bl_ast_list);
2010                 }
2011                 /*
2012                  * When this is called from recovery done, we always want
2013                  * to scan the whole list no matter what 'rc' is returned.
2014                  */
2015                 if (rc != LDLM_ITER_CONTINUE &&
2016                     intention == LDLM_PROCESS_RESCAN)
2017                         break;
2018         }
2019
2020         if (!list_empty(&bl_ast_list)) {
2021                 unlock_res(res);
2022
2023                 rc = ldlm_run_ast_work(ldlm_res_to_ns(res), &bl_ast_list,
2024                                        LDLM_WORK_BL_AST);
2025
2026                 lock_res(res);
2027                 if (rc == -ERESTART)
2028                         GOTO(restart, rc);
2029         }
2030
2031         if (!list_empty(&bl_ast_list))
2032                 ldlm_discard_bl_list(&bl_ast_list);
2033
2034         RETURN(intention == LDLM_PROCESS_RESCAN ? rc : LDLM_ITER_CONTINUE);
2035 }
2036
2037 /**
2038  * Conflicting locks are detected for a lock to be enqueued, add the lock
2039  * into waiting list and send blocking ASTs to the conflicting locks.
2040  *
2041  * \param[in] lock              The lock to be enqueued.
2042  * \param[out] flags            Lock flags for the lock to be enqueued.
2043  * \param[in] rpc_list          Conflicting locks list.
2044  *
2045  * \retval -ERESTART:   Some lock was instantly canceled while sending
2046  *                      blocking ASTs, caller needs to re-check conflicting
2047  *                      locks.
2048  * \retval -EAGAIN:     Lock was destroyed, caller should return error.
2049  * \reval 0:            Lock is successfully added in waiting list.
2050  */
2051 int ldlm_handle_conflict_lock(struct ldlm_lock *lock, __u64 *flags,
2052                               struct list_head *rpc_list)
2053 {
2054         struct ldlm_resource *res = lock->l_resource;
2055         int rc;
2056         ENTRY;
2057
2058         check_res_locked(res);
2059
2060         /* If either of the compat_queue()s returned failure, then we
2061          * have ASTs to send and must go onto the waiting list.
2062          *
2063          * bug 2322: we used to unlink and re-add here, which was a
2064          * terrible folly -- if we goto restart, we could get
2065          * re-ordered!  Causes deadlock, because ASTs aren't sent! */
2066         if (list_empty(&lock->l_res_link))
2067                 ldlm_resource_add_lock(res, &res->lr_waiting, lock);
2068         unlock_res(res);
2069
2070         rc = ldlm_run_ast_work(ldlm_res_to_ns(res), rpc_list,
2071                                LDLM_WORK_BL_AST);
2072
2073         if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_OST_FAIL_RACE) &&
2074             !ns_is_client(ldlm_res_to_ns(res)))
2075                 class_fail_export(lock->l_export);
2076
2077         if (rc == -ERESTART)
2078                 ldlm_reprocess_all(res, 0);
2079
2080         lock_res(res);
2081         if (rc == -ERESTART) {
2082                 /* 15715: The lock was granted and destroyed after
2083                  * resource lock was dropped. Interval node was freed
2084                  * in ldlm_lock_destroy. Anyway, this always happens
2085                  * when a client is being evicted. So it would be
2086                  * ok to return an error. -jay */
2087                 if (ldlm_is_destroyed(lock))
2088                         RETURN(-EAGAIN);
2089
2090                 /* lock was granted while resource was unlocked. */
2091                 if (ldlm_is_granted(lock)) {
2092                         /* bug 11300: if the lock has been granted,
2093                          * break earlier because otherwise, we will go
2094                          * to restart and ldlm_resource_unlink will be
2095                          * called and it causes the interval node to be
2096                          * freed. Then we will fail at
2097                          * ldlm_extent_add_lock() */
2098                         *flags &= ~LDLM_FL_BLOCKED_MASK;
2099                 }
2100
2101         }
2102         *flags |= LDLM_FL_BLOCK_GRANTED;
2103
2104         RETURN(0);
2105 }
2106
2107 /**
2108  * Discard all AST work items from list.
2109  *
2110  * If for whatever reason we do not want to send ASTs to conflicting locks
2111  * anymore, disassemble the list with this function.
2112  */
2113 void ldlm_discard_bl_list(struct list_head *bl_list)
2114 {
2115         struct ldlm_lock *lock, *tmp;
2116
2117         ENTRY;
2118
2119         list_for_each_entry_safe(lock, tmp, bl_list, l_bl_ast) {
2120                 LASSERT(!list_empty(&lock->l_bl_ast));
2121                 list_del_init(&lock->l_bl_ast);
2122                 ldlm_clear_ast_sent(lock);
2123                 LASSERT(lock->l_bl_ast_run == 0);
2124                 ldlm_clear_blocking_lock(lock);
2125                 LDLM_LOCK_RELEASE(lock);
2126         }
2127         EXIT;
2128 }
2129
2130 /**
2131  * Process a call to blocking AST callback for a lock in ast_work list
2132  */
2133 static int
2134 ldlm_work_bl_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
2135 {
2136         struct ldlm_cb_set_arg *arg = opaq;
2137         struct ldlm_lock *lock;
2138         struct ldlm_lock_desc d;
2139         struct ldlm_bl_desc bld;
2140         int rc;
2141
2142         ENTRY;
2143
2144         if (list_empty(arg->list))
2145                 RETURN(-ENOENT);
2146
2147         lock = list_first_entry(arg->list, struct ldlm_lock, l_bl_ast);
2148
2149         /* nobody should touch l_bl_ast but some locks in the list may become
2150          * granted after lock convert or COS downgrade, these locks should be
2151          * just skipped here and removed from the list.
2152          */
2153         lock_res_and_lock(lock);
2154         list_del_init(&lock->l_bl_ast);
2155
2156         /* lock is not blocking lock anymore, but was kept in the list because
2157          * it can managed only here.
2158          */
2159         if (!ldlm_is_ast_sent(lock)) {
2160                 unlock_res_and_lock(lock);
2161                 LDLM_LOCK_RELEASE(lock);
2162                 RETURN(0);
2163         }
2164
2165         LASSERT(lock->l_blocking_lock);
2166         ldlm_lock2desc(lock->l_blocking_lock, &d);
2167         /* copy blocking lock ibits in cancel_bits as well,
2168          * new client may use them for lock convert and it is
2169          * important to use new field to convert locks from
2170          * new servers only
2171          */
2172         d.l_policy_data.l_inodebits.cancel_bits =
2173                 lock->l_blocking_lock->l_policy_data.l_inodebits.bits;
2174
2175         /* Blocking lock is being destroyed here but some information about it
2176          * may be needed inside l_blocking_ast() function below,
2177          * e.g. in mdt_blocking_ast(). So save needed data in bl_desc.
2178          */
2179         bld.bl_same_client = lock->l_client_cookie ==
2180                              lock->l_blocking_lock->l_client_cookie;
2181         bld.bl_cos_incompat = ldlm_is_cos_incompat(lock->l_blocking_lock);
2182         arg->bl_desc = &bld;
2183
2184         LASSERT(ldlm_is_ast_sent(lock));
2185         LASSERT(lock->l_bl_ast_run == 0);
2186         lock->l_bl_ast_run++;
2187         ldlm_clear_blocking_lock(lock);
2188         unlock_res_and_lock(lock);
2189
2190         rc = lock->l_blocking_ast(lock, &d, (void *)arg, LDLM_CB_BLOCKING);
2191
2192         LDLM_LOCK_RELEASE(lock);
2193
2194         RETURN(rc);
2195 }
2196
2197 /**
2198  * Process a call to revocation AST callback for a lock in ast_work list
2199  */
2200 static int
2201 ldlm_work_revoke_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
2202 {
2203         struct ldlm_cb_set_arg *arg = opaq;
2204         struct ldlm_lock_desc   desc;
2205         int                     rc;
2206         struct ldlm_lock       *lock;
2207         ENTRY;
2208
2209         if (list_empty(arg->list))
2210                 RETURN(-ENOENT);
2211
2212         lock = list_first_entry(arg->list, struct ldlm_lock, l_rk_ast);
2213         list_del_init(&lock->l_rk_ast);
2214
2215         /* the desc just pretend to exclusive */
2216         ldlm_lock2desc(lock, &desc);
2217         desc.l_req_mode = LCK_EX;
2218         desc.l_granted_mode = 0;
2219
2220         rc = lock->l_blocking_ast(lock, &desc, (void*)arg, LDLM_CB_BLOCKING);
2221         LDLM_LOCK_RELEASE(lock);
2222
2223         RETURN(rc);
2224 }
2225
2226 /**
2227  * Process a call to glimpse AST callback for a lock in ast_work list
2228  */
2229 int ldlm_work_gl_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
2230 {
2231         struct ldlm_cb_set_arg          *arg = opaq;
2232         struct ldlm_glimpse_work        *gl_work;
2233         struct ldlm_lock                *lock;
2234         int                              rc = 0;
2235         ENTRY;
2236
2237         if (list_empty(arg->list))
2238                 RETURN(-ENOENT);
2239
2240         gl_work = list_first_entry(arg->list, struct ldlm_glimpse_work,
2241                                    gl_list);
2242         list_del_init(&gl_work->gl_list);
2243
2244         lock = gl_work->gl_lock;
2245
2246         /* transfer the glimpse descriptor to ldlm_cb_set_arg */
2247         arg->gl_desc = gl_work->gl_desc;
2248         arg->gl_interpret_reply = gl_work->gl_interpret_reply;
2249         arg->gl_interpret_data = gl_work->gl_interpret_data;
2250
2251         /* invoke the actual glimpse callback */
2252         rc = lock->l_glimpse_ast(lock, (void *)arg);
2253         if (rc == 0)
2254                 rc = 1; /* update LVB if this is server lock */
2255         else if (rc == -ELDLM_NO_LOCK_DATA)
2256                 ldlm_lvbo_update(lock->l_resource, lock, NULL, 1);
2257
2258         LDLM_LOCK_RELEASE(lock);
2259         if (gl_work->gl_flags & LDLM_GL_WORK_SLAB_ALLOCATED)
2260                 OBD_SLAB_FREE_PTR(gl_work, ldlm_glimpse_work_kmem);
2261         else
2262                 OBD_FREE_PTR(gl_work);
2263
2264         RETURN(rc);
2265 }
2266 #endif
2267
2268 /**
2269  * Process a call to completion AST callback for a lock in ast_work list
2270  */
2271 static int
2272 ldlm_work_cp_ast_lock(struct ptlrpc_request_set *rqset, void *opaq)
2273 {
2274         struct ldlm_cb_set_arg *arg = opaq;
2275         struct ldlm_lock *lock;
2276         ldlm_completion_callback completion_callback;
2277         int rc = 0;
2278
2279         ENTRY;
2280
2281         if (list_empty(arg->list))
2282                 RETURN(-ENOENT);
2283
2284         lock = list_first_entry(arg->list, struct ldlm_lock, l_cp_ast);
2285
2286         /* It's possible to receive a completion AST before we've set
2287          * the l_completion_ast pointer: either because the AST arrived
2288          * before the reply, or simply because there's a small race
2289          * window between receiving the reply and finishing the local
2290          * enqueue. (bug 842)
2291          *
2292          * This can't happen with the blocking_ast, however, because we
2293          * will never call the local blocking_ast until we drop our
2294          * reader/writer reference, which we won't do until we get the
2295          * reply and finish enqueueing. */
2296
2297         /* nobody should touch l_cp_ast */
2298         lock_res_and_lock(lock);
2299         list_del_init(&lock->l_cp_ast);
2300         LASSERT(ldlm_is_cp_reqd(lock));
2301         /* save l_completion_ast since it can be changed by
2302          * mds_intent_policy(), see bug 14225 */
2303         completion_callback = lock->l_completion_ast;
2304         ldlm_clear_cp_reqd(lock);
2305         unlock_res_and_lock(lock);
2306
2307         if (completion_callback != NULL)
2308                 rc = completion_callback(lock, 0, (void *)arg);
2309         LDLM_LOCK_RELEASE(lock);
2310
2311         RETURN(rc);
2312 }
2313
2314 /**
2315  * Process list of locks in need of ASTs being sent.
2316  *
2317  * Used on server to send multiple ASTs together instead of sending one by
2318  * one.
2319  */
2320 int ldlm_run_ast_work(struct ldlm_namespace *ns, struct list_head *rpc_list,
2321                       ldlm_desc_ast_t ast_type)
2322 {
2323         struct ldlm_cb_set_arg *arg;
2324         set_producer_func work_ast_lock;
2325         int rc;
2326
2327         if (list_empty(rpc_list))
2328                 RETURN(0);
2329
2330         OBD_ALLOC_PTR(arg);
2331         if (arg == NULL)
2332                 RETURN(-ENOMEM);
2333
2334         atomic_set(&arg->restart, 0);
2335         arg->list = rpc_list;
2336
2337         switch (ast_type) {
2338         case LDLM_WORK_CP_AST:
2339                 arg->type = LDLM_CP_CALLBACK;
2340                 work_ast_lock = ldlm_work_cp_ast_lock;
2341                 break;
2342 #ifdef HAVE_SERVER_SUPPORT
2343         case LDLM_WORK_BL_AST:
2344                 arg->type = LDLM_BL_CALLBACK;
2345                 work_ast_lock = ldlm_work_bl_ast_lock;
2346                 break;
2347         case LDLM_WORK_REVOKE_AST:
2348                 arg->type = LDLM_BL_CALLBACK;
2349                 work_ast_lock = ldlm_work_revoke_ast_lock;
2350                 break;
2351         case LDLM_WORK_GL_AST:
2352                 arg->type = LDLM_GL_CALLBACK;
2353                 work_ast_lock = ldlm_work_gl_ast_lock;
2354                 break;
2355 #endif
2356         default:
2357                 LBUG();
2358         }
2359
2360         /* We create a ptlrpc request set with flow control extension.
2361          * This request set will use the work_ast_lock function to produce new
2362          * requests and will send a new request each time one completes in order
2363          * to keep the number of requests in flight to ns_max_parallel_ast */
2364         arg->set = ptlrpc_prep_fcset(ns->ns_max_parallel_ast ? : UINT_MAX,
2365                                      work_ast_lock, arg);
2366         if (arg->set == NULL)
2367                 GOTO(out, rc = -ENOMEM);
2368
2369         ptlrpc_set_wait(NULL, arg->set);
2370         ptlrpc_set_destroy(arg->set);
2371
2372         rc = atomic_read(&arg->restart) ? -ERESTART : 0;
2373         GOTO(out, rc);
2374 out:
2375         OBD_FREE_PTR(arg);
2376         return rc;
2377 }
2378
2379 /**
2380  * Try to grant all waiting locks on a resource.
2381  *
2382  * Calls ldlm_reprocess_queue on waiting queue.
2383  *
2384  * Typically called after some resource locks are cancelled to see
2385  * if anything could be granted as a result of the cancellation.
2386  */
2387 static void __ldlm_reprocess_all(struct ldlm_resource *res,
2388                                  enum ldlm_process_intention intention,
2389                                  __u64 hint)
2390 {
2391         LIST_HEAD(rpc_list);
2392 #ifdef HAVE_SERVER_SUPPORT
2393         ldlm_reprocessing_policy reprocess;
2394         struct obd_device *obd;
2395         int rc;
2396
2397         ENTRY;
2398
2399         /* Local lock trees don't get reprocessed. */
2400         if (ns_is_client(ldlm_res_to_ns(res))) {
2401                 EXIT;
2402                 return;
2403         }
2404
2405         /* Disable reprocess during lock replay stage but allow during
2406          * request replay stage.
2407          */
2408         obd = ldlm_res_to_ns(res)->ns_obd;
2409         if (obd->obd_recovering &&
2410             atomic_read(&obd->obd_req_replay_clients) == 0)
2411                 RETURN_EXIT;
2412 restart:
2413         lock_res(res);
2414         reprocess = ldlm_get_reprocessing_policy(res);
2415         reprocess(res, &res->lr_waiting, &rpc_list, intention, hint);
2416         unlock_res(res);
2417
2418         rc = ldlm_run_ast_work(ldlm_res_to_ns(res), &rpc_list,
2419                                LDLM_WORK_CP_AST);
2420         if (rc == -ERESTART) {
2421                 LASSERT(list_empty(&rpc_list));
2422                 hint = 0;
2423                 goto restart;
2424         }
2425 #else
2426         ENTRY;
2427
2428         if (!ns_is_client(ldlm_res_to_ns(res))) {
2429                 CERROR("This is client-side-only module, cannot handle "
2430                        "LDLM_NAMESPACE_SERVER resource type lock.\n");
2431                 LBUG();
2432         }
2433 #endif
2434         EXIT;
2435 }
2436
2437 void ldlm_reprocess_all(struct ldlm_resource *res, __u64 hint)
2438 {
2439         __ldlm_reprocess_all(res, LDLM_PROCESS_RESCAN, hint);
2440 }
2441 EXPORT_SYMBOL(ldlm_reprocess_all);
2442
2443 static int ldlm_reprocess_res(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2444                               struct hlist_node *hnode, void *arg)
2445 {
2446         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
2447
2448         /* This is only called once after recovery done. LU-8306. */
2449         __ldlm_reprocess_all(res, LDLM_PROCESS_RECOVERY, 0);
2450         return 0;
2451 }
2452
2453 /**
2454  * Iterate through all resources on a namespace attempting to grant waiting
2455  * locks.
2456  */
2457 void ldlm_reprocess_recovery_done(struct ldlm_namespace *ns)
2458 {
2459         ENTRY;
2460
2461         if (ns != NULL) {
2462                 cfs_hash_for_each_nolock(ns->ns_rs_hash,
2463                                          ldlm_reprocess_res, NULL, 0);
2464         }
2465         EXIT;
2466 }
2467
2468 /**
2469  * Helper function to call blocking AST for LDLM lock \a lock in a
2470  * "cancelling" mode.
2471  */
2472 void ldlm_cancel_callback(struct ldlm_lock *lock)
2473 {
2474         check_res_locked(lock->l_resource);
2475         if (!ldlm_is_cancel(lock)) {
2476                 ldlm_set_cancel(lock);
2477                 if (lock->l_blocking_ast) {
2478                         unlock_res_and_lock(lock);
2479                         lock->l_blocking_ast(lock, NULL, lock->l_ast_data,
2480                                              LDLM_CB_CANCELING);
2481                         lock_res_and_lock(lock);
2482                 } else {
2483                         LDLM_DEBUG(lock, "no blocking ast");
2484                 }
2485
2486                 /* only canceller can set bl_done bit */
2487                 ldlm_set_bl_done(lock);
2488                 wake_up(&lock->l_waitq);
2489         } else if (!ldlm_is_bl_done(lock)) {
2490                 /* The lock is guaranteed to have been canceled once
2491                  * returning from this function. */
2492                 unlock_res_and_lock(lock);
2493                 wait_event_idle(lock->l_waitq, is_bl_done(lock));
2494                 lock_res_and_lock(lock);
2495         }
2496 }
2497
2498 /**
2499  * Remove skiplist-enabled LDLM lock \a req from granted list
2500  */
2501 void ldlm_unlink_lock_skiplist(struct ldlm_lock *req)
2502 {
2503         if (req->l_resource->lr_type != LDLM_PLAIN &&
2504             req->l_resource->lr_type != LDLM_IBITS)
2505                 return;
2506
2507         list_del_init(&req->l_sl_policy);
2508         list_del_init(&req->l_sl_mode);
2509 }
2510
2511 /**
2512  * Attempts to cancel LDLM lock \a lock that has no reader/writer references.
2513  */
2514 void ldlm_lock_cancel(struct ldlm_lock *lock)
2515 {
2516         struct ldlm_resource *res;
2517         struct ldlm_namespace *ns;
2518         ENTRY;
2519
2520         lock_res_and_lock(lock);
2521
2522         res = lock->l_resource;
2523         ns  = ldlm_res_to_ns(res);
2524
2525         /* Please do not, no matter how tempting, remove this LBUG without
2526          * talking to me first. -phik */
2527         if (lock->l_readers || lock->l_writers) {
2528                 LDLM_ERROR(lock, "lock still has references");
2529                 unlock_res_and_lock(lock);
2530                 LBUG();
2531         }
2532
2533         if (ldlm_is_waited(lock))
2534                 ldlm_del_waiting_lock(lock);
2535
2536         /* Releases cancel callback. */
2537         ldlm_cancel_callback(lock);
2538
2539         /* Yes, second time, just in case it was added again while we were
2540          * running with no res lock in ldlm_cancel_callback */
2541         if (ldlm_is_waited(lock))
2542                 ldlm_del_waiting_lock(lock);
2543
2544         ldlm_resource_unlink_lock(lock);
2545         ldlm_lock_destroy_nolock(lock);
2546
2547         if (ldlm_is_granted(lock))
2548                 ldlm_pool_del(&ns->ns_pool, lock);
2549
2550         /* Make sure we will not be called again for same lock what is possible
2551          * if not to zero out lock->l_granted_mode */
2552         lock->l_granted_mode = LCK_MINMODE;
2553         unlock_res_and_lock(lock);
2554
2555         EXIT;
2556 }
2557 EXPORT_SYMBOL(ldlm_lock_cancel);
2558
2559 /**
2560  * Set opaque data into the lock that only makes sense to upper layer.
2561  */
2562 int ldlm_lock_set_data(const struct lustre_handle *lockh, void *data)
2563 {
2564         struct ldlm_lock *lock = ldlm_handle2lock(lockh);
2565         int rc = -EINVAL;
2566         ENTRY;
2567
2568         if (lock) {
2569                 if (lock->l_ast_data == NULL)
2570                         lock->l_ast_data = data;
2571                 if (lock->l_ast_data == data)
2572                         rc = 0;
2573                 LDLM_LOCK_PUT(lock);
2574         }
2575         RETURN(rc);
2576 }
2577 EXPORT_SYMBOL(ldlm_lock_set_data);
2578
2579 struct export_cl_data {
2580         const struct lu_env     *ecl_env;
2581         struct obd_export       *ecl_exp;
2582         int                     ecl_loop;
2583 };
2584
2585 static void ldlm_cancel_lock_for_export(struct obd_export *exp,
2586                                         struct ldlm_lock *lock,
2587                                         struct export_cl_data *ecl)
2588 {
2589         struct ldlm_resource *res;
2590
2591         res = ldlm_resource_getref(lock->l_resource);
2592
2593         ldlm_lvbo_update(res, lock, NULL, 1);
2594         ldlm_lock_cancel(lock);
2595         if (!exp->exp_obd->obd_stopping)
2596                 ldlm_reprocess_all(res, lock->l_policy_data.l_inodebits.bits);
2597         ldlm_resource_putref(res);
2598
2599         ecl->ecl_loop++;
2600         if ((ecl->ecl_loop & -ecl->ecl_loop) == ecl->ecl_loop) {
2601                 CDEBUG(D_INFO, "Export %p, %d locks cancelled.\n",
2602                        exp, ecl->ecl_loop);
2603         }
2604 }
2605
2606 /**
2607  * Iterator function for ldlm_export_cancel_locks.
2608  * Cancels passed locks.
2609  */
2610 static int
2611 ldlm_cancel_locks_for_export_cb(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2612                                 struct hlist_node *hnode, void *data)
2613
2614 {
2615         struct export_cl_data   *ecl = (struct export_cl_data *)data;
2616         struct obd_export       *exp  = ecl->ecl_exp;
2617         struct ldlm_lock        *lock = cfs_hash_object(hs, hnode);
2618
2619         LDLM_LOCK_GET(lock);
2620         ldlm_cancel_lock_for_export(exp, lock, ecl);
2621         LDLM_LOCK_RELEASE(lock);
2622
2623         return 0;
2624 }
2625
2626 /**
2627  * Cancel all blocked locks for given export.
2628  *
2629  * Typically called on client disconnection/eviction
2630  */
2631 int ldlm_export_cancel_blocked_locks(struct obd_export *exp)
2632 {
2633         struct lu_env env;
2634         struct export_cl_data   ecl = {
2635                 .ecl_exp        = exp,
2636                 .ecl_loop       = 0,
2637         };
2638         int rc;
2639
2640         rc = lu_env_init(&env, LCT_DT_THREAD);
2641         if (rc)
2642                 RETURN(rc);
2643         ecl.ecl_env = &env;
2644
2645         while (!list_empty(&exp->exp_bl_list)) {
2646                 struct ldlm_lock *lock;
2647
2648                 spin_lock_bh(&exp->exp_bl_list_lock);
2649                 if (!list_empty(&exp->exp_bl_list)) {
2650                         lock = list_first_entry(&exp->exp_bl_list,
2651                                                 struct ldlm_lock, l_exp_list);
2652                         LDLM_LOCK_GET(lock);
2653                         list_del_init(&lock->l_exp_list);
2654                 } else {
2655                         lock = NULL;
2656                 }
2657                 spin_unlock_bh(&exp->exp_bl_list_lock);
2658
2659                 if (lock == NULL)
2660                         break;
2661
2662                 ldlm_cancel_lock_for_export(exp, lock, &ecl);
2663                 LDLM_LOCK_RELEASE(lock);
2664         }
2665
2666         lu_env_fini(&env);
2667
2668         CDEBUG(D_DLMTRACE, "Export %p, canceled %d locks, "
2669                "left on hash table %d.\n", exp, ecl.ecl_loop,
2670                atomic_read(&exp->exp_lock_hash->hs_count));
2671
2672         return ecl.ecl_loop;
2673 }
2674
2675 /**
2676  * Cancel all locks for given export.
2677  *
2678  * Typically called after client disconnection/eviction
2679  */
2680 int ldlm_export_cancel_locks(struct obd_export *exp)
2681 {
2682         struct export_cl_data ecl;
2683         struct lu_env env;
2684         int rc;
2685
2686         rc = lu_env_init(&env, LCT_DT_THREAD);
2687         if (rc)
2688                 RETURN(rc);
2689         ecl.ecl_env = &env;
2690         ecl.ecl_exp = exp;
2691         ecl.ecl_loop = 0;
2692
2693         cfs_hash_for_each_empty(exp->exp_lock_hash,
2694                                 ldlm_cancel_locks_for_export_cb, &ecl);
2695
2696         CDEBUG(D_DLMTRACE, "Export %p, canceled %d locks, "
2697                "left on hash table %d.\n", exp, ecl.ecl_loop,
2698                atomic_read(&exp->exp_lock_hash->hs_count));
2699
2700         if (ecl.ecl_loop > 0 &&
2701             atomic_read(&exp->exp_lock_hash->hs_count) == 0 &&
2702             exp->exp_obd->obd_stopping)
2703                 ldlm_reprocess_recovery_done(exp->exp_obd->obd_namespace);
2704
2705         lu_env_fini(&env);
2706
2707         return ecl.ecl_loop;
2708 }
2709
2710 /**
2711  * Downgrade an PW/EX lock to COS | CR mode.
2712  *
2713  * A lock mode convertion from PW/EX mode to less conflict mode. The
2714  * convertion may fail if lock was canceled before downgrade, but it doesn't
2715  * indicate any problem, because such lock has no reader or writer, and will
2716  * be released soon.
2717  *
2718  * Used by Commit on Sharing (COS) code to force object changes commit in case
2719  * of conflict. Converted lock is considered as new lock and all blocking AST
2720  * things are cleared, so any pending or new blocked lock on that lock will
2721  * cause new call to blocking_ast and force resource object commit.
2722  *
2723  * Also used by layout_change to replace EX lock to CR lock.
2724  *
2725  * \param lock A lock to convert
2726  * \param new_mode new lock mode
2727  */
2728 void ldlm_lock_mode_downgrade(struct ldlm_lock *lock, enum ldlm_mode new_mode)
2729 {
2730 #ifdef HAVE_SERVER_SUPPORT
2731         ENTRY;
2732
2733         LASSERT(new_mode == LCK_COS || new_mode == LCK_CR);
2734
2735         lock_res_and_lock(lock);
2736
2737         if (!(lock->l_granted_mode & (LCK_PW | LCK_EX))) {
2738                 unlock_res_and_lock(lock);
2739
2740                 LASSERT(lock->l_granted_mode == LCK_MINMODE);
2741                 LDLM_DEBUG(lock, "lock was canceled before downgrade");
2742                 RETURN_EXIT;
2743         }
2744
2745         ldlm_resource_unlink_lock(lock);
2746         /*
2747          * Remove the lock from pool as it will be added again in
2748          * ldlm_grant_lock() called below.
2749          */
2750         ldlm_pool_del(&ldlm_lock_to_ns(lock)->ns_pool, lock);
2751
2752         /* Consider downgraded lock as a new lock and clear all states
2753          * related to a previous blocking AST processing.
2754          */
2755         ldlm_clear_blocking_data(lock);
2756
2757         lock->l_req_mode = new_mode;
2758         ldlm_grant_lock(lock, NULL);
2759         unlock_res_and_lock(lock);
2760
2761         ldlm_reprocess_all(lock->l_resource,
2762                            lock->l_policy_data.l_inodebits.bits);
2763
2764         EXIT;
2765 #endif
2766 }
2767 EXPORT_SYMBOL(ldlm_lock_mode_downgrade);
2768
2769 /**
2770  * Print lock with lock handle \a lockh description into debug log.
2771  *
2772  * Used when printing all locks on a resource for debug purposes.
2773  */
2774 void ldlm_lock_dump_handle(int level, const struct lustre_handle *lockh)
2775 {
2776         struct ldlm_lock *lock;
2777
2778         if (!((libcfs_debug | D_ERROR) & level))
2779                 return;
2780
2781         lock = ldlm_handle2lock(lockh);
2782         if (lock == NULL)
2783                 return;
2784
2785         LDLM_DEBUG_LIMIT(level, lock, "###");
2786
2787         LDLM_LOCK_PUT(lock);
2788 }
2789 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2790
2791 /**
2792  * Print lock information with custom message into debug log.
2793  * Helper function.
2794  */
2795 void _ldlm_lock_debug(struct ldlm_lock *lock,
2796                       struct libcfs_debug_msg_data *msgdata,
2797                       const char *fmt, ...)
2798 {
2799         va_list args;
2800         struct obd_export *exp = lock->l_export;
2801         struct ldlm_resource *resource = NULL;
2802         struct va_format vaf;
2803         char *nid = "local";
2804
2805         rcu_read_lock();
2806         resource = rcu_dereference(lock->l_resource);
2807         if (resource && !atomic_inc_not_zero(&resource->lr_refcount))
2808                 resource = NULL;
2809         rcu_read_unlock();
2810
2811         va_start(args, fmt);
2812         vaf.fmt = fmt;
2813         vaf.va = &args;
2814
2815         if (exp && exp->exp_connection) {
2816                 nid = obd_export_nid2str(exp);
2817         } else if (exp && exp->exp_obd != NULL) {
2818                 struct obd_import *imp = exp->exp_obd->u.cli.cl_import;
2819                 nid = obd_import_nid2str(imp);
2820         }
2821
2822         if (resource == NULL) {
2823                 libcfs_debug_msg(msgdata,
2824                                  "%pV 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: %lld lvb_type: %d\n",
2825                                  &vaf,
2826                                  lock,
2827                                  lock->l_handle.h_cookie,
2828                                  refcount_read(&lock->l_handle.h_ref),
2829                                  lock->l_readers, lock->l_writers,
2830                                  ldlm_lockname[lock->l_granted_mode],
2831                                  ldlm_lockname[lock->l_req_mode],
2832                                  lock->l_flags, nid,
2833                                  lock->l_remote_handle.cookie,
2834                                  exp ? refcount_read(&exp->exp_handle.h_ref) : -99,
2835                                  lock->l_pid, lock->l_callback_timestamp,
2836                                  lock->l_lvb_type);
2837                 va_end(args);
2838                 return;
2839         }
2840
2841         switch (resource->lr_type) {
2842         case LDLM_EXTENT:
2843                 libcfs_debug_msg(msgdata,
2844                                  "%pV ns: %s lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: " DLDLMRES " rrc: %d type: %s [%llu->%llu] (req %llu->%llu) gid %llu flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lld lvb_type: %d\n",
2845                                  &vaf,
2846                                  ldlm_lock_to_ns_name(lock), lock,
2847                                  lock->l_handle.h_cookie,
2848                                  refcount_read(&lock->l_handle.h_ref),
2849                                  lock->l_readers, lock->l_writers,
2850                                  ldlm_lockname[lock->l_granted_mode],
2851                                  ldlm_lockname[lock->l_req_mode],
2852                                  PLDLMRES(resource),
2853                                  atomic_read(&resource->lr_refcount),
2854                                  ldlm_typename[resource->lr_type],
2855                                  lock->l_policy_data.l_extent.start,
2856                                  lock->l_policy_data.l_extent.end,
2857                                  lock->l_req_extent.start, lock->l_req_extent.end,
2858                                  lock->l_req_extent.gid,
2859                                  lock->l_flags, nid,
2860                                  lock->l_remote_handle.cookie,
2861                                  exp ? refcount_read(&exp->exp_handle.h_ref) : -99,
2862                                  lock->l_pid, lock->l_callback_timestamp,
2863                                  lock->l_lvb_type);
2864                 break;
2865
2866         case LDLM_FLOCK:
2867                 libcfs_debug_msg(msgdata,
2868                                  "%pV 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: %lld\n",
2869                                  &vaf,
2870                                  ldlm_lock_to_ns_name(lock), lock,
2871                                  lock->l_handle.h_cookie,
2872                                  refcount_read(&lock->l_handle.h_ref),
2873                                  lock->l_readers, lock->l_writers,
2874                                  ldlm_lockname[lock->l_granted_mode],
2875                                  ldlm_lockname[lock->l_req_mode],
2876                                  PLDLMRES(resource),
2877                                  atomic_read(&resource->lr_refcount),
2878                                  ldlm_typename[resource->lr_type],
2879                                  lock->l_policy_data.l_flock.pid,
2880                                  lock->l_policy_data.l_flock.start,
2881                                  lock->l_policy_data.l_flock.end,
2882                                  lock->l_flags, nid,
2883                                  lock->l_remote_handle.cookie,
2884                                  exp ? refcount_read(&exp->exp_handle.h_ref) : -99,
2885                                  lock->l_pid, lock->l_callback_timestamp);
2886                 break;
2887
2888         case LDLM_IBITS:
2889                 libcfs_debug_msg(msgdata,
2890                                  "%pV ns: %s lock: %p/%#llx lrc: %d/%d,%d mode: %s/%s res: " DLDLMRES " bits %#llx/%#llx rrc: %d type: %s gid %llu flags: %#llx nid: %s remote: %#llx expref: %d pid: %u timeout: %lld lvb_type: %d\n",
2891                                  &vaf,
2892                                  ldlm_lock_to_ns_name(lock),
2893                                  lock, lock->l_handle.h_cookie,
2894                                  refcount_read(&lock->l_handle.h_ref),
2895                                  lock->l_readers, lock->l_writers,
2896                                  ldlm_lockname[lock->l_granted_mode],
2897                                  ldlm_lockname[lock->l_req_mode],
2898                                  PLDLMRES(resource),
2899                                  lock->l_policy_data.l_inodebits.bits,
2900                                  lock->l_policy_data.l_inodebits.try_bits,
2901                                  atomic_read(&resource->lr_refcount),
2902                                  ldlm_typename[resource->lr_type],
2903                                  lock->l_policy_data.l_inodebits.li_gid,
2904                                  lock->l_flags, nid,
2905                                  lock->l_remote_handle.cookie,
2906                                  exp ? refcount_read(&exp->exp_handle.h_ref) : -99,
2907                                  lock->l_pid, lock->l_callback_timestamp,
2908                                  lock->l_lvb_type);
2909                 break;
2910
2911         default:
2912                 libcfs_debug_msg(msgdata,
2913                                  "%pV 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: %lld lvb_type: %d\n",
2914                                  &vaf,
2915                                  ldlm_lock_to_ns_name(lock),
2916                                  lock, lock->l_handle.h_cookie,
2917                                  refcount_read(&lock->l_handle.h_ref),
2918                                  lock->l_readers, lock->l_writers,
2919                                  ldlm_lockname[lock->l_granted_mode],
2920                                  ldlm_lockname[lock->l_req_mode],
2921                                  PLDLMRES(resource),
2922                                  atomic_read(&resource->lr_refcount),
2923                                  ldlm_typename[resource->lr_type],
2924                                  lock->l_flags, nid,
2925                                  lock->l_remote_handle.cookie,
2926                                  exp ? refcount_read(&exp->exp_handle.h_ref) : -99,
2927                                  lock->l_pid, lock->l_callback_timestamp,
2928                                  lock->l_lvb_type);
2929                 break;
2930         }
2931         va_end(args);
2932         ldlm_resource_putref(resource);
2933 }
2934 EXPORT_SYMBOL(_ldlm_lock_debug);