1 // SPDX-License-Identifier: GPL-2.0-only
5 * Runtime locking correctness validator
7 * Started by Ingo Molnar:
9 * Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
10 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
12 * this code maps all the lock dependencies as they occur in a live kernel
13 * and will warn about the following classes of locking bugs:
15 * - lock inversion scenarios
16 * - circular lock dependencies
17 * - hardirq/softirq safe/unsafe locking bugs
19 * Bugs are reported even if the current locking scenario does not cause
20 * any deadlock at this point.
22 * I.e. if anytime in the past two locks were taken in a different order,
23 * even if it happened for another task, even if those were different
24 * locks (but of the same class as this lock), this code will detect it.
26 * Thanks to Arjan van de Ven for coming up with the initial idea of
27 * mapping lock dependencies runtime.
29 #define DISABLE_BRANCH_PROFILING
30 #include <linux/mutex.h>
31 #include <linux/sched.h>
32 #include <linux/sched/clock.h>
33 #include <linux/sched/task.h>
34 #include <linux/sched/mm.h>
35 #include <linux/delay.h>
36 #include <linux/module.h>
37 #include <linux/proc_fs.h>
38 #include <linux/seq_file.h>
39 #include <linux/spinlock.h>
40 #include <linux/kallsyms.h>
41 #include <linux/interrupt.h>
42 #include <linux/stacktrace.h>
43 #include <linux/debug_locks.h>
44 #include <linux/irqflags.h>
45 #include <linux/utsname.h>
46 #include <linux/hash.h>
47 #include <linux/ftrace.h>
48 #include <linux/stringify.h>
49 #include <linux/bitmap.h>
50 #include <linux/bitops.h>
51 #include <linux/gfp.h>
52 #include <linux/random.h>
53 #include <linux/jhash.h>
54 #include <linux/nmi.h>
55 #include <linux/rcupdate.h>
56 #include <linux/kprobes.h>
58 #include <asm/sections.h>
60 #include "lockdep_internals.h"
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/lock.h>
65 #ifdef CONFIG_PROVE_LOCKING
66 int prove_locking = 1;
67 module_param(prove_locking, int, 0644);
69 #define prove_locking 0
72 #ifdef CONFIG_LOCK_STAT
74 module_param(lock_stat, int, 0644);
80 * lockdep_lock: protects the lockdep graph, the hashes and the
81 * class/list/hash allocators.
83 * This is one of the rare exceptions where it's justified
84 * to use a raw spinlock - we really dont want the spinlock
85 * code to recurse back into the lockdep code...
87 static arch_spinlock_t lockdep_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
88 static struct task_struct *lockdep_selftest_task_struct;
90 static int graph_lock(void)
92 arch_spin_lock(&lockdep_lock);
94 * Make sure that if another CPU detected a bug while
95 * walking the graph we dont change it (while the other
96 * CPU is busy printing out stuff with the graph lock
100 arch_spin_unlock(&lockdep_lock);
103 /* prevent any recursions within lockdep from causing deadlocks */
104 current->lockdep_recursion++;
108 static inline int graph_unlock(void)
110 if (debug_locks && !arch_spin_is_locked(&lockdep_lock)) {
112 * The lockdep graph lock isn't locked while we expect it to
113 * be, we're confused now, bye!
115 return DEBUG_LOCKS_WARN_ON(1);
118 current->lockdep_recursion--;
119 arch_spin_unlock(&lockdep_lock);
124 * Turn lock debugging off and return with 0 if it was off already,
125 * and also release the graph lock:
127 static inline int debug_locks_off_graph_unlock(void)
129 int ret = debug_locks_off();
131 arch_spin_unlock(&lockdep_lock);
136 unsigned long nr_list_entries;
137 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
138 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
141 * All data structures here are protected by the global debug_lock.
143 * nr_lock_classes is the number of elements of lock_classes[] that is
146 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
147 #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
148 static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
149 unsigned long nr_lock_classes;
150 #ifndef CONFIG_DEBUG_LOCKDEP
153 struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
154 static DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
156 static inline struct lock_class *hlock_class(struct held_lock *hlock)
158 unsigned int class_idx = hlock->class_idx;
160 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
163 if (!test_bit(class_idx, lock_classes_in_use)) {
165 * Someone passed in garbage, we give up.
167 DEBUG_LOCKS_WARN_ON(1);
172 * At this point, if the passed hlock->class_idx is still garbage,
173 * we just have to live with it
175 return lock_classes + class_idx;
178 #ifdef CONFIG_LOCK_STAT
179 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
181 static inline u64 lockstat_clock(void)
183 return local_clock();
186 static int lock_point(unsigned long points[], unsigned long ip)
190 for (i = 0; i < LOCKSTAT_POINTS; i++) {
191 if (points[i] == 0) {
202 static void lock_time_inc(struct lock_time *lt, u64 time)
207 if (time < lt->min || !lt->nr)
214 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
219 if (src->max > dst->max)
222 if (src->min < dst->min || !dst->nr)
225 dst->total += src->total;
229 struct lock_class_stats lock_stats(struct lock_class *class)
231 struct lock_class_stats stats;
234 memset(&stats, 0, sizeof(struct lock_class_stats));
235 for_each_possible_cpu(cpu) {
236 struct lock_class_stats *pcs =
237 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
239 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
240 stats.contention_point[i] += pcs->contention_point[i];
242 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
243 stats.contending_point[i] += pcs->contending_point[i];
245 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
246 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
248 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
249 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
251 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
252 stats.bounces[i] += pcs->bounces[i];
258 void clear_lock_stats(struct lock_class *class)
262 for_each_possible_cpu(cpu) {
263 struct lock_class_stats *cpu_stats =
264 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
266 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
268 memset(class->contention_point, 0, sizeof(class->contention_point));
269 memset(class->contending_point, 0, sizeof(class->contending_point));
272 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
274 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
277 static void lock_release_holdtime(struct held_lock *hlock)
279 struct lock_class_stats *stats;
285 holdtime = lockstat_clock() - hlock->holdtime_stamp;
287 stats = get_lock_stats(hlock_class(hlock));
289 lock_time_inc(&stats->read_holdtime, holdtime);
291 lock_time_inc(&stats->write_holdtime, holdtime);
294 static inline void lock_release_holdtime(struct held_lock *hlock)
300 * We keep a global list of all lock classes. The list is only accessed with
301 * the lockdep spinlock lock held. free_lock_classes is a list with free
302 * elements. These elements are linked together by the lock_entry member in
305 LIST_HEAD(all_lock_classes);
306 static LIST_HEAD(free_lock_classes);
309 * struct pending_free - information about data structures about to be freed
310 * @zapped: Head of a list with struct lock_class elements.
311 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
312 * are about to be freed.
314 struct pending_free {
315 struct list_head zapped;
316 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
320 * struct delayed_free - data structures used for delayed freeing
322 * A data structure for delayed freeing of data structures that may be
323 * accessed by RCU readers at the time these were freed.
325 * @rcu_head: Used to schedule an RCU callback for freeing data structures.
326 * @index: Index of @pf to which freed data structures are added.
327 * @scheduled: Whether or not an RCU callback has been scheduled.
328 * @pf: Array with information about data structures about to be freed.
330 static struct delayed_free {
331 struct rcu_head rcu_head;
334 struct pending_free pf[2];
338 * The lockdep classes are in a hash-table as well, for fast lookup:
340 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
341 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
342 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
343 #define classhashentry(key) (classhash_table + __classhashfn((key)))
345 static struct hlist_head classhash_table[CLASSHASH_SIZE];
348 * We put the lock dependency chains into a hash-table as well, to cache
351 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
352 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
353 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
354 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
356 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
359 * The hash key of the lock dependency chains is a hash itself too:
360 * it's a hash of all locks taken up to that lock, including that lock.
361 * It's a 64-bit hash, because it's important for the keys to be
364 static inline u64 iterate_chain_key(u64 key, u32 idx)
366 u32 k0 = key, k1 = key >> 32;
368 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
370 return k0 | (u64)k1 << 32;
373 void lockdep_init_task(struct task_struct *task)
375 task->lockdep_depth = 0; /* no locks held yet */
376 task->curr_chain_key = INITIAL_CHAIN_KEY;
377 task->lockdep_recursion = 0;
380 void lockdep_off(void)
382 current->lockdep_recursion++;
384 EXPORT_SYMBOL(lockdep_off);
386 void lockdep_on(void)
388 current->lockdep_recursion--;
390 EXPORT_SYMBOL(lockdep_on);
392 void lockdep_set_selftest_task(struct task_struct *task)
394 lockdep_selftest_task_struct = task;
398 * Debugging switches:
402 #define VERY_VERBOSE 0
405 # define HARDIRQ_VERBOSE 1
406 # define SOFTIRQ_VERBOSE 1
408 # define HARDIRQ_VERBOSE 0
409 # define SOFTIRQ_VERBOSE 0
412 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
414 * Quick filtering for interesting events:
416 static int class_filter(struct lock_class *class)
420 if (class->name_version == 1 &&
421 !strcmp(class->name, "lockname"))
423 if (class->name_version == 1 &&
424 !strcmp(class->name, "&struct->lockfield"))
427 /* Filter everything else. 1 would be to allow everything else */
432 static int verbose(struct lock_class *class)
435 return class_filter(class);
441 * Stack-trace: tightly packed array of stack backtrace
442 * addresses. Protected by the graph_lock.
444 unsigned long nr_stack_trace_entries;
445 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
447 static void print_lockdep_off(const char *bug_msg)
449 printk(KERN_DEBUG "%s\n", bug_msg);
450 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
451 #ifdef CONFIG_LOCK_STAT
452 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
456 static int save_trace(struct lock_trace *trace)
458 unsigned long *entries = stack_trace + nr_stack_trace_entries;
459 unsigned int max_entries;
461 trace->offset = nr_stack_trace_entries;
462 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
463 trace->nr_entries = stack_trace_save(entries, max_entries, 3);
464 nr_stack_trace_entries += trace->nr_entries;
466 if (nr_stack_trace_entries >= MAX_STACK_TRACE_ENTRIES-1) {
467 if (!debug_locks_off_graph_unlock())
470 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
479 unsigned int nr_hardirq_chains;
480 unsigned int nr_softirq_chains;
481 unsigned int nr_process_chains;
482 unsigned int max_lockdep_depth;
484 #ifdef CONFIG_DEBUG_LOCKDEP
486 * Various lockdep statistics:
488 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
495 #define __USAGE(__STATE) \
496 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
497 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
498 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
499 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
501 static const char *usage_str[] =
503 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
504 #include "lockdep_states.h"
506 [LOCK_USED] = "INITIAL USE",
509 const char * __get_key_name(struct lockdep_subclass_key *key, char *str)
511 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
514 static inline unsigned long lock_flag(enum lock_usage_bit bit)
519 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
522 * The usage character defaults to '.' (i.e., irqs disabled and not in
523 * irq context), which is the safest usage category.
528 * The order of the following usage checks matters, which will
529 * result in the outcome character as follows:
531 * - '+': irq is enabled and not in irq context
532 * - '-': in irq context and irq is disabled
533 * - '?': in irq context and irq is enabled
535 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
537 if (class->usage_mask & lock_flag(bit))
539 } else if (class->usage_mask & lock_flag(bit))
545 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
549 #define LOCKDEP_STATE(__STATE) \
550 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
551 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
552 #include "lockdep_states.h"
558 static void __print_lock_name(struct lock_class *class)
560 char str[KSYM_NAME_LEN];
565 name = __get_key_name(class->key, str);
566 printk(KERN_CONT "%s", name);
568 printk(KERN_CONT "%s", name);
569 if (class->name_version > 1)
570 printk(KERN_CONT "#%d", class->name_version);
572 printk(KERN_CONT "/%d", class->subclass);
576 static void print_lock_name(struct lock_class *class)
578 char usage[LOCK_USAGE_CHARS];
580 get_usage_chars(class, usage);
582 printk(KERN_CONT " (");
583 __print_lock_name(class);
584 printk(KERN_CONT "){%s}", usage);
587 static void print_lockdep_cache(struct lockdep_map *lock)
590 char str[KSYM_NAME_LEN];
594 name = __get_key_name(lock->key->subkeys, str);
596 printk(KERN_CONT "%s", name);
599 static void print_lock(struct held_lock *hlock)
602 * We can be called locklessly through debug_show_all_locks() so be
603 * extra careful, the hlock might have been released and cleared.
605 * If this indeed happens, lets pretend it does not hurt to continue
606 * to print the lock unless the hlock class_idx does not point to a
607 * registered class. The rationale here is: since we don't attempt
608 * to distinguish whether we are in this situation, if it just
609 * happened we can't count on class_idx to tell either.
611 struct lock_class *lock = hlock_class(hlock);
614 printk(KERN_CONT "<RELEASED>\n");
618 printk(KERN_CONT "%p", hlock->instance);
619 print_lock_name(lock);
620 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
623 static void lockdep_print_held_locks(struct task_struct *p)
625 int i, depth = READ_ONCE(p->lockdep_depth);
628 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
630 printk("%d lock%s held by %s/%d:\n", depth,
631 depth > 1 ? "s" : "", p->comm, task_pid_nr(p));
633 * It's not reliable to print a task's held locks if it's not sleeping
634 * and it's not the current task.
636 if (p->state == TASK_RUNNING && p != current)
638 for (i = 0; i < depth; i++) {
640 print_lock(p->held_locks + i);
644 static void print_kernel_ident(void)
646 printk("%s %.*s %s\n", init_utsname()->release,
647 (int)strcspn(init_utsname()->version, " "),
648 init_utsname()->version,
652 static int very_verbose(struct lock_class *class)
655 return class_filter(class);
661 * Is this the address of a static object:
664 static int static_obj(const void *obj)
666 unsigned long start = (unsigned long) &_stext,
667 end = (unsigned long) &_end,
668 addr = (unsigned long) obj;
670 if (arch_is_kernel_initmem_freed(addr))
676 if ((addr >= start) && (addr < end))
679 if (arch_is_kernel_data(addr))
683 * in-kernel percpu var?
685 if (is_kernel_percpu_address(addr))
689 * module static or percpu var?
691 return is_module_address(addr) || is_module_percpu_address(addr);
696 * To make lock name printouts unique, we calculate a unique
697 * class->name_version generation counter. The caller must hold the graph
700 static int count_matching_names(struct lock_class *new_class)
702 struct lock_class *class;
705 if (!new_class->name)
708 list_for_each_entry(class, &all_lock_classes, lock_entry) {
709 if (new_class->key - new_class->subclass == class->key)
710 return class->name_version;
711 if (class->name && !strcmp(class->name, new_class->name))
712 count = max(count, class->name_version);
718 static inline struct lock_class *
719 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
721 struct lockdep_subclass_key *key;
722 struct hlist_head *hash_head;
723 struct lock_class *class;
725 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
728 "BUG: looking up invalid subclass: %u\n", subclass);
730 "turning off the locking correctness validator.\n");
736 * If it is not initialised then it has never been locked,
737 * so it won't be present in the hash table.
739 if (unlikely(!lock->key))
743 * NOTE: the class-key must be unique. For dynamic locks, a static
744 * lock_class_key variable is passed in through the mutex_init()
745 * (or spin_lock_init()) call - which acts as the key. For static
746 * locks we use the lock object itself as the key.
748 BUILD_BUG_ON(sizeof(struct lock_class_key) >
749 sizeof(struct lockdep_map));
751 key = lock->key->subkeys + subclass;
753 hash_head = classhashentry(key);
756 * We do an RCU walk of the hash, see lockdep_free_key_range().
758 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
761 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
762 if (class->key == key) {
764 * Huh! same key, different name? Did someone trample
765 * on some memory? We're most confused.
767 WARN_ON_ONCE(class->name != lock->name &&
768 lock->key != &__lockdep_no_validate__);
777 * Static locks do not have their class-keys yet - for them the key is
778 * the lock object itself. If the lock is in the per cpu area, the
779 * canonical address of the lock (per cpu offset removed) is used.
781 static bool assign_lock_key(struct lockdep_map *lock)
783 unsigned long can_addr, addr = (unsigned long)lock;
787 * lockdep_free_key_range() assumes that struct lock_class_key
788 * objects do not overlap. Since we use the address of lock
789 * objects as class key for static objects, check whether the
790 * size of lock_class_key objects does not exceed the size of
791 * the smallest lock object.
793 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
796 if (__is_kernel_percpu_address(addr, &can_addr))
797 lock->key = (void *)can_addr;
798 else if (__is_module_percpu_address(addr, &can_addr))
799 lock->key = (void *)can_addr;
800 else if (static_obj(lock))
801 lock->key = (void *)lock;
803 /* Debug-check: all keys must be persistent! */
805 pr_err("INFO: trying to register non-static key.\n");
806 pr_err("the code is fine but needs lockdep annotation.\n");
807 pr_err("turning off the locking correctness validator.\n");
815 #ifdef CONFIG_DEBUG_LOCKDEP
817 /* Check whether element @e occurs in list @h */
818 static bool in_list(struct list_head *e, struct list_head *h)
822 list_for_each(f, h) {
831 * Check whether entry @e occurs in any of the locks_after or locks_before
834 static bool in_any_class_list(struct list_head *e)
836 struct lock_class *class;
839 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
840 class = &lock_classes[i];
841 if (in_list(e, &class->locks_after) ||
842 in_list(e, &class->locks_before))
848 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
852 list_for_each_entry(e, h, entry) {
853 if (e->links_to != c) {
854 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
856 (unsigned long)(e - list_entries),
857 e->links_to && e->links_to->name ?
858 e->links_to->name : "(?)",
859 e->class && e->class->name ? e->class->name :
867 #ifdef CONFIG_PROVE_LOCKING
868 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
871 static bool check_lock_chain_key(struct lock_chain *chain)
873 #ifdef CONFIG_PROVE_LOCKING
874 u64 chain_key = INITIAL_CHAIN_KEY;
877 for (i = chain->base; i < chain->base + chain->depth; i++)
878 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
880 * The 'unsigned long long' casts avoid that a compiler warning
881 * is reported when building tools/lib/lockdep.
883 if (chain->chain_key != chain_key) {
884 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
885 (unsigned long long)(chain - lock_chains),
886 (unsigned long long)chain->chain_key,
887 (unsigned long long)chain_key);
894 static bool in_any_zapped_class_list(struct lock_class *class)
896 struct pending_free *pf;
899 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
900 if (in_list(&class->lock_entry, &pf->zapped))
907 static bool __check_data_structures(void)
909 struct lock_class *class;
910 struct lock_chain *chain;
911 struct hlist_head *head;
915 /* Check whether all classes occur in a lock list. */
916 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
917 class = &lock_classes[i];
918 if (!in_list(&class->lock_entry, &all_lock_classes) &&
919 !in_list(&class->lock_entry, &free_lock_classes) &&
920 !in_any_zapped_class_list(class)) {
921 printk(KERN_INFO "class %px/%s is not in any class list\n",
922 class, class->name ? : "(?)");
927 /* Check whether all classes have valid lock lists. */
928 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
929 class = &lock_classes[i];
930 if (!class_lock_list_valid(class, &class->locks_before))
932 if (!class_lock_list_valid(class, &class->locks_after))
936 /* Check the chain_key of all lock chains. */
937 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
938 head = chainhash_table + i;
939 hlist_for_each_entry_rcu(chain, head, entry) {
940 if (!check_lock_chain_key(chain))
946 * Check whether all list entries that are in use occur in a class
949 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
950 e = list_entries + i;
951 if (!in_any_class_list(&e->entry)) {
952 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
953 (unsigned int)(e - list_entries),
954 e->class->name ? : "(?)",
955 e->links_to->name ? : "(?)");
961 * Check whether all list entries that are not in use do not occur in
964 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
965 e = list_entries + i;
966 if (in_any_class_list(&e->entry)) {
967 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
968 (unsigned int)(e - list_entries),
969 e->class && e->class->name ? e->class->name :
971 e->links_to && e->links_to->name ?
972 e->links_to->name : "(?)");
980 int check_consistency = 0;
981 module_param(check_consistency, int, 0644);
983 static void check_data_structures(void)
985 static bool once = false;
987 if (check_consistency && !once) {
988 if (!__check_data_structures()) {
995 #else /* CONFIG_DEBUG_LOCKDEP */
997 static inline void check_data_structures(void) { }
999 #endif /* CONFIG_DEBUG_LOCKDEP */
1002 * Initialize the lock_classes[] array elements, the free_lock_classes list
1003 * and also the delayed_free structure.
1005 static void init_data_structures_once(void)
1007 static bool ds_initialized, rcu_head_initialized;
1010 if (likely(rcu_head_initialized))
1013 if (system_state >= SYSTEM_SCHEDULING) {
1014 init_rcu_head(&delayed_free.rcu_head);
1015 rcu_head_initialized = true;
1021 ds_initialized = true;
1023 INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
1024 INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
1026 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1027 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
1028 INIT_LIST_HEAD(&lock_classes[i].locks_after);
1029 INIT_LIST_HEAD(&lock_classes[i].locks_before);
1033 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
1035 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
1037 return lock_keys_hash + hash;
1040 /* Register a dynamically allocated key. */
1041 void lockdep_register_key(struct lock_class_key *key)
1043 struct hlist_head *hash_head;
1044 struct lock_class_key *k;
1045 unsigned long flags;
1047 if (WARN_ON_ONCE(static_obj(key)))
1049 hash_head = keyhashentry(key);
1051 raw_local_irq_save(flags);
1054 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1055 if (WARN_ON_ONCE(k == key))
1058 hlist_add_head_rcu(&key->hash_entry, hash_head);
1062 raw_local_irq_restore(flags);
1064 EXPORT_SYMBOL_GPL(lockdep_register_key);
1066 /* Check whether a key has been registered as a dynamic key. */
1067 static bool is_dynamic_key(const struct lock_class_key *key)
1069 struct hlist_head *hash_head;
1070 struct lock_class_key *k;
1073 if (WARN_ON_ONCE(static_obj(key)))
1077 * If lock debugging is disabled lock_keys_hash[] may contain
1078 * pointers to memory that has already been freed. Avoid triggering
1079 * a use-after-free in that case by returning early.
1084 hash_head = keyhashentry(key);
1087 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1099 * Register a lock's class in the hash-table, if the class is not present
1100 * yet. Otherwise we look it up. We cache the result in the lock object
1101 * itself, so actual lookup of the hash should be once per lock object.
1103 static struct lock_class *
1104 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1106 struct lockdep_subclass_key *key;
1107 struct hlist_head *hash_head;
1108 struct lock_class *class;
1110 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1112 class = look_up_lock_class(lock, subclass);
1114 goto out_set_class_cache;
1117 if (!assign_lock_key(lock))
1119 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
1123 key = lock->key->subkeys + subclass;
1124 hash_head = classhashentry(key);
1126 if (!graph_lock()) {
1130 * We have to do the hash-walk again, to avoid races
1133 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
1134 if (class->key == key)
1135 goto out_unlock_set;
1138 init_data_structures_once();
1140 /* Allocate a new lock class and add it to the hash. */
1141 class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
1144 if (!debug_locks_off_graph_unlock()) {
1148 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
1153 __set_bit(class - lock_classes, lock_classes_in_use);
1154 debug_atomic_inc(nr_unused_locks);
1156 class->name = lock->name;
1157 class->subclass = subclass;
1158 WARN_ON_ONCE(!list_empty(&class->locks_before));
1159 WARN_ON_ONCE(!list_empty(&class->locks_after));
1160 class->name_version = count_matching_names(class);
1162 * We use RCU's safe list-add method to make
1163 * parallel walking of the hash-list safe:
1165 hlist_add_head_rcu(&class->hash_entry, hash_head);
1167 * Remove the class from the free list and add it to the global list
1170 list_move_tail(&class->lock_entry, &all_lock_classes);
1172 if (verbose(class)) {
1175 printk("\nnew class %px: %s", class->key, class->name);
1176 if (class->name_version > 1)
1177 printk(KERN_CONT "#%d", class->name_version);
1178 printk(KERN_CONT "\n");
1181 if (!graph_lock()) {
1188 out_set_class_cache:
1189 if (!subclass || force)
1190 lock->class_cache[0] = class;
1191 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
1192 lock->class_cache[subclass] = class;
1195 * Hash collision, did we smoke some? We found a class with a matching
1196 * hash but the subclass -- which is hashed in -- didn't match.
1198 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
1204 #ifdef CONFIG_PROVE_LOCKING
1206 * Allocate a lockdep entry. (assumes the graph_lock held, returns
1207 * with NULL on failure)
1209 static struct lock_list *alloc_list_entry(void)
1211 int idx = find_first_zero_bit(list_entries_in_use,
1212 ARRAY_SIZE(list_entries));
1214 if (idx >= ARRAY_SIZE(list_entries)) {
1215 if (!debug_locks_off_graph_unlock())
1218 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
1223 __set_bit(idx, list_entries_in_use);
1224 return list_entries + idx;
1228 * Add a new dependency to the head of the list:
1230 static int add_lock_to_list(struct lock_class *this,
1231 struct lock_class *links_to, struct list_head *head,
1232 unsigned long ip, int distance,
1233 struct lock_trace *trace)
1235 struct lock_list *entry;
1237 * Lock not present yet - get a new dependency struct and
1238 * add it to the list:
1240 entry = alloc_list_entry();
1244 entry->class = this;
1245 entry->links_to = links_to;
1246 entry->distance = distance;
1247 entry->trace = *trace;
1249 * Both allocation and removal are done under the graph lock; but
1250 * iteration is under RCU-sched; see look_up_lock_class() and
1251 * lockdep_free_key_range().
1253 list_add_tail_rcu(&entry->entry, head);
1259 * For good efficiency of modular, we use power of 2
1261 #define MAX_CIRCULAR_QUEUE_SIZE 4096UL
1262 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
1265 * The circular_queue and helpers are used to implement graph
1266 * breadth-first search (BFS) algorithm, by which we can determine
1267 * whether there is a path from a lock to another. In deadlock checks,
1268 * a path from the next lock to be acquired to a previous held lock
1269 * indicates that adding the <prev> -> <next> lock dependency will
1270 * produce a circle in the graph. Breadth-first search instead of
1271 * depth-first search is used in order to find the shortest (circular)
1274 struct circular_queue {
1275 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
1276 unsigned int front, rear;
1279 static struct circular_queue lock_cq;
1281 unsigned int max_bfs_queue_depth;
1283 static unsigned int lockdep_dependency_gen_id;
1285 static inline void __cq_init(struct circular_queue *cq)
1287 cq->front = cq->rear = 0;
1288 lockdep_dependency_gen_id++;
1291 static inline int __cq_empty(struct circular_queue *cq)
1293 return (cq->front == cq->rear);
1296 static inline int __cq_full(struct circular_queue *cq)
1298 return ((cq->rear + 1) & CQ_MASK) == cq->front;
1301 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
1306 cq->element[cq->rear] = elem;
1307 cq->rear = (cq->rear + 1) & CQ_MASK;
1312 * Dequeue an element from the circular_queue, return a lock_list if
1313 * the queue is not empty, or NULL if otherwise.
1315 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
1317 struct lock_list * lock;
1322 lock = cq->element[cq->front];
1323 cq->front = (cq->front + 1) & CQ_MASK;
1328 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
1330 return (cq->rear - cq->front) & CQ_MASK;
1333 static inline void mark_lock_accessed(struct lock_list *lock,
1334 struct lock_list *parent)
1338 nr = lock - list_entries;
1339 WARN_ON(nr >= ARRAY_SIZE(list_entries)); /* Out-of-bounds, input fail */
1340 lock->parent = parent;
1341 lock->class->dep_gen_id = lockdep_dependency_gen_id;
1344 static inline unsigned long lock_accessed(struct lock_list *lock)
1348 nr = lock - list_entries;
1349 WARN_ON(nr >= ARRAY_SIZE(list_entries)); /* Out-of-bounds, input fail */
1350 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
1353 static inline struct lock_list *get_lock_parent(struct lock_list *child)
1355 return child->parent;
1358 static inline int get_lock_depth(struct lock_list *child)
1361 struct lock_list *parent;
1363 while ((parent = get_lock_parent(child))) {
1371 * Return the forward or backward dependency list.
1373 * @lock: the lock_list to get its class's dependency list
1374 * @offset: the offset to struct lock_class to determine whether it is
1375 * locks_after or locks_before
1377 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
1379 void *lock_class = lock->class;
1381 return lock_class + offset;
1385 * Forward- or backward-dependency search, used for both circular dependency
1386 * checking and hardirq-unsafe/softirq-unsafe checking.
1388 static int __bfs(struct lock_list *source_entry,
1390 int (*match)(struct lock_list *entry, void *data),
1391 struct lock_list **target_entry,
1394 struct lock_list *entry;
1395 struct lock_list *lock;
1396 struct list_head *head;
1397 struct circular_queue *cq = &lock_cq;
1400 if (match(source_entry, data)) {
1401 *target_entry = source_entry;
1406 head = get_dep_list(source_entry, offset);
1407 if (list_empty(head))
1411 __cq_enqueue(cq, source_entry);
1413 while ((lock = __cq_dequeue(cq))) {
1420 head = get_dep_list(lock, offset);
1422 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1424 list_for_each_entry_rcu(entry, head, entry) {
1425 if (!lock_accessed(entry)) {
1426 unsigned int cq_depth;
1427 mark_lock_accessed(entry, lock);
1428 if (match(entry, data)) {
1429 *target_entry = entry;
1434 if (__cq_enqueue(cq, entry)) {
1438 cq_depth = __cq_get_elem_count(cq);
1439 if (max_bfs_queue_depth < cq_depth)
1440 max_bfs_queue_depth = cq_depth;
1448 static inline int __bfs_forwards(struct lock_list *src_entry,
1450 int (*match)(struct lock_list *entry, void *data),
1451 struct lock_list **target_entry)
1453 return __bfs(src_entry, data, match, target_entry,
1454 offsetof(struct lock_class, locks_after));
1458 static inline int __bfs_backwards(struct lock_list *src_entry,
1460 int (*match)(struct lock_list *entry, void *data),
1461 struct lock_list **target_entry)
1463 return __bfs(src_entry, data, match, target_entry,
1464 offsetof(struct lock_class, locks_before));
1468 static void print_lock_trace(struct lock_trace *trace, unsigned int spaces)
1470 unsigned long *entries = stack_trace + trace->offset;
1472 stack_trace_print(entries, trace->nr_entries, spaces);
1476 * Print a dependency chain entry (this is only done when a deadlock
1477 * has been detected):
1479 static noinline void
1480 print_circular_bug_entry(struct lock_list *target, int depth)
1482 if (debug_locks_silent)
1484 printk("\n-> #%u", depth);
1485 print_lock_name(target->class);
1486 printk(KERN_CONT ":\n");
1487 print_lock_trace(&target->trace, 6);
1491 print_circular_lock_scenario(struct held_lock *src,
1492 struct held_lock *tgt,
1493 struct lock_list *prt)
1495 struct lock_class *source = hlock_class(src);
1496 struct lock_class *target = hlock_class(tgt);
1497 struct lock_class *parent = prt->class;
1500 * A direct locking problem where unsafe_class lock is taken
1501 * directly by safe_class lock, then all we need to show
1502 * is the deadlock scenario, as it is obvious that the
1503 * unsafe lock is taken under the safe lock.
1505 * But if there is a chain instead, where the safe lock takes
1506 * an intermediate lock (middle_class) where this lock is
1507 * not the same as the safe lock, then the lock chain is
1508 * used to describe the problem. Otherwise we would need
1509 * to show a different CPU case for each link in the chain
1510 * from the safe_class lock to the unsafe_class lock.
1512 if (parent != source) {
1513 printk("Chain exists of:\n ");
1514 __print_lock_name(source);
1515 printk(KERN_CONT " --> ");
1516 __print_lock_name(parent);
1517 printk(KERN_CONT " --> ");
1518 __print_lock_name(target);
1519 printk(KERN_CONT "\n\n");
1522 printk(" Possible unsafe locking scenario:\n\n");
1523 printk(" CPU0 CPU1\n");
1524 printk(" ---- ----\n");
1526 __print_lock_name(target);
1527 printk(KERN_CONT ");\n");
1529 __print_lock_name(parent);
1530 printk(KERN_CONT ");\n");
1532 __print_lock_name(target);
1533 printk(KERN_CONT ");\n");
1535 __print_lock_name(source);
1536 printk(KERN_CONT ");\n");
1537 printk("\n *** DEADLOCK ***\n\n");
1541 * When a circular dependency is detected, print the
1544 static noinline void
1545 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1546 struct held_lock *check_src,
1547 struct held_lock *check_tgt)
1549 struct task_struct *curr = current;
1551 if (debug_locks_silent)
1555 pr_warn("======================================================\n");
1556 pr_warn("WARNING: possible circular locking dependency detected\n");
1557 print_kernel_ident();
1558 pr_warn("------------------------------------------------------\n");
1559 pr_warn("%s/%d is trying to acquire lock:\n",
1560 curr->comm, task_pid_nr(curr));
1561 print_lock(check_src);
1563 pr_warn("\nbut task is already holding lock:\n");
1565 print_lock(check_tgt);
1566 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1567 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1569 print_circular_bug_entry(entry, depth);
1572 static inline int class_equal(struct lock_list *entry, void *data)
1574 return entry->class == data;
1577 static noinline void print_circular_bug(struct lock_list *this,
1578 struct lock_list *target,
1579 struct held_lock *check_src,
1580 struct held_lock *check_tgt)
1582 struct task_struct *curr = current;
1583 struct lock_list *parent;
1584 struct lock_list *first_parent;
1587 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1590 if (!save_trace(&this->trace))
1593 depth = get_lock_depth(target);
1595 print_circular_bug_header(target, depth, check_src, check_tgt);
1597 parent = get_lock_parent(target);
1598 first_parent = parent;
1601 print_circular_bug_entry(parent, --depth);
1602 parent = get_lock_parent(parent);
1605 printk("\nother info that might help us debug this:\n\n");
1606 print_circular_lock_scenario(check_src, check_tgt,
1609 lockdep_print_held_locks(curr);
1611 printk("\nstack backtrace:\n");
1615 static noinline void print_bfs_bug(int ret)
1617 if (!debug_locks_off_graph_unlock())
1621 * Breadth-first-search failed, graph got corrupted?
1623 WARN(1, "lockdep bfs error:%d\n", ret);
1626 static int noop_count(struct lock_list *entry, void *data)
1628 (*(unsigned long *)data)++;
1632 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
1634 unsigned long count = 0;
1635 struct lock_list *uninitialized_var(target_entry);
1637 __bfs_forwards(this, (void *)&count, noop_count, &target_entry);
1641 unsigned long lockdep_count_forward_deps(struct lock_class *class)
1643 unsigned long ret, flags;
1644 struct lock_list this;
1649 raw_local_irq_save(flags);
1650 arch_spin_lock(&lockdep_lock);
1651 ret = __lockdep_count_forward_deps(&this);
1652 arch_spin_unlock(&lockdep_lock);
1653 raw_local_irq_restore(flags);
1658 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
1660 unsigned long count = 0;
1661 struct lock_list *uninitialized_var(target_entry);
1663 __bfs_backwards(this, (void *)&count, noop_count, &target_entry);
1668 unsigned long lockdep_count_backward_deps(struct lock_class *class)
1670 unsigned long ret, flags;
1671 struct lock_list this;
1676 raw_local_irq_save(flags);
1677 arch_spin_lock(&lockdep_lock);
1678 ret = __lockdep_count_backward_deps(&this);
1679 arch_spin_unlock(&lockdep_lock);
1680 raw_local_irq_restore(flags);
1686 * Check that the dependency graph starting at <src> can lead to
1687 * <target> or not. Print an error and return 0 if it does.
1690 check_path(struct lock_class *target, struct lock_list *src_entry,
1691 struct lock_list **target_entry)
1695 ret = __bfs_forwards(src_entry, (void *)target, class_equal,
1698 if (unlikely(ret < 0))
1705 * Prove that the dependency graph starting at <src> can not
1706 * lead to <target>. If it can, there is a circle when adding
1707 * <target> -> <src> dependency.
1709 * Print an error and return 0 if it does.
1712 check_noncircular(struct held_lock *src, struct held_lock *target,
1713 struct lock_trace *trace)
1716 struct lock_list *uninitialized_var(target_entry);
1717 struct lock_list src_entry = {
1718 .class = hlock_class(src),
1722 debug_atomic_inc(nr_cyclic_checks);
1724 ret = check_path(hlock_class(target), &src_entry, &target_entry);
1726 if (unlikely(!ret)) {
1727 if (!trace->nr_entries) {
1729 * If save_trace fails here, the printing might
1730 * trigger a WARN but because of the !nr_entries it
1731 * should not do bad things.
1736 print_circular_bug(&src_entry, target_entry, src, target);
1742 #ifdef CONFIG_LOCKDEP_SMALL
1744 * Check that the dependency graph starting at <src> can lead to
1745 * <target> or not. If it can, <src> -> <target> dependency is already
1748 * Print an error and return 2 if it does or 1 if it does not.
1751 check_redundant(struct held_lock *src, struct held_lock *target)
1754 struct lock_list *uninitialized_var(target_entry);
1755 struct lock_list src_entry = {
1756 .class = hlock_class(src),
1760 debug_atomic_inc(nr_redundant_checks);
1762 ret = check_path(hlock_class(target), &src_entry, &target_entry);
1765 debug_atomic_inc(nr_redundant);
1774 #ifdef CONFIG_TRACE_IRQFLAGS
1776 static inline int usage_accumulate(struct lock_list *entry, void *mask)
1778 *(unsigned long *)mask |= entry->class->usage_mask;
1784 * Forwards and backwards subgraph searching, for the purposes of
1785 * proving that two subgraphs can be connected by a new dependency
1786 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
1789 static inline int usage_match(struct lock_list *entry, void *mask)
1791 return entry->class->usage_mask & *(unsigned long *)mask;
1795 * Find a node in the forwards-direction dependency sub-graph starting
1796 * at @root->class that matches @bit.
1798 * Return 0 if such a node exists in the subgraph, and put that node
1799 * into *@target_entry.
1801 * Return 1 otherwise and keep *@target_entry unchanged.
1802 * Return <0 on error.
1805 find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
1806 struct lock_list **target_entry)
1810 debug_atomic_inc(nr_find_usage_forwards_checks);
1812 result = __bfs_forwards(root, &usage_mask, usage_match, target_entry);
1818 * Find a node in the backwards-direction dependency sub-graph starting
1819 * at @root->class that matches @bit.
1821 * Return 0 if such a node exists in the subgraph, and put that node
1822 * into *@target_entry.
1824 * Return 1 otherwise and keep *@target_entry unchanged.
1825 * Return <0 on error.
1828 find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
1829 struct lock_list **target_entry)
1833 debug_atomic_inc(nr_find_usage_backwards_checks);
1835 result = __bfs_backwards(root, &usage_mask, usage_match, target_entry);
1840 static void print_lock_class_header(struct lock_class *class, int depth)
1844 printk("%*s->", depth, "");
1845 print_lock_name(class);
1846 #ifdef CONFIG_DEBUG_LOCKDEP
1847 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
1849 printk(KERN_CONT " {\n");
1851 for (bit = 0; bit < LOCK_USAGE_STATES; bit++) {
1852 if (class->usage_mask & (1 << bit)) {
1855 len += printk("%*s %s", depth, "", usage_str[bit]);
1856 len += printk(KERN_CONT " at:\n");
1857 print_lock_trace(class->usage_traces + bit, len);
1860 printk("%*s }\n", depth, "");
1862 printk("%*s ... key at: [<%px>] %pS\n",
1863 depth, "", class->key, class->key);
1867 * printk the shortest lock dependencies from @start to @end in reverse order:
1870 print_shortest_lock_dependencies(struct lock_list *leaf,
1871 struct lock_list *root)
1873 struct lock_list *entry = leaf;
1876 /*compute depth from generated tree by BFS*/
1877 depth = get_lock_depth(leaf);
1880 print_lock_class_header(entry->class, depth);
1881 printk("%*s ... acquired at:\n", depth, "");
1882 print_lock_trace(&entry->trace, 2);
1885 if (depth == 0 && (entry != root)) {
1886 printk("lockdep:%s bad path found in chain graph\n", __func__);
1890 entry = get_lock_parent(entry);
1892 } while (entry && (depth >= 0));
1896 print_irq_lock_scenario(struct lock_list *safe_entry,
1897 struct lock_list *unsafe_entry,
1898 struct lock_class *prev_class,
1899 struct lock_class *next_class)
1901 struct lock_class *safe_class = safe_entry->class;
1902 struct lock_class *unsafe_class = unsafe_entry->class;
1903 struct lock_class *middle_class = prev_class;
1905 if (middle_class == safe_class)
1906 middle_class = next_class;
1909 * A direct locking problem where unsafe_class lock is taken
1910 * directly by safe_class lock, then all we need to show
1911 * is the deadlock scenario, as it is obvious that the
1912 * unsafe lock is taken under the safe lock.
1914 * But if there is a chain instead, where the safe lock takes
1915 * an intermediate lock (middle_class) where this lock is
1916 * not the same as the safe lock, then the lock chain is
1917 * used to describe the problem. Otherwise we would need
1918 * to show a different CPU case for each link in the chain
1919 * from the safe_class lock to the unsafe_class lock.
1921 if (middle_class != unsafe_class) {
1922 printk("Chain exists of:\n ");
1923 __print_lock_name(safe_class);
1924 printk(KERN_CONT " --> ");
1925 __print_lock_name(middle_class);
1926 printk(KERN_CONT " --> ");
1927 __print_lock_name(unsafe_class);
1928 printk(KERN_CONT "\n\n");
1931 printk(" Possible interrupt unsafe locking scenario:\n\n");
1932 printk(" CPU0 CPU1\n");
1933 printk(" ---- ----\n");
1935 __print_lock_name(unsafe_class);
1936 printk(KERN_CONT ");\n");
1937 printk(" local_irq_disable();\n");
1939 __print_lock_name(safe_class);
1940 printk(KERN_CONT ");\n");
1942 __print_lock_name(middle_class);
1943 printk(KERN_CONT ");\n");
1944 printk(" <Interrupt>\n");
1946 __print_lock_name(safe_class);
1947 printk(KERN_CONT ");\n");
1948 printk("\n *** DEADLOCK ***\n\n");
1952 print_bad_irq_dependency(struct task_struct *curr,
1953 struct lock_list *prev_root,
1954 struct lock_list *next_root,
1955 struct lock_list *backwards_entry,
1956 struct lock_list *forwards_entry,
1957 struct held_lock *prev,
1958 struct held_lock *next,
1959 enum lock_usage_bit bit1,
1960 enum lock_usage_bit bit2,
1961 const char *irqclass)
1963 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1967 pr_warn("=====================================================\n");
1968 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
1969 irqclass, irqclass);
1970 print_kernel_ident();
1971 pr_warn("-----------------------------------------------------\n");
1972 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
1973 curr->comm, task_pid_nr(curr),
1974 curr->hardirq_context, hardirq_count() >> HARDIRQ_SHIFT,
1975 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
1976 curr->hardirqs_enabled,
1977 curr->softirqs_enabled);
1980 pr_warn("\nand this task is already holding:\n");
1982 pr_warn("which would create a new lock dependency:\n");
1983 print_lock_name(hlock_class(prev));
1985 print_lock_name(hlock_class(next));
1988 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
1990 print_lock_name(backwards_entry->class);
1991 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
1993 print_lock_trace(backwards_entry->class->usage_traces + bit1, 1);
1995 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
1996 print_lock_name(forwards_entry->class);
1997 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
2000 print_lock_trace(forwards_entry->class->usage_traces + bit2, 1);
2002 pr_warn("\nother info that might help us debug this:\n\n");
2003 print_irq_lock_scenario(backwards_entry, forwards_entry,
2004 hlock_class(prev), hlock_class(next));
2006 lockdep_print_held_locks(curr);
2008 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
2009 if (!save_trace(&prev_root->trace))
2011 print_shortest_lock_dependencies(backwards_entry, prev_root);
2013 pr_warn("\nthe dependencies between the lock to be acquired");
2014 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
2015 if (!save_trace(&next_root->trace))
2017 print_shortest_lock_dependencies(forwards_entry, next_root);
2019 pr_warn("\nstack backtrace:\n");
2023 static const char *state_names[] = {
2024 #define LOCKDEP_STATE(__STATE) \
2025 __stringify(__STATE),
2026 #include "lockdep_states.h"
2027 #undef LOCKDEP_STATE
2030 static const char *state_rnames[] = {
2031 #define LOCKDEP_STATE(__STATE) \
2032 __stringify(__STATE)"-READ",
2033 #include "lockdep_states.h"
2034 #undef LOCKDEP_STATE
2037 static inline const char *state_name(enum lock_usage_bit bit)
2039 if (bit & LOCK_USAGE_READ_MASK)
2040 return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
2042 return state_names[bit >> LOCK_USAGE_DIR_MASK];
2046 * The bit number is encoded like:
2048 * bit0: 0 exclusive, 1 read lock
2049 * bit1: 0 used in irq, 1 irq enabled
2052 static int exclusive_bit(int new_bit)
2054 int state = new_bit & LOCK_USAGE_STATE_MASK;
2055 int dir = new_bit & LOCK_USAGE_DIR_MASK;
2058 * keep state, bit flip the direction and strip read.
2060 return state | (dir ^ LOCK_USAGE_DIR_MASK);
2064 * Observe that when given a bitmask where each bitnr is encoded as above, a
2065 * right shift of the mask transforms the individual bitnrs as -1 and
2066 * conversely, a left shift transforms into +1 for the individual bitnrs.
2068 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
2069 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
2070 * instead by subtracting the bit number by 2, or shifting the mask right by 2.
2072 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
2074 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
2075 * all bits set) and recompose with bitnr1 flipped.
2077 static unsigned long invert_dir_mask(unsigned long mask)
2079 unsigned long excl = 0;
2082 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
2083 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
2089 * As above, we clear bitnr0 (LOCK_*_READ off) with bitmask ops. First, for all
2090 * bits with bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*).
2091 * And then mask out all bitnr0.
2093 static unsigned long exclusive_mask(unsigned long mask)
2095 unsigned long excl = invert_dir_mask(mask);
2098 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2099 excl &= ~LOCKF_IRQ_READ;
2105 * Retrieve the _possible_ original mask to which @mask is
2106 * exclusive. Ie: this is the opposite of exclusive_mask().
2107 * Note that 2 possible original bits can match an exclusive
2108 * bit: one has LOCK_USAGE_READ_MASK set, the other has it
2109 * cleared. So both are returned for each exclusive bit.
2111 static unsigned long original_mask(unsigned long mask)
2113 unsigned long excl = invert_dir_mask(mask);
2115 /* Include read in existing usages */
2116 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2122 * Find the first pair of bit match between an original
2123 * usage mask and an exclusive usage mask.
2125 static int find_exclusive_match(unsigned long mask,
2126 unsigned long excl_mask,
2127 enum lock_usage_bit *bitp,
2128 enum lock_usage_bit *excl_bitp)
2132 for_each_set_bit(bit, &mask, LOCK_USED) {
2133 excl = exclusive_bit(bit);
2134 if (excl_mask & lock_flag(excl)) {
2144 * Prove that the new dependency does not connect a hardirq-safe(-read)
2145 * lock with a hardirq-unsafe lock - to achieve this we search
2146 * the backwards-subgraph starting at <prev>, and the
2147 * forwards-subgraph starting at <next>:
2149 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
2150 struct held_lock *next)
2152 unsigned long usage_mask = 0, forward_mask, backward_mask;
2153 enum lock_usage_bit forward_bit = 0, backward_bit = 0;
2154 struct lock_list *uninitialized_var(target_entry1);
2155 struct lock_list *uninitialized_var(target_entry);
2156 struct lock_list this, that;
2160 * Step 1: gather all hard/soft IRQs usages backward in an
2161 * accumulated usage mask.
2164 this.class = hlock_class(prev);
2166 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, NULL);
2172 usage_mask &= LOCKF_USED_IN_IRQ_ALL;
2177 * Step 2: find exclusive uses forward that match the previous
2178 * backward accumulated mask.
2180 forward_mask = exclusive_mask(usage_mask);
2183 that.class = hlock_class(next);
2185 ret = find_usage_forwards(&that, forward_mask, &target_entry1);
2194 * Step 3: we found a bad match! Now retrieve a lock from the backward
2195 * list whose usage mask matches the exclusive usage mask from the
2196 * lock found on the forward list.
2198 backward_mask = original_mask(target_entry1->class->usage_mask);
2200 ret = find_usage_backwards(&this, backward_mask, &target_entry);
2205 if (DEBUG_LOCKS_WARN_ON(ret == 1))
2209 * Step 4: narrow down to a pair of incompatible usage bits
2212 ret = find_exclusive_match(target_entry->class->usage_mask,
2213 target_entry1->class->usage_mask,
2214 &backward_bit, &forward_bit);
2215 if (DEBUG_LOCKS_WARN_ON(ret == -1))
2218 print_bad_irq_dependency(curr, &this, &that,
2219 target_entry, target_entry1,
2221 backward_bit, forward_bit,
2222 state_name(backward_bit));
2227 static void inc_chains(void)
2229 if (current->hardirq_context)
2230 nr_hardirq_chains++;
2232 if (current->softirq_context)
2233 nr_softirq_chains++;
2235 nr_process_chains++;
2241 static inline int check_irq_usage(struct task_struct *curr,
2242 struct held_lock *prev, struct held_lock *next)
2247 static inline void inc_chains(void)
2249 nr_process_chains++;
2252 #endif /* CONFIG_TRACE_IRQFLAGS */
2255 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
2257 struct lock_class *next = hlock_class(nxt);
2258 struct lock_class *prev = hlock_class(prv);
2260 printk(" Possible unsafe locking scenario:\n\n");
2264 __print_lock_name(prev);
2265 printk(KERN_CONT ");\n");
2267 __print_lock_name(next);
2268 printk(KERN_CONT ");\n");
2269 printk("\n *** DEADLOCK ***\n\n");
2270 printk(" May be due to missing lock nesting notation\n\n");
2274 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
2275 struct held_lock *next)
2277 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2281 pr_warn("============================================\n");
2282 pr_warn("WARNING: possible recursive locking detected\n");
2283 print_kernel_ident();
2284 pr_warn("--------------------------------------------\n");
2285 pr_warn("%s/%d is trying to acquire lock:\n",
2286 curr->comm, task_pid_nr(curr));
2288 pr_warn("\nbut task is already holding lock:\n");
2291 pr_warn("\nother info that might help us debug this:\n");
2292 print_deadlock_scenario(next, prev);
2293 lockdep_print_held_locks(curr);
2295 pr_warn("\nstack backtrace:\n");
2300 * Check whether we are holding such a class already.
2302 * (Note that this has to be done separately, because the graph cannot
2303 * detect such classes of deadlocks.)
2305 * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
2308 check_deadlock(struct task_struct *curr, struct held_lock *next)
2310 struct held_lock *prev;
2311 struct held_lock *nest = NULL;
2314 for (i = 0; i < curr->lockdep_depth; i++) {
2315 prev = curr->held_locks + i;
2317 if (prev->instance == next->nest_lock)
2320 if (hlock_class(prev) != hlock_class(next))
2324 * Allow read-after-read recursion of the same
2325 * lock class (i.e. read_lock(lock)+read_lock(lock)):
2327 if ((next->read == 2) && prev->read)
2331 * We're holding the nest_lock, which serializes this lock's
2332 * nesting behaviour.
2337 print_deadlock_bug(curr, prev, next);
2344 * There was a chain-cache miss, and we are about to add a new dependency
2345 * to a previous lock. We validate the following rules:
2347 * - would the adding of the <prev> -> <next> dependency create a
2348 * circular dependency in the graph? [== circular deadlock]
2350 * - does the new prev->next dependency connect any hardirq-safe lock
2351 * (in the full backwards-subgraph starting at <prev>) with any
2352 * hardirq-unsafe lock (in the full forwards-subgraph starting at
2353 * <next>)? [== illegal lock inversion with hardirq contexts]
2355 * - does the new prev->next dependency connect any softirq-safe lock
2356 * (in the full backwards-subgraph starting at <prev>) with any
2357 * softirq-unsafe lock (in the full forwards-subgraph starting at
2358 * <next>)? [== illegal lock inversion with softirq contexts]
2360 * any of these scenarios could lead to a deadlock.
2362 * Then if all the validations pass, we add the forwards and backwards
2366 check_prev_add(struct task_struct *curr, struct held_lock *prev,
2367 struct held_lock *next, int distance, struct lock_trace *trace)
2369 struct lock_list *entry;
2372 if (!hlock_class(prev)->key || !hlock_class(next)->key) {
2374 * The warning statements below may trigger a use-after-free
2375 * of the class name. It is better to trigger a use-after free
2376 * and to have the class name most of the time instead of not
2377 * having the class name available.
2379 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
2380 "Detected use-after-free of lock class %px/%s\n",
2382 hlock_class(prev)->name);
2383 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
2384 "Detected use-after-free of lock class %px/%s\n",
2386 hlock_class(next)->name);
2391 * Prove that the new <prev> -> <next> dependency would not
2392 * create a circular dependency in the graph. (We do this by
2393 * a breadth-first search into the graph starting at <next>,
2394 * and check whether we can reach <prev>.)
2396 * The search is limited by the size of the circular queue (i.e.,
2397 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
2398 * in the graph whose neighbours are to be checked.
2400 ret = check_noncircular(next, prev, trace);
2401 if (unlikely(ret <= 0))
2404 if (!check_irq_usage(curr, prev, next))
2408 * For recursive read-locks we do all the dependency checks,
2409 * but we dont store read-triggered dependencies (only
2410 * write-triggered dependencies). This ensures that only the
2411 * write-side dependencies matter, and that if for example a
2412 * write-lock never takes any other locks, then the reads are
2413 * equivalent to a NOP.
2415 if (next->read == 2 || prev->read == 2)
2418 * Is the <prev> -> <next> dependency already present?
2420 * (this may occur even though this is a new chain: consider
2421 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
2422 * chains - the second one will be new, but L1 already has
2423 * L2 added to its dependency list, due to the first chain.)
2425 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
2426 if (entry->class == hlock_class(next)) {
2428 entry->distance = 1;
2433 #ifdef CONFIG_LOCKDEP_SMALL
2435 * Is the <prev> -> <next> link redundant?
2437 ret = check_redundant(prev, next);
2442 if (!trace->nr_entries && !save_trace(trace))
2446 * Ok, all validations passed, add the new lock
2447 * to the previous lock's dependency list:
2449 ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
2450 &hlock_class(prev)->locks_after,
2451 next->acquire_ip, distance, trace);
2456 ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
2457 &hlock_class(next)->locks_before,
2458 next->acquire_ip, distance, trace);
2466 * Add the dependency to all directly-previous locks that are 'relevant'.
2467 * The ones that are relevant are (in increasing distance from curr):
2468 * all consecutive trylock entries and the final non-trylock entry - or
2469 * the end of this context's lock-chain - whichever comes first.
2472 check_prevs_add(struct task_struct *curr, struct held_lock *next)
2474 struct lock_trace trace = { .nr_entries = 0 };
2475 int depth = curr->lockdep_depth;
2476 struct held_lock *hlock;
2481 * Depth must not be zero for a non-head lock:
2486 * At least two relevant locks must exist for this
2489 if (curr->held_locks[depth].irq_context !=
2490 curr->held_locks[depth-1].irq_context)
2494 int distance = curr->lockdep_depth - depth + 1;
2495 hlock = curr->held_locks + depth - 1;
2498 * Only non-recursive-read entries get new dependencies
2501 if (hlock->read != 2 && hlock->check) {
2502 int ret = check_prev_add(curr, hlock, next, distance,
2508 * Stop after the first non-trylock entry,
2509 * as non-trylock entries have added their
2510 * own direct dependencies already, so this
2511 * lock is connected to them indirectly:
2513 if (!hlock->trylock)
2519 * End of lock-stack?
2524 * Stop the search if we cross into another context:
2526 if (curr->held_locks[depth].irq_context !=
2527 curr->held_locks[depth-1].irq_context)
2532 if (!debug_locks_off_graph_unlock())
2536 * Clearly we all shouldn't be here, but since we made it we
2537 * can reliable say we messed up our state. See the above two
2538 * gotos for reasons why we could possibly end up here.
2545 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
2546 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
2547 int nr_chain_hlocks;
2548 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
2550 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
2552 return lock_classes + chain_hlocks[chain->base + i];
2556 * Returns the index of the first held_lock of the current chain
2558 static inline int get_first_held_lock(struct task_struct *curr,
2559 struct held_lock *hlock)
2562 struct held_lock *hlock_curr;
2564 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
2565 hlock_curr = curr->held_locks + i;
2566 if (hlock_curr->irq_context != hlock->irq_context)
2574 #ifdef CONFIG_DEBUG_LOCKDEP
2576 * Returns the next chain_key iteration
2578 static u64 print_chain_key_iteration(int class_idx, u64 chain_key)
2580 u64 new_chain_key = iterate_chain_key(chain_key, class_idx);
2582 printk(" class_idx:%d -> chain_key:%016Lx",
2584 (unsigned long long)new_chain_key);
2585 return new_chain_key;
2589 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
2591 struct held_lock *hlock;
2592 u64 chain_key = INITIAL_CHAIN_KEY;
2593 int depth = curr->lockdep_depth;
2594 int i = get_first_held_lock(curr, hlock_next);
2596 printk("depth: %u (irq_context %u)\n", depth - i + 1,
2597 hlock_next->irq_context);
2598 for (; i < depth; i++) {
2599 hlock = curr->held_locks + i;
2600 chain_key = print_chain_key_iteration(hlock->class_idx, chain_key);
2605 print_chain_key_iteration(hlock_next->class_idx, chain_key);
2606 print_lock(hlock_next);
2609 static void print_chain_keys_chain(struct lock_chain *chain)
2612 u64 chain_key = INITIAL_CHAIN_KEY;
2615 printk("depth: %u\n", chain->depth);
2616 for (i = 0; i < chain->depth; i++) {
2617 class_id = chain_hlocks[chain->base + i];
2618 chain_key = print_chain_key_iteration(class_id, chain_key);
2620 print_lock_name(lock_classes + class_id);
2625 static void print_collision(struct task_struct *curr,
2626 struct held_lock *hlock_next,
2627 struct lock_chain *chain)
2630 pr_warn("============================\n");
2631 pr_warn("WARNING: chain_key collision\n");
2632 print_kernel_ident();
2633 pr_warn("----------------------------\n");
2634 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
2635 pr_warn("Hash chain already cached but the contents don't match!\n");
2637 pr_warn("Held locks:");
2638 print_chain_keys_held_locks(curr, hlock_next);
2640 pr_warn("Locks in cached chain:");
2641 print_chain_keys_chain(chain);
2643 pr_warn("\nstack backtrace:\n");
2649 * Checks whether the chain and the current held locks are consistent
2650 * in depth and also in content. If they are not it most likely means
2651 * that there was a collision during the calculation of the chain_key.
2652 * Returns: 0 not passed, 1 passed
2654 static int check_no_collision(struct task_struct *curr,
2655 struct held_lock *hlock,
2656 struct lock_chain *chain)
2658 #ifdef CONFIG_DEBUG_LOCKDEP
2661 i = get_first_held_lock(curr, hlock);
2663 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
2664 print_collision(curr, hlock, chain);
2668 for (j = 0; j < chain->depth - 1; j++, i++) {
2669 id = curr->held_locks[i].class_idx;
2671 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
2672 print_collision(curr, hlock, chain);
2681 * Given an index that is >= -1, return the index of the next lock chain.
2682 * Return -2 if there is no next lock chain.
2684 long lockdep_next_lockchain(long i)
2686 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
2687 return i < ARRAY_SIZE(lock_chains) ? i : -2;
2690 unsigned long lock_chain_count(void)
2692 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
2695 /* Must be called with the graph lock held. */
2696 static struct lock_chain *alloc_lock_chain(void)
2698 int idx = find_first_zero_bit(lock_chains_in_use,
2699 ARRAY_SIZE(lock_chains));
2701 if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
2703 __set_bit(idx, lock_chains_in_use);
2704 return lock_chains + idx;
2708 * Adds a dependency chain into chain hashtable. And must be called with
2711 * Return 0 if fail, and graph_lock is released.
2712 * Return 1 if succeed, with graph_lock held.
2714 static inline int add_chain_cache(struct task_struct *curr,
2715 struct held_lock *hlock,
2718 struct lock_class *class = hlock_class(hlock);
2719 struct hlist_head *hash_head = chainhashentry(chain_key);
2720 struct lock_chain *chain;
2724 * The caller must hold the graph lock, ensure we've got IRQs
2725 * disabled to make this an IRQ-safe lock.. for recursion reasons
2726 * lockdep won't complain about its own locking errors.
2728 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2731 chain = alloc_lock_chain();
2733 if (!debug_locks_off_graph_unlock())
2736 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
2740 chain->chain_key = chain_key;
2741 chain->irq_context = hlock->irq_context;
2742 i = get_first_held_lock(curr, hlock);
2743 chain->depth = curr->lockdep_depth + 1 - i;
2745 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
2746 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
2747 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
2749 if (likely(nr_chain_hlocks + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS)) {
2750 chain->base = nr_chain_hlocks;
2751 for (j = 0; j < chain->depth - 1; j++, i++) {
2752 int lock_id = curr->held_locks[i].class_idx;
2753 chain_hlocks[chain->base + j] = lock_id;
2755 chain_hlocks[chain->base + j] = class - lock_classes;
2756 nr_chain_hlocks += chain->depth;
2758 if (!debug_locks_off_graph_unlock())
2761 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
2766 hlist_add_head_rcu(&chain->entry, hash_head);
2767 debug_atomic_inc(chain_lookup_misses);
2774 * Look up a dependency chain. Must be called with either the graph lock or
2775 * the RCU read lock held.
2777 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
2779 struct hlist_head *hash_head = chainhashentry(chain_key);
2780 struct lock_chain *chain;
2782 hlist_for_each_entry_rcu(chain, hash_head, entry) {
2783 if (READ_ONCE(chain->chain_key) == chain_key) {
2784 debug_atomic_inc(chain_lookup_hits);
2792 * If the key is not present yet in dependency chain cache then
2793 * add it and return 1 - in this case the new dependency chain is
2794 * validated. If the key is already hashed, return 0.
2795 * (On return with 1 graph_lock is held.)
2797 static inline int lookup_chain_cache_add(struct task_struct *curr,
2798 struct held_lock *hlock,
2801 struct lock_class *class = hlock_class(hlock);
2802 struct lock_chain *chain = lookup_chain_cache(chain_key);
2806 if (!check_no_collision(curr, hlock, chain))
2809 if (very_verbose(class)) {
2810 printk("\nhash chain already cached, key: "
2811 "%016Lx tail class: [%px] %s\n",
2812 (unsigned long long)chain_key,
2813 class->key, class->name);
2819 if (very_verbose(class)) {
2820 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
2821 (unsigned long long)chain_key, class->key, class->name);
2828 * We have to walk the chain again locked - to avoid duplicates:
2830 chain = lookup_chain_cache(chain_key);
2836 if (!add_chain_cache(curr, hlock, chain_key))
2842 static int validate_chain(struct task_struct *curr,
2843 struct held_lock *hlock,
2844 int chain_head, u64 chain_key)
2847 * Trylock needs to maintain the stack of held locks, but it
2848 * does not add new dependencies, because trylock can be done
2851 * We look up the chain_key and do the O(N^2) check and update of
2852 * the dependencies only if this is a new dependency chain.
2853 * (If lookup_chain_cache_add() return with 1 it acquires
2854 * graph_lock for us)
2856 if (!hlock->trylock && hlock->check &&
2857 lookup_chain_cache_add(curr, hlock, chain_key)) {
2859 * Check whether last held lock:
2861 * - is irq-safe, if this lock is irq-unsafe
2862 * - is softirq-safe, if this lock is hardirq-unsafe
2864 * And check whether the new lock's dependency graph
2865 * could lead back to the previous lock:
2867 * - within the current held-lock stack
2868 * - across our accumulated lock dependency records
2870 * any of these scenarios could lead to a deadlock.
2873 * The simple case: does the current hold the same lock
2876 int ret = check_deadlock(curr, hlock);
2881 * Mark recursive read, as we jump over it when
2882 * building dependencies (just like we jump over
2888 * Add dependency only if this lock is not the head
2889 * of the chain, and if it's not a secondary read-lock:
2891 if (!chain_head && ret != 2) {
2892 if (!check_prevs_add(curr, hlock))
2898 /* after lookup_chain_cache_add(): */
2899 if (unlikely(!debug_locks))
2906 static inline int validate_chain(struct task_struct *curr,
2907 struct held_lock *hlock,
2908 int chain_head, u64 chain_key)
2912 #endif /* CONFIG_PROVE_LOCKING */
2915 * We are building curr_chain_key incrementally, so double-check
2916 * it from scratch, to make sure that it's done correctly:
2918 static void check_chain_key(struct task_struct *curr)
2920 #ifdef CONFIG_DEBUG_LOCKDEP
2921 struct held_lock *hlock, *prev_hlock = NULL;
2923 u64 chain_key = INITIAL_CHAIN_KEY;
2925 for (i = 0; i < curr->lockdep_depth; i++) {
2926 hlock = curr->held_locks + i;
2927 if (chain_key != hlock->prev_chain_key) {
2930 * We got mighty confused, our chain keys don't match
2931 * with what we expect, someone trample on our task state?
2933 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
2934 curr->lockdep_depth, i,
2935 (unsigned long long)chain_key,
2936 (unsigned long long)hlock->prev_chain_key);
2941 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
2942 * it registered lock class index?
2944 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
2947 if (prev_hlock && (prev_hlock->irq_context !=
2948 hlock->irq_context))
2949 chain_key = INITIAL_CHAIN_KEY;
2950 chain_key = iterate_chain_key(chain_key, hlock->class_idx);
2953 if (chain_key != curr->curr_chain_key) {
2956 * More smoking hash instead of calculating it, damn see these
2957 * numbers float.. I bet that a pink elephant stepped on my memory.
2959 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
2960 curr->lockdep_depth, i,
2961 (unsigned long long)chain_key,
2962 (unsigned long long)curr->curr_chain_key);
2967 static int mark_lock(struct task_struct *curr, struct held_lock *this,
2968 enum lock_usage_bit new_bit);
2970 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
2973 static void print_usage_bug_scenario(struct held_lock *lock)
2975 struct lock_class *class = hlock_class(lock);
2977 printk(" Possible unsafe locking scenario:\n\n");
2981 __print_lock_name(class);
2982 printk(KERN_CONT ");\n");
2983 printk(" <Interrupt>\n");
2985 __print_lock_name(class);
2986 printk(KERN_CONT ");\n");
2987 printk("\n *** DEADLOCK ***\n\n");
2991 print_usage_bug(struct task_struct *curr, struct held_lock *this,
2992 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
2994 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2998 pr_warn("================================\n");
2999 pr_warn("WARNING: inconsistent lock state\n");
3000 print_kernel_ident();
3001 pr_warn("--------------------------------\n");
3003 pr_warn("inconsistent {%s} -> {%s} usage.\n",
3004 usage_str[prev_bit], usage_str[new_bit]);
3006 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
3007 curr->comm, task_pid_nr(curr),
3008 trace_hardirq_context(curr), hardirq_count() >> HARDIRQ_SHIFT,
3009 trace_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
3010 trace_hardirqs_enabled(curr),
3011 trace_softirqs_enabled(curr));
3014 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
3015 print_lock_trace(hlock_class(this)->usage_traces + prev_bit, 1);
3017 print_irqtrace_events(curr);
3018 pr_warn("\nother info that might help us debug this:\n");
3019 print_usage_bug_scenario(this);
3021 lockdep_print_held_locks(curr);
3023 pr_warn("\nstack backtrace:\n");
3028 * Print out an error if an invalid bit is set:
3031 valid_state(struct task_struct *curr, struct held_lock *this,
3032 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
3034 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
3035 print_usage_bug(curr, this, bad_bit, new_bit);
3043 * print irq inversion bug:
3046 print_irq_inversion_bug(struct task_struct *curr,
3047 struct lock_list *root, struct lock_list *other,
3048 struct held_lock *this, int forwards,
3049 const char *irqclass)
3051 struct lock_list *entry = other;
3052 struct lock_list *middle = NULL;
3055 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3059 pr_warn("========================================================\n");
3060 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
3061 print_kernel_ident();
3062 pr_warn("--------------------------------------------------------\n");
3063 pr_warn("%s/%d just changed the state of lock:\n",
3064 curr->comm, task_pid_nr(curr));
3067 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
3069 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
3070 print_lock_name(other->class);
3071 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
3073 pr_warn("\nother info that might help us debug this:\n");
3075 /* Find a middle lock (if one exists) */
3076 depth = get_lock_depth(other);
3078 if (depth == 0 && (entry != root)) {
3079 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
3083 entry = get_lock_parent(entry);
3085 } while (entry && entry != root && (depth >= 0));
3087 print_irq_lock_scenario(root, other,
3088 middle ? middle->class : root->class, other->class);
3090 print_irq_lock_scenario(other, root,
3091 middle ? middle->class : other->class, root->class);
3093 lockdep_print_held_locks(curr);
3095 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
3096 if (!save_trace(&root->trace))
3098 print_shortest_lock_dependencies(other, root);
3100 pr_warn("\nstack backtrace:\n");
3105 * Prove that in the forwards-direction subgraph starting at <this>
3106 * there is no lock matching <mask>:
3109 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
3110 enum lock_usage_bit bit, const char *irqclass)
3113 struct lock_list root;
3114 struct lock_list *uninitialized_var(target_entry);
3117 root.class = hlock_class(this);
3118 ret = find_usage_forwards(&root, lock_flag(bit), &target_entry);
3126 print_irq_inversion_bug(curr, &root, target_entry,
3132 * Prove that in the backwards-direction subgraph starting at <this>
3133 * there is no lock matching <mask>:
3136 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
3137 enum lock_usage_bit bit, const char *irqclass)
3140 struct lock_list root;
3141 struct lock_list *uninitialized_var(target_entry);
3144 root.class = hlock_class(this);
3145 ret = find_usage_backwards(&root, lock_flag(bit), &target_entry);
3153 print_irq_inversion_bug(curr, &root, target_entry,
3158 void print_irqtrace_events(struct task_struct *curr)
3160 printk("irq event stamp: %u\n", curr->irq_events);
3161 printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
3162 curr->hardirq_enable_event, (void *)curr->hardirq_enable_ip,
3163 (void *)curr->hardirq_enable_ip);
3164 printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
3165 curr->hardirq_disable_event, (void *)curr->hardirq_disable_ip,
3166 (void *)curr->hardirq_disable_ip);
3167 printk("softirqs last enabled at (%u): [<%px>] %pS\n",
3168 curr->softirq_enable_event, (void *)curr->softirq_enable_ip,
3169 (void *)curr->softirq_enable_ip);
3170 printk("softirqs last disabled at (%u): [<%px>] %pS\n",
3171 curr->softirq_disable_event, (void *)curr->softirq_disable_ip,
3172 (void *)curr->softirq_disable_ip);
3175 static int HARDIRQ_verbose(struct lock_class *class)
3178 return class_filter(class);
3183 static int SOFTIRQ_verbose(struct lock_class *class)
3186 return class_filter(class);
3191 #define STRICT_READ_CHECKS 1
3193 static int (*state_verbose_f[])(struct lock_class *class) = {
3194 #define LOCKDEP_STATE(__STATE) \
3196 #include "lockdep_states.h"
3197 #undef LOCKDEP_STATE
3200 static inline int state_verbose(enum lock_usage_bit bit,
3201 struct lock_class *class)
3203 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
3206 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
3207 enum lock_usage_bit bit, const char *name);
3210 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
3211 enum lock_usage_bit new_bit)
3213 int excl_bit = exclusive_bit(new_bit);
3214 int read = new_bit & LOCK_USAGE_READ_MASK;
3215 int dir = new_bit & LOCK_USAGE_DIR_MASK;
3218 * mark USED_IN has to look forwards -- to ensure no dependency
3219 * has ENABLED state, which would allow recursion deadlocks.
3221 * mark ENABLED has to look backwards -- to ensure no dependee
3222 * has USED_IN state, which, again, would allow recursion deadlocks.
3224 check_usage_f usage = dir ?
3225 check_usage_backwards : check_usage_forwards;
3228 * Validate that this particular lock does not have conflicting
3231 if (!valid_state(curr, this, new_bit, excl_bit))
3235 * Validate that the lock dependencies don't have conflicting usage
3238 if ((!read || STRICT_READ_CHECKS) &&
3239 !usage(curr, this, excl_bit, state_name(new_bit & ~LOCK_USAGE_READ_MASK)))
3243 * Check for read in write conflicts
3246 if (!valid_state(curr, this, new_bit, excl_bit + LOCK_USAGE_READ_MASK))
3249 if (STRICT_READ_CHECKS &&
3250 !usage(curr, this, excl_bit + LOCK_USAGE_READ_MASK,
3251 state_name(new_bit + LOCK_USAGE_READ_MASK)))
3255 if (state_verbose(new_bit, hlock_class(this)))
3262 * Mark all held locks with a usage bit:
3265 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
3267 struct held_lock *hlock;
3270 for (i = 0; i < curr->lockdep_depth; i++) {
3271 enum lock_usage_bit hlock_bit = base_bit;
3272 hlock = curr->held_locks + i;
3275 hlock_bit += LOCK_USAGE_READ_MASK;
3277 BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
3282 if (!mark_lock(curr, hlock, hlock_bit))
3290 * Hardirqs will be enabled:
3292 static void __trace_hardirqs_on_caller(unsigned long ip)
3294 struct task_struct *curr = current;
3296 /* we'll do an OFF -> ON transition: */
3297 curr->hardirqs_enabled = 1;
3300 * We are going to turn hardirqs on, so set the
3301 * usage bit for all held locks:
3303 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
3306 * If we have softirqs enabled, then set the usage
3307 * bit for all held locks. (disabled hardirqs prevented
3308 * this bit from being set before)
3310 if (curr->softirqs_enabled)
3311 if (!mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ))
3314 curr->hardirq_enable_ip = ip;
3315 curr->hardirq_enable_event = ++curr->irq_events;
3316 debug_atomic_inc(hardirqs_on_events);
3319 void lockdep_hardirqs_on(unsigned long ip)
3321 if (unlikely(!debug_locks || current->lockdep_recursion))
3324 if (unlikely(current->hardirqs_enabled)) {
3326 * Neither irq nor preemption are disabled here
3327 * so this is racy by nature but losing one hit
3328 * in a stat is not a big deal.
3330 __debug_atomic_inc(redundant_hardirqs_on);
3335 * We're enabling irqs and according to our state above irqs weren't
3336 * already enabled, yet we find the hardware thinks they are in fact
3337 * enabled.. someone messed up their IRQ state tracing.
3339 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3343 * See the fine text that goes along with this variable definition.
3345 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
3349 * Can't allow enabling interrupts while in an interrupt handler,
3350 * that's general bad form and such. Recursion, limited stack etc..
3352 if (DEBUG_LOCKS_WARN_ON(current->hardirq_context))
3355 current->lockdep_recursion = 1;
3356 __trace_hardirqs_on_caller(ip);
3357 current->lockdep_recursion = 0;
3359 NOKPROBE_SYMBOL(lockdep_hardirqs_on);
3362 * Hardirqs were disabled:
3364 void lockdep_hardirqs_off(unsigned long ip)
3366 struct task_struct *curr = current;
3368 if (unlikely(!debug_locks || current->lockdep_recursion))
3372 * So we're supposed to get called after you mask local IRQs, but for
3373 * some reason the hardware doesn't quite think you did a proper job.
3375 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3378 if (curr->hardirqs_enabled) {
3380 * We have done an ON -> OFF transition:
3382 curr->hardirqs_enabled = 0;
3383 curr->hardirq_disable_ip = ip;
3384 curr->hardirq_disable_event = ++curr->irq_events;
3385 debug_atomic_inc(hardirqs_off_events);
3387 debug_atomic_inc(redundant_hardirqs_off);
3389 NOKPROBE_SYMBOL(lockdep_hardirqs_off);
3392 * Softirqs will be enabled:
3394 void trace_softirqs_on(unsigned long ip)
3396 struct task_struct *curr = current;
3398 if (unlikely(!debug_locks || current->lockdep_recursion))
3402 * We fancy IRQs being disabled here, see softirq.c, avoids
3403 * funny state and nesting things.
3405 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3408 if (curr->softirqs_enabled) {
3409 debug_atomic_inc(redundant_softirqs_on);
3413 current->lockdep_recursion = 1;
3415 * We'll do an OFF -> ON transition:
3417 curr->softirqs_enabled = 1;
3418 curr->softirq_enable_ip = ip;
3419 curr->softirq_enable_event = ++curr->irq_events;
3420 debug_atomic_inc(softirqs_on_events);
3422 * We are going to turn softirqs on, so set the
3423 * usage bit for all held locks, if hardirqs are
3426 if (curr->hardirqs_enabled)
3427 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
3428 current->lockdep_recursion = 0;
3432 * Softirqs were disabled:
3434 void trace_softirqs_off(unsigned long ip)
3436 struct task_struct *curr = current;
3438 if (unlikely(!debug_locks || current->lockdep_recursion))
3442 * We fancy IRQs being disabled here, see softirq.c
3444 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3447 if (curr->softirqs_enabled) {
3449 * We have done an ON -> OFF transition:
3451 curr->softirqs_enabled = 0;
3452 curr->softirq_disable_ip = ip;
3453 curr->softirq_disable_event = ++curr->irq_events;
3454 debug_atomic_inc(softirqs_off_events);
3456 * Whoops, we wanted softirqs off, so why aren't they?
3458 DEBUG_LOCKS_WARN_ON(!softirq_count());
3460 debug_atomic_inc(redundant_softirqs_off);
3464 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
3470 * If non-trylock use in a hardirq or softirq context, then
3471 * mark the lock as used in these contexts:
3473 if (!hlock->trylock) {
3475 if (curr->hardirq_context)
3476 if (!mark_lock(curr, hlock,
3477 LOCK_USED_IN_HARDIRQ_READ))
3479 if (curr->softirq_context)
3480 if (!mark_lock(curr, hlock,
3481 LOCK_USED_IN_SOFTIRQ_READ))
3484 if (curr->hardirq_context)
3485 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
3487 if (curr->softirq_context)
3488 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
3492 if (!hlock->hardirqs_off) {
3494 if (!mark_lock(curr, hlock,
3495 LOCK_ENABLED_HARDIRQ_READ))
3497 if (curr->softirqs_enabled)
3498 if (!mark_lock(curr, hlock,
3499 LOCK_ENABLED_SOFTIRQ_READ))
3502 if (!mark_lock(curr, hlock,
3503 LOCK_ENABLED_HARDIRQ))
3505 if (curr->softirqs_enabled)
3506 if (!mark_lock(curr, hlock,
3507 LOCK_ENABLED_SOFTIRQ))
3513 /* mark it as used: */
3514 if (!mark_lock(curr, hlock, LOCK_USED))
3520 static inline unsigned int task_irq_context(struct task_struct *task)
3522 return 2 * !!task->hardirq_context + !!task->softirq_context;
3525 static int separate_irq_context(struct task_struct *curr,
3526 struct held_lock *hlock)
3528 unsigned int depth = curr->lockdep_depth;
3531 * Keep track of points where we cross into an interrupt context:
3534 struct held_lock *prev_hlock;
3536 prev_hlock = curr->held_locks + depth-1;
3538 * If we cross into another context, reset the
3539 * hash key (this also prevents the checking and the
3540 * adding of the dependency to 'prev'):
3542 if (prev_hlock->irq_context != hlock->irq_context)
3548 #else /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
3551 int mark_lock_irq(struct task_struct *curr, struct held_lock *this,
3552 enum lock_usage_bit new_bit)
3554 WARN_ON(1); /* Impossible innit? when we don't have TRACE_IRQFLAG */
3559 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
3564 static inline unsigned int task_irq_context(struct task_struct *task)
3569 static inline int separate_irq_context(struct task_struct *curr,
3570 struct held_lock *hlock)
3575 #endif /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
3578 * Mark a lock with a usage bit, and validate the state transition:
3580 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3581 enum lock_usage_bit new_bit)
3583 unsigned int new_mask = 1 << new_bit, ret = 1;
3585 if (new_bit >= LOCK_USAGE_STATES) {
3586 DEBUG_LOCKS_WARN_ON(1);
3591 * If already set then do not dirty the cacheline,
3592 * nor do any checks:
3594 if (likely(hlock_class(this)->usage_mask & new_mask))
3600 * Make sure we didn't race:
3602 if (unlikely(hlock_class(this)->usage_mask & new_mask)) {
3607 hlock_class(this)->usage_mask |= new_mask;
3609 if (!save_trace(hlock_class(this)->usage_traces + new_bit))
3614 debug_atomic_dec(nr_unused_locks);
3617 ret = mark_lock_irq(curr, this, new_bit);
3625 * We must printk outside of the graph_lock:
3628 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
3630 print_irqtrace_events(curr);
3638 * Initialize a lock instance's lock-class mapping info:
3640 void lockdep_init_map(struct lockdep_map *lock, const char *name,
3641 struct lock_class_key *key, int subclass)
3645 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
3646 lock->class_cache[i] = NULL;
3648 #ifdef CONFIG_LOCK_STAT
3649 lock->cpu = raw_smp_processor_id();
3653 * Can't be having no nameless bastards around this place!
3655 if (DEBUG_LOCKS_WARN_ON(!name)) {
3656 lock->name = "NULL";
3663 * No key, no joy, we need to hash something.
3665 if (DEBUG_LOCKS_WARN_ON(!key))
3668 * Sanity check, the lock-class key must either have been allocated
3669 * statically or must have been registered as a dynamic key.
3671 if (!static_obj(key) && !is_dynamic_key(key)) {
3673 printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
3674 DEBUG_LOCKS_WARN_ON(1);
3679 if (unlikely(!debug_locks))
3683 unsigned long flags;
3685 if (DEBUG_LOCKS_WARN_ON(current->lockdep_recursion))
3688 raw_local_irq_save(flags);
3689 current->lockdep_recursion = 1;
3690 register_lock_class(lock, subclass, 1);
3691 current->lockdep_recursion = 0;
3692 raw_local_irq_restore(flags);
3695 EXPORT_SYMBOL_GPL(lockdep_init_map);
3697 struct lock_class_key __lockdep_no_validate__;
3698 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
3701 print_lock_nested_lock_not_held(struct task_struct *curr,
3702 struct held_lock *hlock,
3705 if (!debug_locks_off())
3707 if (debug_locks_silent)
3711 pr_warn("==================================\n");
3712 pr_warn("WARNING: Nested lock was not taken\n");
3713 print_kernel_ident();
3714 pr_warn("----------------------------------\n");
3716 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
3719 pr_warn("\nbut this task is not holding:\n");
3720 pr_warn("%s\n", hlock->nest_lock->name);
3722 pr_warn("\nstack backtrace:\n");
3725 pr_warn("\nother info that might help us debug this:\n");
3726 lockdep_print_held_locks(curr);
3728 pr_warn("\nstack backtrace:\n");
3732 static int __lock_is_held(const struct lockdep_map *lock, int read);
3735 * This gets called for every mutex_lock*()/spin_lock*() operation.
3736 * We maintain the dependency maps and validate the locking attempt:
3738 * The callers must make sure that IRQs are disabled before calling it,
3739 * otherwise we could get an interrupt which would want to take locks,
3740 * which would end up in lockdep again.
3742 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3743 int trylock, int read, int check, int hardirqs_off,
3744 struct lockdep_map *nest_lock, unsigned long ip,
3745 int references, int pin_count)
3747 struct task_struct *curr = current;
3748 struct lock_class *class = NULL;
3749 struct held_lock *hlock;
3755 if (unlikely(!debug_locks))
3758 if (!prove_locking || lock->key == &__lockdep_no_validate__)
3761 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
3762 class = lock->class_cache[subclass];
3766 if (unlikely(!class)) {
3767 class = register_lock_class(lock, subclass, 0);
3772 debug_class_ops_inc(class);
3774 if (very_verbose(class)) {
3775 printk("\nacquire class [%px] %s", class->key, class->name);
3776 if (class->name_version > 1)
3777 printk(KERN_CONT "#%d", class->name_version);
3778 printk(KERN_CONT "\n");
3783 * Add the lock to the list of currently held locks.
3784 * (we dont increase the depth just yet, up until the
3785 * dependency checks are done)
3787 depth = curr->lockdep_depth;
3789 * Ran out of static storage for our per-task lock stack again have we?
3791 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
3794 class_idx = class - lock_classes;
3797 hlock = curr->held_locks + depth - 1;
3798 if (hlock->class_idx == class_idx && nest_lock) {
3799 if (hlock->references) {
3801 * Check: unsigned int references:12, overflow.
3803 if (DEBUG_LOCKS_WARN_ON(hlock->references == (1 << 12)-1))
3806 hlock->references++;
3808 hlock->references = 2;
3815 hlock = curr->held_locks + depth;
3817 * Plain impossible, we just registered it and checked it weren't no
3818 * NULL like.. I bet this mushroom I ate was good!
3820 if (DEBUG_LOCKS_WARN_ON(!class))
3822 hlock->class_idx = class_idx;
3823 hlock->acquire_ip = ip;
3824 hlock->instance = lock;
3825 hlock->nest_lock = nest_lock;
3826 hlock->irq_context = task_irq_context(curr);
3827 hlock->trylock = trylock;
3829 hlock->check = check;
3830 hlock->hardirqs_off = !!hardirqs_off;
3831 hlock->references = references;
3832 #ifdef CONFIG_LOCK_STAT
3833 hlock->waittime_stamp = 0;
3834 hlock->holdtime_stamp = lockstat_clock();
3836 hlock->pin_count = pin_count;
3838 /* Initialize the lock usage bit */
3839 if (!mark_usage(curr, hlock, check))
3843 * Calculate the chain hash: it's the combined hash of all the
3844 * lock keys along the dependency chain. We save the hash value
3845 * at every step so that we can get the current hash easily
3846 * after unlock. The chain hash is then used to cache dependency
3849 * The 'key ID' is what is the most compact key value to drive
3850 * the hash, not class->key.
3853 * Whoops, we did it again.. class_idx is invalid.
3855 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
3858 chain_key = curr->curr_chain_key;
3861 * How can we have a chain hash when we ain't got no keys?!
3863 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
3868 hlock->prev_chain_key = chain_key;
3869 if (separate_irq_context(curr, hlock)) {
3870 chain_key = INITIAL_CHAIN_KEY;
3873 chain_key = iterate_chain_key(chain_key, class_idx);
3875 if (nest_lock && !__lock_is_held(nest_lock, -1)) {
3876 print_lock_nested_lock_not_held(curr, hlock, ip);
3880 if (!debug_locks_silent) {
3881 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
3882 WARN_ON_ONCE(!hlock_class(hlock)->key);
3885 if (!validate_chain(curr, hlock, chain_head, chain_key))
3888 curr->curr_chain_key = chain_key;
3889 curr->lockdep_depth++;
3890 check_chain_key(curr);
3891 #ifdef CONFIG_DEBUG_LOCKDEP
3892 if (unlikely(!debug_locks))
3895 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
3897 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
3898 printk(KERN_DEBUG "depth: %i max: %lu!\n",
3899 curr->lockdep_depth, MAX_LOCK_DEPTH);
3901 lockdep_print_held_locks(current);
3902 debug_show_all_locks();
3908 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
3909 max_lockdep_depth = curr->lockdep_depth;
3914 static void print_unlock_imbalance_bug(struct task_struct *curr,
3915 struct lockdep_map *lock,
3918 if (!debug_locks_off())
3920 if (debug_locks_silent)
3924 pr_warn("=====================================\n");
3925 pr_warn("WARNING: bad unlock balance detected!\n");
3926 print_kernel_ident();
3927 pr_warn("-------------------------------------\n");
3928 pr_warn("%s/%d is trying to release lock (",
3929 curr->comm, task_pid_nr(curr));
3930 print_lockdep_cache(lock);
3933 pr_warn("but there are no more locks to release!\n");
3934 pr_warn("\nother info that might help us debug this:\n");
3935 lockdep_print_held_locks(curr);
3937 pr_warn("\nstack backtrace:\n");
3941 static int match_held_lock(const struct held_lock *hlock,
3942 const struct lockdep_map *lock)
3944 if (hlock->instance == lock)
3947 if (hlock->references) {
3948 const struct lock_class *class = lock->class_cache[0];
3951 class = look_up_lock_class(lock, 0);
3954 * If look_up_lock_class() failed to find a class, we're trying
3955 * to test if we hold a lock that has never yet been acquired.
3956 * Clearly if the lock hasn't been acquired _ever_, we're not
3957 * holding it either, so report failure.
3963 * References, but not a lock we're actually ref-counting?
3964 * State got messed up, follow the sites that change ->references
3965 * and try to make sense of it.
3967 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
3970 if (hlock->class_idx == class - lock_classes)
3977 /* @depth must not be zero */
3978 static struct held_lock *find_held_lock(struct task_struct *curr,
3979 struct lockdep_map *lock,
3980 unsigned int depth, int *idx)
3982 struct held_lock *ret, *hlock, *prev_hlock;
3986 hlock = curr->held_locks + i;
3988 if (match_held_lock(hlock, lock))
3992 for (i--, prev_hlock = hlock--;
3994 i--, prev_hlock = hlock--) {
3996 * We must not cross into another context:
3998 if (prev_hlock->irq_context != hlock->irq_context) {
4002 if (match_held_lock(hlock, lock)) {
4013 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
4014 int idx, unsigned int *merged)
4016 struct held_lock *hlock;
4017 int first_idx = idx;
4019 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4022 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
4023 switch (__lock_acquire(hlock->instance,
4024 hlock_class(hlock)->subclass,
4026 hlock->read, hlock->check,
4027 hlock->hardirqs_off,
4028 hlock->nest_lock, hlock->acquire_ip,
4029 hlock->references, hlock->pin_count)) {
4035 *merged += (idx == first_idx);
4046 __lock_set_class(struct lockdep_map *lock, const char *name,
4047 struct lock_class_key *key, unsigned int subclass,
4050 struct task_struct *curr = current;
4051 unsigned int depth, merged = 0;
4052 struct held_lock *hlock;
4053 struct lock_class *class;
4056 if (unlikely(!debug_locks))
4059 depth = curr->lockdep_depth;
4061 * This function is about (re)setting the class of a held lock,
4062 * yet we're not actually holding any locks. Naughty user!
4064 if (DEBUG_LOCKS_WARN_ON(!depth))
4067 hlock = find_held_lock(curr, lock, depth, &i);
4069 print_unlock_imbalance_bug(curr, lock, ip);
4073 lockdep_init_map(lock, name, key, 0);
4074 class = register_lock_class(lock, subclass, 0);
4075 hlock->class_idx = class - lock_classes;
4077 curr->lockdep_depth = i;
4078 curr->curr_chain_key = hlock->prev_chain_key;
4080 if (reacquire_held_locks(curr, depth, i, &merged))
4084 * I took it apart and put it back together again, except now I have
4085 * these 'spare' parts.. where shall I put them.
4087 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
4092 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
4094 struct task_struct *curr = current;
4095 unsigned int depth, merged = 0;
4096 struct held_lock *hlock;
4099 if (unlikely(!debug_locks))
4102 depth = curr->lockdep_depth;
4104 * This function is about (re)setting the class of a held lock,
4105 * yet we're not actually holding any locks. Naughty user!
4107 if (DEBUG_LOCKS_WARN_ON(!depth))
4110 hlock = find_held_lock(curr, lock, depth, &i);
4112 print_unlock_imbalance_bug(curr, lock, ip);
4116 curr->lockdep_depth = i;
4117 curr->curr_chain_key = hlock->prev_chain_key;
4119 WARN(hlock->read, "downgrading a read lock");
4121 hlock->acquire_ip = ip;
4123 if (reacquire_held_locks(curr, depth, i, &merged))
4126 /* Merging can't happen with unchanged classes.. */
4127 if (DEBUG_LOCKS_WARN_ON(merged))
4131 * I took it apart and put it back together again, except now I have
4132 * these 'spare' parts.. where shall I put them.
4134 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
4141 * Remove the lock to the list of currently held locks - this gets
4142 * called on mutex_unlock()/spin_unlock*() (or on a failed
4143 * mutex_lock_interruptible()).
4145 * @nested is an hysterical artifact, needs a tree wide cleanup.
4148 __lock_release(struct lockdep_map *lock, unsigned long ip)
4150 struct task_struct *curr = current;
4151 unsigned int depth, merged = 1;
4152 struct held_lock *hlock;
4155 if (unlikely(!debug_locks))
4158 depth = curr->lockdep_depth;
4160 * So we're all set to release this lock.. wait what lock? We don't
4161 * own any locks, you've been drinking again?
4163 if (DEBUG_LOCKS_WARN_ON(depth <= 0)) {
4164 print_unlock_imbalance_bug(curr, lock, ip);
4169 * Check whether the lock exists in the current stack
4172 hlock = find_held_lock(curr, lock, depth, &i);
4174 print_unlock_imbalance_bug(curr, lock, ip);
4178 if (hlock->instance == lock)
4179 lock_release_holdtime(hlock);
4181 WARN(hlock->pin_count, "releasing a pinned lock\n");
4183 if (hlock->references) {
4184 hlock->references--;
4185 if (hlock->references) {
4187 * We had, and after removing one, still have
4188 * references, the current lock stack is still
4189 * valid. We're done!
4196 * We have the right lock to unlock, 'hlock' points to it.
4197 * Now we remove it from the stack, and add back the other
4198 * entries (if any), recalculating the hash along the way:
4201 curr->lockdep_depth = i;
4202 curr->curr_chain_key = hlock->prev_chain_key;
4205 * The most likely case is when the unlock is on the innermost
4206 * lock. In this case, we are done!
4211 if (reacquire_held_locks(curr, depth, i + 1, &merged))
4215 * We had N bottles of beer on the wall, we drank one, but now
4216 * there's not N-1 bottles of beer left on the wall...
4217 * Pouring two of the bottles together is acceptable.
4219 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
4222 * Since reacquire_held_locks() would have called check_chain_key()
4223 * indirectly via __lock_acquire(), we don't need to do it again
4229 static nokprobe_inline
4230 int __lock_is_held(const struct lockdep_map *lock, int read)
4232 struct task_struct *curr = current;
4235 for (i = 0; i < curr->lockdep_depth; i++) {
4236 struct held_lock *hlock = curr->held_locks + i;
4238 if (match_held_lock(hlock, lock)) {
4239 if (read == -1 || hlock->read == read)
4249 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
4251 struct pin_cookie cookie = NIL_COOKIE;
4252 struct task_struct *curr = current;
4255 if (unlikely(!debug_locks))
4258 for (i = 0; i < curr->lockdep_depth; i++) {
4259 struct held_lock *hlock = curr->held_locks + i;
4261 if (match_held_lock(hlock, lock)) {
4263 * Grab 16bits of randomness; this is sufficient to not
4264 * be guessable and still allows some pin nesting in
4265 * our u32 pin_count.
4267 cookie.val = 1 + (prandom_u32() >> 16);
4268 hlock->pin_count += cookie.val;
4273 WARN(1, "pinning an unheld lock\n");
4277 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4279 struct task_struct *curr = current;
4282 if (unlikely(!debug_locks))
4285 for (i = 0; i < curr->lockdep_depth; i++) {
4286 struct held_lock *hlock = curr->held_locks + i;
4288 if (match_held_lock(hlock, lock)) {
4289 hlock->pin_count += cookie.val;
4294 WARN(1, "pinning an unheld lock\n");
4297 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4299 struct task_struct *curr = current;
4302 if (unlikely(!debug_locks))
4305 for (i = 0; i < curr->lockdep_depth; i++) {
4306 struct held_lock *hlock = curr->held_locks + i;
4308 if (match_held_lock(hlock, lock)) {
4309 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
4312 hlock->pin_count -= cookie.val;
4314 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
4315 hlock->pin_count = 0;
4321 WARN(1, "unpinning an unheld lock\n");
4325 * Check whether we follow the irq-flags state precisely:
4327 static void check_flags(unsigned long flags)
4329 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP) && \
4330 defined(CONFIG_TRACE_IRQFLAGS)
4334 if (irqs_disabled_flags(flags)) {
4335 if (DEBUG_LOCKS_WARN_ON(current->hardirqs_enabled)) {
4336 printk("possible reason: unannotated irqs-off.\n");
4339 if (DEBUG_LOCKS_WARN_ON(!current->hardirqs_enabled)) {
4340 printk("possible reason: unannotated irqs-on.\n");
4345 * We dont accurately track softirq state in e.g.
4346 * hardirq contexts (such as on 4KSTACKS), so only
4347 * check if not in hardirq contexts:
4349 if (!hardirq_count()) {
4350 if (softirq_count()) {
4351 /* like the above, but with softirqs */
4352 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
4354 /* lick the above, does it taste good? */
4355 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
4360 print_irqtrace_events(current);
4364 void lock_set_class(struct lockdep_map *lock, const char *name,
4365 struct lock_class_key *key, unsigned int subclass,
4368 unsigned long flags;
4370 if (unlikely(current->lockdep_recursion))
4373 raw_local_irq_save(flags);
4374 current->lockdep_recursion = 1;
4376 if (__lock_set_class(lock, name, key, subclass, ip))
4377 check_chain_key(current);
4378 current->lockdep_recursion = 0;
4379 raw_local_irq_restore(flags);
4381 EXPORT_SYMBOL_GPL(lock_set_class);
4383 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
4385 unsigned long flags;
4387 if (unlikely(current->lockdep_recursion))
4390 raw_local_irq_save(flags);
4391 current->lockdep_recursion = 1;
4393 if (__lock_downgrade(lock, ip))
4394 check_chain_key(current);
4395 current->lockdep_recursion = 0;
4396 raw_local_irq_restore(flags);
4398 EXPORT_SYMBOL_GPL(lock_downgrade);
4401 * We are not always called with irqs disabled - do that here,
4402 * and also avoid lockdep recursion:
4404 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
4405 int trylock, int read, int check,
4406 struct lockdep_map *nest_lock, unsigned long ip)
4408 unsigned long flags;
4410 if (unlikely(current->lockdep_recursion))
4413 raw_local_irq_save(flags);
4416 current->lockdep_recursion = 1;
4417 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
4418 __lock_acquire(lock, subclass, trylock, read, check,
4419 irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
4420 current->lockdep_recursion = 0;
4421 raw_local_irq_restore(flags);
4423 EXPORT_SYMBOL_GPL(lock_acquire);
4425 void lock_release(struct lockdep_map *lock, int nested,
4428 unsigned long flags;
4430 if (unlikely(current->lockdep_recursion))
4433 raw_local_irq_save(flags);
4435 current->lockdep_recursion = 1;
4436 trace_lock_release(lock, ip);
4437 if (__lock_release(lock, ip))
4438 check_chain_key(current);
4439 current->lockdep_recursion = 0;
4440 raw_local_irq_restore(flags);
4442 EXPORT_SYMBOL_GPL(lock_release);
4444 int lock_is_held_type(const struct lockdep_map *lock, int read)
4446 unsigned long flags;
4449 if (unlikely(current->lockdep_recursion))
4450 return 1; /* avoid false negative lockdep_assert_held() */
4452 raw_local_irq_save(flags);
4455 current->lockdep_recursion = 1;
4456 ret = __lock_is_held(lock, read);
4457 current->lockdep_recursion = 0;
4458 raw_local_irq_restore(flags);
4462 EXPORT_SYMBOL_GPL(lock_is_held_type);
4463 NOKPROBE_SYMBOL(lock_is_held_type);
4465 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
4467 struct pin_cookie cookie = NIL_COOKIE;
4468 unsigned long flags;
4470 if (unlikely(current->lockdep_recursion))
4473 raw_local_irq_save(flags);
4476 current->lockdep_recursion = 1;
4477 cookie = __lock_pin_lock(lock);
4478 current->lockdep_recursion = 0;
4479 raw_local_irq_restore(flags);
4483 EXPORT_SYMBOL_GPL(lock_pin_lock);
4485 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4487 unsigned long flags;
4489 if (unlikely(current->lockdep_recursion))
4492 raw_local_irq_save(flags);
4495 current->lockdep_recursion = 1;
4496 __lock_repin_lock(lock, cookie);
4497 current->lockdep_recursion = 0;
4498 raw_local_irq_restore(flags);
4500 EXPORT_SYMBOL_GPL(lock_repin_lock);
4502 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
4504 unsigned long flags;
4506 if (unlikely(current->lockdep_recursion))
4509 raw_local_irq_save(flags);
4512 current->lockdep_recursion = 1;
4513 __lock_unpin_lock(lock, cookie);
4514 current->lockdep_recursion = 0;
4515 raw_local_irq_restore(flags);
4517 EXPORT_SYMBOL_GPL(lock_unpin_lock);
4519 #ifdef CONFIG_LOCK_STAT
4520 static void print_lock_contention_bug(struct task_struct *curr,
4521 struct lockdep_map *lock,
4524 if (!debug_locks_off())
4526 if (debug_locks_silent)
4530 pr_warn("=================================\n");
4531 pr_warn("WARNING: bad contention detected!\n");
4532 print_kernel_ident();
4533 pr_warn("---------------------------------\n");
4534 pr_warn("%s/%d is trying to contend lock (",
4535 curr->comm, task_pid_nr(curr));
4536 print_lockdep_cache(lock);
4539 pr_warn("but there are no locks held!\n");
4540 pr_warn("\nother info that might help us debug this:\n");
4541 lockdep_print_held_locks(curr);
4543 pr_warn("\nstack backtrace:\n");
4548 __lock_contended(struct lockdep_map *lock, unsigned long ip)
4550 struct task_struct *curr = current;
4551 struct held_lock *hlock;
4552 struct lock_class_stats *stats;
4554 int i, contention_point, contending_point;
4556 depth = curr->lockdep_depth;
4558 * Whee, we contended on this lock, except it seems we're not
4559 * actually trying to acquire anything much at all..
4561 if (DEBUG_LOCKS_WARN_ON(!depth))
4564 hlock = find_held_lock(curr, lock, depth, &i);
4566 print_lock_contention_bug(curr, lock, ip);
4570 if (hlock->instance != lock)
4573 hlock->waittime_stamp = lockstat_clock();
4575 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
4576 contending_point = lock_point(hlock_class(hlock)->contending_point,
4579 stats = get_lock_stats(hlock_class(hlock));
4580 if (contention_point < LOCKSTAT_POINTS)
4581 stats->contention_point[contention_point]++;
4582 if (contending_point < LOCKSTAT_POINTS)
4583 stats->contending_point[contending_point]++;
4584 if (lock->cpu != smp_processor_id())
4585 stats->bounces[bounce_contended + !!hlock->read]++;
4589 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
4591 struct task_struct *curr = current;
4592 struct held_lock *hlock;
4593 struct lock_class_stats *stats;
4595 u64 now, waittime = 0;
4598 depth = curr->lockdep_depth;
4600 * Yay, we acquired ownership of this lock we didn't try to
4601 * acquire, how the heck did that happen?
4603 if (DEBUG_LOCKS_WARN_ON(!depth))
4606 hlock = find_held_lock(curr, lock, depth, &i);
4608 print_lock_contention_bug(curr, lock, _RET_IP_);
4612 if (hlock->instance != lock)
4615 cpu = smp_processor_id();
4616 if (hlock->waittime_stamp) {
4617 now = lockstat_clock();
4618 waittime = now - hlock->waittime_stamp;
4619 hlock->holdtime_stamp = now;
4622 trace_lock_acquired(lock, ip);
4624 stats = get_lock_stats(hlock_class(hlock));
4627 lock_time_inc(&stats->read_waittime, waittime);
4629 lock_time_inc(&stats->write_waittime, waittime);
4631 if (lock->cpu != cpu)
4632 stats->bounces[bounce_acquired + !!hlock->read]++;
4638 void lock_contended(struct lockdep_map *lock, unsigned long ip)
4640 unsigned long flags;
4642 if (unlikely(!lock_stat || !debug_locks))
4645 if (unlikely(current->lockdep_recursion))
4648 raw_local_irq_save(flags);
4650 current->lockdep_recursion = 1;
4651 trace_lock_contended(lock, ip);
4652 __lock_contended(lock, ip);
4653 current->lockdep_recursion = 0;
4654 raw_local_irq_restore(flags);
4656 EXPORT_SYMBOL_GPL(lock_contended);
4658 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
4660 unsigned long flags;
4662 if (unlikely(!lock_stat || !debug_locks))
4665 if (unlikely(current->lockdep_recursion))
4668 raw_local_irq_save(flags);
4670 current->lockdep_recursion = 1;
4671 __lock_acquired(lock, ip);
4672 current->lockdep_recursion = 0;
4673 raw_local_irq_restore(flags);
4675 EXPORT_SYMBOL_GPL(lock_acquired);
4679 * Used by the testsuite, sanitize the validator state
4680 * after a simulated failure:
4683 void lockdep_reset(void)
4685 unsigned long flags;
4688 raw_local_irq_save(flags);
4689 lockdep_init_task(current);
4690 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
4691 nr_hardirq_chains = 0;
4692 nr_softirq_chains = 0;
4693 nr_process_chains = 0;
4695 for (i = 0; i < CHAINHASH_SIZE; i++)
4696 INIT_HLIST_HEAD(chainhash_table + i);
4697 raw_local_irq_restore(flags);
4700 /* Remove a class from a lock chain. Must be called with the graph lock held. */
4701 static void remove_class_from_lock_chain(struct pending_free *pf,
4702 struct lock_chain *chain,
4703 struct lock_class *class)
4705 #ifdef CONFIG_PROVE_LOCKING
4706 struct lock_chain *new_chain;
4710 for (i = chain->base; i < chain->base + chain->depth; i++) {
4711 if (chain_hlocks[i] != class - lock_classes)
4713 /* The code below leaks one chain_hlock[] entry. */
4714 if (--chain->depth > 0) {
4715 memmove(&chain_hlocks[i], &chain_hlocks[i + 1],
4716 (chain->base + chain->depth - i) *
4717 sizeof(chain_hlocks[0]));
4720 * Each lock class occurs at most once in a lock chain so once
4721 * we found a match we can break out of this loop.
4725 /* Since the chain has not been modified, return. */
4729 chain_key = INITIAL_CHAIN_KEY;
4730 for (i = chain->base; i < chain->base + chain->depth; i++)
4731 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
4732 if (chain->depth && chain->chain_key == chain_key)
4734 /* Overwrite the chain key for concurrent RCU readers. */
4735 WRITE_ONCE(chain->chain_key, chain_key);
4737 * Note: calling hlist_del_rcu() from inside a
4738 * hlist_for_each_entry_rcu() loop is safe.
4740 hlist_del_rcu(&chain->entry);
4741 __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
4742 if (chain->depth == 0)
4745 * If the modified lock chain matches an existing lock chain, drop
4746 * the modified lock chain.
4748 if (lookup_chain_cache(chain_key))
4750 new_chain = alloc_lock_chain();
4751 if (WARN_ON_ONCE(!new_chain)) {
4755 *new_chain = *chain;
4756 hlist_add_head_rcu(&new_chain->entry, chainhashentry(chain_key));
4760 /* Must be called with the graph lock held. */
4761 static void remove_class_from_lock_chains(struct pending_free *pf,
4762 struct lock_class *class)
4764 struct lock_chain *chain;
4765 struct hlist_head *head;
4768 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
4769 head = chainhash_table + i;
4770 hlist_for_each_entry_rcu(chain, head, entry) {
4771 remove_class_from_lock_chain(pf, chain, class);
4777 * Remove all references to a lock class. The caller must hold the graph lock.
4779 static void zap_class(struct pending_free *pf, struct lock_class *class)
4781 struct lock_list *entry;
4784 WARN_ON_ONCE(!class->key);
4787 * Remove all dependencies this lock is
4790 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
4791 entry = list_entries + i;
4792 if (entry->class != class && entry->links_to != class)
4794 __clear_bit(i, list_entries_in_use);
4796 list_del_rcu(&entry->entry);
4798 if (list_empty(&class->locks_after) &&
4799 list_empty(&class->locks_before)) {
4800 list_move_tail(&class->lock_entry, &pf->zapped);
4801 hlist_del_rcu(&class->hash_entry);
4802 WRITE_ONCE(class->key, NULL);
4803 WRITE_ONCE(class->name, NULL);
4805 __clear_bit(class - lock_classes, lock_classes_in_use);
4807 WARN_ONCE(true, "%s() failed for class %s\n", __func__,
4811 remove_class_from_lock_chains(pf, class);
4814 static void reinit_class(struct lock_class *class)
4816 void *const p = class;
4817 const unsigned int offset = offsetof(struct lock_class, key);
4819 WARN_ON_ONCE(!class->lock_entry.next);
4820 WARN_ON_ONCE(!list_empty(&class->locks_after));
4821 WARN_ON_ONCE(!list_empty(&class->locks_before));
4822 memset(p + offset, 0, sizeof(*class) - offset);
4823 WARN_ON_ONCE(!class->lock_entry.next);
4824 WARN_ON_ONCE(!list_empty(&class->locks_after));
4825 WARN_ON_ONCE(!list_empty(&class->locks_before));
4828 static inline int within(const void *addr, void *start, unsigned long size)
4830 return addr >= start && addr < start + size;
4833 static bool inside_selftest(void)
4835 return current == lockdep_selftest_task_struct;
4838 /* The caller must hold the graph lock. */
4839 static struct pending_free *get_pending_free(void)
4841 return delayed_free.pf + delayed_free.index;
4844 static void free_zapped_rcu(struct rcu_head *cb);
4847 * Schedule an RCU callback if no RCU callback is pending. Must be called with
4848 * the graph lock held.
4850 static void call_rcu_zapped(struct pending_free *pf)
4852 WARN_ON_ONCE(inside_selftest());
4854 if (list_empty(&pf->zapped))
4857 if (delayed_free.scheduled)
4860 delayed_free.scheduled = true;
4862 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
4863 delayed_free.index ^= 1;
4865 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
4868 /* The caller must hold the graph lock. May be called from RCU context. */
4869 static void __free_zapped_classes(struct pending_free *pf)
4871 struct lock_class *class;
4873 check_data_structures();
4875 list_for_each_entry(class, &pf->zapped, lock_entry)
4876 reinit_class(class);
4878 list_splice_init(&pf->zapped, &free_lock_classes);
4880 #ifdef CONFIG_PROVE_LOCKING
4881 bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
4882 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
4883 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
4887 static void free_zapped_rcu(struct rcu_head *ch)
4889 struct pending_free *pf;
4890 unsigned long flags;
4892 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
4895 raw_local_irq_save(flags);
4896 arch_spin_lock(&lockdep_lock);
4897 current->lockdep_recursion = 1;
4900 pf = delayed_free.pf + (delayed_free.index ^ 1);
4901 __free_zapped_classes(pf);
4902 delayed_free.scheduled = false;
4905 * If there's anything on the open list, close and start a new callback.
4907 call_rcu_zapped(delayed_free.pf + delayed_free.index);
4909 current->lockdep_recursion = 0;
4910 arch_spin_unlock(&lockdep_lock);
4911 raw_local_irq_restore(flags);
4915 * Remove all lock classes from the class hash table and from the
4916 * all_lock_classes list whose key or name is in the address range [start,
4917 * start + size). Move these lock classes to the zapped_classes list. Must
4918 * be called with the graph lock held.
4920 static void __lockdep_free_key_range(struct pending_free *pf, void *start,
4923 struct lock_class *class;
4924 struct hlist_head *head;
4927 /* Unhash all classes that were created by a module. */
4928 for (i = 0; i < CLASSHASH_SIZE; i++) {
4929 head = classhash_table + i;
4930 hlist_for_each_entry_rcu(class, head, hash_entry) {
4931 if (!within(class->key, start, size) &&
4932 !within(class->name, start, size))
4934 zap_class(pf, class);
4940 * Used in module.c to remove lock classes from memory that is going to be
4941 * freed; and possibly re-used by other modules.
4943 * We will have had one synchronize_rcu() before getting here, so we're
4944 * guaranteed nobody will look up these exact classes -- they're properly dead
4945 * but still allocated.
4947 static void lockdep_free_key_range_reg(void *start, unsigned long size)
4949 struct pending_free *pf;
4950 unsigned long flags;
4952 init_data_structures_once();
4954 raw_local_irq_save(flags);
4955 arch_spin_lock(&lockdep_lock);
4956 current->lockdep_recursion = 1;
4957 pf = get_pending_free();
4958 __lockdep_free_key_range(pf, start, size);
4959 call_rcu_zapped(pf);
4960 current->lockdep_recursion = 0;
4961 arch_spin_unlock(&lockdep_lock);
4962 raw_local_irq_restore(flags);
4965 * Wait for any possible iterators from look_up_lock_class() to pass
4966 * before continuing to free the memory they refer to.
4972 * Free all lockdep keys in the range [start, start+size). Does not sleep.
4973 * Ignores debug_locks. Must only be used by the lockdep selftests.
4975 static void lockdep_free_key_range_imm(void *start, unsigned long size)
4977 struct pending_free *pf = delayed_free.pf;
4978 unsigned long flags;
4980 init_data_structures_once();
4982 raw_local_irq_save(flags);
4983 arch_spin_lock(&lockdep_lock);
4984 __lockdep_free_key_range(pf, start, size);
4985 __free_zapped_classes(pf);
4986 arch_spin_unlock(&lockdep_lock);
4987 raw_local_irq_restore(flags);
4990 void lockdep_free_key_range(void *start, unsigned long size)
4992 init_data_structures_once();
4994 if (inside_selftest())
4995 lockdep_free_key_range_imm(start, size);
4997 lockdep_free_key_range_reg(start, size);
5001 * Check whether any element of the @lock->class_cache[] array refers to a
5002 * registered lock class. The caller must hold either the graph lock or the
5005 static bool lock_class_cache_is_registered(struct lockdep_map *lock)
5007 struct lock_class *class;
5008 struct hlist_head *head;
5011 for (i = 0; i < CLASSHASH_SIZE; i++) {
5012 head = classhash_table + i;
5013 hlist_for_each_entry_rcu(class, head, hash_entry) {
5014 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
5015 if (lock->class_cache[j] == class)
5022 /* The caller must hold the graph lock. Does not sleep. */
5023 static void __lockdep_reset_lock(struct pending_free *pf,
5024 struct lockdep_map *lock)
5026 struct lock_class *class;
5030 * Remove all classes this lock might have:
5032 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
5034 * If the class exists we look it up and zap it:
5036 class = look_up_lock_class(lock, j);
5038 zap_class(pf, class);
5041 * Debug check: in the end all mapped classes should
5044 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
5049 * Remove all information lockdep has about a lock if debug_locks == 1. Free
5050 * released data structures from RCU context.
5052 static void lockdep_reset_lock_reg(struct lockdep_map *lock)
5054 struct pending_free *pf;
5055 unsigned long flags;
5058 raw_local_irq_save(flags);
5059 locked = graph_lock();
5063 pf = get_pending_free();
5064 __lockdep_reset_lock(pf, lock);
5065 call_rcu_zapped(pf);
5069 raw_local_irq_restore(flags);
5073 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
5074 * lockdep selftests.
5076 static void lockdep_reset_lock_imm(struct lockdep_map *lock)
5078 struct pending_free *pf = delayed_free.pf;
5079 unsigned long flags;
5081 raw_local_irq_save(flags);
5082 arch_spin_lock(&lockdep_lock);
5083 __lockdep_reset_lock(pf, lock);
5084 __free_zapped_classes(pf);
5085 arch_spin_unlock(&lockdep_lock);
5086 raw_local_irq_restore(flags);
5089 void lockdep_reset_lock(struct lockdep_map *lock)
5091 init_data_structures_once();
5093 if (inside_selftest())
5094 lockdep_reset_lock_imm(lock);
5096 lockdep_reset_lock_reg(lock);
5099 /* Unregister a dynamically allocated key. */
5100 void lockdep_unregister_key(struct lock_class_key *key)
5102 struct hlist_head *hash_head = keyhashentry(key);
5103 struct lock_class_key *k;
5104 struct pending_free *pf;
5105 unsigned long flags;
5110 if (WARN_ON_ONCE(static_obj(key)))
5113 raw_local_irq_save(flags);
5117 pf = get_pending_free();
5118 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
5120 hlist_del_rcu(&k->hash_entry);
5125 WARN_ON_ONCE(!found);
5126 __lockdep_free_key_range(pf, key, 1);
5127 call_rcu_zapped(pf);
5130 raw_local_irq_restore(flags);
5132 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
5135 EXPORT_SYMBOL_GPL(lockdep_unregister_key);
5137 void __init lockdep_init(void)
5139 printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
5141 printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
5142 printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
5143 printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
5144 printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
5145 printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
5146 printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
5147 printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
5149 printk(" memory used by lock dependency info: %zu kB\n",
5150 (sizeof(lock_classes) +
5151 sizeof(lock_classes_in_use) +
5152 sizeof(classhash_table) +
5153 sizeof(list_entries) +
5154 sizeof(list_entries_in_use) +
5155 sizeof(chainhash_table) +
5156 sizeof(delayed_free)
5157 #ifdef CONFIG_PROVE_LOCKING
5159 + sizeof(lock_chains)
5160 + sizeof(lock_chains_in_use)
5161 + sizeof(chain_hlocks)
5166 printk(" per task-struct memory footprint: %zu bytes\n",
5167 sizeof(((struct task_struct *)NULL)->held_locks));
5171 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
5172 const void *mem_to, struct held_lock *hlock)
5174 if (!debug_locks_off())
5176 if (debug_locks_silent)
5180 pr_warn("=========================\n");
5181 pr_warn("WARNING: held lock freed!\n");
5182 print_kernel_ident();
5183 pr_warn("-------------------------\n");
5184 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
5185 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
5187 lockdep_print_held_locks(curr);
5189 pr_warn("\nstack backtrace:\n");
5193 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
5194 const void* lock_from, unsigned long lock_len)
5196 return lock_from + lock_len <= mem_from ||
5197 mem_from + mem_len <= lock_from;
5201 * Called when kernel memory is freed (or unmapped), or if a lock
5202 * is destroyed or reinitialized - this code checks whether there is
5203 * any held lock in the memory range of <from> to <to>:
5205 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
5207 struct task_struct *curr = current;
5208 struct held_lock *hlock;
5209 unsigned long flags;
5212 if (unlikely(!debug_locks))
5215 raw_local_irq_save(flags);
5216 for (i = 0; i < curr->lockdep_depth; i++) {
5217 hlock = curr->held_locks + i;
5219 if (not_in_range(mem_from, mem_len, hlock->instance,
5220 sizeof(*hlock->instance)))
5223 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
5226 raw_local_irq_restore(flags);
5228 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
5230 static void print_held_locks_bug(void)
5232 if (!debug_locks_off())
5234 if (debug_locks_silent)
5238 pr_warn("====================================\n");
5239 pr_warn("WARNING: %s/%d still has locks held!\n",
5240 current->comm, task_pid_nr(current));
5241 print_kernel_ident();
5242 pr_warn("------------------------------------\n");
5243 lockdep_print_held_locks(current);
5244 pr_warn("\nstack backtrace:\n");
5248 void debug_check_no_locks_held(void)
5250 if (unlikely(current->lockdep_depth > 0))
5251 print_held_locks_bug();
5253 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
5256 void debug_show_all_locks(void)
5258 struct task_struct *g, *p;
5260 if (unlikely(!debug_locks)) {
5261 pr_warn("INFO: lockdep is turned off.\n");
5264 pr_warn("\nShowing all locks held in the system:\n");
5267 for_each_process_thread(g, p) {
5268 if (!p->lockdep_depth)
5270 lockdep_print_held_locks(p);
5271 touch_nmi_watchdog();
5272 touch_all_softlockup_watchdogs();
5277 pr_warn("=============================================\n\n");
5279 EXPORT_SYMBOL_GPL(debug_show_all_locks);
5283 * Careful: only use this function if you are sure that
5284 * the task cannot run in parallel!
5286 void debug_show_held_locks(struct task_struct *task)
5288 if (unlikely(!debug_locks)) {
5289 printk("INFO: lockdep is turned off.\n");
5292 lockdep_print_held_locks(task);
5294 EXPORT_SYMBOL_GPL(debug_show_held_locks);
5296 asmlinkage __visible void lockdep_sys_exit(void)
5298 struct task_struct *curr = current;
5300 if (unlikely(curr->lockdep_depth)) {
5301 if (!debug_locks_off())
5304 pr_warn("================================================\n");
5305 pr_warn("WARNING: lock held when returning to user space!\n");
5306 print_kernel_ident();
5307 pr_warn("------------------------------------------------\n");
5308 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
5309 curr->comm, curr->pid);
5310 lockdep_print_held_locks(curr);
5314 * The lock history for each syscall should be independent. So wipe the
5315 * slate clean on return to userspace.
5317 lockdep_invariant_state(false);
5320 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
5322 struct task_struct *curr = current;
5324 /* Note: the following can be executed concurrently, so be careful. */
5326 pr_warn("=============================\n");
5327 pr_warn("WARNING: suspicious RCU usage\n");
5328 print_kernel_ident();
5329 pr_warn("-----------------------------\n");
5330 pr_warn("%s:%d %s!\n", file, line, s);
5331 pr_warn("\nother info that might help us debug this:\n\n");
5332 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
5333 !rcu_lockdep_current_cpu_online()
5334 ? "RCU used illegally from offline CPU!\n"
5335 : !rcu_is_watching()
5336 ? "RCU used illegally from idle CPU!\n"
5338 rcu_scheduler_active, debug_locks);
5341 * If a CPU is in the RCU-free window in idle (ie: in the section
5342 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
5343 * considers that CPU to be in an "extended quiescent state",
5344 * which means that RCU will be completely ignoring that CPU.
5345 * Therefore, rcu_read_lock() and friends have absolutely no
5346 * effect on a CPU running in that state. In other words, even if
5347 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
5348 * delete data structures out from under it. RCU really has no
5349 * choice here: we need to keep an RCU-free window in idle where
5350 * the CPU may possibly enter into low power mode. This way we can
5351 * notice an extended quiescent state to other CPUs that started a grace
5352 * period. Otherwise we would delay any grace period as long as we run
5355 * So complain bitterly if someone does call rcu_read_lock(),
5356 * rcu_read_lock_bh() and so on from extended quiescent states.
5358 if (!rcu_is_watching())
5359 pr_warn("RCU used illegally from extended quiescent state!\n");
5361 lockdep_print_held_locks(curr);
5362 pr_warn("\nstack backtrace:\n");
5365 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);