1 // SPDX-License-Identifier: GPL-2.0-only
5 * Runtime locking correctness validator
7 * Started by Ingo Molnar:
10 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
12 * this code maps all the lock dependencies as they occur in a live kernel
13 * and will warn about the following classes of locking bugs:
15 * - lock inversion scenarios
16 * - circular lock dependencies
17 * - hardirq/softirq safe/unsafe locking bugs
19 * Bugs are reported even if the current locking scenario does not cause
20 * any deadlock at this point.
22 * I.e. if anytime in the past two locks were taken in a different order,
23 * even if it happened for another task, even if those were different
24 * locks (but of the same class as this lock), this code will detect it.
26 * Thanks to Arjan van de Ven for coming up with the initial idea of
27 * mapping lock dependencies runtime.
29 #define DISABLE_BRANCH_PROFILING
30 #include <linux/mutex.h>
31 #include <linux/sched.h>
32 #include <linux/sched/clock.h>
33 #include <linux/sched/task.h>
34 #include <linux/sched/mm.h>
35 #include <linux/delay.h>
36 #include <linux/module.h>
37 #include <linux/proc_fs.h>
38 #include <linux/seq_file.h>
39 #include <linux/spinlock.h>
40 #include <linux/kallsyms.h>
41 #include <linux/interrupt.h>
42 #include <linux/stacktrace.h>
43 #include <linux/debug_locks.h>
44 #include <linux/irqflags.h>
45 #include <linux/utsname.h>
46 #include <linux/hash.h>
47 #include <linux/ftrace.h>
48 #include <linux/stringify.h>
49 #include <linux/bitmap.h>
50 #include <linux/bitops.h>
51 #include <linux/gfp.h>
52 #include <linux/random.h>
53 #include <linux/jhash.h>
54 #include <linux/nmi.h>
55 #include <linux/rcupdate.h>
56 #include <linux/kprobes.h>
57 #include <linux/lockdep.h>
59 #include <asm/sections.h>
61 #include "lockdep_internals.h"
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/lock.h>
66 #ifdef CONFIG_PROVE_LOCKING
67 int prove_locking = 1;
68 module_param(prove_locking, int, 0644);
70 #define prove_locking 0
73 #ifdef CONFIG_LOCK_STAT
75 module_param(lock_stat, int, 0644);
80 DEFINE_PER_CPU(unsigned int, lockdep_recursion);
81 EXPORT_PER_CPU_SYMBOL_GPL(lockdep_recursion);
83 static __always_inline bool lockdep_enabled(void)
88 if (this_cpu_read(lockdep_recursion))
91 if (current->lockdep_recursion)
98 * lockdep_lock: protects the lockdep graph, the hashes and the
99 * class/list/hash allocators.
101 * This is one of the rare exceptions where it's justified
102 * to use a raw spinlock - we really dont want the spinlock
103 * code to recurse back into the lockdep code...
105 static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
106 static struct task_struct *__owner;
108 static inline void lockdep_lock(void)
110 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
112 __this_cpu_inc(lockdep_recursion);
113 arch_spin_lock(&__lock);
117 static inline void lockdep_unlock(void)
119 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
121 if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current))
125 arch_spin_unlock(&__lock);
126 __this_cpu_dec(lockdep_recursion);
129 static inline bool lockdep_assert_locked(void)
131 return DEBUG_LOCKS_WARN_ON(__owner != current);
134 static struct task_struct *lockdep_selftest_task_struct;
137 static int graph_lock(void)
141 * Make sure that if another CPU detected a bug while
142 * walking the graph we dont change it (while the other
143 * CPU is busy printing out stuff with the graph lock
153 static inline void graph_unlock(void)
159 * Turn lock debugging off and return with 0 if it was off already,
160 * and also release the graph lock:
162 static inline int debug_locks_off_graph_unlock(void)
164 int ret = debug_locks_off();
171 unsigned long nr_list_entries;
172 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
173 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
176 * All data structures here are protected by the global debug_lock.
178 * nr_lock_classes is the number of elements of lock_classes[] that is
181 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
182 #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
183 static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
184 unsigned long nr_lock_classes;
185 unsigned long nr_zapped_classes;
186 #ifndef CONFIG_DEBUG_LOCKDEP
189 struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
190 static DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
192 static inline struct lock_class *hlock_class(struct held_lock *hlock)
194 unsigned int class_idx = hlock->class_idx;
196 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
199 if (!test_bit(class_idx, lock_classes_in_use)) {
201 * Someone passed in garbage, we give up.
203 DEBUG_LOCKS_WARN_ON(1);
208 * At this point, if the passed hlock->class_idx is still garbage,
209 * we just have to live with it
211 return lock_classes + class_idx;
214 #ifdef CONFIG_LOCK_STAT
215 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
217 static inline u64 lockstat_clock(void)
219 return local_clock();
222 static int lock_point(unsigned long points[], unsigned long ip)
226 for (i = 0; i < LOCKSTAT_POINTS; i++) {
227 if (points[i] == 0) {
238 static void lock_time_inc(struct lock_time *lt, u64 time)
243 if (time < lt->min || !lt->nr)
250 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
255 if (src->max > dst->max)
258 if (src->min < dst->min || !dst->nr)
261 dst->total += src->total;
265 struct lock_class_stats lock_stats(struct lock_class *class)
267 struct lock_class_stats stats;
270 memset(&stats, 0, sizeof(struct lock_class_stats));
271 for_each_possible_cpu(cpu) {
272 struct lock_class_stats *pcs =
273 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
275 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
276 stats.contention_point[i] += pcs->contention_point[i];
278 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
279 stats.contending_point[i] += pcs->contending_point[i];
281 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
282 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
284 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
285 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
287 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
288 stats.bounces[i] += pcs->bounces[i];
294 void clear_lock_stats(struct lock_class *class)
298 for_each_possible_cpu(cpu) {
299 struct lock_class_stats *cpu_stats =
300 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
302 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
304 memset(class->contention_point, 0, sizeof(class->contention_point));
305 memset(class->contending_point, 0, sizeof(class->contending_point));
308 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
310 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
313 static void lock_release_holdtime(struct held_lock *hlock)
315 struct lock_class_stats *stats;
321 holdtime = lockstat_clock() - hlock->holdtime_stamp;
323 stats = get_lock_stats(hlock_class(hlock));
325 lock_time_inc(&stats->read_holdtime, holdtime);
327 lock_time_inc(&stats->write_holdtime, holdtime);
330 static inline void lock_release_holdtime(struct held_lock *hlock)
336 * We keep a global list of all lock classes. The list is only accessed with
337 * the lockdep spinlock lock held. free_lock_classes is a list with free
338 * elements. These elements are linked together by the lock_entry member in
341 LIST_HEAD(all_lock_classes);
342 static LIST_HEAD(free_lock_classes);
345 * struct pending_free - information about data structures about to be freed
346 * @zapped: Head of a list with struct lock_class elements.
347 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
348 * are about to be freed.
350 struct pending_free {
351 struct list_head zapped;
352 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
356 * struct delayed_free - data structures used for delayed freeing
358 * A data structure for delayed freeing of data structures that may be
359 * accessed by RCU readers at the time these were freed.
361 * @rcu_head: Used to schedule an RCU callback for freeing data structures.
362 * @index: Index of @pf to which freed data structures are added.
363 * @scheduled: Whether or not an RCU callback has been scheduled.
364 * @pf: Array with information about data structures about to be freed.
366 static struct delayed_free {
367 struct rcu_head rcu_head;
370 struct pending_free pf[2];
374 * The lockdep classes are in a hash-table as well, for fast lookup:
376 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
377 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
378 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
379 #define classhashentry(key) (classhash_table + __classhashfn((key)))
381 static struct hlist_head classhash_table[CLASSHASH_SIZE];
384 * We put the lock dependency chains into a hash-table as well, to cache
387 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
388 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
389 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
390 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
392 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
395 * the id of held_lock
397 static inline u16 hlock_id(struct held_lock *hlock)
399 BUILD_BUG_ON(MAX_LOCKDEP_KEYS_BITS + 2 > 16);
401 return (hlock->class_idx | (hlock->read << MAX_LOCKDEP_KEYS_BITS));
404 static inline unsigned int chain_hlock_class_idx(u16 hlock_id)
406 return hlock_id & (MAX_LOCKDEP_KEYS - 1);
410 * The hash key of the lock dependency chains is a hash itself too:
411 * it's a hash of all locks taken up to that lock, including that lock.
412 * It's a 64-bit hash, because it's important for the keys to be
415 static inline u64 iterate_chain_key(u64 key, u32 idx)
417 u32 k0 = key, k1 = key >> 32;
419 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
421 return k0 | (u64)k1 << 32;
424 void lockdep_init_task(struct task_struct *task)
426 task->lockdep_depth = 0; /* no locks held yet */
427 task->curr_chain_key = INITIAL_CHAIN_KEY;
428 task->lockdep_recursion = 0;
431 static __always_inline void lockdep_recursion_inc(void)
433 __this_cpu_inc(lockdep_recursion);
436 static __always_inline void lockdep_recursion_finish(void)
438 if (WARN_ON_ONCE(__this_cpu_dec_return(lockdep_recursion)))
439 __this_cpu_write(lockdep_recursion, 0);
442 void lockdep_set_selftest_task(struct task_struct *task)
444 lockdep_selftest_task_struct = task;
448 * Debugging switches:
452 #define VERY_VERBOSE 0
455 # define HARDIRQ_VERBOSE 1
456 # define SOFTIRQ_VERBOSE 1
458 # define HARDIRQ_VERBOSE 0
459 # define SOFTIRQ_VERBOSE 0
462 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
464 * Quick filtering for interesting events:
466 static int class_filter(struct lock_class *class)
470 if (class->name_version == 1 &&
471 !strcmp(class->name, "lockname"))
473 if (class->name_version == 1 &&
474 !strcmp(class->name, "&struct->lockfield"))
477 /* Filter everything else. 1 would be to allow everything else */
482 static int verbose(struct lock_class *class)
485 return class_filter(class);
490 static void print_lockdep_off(const char *bug_msg)
492 printk(KERN_DEBUG "%s\n", bug_msg);
493 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
494 #ifdef CONFIG_LOCK_STAT
495 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
499 unsigned long nr_stack_trace_entries;
501 #ifdef CONFIG_PROVE_LOCKING
503 * struct lock_trace - single stack backtrace
504 * @hash_entry: Entry in a stack_trace_hash[] list.
505 * @hash: jhash() of @entries.
506 * @nr_entries: Number of entries in @entries.
507 * @entries: Actual stack backtrace.
510 struct hlist_node hash_entry;
513 unsigned long entries[] __aligned(sizeof(unsigned long));
515 #define LOCK_TRACE_SIZE_IN_LONGS \
516 (sizeof(struct lock_trace) / sizeof(unsigned long))
518 * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock.
520 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
521 static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE];
523 static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2)
525 return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries &&
526 memcmp(t1->entries, t2->entries,
527 t1->nr_entries * sizeof(t1->entries[0])) == 0;
530 static struct lock_trace *save_trace(void)
532 struct lock_trace *trace, *t2;
533 struct hlist_head *hash_head;
537 BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE);
538 BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES);
540 trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries);
541 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries -
542 LOCK_TRACE_SIZE_IN_LONGS;
544 if (max_entries <= 0) {
545 if (!debug_locks_off_graph_unlock())
548 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
553 trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3);
555 hash = jhash(trace->entries, trace->nr_entries *
556 sizeof(trace->entries[0]), 0);
558 hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1));
559 hlist_for_each_entry(t2, hash_head, hash_entry) {
560 if (traces_identical(trace, t2))
563 nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries;
564 hlist_add_head(&trace->hash_entry, hash_head);
569 /* Return the number of stack traces in the stack_trace[] array. */
570 u64 lockdep_stack_trace_count(void)
572 struct lock_trace *trace;
576 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) {
577 hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) {
585 /* Return the number of stack hash chains that have at least one stack trace. */
586 u64 lockdep_stack_hash_count(void)
591 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++)
592 if (!hlist_empty(&stack_trace_hash[i]))
599 unsigned int nr_hardirq_chains;
600 unsigned int nr_softirq_chains;
601 unsigned int nr_process_chains;
602 unsigned int max_lockdep_depth;
604 #ifdef CONFIG_DEBUG_LOCKDEP
606 * Various lockdep statistics:
608 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
611 #ifdef CONFIG_PROVE_LOCKING
616 #define __USAGE(__STATE) \
617 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
618 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
619 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
620 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
622 static const char *usage_str[] =
624 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
625 #include "lockdep_states.h"
627 [LOCK_USED] = "INITIAL USE",
628 [LOCK_USED_READ] = "INITIAL READ USE",
629 /* abused as string storage for verify_lock_unused() */
630 [LOCK_USAGE_STATES] = "IN-NMI",
634 const char *__get_key_name(const struct lockdep_subclass_key *key, char *str)
636 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
639 static inline unsigned long lock_flag(enum lock_usage_bit bit)
644 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
647 * The usage character defaults to '.' (i.e., irqs disabled and not in
648 * irq context), which is the safest usage category.
653 * The order of the following usage checks matters, which will
654 * result in the outcome character as follows:
656 * - '+': irq is enabled and not in irq context
657 * - '-': in irq context and irq is disabled
658 * - '?': in irq context and irq is enabled
660 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
662 if (class->usage_mask & lock_flag(bit))
664 } else if (class->usage_mask & lock_flag(bit))
670 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
674 #define LOCKDEP_STATE(__STATE) \
675 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
676 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
677 #include "lockdep_states.h"
683 static void __print_lock_name(struct lock_class *class)
685 char str[KSYM_NAME_LEN];
690 name = __get_key_name(class->key, str);
691 printk(KERN_CONT "%s", name);
693 printk(KERN_CONT "%s", name);
694 if (class->name_version > 1)
695 printk(KERN_CONT "#%d", class->name_version);
697 printk(KERN_CONT "/%d", class->subclass);
701 static void print_lock_name(struct lock_class *class)
703 char usage[LOCK_USAGE_CHARS];
705 get_usage_chars(class, usage);
707 printk(KERN_CONT " (");
708 __print_lock_name(class);
709 printk(KERN_CONT "){%s}-{%d:%d}", usage,
710 class->wait_type_outer ?: class->wait_type_inner,
711 class->wait_type_inner);
714 static void print_lockdep_cache(struct lockdep_map *lock)
717 char str[KSYM_NAME_LEN];
721 name = __get_key_name(lock->key->subkeys, str);
723 printk(KERN_CONT "%s", name);
726 static void print_lock(struct held_lock *hlock)
729 * We can be called locklessly through debug_show_all_locks() so be
730 * extra careful, the hlock might have been released and cleared.
732 * If this indeed happens, lets pretend it does not hurt to continue
733 * to print the lock unless the hlock class_idx does not point to a
734 * registered class. The rationale here is: since we don't attempt
735 * to distinguish whether we are in this situation, if it just
736 * happened we can't count on class_idx to tell either.
738 struct lock_class *lock = hlock_class(hlock);
741 printk(KERN_CONT "<RELEASED>\n");
745 printk(KERN_CONT "%px", hlock->instance);
746 print_lock_name(lock);
747 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
750 static void lockdep_print_held_locks(struct task_struct *p)
752 int i, depth = READ_ONCE(p->lockdep_depth);
755 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
757 printk("%d lock%s held by %s/%d:\n", depth,
758 depth > 1 ? "s" : "", p->comm, task_pid_nr(p));
760 * It's not reliable to print a task's held locks if it's not sleeping
761 * and it's not the current task.
763 if (p->state == TASK_RUNNING && p != current)
765 for (i = 0; i < depth; i++) {
767 print_lock(p->held_locks + i);
771 static void print_kernel_ident(void)
773 printk("%s %.*s %s\n", init_utsname()->release,
774 (int)strcspn(init_utsname()->version, " "),
775 init_utsname()->version,
779 static int very_verbose(struct lock_class *class)
782 return class_filter(class);
788 * Is this the address of a static object:
791 static int static_obj(const void *obj)
793 unsigned long start = (unsigned long) &_stext,
794 end = (unsigned long) &_end,
795 addr = (unsigned long) obj;
797 if (arch_is_kernel_initmem_freed(addr))
803 if ((addr >= start) && (addr < end))
806 if (arch_is_kernel_data(addr))
810 * in-kernel percpu var?
812 if (is_kernel_percpu_address(addr))
816 * module static or percpu var?
818 return is_module_address(addr) || is_module_percpu_address(addr);
823 * To make lock name printouts unique, we calculate a unique
824 * class->name_version generation counter. The caller must hold the graph
827 static int count_matching_names(struct lock_class *new_class)
829 struct lock_class *class;
832 if (!new_class->name)
835 list_for_each_entry(class, &all_lock_classes, lock_entry) {
836 if (new_class->key - new_class->subclass == class->key)
837 return class->name_version;
838 if (class->name && !strcmp(class->name, new_class->name))
839 count = max(count, class->name_version);
845 /* used from NMI context -- must be lockless */
846 static __always_inline struct lock_class *
847 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
849 struct lockdep_subclass_key *key;
850 struct hlist_head *hash_head;
851 struct lock_class *class;
853 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
856 "BUG: looking up invalid subclass: %u\n", subclass);
858 "turning off the locking correctness validator.\n");
864 * If it is not initialised then it has never been locked,
865 * so it won't be present in the hash table.
867 if (unlikely(!lock->key))
871 * NOTE: the class-key must be unique. For dynamic locks, a static
872 * lock_class_key variable is passed in through the mutex_init()
873 * (or spin_lock_init()) call - which acts as the key. For static
874 * locks we use the lock object itself as the key.
876 BUILD_BUG_ON(sizeof(struct lock_class_key) >
877 sizeof(struct lockdep_map));
879 key = lock->key->subkeys + subclass;
881 hash_head = classhashentry(key);
884 * We do an RCU walk of the hash, see lockdep_free_key_range().
886 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
889 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
890 if (class->key == key) {
892 * Huh! same key, different name? Did someone trample
893 * on some memory? We're most confused.
895 WARN_ON_ONCE(class->name != lock->name &&
896 lock->key != &__lockdep_no_validate__);
905 * Static locks do not have their class-keys yet - for them the key is
906 * the lock object itself. If the lock is in the per cpu area, the
907 * canonical address of the lock (per cpu offset removed) is used.
909 static bool assign_lock_key(struct lockdep_map *lock)
911 unsigned long can_addr, addr = (unsigned long)lock;
915 * lockdep_free_key_range() assumes that struct lock_class_key
916 * objects do not overlap. Since we use the address of lock
917 * objects as class key for static objects, check whether the
918 * size of lock_class_key objects does not exceed the size of
919 * the smallest lock object.
921 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
924 if (__is_kernel_percpu_address(addr, &can_addr))
925 lock->key = (void *)can_addr;
926 else if (__is_module_percpu_address(addr, &can_addr))
927 lock->key = (void *)can_addr;
928 else if (static_obj(lock))
929 lock->key = (void *)lock;
931 /* Debug-check: all keys must be persistent! */
933 pr_err("INFO: trying to register non-static key.\n");
934 pr_err("The code is fine but needs lockdep annotation, or maybe\n");
935 pr_err("you didn't initialize this object before use?\n");
936 pr_err("turning off the locking correctness validator.\n");
944 #ifdef CONFIG_DEBUG_LOCKDEP
946 /* Check whether element @e occurs in list @h */
947 static bool in_list(struct list_head *e, struct list_head *h)
951 list_for_each(f, h) {
960 * Check whether entry @e occurs in any of the locks_after or locks_before
963 static bool in_any_class_list(struct list_head *e)
965 struct lock_class *class;
968 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
969 class = &lock_classes[i];
970 if (in_list(e, &class->locks_after) ||
971 in_list(e, &class->locks_before))
977 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
981 list_for_each_entry(e, h, entry) {
982 if (e->links_to != c) {
983 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
985 (unsigned long)(e - list_entries),
986 e->links_to && e->links_to->name ?
987 e->links_to->name : "(?)",
988 e->class && e->class->name ? e->class->name :
996 #ifdef CONFIG_PROVE_LOCKING
997 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
1000 static bool check_lock_chain_key(struct lock_chain *chain)
1002 #ifdef CONFIG_PROVE_LOCKING
1003 u64 chain_key = INITIAL_CHAIN_KEY;
1006 for (i = chain->base; i < chain->base + chain->depth; i++)
1007 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
1009 * The 'unsigned long long' casts avoid that a compiler warning
1010 * is reported when building tools/lib/lockdep.
1012 if (chain->chain_key != chain_key) {
1013 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
1014 (unsigned long long)(chain - lock_chains),
1015 (unsigned long long)chain->chain_key,
1016 (unsigned long long)chain_key);
1023 static bool in_any_zapped_class_list(struct lock_class *class)
1025 struct pending_free *pf;
1028 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
1029 if (in_list(&class->lock_entry, &pf->zapped))
1036 static bool __check_data_structures(void)
1038 struct lock_class *class;
1039 struct lock_chain *chain;
1040 struct hlist_head *head;
1041 struct lock_list *e;
1044 /* Check whether all classes occur in a lock list. */
1045 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1046 class = &lock_classes[i];
1047 if (!in_list(&class->lock_entry, &all_lock_classes) &&
1048 !in_list(&class->lock_entry, &free_lock_classes) &&
1049 !in_any_zapped_class_list(class)) {
1050 printk(KERN_INFO "class %px/%s is not in any class list\n",
1051 class, class->name ? : "(?)");
1056 /* Check whether all classes have valid lock lists. */
1057 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1058 class = &lock_classes[i];
1059 if (!class_lock_list_valid(class, &class->locks_before))
1061 if (!class_lock_list_valid(class, &class->locks_after))
1065 /* Check the chain_key of all lock chains. */
1066 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
1067 head = chainhash_table + i;
1068 hlist_for_each_entry_rcu(chain, head, entry) {
1069 if (!check_lock_chain_key(chain))
1075 * Check whether all list entries that are in use occur in a class
1078 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1079 e = list_entries + i;
1080 if (!in_any_class_list(&e->entry)) {
1081 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
1082 (unsigned int)(e - list_entries),
1083 e->class->name ? : "(?)",
1084 e->links_to->name ? : "(?)");
1090 * Check whether all list entries that are not in use do not occur in
1091 * a class lock list.
1093 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1094 e = list_entries + i;
1095 if (in_any_class_list(&e->entry)) {
1096 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
1097 (unsigned int)(e - list_entries),
1098 e->class && e->class->name ? e->class->name :
1100 e->links_to && e->links_to->name ?
1101 e->links_to->name : "(?)");
1109 int check_consistency = 0;
1110 module_param(check_consistency, int, 0644);
1112 static void check_data_structures(void)
1114 static bool once = false;
1116 if (check_consistency && !once) {
1117 if (!__check_data_structures()) {
1124 #else /* CONFIG_DEBUG_LOCKDEP */
1126 static inline void check_data_structures(void) { }
1128 #endif /* CONFIG_DEBUG_LOCKDEP */
1130 static void init_chain_block_buckets(void);
1133 * Initialize the lock_classes[] array elements, the free_lock_classes list
1134 * and also the delayed_free structure.
1136 static void init_data_structures_once(void)
1138 static bool __read_mostly ds_initialized, rcu_head_initialized;
1141 if (likely(rcu_head_initialized))
1144 if (system_state >= SYSTEM_SCHEDULING) {
1145 init_rcu_head(&delayed_free.rcu_head);
1146 rcu_head_initialized = true;
1152 ds_initialized = true;
1154 INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
1155 INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
1157 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1158 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
1159 INIT_LIST_HEAD(&lock_classes[i].locks_after);
1160 INIT_LIST_HEAD(&lock_classes[i].locks_before);
1162 init_chain_block_buckets();
1165 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
1167 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
1169 return lock_keys_hash + hash;
1172 /* Register a dynamically allocated key. */
1173 void lockdep_register_key(struct lock_class_key *key)
1175 struct hlist_head *hash_head;
1176 struct lock_class_key *k;
1177 unsigned long flags;
1179 if (WARN_ON_ONCE(static_obj(key)))
1181 hash_head = keyhashentry(key);
1183 raw_local_irq_save(flags);
1186 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1187 if (WARN_ON_ONCE(k == key))
1190 hlist_add_head_rcu(&key->hash_entry, hash_head);
1194 raw_local_irq_restore(flags);
1196 EXPORT_SYMBOL_GPL(lockdep_register_key);
1198 /* Check whether a key has been registered as a dynamic key. */
1199 static bool is_dynamic_key(const struct lock_class_key *key)
1201 struct hlist_head *hash_head;
1202 struct lock_class_key *k;
1205 if (WARN_ON_ONCE(static_obj(key)))
1209 * If lock debugging is disabled lock_keys_hash[] may contain
1210 * pointers to memory that has already been freed. Avoid triggering
1211 * a use-after-free in that case by returning early.
1216 hash_head = keyhashentry(key);
1219 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1231 * Register a lock's class in the hash-table, if the class is not present
1232 * yet. Otherwise we look it up. We cache the result in the lock object
1233 * itself, so actual lookup of the hash should be once per lock object.
1235 static struct lock_class *
1236 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1238 struct lockdep_subclass_key *key;
1239 struct hlist_head *hash_head;
1240 struct lock_class *class;
1242 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1244 class = look_up_lock_class(lock, subclass);
1246 goto out_set_class_cache;
1249 if (!assign_lock_key(lock))
1251 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
1255 key = lock->key->subkeys + subclass;
1256 hash_head = classhashentry(key);
1258 if (!graph_lock()) {
1262 * We have to do the hash-walk again, to avoid races
1265 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
1266 if (class->key == key)
1267 goto out_unlock_set;
1270 init_data_structures_once();
1272 /* Allocate a new lock class and add it to the hash. */
1273 class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
1276 if (!debug_locks_off_graph_unlock()) {
1280 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
1285 __set_bit(class - lock_classes, lock_classes_in_use);
1286 debug_atomic_inc(nr_unused_locks);
1288 class->name = lock->name;
1289 class->subclass = subclass;
1290 WARN_ON_ONCE(!list_empty(&class->locks_before));
1291 WARN_ON_ONCE(!list_empty(&class->locks_after));
1292 class->name_version = count_matching_names(class);
1293 class->wait_type_inner = lock->wait_type_inner;
1294 class->wait_type_outer = lock->wait_type_outer;
1295 class->lock_type = lock->lock_type;
1297 * We use RCU's safe list-add method to make
1298 * parallel walking of the hash-list safe:
1300 hlist_add_head_rcu(&class->hash_entry, hash_head);
1302 * Remove the class from the free list and add it to the global list
1305 list_move_tail(&class->lock_entry, &all_lock_classes);
1307 if (verbose(class)) {
1310 printk("\nnew class %px: %s", class->key, class->name);
1311 if (class->name_version > 1)
1312 printk(KERN_CONT "#%d", class->name_version);
1313 printk(KERN_CONT "\n");
1316 if (!graph_lock()) {
1323 out_set_class_cache:
1324 if (!subclass || force)
1325 lock->class_cache[0] = class;
1326 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
1327 lock->class_cache[subclass] = class;
1330 * Hash collision, did we smoke some? We found a class with a matching
1331 * hash but the subclass -- which is hashed in -- didn't match.
1333 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
1339 #ifdef CONFIG_PROVE_LOCKING
1341 * Allocate a lockdep entry. (assumes the graph_lock held, returns
1342 * with NULL on failure)
1344 static struct lock_list *alloc_list_entry(void)
1346 int idx = find_first_zero_bit(list_entries_in_use,
1347 ARRAY_SIZE(list_entries));
1349 if (idx >= ARRAY_SIZE(list_entries)) {
1350 if (!debug_locks_off_graph_unlock())
1353 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
1358 __set_bit(idx, list_entries_in_use);
1359 return list_entries + idx;
1363 * Add a new dependency to the head of the list:
1365 static int add_lock_to_list(struct lock_class *this,
1366 struct lock_class *links_to, struct list_head *head,
1367 unsigned long ip, u16 distance, u8 dep,
1368 const struct lock_trace *trace)
1370 struct lock_list *entry;
1372 * Lock not present yet - get a new dependency struct and
1373 * add it to the list:
1375 entry = alloc_list_entry();
1379 entry->class = this;
1380 entry->links_to = links_to;
1382 entry->distance = distance;
1383 entry->trace = trace;
1385 * Both allocation and removal are done under the graph lock; but
1386 * iteration is under RCU-sched; see look_up_lock_class() and
1387 * lockdep_free_key_range().
1389 list_add_tail_rcu(&entry->entry, head);
1395 * For good efficiency of modular, we use power of 2
1397 #define MAX_CIRCULAR_QUEUE_SIZE (1UL << CONFIG_LOCKDEP_CIRCULAR_QUEUE_BITS)
1398 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
1401 * The circular_queue and helpers are used to implement graph
1402 * breadth-first search (BFS) algorithm, by which we can determine
1403 * whether there is a path from a lock to another. In deadlock checks,
1404 * a path from the next lock to be acquired to a previous held lock
1405 * indicates that adding the <prev> -> <next> lock dependency will
1406 * produce a circle in the graph. Breadth-first search instead of
1407 * depth-first search is used in order to find the shortest (circular)
1410 struct circular_queue {
1411 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
1412 unsigned int front, rear;
1415 static struct circular_queue lock_cq;
1417 unsigned int max_bfs_queue_depth;
1419 static unsigned int lockdep_dependency_gen_id;
1421 static inline void __cq_init(struct circular_queue *cq)
1423 cq->front = cq->rear = 0;
1424 lockdep_dependency_gen_id++;
1427 static inline int __cq_empty(struct circular_queue *cq)
1429 return (cq->front == cq->rear);
1432 static inline int __cq_full(struct circular_queue *cq)
1434 return ((cq->rear + 1) & CQ_MASK) == cq->front;
1437 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
1442 cq->element[cq->rear] = elem;
1443 cq->rear = (cq->rear + 1) & CQ_MASK;
1448 * Dequeue an element from the circular_queue, return a lock_list if
1449 * the queue is not empty, or NULL if otherwise.
1451 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
1453 struct lock_list * lock;
1458 lock = cq->element[cq->front];
1459 cq->front = (cq->front + 1) & CQ_MASK;
1464 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
1466 return (cq->rear - cq->front) & CQ_MASK;
1469 static inline void mark_lock_accessed(struct lock_list *lock)
1471 lock->class->dep_gen_id = lockdep_dependency_gen_id;
1474 static inline void visit_lock_entry(struct lock_list *lock,
1475 struct lock_list *parent)
1477 lock->parent = parent;
1480 static inline unsigned long lock_accessed(struct lock_list *lock)
1482 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
1485 static inline struct lock_list *get_lock_parent(struct lock_list *child)
1487 return child->parent;
1490 static inline int get_lock_depth(struct lock_list *child)
1493 struct lock_list *parent;
1495 while ((parent = get_lock_parent(child))) {
1503 * Return the forward or backward dependency list.
1505 * @lock: the lock_list to get its class's dependency list
1506 * @offset: the offset to struct lock_class to determine whether it is
1507 * locks_after or locks_before
1509 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
1511 void *lock_class = lock->class;
1513 return lock_class + offset;
1516 * Return values of a bfs search:
1518 * BFS_E* indicates an error
1519 * BFS_R* indicates a result (match or not)
1521 * BFS_EINVALIDNODE: Find a invalid node in the graph.
1523 * BFS_EQUEUEFULL: The queue is full while doing the bfs.
1525 * BFS_RMATCH: Find the matched node in the graph, and put that node into
1528 * BFS_RNOMATCH: Haven't found the matched node and keep *@target_entry
1532 BFS_EINVALIDNODE = -2,
1533 BFS_EQUEUEFULL = -1,
1539 * bfs_result < 0 means error
1541 static inline bool bfs_error(enum bfs_result res)
1547 * DEP_*_BIT in lock_list::dep
1549 * For dependency @prev -> @next:
1551 * SR: @prev is shared reader (->read != 0) and @next is recursive reader
1553 * ER: @prev is exclusive locker (->read == 0) and @next is recursive reader
1554 * SN: @prev is shared reader and @next is non-recursive locker (->read != 2)
1555 * EN: @prev is exclusive locker and @next is non-recursive locker
1557 * Note that we define the value of DEP_*_BITs so that:
1558 * bit0 is prev->read == 0
1559 * bit1 is next->read != 2
1561 #define DEP_SR_BIT (0 + (0 << 1)) /* 0 */
1562 #define DEP_ER_BIT (1 + (0 << 1)) /* 1 */
1563 #define DEP_SN_BIT (0 + (1 << 1)) /* 2 */
1564 #define DEP_EN_BIT (1 + (1 << 1)) /* 3 */
1566 #define DEP_SR_MASK (1U << (DEP_SR_BIT))
1567 #define DEP_ER_MASK (1U << (DEP_ER_BIT))
1568 #define DEP_SN_MASK (1U << (DEP_SN_BIT))
1569 #define DEP_EN_MASK (1U << (DEP_EN_BIT))
1571 static inline unsigned int
1572 __calc_dep_bit(struct held_lock *prev, struct held_lock *next)
1574 return (prev->read == 0) + ((next->read != 2) << 1);
1577 static inline u8 calc_dep(struct held_lock *prev, struct held_lock *next)
1579 return 1U << __calc_dep_bit(prev, next);
1583 * calculate the dep_bit for backwards edges. We care about whether @prev is
1584 * shared and whether @next is recursive.
1586 static inline unsigned int
1587 __calc_dep_bitb(struct held_lock *prev, struct held_lock *next)
1589 return (next->read != 2) + ((prev->read == 0) << 1);
1592 static inline u8 calc_depb(struct held_lock *prev, struct held_lock *next)
1594 return 1U << __calc_dep_bitb(prev, next);
1598 * Initialize a lock_list entry @lock belonging to @class as the root for a BFS
1601 static inline void __bfs_init_root(struct lock_list *lock,
1602 struct lock_class *class)
1604 lock->class = class;
1605 lock->parent = NULL;
1610 * Initialize a lock_list entry @lock based on a lock acquisition @hlock as the
1611 * root for a BFS search.
1613 * ->only_xr of the initial lock node is set to @hlock->read == 2, to make sure
1614 * that <prev> -> @hlock and @hlock -> <whatever __bfs() found> is not -(*R)->
1617 static inline void bfs_init_root(struct lock_list *lock,
1618 struct held_lock *hlock)
1620 __bfs_init_root(lock, hlock_class(hlock));
1621 lock->only_xr = (hlock->read == 2);
1625 * Similar to bfs_init_root() but initialize the root for backwards BFS.
1627 * ->only_xr of the initial lock node is set to @hlock->read != 0, to make sure
1628 * that <next> -> @hlock and @hlock -> <whatever backwards BFS found> is not
1629 * -(*S)-> and -(R*)-> (reverse order of -(*R)-> and -(S*)->).
1631 static inline void bfs_init_rootb(struct lock_list *lock,
1632 struct held_lock *hlock)
1634 __bfs_init_root(lock, hlock_class(hlock));
1635 lock->only_xr = (hlock->read != 0);
1638 static inline struct lock_list *__bfs_next(struct lock_list *lock, int offset)
1640 if (!lock || !lock->parent)
1643 return list_next_or_null_rcu(get_dep_list(lock->parent, offset),
1644 &lock->entry, struct lock_list, entry);
1648 * Breadth-First Search to find a strong path in the dependency graph.
1650 * @source_entry: the source of the path we are searching for.
1651 * @data: data used for the second parameter of @match function
1652 * @match: match function for the search
1653 * @target_entry: pointer to the target of a matched path
1654 * @offset: the offset to struct lock_class to determine whether it is
1655 * locks_after or locks_before
1657 * We may have multiple edges (considering different kinds of dependencies,
1658 * e.g. ER and SN) between two nodes in the dependency graph. But
1659 * only the strong dependency path in the graph is relevant to deadlocks. A
1660 * strong dependency path is a dependency path that doesn't have two adjacent
1661 * dependencies as -(*R)-> -(S*)->, please see:
1663 * Documentation/locking/lockdep-design.rst
1665 * for more explanation of the definition of strong dependency paths
1667 * In __bfs(), we only traverse in the strong dependency path:
1669 * In lock_list::only_xr, we record whether the previous dependency only
1670 * has -(*R)-> in the search, and if it does (prev only has -(*R)->), we
1671 * filter out any -(S*)-> in the current dependency and after that, the
1672 * ->only_xr is set according to whether we only have -(*R)-> left.
1674 static enum bfs_result __bfs(struct lock_list *source_entry,
1676 bool (*match)(struct lock_list *entry, void *data),
1677 bool (*skip)(struct lock_list *entry, void *data),
1678 struct lock_list **target_entry,
1681 struct circular_queue *cq = &lock_cq;
1682 struct lock_list *lock = NULL;
1683 struct lock_list *entry;
1684 struct list_head *head;
1685 unsigned int cq_depth;
1688 lockdep_assert_locked();
1691 __cq_enqueue(cq, source_entry);
1693 while ((lock = __bfs_next(lock, offset)) || (lock = __cq_dequeue(cq))) {
1695 return BFS_EINVALIDNODE;
1698 * Step 1: check whether we already finish on this one.
1700 * If we have visited all the dependencies from this @lock to
1701 * others (iow, if we have visited all lock_list entries in
1702 * @lock->class->locks_{after,before}) we skip, otherwise go
1703 * and visit all the dependencies in the list and mark this
1706 if (lock_accessed(lock))
1709 mark_lock_accessed(lock);
1712 * Step 2: check whether prev dependency and this form a strong
1715 if (lock->parent) { /* Parent exists, check prev dependency */
1717 bool prev_only_xr = lock->parent->only_xr;
1720 * Mask out all -(S*)-> if we only have *R in previous
1721 * step, because -(*R)-> -(S*)-> don't make up a strong
1725 dep &= ~(DEP_SR_MASK | DEP_SN_MASK);
1727 /* If nothing left, we skip */
1731 /* If there are only -(*R)-> left, set that for the next step */
1732 lock->only_xr = !(dep & (DEP_SN_MASK | DEP_EN_MASK));
1736 * Step 3: we haven't visited this and there is a strong
1737 * dependency path to this, so check with @match.
1738 * If @skip is provide and returns true, we skip this
1739 * lock (and any path this lock is in).
1741 if (skip && skip(lock, data))
1744 if (match(lock, data)) {
1745 *target_entry = lock;
1750 * Step 4: if not match, expand the path by adding the
1751 * forward or backwards dependencies in the search
1755 head = get_dep_list(lock, offset);
1756 list_for_each_entry_rcu(entry, head, entry) {
1757 visit_lock_entry(entry, lock);
1760 * Note we only enqueue the first of the list into the
1761 * queue, because we can always find a sibling
1762 * dependency from one (see __bfs_next()), as a result
1763 * the space of queue is saved.
1770 if (__cq_enqueue(cq, entry))
1771 return BFS_EQUEUEFULL;
1773 cq_depth = __cq_get_elem_count(cq);
1774 if (max_bfs_queue_depth < cq_depth)
1775 max_bfs_queue_depth = cq_depth;
1779 return BFS_RNOMATCH;
1782 static inline enum bfs_result
1783 __bfs_forwards(struct lock_list *src_entry,
1785 bool (*match)(struct lock_list *entry, void *data),
1786 bool (*skip)(struct lock_list *entry, void *data),
1787 struct lock_list **target_entry)
1789 return __bfs(src_entry, data, match, skip, target_entry,
1790 offsetof(struct lock_class, locks_after));
1794 static inline enum bfs_result
1795 __bfs_backwards(struct lock_list *src_entry,
1797 bool (*match)(struct lock_list *entry, void *data),
1798 bool (*skip)(struct lock_list *entry, void *data),
1799 struct lock_list **target_entry)
1801 return __bfs(src_entry, data, match, skip, target_entry,
1802 offsetof(struct lock_class, locks_before));
1806 static void print_lock_trace(const struct lock_trace *trace,
1807 unsigned int spaces)
1809 stack_trace_print(trace->entries, trace->nr_entries, spaces);
1813 * Print a dependency chain entry (this is only done when a deadlock
1814 * has been detected):
1816 static noinline void
1817 print_circular_bug_entry(struct lock_list *target, int depth)
1819 if (debug_locks_silent)
1821 printk("\n-> #%u", depth);
1822 print_lock_name(target->class);
1823 printk(KERN_CONT ":\n");
1824 print_lock_trace(target->trace, 6);
1828 print_circular_lock_scenario(struct held_lock *src,
1829 struct held_lock *tgt,
1830 struct lock_list *prt)
1832 struct lock_class *source = hlock_class(src);
1833 struct lock_class *target = hlock_class(tgt);
1834 struct lock_class *parent = prt->class;
1837 * A direct locking problem where unsafe_class lock is taken
1838 * directly by safe_class lock, then all we need to show
1839 * is the deadlock scenario, as it is obvious that the
1840 * unsafe lock is taken under the safe lock.
1842 * But if there is a chain instead, where the safe lock takes
1843 * an intermediate lock (middle_class) where this lock is
1844 * not the same as the safe lock, then the lock chain is
1845 * used to describe the problem. Otherwise we would need
1846 * to show a different CPU case for each link in the chain
1847 * from the safe_class lock to the unsafe_class lock.
1849 if (parent != source) {
1850 printk("Chain exists of:\n ");
1851 __print_lock_name(source);
1852 printk(KERN_CONT " --> ");
1853 __print_lock_name(parent);
1854 printk(KERN_CONT " --> ");
1855 __print_lock_name(target);
1856 printk(KERN_CONT "\n\n");
1859 printk(" Possible unsafe locking scenario:\n\n");
1860 printk(" CPU0 CPU1\n");
1861 printk(" ---- ----\n");
1863 __print_lock_name(target);
1864 printk(KERN_CONT ");\n");
1866 __print_lock_name(parent);
1867 printk(KERN_CONT ");\n");
1869 __print_lock_name(target);
1870 printk(KERN_CONT ");\n");
1872 __print_lock_name(source);
1873 printk(KERN_CONT ");\n");
1874 printk("\n *** DEADLOCK ***\n\n");
1878 * When a circular dependency is detected, print the
1881 static noinline void
1882 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1883 struct held_lock *check_src,
1884 struct held_lock *check_tgt)
1886 struct task_struct *curr = current;
1888 if (debug_locks_silent)
1892 pr_warn("======================================================\n");
1893 pr_warn("WARNING: possible circular locking dependency detected\n");
1894 print_kernel_ident();
1895 pr_warn("------------------------------------------------------\n");
1896 pr_warn("%s/%d is trying to acquire lock:\n",
1897 curr->comm, task_pid_nr(curr));
1898 print_lock(check_src);
1900 pr_warn("\nbut task is already holding lock:\n");
1902 print_lock(check_tgt);
1903 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1904 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1906 print_circular_bug_entry(entry, depth);
1910 * We are about to add A -> B into the dependency graph, and in __bfs() a
1911 * strong dependency path A -> .. -> B is found: hlock_class equals
1914 * If A -> .. -> B can replace A -> B in any __bfs() search (means the former
1915 * is _stronger_ than or equal to the latter), we consider A -> B as redundant.
1916 * For example if A -> .. -> B is -(EN)-> (i.e. A -(E*)-> .. -(*N)-> B), and A
1917 * -> B is -(ER)-> or -(EN)->, then we don't need to add A -> B into the
1918 * dependency graph, as any strong path ..-> A -> B ->.. we can get with
1919 * having dependency A -> B, we could already get a equivalent path ..-> A ->
1920 * .. -> B -> .. with A -> .. -> B. Therefore A -> B is redundant.
1922 * We need to make sure both the start and the end of A -> .. -> B is not
1923 * weaker than A -> B. For the start part, please see the comment in
1924 * check_redundant(). For the end part, we need:
1928 * a) A -> B is -(*R)-> (everything is not weaker than that)
1932 * b) A -> .. -> B is -(*N)-> (nothing is stronger than this)
1935 static inline bool hlock_equal(struct lock_list *entry, void *data)
1937 struct held_lock *hlock = (struct held_lock *)data;
1939 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
1940 (hlock->read == 2 || /* A -> B is -(*R)-> */
1941 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
1945 * We are about to add B -> A into the dependency graph, and in __bfs() a
1946 * strong dependency path A -> .. -> B is found: hlock_class equals
1949 * We will have a deadlock case (conflict) if A -> .. -> B -> A is a strong
1950 * dependency cycle, that means:
1954 * a) B -> A is -(E*)->
1958 * b) A -> .. -> B is -(*N)-> (i.e. A -> .. -(*N)-> B)
1960 * as then we don't have -(*R)-> -(S*)-> in the cycle.
1962 static inline bool hlock_conflict(struct lock_list *entry, void *data)
1964 struct held_lock *hlock = (struct held_lock *)data;
1966 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
1967 (hlock->read == 0 || /* B -> A is -(E*)-> */
1968 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
1971 static noinline void print_circular_bug(struct lock_list *this,
1972 struct lock_list *target,
1973 struct held_lock *check_src,
1974 struct held_lock *check_tgt)
1976 struct task_struct *curr = current;
1977 struct lock_list *parent;
1978 struct lock_list *first_parent;
1981 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1984 this->trace = save_trace();
1988 depth = get_lock_depth(target);
1990 print_circular_bug_header(target, depth, check_src, check_tgt);
1992 parent = get_lock_parent(target);
1993 first_parent = parent;
1996 print_circular_bug_entry(parent, --depth);
1997 parent = get_lock_parent(parent);
2000 printk("\nother info that might help us debug this:\n\n");
2001 print_circular_lock_scenario(check_src, check_tgt,
2004 lockdep_print_held_locks(curr);
2006 printk("\nstack backtrace:\n");
2010 static noinline void print_bfs_bug(int ret)
2012 if (!debug_locks_off_graph_unlock())
2016 * Breadth-first-search failed, graph got corrupted?
2018 WARN(1, "lockdep bfs error:%d\n", ret);
2021 static bool noop_count(struct lock_list *entry, void *data)
2023 (*(unsigned long *)data)++;
2027 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
2029 unsigned long count = 0;
2030 struct lock_list *target_entry;
2032 __bfs_forwards(this, (void *)&count, noop_count, NULL, &target_entry);
2036 unsigned long lockdep_count_forward_deps(struct lock_class *class)
2038 unsigned long ret, flags;
2039 struct lock_list this;
2041 __bfs_init_root(&this, class);
2043 raw_local_irq_save(flags);
2045 ret = __lockdep_count_forward_deps(&this);
2047 raw_local_irq_restore(flags);
2052 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
2054 unsigned long count = 0;
2055 struct lock_list *target_entry;
2057 __bfs_backwards(this, (void *)&count, noop_count, NULL, &target_entry);
2062 unsigned long lockdep_count_backward_deps(struct lock_class *class)
2064 unsigned long ret, flags;
2065 struct lock_list this;
2067 __bfs_init_root(&this, class);
2069 raw_local_irq_save(flags);
2071 ret = __lockdep_count_backward_deps(&this);
2073 raw_local_irq_restore(flags);
2079 * Check that the dependency graph starting at <src> can lead to
2082 static noinline enum bfs_result
2083 check_path(struct held_lock *target, struct lock_list *src_entry,
2084 bool (*match)(struct lock_list *entry, void *data),
2085 bool (*skip)(struct lock_list *entry, void *data),
2086 struct lock_list **target_entry)
2088 enum bfs_result ret;
2090 ret = __bfs_forwards(src_entry, target, match, skip, target_entry);
2092 if (unlikely(bfs_error(ret)))
2099 * Prove that the dependency graph starting at <src> can not
2100 * lead to <target>. If it can, there is a circle when adding
2101 * <target> -> <src> dependency.
2103 * Print an error and return BFS_RMATCH if it does.
2105 static noinline enum bfs_result
2106 check_noncircular(struct held_lock *src, struct held_lock *target,
2107 struct lock_trace **const trace)
2109 enum bfs_result ret;
2110 struct lock_list *target_entry;
2111 struct lock_list src_entry;
2113 bfs_init_root(&src_entry, src);
2115 debug_atomic_inc(nr_cyclic_checks);
2117 ret = check_path(target, &src_entry, hlock_conflict, NULL, &target_entry);
2119 if (unlikely(ret == BFS_RMATCH)) {
2122 * If save_trace fails here, the printing might
2123 * trigger a WARN but because of the !nr_entries it
2124 * should not do bad things.
2126 *trace = save_trace();
2129 print_circular_bug(&src_entry, target_entry, src, target);
2135 #ifdef CONFIG_TRACE_IRQFLAGS
2138 * Forwards and backwards subgraph searching, for the purposes of
2139 * proving that two subgraphs can be connected by a new dependency
2140 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
2142 * A irq safe->unsafe deadlock happens with the following conditions:
2144 * 1) We have a strong dependency path A -> ... -> B
2146 * 2) and we have ENABLED_IRQ usage of B and USED_IN_IRQ usage of A, therefore
2147 * irq can create a new dependency B -> A (consider the case that a holder
2148 * of B gets interrupted by an irq whose handler will try to acquire A).
2150 * 3) the dependency circle A -> ... -> B -> A we get from 1) and 2) is a
2153 * For the usage bits of B:
2154 * a) if A -> B is -(*N)->, then B -> A could be any type, so any
2155 * ENABLED_IRQ usage suffices.
2156 * b) if A -> B is -(*R)->, then B -> A must be -(E*)->, so only
2157 * ENABLED_IRQ_*_READ usage suffices.
2159 * For the usage bits of A:
2160 * c) if A -> B is -(E*)->, then B -> A could be any type, so any
2161 * USED_IN_IRQ usage suffices.
2162 * d) if A -> B is -(S*)->, then B -> A must be -(*N)->, so only
2163 * USED_IN_IRQ_*_READ usage suffices.
2167 * There is a strong dependency path in the dependency graph: A -> B, and now
2168 * we need to decide which usage bit of A should be accumulated to detect
2169 * safe->unsafe bugs.
2171 * Note that usage_accumulate() is used in backwards search, so ->only_xr
2172 * stands for whether A -> B only has -(S*)-> (in this case ->only_xr is true).
2174 * As above, if only_xr is false, which means A -> B has -(E*)-> dependency
2175 * path, any usage of A should be considered. Otherwise, we should only
2176 * consider _READ usage.
2178 static inline bool usage_accumulate(struct lock_list *entry, void *mask)
2180 if (!entry->only_xr)
2181 *(unsigned long *)mask |= entry->class->usage_mask;
2182 else /* Mask out _READ usage bits */
2183 *(unsigned long *)mask |= (entry->class->usage_mask & LOCKF_IRQ);
2189 * There is a strong dependency path in the dependency graph: A -> B, and now
2190 * we need to decide which usage bit of B conflicts with the usage bits of A,
2191 * i.e. which usage bit of B may introduce safe->unsafe deadlocks.
2193 * As above, if only_xr is false, which means A -> B has -(*N)-> dependency
2194 * path, any usage of B should be considered. Otherwise, we should only
2195 * consider _READ usage.
2197 static inline bool usage_match(struct lock_list *entry, void *mask)
2199 if (!entry->only_xr)
2200 return !!(entry->class->usage_mask & *(unsigned long *)mask);
2201 else /* Mask out _READ usage bits */
2202 return !!((entry->class->usage_mask & LOCKF_IRQ) & *(unsigned long *)mask);
2205 static inline bool usage_skip(struct lock_list *entry, void *mask)
2208 * Skip local_lock() for irq inversion detection.
2210 * For !RT, local_lock() is not a real lock, so it won't carry any
2213 * For RT, an irq inversion happens when we have lock A and B, and on
2214 * some CPU we can have:
2220 * where lock(B) cannot sleep, and we have a dependency B -> ... -> A.
2222 * Now we prove local_lock() cannot exist in that dependency. First we
2223 * have the observation for any lock chain L1 -> ... -> Ln, for any
2224 * 1 <= i <= n, Li.inner_wait_type <= L1.inner_wait_type, otherwise
2225 * wait context check will complain. And since B is not a sleep lock,
2226 * therefore B.inner_wait_type >= 2, and since the inner_wait_type of
2227 * local_lock() is 3, which is greater than 2, therefore there is no
2228 * way the local_lock() exists in the dependency B -> ... -> A.
2230 * As a result, we will skip local_lock(), when we search for irq
2233 if (entry->class->lock_type == LD_LOCK_PERCPU) {
2234 if (DEBUG_LOCKS_WARN_ON(entry->class->wait_type_inner < LD_WAIT_CONFIG))
2244 * Find a node in the forwards-direction dependency sub-graph starting
2245 * at @root->class that matches @bit.
2247 * Return BFS_MATCH if such a node exists in the subgraph, and put that node
2248 * into *@target_entry.
2250 static enum bfs_result
2251 find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
2252 struct lock_list **target_entry)
2254 enum bfs_result result;
2256 debug_atomic_inc(nr_find_usage_forwards_checks);
2258 result = __bfs_forwards(root, &usage_mask, usage_match, usage_skip, target_entry);
2264 * Find a node in the backwards-direction dependency sub-graph starting
2265 * at @root->class that matches @bit.
2267 static enum bfs_result
2268 find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
2269 struct lock_list **target_entry)
2271 enum bfs_result result;
2273 debug_atomic_inc(nr_find_usage_backwards_checks);
2275 result = __bfs_backwards(root, &usage_mask, usage_match, usage_skip, target_entry);
2280 static void print_lock_class_header(struct lock_class *class, int depth)
2284 printk("%*s->", depth, "");
2285 print_lock_name(class);
2286 #ifdef CONFIG_DEBUG_LOCKDEP
2287 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
2289 printk(KERN_CONT " {\n");
2291 for (bit = 0; bit < LOCK_TRACE_STATES; bit++) {
2292 if (class->usage_mask & (1 << bit)) {
2295 len += printk("%*s %s", depth, "", usage_str[bit]);
2296 len += printk(KERN_CONT " at:\n");
2297 print_lock_trace(class->usage_traces[bit], len);
2300 printk("%*s }\n", depth, "");
2302 printk("%*s ... key at: [<%px>] %pS\n",
2303 depth, "", class->key, class->key);
2307 * printk the shortest lock dependencies from @start to @end in reverse order:
2310 print_shortest_lock_dependencies(struct lock_list *leaf,
2311 struct lock_list *root)
2313 struct lock_list *entry = leaf;
2316 /*compute depth from generated tree by BFS*/
2317 depth = get_lock_depth(leaf);
2320 print_lock_class_header(entry->class, depth);
2321 printk("%*s ... acquired at:\n", depth, "");
2322 print_lock_trace(entry->trace, 2);
2325 if (depth == 0 && (entry != root)) {
2326 printk("lockdep:%s bad path found in chain graph\n", __func__);
2330 entry = get_lock_parent(entry);
2332 } while (entry && (depth >= 0));
2336 print_irq_lock_scenario(struct lock_list *safe_entry,
2337 struct lock_list *unsafe_entry,
2338 struct lock_class *prev_class,
2339 struct lock_class *next_class)
2341 struct lock_class *safe_class = safe_entry->class;
2342 struct lock_class *unsafe_class = unsafe_entry->class;
2343 struct lock_class *middle_class = prev_class;
2345 if (middle_class == safe_class)
2346 middle_class = next_class;
2349 * A direct locking problem where unsafe_class lock is taken
2350 * directly by safe_class lock, then all we need to show
2351 * is the deadlock scenario, as it is obvious that the
2352 * unsafe lock is taken under the safe lock.
2354 * But if there is a chain instead, where the safe lock takes
2355 * an intermediate lock (middle_class) where this lock is
2356 * not the same as the safe lock, then the lock chain is
2357 * used to describe the problem. Otherwise we would need
2358 * to show a different CPU case for each link in the chain
2359 * from the safe_class lock to the unsafe_class lock.
2361 if (middle_class != unsafe_class) {
2362 printk("Chain exists of:\n ");
2363 __print_lock_name(safe_class);
2364 printk(KERN_CONT " --> ");
2365 __print_lock_name(middle_class);
2366 printk(KERN_CONT " --> ");
2367 __print_lock_name(unsafe_class);
2368 printk(KERN_CONT "\n\n");
2371 printk(" Possible interrupt unsafe locking scenario:\n\n");
2372 printk(" CPU0 CPU1\n");
2373 printk(" ---- ----\n");
2375 __print_lock_name(unsafe_class);
2376 printk(KERN_CONT ");\n");
2377 printk(" local_irq_disable();\n");
2379 __print_lock_name(safe_class);
2380 printk(KERN_CONT ");\n");
2382 __print_lock_name(middle_class);
2383 printk(KERN_CONT ");\n");
2384 printk(" <Interrupt>\n");
2386 __print_lock_name(safe_class);
2387 printk(KERN_CONT ");\n");
2388 printk("\n *** DEADLOCK ***\n\n");
2392 print_bad_irq_dependency(struct task_struct *curr,
2393 struct lock_list *prev_root,
2394 struct lock_list *next_root,
2395 struct lock_list *backwards_entry,
2396 struct lock_list *forwards_entry,
2397 struct held_lock *prev,
2398 struct held_lock *next,
2399 enum lock_usage_bit bit1,
2400 enum lock_usage_bit bit2,
2401 const char *irqclass)
2403 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2407 pr_warn("=====================================================\n");
2408 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
2409 irqclass, irqclass);
2410 print_kernel_ident();
2411 pr_warn("-----------------------------------------------------\n");
2412 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
2413 curr->comm, task_pid_nr(curr),
2414 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
2415 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
2416 lockdep_hardirqs_enabled(),
2417 curr->softirqs_enabled);
2420 pr_warn("\nand this task is already holding:\n");
2422 pr_warn("which would create a new lock dependency:\n");
2423 print_lock_name(hlock_class(prev));
2425 print_lock_name(hlock_class(next));
2428 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
2430 print_lock_name(backwards_entry->class);
2431 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
2433 print_lock_trace(backwards_entry->class->usage_traces[bit1], 1);
2435 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
2436 print_lock_name(forwards_entry->class);
2437 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
2440 print_lock_trace(forwards_entry->class->usage_traces[bit2], 1);
2442 pr_warn("\nother info that might help us debug this:\n\n");
2443 print_irq_lock_scenario(backwards_entry, forwards_entry,
2444 hlock_class(prev), hlock_class(next));
2446 lockdep_print_held_locks(curr);
2448 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
2449 prev_root->trace = save_trace();
2450 if (!prev_root->trace)
2452 print_shortest_lock_dependencies(backwards_entry, prev_root);
2454 pr_warn("\nthe dependencies between the lock to be acquired");
2455 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
2456 next_root->trace = save_trace();
2457 if (!next_root->trace)
2459 print_shortest_lock_dependencies(forwards_entry, next_root);
2461 pr_warn("\nstack backtrace:\n");
2465 static const char *state_names[] = {
2466 #define LOCKDEP_STATE(__STATE) \
2467 __stringify(__STATE),
2468 #include "lockdep_states.h"
2469 #undef LOCKDEP_STATE
2472 static const char *state_rnames[] = {
2473 #define LOCKDEP_STATE(__STATE) \
2474 __stringify(__STATE)"-READ",
2475 #include "lockdep_states.h"
2476 #undef LOCKDEP_STATE
2479 static inline const char *state_name(enum lock_usage_bit bit)
2481 if (bit & LOCK_USAGE_READ_MASK)
2482 return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
2484 return state_names[bit >> LOCK_USAGE_DIR_MASK];
2488 * The bit number is encoded like:
2490 * bit0: 0 exclusive, 1 read lock
2491 * bit1: 0 used in irq, 1 irq enabled
2494 static int exclusive_bit(int new_bit)
2496 int state = new_bit & LOCK_USAGE_STATE_MASK;
2497 int dir = new_bit & LOCK_USAGE_DIR_MASK;
2500 * keep state, bit flip the direction and strip read.
2502 return state | (dir ^ LOCK_USAGE_DIR_MASK);
2506 * Observe that when given a bitmask where each bitnr is encoded as above, a
2507 * right shift of the mask transforms the individual bitnrs as -1 and
2508 * conversely, a left shift transforms into +1 for the individual bitnrs.
2510 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
2511 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
2512 * instead by subtracting the bit number by 2, or shifting the mask right by 2.
2514 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
2516 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
2517 * all bits set) and recompose with bitnr1 flipped.
2519 static unsigned long invert_dir_mask(unsigned long mask)
2521 unsigned long excl = 0;
2524 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
2525 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
2531 * Note that a LOCK_ENABLED_IRQ_*_READ usage and a LOCK_USED_IN_IRQ_*_READ
2532 * usage may cause deadlock too, for example:
2536 * write_lock(l1); <irq enabled>
2542 * , in above case, l1 will be marked as LOCK_USED_IN_IRQ_HARDIRQ_READ and l2
2543 * will marked as LOCK_ENABLE_IRQ_HARDIRQ_READ, and this is a possible
2546 * In fact, all of the following cases may cause deadlocks:
2548 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*
2549 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*
2550 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*_READ
2551 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*_READ
2553 * As a result, to calculate the "exclusive mask", first we invert the
2554 * direction (USED_IN/ENABLED) of the original mask, and 1) for all bits with
2555 * bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*). 2) for all
2556 * bits with bitnr0 cleared (LOCK_*_READ), add those with bitnr0 set (LOCK_*).
2558 static unsigned long exclusive_mask(unsigned long mask)
2560 unsigned long excl = invert_dir_mask(mask);
2562 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2563 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2569 * Retrieve the _possible_ original mask to which @mask is
2570 * exclusive. Ie: this is the opposite of exclusive_mask().
2571 * Note that 2 possible original bits can match an exclusive
2572 * bit: one has LOCK_USAGE_READ_MASK set, the other has it
2573 * cleared. So both are returned for each exclusive bit.
2575 static unsigned long original_mask(unsigned long mask)
2577 unsigned long excl = invert_dir_mask(mask);
2579 /* Include read in existing usages */
2580 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2581 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2587 * Find the first pair of bit match between an original
2588 * usage mask and an exclusive usage mask.
2590 static int find_exclusive_match(unsigned long mask,
2591 unsigned long excl_mask,
2592 enum lock_usage_bit *bitp,
2593 enum lock_usage_bit *excl_bitp)
2595 int bit, excl, excl_read;
2597 for_each_set_bit(bit, &mask, LOCK_USED) {
2599 * exclusive_bit() strips the read bit, however,
2600 * LOCK_ENABLED_IRQ_*_READ may cause deadlocks too, so we need
2601 * to search excl | LOCK_USAGE_READ_MASK as well.
2603 excl = exclusive_bit(bit);
2604 excl_read = excl | LOCK_USAGE_READ_MASK;
2605 if (excl_mask & lock_flag(excl)) {
2609 } else if (excl_mask & lock_flag(excl_read)) {
2611 *excl_bitp = excl_read;
2619 * Prove that the new dependency does not connect a hardirq-safe(-read)
2620 * lock with a hardirq-unsafe lock - to achieve this we search
2621 * the backwards-subgraph starting at <prev>, and the
2622 * forwards-subgraph starting at <next>:
2624 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
2625 struct held_lock *next)
2627 unsigned long usage_mask = 0, forward_mask, backward_mask;
2628 enum lock_usage_bit forward_bit = 0, backward_bit = 0;
2629 struct lock_list *target_entry1;
2630 struct lock_list *target_entry;
2631 struct lock_list this, that;
2632 enum bfs_result ret;
2635 * Step 1: gather all hard/soft IRQs usages backward in an
2636 * accumulated usage mask.
2638 bfs_init_rootb(&this, prev);
2640 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, usage_skip, NULL);
2641 if (bfs_error(ret)) {
2646 usage_mask &= LOCKF_USED_IN_IRQ_ALL;
2651 * Step 2: find exclusive uses forward that match the previous
2652 * backward accumulated mask.
2654 forward_mask = exclusive_mask(usage_mask);
2656 bfs_init_root(&that, next);
2658 ret = find_usage_forwards(&that, forward_mask, &target_entry1);
2659 if (bfs_error(ret)) {
2663 if (ret == BFS_RNOMATCH)
2667 * Step 3: we found a bad match! Now retrieve a lock from the backward
2668 * list whose usage mask matches the exclusive usage mask from the
2669 * lock found on the forward list.
2671 backward_mask = original_mask(target_entry1->class->usage_mask);
2673 ret = find_usage_backwards(&this, backward_mask, &target_entry);
2674 if (bfs_error(ret)) {
2678 if (DEBUG_LOCKS_WARN_ON(ret == BFS_RNOMATCH))
2682 * Step 4: narrow down to a pair of incompatible usage bits
2685 ret = find_exclusive_match(target_entry->class->usage_mask,
2686 target_entry1->class->usage_mask,
2687 &backward_bit, &forward_bit);
2688 if (DEBUG_LOCKS_WARN_ON(ret == -1))
2691 print_bad_irq_dependency(curr, &this, &that,
2692 target_entry, target_entry1,
2694 backward_bit, forward_bit,
2695 state_name(backward_bit));
2702 static inline int check_irq_usage(struct task_struct *curr,
2703 struct held_lock *prev, struct held_lock *next)
2708 static inline bool usage_skip(struct lock_list *entry, void *mask)
2713 #endif /* CONFIG_TRACE_IRQFLAGS */
2715 #ifdef CONFIG_LOCKDEP_SMALL
2717 * Check that the dependency graph starting at <src> can lead to
2718 * <target> or not. If it can, <src> -> <target> dependency is already
2721 * Return BFS_RMATCH if it does, or BFS_RMATCH if it does not, return BFS_E* if
2722 * any error appears in the bfs search.
2724 static noinline enum bfs_result
2725 check_redundant(struct held_lock *src, struct held_lock *target)
2727 enum bfs_result ret;
2728 struct lock_list *target_entry;
2729 struct lock_list src_entry;
2731 bfs_init_root(&src_entry, src);
2733 * Special setup for check_redundant().
2735 * To report redundant, we need to find a strong dependency path that
2736 * is equal to or stronger than <src> -> <target>. So if <src> is E,
2737 * we need to let __bfs() only search for a path starting at a -(E*)->,
2738 * we achieve this by setting the initial node's ->only_xr to true in
2739 * that case. And if <prev> is S, we set initial ->only_xr to false
2740 * because both -(S*)-> (equal) and -(E*)-> (stronger) are redundant.
2742 src_entry.only_xr = src->read == 0;
2744 debug_atomic_inc(nr_redundant_checks);
2747 * Note: we skip local_lock() for redundant check, because as the
2748 * comment in usage_skip(), A -> local_lock() -> B and A -> B are not
2751 ret = check_path(target, &src_entry, hlock_equal, usage_skip, &target_entry);
2753 if (ret == BFS_RMATCH)
2754 debug_atomic_inc(nr_redundant);
2761 static inline enum bfs_result
2762 check_redundant(struct held_lock *src, struct held_lock *target)
2764 return BFS_RNOMATCH;
2769 static void inc_chains(int irq_context)
2771 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2772 nr_hardirq_chains++;
2773 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2774 nr_softirq_chains++;
2776 nr_process_chains++;
2779 static void dec_chains(int irq_context)
2781 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2782 nr_hardirq_chains--;
2783 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2784 nr_softirq_chains--;
2786 nr_process_chains--;
2790 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
2792 struct lock_class *next = hlock_class(nxt);
2793 struct lock_class *prev = hlock_class(prv);
2795 printk(" Possible unsafe locking scenario:\n\n");
2799 __print_lock_name(prev);
2800 printk(KERN_CONT ");\n");
2802 __print_lock_name(next);
2803 printk(KERN_CONT ");\n");
2804 printk("\n *** DEADLOCK ***\n\n");
2805 printk(" May be due to missing lock nesting notation\n\n");
2809 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
2810 struct held_lock *next)
2812 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2816 pr_warn("============================================\n");
2817 pr_warn("WARNING: possible recursive locking detected\n");
2818 print_kernel_ident();
2819 pr_warn("--------------------------------------------\n");
2820 pr_warn("%s/%d is trying to acquire lock:\n",
2821 curr->comm, task_pid_nr(curr));
2823 pr_warn("\nbut task is already holding lock:\n");
2826 pr_warn("\nother info that might help us debug this:\n");
2827 print_deadlock_scenario(next, prev);
2828 lockdep_print_held_locks(curr);
2830 pr_warn("\nstack backtrace:\n");
2835 * Check whether we are holding such a class already.
2837 * (Note that this has to be done separately, because the graph cannot
2838 * detect such classes of deadlocks.)
2840 * Returns: 0 on deadlock detected, 1 on OK, 2 if another lock with the same
2841 * lock class is held but nest_lock is also held, i.e. we rely on the
2842 * nest_lock to avoid the deadlock.
2845 check_deadlock(struct task_struct *curr, struct held_lock *next)
2847 struct held_lock *prev;
2848 struct held_lock *nest = NULL;
2851 for (i = 0; i < curr->lockdep_depth; i++) {
2852 prev = curr->held_locks + i;
2854 if (prev->instance == next->nest_lock)
2857 if (hlock_class(prev) != hlock_class(next))
2861 * Allow read-after-read recursion of the same
2862 * lock class (i.e. read_lock(lock)+read_lock(lock)):
2864 if ((next->read == 2) && prev->read)
2868 * We're holding the nest_lock, which serializes this lock's
2869 * nesting behaviour.
2874 print_deadlock_bug(curr, prev, next);
2881 * There was a chain-cache miss, and we are about to add a new dependency
2882 * to a previous lock. We validate the following rules:
2884 * - would the adding of the <prev> -> <next> dependency create a
2885 * circular dependency in the graph? [== circular deadlock]
2887 * - does the new prev->next dependency connect any hardirq-safe lock
2888 * (in the full backwards-subgraph starting at <prev>) with any
2889 * hardirq-unsafe lock (in the full forwards-subgraph starting at
2890 * <next>)? [== illegal lock inversion with hardirq contexts]
2892 * - does the new prev->next dependency connect any softirq-safe lock
2893 * (in the full backwards-subgraph starting at <prev>) with any
2894 * softirq-unsafe lock (in the full forwards-subgraph starting at
2895 * <next>)? [== illegal lock inversion with softirq contexts]
2897 * any of these scenarios could lead to a deadlock.
2899 * Then if all the validations pass, we add the forwards and backwards
2903 check_prev_add(struct task_struct *curr, struct held_lock *prev,
2904 struct held_lock *next, u16 distance,
2905 struct lock_trace **const trace)
2907 struct lock_list *entry;
2908 enum bfs_result ret;
2910 if (!hlock_class(prev)->key || !hlock_class(next)->key) {
2912 * The warning statements below may trigger a use-after-free
2913 * of the class name. It is better to trigger a use-after free
2914 * and to have the class name most of the time instead of not
2915 * having the class name available.
2917 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
2918 "Detected use-after-free of lock class %px/%s\n",
2920 hlock_class(prev)->name);
2921 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
2922 "Detected use-after-free of lock class %px/%s\n",
2924 hlock_class(next)->name);
2929 * Prove that the new <prev> -> <next> dependency would not
2930 * create a circular dependency in the graph. (We do this by
2931 * a breadth-first search into the graph starting at <next>,
2932 * and check whether we can reach <prev>.)
2934 * The search is limited by the size of the circular queue (i.e.,
2935 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
2936 * in the graph whose neighbours are to be checked.
2938 ret = check_noncircular(next, prev, trace);
2939 if (unlikely(bfs_error(ret) || ret == BFS_RMATCH))
2942 if (!check_irq_usage(curr, prev, next))
2946 * Is the <prev> -> <next> dependency already present?
2948 * (this may occur even though this is a new chain: consider
2949 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
2950 * chains - the second one will be new, but L1 already has
2951 * L2 added to its dependency list, due to the first chain.)
2953 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
2954 if (entry->class == hlock_class(next)) {
2956 entry->distance = 1;
2957 entry->dep |= calc_dep(prev, next);
2960 * Also, update the reverse dependency in @next's
2961 * ->locks_before list.
2963 * Here we reuse @entry as the cursor, which is fine
2964 * because we won't go to the next iteration of the
2967 * For normal cases, we return in the inner loop.
2969 * If we fail to return, we have inconsistency, i.e.
2970 * <prev>::locks_after contains <next> while
2971 * <next>::locks_before doesn't contain <prev>. In
2972 * that case, we return after the inner and indicate
2973 * something is wrong.
2975 list_for_each_entry(entry, &hlock_class(next)->locks_before, entry) {
2976 if (entry->class == hlock_class(prev)) {
2978 entry->distance = 1;
2979 entry->dep |= calc_depb(prev, next);
2984 /* <prev> is not found in <next>::locks_before */
2990 * Is the <prev> -> <next> link redundant?
2992 ret = check_redundant(prev, next);
2995 else if (ret == BFS_RMATCH)
2999 *trace = save_trace();
3005 * Ok, all validations passed, add the new lock
3006 * to the previous lock's dependency list:
3008 ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
3009 &hlock_class(prev)->locks_after,
3010 next->acquire_ip, distance,
3011 calc_dep(prev, next),
3017 ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
3018 &hlock_class(next)->locks_before,
3019 next->acquire_ip, distance,
3020 calc_depb(prev, next),
3029 * Add the dependency to all directly-previous locks that are 'relevant'.
3030 * The ones that are relevant are (in increasing distance from curr):
3031 * all consecutive trylock entries and the final non-trylock entry - or
3032 * the end of this context's lock-chain - whichever comes first.
3035 check_prevs_add(struct task_struct *curr, struct held_lock *next)
3037 struct lock_trace *trace = NULL;
3038 int depth = curr->lockdep_depth;
3039 struct held_lock *hlock;
3044 * Depth must not be zero for a non-head lock:
3049 * At least two relevant locks must exist for this
3052 if (curr->held_locks[depth].irq_context !=
3053 curr->held_locks[depth-1].irq_context)
3057 u16 distance = curr->lockdep_depth - depth + 1;
3058 hlock = curr->held_locks + depth - 1;
3061 int ret = check_prev_add(curr, hlock, next, distance, &trace);
3066 * Stop after the first non-trylock entry,
3067 * as non-trylock entries have added their
3068 * own direct dependencies already, so this
3069 * lock is connected to them indirectly:
3071 if (!hlock->trylock)
3077 * End of lock-stack?
3082 * Stop the search if we cross into another context:
3084 if (curr->held_locks[depth].irq_context !=
3085 curr->held_locks[depth-1].irq_context)
3090 if (!debug_locks_off_graph_unlock())
3094 * Clearly we all shouldn't be here, but since we made it we
3095 * can reliable say we messed up our state. See the above two
3096 * gotos for reasons why we could possibly end up here.
3103 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
3104 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
3105 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
3106 unsigned long nr_zapped_lock_chains;
3107 unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */
3108 unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */
3109 unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */
3112 * The first 2 chain_hlocks entries in the chain block in the bucket
3113 * list contains the following meta data:
3116 * Bit 15 - always set to 1 (it is not a class index)
3117 * Bits 0-14 - upper 15 bits of the next block index
3118 * entry[1] - lower 16 bits of next block index
3120 * A next block index of all 1 bits means it is the end of the list.
3122 * On the unsized bucket (bucket-0), the 3rd and 4th entries contain
3123 * the chain block size:
3125 * entry[2] - upper 16 bits of the chain block size
3126 * entry[3] - lower 16 bits of the chain block size
3128 #define MAX_CHAIN_BUCKETS 16
3129 #define CHAIN_BLK_FLAG (1U << 15)
3130 #define CHAIN_BLK_LIST_END 0xFFFFU
3132 static int chain_block_buckets[MAX_CHAIN_BUCKETS];
3134 static inline int size_to_bucket(int size)
3136 if (size > MAX_CHAIN_BUCKETS)
3143 * Iterate all the chain blocks in a bucket.
3145 #define for_each_chain_block(bucket, prev, curr) \
3146 for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \
3148 (prev) = (curr), (curr) = chain_block_next(curr))
3153 static inline int chain_block_next(int offset)
3155 int next = chain_hlocks[offset];
3157 WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG));
3159 if (next == CHAIN_BLK_LIST_END)
3162 next &= ~CHAIN_BLK_FLAG;
3164 next |= chain_hlocks[offset + 1];
3172 static inline int chain_block_size(int offset)
3174 return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3];
3177 static inline void init_chain_block(int offset, int next, int bucket, int size)
3179 chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG;
3180 chain_hlocks[offset + 1] = (u16)next;
3182 if (size && !bucket) {
3183 chain_hlocks[offset + 2] = size >> 16;
3184 chain_hlocks[offset + 3] = (u16)size;
3188 static inline void add_chain_block(int offset, int size)
3190 int bucket = size_to_bucket(size);
3191 int next = chain_block_buckets[bucket];
3194 if (unlikely(size < 2)) {
3196 * We can't store single entries on the freelist. Leak them.
3198 * One possible way out would be to uniquely mark them, other
3199 * than with CHAIN_BLK_FLAG, such that we can recover them when
3200 * the block before it is re-added.
3203 nr_lost_chain_hlocks++;
3207 nr_free_chain_hlocks += size;
3209 nr_large_chain_blocks++;
3212 * Variable sized, sort large to small.
3214 for_each_chain_block(0, prev, curr) {
3215 if (size >= chain_block_size(curr))
3218 init_chain_block(offset, curr, 0, size);
3220 chain_block_buckets[0] = offset;
3222 init_chain_block(prev, offset, 0, 0);
3226 * Fixed size, add to head.
3228 init_chain_block(offset, next, bucket, size);
3229 chain_block_buckets[bucket] = offset;
3233 * Only the first block in the list can be deleted.
3235 * For the variable size bucket[0], the first block (the largest one) is
3236 * returned, broken up and put back into the pool. So if a chain block of
3237 * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be
3238 * queued up after the primordial chain block and never be used until the
3239 * hlock entries in the primordial chain block is almost used up. That
3240 * causes fragmentation and reduce allocation efficiency. That can be
3241 * monitored by looking at the "large chain blocks" number in lockdep_stats.
3243 static inline void del_chain_block(int bucket, int size, int next)
3245 nr_free_chain_hlocks -= size;
3246 chain_block_buckets[bucket] = next;
3249 nr_large_chain_blocks--;
3252 static void init_chain_block_buckets(void)
3256 for (i = 0; i < MAX_CHAIN_BUCKETS; i++)
3257 chain_block_buckets[i] = -1;
3259 add_chain_block(0, ARRAY_SIZE(chain_hlocks));
3263 * Return offset of a chain block of the right size or -1 if not found.
3265 * Fairly simple worst-fit allocator with the addition of a number of size
3266 * specific free lists.
3268 static int alloc_chain_hlocks(int req)
3270 int bucket, curr, size;
3273 * We rely on the MSB to act as an escape bit to denote freelist
3274 * pointers. Make sure this bit isn't set in 'normal' class_idx usage.
3276 BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG);
3278 init_data_structures_once();
3280 if (nr_free_chain_hlocks < req)
3284 * We require a minimum of 2 (u16) entries to encode a freelist
3288 bucket = size_to_bucket(req);
3289 curr = chain_block_buckets[bucket];
3293 del_chain_block(bucket, req, chain_block_next(curr));
3297 curr = chain_block_buckets[0];
3301 * The variable sized freelist is sorted by size; the first entry is
3302 * the largest. Use it if it fits.
3305 size = chain_block_size(curr);
3306 if (likely(size >= req)) {
3307 del_chain_block(0, size, chain_block_next(curr));
3308 add_chain_block(curr + req, size - req);
3314 * Last resort, split a block in a larger sized bucket.
3316 for (size = MAX_CHAIN_BUCKETS; size > req; size--) {
3317 bucket = size_to_bucket(size);
3318 curr = chain_block_buckets[bucket];
3322 del_chain_block(bucket, size, chain_block_next(curr));
3323 add_chain_block(curr + req, size - req);
3330 static inline void free_chain_hlocks(int base, int size)
3332 add_chain_block(base, max(size, 2));
3335 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
3337 u16 chain_hlock = chain_hlocks[chain->base + i];
3338 unsigned int class_idx = chain_hlock_class_idx(chain_hlock);
3340 return lock_classes + class_idx - 1;
3344 * Returns the index of the first held_lock of the current chain
3346 static inline int get_first_held_lock(struct task_struct *curr,
3347 struct held_lock *hlock)
3350 struct held_lock *hlock_curr;
3352 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
3353 hlock_curr = curr->held_locks + i;
3354 if (hlock_curr->irq_context != hlock->irq_context)
3362 #ifdef CONFIG_DEBUG_LOCKDEP
3364 * Returns the next chain_key iteration
3366 static u64 print_chain_key_iteration(u16 hlock_id, u64 chain_key)
3368 u64 new_chain_key = iterate_chain_key(chain_key, hlock_id);
3370 printk(" hlock_id:%d -> chain_key:%016Lx",
3371 (unsigned int)hlock_id,
3372 (unsigned long long)new_chain_key);
3373 return new_chain_key;
3377 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
3379 struct held_lock *hlock;
3380 u64 chain_key = INITIAL_CHAIN_KEY;
3381 int depth = curr->lockdep_depth;
3382 int i = get_first_held_lock(curr, hlock_next);
3384 printk("depth: %u (irq_context %u)\n", depth - i + 1,
3385 hlock_next->irq_context);
3386 for (; i < depth; i++) {
3387 hlock = curr->held_locks + i;
3388 chain_key = print_chain_key_iteration(hlock_id(hlock), chain_key);
3393 print_chain_key_iteration(hlock_id(hlock_next), chain_key);
3394 print_lock(hlock_next);
3397 static void print_chain_keys_chain(struct lock_chain *chain)
3400 u64 chain_key = INITIAL_CHAIN_KEY;
3403 printk("depth: %u\n", chain->depth);
3404 for (i = 0; i < chain->depth; i++) {
3405 hlock_id = chain_hlocks[chain->base + i];
3406 chain_key = print_chain_key_iteration(hlock_id, chain_key);
3408 print_lock_name(lock_classes + chain_hlock_class_idx(hlock_id) - 1);
3413 static void print_collision(struct task_struct *curr,
3414 struct held_lock *hlock_next,
3415 struct lock_chain *chain)
3418 pr_warn("============================\n");
3419 pr_warn("WARNING: chain_key collision\n");
3420 print_kernel_ident();
3421 pr_warn("----------------------------\n");
3422 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
3423 pr_warn("Hash chain already cached but the contents don't match!\n");
3425 pr_warn("Held locks:");
3426 print_chain_keys_held_locks(curr, hlock_next);
3428 pr_warn("Locks in cached chain:");
3429 print_chain_keys_chain(chain);
3431 pr_warn("\nstack backtrace:\n");
3437 * Checks whether the chain and the current held locks are consistent
3438 * in depth and also in content. If they are not it most likely means
3439 * that there was a collision during the calculation of the chain_key.
3440 * Returns: 0 not passed, 1 passed
3442 static int check_no_collision(struct task_struct *curr,
3443 struct held_lock *hlock,
3444 struct lock_chain *chain)
3446 #ifdef CONFIG_DEBUG_LOCKDEP
3449 i = get_first_held_lock(curr, hlock);
3451 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
3452 print_collision(curr, hlock, chain);
3456 for (j = 0; j < chain->depth - 1; j++, i++) {
3457 id = hlock_id(&curr->held_locks[i]);
3459 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
3460 print_collision(curr, hlock, chain);
3469 * Given an index that is >= -1, return the index of the next lock chain.
3470 * Return -2 if there is no next lock chain.
3472 long lockdep_next_lockchain(long i)
3474 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
3475 return i < ARRAY_SIZE(lock_chains) ? i : -2;
3478 unsigned long lock_chain_count(void)
3480 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
3483 /* Must be called with the graph lock held. */
3484 static struct lock_chain *alloc_lock_chain(void)
3486 int idx = find_first_zero_bit(lock_chains_in_use,
3487 ARRAY_SIZE(lock_chains));
3489 if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
3491 __set_bit(idx, lock_chains_in_use);
3492 return lock_chains + idx;
3496 * Adds a dependency chain into chain hashtable. And must be called with
3499 * Return 0 if fail, and graph_lock is released.
3500 * Return 1 if succeed, with graph_lock held.
3502 static inline int add_chain_cache(struct task_struct *curr,
3503 struct held_lock *hlock,
3506 struct hlist_head *hash_head = chainhashentry(chain_key);
3507 struct lock_chain *chain;
3511 * The caller must hold the graph lock, ensure we've got IRQs
3512 * disabled to make this an IRQ-safe lock.. for recursion reasons
3513 * lockdep won't complain about its own locking errors.
3515 if (lockdep_assert_locked())
3518 chain = alloc_lock_chain();
3520 if (!debug_locks_off_graph_unlock())
3523 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
3527 chain->chain_key = chain_key;
3528 chain->irq_context = hlock->irq_context;
3529 i = get_first_held_lock(curr, hlock);
3530 chain->depth = curr->lockdep_depth + 1 - i;
3532 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
3533 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
3534 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
3536 j = alloc_chain_hlocks(chain->depth);
3538 if (!debug_locks_off_graph_unlock())
3541 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
3547 for (j = 0; j < chain->depth - 1; j++, i++) {
3548 int lock_id = hlock_id(curr->held_locks + i);
3550 chain_hlocks[chain->base + j] = lock_id;
3552 chain_hlocks[chain->base + j] = hlock_id(hlock);
3553 hlist_add_head_rcu(&chain->entry, hash_head);
3554 debug_atomic_inc(chain_lookup_misses);
3555 inc_chains(chain->irq_context);
3561 * Look up a dependency chain. Must be called with either the graph lock or
3562 * the RCU read lock held.
3564 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
3566 struct hlist_head *hash_head = chainhashentry(chain_key);
3567 struct lock_chain *chain;
3569 hlist_for_each_entry_rcu(chain, hash_head, entry) {
3570 if (READ_ONCE(chain->chain_key) == chain_key) {
3571 debug_atomic_inc(chain_lookup_hits);
3579 * If the key is not present yet in dependency chain cache then
3580 * add it and return 1 - in this case the new dependency chain is
3581 * validated. If the key is already hashed, return 0.
3582 * (On return with 1 graph_lock is held.)
3584 static inline int lookup_chain_cache_add(struct task_struct *curr,
3585 struct held_lock *hlock,
3588 struct lock_class *class = hlock_class(hlock);
3589 struct lock_chain *chain = lookup_chain_cache(chain_key);
3593 if (!check_no_collision(curr, hlock, chain))
3596 if (very_verbose(class)) {
3597 printk("\nhash chain already cached, key: "
3598 "%016Lx tail class: [%px] %s\n",
3599 (unsigned long long)chain_key,
3600 class->key, class->name);
3606 if (very_verbose(class)) {
3607 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
3608 (unsigned long long)chain_key, class->key, class->name);
3615 * We have to walk the chain again locked - to avoid duplicates:
3617 chain = lookup_chain_cache(chain_key);
3623 if (!add_chain_cache(curr, hlock, chain_key))
3629 static int validate_chain(struct task_struct *curr,
3630 struct held_lock *hlock,
3631 int chain_head, u64 chain_key)
3634 * Trylock needs to maintain the stack of held locks, but it
3635 * does not add new dependencies, because trylock can be done
3638 * We look up the chain_key and do the O(N^2) check and update of
3639 * the dependencies only if this is a new dependency chain.
3640 * (If lookup_chain_cache_add() return with 1 it acquires
3641 * graph_lock for us)
3643 if (!hlock->trylock && hlock->check &&
3644 lookup_chain_cache_add(curr, hlock, chain_key)) {
3646 * Check whether last held lock:
3648 * - is irq-safe, if this lock is irq-unsafe
3649 * - is softirq-safe, if this lock is hardirq-unsafe
3651 * And check whether the new lock's dependency graph
3652 * could lead back to the previous lock:
3654 * - within the current held-lock stack
3655 * - across our accumulated lock dependency records
3657 * any of these scenarios could lead to a deadlock.
3660 * The simple case: does the current hold the same lock
3663 int ret = check_deadlock(curr, hlock);
3668 * Add dependency only if this lock is not the head
3669 * of the chain, and if the new lock introduces no more
3670 * lock dependency (because we already hold a lock with the
3671 * same lock class) nor deadlock (because the nest_lock
3672 * serializes nesting locks), see the comments for
3675 if (!chain_head && ret != 2) {
3676 if (!check_prevs_add(curr, hlock))
3682 /* after lookup_chain_cache_add(): */
3683 if (unlikely(!debug_locks))
3690 static inline int validate_chain(struct task_struct *curr,
3691 struct held_lock *hlock,
3692 int chain_head, u64 chain_key)
3697 static void init_chain_block_buckets(void) { }
3698 #endif /* CONFIG_PROVE_LOCKING */
3701 * We are building curr_chain_key incrementally, so double-check
3702 * it from scratch, to make sure that it's done correctly:
3704 static void check_chain_key(struct task_struct *curr)
3706 #ifdef CONFIG_DEBUG_LOCKDEP
3707 struct held_lock *hlock, *prev_hlock = NULL;
3709 u64 chain_key = INITIAL_CHAIN_KEY;
3711 for (i = 0; i < curr->lockdep_depth; i++) {
3712 hlock = curr->held_locks + i;
3713 if (chain_key != hlock->prev_chain_key) {
3716 * We got mighty confused, our chain keys don't match
3717 * with what we expect, someone trample on our task state?
3719 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
3720 curr->lockdep_depth, i,
3721 (unsigned long long)chain_key,
3722 (unsigned long long)hlock->prev_chain_key);
3727 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
3728 * it registered lock class index?
3730 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
3733 if (prev_hlock && (prev_hlock->irq_context !=
3734 hlock->irq_context))
3735 chain_key = INITIAL_CHAIN_KEY;
3736 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
3739 if (chain_key != curr->curr_chain_key) {
3742 * More smoking hash instead of calculating it, damn see these
3743 * numbers float.. I bet that a pink elephant stepped on my memory.
3745 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
3746 curr->lockdep_depth, i,
3747 (unsigned long long)chain_key,
3748 (unsigned long long)curr->curr_chain_key);
3753 #ifdef CONFIG_PROVE_LOCKING
3754 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3755 enum lock_usage_bit new_bit);
3757 static void print_usage_bug_scenario(struct held_lock *lock)
3759 struct lock_class *class = hlock_class(lock);
3761 printk(" Possible unsafe locking scenario:\n\n");
3765 __print_lock_name(class);
3766 printk(KERN_CONT ");\n");
3767 printk(" <Interrupt>\n");
3769 __print_lock_name(class);
3770 printk(KERN_CONT ");\n");
3771 printk("\n *** DEADLOCK ***\n\n");
3775 print_usage_bug(struct task_struct *curr, struct held_lock *this,
3776 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
3778 if (!debug_locks_off() || debug_locks_silent)
3782 pr_warn("================================\n");
3783 pr_warn("WARNING: inconsistent lock state\n");
3784 print_kernel_ident();
3785 pr_warn("--------------------------------\n");
3787 pr_warn("inconsistent {%s} -> {%s} usage.\n",
3788 usage_str[prev_bit], usage_str[new_bit]);
3790 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
3791 curr->comm, task_pid_nr(curr),
3792 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
3793 lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
3794 lockdep_hardirqs_enabled(),
3795 lockdep_softirqs_enabled(curr));
3798 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
3799 print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1);
3801 print_irqtrace_events(curr);
3802 pr_warn("\nother info that might help us debug this:\n");
3803 print_usage_bug_scenario(this);
3805 lockdep_print_held_locks(curr);
3807 pr_warn("\nstack backtrace:\n");
3812 * Print out an error if an invalid bit is set:
3815 valid_state(struct task_struct *curr, struct held_lock *this,
3816 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
3818 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
3820 print_usage_bug(curr, this, bad_bit, new_bit);
3828 * print irq inversion bug:
3831 print_irq_inversion_bug(struct task_struct *curr,
3832 struct lock_list *root, struct lock_list *other,
3833 struct held_lock *this, int forwards,
3834 const char *irqclass)
3836 struct lock_list *entry = other;
3837 struct lock_list *middle = NULL;
3840 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3844 pr_warn("========================================================\n");
3845 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
3846 print_kernel_ident();
3847 pr_warn("--------------------------------------------------------\n");
3848 pr_warn("%s/%d just changed the state of lock:\n",
3849 curr->comm, task_pid_nr(curr));
3852 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
3854 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
3855 print_lock_name(other->class);
3856 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
3858 pr_warn("\nother info that might help us debug this:\n");
3860 /* Find a middle lock (if one exists) */
3861 depth = get_lock_depth(other);
3863 if (depth == 0 && (entry != root)) {
3864 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
3868 entry = get_lock_parent(entry);
3870 } while (entry && entry != root && (depth >= 0));
3872 print_irq_lock_scenario(root, other,
3873 middle ? middle->class : root->class, other->class);
3875 print_irq_lock_scenario(other, root,
3876 middle ? middle->class : other->class, root->class);
3878 lockdep_print_held_locks(curr);
3880 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
3881 root->trace = save_trace();
3884 print_shortest_lock_dependencies(other, root);
3886 pr_warn("\nstack backtrace:\n");
3891 * Prove that in the forwards-direction subgraph starting at <this>
3892 * there is no lock matching <mask>:
3895 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
3896 enum lock_usage_bit bit)
3898 enum bfs_result ret;
3899 struct lock_list root;
3900 struct lock_list *target_entry;
3901 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
3902 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
3904 bfs_init_root(&root, this);
3905 ret = find_usage_forwards(&root, usage_mask, &target_entry);
3906 if (bfs_error(ret)) {
3910 if (ret == BFS_RNOMATCH)
3913 /* Check whether write or read usage is the match */
3914 if (target_entry->class->usage_mask & lock_flag(bit)) {
3915 print_irq_inversion_bug(curr, &root, target_entry,
3916 this, 1, state_name(bit));
3918 print_irq_inversion_bug(curr, &root, target_entry,
3919 this, 1, state_name(read_bit));
3926 * Prove that in the backwards-direction subgraph starting at <this>
3927 * there is no lock matching <mask>:
3930 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
3931 enum lock_usage_bit bit)
3933 enum bfs_result ret;
3934 struct lock_list root;
3935 struct lock_list *target_entry;
3936 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
3937 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
3939 bfs_init_rootb(&root, this);
3940 ret = find_usage_backwards(&root, usage_mask, &target_entry);
3941 if (bfs_error(ret)) {
3945 if (ret == BFS_RNOMATCH)
3948 /* Check whether write or read usage is the match */
3949 if (target_entry->class->usage_mask & lock_flag(bit)) {
3950 print_irq_inversion_bug(curr, &root, target_entry,
3951 this, 0, state_name(bit));
3953 print_irq_inversion_bug(curr, &root, target_entry,
3954 this, 0, state_name(read_bit));
3960 void print_irqtrace_events(struct task_struct *curr)
3962 const struct irqtrace_events *trace = &curr->irqtrace;
3964 printk("irq event stamp: %u\n", trace->irq_events);
3965 printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
3966 trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip,
3967 (void *)trace->hardirq_enable_ip);
3968 printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
3969 trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip,
3970 (void *)trace->hardirq_disable_ip);
3971 printk("softirqs last enabled at (%u): [<%px>] %pS\n",
3972 trace->softirq_enable_event, (void *)trace->softirq_enable_ip,
3973 (void *)trace->softirq_enable_ip);
3974 printk("softirqs last disabled at (%u): [<%px>] %pS\n",
3975 trace->softirq_disable_event, (void *)trace->softirq_disable_ip,
3976 (void *)trace->softirq_disable_ip);
3979 static int HARDIRQ_verbose(struct lock_class *class)
3982 return class_filter(class);
3987 static int SOFTIRQ_verbose(struct lock_class *class)
3990 return class_filter(class);
3995 static int (*state_verbose_f[])(struct lock_class *class) = {
3996 #define LOCKDEP_STATE(__STATE) \
3998 #include "lockdep_states.h"
3999 #undef LOCKDEP_STATE
4002 static inline int state_verbose(enum lock_usage_bit bit,
4003 struct lock_class *class)
4005 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
4008 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
4009 enum lock_usage_bit bit, const char *name);
4012 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
4013 enum lock_usage_bit new_bit)
4015 int excl_bit = exclusive_bit(new_bit);
4016 int read = new_bit & LOCK_USAGE_READ_MASK;
4017 int dir = new_bit & LOCK_USAGE_DIR_MASK;
4020 * Validate that this particular lock does not have conflicting
4023 if (!valid_state(curr, this, new_bit, excl_bit))
4027 * Check for read in write conflicts
4029 if (!read && !valid_state(curr, this, new_bit,
4030 excl_bit + LOCK_USAGE_READ_MASK))
4035 * Validate that the lock dependencies don't have conflicting usage
4040 * mark ENABLED has to look backwards -- to ensure no dependee
4041 * has USED_IN state, which, again, would allow recursion deadlocks.
4043 if (!check_usage_backwards(curr, this, excl_bit))
4047 * mark USED_IN has to look forwards -- to ensure no dependency
4048 * has ENABLED state, which would allow recursion deadlocks.
4050 if (!check_usage_forwards(curr, this, excl_bit))
4054 if (state_verbose(new_bit, hlock_class(this)))
4061 * Mark all held locks with a usage bit:
4064 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
4066 struct held_lock *hlock;
4069 for (i = 0; i < curr->lockdep_depth; i++) {
4070 enum lock_usage_bit hlock_bit = base_bit;
4071 hlock = curr->held_locks + i;
4074 hlock_bit += LOCK_USAGE_READ_MASK;
4076 BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
4081 if (!mark_lock(curr, hlock, hlock_bit))
4089 * Hardirqs will be enabled:
4091 static void __trace_hardirqs_on_caller(void)
4093 struct task_struct *curr = current;
4096 * We are going to turn hardirqs on, so set the
4097 * usage bit for all held locks:
4099 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
4102 * If we have softirqs enabled, then set the usage
4103 * bit for all held locks. (disabled hardirqs prevented
4104 * this bit from being set before)
4106 if (curr->softirqs_enabled)
4107 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
4111 * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts
4112 * @ip: Caller address
4114 * Invoked before a possible transition to RCU idle from exit to user or
4115 * guest mode. This ensures that all RCU operations are done before RCU
4116 * stops watching. After the RCU transition lockdep_hardirqs_on() has to be
4117 * invoked to set the final state.
4119 void lockdep_hardirqs_on_prepare(unsigned long ip)
4121 if (unlikely(!debug_locks))
4125 * NMIs do not (and cannot) track lock dependencies, nothing to do.
4127 if (unlikely(in_nmi()))
4130 if (unlikely(this_cpu_read(lockdep_recursion)))
4133 if (unlikely(lockdep_hardirqs_enabled())) {
4135 * Neither irq nor preemption are disabled here
4136 * so this is racy by nature but losing one hit
4137 * in a stat is not a big deal.
4139 __debug_atomic_inc(redundant_hardirqs_on);
4144 * We're enabling irqs and according to our state above irqs weren't
4145 * already enabled, yet we find the hardware thinks they are in fact
4146 * enabled.. someone messed up their IRQ state tracing.
4148 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4152 * See the fine text that goes along with this variable definition.
4154 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
4158 * Can't allow enabling interrupts while in an interrupt handler,
4159 * that's general bad form and such. Recursion, limited stack etc..
4161 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context()))
4164 current->hardirq_chain_key = current->curr_chain_key;
4166 lockdep_recursion_inc();
4167 __trace_hardirqs_on_caller();
4168 lockdep_recursion_finish();
4170 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare);
4172 void noinstr lockdep_hardirqs_on(unsigned long ip)
4174 struct irqtrace_events *trace = ¤t->irqtrace;
4176 if (unlikely(!debug_locks))
4180 * NMIs can happen in the middle of local_irq_{en,dis}able() where the
4181 * tracking state and hardware state are out of sync.
4183 * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from,
4184 * and not rely on hardware state like normal interrupts.
4186 if (unlikely(in_nmi())) {
4187 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4192 * - recursion check, because NMI can hit lockdep;
4193 * - hardware state check, because above;
4194 * - chain_key check, see lockdep_hardirqs_on_prepare().
4199 if (unlikely(this_cpu_read(lockdep_recursion)))
4202 if (lockdep_hardirqs_enabled()) {
4204 * Neither irq nor preemption are disabled here
4205 * so this is racy by nature but losing one hit
4206 * in a stat is not a big deal.
4208 __debug_atomic_inc(redundant_hardirqs_on);
4213 * We're enabling irqs and according to our state above irqs weren't
4214 * already enabled, yet we find the hardware thinks they are in fact
4215 * enabled.. someone messed up their IRQ state tracing.
4217 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4221 * Ensure the lock stack remained unchanged between
4222 * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on().
4224 DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key !=
4225 current->curr_chain_key);
4228 /* we'll do an OFF -> ON transition: */
4229 __this_cpu_write(hardirqs_enabled, 1);
4230 trace->hardirq_enable_ip = ip;
4231 trace->hardirq_enable_event = ++trace->irq_events;
4232 debug_atomic_inc(hardirqs_on_events);
4234 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on);
4237 * Hardirqs were disabled:
4239 void noinstr lockdep_hardirqs_off(unsigned long ip)
4241 if (unlikely(!debug_locks))
4245 * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep;
4246 * they will restore the software state. This ensures the software
4247 * state is consistent inside NMIs as well.
4250 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4252 } else if (__this_cpu_read(lockdep_recursion))
4256 * So we're supposed to get called after you mask local IRQs, but for
4257 * some reason the hardware doesn't quite think you did a proper job.
4259 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4262 if (lockdep_hardirqs_enabled()) {
4263 struct irqtrace_events *trace = ¤t->irqtrace;
4266 * We have done an ON -> OFF transition:
4268 __this_cpu_write(hardirqs_enabled, 0);
4269 trace->hardirq_disable_ip = ip;
4270 trace->hardirq_disable_event = ++trace->irq_events;
4271 debug_atomic_inc(hardirqs_off_events);
4273 debug_atomic_inc(redundant_hardirqs_off);
4276 EXPORT_SYMBOL_GPL(lockdep_hardirqs_off);
4279 * Softirqs will be enabled:
4281 void lockdep_softirqs_on(unsigned long ip)
4283 struct irqtrace_events *trace = ¤t->irqtrace;
4285 if (unlikely(!lockdep_enabled()))
4289 * We fancy IRQs being disabled here, see softirq.c, avoids
4290 * funny state and nesting things.
4292 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4295 if (current->softirqs_enabled) {
4296 debug_atomic_inc(redundant_softirqs_on);
4300 lockdep_recursion_inc();
4302 * We'll do an OFF -> ON transition:
4304 current->softirqs_enabled = 1;
4305 trace->softirq_enable_ip = ip;
4306 trace->softirq_enable_event = ++trace->irq_events;
4307 debug_atomic_inc(softirqs_on_events);
4309 * We are going to turn softirqs on, so set the
4310 * usage bit for all held locks, if hardirqs are
4313 if (lockdep_hardirqs_enabled())
4314 mark_held_locks(current, LOCK_ENABLED_SOFTIRQ);
4315 lockdep_recursion_finish();
4319 * Softirqs were disabled:
4321 void lockdep_softirqs_off(unsigned long ip)
4323 if (unlikely(!lockdep_enabled()))
4327 * We fancy IRQs being disabled here, see softirq.c
4329 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4332 if (current->softirqs_enabled) {
4333 struct irqtrace_events *trace = ¤t->irqtrace;
4336 * We have done an ON -> OFF transition:
4338 current->softirqs_enabled = 0;
4339 trace->softirq_disable_ip = ip;
4340 trace->softirq_disable_event = ++trace->irq_events;
4341 debug_atomic_inc(softirqs_off_events);
4343 * Whoops, we wanted softirqs off, so why aren't they?
4345 DEBUG_LOCKS_WARN_ON(!softirq_count());
4347 debug_atomic_inc(redundant_softirqs_off);
4351 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4357 * If non-trylock use in a hardirq or softirq context, then
4358 * mark the lock as used in these contexts:
4360 if (!hlock->trylock) {
4362 if (lockdep_hardirq_context())
4363 if (!mark_lock(curr, hlock,
4364 LOCK_USED_IN_HARDIRQ_READ))
4366 if (curr->softirq_context)
4367 if (!mark_lock(curr, hlock,
4368 LOCK_USED_IN_SOFTIRQ_READ))
4371 if (lockdep_hardirq_context())
4372 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
4374 if (curr->softirq_context)
4375 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
4379 if (!hlock->hardirqs_off) {
4381 if (!mark_lock(curr, hlock,
4382 LOCK_ENABLED_HARDIRQ_READ))
4384 if (curr->softirqs_enabled)
4385 if (!mark_lock(curr, hlock,
4386 LOCK_ENABLED_SOFTIRQ_READ))
4389 if (!mark_lock(curr, hlock,
4390 LOCK_ENABLED_HARDIRQ))
4392 if (curr->softirqs_enabled)
4393 if (!mark_lock(curr, hlock,
4394 LOCK_ENABLED_SOFTIRQ))
4400 /* mark it as used: */
4401 if (!mark_lock(curr, hlock, LOCK_USED))
4407 static inline unsigned int task_irq_context(struct task_struct *task)
4409 return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() +
4410 LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context;
4413 static int separate_irq_context(struct task_struct *curr,
4414 struct held_lock *hlock)
4416 unsigned int depth = curr->lockdep_depth;
4419 * Keep track of points where we cross into an interrupt context:
4422 struct held_lock *prev_hlock;
4424 prev_hlock = curr->held_locks + depth-1;
4426 * If we cross into another context, reset the
4427 * hash key (this also prevents the checking and the
4428 * adding of the dependency to 'prev'):
4430 if (prev_hlock->irq_context != hlock->irq_context)
4437 * Mark a lock with a usage bit, and validate the state transition:
4439 static int mark_lock(struct task_struct *curr, struct held_lock *this,
4440 enum lock_usage_bit new_bit)
4442 unsigned int new_mask, ret = 1;
4444 if (new_bit >= LOCK_USAGE_STATES) {
4445 DEBUG_LOCKS_WARN_ON(1);
4449 if (new_bit == LOCK_USED && this->read)
4450 new_bit = LOCK_USED_READ;
4452 new_mask = 1 << new_bit;
4455 * If already set then do not dirty the cacheline,
4456 * nor do any checks:
4458 if (likely(hlock_class(this)->usage_mask & new_mask))
4464 * Make sure we didn't race:
4466 if (unlikely(hlock_class(this)->usage_mask & new_mask))
4469 if (!hlock_class(this)->usage_mask)
4470 debug_atomic_dec(nr_unused_locks);
4472 hlock_class(this)->usage_mask |= new_mask;
4474 if (new_bit < LOCK_TRACE_STATES) {
4475 if (!(hlock_class(this)->usage_traces[new_bit] = save_trace()))
4479 if (new_bit < LOCK_USED) {
4480 ret = mark_lock_irq(curr, this, new_bit);
4489 * We must printk outside of the graph_lock:
4492 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
4494 print_irqtrace_events(curr);
4501 static inline short task_wait_context(struct task_struct *curr)
4504 * Set appropriate wait type for the context; for IRQs we have to take
4505 * into account force_irqthread as that is implied by PREEMPT_RT.
4507 if (lockdep_hardirq_context()) {
4509 * Check if force_irqthreads will run us threaded.
4511 if (curr->hardirq_threaded || curr->irq_config)
4512 return LD_WAIT_CONFIG;
4514 return LD_WAIT_SPIN;
4515 } else if (curr->softirq_context) {
4517 * Softirqs are always threaded.
4519 return LD_WAIT_CONFIG;
4526 print_lock_invalid_wait_context(struct task_struct *curr,
4527 struct held_lock *hlock)
4531 if (!debug_locks_off())
4533 if (debug_locks_silent)
4537 pr_warn("=============================\n");
4538 pr_warn("[ BUG: Invalid wait context ]\n");
4539 print_kernel_ident();
4540 pr_warn("-----------------------------\n");
4542 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4545 pr_warn("other info that might help us debug this:\n");
4547 curr_inner = task_wait_context(curr);
4548 pr_warn("context-{%d:%d}\n", curr_inner, curr_inner);
4550 lockdep_print_held_locks(curr);
4552 pr_warn("stack backtrace:\n");
4559 * Verify the wait_type context.
4561 * This check validates we takes locks in the right wait-type order; that is it
4562 * ensures that we do not take mutexes inside spinlocks and do not attempt to
4563 * acquire spinlocks inside raw_spinlocks and the sort.
4565 * The entire thing is slightly more complex because of RCU, RCU is a lock that
4566 * can be taken from (pretty much) any context but also has constraints.
4567 * However when taken in a stricter environment the RCU lock does not loosen
4570 * Therefore we must look for the strictest environment in the lock stack and
4571 * compare that to the lock we're trying to acquire.
4573 static int check_wait_context(struct task_struct *curr, struct held_lock *next)
4575 u8 next_inner = hlock_class(next)->wait_type_inner;
4576 u8 next_outer = hlock_class(next)->wait_type_outer;
4580 if (!curr->lockdep_depth || !next_inner || next->trylock)
4584 next_outer = next_inner;
4587 * Find start of current irq_context..
4589 for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) {
4590 struct held_lock *prev = curr->held_locks + depth;
4591 if (prev->irq_context != next->irq_context)
4596 curr_inner = task_wait_context(curr);
4598 for (; depth < curr->lockdep_depth; depth++) {
4599 struct held_lock *prev = curr->held_locks + depth;
4600 u8 prev_inner = hlock_class(prev)->wait_type_inner;
4604 * We can have a bigger inner than a previous one
4605 * when outer is smaller than inner, as with RCU.
4607 * Also due to trylocks.
4609 curr_inner = min(curr_inner, prev_inner);
4613 if (next_outer > curr_inner)
4614 return print_lock_invalid_wait_context(curr, next);
4619 #else /* CONFIG_PROVE_LOCKING */
4622 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4627 static inline unsigned int task_irq_context(struct task_struct *task)
4632 static inline int separate_irq_context(struct task_struct *curr,
4633 struct held_lock *hlock)
4638 static inline int check_wait_context(struct task_struct *curr,
4639 struct held_lock *next)
4644 #endif /* CONFIG_PROVE_LOCKING */
4647 * Initialize a lock instance's lock-class mapping info:
4649 void lockdep_init_map_type(struct lockdep_map *lock, const char *name,
4650 struct lock_class_key *key, int subclass,
4651 u8 inner, u8 outer, u8 lock_type)
4655 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
4656 lock->class_cache[i] = NULL;
4658 #ifdef CONFIG_LOCK_STAT
4659 lock->cpu = raw_smp_processor_id();
4663 * Can't be having no nameless bastards around this place!
4665 if (DEBUG_LOCKS_WARN_ON(!name)) {
4666 lock->name = "NULL";
4672 lock->wait_type_outer = outer;
4673 lock->wait_type_inner = inner;
4674 lock->lock_type = lock_type;
4677 * No key, no joy, we need to hash something.
4679 if (DEBUG_LOCKS_WARN_ON(!key))
4682 * Sanity check, the lock-class key must either have been allocated
4683 * statically or must have been registered as a dynamic key.
4685 if (!static_obj(key) && !is_dynamic_key(key)) {
4687 printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
4688 DEBUG_LOCKS_WARN_ON(1);
4693 if (unlikely(!debug_locks))
4697 unsigned long flags;
4699 if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled()))
4702 raw_local_irq_save(flags);
4703 lockdep_recursion_inc();
4704 register_lock_class(lock, subclass, 1);
4705 lockdep_recursion_finish();
4706 raw_local_irq_restore(flags);
4709 EXPORT_SYMBOL_GPL(lockdep_init_map_type);
4711 struct lock_class_key __lockdep_no_validate__;
4712 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
4715 print_lock_nested_lock_not_held(struct task_struct *curr,
4716 struct held_lock *hlock,
4719 if (!debug_locks_off())
4721 if (debug_locks_silent)
4725 pr_warn("==================================\n");
4726 pr_warn("WARNING: Nested lock was not taken\n");
4727 print_kernel_ident();
4728 pr_warn("----------------------------------\n");
4730 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4733 pr_warn("\nbut this task is not holding:\n");
4734 pr_warn("%s\n", hlock->nest_lock->name);
4736 pr_warn("\nstack backtrace:\n");
4739 pr_warn("\nother info that might help us debug this:\n");
4740 lockdep_print_held_locks(curr);
4742 pr_warn("\nstack backtrace:\n");
4746 static int __lock_is_held(const struct lockdep_map *lock, int read);
4749 * This gets called for every mutex_lock*()/spin_lock*() operation.
4750 * We maintain the dependency maps and validate the locking attempt:
4752 * The callers must make sure that IRQs are disabled before calling it,
4753 * otherwise we could get an interrupt which would want to take locks,
4754 * which would end up in lockdep again.
4756 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
4757 int trylock, int read, int check, int hardirqs_off,
4758 struct lockdep_map *nest_lock, unsigned long ip,
4759 int references, int pin_count)
4761 struct task_struct *curr = current;
4762 struct lock_class *class = NULL;
4763 struct held_lock *hlock;
4769 if (unlikely(!debug_locks))
4772 if (!prove_locking || lock->key == &__lockdep_no_validate__)
4775 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
4776 class = lock->class_cache[subclass];
4780 if (unlikely(!class)) {
4781 class = register_lock_class(lock, subclass, 0);
4786 debug_class_ops_inc(class);
4788 if (very_verbose(class)) {
4789 printk("\nacquire class [%px] %s", class->key, class->name);
4790 if (class->name_version > 1)
4791 printk(KERN_CONT "#%d", class->name_version);
4792 printk(KERN_CONT "\n");
4797 * Add the lock to the list of currently held locks.
4798 * (we dont increase the depth just yet, up until the
4799 * dependency checks are done)
4801 depth = curr->lockdep_depth;
4803 * Ran out of static storage for our per-task lock stack again have we?
4805 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
4808 class_idx = class - lock_classes;
4810 if (depth) { /* we're holding locks */
4811 hlock = curr->held_locks + depth - 1;
4812 if (hlock->class_idx == class_idx && nest_lock) {
4816 if (!hlock->references)
4817 hlock->references++;
4819 hlock->references += references;
4822 if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
4829 hlock = curr->held_locks + depth;
4831 * Plain impossible, we just registered it and checked it weren't no
4832 * NULL like.. I bet this mushroom I ate was good!
4834 if (DEBUG_LOCKS_WARN_ON(!class))
4836 hlock->class_idx = class_idx;
4837 hlock->acquire_ip = ip;
4838 hlock->instance = lock;
4839 hlock->nest_lock = nest_lock;
4840 hlock->irq_context = task_irq_context(curr);
4841 hlock->trylock = trylock;
4843 hlock->check = check;
4844 hlock->hardirqs_off = !!hardirqs_off;
4845 hlock->references = references;
4846 #ifdef CONFIG_LOCK_STAT
4847 hlock->waittime_stamp = 0;
4848 hlock->holdtime_stamp = lockstat_clock();
4850 hlock->pin_count = pin_count;
4852 if (check_wait_context(curr, hlock))
4855 /* Initialize the lock usage bit */
4856 if (!mark_usage(curr, hlock, check))
4860 * Calculate the chain hash: it's the combined hash of all the
4861 * lock keys along the dependency chain. We save the hash value
4862 * at every step so that we can get the current hash easily
4863 * after unlock. The chain hash is then used to cache dependency
4866 * The 'key ID' is what is the most compact key value to drive
4867 * the hash, not class->key.
4870 * Whoops, we did it again.. class_idx is invalid.
4872 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
4875 chain_key = curr->curr_chain_key;
4878 * How can we have a chain hash when we ain't got no keys?!
4880 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
4885 hlock->prev_chain_key = chain_key;
4886 if (separate_irq_context(curr, hlock)) {
4887 chain_key = INITIAL_CHAIN_KEY;
4890 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
4892 if (nest_lock && !__lock_is_held(nest_lock, -1)) {
4893 print_lock_nested_lock_not_held(curr, hlock, ip);
4897 if (!debug_locks_silent) {
4898 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
4899 WARN_ON_ONCE(!hlock_class(hlock)->key);
4902 if (!validate_chain(curr, hlock, chain_head, chain_key))
4905 curr->curr_chain_key = chain_key;
4906 curr->lockdep_depth++;
4907 check_chain_key(curr);
4908 #ifdef CONFIG_DEBUG_LOCKDEP
4909 if (unlikely(!debug_locks))
4912 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
4914 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
4915 printk(KERN_DEBUG "depth: %i max: %lu!\n",
4916 curr->lockdep_depth, MAX_LOCK_DEPTH);
4918 lockdep_print_held_locks(current);
4919 debug_show_all_locks();
4925 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
4926 max_lockdep_depth = curr->lockdep_depth;
4931 static void print_unlock_imbalance_bug(struct task_struct *curr,
4932 struct lockdep_map *lock,
4935 if (!debug_locks_off())
4937 if (debug_locks_silent)
4941 pr_warn("=====================================\n");
4942 pr_warn("WARNING: bad unlock balance detected!\n");
4943 print_kernel_ident();
4944 pr_warn("-------------------------------------\n");
4945 pr_warn("%s/%d is trying to release lock (",
4946 curr->comm, task_pid_nr(curr));
4947 print_lockdep_cache(lock);
4949 print_ip_sym(KERN_WARNING, ip);
4950 pr_warn("but there are no more locks to release!\n");
4951 pr_warn("\nother info that might help us debug this:\n");
4952 lockdep_print_held_locks(curr);
4954 pr_warn("\nstack backtrace:\n");
4958 static noinstr int match_held_lock(const struct held_lock *hlock,
4959 const struct lockdep_map *lock)
4961 if (hlock->instance == lock)
4964 if (hlock->references) {
4965 const struct lock_class *class = lock->class_cache[0];
4968 class = look_up_lock_class(lock, 0);
4971 * If look_up_lock_class() failed to find a class, we're trying
4972 * to test if we hold a lock that has never yet been acquired.
4973 * Clearly if the lock hasn't been acquired _ever_, we're not
4974 * holding it either, so report failure.
4980 * References, but not a lock we're actually ref-counting?
4981 * State got messed up, follow the sites that change ->references
4982 * and try to make sense of it.
4984 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
4987 if (hlock->class_idx == class - lock_classes)
4994 /* @depth must not be zero */
4995 static struct held_lock *find_held_lock(struct task_struct *curr,
4996 struct lockdep_map *lock,
4997 unsigned int depth, int *idx)
4999 struct held_lock *ret, *hlock, *prev_hlock;
5003 hlock = curr->held_locks + i;
5005 if (match_held_lock(hlock, lock))
5009 for (i--, prev_hlock = hlock--;
5011 i--, prev_hlock = hlock--) {
5013 * We must not cross into another context:
5015 if (prev_hlock->irq_context != hlock->irq_context) {
5019 if (match_held_lock(hlock, lock)) {
5030 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
5031 int idx, unsigned int *merged)
5033 struct held_lock *hlock;
5034 int first_idx = idx;
5036 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
5039 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
5040 switch (__lock_acquire(hlock->instance,
5041 hlock_class(hlock)->subclass,
5043 hlock->read, hlock->check,
5044 hlock->hardirqs_off,
5045 hlock->nest_lock, hlock->acquire_ip,
5046 hlock->references, hlock->pin_count)) {
5052 *merged += (idx == first_idx);
5063 __lock_set_class(struct lockdep_map *lock, const char *name,
5064 struct lock_class_key *key, unsigned int subclass,
5067 struct task_struct *curr = current;
5068 unsigned int depth, merged = 0;
5069 struct held_lock *hlock;
5070 struct lock_class *class;
5073 if (unlikely(!debug_locks))
5076 depth = curr->lockdep_depth;
5078 * This function is about (re)setting the class of a held lock,
5079 * yet we're not actually holding any locks. Naughty user!
5081 if (DEBUG_LOCKS_WARN_ON(!depth))
5084 hlock = find_held_lock(curr, lock, depth, &i);
5086 print_unlock_imbalance_bug(curr, lock, ip);
5090 lockdep_init_map_waits(lock, name, key, 0,
5091 lock->wait_type_inner,
5092 lock->wait_type_outer);
5093 class = register_lock_class(lock, subclass, 0);
5094 hlock->class_idx = class - lock_classes;
5096 curr->lockdep_depth = i;
5097 curr->curr_chain_key = hlock->prev_chain_key;
5099 if (reacquire_held_locks(curr, depth, i, &merged))
5103 * I took it apart and put it back together again, except now I have
5104 * these 'spare' parts.. where shall I put them.
5106 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
5111 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5113 struct task_struct *curr = current;
5114 unsigned int depth, merged = 0;
5115 struct held_lock *hlock;
5118 if (unlikely(!debug_locks))
5121 depth = curr->lockdep_depth;
5123 * This function is about (re)setting the class of a held lock,
5124 * yet we're not actually holding any locks. Naughty user!
5126 if (DEBUG_LOCKS_WARN_ON(!depth))
5129 hlock = find_held_lock(curr, lock, depth, &i);
5131 print_unlock_imbalance_bug(curr, lock, ip);
5135 curr->lockdep_depth = i;
5136 curr->curr_chain_key = hlock->prev_chain_key;
5138 WARN(hlock->read, "downgrading a read lock");
5140 hlock->acquire_ip = ip;
5142 if (reacquire_held_locks(curr, depth, i, &merged))
5145 /* Merging can't happen with unchanged classes.. */
5146 if (DEBUG_LOCKS_WARN_ON(merged))
5150 * I took it apart and put it back together again, except now I have
5151 * these 'spare' parts.. where shall I put them.
5153 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
5160 * Remove the lock from the list of currently held locks - this gets
5161 * called on mutex_unlock()/spin_unlock*() (or on a failed
5162 * mutex_lock_interruptible()).
5165 __lock_release(struct lockdep_map *lock, unsigned long ip)
5167 struct task_struct *curr = current;
5168 unsigned int depth, merged = 1;
5169 struct held_lock *hlock;
5172 if (unlikely(!debug_locks))
5175 depth = curr->lockdep_depth;
5177 * So we're all set to release this lock.. wait what lock? We don't
5178 * own any locks, you've been drinking again?
5181 print_unlock_imbalance_bug(curr, lock, ip);
5186 * Check whether the lock exists in the current stack
5189 hlock = find_held_lock(curr, lock, depth, &i);
5191 print_unlock_imbalance_bug(curr, lock, ip);
5195 if (hlock->instance == lock)
5196 lock_release_holdtime(hlock);
5198 WARN(hlock->pin_count, "releasing a pinned lock\n");
5200 if (hlock->references) {
5201 hlock->references--;
5202 if (hlock->references) {
5204 * We had, and after removing one, still have
5205 * references, the current lock stack is still
5206 * valid. We're done!
5213 * We have the right lock to unlock, 'hlock' points to it.
5214 * Now we remove it from the stack, and add back the other
5215 * entries (if any), recalculating the hash along the way:
5218 curr->lockdep_depth = i;
5219 curr->curr_chain_key = hlock->prev_chain_key;
5222 * The most likely case is when the unlock is on the innermost
5223 * lock. In this case, we are done!
5228 if (reacquire_held_locks(curr, depth, i + 1, &merged))
5232 * We had N bottles of beer on the wall, we drank one, but now
5233 * there's not N-1 bottles of beer left on the wall...
5234 * Pouring two of the bottles together is acceptable.
5236 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
5239 * Since reacquire_held_locks() would have called check_chain_key()
5240 * indirectly via __lock_acquire(), we don't need to do it again
5246 static __always_inline
5247 int __lock_is_held(const struct lockdep_map *lock, int read)
5249 struct task_struct *curr = current;
5252 for (i = 0; i < curr->lockdep_depth; i++) {
5253 struct held_lock *hlock = curr->held_locks + i;
5255 if (match_held_lock(hlock, lock)) {
5256 if (read == -1 || hlock->read == read)
5257 return LOCK_STATE_HELD;
5259 return LOCK_STATE_NOT_HELD;
5263 return LOCK_STATE_NOT_HELD;
5266 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
5268 struct pin_cookie cookie = NIL_COOKIE;
5269 struct task_struct *curr = current;
5272 if (unlikely(!debug_locks))
5275 for (i = 0; i < curr->lockdep_depth; i++) {
5276 struct held_lock *hlock = curr->held_locks + i;
5278 if (match_held_lock(hlock, lock)) {
5280 * Grab 16bits of randomness; this is sufficient to not
5281 * be guessable and still allows some pin nesting in
5282 * our u32 pin_count.
5284 cookie.val = 1 + (prandom_u32() >> 16);
5285 hlock->pin_count += cookie.val;
5290 WARN(1, "pinning an unheld lock\n");
5294 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5296 struct task_struct *curr = current;
5299 if (unlikely(!debug_locks))
5302 for (i = 0; i < curr->lockdep_depth; i++) {
5303 struct held_lock *hlock = curr->held_locks + i;
5305 if (match_held_lock(hlock, lock)) {
5306 hlock->pin_count += cookie.val;
5311 WARN(1, "pinning an unheld lock\n");
5314 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5316 struct task_struct *curr = current;
5319 if (unlikely(!debug_locks))
5322 for (i = 0; i < curr->lockdep_depth; i++) {
5323 struct held_lock *hlock = curr->held_locks + i;
5325 if (match_held_lock(hlock, lock)) {
5326 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
5329 hlock->pin_count -= cookie.val;
5331 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
5332 hlock->pin_count = 0;
5338 WARN(1, "unpinning an unheld lock\n");
5342 * Check whether we follow the irq-flags state precisely:
5344 static noinstr void check_flags(unsigned long flags)
5346 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP)
5350 /* Get the warning out.. */
5351 instrumentation_begin();
5353 if (irqs_disabled_flags(flags)) {
5354 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) {
5355 printk("possible reason: unannotated irqs-off.\n");
5358 if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) {
5359 printk("possible reason: unannotated irqs-on.\n");
5364 * We dont accurately track softirq state in e.g.
5365 * hardirq contexts (such as on 4KSTACKS), so only
5366 * check if not in hardirq contexts:
5368 if (!hardirq_count()) {
5369 if (softirq_count()) {
5370 /* like the above, but with softirqs */
5371 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
5373 /* lick the above, does it taste good? */
5374 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
5379 print_irqtrace_events(current);
5381 instrumentation_end();
5385 void lock_set_class(struct lockdep_map *lock, const char *name,
5386 struct lock_class_key *key, unsigned int subclass,
5389 unsigned long flags;
5391 if (unlikely(!lockdep_enabled()))
5394 raw_local_irq_save(flags);
5395 lockdep_recursion_inc();
5397 if (__lock_set_class(lock, name, key, subclass, ip))
5398 check_chain_key(current);
5399 lockdep_recursion_finish();
5400 raw_local_irq_restore(flags);
5402 EXPORT_SYMBOL_GPL(lock_set_class);
5404 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5406 unsigned long flags;
5408 if (unlikely(!lockdep_enabled()))
5411 raw_local_irq_save(flags);
5412 lockdep_recursion_inc();
5414 if (__lock_downgrade(lock, ip))
5415 check_chain_key(current);
5416 lockdep_recursion_finish();
5417 raw_local_irq_restore(flags);
5419 EXPORT_SYMBOL_GPL(lock_downgrade);
5421 /* NMI context !!! */
5422 static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass)
5424 #ifdef CONFIG_PROVE_LOCKING
5425 struct lock_class *class = look_up_lock_class(lock, subclass);
5426 unsigned long mask = LOCKF_USED;
5428 /* if it doesn't have a class (yet), it certainly hasn't been used yet */
5433 * READ locks only conflict with USED, such that if we only ever use
5434 * READ locks, there is no deadlock possible -- RCU.
5437 mask |= LOCKF_USED_READ;
5439 if (!(class->usage_mask & mask))
5442 hlock->class_idx = class - lock_classes;
5444 print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES);
5448 static bool lockdep_nmi(void)
5450 if (raw_cpu_read(lockdep_recursion))
5460 * read_lock() is recursive if:
5461 * 1. We force lockdep think this way in selftests or
5462 * 2. The implementation is not queued read/write lock or
5463 * 3. The locker is at an in_interrupt() context.
5465 bool read_lock_is_recursive(void)
5467 return force_read_lock_recursive ||
5468 !IS_ENABLED(CONFIG_QUEUED_RWLOCKS) ||
5471 EXPORT_SYMBOL_GPL(read_lock_is_recursive);
5474 * We are not always called with irqs disabled - do that here,
5475 * and also avoid lockdep recursion:
5477 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
5478 int trylock, int read, int check,
5479 struct lockdep_map *nest_lock, unsigned long ip)
5481 unsigned long flags;
5483 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
5488 if (unlikely(!lockdep_enabled())) {
5489 /* XXX allow trylock from NMI ?!? */
5490 if (lockdep_nmi() && !trylock) {
5491 struct held_lock hlock;
5493 hlock.acquire_ip = ip;
5494 hlock.instance = lock;
5495 hlock.nest_lock = nest_lock;
5496 hlock.irq_context = 2; // XXX
5497 hlock.trylock = trylock;
5499 hlock.check = check;
5500 hlock.hardirqs_off = true;
5501 hlock.references = 0;
5503 verify_lock_unused(lock, &hlock, subclass);
5508 raw_local_irq_save(flags);
5511 lockdep_recursion_inc();
5512 __lock_acquire(lock, subclass, trylock, read, check,
5513 irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
5514 lockdep_recursion_finish();
5515 raw_local_irq_restore(flags);
5517 EXPORT_SYMBOL_GPL(lock_acquire);
5519 void lock_release(struct lockdep_map *lock, unsigned long ip)
5521 unsigned long flags;
5523 trace_lock_release(lock, ip);
5525 if (unlikely(!lockdep_enabled()))
5528 raw_local_irq_save(flags);
5531 lockdep_recursion_inc();
5532 if (__lock_release(lock, ip))
5533 check_chain_key(current);
5534 lockdep_recursion_finish();
5535 raw_local_irq_restore(flags);
5537 EXPORT_SYMBOL_GPL(lock_release);
5539 noinstr int lock_is_held_type(const struct lockdep_map *lock, int read)
5541 unsigned long flags;
5542 int ret = LOCK_STATE_NOT_HELD;
5545 * Avoid false negative lockdep_assert_held() and
5546 * lockdep_assert_not_held().
5548 if (unlikely(!lockdep_enabled()))
5549 return LOCK_STATE_UNKNOWN;
5551 raw_local_irq_save(flags);
5554 lockdep_recursion_inc();
5555 ret = __lock_is_held(lock, read);
5556 lockdep_recursion_finish();
5557 raw_local_irq_restore(flags);
5561 EXPORT_SYMBOL_GPL(lock_is_held_type);
5562 NOKPROBE_SYMBOL(lock_is_held_type);
5564 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
5566 struct pin_cookie cookie = NIL_COOKIE;
5567 unsigned long flags;
5569 if (unlikely(!lockdep_enabled()))
5572 raw_local_irq_save(flags);
5575 lockdep_recursion_inc();
5576 cookie = __lock_pin_lock(lock);
5577 lockdep_recursion_finish();
5578 raw_local_irq_restore(flags);
5582 EXPORT_SYMBOL_GPL(lock_pin_lock);
5584 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5586 unsigned long flags;
5588 if (unlikely(!lockdep_enabled()))
5591 raw_local_irq_save(flags);
5594 lockdep_recursion_inc();
5595 __lock_repin_lock(lock, cookie);
5596 lockdep_recursion_finish();
5597 raw_local_irq_restore(flags);
5599 EXPORT_SYMBOL_GPL(lock_repin_lock);
5601 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5603 unsigned long flags;
5605 if (unlikely(!lockdep_enabled()))
5608 raw_local_irq_save(flags);
5611 lockdep_recursion_inc();
5612 __lock_unpin_lock(lock, cookie);
5613 lockdep_recursion_finish();
5614 raw_local_irq_restore(flags);
5616 EXPORT_SYMBOL_GPL(lock_unpin_lock);
5618 #ifdef CONFIG_LOCK_STAT
5619 static void print_lock_contention_bug(struct task_struct *curr,
5620 struct lockdep_map *lock,
5623 if (!debug_locks_off())
5625 if (debug_locks_silent)
5629 pr_warn("=================================\n");
5630 pr_warn("WARNING: bad contention detected!\n");
5631 print_kernel_ident();
5632 pr_warn("---------------------------------\n");
5633 pr_warn("%s/%d is trying to contend lock (",
5634 curr->comm, task_pid_nr(curr));
5635 print_lockdep_cache(lock);
5637 print_ip_sym(KERN_WARNING, ip);
5638 pr_warn("but there are no locks held!\n");
5639 pr_warn("\nother info that might help us debug this:\n");
5640 lockdep_print_held_locks(curr);
5642 pr_warn("\nstack backtrace:\n");
5647 __lock_contended(struct lockdep_map *lock, unsigned long ip)
5649 struct task_struct *curr = current;
5650 struct held_lock *hlock;
5651 struct lock_class_stats *stats;
5653 int i, contention_point, contending_point;
5655 depth = curr->lockdep_depth;
5657 * Whee, we contended on this lock, except it seems we're not
5658 * actually trying to acquire anything much at all..
5660 if (DEBUG_LOCKS_WARN_ON(!depth))
5663 hlock = find_held_lock(curr, lock, depth, &i);
5665 print_lock_contention_bug(curr, lock, ip);
5669 if (hlock->instance != lock)
5672 hlock->waittime_stamp = lockstat_clock();
5674 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
5675 contending_point = lock_point(hlock_class(hlock)->contending_point,
5678 stats = get_lock_stats(hlock_class(hlock));
5679 if (contention_point < LOCKSTAT_POINTS)
5680 stats->contention_point[contention_point]++;
5681 if (contending_point < LOCKSTAT_POINTS)
5682 stats->contending_point[contending_point]++;
5683 if (lock->cpu != smp_processor_id())
5684 stats->bounces[bounce_contended + !!hlock->read]++;
5688 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
5690 struct task_struct *curr = current;
5691 struct held_lock *hlock;
5692 struct lock_class_stats *stats;
5694 u64 now, waittime = 0;
5697 depth = curr->lockdep_depth;
5699 * Yay, we acquired ownership of this lock we didn't try to
5700 * acquire, how the heck did that happen?
5702 if (DEBUG_LOCKS_WARN_ON(!depth))
5705 hlock = find_held_lock(curr, lock, depth, &i);
5707 print_lock_contention_bug(curr, lock, _RET_IP_);
5711 if (hlock->instance != lock)
5714 cpu = smp_processor_id();
5715 if (hlock->waittime_stamp) {
5716 now = lockstat_clock();
5717 waittime = now - hlock->waittime_stamp;
5718 hlock->holdtime_stamp = now;
5721 stats = get_lock_stats(hlock_class(hlock));
5724 lock_time_inc(&stats->read_waittime, waittime);
5726 lock_time_inc(&stats->write_waittime, waittime);
5728 if (lock->cpu != cpu)
5729 stats->bounces[bounce_acquired + !!hlock->read]++;
5735 void lock_contended(struct lockdep_map *lock, unsigned long ip)
5737 unsigned long flags;
5739 trace_lock_acquired(lock, ip);
5741 if (unlikely(!lock_stat || !lockdep_enabled()))
5744 raw_local_irq_save(flags);
5746 lockdep_recursion_inc();
5747 __lock_contended(lock, ip);
5748 lockdep_recursion_finish();
5749 raw_local_irq_restore(flags);
5751 EXPORT_SYMBOL_GPL(lock_contended);
5753 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
5755 unsigned long flags;
5757 trace_lock_contended(lock, ip);
5759 if (unlikely(!lock_stat || !lockdep_enabled()))
5762 raw_local_irq_save(flags);
5764 lockdep_recursion_inc();
5765 __lock_acquired(lock, ip);
5766 lockdep_recursion_finish();
5767 raw_local_irq_restore(flags);
5769 EXPORT_SYMBOL_GPL(lock_acquired);
5773 * Used by the testsuite, sanitize the validator state
5774 * after a simulated failure:
5777 void lockdep_reset(void)
5779 unsigned long flags;
5782 raw_local_irq_save(flags);
5783 lockdep_init_task(current);
5784 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
5785 nr_hardirq_chains = 0;
5786 nr_softirq_chains = 0;
5787 nr_process_chains = 0;
5789 for (i = 0; i < CHAINHASH_SIZE; i++)
5790 INIT_HLIST_HEAD(chainhash_table + i);
5791 raw_local_irq_restore(flags);
5794 /* Remove a class from a lock chain. Must be called with the graph lock held. */
5795 static void remove_class_from_lock_chain(struct pending_free *pf,
5796 struct lock_chain *chain,
5797 struct lock_class *class)
5799 #ifdef CONFIG_PROVE_LOCKING
5802 for (i = chain->base; i < chain->base + chain->depth; i++) {
5803 if (chain_hlock_class_idx(chain_hlocks[i]) != class - lock_classes)
5806 * Each lock class occurs at most once in a lock chain so once
5807 * we found a match we can break out of this loop.
5809 goto free_lock_chain;
5811 /* Since the chain has not been modified, return. */
5815 free_chain_hlocks(chain->base, chain->depth);
5816 /* Overwrite the chain key for concurrent RCU readers. */
5817 WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY);
5818 dec_chains(chain->irq_context);
5821 * Note: calling hlist_del_rcu() from inside a
5822 * hlist_for_each_entry_rcu() loop is safe.
5824 hlist_del_rcu(&chain->entry);
5825 __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
5826 nr_zapped_lock_chains++;
5830 /* Must be called with the graph lock held. */
5831 static void remove_class_from_lock_chains(struct pending_free *pf,
5832 struct lock_class *class)
5834 struct lock_chain *chain;
5835 struct hlist_head *head;
5838 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
5839 head = chainhash_table + i;
5840 hlist_for_each_entry_rcu(chain, head, entry) {
5841 remove_class_from_lock_chain(pf, chain, class);
5847 * Remove all references to a lock class. The caller must hold the graph lock.
5849 static void zap_class(struct pending_free *pf, struct lock_class *class)
5851 struct lock_list *entry;
5854 WARN_ON_ONCE(!class->key);
5857 * Remove all dependencies this lock is
5860 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
5861 entry = list_entries + i;
5862 if (entry->class != class && entry->links_to != class)
5864 __clear_bit(i, list_entries_in_use);
5866 list_del_rcu(&entry->entry);
5868 if (list_empty(&class->locks_after) &&
5869 list_empty(&class->locks_before)) {
5870 list_move_tail(&class->lock_entry, &pf->zapped);
5871 hlist_del_rcu(&class->hash_entry);
5872 WRITE_ONCE(class->key, NULL);
5873 WRITE_ONCE(class->name, NULL);
5875 __clear_bit(class - lock_classes, lock_classes_in_use);
5877 WARN_ONCE(true, "%s() failed for class %s\n", __func__,
5881 remove_class_from_lock_chains(pf, class);
5882 nr_zapped_classes++;
5885 static void reinit_class(struct lock_class *class)
5887 void *const p = class;
5888 const unsigned int offset = offsetof(struct lock_class, key);
5890 WARN_ON_ONCE(!class->lock_entry.next);
5891 WARN_ON_ONCE(!list_empty(&class->locks_after));
5892 WARN_ON_ONCE(!list_empty(&class->locks_before));
5893 memset(p + offset, 0, sizeof(*class) - offset);
5894 WARN_ON_ONCE(!class->lock_entry.next);
5895 WARN_ON_ONCE(!list_empty(&class->locks_after));
5896 WARN_ON_ONCE(!list_empty(&class->locks_before));
5899 static inline int within(const void *addr, void *start, unsigned long size)
5901 return addr >= start && addr < start + size;
5904 static bool inside_selftest(void)
5906 return current == lockdep_selftest_task_struct;
5909 /* The caller must hold the graph lock. */
5910 static struct pending_free *get_pending_free(void)
5912 return delayed_free.pf + delayed_free.index;
5915 static void free_zapped_rcu(struct rcu_head *cb);
5918 * Schedule an RCU callback if no RCU callback is pending. Must be called with
5919 * the graph lock held.
5921 static void call_rcu_zapped(struct pending_free *pf)
5923 WARN_ON_ONCE(inside_selftest());
5925 if (list_empty(&pf->zapped))
5928 if (delayed_free.scheduled)
5931 delayed_free.scheduled = true;
5933 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
5934 delayed_free.index ^= 1;
5936 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
5939 /* The caller must hold the graph lock. May be called from RCU context. */
5940 static void __free_zapped_classes(struct pending_free *pf)
5942 struct lock_class *class;
5944 check_data_structures();
5946 list_for_each_entry(class, &pf->zapped, lock_entry)
5947 reinit_class(class);
5949 list_splice_init(&pf->zapped, &free_lock_classes);
5951 #ifdef CONFIG_PROVE_LOCKING
5952 bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
5953 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
5954 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
5958 static void free_zapped_rcu(struct rcu_head *ch)
5960 struct pending_free *pf;
5961 unsigned long flags;
5963 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
5966 raw_local_irq_save(flags);
5970 pf = delayed_free.pf + (delayed_free.index ^ 1);
5971 __free_zapped_classes(pf);
5972 delayed_free.scheduled = false;
5975 * If there's anything on the open list, close and start a new callback.
5977 call_rcu_zapped(delayed_free.pf + delayed_free.index);
5980 raw_local_irq_restore(flags);
5984 * Remove all lock classes from the class hash table and from the
5985 * all_lock_classes list whose key or name is in the address range [start,
5986 * start + size). Move these lock classes to the zapped_classes list. Must
5987 * be called with the graph lock held.
5989 static void __lockdep_free_key_range(struct pending_free *pf, void *start,
5992 struct lock_class *class;
5993 struct hlist_head *head;
5996 /* Unhash all classes that were created by a module. */
5997 for (i = 0; i < CLASSHASH_SIZE; i++) {
5998 head = classhash_table + i;
5999 hlist_for_each_entry_rcu(class, head, hash_entry) {
6000 if (!within(class->key, start, size) &&
6001 !within(class->name, start, size))
6003 zap_class(pf, class);
6009 * Used in module.c to remove lock classes from memory that is going to be
6010 * freed; and possibly re-used by other modules.
6012 * We will have had one synchronize_rcu() before getting here, so we're
6013 * guaranteed nobody will look up these exact classes -- they're properly dead
6014 * but still allocated.
6016 static void lockdep_free_key_range_reg(void *start, unsigned long size)
6018 struct pending_free *pf;
6019 unsigned long flags;
6021 init_data_structures_once();
6023 raw_local_irq_save(flags);
6025 pf = get_pending_free();
6026 __lockdep_free_key_range(pf, start, size);
6027 call_rcu_zapped(pf);
6029 raw_local_irq_restore(flags);
6032 * Wait for any possible iterators from look_up_lock_class() to pass
6033 * before continuing to free the memory they refer to.
6039 * Free all lockdep keys in the range [start, start+size). Does not sleep.
6040 * Ignores debug_locks. Must only be used by the lockdep selftests.
6042 static void lockdep_free_key_range_imm(void *start, unsigned long size)
6044 struct pending_free *pf = delayed_free.pf;
6045 unsigned long flags;
6047 init_data_structures_once();
6049 raw_local_irq_save(flags);
6051 __lockdep_free_key_range(pf, start, size);
6052 __free_zapped_classes(pf);
6054 raw_local_irq_restore(flags);
6057 void lockdep_free_key_range(void *start, unsigned long size)
6059 init_data_structures_once();
6061 if (inside_selftest())
6062 lockdep_free_key_range_imm(start, size);
6064 lockdep_free_key_range_reg(start, size);
6068 * Check whether any element of the @lock->class_cache[] array refers to a
6069 * registered lock class. The caller must hold either the graph lock or the
6072 static bool lock_class_cache_is_registered(struct lockdep_map *lock)
6074 struct lock_class *class;
6075 struct hlist_head *head;
6078 for (i = 0; i < CLASSHASH_SIZE; i++) {
6079 head = classhash_table + i;
6080 hlist_for_each_entry_rcu(class, head, hash_entry) {
6081 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
6082 if (lock->class_cache[j] == class)
6089 /* The caller must hold the graph lock. Does not sleep. */
6090 static void __lockdep_reset_lock(struct pending_free *pf,
6091 struct lockdep_map *lock)
6093 struct lock_class *class;
6097 * Remove all classes this lock might have:
6099 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
6101 * If the class exists we look it up and zap it:
6103 class = look_up_lock_class(lock, j);
6105 zap_class(pf, class);
6108 * Debug check: in the end all mapped classes should
6111 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
6116 * Remove all information lockdep has about a lock if debug_locks == 1. Free
6117 * released data structures from RCU context.
6119 static void lockdep_reset_lock_reg(struct lockdep_map *lock)
6121 struct pending_free *pf;
6122 unsigned long flags;
6125 raw_local_irq_save(flags);
6126 locked = graph_lock();
6130 pf = get_pending_free();
6131 __lockdep_reset_lock(pf, lock);
6132 call_rcu_zapped(pf);
6136 raw_local_irq_restore(flags);
6140 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
6141 * lockdep selftests.
6143 static void lockdep_reset_lock_imm(struct lockdep_map *lock)
6145 struct pending_free *pf = delayed_free.pf;
6146 unsigned long flags;
6148 raw_local_irq_save(flags);
6150 __lockdep_reset_lock(pf, lock);
6151 __free_zapped_classes(pf);
6153 raw_local_irq_restore(flags);
6156 void lockdep_reset_lock(struct lockdep_map *lock)
6158 init_data_structures_once();
6160 if (inside_selftest())
6161 lockdep_reset_lock_imm(lock);
6163 lockdep_reset_lock_reg(lock);
6166 /* Unregister a dynamically allocated key. */
6167 void lockdep_unregister_key(struct lock_class_key *key)
6169 struct hlist_head *hash_head = keyhashentry(key);
6170 struct lock_class_key *k;
6171 struct pending_free *pf;
6172 unsigned long flags;
6177 if (WARN_ON_ONCE(static_obj(key)))
6180 raw_local_irq_save(flags);
6184 pf = get_pending_free();
6185 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
6187 hlist_del_rcu(&k->hash_entry);
6192 WARN_ON_ONCE(!found);
6193 __lockdep_free_key_range(pf, key, 1);
6194 call_rcu_zapped(pf);
6197 raw_local_irq_restore(flags);
6199 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
6202 EXPORT_SYMBOL_GPL(lockdep_unregister_key);
6204 void __init lockdep_init(void)
6206 printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
6208 printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
6209 printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
6210 printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
6211 printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
6212 printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
6213 printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
6214 printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
6216 printk(" memory used by lock dependency info: %zu kB\n",
6217 (sizeof(lock_classes) +
6218 sizeof(lock_classes_in_use) +
6219 sizeof(classhash_table) +
6220 sizeof(list_entries) +
6221 sizeof(list_entries_in_use) +
6222 sizeof(chainhash_table) +
6223 sizeof(delayed_free)
6224 #ifdef CONFIG_PROVE_LOCKING
6226 + sizeof(lock_chains)
6227 + sizeof(lock_chains_in_use)
6228 + sizeof(chain_hlocks)
6233 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
6234 printk(" memory used for stack traces: %zu kB\n",
6235 (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
6239 printk(" per task-struct memory footprint: %zu bytes\n",
6240 sizeof(((struct task_struct *)NULL)->held_locks));
6244 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
6245 const void *mem_to, struct held_lock *hlock)
6247 if (!debug_locks_off())
6249 if (debug_locks_silent)
6253 pr_warn("=========================\n");
6254 pr_warn("WARNING: held lock freed!\n");
6255 print_kernel_ident();
6256 pr_warn("-------------------------\n");
6257 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
6258 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
6260 lockdep_print_held_locks(curr);
6262 pr_warn("\nstack backtrace:\n");
6266 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
6267 const void* lock_from, unsigned long lock_len)
6269 return lock_from + lock_len <= mem_from ||
6270 mem_from + mem_len <= lock_from;
6274 * Called when kernel memory is freed (or unmapped), or if a lock
6275 * is destroyed or reinitialized - this code checks whether there is
6276 * any held lock in the memory range of <from> to <to>:
6278 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
6280 struct task_struct *curr = current;
6281 struct held_lock *hlock;
6282 unsigned long flags;
6285 if (unlikely(!debug_locks))
6288 raw_local_irq_save(flags);
6289 for (i = 0; i < curr->lockdep_depth; i++) {
6290 hlock = curr->held_locks + i;
6292 if (not_in_range(mem_from, mem_len, hlock->instance,
6293 sizeof(*hlock->instance)))
6296 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
6299 raw_local_irq_restore(flags);
6301 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
6303 static void print_held_locks_bug(void)
6305 if (!debug_locks_off())
6307 if (debug_locks_silent)
6311 pr_warn("====================================\n");
6312 pr_warn("WARNING: %s/%d still has locks held!\n",
6313 current->comm, task_pid_nr(current));
6314 print_kernel_ident();
6315 pr_warn("------------------------------------\n");
6316 lockdep_print_held_locks(current);
6317 pr_warn("\nstack backtrace:\n");
6321 void debug_check_no_locks_held(void)
6323 if (unlikely(current->lockdep_depth > 0))
6324 print_held_locks_bug();
6326 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
6329 void debug_show_all_locks(void)
6331 struct task_struct *g, *p;
6333 if (unlikely(!debug_locks)) {
6334 pr_warn("INFO: lockdep is turned off.\n");
6337 pr_warn("\nShowing all locks held in the system:\n");
6340 for_each_process_thread(g, p) {
6341 if (!p->lockdep_depth)
6343 lockdep_print_held_locks(p);
6344 touch_nmi_watchdog();
6345 touch_all_softlockup_watchdogs();
6350 pr_warn("=============================================\n\n");
6352 EXPORT_SYMBOL_GPL(debug_show_all_locks);
6356 * Careful: only use this function if you are sure that
6357 * the task cannot run in parallel!
6359 void debug_show_held_locks(struct task_struct *task)
6361 if (unlikely(!debug_locks)) {
6362 printk("INFO: lockdep is turned off.\n");
6365 lockdep_print_held_locks(task);
6367 EXPORT_SYMBOL_GPL(debug_show_held_locks);
6369 asmlinkage __visible void lockdep_sys_exit(void)
6371 struct task_struct *curr = current;
6373 if (unlikely(curr->lockdep_depth)) {
6374 if (!debug_locks_off())
6377 pr_warn("================================================\n");
6378 pr_warn("WARNING: lock held when returning to user space!\n");
6379 print_kernel_ident();
6380 pr_warn("------------------------------------------------\n");
6381 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
6382 curr->comm, curr->pid);
6383 lockdep_print_held_locks(curr);
6387 * The lock history for each syscall should be independent. So wipe the
6388 * slate clean on return to userspace.
6390 lockdep_invariant_state(false);
6393 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
6395 struct task_struct *curr = current;
6397 /* Note: the following can be executed concurrently, so be careful. */
6399 pr_warn("=============================\n");
6400 pr_warn("WARNING: suspicious RCU usage\n");
6401 print_kernel_ident();
6402 pr_warn("-----------------------------\n");
6403 pr_warn("%s:%d %s!\n", file, line, s);
6404 pr_warn("\nother info that might help us debug this:\n\n");
6405 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
6406 !rcu_lockdep_current_cpu_online()
6407 ? "RCU used illegally from offline CPU!\n"
6409 rcu_scheduler_active, debug_locks);
6412 * If a CPU is in the RCU-free window in idle (ie: in the section
6413 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
6414 * considers that CPU to be in an "extended quiescent state",
6415 * which means that RCU will be completely ignoring that CPU.
6416 * Therefore, rcu_read_lock() and friends have absolutely no
6417 * effect on a CPU running in that state. In other words, even if
6418 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
6419 * delete data structures out from under it. RCU really has no
6420 * choice here: we need to keep an RCU-free window in idle where
6421 * the CPU may possibly enter into low power mode. This way we can
6422 * notice an extended quiescent state to other CPUs that started a grace
6423 * period. Otherwise we would delay any grace period as long as we run
6426 * So complain bitterly if someone does call rcu_read_lock(),
6427 * rcu_read_lock_bh() and so on from extended quiescent states.
6429 if (!rcu_is_watching())
6430 pr_warn("RCU used illegally from extended quiescent state!\n");
6432 lockdep_print_held_locks(curr);
6433 pr_warn("\nstack backtrace:\n");
6436 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);