OSDN Git Service

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