4 * Runtime locking correctness validator
6 * Started by Ingo Molnar:
8 * Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
9 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
11 * this code maps all the lock dependencies as they occur in a live kernel
12 * and will warn about the following classes of locking bugs:
14 * - lock inversion scenarios
15 * - circular lock dependencies
16 * - hardirq/softirq safe/unsafe locking bugs
18 * Bugs are reported even if the current locking scenario does not cause
19 * any deadlock at this point.
21 * I.e. if anytime in the past two locks were taken in a different order,
22 * even if it happened for another task, even if those were different
23 * locks (but of the same class as this lock), this code will detect it.
25 * Thanks to Arjan van de Ven for coming up with the initial idea of
26 * mapping lock dependencies runtime.
28 #define DISABLE_BRANCH_PROFILING
29 #include <linux/mutex.h>
30 #include <linux/sched.h>
31 #include <linux/sched/clock.h>
32 #include <linux/sched/task.h>
33 #include <linux/sched/mm.h>
34 #include <linux/delay.h>
35 #include <linux/module.h>
36 #include <linux/proc_fs.h>
37 #include <linux/seq_file.h>
38 #include <linux/spinlock.h>
39 #include <linux/kallsyms.h>
40 #include <linux/interrupt.h>
41 #include <linux/stacktrace.h>
42 #include <linux/debug_locks.h>
43 #include <linux/irqflags.h>
44 #include <linux/utsname.h>
45 #include <linux/hash.h>
46 #include <linux/ftrace.h>
47 #include <linux/stringify.h>
48 #include <linux/bitops.h>
49 #include <linux/gfp.h>
50 #include <linux/kmemcheck.h>
51 #include <linux/random.h>
52 #include <linux/jhash.h>
54 #include <asm/sections.h>
56 #include "lockdep_internals.h"
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/lock.h>
61 #ifdef CONFIG_LOCKDEP_CROSSRELEASE
62 #include <linux/slab.h>
65 #ifdef CONFIG_PROVE_LOCKING
66 int prove_locking = 1;
67 module_param(prove_locking, int, 0644);
69 #define prove_locking 0
72 #ifdef CONFIG_LOCK_STAT
74 module_param(lock_stat, int, 0644);
80 * lockdep_lock: protects the lockdep graph, the hashes and the
81 * class/list/hash allocators.
83 * This is one of the rare exceptions where it's justified
84 * to use a raw spinlock - we really dont want the spinlock
85 * code to recurse back into the lockdep code...
87 static arch_spinlock_t lockdep_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
89 static int graph_lock(void)
91 arch_spin_lock(&lockdep_lock);
93 * Make sure that if another CPU detected a bug while
94 * walking the graph we dont change it (while the other
95 * CPU is busy printing out stuff with the graph lock
99 arch_spin_unlock(&lockdep_lock);
102 /* prevent any recursions within lockdep from causing deadlocks */
103 current->lockdep_recursion++;
107 static inline int graph_unlock(void)
109 if (debug_locks && !arch_spin_is_locked(&lockdep_lock)) {
111 * The lockdep graph lock isn't locked while we expect it to
112 * be, we're confused now, bye!
114 return DEBUG_LOCKS_WARN_ON(1);
117 current->lockdep_recursion--;
118 arch_spin_unlock(&lockdep_lock);
123 * Turn lock debugging off and return with 0 if it was off already,
124 * and also release the graph lock:
126 static inline int debug_locks_off_graph_unlock(void)
128 int ret = debug_locks_off();
130 arch_spin_unlock(&lockdep_lock);
135 unsigned long nr_list_entries;
136 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
139 * All data structures here are protected by the global debug_lock.
141 * Mutex key structs only get allocated, once during bootup, and never
142 * get freed - this significantly simplifies the debugging code.
144 unsigned long nr_lock_classes;
145 static struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
147 static inline struct lock_class *hlock_class(struct held_lock *hlock)
149 if (!hlock->class_idx) {
151 * Someone passed in garbage, we give up.
153 DEBUG_LOCKS_WARN_ON(1);
156 return lock_classes + hlock->class_idx - 1;
159 #ifdef CONFIG_LOCK_STAT
160 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
162 static inline u64 lockstat_clock(void)
164 return local_clock();
167 static int lock_point(unsigned long points[], unsigned long ip)
171 for (i = 0; i < LOCKSTAT_POINTS; i++) {
172 if (points[i] == 0) {
183 static void lock_time_inc(struct lock_time *lt, u64 time)
188 if (time < lt->min || !lt->nr)
195 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
200 if (src->max > dst->max)
203 if (src->min < dst->min || !dst->nr)
206 dst->total += src->total;
210 struct lock_class_stats lock_stats(struct lock_class *class)
212 struct lock_class_stats stats;
215 memset(&stats, 0, sizeof(struct lock_class_stats));
216 for_each_possible_cpu(cpu) {
217 struct lock_class_stats *pcs =
218 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
220 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
221 stats.contention_point[i] += pcs->contention_point[i];
223 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
224 stats.contending_point[i] += pcs->contending_point[i];
226 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
227 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
229 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
230 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
232 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
233 stats.bounces[i] += pcs->bounces[i];
239 void clear_lock_stats(struct lock_class *class)
243 for_each_possible_cpu(cpu) {
244 struct lock_class_stats *cpu_stats =
245 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
247 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
249 memset(class->contention_point, 0, sizeof(class->contention_point));
250 memset(class->contending_point, 0, sizeof(class->contending_point));
253 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
255 return &get_cpu_var(cpu_lock_stats)[class - lock_classes];
258 static void put_lock_stats(struct lock_class_stats *stats)
260 put_cpu_var(cpu_lock_stats);
263 static void lock_release_holdtime(struct held_lock *hlock)
265 struct lock_class_stats *stats;
271 holdtime = lockstat_clock() - hlock->holdtime_stamp;
273 stats = get_lock_stats(hlock_class(hlock));
275 lock_time_inc(&stats->read_holdtime, holdtime);
277 lock_time_inc(&stats->write_holdtime, holdtime);
278 put_lock_stats(stats);
281 static inline void lock_release_holdtime(struct held_lock *hlock)
287 * We keep a global list of all lock classes. The list only grows,
288 * never shrinks. The list is only accessed with the lockdep
289 * spinlock lock held.
291 LIST_HEAD(all_lock_classes);
294 * The lockdep classes are in a hash-table as well, for fast lookup:
296 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
297 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
298 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
299 #define classhashentry(key) (classhash_table + __classhashfn((key)))
301 static struct hlist_head classhash_table[CLASSHASH_SIZE];
304 * We put the lock dependency chains into a hash-table as well, to cache
307 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
308 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
309 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
310 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
312 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
315 * The hash key of the lock dependency chains is a hash itself too:
316 * it's a hash of all locks taken up to that lock, including that lock.
317 * It's a 64-bit hash, because it's important for the keys to be
320 static inline u64 iterate_chain_key(u64 key, u32 idx)
322 u32 k0 = key, k1 = key >> 32;
324 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
326 return k0 | (u64)k1 << 32;
329 void lockdep_off(void)
331 current->lockdep_recursion++;
333 EXPORT_SYMBOL(lockdep_off);
335 void lockdep_on(void)
337 current->lockdep_recursion--;
339 EXPORT_SYMBOL(lockdep_on);
342 * Debugging switches:
346 #define VERY_VERBOSE 0
349 # define HARDIRQ_VERBOSE 1
350 # define SOFTIRQ_VERBOSE 1
352 # define HARDIRQ_VERBOSE 0
353 # define SOFTIRQ_VERBOSE 0
356 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
358 * Quick filtering for interesting events:
360 static int class_filter(struct lock_class *class)
364 if (class->name_version == 1 &&
365 !strcmp(class->name, "lockname"))
367 if (class->name_version == 1 &&
368 !strcmp(class->name, "&struct->lockfield"))
371 /* Filter everything else. 1 would be to allow everything else */
376 static int verbose(struct lock_class *class)
379 return class_filter(class);
385 * Stack-trace: tightly packed array of stack backtrace
386 * addresses. Protected by the graph_lock.
388 unsigned long nr_stack_trace_entries;
389 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
391 static void print_lockdep_off(const char *bug_msg)
393 printk(KERN_DEBUG "%s\n", bug_msg);
394 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
395 #ifdef CONFIG_LOCK_STAT
396 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
400 static int save_trace(struct stack_trace *trace)
402 trace->nr_entries = 0;
403 trace->max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
404 trace->entries = stack_trace + nr_stack_trace_entries;
408 save_stack_trace(trace);
411 * Some daft arches put -1 at the end to indicate its a full trace.
413 * <rant> this is buggy anyway, since it takes a whole extra entry so a
414 * complete trace that maxes out the entries provided will be reported
415 * as incomplete, friggin useless </rant>
417 if (trace->nr_entries != 0 &&
418 trace->entries[trace->nr_entries-1] == ULONG_MAX)
421 trace->max_entries = trace->nr_entries;
423 nr_stack_trace_entries += trace->nr_entries;
425 if (nr_stack_trace_entries >= MAX_STACK_TRACE_ENTRIES-1) {
426 if (!debug_locks_off_graph_unlock())
429 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
438 unsigned int nr_hardirq_chains;
439 unsigned int nr_softirq_chains;
440 unsigned int nr_process_chains;
441 unsigned int max_lockdep_depth;
443 #ifdef CONFIG_DEBUG_LOCKDEP
445 * Various lockdep statistics:
447 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
454 #define __USAGE(__STATE) \
455 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
456 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
457 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
458 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
460 static const char *usage_str[] =
462 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
463 #include "lockdep_states.h"
465 [LOCK_USED] = "INITIAL USE",
468 const char * __get_key_name(struct lockdep_subclass_key *key, char *str)
470 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
473 static inline unsigned long lock_flag(enum lock_usage_bit bit)
478 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
482 if (class->usage_mask & lock_flag(bit + 2))
484 if (class->usage_mask & lock_flag(bit)) {
486 if (class->usage_mask & lock_flag(bit + 2))
493 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
497 #define LOCKDEP_STATE(__STATE) \
498 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
499 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
500 #include "lockdep_states.h"
506 static void __print_lock_name(struct lock_class *class)
508 char str[KSYM_NAME_LEN];
513 name = __get_key_name(class->key, str);
514 printk(KERN_CONT "%s", name);
516 printk(KERN_CONT "%s", name);
517 if (class->name_version > 1)
518 printk(KERN_CONT "#%d", class->name_version);
520 printk(KERN_CONT "/%d", class->subclass);
524 static void print_lock_name(struct lock_class *class)
526 char usage[LOCK_USAGE_CHARS];
528 get_usage_chars(class, usage);
530 printk(KERN_CONT " (");
531 __print_lock_name(class);
532 printk(KERN_CONT "){%s}", usage);
535 static void print_lockdep_cache(struct lockdep_map *lock)
538 char str[KSYM_NAME_LEN];
542 name = __get_key_name(lock->key->subkeys, str);
544 printk(KERN_CONT "%s", name);
547 static void print_lock(struct held_lock *hlock)
550 * We can be called locklessly through debug_show_all_locks() so be
551 * extra careful, the hlock might have been released and cleared.
553 unsigned int class_idx = hlock->class_idx;
555 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfields: */
558 if (!class_idx || (class_idx - 1) >= MAX_LOCKDEP_KEYS) {
559 printk(KERN_CONT "<RELEASED>\n");
563 print_lock_name(lock_classes + class_idx - 1);
564 printk(KERN_CONT ", at: [<%p>] %pS\n",
565 (void *)hlock->acquire_ip, (void *)hlock->acquire_ip);
568 static void lockdep_print_held_locks(struct task_struct *curr)
570 int i, depth = curr->lockdep_depth;
573 printk("no locks held by %s/%d.\n", curr->comm, task_pid_nr(curr));
576 printk("%d lock%s held by %s/%d:\n",
577 depth, depth > 1 ? "s" : "", curr->comm, task_pid_nr(curr));
579 for (i = 0; i < depth; i++) {
581 print_lock(curr->held_locks + i);
585 static void print_kernel_ident(void)
587 printk("%s %.*s %s\n", init_utsname()->release,
588 (int)strcspn(init_utsname()->version, " "),
589 init_utsname()->version,
593 static int very_verbose(struct lock_class *class)
596 return class_filter(class);
602 * Is this the address of a static object:
605 static int static_obj(void *obj)
607 unsigned long start = (unsigned long) &_stext,
608 end = (unsigned long) &_end,
609 addr = (unsigned long) obj;
614 if ((addr >= start) && (addr < end))
617 if (arch_is_kernel_data(addr))
621 * in-kernel percpu var?
623 if (is_kernel_percpu_address(addr))
627 * module static or percpu var?
629 return is_module_address(addr) || is_module_percpu_address(addr);
634 * To make lock name printouts unique, we calculate a unique
635 * class->name_version generation counter:
637 static int count_matching_names(struct lock_class *new_class)
639 struct lock_class *class;
642 if (!new_class->name)
645 list_for_each_entry_rcu(class, &all_lock_classes, lock_entry) {
646 if (new_class->key - new_class->subclass == class->key)
647 return class->name_version;
648 if (class->name && !strcmp(class->name, new_class->name))
649 count = max(count, class->name_version);
656 * Register a lock's class in the hash-table, if the class is not present
657 * yet. Otherwise we look it up. We cache the result in the lock object
658 * itself, so actual lookup of the hash should be once per lock object.
660 static inline struct lock_class *
661 look_up_lock_class(struct lockdep_map *lock, unsigned int subclass)
663 struct lockdep_subclass_key *key;
664 struct hlist_head *hash_head;
665 struct lock_class *class;
666 bool is_static = false;
668 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
671 "BUG: looking up invalid subclass: %u\n", subclass);
673 "turning off the locking correctness validator.\n");
679 * Static locks do not have their class-keys yet - for them the key
680 * is the lock object itself. If the lock is in the per cpu area,
681 * the canonical address of the lock (per cpu offset removed) is
684 if (unlikely(!lock->key)) {
685 unsigned long can_addr, addr = (unsigned long)lock;
687 if (__is_kernel_percpu_address(addr, &can_addr))
688 lock->key = (void *)can_addr;
689 else if (__is_module_percpu_address(addr, &can_addr))
690 lock->key = (void *)can_addr;
691 else if (static_obj(lock))
692 lock->key = (void *)lock;
694 return ERR_PTR(-EINVAL);
699 * NOTE: the class-key must be unique. For dynamic locks, a static
700 * lock_class_key variable is passed in through the mutex_init()
701 * (or spin_lock_init()) call - which acts as the key. For static
702 * locks we use the lock object itself as the key.
704 BUILD_BUG_ON(sizeof(struct lock_class_key) >
705 sizeof(struct lockdep_map));
707 key = lock->key->subkeys + subclass;
709 hash_head = classhashentry(key);
712 * We do an RCU walk of the hash, see lockdep_free_key_range().
714 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
717 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
718 if (class->key == key) {
720 * Huh! same key, different name? Did someone trample
721 * on some memory? We're most confused.
723 WARN_ON_ONCE(class->name != lock->name);
728 return is_static || static_obj(lock->key) ? NULL : ERR_PTR(-EINVAL);
731 #ifdef CONFIG_LOCKDEP_CROSSRELEASE
732 static void cross_init(struct lockdep_map *lock, int cross);
733 static int cross_lock(struct lockdep_map *lock);
734 static int lock_acquire_crosslock(struct held_lock *hlock);
735 static int lock_release_crosslock(struct lockdep_map *lock);
737 static inline void cross_init(struct lockdep_map *lock, int cross) {}
738 static inline int cross_lock(struct lockdep_map *lock) { return 0; }
739 static inline int lock_acquire_crosslock(struct held_lock *hlock) { return 2; }
740 static inline int lock_release_crosslock(struct lockdep_map *lock) { return 2; }
744 * Register a lock's class in the hash-table, if the class is not present
745 * yet. Otherwise we look it up. We cache the result in the lock object
746 * itself, so actual lookup of the hash should be once per lock object.
748 static struct lock_class *
749 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
751 struct lockdep_subclass_key *key;
752 struct hlist_head *hash_head;
753 struct lock_class *class;
755 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
757 class = look_up_lock_class(lock, subclass);
758 if (likely(!IS_ERR_OR_NULL(class)))
759 goto out_set_class_cache;
762 * Debug-check: all keys must be persistent!
766 printk("INFO: trying to register non-static key.\n");
767 printk("the code is fine but needs lockdep annotation.\n");
768 printk("turning off the locking correctness validator.\n");
773 key = lock->key->subkeys + subclass;
774 hash_head = classhashentry(key);
780 * We have to do the hash-walk again, to avoid races
783 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
784 if (class->key == key)
789 * Allocate a new key from the static array, and add it to
792 if (nr_lock_classes >= MAX_LOCKDEP_KEYS) {
793 if (!debug_locks_off_graph_unlock()) {
797 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
801 class = lock_classes + nr_lock_classes++;
802 debug_atomic_inc(nr_unused_locks);
804 class->name = lock->name;
805 class->subclass = subclass;
806 INIT_LIST_HEAD(&class->lock_entry);
807 INIT_LIST_HEAD(&class->locks_before);
808 INIT_LIST_HEAD(&class->locks_after);
809 class->name_version = count_matching_names(class);
811 * We use RCU's safe list-add method to make
812 * parallel walking of the hash-list safe:
814 hlist_add_head_rcu(&class->hash_entry, hash_head);
816 * Add it to the global list of classes:
818 list_add_tail_rcu(&class->lock_entry, &all_lock_classes);
820 if (verbose(class)) {
823 printk("\nnew class %p: %s", class->key, class->name);
824 if (class->name_version > 1)
825 printk(KERN_CONT "#%d", class->name_version);
826 printk(KERN_CONT "\n");
837 if (!subclass || force)
838 lock->class_cache[0] = class;
839 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
840 lock->class_cache[subclass] = class;
843 * Hash collision, did we smoke some? We found a class with a matching
844 * hash but the subclass -- which is hashed in -- didn't match.
846 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
852 #ifdef CONFIG_PROVE_LOCKING
854 * Allocate a lockdep entry. (assumes the graph_lock held, returns
855 * with NULL on failure)
857 static struct lock_list *alloc_list_entry(void)
859 if (nr_list_entries >= MAX_LOCKDEP_ENTRIES) {
860 if (!debug_locks_off_graph_unlock())
863 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
867 return list_entries + nr_list_entries++;
871 * Add a new dependency to the head of the list:
873 static int add_lock_to_list(struct lock_class *this, struct list_head *head,
874 unsigned long ip, int distance,
875 struct stack_trace *trace)
877 struct lock_list *entry;
879 * Lock not present yet - get a new dependency struct and
880 * add it to the list:
882 entry = alloc_list_entry();
887 entry->distance = distance;
888 entry->trace = *trace;
890 * Both allocation and removal are done under the graph lock; but
891 * iteration is under RCU-sched; see look_up_lock_class() and
892 * lockdep_free_key_range().
894 list_add_tail_rcu(&entry->entry, head);
900 * For good efficiency of modular, we use power of 2
902 #define MAX_CIRCULAR_QUEUE_SIZE 4096UL
903 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
906 * The circular_queue and helpers is used to implement the
907 * breadth-first search(BFS)algorithem, by which we can build
908 * the shortest path from the next lock to be acquired to the
909 * previous held lock if there is a circular between them.
911 struct circular_queue {
912 unsigned long element[MAX_CIRCULAR_QUEUE_SIZE];
913 unsigned int front, rear;
916 static struct circular_queue lock_cq;
918 unsigned int max_bfs_queue_depth;
920 static unsigned int lockdep_dependency_gen_id;
922 static inline void __cq_init(struct circular_queue *cq)
924 cq->front = cq->rear = 0;
925 lockdep_dependency_gen_id++;
928 static inline int __cq_empty(struct circular_queue *cq)
930 return (cq->front == cq->rear);
933 static inline int __cq_full(struct circular_queue *cq)
935 return ((cq->rear + 1) & CQ_MASK) == cq->front;
938 static inline int __cq_enqueue(struct circular_queue *cq, unsigned long elem)
943 cq->element[cq->rear] = elem;
944 cq->rear = (cq->rear + 1) & CQ_MASK;
948 static inline int __cq_dequeue(struct circular_queue *cq, unsigned long *elem)
953 *elem = cq->element[cq->front];
954 cq->front = (cq->front + 1) & CQ_MASK;
958 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
960 return (cq->rear - cq->front) & CQ_MASK;
963 static inline void mark_lock_accessed(struct lock_list *lock,
964 struct lock_list *parent)
968 nr = lock - list_entries;
969 WARN_ON(nr >= nr_list_entries); /* Out-of-bounds, input fail */
970 lock->parent = parent;
971 lock->class->dep_gen_id = lockdep_dependency_gen_id;
974 static inline unsigned long lock_accessed(struct lock_list *lock)
978 nr = lock - list_entries;
979 WARN_ON(nr >= nr_list_entries); /* Out-of-bounds, input fail */
980 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
983 static inline struct lock_list *get_lock_parent(struct lock_list *child)
985 return child->parent;
988 static inline int get_lock_depth(struct lock_list *child)
991 struct lock_list *parent;
993 while ((parent = get_lock_parent(child))) {
1000 static int __bfs(struct lock_list *source_entry,
1002 int (*match)(struct lock_list *entry, void *data),
1003 struct lock_list **target_entry,
1006 struct lock_list *entry;
1007 struct list_head *head;
1008 struct circular_queue *cq = &lock_cq;
1011 if (match(source_entry, data)) {
1012 *target_entry = source_entry;
1018 head = &source_entry->class->locks_after;
1020 head = &source_entry->class->locks_before;
1022 if (list_empty(head))
1026 __cq_enqueue(cq, (unsigned long)source_entry);
1028 while (!__cq_empty(cq)) {
1029 struct lock_list *lock;
1031 __cq_dequeue(cq, (unsigned long *)&lock);
1039 head = &lock->class->locks_after;
1041 head = &lock->class->locks_before;
1043 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1045 list_for_each_entry_rcu(entry, head, entry) {
1046 if (!lock_accessed(entry)) {
1047 unsigned int cq_depth;
1048 mark_lock_accessed(entry, lock);
1049 if (match(entry, data)) {
1050 *target_entry = entry;
1055 if (__cq_enqueue(cq, (unsigned long)entry)) {
1059 cq_depth = __cq_get_elem_count(cq);
1060 if (max_bfs_queue_depth < cq_depth)
1061 max_bfs_queue_depth = cq_depth;
1069 static inline int __bfs_forwards(struct lock_list *src_entry,
1071 int (*match)(struct lock_list *entry, void *data),
1072 struct lock_list **target_entry)
1074 return __bfs(src_entry, data, match, target_entry, 1);
1078 static inline int __bfs_backwards(struct lock_list *src_entry,
1080 int (*match)(struct lock_list *entry, void *data),
1081 struct lock_list **target_entry)
1083 return __bfs(src_entry, data, match, target_entry, 0);
1088 * Recursive, forwards-direction lock-dependency checking, used for
1089 * both noncyclic checking and for hardirq-unsafe/softirq-unsafe
1094 * Print a dependency chain entry (this is only done when a deadlock
1095 * has been detected):
1098 print_circular_bug_entry(struct lock_list *target, int depth)
1100 if (debug_locks_silent)
1102 printk("\n-> #%u", depth);
1103 print_lock_name(target->class);
1104 printk(KERN_CONT ":\n");
1105 print_stack_trace(&target->trace, 6);
1111 print_circular_lock_scenario(struct held_lock *src,
1112 struct held_lock *tgt,
1113 struct lock_list *prt)
1115 struct lock_class *source = hlock_class(src);
1116 struct lock_class *target = hlock_class(tgt);
1117 struct lock_class *parent = prt->class;
1120 * A direct locking problem where unsafe_class lock is taken
1121 * directly by safe_class lock, then all we need to show
1122 * is the deadlock scenario, as it is obvious that the
1123 * unsafe lock is taken under the safe lock.
1125 * But if there is a chain instead, where the safe lock takes
1126 * an intermediate lock (middle_class) where this lock is
1127 * not the same as the safe lock, then the lock chain is
1128 * used to describe the problem. Otherwise we would need
1129 * to show a different CPU case for each link in the chain
1130 * from the safe_class lock to the unsafe_class lock.
1132 if (parent != source) {
1133 printk("Chain exists of:\n ");
1134 __print_lock_name(source);
1135 printk(KERN_CONT " --> ");
1136 __print_lock_name(parent);
1137 printk(KERN_CONT " --> ");
1138 __print_lock_name(target);
1139 printk(KERN_CONT "\n\n");
1142 if (cross_lock(tgt->instance)) {
1143 printk(" Possible unsafe locking scenario by crosslock:\n\n");
1144 printk(" CPU0 CPU1\n");
1145 printk(" ---- ----\n");
1147 __print_lock_name(parent);
1148 printk(KERN_CONT ");\n");
1150 __print_lock_name(target);
1151 printk(KERN_CONT ");\n");
1153 __print_lock_name(source);
1154 printk(KERN_CONT ");\n");
1156 __print_lock_name(target);
1157 printk(KERN_CONT ");\n");
1158 printk("\n *** DEADLOCK ***\n\n");
1160 printk(" Possible unsafe locking scenario:\n\n");
1161 printk(" CPU0 CPU1\n");
1162 printk(" ---- ----\n");
1164 __print_lock_name(target);
1165 printk(KERN_CONT ");\n");
1167 __print_lock_name(parent);
1168 printk(KERN_CONT ");\n");
1170 __print_lock_name(target);
1171 printk(KERN_CONT ");\n");
1173 __print_lock_name(source);
1174 printk(KERN_CONT ");\n");
1175 printk("\n *** DEADLOCK ***\n\n");
1180 * When a circular dependency is detected, print the
1184 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1185 struct held_lock *check_src,
1186 struct held_lock *check_tgt)
1188 struct task_struct *curr = current;
1190 if (debug_locks_silent)
1194 pr_warn("======================================================\n");
1195 pr_warn("WARNING: possible circular locking dependency detected\n");
1196 print_kernel_ident();
1197 pr_warn("------------------------------------------------------\n");
1198 pr_warn("%s/%d is trying to acquire lock:\n",
1199 curr->comm, task_pid_nr(curr));
1200 print_lock(check_src);
1202 if (cross_lock(check_tgt->instance))
1203 pr_warn("\nbut now in release context of a crosslock acquired at the following:\n");
1205 pr_warn("\nbut task is already holding lock:\n");
1207 print_lock(check_tgt);
1208 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1209 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1211 print_circular_bug_entry(entry, depth);
1216 static inline int class_equal(struct lock_list *entry, void *data)
1218 return entry->class == data;
1221 static noinline int print_circular_bug(struct lock_list *this,
1222 struct lock_list *target,
1223 struct held_lock *check_src,
1224 struct held_lock *check_tgt,
1225 struct stack_trace *trace)
1227 struct task_struct *curr = current;
1228 struct lock_list *parent;
1229 struct lock_list *first_parent;
1232 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1235 if (cross_lock(check_tgt->instance))
1236 this->trace = *trace;
1237 else if (!save_trace(&this->trace))
1240 depth = get_lock_depth(target);
1242 print_circular_bug_header(target, depth, check_src, check_tgt);
1244 parent = get_lock_parent(target);
1245 first_parent = parent;
1248 print_circular_bug_entry(parent, --depth);
1249 parent = get_lock_parent(parent);
1252 printk("\nother info that might help us debug this:\n\n");
1253 print_circular_lock_scenario(check_src, check_tgt,
1256 lockdep_print_held_locks(curr);
1258 printk("\nstack backtrace:\n");
1264 static noinline int print_bfs_bug(int ret)
1266 if (!debug_locks_off_graph_unlock())
1270 * Breadth-first-search failed, graph got corrupted?
1272 WARN(1, "lockdep bfs error:%d\n", ret);
1277 static int noop_count(struct lock_list *entry, void *data)
1279 (*(unsigned long *)data)++;
1283 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
1285 unsigned long count = 0;
1286 struct lock_list *uninitialized_var(target_entry);
1288 __bfs_forwards(this, (void *)&count, noop_count, &target_entry);
1292 unsigned long lockdep_count_forward_deps(struct lock_class *class)
1294 unsigned long ret, flags;
1295 struct lock_list this;
1300 local_irq_save(flags);
1301 arch_spin_lock(&lockdep_lock);
1302 ret = __lockdep_count_forward_deps(&this);
1303 arch_spin_unlock(&lockdep_lock);
1304 local_irq_restore(flags);
1309 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
1311 unsigned long count = 0;
1312 struct lock_list *uninitialized_var(target_entry);
1314 __bfs_backwards(this, (void *)&count, noop_count, &target_entry);
1319 unsigned long lockdep_count_backward_deps(struct lock_class *class)
1321 unsigned long ret, flags;
1322 struct lock_list this;
1327 local_irq_save(flags);
1328 arch_spin_lock(&lockdep_lock);
1329 ret = __lockdep_count_backward_deps(&this);
1330 arch_spin_unlock(&lockdep_lock);
1331 local_irq_restore(flags);
1337 * Prove that the dependency graph starting at <entry> can not
1338 * lead to <target>. Print an error and return 0 if it does.
1341 check_noncircular(struct lock_list *root, struct lock_class *target,
1342 struct lock_list **target_entry)
1346 debug_atomic_inc(nr_cyclic_checks);
1348 result = __bfs_forwards(root, target, class_equal, target_entry);
1354 check_redundant(struct lock_list *root, struct lock_class *target,
1355 struct lock_list **target_entry)
1359 debug_atomic_inc(nr_redundant_checks);
1361 result = __bfs_forwards(root, target, class_equal, target_entry);
1366 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
1368 * Forwards and backwards subgraph searching, for the purposes of
1369 * proving that two subgraphs can be connected by a new dependency
1370 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
1373 static inline int usage_match(struct lock_list *entry, void *bit)
1375 return entry->class->usage_mask & (1 << (enum lock_usage_bit)bit);
1381 * Find a node in the forwards-direction dependency sub-graph starting
1382 * at @root->class that matches @bit.
1384 * Return 0 if such a node exists in the subgraph, and put that node
1385 * into *@target_entry.
1387 * Return 1 otherwise and keep *@target_entry unchanged.
1388 * Return <0 on error.
1391 find_usage_forwards(struct lock_list *root, enum lock_usage_bit bit,
1392 struct lock_list **target_entry)
1396 debug_atomic_inc(nr_find_usage_forwards_checks);
1398 result = __bfs_forwards(root, (void *)bit, usage_match, target_entry);
1404 * Find a node in the backwards-direction dependency sub-graph starting
1405 * at @root->class that matches @bit.
1407 * Return 0 if such a node exists in the subgraph, and put that node
1408 * into *@target_entry.
1410 * Return 1 otherwise and keep *@target_entry unchanged.
1411 * Return <0 on error.
1414 find_usage_backwards(struct lock_list *root, enum lock_usage_bit bit,
1415 struct lock_list **target_entry)
1419 debug_atomic_inc(nr_find_usage_backwards_checks);
1421 result = __bfs_backwards(root, (void *)bit, usage_match, target_entry);
1426 static void print_lock_class_header(struct lock_class *class, int depth)
1430 printk("%*s->", depth, "");
1431 print_lock_name(class);
1432 printk(KERN_CONT " ops: %lu", class->ops);
1433 printk(KERN_CONT " {\n");
1435 for (bit = 0; bit < LOCK_USAGE_STATES; bit++) {
1436 if (class->usage_mask & (1 << bit)) {
1439 len += printk("%*s %s", depth, "", usage_str[bit]);
1440 len += printk(KERN_CONT " at:\n");
1441 print_stack_trace(class->usage_traces + bit, len);
1444 printk("%*s }\n", depth, "");
1446 printk("%*s ... key at: [<%p>] %pS\n",
1447 depth, "", class->key, class->key);
1451 * printk the shortest lock dependencies from @start to @end in reverse order:
1454 print_shortest_lock_dependencies(struct lock_list *leaf,
1455 struct lock_list *root)
1457 struct lock_list *entry = leaf;
1460 /*compute depth from generated tree by BFS*/
1461 depth = get_lock_depth(leaf);
1464 print_lock_class_header(entry->class, depth);
1465 printk("%*s ... acquired at:\n", depth, "");
1466 print_stack_trace(&entry->trace, 2);
1469 if (depth == 0 && (entry != root)) {
1470 printk("lockdep:%s bad path found in chain graph\n", __func__);
1474 entry = get_lock_parent(entry);
1476 } while (entry && (depth >= 0));
1482 print_irq_lock_scenario(struct lock_list *safe_entry,
1483 struct lock_list *unsafe_entry,
1484 struct lock_class *prev_class,
1485 struct lock_class *next_class)
1487 struct lock_class *safe_class = safe_entry->class;
1488 struct lock_class *unsafe_class = unsafe_entry->class;
1489 struct lock_class *middle_class = prev_class;
1491 if (middle_class == safe_class)
1492 middle_class = next_class;
1495 * A direct locking problem where unsafe_class lock is taken
1496 * directly by safe_class lock, then all we need to show
1497 * is the deadlock scenario, as it is obvious that the
1498 * unsafe lock is taken under the safe lock.
1500 * But if there is a chain instead, where the safe lock takes
1501 * an intermediate lock (middle_class) where this lock is
1502 * not the same as the safe lock, then the lock chain is
1503 * used to describe the problem. Otherwise we would need
1504 * to show a different CPU case for each link in the chain
1505 * from the safe_class lock to the unsafe_class lock.
1507 if (middle_class != unsafe_class) {
1508 printk("Chain exists of:\n ");
1509 __print_lock_name(safe_class);
1510 printk(KERN_CONT " --> ");
1511 __print_lock_name(middle_class);
1512 printk(KERN_CONT " --> ");
1513 __print_lock_name(unsafe_class);
1514 printk(KERN_CONT "\n\n");
1517 printk(" Possible interrupt unsafe locking scenario:\n\n");
1518 printk(" CPU0 CPU1\n");
1519 printk(" ---- ----\n");
1521 __print_lock_name(unsafe_class);
1522 printk(KERN_CONT ");\n");
1523 printk(" local_irq_disable();\n");
1525 __print_lock_name(safe_class);
1526 printk(KERN_CONT ");\n");
1528 __print_lock_name(middle_class);
1529 printk(KERN_CONT ");\n");
1530 printk(" <Interrupt>\n");
1532 __print_lock_name(safe_class);
1533 printk(KERN_CONT ");\n");
1534 printk("\n *** DEADLOCK ***\n\n");
1538 print_bad_irq_dependency(struct task_struct *curr,
1539 struct lock_list *prev_root,
1540 struct lock_list *next_root,
1541 struct lock_list *backwards_entry,
1542 struct lock_list *forwards_entry,
1543 struct held_lock *prev,
1544 struct held_lock *next,
1545 enum lock_usage_bit bit1,
1546 enum lock_usage_bit bit2,
1547 const char *irqclass)
1549 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1553 pr_warn("=====================================================\n");
1554 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
1555 irqclass, irqclass);
1556 print_kernel_ident();
1557 pr_warn("-----------------------------------------------------\n");
1558 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
1559 curr->comm, task_pid_nr(curr),
1560 curr->hardirq_context, hardirq_count() >> HARDIRQ_SHIFT,
1561 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
1562 curr->hardirqs_enabled,
1563 curr->softirqs_enabled);
1566 pr_warn("\nand this task is already holding:\n");
1568 pr_warn("which would create a new lock dependency:\n");
1569 print_lock_name(hlock_class(prev));
1571 print_lock_name(hlock_class(next));
1574 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
1576 print_lock_name(backwards_entry->class);
1577 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
1579 print_stack_trace(backwards_entry->class->usage_traces + bit1, 1);
1581 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
1582 print_lock_name(forwards_entry->class);
1583 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
1586 print_stack_trace(forwards_entry->class->usage_traces + bit2, 1);
1588 pr_warn("\nother info that might help us debug this:\n\n");
1589 print_irq_lock_scenario(backwards_entry, forwards_entry,
1590 hlock_class(prev), hlock_class(next));
1592 lockdep_print_held_locks(curr);
1594 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
1595 if (!save_trace(&prev_root->trace))
1597 print_shortest_lock_dependencies(backwards_entry, prev_root);
1599 pr_warn("\nthe dependencies between the lock to be acquired");
1600 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
1601 if (!save_trace(&next_root->trace))
1603 print_shortest_lock_dependencies(forwards_entry, next_root);
1605 pr_warn("\nstack backtrace:\n");
1612 check_usage(struct task_struct *curr, struct held_lock *prev,
1613 struct held_lock *next, enum lock_usage_bit bit_backwards,
1614 enum lock_usage_bit bit_forwards, const char *irqclass)
1617 struct lock_list this, that;
1618 struct lock_list *uninitialized_var(target_entry);
1619 struct lock_list *uninitialized_var(target_entry1);
1623 this.class = hlock_class(prev);
1624 ret = find_usage_backwards(&this, bit_backwards, &target_entry);
1626 return print_bfs_bug(ret);
1631 that.class = hlock_class(next);
1632 ret = find_usage_forwards(&that, bit_forwards, &target_entry1);
1634 return print_bfs_bug(ret);
1638 return print_bad_irq_dependency(curr, &this, &that,
1639 target_entry, target_entry1,
1641 bit_backwards, bit_forwards, irqclass);
1644 static const char *state_names[] = {
1645 #define LOCKDEP_STATE(__STATE) \
1646 __stringify(__STATE),
1647 #include "lockdep_states.h"
1648 #undef LOCKDEP_STATE
1651 static const char *state_rnames[] = {
1652 #define LOCKDEP_STATE(__STATE) \
1653 __stringify(__STATE)"-READ",
1654 #include "lockdep_states.h"
1655 #undef LOCKDEP_STATE
1658 static inline const char *state_name(enum lock_usage_bit bit)
1660 return (bit & 1) ? state_rnames[bit >> 2] : state_names[bit >> 2];
1663 static int exclusive_bit(int new_bit)
1671 * bit 0 - write/read
1672 * bit 1 - used_in/enabled
1676 int state = new_bit & ~3;
1677 int dir = new_bit & 2;
1680 * keep state, bit flip the direction and strip read.
1682 return state | (dir ^ 2);
1685 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
1686 struct held_lock *next, enum lock_usage_bit bit)
1689 * Prove that the new dependency does not connect a hardirq-safe
1690 * lock with a hardirq-unsafe lock - to achieve this we search
1691 * the backwards-subgraph starting at <prev>, and the
1692 * forwards-subgraph starting at <next>:
1694 if (!check_usage(curr, prev, next, bit,
1695 exclusive_bit(bit), state_name(bit)))
1701 * Prove that the new dependency does not connect a hardirq-safe-read
1702 * lock with a hardirq-unsafe lock - to achieve this we search
1703 * the backwards-subgraph starting at <prev>, and the
1704 * forwards-subgraph starting at <next>:
1706 if (!check_usage(curr, prev, next, bit,
1707 exclusive_bit(bit), state_name(bit)))
1714 check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
1715 struct held_lock *next)
1717 #define LOCKDEP_STATE(__STATE) \
1718 if (!check_irq_usage(curr, prev, next, LOCK_USED_IN_##__STATE)) \
1720 #include "lockdep_states.h"
1721 #undef LOCKDEP_STATE
1726 static void inc_chains(void)
1728 if (current->hardirq_context)
1729 nr_hardirq_chains++;
1731 if (current->softirq_context)
1732 nr_softirq_chains++;
1734 nr_process_chains++;
1741 check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
1742 struct held_lock *next)
1747 static inline void inc_chains(void)
1749 nr_process_chains++;
1755 print_deadlock_scenario(struct held_lock *nxt,
1756 struct held_lock *prv)
1758 struct lock_class *next = hlock_class(nxt);
1759 struct lock_class *prev = hlock_class(prv);
1761 printk(" Possible unsafe locking scenario:\n\n");
1765 __print_lock_name(prev);
1766 printk(KERN_CONT ");\n");
1768 __print_lock_name(next);
1769 printk(KERN_CONT ");\n");
1770 printk("\n *** DEADLOCK ***\n\n");
1771 printk(" May be due to missing lock nesting notation\n\n");
1775 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
1776 struct held_lock *next)
1778 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1782 pr_warn("============================================\n");
1783 pr_warn("WARNING: possible recursive locking detected\n");
1784 print_kernel_ident();
1785 pr_warn("--------------------------------------------\n");
1786 pr_warn("%s/%d is trying to acquire lock:\n",
1787 curr->comm, task_pid_nr(curr));
1789 pr_warn("\nbut task is already holding lock:\n");
1792 pr_warn("\nother info that might help us debug this:\n");
1793 print_deadlock_scenario(next, prev);
1794 lockdep_print_held_locks(curr);
1796 pr_warn("\nstack backtrace:\n");
1803 * Check whether we are holding such a class already.
1805 * (Note that this has to be done separately, because the graph cannot
1806 * detect such classes of deadlocks.)
1808 * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
1811 check_deadlock(struct task_struct *curr, struct held_lock *next,
1812 struct lockdep_map *next_instance, int read)
1814 struct held_lock *prev;
1815 struct held_lock *nest = NULL;
1818 for (i = 0; i < curr->lockdep_depth; i++) {
1819 prev = curr->held_locks + i;
1821 if (prev->instance == next->nest_lock)
1824 if (hlock_class(prev) != hlock_class(next))
1828 * Allow read-after-read recursion of the same
1829 * lock class (i.e. read_lock(lock)+read_lock(lock)):
1831 if ((read == 2) && prev->read)
1835 * We're holding the nest_lock, which serializes this lock's
1836 * nesting behaviour.
1841 if (cross_lock(prev->instance))
1844 return print_deadlock_bug(curr, prev, next);
1850 * There was a chain-cache miss, and we are about to add a new dependency
1851 * to a previous lock. We recursively validate the following rules:
1853 * - would the adding of the <prev> -> <next> dependency create a
1854 * circular dependency in the graph? [== circular deadlock]
1856 * - does the new prev->next dependency connect any hardirq-safe lock
1857 * (in the full backwards-subgraph starting at <prev>) with any
1858 * hardirq-unsafe lock (in the full forwards-subgraph starting at
1859 * <next>)? [== illegal lock inversion with hardirq contexts]
1861 * - does the new prev->next dependency connect any softirq-safe lock
1862 * (in the full backwards-subgraph starting at <prev>) with any
1863 * softirq-unsafe lock (in the full forwards-subgraph starting at
1864 * <next>)? [== illegal lock inversion with softirq contexts]
1866 * any of these scenarios could lead to a deadlock.
1868 * Then if all the validations pass, we add the forwards and backwards
1872 check_prev_add(struct task_struct *curr, struct held_lock *prev,
1873 struct held_lock *next, int distance, struct stack_trace *trace,
1874 int (*save)(struct stack_trace *trace))
1876 struct lock_list *uninitialized_var(target_entry);
1877 struct lock_list *entry;
1878 struct lock_list this;
1882 * Prove that the new <prev> -> <next> dependency would not
1883 * create a circular dependency in the graph. (We do this by
1884 * forward-recursing into the graph starting at <next>, and
1885 * checking whether we can reach <prev>.)
1887 * We are using global variables to control the recursion, to
1888 * keep the stackframe size of the recursive functions low:
1890 this.class = hlock_class(next);
1892 ret = check_noncircular(&this, hlock_class(prev), &target_entry);
1893 if (unlikely(!ret)) {
1894 if (!trace->entries) {
1896 * If @save fails here, the printing might trigger
1897 * a WARN but because of the !nr_entries it should
1898 * not do bad things.
1902 return print_circular_bug(&this, target_entry, next, prev, trace);
1904 else if (unlikely(ret < 0))
1905 return print_bfs_bug(ret);
1907 if (!check_prev_add_irq(curr, prev, next))
1911 * For recursive read-locks we do all the dependency checks,
1912 * but we dont store read-triggered dependencies (only
1913 * write-triggered dependencies). This ensures that only the
1914 * write-side dependencies matter, and that if for example a
1915 * write-lock never takes any other locks, then the reads are
1916 * equivalent to a NOP.
1918 if (next->read == 2 || prev->read == 2)
1921 * Is the <prev> -> <next> dependency already present?
1923 * (this may occur even though this is a new chain: consider
1924 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
1925 * chains - the second one will be new, but L1 already has
1926 * L2 added to its dependency list, due to the first chain.)
1928 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
1929 if (entry->class == hlock_class(next)) {
1931 entry->distance = 1;
1937 * Is the <prev> -> <next> link redundant?
1939 this.class = hlock_class(prev);
1941 ret = check_redundant(&this, hlock_class(next), &target_entry);
1943 debug_atomic_inc(nr_redundant);
1947 return print_bfs_bug(ret);
1950 if (!trace->entries && !save(trace))
1954 * Ok, all validations passed, add the new lock
1955 * to the previous lock's dependency list:
1957 ret = add_lock_to_list(hlock_class(next),
1958 &hlock_class(prev)->locks_after,
1959 next->acquire_ip, distance, trace);
1964 ret = add_lock_to_list(hlock_class(prev),
1965 &hlock_class(next)->locks_before,
1966 next->acquire_ip, distance, trace);
1974 * Add the dependency to all directly-previous locks that are 'relevant'.
1975 * The ones that are relevant are (in increasing distance from curr):
1976 * all consecutive trylock entries and the final non-trylock entry - or
1977 * the end of this context's lock-chain - whichever comes first.
1980 check_prevs_add(struct task_struct *curr, struct held_lock *next)
1982 int depth = curr->lockdep_depth;
1983 struct held_lock *hlock;
1984 struct stack_trace trace = {
1994 * Depth must not be zero for a non-head lock:
1999 * At least two relevant locks must exist for this
2002 if (curr->held_locks[depth].irq_context !=
2003 curr->held_locks[depth-1].irq_context)
2007 int distance = curr->lockdep_depth - depth + 1;
2008 hlock = curr->held_locks + depth - 1;
2010 * Only non-crosslock entries get new dependencies added.
2011 * Crosslock entries will be added by commit later:
2013 if (!cross_lock(hlock->instance)) {
2015 * Only non-recursive-read entries get new dependencies
2018 if (hlock->read != 2 && hlock->check) {
2019 int ret = check_prev_add(curr, hlock, next,
2020 distance, &trace, save_trace);
2025 * Stop after the first non-trylock entry,
2026 * as non-trylock entries have added their
2027 * own direct dependencies already, so this
2028 * lock is connected to them indirectly:
2030 if (!hlock->trylock)
2036 * End of lock-stack?
2041 * Stop the search if we cross into another context:
2043 if (curr->held_locks[depth].irq_context !=
2044 curr->held_locks[depth-1].irq_context)
2049 if (!debug_locks_off_graph_unlock())
2053 * Clearly we all shouldn't be here, but since we made it we
2054 * can reliable say we messed up our state. See the above two
2055 * gotos for reasons why we could possibly end up here.
2062 unsigned long nr_lock_chains;
2063 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
2064 int nr_chain_hlocks;
2065 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
2067 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
2069 return lock_classes + chain_hlocks[chain->base + i];
2073 * Returns the index of the first held_lock of the current chain
2075 static inline int get_first_held_lock(struct task_struct *curr,
2076 struct held_lock *hlock)
2079 struct held_lock *hlock_curr;
2081 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
2082 hlock_curr = curr->held_locks + i;
2083 if (hlock_curr->irq_context != hlock->irq_context)
2091 #ifdef CONFIG_DEBUG_LOCKDEP
2093 * Returns the next chain_key iteration
2095 static u64 print_chain_key_iteration(int class_idx, u64 chain_key)
2097 u64 new_chain_key = iterate_chain_key(chain_key, class_idx);
2099 printk(" class_idx:%d -> chain_key:%016Lx",
2101 (unsigned long long)new_chain_key);
2102 return new_chain_key;
2106 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
2108 struct held_lock *hlock;
2110 int depth = curr->lockdep_depth;
2113 printk("depth: %u\n", depth + 1);
2114 for (i = get_first_held_lock(curr, hlock_next); i < depth; i++) {
2115 hlock = curr->held_locks + i;
2116 chain_key = print_chain_key_iteration(hlock->class_idx, chain_key);
2121 print_chain_key_iteration(hlock_next->class_idx, chain_key);
2122 print_lock(hlock_next);
2125 static void print_chain_keys_chain(struct lock_chain *chain)
2131 printk("depth: %u\n", chain->depth);
2132 for (i = 0; i < chain->depth; i++) {
2133 class_id = chain_hlocks[chain->base + i];
2134 chain_key = print_chain_key_iteration(class_id + 1, chain_key);
2136 print_lock_name(lock_classes + class_id);
2141 static void print_collision(struct task_struct *curr,
2142 struct held_lock *hlock_next,
2143 struct lock_chain *chain)
2146 pr_warn("============================\n");
2147 pr_warn("WARNING: chain_key collision\n");
2148 print_kernel_ident();
2149 pr_warn("----------------------------\n");
2150 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
2151 pr_warn("Hash chain already cached but the contents don't match!\n");
2153 pr_warn("Held locks:");
2154 print_chain_keys_held_locks(curr, hlock_next);
2156 pr_warn("Locks in cached chain:");
2157 print_chain_keys_chain(chain);
2159 pr_warn("\nstack backtrace:\n");
2165 * Checks whether the chain and the current held locks are consistent
2166 * in depth and also in content. If they are not it most likely means
2167 * that there was a collision during the calculation of the chain_key.
2168 * Returns: 0 not passed, 1 passed
2170 static int check_no_collision(struct task_struct *curr,
2171 struct held_lock *hlock,
2172 struct lock_chain *chain)
2174 #ifdef CONFIG_DEBUG_LOCKDEP
2177 i = get_first_held_lock(curr, hlock);
2179 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
2180 print_collision(curr, hlock, chain);
2184 for (j = 0; j < chain->depth - 1; j++, i++) {
2185 id = curr->held_locks[i].class_idx - 1;
2187 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
2188 print_collision(curr, hlock, chain);
2197 * This is for building a chain between just two different classes,
2198 * instead of adding a new hlock upon current, which is done by
2199 * add_chain_cache().
2201 * This can be called in any context with two classes, while
2202 * add_chain_cache() must be done within the lock owener's context
2203 * since it uses hlock which might be racy in another context.
2205 static inline int add_chain_cache_classes(unsigned int prev,
2207 unsigned int irq_context,
2210 struct hlist_head *hash_head = chainhashentry(chain_key);
2211 struct lock_chain *chain;
2214 * Allocate a new chain entry from the static array, and add
2219 * We might need to take the graph lock, ensure we've got IRQs
2220 * disabled to make this an IRQ-safe lock.. for recursion reasons
2221 * lockdep won't complain about its own locking errors.
2223 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2226 if (unlikely(nr_lock_chains >= MAX_LOCKDEP_CHAINS)) {
2227 if (!debug_locks_off_graph_unlock())
2230 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
2235 chain = lock_chains + nr_lock_chains++;
2236 chain->chain_key = chain_key;
2237 chain->irq_context = irq_context;
2239 if (likely(nr_chain_hlocks + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS)) {
2240 chain->base = nr_chain_hlocks;
2241 nr_chain_hlocks += chain->depth;
2242 chain_hlocks[chain->base] = prev - 1;
2243 chain_hlocks[chain->base + 1] = next -1;
2245 #ifdef CONFIG_DEBUG_LOCKDEP
2247 * Important for check_no_collision().
2250 if (!debug_locks_off_graph_unlock())
2253 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
2259 hlist_add_head_rcu(&chain->entry, hash_head);
2260 debug_atomic_inc(chain_lookup_misses);
2267 * Adds a dependency chain into chain hashtable. And must be called with
2270 * Return 0 if fail, and graph_lock is released.
2271 * Return 1 if succeed, with graph_lock held.
2273 static inline int add_chain_cache(struct task_struct *curr,
2274 struct held_lock *hlock,
2277 struct lock_class *class = hlock_class(hlock);
2278 struct hlist_head *hash_head = chainhashentry(chain_key);
2279 struct lock_chain *chain;
2283 * Allocate a new chain entry from the static array, and add
2288 * We might need to take the graph lock, ensure we've got IRQs
2289 * disabled to make this an IRQ-safe lock.. for recursion reasons
2290 * lockdep won't complain about its own locking errors.
2292 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2295 if (unlikely(nr_lock_chains >= MAX_LOCKDEP_CHAINS)) {
2296 if (!debug_locks_off_graph_unlock())
2299 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
2303 chain = lock_chains + nr_lock_chains++;
2304 chain->chain_key = chain_key;
2305 chain->irq_context = hlock->irq_context;
2306 i = get_first_held_lock(curr, hlock);
2307 chain->depth = curr->lockdep_depth + 1 - i;
2309 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
2310 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
2311 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
2313 if (likely(nr_chain_hlocks + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS)) {
2314 chain->base = nr_chain_hlocks;
2315 for (j = 0; j < chain->depth - 1; j++, i++) {
2316 int lock_id = curr->held_locks[i].class_idx - 1;
2317 chain_hlocks[chain->base + j] = lock_id;
2319 chain_hlocks[chain->base + j] = class - lock_classes;
2322 if (nr_chain_hlocks < MAX_LOCKDEP_CHAIN_HLOCKS)
2323 nr_chain_hlocks += chain->depth;
2325 #ifdef CONFIG_DEBUG_LOCKDEP
2327 * Important for check_no_collision().
2329 if (unlikely(nr_chain_hlocks > MAX_LOCKDEP_CHAIN_HLOCKS)) {
2330 if (!debug_locks_off_graph_unlock())
2333 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
2339 hlist_add_head_rcu(&chain->entry, hash_head);
2340 debug_atomic_inc(chain_lookup_misses);
2347 * Look up a dependency chain.
2349 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
2351 struct hlist_head *hash_head = chainhashentry(chain_key);
2352 struct lock_chain *chain;
2355 * We can walk it lock-free, because entries only get added
2358 hlist_for_each_entry_rcu(chain, hash_head, entry) {
2359 if (chain->chain_key == chain_key) {
2360 debug_atomic_inc(chain_lookup_hits);
2368 * If the key is not present yet in dependency chain cache then
2369 * add it and return 1 - in this case the new dependency chain is
2370 * validated. If the key is already hashed, return 0.
2371 * (On return with 1 graph_lock is held.)
2373 static inline int lookup_chain_cache_add(struct task_struct *curr,
2374 struct held_lock *hlock,
2377 struct lock_class *class = hlock_class(hlock);
2378 struct lock_chain *chain = lookup_chain_cache(chain_key);
2382 if (!check_no_collision(curr, hlock, chain))
2385 if (very_verbose(class)) {
2386 printk("\nhash chain already cached, key: "
2387 "%016Lx tail class: [%p] %s\n",
2388 (unsigned long long)chain_key,
2389 class->key, class->name);
2395 if (very_verbose(class)) {
2396 printk("\nnew hash chain, key: %016Lx tail class: [%p] %s\n",
2397 (unsigned long long)chain_key, class->key, class->name);
2404 * We have to walk the chain again locked - to avoid duplicates:
2406 chain = lookup_chain_cache(chain_key);
2412 if (!add_chain_cache(curr, hlock, chain_key))
2418 static int validate_chain(struct task_struct *curr, struct lockdep_map *lock,
2419 struct held_lock *hlock, int chain_head, u64 chain_key)
2422 * Trylock needs to maintain the stack of held locks, but it
2423 * does not add new dependencies, because trylock can be done
2426 * We look up the chain_key and do the O(N^2) check and update of
2427 * the dependencies only if this is a new dependency chain.
2428 * (If lookup_chain_cache_add() return with 1 it acquires
2429 * graph_lock for us)
2431 if (!hlock->trylock && hlock->check &&
2432 lookup_chain_cache_add(curr, hlock, chain_key)) {
2434 * Check whether last held lock:
2436 * - is irq-safe, if this lock is irq-unsafe
2437 * - is softirq-safe, if this lock is hardirq-unsafe
2439 * And check whether the new lock's dependency graph
2440 * could lead back to the previous lock.
2442 * any of these scenarios could lead to a deadlock. If
2445 int ret = check_deadlock(curr, hlock, lock, hlock->read);
2450 * Mark recursive read, as we jump over it when
2451 * building dependencies (just like we jump over
2457 * Add dependency only if this lock is not the head
2458 * of the chain, and if it's not a secondary read-lock:
2460 if (!chain_head && ret != 2) {
2461 if (!check_prevs_add(curr, hlock))
2467 /* after lookup_chain_cache_add(): */
2468 if (unlikely(!debug_locks))
2475 static inline int validate_chain(struct task_struct *curr,
2476 struct lockdep_map *lock, struct held_lock *hlock,
2477 int chain_head, u64 chain_key)
2484 * We are building curr_chain_key incrementally, so double-check
2485 * it from scratch, to make sure that it's done correctly:
2487 static void check_chain_key(struct task_struct *curr)
2489 #ifdef CONFIG_DEBUG_LOCKDEP
2490 struct held_lock *hlock, *prev_hlock = NULL;
2494 for (i = 0; i < curr->lockdep_depth; i++) {
2495 hlock = curr->held_locks + i;
2496 if (chain_key != hlock->prev_chain_key) {
2499 * We got mighty confused, our chain keys don't match
2500 * with what we expect, someone trample on our task state?
2502 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
2503 curr->lockdep_depth, i,
2504 (unsigned long long)chain_key,
2505 (unsigned long long)hlock->prev_chain_key);
2509 * Whoops ran out of static storage again?
2511 if (DEBUG_LOCKS_WARN_ON(hlock->class_idx > MAX_LOCKDEP_KEYS))
2514 if (prev_hlock && (prev_hlock->irq_context !=
2515 hlock->irq_context))
2517 chain_key = iterate_chain_key(chain_key, hlock->class_idx);
2520 if (chain_key != curr->curr_chain_key) {
2523 * More smoking hash instead of calculating it, damn see these
2524 * numbers float.. I bet that a pink elephant stepped on my memory.
2526 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
2527 curr->lockdep_depth, i,
2528 (unsigned long long)chain_key,
2529 (unsigned long long)curr->curr_chain_key);
2535 print_usage_bug_scenario(struct held_lock *lock)
2537 struct lock_class *class = hlock_class(lock);
2539 printk(" Possible unsafe locking scenario:\n\n");
2543 __print_lock_name(class);
2544 printk(KERN_CONT ");\n");
2545 printk(" <Interrupt>\n");
2547 __print_lock_name(class);
2548 printk(KERN_CONT ");\n");
2549 printk("\n *** DEADLOCK ***\n\n");
2553 print_usage_bug(struct task_struct *curr, struct held_lock *this,
2554 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
2556 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2560 pr_warn("================================\n");
2561 pr_warn("WARNING: inconsistent lock state\n");
2562 print_kernel_ident();
2563 pr_warn("--------------------------------\n");
2565 pr_warn("inconsistent {%s} -> {%s} usage.\n",
2566 usage_str[prev_bit], usage_str[new_bit]);
2568 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
2569 curr->comm, task_pid_nr(curr),
2570 trace_hardirq_context(curr), hardirq_count() >> HARDIRQ_SHIFT,
2571 trace_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
2572 trace_hardirqs_enabled(curr),
2573 trace_softirqs_enabled(curr));
2576 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
2577 print_stack_trace(hlock_class(this)->usage_traces + prev_bit, 1);
2579 print_irqtrace_events(curr);
2580 pr_warn("\nother info that might help us debug this:\n");
2581 print_usage_bug_scenario(this);
2583 lockdep_print_held_locks(curr);
2585 pr_warn("\nstack backtrace:\n");
2592 * Print out an error if an invalid bit is set:
2595 valid_state(struct task_struct *curr, struct held_lock *this,
2596 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
2598 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit)))
2599 return print_usage_bug(curr, this, bad_bit, new_bit);
2603 static int mark_lock(struct task_struct *curr, struct held_lock *this,
2604 enum lock_usage_bit new_bit);
2606 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
2609 * print irq inversion bug:
2612 print_irq_inversion_bug(struct task_struct *curr,
2613 struct lock_list *root, struct lock_list *other,
2614 struct held_lock *this, int forwards,
2615 const char *irqclass)
2617 struct lock_list *entry = other;
2618 struct lock_list *middle = NULL;
2621 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2625 pr_warn("========================================================\n");
2626 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
2627 print_kernel_ident();
2628 pr_warn("--------------------------------------------------------\n");
2629 pr_warn("%s/%d just changed the state of lock:\n",
2630 curr->comm, task_pid_nr(curr));
2633 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
2635 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
2636 print_lock_name(other->class);
2637 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
2639 pr_warn("\nother info that might help us debug this:\n");
2641 /* Find a middle lock (if one exists) */
2642 depth = get_lock_depth(other);
2644 if (depth == 0 && (entry != root)) {
2645 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
2649 entry = get_lock_parent(entry);
2651 } while (entry && entry != root && (depth >= 0));
2653 print_irq_lock_scenario(root, other,
2654 middle ? middle->class : root->class, other->class);
2656 print_irq_lock_scenario(other, root,
2657 middle ? middle->class : other->class, root->class);
2659 lockdep_print_held_locks(curr);
2661 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
2662 if (!save_trace(&root->trace))
2664 print_shortest_lock_dependencies(other, root);
2666 pr_warn("\nstack backtrace:\n");
2673 * Prove that in the forwards-direction subgraph starting at <this>
2674 * there is no lock matching <mask>:
2677 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
2678 enum lock_usage_bit bit, const char *irqclass)
2681 struct lock_list root;
2682 struct lock_list *uninitialized_var(target_entry);
2685 root.class = hlock_class(this);
2686 ret = find_usage_forwards(&root, bit, &target_entry);
2688 return print_bfs_bug(ret);
2692 return print_irq_inversion_bug(curr, &root, target_entry,
2697 * Prove that in the backwards-direction subgraph starting at <this>
2698 * there is no lock matching <mask>:
2701 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
2702 enum lock_usage_bit bit, const char *irqclass)
2705 struct lock_list root;
2706 struct lock_list *uninitialized_var(target_entry);
2709 root.class = hlock_class(this);
2710 ret = find_usage_backwards(&root, bit, &target_entry);
2712 return print_bfs_bug(ret);
2716 return print_irq_inversion_bug(curr, &root, target_entry,
2720 void print_irqtrace_events(struct task_struct *curr)
2722 printk("irq event stamp: %u\n", curr->irq_events);
2723 printk("hardirqs last enabled at (%u): [<%p>] %pS\n",
2724 curr->hardirq_enable_event, (void *)curr->hardirq_enable_ip,
2725 (void *)curr->hardirq_enable_ip);
2726 printk("hardirqs last disabled at (%u): [<%p>] %pS\n",
2727 curr->hardirq_disable_event, (void *)curr->hardirq_disable_ip,
2728 (void *)curr->hardirq_disable_ip);
2729 printk("softirqs last enabled at (%u): [<%p>] %pS\n",
2730 curr->softirq_enable_event, (void *)curr->softirq_enable_ip,
2731 (void *)curr->softirq_enable_ip);
2732 printk("softirqs last disabled at (%u): [<%p>] %pS\n",
2733 curr->softirq_disable_event, (void *)curr->softirq_disable_ip,
2734 (void *)curr->softirq_disable_ip);
2737 static int HARDIRQ_verbose(struct lock_class *class)
2740 return class_filter(class);
2745 static int SOFTIRQ_verbose(struct lock_class *class)
2748 return class_filter(class);
2753 #define STRICT_READ_CHECKS 1
2755 static int (*state_verbose_f[])(struct lock_class *class) = {
2756 #define LOCKDEP_STATE(__STATE) \
2758 #include "lockdep_states.h"
2759 #undef LOCKDEP_STATE
2762 static inline int state_verbose(enum lock_usage_bit bit,
2763 struct lock_class *class)
2765 return state_verbose_f[bit >> 2](class);
2768 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
2769 enum lock_usage_bit bit, const char *name);
2772 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
2773 enum lock_usage_bit new_bit)
2775 int excl_bit = exclusive_bit(new_bit);
2776 int read = new_bit & 1;
2777 int dir = new_bit & 2;
2780 * mark USED_IN has to look forwards -- to ensure no dependency
2781 * has ENABLED state, which would allow recursion deadlocks.
2783 * mark ENABLED has to look backwards -- to ensure no dependee
2784 * has USED_IN state, which, again, would allow recursion deadlocks.
2786 check_usage_f usage = dir ?
2787 check_usage_backwards : check_usage_forwards;
2790 * Validate that this particular lock does not have conflicting
2793 if (!valid_state(curr, this, new_bit, excl_bit))
2797 * Validate that the lock dependencies don't have conflicting usage
2800 if ((!read || !dir || STRICT_READ_CHECKS) &&
2801 !usage(curr, this, excl_bit, state_name(new_bit & ~1)))
2805 * Check for read in write conflicts
2808 if (!valid_state(curr, this, new_bit, excl_bit + 1))
2811 if (STRICT_READ_CHECKS &&
2812 !usage(curr, this, excl_bit + 1,
2813 state_name(new_bit + 1)))
2817 if (state_verbose(new_bit, hlock_class(this)))
2824 #define LOCKDEP_STATE(__STATE) __STATE,
2825 #include "lockdep_states.h"
2826 #undef LOCKDEP_STATE
2830 * Mark all held locks with a usage bit:
2833 mark_held_locks(struct task_struct *curr, enum mark_type mark)
2835 enum lock_usage_bit usage_bit;
2836 struct held_lock *hlock;
2839 for (i = 0; i < curr->lockdep_depth; i++) {
2840 hlock = curr->held_locks + i;
2842 usage_bit = 2 + (mark << 2); /* ENABLED */
2844 usage_bit += 1; /* READ */
2846 BUG_ON(usage_bit >= LOCK_USAGE_STATES);
2851 if (!mark_lock(curr, hlock, usage_bit))
2859 * Hardirqs will be enabled:
2861 static void __trace_hardirqs_on_caller(unsigned long ip)
2863 struct task_struct *curr = current;
2865 /* we'll do an OFF -> ON transition: */
2866 curr->hardirqs_enabled = 1;
2869 * We are going to turn hardirqs on, so set the
2870 * usage bit for all held locks:
2872 if (!mark_held_locks(curr, HARDIRQ))
2875 * If we have softirqs enabled, then set the usage
2876 * bit for all held locks. (disabled hardirqs prevented
2877 * this bit from being set before)
2879 if (curr->softirqs_enabled)
2880 if (!mark_held_locks(curr, SOFTIRQ))
2883 curr->hardirq_enable_ip = ip;
2884 curr->hardirq_enable_event = ++curr->irq_events;
2885 debug_atomic_inc(hardirqs_on_events);
2888 __visible void trace_hardirqs_on_caller(unsigned long ip)
2890 time_hardirqs_on(CALLER_ADDR0, ip);
2892 if (unlikely(!debug_locks || current->lockdep_recursion))
2895 if (unlikely(current->hardirqs_enabled)) {
2897 * Neither irq nor preemption are disabled here
2898 * so this is racy by nature but losing one hit
2899 * in a stat is not a big deal.
2901 __debug_atomic_inc(redundant_hardirqs_on);
2906 * We're enabling irqs and according to our state above irqs weren't
2907 * already enabled, yet we find the hardware thinks they are in fact
2908 * enabled.. someone messed up their IRQ state tracing.
2910 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2914 * See the fine text that goes along with this variable definition.
2916 if (DEBUG_LOCKS_WARN_ON(unlikely(early_boot_irqs_disabled)))
2920 * Can't allow enabling interrupts while in an interrupt handler,
2921 * that's general bad form and such. Recursion, limited stack etc..
2923 if (DEBUG_LOCKS_WARN_ON(current->hardirq_context))
2926 current->lockdep_recursion = 1;
2927 __trace_hardirqs_on_caller(ip);
2928 current->lockdep_recursion = 0;
2930 EXPORT_SYMBOL(trace_hardirqs_on_caller);
2932 void trace_hardirqs_on(void)
2934 trace_hardirqs_on_caller(CALLER_ADDR0);
2936 EXPORT_SYMBOL(trace_hardirqs_on);
2939 * Hardirqs were disabled:
2941 __visible void trace_hardirqs_off_caller(unsigned long ip)
2943 struct task_struct *curr = current;
2945 time_hardirqs_off(CALLER_ADDR0, ip);
2947 if (unlikely(!debug_locks || current->lockdep_recursion))
2951 * So we're supposed to get called after you mask local IRQs, but for
2952 * some reason the hardware doesn't quite think you did a proper job.
2954 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2957 if (curr->hardirqs_enabled) {
2959 * We have done an ON -> OFF transition:
2961 curr->hardirqs_enabled = 0;
2962 curr->hardirq_disable_ip = ip;
2963 curr->hardirq_disable_event = ++curr->irq_events;
2964 debug_atomic_inc(hardirqs_off_events);
2966 debug_atomic_inc(redundant_hardirqs_off);
2968 EXPORT_SYMBOL(trace_hardirqs_off_caller);
2970 void trace_hardirqs_off(void)
2972 trace_hardirqs_off_caller(CALLER_ADDR0);
2974 EXPORT_SYMBOL(trace_hardirqs_off);
2977 * Softirqs will be enabled:
2979 void trace_softirqs_on(unsigned long ip)
2981 struct task_struct *curr = current;
2983 if (unlikely(!debug_locks || current->lockdep_recursion))
2987 * We fancy IRQs being disabled here, see softirq.c, avoids
2988 * funny state and nesting things.
2990 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2993 if (curr->softirqs_enabled) {
2994 debug_atomic_inc(redundant_softirqs_on);
2998 current->lockdep_recursion = 1;
3000 * We'll do an OFF -> ON transition:
3002 curr->softirqs_enabled = 1;
3003 curr->softirq_enable_ip = ip;
3004 curr->softirq_enable_event = ++curr->irq_events;
3005 debug_atomic_inc(softirqs_on_events);
3007 * We are going to turn softirqs on, so set the
3008 * usage bit for all held locks, if hardirqs are
3011 if (curr->hardirqs_enabled)
3012 mark_held_locks(curr, SOFTIRQ);
3013 current->lockdep_recursion = 0;
3017 * Softirqs were disabled:
3019 void trace_softirqs_off(unsigned long ip)
3021 struct task_struct *curr = current;
3023 if (unlikely(!debug_locks || current->lockdep_recursion))
3027 * We fancy IRQs being disabled here, see softirq.c
3029 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3032 if (curr->softirqs_enabled) {
3034 * We have done an ON -> OFF transition:
3036 curr->softirqs_enabled = 0;
3037 curr->softirq_disable_ip = ip;
3038 curr->softirq_disable_event = ++curr->irq_events;
3039 debug_atomic_inc(softirqs_off_events);
3041 * Whoops, we wanted softirqs off, so why aren't they?
3043 DEBUG_LOCKS_WARN_ON(!softirq_count());
3045 debug_atomic_inc(redundant_softirqs_off);
3048 static int mark_irqflags(struct task_struct *curr, struct held_lock *hlock)
3051 * If non-trylock use in a hardirq or softirq context, then
3052 * mark the lock as used in these contexts:
3054 if (!hlock->trylock) {
3056 if (curr->hardirq_context)
3057 if (!mark_lock(curr, hlock,
3058 LOCK_USED_IN_HARDIRQ_READ))
3060 if (curr->softirq_context)
3061 if (!mark_lock(curr, hlock,
3062 LOCK_USED_IN_SOFTIRQ_READ))
3065 if (curr->hardirq_context)
3066 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
3068 if (curr->softirq_context)
3069 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
3073 if (!hlock->hardirqs_off) {
3075 if (!mark_lock(curr, hlock,
3076 LOCK_ENABLED_HARDIRQ_READ))
3078 if (curr->softirqs_enabled)
3079 if (!mark_lock(curr, hlock,
3080 LOCK_ENABLED_SOFTIRQ_READ))
3083 if (!mark_lock(curr, hlock,
3084 LOCK_ENABLED_HARDIRQ))
3086 if (curr->softirqs_enabled)
3087 if (!mark_lock(curr, hlock,
3088 LOCK_ENABLED_SOFTIRQ))
3096 static inline unsigned int task_irq_context(struct task_struct *task)
3098 return 2 * !!task->hardirq_context + !!task->softirq_context;
3101 static int separate_irq_context(struct task_struct *curr,
3102 struct held_lock *hlock)
3104 unsigned int depth = curr->lockdep_depth;
3107 * Keep track of points where we cross into an interrupt context:
3110 struct held_lock *prev_hlock;
3112 prev_hlock = curr->held_locks + depth-1;
3114 * If we cross into another context, reset the
3115 * hash key (this also prevents the checking and the
3116 * adding of the dependency to 'prev'):
3118 if (prev_hlock->irq_context != hlock->irq_context)
3124 #else /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
3127 int mark_lock_irq(struct task_struct *curr, struct held_lock *this,
3128 enum lock_usage_bit new_bit)
3130 WARN_ON(1); /* Impossible innit? when we don't have TRACE_IRQFLAG */
3134 static inline int mark_irqflags(struct task_struct *curr,
3135 struct held_lock *hlock)
3140 static inline unsigned int task_irq_context(struct task_struct *task)
3145 static inline int separate_irq_context(struct task_struct *curr,
3146 struct held_lock *hlock)
3151 #endif /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
3154 * Mark a lock with a usage bit, and validate the state transition:
3156 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3157 enum lock_usage_bit new_bit)
3159 unsigned int new_mask = 1 << new_bit, ret = 1;
3162 * If already set then do not dirty the cacheline,
3163 * nor do any checks:
3165 if (likely(hlock_class(this)->usage_mask & new_mask))
3171 * Make sure we didn't race:
3173 if (unlikely(hlock_class(this)->usage_mask & new_mask)) {
3178 hlock_class(this)->usage_mask |= new_mask;
3180 if (!save_trace(hlock_class(this)->usage_traces + new_bit))
3184 #define LOCKDEP_STATE(__STATE) \
3185 case LOCK_USED_IN_##__STATE: \
3186 case LOCK_USED_IN_##__STATE##_READ: \
3187 case LOCK_ENABLED_##__STATE: \
3188 case LOCK_ENABLED_##__STATE##_READ:
3189 #include "lockdep_states.h"
3190 #undef LOCKDEP_STATE
3191 ret = mark_lock_irq(curr, this, new_bit);
3196 debug_atomic_dec(nr_unused_locks);
3199 if (!debug_locks_off_graph_unlock())
3208 * We must printk outside of the graph_lock:
3211 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
3213 print_irqtrace_events(curr);
3221 * Initialize a lock instance's lock-class mapping info:
3223 static void __lockdep_init_map(struct lockdep_map *lock, const char *name,
3224 struct lock_class_key *key, int subclass)
3228 kmemcheck_mark_initialized(lock, sizeof(*lock));
3230 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
3231 lock->class_cache[i] = NULL;
3233 #ifdef CONFIG_LOCK_STAT
3234 lock->cpu = raw_smp_processor_id();
3238 * Can't be having no nameless bastards around this place!
3240 if (DEBUG_LOCKS_WARN_ON(!name)) {
3241 lock->name = "NULL";
3248 * No key, no joy, we need to hash something.
3250 if (DEBUG_LOCKS_WARN_ON(!key))
3253 * Sanity check, the lock-class key must be persistent:
3255 if (!static_obj(key)) {
3256 printk("BUG: key %p not in .data!\n", key);
3258 * What it says above ^^^^^, I suggest you read it.
3260 DEBUG_LOCKS_WARN_ON(1);
3265 if (unlikely(!debug_locks))
3269 unsigned long flags;
3271 if (DEBUG_LOCKS_WARN_ON(current->lockdep_recursion))
3274 raw_local_irq_save(flags);
3275 current->lockdep_recursion = 1;
3276 register_lock_class(lock, subclass, 1);
3277 current->lockdep_recursion = 0;
3278 raw_local_irq_restore(flags);
3282 void lockdep_init_map(struct lockdep_map *lock, const char *name,
3283 struct lock_class_key *key, int subclass)
3285 cross_init(lock, 0);
3286 __lockdep_init_map(lock, name, key, subclass);
3288 EXPORT_SYMBOL_GPL(lockdep_init_map);
3290 #ifdef CONFIG_LOCKDEP_CROSSRELEASE
3291 void lockdep_init_map_crosslock(struct lockdep_map *lock, const char *name,
3292 struct lock_class_key *key, int subclass)
3294 cross_init(lock, 1);
3295 __lockdep_init_map(lock, name, key, subclass);
3297 EXPORT_SYMBOL_GPL(lockdep_init_map_crosslock);
3300 struct lock_class_key __lockdep_no_validate__;
3301 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
3304 print_lock_nested_lock_not_held(struct task_struct *curr,
3305 struct held_lock *hlock,
3308 if (!debug_locks_off())
3310 if (debug_locks_silent)
3314 pr_warn("==================================\n");
3315 pr_warn("WARNING: Nested lock was not taken\n");
3316 print_kernel_ident();
3317 pr_warn("----------------------------------\n");
3319 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
3322 pr_warn("\nbut this task is not holding:\n");
3323 pr_warn("%s\n", hlock->nest_lock->name);
3325 pr_warn("\nstack backtrace:\n");
3328 pr_warn("\nother info that might help us debug this:\n");
3329 lockdep_print_held_locks(curr);
3331 pr_warn("\nstack backtrace:\n");
3337 static int __lock_is_held(struct lockdep_map *lock, int read);
3340 * This gets called for every mutex_lock*()/spin_lock*() operation.
3341 * We maintain the dependency maps and validate the locking attempt:
3343 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3344 int trylock, int read, int check, int hardirqs_off,
3345 struct lockdep_map *nest_lock, unsigned long ip,
3346 int references, int pin_count)
3348 struct task_struct *curr = current;
3349 struct lock_class *class = NULL;
3350 struct held_lock *hlock;
3357 if (unlikely(!debug_locks))
3361 * Lockdep should run with IRQs disabled, otherwise we could
3362 * get an interrupt which would want to take locks, which would
3363 * end up in lockdep and have you got a head-ache already?
3365 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3368 if (!prove_locking || lock->key == &__lockdep_no_validate__)
3371 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
3372 class = lock->class_cache[subclass];
3376 if (unlikely(!class)) {
3377 class = register_lock_class(lock, subclass, 0);
3381 atomic_inc((atomic_t *)&class->ops);
3382 if (very_verbose(class)) {
3383 printk("\nacquire class [%p] %s", class->key, class->name);
3384 if (class->name_version > 1)
3385 printk(KERN_CONT "#%d", class->name_version);
3386 printk(KERN_CONT "\n");
3391 * Add the lock to the list of currently held locks.
3392 * (we dont increase the depth just yet, up until the
3393 * dependency checks are done)
3395 depth = curr->lockdep_depth;
3397 * Ran out of static storage for our per-task lock stack again have we?
3399 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
3402 class_idx = class - lock_classes + 1;
3404 /* TODO: nest_lock is not implemented for crosslock yet. */
3405 if (depth && !cross_lock(lock)) {
3406 hlock = curr->held_locks + depth - 1;
3407 if (hlock->class_idx == class_idx && nest_lock) {
3408 if (hlock->references) {
3410 * Check: unsigned int references:12, overflow.
3412 if (DEBUG_LOCKS_WARN_ON(hlock->references == (1 << 12)-1))
3415 hlock->references++;
3417 hlock->references = 2;
3424 hlock = curr->held_locks + depth;
3426 * Plain impossible, we just registered it and checked it weren't no
3427 * NULL like.. I bet this mushroom I ate was good!
3429 if (DEBUG_LOCKS_WARN_ON(!class))
3431 hlock->class_idx = class_idx;
3432 hlock->acquire_ip = ip;
3433 hlock->instance = lock;
3434 hlock->nest_lock = nest_lock;
3435 hlock->irq_context = task_irq_context(curr);
3436 hlock->trylock = trylock;
3438 hlock->check = check;
3439 hlock->hardirqs_off = !!hardirqs_off;
3440 hlock->references = references;
3441 #ifdef CONFIG_LOCK_STAT
3442 hlock->waittime_stamp = 0;
3443 hlock->holdtime_stamp = lockstat_clock();
3445 hlock->pin_count = pin_count;
3447 if (check && !mark_irqflags(curr, hlock))
3450 /* mark it as used: */
3451 if (!mark_lock(curr, hlock, LOCK_USED))
3455 * Calculate the chain hash: it's the combined hash of all the
3456 * lock keys along the dependency chain. We save the hash value
3457 * at every step so that we can get the current hash easily
3458 * after unlock. The chain hash is then used to cache dependency
3461 * The 'key ID' is what is the most compact key value to drive
3462 * the hash, not class->key.
3465 * Whoops, we did it again.. ran straight out of our static allocation.
3467 if (DEBUG_LOCKS_WARN_ON(class_idx > MAX_LOCKDEP_KEYS))
3470 chain_key = curr->curr_chain_key;
3473 * How can we have a chain hash when we ain't got no keys?!
3475 if (DEBUG_LOCKS_WARN_ON(chain_key != 0))
3480 hlock->prev_chain_key = chain_key;
3481 if (separate_irq_context(curr, hlock)) {
3485 chain_key = iterate_chain_key(chain_key, class_idx);
3487 if (nest_lock && !__lock_is_held(nest_lock, -1))
3488 return print_lock_nested_lock_not_held(curr, hlock, ip);
3490 if (!validate_chain(curr, lock, hlock, chain_head, chain_key))
3493 ret = lock_acquire_crosslock(hlock);
3495 * 2 means normal acquire operations are needed. Otherwise, it's
3496 * ok just to return with '0:fail, 1:success'.
3501 curr->curr_chain_key = chain_key;
3502 curr->lockdep_depth++;
3503 check_chain_key(curr);
3504 #ifdef CONFIG_DEBUG_LOCKDEP
3505 if (unlikely(!debug_locks))
3508 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
3510 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
3511 printk(KERN_DEBUG "depth: %i max: %lu!\n",
3512 curr->lockdep_depth, MAX_LOCK_DEPTH);
3514 lockdep_print_held_locks(current);
3515 debug_show_all_locks();
3521 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
3522 max_lockdep_depth = curr->lockdep_depth;
3528 print_unlock_imbalance_bug(struct task_struct *curr, struct lockdep_map *lock,
3531 if (!debug_locks_off())
3533 if (debug_locks_silent)
3537 pr_warn("=====================================\n");
3538 pr_warn("WARNING: bad unlock balance detected!\n");
3539 print_kernel_ident();
3540 pr_warn("-------------------------------------\n");
3541 pr_warn("%s/%d is trying to release lock (",
3542 curr->comm, task_pid_nr(curr));
3543 print_lockdep_cache(lock);
3546 pr_warn("but there are no more locks to release!\n");
3547 pr_warn("\nother info that might help us debug this:\n");
3548 lockdep_print_held_locks(curr);
3550 pr_warn("\nstack backtrace:\n");
3556 static int match_held_lock(struct held_lock *hlock, struct lockdep_map *lock)
3558 if (hlock->instance == lock)
3561 if (hlock->references) {
3562 struct lock_class *class = lock->class_cache[0];
3565 class = look_up_lock_class(lock, 0);
3568 * If look_up_lock_class() failed to find a class, we're trying
3569 * to test if we hold a lock that has never yet been acquired.
3570 * Clearly if the lock hasn't been acquired _ever_, we're not
3571 * holding it either, so report failure.
3573 if (IS_ERR_OR_NULL(class))
3577 * References, but not a lock we're actually ref-counting?
3578 * State got messed up, follow the sites that change ->references
3579 * and try to make sense of it.
3581 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
3584 if (hlock->class_idx == class - lock_classes + 1)
3591 /* @depth must not be zero */
3592 static struct held_lock *find_held_lock(struct task_struct *curr,
3593 struct lockdep_map *lock,
3594 unsigned int depth, int *idx)
3596 struct held_lock *ret, *hlock, *prev_hlock;
3600 hlock = curr->held_locks + i;
3602 if (match_held_lock(hlock, lock))
3606 for (i--, prev_hlock = hlock--;
3608 i--, prev_hlock = hlock--) {
3610 * We must not cross into another context:
3612 if (prev_hlock->irq_context != hlock->irq_context) {
3616 if (match_held_lock(hlock, lock)) {
3627 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
3630 struct held_lock *hlock;
3632 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
3633 if (!__lock_acquire(hlock->instance,
3634 hlock_class(hlock)->subclass,
3636 hlock->read, hlock->check,
3637 hlock->hardirqs_off,
3638 hlock->nest_lock, hlock->acquire_ip,
3639 hlock->references, hlock->pin_count))
3646 __lock_set_class(struct lockdep_map *lock, const char *name,
3647 struct lock_class_key *key, unsigned int subclass,
3650 struct task_struct *curr = current;
3651 struct held_lock *hlock;
3652 struct lock_class *class;
3656 depth = curr->lockdep_depth;
3658 * This function is about (re)setting the class of a held lock,
3659 * yet we're not actually holding any locks. Naughty user!
3661 if (DEBUG_LOCKS_WARN_ON(!depth))
3664 hlock = find_held_lock(curr, lock, depth, &i);
3666 return print_unlock_imbalance_bug(curr, lock, ip);
3668 lockdep_init_map(lock, name, key, 0);
3669 class = register_lock_class(lock, subclass, 0);
3670 hlock->class_idx = class - lock_classes + 1;
3672 curr->lockdep_depth = i;
3673 curr->curr_chain_key = hlock->prev_chain_key;
3675 if (reacquire_held_locks(curr, depth, i))
3679 * I took it apart and put it back together again, except now I have
3680 * these 'spare' parts.. where shall I put them.
3682 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
3687 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
3689 struct task_struct *curr = current;
3690 struct held_lock *hlock;
3694 depth = curr->lockdep_depth;
3696 * This function is about (re)setting the class of a held lock,
3697 * yet we're not actually holding any locks. Naughty user!
3699 if (DEBUG_LOCKS_WARN_ON(!depth))
3702 hlock = find_held_lock(curr, lock, depth, &i);
3704 return print_unlock_imbalance_bug(curr, lock, ip);
3706 curr->lockdep_depth = i;
3707 curr->curr_chain_key = hlock->prev_chain_key;
3709 WARN(hlock->read, "downgrading a read lock");
3711 hlock->acquire_ip = ip;
3713 if (reacquire_held_locks(curr, depth, i))
3717 * I took it apart and put it back together again, except now I have
3718 * these 'spare' parts.. where shall I put them.
3720 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
3726 * Remove the lock to the list of currently held locks - this gets
3727 * called on mutex_unlock()/spin_unlock*() (or on a failed
3728 * mutex_lock_interruptible()).
3730 * @nested is an hysterical artifact, needs a tree wide cleanup.
3733 __lock_release(struct lockdep_map *lock, int nested, unsigned long ip)
3735 struct task_struct *curr = current;
3736 struct held_lock *hlock;
3740 if (unlikely(!debug_locks))
3743 ret = lock_release_crosslock(lock);
3745 * 2 means normal release operations are needed. Otherwise, it's
3746 * ok just to return with '0:fail, 1:success'.
3751 depth = curr->lockdep_depth;
3753 * So we're all set to release this lock.. wait what lock? We don't
3754 * own any locks, you've been drinking again?
3756 if (DEBUG_LOCKS_WARN_ON(depth <= 0))
3757 return print_unlock_imbalance_bug(curr, lock, ip);
3760 * Check whether the lock exists in the current stack
3763 hlock = find_held_lock(curr, lock, depth, &i);
3765 return print_unlock_imbalance_bug(curr, lock, ip);
3767 if (hlock->instance == lock)
3768 lock_release_holdtime(hlock);
3770 WARN(hlock->pin_count, "releasing a pinned lock\n");
3772 if (hlock->references) {
3773 hlock->references--;
3774 if (hlock->references) {
3776 * We had, and after removing one, still have
3777 * references, the current lock stack is still
3778 * valid. We're done!
3785 * We have the right lock to unlock, 'hlock' points to it.
3786 * Now we remove it from the stack, and add back the other
3787 * entries (if any), recalculating the hash along the way:
3790 curr->lockdep_depth = i;
3791 curr->curr_chain_key = hlock->prev_chain_key;
3793 if (reacquire_held_locks(curr, depth, i + 1))
3797 * We had N bottles of beer on the wall, we drank one, but now
3798 * there's not N-1 bottles of beer left on the wall...
3800 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - 1))
3806 static int __lock_is_held(struct lockdep_map *lock, int read)
3808 struct task_struct *curr = current;
3811 for (i = 0; i < curr->lockdep_depth; i++) {
3812 struct held_lock *hlock = curr->held_locks + i;
3814 if (match_held_lock(hlock, lock)) {
3815 if (read == -1 || hlock->read == read)
3825 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
3827 struct pin_cookie cookie = NIL_COOKIE;
3828 struct task_struct *curr = current;
3831 if (unlikely(!debug_locks))
3834 for (i = 0; i < curr->lockdep_depth; i++) {
3835 struct held_lock *hlock = curr->held_locks + i;
3837 if (match_held_lock(hlock, lock)) {
3839 * Grab 16bits of randomness; this is sufficient to not
3840 * be guessable and still allows some pin nesting in
3841 * our u32 pin_count.
3843 cookie.val = 1 + (prandom_u32() >> 16);
3844 hlock->pin_count += cookie.val;
3849 WARN(1, "pinning an unheld lock\n");
3853 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
3855 struct task_struct *curr = current;
3858 if (unlikely(!debug_locks))
3861 for (i = 0; i < curr->lockdep_depth; i++) {
3862 struct held_lock *hlock = curr->held_locks + i;
3864 if (match_held_lock(hlock, lock)) {
3865 hlock->pin_count += cookie.val;
3870 WARN(1, "pinning an unheld lock\n");
3873 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
3875 struct task_struct *curr = current;
3878 if (unlikely(!debug_locks))
3881 for (i = 0; i < curr->lockdep_depth; i++) {
3882 struct held_lock *hlock = curr->held_locks + i;
3884 if (match_held_lock(hlock, lock)) {
3885 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
3888 hlock->pin_count -= cookie.val;
3890 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
3891 hlock->pin_count = 0;
3897 WARN(1, "unpinning an unheld lock\n");
3901 * Check whether we follow the irq-flags state precisely:
3903 static void check_flags(unsigned long flags)
3905 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP) && \
3906 defined(CONFIG_TRACE_IRQFLAGS)
3910 if (irqs_disabled_flags(flags)) {
3911 if (DEBUG_LOCKS_WARN_ON(current->hardirqs_enabled)) {
3912 printk("possible reason: unannotated irqs-off.\n");
3915 if (DEBUG_LOCKS_WARN_ON(!current->hardirqs_enabled)) {
3916 printk("possible reason: unannotated irqs-on.\n");
3921 * We dont accurately track softirq state in e.g.
3922 * hardirq contexts (such as on 4KSTACKS), so only
3923 * check if not in hardirq contexts:
3925 if (!hardirq_count()) {
3926 if (softirq_count()) {
3927 /* like the above, but with softirqs */
3928 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
3930 /* lick the above, does it taste good? */
3931 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
3936 print_irqtrace_events(current);
3940 void lock_set_class(struct lockdep_map *lock, const char *name,
3941 struct lock_class_key *key, unsigned int subclass,
3944 unsigned long flags;
3946 if (unlikely(current->lockdep_recursion))
3949 raw_local_irq_save(flags);
3950 current->lockdep_recursion = 1;
3952 if (__lock_set_class(lock, name, key, subclass, ip))
3953 check_chain_key(current);
3954 current->lockdep_recursion = 0;
3955 raw_local_irq_restore(flags);
3957 EXPORT_SYMBOL_GPL(lock_set_class);
3959 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
3961 unsigned long flags;
3963 if (unlikely(current->lockdep_recursion))
3966 raw_local_irq_save(flags);
3967 current->lockdep_recursion = 1;
3969 if (__lock_downgrade(lock, ip))
3970 check_chain_key(current);
3971 current->lockdep_recursion = 0;
3972 raw_local_irq_restore(flags);
3974 EXPORT_SYMBOL_GPL(lock_downgrade);
3977 * We are not always called with irqs disabled - do that here,
3978 * and also avoid lockdep recursion:
3980 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3981 int trylock, int read, int check,
3982 struct lockdep_map *nest_lock, unsigned long ip)
3984 unsigned long flags;
3986 if (unlikely(current->lockdep_recursion))
3989 raw_local_irq_save(flags);
3992 current->lockdep_recursion = 1;
3993 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
3994 __lock_acquire(lock, subclass, trylock, read, check,
3995 irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
3996 current->lockdep_recursion = 0;
3997 raw_local_irq_restore(flags);
3999 EXPORT_SYMBOL_GPL(lock_acquire);
4001 void lock_release(struct lockdep_map *lock, int nested,
4004 unsigned long flags;
4006 if (unlikely(current->lockdep_recursion))
4009 raw_local_irq_save(flags);
4011 current->lockdep_recursion = 1;
4012 trace_lock_release(lock, ip);
4013 if (__lock_release(lock, nested, ip))
4014 check_chain_key(current);
4015 current->lockdep_recursion = 0;
4016 raw_local_irq_restore(flags);
4018 EXPORT_SYMBOL_GPL(lock_release);
4020 int lock_is_held_type(struct lockdep_map *lock, int read)
4022 unsigned long flags;
4025 if (unlikely(current->lockdep_recursion))
4026 return 1; /* avoid false negative lockdep_assert_held() */
4028 raw_local_irq_save(flags);
4031 current->lockdep_recursion = 1;
4032 ret = __lock_is_held(lock, read);
4033 current->lockdep_recursion = 0;
4034 raw_local_irq_restore(flags);
4038 EXPORT_SYMBOL_GPL(lock_is_held_type);
4040 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
4042 struct pin_cookie cookie = NIL_COOKIE;
4043 unsigned long flags;
4045 if (unlikely(current->lockdep_recursion))
4048 raw_local_irq_save(flags);
4051 current->lockdep_recursion = 1;
4052 cookie = __lock_pin_lock(lock);
4053 current->lockdep_recursion = 0;
4054 raw_local_irq_restore(flags);
4058 EXPORT_SYMBOL_GPL(lock_pin_lock);
4060 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4062 unsigned long flags;
4064 if (unlikely(current->lockdep_recursion))
4067 raw_local_irq_save(flags);
4070 current->lockdep_recursion = 1;
4071 __lock_repin_lock(lock, cookie);
4072 current->lockdep_recursion = 0;
4073 raw_local_irq_restore(flags);
4075 EXPORT_SYMBOL_GPL(lock_repin_lock);
4077 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4079 unsigned long flags;
4081 if (unlikely(current->lockdep_recursion))
4084 raw_local_irq_save(flags);
4087 current->lockdep_recursion = 1;
4088 __lock_unpin_lock(lock, cookie);
4089 current->lockdep_recursion = 0;
4090 raw_local_irq_restore(flags);
4092 EXPORT_SYMBOL_GPL(lock_unpin_lock);
4094 #ifdef CONFIG_LOCK_STAT
4096 print_lock_contention_bug(struct task_struct *curr, struct lockdep_map *lock,
4099 if (!debug_locks_off())
4101 if (debug_locks_silent)
4105 pr_warn("=================================\n");
4106 pr_warn("WARNING: bad contention detected!\n");
4107 print_kernel_ident();
4108 pr_warn("---------------------------------\n");
4109 pr_warn("%s/%d is trying to contend lock (",
4110 curr->comm, task_pid_nr(curr));
4111 print_lockdep_cache(lock);
4114 pr_warn("but there are no locks held!\n");
4115 pr_warn("\nother info that might help us debug this:\n");
4116 lockdep_print_held_locks(curr);
4118 pr_warn("\nstack backtrace:\n");
4125 __lock_contended(struct lockdep_map *lock, unsigned long ip)
4127 struct task_struct *curr = current;
4128 struct held_lock *hlock;
4129 struct lock_class_stats *stats;
4131 int i, contention_point, contending_point;
4133 depth = curr->lockdep_depth;
4135 * Whee, we contended on this lock, except it seems we're not
4136 * actually trying to acquire anything much at all..
4138 if (DEBUG_LOCKS_WARN_ON(!depth))
4141 hlock = find_held_lock(curr, lock, depth, &i);
4143 print_lock_contention_bug(curr, lock, ip);
4147 if (hlock->instance != lock)
4150 hlock->waittime_stamp = lockstat_clock();
4152 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
4153 contending_point = lock_point(hlock_class(hlock)->contending_point,
4156 stats = get_lock_stats(hlock_class(hlock));
4157 if (contention_point < LOCKSTAT_POINTS)
4158 stats->contention_point[contention_point]++;
4159 if (contending_point < LOCKSTAT_POINTS)
4160 stats->contending_point[contending_point]++;
4161 if (lock->cpu != smp_processor_id())
4162 stats->bounces[bounce_contended + !!hlock->read]++;
4163 put_lock_stats(stats);
4167 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
4169 struct task_struct *curr = current;
4170 struct held_lock *hlock;
4171 struct lock_class_stats *stats;
4173 u64 now, waittime = 0;
4176 depth = curr->lockdep_depth;
4178 * Yay, we acquired ownership of this lock we didn't try to
4179 * acquire, how the heck did that happen?
4181 if (DEBUG_LOCKS_WARN_ON(!depth))
4184 hlock = find_held_lock(curr, lock, depth, &i);
4186 print_lock_contention_bug(curr, lock, _RET_IP_);
4190 if (hlock->instance != lock)
4193 cpu = smp_processor_id();
4194 if (hlock->waittime_stamp) {
4195 now = lockstat_clock();
4196 waittime = now - hlock->waittime_stamp;
4197 hlock->holdtime_stamp = now;
4200 trace_lock_acquired(lock, ip);
4202 stats = get_lock_stats(hlock_class(hlock));
4205 lock_time_inc(&stats->read_waittime, waittime);
4207 lock_time_inc(&stats->write_waittime, waittime);
4209 if (lock->cpu != cpu)
4210 stats->bounces[bounce_acquired + !!hlock->read]++;
4211 put_lock_stats(stats);
4217 void lock_contended(struct lockdep_map *lock, unsigned long ip)
4219 unsigned long flags;
4221 if (unlikely(!lock_stat))
4224 if (unlikely(current->lockdep_recursion))
4227 raw_local_irq_save(flags);
4229 current->lockdep_recursion = 1;
4230 trace_lock_contended(lock, ip);
4231 __lock_contended(lock, ip);
4232 current->lockdep_recursion = 0;
4233 raw_local_irq_restore(flags);
4235 EXPORT_SYMBOL_GPL(lock_contended);
4237 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
4239 unsigned long flags;
4241 if (unlikely(!lock_stat))
4244 if (unlikely(current->lockdep_recursion))
4247 raw_local_irq_save(flags);
4249 current->lockdep_recursion = 1;
4250 __lock_acquired(lock, ip);
4251 current->lockdep_recursion = 0;
4252 raw_local_irq_restore(flags);
4254 EXPORT_SYMBOL_GPL(lock_acquired);
4258 * Used by the testsuite, sanitize the validator state
4259 * after a simulated failure:
4262 void lockdep_reset(void)
4264 unsigned long flags;
4267 raw_local_irq_save(flags);
4268 current->curr_chain_key = 0;
4269 current->lockdep_depth = 0;
4270 current->lockdep_recursion = 0;
4271 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
4272 nr_hardirq_chains = 0;
4273 nr_softirq_chains = 0;
4274 nr_process_chains = 0;
4276 for (i = 0; i < CHAINHASH_SIZE; i++)
4277 INIT_HLIST_HEAD(chainhash_table + i);
4278 raw_local_irq_restore(flags);
4281 static void zap_class(struct lock_class *class)
4286 * Remove all dependencies this lock is
4289 for (i = 0; i < nr_list_entries; i++) {
4290 if (list_entries[i].class == class)
4291 list_del_rcu(&list_entries[i].entry);
4294 * Unhash the class and remove it from the all_lock_classes list:
4296 hlist_del_rcu(&class->hash_entry);
4297 list_del_rcu(&class->lock_entry);
4299 RCU_INIT_POINTER(class->key, NULL);
4300 RCU_INIT_POINTER(class->name, NULL);
4303 static inline int within(const void *addr, void *start, unsigned long size)
4305 return addr >= start && addr < start + size;
4309 * Used in module.c to remove lock classes from memory that is going to be
4310 * freed; and possibly re-used by other modules.
4312 * We will have had one sync_sched() before getting here, so we're guaranteed
4313 * nobody will look up these exact classes -- they're properly dead but still
4316 void lockdep_free_key_range(void *start, unsigned long size)
4318 struct lock_class *class;
4319 struct hlist_head *head;
4320 unsigned long flags;
4324 raw_local_irq_save(flags);
4325 locked = graph_lock();
4328 * Unhash all classes that were created by this module:
4330 for (i = 0; i < CLASSHASH_SIZE; i++) {
4331 head = classhash_table + i;
4332 hlist_for_each_entry_rcu(class, head, hash_entry) {
4333 if (within(class->key, start, size))
4335 else if (within(class->name, start, size))
4342 raw_local_irq_restore(flags);
4345 * Wait for any possible iterators from look_up_lock_class() to pass
4346 * before continuing to free the memory they refer to.
4348 * sync_sched() is sufficient because the read-side is IRQ disable.
4350 synchronize_sched();
4353 * XXX at this point we could return the resources to the pool;
4354 * instead we leak them. We would need to change to bitmap allocators
4355 * instead of the linear allocators we have now.
4359 void lockdep_reset_lock(struct lockdep_map *lock)
4361 struct lock_class *class;
4362 struct hlist_head *head;
4363 unsigned long flags;
4367 raw_local_irq_save(flags);
4370 * Remove all classes this lock might have:
4372 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
4374 * If the class exists we look it up and zap it:
4376 class = look_up_lock_class(lock, j);
4377 if (!IS_ERR_OR_NULL(class))
4381 * Debug check: in the end all mapped classes should
4384 locked = graph_lock();
4385 for (i = 0; i < CLASSHASH_SIZE; i++) {
4386 head = classhash_table + i;
4387 hlist_for_each_entry_rcu(class, head, hash_entry) {
4390 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
4391 match |= class == lock->class_cache[j];
4393 if (unlikely(match)) {
4394 if (debug_locks_off_graph_unlock()) {
4396 * We all just reset everything, how did it match?
4408 raw_local_irq_restore(flags);
4411 void __init lockdep_info(void)
4413 printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
4415 printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
4416 printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
4417 printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
4418 printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
4419 printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
4420 printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
4421 printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
4423 printk(" memory used by lock dependency info: %lu kB\n",
4424 (sizeof(struct lock_class) * MAX_LOCKDEP_KEYS +
4425 sizeof(struct list_head) * CLASSHASH_SIZE +
4426 sizeof(struct lock_list) * MAX_LOCKDEP_ENTRIES +
4427 sizeof(struct lock_chain) * MAX_LOCKDEP_CHAINS +
4428 sizeof(struct list_head) * CHAINHASH_SIZE
4429 #ifdef CONFIG_PROVE_LOCKING
4430 + sizeof(struct circular_queue)
4435 printk(" per task-struct memory footprint: %lu bytes\n",
4436 sizeof(struct held_lock) * MAX_LOCK_DEPTH);
4440 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
4441 const void *mem_to, struct held_lock *hlock)
4443 if (!debug_locks_off())
4445 if (debug_locks_silent)
4449 pr_warn("=========================\n");
4450 pr_warn("WARNING: held lock freed!\n");
4451 print_kernel_ident();
4452 pr_warn("-------------------------\n");
4453 pr_warn("%s/%d is freeing memory %p-%p, with a lock still held there!\n",
4454 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
4456 lockdep_print_held_locks(curr);
4458 pr_warn("\nstack backtrace:\n");
4462 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
4463 const void* lock_from, unsigned long lock_len)
4465 return lock_from + lock_len <= mem_from ||
4466 mem_from + mem_len <= lock_from;
4470 * Called when kernel memory is freed (or unmapped), or if a lock
4471 * is destroyed or reinitialized - this code checks whether there is
4472 * any held lock in the memory range of <from> to <to>:
4474 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
4476 struct task_struct *curr = current;
4477 struct held_lock *hlock;
4478 unsigned long flags;
4481 if (unlikely(!debug_locks))
4484 local_irq_save(flags);
4485 for (i = 0; i < curr->lockdep_depth; i++) {
4486 hlock = curr->held_locks + i;
4488 if (not_in_range(mem_from, mem_len, hlock->instance,
4489 sizeof(*hlock->instance)))
4492 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
4495 local_irq_restore(flags);
4497 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
4499 static void print_held_locks_bug(void)
4501 if (!debug_locks_off())
4503 if (debug_locks_silent)
4507 pr_warn("====================================\n");
4508 pr_warn("WARNING: %s/%d still has locks held!\n",
4509 current->comm, task_pid_nr(current));
4510 print_kernel_ident();
4511 pr_warn("------------------------------------\n");
4512 lockdep_print_held_locks(current);
4513 pr_warn("\nstack backtrace:\n");
4517 void debug_check_no_locks_held(void)
4519 if (unlikely(current->lockdep_depth > 0))
4520 print_held_locks_bug();
4522 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
4525 void debug_show_all_locks(void)
4527 struct task_struct *g, *p;
4531 if (unlikely(!debug_locks)) {
4532 pr_warn("INFO: lockdep is turned off.\n");
4535 pr_warn("\nShowing all locks held in the system:\n");
4538 * Here we try to get the tasklist_lock as hard as possible,
4539 * if not successful after 2 seconds we ignore it (but keep
4540 * trying). This is to enable a debug printout even if a
4541 * tasklist_lock-holding task deadlocks or crashes.
4544 if (!read_trylock(&tasklist_lock)) {
4546 pr_warn("hm, tasklist_lock locked, retrying... ");
4549 pr_cont(" #%d", 10-count);
4553 pr_cont(" ignoring it.\n");
4557 pr_cont(" locked it.\n");
4560 do_each_thread(g, p) {
4562 * It's not reliable to print a task's held locks
4563 * if it's not sleeping (or if it's not the current
4566 if (p->state == TASK_RUNNING && p != current)
4568 if (p->lockdep_depth)
4569 lockdep_print_held_locks(p);
4571 if (read_trylock(&tasklist_lock))
4573 } while_each_thread(g, p);
4576 pr_warn("=============================================\n\n");
4579 read_unlock(&tasklist_lock);
4581 EXPORT_SYMBOL_GPL(debug_show_all_locks);
4585 * Careful: only use this function if you are sure that
4586 * the task cannot run in parallel!
4588 void debug_show_held_locks(struct task_struct *task)
4590 if (unlikely(!debug_locks)) {
4591 printk("INFO: lockdep is turned off.\n");
4594 lockdep_print_held_locks(task);
4596 EXPORT_SYMBOL_GPL(debug_show_held_locks);
4598 asmlinkage __visible void lockdep_sys_exit(void)
4600 struct task_struct *curr = current;
4602 if (unlikely(curr->lockdep_depth)) {
4603 if (!debug_locks_off())
4606 pr_warn("================================================\n");
4607 pr_warn("WARNING: lock held when returning to user space!\n");
4608 print_kernel_ident();
4609 pr_warn("------------------------------------------------\n");
4610 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
4611 curr->comm, curr->pid);
4612 lockdep_print_held_locks(curr);
4616 * The lock history for each syscall should be independent. So wipe the
4617 * slate clean on return to userspace.
4619 lockdep_invariant_state(false);
4622 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
4624 struct task_struct *curr = current;
4626 /* Note: the following can be executed concurrently, so be careful. */
4628 pr_warn("=============================\n");
4629 pr_warn("WARNING: suspicious RCU usage\n");
4630 print_kernel_ident();
4631 pr_warn("-----------------------------\n");
4632 pr_warn("%s:%d %s!\n", file, line, s);
4633 pr_warn("\nother info that might help us debug this:\n\n");
4634 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
4635 !rcu_lockdep_current_cpu_online()
4636 ? "RCU used illegally from offline CPU!\n"
4637 : !rcu_is_watching()
4638 ? "RCU used illegally from idle CPU!\n"
4640 rcu_scheduler_active, debug_locks);
4643 * If a CPU is in the RCU-free window in idle (ie: in the section
4644 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
4645 * considers that CPU to be in an "extended quiescent state",
4646 * which means that RCU will be completely ignoring that CPU.
4647 * Therefore, rcu_read_lock() and friends have absolutely no
4648 * effect on a CPU running in that state. In other words, even if
4649 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
4650 * delete data structures out from under it. RCU really has no
4651 * choice here: we need to keep an RCU-free window in idle where
4652 * the CPU may possibly enter into low power mode. This way we can
4653 * notice an extended quiescent state to other CPUs that started a grace
4654 * period. Otherwise we would delay any grace period as long as we run
4657 * So complain bitterly if someone does call rcu_read_lock(),
4658 * rcu_read_lock_bh() and so on from extended quiescent states.
4660 if (!rcu_is_watching())
4661 pr_warn("RCU used illegally from extended quiescent state!\n");
4663 lockdep_print_held_locks(curr);
4664 pr_warn("\nstack backtrace:\n");
4667 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);
4669 #ifdef CONFIG_LOCKDEP_CROSSRELEASE
4672 * Crossrelease works by recording a lock history for each thread and
4673 * connecting those historic locks that were taken after the
4674 * wait_for_completion() in the complete() context.
4681 * wait_for_completion(&C);
4682 * lock_acquire_crosslock();
4683 * atomic_inc_return(&cross_gen_id);
4686 * | mutex_unlock(&B);
4689 * `-- lock_commit_crosslock();
4691 * Which will then add a dependency between B and C.
4694 #define xhlock(i) (current->xhlocks[(i) % MAX_XHLOCKS_NR])
4697 * Whenever a crosslock is held, cross_gen_id will be increased.
4699 static atomic_t cross_gen_id; /* Can be wrapped */
4702 * Make an entry of the ring buffer invalid.
4704 static inline void invalidate_xhlock(struct hist_lock *xhlock)
4707 * Normally, xhlock->hlock.instance must be !NULL.
4709 xhlock->hlock.instance = NULL;
4713 * Lock history stacks; we have 2 nested lock history stacks:
4718 * The thing is that once we complete a HARD/SOFT IRQ the future task locks
4719 * should not depend on any of the locks observed while running the IRQ. So
4720 * what we do is rewind the history buffer and erase all our knowledge of that
4724 void crossrelease_hist_start(enum xhlock_context_t c)
4726 struct task_struct *cur = current;
4731 cur->xhlock_idx_hist[c] = cur->xhlock_idx;
4732 cur->hist_id_save[c] = cur->hist_id;
4735 void crossrelease_hist_end(enum xhlock_context_t c)
4737 struct task_struct *cur = current;
4740 unsigned int idx = cur->xhlock_idx_hist[c];
4741 struct hist_lock *h = &xhlock(idx);
4743 cur->xhlock_idx = idx;
4745 /* Check if the ring was overwritten. */
4746 if (h->hist_id != cur->hist_id_save[c])
4747 invalidate_xhlock(h);
4752 * lockdep_invariant_state() is used to annotate independence inside a task, to
4753 * make one task look like multiple independent 'tasks'.
4755 * Take for instance workqueues; each work is independent of the last. The
4756 * completion of a future work does not depend on the completion of a past work
4757 * (in general). Therefore we must not carry that (lock) dependency across
4760 * This is true for many things; pretty much all kthreads fall into this
4761 * pattern, where they have an invariant state and future completions do not
4762 * depend on past completions. Its just that since they all have the 'same'
4763 * form -- the kthread does the same over and over -- it doesn't typically
4766 * The same is true for system-calls, once a system call is completed (we've
4767 * returned to userspace) the next system call does not depend on the lock
4768 * history of the previous system call.
4770 * They key property for independence, this invariant state, is that it must be
4771 * a point where we hold no locks and have no history. Because if we were to
4772 * hold locks, the restore at _end() would not necessarily recover it's history
4773 * entry. Similarly, independence per-definition means it does not depend on
4776 void lockdep_invariant_state(bool force)
4779 * We call this at an invariant point, no current state, no history.
4780 * Verify the former, enforce the latter.
4782 WARN_ON_ONCE(!force && current->lockdep_depth);
4783 invalidate_xhlock(&xhlock(current->xhlock_idx));
4786 static int cross_lock(struct lockdep_map *lock)
4788 return lock ? lock->cross : 0;
4792 * This is needed to decide the relationship between wrapable variables.
4794 static inline int before(unsigned int a, unsigned int b)
4796 return (int)(a - b) < 0;
4799 static inline struct lock_class *xhlock_class(struct hist_lock *xhlock)
4801 return hlock_class(&xhlock->hlock);
4804 static inline struct lock_class *xlock_class(struct cross_lock *xlock)
4806 return hlock_class(&xlock->hlock);
4810 * Should we check a dependency with previous one?
4812 static inline int depend_before(struct held_lock *hlock)
4814 return hlock->read != 2 && hlock->check && !hlock->trylock;
4818 * Should we check a dependency with next one?
4820 static inline int depend_after(struct held_lock *hlock)
4822 return hlock->read != 2 && hlock->check;
4826 * Check if the xhlock is valid, which would be false if,
4828 * 1. Has not used after initializaion yet.
4829 * 2. Got invalidated.
4831 * Remind hist_lock is implemented as a ring buffer.
4833 static inline int xhlock_valid(struct hist_lock *xhlock)
4836 * xhlock->hlock.instance must be !NULL.
4838 return !!xhlock->hlock.instance;
4842 * Record a hist_lock entry.
4844 * Irq disable is only required.
4846 static void add_xhlock(struct held_lock *hlock)
4848 unsigned int idx = ++current->xhlock_idx;
4849 struct hist_lock *xhlock = &xhlock(idx);
4851 #ifdef CONFIG_DEBUG_LOCKDEP
4853 * This can be done locklessly because they are all task-local
4854 * state, we must however ensure IRQs are disabled.
4856 WARN_ON_ONCE(!irqs_disabled());
4859 /* Initialize hist_lock's members */
4860 xhlock->hlock = *hlock;
4861 xhlock->hist_id = ++current->hist_id;
4863 xhlock->trace.nr_entries = 0;
4864 xhlock->trace.max_entries = MAX_XHLOCK_TRACE_ENTRIES;
4865 xhlock->trace.entries = xhlock->trace_entries;
4866 xhlock->trace.skip = 3;
4867 save_stack_trace(&xhlock->trace);
4870 static inline int same_context_xhlock(struct hist_lock *xhlock)
4872 return xhlock->hlock.irq_context == task_irq_context(current);
4876 * This should be lockless as far as possible because this would be
4877 * called very frequently.
4879 static void check_add_xhlock(struct held_lock *hlock)
4882 * Record a hist_lock, only in case that acquisitions ahead
4883 * could depend on the held_lock. For example, if the held_lock
4884 * is trylock then acquisitions ahead never depends on that.
4885 * In that case, we don't need to record it. Just return.
4887 if (!current->xhlocks || !depend_before(hlock))
4896 static int add_xlock(struct held_lock *hlock)
4898 struct cross_lock *xlock;
4899 unsigned int gen_id;
4904 xlock = &((struct lockdep_map_cross *)hlock->instance)->xlock;
4907 * When acquisitions for a crosslock are overlapped, we use
4908 * nr_acquire to perform commit for them, based on cross_gen_id
4909 * of the first acquisition, which allows to add additional
4912 * Moreover, when no acquisition of a crosslock is in progress,
4913 * we should not perform commit because the lock might not exist
4914 * any more, which might cause incorrect memory access. So we
4915 * have to track the number of acquisitions of a crosslock.
4917 * depend_after() is necessary to initialize only the first
4918 * valid xlock so that the xlock can be used on its commit.
4920 if (xlock->nr_acquire++ && depend_after(&xlock->hlock))
4923 gen_id = (unsigned int)atomic_inc_return(&cross_gen_id);
4924 xlock->hlock = *hlock;
4925 xlock->hlock.gen_id = gen_id;
4932 * Called for both normal and crosslock acquires. Normal locks will be
4933 * pushed on the hist_lock queue. Cross locks will record state and
4934 * stop regular lock_acquire() to avoid being placed on the held_lock
4937 * Return: 0 - failure;
4938 * 1 - crosslock, done;
4939 * 2 - normal lock, continue to held_lock[] ops.
4941 static int lock_acquire_crosslock(struct held_lock *hlock)
4944 * CONTEXT 1 CONTEXT 2
4945 * --------- ---------
4947 * X = atomic_inc_return(&cross_gen_id)
4948 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4949 * Y = atomic_read_acquire(&cross_gen_id)
4952 * atomic_read_acquire() is for ordering between A and B,
4953 * IOW, A happens before B, when CONTEXT 2 see Y >= X.
4955 * Pairs with atomic_inc_return() in add_xlock().
4957 hlock->gen_id = (unsigned int)atomic_read_acquire(&cross_gen_id);
4959 if (cross_lock(hlock->instance))
4960 return add_xlock(hlock);
4962 check_add_xhlock(hlock);
4966 static int copy_trace(struct stack_trace *trace)
4968 unsigned long *buf = stack_trace + nr_stack_trace_entries;
4969 unsigned int max_nr = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
4970 unsigned int nr = min(max_nr, trace->nr_entries);
4972 trace->nr_entries = nr;
4973 memcpy(buf, trace->entries, nr * sizeof(trace->entries[0]));
4974 trace->entries = buf;
4975 nr_stack_trace_entries += nr;
4977 if (nr_stack_trace_entries >= MAX_STACK_TRACE_ENTRIES-1) {
4978 if (!debug_locks_off_graph_unlock())
4981 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
4990 static int commit_xhlock(struct cross_lock *xlock, struct hist_lock *xhlock)
4992 unsigned int xid, pid;
4995 xid = xlock_class(xlock) - lock_classes;
4996 chain_key = iterate_chain_key((u64)0, xid);
4997 pid = xhlock_class(xhlock) - lock_classes;
4998 chain_key = iterate_chain_key(chain_key, pid);
5000 if (lookup_chain_cache(chain_key))
5003 if (!add_chain_cache_classes(xid, pid, xhlock->hlock.irq_context,
5007 if (!check_prev_add(current, &xlock->hlock, &xhlock->hlock, 1,
5008 &xhlock->trace, copy_trace))
5014 static void commit_xhlocks(struct cross_lock *xlock)
5016 unsigned int cur = current->xhlock_idx;
5017 unsigned int prev_hist_id = xhlock(cur).hist_id;
5023 if (xlock->nr_acquire) {
5024 for (i = 0; i < MAX_XHLOCKS_NR; i++) {
5025 struct hist_lock *xhlock = &xhlock(cur - i);
5027 if (!xhlock_valid(xhlock))
5030 if (before(xhlock->hlock.gen_id, xlock->hlock.gen_id))
5033 if (!same_context_xhlock(xhlock))
5037 * Filter out the cases where the ring buffer was
5038 * overwritten and the current entry has a bigger
5039 * hist_id than the previous one, which is impossible
5042 if (unlikely(before(prev_hist_id, xhlock->hist_id)))
5045 prev_hist_id = xhlock->hist_id;
5048 * commit_xhlock() returns 0 with graph_lock already
5051 if (!commit_xhlock(xlock, xhlock))
5059 void lock_commit_crosslock(struct lockdep_map *lock)
5061 struct cross_lock *xlock;
5062 unsigned long flags;
5064 if (unlikely(!debug_locks || current->lockdep_recursion))
5067 if (!current->xhlocks)
5071 * Do commit hist_locks with the cross_lock, only in case that
5072 * the cross_lock could depend on acquisitions after that.
5074 * For example, if the cross_lock does not have the 'check' flag
5075 * then we don't need to check dependencies and commit for that.
5076 * Just skip it. In that case, of course, the cross_lock does
5077 * not depend on acquisitions ahead, either.
5079 * WARNING: Don't do that in add_xlock() in advance. When an
5080 * acquisition context is different from the commit context,
5081 * invalid(skipped) cross_lock might be accessed.
5083 if (!depend_after(&((struct lockdep_map_cross *)lock)->xlock.hlock))
5086 raw_local_irq_save(flags);
5088 current->lockdep_recursion = 1;
5089 xlock = &((struct lockdep_map_cross *)lock)->xlock;
5090 commit_xhlocks(xlock);
5091 current->lockdep_recursion = 0;
5092 raw_local_irq_restore(flags);
5094 EXPORT_SYMBOL_GPL(lock_commit_crosslock);
5097 * Return: 0 - failure;
5098 * 1 - crosslock, done;
5099 * 2 - normal lock, continue to held_lock[] ops.
5101 static int lock_release_crosslock(struct lockdep_map *lock)
5103 if (cross_lock(lock)) {
5106 ((struct lockdep_map_cross *)lock)->xlock.nr_acquire--;
5113 static void cross_init(struct lockdep_map *lock, int cross)
5116 ((struct lockdep_map_cross *)lock)->xlock.nr_acquire = 0;
5118 lock->cross = cross;
5121 * Crossrelease assumes that the ring buffer size of xhlocks
5122 * is aligned with power of 2. So force it on build.
5124 BUILD_BUG_ON(MAX_XHLOCKS_NR & (MAX_XHLOCKS_NR - 1));
5127 void lockdep_init_task(struct task_struct *task)
5131 task->xhlock_idx = UINT_MAX;
5134 for (i = 0; i < XHLOCK_CTX_NR; i++) {
5135 task->xhlock_idx_hist[i] = UINT_MAX;
5136 task->hist_id_save[i] = 0;
5139 task->xhlocks = kzalloc(sizeof(struct hist_lock) * MAX_XHLOCKS_NR,
5143 void lockdep_free_task(struct task_struct *task)
5145 if (task->xhlocks) {
5146 void *tmp = task->xhlocks;
5147 /* Diable crossrelease for current */
5148 task->xhlocks = NULL;