1 // SPDX-License-Identifier: GPL-2.0-only
5 * Runtime locking correctness validator
7 * Started by Ingo Molnar:
9 * Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
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>
58 #include <asm/sections.h>
60 #include "lockdep_internals.h"
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/lock.h>
65 #ifdef CONFIG_PROVE_LOCKING
66 int prove_locking = 1;
67 module_param(prove_locking, int, 0644);
69 #define prove_locking 0
72 #ifdef CONFIG_LOCK_STAT
74 module_param(lock_stat, int, 0644);
80 * lockdep_lock: protects the lockdep graph, the hashes and the
81 * class/list/hash allocators.
83 * This is one of the rare exceptions where it's justified
84 * to use a raw spinlock - we really dont want the spinlock
85 * code to recurse back into the lockdep code...
87 static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
88 static struct task_struct *__owner;
90 static inline void lockdep_lock(void)
92 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
94 arch_spin_lock(&__lock);
96 current->lockdep_recursion++;
99 static inline void lockdep_unlock(void)
101 if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current))
104 current->lockdep_recursion--;
106 arch_spin_unlock(&__lock);
109 static inline bool lockdep_assert_locked(void)
111 return DEBUG_LOCKS_WARN_ON(__owner != current);
114 static struct task_struct *lockdep_selftest_task_struct;
117 static int graph_lock(void)
121 * Make sure that if another CPU detected a bug while
122 * walking the graph we dont change it (while the other
123 * CPU is busy printing out stuff with the graph lock
133 static inline void graph_unlock(void)
139 * Turn lock debugging off and return with 0 if it was off already,
140 * and also release the graph lock:
142 static inline int debug_locks_off_graph_unlock(void)
144 int ret = debug_locks_off();
151 unsigned long nr_list_entries;
152 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
153 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
156 * All data structures here are protected by the global debug_lock.
158 * nr_lock_classes is the number of elements of lock_classes[] that is
161 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
162 #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
163 static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
164 unsigned long nr_lock_classes;
165 unsigned long nr_zapped_classes;
166 #ifndef CONFIG_DEBUG_LOCKDEP
169 struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
170 static DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
172 static inline struct lock_class *hlock_class(struct held_lock *hlock)
174 unsigned int class_idx = hlock->class_idx;
176 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
179 if (!test_bit(class_idx, lock_classes_in_use)) {
181 * Someone passed in garbage, we give up.
183 DEBUG_LOCKS_WARN_ON(1);
188 * At this point, if the passed hlock->class_idx is still garbage,
189 * we just have to live with it
191 return lock_classes + class_idx;
194 #ifdef CONFIG_LOCK_STAT
195 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
197 static inline u64 lockstat_clock(void)
199 return local_clock();
202 static int lock_point(unsigned long points[], unsigned long ip)
206 for (i = 0; i < LOCKSTAT_POINTS; i++) {
207 if (points[i] == 0) {
218 static void lock_time_inc(struct lock_time *lt, u64 time)
223 if (time < lt->min || !lt->nr)
230 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
235 if (src->max > dst->max)
238 if (src->min < dst->min || !dst->nr)
241 dst->total += src->total;
245 struct lock_class_stats lock_stats(struct lock_class *class)
247 struct lock_class_stats stats;
250 memset(&stats, 0, sizeof(struct lock_class_stats));
251 for_each_possible_cpu(cpu) {
252 struct lock_class_stats *pcs =
253 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
255 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
256 stats.contention_point[i] += pcs->contention_point[i];
258 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
259 stats.contending_point[i] += pcs->contending_point[i];
261 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
262 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
264 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
265 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
267 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
268 stats.bounces[i] += pcs->bounces[i];
274 void clear_lock_stats(struct lock_class *class)
278 for_each_possible_cpu(cpu) {
279 struct lock_class_stats *cpu_stats =
280 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
282 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
284 memset(class->contention_point, 0, sizeof(class->contention_point));
285 memset(class->contending_point, 0, sizeof(class->contending_point));
288 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
290 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
293 static void lock_release_holdtime(struct held_lock *hlock)
295 struct lock_class_stats *stats;
301 holdtime = lockstat_clock() - hlock->holdtime_stamp;
303 stats = get_lock_stats(hlock_class(hlock));
305 lock_time_inc(&stats->read_holdtime, holdtime);
307 lock_time_inc(&stats->write_holdtime, holdtime);
310 static inline void lock_release_holdtime(struct held_lock *hlock)
316 * We keep a global list of all lock classes. The list is only accessed with
317 * the lockdep spinlock lock held. free_lock_classes is a list with free
318 * elements. These elements are linked together by the lock_entry member in
321 LIST_HEAD(all_lock_classes);
322 static LIST_HEAD(free_lock_classes);
325 * struct pending_free - information about data structures about to be freed
326 * @zapped: Head of a list with struct lock_class elements.
327 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
328 * are about to be freed.
330 struct pending_free {
331 struct list_head zapped;
332 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
336 * struct delayed_free - data structures used for delayed freeing
338 * A data structure for delayed freeing of data structures that may be
339 * accessed by RCU readers at the time these were freed.
341 * @rcu_head: Used to schedule an RCU callback for freeing data structures.
342 * @index: Index of @pf to which freed data structures are added.
343 * @scheduled: Whether or not an RCU callback has been scheduled.
344 * @pf: Array with information about data structures about to be freed.
346 static struct delayed_free {
347 struct rcu_head rcu_head;
350 struct pending_free pf[2];
354 * The lockdep classes are in a hash-table as well, for fast lookup:
356 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
357 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
358 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
359 #define classhashentry(key) (classhash_table + __classhashfn((key)))
361 static struct hlist_head classhash_table[CLASSHASH_SIZE];
364 * We put the lock dependency chains into a hash-table as well, to cache
367 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
368 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
369 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
370 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
372 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
375 * The hash key of the lock dependency chains is a hash itself too:
376 * it's a hash of all locks taken up to that lock, including that lock.
377 * It's a 64-bit hash, because it's important for the keys to be
380 static inline u64 iterate_chain_key(u64 key, u32 idx)
382 u32 k0 = key, k1 = key >> 32;
384 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
386 return k0 | (u64)k1 << 32;
389 void lockdep_init_task(struct task_struct *task)
391 task->lockdep_depth = 0; /* no locks held yet */
392 task->curr_chain_key = INITIAL_CHAIN_KEY;
393 task->lockdep_recursion = 0;
396 static __always_inline void lockdep_recursion_finish(void)
398 if (WARN_ON_ONCE((--current->lockdep_recursion) & LOCKDEP_RECURSION_MASK))
399 current->lockdep_recursion = 0;
402 void lockdep_set_selftest_task(struct task_struct *task)
404 lockdep_selftest_task_struct = task;
408 * Debugging switches:
412 #define VERY_VERBOSE 0
415 # define HARDIRQ_VERBOSE 1
416 # define SOFTIRQ_VERBOSE 1
418 # define HARDIRQ_VERBOSE 0
419 # define SOFTIRQ_VERBOSE 0
422 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
424 * Quick filtering for interesting events:
426 static int class_filter(struct lock_class *class)
430 if (class->name_version == 1 &&
431 !strcmp(class->name, "lockname"))
433 if (class->name_version == 1 &&
434 !strcmp(class->name, "&struct->lockfield"))
437 /* Filter everything else. 1 would be to allow everything else */
442 static int verbose(struct lock_class *class)
445 return class_filter(class);
450 static void print_lockdep_off(const char *bug_msg)
452 printk(KERN_DEBUG "%s\n", bug_msg);
453 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
454 #ifdef CONFIG_LOCK_STAT
455 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
459 unsigned long nr_stack_trace_entries;
461 #ifdef CONFIG_PROVE_LOCKING
463 * struct lock_trace - single stack backtrace
464 * @hash_entry: Entry in a stack_trace_hash[] list.
465 * @hash: jhash() of @entries.
466 * @nr_entries: Number of entries in @entries.
467 * @entries: Actual stack backtrace.
470 struct hlist_node hash_entry;
473 unsigned long entries[] __aligned(sizeof(unsigned long));
475 #define LOCK_TRACE_SIZE_IN_LONGS \
476 (sizeof(struct lock_trace) / sizeof(unsigned long))
478 * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock.
480 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
481 static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE];
483 static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2)
485 return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries &&
486 memcmp(t1->entries, t2->entries,
487 t1->nr_entries * sizeof(t1->entries[0])) == 0;
490 static struct lock_trace *save_trace(void)
492 struct lock_trace *trace, *t2;
493 struct hlist_head *hash_head;
497 BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE);
498 BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES);
500 trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries);
501 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries -
502 LOCK_TRACE_SIZE_IN_LONGS;
504 if (max_entries <= 0) {
505 if (!debug_locks_off_graph_unlock())
508 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
513 trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3);
515 hash = jhash(trace->entries, trace->nr_entries *
516 sizeof(trace->entries[0]), 0);
518 hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1));
519 hlist_for_each_entry(t2, hash_head, hash_entry) {
520 if (traces_identical(trace, t2))
523 nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries;
524 hlist_add_head(&trace->hash_entry, hash_head);
529 /* Return the number of stack traces in the stack_trace[] array. */
530 u64 lockdep_stack_trace_count(void)
532 struct lock_trace *trace;
536 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) {
537 hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) {
545 /* Return the number of stack hash chains that have at least one stack trace. */
546 u64 lockdep_stack_hash_count(void)
551 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++)
552 if (!hlist_empty(&stack_trace_hash[i]))
559 unsigned int nr_hardirq_chains;
560 unsigned int nr_softirq_chains;
561 unsigned int nr_process_chains;
562 unsigned int max_lockdep_depth;
564 #ifdef CONFIG_DEBUG_LOCKDEP
566 * Various lockdep statistics:
568 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
571 #ifdef CONFIG_PROVE_LOCKING
576 #define __USAGE(__STATE) \
577 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
578 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
579 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
580 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
582 static const char *usage_str[] =
584 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
585 #include "lockdep_states.h"
587 [LOCK_USED] = "INITIAL USE",
588 [LOCK_USED_READ] = "INITIAL READ USE",
589 /* abused as string storage for verify_lock_unused() */
590 [LOCK_USAGE_STATES] = "IN-NMI",
594 const char *__get_key_name(const struct lockdep_subclass_key *key, char *str)
596 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
599 static inline unsigned long lock_flag(enum lock_usage_bit bit)
604 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
607 * The usage character defaults to '.' (i.e., irqs disabled and not in
608 * irq context), which is the safest usage category.
613 * The order of the following usage checks matters, which will
614 * result in the outcome character as follows:
616 * - '+': irq is enabled and not in irq context
617 * - '-': in irq context and irq is disabled
618 * - '?': in irq context and irq is enabled
620 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
622 if (class->usage_mask & lock_flag(bit))
624 } else if (class->usage_mask & lock_flag(bit))
630 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
634 #define LOCKDEP_STATE(__STATE) \
635 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
636 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
637 #include "lockdep_states.h"
643 static void __print_lock_name(struct lock_class *class)
645 char str[KSYM_NAME_LEN];
650 name = __get_key_name(class->key, str);
651 printk(KERN_CONT "%s", name);
653 printk(KERN_CONT "%s", name);
654 if (class->name_version > 1)
655 printk(KERN_CONT "#%d", class->name_version);
657 printk(KERN_CONT "/%d", class->subclass);
661 static void print_lock_name(struct lock_class *class)
663 char usage[LOCK_USAGE_CHARS];
665 get_usage_chars(class, usage);
667 printk(KERN_CONT " (");
668 __print_lock_name(class);
669 printk(KERN_CONT "){%s}-{%hd:%hd}", usage,
670 class->wait_type_outer ?: class->wait_type_inner,
671 class->wait_type_inner);
674 static void print_lockdep_cache(struct lockdep_map *lock)
677 char str[KSYM_NAME_LEN];
681 name = __get_key_name(lock->key->subkeys, str);
683 printk(KERN_CONT "%s", name);
686 static void print_lock(struct held_lock *hlock)
689 * We can be called locklessly through debug_show_all_locks() so be
690 * extra careful, the hlock might have been released and cleared.
692 * If this indeed happens, lets pretend it does not hurt to continue
693 * to print the lock unless the hlock class_idx does not point to a
694 * registered class. The rationale here is: since we don't attempt
695 * to distinguish whether we are in this situation, if it just
696 * happened we can't count on class_idx to tell either.
698 struct lock_class *lock = hlock_class(hlock);
701 printk(KERN_CONT "<RELEASED>\n");
705 printk(KERN_CONT "%px", hlock->instance);
706 print_lock_name(lock);
707 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
710 static void lockdep_print_held_locks(struct task_struct *p)
712 int i, depth = READ_ONCE(p->lockdep_depth);
715 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
717 printk("%d lock%s held by %s/%d:\n", depth,
718 depth > 1 ? "s" : "", p->comm, task_pid_nr(p));
720 * It's not reliable to print a task's held locks if it's not sleeping
721 * and it's not the current task.
723 if (p->state == TASK_RUNNING && p != current)
725 for (i = 0; i < depth; i++) {
727 print_lock(p->held_locks + i);
731 static void print_kernel_ident(void)
733 printk("%s %.*s %s\n", init_utsname()->release,
734 (int)strcspn(init_utsname()->version, " "),
735 init_utsname()->version,
739 static int very_verbose(struct lock_class *class)
742 return class_filter(class);
748 * Is this the address of a static object:
751 static int static_obj(const void *obj)
753 unsigned long start = (unsigned long) &_stext,
754 end = (unsigned long) &_end,
755 addr = (unsigned long) obj;
757 if (arch_is_kernel_initmem_freed(addr))
763 if ((addr >= start) && (addr < end))
766 if (arch_is_kernel_data(addr))
770 * in-kernel percpu var?
772 if (is_kernel_percpu_address(addr))
776 * module static or percpu var?
778 return is_module_address(addr) || is_module_percpu_address(addr);
783 * To make lock name printouts unique, we calculate a unique
784 * class->name_version generation counter. The caller must hold the graph
787 static int count_matching_names(struct lock_class *new_class)
789 struct lock_class *class;
792 if (!new_class->name)
795 list_for_each_entry(class, &all_lock_classes, lock_entry) {
796 if (new_class->key - new_class->subclass == class->key)
797 return class->name_version;
798 if (class->name && !strcmp(class->name, new_class->name))
799 count = max(count, class->name_version);
805 /* used from NMI context -- must be lockless */
806 static __always_inline struct lock_class *
807 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
809 struct lockdep_subclass_key *key;
810 struct hlist_head *hash_head;
811 struct lock_class *class;
813 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
816 "BUG: looking up invalid subclass: %u\n", subclass);
818 "turning off the locking correctness validator.\n");
824 * If it is not initialised then it has never been locked,
825 * so it won't be present in the hash table.
827 if (unlikely(!lock->key))
831 * NOTE: the class-key must be unique. For dynamic locks, a static
832 * lock_class_key variable is passed in through the mutex_init()
833 * (or spin_lock_init()) call - which acts as the key. For static
834 * locks we use the lock object itself as the key.
836 BUILD_BUG_ON(sizeof(struct lock_class_key) >
837 sizeof(struct lockdep_map));
839 key = lock->key->subkeys + subclass;
841 hash_head = classhashentry(key);
844 * We do an RCU walk of the hash, see lockdep_free_key_range().
846 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
849 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
850 if (class->key == key) {
852 * Huh! same key, different name? Did someone trample
853 * on some memory? We're most confused.
855 WARN_ON_ONCE(class->name != lock->name &&
856 lock->key != &__lockdep_no_validate__);
865 * Static locks do not have their class-keys yet - for them the key is
866 * the lock object itself. If the lock is in the per cpu area, the
867 * canonical address of the lock (per cpu offset removed) is used.
869 static bool assign_lock_key(struct lockdep_map *lock)
871 unsigned long can_addr, addr = (unsigned long)lock;
875 * lockdep_free_key_range() assumes that struct lock_class_key
876 * objects do not overlap. Since we use the address of lock
877 * objects as class key for static objects, check whether the
878 * size of lock_class_key objects does not exceed the size of
879 * the smallest lock object.
881 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
884 if (__is_kernel_percpu_address(addr, &can_addr))
885 lock->key = (void *)can_addr;
886 else if (__is_module_percpu_address(addr, &can_addr))
887 lock->key = (void *)can_addr;
888 else if (static_obj(lock))
889 lock->key = (void *)lock;
891 /* Debug-check: all keys must be persistent! */
893 pr_err("INFO: trying to register non-static key.\n");
894 pr_err("the code is fine but needs lockdep annotation.\n");
895 pr_err("turning off the locking correctness validator.\n");
903 #ifdef CONFIG_DEBUG_LOCKDEP
905 /* Check whether element @e occurs in list @h */
906 static bool in_list(struct list_head *e, struct list_head *h)
910 list_for_each(f, h) {
919 * Check whether entry @e occurs in any of the locks_after or locks_before
922 static bool in_any_class_list(struct list_head *e)
924 struct lock_class *class;
927 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
928 class = &lock_classes[i];
929 if (in_list(e, &class->locks_after) ||
930 in_list(e, &class->locks_before))
936 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
940 list_for_each_entry(e, h, entry) {
941 if (e->links_to != c) {
942 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
944 (unsigned long)(e - list_entries),
945 e->links_to && e->links_to->name ?
946 e->links_to->name : "(?)",
947 e->class && e->class->name ? e->class->name :
955 #ifdef CONFIG_PROVE_LOCKING
956 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
959 static bool check_lock_chain_key(struct lock_chain *chain)
961 #ifdef CONFIG_PROVE_LOCKING
962 u64 chain_key = INITIAL_CHAIN_KEY;
965 for (i = chain->base; i < chain->base + chain->depth; i++)
966 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
968 * The 'unsigned long long' casts avoid that a compiler warning
969 * is reported when building tools/lib/lockdep.
971 if (chain->chain_key != chain_key) {
972 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
973 (unsigned long long)(chain - lock_chains),
974 (unsigned long long)chain->chain_key,
975 (unsigned long long)chain_key);
982 static bool in_any_zapped_class_list(struct lock_class *class)
984 struct pending_free *pf;
987 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
988 if (in_list(&class->lock_entry, &pf->zapped))
995 static bool __check_data_structures(void)
997 struct lock_class *class;
998 struct lock_chain *chain;
999 struct hlist_head *head;
1000 struct lock_list *e;
1003 /* Check whether all classes occur in a lock list. */
1004 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1005 class = &lock_classes[i];
1006 if (!in_list(&class->lock_entry, &all_lock_classes) &&
1007 !in_list(&class->lock_entry, &free_lock_classes) &&
1008 !in_any_zapped_class_list(class)) {
1009 printk(KERN_INFO "class %px/%s is not in any class list\n",
1010 class, class->name ? : "(?)");
1015 /* Check whether all classes have valid lock lists. */
1016 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1017 class = &lock_classes[i];
1018 if (!class_lock_list_valid(class, &class->locks_before))
1020 if (!class_lock_list_valid(class, &class->locks_after))
1024 /* Check the chain_key of all lock chains. */
1025 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
1026 head = chainhash_table + i;
1027 hlist_for_each_entry_rcu(chain, head, entry) {
1028 if (!check_lock_chain_key(chain))
1034 * Check whether all list entries that are in use occur in a class
1037 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1038 e = list_entries + i;
1039 if (!in_any_class_list(&e->entry)) {
1040 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
1041 (unsigned int)(e - list_entries),
1042 e->class->name ? : "(?)",
1043 e->links_to->name ? : "(?)");
1049 * Check whether all list entries that are not in use do not occur in
1050 * a class lock list.
1052 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1053 e = list_entries + i;
1054 if (in_any_class_list(&e->entry)) {
1055 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
1056 (unsigned int)(e - list_entries),
1057 e->class && e->class->name ? e->class->name :
1059 e->links_to && e->links_to->name ?
1060 e->links_to->name : "(?)");
1068 int check_consistency = 0;
1069 module_param(check_consistency, int, 0644);
1071 static void check_data_structures(void)
1073 static bool once = false;
1075 if (check_consistency && !once) {
1076 if (!__check_data_structures()) {
1083 #else /* CONFIG_DEBUG_LOCKDEP */
1085 static inline void check_data_structures(void) { }
1087 #endif /* CONFIG_DEBUG_LOCKDEP */
1089 static void init_chain_block_buckets(void);
1092 * Initialize the lock_classes[] array elements, the free_lock_classes list
1093 * and also the delayed_free structure.
1095 static void init_data_structures_once(void)
1097 static bool __read_mostly ds_initialized, rcu_head_initialized;
1100 if (likely(rcu_head_initialized))
1103 if (system_state >= SYSTEM_SCHEDULING) {
1104 init_rcu_head(&delayed_free.rcu_head);
1105 rcu_head_initialized = true;
1111 ds_initialized = true;
1113 INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
1114 INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
1116 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1117 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
1118 INIT_LIST_HEAD(&lock_classes[i].locks_after);
1119 INIT_LIST_HEAD(&lock_classes[i].locks_before);
1121 init_chain_block_buckets();
1124 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
1126 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
1128 return lock_keys_hash + hash;
1131 /* Register a dynamically allocated key. */
1132 void lockdep_register_key(struct lock_class_key *key)
1134 struct hlist_head *hash_head;
1135 struct lock_class_key *k;
1136 unsigned long flags;
1138 if (WARN_ON_ONCE(static_obj(key)))
1140 hash_head = keyhashentry(key);
1142 raw_local_irq_save(flags);
1145 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1146 if (WARN_ON_ONCE(k == key))
1149 hlist_add_head_rcu(&key->hash_entry, hash_head);
1153 raw_local_irq_restore(flags);
1155 EXPORT_SYMBOL_GPL(lockdep_register_key);
1157 /* Check whether a key has been registered as a dynamic key. */
1158 static bool is_dynamic_key(const struct lock_class_key *key)
1160 struct hlist_head *hash_head;
1161 struct lock_class_key *k;
1164 if (WARN_ON_ONCE(static_obj(key)))
1168 * If lock debugging is disabled lock_keys_hash[] may contain
1169 * pointers to memory that has already been freed. Avoid triggering
1170 * a use-after-free in that case by returning early.
1175 hash_head = keyhashentry(key);
1178 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1190 * Register a lock's class in the hash-table, if the class is not present
1191 * yet. Otherwise we look it up. We cache the result in the lock object
1192 * itself, so actual lookup of the hash should be once per lock object.
1194 static struct lock_class *
1195 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1197 struct lockdep_subclass_key *key;
1198 struct hlist_head *hash_head;
1199 struct lock_class *class;
1201 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1203 class = look_up_lock_class(lock, subclass);
1205 goto out_set_class_cache;
1208 if (!assign_lock_key(lock))
1210 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
1214 key = lock->key->subkeys + subclass;
1215 hash_head = classhashentry(key);
1217 if (!graph_lock()) {
1221 * We have to do the hash-walk again, to avoid races
1224 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
1225 if (class->key == key)
1226 goto out_unlock_set;
1229 init_data_structures_once();
1231 /* Allocate a new lock class and add it to the hash. */
1232 class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
1235 if (!debug_locks_off_graph_unlock()) {
1239 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
1244 __set_bit(class - lock_classes, lock_classes_in_use);
1245 debug_atomic_inc(nr_unused_locks);
1247 class->name = lock->name;
1248 class->subclass = subclass;
1249 WARN_ON_ONCE(!list_empty(&class->locks_before));
1250 WARN_ON_ONCE(!list_empty(&class->locks_after));
1251 class->name_version = count_matching_names(class);
1252 class->wait_type_inner = lock->wait_type_inner;
1253 class->wait_type_outer = lock->wait_type_outer;
1255 * We use RCU's safe list-add method to make
1256 * parallel walking of the hash-list safe:
1258 hlist_add_head_rcu(&class->hash_entry, hash_head);
1260 * Remove the class from the free list and add it to the global list
1263 list_move_tail(&class->lock_entry, &all_lock_classes);
1265 if (verbose(class)) {
1268 printk("\nnew class %px: %s", class->key, class->name);
1269 if (class->name_version > 1)
1270 printk(KERN_CONT "#%d", class->name_version);
1271 printk(KERN_CONT "\n");
1274 if (!graph_lock()) {
1281 out_set_class_cache:
1282 if (!subclass || force)
1283 lock->class_cache[0] = class;
1284 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
1285 lock->class_cache[subclass] = class;
1288 * Hash collision, did we smoke some? We found a class with a matching
1289 * hash but the subclass -- which is hashed in -- didn't match.
1291 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
1297 #ifdef CONFIG_PROVE_LOCKING
1299 * Allocate a lockdep entry. (assumes the graph_lock held, returns
1300 * with NULL on failure)
1302 static struct lock_list *alloc_list_entry(void)
1304 int idx = find_first_zero_bit(list_entries_in_use,
1305 ARRAY_SIZE(list_entries));
1307 if (idx >= ARRAY_SIZE(list_entries)) {
1308 if (!debug_locks_off_graph_unlock())
1311 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
1316 __set_bit(idx, list_entries_in_use);
1317 return list_entries + idx;
1321 * Add a new dependency to the head of the list:
1323 static int add_lock_to_list(struct lock_class *this,
1324 struct lock_class *links_to, struct list_head *head,
1325 unsigned long ip, int distance,
1326 const struct lock_trace *trace)
1328 struct lock_list *entry;
1330 * Lock not present yet - get a new dependency struct and
1331 * add it to the list:
1333 entry = alloc_list_entry();
1337 entry->class = this;
1338 entry->links_to = links_to;
1339 entry->distance = distance;
1340 entry->trace = trace;
1342 * Both allocation and removal are done under the graph lock; but
1343 * iteration is under RCU-sched; see look_up_lock_class() and
1344 * lockdep_free_key_range().
1346 list_add_tail_rcu(&entry->entry, head);
1352 * For good efficiency of modular, we use power of 2
1354 #define MAX_CIRCULAR_QUEUE_SIZE 4096UL
1355 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
1358 * The circular_queue and helpers are used to implement graph
1359 * breadth-first search (BFS) algorithm, by which we can determine
1360 * whether there is a path from a lock to another. In deadlock checks,
1361 * a path from the next lock to be acquired to a previous held lock
1362 * indicates that adding the <prev> -> <next> lock dependency will
1363 * produce a circle in the graph. Breadth-first search instead of
1364 * depth-first search is used in order to find the shortest (circular)
1367 struct circular_queue {
1368 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
1369 unsigned int front, rear;
1372 static struct circular_queue lock_cq;
1374 unsigned int max_bfs_queue_depth;
1376 static unsigned int lockdep_dependency_gen_id;
1378 static inline void __cq_init(struct circular_queue *cq)
1380 cq->front = cq->rear = 0;
1381 lockdep_dependency_gen_id++;
1384 static inline int __cq_empty(struct circular_queue *cq)
1386 return (cq->front == cq->rear);
1389 static inline int __cq_full(struct circular_queue *cq)
1391 return ((cq->rear + 1) & CQ_MASK) == cq->front;
1394 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
1399 cq->element[cq->rear] = elem;
1400 cq->rear = (cq->rear + 1) & CQ_MASK;
1405 * Dequeue an element from the circular_queue, return a lock_list if
1406 * the queue is not empty, or NULL if otherwise.
1408 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
1410 struct lock_list * lock;
1415 lock = cq->element[cq->front];
1416 cq->front = (cq->front + 1) & CQ_MASK;
1421 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
1423 return (cq->rear - cq->front) & CQ_MASK;
1426 static inline void mark_lock_accessed(struct lock_list *lock,
1427 struct lock_list *parent)
1431 nr = lock - list_entries;
1432 WARN_ON(nr >= ARRAY_SIZE(list_entries)); /* Out-of-bounds, input fail */
1433 lock->parent = parent;
1434 lock->class->dep_gen_id = lockdep_dependency_gen_id;
1437 static inline unsigned long lock_accessed(struct lock_list *lock)
1441 nr = lock - list_entries;
1442 WARN_ON(nr >= ARRAY_SIZE(list_entries)); /* Out-of-bounds, input fail */
1443 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
1446 static inline struct lock_list *get_lock_parent(struct lock_list *child)
1448 return child->parent;
1451 static inline int get_lock_depth(struct lock_list *child)
1454 struct lock_list *parent;
1456 while ((parent = get_lock_parent(child))) {
1464 * Return the forward or backward dependency list.
1466 * @lock: the lock_list to get its class's dependency list
1467 * @offset: the offset to struct lock_class to determine whether it is
1468 * locks_after or locks_before
1470 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
1472 void *lock_class = lock->class;
1474 return lock_class + offset;
1478 * Forward- or backward-dependency search, used for both circular dependency
1479 * checking and hardirq-unsafe/softirq-unsafe checking.
1481 static int __bfs(struct lock_list *source_entry,
1483 int (*match)(struct lock_list *entry, void *data),
1484 struct lock_list **target_entry,
1487 struct lock_list *entry;
1488 struct lock_list *lock;
1489 struct list_head *head;
1490 struct circular_queue *cq = &lock_cq;
1493 lockdep_assert_locked();
1495 if (match(source_entry, data)) {
1496 *target_entry = source_entry;
1501 head = get_dep_list(source_entry, offset);
1502 if (list_empty(head))
1506 __cq_enqueue(cq, source_entry);
1508 while ((lock = __cq_dequeue(cq))) {
1515 head = get_dep_list(lock, offset);
1517 list_for_each_entry_rcu(entry, head, entry) {
1518 if (!lock_accessed(entry)) {
1519 unsigned int cq_depth;
1520 mark_lock_accessed(entry, lock);
1521 if (match(entry, data)) {
1522 *target_entry = entry;
1527 if (__cq_enqueue(cq, entry)) {
1531 cq_depth = __cq_get_elem_count(cq);
1532 if (max_bfs_queue_depth < cq_depth)
1533 max_bfs_queue_depth = cq_depth;
1541 static inline int __bfs_forwards(struct lock_list *src_entry,
1543 int (*match)(struct lock_list *entry, void *data),
1544 struct lock_list **target_entry)
1546 return __bfs(src_entry, data, match, target_entry,
1547 offsetof(struct lock_class, locks_after));
1551 static inline int __bfs_backwards(struct lock_list *src_entry,
1553 int (*match)(struct lock_list *entry, void *data),
1554 struct lock_list **target_entry)
1556 return __bfs(src_entry, data, match, target_entry,
1557 offsetof(struct lock_class, locks_before));
1561 static void print_lock_trace(const struct lock_trace *trace,
1562 unsigned int spaces)
1564 stack_trace_print(trace->entries, trace->nr_entries, spaces);
1568 * Print a dependency chain entry (this is only done when a deadlock
1569 * has been detected):
1571 static noinline void
1572 print_circular_bug_entry(struct lock_list *target, int depth)
1574 if (debug_locks_silent)
1576 printk("\n-> #%u", depth);
1577 print_lock_name(target->class);
1578 printk(KERN_CONT ":\n");
1579 print_lock_trace(target->trace, 6);
1583 print_circular_lock_scenario(struct held_lock *src,
1584 struct held_lock *tgt,
1585 struct lock_list *prt)
1587 struct lock_class *source = hlock_class(src);
1588 struct lock_class *target = hlock_class(tgt);
1589 struct lock_class *parent = prt->class;
1592 * A direct locking problem where unsafe_class lock is taken
1593 * directly by safe_class lock, then all we need to show
1594 * is the deadlock scenario, as it is obvious that the
1595 * unsafe lock is taken under the safe lock.
1597 * But if there is a chain instead, where the safe lock takes
1598 * an intermediate lock (middle_class) where this lock is
1599 * not the same as the safe lock, then the lock chain is
1600 * used to describe the problem. Otherwise we would need
1601 * to show a different CPU case for each link in the chain
1602 * from the safe_class lock to the unsafe_class lock.
1604 if (parent != source) {
1605 printk("Chain exists of:\n ");
1606 __print_lock_name(source);
1607 printk(KERN_CONT " --> ");
1608 __print_lock_name(parent);
1609 printk(KERN_CONT " --> ");
1610 __print_lock_name(target);
1611 printk(KERN_CONT "\n\n");
1614 printk(" Possible unsafe locking scenario:\n\n");
1615 printk(" CPU0 CPU1\n");
1616 printk(" ---- ----\n");
1618 __print_lock_name(target);
1619 printk(KERN_CONT ");\n");
1621 __print_lock_name(parent);
1622 printk(KERN_CONT ");\n");
1624 __print_lock_name(target);
1625 printk(KERN_CONT ");\n");
1627 __print_lock_name(source);
1628 printk(KERN_CONT ");\n");
1629 printk("\n *** DEADLOCK ***\n\n");
1633 * When a circular dependency is detected, print the
1636 static noinline void
1637 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1638 struct held_lock *check_src,
1639 struct held_lock *check_tgt)
1641 struct task_struct *curr = current;
1643 if (debug_locks_silent)
1647 pr_warn("======================================================\n");
1648 pr_warn("WARNING: possible circular locking dependency detected\n");
1649 print_kernel_ident();
1650 pr_warn("------------------------------------------------------\n");
1651 pr_warn("%s/%d is trying to acquire lock:\n",
1652 curr->comm, task_pid_nr(curr));
1653 print_lock(check_src);
1655 pr_warn("\nbut task is already holding lock:\n");
1657 print_lock(check_tgt);
1658 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1659 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1661 print_circular_bug_entry(entry, depth);
1664 static inline int class_equal(struct lock_list *entry, void *data)
1666 return entry->class == data;
1669 static noinline void print_circular_bug(struct lock_list *this,
1670 struct lock_list *target,
1671 struct held_lock *check_src,
1672 struct held_lock *check_tgt)
1674 struct task_struct *curr = current;
1675 struct lock_list *parent;
1676 struct lock_list *first_parent;
1679 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1682 this->trace = save_trace();
1686 depth = get_lock_depth(target);
1688 print_circular_bug_header(target, depth, check_src, check_tgt);
1690 parent = get_lock_parent(target);
1691 first_parent = parent;
1694 print_circular_bug_entry(parent, --depth);
1695 parent = get_lock_parent(parent);
1698 printk("\nother info that might help us debug this:\n\n");
1699 print_circular_lock_scenario(check_src, check_tgt,
1702 lockdep_print_held_locks(curr);
1704 printk("\nstack backtrace:\n");
1708 static noinline void print_bfs_bug(int ret)
1710 if (!debug_locks_off_graph_unlock())
1714 * Breadth-first-search failed, graph got corrupted?
1716 WARN(1, "lockdep bfs error:%d\n", ret);
1719 static int noop_count(struct lock_list *entry, void *data)
1721 (*(unsigned long *)data)++;
1725 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
1727 unsigned long count = 0;
1728 struct lock_list *target_entry;
1730 __bfs_forwards(this, (void *)&count, noop_count, &target_entry);
1734 unsigned long lockdep_count_forward_deps(struct lock_class *class)
1736 unsigned long ret, flags;
1737 struct lock_list this;
1742 raw_local_irq_save(flags);
1744 ret = __lockdep_count_forward_deps(&this);
1746 raw_local_irq_restore(flags);
1751 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
1753 unsigned long count = 0;
1754 struct lock_list *target_entry;
1756 __bfs_backwards(this, (void *)&count, noop_count, &target_entry);
1761 unsigned long lockdep_count_backward_deps(struct lock_class *class)
1763 unsigned long ret, flags;
1764 struct lock_list this;
1769 raw_local_irq_save(flags);
1771 ret = __lockdep_count_backward_deps(&this);
1773 raw_local_irq_restore(flags);
1779 * Check that the dependency graph starting at <src> can lead to
1780 * <target> or not. Print an error and return 0 if it does.
1783 check_path(struct lock_class *target, struct lock_list *src_entry,
1784 struct lock_list **target_entry)
1788 ret = __bfs_forwards(src_entry, (void *)target, class_equal,
1791 if (unlikely(ret < 0))
1798 * Prove that the dependency graph starting at <src> can not
1799 * lead to <target>. If it can, there is a circle when adding
1800 * <target> -> <src> dependency.
1802 * Print an error and return 0 if it does.
1805 check_noncircular(struct held_lock *src, struct held_lock *target,
1806 struct lock_trace **const trace)
1809 struct lock_list *target_entry;
1810 struct lock_list src_entry = {
1811 .class = hlock_class(src),
1815 debug_atomic_inc(nr_cyclic_checks);
1817 ret = check_path(hlock_class(target), &src_entry, &target_entry);
1819 if (unlikely(!ret)) {
1822 * If save_trace fails here, the printing might
1823 * trigger a WARN but because of the !nr_entries it
1824 * should not do bad things.
1826 *trace = save_trace();
1829 print_circular_bug(&src_entry, target_entry, src, target);
1835 #ifdef CONFIG_LOCKDEP_SMALL
1837 * Check that the dependency graph starting at <src> can lead to
1838 * <target> or not. If it can, <src> -> <target> dependency is already
1841 * Print an error and return 2 if it does or 1 if it does not.
1844 check_redundant(struct held_lock *src, struct held_lock *target)
1847 struct lock_list *target_entry;
1848 struct lock_list src_entry = {
1849 .class = hlock_class(src),
1853 debug_atomic_inc(nr_redundant_checks);
1855 ret = check_path(hlock_class(target), &src_entry, &target_entry);
1858 debug_atomic_inc(nr_redundant);
1867 #ifdef CONFIG_TRACE_IRQFLAGS
1869 static inline int usage_accumulate(struct lock_list *entry, void *mask)
1871 *(unsigned long *)mask |= entry->class->usage_mask;
1877 * Forwards and backwards subgraph searching, for the purposes of
1878 * proving that two subgraphs can be connected by a new dependency
1879 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
1882 static inline int usage_match(struct lock_list *entry, void *mask)
1884 return entry->class->usage_mask & *(unsigned long *)mask;
1888 * Find a node in the forwards-direction dependency sub-graph starting
1889 * at @root->class that matches @bit.
1891 * Return 0 if such a node exists in the subgraph, and put that node
1892 * into *@target_entry.
1894 * Return 1 otherwise and keep *@target_entry unchanged.
1895 * Return <0 on error.
1898 find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
1899 struct lock_list **target_entry)
1903 debug_atomic_inc(nr_find_usage_forwards_checks);
1905 result = __bfs_forwards(root, &usage_mask, usage_match, target_entry);
1911 * Find a node in the backwards-direction dependency sub-graph starting
1912 * at @root->class that matches @bit.
1914 * Return 0 if such a node exists in the subgraph, and put that node
1915 * into *@target_entry.
1917 * Return 1 otherwise and keep *@target_entry unchanged.
1918 * Return <0 on error.
1921 find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
1922 struct lock_list **target_entry)
1926 debug_atomic_inc(nr_find_usage_backwards_checks);
1928 result = __bfs_backwards(root, &usage_mask, usage_match, target_entry);
1933 static void print_lock_class_header(struct lock_class *class, int depth)
1937 printk("%*s->", depth, "");
1938 print_lock_name(class);
1939 #ifdef CONFIG_DEBUG_LOCKDEP
1940 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
1942 printk(KERN_CONT " {\n");
1944 for (bit = 0; bit < LOCK_TRACE_STATES; bit++) {
1945 if (class->usage_mask & (1 << bit)) {
1948 len += printk("%*s %s", depth, "", usage_str[bit]);
1949 len += printk(KERN_CONT " at:\n");
1950 print_lock_trace(class->usage_traces[bit], len);
1953 printk("%*s }\n", depth, "");
1955 printk("%*s ... key at: [<%px>] %pS\n",
1956 depth, "", class->key, class->key);
1960 * printk the shortest lock dependencies from @start to @end in reverse order:
1963 print_shortest_lock_dependencies(struct lock_list *leaf,
1964 struct lock_list *root)
1966 struct lock_list *entry = leaf;
1969 /*compute depth from generated tree by BFS*/
1970 depth = get_lock_depth(leaf);
1973 print_lock_class_header(entry->class, depth);
1974 printk("%*s ... acquired at:\n", depth, "");
1975 print_lock_trace(entry->trace, 2);
1978 if (depth == 0 && (entry != root)) {
1979 printk("lockdep:%s bad path found in chain graph\n", __func__);
1983 entry = get_lock_parent(entry);
1985 } while (entry && (depth >= 0));
1989 print_irq_lock_scenario(struct lock_list *safe_entry,
1990 struct lock_list *unsafe_entry,
1991 struct lock_class *prev_class,
1992 struct lock_class *next_class)
1994 struct lock_class *safe_class = safe_entry->class;
1995 struct lock_class *unsafe_class = unsafe_entry->class;
1996 struct lock_class *middle_class = prev_class;
1998 if (middle_class == safe_class)
1999 middle_class = next_class;
2002 * A direct locking problem where unsafe_class lock is taken
2003 * directly by safe_class lock, then all we need to show
2004 * is the deadlock scenario, as it is obvious that the
2005 * unsafe lock is taken under the safe lock.
2007 * But if there is a chain instead, where the safe lock takes
2008 * an intermediate lock (middle_class) where this lock is
2009 * not the same as the safe lock, then the lock chain is
2010 * used to describe the problem. Otherwise we would need
2011 * to show a different CPU case for each link in the chain
2012 * from the safe_class lock to the unsafe_class lock.
2014 if (middle_class != unsafe_class) {
2015 printk("Chain exists of:\n ");
2016 __print_lock_name(safe_class);
2017 printk(KERN_CONT " --> ");
2018 __print_lock_name(middle_class);
2019 printk(KERN_CONT " --> ");
2020 __print_lock_name(unsafe_class);
2021 printk(KERN_CONT "\n\n");
2024 printk(" Possible interrupt unsafe locking scenario:\n\n");
2025 printk(" CPU0 CPU1\n");
2026 printk(" ---- ----\n");
2028 __print_lock_name(unsafe_class);
2029 printk(KERN_CONT ");\n");
2030 printk(" local_irq_disable();\n");
2032 __print_lock_name(safe_class);
2033 printk(KERN_CONT ");\n");
2035 __print_lock_name(middle_class);
2036 printk(KERN_CONT ");\n");
2037 printk(" <Interrupt>\n");
2039 __print_lock_name(safe_class);
2040 printk(KERN_CONT ");\n");
2041 printk("\n *** DEADLOCK ***\n\n");
2045 print_bad_irq_dependency(struct task_struct *curr,
2046 struct lock_list *prev_root,
2047 struct lock_list *next_root,
2048 struct lock_list *backwards_entry,
2049 struct lock_list *forwards_entry,
2050 struct held_lock *prev,
2051 struct held_lock *next,
2052 enum lock_usage_bit bit1,
2053 enum lock_usage_bit bit2,
2054 const char *irqclass)
2056 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2060 pr_warn("=====================================================\n");
2061 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
2062 irqclass, irqclass);
2063 print_kernel_ident();
2064 pr_warn("-----------------------------------------------------\n");
2065 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
2066 curr->comm, task_pid_nr(curr),
2067 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
2068 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
2069 lockdep_hardirqs_enabled(),
2070 curr->softirqs_enabled);
2073 pr_warn("\nand this task is already holding:\n");
2075 pr_warn("which would create a new lock dependency:\n");
2076 print_lock_name(hlock_class(prev));
2078 print_lock_name(hlock_class(next));
2081 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
2083 print_lock_name(backwards_entry->class);
2084 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
2086 print_lock_trace(backwards_entry->class->usage_traces[bit1], 1);
2088 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
2089 print_lock_name(forwards_entry->class);
2090 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
2093 print_lock_trace(forwards_entry->class->usage_traces[bit2], 1);
2095 pr_warn("\nother info that might help us debug this:\n\n");
2096 print_irq_lock_scenario(backwards_entry, forwards_entry,
2097 hlock_class(prev), hlock_class(next));
2099 lockdep_print_held_locks(curr);
2101 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
2102 prev_root->trace = save_trace();
2103 if (!prev_root->trace)
2105 print_shortest_lock_dependencies(backwards_entry, prev_root);
2107 pr_warn("\nthe dependencies between the lock to be acquired");
2108 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
2109 next_root->trace = save_trace();
2110 if (!next_root->trace)
2112 print_shortest_lock_dependencies(forwards_entry, next_root);
2114 pr_warn("\nstack backtrace:\n");
2118 static const char *state_names[] = {
2119 #define LOCKDEP_STATE(__STATE) \
2120 __stringify(__STATE),
2121 #include "lockdep_states.h"
2122 #undef LOCKDEP_STATE
2125 static const char *state_rnames[] = {
2126 #define LOCKDEP_STATE(__STATE) \
2127 __stringify(__STATE)"-READ",
2128 #include "lockdep_states.h"
2129 #undef LOCKDEP_STATE
2132 static inline const char *state_name(enum lock_usage_bit bit)
2134 if (bit & LOCK_USAGE_READ_MASK)
2135 return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
2137 return state_names[bit >> LOCK_USAGE_DIR_MASK];
2141 * The bit number is encoded like:
2143 * bit0: 0 exclusive, 1 read lock
2144 * bit1: 0 used in irq, 1 irq enabled
2147 static int exclusive_bit(int new_bit)
2149 int state = new_bit & LOCK_USAGE_STATE_MASK;
2150 int dir = new_bit & LOCK_USAGE_DIR_MASK;
2153 * keep state, bit flip the direction and strip read.
2155 return state | (dir ^ LOCK_USAGE_DIR_MASK);
2159 * Observe that when given a bitmask where each bitnr is encoded as above, a
2160 * right shift of the mask transforms the individual bitnrs as -1 and
2161 * conversely, a left shift transforms into +1 for the individual bitnrs.
2163 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
2164 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
2165 * instead by subtracting the bit number by 2, or shifting the mask right by 2.
2167 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
2169 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
2170 * all bits set) and recompose with bitnr1 flipped.
2172 static unsigned long invert_dir_mask(unsigned long mask)
2174 unsigned long excl = 0;
2177 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
2178 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
2184 * As above, we clear bitnr0 (LOCK_*_READ off) with bitmask ops. First, for all
2185 * bits with bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*).
2186 * And then mask out all bitnr0.
2188 static unsigned long exclusive_mask(unsigned long mask)
2190 unsigned long excl = invert_dir_mask(mask);
2193 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2194 excl &= ~LOCKF_IRQ_READ;
2200 * Retrieve the _possible_ original mask to which @mask is
2201 * exclusive. Ie: this is the opposite of exclusive_mask().
2202 * Note that 2 possible original bits can match an exclusive
2203 * bit: one has LOCK_USAGE_READ_MASK set, the other has it
2204 * cleared. So both are returned for each exclusive bit.
2206 static unsigned long original_mask(unsigned long mask)
2208 unsigned long excl = invert_dir_mask(mask);
2210 /* Include read in existing usages */
2211 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2217 * Find the first pair of bit match between an original
2218 * usage mask and an exclusive usage mask.
2220 static int find_exclusive_match(unsigned long mask,
2221 unsigned long excl_mask,
2222 enum lock_usage_bit *bitp,
2223 enum lock_usage_bit *excl_bitp)
2227 for_each_set_bit(bit, &mask, LOCK_USED) {
2228 excl = exclusive_bit(bit);
2229 if (excl_mask & lock_flag(excl)) {
2239 * Prove that the new dependency does not connect a hardirq-safe(-read)
2240 * lock with a hardirq-unsafe lock - to achieve this we search
2241 * the backwards-subgraph starting at <prev>, and the
2242 * forwards-subgraph starting at <next>:
2244 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
2245 struct held_lock *next)
2247 unsigned long usage_mask = 0, forward_mask, backward_mask;
2248 enum lock_usage_bit forward_bit = 0, backward_bit = 0;
2249 struct lock_list *target_entry1;
2250 struct lock_list *target_entry;
2251 struct lock_list this, that;
2255 * Step 1: gather all hard/soft IRQs usages backward in an
2256 * accumulated usage mask.
2259 this.class = hlock_class(prev);
2261 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, NULL);
2267 usage_mask &= LOCKF_USED_IN_IRQ_ALL;
2272 * Step 2: find exclusive uses forward that match the previous
2273 * backward accumulated mask.
2275 forward_mask = exclusive_mask(usage_mask);
2278 that.class = hlock_class(next);
2280 ret = find_usage_forwards(&that, forward_mask, &target_entry1);
2289 * Step 3: we found a bad match! Now retrieve a lock from the backward
2290 * list whose usage mask matches the exclusive usage mask from the
2291 * lock found on the forward list.
2293 backward_mask = original_mask(target_entry1->class->usage_mask);
2295 ret = find_usage_backwards(&this, backward_mask, &target_entry);
2300 if (DEBUG_LOCKS_WARN_ON(ret == 1))
2304 * Step 4: narrow down to a pair of incompatible usage bits
2307 ret = find_exclusive_match(target_entry->class->usage_mask,
2308 target_entry1->class->usage_mask,
2309 &backward_bit, &forward_bit);
2310 if (DEBUG_LOCKS_WARN_ON(ret == -1))
2313 print_bad_irq_dependency(curr, &this, &that,
2314 target_entry, target_entry1,
2316 backward_bit, forward_bit,
2317 state_name(backward_bit));
2324 static inline int check_irq_usage(struct task_struct *curr,
2325 struct held_lock *prev, struct held_lock *next)
2329 #endif /* CONFIG_TRACE_IRQFLAGS */
2331 static void inc_chains(int irq_context)
2333 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2334 nr_hardirq_chains++;
2335 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2336 nr_softirq_chains++;
2338 nr_process_chains++;
2341 static void dec_chains(int irq_context)
2343 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2344 nr_hardirq_chains--;
2345 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2346 nr_softirq_chains--;
2348 nr_process_chains--;
2352 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
2354 struct lock_class *next = hlock_class(nxt);
2355 struct lock_class *prev = hlock_class(prv);
2357 printk(" Possible unsafe locking scenario:\n\n");
2361 __print_lock_name(prev);
2362 printk(KERN_CONT ");\n");
2364 __print_lock_name(next);
2365 printk(KERN_CONT ");\n");
2366 printk("\n *** DEADLOCK ***\n\n");
2367 printk(" May be due to missing lock nesting notation\n\n");
2371 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
2372 struct held_lock *next)
2374 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2378 pr_warn("============================================\n");
2379 pr_warn("WARNING: possible recursive locking detected\n");
2380 print_kernel_ident();
2381 pr_warn("--------------------------------------------\n");
2382 pr_warn("%s/%d is trying to acquire lock:\n",
2383 curr->comm, task_pid_nr(curr));
2385 pr_warn("\nbut task is already holding lock:\n");
2388 pr_warn("\nother info that might help us debug this:\n");
2389 print_deadlock_scenario(next, prev);
2390 lockdep_print_held_locks(curr);
2392 pr_warn("\nstack backtrace:\n");
2397 * Check whether we are holding such a class already.
2399 * (Note that this has to be done separately, because the graph cannot
2400 * detect such classes of deadlocks.)
2402 * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
2405 check_deadlock(struct task_struct *curr, struct held_lock *next)
2407 struct held_lock *prev;
2408 struct held_lock *nest = NULL;
2411 for (i = 0; i < curr->lockdep_depth; i++) {
2412 prev = curr->held_locks + i;
2414 if (prev->instance == next->nest_lock)
2417 if (hlock_class(prev) != hlock_class(next))
2421 * Allow read-after-read recursion of the same
2422 * lock class (i.e. read_lock(lock)+read_lock(lock)):
2424 if ((next->read == 2) && prev->read)
2428 * We're holding the nest_lock, which serializes this lock's
2429 * nesting behaviour.
2434 print_deadlock_bug(curr, prev, next);
2441 * There was a chain-cache miss, and we are about to add a new dependency
2442 * to a previous lock. We validate the following rules:
2444 * - would the adding of the <prev> -> <next> dependency create a
2445 * circular dependency in the graph? [== circular deadlock]
2447 * - does the new prev->next dependency connect any hardirq-safe lock
2448 * (in the full backwards-subgraph starting at <prev>) with any
2449 * hardirq-unsafe lock (in the full forwards-subgraph starting at
2450 * <next>)? [== illegal lock inversion with hardirq contexts]
2452 * - does the new prev->next dependency connect any softirq-safe lock
2453 * (in the full backwards-subgraph starting at <prev>) with any
2454 * softirq-unsafe lock (in the full forwards-subgraph starting at
2455 * <next>)? [== illegal lock inversion with softirq contexts]
2457 * any of these scenarios could lead to a deadlock.
2459 * Then if all the validations pass, we add the forwards and backwards
2463 check_prev_add(struct task_struct *curr, struct held_lock *prev,
2464 struct held_lock *next, int distance,
2465 struct lock_trace **const trace)
2467 struct lock_list *entry;
2470 if (!hlock_class(prev)->key || !hlock_class(next)->key) {
2472 * The warning statements below may trigger a use-after-free
2473 * of the class name. It is better to trigger a use-after free
2474 * and to have the class name most of the time instead of not
2475 * having the class name available.
2477 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
2478 "Detected use-after-free of lock class %px/%s\n",
2480 hlock_class(prev)->name);
2481 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
2482 "Detected use-after-free of lock class %px/%s\n",
2484 hlock_class(next)->name);
2489 * Prove that the new <prev> -> <next> dependency would not
2490 * create a circular dependency in the graph. (We do this by
2491 * a breadth-first search into the graph starting at <next>,
2492 * and check whether we can reach <prev>.)
2494 * The search is limited by the size of the circular queue (i.e.,
2495 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
2496 * in the graph whose neighbours are to be checked.
2498 ret = check_noncircular(next, prev, trace);
2499 if (unlikely(ret <= 0))
2502 if (!check_irq_usage(curr, prev, next))
2506 * For recursive read-locks we do all the dependency checks,
2507 * but we dont store read-triggered dependencies (only
2508 * write-triggered dependencies). This ensures that only the
2509 * write-side dependencies matter, and that if for example a
2510 * write-lock never takes any other locks, then the reads are
2511 * equivalent to a NOP.
2513 if (next->read == 2 || prev->read == 2)
2516 * Is the <prev> -> <next> dependency already present?
2518 * (this may occur even though this is a new chain: consider
2519 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
2520 * chains - the second one will be new, but L1 already has
2521 * L2 added to its dependency list, due to the first chain.)
2523 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
2524 if (entry->class == hlock_class(next)) {
2526 entry->distance = 1;
2531 #ifdef CONFIG_LOCKDEP_SMALL
2533 * Is the <prev> -> <next> link redundant?
2535 ret = check_redundant(prev, next);
2541 *trace = save_trace();
2547 * Ok, all validations passed, add the new lock
2548 * to the previous lock's dependency list:
2550 ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
2551 &hlock_class(prev)->locks_after,
2552 next->acquire_ip, distance, *trace);
2557 ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
2558 &hlock_class(next)->locks_before,
2559 next->acquire_ip, distance, *trace);
2567 * Add the dependency to all directly-previous locks that are 'relevant'.
2568 * The ones that are relevant are (in increasing distance from curr):
2569 * all consecutive trylock entries and the final non-trylock entry - or
2570 * the end of this context's lock-chain - whichever comes first.
2573 check_prevs_add(struct task_struct *curr, struct held_lock *next)
2575 struct lock_trace *trace = NULL;
2576 int depth = curr->lockdep_depth;
2577 struct held_lock *hlock;
2582 * Depth must not be zero for a non-head lock:
2587 * At least two relevant locks must exist for this
2590 if (curr->held_locks[depth].irq_context !=
2591 curr->held_locks[depth-1].irq_context)
2595 int distance = curr->lockdep_depth - depth + 1;
2596 hlock = curr->held_locks + depth - 1;
2599 * Only non-recursive-read entries get new dependencies
2602 if (hlock->read != 2 && hlock->check) {
2603 int ret = check_prev_add(curr, hlock, next, distance,
2609 * Stop after the first non-trylock entry,
2610 * as non-trylock entries have added their
2611 * own direct dependencies already, so this
2612 * lock is connected to them indirectly:
2614 if (!hlock->trylock)
2620 * End of lock-stack?
2625 * Stop the search if we cross into another context:
2627 if (curr->held_locks[depth].irq_context !=
2628 curr->held_locks[depth-1].irq_context)
2633 if (!debug_locks_off_graph_unlock())
2637 * Clearly we all shouldn't be here, but since we made it we
2638 * can reliable say we messed up our state. See the above two
2639 * gotos for reasons why we could possibly end up here.
2646 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
2647 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
2648 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
2649 unsigned long nr_zapped_lock_chains;
2650 unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */
2651 unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */
2652 unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */
2655 * The first 2 chain_hlocks entries in the chain block in the bucket
2656 * list contains the following meta data:
2659 * Bit 15 - always set to 1 (it is not a class index)
2660 * Bits 0-14 - upper 15 bits of the next block index
2661 * entry[1] - lower 16 bits of next block index
2663 * A next block index of all 1 bits means it is the end of the list.
2665 * On the unsized bucket (bucket-0), the 3rd and 4th entries contain
2666 * the chain block size:
2668 * entry[2] - upper 16 bits of the chain block size
2669 * entry[3] - lower 16 bits of the chain block size
2671 #define MAX_CHAIN_BUCKETS 16
2672 #define CHAIN_BLK_FLAG (1U << 15)
2673 #define CHAIN_BLK_LIST_END 0xFFFFU
2675 static int chain_block_buckets[MAX_CHAIN_BUCKETS];
2677 static inline int size_to_bucket(int size)
2679 if (size > MAX_CHAIN_BUCKETS)
2686 * Iterate all the chain blocks in a bucket.
2688 #define for_each_chain_block(bucket, prev, curr) \
2689 for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \
2691 (prev) = (curr), (curr) = chain_block_next(curr))
2696 static inline int chain_block_next(int offset)
2698 int next = chain_hlocks[offset];
2700 WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG));
2702 if (next == CHAIN_BLK_LIST_END)
2705 next &= ~CHAIN_BLK_FLAG;
2707 next |= chain_hlocks[offset + 1];
2715 static inline int chain_block_size(int offset)
2717 return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3];
2720 static inline void init_chain_block(int offset, int next, int bucket, int size)
2722 chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG;
2723 chain_hlocks[offset + 1] = (u16)next;
2725 if (size && !bucket) {
2726 chain_hlocks[offset + 2] = size >> 16;
2727 chain_hlocks[offset + 3] = (u16)size;
2731 static inline void add_chain_block(int offset, int size)
2733 int bucket = size_to_bucket(size);
2734 int next = chain_block_buckets[bucket];
2737 if (unlikely(size < 2)) {
2739 * We can't store single entries on the freelist. Leak them.
2741 * One possible way out would be to uniquely mark them, other
2742 * than with CHAIN_BLK_FLAG, such that we can recover them when
2743 * the block before it is re-added.
2746 nr_lost_chain_hlocks++;
2750 nr_free_chain_hlocks += size;
2752 nr_large_chain_blocks++;
2755 * Variable sized, sort large to small.
2757 for_each_chain_block(0, prev, curr) {
2758 if (size >= chain_block_size(curr))
2761 init_chain_block(offset, curr, 0, size);
2763 chain_block_buckets[0] = offset;
2765 init_chain_block(prev, offset, 0, 0);
2769 * Fixed size, add to head.
2771 init_chain_block(offset, next, bucket, size);
2772 chain_block_buckets[bucket] = offset;
2776 * Only the first block in the list can be deleted.
2778 * For the variable size bucket[0], the first block (the largest one) is
2779 * returned, broken up and put back into the pool. So if a chain block of
2780 * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be
2781 * queued up after the primordial chain block and never be used until the
2782 * hlock entries in the primordial chain block is almost used up. That
2783 * causes fragmentation and reduce allocation efficiency. That can be
2784 * monitored by looking at the "large chain blocks" number in lockdep_stats.
2786 static inline void del_chain_block(int bucket, int size, int next)
2788 nr_free_chain_hlocks -= size;
2789 chain_block_buckets[bucket] = next;
2792 nr_large_chain_blocks--;
2795 static void init_chain_block_buckets(void)
2799 for (i = 0; i < MAX_CHAIN_BUCKETS; i++)
2800 chain_block_buckets[i] = -1;
2802 add_chain_block(0, ARRAY_SIZE(chain_hlocks));
2806 * Return offset of a chain block of the right size or -1 if not found.
2808 * Fairly simple worst-fit allocator with the addition of a number of size
2809 * specific free lists.
2811 static int alloc_chain_hlocks(int req)
2813 int bucket, curr, size;
2816 * We rely on the MSB to act as an escape bit to denote freelist
2817 * pointers. Make sure this bit isn't set in 'normal' class_idx usage.
2819 BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG);
2821 init_data_structures_once();
2823 if (nr_free_chain_hlocks < req)
2827 * We require a minimum of 2 (u16) entries to encode a freelist
2831 bucket = size_to_bucket(req);
2832 curr = chain_block_buckets[bucket];
2836 del_chain_block(bucket, req, chain_block_next(curr));
2840 curr = chain_block_buckets[0];
2844 * The variable sized freelist is sorted by size; the first entry is
2845 * the largest. Use it if it fits.
2848 size = chain_block_size(curr);
2849 if (likely(size >= req)) {
2850 del_chain_block(0, size, chain_block_next(curr));
2851 add_chain_block(curr + req, size - req);
2857 * Last resort, split a block in a larger sized bucket.
2859 for (size = MAX_CHAIN_BUCKETS; size > req; size--) {
2860 bucket = size_to_bucket(size);
2861 curr = chain_block_buckets[bucket];
2865 del_chain_block(bucket, size, chain_block_next(curr));
2866 add_chain_block(curr + req, size - req);
2873 static inline void free_chain_hlocks(int base, int size)
2875 add_chain_block(base, max(size, 2));
2878 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
2880 return lock_classes + chain_hlocks[chain->base + i];
2884 * Returns the index of the first held_lock of the current chain
2886 static inline int get_first_held_lock(struct task_struct *curr,
2887 struct held_lock *hlock)
2890 struct held_lock *hlock_curr;
2892 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
2893 hlock_curr = curr->held_locks + i;
2894 if (hlock_curr->irq_context != hlock->irq_context)
2902 #ifdef CONFIG_DEBUG_LOCKDEP
2904 * Returns the next chain_key iteration
2906 static u64 print_chain_key_iteration(int class_idx, u64 chain_key)
2908 u64 new_chain_key = iterate_chain_key(chain_key, class_idx);
2910 printk(" class_idx:%d -> chain_key:%016Lx",
2912 (unsigned long long)new_chain_key);
2913 return new_chain_key;
2917 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
2919 struct held_lock *hlock;
2920 u64 chain_key = INITIAL_CHAIN_KEY;
2921 int depth = curr->lockdep_depth;
2922 int i = get_first_held_lock(curr, hlock_next);
2924 printk("depth: %u (irq_context %u)\n", depth - i + 1,
2925 hlock_next->irq_context);
2926 for (; i < depth; i++) {
2927 hlock = curr->held_locks + i;
2928 chain_key = print_chain_key_iteration(hlock->class_idx, chain_key);
2933 print_chain_key_iteration(hlock_next->class_idx, chain_key);
2934 print_lock(hlock_next);
2937 static void print_chain_keys_chain(struct lock_chain *chain)
2940 u64 chain_key = INITIAL_CHAIN_KEY;
2943 printk("depth: %u\n", chain->depth);
2944 for (i = 0; i < chain->depth; i++) {
2945 class_id = chain_hlocks[chain->base + i];
2946 chain_key = print_chain_key_iteration(class_id, chain_key);
2948 print_lock_name(lock_classes + class_id);
2953 static void print_collision(struct task_struct *curr,
2954 struct held_lock *hlock_next,
2955 struct lock_chain *chain)
2958 pr_warn("============================\n");
2959 pr_warn("WARNING: chain_key collision\n");
2960 print_kernel_ident();
2961 pr_warn("----------------------------\n");
2962 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
2963 pr_warn("Hash chain already cached but the contents don't match!\n");
2965 pr_warn("Held locks:");
2966 print_chain_keys_held_locks(curr, hlock_next);
2968 pr_warn("Locks in cached chain:");
2969 print_chain_keys_chain(chain);
2971 pr_warn("\nstack backtrace:\n");
2977 * Checks whether the chain and the current held locks are consistent
2978 * in depth and also in content. If they are not it most likely means
2979 * that there was a collision during the calculation of the chain_key.
2980 * Returns: 0 not passed, 1 passed
2982 static int check_no_collision(struct task_struct *curr,
2983 struct held_lock *hlock,
2984 struct lock_chain *chain)
2986 #ifdef CONFIG_DEBUG_LOCKDEP
2989 i = get_first_held_lock(curr, hlock);
2991 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
2992 print_collision(curr, hlock, chain);
2996 for (j = 0; j < chain->depth - 1; j++, i++) {
2997 id = curr->held_locks[i].class_idx;
2999 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
3000 print_collision(curr, hlock, chain);
3009 * Given an index that is >= -1, return the index of the next lock chain.
3010 * Return -2 if there is no next lock chain.
3012 long lockdep_next_lockchain(long i)
3014 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
3015 return i < ARRAY_SIZE(lock_chains) ? i : -2;
3018 unsigned long lock_chain_count(void)
3020 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
3023 /* Must be called with the graph lock held. */
3024 static struct lock_chain *alloc_lock_chain(void)
3026 int idx = find_first_zero_bit(lock_chains_in_use,
3027 ARRAY_SIZE(lock_chains));
3029 if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
3031 __set_bit(idx, lock_chains_in_use);
3032 return lock_chains + idx;
3036 * Adds a dependency chain into chain hashtable. And must be called with
3039 * Return 0 if fail, and graph_lock is released.
3040 * Return 1 if succeed, with graph_lock held.
3042 static inline int add_chain_cache(struct task_struct *curr,
3043 struct held_lock *hlock,
3046 struct lock_class *class = hlock_class(hlock);
3047 struct hlist_head *hash_head = chainhashentry(chain_key);
3048 struct lock_chain *chain;
3052 * The caller must hold the graph lock, ensure we've got IRQs
3053 * disabled to make this an IRQ-safe lock.. for recursion reasons
3054 * lockdep won't complain about its own locking errors.
3056 if (lockdep_assert_locked())
3059 chain = alloc_lock_chain();
3061 if (!debug_locks_off_graph_unlock())
3064 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
3068 chain->chain_key = chain_key;
3069 chain->irq_context = hlock->irq_context;
3070 i = get_first_held_lock(curr, hlock);
3071 chain->depth = curr->lockdep_depth + 1 - i;
3073 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
3074 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
3075 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
3077 j = alloc_chain_hlocks(chain->depth);
3079 if (!debug_locks_off_graph_unlock())
3082 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
3088 for (j = 0; j < chain->depth - 1; j++, i++) {
3089 int lock_id = curr->held_locks[i].class_idx;
3091 chain_hlocks[chain->base + j] = lock_id;
3093 chain_hlocks[chain->base + j] = class - lock_classes;
3094 hlist_add_head_rcu(&chain->entry, hash_head);
3095 debug_atomic_inc(chain_lookup_misses);
3096 inc_chains(chain->irq_context);
3102 * Look up a dependency chain. Must be called with either the graph lock or
3103 * the RCU read lock held.
3105 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
3107 struct hlist_head *hash_head = chainhashentry(chain_key);
3108 struct lock_chain *chain;
3110 hlist_for_each_entry_rcu(chain, hash_head, entry) {
3111 if (READ_ONCE(chain->chain_key) == chain_key) {
3112 debug_atomic_inc(chain_lookup_hits);
3120 * If the key is not present yet in dependency chain cache then
3121 * add it and return 1 - in this case the new dependency chain is
3122 * validated. If the key is already hashed, return 0.
3123 * (On return with 1 graph_lock is held.)
3125 static inline int lookup_chain_cache_add(struct task_struct *curr,
3126 struct held_lock *hlock,
3129 struct lock_class *class = hlock_class(hlock);
3130 struct lock_chain *chain = lookup_chain_cache(chain_key);
3134 if (!check_no_collision(curr, hlock, chain))
3137 if (very_verbose(class)) {
3138 printk("\nhash chain already cached, key: "
3139 "%016Lx tail class: [%px] %s\n",
3140 (unsigned long long)chain_key,
3141 class->key, class->name);
3147 if (very_verbose(class)) {
3148 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
3149 (unsigned long long)chain_key, class->key, class->name);
3156 * We have to walk the chain again locked - to avoid duplicates:
3158 chain = lookup_chain_cache(chain_key);
3164 if (!add_chain_cache(curr, hlock, chain_key))
3170 static int validate_chain(struct task_struct *curr,
3171 struct held_lock *hlock,
3172 int chain_head, u64 chain_key)
3175 * Trylock needs to maintain the stack of held locks, but it
3176 * does not add new dependencies, because trylock can be done
3179 * We look up the chain_key and do the O(N^2) check and update of
3180 * the dependencies only if this is a new dependency chain.
3181 * (If lookup_chain_cache_add() return with 1 it acquires
3182 * graph_lock for us)
3184 if (!hlock->trylock && hlock->check &&
3185 lookup_chain_cache_add(curr, hlock, chain_key)) {
3187 * Check whether last held lock:
3189 * - is irq-safe, if this lock is irq-unsafe
3190 * - is softirq-safe, if this lock is hardirq-unsafe
3192 * And check whether the new lock's dependency graph
3193 * could lead back to the previous lock:
3195 * - within the current held-lock stack
3196 * - across our accumulated lock dependency records
3198 * any of these scenarios could lead to a deadlock.
3201 * The simple case: does the current hold the same lock
3204 int ret = check_deadlock(curr, hlock);
3209 * Mark recursive read, as we jump over it when
3210 * building dependencies (just like we jump over
3216 * Add dependency only if this lock is not the head
3217 * of the chain, and if it's not a secondary read-lock:
3219 if (!chain_head && ret != 2) {
3220 if (!check_prevs_add(curr, hlock))
3226 /* after lookup_chain_cache_add(): */
3227 if (unlikely(!debug_locks))
3234 static inline int validate_chain(struct task_struct *curr,
3235 struct held_lock *hlock,
3236 int chain_head, u64 chain_key)
3241 static void init_chain_block_buckets(void) { }
3242 #endif /* CONFIG_PROVE_LOCKING */
3245 * We are building curr_chain_key incrementally, so double-check
3246 * it from scratch, to make sure that it's done correctly:
3248 static void check_chain_key(struct task_struct *curr)
3250 #ifdef CONFIG_DEBUG_LOCKDEP
3251 struct held_lock *hlock, *prev_hlock = NULL;
3253 u64 chain_key = INITIAL_CHAIN_KEY;
3255 for (i = 0; i < curr->lockdep_depth; i++) {
3256 hlock = curr->held_locks + i;
3257 if (chain_key != hlock->prev_chain_key) {
3260 * We got mighty confused, our chain keys don't match
3261 * with what we expect, someone trample on our task state?
3263 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
3264 curr->lockdep_depth, i,
3265 (unsigned long long)chain_key,
3266 (unsigned long long)hlock->prev_chain_key);
3271 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
3272 * it registered lock class index?
3274 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
3277 if (prev_hlock && (prev_hlock->irq_context !=
3278 hlock->irq_context))
3279 chain_key = INITIAL_CHAIN_KEY;
3280 chain_key = iterate_chain_key(chain_key, hlock->class_idx);
3283 if (chain_key != curr->curr_chain_key) {
3286 * More smoking hash instead of calculating it, damn see these
3287 * numbers float.. I bet that a pink elephant stepped on my memory.
3289 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
3290 curr->lockdep_depth, i,
3291 (unsigned long long)chain_key,
3292 (unsigned long long)curr->curr_chain_key);
3297 #ifdef CONFIG_PROVE_LOCKING
3298 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3299 enum lock_usage_bit new_bit);
3301 static void print_usage_bug_scenario(struct held_lock *lock)
3303 struct lock_class *class = hlock_class(lock);
3305 printk(" Possible unsafe locking scenario:\n\n");
3309 __print_lock_name(class);
3310 printk(KERN_CONT ");\n");
3311 printk(" <Interrupt>\n");
3313 __print_lock_name(class);
3314 printk(KERN_CONT ");\n");
3315 printk("\n *** DEADLOCK ***\n\n");
3319 print_usage_bug(struct task_struct *curr, struct held_lock *this,
3320 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
3322 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3326 pr_warn("================================\n");
3327 pr_warn("WARNING: inconsistent lock state\n");
3328 print_kernel_ident();
3329 pr_warn("--------------------------------\n");
3331 pr_warn("inconsistent {%s} -> {%s} usage.\n",
3332 usage_str[prev_bit], usage_str[new_bit]);
3334 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
3335 curr->comm, task_pid_nr(curr),
3336 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
3337 lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
3338 lockdep_hardirqs_enabled(),
3339 lockdep_softirqs_enabled(curr));
3342 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
3343 print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1);
3345 print_irqtrace_events(curr);
3346 pr_warn("\nother info that might help us debug this:\n");
3347 print_usage_bug_scenario(this);
3349 lockdep_print_held_locks(curr);
3351 pr_warn("\nstack backtrace:\n");
3356 * Print out an error if an invalid bit is set:
3359 valid_state(struct task_struct *curr, struct held_lock *this,
3360 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
3362 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
3363 print_usage_bug(curr, this, bad_bit, new_bit);
3371 * print irq inversion bug:
3374 print_irq_inversion_bug(struct task_struct *curr,
3375 struct lock_list *root, struct lock_list *other,
3376 struct held_lock *this, int forwards,
3377 const char *irqclass)
3379 struct lock_list *entry = other;
3380 struct lock_list *middle = NULL;
3383 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3387 pr_warn("========================================================\n");
3388 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
3389 print_kernel_ident();
3390 pr_warn("--------------------------------------------------------\n");
3391 pr_warn("%s/%d just changed the state of lock:\n",
3392 curr->comm, task_pid_nr(curr));
3395 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
3397 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
3398 print_lock_name(other->class);
3399 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
3401 pr_warn("\nother info that might help us debug this:\n");
3403 /* Find a middle lock (if one exists) */
3404 depth = get_lock_depth(other);
3406 if (depth == 0 && (entry != root)) {
3407 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
3411 entry = get_lock_parent(entry);
3413 } while (entry && entry != root && (depth >= 0));
3415 print_irq_lock_scenario(root, other,
3416 middle ? middle->class : root->class, other->class);
3418 print_irq_lock_scenario(other, root,
3419 middle ? middle->class : other->class, root->class);
3421 lockdep_print_held_locks(curr);
3423 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
3424 root->trace = save_trace();
3427 print_shortest_lock_dependencies(other, root);
3429 pr_warn("\nstack backtrace:\n");
3434 * Prove that in the forwards-direction subgraph starting at <this>
3435 * there is no lock matching <mask>:
3438 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
3439 enum lock_usage_bit bit, const char *irqclass)
3442 struct lock_list root;
3443 struct lock_list *target_entry;
3446 root.class = hlock_class(this);
3447 ret = find_usage_forwards(&root, lock_flag(bit), &target_entry);
3455 print_irq_inversion_bug(curr, &root, target_entry,
3461 * Prove that in the backwards-direction subgraph starting at <this>
3462 * there is no lock matching <mask>:
3465 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
3466 enum lock_usage_bit bit, const char *irqclass)
3469 struct lock_list root;
3470 struct lock_list *target_entry;
3473 root.class = hlock_class(this);
3474 ret = find_usage_backwards(&root, lock_flag(bit), &target_entry);
3482 print_irq_inversion_bug(curr, &root, target_entry,
3487 void print_irqtrace_events(struct task_struct *curr)
3489 const struct irqtrace_events *trace = &curr->irqtrace;
3491 printk("irq event stamp: %u\n", trace->irq_events);
3492 printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
3493 trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip,
3494 (void *)trace->hardirq_enable_ip);
3495 printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
3496 trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip,
3497 (void *)trace->hardirq_disable_ip);
3498 printk("softirqs last enabled at (%u): [<%px>] %pS\n",
3499 trace->softirq_enable_event, (void *)trace->softirq_enable_ip,
3500 (void *)trace->softirq_enable_ip);
3501 printk("softirqs last disabled at (%u): [<%px>] %pS\n",
3502 trace->softirq_disable_event, (void *)trace->softirq_disable_ip,
3503 (void *)trace->softirq_disable_ip);
3506 static int HARDIRQ_verbose(struct lock_class *class)
3509 return class_filter(class);
3514 static int SOFTIRQ_verbose(struct lock_class *class)
3517 return class_filter(class);
3522 #define STRICT_READ_CHECKS 1
3524 static int (*state_verbose_f[])(struct lock_class *class) = {
3525 #define LOCKDEP_STATE(__STATE) \
3527 #include "lockdep_states.h"
3528 #undef LOCKDEP_STATE
3531 static inline int state_verbose(enum lock_usage_bit bit,
3532 struct lock_class *class)
3534 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
3537 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
3538 enum lock_usage_bit bit, const char *name);
3541 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
3542 enum lock_usage_bit new_bit)
3544 int excl_bit = exclusive_bit(new_bit);
3545 int read = new_bit & LOCK_USAGE_READ_MASK;
3546 int dir = new_bit & LOCK_USAGE_DIR_MASK;
3549 * mark USED_IN has to look forwards -- to ensure no dependency
3550 * has ENABLED state, which would allow recursion deadlocks.
3552 * mark ENABLED has to look backwards -- to ensure no dependee
3553 * has USED_IN state, which, again, would allow recursion deadlocks.
3555 check_usage_f usage = dir ?
3556 check_usage_backwards : check_usage_forwards;
3559 * Validate that this particular lock does not have conflicting
3562 if (!valid_state(curr, this, new_bit, excl_bit))
3566 * Validate that the lock dependencies don't have conflicting usage
3569 if ((!read || STRICT_READ_CHECKS) &&
3570 !usage(curr, this, excl_bit, state_name(new_bit & ~LOCK_USAGE_READ_MASK)))
3574 * Check for read in write conflicts
3577 if (!valid_state(curr, this, new_bit, excl_bit + LOCK_USAGE_READ_MASK))
3580 if (STRICT_READ_CHECKS &&
3581 !usage(curr, this, excl_bit + LOCK_USAGE_READ_MASK,
3582 state_name(new_bit + LOCK_USAGE_READ_MASK)))
3586 if (state_verbose(new_bit, hlock_class(this)))
3593 * Mark all held locks with a usage bit:
3596 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
3598 struct held_lock *hlock;
3601 for (i = 0; i < curr->lockdep_depth; i++) {
3602 enum lock_usage_bit hlock_bit = base_bit;
3603 hlock = curr->held_locks + i;
3606 hlock_bit += LOCK_USAGE_READ_MASK;
3608 BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
3613 if (!mark_lock(curr, hlock, hlock_bit))
3621 * Hardirqs will be enabled:
3623 static void __trace_hardirqs_on_caller(void)
3625 struct task_struct *curr = current;
3628 * We are going to turn hardirqs on, so set the
3629 * usage bit for all held locks:
3631 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
3634 * If we have softirqs enabled, then set the usage
3635 * bit for all held locks. (disabled hardirqs prevented
3636 * this bit from being set before)
3638 if (curr->softirqs_enabled)
3639 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
3643 * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts
3644 * @ip: Caller address
3646 * Invoked before a possible transition to RCU idle from exit to user or
3647 * guest mode. This ensures that all RCU operations are done before RCU
3648 * stops watching. After the RCU transition lockdep_hardirqs_on() has to be
3649 * invoked to set the final state.
3651 void lockdep_hardirqs_on_prepare(unsigned long ip)
3653 if (unlikely(!debug_locks))
3657 * NMIs do not (and cannot) track lock dependencies, nothing to do.
3659 if (unlikely(in_nmi()))
3662 if (unlikely(current->lockdep_recursion & LOCKDEP_RECURSION_MASK))
3665 if (unlikely(lockdep_hardirqs_enabled())) {
3667 * Neither irq nor preemption are disabled here
3668 * so this is racy by nature but losing one hit
3669 * in a stat is not a big deal.
3671 __debug_atomic_inc(redundant_hardirqs_on);
3676 * We're enabling irqs and according to our state above irqs weren't
3677 * already enabled, yet we find the hardware thinks they are in fact
3678 * enabled.. someone messed up their IRQ state tracing.
3680 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3684 * See the fine text that goes along with this variable definition.
3686 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
3690 * Can't allow enabling interrupts while in an interrupt handler,
3691 * that's general bad form and such. Recursion, limited stack etc..
3693 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context()))
3696 current->hardirq_chain_key = current->curr_chain_key;
3698 current->lockdep_recursion++;
3699 __trace_hardirqs_on_caller();
3700 lockdep_recursion_finish();
3702 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare);
3704 void noinstr lockdep_hardirqs_on(unsigned long ip)
3706 struct irqtrace_events *trace = ¤t->irqtrace;
3708 if (unlikely(!debug_locks))
3712 * NMIs can happen in the middle of local_irq_{en,dis}able() where the
3713 * tracking state and hardware state are out of sync.
3715 * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from,
3716 * and not rely on hardware state like normal interrupts.
3718 if (unlikely(in_nmi())) {
3719 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
3724 * - recursion check, because NMI can hit lockdep;
3725 * - hardware state check, because above;
3726 * - chain_key check, see lockdep_hardirqs_on_prepare().
3731 if (unlikely(current->lockdep_recursion & LOCKDEP_RECURSION_MASK))
3734 if (lockdep_hardirqs_enabled()) {
3736 * Neither irq nor preemption are disabled here
3737 * so this is racy by nature but losing one hit
3738 * in a stat is not a big deal.
3740 __debug_atomic_inc(redundant_hardirqs_on);
3745 * We're enabling irqs and according to our state above irqs weren't
3746 * already enabled, yet we find the hardware thinks they are in fact
3747 * enabled.. someone messed up their IRQ state tracing.
3749 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3753 * Ensure the lock stack remained unchanged between
3754 * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on().
3756 DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key !=
3757 current->curr_chain_key);
3760 /* we'll do an OFF -> ON transition: */
3761 __this_cpu_write(hardirqs_enabled, 1);
3762 trace->hardirq_enable_ip = ip;
3763 trace->hardirq_enable_event = ++trace->irq_events;
3764 debug_atomic_inc(hardirqs_on_events);
3766 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on);
3769 * Hardirqs were disabled:
3771 void noinstr lockdep_hardirqs_off(unsigned long ip)
3773 if (unlikely(!debug_locks))
3777 * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep;
3778 * they will restore the software state. This ensures the software
3779 * state is consistent inside NMIs as well.
3782 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
3784 } else if (current->lockdep_recursion & LOCKDEP_RECURSION_MASK)
3788 * So we're supposed to get called after you mask local IRQs, but for
3789 * some reason the hardware doesn't quite think you did a proper job.
3791 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3794 if (lockdep_hardirqs_enabled()) {
3795 struct irqtrace_events *trace = ¤t->irqtrace;
3798 * We have done an ON -> OFF transition:
3800 __this_cpu_write(hardirqs_enabled, 0);
3801 trace->hardirq_disable_ip = ip;
3802 trace->hardirq_disable_event = ++trace->irq_events;
3803 debug_atomic_inc(hardirqs_off_events);
3805 debug_atomic_inc(redundant_hardirqs_off);
3808 EXPORT_SYMBOL_GPL(lockdep_hardirqs_off);
3811 * Softirqs will be enabled:
3813 void lockdep_softirqs_on(unsigned long ip)
3815 struct irqtrace_events *trace = ¤t->irqtrace;
3817 if (unlikely(!debug_locks || current->lockdep_recursion))
3821 * We fancy IRQs being disabled here, see softirq.c, avoids
3822 * funny state and nesting things.
3824 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3827 if (current->softirqs_enabled) {
3828 debug_atomic_inc(redundant_softirqs_on);
3832 current->lockdep_recursion++;
3834 * We'll do an OFF -> ON transition:
3836 current->softirqs_enabled = 1;
3837 trace->softirq_enable_ip = ip;
3838 trace->softirq_enable_event = ++trace->irq_events;
3839 debug_atomic_inc(softirqs_on_events);
3841 * We are going to turn softirqs on, so set the
3842 * usage bit for all held locks, if hardirqs are
3845 if (lockdep_hardirqs_enabled())
3846 mark_held_locks(current, LOCK_ENABLED_SOFTIRQ);
3847 lockdep_recursion_finish();
3851 * Softirqs were disabled:
3853 void lockdep_softirqs_off(unsigned long ip)
3855 if (unlikely(!debug_locks || current->lockdep_recursion))
3859 * We fancy IRQs being disabled here, see softirq.c
3861 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3864 if (current->softirqs_enabled) {
3865 struct irqtrace_events *trace = ¤t->irqtrace;
3868 * We have done an ON -> OFF transition:
3870 current->softirqs_enabled = 0;
3871 trace->softirq_disable_ip = ip;
3872 trace->softirq_disable_event = ++trace->irq_events;
3873 debug_atomic_inc(softirqs_off_events);
3875 * Whoops, we wanted softirqs off, so why aren't they?
3877 DEBUG_LOCKS_WARN_ON(!softirq_count());
3879 debug_atomic_inc(redundant_softirqs_off);
3883 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
3889 * If non-trylock use in a hardirq or softirq context, then
3890 * mark the lock as used in these contexts:
3892 if (!hlock->trylock) {
3894 if (lockdep_hardirq_context())
3895 if (!mark_lock(curr, hlock,
3896 LOCK_USED_IN_HARDIRQ_READ))
3898 if (curr->softirq_context)
3899 if (!mark_lock(curr, hlock,
3900 LOCK_USED_IN_SOFTIRQ_READ))
3903 if (lockdep_hardirq_context())
3904 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
3906 if (curr->softirq_context)
3907 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
3911 if (!hlock->hardirqs_off) {
3913 if (!mark_lock(curr, hlock,
3914 LOCK_ENABLED_HARDIRQ_READ))
3916 if (curr->softirqs_enabled)
3917 if (!mark_lock(curr, hlock,
3918 LOCK_ENABLED_SOFTIRQ_READ))
3921 if (!mark_lock(curr, hlock,
3922 LOCK_ENABLED_HARDIRQ))
3924 if (curr->softirqs_enabled)
3925 if (!mark_lock(curr, hlock,
3926 LOCK_ENABLED_SOFTIRQ))
3932 /* mark it as used: */
3933 if (!mark_lock(curr, hlock, LOCK_USED))
3939 static inline unsigned int task_irq_context(struct task_struct *task)
3941 return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() +
3942 LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context;
3945 static int separate_irq_context(struct task_struct *curr,
3946 struct held_lock *hlock)
3948 unsigned int depth = curr->lockdep_depth;
3951 * Keep track of points where we cross into an interrupt context:
3954 struct held_lock *prev_hlock;
3956 prev_hlock = curr->held_locks + depth-1;
3958 * If we cross into another context, reset the
3959 * hash key (this also prevents the checking and the
3960 * adding of the dependency to 'prev'):
3962 if (prev_hlock->irq_context != hlock->irq_context)
3969 * Mark a lock with a usage bit, and validate the state transition:
3971 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3972 enum lock_usage_bit new_bit)
3974 unsigned int new_mask, ret = 1;
3976 if (new_bit >= LOCK_USAGE_STATES) {
3977 DEBUG_LOCKS_WARN_ON(1);
3981 if (new_bit == LOCK_USED && this->read)
3982 new_bit = LOCK_USED_READ;
3984 new_mask = 1 << new_bit;
3987 * If already set then do not dirty the cacheline,
3988 * nor do any checks:
3990 if (likely(hlock_class(this)->usage_mask & new_mask))
3996 * Make sure we didn't race:
3998 if (unlikely(hlock_class(this)->usage_mask & new_mask))
4001 hlock_class(this)->usage_mask |= new_mask;
4003 if (new_bit < LOCK_TRACE_STATES) {
4004 if (!(hlock_class(this)->usage_traces[new_bit] = save_trace()))
4009 case 0 ... LOCK_USED-1:
4010 ret = mark_lock_irq(curr, this, new_bit);
4016 debug_atomic_dec(nr_unused_locks);
4027 * We must printk outside of the graph_lock:
4030 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
4032 print_irqtrace_events(curr);
4039 static inline short task_wait_context(struct task_struct *curr)
4042 * Set appropriate wait type for the context; for IRQs we have to take
4043 * into account force_irqthread as that is implied by PREEMPT_RT.
4045 if (lockdep_hardirq_context()) {
4047 * Check if force_irqthreads will run us threaded.
4049 if (curr->hardirq_threaded || curr->irq_config)
4050 return LD_WAIT_CONFIG;
4052 return LD_WAIT_SPIN;
4053 } else if (curr->softirq_context) {
4055 * Softirqs are always threaded.
4057 return LD_WAIT_CONFIG;
4064 print_lock_invalid_wait_context(struct task_struct *curr,
4065 struct held_lock *hlock)
4069 if (!debug_locks_off())
4071 if (debug_locks_silent)
4075 pr_warn("=============================\n");
4076 pr_warn("[ BUG: Invalid wait context ]\n");
4077 print_kernel_ident();
4078 pr_warn("-----------------------------\n");
4080 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4083 pr_warn("other info that might help us debug this:\n");
4085 curr_inner = task_wait_context(curr);
4086 pr_warn("context-{%d:%d}\n", curr_inner, curr_inner);
4088 lockdep_print_held_locks(curr);
4090 pr_warn("stack backtrace:\n");
4097 * Verify the wait_type context.
4099 * This check validates we takes locks in the right wait-type order; that is it
4100 * ensures that we do not take mutexes inside spinlocks and do not attempt to
4101 * acquire spinlocks inside raw_spinlocks and the sort.
4103 * The entire thing is slightly more complex because of RCU, RCU is a lock that
4104 * can be taken from (pretty much) any context but also has constraints.
4105 * However when taken in a stricter environment the RCU lock does not loosen
4108 * Therefore we must look for the strictest environment in the lock stack and
4109 * compare that to the lock we're trying to acquire.
4111 static int check_wait_context(struct task_struct *curr, struct held_lock *next)
4113 short next_inner = hlock_class(next)->wait_type_inner;
4114 short next_outer = hlock_class(next)->wait_type_outer;
4118 if (!curr->lockdep_depth || !next_inner || next->trylock)
4122 next_outer = next_inner;
4125 * Find start of current irq_context..
4127 for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) {
4128 struct held_lock *prev = curr->held_locks + depth;
4129 if (prev->irq_context != next->irq_context)
4134 curr_inner = task_wait_context(curr);
4136 for (; depth < curr->lockdep_depth; depth++) {
4137 struct held_lock *prev = curr->held_locks + depth;
4138 short prev_inner = hlock_class(prev)->wait_type_inner;
4142 * We can have a bigger inner than a previous one
4143 * when outer is smaller than inner, as with RCU.
4145 * Also due to trylocks.
4147 curr_inner = min(curr_inner, prev_inner);
4151 if (next_outer > curr_inner)
4152 return print_lock_invalid_wait_context(curr, next);
4157 #else /* CONFIG_PROVE_LOCKING */
4160 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4165 static inline unsigned int task_irq_context(struct task_struct *task)
4170 static inline int separate_irq_context(struct task_struct *curr,
4171 struct held_lock *hlock)
4176 static inline int check_wait_context(struct task_struct *curr,
4177 struct held_lock *next)
4182 #endif /* CONFIG_PROVE_LOCKING */
4185 * Initialize a lock instance's lock-class mapping info:
4187 void lockdep_init_map_waits(struct lockdep_map *lock, const char *name,
4188 struct lock_class_key *key, int subclass,
4189 short inner, short outer)
4193 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
4194 lock->class_cache[i] = NULL;
4196 #ifdef CONFIG_LOCK_STAT
4197 lock->cpu = raw_smp_processor_id();
4201 * Can't be having no nameless bastards around this place!
4203 if (DEBUG_LOCKS_WARN_ON(!name)) {
4204 lock->name = "NULL";
4210 lock->wait_type_outer = outer;
4211 lock->wait_type_inner = inner;
4214 * No key, no joy, we need to hash something.
4216 if (DEBUG_LOCKS_WARN_ON(!key))
4219 * Sanity check, the lock-class key must either have been allocated
4220 * statically or must have been registered as a dynamic key.
4222 if (!static_obj(key) && !is_dynamic_key(key)) {
4224 printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
4225 DEBUG_LOCKS_WARN_ON(1);
4230 if (unlikely(!debug_locks))
4234 unsigned long flags;
4236 if (DEBUG_LOCKS_WARN_ON(current->lockdep_recursion))
4239 raw_local_irq_save(flags);
4240 current->lockdep_recursion++;
4241 register_lock_class(lock, subclass, 1);
4242 lockdep_recursion_finish();
4243 raw_local_irq_restore(flags);
4246 EXPORT_SYMBOL_GPL(lockdep_init_map_waits);
4248 struct lock_class_key __lockdep_no_validate__;
4249 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
4252 print_lock_nested_lock_not_held(struct task_struct *curr,
4253 struct held_lock *hlock,
4256 if (!debug_locks_off())
4258 if (debug_locks_silent)
4262 pr_warn("==================================\n");
4263 pr_warn("WARNING: Nested lock was not taken\n");
4264 print_kernel_ident();
4265 pr_warn("----------------------------------\n");
4267 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4270 pr_warn("\nbut this task is not holding:\n");
4271 pr_warn("%s\n", hlock->nest_lock->name);
4273 pr_warn("\nstack backtrace:\n");
4276 pr_warn("\nother info that might help us debug this:\n");
4277 lockdep_print_held_locks(curr);
4279 pr_warn("\nstack backtrace:\n");
4283 static int __lock_is_held(const struct lockdep_map *lock, int read);
4286 * This gets called for every mutex_lock*()/spin_lock*() operation.
4287 * We maintain the dependency maps and validate the locking attempt:
4289 * The callers must make sure that IRQs are disabled before calling it,
4290 * otherwise we could get an interrupt which would want to take locks,
4291 * which would end up in lockdep again.
4293 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
4294 int trylock, int read, int check, int hardirqs_off,
4295 struct lockdep_map *nest_lock, unsigned long ip,
4296 int references, int pin_count)
4298 struct task_struct *curr = current;
4299 struct lock_class *class = NULL;
4300 struct held_lock *hlock;
4306 if (unlikely(!debug_locks))
4309 if (!prove_locking || lock->key == &__lockdep_no_validate__)
4312 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
4313 class = lock->class_cache[subclass];
4317 if (unlikely(!class)) {
4318 class = register_lock_class(lock, subclass, 0);
4323 debug_class_ops_inc(class);
4325 if (very_verbose(class)) {
4326 printk("\nacquire class [%px] %s", class->key, class->name);
4327 if (class->name_version > 1)
4328 printk(KERN_CONT "#%d", class->name_version);
4329 printk(KERN_CONT "\n");
4334 * Add the lock to the list of currently held locks.
4335 * (we dont increase the depth just yet, up until the
4336 * dependency checks are done)
4338 depth = curr->lockdep_depth;
4340 * Ran out of static storage for our per-task lock stack again have we?
4342 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
4345 class_idx = class - lock_classes;
4347 if (depth) { /* we're holding locks */
4348 hlock = curr->held_locks + depth - 1;
4349 if (hlock->class_idx == class_idx && nest_lock) {
4353 if (!hlock->references)
4354 hlock->references++;
4356 hlock->references += references;
4359 if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
4366 hlock = curr->held_locks + depth;
4368 * Plain impossible, we just registered it and checked it weren't no
4369 * NULL like.. I bet this mushroom I ate was good!
4371 if (DEBUG_LOCKS_WARN_ON(!class))
4373 hlock->class_idx = class_idx;
4374 hlock->acquire_ip = ip;
4375 hlock->instance = lock;
4376 hlock->nest_lock = nest_lock;
4377 hlock->irq_context = task_irq_context(curr);
4378 hlock->trylock = trylock;
4380 hlock->check = check;
4381 hlock->hardirqs_off = !!hardirqs_off;
4382 hlock->references = references;
4383 #ifdef CONFIG_LOCK_STAT
4384 hlock->waittime_stamp = 0;
4385 hlock->holdtime_stamp = lockstat_clock();
4387 hlock->pin_count = pin_count;
4389 if (check_wait_context(curr, hlock))
4392 /* Initialize the lock usage bit */
4393 if (!mark_usage(curr, hlock, check))
4397 * Calculate the chain hash: it's the combined hash of all the
4398 * lock keys along the dependency chain. We save the hash value
4399 * at every step so that we can get the current hash easily
4400 * after unlock. The chain hash is then used to cache dependency
4403 * The 'key ID' is what is the most compact key value to drive
4404 * the hash, not class->key.
4407 * Whoops, we did it again.. class_idx is invalid.
4409 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
4412 chain_key = curr->curr_chain_key;
4415 * How can we have a chain hash when we ain't got no keys?!
4417 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
4422 hlock->prev_chain_key = chain_key;
4423 if (separate_irq_context(curr, hlock)) {
4424 chain_key = INITIAL_CHAIN_KEY;
4427 chain_key = iterate_chain_key(chain_key, class_idx);
4429 if (nest_lock && !__lock_is_held(nest_lock, -1)) {
4430 print_lock_nested_lock_not_held(curr, hlock, ip);
4434 if (!debug_locks_silent) {
4435 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
4436 WARN_ON_ONCE(!hlock_class(hlock)->key);
4439 if (!validate_chain(curr, hlock, chain_head, chain_key))
4442 curr->curr_chain_key = chain_key;
4443 curr->lockdep_depth++;
4444 check_chain_key(curr);
4445 #ifdef CONFIG_DEBUG_LOCKDEP
4446 if (unlikely(!debug_locks))
4449 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
4451 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
4452 printk(KERN_DEBUG "depth: %i max: %lu!\n",
4453 curr->lockdep_depth, MAX_LOCK_DEPTH);
4455 lockdep_print_held_locks(current);
4456 debug_show_all_locks();
4462 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
4463 max_lockdep_depth = curr->lockdep_depth;
4468 static void print_unlock_imbalance_bug(struct task_struct *curr,
4469 struct lockdep_map *lock,
4472 if (!debug_locks_off())
4474 if (debug_locks_silent)
4478 pr_warn("=====================================\n");
4479 pr_warn("WARNING: bad unlock balance detected!\n");
4480 print_kernel_ident();
4481 pr_warn("-------------------------------------\n");
4482 pr_warn("%s/%d is trying to release lock (",
4483 curr->comm, task_pid_nr(curr));
4484 print_lockdep_cache(lock);
4486 print_ip_sym(KERN_WARNING, ip);
4487 pr_warn("but there are no more locks to release!\n");
4488 pr_warn("\nother info that might help us debug this:\n");
4489 lockdep_print_held_locks(curr);
4491 pr_warn("\nstack backtrace:\n");
4495 static noinstr int match_held_lock(const struct held_lock *hlock,
4496 const struct lockdep_map *lock)
4498 if (hlock->instance == lock)
4501 if (hlock->references) {
4502 const struct lock_class *class = lock->class_cache[0];
4505 class = look_up_lock_class(lock, 0);
4508 * If look_up_lock_class() failed to find a class, we're trying
4509 * to test if we hold a lock that has never yet been acquired.
4510 * Clearly if the lock hasn't been acquired _ever_, we're not
4511 * holding it either, so report failure.
4517 * References, but not a lock we're actually ref-counting?
4518 * State got messed up, follow the sites that change ->references
4519 * and try to make sense of it.
4521 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
4524 if (hlock->class_idx == class - lock_classes)
4531 /* @depth must not be zero */
4532 static struct held_lock *find_held_lock(struct task_struct *curr,
4533 struct lockdep_map *lock,
4534 unsigned int depth, int *idx)
4536 struct held_lock *ret, *hlock, *prev_hlock;
4540 hlock = curr->held_locks + i;
4542 if (match_held_lock(hlock, lock))
4546 for (i--, prev_hlock = hlock--;
4548 i--, prev_hlock = hlock--) {
4550 * We must not cross into another context:
4552 if (prev_hlock->irq_context != hlock->irq_context) {
4556 if (match_held_lock(hlock, lock)) {
4567 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
4568 int idx, unsigned int *merged)
4570 struct held_lock *hlock;
4571 int first_idx = idx;
4573 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4576 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
4577 switch (__lock_acquire(hlock->instance,
4578 hlock_class(hlock)->subclass,
4580 hlock->read, hlock->check,
4581 hlock->hardirqs_off,
4582 hlock->nest_lock, hlock->acquire_ip,
4583 hlock->references, hlock->pin_count)) {
4589 *merged += (idx == first_idx);
4600 __lock_set_class(struct lockdep_map *lock, const char *name,
4601 struct lock_class_key *key, unsigned int subclass,
4604 struct task_struct *curr = current;
4605 unsigned int depth, merged = 0;
4606 struct held_lock *hlock;
4607 struct lock_class *class;
4610 if (unlikely(!debug_locks))
4613 depth = curr->lockdep_depth;
4615 * This function is about (re)setting the class of a held lock,
4616 * yet we're not actually holding any locks. Naughty user!
4618 if (DEBUG_LOCKS_WARN_ON(!depth))
4621 hlock = find_held_lock(curr, lock, depth, &i);
4623 print_unlock_imbalance_bug(curr, lock, ip);
4627 lockdep_init_map_waits(lock, name, key, 0,
4628 lock->wait_type_inner,
4629 lock->wait_type_outer);
4630 class = register_lock_class(lock, subclass, 0);
4631 hlock->class_idx = class - lock_classes;
4633 curr->lockdep_depth = i;
4634 curr->curr_chain_key = hlock->prev_chain_key;
4636 if (reacquire_held_locks(curr, depth, i, &merged))
4640 * I took it apart and put it back together again, except now I have
4641 * these 'spare' parts.. where shall I put them.
4643 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
4648 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
4650 struct task_struct *curr = current;
4651 unsigned int depth, merged = 0;
4652 struct held_lock *hlock;
4655 if (unlikely(!debug_locks))
4658 depth = curr->lockdep_depth;
4660 * This function is about (re)setting the class of a held lock,
4661 * yet we're not actually holding any locks. Naughty user!
4663 if (DEBUG_LOCKS_WARN_ON(!depth))
4666 hlock = find_held_lock(curr, lock, depth, &i);
4668 print_unlock_imbalance_bug(curr, lock, ip);
4672 curr->lockdep_depth = i;
4673 curr->curr_chain_key = hlock->prev_chain_key;
4675 WARN(hlock->read, "downgrading a read lock");
4677 hlock->acquire_ip = ip;
4679 if (reacquire_held_locks(curr, depth, i, &merged))
4682 /* Merging can't happen with unchanged classes.. */
4683 if (DEBUG_LOCKS_WARN_ON(merged))
4687 * I took it apart and put it back together again, except now I have
4688 * these 'spare' parts.. where shall I put them.
4690 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
4697 * Remove the lock from the list of currently held locks - this gets
4698 * called on mutex_unlock()/spin_unlock*() (or on a failed
4699 * mutex_lock_interruptible()).
4702 __lock_release(struct lockdep_map *lock, unsigned long ip)
4704 struct task_struct *curr = current;
4705 unsigned int depth, merged = 1;
4706 struct held_lock *hlock;
4709 if (unlikely(!debug_locks))
4712 depth = curr->lockdep_depth;
4714 * So we're all set to release this lock.. wait what lock? We don't
4715 * own any locks, you've been drinking again?
4718 print_unlock_imbalance_bug(curr, lock, ip);
4723 * Check whether the lock exists in the current stack
4726 hlock = find_held_lock(curr, lock, depth, &i);
4728 print_unlock_imbalance_bug(curr, lock, ip);
4732 if (hlock->instance == lock)
4733 lock_release_holdtime(hlock);
4735 WARN(hlock->pin_count, "releasing a pinned lock\n");
4737 if (hlock->references) {
4738 hlock->references--;
4739 if (hlock->references) {
4741 * We had, and after removing one, still have
4742 * references, the current lock stack is still
4743 * valid. We're done!
4750 * We have the right lock to unlock, 'hlock' points to it.
4751 * Now we remove it from the stack, and add back the other
4752 * entries (if any), recalculating the hash along the way:
4755 curr->lockdep_depth = i;
4756 curr->curr_chain_key = hlock->prev_chain_key;
4759 * The most likely case is when the unlock is on the innermost
4760 * lock. In this case, we are done!
4765 if (reacquire_held_locks(curr, depth, i + 1, &merged))
4769 * We had N bottles of beer on the wall, we drank one, but now
4770 * there's not N-1 bottles of beer left on the wall...
4771 * Pouring two of the bottles together is acceptable.
4773 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
4776 * Since reacquire_held_locks() would have called check_chain_key()
4777 * indirectly via __lock_acquire(), we don't need to do it again
4783 static __always_inline
4784 int __lock_is_held(const struct lockdep_map *lock, int read)
4786 struct task_struct *curr = current;
4789 for (i = 0; i < curr->lockdep_depth; i++) {
4790 struct held_lock *hlock = curr->held_locks + i;
4792 if (match_held_lock(hlock, lock)) {
4793 if (read == -1 || hlock->read == read)
4803 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
4805 struct pin_cookie cookie = NIL_COOKIE;
4806 struct task_struct *curr = current;
4809 if (unlikely(!debug_locks))
4812 for (i = 0; i < curr->lockdep_depth; i++) {
4813 struct held_lock *hlock = curr->held_locks + i;
4815 if (match_held_lock(hlock, lock)) {
4817 * Grab 16bits of randomness; this is sufficient to not
4818 * be guessable and still allows some pin nesting in
4819 * our u32 pin_count.
4821 cookie.val = 1 + (prandom_u32() >> 16);
4822 hlock->pin_count += cookie.val;
4827 WARN(1, "pinning an unheld lock\n");
4831 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4833 struct task_struct *curr = current;
4836 if (unlikely(!debug_locks))
4839 for (i = 0; i < curr->lockdep_depth; i++) {
4840 struct held_lock *hlock = curr->held_locks + i;
4842 if (match_held_lock(hlock, lock)) {
4843 hlock->pin_count += cookie.val;
4848 WARN(1, "pinning an unheld lock\n");
4851 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4853 struct task_struct *curr = current;
4856 if (unlikely(!debug_locks))
4859 for (i = 0; i < curr->lockdep_depth; i++) {
4860 struct held_lock *hlock = curr->held_locks + i;
4862 if (match_held_lock(hlock, lock)) {
4863 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
4866 hlock->pin_count -= cookie.val;
4868 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
4869 hlock->pin_count = 0;
4875 WARN(1, "unpinning an unheld lock\n");
4879 * Check whether we follow the irq-flags state precisely:
4881 static void check_flags(unsigned long flags)
4883 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP)
4887 if (irqs_disabled_flags(flags)) {
4888 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) {
4889 printk("possible reason: unannotated irqs-off.\n");
4892 if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) {
4893 printk("possible reason: unannotated irqs-on.\n");
4898 * We dont accurately track softirq state in e.g.
4899 * hardirq contexts (such as on 4KSTACKS), so only
4900 * check if not in hardirq contexts:
4902 if (!hardirq_count()) {
4903 if (softirq_count()) {
4904 /* like the above, but with softirqs */
4905 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
4907 /* lick the above, does it taste good? */
4908 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
4913 print_irqtrace_events(current);
4917 void lock_set_class(struct lockdep_map *lock, const char *name,
4918 struct lock_class_key *key, unsigned int subclass,
4921 unsigned long flags;
4923 if (unlikely(current->lockdep_recursion))
4926 raw_local_irq_save(flags);
4927 current->lockdep_recursion++;
4929 if (__lock_set_class(lock, name, key, subclass, ip))
4930 check_chain_key(current);
4931 lockdep_recursion_finish();
4932 raw_local_irq_restore(flags);
4934 EXPORT_SYMBOL_GPL(lock_set_class);
4936 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
4938 unsigned long flags;
4940 if (unlikely(current->lockdep_recursion))
4943 raw_local_irq_save(flags);
4944 current->lockdep_recursion++;
4946 if (__lock_downgrade(lock, ip))
4947 check_chain_key(current);
4948 lockdep_recursion_finish();
4949 raw_local_irq_restore(flags);
4951 EXPORT_SYMBOL_GPL(lock_downgrade);
4953 /* NMI context !!! */
4954 static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass)
4956 #ifdef CONFIG_PROVE_LOCKING
4957 struct lock_class *class = look_up_lock_class(lock, subclass);
4958 unsigned long mask = LOCKF_USED;
4960 /* if it doesn't have a class (yet), it certainly hasn't been used yet */
4965 * READ locks only conflict with USED, such that if we only ever use
4966 * READ locks, there is no deadlock possible -- RCU.
4969 mask |= LOCKF_USED_READ;
4971 if (!(class->usage_mask & mask))
4974 hlock->class_idx = class - lock_classes;
4976 print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES);
4980 static bool lockdep_nmi(void)
4982 if (current->lockdep_recursion & LOCKDEP_RECURSION_MASK)
4992 * We are not always called with irqs disabled - do that here,
4993 * and also avoid lockdep recursion:
4995 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
4996 int trylock, int read, int check,
4997 struct lockdep_map *nest_lock, unsigned long ip)
4999 unsigned long flags;
5001 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
5003 if (unlikely(current->lockdep_recursion)) {
5004 /* XXX allow trylock from NMI ?!? */
5005 if (lockdep_nmi() && !trylock) {
5006 struct held_lock hlock;
5008 hlock.acquire_ip = ip;
5009 hlock.instance = lock;
5010 hlock.nest_lock = nest_lock;
5011 hlock.irq_context = 2; // XXX
5012 hlock.trylock = trylock;
5014 hlock.check = check;
5015 hlock.hardirqs_off = true;
5016 hlock.references = 0;
5018 verify_lock_unused(lock, &hlock, subclass);
5023 raw_local_irq_save(flags);
5026 current->lockdep_recursion++;
5027 __lock_acquire(lock, subclass, trylock, read, check,
5028 irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
5029 lockdep_recursion_finish();
5030 raw_local_irq_restore(flags);
5032 EXPORT_SYMBOL_GPL(lock_acquire);
5034 void lock_release(struct lockdep_map *lock, unsigned long ip)
5036 unsigned long flags;
5038 trace_lock_release(lock, ip);
5040 if (unlikely(current->lockdep_recursion))
5043 raw_local_irq_save(flags);
5046 current->lockdep_recursion++;
5047 if (__lock_release(lock, ip))
5048 check_chain_key(current);
5049 lockdep_recursion_finish();
5050 raw_local_irq_restore(flags);
5052 EXPORT_SYMBOL_GPL(lock_release);
5054 noinstr int lock_is_held_type(const struct lockdep_map *lock, int read)
5056 unsigned long flags;
5059 if (unlikely(current->lockdep_recursion))
5060 return 1; /* avoid false negative lockdep_assert_held() */
5062 raw_local_irq_save(flags);
5065 current->lockdep_recursion++;
5066 ret = __lock_is_held(lock, read);
5067 lockdep_recursion_finish();
5068 raw_local_irq_restore(flags);
5072 EXPORT_SYMBOL_GPL(lock_is_held_type);
5073 NOKPROBE_SYMBOL(lock_is_held_type);
5075 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
5077 struct pin_cookie cookie = NIL_COOKIE;
5078 unsigned long flags;
5080 if (unlikely(current->lockdep_recursion))
5083 raw_local_irq_save(flags);
5086 current->lockdep_recursion++;
5087 cookie = __lock_pin_lock(lock);
5088 lockdep_recursion_finish();
5089 raw_local_irq_restore(flags);
5093 EXPORT_SYMBOL_GPL(lock_pin_lock);
5095 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5097 unsigned long flags;
5099 if (unlikely(current->lockdep_recursion))
5102 raw_local_irq_save(flags);
5105 current->lockdep_recursion++;
5106 __lock_repin_lock(lock, cookie);
5107 lockdep_recursion_finish();
5108 raw_local_irq_restore(flags);
5110 EXPORT_SYMBOL_GPL(lock_repin_lock);
5112 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5114 unsigned long flags;
5116 if (unlikely(current->lockdep_recursion))
5119 raw_local_irq_save(flags);
5122 current->lockdep_recursion++;
5123 __lock_unpin_lock(lock, cookie);
5124 lockdep_recursion_finish();
5125 raw_local_irq_restore(flags);
5127 EXPORT_SYMBOL_GPL(lock_unpin_lock);
5129 #ifdef CONFIG_LOCK_STAT
5130 static void print_lock_contention_bug(struct task_struct *curr,
5131 struct lockdep_map *lock,
5134 if (!debug_locks_off())
5136 if (debug_locks_silent)
5140 pr_warn("=================================\n");
5141 pr_warn("WARNING: bad contention detected!\n");
5142 print_kernel_ident();
5143 pr_warn("---------------------------------\n");
5144 pr_warn("%s/%d is trying to contend lock (",
5145 curr->comm, task_pid_nr(curr));
5146 print_lockdep_cache(lock);
5148 print_ip_sym(KERN_WARNING, ip);
5149 pr_warn("but there are no locks held!\n");
5150 pr_warn("\nother info that might help us debug this:\n");
5151 lockdep_print_held_locks(curr);
5153 pr_warn("\nstack backtrace:\n");
5158 __lock_contended(struct lockdep_map *lock, unsigned long ip)
5160 struct task_struct *curr = current;
5161 struct held_lock *hlock;
5162 struct lock_class_stats *stats;
5164 int i, contention_point, contending_point;
5166 depth = curr->lockdep_depth;
5168 * Whee, we contended on this lock, except it seems we're not
5169 * actually trying to acquire anything much at all..
5171 if (DEBUG_LOCKS_WARN_ON(!depth))
5174 hlock = find_held_lock(curr, lock, depth, &i);
5176 print_lock_contention_bug(curr, lock, ip);
5180 if (hlock->instance != lock)
5183 hlock->waittime_stamp = lockstat_clock();
5185 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
5186 contending_point = lock_point(hlock_class(hlock)->contending_point,
5189 stats = get_lock_stats(hlock_class(hlock));
5190 if (contention_point < LOCKSTAT_POINTS)
5191 stats->contention_point[contention_point]++;
5192 if (contending_point < LOCKSTAT_POINTS)
5193 stats->contending_point[contending_point]++;
5194 if (lock->cpu != smp_processor_id())
5195 stats->bounces[bounce_contended + !!hlock->read]++;
5199 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
5201 struct task_struct *curr = current;
5202 struct held_lock *hlock;
5203 struct lock_class_stats *stats;
5205 u64 now, waittime = 0;
5208 depth = curr->lockdep_depth;
5210 * Yay, we acquired ownership of this lock we didn't try to
5211 * acquire, how the heck did that happen?
5213 if (DEBUG_LOCKS_WARN_ON(!depth))
5216 hlock = find_held_lock(curr, lock, depth, &i);
5218 print_lock_contention_bug(curr, lock, _RET_IP_);
5222 if (hlock->instance != lock)
5225 cpu = smp_processor_id();
5226 if (hlock->waittime_stamp) {
5227 now = lockstat_clock();
5228 waittime = now - hlock->waittime_stamp;
5229 hlock->holdtime_stamp = now;
5232 stats = get_lock_stats(hlock_class(hlock));
5235 lock_time_inc(&stats->read_waittime, waittime);
5237 lock_time_inc(&stats->write_waittime, waittime);
5239 if (lock->cpu != cpu)
5240 stats->bounces[bounce_acquired + !!hlock->read]++;
5246 void lock_contended(struct lockdep_map *lock, unsigned long ip)
5248 unsigned long flags;
5250 trace_lock_acquired(lock, ip);
5252 if (unlikely(!lock_stat || !debug_locks))
5255 if (unlikely(current->lockdep_recursion))
5258 raw_local_irq_save(flags);
5260 current->lockdep_recursion++;
5261 __lock_contended(lock, ip);
5262 lockdep_recursion_finish();
5263 raw_local_irq_restore(flags);
5265 EXPORT_SYMBOL_GPL(lock_contended);
5267 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
5269 unsigned long flags;
5271 trace_lock_contended(lock, ip);
5273 if (unlikely(!lock_stat || !debug_locks))
5276 if (unlikely(current->lockdep_recursion))
5279 raw_local_irq_save(flags);
5281 current->lockdep_recursion++;
5282 __lock_acquired(lock, ip);
5283 lockdep_recursion_finish();
5284 raw_local_irq_restore(flags);
5286 EXPORT_SYMBOL_GPL(lock_acquired);
5290 * Used by the testsuite, sanitize the validator state
5291 * after a simulated failure:
5294 void lockdep_reset(void)
5296 unsigned long flags;
5299 raw_local_irq_save(flags);
5300 lockdep_init_task(current);
5301 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
5302 nr_hardirq_chains = 0;
5303 nr_softirq_chains = 0;
5304 nr_process_chains = 0;
5306 for (i = 0; i < CHAINHASH_SIZE; i++)
5307 INIT_HLIST_HEAD(chainhash_table + i);
5308 raw_local_irq_restore(flags);
5311 /* Remove a class from a lock chain. Must be called with the graph lock held. */
5312 static void remove_class_from_lock_chain(struct pending_free *pf,
5313 struct lock_chain *chain,
5314 struct lock_class *class)
5316 #ifdef CONFIG_PROVE_LOCKING
5319 for (i = chain->base; i < chain->base + chain->depth; i++) {
5320 if (chain_hlocks[i] != class - lock_classes)
5323 * Each lock class occurs at most once in a lock chain so once
5324 * we found a match we can break out of this loop.
5326 goto free_lock_chain;
5328 /* Since the chain has not been modified, return. */
5332 free_chain_hlocks(chain->base, chain->depth);
5333 /* Overwrite the chain key for concurrent RCU readers. */
5334 WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY);
5335 dec_chains(chain->irq_context);
5338 * Note: calling hlist_del_rcu() from inside a
5339 * hlist_for_each_entry_rcu() loop is safe.
5341 hlist_del_rcu(&chain->entry);
5342 __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
5343 nr_zapped_lock_chains++;
5347 /* Must be called with the graph lock held. */
5348 static void remove_class_from_lock_chains(struct pending_free *pf,
5349 struct lock_class *class)
5351 struct lock_chain *chain;
5352 struct hlist_head *head;
5355 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
5356 head = chainhash_table + i;
5357 hlist_for_each_entry_rcu(chain, head, entry) {
5358 remove_class_from_lock_chain(pf, chain, class);
5364 * Remove all references to a lock class. The caller must hold the graph lock.
5366 static void zap_class(struct pending_free *pf, struct lock_class *class)
5368 struct lock_list *entry;
5371 WARN_ON_ONCE(!class->key);
5374 * Remove all dependencies this lock is
5377 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
5378 entry = list_entries + i;
5379 if (entry->class != class && entry->links_to != class)
5381 __clear_bit(i, list_entries_in_use);
5383 list_del_rcu(&entry->entry);
5385 if (list_empty(&class->locks_after) &&
5386 list_empty(&class->locks_before)) {
5387 list_move_tail(&class->lock_entry, &pf->zapped);
5388 hlist_del_rcu(&class->hash_entry);
5389 WRITE_ONCE(class->key, NULL);
5390 WRITE_ONCE(class->name, NULL);
5392 __clear_bit(class - lock_classes, lock_classes_in_use);
5394 WARN_ONCE(true, "%s() failed for class %s\n", __func__,
5398 remove_class_from_lock_chains(pf, class);
5399 nr_zapped_classes++;
5402 static void reinit_class(struct lock_class *class)
5404 void *const p = class;
5405 const unsigned int offset = offsetof(struct lock_class, key);
5407 WARN_ON_ONCE(!class->lock_entry.next);
5408 WARN_ON_ONCE(!list_empty(&class->locks_after));
5409 WARN_ON_ONCE(!list_empty(&class->locks_before));
5410 memset(p + offset, 0, sizeof(*class) - offset);
5411 WARN_ON_ONCE(!class->lock_entry.next);
5412 WARN_ON_ONCE(!list_empty(&class->locks_after));
5413 WARN_ON_ONCE(!list_empty(&class->locks_before));
5416 static inline int within(const void *addr, void *start, unsigned long size)
5418 return addr >= start && addr < start + size;
5421 static bool inside_selftest(void)
5423 return current == lockdep_selftest_task_struct;
5426 /* The caller must hold the graph lock. */
5427 static struct pending_free *get_pending_free(void)
5429 return delayed_free.pf + delayed_free.index;
5432 static void free_zapped_rcu(struct rcu_head *cb);
5435 * Schedule an RCU callback if no RCU callback is pending. Must be called with
5436 * the graph lock held.
5438 static void call_rcu_zapped(struct pending_free *pf)
5440 WARN_ON_ONCE(inside_selftest());
5442 if (list_empty(&pf->zapped))
5445 if (delayed_free.scheduled)
5448 delayed_free.scheduled = true;
5450 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
5451 delayed_free.index ^= 1;
5453 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
5456 /* The caller must hold the graph lock. May be called from RCU context. */
5457 static void __free_zapped_classes(struct pending_free *pf)
5459 struct lock_class *class;
5461 check_data_structures();
5463 list_for_each_entry(class, &pf->zapped, lock_entry)
5464 reinit_class(class);
5466 list_splice_init(&pf->zapped, &free_lock_classes);
5468 #ifdef CONFIG_PROVE_LOCKING
5469 bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
5470 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
5471 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
5475 static void free_zapped_rcu(struct rcu_head *ch)
5477 struct pending_free *pf;
5478 unsigned long flags;
5480 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
5483 raw_local_irq_save(flags);
5487 pf = delayed_free.pf + (delayed_free.index ^ 1);
5488 __free_zapped_classes(pf);
5489 delayed_free.scheduled = false;
5492 * If there's anything on the open list, close and start a new callback.
5494 call_rcu_zapped(delayed_free.pf + delayed_free.index);
5497 raw_local_irq_restore(flags);
5501 * Remove all lock classes from the class hash table and from the
5502 * all_lock_classes list whose key or name is in the address range [start,
5503 * start + size). Move these lock classes to the zapped_classes list. Must
5504 * be called with the graph lock held.
5506 static void __lockdep_free_key_range(struct pending_free *pf, void *start,
5509 struct lock_class *class;
5510 struct hlist_head *head;
5513 /* Unhash all classes that were created by a module. */
5514 for (i = 0; i < CLASSHASH_SIZE; i++) {
5515 head = classhash_table + i;
5516 hlist_for_each_entry_rcu(class, head, hash_entry) {
5517 if (!within(class->key, start, size) &&
5518 !within(class->name, start, size))
5520 zap_class(pf, class);
5526 * Used in module.c to remove lock classes from memory that is going to be
5527 * freed; and possibly re-used by other modules.
5529 * We will have had one synchronize_rcu() before getting here, so we're
5530 * guaranteed nobody will look up these exact classes -- they're properly dead
5531 * but still allocated.
5533 static void lockdep_free_key_range_reg(void *start, unsigned long size)
5535 struct pending_free *pf;
5536 unsigned long flags;
5538 init_data_structures_once();
5540 raw_local_irq_save(flags);
5542 pf = get_pending_free();
5543 __lockdep_free_key_range(pf, start, size);
5544 call_rcu_zapped(pf);
5546 raw_local_irq_restore(flags);
5549 * Wait for any possible iterators from look_up_lock_class() to pass
5550 * before continuing to free the memory they refer to.
5556 * Free all lockdep keys in the range [start, start+size). Does not sleep.
5557 * Ignores debug_locks. Must only be used by the lockdep selftests.
5559 static void lockdep_free_key_range_imm(void *start, unsigned long size)
5561 struct pending_free *pf = delayed_free.pf;
5562 unsigned long flags;
5564 init_data_structures_once();
5566 raw_local_irq_save(flags);
5568 __lockdep_free_key_range(pf, start, size);
5569 __free_zapped_classes(pf);
5571 raw_local_irq_restore(flags);
5574 void lockdep_free_key_range(void *start, unsigned long size)
5576 init_data_structures_once();
5578 if (inside_selftest())
5579 lockdep_free_key_range_imm(start, size);
5581 lockdep_free_key_range_reg(start, size);
5585 * Check whether any element of the @lock->class_cache[] array refers to a
5586 * registered lock class. The caller must hold either the graph lock or the
5589 static bool lock_class_cache_is_registered(struct lockdep_map *lock)
5591 struct lock_class *class;
5592 struct hlist_head *head;
5595 for (i = 0; i < CLASSHASH_SIZE; i++) {
5596 head = classhash_table + i;
5597 hlist_for_each_entry_rcu(class, head, hash_entry) {
5598 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
5599 if (lock->class_cache[j] == class)
5606 /* The caller must hold the graph lock. Does not sleep. */
5607 static void __lockdep_reset_lock(struct pending_free *pf,
5608 struct lockdep_map *lock)
5610 struct lock_class *class;
5614 * Remove all classes this lock might have:
5616 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
5618 * If the class exists we look it up and zap it:
5620 class = look_up_lock_class(lock, j);
5622 zap_class(pf, class);
5625 * Debug check: in the end all mapped classes should
5628 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
5633 * Remove all information lockdep has about a lock if debug_locks == 1. Free
5634 * released data structures from RCU context.
5636 static void lockdep_reset_lock_reg(struct lockdep_map *lock)
5638 struct pending_free *pf;
5639 unsigned long flags;
5642 raw_local_irq_save(flags);
5643 locked = graph_lock();
5647 pf = get_pending_free();
5648 __lockdep_reset_lock(pf, lock);
5649 call_rcu_zapped(pf);
5653 raw_local_irq_restore(flags);
5657 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
5658 * lockdep selftests.
5660 static void lockdep_reset_lock_imm(struct lockdep_map *lock)
5662 struct pending_free *pf = delayed_free.pf;
5663 unsigned long flags;
5665 raw_local_irq_save(flags);
5667 __lockdep_reset_lock(pf, lock);
5668 __free_zapped_classes(pf);
5670 raw_local_irq_restore(flags);
5673 void lockdep_reset_lock(struct lockdep_map *lock)
5675 init_data_structures_once();
5677 if (inside_selftest())
5678 lockdep_reset_lock_imm(lock);
5680 lockdep_reset_lock_reg(lock);
5683 /* Unregister a dynamically allocated key. */
5684 void lockdep_unregister_key(struct lock_class_key *key)
5686 struct hlist_head *hash_head = keyhashentry(key);
5687 struct lock_class_key *k;
5688 struct pending_free *pf;
5689 unsigned long flags;
5694 if (WARN_ON_ONCE(static_obj(key)))
5697 raw_local_irq_save(flags);
5701 pf = get_pending_free();
5702 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
5704 hlist_del_rcu(&k->hash_entry);
5709 WARN_ON_ONCE(!found);
5710 __lockdep_free_key_range(pf, key, 1);
5711 call_rcu_zapped(pf);
5714 raw_local_irq_restore(flags);
5716 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
5719 EXPORT_SYMBOL_GPL(lockdep_unregister_key);
5721 void __init lockdep_init(void)
5723 printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
5725 printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
5726 printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
5727 printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
5728 printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
5729 printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
5730 printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
5731 printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
5733 printk(" memory used by lock dependency info: %zu kB\n",
5734 (sizeof(lock_classes) +
5735 sizeof(lock_classes_in_use) +
5736 sizeof(classhash_table) +
5737 sizeof(list_entries) +
5738 sizeof(list_entries_in_use) +
5739 sizeof(chainhash_table) +
5740 sizeof(delayed_free)
5741 #ifdef CONFIG_PROVE_LOCKING
5743 + sizeof(lock_chains)
5744 + sizeof(lock_chains_in_use)
5745 + sizeof(chain_hlocks)
5750 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
5751 printk(" memory used for stack traces: %zu kB\n",
5752 (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
5756 printk(" per task-struct memory footprint: %zu bytes\n",
5757 sizeof(((struct task_struct *)NULL)->held_locks));
5761 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
5762 const void *mem_to, struct held_lock *hlock)
5764 if (!debug_locks_off())
5766 if (debug_locks_silent)
5770 pr_warn("=========================\n");
5771 pr_warn("WARNING: held lock freed!\n");
5772 print_kernel_ident();
5773 pr_warn("-------------------------\n");
5774 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
5775 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
5777 lockdep_print_held_locks(curr);
5779 pr_warn("\nstack backtrace:\n");
5783 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
5784 const void* lock_from, unsigned long lock_len)
5786 return lock_from + lock_len <= mem_from ||
5787 mem_from + mem_len <= lock_from;
5791 * Called when kernel memory is freed (or unmapped), or if a lock
5792 * is destroyed or reinitialized - this code checks whether there is
5793 * any held lock in the memory range of <from> to <to>:
5795 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
5797 struct task_struct *curr = current;
5798 struct held_lock *hlock;
5799 unsigned long flags;
5802 if (unlikely(!debug_locks))
5805 raw_local_irq_save(flags);
5806 for (i = 0; i < curr->lockdep_depth; i++) {
5807 hlock = curr->held_locks + i;
5809 if (not_in_range(mem_from, mem_len, hlock->instance,
5810 sizeof(*hlock->instance)))
5813 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
5816 raw_local_irq_restore(flags);
5818 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
5820 static void print_held_locks_bug(void)
5822 if (!debug_locks_off())
5824 if (debug_locks_silent)
5828 pr_warn("====================================\n");
5829 pr_warn("WARNING: %s/%d still has locks held!\n",
5830 current->comm, task_pid_nr(current));
5831 print_kernel_ident();
5832 pr_warn("------------------------------------\n");
5833 lockdep_print_held_locks(current);
5834 pr_warn("\nstack backtrace:\n");
5838 void debug_check_no_locks_held(void)
5840 if (unlikely(current->lockdep_depth > 0))
5841 print_held_locks_bug();
5843 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
5846 void debug_show_all_locks(void)
5848 struct task_struct *g, *p;
5850 if (unlikely(!debug_locks)) {
5851 pr_warn("INFO: lockdep is turned off.\n");
5854 pr_warn("\nShowing all locks held in the system:\n");
5857 for_each_process_thread(g, p) {
5858 if (!p->lockdep_depth)
5860 lockdep_print_held_locks(p);
5861 touch_nmi_watchdog();
5862 touch_all_softlockup_watchdogs();
5867 pr_warn("=============================================\n\n");
5869 EXPORT_SYMBOL_GPL(debug_show_all_locks);
5873 * Careful: only use this function if you are sure that
5874 * the task cannot run in parallel!
5876 void debug_show_held_locks(struct task_struct *task)
5878 if (unlikely(!debug_locks)) {
5879 printk("INFO: lockdep is turned off.\n");
5882 lockdep_print_held_locks(task);
5884 EXPORT_SYMBOL_GPL(debug_show_held_locks);
5886 asmlinkage __visible void lockdep_sys_exit(void)
5888 struct task_struct *curr = current;
5890 if (unlikely(curr->lockdep_depth)) {
5891 if (!debug_locks_off())
5894 pr_warn("================================================\n");
5895 pr_warn("WARNING: lock held when returning to user space!\n");
5896 print_kernel_ident();
5897 pr_warn("------------------------------------------------\n");
5898 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
5899 curr->comm, curr->pid);
5900 lockdep_print_held_locks(curr);
5904 * The lock history for each syscall should be independent. So wipe the
5905 * slate clean on return to userspace.
5907 lockdep_invariant_state(false);
5910 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
5912 struct task_struct *curr = current;
5914 /* Note: the following can be executed concurrently, so be careful. */
5916 pr_warn("=============================\n");
5917 pr_warn("WARNING: suspicious RCU usage\n");
5918 print_kernel_ident();
5919 pr_warn("-----------------------------\n");
5920 pr_warn("%s:%d %s!\n", file, line, s);
5921 pr_warn("\nother info that might help us debug this:\n\n");
5922 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
5923 !rcu_lockdep_current_cpu_online()
5924 ? "RCU used illegally from offline CPU!\n"
5926 rcu_scheduler_active, debug_locks);
5929 * If a CPU is in the RCU-free window in idle (ie: in the section
5930 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
5931 * considers that CPU to be in an "extended quiescent state",
5932 * which means that RCU will be completely ignoring that CPU.
5933 * Therefore, rcu_read_lock() and friends have absolutely no
5934 * effect on a CPU running in that state. In other words, even if
5935 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
5936 * delete data structures out from under it. RCU really has no
5937 * choice here: we need to keep an RCU-free window in idle where
5938 * the CPU may possibly enter into low power mode. This way we can
5939 * notice an extended quiescent state to other CPUs that started a grace
5940 * period. Otherwise we would delay any grace period as long as we run
5943 * So complain bitterly if someone does call rcu_read_lock(),
5944 * rcu_read_lock_bh() and so on from extended quiescent states.
5946 if (!rcu_is_watching())
5947 pr_warn("RCU used illegally from extended quiescent state!\n");
5949 lockdep_print_held_locks(curr);
5950 pr_warn("\nstack backtrace:\n");
5953 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);