1 // SPDX-License-Identifier: GPL-2.0-only
5 * Runtime locking correctness validator
7 * Started by Ingo Molnar:
10 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
12 * this code maps all the lock dependencies as they occur in a live kernel
13 * and will warn about the following classes of locking bugs:
15 * - lock inversion scenarios
16 * - circular lock dependencies
17 * - hardirq/softirq safe/unsafe locking bugs
19 * Bugs are reported even if the current locking scenario does not cause
20 * any deadlock at this point.
22 * I.e. if anytime in the past two locks were taken in a different order,
23 * even if it happened for another task, even if those were different
24 * locks (but of the same class as this lock), this code will detect it.
26 * Thanks to Arjan van de Ven for coming up with the initial idea of
27 * mapping lock dependencies runtime.
29 #define DISABLE_BRANCH_PROFILING
30 #include <linux/mutex.h>
31 #include <linux/sched.h>
32 #include <linux/sched/clock.h>
33 #include <linux/sched/task.h>
34 #include <linux/sched/mm.h>
35 #include <linux/delay.h>
36 #include <linux/module.h>
37 #include <linux/proc_fs.h>
38 #include <linux/seq_file.h>
39 #include <linux/spinlock.h>
40 #include <linux/kallsyms.h>
41 #include <linux/interrupt.h>
42 #include <linux/stacktrace.h>
43 #include <linux/debug_locks.h>
44 #include <linux/irqflags.h>
45 #include <linux/utsname.h>
46 #include <linux/hash.h>
47 #include <linux/ftrace.h>
48 #include <linux/stringify.h>
49 #include <linux/bitmap.h>
50 #include <linux/bitops.h>
51 #include <linux/gfp.h>
52 #include <linux/random.h>
53 #include <linux/jhash.h>
54 #include <linux/nmi.h>
55 #include <linux/rcupdate.h>
56 #include <linux/kprobes.h>
57 #include <linux/lockdep.h>
59 #include <asm/sections.h>
61 #include "lockdep_internals.h"
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/lock.h>
66 #ifdef CONFIG_PROVE_LOCKING
67 int prove_locking = 1;
68 module_param(prove_locking, int, 0644);
70 #define prove_locking 0
73 #ifdef CONFIG_LOCK_STAT
75 module_param(lock_stat, int, 0644);
80 DEFINE_PER_CPU(unsigned int, lockdep_recursion);
81 EXPORT_PER_CPU_SYMBOL_GPL(lockdep_recursion);
83 static __always_inline bool lockdep_enabled(void)
88 if (this_cpu_read(lockdep_recursion))
91 if (current->lockdep_recursion)
98 * lockdep_lock: protects the lockdep graph, the hashes and the
99 * class/list/hash allocators.
101 * This is one of the rare exceptions where it's justified
102 * to use a raw spinlock - we really dont want the spinlock
103 * code to recurse back into the lockdep code...
105 static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
106 static struct task_struct *__owner;
108 static inline void lockdep_lock(void)
110 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
112 __this_cpu_inc(lockdep_recursion);
113 arch_spin_lock(&__lock);
117 static inline void lockdep_unlock(void)
119 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
121 if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current))
125 arch_spin_unlock(&__lock);
126 __this_cpu_dec(lockdep_recursion);
129 static inline bool lockdep_assert_locked(void)
131 return DEBUG_LOCKS_WARN_ON(__owner != current);
134 static struct task_struct *lockdep_selftest_task_struct;
137 static int graph_lock(void)
141 * Make sure that if another CPU detected a bug while
142 * walking the graph we dont change it (while the other
143 * CPU is busy printing out stuff with the graph lock
153 static inline void graph_unlock(void)
159 * Turn lock debugging off and return with 0 if it was off already,
160 * and also release the graph lock:
162 static inline int debug_locks_off_graph_unlock(void)
164 int ret = debug_locks_off();
171 unsigned long nr_list_entries;
172 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
173 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
176 * All data structures here are protected by the global debug_lock.
178 * nr_lock_classes is the number of elements of lock_classes[] that is
181 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
182 #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
183 static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
184 unsigned long nr_lock_classes;
185 unsigned long nr_zapped_classes;
186 unsigned long max_lock_class_idx;
187 struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
188 DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
190 static inline struct lock_class *hlock_class(struct held_lock *hlock)
192 unsigned int class_idx = hlock->class_idx;
194 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
197 if (!test_bit(class_idx, lock_classes_in_use)) {
199 * Someone passed in garbage, we give up.
201 DEBUG_LOCKS_WARN_ON(1);
206 * At this point, if the passed hlock->class_idx is still garbage,
207 * we just have to live with it
209 return lock_classes + class_idx;
212 #ifdef CONFIG_LOCK_STAT
213 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
215 static inline u64 lockstat_clock(void)
217 return local_clock();
220 static int lock_point(unsigned long points[], unsigned long ip)
224 for (i = 0; i < LOCKSTAT_POINTS; i++) {
225 if (points[i] == 0) {
236 static void lock_time_inc(struct lock_time *lt, u64 time)
241 if (time < lt->min || !lt->nr)
248 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
253 if (src->max > dst->max)
256 if (src->min < dst->min || !dst->nr)
259 dst->total += src->total;
263 struct lock_class_stats lock_stats(struct lock_class *class)
265 struct lock_class_stats stats;
268 memset(&stats, 0, sizeof(struct lock_class_stats));
269 for_each_possible_cpu(cpu) {
270 struct lock_class_stats *pcs =
271 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
273 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
274 stats.contention_point[i] += pcs->contention_point[i];
276 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
277 stats.contending_point[i] += pcs->contending_point[i];
279 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
280 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
282 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
283 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
285 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
286 stats.bounces[i] += pcs->bounces[i];
292 void clear_lock_stats(struct lock_class *class)
296 for_each_possible_cpu(cpu) {
297 struct lock_class_stats *cpu_stats =
298 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
300 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
302 memset(class->contention_point, 0, sizeof(class->contention_point));
303 memset(class->contending_point, 0, sizeof(class->contending_point));
306 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
308 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
311 static void lock_release_holdtime(struct held_lock *hlock)
313 struct lock_class_stats *stats;
319 holdtime = lockstat_clock() - hlock->holdtime_stamp;
321 stats = get_lock_stats(hlock_class(hlock));
323 lock_time_inc(&stats->read_holdtime, holdtime);
325 lock_time_inc(&stats->write_holdtime, holdtime);
328 static inline void lock_release_holdtime(struct held_lock *hlock)
334 * We keep a global list of all lock classes. The list is only accessed with
335 * the lockdep spinlock lock held. free_lock_classes is a list with free
336 * elements. These elements are linked together by the lock_entry member in
339 static LIST_HEAD(all_lock_classes);
340 static LIST_HEAD(free_lock_classes);
343 * struct pending_free - information about data structures about to be freed
344 * @zapped: Head of a list with struct lock_class elements.
345 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
346 * are about to be freed.
348 struct pending_free {
349 struct list_head zapped;
350 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
354 * struct delayed_free - data structures used for delayed freeing
356 * A data structure for delayed freeing of data structures that may be
357 * accessed by RCU readers at the time these were freed.
359 * @rcu_head: Used to schedule an RCU callback for freeing data structures.
360 * @index: Index of @pf to which freed data structures are added.
361 * @scheduled: Whether or not an RCU callback has been scheduled.
362 * @pf: Array with information about data structures about to be freed.
364 static struct delayed_free {
365 struct rcu_head rcu_head;
368 struct pending_free pf[2];
372 * The lockdep classes are in a hash-table as well, for fast lookup:
374 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
375 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
376 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
377 #define classhashentry(key) (classhash_table + __classhashfn((key)))
379 static struct hlist_head classhash_table[CLASSHASH_SIZE];
382 * We put the lock dependency chains into a hash-table as well, to cache
385 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
386 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
387 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
388 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
390 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
393 * the id of held_lock
395 static inline u16 hlock_id(struct held_lock *hlock)
397 BUILD_BUG_ON(MAX_LOCKDEP_KEYS_BITS + 2 > 16);
399 return (hlock->class_idx | (hlock->read << MAX_LOCKDEP_KEYS_BITS));
402 static inline unsigned int chain_hlock_class_idx(u16 hlock_id)
404 return hlock_id & (MAX_LOCKDEP_KEYS - 1);
408 * The hash key of the lock dependency chains is a hash itself too:
409 * it's a hash of all locks taken up to that lock, including that lock.
410 * It's a 64-bit hash, because it's important for the keys to be
413 static inline u64 iterate_chain_key(u64 key, u32 idx)
415 u32 k0 = key, k1 = key >> 32;
417 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
419 return k0 | (u64)k1 << 32;
422 void lockdep_init_task(struct task_struct *task)
424 task->lockdep_depth = 0; /* no locks held yet */
425 task->curr_chain_key = INITIAL_CHAIN_KEY;
426 task->lockdep_recursion = 0;
429 static __always_inline void lockdep_recursion_inc(void)
431 __this_cpu_inc(lockdep_recursion);
434 static __always_inline void lockdep_recursion_finish(void)
436 if (WARN_ON_ONCE(__this_cpu_dec_return(lockdep_recursion)))
437 __this_cpu_write(lockdep_recursion, 0);
440 void lockdep_set_selftest_task(struct task_struct *task)
442 lockdep_selftest_task_struct = task;
446 * Debugging switches:
450 #define VERY_VERBOSE 0
453 # define HARDIRQ_VERBOSE 1
454 # define SOFTIRQ_VERBOSE 1
456 # define HARDIRQ_VERBOSE 0
457 # define SOFTIRQ_VERBOSE 0
460 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
462 * Quick filtering for interesting events:
464 static int class_filter(struct lock_class *class)
468 if (class->name_version == 1 &&
469 !strcmp(class->name, "lockname"))
471 if (class->name_version == 1 &&
472 !strcmp(class->name, "&struct->lockfield"))
475 /* Filter everything else. 1 would be to allow everything else */
480 static int verbose(struct lock_class *class)
483 return class_filter(class);
488 static void print_lockdep_off(const char *bug_msg)
490 printk(KERN_DEBUG "%s\n", bug_msg);
491 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
492 #ifdef CONFIG_LOCK_STAT
493 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
497 unsigned long nr_stack_trace_entries;
499 #ifdef CONFIG_PROVE_LOCKING
501 * struct lock_trace - single stack backtrace
502 * @hash_entry: Entry in a stack_trace_hash[] list.
503 * @hash: jhash() of @entries.
504 * @nr_entries: Number of entries in @entries.
505 * @entries: Actual stack backtrace.
508 struct hlist_node hash_entry;
511 unsigned long entries[] __aligned(sizeof(unsigned long));
513 #define LOCK_TRACE_SIZE_IN_LONGS \
514 (sizeof(struct lock_trace) / sizeof(unsigned long))
516 * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock.
518 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
519 static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE];
521 static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2)
523 return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries &&
524 memcmp(t1->entries, t2->entries,
525 t1->nr_entries * sizeof(t1->entries[0])) == 0;
528 static struct lock_trace *save_trace(void)
530 struct lock_trace *trace, *t2;
531 struct hlist_head *hash_head;
535 BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE);
536 BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES);
538 trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries);
539 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries -
540 LOCK_TRACE_SIZE_IN_LONGS;
542 if (max_entries <= 0) {
543 if (!debug_locks_off_graph_unlock())
546 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
551 trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3);
553 hash = jhash(trace->entries, trace->nr_entries *
554 sizeof(trace->entries[0]), 0);
556 hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1));
557 hlist_for_each_entry(t2, hash_head, hash_entry) {
558 if (traces_identical(trace, t2))
561 nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries;
562 hlist_add_head(&trace->hash_entry, hash_head);
567 /* Return the number of stack traces in the stack_trace[] array. */
568 u64 lockdep_stack_trace_count(void)
570 struct lock_trace *trace;
574 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) {
575 hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) {
583 /* Return the number of stack hash chains that have at least one stack trace. */
584 u64 lockdep_stack_hash_count(void)
589 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++)
590 if (!hlist_empty(&stack_trace_hash[i]))
597 unsigned int nr_hardirq_chains;
598 unsigned int nr_softirq_chains;
599 unsigned int nr_process_chains;
600 unsigned int max_lockdep_depth;
602 #ifdef CONFIG_DEBUG_LOCKDEP
604 * Various lockdep statistics:
606 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
609 #ifdef CONFIG_PROVE_LOCKING
614 #define __USAGE(__STATE) \
615 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
616 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
617 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
618 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
620 static const char *usage_str[] =
622 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
623 #include "lockdep_states.h"
625 [LOCK_USED] = "INITIAL USE",
626 [LOCK_USED_READ] = "INITIAL READ USE",
627 /* abused as string storage for verify_lock_unused() */
628 [LOCK_USAGE_STATES] = "IN-NMI",
632 const char *__get_key_name(const struct lockdep_subclass_key *key, char *str)
634 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
637 static inline unsigned long lock_flag(enum lock_usage_bit bit)
642 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
645 * The usage character defaults to '.' (i.e., irqs disabled and not in
646 * irq context), which is the safest usage category.
651 * The order of the following usage checks matters, which will
652 * result in the outcome character as follows:
654 * - '+': irq is enabled and not in irq context
655 * - '-': in irq context and irq is disabled
656 * - '?': in irq context and irq is enabled
658 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
660 if (class->usage_mask & lock_flag(bit))
662 } else if (class->usage_mask & lock_flag(bit))
668 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
672 #define LOCKDEP_STATE(__STATE) \
673 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
674 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
675 #include "lockdep_states.h"
681 static void __print_lock_name(struct lock_class *class)
683 char str[KSYM_NAME_LEN];
688 name = __get_key_name(class->key, str);
689 printk(KERN_CONT "%s", name);
691 printk(KERN_CONT "%s", name);
692 if (class->name_version > 1)
693 printk(KERN_CONT "#%d", class->name_version);
695 printk(KERN_CONT "/%d", class->subclass);
699 static void print_lock_name(struct lock_class *class)
701 char usage[LOCK_USAGE_CHARS];
703 get_usage_chars(class, usage);
705 printk(KERN_CONT " (");
706 __print_lock_name(class);
707 printk(KERN_CONT "){%s}-{%d:%d}", usage,
708 class->wait_type_outer ?: class->wait_type_inner,
709 class->wait_type_inner);
712 static void print_lockdep_cache(struct lockdep_map *lock)
715 char str[KSYM_NAME_LEN];
719 name = __get_key_name(lock->key->subkeys, str);
721 printk(KERN_CONT "%s", name);
724 static void print_lock(struct held_lock *hlock)
727 * We can be called locklessly through debug_show_all_locks() so be
728 * extra careful, the hlock might have been released and cleared.
730 * If this indeed happens, lets pretend it does not hurt to continue
731 * to print the lock unless the hlock class_idx does not point to a
732 * registered class. The rationale here is: since we don't attempt
733 * to distinguish whether we are in this situation, if it just
734 * happened we can't count on class_idx to tell either.
736 struct lock_class *lock = hlock_class(hlock);
739 printk(KERN_CONT "<RELEASED>\n");
743 printk(KERN_CONT "%px", hlock->instance);
744 print_lock_name(lock);
745 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
748 static void lockdep_print_held_locks(struct task_struct *p)
750 int i, depth = READ_ONCE(p->lockdep_depth);
753 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
755 printk("%d lock%s held by %s/%d:\n", depth,
756 depth > 1 ? "s" : "", p->comm, task_pid_nr(p));
758 * It's not reliable to print a task's held locks if it's not sleeping
759 * and it's not the current task.
761 if (p != current && task_is_running(p))
763 for (i = 0; i < depth; i++) {
765 print_lock(p->held_locks + i);
769 static void print_kernel_ident(void)
771 printk("%s %.*s %s\n", init_utsname()->release,
772 (int)strcspn(init_utsname()->version, " "),
773 init_utsname()->version,
777 static int very_verbose(struct lock_class *class)
780 return class_filter(class);
786 * Is this the address of a static object:
790 * Check if an address is part of freed initmem. After initmem is freed,
791 * memory can be allocated from it, and such allocations would then have
792 * addresses within the range [_stext, _end].
794 #ifndef arch_is_kernel_initmem_freed
795 static int arch_is_kernel_initmem_freed(unsigned long addr)
797 if (system_state < SYSTEM_FREEING_INITMEM)
800 return init_section_contains((void *)addr, 1);
804 static int static_obj(const void *obj)
806 unsigned long start = (unsigned long) &_stext,
807 end = (unsigned long) &_end,
808 addr = (unsigned long) obj;
810 if (arch_is_kernel_initmem_freed(addr))
816 if ((addr >= start) && (addr < end))
820 * in-kernel percpu var?
822 if (is_kernel_percpu_address(addr))
826 * module static or percpu var?
828 return is_module_address(addr) || is_module_percpu_address(addr);
833 * To make lock name printouts unique, we calculate a unique
834 * class->name_version generation counter. The caller must hold the graph
837 static int count_matching_names(struct lock_class *new_class)
839 struct lock_class *class;
842 if (!new_class->name)
845 list_for_each_entry(class, &all_lock_classes, lock_entry) {
846 if (new_class->key - new_class->subclass == class->key)
847 return class->name_version;
848 if (class->name && !strcmp(class->name, new_class->name))
849 count = max(count, class->name_version);
855 /* used from NMI context -- must be lockless */
856 static noinstr struct lock_class *
857 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
859 struct lockdep_subclass_key *key;
860 struct hlist_head *hash_head;
861 struct lock_class *class;
863 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
864 instrumentation_begin();
867 "BUG: looking up invalid subclass: %u\n", subclass);
869 "turning off the locking correctness validator.\n");
871 instrumentation_end();
876 * If it is not initialised then it has never been locked,
877 * so it won't be present in the hash table.
879 if (unlikely(!lock->key))
883 * NOTE: the class-key must be unique. For dynamic locks, a static
884 * lock_class_key variable is passed in through the mutex_init()
885 * (or spin_lock_init()) call - which acts as the key. For static
886 * locks we use the lock object itself as the key.
888 BUILD_BUG_ON(sizeof(struct lock_class_key) >
889 sizeof(struct lockdep_map));
891 key = lock->key->subkeys + subclass;
893 hash_head = classhashentry(key);
896 * We do an RCU walk of the hash, see lockdep_free_key_range().
898 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
901 hlist_for_each_entry_rcu_notrace(class, hash_head, hash_entry) {
902 if (class->key == key) {
904 * Huh! same key, different name? Did someone trample
905 * on some memory? We're most confused.
907 WARN_ON_ONCE(class->name != lock->name &&
908 lock->key != &__lockdep_no_validate__);
917 * Static locks do not have their class-keys yet - for them the key is
918 * the lock object itself. If the lock is in the per cpu area, the
919 * canonical address of the lock (per cpu offset removed) is used.
921 static bool assign_lock_key(struct lockdep_map *lock)
923 unsigned long can_addr, addr = (unsigned long)lock;
927 * lockdep_free_key_range() assumes that struct lock_class_key
928 * objects do not overlap. Since we use the address of lock
929 * objects as class key for static objects, check whether the
930 * size of lock_class_key objects does not exceed the size of
931 * the smallest lock object.
933 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
936 if (__is_kernel_percpu_address(addr, &can_addr))
937 lock->key = (void *)can_addr;
938 else if (__is_module_percpu_address(addr, &can_addr))
939 lock->key = (void *)can_addr;
940 else if (static_obj(lock))
941 lock->key = (void *)lock;
943 /* Debug-check: all keys must be persistent! */
945 pr_err("INFO: trying to register non-static key.\n");
946 pr_err("The code is fine but needs lockdep annotation, or maybe\n");
947 pr_err("you didn't initialize this object before use?\n");
948 pr_err("turning off the locking correctness validator.\n");
956 #ifdef CONFIG_DEBUG_LOCKDEP
958 /* Check whether element @e occurs in list @h */
959 static bool in_list(struct list_head *e, struct list_head *h)
963 list_for_each(f, h) {
972 * Check whether entry @e occurs in any of the locks_after or locks_before
975 static bool in_any_class_list(struct list_head *e)
977 struct lock_class *class;
980 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
981 class = &lock_classes[i];
982 if (in_list(e, &class->locks_after) ||
983 in_list(e, &class->locks_before))
989 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
993 list_for_each_entry(e, h, entry) {
994 if (e->links_to != c) {
995 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
997 (unsigned long)(e - list_entries),
998 e->links_to && e->links_to->name ?
999 e->links_to->name : "(?)",
1000 e->class && e->class->name ? e->class->name :
1008 #ifdef CONFIG_PROVE_LOCKING
1009 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
1012 static bool check_lock_chain_key(struct lock_chain *chain)
1014 #ifdef CONFIG_PROVE_LOCKING
1015 u64 chain_key = INITIAL_CHAIN_KEY;
1018 for (i = chain->base; i < chain->base + chain->depth; i++)
1019 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
1021 * The 'unsigned long long' casts avoid that a compiler warning
1022 * is reported when building tools/lib/lockdep.
1024 if (chain->chain_key != chain_key) {
1025 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
1026 (unsigned long long)(chain - lock_chains),
1027 (unsigned long long)chain->chain_key,
1028 (unsigned long long)chain_key);
1035 static bool in_any_zapped_class_list(struct lock_class *class)
1037 struct pending_free *pf;
1040 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
1041 if (in_list(&class->lock_entry, &pf->zapped))
1048 static bool __check_data_structures(void)
1050 struct lock_class *class;
1051 struct lock_chain *chain;
1052 struct hlist_head *head;
1053 struct lock_list *e;
1056 /* Check whether all classes occur in a lock list. */
1057 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1058 class = &lock_classes[i];
1059 if (!in_list(&class->lock_entry, &all_lock_classes) &&
1060 !in_list(&class->lock_entry, &free_lock_classes) &&
1061 !in_any_zapped_class_list(class)) {
1062 printk(KERN_INFO "class %px/%s is not in any class list\n",
1063 class, class->name ? : "(?)");
1068 /* Check whether all classes have valid lock lists. */
1069 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1070 class = &lock_classes[i];
1071 if (!class_lock_list_valid(class, &class->locks_before))
1073 if (!class_lock_list_valid(class, &class->locks_after))
1077 /* Check the chain_key of all lock chains. */
1078 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
1079 head = chainhash_table + i;
1080 hlist_for_each_entry_rcu(chain, head, entry) {
1081 if (!check_lock_chain_key(chain))
1087 * Check whether all list entries that are in use occur in a class
1090 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1091 e = list_entries + i;
1092 if (!in_any_class_list(&e->entry)) {
1093 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
1094 (unsigned int)(e - list_entries),
1095 e->class->name ? : "(?)",
1096 e->links_to->name ? : "(?)");
1102 * Check whether all list entries that are not in use do not occur in
1103 * a class lock list.
1105 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1106 e = list_entries + i;
1107 if (in_any_class_list(&e->entry)) {
1108 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
1109 (unsigned int)(e - list_entries),
1110 e->class && e->class->name ? e->class->name :
1112 e->links_to && e->links_to->name ?
1113 e->links_to->name : "(?)");
1121 int check_consistency = 0;
1122 module_param(check_consistency, int, 0644);
1124 static void check_data_structures(void)
1126 static bool once = false;
1128 if (check_consistency && !once) {
1129 if (!__check_data_structures()) {
1136 #else /* CONFIG_DEBUG_LOCKDEP */
1138 static inline void check_data_structures(void) { }
1140 #endif /* CONFIG_DEBUG_LOCKDEP */
1142 static void init_chain_block_buckets(void);
1145 * Initialize the lock_classes[] array elements, the free_lock_classes list
1146 * and also the delayed_free structure.
1148 static void init_data_structures_once(void)
1150 static bool __read_mostly ds_initialized, rcu_head_initialized;
1153 if (likely(rcu_head_initialized))
1156 if (system_state >= SYSTEM_SCHEDULING) {
1157 init_rcu_head(&delayed_free.rcu_head);
1158 rcu_head_initialized = true;
1164 ds_initialized = true;
1166 INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
1167 INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
1169 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1170 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
1171 INIT_LIST_HEAD(&lock_classes[i].locks_after);
1172 INIT_LIST_HEAD(&lock_classes[i].locks_before);
1174 init_chain_block_buckets();
1177 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
1179 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
1181 return lock_keys_hash + hash;
1184 /* Register a dynamically allocated key. */
1185 void lockdep_register_key(struct lock_class_key *key)
1187 struct hlist_head *hash_head;
1188 struct lock_class_key *k;
1189 unsigned long flags;
1191 if (WARN_ON_ONCE(static_obj(key)))
1193 hash_head = keyhashentry(key);
1195 raw_local_irq_save(flags);
1198 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1199 if (WARN_ON_ONCE(k == key))
1202 hlist_add_head_rcu(&key->hash_entry, hash_head);
1206 raw_local_irq_restore(flags);
1208 EXPORT_SYMBOL_GPL(lockdep_register_key);
1210 /* Check whether a key has been registered as a dynamic key. */
1211 static bool is_dynamic_key(const struct lock_class_key *key)
1213 struct hlist_head *hash_head;
1214 struct lock_class_key *k;
1217 if (WARN_ON_ONCE(static_obj(key)))
1221 * If lock debugging is disabled lock_keys_hash[] may contain
1222 * pointers to memory that has already been freed. Avoid triggering
1223 * a use-after-free in that case by returning early.
1228 hash_head = keyhashentry(key);
1231 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1243 * Register a lock's class in the hash-table, if the class is not present
1244 * yet. Otherwise we look it up. We cache the result in the lock object
1245 * itself, so actual lookup of the hash should be once per lock object.
1247 static struct lock_class *
1248 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1250 struct lockdep_subclass_key *key;
1251 struct hlist_head *hash_head;
1252 struct lock_class *class;
1255 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1257 class = look_up_lock_class(lock, subclass);
1259 goto out_set_class_cache;
1262 if (!assign_lock_key(lock))
1264 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
1268 key = lock->key->subkeys + subclass;
1269 hash_head = classhashentry(key);
1271 if (!graph_lock()) {
1275 * We have to do the hash-walk again, to avoid races
1278 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
1279 if (class->key == key)
1280 goto out_unlock_set;
1283 init_data_structures_once();
1285 /* Allocate a new lock class and add it to the hash. */
1286 class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
1289 if (!debug_locks_off_graph_unlock()) {
1293 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
1298 __set_bit(class - lock_classes, lock_classes_in_use);
1299 debug_atomic_inc(nr_unused_locks);
1301 class->name = lock->name;
1302 class->subclass = subclass;
1303 WARN_ON_ONCE(!list_empty(&class->locks_before));
1304 WARN_ON_ONCE(!list_empty(&class->locks_after));
1305 class->name_version = count_matching_names(class);
1306 class->wait_type_inner = lock->wait_type_inner;
1307 class->wait_type_outer = lock->wait_type_outer;
1308 class->lock_type = lock->lock_type;
1310 * We use RCU's safe list-add method to make
1311 * parallel walking of the hash-list safe:
1313 hlist_add_head_rcu(&class->hash_entry, hash_head);
1315 * Remove the class from the free list and add it to the global list
1318 list_move_tail(&class->lock_entry, &all_lock_classes);
1319 idx = class - lock_classes;
1320 if (idx > max_lock_class_idx)
1321 max_lock_class_idx = idx;
1323 if (verbose(class)) {
1326 printk("\nnew class %px: %s", class->key, class->name);
1327 if (class->name_version > 1)
1328 printk(KERN_CONT "#%d", class->name_version);
1329 printk(KERN_CONT "\n");
1332 if (!graph_lock()) {
1339 out_set_class_cache:
1340 if (!subclass || force)
1341 lock->class_cache[0] = class;
1342 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
1343 lock->class_cache[subclass] = class;
1346 * Hash collision, did we smoke some? We found a class with a matching
1347 * hash but the subclass -- which is hashed in -- didn't match.
1349 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
1355 #ifdef CONFIG_PROVE_LOCKING
1357 * Allocate a lockdep entry. (assumes the graph_lock held, returns
1358 * with NULL on failure)
1360 static struct lock_list *alloc_list_entry(void)
1362 int idx = find_first_zero_bit(list_entries_in_use,
1363 ARRAY_SIZE(list_entries));
1365 if (idx >= ARRAY_SIZE(list_entries)) {
1366 if (!debug_locks_off_graph_unlock())
1369 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
1374 __set_bit(idx, list_entries_in_use);
1375 return list_entries + idx;
1379 * Add a new dependency to the head of the list:
1381 static int add_lock_to_list(struct lock_class *this,
1382 struct lock_class *links_to, struct list_head *head,
1383 unsigned long ip, u16 distance, u8 dep,
1384 const struct lock_trace *trace)
1386 struct lock_list *entry;
1388 * Lock not present yet - get a new dependency struct and
1389 * add it to the list:
1391 entry = alloc_list_entry();
1395 entry->class = this;
1396 entry->links_to = links_to;
1398 entry->distance = distance;
1399 entry->trace = trace;
1401 * Both allocation and removal are done under the graph lock; but
1402 * iteration is under RCU-sched; see look_up_lock_class() and
1403 * lockdep_free_key_range().
1405 list_add_tail_rcu(&entry->entry, head);
1411 * For good efficiency of modular, we use power of 2
1413 #define MAX_CIRCULAR_QUEUE_SIZE (1UL << CONFIG_LOCKDEP_CIRCULAR_QUEUE_BITS)
1414 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
1417 * The circular_queue and helpers are used to implement graph
1418 * breadth-first search (BFS) algorithm, by which we can determine
1419 * whether there is a path from a lock to another. In deadlock checks,
1420 * a path from the next lock to be acquired to a previous held lock
1421 * indicates that adding the <prev> -> <next> lock dependency will
1422 * produce a circle in the graph. Breadth-first search instead of
1423 * depth-first search is used in order to find the shortest (circular)
1426 struct circular_queue {
1427 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
1428 unsigned int front, rear;
1431 static struct circular_queue lock_cq;
1433 unsigned int max_bfs_queue_depth;
1435 static unsigned int lockdep_dependency_gen_id;
1437 static inline void __cq_init(struct circular_queue *cq)
1439 cq->front = cq->rear = 0;
1440 lockdep_dependency_gen_id++;
1443 static inline int __cq_empty(struct circular_queue *cq)
1445 return (cq->front == cq->rear);
1448 static inline int __cq_full(struct circular_queue *cq)
1450 return ((cq->rear + 1) & CQ_MASK) == cq->front;
1453 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
1458 cq->element[cq->rear] = elem;
1459 cq->rear = (cq->rear + 1) & CQ_MASK;
1464 * Dequeue an element from the circular_queue, return a lock_list if
1465 * the queue is not empty, or NULL if otherwise.
1467 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
1469 struct lock_list * lock;
1474 lock = cq->element[cq->front];
1475 cq->front = (cq->front + 1) & CQ_MASK;
1480 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
1482 return (cq->rear - cq->front) & CQ_MASK;
1485 static inline void mark_lock_accessed(struct lock_list *lock)
1487 lock->class->dep_gen_id = lockdep_dependency_gen_id;
1490 static inline void visit_lock_entry(struct lock_list *lock,
1491 struct lock_list *parent)
1493 lock->parent = parent;
1496 static inline unsigned long lock_accessed(struct lock_list *lock)
1498 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
1501 static inline struct lock_list *get_lock_parent(struct lock_list *child)
1503 return child->parent;
1506 static inline int get_lock_depth(struct lock_list *child)
1509 struct lock_list *parent;
1511 while ((parent = get_lock_parent(child))) {
1519 * Return the forward or backward dependency list.
1521 * @lock: the lock_list to get its class's dependency list
1522 * @offset: the offset to struct lock_class to determine whether it is
1523 * locks_after or locks_before
1525 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
1527 void *lock_class = lock->class;
1529 return lock_class + offset;
1532 * Return values of a bfs search:
1534 * BFS_E* indicates an error
1535 * BFS_R* indicates a result (match or not)
1537 * BFS_EINVALIDNODE: Find a invalid node in the graph.
1539 * BFS_EQUEUEFULL: The queue is full while doing the bfs.
1541 * BFS_RMATCH: Find the matched node in the graph, and put that node into
1544 * BFS_RNOMATCH: Haven't found the matched node and keep *@target_entry
1548 BFS_EINVALIDNODE = -2,
1549 BFS_EQUEUEFULL = -1,
1555 * bfs_result < 0 means error
1557 static inline bool bfs_error(enum bfs_result res)
1563 * DEP_*_BIT in lock_list::dep
1565 * For dependency @prev -> @next:
1567 * SR: @prev is shared reader (->read != 0) and @next is recursive reader
1569 * ER: @prev is exclusive locker (->read == 0) and @next is recursive reader
1570 * SN: @prev is shared reader and @next is non-recursive locker (->read != 2)
1571 * EN: @prev is exclusive locker and @next is non-recursive locker
1573 * Note that we define the value of DEP_*_BITs so that:
1574 * bit0 is prev->read == 0
1575 * bit1 is next->read != 2
1577 #define DEP_SR_BIT (0 + (0 << 1)) /* 0 */
1578 #define DEP_ER_BIT (1 + (0 << 1)) /* 1 */
1579 #define DEP_SN_BIT (0 + (1 << 1)) /* 2 */
1580 #define DEP_EN_BIT (1 + (1 << 1)) /* 3 */
1582 #define DEP_SR_MASK (1U << (DEP_SR_BIT))
1583 #define DEP_ER_MASK (1U << (DEP_ER_BIT))
1584 #define DEP_SN_MASK (1U << (DEP_SN_BIT))
1585 #define DEP_EN_MASK (1U << (DEP_EN_BIT))
1587 static inline unsigned int
1588 __calc_dep_bit(struct held_lock *prev, struct held_lock *next)
1590 return (prev->read == 0) + ((next->read != 2) << 1);
1593 static inline u8 calc_dep(struct held_lock *prev, struct held_lock *next)
1595 return 1U << __calc_dep_bit(prev, next);
1599 * calculate the dep_bit for backwards edges. We care about whether @prev is
1600 * shared and whether @next is recursive.
1602 static inline unsigned int
1603 __calc_dep_bitb(struct held_lock *prev, struct held_lock *next)
1605 return (next->read != 2) + ((prev->read == 0) << 1);
1608 static inline u8 calc_depb(struct held_lock *prev, struct held_lock *next)
1610 return 1U << __calc_dep_bitb(prev, next);
1614 * Initialize a lock_list entry @lock belonging to @class as the root for a BFS
1617 static inline void __bfs_init_root(struct lock_list *lock,
1618 struct lock_class *class)
1620 lock->class = class;
1621 lock->parent = NULL;
1626 * Initialize a lock_list entry @lock based on a lock acquisition @hlock as the
1627 * root for a BFS search.
1629 * ->only_xr of the initial lock node is set to @hlock->read == 2, to make sure
1630 * that <prev> -> @hlock and @hlock -> <whatever __bfs() found> is not -(*R)->
1633 static inline void bfs_init_root(struct lock_list *lock,
1634 struct held_lock *hlock)
1636 __bfs_init_root(lock, hlock_class(hlock));
1637 lock->only_xr = (hlock->read == 2);
1641 * Similar to bfs_init_root() but initialize the root for backwards BFS.
1643 * ->only_xr of the initial lock node is set to @hlock->read != 0, to make sure
1644 * that <next> -> @hlock and @hlock -> <whatever backwards BFS found> is not
1645 * -(*S)-> and -(R*)-> (reverse order of -(*R)-> and -(S*)->).
1647 static inline void bfs_init_rootb(struct lock_list *lock,
1648 struct held_lock *hlock)
1650 __bfs_init_root(lock, hlock_class(hlock));
1651 lock->only_xr = (hlock->read != 0);
1654 static inline struct lock_list *__bfs_next(struct lock_list *lock, int offset)
1656 if (!lock || !lock->parent)
1659 return list_next_or_null_rcu(get_dep_list(lock->parent, offset),
1660 &lock->entry, struct lock_list, entry);
1664 * Breadth-First Search to find a strong path in the dependency graph.
1666 * @source_entry: the source of the path we are searching for.
1667 * @data: data used for the second parameter of @match function
1668 * @match: match function for the search
1669 * @target_entry: pointer to the target of a matched path
1670 * @offset: the offset to struct lock_class to determine whether it is
1671 * locks_after or locks_before
1673 * We may have multiple edges (considering different kinds of dependencies,
1674 * e.g. ER and SN) between two nodes in the dependency graph. But
1675 * only the strong dependency path in the graph is relevant to deadlocks. A
1676 * strong dependency path is a dependency path that doesn't have two adjacent
1677 * dependencies as -(*R)-> -(S*)->, please see:
1679 * Documentation/locking/lockdep-design.rst
1681 * for more explanation of the definition of strong dependency paths
1683 * In __bfs(), we only traverse in the strong dependency path:
1685 * In lock_list::only_xr, we record whether the previous dependency only
1686 * has -(*R)-> in the search, and if it does (prev only has -(*R)->), we
1687 * filter out any -(S*)-> in the current dependency and after that, the
1688 * ->only_xr is set according to whether we only have -(*R)-> left.
1690 static enum bfs_result __bfs(struct lock_list *source_entry,
1692 bool (*match)(struct lock_list *entry, void *data),
1693 bool (*skip)(struct lock_list *entry, void *data),
1694 struct lock_list **target_entry,
1697 struct circular_queue *cq = &lock_cq;
1698 struct lock_list *lock = NULL;
1699 struct lock_list *entry;
1700 struct list_head *head;
1701 unsigned int cq_depth;
1704 lockdep_assert_locked();
1707 __cq_enqueue(cq, source_entry);
1709 while ((lock = __bfs_next(lock, offset)) || (lock = __cq_dequeue(cq))) {
1711 return BFS_EINVALIDNODE;
1714 * Step 1: check whether we already finish on this one.
1716 * If we have visited all the dependencies from this @lock to
1717 * others (iow, if we have visited all lock_list entries in
1718 * @lock->class->locks_{after,before}) we skip, otherwise go
1719 * and visit all the dependencies in the list and mark this
1722 if (lock_accessed(lock))
1725 mark_lock_accessed(lock);
1728 * Step 2: check whether prev dependency and this form a strong
1731 if (lock->parent) { /* Parent exists, check prev dependency */
1733 bool prev_only_xr = lock->parent->only_xr;
1736 * Mask out all -(S*)-> if we only have *R in previous
1737 * step, because -(*R)-> -(S*)-> don't make up a strong
1741 dep &= ~(DEP_SR_MASK | DEP_SN_MASK);
1743 /* If nothing left, we skip */
1747 /* If there are only -(*R)-> left, set that for the next step */
1748 lock->only_xr = !(dep & (DEP_SN_MASK | DEP_EN_MASK));
1752 * Step 3: we haven't visited this and there is a strong
1753 * dependency path to this, so check with @match.
1754 * If @skip is provide and returns true, we skip this
1755 * lock (and any path this lock is in).
1757 if (skip && skip(lock, data))
1760 if (match(lock, data)) {
1761 *target_entry = lock;
1766 * Step 4: if not match, expand the path by adding the
1767 * forward or backwards dependencies in the search
1771 head = get_dep_list(lock, offset);
1772 list_for_each_entry_rcu(entry, head, entry) {
1773 visit_lock_entry(entry, lock);
1776 * Note we only enqueue the first of the list into the
1777 * queue, because we can always find a sibling
1778 * dependency from one (see __bfs_next()), as a result
1779 * the space of queue is saved.
1786 if (__cq_enqueue(cq, entry))
1787 return BFS_EQUEUEFULL;
1789 cq_depth = __cq_get_elem_count(cq);
1790 if (max_bfs_queue_depth < cq_depth)
1791 max_bfs_queue_depth = cq_depth;
1795 return BFS_RNOMATCH;
1798 static inline enum bfs_result
1799 __bfs_forwards(struct lock_list *src_entry,
1801 bool (*match)(struct lock_list *entry, void *data),
1802 bool (*skip)(struct lock_list *entry, void *data),
1803 struct lock_list **target_entry)
1805 return __bfs(src_entry, data, match, skip, target_entry,
1806 offsetof(struct lock_class, locks_after));
1810 static inline enum bfs_result
1811 __bfs_backwards(struct lock_list *src_entry,
1813 bool (*match)(struct lock_list *entry, void *data),
1814 bool (*skip)(struct lock_list *entry, void *data),
1815 struct lock_list **target_entry)
1817 return __bfs(src_entry, data, match, skip, target_entry,
1818 offsetof(struct lock_class, locks_before));
1822 static void print_lock_trace(const struct lock_trace *trace,
1823 unsigned int spaces)
1825 stack_trace_print(trace->entries, trace->nr_entries, spaces);
1829 * Print a dependency chain entry (this is only done when a deadlock
1830 * has been detected):
1832 static noinline void
1833 print_circular_bug_entry(struct lock_list *target, int depth)
1835 if (debug_locks_silent)
1837 printk("\n-> #%u", depth);
1838 print_lock_name(target->class);
1839 printk(KERN_CONT ":\n");
1840 print_lock_trace(target->trace, 6);
1844 print_circular_lock_scenario(struct held_lock *src,
1845 struct held_lock *tgt,
1846 struct lock_list *prt)
1848 struct lock_class *source = hlock_class(src);
1849 struct lock_class *target = hlock_class(tgt);
1850 struct lock_class *parent = prt->class;
1853 * A direct locking problem where unsafe_class lock is taken
1854 * directly by safe_class lock, then all we need to show
1855 * is the deadlock scenario, as it is obvious that the
1856 * unsafe lock is taken under the safe lock.
1858 * But if there is a chain instead, where the safe lock takes
1859 * an intermediate lock (middle_class) where this lock is
1860 * not the same as the safe lock, then the lock chain is
1861 * used to describe the problem. Otherwise we would need
1862 * to show a different CPU case for each link in the chain
1863 * from the safe_class lock to the unsafe_class lock.
1865 if (parent != source) {
1866 printk("Chain exists of:\n ");
1867 __print_lock_name(source);
1868 printk(KERN_CONT " --> ");
1869 __print_lock_name(parent);
1870 printk(KERN_CONT " --> ");
1871 __print_lock_name(target);
1872 printk(KERN_CONT "\n\n");
1875 printk(" Possible unsafe locking scenario:\n\n");
1876 printk(" CPU0 CPU1\n");
1877 printk(" ---- ----\n");
1879 __print_lock_name(target);
1880 printk(KERN_CONT ");\n");
1882 __print_lock_name(parent);
1883 printk(KERN_CONT ");\n");
1885 __print_lock_name(target);
1886 printk(KERN_CONT ");\n");
1888 __print_lock_name(source);
1889 printk(KERN_CONT ");\n");
1890 printk("\n *** DEADLOCK ***\n\n");
1894 * When a circular dependency is detected, print the
1897 static noinline void
1898 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1899 struct held_lock *check_src,
1900 struct held_lock *check_tgt)
1902 struct task_struct *curr = current;
1904 if (debug_locks_silent)
1908 pr_warn("======================================================\n");
1909 pr_warn("WARNING: possible circular locking dependency detected\n");
1910 print_kernel_ident();
1911 pr_warn("------------------------------------------------------\n");
1912 pr_warn("%s/%d is trying to acquire lock:\n",
1913 curr->comm, task_pid_nr(curr));
1914 print_lock(check_src);
1916 pr_warn("\nbut task is already holding lock:\n");
1918 print_lock(check_tgt);
1919 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1920 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1922 print_circular_bug_entry(entry, depth);
1926 * We are about to add A -> B into the dependency graph, and in __bfs() a
1927 * strong dependency path A -> .. -> B is found: hlock_class equals
1930 * If A -> .. -> B can replace A -> B in any __bfs() search (means the former
1931 * is _stronger_ than or equal to the latter), we consider A -> B as redundant.
1932 * For example if A -> .. -> B is -(EN)-> (i.e. A -(E*)-> .. -(*N)-> B), and A
1933 * -> B is -(ER)-> or -(EN)->, then we don't need to add A -> B into the
1934 * dependency graph, as any strong path ..-> A -> B ->.. we can get with
1935 * having dependency A -> B, we could already get a equivalent path ..-> A ->
1936 * .. -> B -> .. with A -> .. -> B. Therefore A -> B is redundant.
1938 * We need to make sure both the start and the end of A -> .. -> B is not
1939 * weaker than A -> B. For the start part, please see the comment in
1940 * check_redundant(). For the end part, we need:
1944 * a) A -> B is -(*R)-> (everything is not weaker than that)
1948 * b) A -> .. -> B is -(*N)-> (nothing is stronger than this)
1951 static inline bool hlock_equal(struct lock_list *entry, void *data)
1953 struct held_lock *hlock = (struct held_lock *)data;
1955 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
1956 (hlock->read == 2 || /* A -> B is -(*R)-> */
1957 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
1961 * We are about to add B -> A into the dependency graph, and in __bfs() a
1962 * strong dependency path A -> .. -> B is found: hlock_class equals
1965 * We will have a deadlock case (conflict) if A -> .. -> B -> A is a strong
1966 * dependency cycle, that means:
1970 * a) B -> A is -(E*)->
1974 * b) A -> .. -> B is -(*N)-> (i.e. A -> .. -(*N)-> B)
1976 * as then we don't have -(*R)-> -(S*)-> in the cycle.
1978 static inline bool hlock_conflict(struct lock_list *entry, void *data)
1980 struct held_lock *hlock = (struct held_lock *)data;
1982 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
1983 (hlock->read == 0 || /* B -> A is -(E*)-> */
1984 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
1987 static noinline void print_circular_bug(struct lock_list *this,
1988 struct lock_list *target,
1989 struct held_lock *check_src,
1990 struct held_lock *check_tgt)
1992 struct task_struct *curr = current;
1993 struct lock_list *parent;
1994 struct lock_list *first_parent;
1997 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2000 this->trace = save_trace();
2004 depth = get_lock_depth(target);
2006 print_circular_bug_header(target, depth, check_src, check_tgt);
2008 parent = get_lock_parent(target);
2009 first_parent = parent;
2012 print_circular_bug_entry(parent, --depth);
2013 parent = get_lock_parent(parent);
2016 printk("\nother info that might help us debug this:\n\n");
2017 print_circular_lock_scenario(check_src, check_tgt,
2020 lockdep_print_held_locks(curr);
2022 printk("\nstack backtrace:\n");
2026 static noinline void print_bfs_bug(int ret)
2028 if (!debug_locks_off_graph_unlock())
2032 * Breadth-first-search failed, graph got corrupted?
2034 WARN(1, "lockdep bfs error:%d\n", ret);
2037 static bool noop_count(struct lock_list *entry, void *data)
2039 (*(unsigned long *)data)++;
2043 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
2045 unsigned long count = 0;
2046 struct lock_list *target_entry;
2048 __bfs_forwards(this, (void *)&count, noop_count, NULL, &target_entry);
2052 unsigned long lockdep_count_forward_deps(struct lock_class *class)
2054 unsigned long ret, flags;
2055 struct lock_list this;
2057 __bfs_init_root(&this, class);
2059 raw_local_irq_save(flags);
2061 ret = __lockdep_count_forward_deps(&this);
2063 raw_local_irq_restore(flags);
2068 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
2070 unsigned long count = 0;
2071 struct lock_list *target_entry;
2073 __bfs_backwards(this, (void *)&count, noop_count, NULL, &target_entry);
2078 unsigned long lockdep_count_backward_deps(struct lock_class *class)
2080 unsigned long ret, flags;
2081 struct lock_list this;
2083 __bfs_init_root(&this, class);
2085 raw_local_irq_save(flags);
2087 ret = __lockdep_count_backward_deps(&this);
2089 raw_local_irq_restore(flags);
2095 * Check that the dependency graph starting at <src> can lead to
2098 static noinline enum bfs_result
2099 check_path(struct held_lock *target, struct lock_list *src_entry,
2100 bool (*match)(struct lock_list *entry, void *data),
2101 bool (*skip)(struct lock_list *entry, void *data),
2102 struct lock_list **target_entry)
2104 enum bfs_result ret;
2106 ret = __bfs_forwards(src_entry, target, match, skip, target_entry);
2108 if (unlikely(bfs_error(ret)))
2115 * Prove that the dependency graph starting at <src> can not
2116 * lead to <target>. If it can, there is a circle when adding
2117 * <target> -> <src> dependency.
2119 * Print an error and return BFS_RMATCH if it does.
2121 static noinline enum bfs_result
2122 check_noncircular(struct held_lock *src, struct held_lock *target,
2123 struct lock_trace **const trace)
2125 enum bfs_result ret;
2126 struct lock_list *target_entry;
2127 struct lock_list src_entry;
2129 bfs_init_root(&src_entry, src);
2131 debug_atomic_inc(nr_cyclic_checks);
2133 ret = check_path(target, &src_entry, hlock_conflict, NULL, &target_entry);
2135 if (unlikely(ret == BFS_RMATCH)) {
2138 * If save_trace fails here, the printing might
2139 * trigger a WARN but because of the !nr_entries it
2140 * should not do bad things.
2142 *trace = save_trace();
2145 print_circular_bug(&src_entry, target_entry, src, target);
2151 #ifdef CONFIG_TRACE_IRQFLAGS
2154 * Forwards and backwards subgraph searching, for the purposes of
2155 * proving that two subgraphs can be connected by a new dependency
2156 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
2158 * A irq safe->unsafe deadlock happens with the following conditions:
2160 * 1) We have a strong dependency path A -> ... -> B
2162 * 2) and we have ENABLED_IRQ usage of B and USED_IN_IRQ usage of A, therefore
2163 * irq can create a new dependency B -> A (consider the case that a holder
2164 * of B gets interrupted by an irq whose handler will try to acquire A).
2166 * 3) the dependency circle A -> ... -> B -> A we get from 1) and 2) is a
2169 * For the usage bits of B:
2170 * a) if A -> B is -(*N)->, then B -> A could be any type, so any
2171 * ENABLED_IRQ usage suffices.
2172 * b) if A -> B is -(*R)->, then B -> A must be -(E*)->, so only
2173 * ENABLED_IRQ_*_READ usage suffices.
2175 * For the usage bits of A:
2176 * c) if A -> B is -(E*)->, then B -> A could be any type, so any
2177 * USED_IN_IRQ usage suffices.
2178 * d) if A -> B is -(S*)->, then B -> A must be -(*N)->, so only
2179 * USED_IN_IRQ_*_READ usage suffices.
2183 * There is a strong dependency path in the dependency graph: A -> B, and now
2184 * we need to decide which usage bit of A should be accumulated to detect
2185 * safe->unsafe bugs.
2187 * Note that usage_accumulate() is used in backwards search, so ->only_xr
2188 * stands for whether A -> B only has -(S*)-> (in this case ->only_xr is true).
2190 * As above, if only_xr is false, which means A -> B has -(E*)-> dependency
2191 * path, any usage of A should be considered. Otherwise, we should only
2192 * consider _READ usage.
2194 static inline bool usage_accumulate(struct lock_list *entry, void *mask)
2196 if (!entry->only_xr)
2197 *(unsigned long *)mask |= entry->class->usage_mask;
2198 else /* Mask out _READ usage bits */
2199 *(unsigned long *)mask |= (entry->class->usage_mask & LOCKF_IRQ);
2205 * There is a strong dependency path in the dependency graph: A -> B, and now
2206 * we need to decide which usage bit of B conflicts with the usage bits of A,
2207 * i.e. which usage bit of B may introduce safe->unsafe deadlocks.
2209 * As above, if only_xr is false, which means A -> B has -(*N)-> dependency
2210 * path, any usage of B should be considered. Otherwise, we should only
2211 * consider _READ usage.
2213 static inline bool usage_match(struct lock_list *entry, void *mask)
2215 if (!entry->only_xr)
2216 return !!(entry->class->usage_mask & *(unsigned long *)mask);
2217 else /* Mask out _READ usage bits */
2218 return !!((entry->class->usage_mask & LOCKF_IRQ) & *(unsigned long *)mask);
2221 static inline bool usage_skip(struct lock_list *entry, void *mask)
2224 * Skip local_lock() for irq inversion detection.
2226 * For !RT, local_lock() is not a real lock, so it won't carry any
2229 * For RT, an irq inversion happens when we have lock A and B, and on
2230 * some CPU we can have:
2236 * where lock(B) cannot sleep, and we have a dependency B -> ... -> A.
2238 * Now we prove local_lock() cannot exist in that dependency. First we
2239 * have the observation for any lock chain L1 -> ... -> Ln, for any
2240 * 1 <= i <= n, Li.inner_wait_type <= L1.inner_wait_type, otherwise
2241 * wait context check will complain. And since B is not a sleep lock,
2242 * therefore B.inner_wait_type >= 2, and since the inner_wait_type of
2243 * local_lock() is 3, which is greater than 2, therefore there is no
2244 * way the local_lock() exists in the dependency B -> ... -> A.
2246 * As a result, we will skip local_lock(), when we search for irq
2249 if (entry->class->lock_type == LD_LOCK_PERCPU) {
2250 if (DEBUG_LOCKS_WARN_ON(entry->class->wait_type_inner < LD_WAIT_CONFIG))
2260 * Find a node in the forwards-direction dependency sub-graph starting
2261 * at @root->class that matches @bit.
2263 * Return BFS_MATCH if such a node exists in the subgraph, and put that node
2264 * into *@target_entry.
2266 static enum bfs_result
2267 find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
2268 struct lock_list **target_entry)
2270 enum bfs_result result;
2272 debug_atomic_inc(nr_find_usage_forwards_checks);
2274 result = __bfs_forwards(root, &usage_mask, usage_match, usage_skip, target_entry);
2280 * Find a node in the backwards-direction dependency sub-graph starting
2281 * at @root->class that matches @bit.
2283 static enum bfs_result
2284 find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
2285 struct lock_list **target_entry)
2287 enum bfs_result result;
2289 debug_atomic_inc(nr_find_usage_backwards_checks);
2291 result = __bfs_backwards(root, &usage_mask, usage_match, usage_skip, target_entry);
2296 static void print_lock_class_header(struct lock_class *class, int depth)
2300 printk("%*s->", depth, "");
2301 print_lock_name(class);
2302 #ifdef CONFIG_DEBUG_LOCKDEP
2303 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
2305 printk(KERN_CONT " {\n");
2307 for (bit = 0; bit < LOCK_TRACE_STATES; bit++) {
2308 if (class->usage_mask & (1 << bit)) {
2311 len += printk("%*s %s", depth, "", usage_str[bit]);
2312 len += printk(KERN_CONT " at:\n");
2313 print_lock_trace(class->usage_traces[bit], len);
2316 printk("%*s }\n", depth, "");
2318 printk("%*s ... key at: [<%px>] %pS\n",
2319 depth, "", class->key, class->key);
2323 * Dependency path printing:
2325 * After BFS we get a lock dependency path (linked via ->parent of lock_list),
2326 * printing out each lock in the dependency path will help on understanding how
2327 * the deadlock could happen. Here are some details about dependency path
2330 * 1) A lock_list can be either forwards or backwards for a lock dependency,
2331 * for a lock dependency A -> B, there are two lock_lists:
2333 * a) lock_list in the ->locks_after list of A, whose ->class is B and
2334 * ->links_to is A. In this case, we can say the lock_list is
2335 * "A -> B" (forwards case).
2337 * b) lock_list in the ->locks_before list of B, whose ->class is A
2338 * and ->links_to is B. In this case, we can say the lock_list is
2339 * "B <- A" (bacwards case).
2341 * The ->trace of both a) and b) point to the call trace where B was
2342 * acquired with A held.
2344 * 2) A "helper" lock_list is introduced during BFS, this lock_list doesn't
2345 * represent a certain lock dependency, it only provides an initial entry
2346 * for BFS. For example, BFS may introduce a "helper" lock_list whose
2347 * ->class is A, as a result BFS will search all dependencies starting with
2348 * A, e.g. A -> B or A -> C.
2350 * The notation of a forwards helper lock_list is like "-> A", which means
2351 * we should search the forwards dependencies starting with "A", e.g A -> B
2354 * The notation of a bacwards helper lock_list is like "<- B", which means
2355 * we should search the backwards dependencies ending with "B", e.g.
2360 * printk the shortest lock dependencies from @root to @leaf in reverse order.
2362 * We have a lock dependency path as follow:
2368 * | lock_list | <--------- | lock_list | ... | lock_list | <--------- | lock_list |
2369 * | -> L1 | | L1 -> L2 | ... |Ln-2 -> Ln-1| | Ln-1 -> Ln|
2371 * , so it's natural that we start from @leaf and print every ->class and
2372 * ->trace until we reach the @root.
2375 print_shortest_lock_dependencies(struct lock_list *leaf,
2376 struct lock_list *root)
2378 struct lock_list *entry = leaf;
2381 /*compute depth from generated tree by BFS*/
2382 depth = get_lock_depth(leaf);
2385 print_lock_class_header(entry->class, depth);
2386 printk("%*s ... acquired at:\n", depth, "");
2387 print_lock_trace(entry->trace, 2);
2390 if (depth == 0 && (entry != root)) {
2391 printk("lockdep:%s bad path found in chain graph\n", __func__);
2395 entry = get_lock_parent(entry);
2397 } while (entry && (depth >= 0));
2401 * printk the shortest lock dependencies from @leaf to @root.
2403 * We have a lock dependency path (from a backwards search) as follow:
2409 * | lock_list | ---------> | lock_list | ... | lock_list | ---------> | lock_list |
2410 * | L2 <- L1 | | L3 <- L2 | ... | Ln <- Ln-1 | | <- Ln |
2412 * , so when we iterate from @leaf to @root, we actually print the lock
2413 * dependency path L1 -> L2 -> .. -> Ln in the non-reverse order.
2415 * Another thing to notice here is that ->class of L2 <- L1 is L1, while the
2416 * ->trace of L2 <- L1 is the call trace of L2, in fact we don't have the call
2417 * trace of L1 in the dependency path, which is alright, because most of the
2418 * time we can figure out where L1 is held from the call trace of L2.
2421 print_shortest_lock_dependencies_backwards(struct lock_list *leaf,
2422 struct lock_list *root)
2424 struct lock_list *entry = leaf;
2425 const struct lock_trace *trace = NULL;
2428 /*compute depth from generated tree by BFS*/
2429 depth = get_lock_depth(leaf);
2432 print_lock_class_header(entry->class, depth);
2434 printk("%*s ... acquired at:\n", depth, "");
2435 print_lock_trace(trace, 2);
2440 * Record the pointer to the trace for the next lock_list
2441 * entry, see the comments for the function.
2443 trace = entry->trace;
2445 if (depth == 0 && (entry != root)) {
2446 printk("lockdep:%s bad path found in chain graph\n", __func__);
2450 entry = get_lock_parent(entry);
2452 } while (entry && (depth >= 0));
2456 print_irq_lock_scenario(struct lock_list *safe_entry,
2457 struct lock_list *unsafe_entry,
2458 struct lock_class *prev_class,
2459 struct lock_class *next_class)
2461 struct lock_class *safe_class = safe_entry->class;
2462 struct lock_class *unsafe_class = unsafe_entry->class;
2463 struct lock_class *middle_class = prev_class;
2465 if (middle_class == safe_class)
2466 middle_class = next_class;
2469 * A direct locking problem where unsafe_class lock is taken
2470 * directly by safe_class lock, then all we need to show
2471 * is the deadlock scenario, as it is obvious that the
2472 * unsafe lock is taken under the safe lock.
2474 * But if there is a chain instead, where the safe lock takes
2475 * an intermediate lock (middle_class) where this lock is
2476 * not the same as the safe lock, then the lock chain is
2477 * used to describe the problem. Otherwise we would need
2478 * to show a different CPU case for each link in the chain
2479 * from the safe_class lock to the unsafe_class lock.
2481 if (middle_class != unsafe_class) {
2482 printk("Chain exists of:\n ");
2483 __print_lock_name(safe_class);
2484 printk(KERN_CONT " --> ");
2485 __print_lock_name(middle_class);
2486 printk(KERN_CONT " --> ");
2487 __print_lock_name(unsafe_class);
2488 printk(KERN_CONT "\n\n");
2491 printk(" Possible interrupt unsafe locking scenario:\n\n");
2492 printk(" CPU0 CPU1\n");
2493 printk(" ---- ----\n");
2495 __print_lock_name(unsafe_class);
2496 printk(KERN_CONT ");\n");
2497 printk(" local_irq_disable();\n");
2499 __print_lock_name(safe_class);
2500 printk(KERN_CONT ");\n");
2502 __print_lock_name(middle_class);
2503 printk(KERN_CONT ");\n");
2504 printk(" <Interrupt>\n");
2506 __print_lock_name(safe_class);
2507 printk(KERN_CONT ");\n");
2508 printk("\n *** DEADLOCK ***\n\n");
2512 print_bad_irq_dependency(struct task_struct *curr,
2513 struct lock_list *prev_root,
2514 struct lock_list *next_root,
2515 struct lock_list *backwards_entry,
2516 struct lock_list *forwards_entry,
2517 struct held_lock *prev,
2518 struct held_lock *next,
2519 enum lock_usage_bit bit1,
2520 enum lock_usage_bit bit2,
2521 const char *irqclass)
2523 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2527 pr_warn("=====================================================\n");
2528 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
2529 irqclass, irqclass);
2530 print_kernel_ident();
2531 pr_warn("-----------------------------------------------------\n");
2532 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
2533 curr->comm, task_pid_nr(curr),
2534 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
2535 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
2536 lockdep_hardirqs_enabled(),
2537 curr->softirqs_enabled);
2540 pr_warn("\nand this task is already holding:\n");
2542 pr_warn("which would create a new lock dependency:\n");
2543 print_lock_name(hlock_class(prev));
2545 print_lock_name(hlock_class(next));
2548 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
2550 print_lock_name(backwards_entry->class);
2551 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
2553 print_lock_trace(backwards_entry->class->usage_traces[bit1], 1);
2555 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
2556 print_lock_name(forwards_entry->class);
2557 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
2560 print_lock_trace(forwards_entry->class->usage_traces[bit2], 1);
2562 pr_warn("\nother info that might help us debug this:\n\n");
2563 print_irq_lock_scenario(backwards_entry, forwards_entry,
2564 hlock_class(prev), hlock_class(next));
2566 lockdep_print_held_locks(curr);
2568 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
2569 print_shortest_lock_dependencies_backwards(backwards_entry, prev_root);
2571 pr_warn("\nthe dependencies between the lock to be acquired");
2572 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
2573 next_root->trace = save_trace();
2574 if (!next_root->trace)
2576 print_shortest_lock_dependencies(forwards_entry, next_root);
2578 pr_warn("\nstack backtrace:\n");
2582 static const char *state_names[] = {
2583 #define LOCKDEP_STATE(__STATE) \
2584 __stringify(__STATE),
2585 #include "lockdep_states.h"
2586 #undef LOCKDEP_STATE
2589 static const char *state_rnames[] = {
2590 #define LOCKDEP_STATE(__STATE) \
2591 __stringify(__STATE)"-READ",
2592 #include "lockdep_states.h"
2593 #undef LOCKDEP_STATE
2596 static inline const char *state_name(enum lock_usage_bit bit)
2598 if (bit & LOCK_USAGE_READ_MASK)
2599 return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
2601 return state_names[bit >> LOCK_USAGE_DIR_MASK];
2605 * The bit number is encoded like:
2607 * bit0: 0 exclusive, 1 read lock
2608 * bit1: 0 used in irq, 1 irq enabled
2611 static int exclusive_bit(int new_bit)
2613 int state = new_bit & LOCK_USAGE_STATE_MASK;
2614 int dir = new_bit & LOCK_USAGE_DIR_MASK;
2617 * keep state, bit flip the direction and strip read.
2619 return state | (dir ^ LOCK_USAGE_DIR_MASK);
2623 * Observe that when given a bitmask where each bitnr is encoded as above, a
2624 * right shift of the mask transforms the individual bitnrs as -1 and
2625 * conversely, a left shift transforms into +1 for the individual bitnrs.
2627 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
2628 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
2629 * instead by subtracting the bit number by 2, or shifting the mask right by 2.
2631 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
2633 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
2634 * all bits set) and recompose with bitnr1 flipped.
2636 static unsigned long invert_dir_mask(unsigned long mask)
2638 unsigned long excl = 0;
2641 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
2642 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
2648 * Note that a LOCK_ENABLED_IRQ_*_READ usage and a LOCK_USED_IN_IRQ_*_READ
2649 * usage may cause deadlock too, for example:
2653 * write_lock(l1); <irq enabled>
2659 * , in above case, l1 will be marked as LOCK_USED_IN_IRQ_HARDIRQ_READ and l2
2660 * will marked as LOCK_ENABLE_IRQ_HARDIRQ_READ, and this is a possible
2663 * In fact, all of the following cases may cause deadlocks:
2665 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*
2666 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*
2667 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*_READ
2668 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*_READ
2670 * As a result, to calculate the "exclusive mask", first we invert the
2671 * direction (USED_IN/ENABLED) of the original mask, and 1) for all bits with
2672 * bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*). 2) for all
2673 * bits with bitnr0 cleared (LOCK_*_READ), add those with bitnr0 set (LOCK_*).
2675 static unsigned long exclusive_mask(unsigned long mask)
2677 unsigned long excl = invert_dir_mask(mask);
2679 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2680 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2686 * Retrieve the _possible_ original mask to which @mask is
2687 * exclusive. Ie: this is the opposite of exclusive_mask().
2688 * Note that 2 possible original bits can match an exclusive
2689 * bit: one has LOCK_USAGE_READ_MASK set, the other has it
2690 * cleared. So both are returned for each exclusive bit.
2692 static unsigned long original_mask(unsigned long mask)
2694 unsigned long excl = invert_dir_mask(mask);
2696 /* Include read in existing usages */
2697 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2698 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2704 * Find the first pair of bit match between an original
2705 * usage mask and an exclusive usage mask.
2707 static int find_exclusive_match(unsigned long mask,
2708 unsigned long excl_mask,
2709 enum lock_usage_bit *bitp,
2710 enum lock_usage_bit *excl_bitp)
2712 int bit, excl, excl_read;
2714 for_each_set_bit(bit, &mask, LOCK_USED) {
2716 * exclusive_bit() strips the read bit, however,
2717 * LOCK_ENABLED_IRQ_*_READ may cause deadlocks too, so we need
2718 * to search excl | LOCK_USAGE_READ_MASK as well.
2720 excl = exclusive_bit(bit);
2721 excl_read = excl | LOCK_USAGE_READ_MASK;
2722 if (excl_mask & lock_flag(excl)) {
2726 } else if (excl_mask & lock_flag(excl_read)) {
2728 *excl_bitp = excl_read;
2736 * Prove that the new dependency does not connect a hardirq-safe(-read)
2737 * lock with a hardirq-unsafe lock - to achieve this we search
2738 * the backwards-subgraph starting at <prev>, and the
2739 * forwards-subgraph starting at <next>:
2741 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
2742 struct held_lock *next)
2744 unsigned long usage_mask = 0, forward_mask, backward_mask;
2745 enum lock_usage_bit forward_bit = 0, backward_bit = 0;
2746 struct lock_list *target_entry1;
2747 struct lock_list *target_entry;
2748 struct lock_list this, that;
2749 enum bfs_result ret;
2752 * Step 1: gather all hard/soft IRQs usages backward in an
2753 * accumulated usage mask.
2755 bfs_init_rootb(&this, prev);
2757 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, usage_skip, NULL);
2758 if (bfs_error(ret)) {
2763 usage_mask &= LOCKF_USED_IN_IRQ_ALL;
2768 * Step 2: find exclusive uses forward that match the previous
2769 * backward accumulated mask.
2771 forward_mask = exclusive_mask(usage_mask);
2773 bfs_init_root(&that, next);
2775 ret = find_usage_forwards(&that, forward_mask, &target_entry1);
2776 if (bfs_error(ret)) {
2780 if (ret == BFS_RNOMATCH)
2784 * Step 3: we found a bad match! Now retrieve a lock from the backward
2785 * list whose usage mask matches the exclusive usage mask from the
2786 * lock found on the forward list.
2788 * Note, we should only keep the LOCKF_ENABLED_IRQ_ALL bits, considering
2791 * When trying to add A -> B to the graph, we find that there is a
2792 * hardirq-safe L, that L -> ... -> A, and another hardirq-unsafe M,
2793 * that B -> ... -> M. However M is **softirq-safe**, if we use exact
2794 * invert bits of M's usage_mask, we will find another lock N that is
2795 * **softirq-unsafe** and N -> ... -> A, however N -> .. -> M will not
2796 * cause a inversion deadlock.
2798 backward_mask = original_mask(target_entry1->class->usage_mask & LOCKF_ENABLED_IRQ_ALL);
2800 ret = find_usage_backwards(&this, backward_mask, &target_entry);
2801 if (bfs_error(ret)) {
2805 if (DEBUG_LOCKS_WARN_ON(ret == BFS_RNOMATCH))
2809 * Step 4: narrow down to a pair of incompatible usage bits
2812 ret = find_exclusive_match(target_entry->class->usage_mask,
2813 target_entry1->class->usage_mask,
2814 &backward_bit, &forward_bit);
2815 if (DEBUG_LOCKS_WARN_ON(ret == -1))
2818 print_bad_irq_dependency(curr, &this, &that,
2819 target_entry, target_entry1,
2821 backward_bit, forward_bit,
2822 state_name(backward_bit));
2829 static inline int check_irq_usage(struct task_struct *curr,
2830 struct held_lock *prev, struct held_lock *next)
2835 static inline bool usage_skip(struct lock_list *entry, void *mask)
2840 #endif /* CONFIG_TRACE_IRQFLAGS */
2842 #ifdef CONFIG_LOCKDEP_SMALL
2844 * Check that the dependency graph starting at <src> can lead to
2845 * <target> or not. If it can, <src> -> <target> dependency is already
2848 * Return BFS_RMATCH if it does, or BFS_RNOMATCH if it does not, return BFS_E* if
2849 * any error appears in the bfs search.
2851 static noinline enum bfs_result
2852 check_redundant(struct held_lock *src, struct held_lock *target)
2854 enum bfs_result ret;
2855 struct lock_list *target_entry;
2856 struct lock_list src_entry;
2858 bfs_init_root(&src_entry, src);
2860 * Special setup for check_redundant().
2862 * To report redundant, we need to find a strong dependency path that
2863 * is equal to or stronger than <src> -> <target>. So if <src> is E,
2864 * we need to let __bfs() only search for a path starting at a -(E*)->,
2865 * we achieve this by setting the initial node's ->only_xr to true in
2866 * that case. And if <prev> is S, we set initial ->only_xr to false
2867 * because both -(S*)-> (equal) and -(E*)-> (stronger) are redundant.
2869 src_entry.only_xr = src->read == 0;
2871 debug_atomic_inc(nr_redundant_checks);
2874 * Note: we skip local_lock() for redundant check, because as the
2875 * comment in usage_skip(), A -> local_lock() -> B and A -> B are not
2878 ret = check_path(target, &src_entry, hlock_equal, usage_skip, &target_entry);
2880 if (ret == BFS_RMATCH)
2881 debug_atomic_inc(nr_redundant);
2888 static inline enum bfs_result
2889 check_redundant(struct held_lock *src, struct held_lock *target)
2891 return BFS_RNOMATCH;
2896 static void inc_chains(int irq_context)
2898 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2899 nr_hardirq_chains++;
2900 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2901 nr_softirq_chains++;
2903 nr_process_chains++;
2906 static void dec_chains(int irq_context)
2908 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2909 nr_hardirq_chains--;
2910 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2911 nr_softirq_chains--;
2913 nr_process_chains--;
2917 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
2919 struct lock_class *next = hlock_class(nxt);
2920 struct lock_class *prev = hlock_class(prv);
2922 printk(" Possible unsafe locking scenario:\n\n");
2926 __print_lock_name(prev);
2927 printk(KERN_CONT ");\n");
2929 __print_lock_name(next);
2930 printk(KERN_CONT ");\n");
2931 printk("\n *** DEADLOCK ***\n\n");
2932 printk(" May be due to missing lock nesting notation\n\n");
2936 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
2937 struct held_lock *next)
2939 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2943 pr_warn("============================================\n");
2944 pr_warn("WARNING: possible recursive locking detected\n");
2945 print_kernel_ident();
2946 pr_warn("--------------------------------------------\n");
2947 pr_warn("%s/%d is trying to acquire lock:\n",
2948 curr->comm, task_pid_nr(curr));
2950 pr_warn("\nbut task is already holding lock:\n");
2953 pr_warn("\nother info that might help us debug this:\n");
2954 print_deadlock_scenario(next, prev);
2955 lockdep_print_held_locks(curr);
2957 pr_warn("\nstack backtrace:\n");
2962 * Check whether we are holding such a class already.
2964 * (Note that this has to be done separately, because the graph cannot
2965 * detect such classes of deadlocks.)
2967 * Returns: 0 on deadlock detected, 1 on OK, 2 if another lock with the same
2968 * lock class is held but nest_lock is also held, i.e. we rely on the
2969 * nest_lock to avoid the deadlock.
2972 check_deadlock(struct task_struct *curr, struct held_lock *next)
2974 struct held_lock *prev;
2975 struct held_lock *nest = NULL;
2978 for (i = 0; i < curr->lockdep_depth; i++) {
2979 prev = curr->held_locks + i;
2981 if (prev->instance == next->nest_lock)
2984 if (hlock_class(prev) != hlock_class(next))
2988 * Allow read-after-read recursion of the same
2989 * lock class (i.e. read_lock(lock)+read_lock(lock)):
2991 if ((next->read == 2) && prev->read)
2995 * We're holding the nest_lock, which serializes this lock's
2996 * nesting behaviour.
3001 print_deadlock_bug(curr, prev, next);
3008 * There was a chain-cache miss, and we are about to add a new dependency
3009 * to a previous lock. We validate the following rules:
3011 * - would the adding of the <prev> -> <next> dependency create a
3012 * circular dependency in the graph? [== circular deadlock]
3014 * - does the new prev->next dependency connect any hardirq-safe lock
3015 * (in the full backwards-subgraph starting at <prev>) with any
3016 * hardirq-unsafe lock (in the full forwards-subgraph starting at
3017 * <next>)? [== illegal lock inversion with hardirq contexts]
3019 * - does the new prev->next dependency connect any softirq-safe lock
3020 * (in the full backwards-subgraph starting at <prev>) with any
3021 * softirq-unsafe lock (in the full forwards-subgraph starting at
3022 * <next>)? [== illegal lock inversion with softirq contexts]
3024 * any of these scenarios could lead to a deadlock.
3026 * Then if all the validations pass, we add the forwards and backwards
3030 check_prev_add(struct task_struct *curr, struct held_lock *prev,
3031 struct held_lock *next, u16 distance,
3032 struct lock_trace **const trace)
3034 struct lock_list *entry;
3035 enum bfs_result ret;
3037 if (!hlock_class(prev)->key || !hlock_class(next)->key) {
3039 * The warning statements below may trigger a use-after-free
3040 * of the class name. It is better to trigger a use-after free
3041 * and to have the class name most of the time instead of not
3042 * having the class name available.
3044 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
3045 "Detected use-after-free of lock class %px/%s\n",
3047 hlock_class(prev)->name);
3048 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
3049 "Detected use-after-free of lock class %px/%s\n",
3051 hlock_class(next)->name);
3056 * Prove that the new <prev> -> <next> dependency would not
3057 * create a circular dependency in the graph. (We do this by
3058 * a breadth-first search into the graph starting at <next>,
3059 * and check whether we can reach <prev>.)
3061 * The search is limited by the size of the circular queue (i.e.,
3062 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
3063 * in the graph whose neighbours are to be checked.
3065 ret = check_noncircular(next, prev, trace);
3066 if (unlikely(bfs_error(ret) || ret == BFS_RMATCH))
3069 if (!check_irq_usage(curr, prev, next))
3073 * Is the <prev> -> <next> dependency already present?
3075 * (this may occur even though this is a new chain: consider
3076 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
3077 * chains - the second one will be new, but L1 already has
3078 * L2 added to its dependency list, due to the first chain.)
3080 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
3081 if (entry->class == hlock_class(next)) {
3083 entry->distance = 1;
3084 entry->dep |= calc_dep(prev, next);
3087 * Also, update the reverse dependency in @next's
3088 * ->locks_before list.
3090 * Here we reuse @entry as the cursor, which is fine
3091 * because we won't go to the next iteration of the
3094 * For normal cases, we return in the inner loop.
3096 * If we fail to return, we have inconsistency, i.e.
3097 * <prev>::locks_after contains <next> while
3098 * <next>::locks_before doesn't contain <prev>. In
3099 * that case, we return after the inner and indicate
3100 * something is wrong.
3102 list_for_each_entry(entry, &hlock_class(next)->locks_before, entry) {
3103 if (entry->class == hlock_class(prev)) {
3105 entry->distance = 1;
3106 entry->dep |= calc_depb(prev, next);
3111 /* <prev> is not found in <next>::locks_before */
3117 * Is the <prev> -> <next> link redundant?
3119 ret = check_redundant(prev, next);
3122 else if (ret == BFS_RMATCH)
3126 *trace = save_trace();
3132 * Ok, all validations passed, add the new lock
3133 * to the previous lock's dependency list:
3135 ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
3136 &hlock_class(prev)->locks_after,
3137 next->acquire_ip, distance,
3138 calc_dep(prev, next),
3144 ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
3145 &hlock_class(next)->locks_before,
3146 next->acquire_ip, distance,
3147 calc_depb(prev, next),
3156 * Add the dependency to all directly-previous locks that are 'relevant'.
3157 * The ones that are relevant are (in increasing distance from curr):
3158 * all consecutive trylock entries and the final non-trylock entry - or
3159 * the end of this context's lock-chain - whichever comes first.
3162 check_prevs_add(struct task_struct *curr, struct held_lock *next)
3164 struct lock_trace *trace = NULL;
3165 int depth = curr->lockdep_depth;
3166 struct held_lock *hlock;
3171 * Depth must not be zero for a non-head lock:
3176 * At least two relevant locks must exist for this
3179 if (curr->held_locks[depth].irq_context !=
3180 curr->held_locks[depth-1].irq_context)
3184 u16 distance = curr->lockdep_depth - depth + 1;
3185 hlock = curr->held_locks + depth - 1;
3188 int ret = check_prev_add(curr, hlock, next, distance, &trace);
3193 * Stop after the first non-trylock entry,
3194 * as non-trylock entries have added their
3195 * own direct dependencies already, so this
3196 * lock is connected to them indirectly:
3198 if (!hlock->trylock)
3204 * End of lock-stack?
3209 * Stop the search if we cross into another context:
3211 if (curr->held_locks[depth].irq_context !=
3212 curr->held_locks[depth-1].irq_context)
3217 if (!debug_locks_off_graph_unlock())
3221 * Clearly we all shouldn't be here, but since we made it we
3222 * can reliable say we messed up our state. See the above two
3223 * gotos for reasons why we could possibly end up here.
3230 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
3231 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
3232 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
3233 unsigned long nr_zapped_lock_chains;
3234 unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */
3235 unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */
3236 unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */
3239 * The first 2 chain_hlocks entries in the chain block in the bucket
3240 * list contains the following meta data:
3243 * Bit 15 - always set to 1 (it is not a class index)
3244 * Bits 0-14 - upper 15 bits of the next block index
3245 * entry[1] - lower 16 bits of next block index
3247 * A next block index of all 1 bits means it is the end of the list.
3249 * On the unsized bucket (bucket-0), the 3rd and 4th entries contain
3250 * the chain block size:
3252 * entry[2] - upper 16 bits of the chain block size
3253 * entry[3] - lower 16 bits of the chain block size
3255 #define MAX_CHAIN_BUCKETS 16
3256 #define CHAIN_BLK_FLAG (1U << 15)
3257 #define CHAIN_BLK_LIST_END 0xFFFFU
3259 static int chain_block_buckets[MAX_CHAIN_BUCKETS];
3261 static inline int size_to_bucket(int size)
3263 if (size > MAX_CHAIN_BUCKETS)
3270 * Iterate all the chain blocks in a bucket.
3272 #define for_each_chain_block(bucket, prev, curr) \
3273 for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \
3275 (prev) = (curr), (curr) = chain_block_next(curr))
3280 static inline int chain_block_next(int offset)
3282 int next = chain_hlocks[offset];
3284 WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG));
3286 if (next == CHAIN_BLK_LIST_END)
3289 next &= ~CHAIN_BLK_FLAG;
3291 next |= chain_hlocks[offset + 1];
3299 static inline int chain_block_size(int offset)
3301 return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3];
3304 static inline void init_chain_block(int offset, int next, int bucket, int size)
3306 chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG;
3307 chain_hlocks[offset + 1] = (u16)next;
3309 if (size && !bucket) {
3310 chain_hlocks[offset + 2] = size >> 16;
3311 chain_hlocks[offset + 3] = (u16)size;
3315 static inline void add_chain_block(int offset, int size)
3317 int bucket = size_to_bucket(size);
3318 int next = chain_block_buckets[bucket];
3321 if (unlikely(size < 2)) {
3323 * We can't store single entries on the freelist. Leak them.
3325 * One possible way out would be to uniquely mark them, other
3326 * than with CHAIN_BLK_FLAG, such that we can recover them when
3327 * the block before it is re-added.
3330 nr_lost_chain_hlocks++;
3334 nr_free_chain_hlocks += size;
3336 nr_large_chain_blocks++;
3339 * Variable sized, sort large to small.
3341 for_each_chain_block(0, prev, curr) {
3342 if (size >= chain_block_size(curr))
3345 init_chain_block(offset, curr, 0, size);
3347 chain_block_buckets[0] = offset;
3349 init_chain_block(prev, offset, 0, 0);
3353 * Fixed size, add to head.
3355 init_chain_block(offset, next, bucket, size);
3356 chain_block_buckets[bucket] = offset;
3360 * Only the first block in the list can be deleted.
3362 * For the variable size bucket[0], the first block (the largest one) is
3363 * returned, broken up and put back into the pool. So if a chain block of
3364 * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be
3365 * queued up after the primordial chain block and never be used until the
3366 * hlock entries in the primordial chain block is almost used up. That
3367 * causes fragmentation and reduce allocation efficiency. That can be
3368 * monitored by looking at the "large chain blocks" number in lockdep_stats.
3370 static inline void del_chain_block(int bucket, int size, int next)
3372 nr_free_chain_hlocks -= size;
3373 chain_block_buckets[bucket] = next;
3376 nr_large_chain_blocks--;
3379 static void init_chain_block_buckets(void)
3383 for (i = 0; i < MAX_CHAIN_BUCKETS; i++)
3384 chain_block_buckets[i] = -1;
3386 add_chain_block(0, ARRAY_SIZE(chain_hlocks));
3390 * Return offset of a chain block of the right size or -1 if not found.
3392 * Fairly simple worst-fit allocator with the addition of a number of size
3393 * specific free lists.
3395 static int alloc_chain_hlocks(int req)
3397 int bucket, curr, size;
3400 * We rely on the MSB to act as an escape bit to denote freelist
3401 * pointers. Make sure this bit isn't set in 'normal' class_idx usage.
3403 BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG);
3405 init_data_structures_once();
3407 if (nr_free_chain_hlocks < req)
3411 * We require a minimum of 2 (u16) entries to encode a freelist
3415 bucket = size_to_bucket(req);
3416 curr = chain_block_buckets[bucket];
3420 del_chain_block(bucket, req, chain_block_next(curr));
3424 curr = chain_block_buckets[0];
3428 * The variable sized freelist is sorted by size; the first entry is
3429 * the largest. Use it if it fits.
3432 size = chain_block_size(curr);
3433 if (likely(size >= req)) {
3434 del_chain_block(0, size, chain_block_next(curr));
3435 add_chain_block(curr + req, size - req);
3441 * Last resort, split a block in a larger sized bucket.
3443 for (size = MAX_CHAIN_BUCKETS; size > req; size--) {
3444 bucket = size_to_bucket(size);
3445 curr = chain_block_buckets[bucket];
3449 del_chain_block(bucket, size, chain_block_next(curr));
3450 add_chain_block(curr + req, size - req);
3457 static inline void free_chain_hlocks(int base, int size)
3459 add_chain_block(base, max(size, 2));
3462 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
3464 u16 chain_hlock = chain_hlocks[chain->base + i];
3465 unsigned int class_idx = chain_hlock_class_idx(chain_hlock);
3467 return lock_classes + class_idx;
3471 * Returns the index of the first held_lock of the current chain
3473 static inline int get_first_held_lock(struct task_struct *curr,
3474 struct held_lock *hlock)
3477 struct held_lock *hlock_curr;
3479 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
3480 hlock_curr = curr->held_locks + i;
3481 if (hlock_curr->irq_context != hlock->irq_context)
3489 #ifdef CONFIG_DEBUG_LOCKDEP
3491 * Returns the next chain_key iteration
3493 static u64 print_chain_key_iteration(u16 hlock_id, u64 chain_key)
3495 u64 new_chain_key = iterate_chain_key(chain_key, hlock_id);
3497 printk(" hlock_id:%d -> chain_key:%016Lx",
3498 (unsigned int)hlock_id,
3499 (unsigned long long)new_chain_key);
3500 return new_chain_key;
3504 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
3506 struct held_lock *hlock;
3507 u64 chain_key = INITIAL_CHAIN_KEY;
3508 int depth = curr->lockdep_depth;
3509 int i = get_first_held_lock(curr, hlock_next);
3511 printk("depth: %u (irq_context %u)\n", depth - i + 1,
3512 hlock_next->irq_context);
3513 for (; i < depth; i++) {
3514 hlock = curr->held_locks + i;
3515 chain_key = print_chain_key_iteration(hlock_id(hlock), chain_key);
3520 print_chain_key_iteration(hlock_id(hlock_next), chain_key);
3521 print_lock(hlock_next);
3524 static void print_chain_keys_chain(struct lock_chain *chain)
3527 u64 chain_key = INITIAL_CHAIN_KEY;
3530 printk("depth: %u\n", chain->depth);
3531 for (i = 0; i < chain->depth; i++) {
3532 hlock_id = chain_hlocks[chain->base + i];
3533 chain_key = print_chain_key_iteration(hlock_id, chain_key);
3535 print_lock_name(lock_classes + chain_hlock_class_idx(hlock_id));
3540 static void print_collision(struct task_struct *curr,
3541 struct held_lock *hlock_next,
3542 struct lock_chain *chain)
3545 pr_warn("============================\n");
3546 pr_warn("WARNING: chain_key collision\n");
3547 print_kernel_ident();
3548 pr_warn("----------------------------\n");
3549 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
3550 pr_warn("Hash chain already cached but the contents don't match!\n");
3552 pr_warn("Held locks:");
3553 print_chain_keys_held_locks(curr, hlock_next);
3555 pr_warn("Locks in cached chain:");
3556 print_chain_keys_chain(chain);
3558 pr_warn("\nstack backtrace:\n");
3564 * Checks whether the chain and the current held locks are consistent
3565 * in depth and also in content. If they are not it most likely means
3566 * that there was a collision during the calculation of the chain_key.
3567 * Returns: 0 not passed, 1 passed
3569 static int check_no_collision(struct task_struct *curr,
3570 struct held_lock *hlock,
3571 struct lock_chain *chain)
3573 #ifdef CONFIG_DEBUG_LOCKDEP
3576 i = get_first_held_lock(curr, hlock);
3578 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
3579 print_collision(curr, hlock, chain);
3583 for (j = 0; j < chain->depth - 1; j++, i++) {
3584 id = hlock_id(&curr->held_locks[i]);
3586 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
3587 print_collision(curr, hlock, chain);
3596 * Given an index that is >= -1, return the index of the next lock chain.
3597 * Return -2 if there is no next lock chain.
3599 long lockdep_next_lockchain(long i)
3601 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
3602 return i < ARRAY_SIZE(lock_chains) ? i : -2;
3605 unsigned long lock_chain_count(void)
3607 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
3610 /* Must be called with the graph lock held. */
3611 static struct lock_chain *alloc_lock_chain(void)
3613 int idx = find_first_zero_bit(lock_chains_in_use,
3614 ARRAY_SIZE(lock_chains));
3616 if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
3618 __set_bit(idx, lock_chains_in_use);
3619 return lock_chains + idx;
3623 * Adds a dependency chain into chain hashtable. And must be called with
3626 * Return 0 if fail, and graph_lock is released.
3627 * Return 1 if succeed, with graph_lock held.
3629 static inline int add_chain_cache(struct task_struct *curr,
3630 struct held_lock *hlock,
3633 struct hlist_head *hash_head = chainhashentry(chain_key);
3634 struct lock_chain *chain;
3638 * The caller must hold the graph lock, ensure we've got IRQs
3639 * disabled to make this an IRQ-safe lock.. for recursion reasons
3640 * lockdep won't complain about its own locking errors.
3642 if (lockdep_assert_locked())
3645 chain = alloc_lock_chain();
3647 if (!debug_locks_off_graph_unlock())
3650 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
3654 chain->chain_key = chain_key;
3655 chain->irq_context = hlock->irq_context;
3656 i = get_first_held_lock(curr, hlock);
3657 chain->depth = curr->lockdep_depth + 1 - i;
3659 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
3660 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
3661 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
3663 j = alloc_chain_hlocks(chain->depth);
3665 if (!debug_locks_off_graph_unlock())
3668 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
3674 for (j = 0; j < chain->depth - 1; j++, i++) {
3675 int lock_id = hlock_id(curr->held_locks + i);
3677 chain_hlocks[chain->base + j] = lock_id;
3679 chain_hlocks[chain->base + j] = hlock_id(hlock);
3680 hlist_add_head_rcu(&chain->entry, hash_head);
3681 debug_atomic_inc(chain_lookup_misses);
3682 inc_chains(chain->irq_context);
3688 * Look up a dependency chain. Must be called with either the graph lock or
3689 * the RCU read lock held.
3691 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
3693 struct hlist_head *hash_head = chainhashentry(chain_key);
3694 struct lock_chain *chain;
3696 hlist_for_each_entry_rcu(chain, hash_head, entry) {
3697 if (READ_ONCE(chain->chain_key) == chain_key) {
3698 debug_atomic_inc(chain_lookup_hits);
3706 * If the key is not present yet in dependency chain cache then
3707 * add it and return 1 - in this case the new dependency chain is
3708 * validated. If the key is already hashed, return 0.
3709 * (On return with 1 graph_lock is held.)
3711 static inline int lookup_chain_cache_add(struct task_struct *curr,
3712 struct held_lock *hlock,
3715 struct lock_class *class = hlock_class(hlock);
3716 struct lock_chain *chain = lookup_chain_cache(chain_key);
3720 if (!check_no_collision(curr, hlock, chain))
3723 if (very_verbose(class)) {
3724 printk("\nhash chain already cached, key: "
3725 "%016Lx tail class: [%px] %s\n",
3726 (unsigned long long)chain_key,
3727 class->key, class->name);
3733 if (very_verbose(class)) {
3734 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
3735 (unsigned long long)chain_key, class->key, class->name);
3742 * We have to walk the chain again locked - to avoid duplicates:
3744 chain = lookup_chain_cache(chain_key);
3750 if (!add_chain_cache(curr, hlock, chain_key))
3756 static int validate_chain(struct task_struct *curr,
3757 struct held_lock *hlock,
3758 int chain_head, u64 chain_key)
3761 * Trylock needs to maintain the stack of held locks, but it
3762 * does not add new dependencies, because trylock can be done
3765 * We look up the chain_key and do the O(N^2) check and update of
3766 * the dependencies only if this is a new dependency chain.
3767 * (If lookup_chain_cache_add() return with 1 it acquires
3768 * graph_lock for us)
3770 if (!hlock->trylock && hlock->check &&
3771 lookup_chain_cache_add(curr, hlock, chain_key)) {
3773 * Check whether last held lock:
3775 * - is irq-safe, if this lock is irq-unsafe
3776 * - is softirq-safe, if this lock is hardirq-unsafe
3778 * And check whether the new lock's dependency graph
3779 * could lead back to the previous lock:
3781 * - within the current held-lock stack
3782 * - across our accumulated lock dependency records
3784 * any of these scenarios could lead to a deadlock.
3787 * The simple case: does the current hold the same lock
3790 int ret = check_deadlock(curr, hlock);
3795 * Add dependency only if this lock is not the head
3796 * of the chain, and if the new lock introduces no more
3797 * lock dependency (because we already hold a lock with the
3798 * same lock class) nor deadlock (because the nest_lock
3799 * serializes nesting locks), see the comments for
3802 if (!chain_head && ret != 2) {
3803 if (!check_prevs_add(curr, hlock))
3809 /* after lookup_chain_cache_add(): */
3810 if (unlikely(!debug_locks))
3817 static inline int validate_chain(struct task_struct *curr,
3818 struct held_lock *hlock,
3819 int chain_head, u64 chain_key)
3824 static void init_chain_block_buckets(void) { }
3825 #endif /* CONFIG_PROVE_LOCKING */
3828 * We are building curr_chain_key incrementally, so double-check
3829 * it from scratch, to make sure that it's done correctly:
3831 static void check_chain_key(struct task_struct *curr)
3833 #ifdef CONFIG_DEBUG_LOCKDEP
3834 struct held_lock *hlock, *prev_hlock = NULL;
3836 u64 chain_key = INITIAL_CHAIN_KEY;
3838 for (i = 0; i < curr->lockdep_depth; i++) {
3839 hlock = curr->held_locks + i;
3840 if (chain_key != hlock->prev_chain_key) {
3843 * We got mighty confused, our chain keys don't match
3844 * with what we expect, someone trample on our task state?
3846 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
3847 curr->lockdep_depth, i,
3848 (unsigned long long)chain_key,
3849 (unsigned long long)hlock->prev_chain_key);
3854 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
3855 * it registered lock class index?
3857 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
3860 if (prev_hlock && (prev_hlock->irq_context !=
3861 hlock->irq_context))
3862 chain_key = INITIAL_CHAIN_KEY;
3863 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
3866 if (chain_key != curr->curr_chain_key) {
3869 * More smoking hash instead of calculating it, damn see these
3870 * numbers float.. I bet that a pink elephant stepped on my memory.
3872 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
3873 curr->lockdep_depth, i,
3874 (unsigned long long)chain_key,
3875 (unsigned long long)curr->curr_chain_key);
3880 #ifdef CONFIG_PROVE_LOCKING
3881 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3882 enum lock_usage_bit new_bit);
3884 static void print_usage_bug_scenario(struct held_lock *lock)
3886 struct lock_class *class = hlock_class(lock);
3888 printk(" Possible unsafe locking scenario:\n\n");
3892 __print_lock_name(class);
3893 printk(KERN_CONT ");\n");
3894 printk(" <Interrupt>\n");
3896 __print_lock_name(class);
3897 printk(KERN_CONT ");\n");
3898 printk("\n *** DEADLOCK ***\n\n");
3902 print_usage_bug(struct task_struct *curr, struct held_lock *this,
3903 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
3905 if (!debug_locks_off() || debug_locks_silent)
3909 pr_warn("================================\n");
3910 pr_warn("WARNING: inconsistent lock state\n");
3911 print_kernel_ident();
3912 pr_warn("--------------------------------\n");
3914 pr_warn("inconsistent {%s} -> {%s} usage.\n",
3915 usage_str[prev_bit], usage_str[new_bit]);
3917 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
3918 curr->comm, task_pid_nr(curr),
3919 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
3920 lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
3921 lockdep_hardirqs_enabled(),
3922 lockdep_softirqs_enabled(curr));
3925 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
3926 print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1);
3928 print_irqtrace_events(curr);
3929 pr_warn("\nother info that might help us debug this:\n");
3930 print_usage_bug_scenario(this);
3932 lockdep_print_held_locks(curr);
3934 pr_warn("\nstack backtrace:\n");
3939 * Print out an error if an invalid bit is set:
3942 valid_state(struct task_struct *curr, struct held_lock *this,
3943 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
3945 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
3947 print_usage_bug(curr, this, bad_bit, new_bit);
3955 * print irq inversion bug:
3958 print_irq_inversion_bug(struct task_struct *curr,
3959 struct lock_list *root, struct lock_list *other,
3960 struct held_lock *this, int forwards,
3961 const char *irqclass)
3963 struct lock_list *entry = other;
3964 struct lock_list *middle = NULL;
3967 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3971 pr_warn("========================================================\n");
3972 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
3973 print_kernel_ident();
3974 pr_warn("--------------------------------------------------------\n");
3975 pr_warn("%s/%d just changed the state of lock:\n",
3976 curr->comm, task_pid_nr(curr));
3979 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
3981 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
3982 print_lock_name(other->class);
3983 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
3985 pr_warn("\nother info that might help us debug this:\n");
3987 /* Find a middle lock (if one exists) */
3988 depth = get_lock_depth(other);
3990 if (depth == 0 && (entry != root)) {
3991 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
3995 entry = get_lock_parent(entry);
3997 } while (entry && entry != root && (depth >= 0));
3999 print_irq_lock_scenario(root, other,
4000 middle ? middle->class : root->class, other->class);
4002 print_irq_lock_scenario(other, root,
4003 middle ? middle->class : other->class, root->class);
4005 lockdep_print_held_locks(curr);
4007 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
4008 root->trace = save_trace();
4011 print_shortest_lock_dependencies(other, root);
4013 pr_warn("\nstack backtrace:\n");
4018 * Prove that in the forwards-direction subgraph starting at <this>
4019 * there is no lock matching <mask>:
4022 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
4023 enum lock_usage_bit bit)
4025 enum bfs_result ret;
4026 struct lock_list root;
4027 struct lock_list *target_entry;
4028 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
4029 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
4031 bfs_init_root(&root, this);
4032 ret = find_usage_forwards(&root, usage_mask, &target_entry);
4033 if (bfs_error(ret)) {
4037 if (ret == BFS_RNOMATCH)
4040 /* Check whether write or read usage is the match */
4041 if (target_entry->class->usage_mask & lock_flag(bit)) {
4042 print_irq_inversion_bug(curr, &root, target_entry,
4043 this, 1, state_name(bit));
4045 print_irq_inversion_bug(curr, &root, target_entry,
4046 this, 1, state_name(read_bit));
4053 * Prove that in the backwards-direction subgraph starting at <this>
4054 * there is no lock matching <mask>:
4057 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
4058 enum lock_usage_bit bit)
4060 enum bfs_result ret;
4061 struct lock_list root;
4062 struct lock_list *target_entry;
4063 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
4064 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
4066 bfs_init_rootb(&root, this);
4067 ret = find_usage_backwards(&root, usage_mask, &target_entry);
4068 if (bfs_error(ret)) {
4072 if (ret == BFS_RNOMATCH)
4075 /* Check whether write or read usage is the match */
4076 if (target_entry->class->usage_mask & lock_flag(bit)) {
4077 print_irq_inversion_bug(curr, &root, target_entry,
4078 this, 0, state_name(bit));
4080 print_irq_inversion_bug(curr, &root, target_entry,
4081 this, 0, state_name(read_bit));
4087 void print_irqtrace_events(struct task_struct *curr)
4089 const struct irqtrace_events *trace = &curr->irqtrace;
4091 printk("irq event stamp: %u\n", trace->irq_events);
4092 printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
4093 trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip,
4094 (void *)trace->hardirq_enable_ip);
4095 printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
4096 trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip,
4097 (void *)trace->hardirq_disable_ip);
4098 printk("softirqs last enabled at (%u): [<%px>] %pS\n",
4099 trace->softirq_enable_event, (void *)trace->softirq_enable_ip,
4100 (void *)trace->softirq_enable_ip);
4101 printk("softirqs last disabled at (%u): [<%px>] %pS\n",
4102 trace->softirq_disable_event, (void *)trace->softirq_disable_ip,
4103 (void *)trace->softirq_disable_ip);
4106 static int HARDIRQ_verbose(struct lock_class *class)
4109 return class_filter(class);
4114 static int SOFTIRQ_verbose(struct lock_class *class)
4117 return class_filter(class);
4122 static int (*state_verbose_f[])(struct lock_class *class) = {
4123 #define LOCKDEP_STATE(__STATE) \
4125 #include "lockdep_states.h"
4126 #undef LOCKDEP_STATE
4129 static inline int state_verbose(enum lock_usage_bit bit,
4130 struct lock_class *class)
4132 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
4135 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
4136 enum lock_usage_bit bit, const char *name);
4139 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
4140 enum lock_usage_bit new_bit)
4142 int excl_bit = exclusive_bit(new_bit);
4143 int read = new_bit & LOCK_USAGE_READ_MASK;
4144 int dir = new_bit & LOCK_USAGE_DIR_MASK;
4147 * Validate that this particular lock does not have conflicting
4150 if (!valid_state(curr, this, new_bit, excl_bit))
4154 * Check for read in write conflicts
4156 if (!read && !valid_state(curr, this, new_bit,
4157 excl_bit + LOCK_USAGE_READ_MASK))
4162 * Validate that the lock dependencies don't have conflicting usage
4167 * mark ENABLED has to look backwards -- to ensure no dependee
4168 * has USED_IN state, which, again, would allow recursion deadlocks.
4170 if (!check_usage_backwards(curr, this, excl_bit))
4174 * mark USED_IN has to look forwards -- to ensure no dependency
4175 * has ENABLED state, which would allow recursion deadlocks.
4177 if (!check_usage_forwards(curr, this, excl_bit))
4181 if (state_verbose(new_bit, hlock_class(this)))
4188 * Mark all held locks with a usage bit:
4191 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
4193 struct held_lock *hlock;
4196 for (i = 0; i < curr->lockdep_depth; i++) {
4197 enum lock_usage_bit hlock_bit = base_bit;
4198 hlock = curr->held_locks + i;
4201 hlock_bit += LOCK_USAGE_READ_MASK;
4203 BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
4208 if (!mark_lock(curr, hlock, hlock_bit))
4216 * Hardirqs will be enabled:
4218 static void __trace_hardirqs_on_caller(void)
4220 struct task_struct *curr = current;
4223 * We are going to turn hardirqs on, so set the
4224 * usage bit for all held locks:
4226 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
4229 * If we have softirqs enabled, then set the usage
4230 * bit for all held locks. (disabled hardirqs prevented
4231 * this bit from being set before)
4233 if (curr->softirqs_enabled)
4234 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
4238 * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts
4239 * @ip: Caller address
4241 * Invoked before a possible transition to RCU idle from exit to user or
4242 * guest mode. This ensures that all RCU operations are done before RCU
4243 * stops watching. After the RCU transition lockdep_hardirqs_on() has to be
4244 * invoked to set the final state.
4246 void lockdep_hardirqs_on_prepare(unsigned long ip)
4248 if (unlikely(!debug_locks))
4252 * NMIs do not (and cannot) track lock dependencies, nothing to do.
4254 if (unlikely(in_nmi()))
4257 if (unlikely(this_cpu_read(lockdep_recursion)))
4260 if (unlikely(lockdep_hardirqs_enabled())) {
4262 * Neither irq nor preemption are disabled here
4263 * so this is racy by nature but losing one hit
4264 * in a stat is not a big deal.
4266 __debug_atomic_inc(redundant_hardirqs_on);
4271 * We're enabling irqs and according to our state above irqs weren't
4272 * already enabled, yet we find the hardware thinks they are in fact
4273 * enabled.. someone messed up their IRQ state tracing.
4275 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4279 * See the fine text that goes along with this variable definition.
4281 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
4285 * Can't allow enabling interrupts while in an interrupt handler,
4286 * that's general bad form and such. Recursion, limited stack etc..
4288 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context()))
4291 current->hardirq_chain_key = current->curr_chain_key;
4293 lockdep_recursion_inc();
4294 __trace_hardirqs_on_caller();
4295 lockdep_recursion_finish();
4297 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare);
4299 void noinstr lockdep_hardirqs_on(unsigned long ip)
4301 struct irqtrace_events *trace = ¤t->irqtrace;
4303 if (unlikely(!debug_locks))
4307 * NMIs can happen in the middle of local_irq_{en,dis}able() where the
4308 * tracking state and hardware state are out of sync.
4310 * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from,
4311 * and not rely on hardware state like normal interrupts.
4313 if (unlikely(in_nmi())) {
4314 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4319 * - recursion check, because NMI can hit lockdep;
4320 * - hardware state check, because above;
4321 * - chain_key check, see lockdep_hardirqs_on_prepare().
4326 if (unlikely(this_cpu_read(lockdep_recursion)))
4329 if (lockdep_hardirqs_enabled()) {
4331 * Neither irq nor preemption are disabled here
4332 * so this is racy by nature but losing one hit
4333 * in a stat is not a big deal.
4335 __debug_atomic_inc(redundant_hardirqs_on);
4340 * We're enabling irqs and according to our state above irqs weren't
4341 * already enabled, yet we find the hardware thinks they are in fact
4342 * enabled.. someone messed up their IRQ state tracing.
4344 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4348 * Ensure the lock stack remained unchanged between
4349 * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on().
4351 DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key !=
4352 current->curr_chain_key);
4355 /* we'll do an OFF -> ON transition: */
4356 __this_cpu_write(hardirqs_enabled, 1);
4357 trace->hardirq_enable_ip = ip;
4358 trace->hardirq_enable_event = ++trace->irq_events;
4359 debug_atomic_inc(hardirqs_on_events);
4361 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on);
4364 * Hardirqs were disabled:
4366 void noinstr lockdep_hardirqs_off(unsigned long ip)
4368 if (unlikely(!debug_locks))
4372 * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep;
4373 * they will restore the software state. This ensures the software
4374 * state is consistent inside NMIs as well.
4377 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4379 } else if (__this_cpu_read(lockdep_recursion))
4383 * So we're supposed to get called after you mask local IRQs, but for
4384 * some reason the hardware doesn't quite think you did a proper job.
4386 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4389 if (lockdep_hardirqs_enabled()) {
4390 struct irqtrace_events *trace = ¤t->irqtrace;
4393 * We have done an ON -> OFF transition:
4395 __this_cpu_write(hardirqs_enabled, 0);
4396 trace->hardirq_disable_ip = ip;
4397 trace->hardirq_disable_event = ++trace->irq_events;
4398 debug_atomic_inc(hardirqs_off_events);
4400 debug_atomic_inc(redundant_hardirqs_off);
4403 EXPORT_SYMBOL_GPL(lockdep_hardirqs_off);
4406 * Softirqs will be enabled:
4408 void lockdep_softirqs_on(unsigned long ip)
4410 struct irqtrace_events *trace = ¤t->irqtrace;
4412 if (unlikely(!lockdep_enabled()))
4416 * We fancy IRQs being disabled here, see softirq.c, avoids
4417 * funny state and nesting things.
4419 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4422 if (current->softirqs_enabled) {
4423 debug_atomic_inc(redundant_softirqs_on);
4427 lockdep_recursion_inc();
4429 * We'll do an OFF -> ON transition:
4431 current->softirqs_enabled = 1;
4432 trace->softirq_enable_ip = ip;
4433 trace->softirq_enable_event = ++trace->irq_events;
4434 debug_atomic_inc(softirqs_on_events);
4436 * We are going to turn softirqs on, so set the
4437 * usage bit for all held locks, if hardirqs are
4440 if (lockdep_hardirqs_enabled())
4441 mark_held_locks(current, LOCK_ENABLED_SOFTIRQ);
4442 lockdep_recursion_finish();
4446 * Softirqs were disabled:
4448 void lockdep_softirqs_off(unsigned long ip)
4450 if (unlikely(!lockdep_enabled()))
4454 * We fancy IRQs being disabled here, see softirq.c
4456 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4459 if (current->softirqs_enabled) {
4460 struct irqtrace_events *trace = ¤t->irqtrace;
4463 * We have done an ON -> OFF transition:
4465 current->softirqs_enabled = 0;
4466 trace->softirq_disable_ip = ip;
4467 trace->softirq_disable_event = ++trace->irq_events;
4468 debug_atomic_inc(softirqs_off_events);
4470 * Whoops, we wanted softirqs off, so why aren't they?
4472 DEBUG_LOCKS_WARN_ON(!softirq_count());
4474 debug_atomic_inc(redundant_softirqs_off);
4478 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4484 * If non-trylock use in a hardirq or softirq context, then
4485 * mark the lock as used in these contexts:
4487 if (!hlock->trylock) {
4489 if (lockdep_hardirq_context())
4490 if (!mark_lock(curr, hlock,
4491 LOCK_USED_IN_HARDIRQ_READ))
4493 if (curr->softirq_context)
4494 if (!mark_lock(curr, hlock,
4495 LOCK_USED_IN_SOFTIRQ_READ))
4498 if (lockdep_hardirq_context())
4499 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
4501 if (curr->softirq_context)
4502 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
4506 if (!hlock->hardirqs_off) {
4508 if (!mark_lock(curr, hlock,
4509 LOCK_ENABLED_HARDIRQ_READ))
4511 if (curr->softirqs_enabled)
4512 if (!mark_lock(curr, hlock,
4513 LOCK_ENABLED_SOFTIRQ_READ))
4516 if (!mark_lock(curr, hlock,
4517 LOCK_ENABLED_HARDIRQ))
4519 if (curr->softirqs_enabled)
4520 if (!mark_lock(curr, hlock,
4521 LOCK_ENABLED_SOFTIRQ))
4527 /* mark it as used: */
4528 if (!mark_lock(curr, hlock, LOCK_USED))
4534 static inline unsigned int task_irq_context(struct task_struct *task)
4536 return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() +
4537 LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context;
4540 static int separate_irq_context(struct task_struct *curr,
4541 struct held_lock *hlock)
4543 unsigned int depth = curr->lockdep_depth;
4546 * Keep track of points where we cross into an interrupt context:
4549 struct held_lock *prev_hlock;
4551 prev_hlock = curr->held_locks + depth-1;
4553 * If we cross into another context, reset the
4554 * hash key (this also prevents the checking and the
4555 * adding of the dependency to 'prev'):
4557 if (prev_hlock->irq_context != hlock->irq_context)
4564 * Mark a lock with a usage bit, and validate the state transition:
4566 static int mark_lock(struct task_struct *curr, struct held_lock *this,
4567 enum lock_usage_bit new_bit)
4569 unsigned int new_mask, ret = 1;
4571 if (new_bit >= LOCK_USAGE_STATES) {
4572 DEBUG_LOCKS_WARN_ON(1);
4576 if (new_bit == LOCK_USED && this->read)
4577 new_bit = LOCK_USED_READ;
4579 new_mask = 1 << new_bit;
4582 * If already set then do not dirty the cacheline,
4583 * nor do any checks:
4585 if (likely(hlock_class(this)->usage_mask & new_mask))
4591 * Make sure we didn't race:
4593 if (unlikely(hlock_class(this)->usage_mask & new_mask))
4596 if (!hlock_class(this)->usage_mask)
4597 debug_atomic_dec(nr_unused_locks);
4599 hlock_class(this)->usage_mask |= new_mask;
4601 if (new_bit < LOCK_TRACE_STATES) {
4602 if (!(hlock_class(this)->usage_traces[new_bit] = save_trace()))
4606 if (new_bit < LOCK_USED) {
4607 ret = mark_lock_irq(curr, this, new_bit);
4616 * We must printk outside of the graph_lock:
4619 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
4621 print_irqtrace_events(curr);
4628 static inline short task_wait_context(struct task_struct *curr)
4631 * Set appropriate wait type for the context; for IRQs we have to take
4632 * into account force_irqthread as that is implied by PREEMPT_RT.
4634 if (lockdep_hardirq_context()) {
4636 * Check if force_irqthreads will run us threaded.
4638 if (curr->hardirq_threaded || curr->irq_config)
4639 return LD_WAIT_CONFIG;
4641 return LD_WAIT_SPIN;
4642 } else if (curr->softirq_context) {
4644 * Softirqs are always threaded.
4646 return LD_WAIT_CONFIG;
4653 print_lock_invalid_wait_context(struct task_struct *curr,
4654 struct held_lock *hlock)
4658 if (!debug_locks_off())
4660 if (debug_locks_silent)
4664 pr_warn("=============================\n");
4665 pr_warn("[ BUG: Invalid wait context ]\n");
4666 print_kernel_ident();
4667 pr_warn("-----------------------------\n");
4669 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4672 pr_warn("other info that might help us debug this:\n");
4674 curr_inner = task_wait_context(curr);
4675 pr_warn("context-{%d:%d}\n", curr_inner, curr_inner);
4677 lockdep_print_held_locks(curr);
4679 pr_warn("stack backtrace:\n");
4686 * Verify the wait_type context.
4688 * This check validates we take locks in the right wait-type order; that is it
4689 * ensures that we do not take mutexes inside spinlocks and do not attempt to
4690 * acquire spinlocks inside raw_spinlocks and the sort.
4692 * The entire thing is slightly more complex because of RCU, RCU is a lock that
4693 * can be taken from (pretty much) any context but also has constraints.
4694 * However when taken in a stricter environment the RCU lock does not loosen
4697 * Therefore we must look for the strictest environment in the lock stack and
4698 * compare that to the lock we're trying to acquire.
4700 static int check_wait_context(struct task_struct *curr, struct held_lock *next)
4702 u8 next_inner = hlock_class(next)->wait_type_inner;
4703 u8 next_outer = hlock_class(next)->wait_type_outer;
4707 if (!next_inner || next->trylock)
4711 next_outer = next_inner;
4714 * Find start of current irq_context..
4716 for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) {
4717 struct held_lock *prev = curr->held_locks + depth;
4718 if (prev->irq_context != next->irq_context)
4723 curr_inner = task_wait_context(curr);
4725 for (; depth < curr->lockdep_depth; depth++) {
4726 struct held_lock *prev = curr->held_locks + depth;
4727 u8 prev_inner = hlock_class(prev)->wait_type_inner;
4731 * We can have a bigger inner than a previous one
4732 * when outer is smaller than inner, as with RCU.
4734 * Also due to trylocks.
4736 curr_inner = min(curr_inner, prev_inner);
4740 if (next_outer > curr_inner)
4741 return print_lock_invalid_wait_context(curr, next);
4746 #else /* CONFIG_PROVE_LOCKING */
4749 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4754 static inline unsigned int task_irq_context(struct task_struct *task)
4759 static inline int separate_irq_context(struct task_struct *curr,
4760 struct held_lock *hlock)
4765 static inline int check_wait_context(struct task_struct *curr,
4766 struct held_lock *next)
4771 #endif /* CONFIG_PROVE_LOCKING */
4774 * Initialize a lock instance's lock-class mapping info:
4776 void lockdep_init_map_type(struct lockdep_map *lock, const char *name,
4777 struct lock_class_key *key, int subclass,
4778 u8 inner, u8 outer, u8 lock_type)
4782 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
4783 lock->class_cache[i] = NULL;
4785 #ifdef CONFIG_LOCK_STAT
4786 lock->cpu = raw_smp_processor_id();
4790 * Can't be having no nameless bastards around this place!
4792 if (DEBUG_LOCKS_WARN_ON(!name)) {
4793 lock->name = "NULL";
4799 lock->wait_type_outer = outer;
4800 lock->wait_type_inner = inner;
4801 lock->lock_type = lock_type;
4804 * No key, no joy, we need to hash something.
4806 if (DEBUG_LOCKS_WARN_ON(!key))
4809 * Sanity check, the lock-class key must either have been allocated
4810 * statically or must have been registered as a dynamic key.
4812 if (!static_obj(key) && !is_dynamic_key(key)) {
4814 printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
4815 DEBUG_LOCKS_WARN_ON(1);
4820 if (unlikely(!debug_locks))
4824 unsigned long flags;
4826 if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled()))
4829 raw_local_irq_save(flags);
4830 lockdep_recursion_inc();
4831 register_lock_class(lock, subclass, 1);
4832 lockdep_recursion_finish();
4833 raw_local_irq_restore(flags);
4836 EXPORT_SYMBOL_GPL(lockdep_init_map_type);
4838 struct lock_class_key __lockdep_no_validate__;
4839 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
4842 print_lock_nested_lock_not_held(struct task_struct *curr,
4843 struct held_lock *hlock,
4846 if (!debug_locks_off())
4848 if (debug_locks_silent)
4852 pr_warn("==================================\n");
4853 pr_warn("WARNING: Nested lock was not taken\n");
4854 print_kernel_ident();
4855 pr_warn("----------------------------------\n");
4857 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4860 pr_warn("\nbut this task is not holding:\n");
4861 pr_warn("%s\n", hlock->nest_lock->name);
4863 pr_warn("\nstack backtrace:\n");
4866 pr_warn("\nother info that might help us debug this:\n");
4867 lockdep_print_held_locks(curr);
4869 pr_warn("\nstack backtrace:\n");
4873 static int __lock_is_held(const struct lockdep_map *lock, int read);
4876 * This gets called for every mutex_lock*()/spin_lock*() operation.
4877 * We maintain the dependency maps and validate the locking attempt:
4879 * The callers must make sure that IRQs are disabled before calling it,
4880 * otherwise we could get an interrupt which would want to take locks,
4881 * which would end up in lockdep again.
4883 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
4884 int trylock, int read, int check, int hardirqs_off,
4885 struct lockdep_map *nest_lock, unsigned long ip,
4886 int references, int pin_count)
4888 struct task_struct *curr = current;
4889 struct lock_class *class = NULL;
4890 struct held_lock *hlock;
4896 if (unlikely(!debug_locks))
4899 if (!prove_locking || lock->key == &__lockdep_no_validate__)
4902 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
4903 class = lock->class_cache[subclass];
4907 if (unlikely(!class)) {
4908 class = register_lock_class(lock, subclass, 0);
4913 debug_class_ops_inc(class);
4915 if (very_verbose(class)) {
4916 printk("\nacquire class [%px] %s", class->key, class->name);
4917 if (class->name_version > 1)
4918 printk(KERN_CONT "#%d", class->name_version);
4919 printk(KERN_CONT "\n");
4924 * Add the lock to the list of currently held locks.
4925 * (we dont increase the depth just yet, up until the
4926 * dependency checks are done)
4928 depth = curr->lockdep_depth;
4930 * Ran out of static storage for our per-task lock stack again have we?
4932 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
4935 class_idx = class - lock_classes;
4937 if (depth) { /* we're holding locks */
4938 hlock = curr->held_locks + depth - 1;
4939 if (hlock->class_idx == class_idx && nest_lock) {
4943 if (!hlock->references)
4944 hlock->references++;
4946 hlock->references += references;
4949 if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
4956 hlock = curr->held_locks + depth;
4958 * Plain impossible, we just registered it and checked it weren't no
4959 * NULL like.. I bet this mushroom I ate was good!
4961 if (DEBUG_LOCKS_WARN_ON(!class))
4963 hlock->class_idx = class_idx;
4964 hlock->acquire_ip = ip;
4965 hlock->instance = lock;
4966 hlock->nest_lock = nest_lock;
4967 hlock->irq_context = task_irq_context(curr);
4968 hlock->trylock = trylock;
4970 hlock->check = check;
4971 hlock->hardirqs_off = !!hardirqs_off;
4972 hlock->references = references;
4973 #ifdef CONFIG_LOCK_STAT
4974 hlock->waittime_stamp = 0;
4975 hlock->holdtime_stamp = lockstat_clock();
4977 hlock->pin_count = pin_count;
4979 if (check_wait_context(curr, hlock))
4982 /* Initialize the lock usage bit */
4983 if (!mark_usage(curr, hlock, check))
4987 * Calculate the chain hash: it's the combined hash of all the
4988 * lock keys along the dependency chain. We save the hash value
4989 * at every step so that we can get the current hash easily
4990 * after unlock. The chain hash is then used to cache dependency
4993 * The 'key ID' is what is the most compact key value to drive
4994 * the hash, not class->key.
4997 * Whoops, we did it again.. class_idx is invalid.
4999 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
5002 chain_key = curr->curr_chain_key;
5005 * How can we have a chain hash when we ain't got no keys?!
5007 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
5012 hlock->prev_chain_key = chain_key;
5013 if (separate_irq_context(curr, hlock)) {
5014 chain_key = INITIAL_CHAIN_KEY;
5017 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
5019 if (nest_lock && !__lock_is_held(nest_lock, -1)) {
5020 print_lock_nested_lock_not_held(curr, hlock, ip);
5024 if (!debug_locks_silent) {
5025 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
5026 WARN_ON_ONCE(!hlock_class(hlock)->key);
5029 if (!validate_chain(curr, hlock, chain_head, chain_key))
5032 curr->curr_chain_key = chain_key;
5033 curr->lockdep_depth++;
5034 check_chain_key(curr);
5035 #ifdef CONFIG_DEBUG_LOCKDEP
5036 if (unlikely(!debug_locks))
5039 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
5041 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
5042 printk(KERN_DEBUG "depth: %i max: %lu!\n",
5043 curr->lockdep_depth, MAX_LOCK_DEPTH);
5045 lockdep_print_held_locks(current);
5046 debug_show_all_locks();
5052 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
5053 max_lockdep_depth = curr->lockdep_depth;
5058 static void print_unlock_imbalance_bug(struct task_struct *curr,
5059 struct lockdep_map *lock,
5062 if (!debug_locks_off())
5064 if (debug_locks_silent)
5068 pr_warn("=====================================\n");
5069 pr_warn("WARNING: bad unlock balance detected!\n");
5070 print_kernel_ident();
5071 pr_warn("-------------------------------------\n");
5072 pr_warn("%s/%d is trying to release lock (",
5073 curr->comm, task_pid_nr(curr));
5074 print_lockdep_cache(lock);
5076 print_ip_sym(KERN_WARNING, ip);
5077 pr_warn("but there are no more locks to release!\n");
5078 pr_warn("\nother info that might help us debug this:\n");
5079 lockdep_print_held_locks(curr);
5081 pr_warn("\nstack backtrace:\n");
5085 static noinstr int match_held_lock(const struct held_lock *hlock,
5086 const struct lockdep_map *lock)
5088 if (hlock->instance == lock)
5091 if (hlock->references) {
5092 const struct lock_class *class = lock->class_cache[0];
5095 class = look_up_lock_class(lock, 0);
5098 * If look_up_lock_class() failed to find a class, we're trying
5099 * to test if we hold a lock that has never yet been acquired.
5100 * Clearly if the lock hasn't been acquired _ever_, we're not
5101 * holding it either, so report failure.
5107 * References, but not a lock we're actually ref-counting?
5108 * State got messed up, follow the sites that change ->references
5109 * and try to make sense of it.
5111 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
5114 if (hlock->class_idx == class - lock_classes)
5121 /* @depth must not be zero */
5122 static struct held_lock *find_held_lock(struct task_struct *curr,
5123 struct lockdep_map *lock,
5124 unsigned int depth, int *idx)
5126 struct held_lock *ret, *hlock, *prev_hlock;
5130 hlock = curr->held_locks + i;
5132 if (match_held_lock(hlock, lock))
5136 for (i--, prev_hlock = hlock--;
5138 i--, prev_hlock = hlock--) {
5140 * We must not cross into another context:
5142 if (prev_hlock->irq_context != hlock->irq_context) {
5146 if (match_held_lock(hlock, lock)) {
5157 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
5158 int idx, unsigned int *merged)
5160 struct held_lock *hlock;
5161 int first_idx = idx;
5163 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
5166 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
5167 switch (__lock_acquire(hlock->instance,
5168 hlock_class(hlock)->subclass,
5170 hlock->read, hlock->check,
5171 hlock->hardirqs_off,
5172 hlock->nest_lock, hlock->acquire_ip,
5173 hlock->references, hlock->pin_count)) {
5179 *merged += (idx == first_idx);
5190 __lock_set_class(struct lockdep_map *lock, const char *name,
5191 struct lock_class_key *key, unsigned int subclass,
5194 struct task_struct *curr = current;
5195 unsigned int depth, merged = 0;
5196 struct held_lock *hlock;
5197 struct lock_class *class;
5200 if (unlikely(!debug_locks))
5203 depth = curr->lockdep_depth;
5205 * This function is about (re)setting the class of a held lock,
5206 * yet we're not actually holding any locks. Naughty user!
5208 if (DEBUG_LOCKS_WARN_ON(!depth))
5211 hlock = find_held_lock(curr, lock, depth, &i);
5213 print_unlock_imbalance_bug(curr, lock, ip);
5217 lockdep_init_map_waits(lock, name, key, 0,
5218 lock->wait_type_inner,
5219 lock->wait_type_outer);
5220 class = register_lock_class(lock, subclass, 0);
5221 hlock->class_idx = class - lock_classes;
5223 curr->lockdep_depth = i;
5224 curr->curr_chain_key = hlock->prev_chain_key;
5226 if (reacquire_held_locks(curr, depth, i, &merged))
5230 * I took it apart and put it back together again, except now I have
5231 * these 'spare' parts.. where shall I put them.
5233 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
5238 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5240 struct task_struct *curr = current;
5241 unsigned int depth, merged = 0;
5242 struct held_lock *hlock;
5245 if (unlikely(!debug_locks))
5248 depth = curr->lockdep_depth;
5250 * This function is about (re)setting the class of a held lock,
5251 * yet we're not actually holding any locks. Naughty user!
5253 if (DEBUG_LOCKS_WARN_ON(!depth))
5256 hlock = find_held_lock(curr, lock, depth, &i);
5258 print_unlock_imbalance_bug(curr, lock, ip);
5262 curr->lockdep_depth = i;
5263 curr->curr_chain_key = hlock->prev_chain_key;
5265 WARN(hlock->read, "downgrading a read lock");
5267 hlock->acquire_ip = ip;
5269 if (reacquire_held_locks(curr, depth, i, &merged))
5272 /* Merging can't happen with unchanged classes.. */
5273 if (DEBUG_LOCKS_WARN_ON(merged))
5277 * I took it apart and put it back together again, except now I have
5278 * these 'spare' parts.. where shall I put them.
5280 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
5287 * Remove the lock from the list of currently held locks - this gets
5288 * called on mutex_unlock()/spin_unlock*() (or on a failed
5289 * mutex_lock_interruptible()).
5292 __lock_release(struct lockdep_map *lock, unsigned long ip)
5294 struct task_struct *curr = current;
5295 unsigned int depth, merged = 1;
5296 struct held_lock *hlock;
5299 if (unlikely(!debug_locks))
5302 depth = curr->lockdep_depth;
5304 * So we're all set to release this lock.. wait what lock? We don't
5305 * own any locks, you've been drinking again?
5308 print_unlock_imbalance_bug(curr, lock, ip);
5313 * Check whether the lock exists in the current stack
5316 hlock = find_held_lock(curr, lock, depth, &i);
5318 print_unlock_imbalance_bug(curr, lock, ip);
5322 if (hlock->instance == lock)
5323 lock_release_holdtime(hlock);
5325 WARN(hlock->pin_count, "releasing a pinned lock\n");
5327 if (hlock->references) {
5328 hlock->references--;
5329 if (hlock->references) {
5331 * We had, and after removing one, still have
5332 * references, the current lock stack is still
5333 * valid. We're done!
5340 * We have the right lock to unlock, 'hlock' points to it.
5341 * Now we remove it from the stack, and add back the other
5342 * entries (if any), recalculating the hash along the way:
5345 curr->lockdep_depth = i;
5346 curr->curr_chain_key = hlock->prev_chain_key;
5349 * The most likely case is when the unlock is on the innermost
5350 * lock. In this case, we are done!
5355 if (reacquire_held_locks(curr, depth, i + 1, &merged))
5359 * We had N bottles of beer on the wall, we drank one, but now
5360 * there's not N-1 bottles of beer left on the wall...
5361 * Pouring two of the bottles together is acceptable.
5363 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
5366 * Since reacquire_held_locks() would have called check_chain_key()
5367 * indirectly via __lock_acquire(), we don't need to do it again
5373 static __always_inline
5374 int __lock_is_held(const struct lockdep_map *lock, int read)
5376 struct task_struct *curr = current;
5379 for (i = 0; i < curr->lockdep_depth; i++) {
5380 struct held_lock *hlock = curr->held_locks + i;
5382 if (match_held_lock(hlock, lock)) {
5383 if (read == -1 || !!hlock->read == read)
5384 return LOCK_STATE_HELD;
5386 return LOCK_STATE_NOT_HELD;
5390 return LOCK_STATE_NOT_HELD;
5393 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
5395 struct pin_cookie cookie = NIL_COOKIE;
5396 struct task_struct *curr = current;
5399 if (unlikely(!debug_locks))
5402 for (i = 0; i < curr->lockdep_depth; i++) {
5403 struct held_lock *hlock = curr->held_locks + i;
5405 if (match_held_lock(hlock, lock)) {
5407 * Grab 16bits of randomness; this is sufficient to not
5408 * be guessable and still allows some pin nesting in
5409 * our u32 pin_count.
5411 cookie.val = 1 + (prandom_u32() >> 16);
5412 hlock->pin_count += cookie.val;
5417 WARN(1, "pinning an unheld lock\n");
5421 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5423 struct task_struct *curr = current;
5426 if (unlikely(!debug_locks))
5429 for (i = 0; i < curr->lockdep_depth; i++) {
5430 struct held_lock *hlock = curr->held_locks + i;
5432 if (match_held_lock(hlock, lock)) {
5433 hlock->pin_count += cookie.val;
5438 WARN(1, "pinning an unheld lock\n");
5441 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5443 struct task_struct *curr = current;
5446 if (unlikely(!debug_locks))
5449 for (i = 0; i < curr->lockdep_depth; i++) {
5450 struct held_lock *hlock = curr->held_locks + i;
5452 if (match_held_lock(hlock, lock)) {
5453 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
5456 hlock->pin_count -= cookie.val;
5458 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
5459 hlock->pin_count = 0;
5465 WARN(1, "unpinning an unheld lock\n");
5469 * Check whether we follow the irq-flags state precisely:
5471 static noinstr void check_flags(unsigned long flags)
5473 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP)
5477 /* Get the warning out.. */
5478 instrumentation_begin();
5480 if (irqs_disabled_flags(flags)) {
5481 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) {
5482 printk("possible reason: unannotated irqs-off.\n");
5485 if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) {
5486 printk("possible reason: unannotated irqs-on.\n");
5490 #ifndef CONFIG_PREEMPT_RT
5492 * We dont accurately track softirq state in e.g.
5493 * hardirq contexts (such as on 4KSTACKS), so only
5494 * check if not in hardirq contexts:
5496 if (!hardirq_count()) {
5497 if (softirq_count()) {
5498 /* like the above, but with softirqs */
5499 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
5501 /* lick the above, does it taste good? */
5502 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
5508 print_irqtrace_events(current);
5510 instrumentation_end();
5514 void lock_set_class(struct lockdep_map *lock, const char *name,
5515 struct lock_class_key *key, unsigned int subclass,
5518 unsigned long flags;
5520 if (unlikely(!lockdep_enabled()))
5523 raw_local_irq_save(flags);
5524 lockdep_recursion_inc();
5526 if (__lock_set_class(lock, name, key, subclass, ip))
5527 check_chain_key(current);
5528 lockdep_recursion_finish();
5529 raw_local_irq_restore(flags);
5531 EXPORT_SYMBOL_GPL(lock_set_class);
5533 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5535 unsigned long flags;
5537 if (unlikely(!lockdep_enabled()))
5540 raw_local_irq_save(flags);
5541 lockdep_recursion_inc();
5543 if (__lock_downgrade(lock, ip))
5544 check_chain_key(current);
5545 lockdep_recursion_finish();
5546 raw_local_irq_restore(flags);
5548 EXPORT_SYMBOL_GPL(lock_downgrade);
5550 /* NMI context !!! */
5551 static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass)
5553 #ifdef CONFIG_PROVE_LOCKING
5554 struct lock_class *class = look_up_lock_class(lock, subclass);
5555 unsigned long mask = LOCKF_USED;
5557 /* if it doesn't have a class (yet), it certainly hasn't been used yet */
5562 * READ locks only conflict with USED, such that if we only ever use
5563 * READ locks, there is no deadlock possible -- RCU.
5566 mask |= LOCKF_USED_READ;
5568 if (!(class->usage_mask & mask))
5571 hlock->class_idx = class - lock_classes;
5573 print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES);
5577 static bool lockdep_nmi(void)
5579 if (raw_cpu_read(lockdep_recursion))
5589 * read_lock() is recursive if:
5590 * 1. We force lockdep think this way in selftests or
5591 * 2. The implementation is not queued read/write lock or
5592 * 3. The locker is at an in_interrupt() context.
5594 bool read_lock_is_recursive(void)
5596 return force_read_lock_recursive ||
5597 !IS_ENABLED(CONFIG_QUEUED_RWLOCKS) ||
5600 EXPORT_SYMBOL_GPL(read_lock_is_recursive);
5603 * We are not always called with irqs disabled - do that here,
5604 * and also avoid lockdep recursion:
5606 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
5607 int trylock, int read, int check,
5608 struct lockdep_map *nest_lock, unsigned long ip)
5610 unsigned long flags;
5612 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
5617 if (unlikely(!lockdep_enabled())) {
5618 /* XXX allow trylock from NMI ?!? */
5619 if (lockdep_nmi() && !trylock) {
5620 struct held_lock hlock;
5622 hlock.acquire_ip = ip;
5623 hlock.instance = lock;
5624 hlock.nest_lock = nest_lock;
5625 hlock.irq_context = 2; // XXX
5626 hlock.trylock = trylock;
5628 hlock.check = check;
5629 hlock.hardirqs_off = true;
5630 hlock.references = 0;
5632 verify_lock_unused(lock, &hlock, subclass);
5637 raw_local_irq_save(flags);
5640 lockdep_recursion_inc();
5641 __lock_acquire(lock, subclass, trylock, read, check,
5642 irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
5643 lockdep_recursion_finish();
5644 raw_local_irq_restore(flags);
5646 EXPORT_SYMBOL_GPL(lock_acquire);
5648 void lock_release(struct lockdep_map *lock, unsigned long ip)
5650 unsigned long flags;
5652 trace_lock_release(lock, ip);
5654 if (unlikely(!lockdep_enabled()))
5657 raw_local_irq_save(flags);
5660 lockdep_recursion_inc();
5661 if (__lock_release(lock, ip))
5662 check_chain_key(current);
5663 lockdep_recursion_finish();
5664 raw_local_irq_restore(flags);
5666 EXPORT_SYMBOL_GPL(lock_release);
5668 noinstr int lock_is_held_type(const struct lockdep_map *lock, int read)
5670 unsigned long flags;
5671 int ret = LOCK_STATE_NOT_HELD;
5674 * Avoid false negative lockdep_assert_held() and
5675 * lockdep_assert_not_held().
5677 if (unlikely(!lockdep_enabled()))
5678 return LOCK_STATE_UNKNOWN;
5680 raw_local_irq_save(flags);
5683 lockdep_recursion_inc();
5684 ret = __lock_is_held(lock, read);
5685 lockdep_recursion_finish();
5686 raw_local_irq_restore(flags);
5690 EXPORT_SYMBOL_GPL(lock_is_held_type);
5691 NOKPROBE_SYMBOL(lock_is_held_type);
5693 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
5695 struct pin_cookie cookie = NIL_COOKIE;
5696 unsigned long flags;
5698 if (unlikely(!lockdep_enabled()))
5701 raw_local_irq_save(flags);
5704 lockdep_recursion_inc();
5705 cookie = __lock_pin_lock(lock);
5706 lockdep_recursion_finish();
5707 raw_local_irq_restore(flags);
5711 EXPORT_SYMBOL_GPL(lock_pin_lock);
5713 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5715 unsigned long flags;
5717 if (unlikely(!lockdep_enabled()))
5720 raw_local_irq_save(flags);
5723 lockdep_recursion_inc();
5724 __lock_repin_lock(lock, cookie);
5725 lockdep_recursion_finish();
5726 raw_local_irq_restore(flags);
5728 EXPORT_SYMBOL_GPL(lock_repin_lock);
5730 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5732 unsigned long flags;
5734 if (unlikely(!lockdep_enabled()))
5737 raw_local_irq_save(flags);
5740 lockdep_recursion_inc();
5741 __lock_unpin_lock(lock, cookie);
5742 lockdep_recursion_finish();
5743 raw_local_irq_restore(flags);
5745 EXPORT_SYMBOL_GPL(lock_unpin_lock);
5747 #ifdef CONFIG_LOCK_STAT
5748 static void print_lock_contention_bug(struct task_struct *curr,
5749 struct lockdep_map *lock,
5752 if (!debug_locks_off())
5754 if (debug_locks_silent)
5758 pr_warn("=================================\n");
5759 pr_warn("WARNING: bad contention detected!\n");
5760 print_kernel_ident();
5761 pr_warn("---------------------------------\n");
5762 pr_warn("%s/%d is trying to contend lock (",
5763 curr->comm, task_pid_nr(curr));
5764 print_lockdep_cache(lock);
5766 print_ip_sym(KERN_WARNING, ip);
5767 pr_warn("but there are no locks held!\n");
5768 pr_warn("\nother info that might help us debug this:\n");
5769 lockdep_print_held_locks(curr);
5771 pr_warn("\nstack backtrace:\n");
5776 __lock_contended(struct lockdep_map *lock, unsigned long ip)
5778 struct task_struct *curr = current;
5779 struct held_lock *hlock;
5780 struct lock_class_stats *stats;
5782 int i, contention_point, contending_point;
5784 depth = curr->lockdep_depth;
5786 * Whee, we contended on this lock, except it seems we're not
5787 * actually trying to acquire anything much at all..
5789 if (DEBUG_LOCKS_WARN_ON(!depth))
5792 hlock = find_held_lock(curr, lock, depth, &i);
5794 print_lock_contention_bug(curr, lock, ip);
5798 if (hlock->instance != lock)
5801 hlock->waittime_stamp = lockstat_clock();
5803 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
5804 contending_point = lock_point(hlock_class(hlock)->contending_point,
5807 stats = get_lock_stats(hlock_class(hlock));
5808 if (contention_point < LOCKSTAT_POINTS)
5809 stats->contention_point[contention_point]++;
5810 if (contending_point < LOCKSTAT_POINTS)
5811 stats->contending_point[contending_point]++;
5812 if (lock->cpu != smp_processor_id())
5813 stats->bounces[bounce_contended + !!hlock->read]++;
5817 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
5819 struct task_struct *curr = current;
5820 struct held_lock *hlock;
5821 struct lock_class_stats *stats;
5823 u64 now, waittime = 0;
5826 depth = curr->lockdep_depth;
5828 * Yay, we acquired ownership of this lock we didn't try to
5829 * acquire, how the heck did that happen?
5831 if (DEBUG_LOCKS_WARN_ON(!depth))
5834 hlock = find_held_lock(curr, lock, depth, &i);
5836 print_lock_contention_bug(curr, lock, _RET_IP_);
5840 if (hlock->instance != lock)
5843 cpu = smp_processor_id();
5844 if (hlock->waittime_stamp) {
5845 now = lockstat_clock();
5846 waittime = now - hlock->waittime_stamp;
5847 hlock->holdtime_stamp = now;
5850 stats = get_lock_stats(hlock_class(hlock));
5853 lock_time_inc(&stats->read_waittime, waittime);
5855 lock_time_inc(&stats->write_waittime, waittime);
5857 if (lock->cpu != cpu)
5858 stats->bounces[bounce_acquired + !!hlock->read]++;
5864 void lock_contended(struct lockdep_map *lock, unsigned long ip)
5866 unsigned long flags;
5868 trace_lock_contended(lock, ip);
5870 if (unlikely(!lock_stat || !lockdep_enabled()))
5873 raw_local_irq_save(flags);
5875 lockdep_recursion_inc();
5876 __lock_contended(lock, ip);
5877 lockdep_recursion_finish();
5878 raw_local_irq_restore(flags);
5880 EXPORT_SYMBOL_GPL(lock_contended);
5882 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
5884 unsigned long flags;
5886 trace_lock_acquired(lock, ip);
5888 if (unlikely(!lock_stat || !lockdep_enabled()))
5891 raw_local_irq_save(flags);
5893 lockdep_recursion_inc();
5894 __lock_acquired(lock, ip);
5895 lockdep_recursion_finish();
5896 raw_local_irq_restore(flags);
5898 EXPORT_SYMBOL_GPL(lock_acquired);
5902 * Used by the testsuite, sanitize the validator state
5903 * after a simulated failure:
5906 void lockdep_reset(void)
5908 unsigned long flags;
5911 raw_local_irq_save(flags);
5912 lockdep_init_task(current);
5913 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
5914 nr_hardirq_chains = 0;
5915 nr_softirq_chains = 0;
5916 nr_process_chains = 0;
5918 for (i = 0; i < CHAINHASH_SIZE; i++)
5919 INIT_HLIST_HEAD(chainhash_table + i);
5920 raw_local_irq_restore(flags);
5923 /* Remove a class from a lock chain. Must be called with the graph lock held. */
5924 static void remove_class_from_lock_chain(struct pending_free *pf,
5925 struct lock_chain *chain,
5926 struct lock_class *class)
5928 #ifdef CONFIG_PROVE_LOCKING
5931 for (i = chain->base; i < chain->base + chain->depth; i++) {
5932 if (chain_hlock_class_idx(chain_hlocks[i]) != class - lock_classes)
5935 * Each lock class occurs at most once in a lock chain so once
5936 * we found a match we can break out of this loop.
5938 goto free_lock_chain;
5940 /* Since the chain has not been modified, return. */
5944 free_chain_hlocks(chain->base, chain->depth);
5945 /* Overwrite the chain key for concurrent RCU readers. */
5946 WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY);
5947 dec_chains(chain->irq_context);
5950 * Note: calling hlist_del_rcu() from inside a
5951 * hlist_for_each_entry_rcu() loop is safe.
5953 hlist_del_rcu(&chain->entry);
5954 __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
5955 nr_zapped_lock_chains++;
5959 /* Must be called with the graph lock held. */
5960 static void remove_class_from_lock_chains(struct pending_free *pf,
5961 struct lock_class *class)
5963 struct lock_chain *chain;
5964 struct hlist_head *head;
5967 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
5968 head = chainhash_table + i;
5969 hlist_for_each_entry_rcu(chain, head, entry) {
5970 remove_class_from_lock_chain(pf, chain, class);
5976 * Remove all references to a lock class. The caller must hold the graph lock.
5978 static void zap_class(struct pending_free *pf, struct lock_class *class)
5980 struct lock_list *entry;
5983 WARN_ON_ONCE(!class->key);
5986 * Remove all dependencies this lock is
5989 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
5990 entry = list_entries + i;
5991 if (entry->class != class && entry->links_to != class)
5993 __clear_bit(i, list_entries_in_use);
5995 list_del_rcu(&entry->entry);
5997 if (list_empty(&class->locks_after) &&
5998 list_empty(&class->locks_before)) {
5999 list_move_tail(&class->lock_entry, &pf->zapped);
6000 hlist_del_rcu(&class->hash_entry);
6001 WRITE_ONCE(class->key, NULL);
6002 WRITE_ONCE(class->name, NULL);
6004 __clear_bit(class - lock_classes, lock_classes_in_use);
6005 if (class - lock_classes == max_lock_class_idx)
6006 max_lock_class_idx--;
6008 WARN_ONCE(true, "%s() failed for class %s\n", __func__,
6012 remove_class_from_lock_chains(pf, class);
6013 nr_zapped_classes++;
6016 static void reinit_class(struct lock_class *class)
6018 WARN_ON_ONCE(!class->lock_entry.next);
6019 WARN_ON_ONCE(!list_empty(&class->locks_after));
6020 WARN_ON_ONCE(!list_empty(&class->locks_before));
6021 memset_startat(class, 0, key);
6022 WARN_ON_ONCE(!class->lock_entry.next);
6023 WARN_ON_ONCE(!list_empty(&class->locks_after));
6024 WARN_ON_ONCE(!list_empty(&class->locks_before));
6027 static inline int within(const void *addr, void *start, unsigned long size)
6029 return addr >= start && addr < start + size;
6032 static bool inside_selftest(void)
6034 return current == lockdep_selftest_task_struct;
6037 /* The caller must hold the graph lock. */
6038 static struct pending_free *get_pending_free(void)
6040 return delayed_free.pf + delayed_free.index;
6043 static void free_zapped_rcu(struct rcu_head *cb);
6046 * Schedule an RCU callback if no RCU callback is pending. Must be called with
6047 * the graph lock held.
6049 static void call_rcu_zapped(struct pending_free *pf)
6051 WARN_ON_ONCE(inside_selftest());
6053 if (list_empty(&pf->zapped))
6056 if (delayed_free.scheduled)
6059 delayed_free.scheduled = true;
6061 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
6062 delayed_free.index ^= 1;
6064 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
6067 /* The caller must hold the graph lock. May be called from RCU context. */
6068 static void __free_zapped_classes(struct pending_free *pf)
6070 struct lock_class *class;
6072 check_data_structures();
6074 list_for_each_entry(class, &pf->zapped, lock_entry)
6075 reinit_class(class);
6077 list_splice_init(&pf->zapped, &free_lock_classes);
6079 #ifdef CONFIG_PROVE_LOCKING
6080 bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
6081 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
6082 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
6086 static void free_zapped_rcu(struct rcu_head *ch)
6088 struct pending_free *pf;
6089 unsigned long flags;
6091 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
6094 raw_local_irq_save(flags);
6098 pf = delayed_free.pf + (delayed_free.index ^ 1);
6099 __free_zapped_classes(pf);
6100 delayed_free.scheduled = false;
6103 * If there's anything on the open list, close and start a new callback.
6105 call_rcu_zapped(delayed_free.pf + delayed_free.index);
6108 raw_local_irq_restore(flags);
6112 * Remove all lock classes from the class hash table and from the
6113 * all_lock_classes list whose key or name is in the address range [start,
6114 * start + size). Move these lock classes to the zapped_classes list. Must
6115 * be called with the graph lock held.
6117 static void __lockdep_free_key_range(struct pending_free *pf, void *start,
6120 struct lock_class *class;
6121 struct hlist_head *head;
6124 /* Unhash all classes that were created by a module. */
6125 for (i = 0; i < CLASSHASH_SIZE; i++) {
6126 head = classhash_table + i;
6127 hlist_for_each_entry_rcu(class, head, hash_entry) {
6128 if (!within(class->key, start, size) &&
6129 !within(class->name, start, size))
6131 zap_class(pf, class);
6137 * Used in module.c to remove lock classes from memory that is going to be
6138 * freed; and possibly re-used by other modules.
6140 * We will have had one synchronize_rcu() before getting here, so we're
6141 * guaranteed nobody will look up these exact classes -- they're properly dead
6142 * but still allocated.
6144 static void lockdep_free_key_range_reg(void *start, unsigned long size)
6146 struct pending_free *pf;
6147 unsigned long flags;
6149 init_data_structures_once();
6151 raw_local_irq_save(flags);
6153 pf = get_pending_free();
6154 __lockdep_free_key_range(pf, start, size);
6155 call_rcu_zapped(pf);
6157 raw_local_irq_restore(flags);
6160 * Wait for any possible iterators from look_up_lock_class() to pass
6161 * before continuing to free the memory they refer to.
6167 * Free all lockdep keys in the range [start, start+size). Does not sleep.
6168 * Ignores debug_locks. Must only be used by the lockdep selftests.
6170 static void lockdep_free_key_range_imm(void *start, unsigned long size)
6172 struct pending_free *pf = delayed_free.pf;
6173 unsigned long flags;
6175 init_data_structures_once();
6177 raw_local_irq_save(flags);
6179 __lockdep_free_key_range(pf, start, size);
6180 __free_zapped_classes(pf);
6182 raw_local_irq_restore(flags);
6185 void lockdep_free_key_range(void *start, unsigned long size)
6187 init_data_structures_once();
6189 if (inside_selftest())
6190 lockdep_free_key_range_imm(start, size);
6192 lockdep_free_key_range_reg(start, size);
6196 * Check whether any element of the @lock->class_cache[] array refers to a
6197 * registered lock class. The caller must hold either the graph lock or the
6200 static bool lock_class_cache_is_registered(struct lockdep_map *lock)
6202 struct lock_class *class;
6203 struct hlist_head *head;
6206 for (i = 0; i < CLASSHASH_SIZE; i++) {
6207 head = classhash_table + i;
6208 hlist_for_each_entry_rcu(class, head, hash_entry) {
6209 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
6210 if (lock->class_cache[j] == class)
6217 /* The caller must hold the graph lock. Does not sleep. */
6218 static void __lockdep_reset_lock(struct pending_free *pf,
6219 struct lockdep_map *lock)
6221 struct lock_class *class;
6225 * Remove all classes this lock might have:
6227 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
6229 * If the class exists we look it up and zap it:
6231 class = look_up_lock_class(lock, j);
6233 zap_class(pf, class);
6236 * Debug check: in the end all mapped classes should
6239 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
6244 * Remove all information lockdep has about a lock if debug_locks == 1. Free
6245 * released data structures from RCU context.
6247 static void lockdep_reset_lock_reg(struct lockdep_map *lock)
6249 struct pending_free *pf;
6250 unsigned long flags;
6253 raw_local_irq_save(flags);
6254 locked = graph_lock();
6258 pf = get_pending_free();
6259 __lockdep_reset_lock(pf, lock);
6260 call_rcu_zapped(pf);
6264 raw_local_irq_restore(flags);
6268 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
6269 * lockdep selftests.
6271 static void lockdep_reset_lock_imm(struct lockdep_map *lock)
6273 struct pending_free *pf = delayed_free.pf;
6274 unsigned long flags;
6276 raw_local_irq_save(flags);
6278 __lockdep_reset_lock(pf, lock);
6279 __free_zapped_classes(pf);
6281 raw_local_irq_restore(flags);
6284 void lockdep_reset_lock(struct lockdep_map *lock)
6286 init_data_structures_once();
6288 if (inside_selftest())
6289 lockdep_reset_lock_imm(lock);
6291 lockdep_reset_lock_reg(lock);
6295 * Unregister a dynamically allocated key.
6297 * Unlike lockdep_register_key(), a search is always done to find a matching
6298 * key irrespective of debug_locks to avoid potential invalid access to freed
6299 * memory in lock_class entry.
6301 void lockdep_unregister_key(struct lock_class_key *key)
6303 struct hlist_head *hash_head = keyhashentry(key);
6304 struct lock_class_key *k;
6305 struct pending_free *pf;
6306 unsigned long flags;
6311 if (WARN_ON_ONCE(static_obj(key)))
6314 raw_local_irq_save(flags);
6317 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
6319 hlist_del_rcu(&k->hash_entry);
6324 WARN_ON_ONCE(!found && debug_locks);
6326 pf = get_pending_free();
6327 __lockdep_free_key_range(pf, key, 1);
6328 call_rcu_zapped(pf);
6331 raw_local_irq_restore(flags);
6333 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
6336 EXPORT_SYMBOL_GPL(lockdep_unregister_key);
6338 void __init lockdep_init(void)
6340 printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
6342 printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
6343 printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
6344 printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
6345 printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
6346 printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
6347 printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
6348 printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
6350 printk(" memory used by lock dependency info: %zu kB\n",
6351 (sizeof(lock_classes) +
6352 sizeof(lock_classes_in_use) +
6353 sizeof(classhash_table) +
6354 sizeof(list_entries) +
6355 sizeof(list_entries_in_use) +
6356 sizeof(chainhash_table) +
6357 sizeof(delayed_free)
6358 #ifdef CONFIG_PROVE_LOCKING
6360 + sizeof(lock_chains)
6361 + sizeof(lock_chains_in_use)
6362 + sizeof(chain_hlocks)
6367 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
6368 printk(" memory used for stack traces: %zu kB\n",
6369 (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
6373 printk(" per task-struct memory footprint: %zu bytes\n",
6374 sizeof(((struct task_struct *)NULL)->held_locks));
6378 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
6379 const void *mem_to, struct held_lock *hlock)
6381 if (!debug_locks_off())
6383 if (debug_locks_silent)
6387 pr_warn("=========================\n");
6388 pr_warn("WARNING: held lock freed!\n");
6389 print_kernel_ident();
6390 pr_warn("-------------------------\n");
6391 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
6392 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
6394 lockdep_print_held_locks(curr);
6396 pr_warn("\nstack backtrace:\n");
6400 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
6401 const void* lock_from, unsigned long lock_len)
6403 return lock_from + lock_len <= mem_from ||
6404 mem_from + mem_len <= lock_from;
6408 * Called when kernel memory is freed (or unmapped), or if a lock
6409 * is destroyed or reinitialized - this code checks whether there is
6410 * any held lock in the memory range of <from> to <to>:
6412 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
6414 struct task_struct *curr = current;
6415 struct held_lock *hlock;
6416 unsigned long flags;
6419 if (unlikely(!debug_locks))
6422 raw_local_irq_save(flags);
6423 for (i = 0; i < curr->lockdep_depth; i++) {
6424 hlock = curr->held_locks + i;
6426 if (not_in_range(mem_from, mem_len, hlock->instance,
6427 sizeof(*hlock->instance)))
6430 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
6433 raw_local_irq_restore(flags);
6435 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
6437 static void print_held_locks_bug(void)
6439 if (!debug_locks_off())
6441 if (debug_locks_silent)
6445 pr_warn("====================================\n");
6446 pr_warn("WARNING: %s/%d still has locks held!\n",
6447 current->comm, task_pid_nr(current));
6448 print_kernel_ident();
6449 pr_warn("------------------------------------\n");
6450 lockdep_print_held_locks(current);
6451 pr_warn("\nstack backtrace:\n");
6455 void debug_check_no_locks_held(void)
6457 if (unlikely(current->lockdep_depth > 0))
6458 print_held_locks_bug();
6460 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
6463 void debug_show_all_locks(void)
6465 struct task_struct *g, *p;
6467 if (unlikely(!debug_locks)) {
6468 pr_warn("INFO: lockdep is turned off.\n");
6471 pr_warn("\nShowing all locks held in the system:\n");
6474 for_each_process_thread(g, p) {
6475 if (!p->lockdep_depth)
6477 lockdep_print_held_locks(p);
6478 touch_nmi_watchdog();
6479 touch_all_softlockup_watchdogs();
6484 pr_warn("=============================================\n\n");
6486 EXPORT_SYMBOL_GPL(debug_show_all_locks);
6490 * Careful: only use this function if you are sure that
6491 * the task cannot run in parallel!
6493 void debug_show_held_locks(struct task_struct *task)
6495 if (unlikely(!debug_locks)) {
6496 printk("INFO: lockdep is turned off.\n");
6499 lockdep_print_held_locks(task);
6501 EXPORT_SYMBOL_GPL(debug_show_held_locks);
6503 asmlinkage __visible void lockdep_sys_exit(void)
6505 struct task_struct *curr = current;
6507 if (unlikely(curr->lockdep_depth)) {
6508 if (!debug_locks_off())
6511 pr_warn("================================================\n");
6512 pr_warn("WARNING: lock held when returning to user space!\n");
6513 print_kernel_ident();
6514 pr_warn("------------------------------------------------\n");
6515 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
6516 curr->comm, curr->pid);
6517 lockdep_print_held_locks(curr);
6521 * The lock history for each syscall should be independent. So wipe the
6522 * slate clean on return to userspace.
6524 lockdep_invariant_state(false);
6527 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
6529 struct task_struct *curr = current;
6530 int dl = READ_ONCE(debug_locks);
6532 /* Note: the following can be executed concurrently, so be careful. */
6534 pr_warn("=============================\n");
6535 pr_warn("WARNING: suspicious RCU usage\n");
6536 print_kernel_ident();
6537 pr_warn("-----------------------------\n");
6538 pr_warn("%s:%d %s!\n", file, line, s);
6539 pr_warn("\nother info that might help us debug this:\n\n");
6540 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n%s",
6541 !rcu_lockdep_current_cpu_online()
6542 ? "RCU used illegally from offline CPU!\n"
6544 rcu_scheduler_active, dl,
6545 dl ? "" : "Possible false positive due to lockdep disabling via debug_locks = 0\n");
6548 * If a CPU is in the RCU-free window in idle (ie: in the section
6549 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
6550 * considers that CPU to be in an "extended quiescent state",
6551 * which means that RCU will be completely ignoring that CPU.
6552 * Therefore, rcu_read_lock() and friends have absolutely no
6553 * effect on a CPU running in that state. In other words, even if
6554 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
6555 * delete data structures out from under it. RCU really has no
6556 * choice here: we need to keep an RCU-free window in idle where
6557 * the CPU may possibly enter into low power mode. This way we can
6558 * notice an extended quiescent state to other CPUs that started a grace
6559 * period. Otherwise we would delay any grace period as long as we run
6562 * So complain bitterly if someone does call rcu_read_lock(),
6563 * rcu_read_lock_bh() and so on from extended quiescent states.
6565 if (!rcu_is_watching())
6566 pr_warn("RCU used illegally from extended quiescent state!\n");
6568 lockdep_print_held_locks(curr);
6569 pr_warn("\nstack backtrace:\n");
6572 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);