Merge tag 'block-5.11-2021-01-10' of git://git.kernel.dk/linux-block
[linux/fpc-iii.git] / kernel / locking / lockdep.c
blobc1418b47f625a25fc32d8b18852057dc48b6cc93
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * kernel/lockdep.c
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);
68 #else
69 #define prove_locking 0
70 #endif
72 #ifdef CONFIG_LOCK_STAT
73 int lock_stat = 1;
74 module_param(lock_stat, int, 0644);
75 #else
76 #define lock_stat 0
77 #endif
79 DEFINE_PER_CPU(unsigned int, lockdep_recursion);
80 EXPORT_PER_CPU_SYMBOL_GPL(lockdep_recursion);
82 static inline bool lockdep_enabled(void)
84 if (!debug_locks)
85 return false;
87 if (this_cpu_read(lockdep_recursion))
88 return false;
90 if (current->lockdep_recursion)
91 return false;
93 return true;
97 * lockdep_lock: protects the lockdep graph, the hashes and the
98 * class/list/hash allocators.
100 * This is one of the rare exceptions where it's justified
101 * to use a raw spinlock - we really dont want the spinlock
102 * code to recurse back into the lockdep code...
104 static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
105 static struct task_struct *__owner;
107 static inline void lockdep_lock(void)
109 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
111 __this_cpu_inc(lockdep_recursion);
112 arch_spin_lock(&__lock);
113 __owner = current;
116 static inline void lockdep_unlock(void)
118 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
120 if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current))
121 return;
123 __owner = NULL;
124 arch_spin_unlock(&__lock);
125 __this_cpu_dec(lockdep_recursion);
128 static inline bool lockdep_assert_locked(void)
130 return DEBUG_LOCKS_WARN_ON(__owner != current);
133 static struct task_struct *lockdep_selftest_task_struct;
136 static int graph_lock(void)
138 lockdep_lock();
140 * Make sure that if another CPU detected a bug while
141 * walking the graph we dont change it (while the other
142 * CPU is busy printing out stuff with the graph lock
143 * dropped already)
145 if (!debug_locks) {
146 lockdep_unlock();
147 return 0;
149 return 1;
152 static inline void graph_unlock(void)
154 lockdep_unlock();
158 * Turn lock debugging off and return with 0 if it was off already,
159 * and also release the graph lock:
161 static inline int debug_locks_off_graph_unlock(void)
163 int ret = debug_locks_off();
165 lockdep_unlock();
167 return ret;
170 unsigned long nr_list_entries;
171 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
172 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
175 * All data structures here are protected by the global debug_lock.
177 * nr_lock_classes is the number of elements of lock_classes[] that is
178 * in use.
180 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
181 #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
182 static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
183 unsigned long nr_lock_classes;
184 unsigned long nr_zapped_classes;
185 #ifndef CONFIG_DEBUG_LOCKDEP
186 static
187 #endif
188 struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
189 static DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
191 static inline struct lock_class *hlock_class(struct held_lock *hlock)
193 unsigned int class_idx = hlock->class_idx;
195 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
196 barrier();
198 if (!test_bit(class_idx, lock_classes_in_use)) {
200 * Someone passed in garbage, we give up.
202 DEBUG_LOCKS_WARN_ON(1);
203 return NULL;
207 * At this point, if the passed hlock->class_idx is still garbage,
208 * we just have to live with it
210 return lock_classes + class_idx;
213 #ifdef CONFIG_LOCK_STAT
214 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
216 static inline u64 lockstat_clock(void)
218 return local_clock();
221 static int lock_point(unsigned long points[], unsigned long ip)
223 int i;
225 for (i = 0; i < LOCKSTAT_POINTS; i++) {
226 if (points[i] == 0) {
227 points[i] = ip;
228 break;
230 if (points[i] == ip)
231 break;
234 return i;
237 static void lock_time_inc(struct lock_time *lt, u64 time)
239 if (time > lt->max)
240 lt->max = time;
242 if (time < lt->min || !lt->nr)
243 lt->min = time;
245 lt->total += time;
246 lt->nr++;
249 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
251 if (!src->nr)
252 return;
254 if (src->max > dst->max)
255 dst->max = src->max;
257 if (src->min < dst->min || !dst->nr)
258 dst->min = src->min;
260 dst->total += src->total;
261 dst->nr += src->nr;
264 struct lock_class_stats lock_stats(struct lock_class *class)
266 struct lock_class_stats stats;
267 int cpu, i;
269 memset(&stats, 0, sizeof(struct lock_class_stats));
270 for_each_possible_cpu(cpu) {
271 struct lock_class_stats *pcs =
272 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
274 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
275 stats.contention_point[i] += pcs->contention_point[i];
277 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
278 stats.contending_point[i] += pcs->contending_point[i];
280 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
281 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
283 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
284 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
286 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
287 stats.bounces[i] += pcs->bounces[i];
290 return stats;
293 void clear_lock_stats(struct lock_class *class)
295 int cpu;
297 for_each_possible_cpu(cpu) {
298 struct lock_class_stats *cpu_stats =
299 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
301 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
303 memset(class->contention_point, 0, sizeof(class->contention_point));
304 memset(class->contending_point, 0, sizeof(class->contending_point));
307 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
309 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
312 static void lock_release_holdtime(struct held_lock *hlock)
314 struct lock_class_stats *stats;
315 u64 holdtime;
317 if (!lock_stat)
318 return;
320 holdtime = lockstat_clock() - hlock->holdtime_stamp;
322 stats = get_lock_stats(hlock_class(hlock));
323 if (hlock->read)
324 lock_time_inc(&stats->read_holdtime, holdtime);
325 else
326 lock_time_inc(&stats->write_holdtime, holdtime);
328 #else
329 static inline void lock_release_holdtime(struct held_lock *hlock)
332 #endif
335 * We keep a global list of all lock classes. The list is only accessed with
336 * the lockdep spinlock lock held. free_lock_classes is a list with free
337 * elements. These elements are linked together by the lock_entry member in
338 * struct lock_class.
340 LIST_HEAD(all_lock_classes);
341 static LIST_HEAD(free_lock_classes);
344 * struct pending_free - information about data structures about to be freed
345 * @zapped: Head of a list with struct lock_class elements.
346 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
347 * are about to be freed.
349 struct pending_free {
350 struct list_head zapped;
351 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
355 * struct delayed_free - data structures used for delayed freeing
357 * A data structure for delayed freeing of data structures that may be
358 * accessed by RCU readers at the time these were freed.
360 * @rcu_head: Used to schedule an RCU callback for freeing data structures.
361 * @index: Index of @pf to which freed data structures are added.
362 * @scheduled: Whether or not an RCU callback has been scheduled.
363 * @pf: Array with information about data structures about to be freed.
365 static struct delayed_free {
366 struct rcu_head rcu_head;
367 int index;
368 int scheduled;
369 struct pending_free pf[2];
370 } delayed_free;
373 * The lockdep classes are in a hash-table as well, for fast lookup:
375 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
376 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
377 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
378 #define classhashentry(key) (classhash_table + __classhashfn((key)))
380 static struct hlist_head classhash_table[CLASSHASH_SIZE];
383 * We put the lock dependency chains into a hash-table as well, to cache
384 * their existence:
386 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
387 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
388 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
389 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
391 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
394 * the id of held_lock
396 static inline u16 hlock_id(struct held_lock *hlock)
398 BUILD_BUG_ON(MAX_LOCKDEP_KEYS_BITS + 2 > 16);
400 return (hlock->class_idx | (hlock->read << MAX_LOCKDEP_KEYS_BITS));
403 static inline unsigned int chain_hlock_class_idx(u16 hlock_id)
405 return hlock_id & (MAX_LOCKDEP_KEYS - 1);
409 * The hash key of the lock dependency chains is a hash itself too:
410 * it's a hash of all locks taken up to that lock, including that lock.
411 * It's a 64-bit hash, because it's important for the keys to be
412 * unique.
414 static inline u64 iterate_chain_key(u64 key, u32 idx)
416 u32 k0 = key, k1 = key >> 32;
418 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
420 return k0 | (u64)k1 << 32;
423 void lockdep_init_task(struct task_struct *task)
425 task->lockdep_depth = 0; /* no locks held yet */
426 task->curr_chain_key = INITIAL_CHAIN_KEY;
427 task->lockdep_recursion = 0;
430 static __always_inline void lockdep_recursion_inc(void)
432 __this_cpu_inc(lockdep_recursion);
435 static __always_inline void lockdep_recursion_finish(void)
437 if (WARN_ON_ONCE(__this_cpu_dec_return(lockdep_recursion)))
438 __this_cpu_write(lockdep_recursion, 0);
441 void lockdep_set_selftest_task(struct task_struct *task)
443 lockdep_selftest_task_struct = task;
447 * Debugging switches:
450 #define VERBOSE 0
451 #define VERY_VERBOSE 0
453 #if VERBOSE
454 # define HARDIRQ_VERBOSE 1
455 # define SOFTIRQ_VERBOSE 1
456 #else
457 # define HARDIRQ_VERBOSE 0
458 # define SOFTIRQ_VERBOSE 0
459 #endif
461 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
463 * Quick filtering for interesting events:
465 static int class_filter(struct lock_class *class)
467 #if 0
468 /* Example */
469 if (class->name_version == 1 &&
470 !strcmp(class->name, "lockname"))
471 return 1;
472 if (class->name_version == 1 &&
473 !strcmp(class->name, "&struct->lockfield"))
474 return 1;
475 #endif
476 /* Filter everything else. 1 would be to allow everything else */
477 return 0;
479 #endif
481 static int verbose(struct lock_class *class)
483 #if VERBOSE
484 return class_filter(class);
485 #endif
486 return 0;
489 static void print_lockdep_off(const char *bug_msg)
491 printk(KERN_DEBUG "%s\n", bug_msg);
492 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
493 #ifdef CONFIG_LOCK_STAT
494 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
495 #endif
498 unsigned long nr_stack_trace_entries;
500 #ifdef CONFIG_PROVE_LOCKING
502 * struct lock_trace - single stack backtrace
503 * @hash_entry: Entry in a stack_trace_hash[] list.
504 * @hash: jhash() of @entries.
505 * @nr_entries: Number of entries in @entries.
506 * @entries: Actual stack backtrace.
508 struct lock_trace {
509 struct hlist_node hash_entry;
510 u32 hash;
511 u32 nr_entries;
512 unsigned long entries[] __aligned(sizeof(unsigned long));
514 #define LOCK_TRACE_SIZE_IN_LONGS \
515 (sizeof(struct lock_trace) / sizeof(unsigned long))
517 * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock.
519 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
520 static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE];
522 static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2)
524 return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries &&
525 memcmp(t1->entries, t2->entries,
526 t1->nr_entries * sizeof(t1->entries[0])) == 0;
529 static struct lock_trace *save_trace(void)
531 struct lock_trace *trace, *t2;
532 struct hlist_head *hash_head;
533 u32 hash;
534 int max_entries;
536 BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE);
537 BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES);
539 trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries);
540 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries -
541 LOCK_TRACE_SIZE_IN_LONGS;
543 if (max_entries <= 0) {
544 if (!debug_locks_off_graph_unlock())
545 return NULL;
547 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
548 dump_stack();
550 return NULL;
552 trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3);
554 hash = jhash(trace->entries, trace->nr_entries *
555 sizeof(trace->entries[0]), 0);
556 trace->hash = hash;
557 hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1));
558 hlist_for_each_entry(t2, hash_head, hash_entry) {
559 if (traces_identical(trace, t2))
560 return t2;
562 nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries;
563 hlist_add_head(&trace->hash_entry, hash_head);
565 return trace;
568 /* Return the number of stack traces in the stack_trace[] array. */
569 u64 lockdep_stack_trace_count(void)
571 struct lock_trace *trace;
572 u64 c = 0;
573 int i;
575 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) {
576 hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) {
577 c++;
581 return c;
584 /* Return the number of stack hash chains that have at least one stack trace. */
585 u64 lockdep_stack_hash_count(void)
587 u64 c = 0;
588 int i;
590 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++)
591 if (!hlist_empty(&stack_trace_hash[i]))
592 c++;
594 return c;
596 #endif
598 unsigned int nr_hardirq_chains;
599 unsigned int nr_softirq_chains;
600 unsigned int nr_process_chains;
601 unsigned int max_lockdep_depth;
603 #ifdef CONFIG_DEBUG_LOCKDEP
605 * Various lockdep statistics:
607 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
608 #endif
610 #ifdef CONFIG_PROVE_LOCKING
612 * Locking printouts:
615 #define __USAGE(__STATE) \
616 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
617 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
618 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
619 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
621 static const char *usage_str[] =
623 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
624 #include "lockdep_states.h"
625 #undef LOCKDEP_STATE
626 [LOCK_USED] = "INITIAL USE",
627 [LOCK_USED_READ] = "INITIAL READ USE",
628 /* abused as string storage for verify_lock_unused() */
629 [LOCK_USAGE_STATES] = "IN-NMI",
631 #endif
633 const char *__get_key_name(const struct lockdep_subclass_key *key, char *str)
635 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
638 static inline unsigned long lock_flag(enum lock_usage_bit bit)
640 return 1UL << bit;
643 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
646 * The usage character defaults to '.' (i.e., irqs disabled and not in
647 * irq context), which is the safest usage category.
649 char c = '.';
652 * The order of the following usage checks matters, which will
653 * result in the outcome character as follows:
655 * - '+': irq is enabled and not in irq context
656 * - '-': in irq context and irq is disabled
657 * - '?': in irq context and irq is enabled
659 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
660 c = '+';
661 if (class->usage_mask & lock_flag(bit))
662 c = '?';
663 } else if (class->usage_mask & lock_flag(bit))
664 c = '-';
666 return c;
669 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
671 int i = 0;
673 #define LOCKDEP_STATE(__STATE) \
674 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
675 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
676 #include "lockdep_states.h"
677 #undef LOCKDEP_STATE
679 usage[i] = '\0';
682 static void __print_lock_name(struct lock_class *class)
684 char str[KSYM_NAME_LEN];
685 const char *name;
687 name = class->name;
688 if (!name) {
689 name = __get_key_name(class->key, str);
690 printk(KERN_CONT "%s", name);
691 } else {
692 printk(KERN_CONT "%s", name);
693 if (class->name_version > 1)
694 printk(KERN_CONT "#%d", class->name_version);
695 if (class->subclass)
696 printk(KERN_CONT "/%d", class->subclass);
700 static void print_lock_name(struct lock_class *class)
702 char usage[LOCK_USAGE_CHARS];
704 get_usage_chars(class, usage);
706 printk(KERN_CONT " (");
707 __print_lock_name(class);
708 printk(KERN_CONT "){%s}-{%hd:%hd}", usage,
709 class->wait_type_outer ?: class->wait_type_inner,
710 class->wait_type_inner);
713 static void print_lockdep_cache(struct lockdep_map *lock)
715 const char *name;
716 char str[KSYM_NAME_LEN];
718 name = lock->name;
719 if (!name)
720 name = __get_key_name(lock->key->subkeys, str);
722 printk(KERN_CONT "%s", name);
725 static void print_lock(struct held_lock *hlock)
728 * We can be called locklessly through debug_show_all_locks() so be
729 * extra careful, the hlock might have been released and cleared.
731 * If this indeed happens, lets pretend it does not hurt to continue
732 * to print the lock unless the hlock class_idx does not point to a
733 * registered class. The rationale here is: since we don't attempt
734 * to distinguish whether we are in this situation, if it just
735 * happened we can't count on class_idx to tell either.
737 struct lock_class *lock = hlock_class(hlock);
739 if (!lock) {
740 printk(KERN_CONT "<RELEASED>\n");
741 return;
744 printk(KERN_CONT "%px", hlock->instance);
745 print_lock_name(lock);
746 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
749 static void lockdep_print_held_locks(struct task_struct *p)
751 int i, depth = READ_ONCE(p->lockdep_depth);
753 if (!depth)
754 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
755 else
756 printk("%d lock%s held by %s/%d:\n", depth,
757 depth > 1 ? "s" : "", p->comm, task_pid_nr(p));
759 * It's not reliable to print a task's held locks if it's not sleeping
760 * and it's not the current task.
762 if (p->state == TASK_RUNNING && p != current)
763 return;
764 for (i = 0; i < depth; i++) {
765 printk(" #%d: ", i);
766 print_lock(p->held_locks + i);
770 static void print_kernel_ident(void)
772 printk("%s %.*s %s\n", init_utsname()->release,
773 (int)strcspn(init_utsname()->version, " "),
774 init_utsname()->version,
775 print_tainted());
778 static int very_verbose(struct lock_class *class)
780 #if VERY_VERBOSE
781 return class_filter(class);
782 #endif
783 return 0;
787 * Is this the address of a static object:
789 #ifdef __KERNEL__
790 static int static_obj(const void *obj)
792 unsigned long start = (unsigned long) &_stext,
793 end = (unsigned long) &_end,
794 addr = (unsigned long) obj;
796 if (arch_is_kernel_initmem_freed(addr))
797 return 0;
800 * static variable?
802 if ((addr >= start) && (addr < end))
803 return 1;
805 if (arch_is_kernel_data(addr))
806 return 1;
809 * in-kernel percpu var?
811 if (is_kernel_percpu_address(addr))
812 return 1;
815 * module static or percpu var?
817 return is_module_address(addr) || is_module_percpu_address(addr);
819 #endif
822 * To make lock name printouts unique, we calculate a unique
823 * class->name_version generation counter. The caller must hold the graph
824 * lock.
826 static int count_matching_names(struct lock_class *new_class)
828 struct lock_class *class;
829 int count = 0;
831 if (!new_class->name)
832 return 0;
834 list_for_each_entry(class, &all_lock_classes, lock_entry) {
835 if (new_class->key - new_class->subclass == class->key)
836 return class->name_version;
837 if (class->name && !strcmp(class->name, new_class->name))
838 count = max(count, class->name_version);
841 return count + 1;
844 /* used from NMI context -- must be lockless */
845 static __always_inline struct lock_class *
846 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
848 struct lockdep_subclass_key *key;
849 struct hlist_head *hash_head;
850 struct lock_class *class;
852 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
853 debug_locks_off();
854 printk(KERN_ERR
855 "BUG: looking up invalid subclass: %u\n", subclass);
856 printk(KERN_ERR
857 "turning off the locking correctness validator.\n");
858 dump_stack();
859 return NULL;
863 * If it is not initialised then it has never been locked,
864 * so it won't be present in the hash table.
866 if (unlikely(!lock->key))
867 return NULL;
870 * NOTE: the class-key must be unique. For dynamic locks, a static
871 * lock_class_key variable is passed in through the mutex_init()
872 * (or spin_lock_init()) call - which acts as the key. For static
873 * locks we use the lock object itself as the key.
875 BUILD_BUG_ON(sizeof(struct lock_class_key) >
876 sizeof(struct lockdep_map));
878 key = lock->key->subkeys + subclass;
880 hash_head = classhashentry(key);
883 * We do an RCU walk of the hash, see lockdep_free_key_range().
885 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
886 return NULL;
888 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
889 if (class->key == key) {
891 * Huh! same key, different name? Did someone trample
892 * on some memory? We're most confused.
894 WARN_ON_ONCE(class->name != lock->name &&
895 lock->key != &__lockdep_no_validate__);
896 return class;
900 return NULL;
904 * Static locks do not have their class-keys yet - for them the key is
905 * the lock object itself. If the lock is in the per cpu area, the
906 * canonical address of the lock (per cpu offset removed) is used.
908 static bool assign_lock_key(struct lockdep_map *lock)
910 unsigned long can_addr, addr = (unsigned long)lock;
912 #ifdef __KERNEL__
914 * lockdep_free_key_range() assumes that struct lock_class_key
915 * objects do not overlap. Since we use the address of lock
916 * objects as class key for static objects, check whether the
917 * size of lock_class_key objects does not exceed the size of
918 * the smallest lock object.
920 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
921 #endif
923 if (__is_kernel_percpu_address(addr, &can_addr))
924 lock->key = (void *)can_addr;
925 else if (__is_module_percpu_address(addr, &can_addr))
926 lock->key = (void *)can_addr;
927 else if (static_obj(lock))
928 lock->key = (void *)lock;
929 else {
930 /* Debug-check: all keys must be persistent! */
931 debug_locks_off();
932 pr_err("INFO: trying to register non-static key.\n");
933 pr_err("the code is fine but needs lockdep annotation.\n");
934 pr_err("turning off the locking correctness validator.\n");
935 dump_stack();
936 return false;
939 return true;
942 #ifdef CONFIG_DEBUG_LOCKDEP
944 /* Check whether element @e occurs in list @h */
945 static bool in_list(struct list_head *e, struct list_head *h)
947 struct list_head *f;
949 list_for_each(f, h) {
950 if (e == f)
951 return true;
954 return false;
958 * Check whether entry @e occurs in any of the locks_after or locks_before
959 * lists.
961 static bool in_any_class_list(struct list_head *e)
963 struct lock_class *class;
964 int i;
966 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
967 class = &lock_classes[i];
968 if (in_list(e, &class->locks_after) ||
969 in_list(e, &class->locks_before))
970 return true;
972 return false;
975 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
977 struct lock_list *e;
979 list_for_each_entry(e, h, entry) {
980 if (e->links_to != c) {
981 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
982 c->name ? : "(?)",
983 (unsigned long)(e - list_entries),
984 e->links_to && e->links_to->name ?
985 e->links_to->name : "(?)",
986 e->class && e->class->name ? e->class->name :
987 "(?)");
988 return false;
991 return true;
994 #ifdef CONFIG_PROVE_LOCKING
995 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
996 #endif
998 static bool check_lock_chain_key(struct lock_chain *chain)
1000 #ifdef CONFIG_PROVE_LOCKING
1001 u64 chain_key = INITIAL_CHAIN_KEY;
1002 int i;
1004 for (i = chain->base; i < chain->base + chain->depth; i++)
1005 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
1007 * The 'unsigned long long' casts avoid that a compiler warning
1008 * is reported when building tools/lib/lockdep.
1010 if (chain->chain_key != chain_key) {
1011 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
1012 (unsigned long long)(chain - lock_chains),
1013 (unsigned long long)chain->chain_key,
1014 (unsigned long long)chain_key);
1015 return false;
1017 #endif
1018 return true;
1021 static bool in_any_zapped_class_list(struct lock_class *class)
1023 struct pending_free *pf;
1024 int i;
1026 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
1027 if (in_list(&class->lock_entry, &pf->zapped))
1028 return true;
1031 return false;
1034 static bool __check_data_structures(void)
1036 struct lock_class *class;
1037 struct lock_chain *chain;
1038 struct hlist_head *head;
1039 struct lock_list *e;
1040 int i;
1042 /* Check whether all classes occur in a lock list. */
1043 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1044 class = &lock_classes[i];
1045 if (!in_list(&class->lock_entry, &all_lock_classes) &&
1046 !in_list(&class->lock_entry, &free_lock_classes) &&
1047 !in_any_zapped_class_list(class)) {
1048 printk(KERN_INFO "class %px/%s is not in any class list\n",
1049 class, class->name ? : "(?)");
1050 return false;
1054 /* Check whether all classes have valid lock lists. */
1055 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1056 class = &lock_classes[i];
1057 if (!class_lock_list_valid(class, &class->locks_before))
1058 return false;
1059 if (!class_lock_list_valid(class, &class->locks_after))
1060 return false;
1063 /* Check the chain_key of all lock chains. */
1064 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
1065 head = chainhash_table + i;
1066 hlist_for_each_entry_rcu(chain, head, entry) {
1067 if (!check_lock_chain_key(chain))
1068 return false;
1073 * Check whether all list entries that are in use occur in a class
1074 * lock list.
1076 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1077 e = list_entries + i;
1078 if (!in_any_class_list(&e->entry)) {
1079 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
1080 (unsigned int)(e - list_entries),
1081 e->class->name ? : "(?)",
1082 e->links_to->name ? : "(?)");
1083 return false;
1088 * Check whether all list entries that are not in use do not occur in
1089 * a class lock list.
1091 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1092 e = list_entries + i;
1093 if (in_any_class_list(&e->entry)) {
1094 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
1095 (unsigned int)(e - list_entries),
1096 e->class && e->class->name ? e->class->name :
1097 "(?)",
1098 e->links_to && e->links_to->name ?
1099 e->links_to->name : "(?)");
1100 return false;
1104 return true;
1107 int check_consistency = 0;
1108 module_param(check_consistency, int, 0644);
1110 static void check_data_structures(void)
1112 static bool once = false;
1114 if (check_consistency && !once) {
1115 if (!__check_data_structures()) {
1116 once = true;
1117 WARN_ON(once);
1122 #else /* CONFIG_DEBUG_LOCKDEP */
1124 static inline void check_data_structures(void) { }
1126 #endif /* CONFIG_DEBUG_LOCKDEP */
1128 static void init_chain_block_buckets(void);
1131 * Initialize the lock_classes[] array elements, the free_lock_classes list
1132 * and also the delayed_free structure.
1134 static void init_data_structures_once(void)
1136 static bool __read_mostly ds_initialized, rcu_head_initialized;
1137 int i;
1139 if (likely(rcu_head_initialized))
1140 return;
1142 if (system_state >= SYSTEM_SCHEDULING) {
1143 init_rcu_head(&delayed_free.rcu_head);
1144 rcu_head_initialized = true;
1147 if (ds_initialized)
1148 return;
1150 ds_initialized = true;
1152 INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
1153 INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
1155 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1156 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
1157 INIT_LIST_HEAD(&lock_classes[i].locks_after);
1158 INIT_LIST_HEAD(&lock_classes[i].locks_before);
1160 init_chain_block_buckets();
1163 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
1165 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
1167 return lock_keys_hash + hash;
1170 /* Register a dynamically allocated key. */
1171 void lockdep_register_key(struct lock_class_key *key)
1173 struct hlist_head *hash_head;
1174 struct lock_class_key *k;
1175 unsigned long flags;
1177 if (WARN_ON_ONCE(static_obj(key)))
1178 return;
1179 hash_head = keyhashentry(key);
1181 raw_local_irq_save(flags);
1182 if (!graph_lock())
1183 goto restore_irqs;
1184 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1185 if (WARN_ON_ONCE(k == key))
1186 goto out_unlock;
1188 hlist_add_head_rcu(&key->hash_entry, hash_head);
1189 out_unlock:
1190 graph_unlock();
1191 restore_irqs:
1192 raw_local_irq_restore(flags);
1194 EXPORT_SYMBOL_GPL(lockdep_register_key);
1196 /* Check whether a key has been registered as a dynamic key. */
1197 static bool is_dynamic_key(const struct lock_class_key *key)
1199 struct hlist_head *hash_head;
1200 struct lock_class_key *k;
1201 bool found = false;
1203 if (WARN_ON_ONCE(static_obj(key)))
1204 return false;
1207 * If lock debugging is disabled lock_keys_hash[] may contain
1208 * pointers to memory that has already been freed. Avoid triggering
1209 * a use-after-free in that case by returning early.
1211 if (!debug_locks)
1212 return true;
1214 hash_head = keyhashentry(key);
1216 rcu_read_lock();
1217 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1218 if (k == key) {
1219 found = true;
1220 break;
1223 rcu_read_unlock();
1225 return found;
1229 * Register a lock's class in the hash-table, if the class is not present
1230 * yet. Otherwise we look it up. We cache the result in the lock object
1231 * itself, so actual lookup of the hash should be once per lock object.
1233 static struct lock_class *
1234 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1236 struct lockdep_subclass_key *key;
1237 struct hlist_head *hash_head;
1238 struct lock_class *class;
1240 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1242 class = look_up_lock_class(lock, subclass);
1243 if (likely(class))
1244 goto out_set_class_cache;
1246 if (!lock->key) {
1247 if (!assign_lock_key(lock))
1248 return NULL;
1249 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
1250 return NULL;
1253 key = lock->key->subkeys + subclass;
1254 hash_head = classhashentry(key);
1256 if (!graph_lock()) {
1257 return NULL;
1260 * We have to do the hash-walk again, to avoid races
1261 * with another CPU:
1263 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
1264 if (class->key == key)
1265 goto out_unlock_set;
1268 init_data_structures_once();
1270 /* Allocate a new lock class and add it to the hash. */
1271 class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
1272 lock_entry);
1273 if (!class) {
1274 if (!debug_locks_off_graph_unlock()) {
1275 return NULL;
1278 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
1279 dump_stack();
1280 return NULL;
1282 nr_lock_classes++;
1283 __set_bit(class - lock_classes, lock_classes_in_use);
1284 debug_atomic_inc(nr_unused_locks);
1285 class->key = key;
1286 class->name = lock->name;
1287 class->subclass = subclass;
1288 WARN_ON_ONCE(!list_empty(&class->locks_before));
1289 WARN_ON_ONCE(!list_empty(&class->locks_after));
1290 class->name_version = count_matching_names(class);
1291 class->wait_type_inner = lock->wait_type_inner;
1292 class->wait_type_outer = lock->wait_type_outer;
1294 * We use RCU's safe list-add method to make
1295 * parallel walking of the hash-list safe:
1297 hlist_add_head_rcu(&class->hash_entry, hash_head);
1299 * Remove the class from the free list and add it to the global list
1300 * of classes.
1302 list_move_tail(&class->lock_entry, &all_lock_classes);
1304 if (verbose(class)) {
1305 graph_unlock();
1307 printk("\nnew class %px: %s", class->key, class->name);
1308 if (class->name_version > 1)
1309 printk(KERN_CONT "#%d", class->name_version);
1310 printk(KERN_CONT "\n");
1311 dump_stack();
1313 if (!graph_lock()) {
1314 return NULL;
1317 out_unlock_set:
1318 graph_unlock();
1320 out_set_class_cache:
1321 if (!subclass || force)
1322 lock->class_cache[0] = class;
1323 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
1324 lock->class_cache[subclass] = class;
1327 * Hash collision, did we smoke some? We found a class with a matching
1328 * hash but the subclass -- which is hashed in -- didn't match.
1330 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
1331 return NULL;
1333 return class;
1336 #ifdef CONFIG_PROVE_LOCKING
1338 * Allocate a lockdep entry. (assumes the graph_lock held, returns
1339 * with NULL on failure)
1341 static struct lock_list *alloc_list_entry(void)
1343 int idx = find_first_zero_bit(list_entries_in_use,
1344 ARRAY_SIZE(list_entries));
1346 if (idx >= ARRAY_SIZE(list_entries)) {
1347 if (!debug_locks_off_graph_unlock())
1348 return NULL;
1350 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
1351 dump_stack();
1352 return NULL;
1354 nr_list_entries++;
1355 __set_bit(idx, list_entries_in_use);
1356 return list_entries + idx;
1360 * Add a new dependency to the head of the list:
1362 static int add_lock_to_list(struct lock_class *this,
1363 struct lock_class *links_to, struct list_head *head,
1364 unsigned long ip, u16 distance, u8 dep,
1365 const struct lock_trace *trace)
1367 struct lock_list *entry;
1369 * Lock not present yet - get a new dependency struct and
1370 * add it to the list:
1372 entry = alloc_list_entry();
1373 if (!entry)
1374 return 0;
1376 entry->class = this;
1377 entry->links_to = links_to;
1378 entry->dep = dep;
1379 entry->distance = distance;
1380 entry->trace = trace;
1382 * Both allocation and removal are done under the graph lock; but
1383 * iteration is under RCU-sched; see look_up_lock_class() and
1384 * lockdep_free_key_range().
1386 list_add_tail_rcu(&entry->entry, head);
1388 return 1;
1392 * For good efficiency of modular, we use power of 2
1394 #define MAX_CIRCULAR_QUEUE_SIZE 4096UL
1395 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
1398 * The circular_queue and helpers are used to implement graph
1399 * breadth-first search (BFS) algorithm, by which we can determine
1400 * whether there is a path from a lock to another. In deadlock checks,
1401 * a path from the next lock to be acquired to a previous held lock
1402 * indicates that adding the <prev> -> <next> lock dependency will
1403 * produce a circle in the graph. Breadth-first search instead of
1404 * depth-first search is used in order to find the shortest (circular)
1405 * path.
1407 struct circular_queue {
1408 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
1409 unsigned int front, rear;
1412 static struct circular_queue lock_cq;
1414 unsigned int max_bfs_queue_depth;
1416 static unsigned int lockdep_dependency_gen_id;
1418 static inline void __cq_init(struct circular_queue *cq)
1420 cq->front = cq->rear = 0;
1421 lockdep_dependency_gen_id++;
1424 static inline int __cq_empty(struct circular_queue *cq)
1426 return (cq->front == cq->rear);
1429 static inline int __cq_full(struct circular_queue *cq)
1431 return ((cq->rear + 1) & CQ_MASK) == cq->front;
1434 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
1436 if (__cq_full(cq))
1437 return -1;
1439 cq->element[cq->rear] = elem;
1440 cq->rear = (cq->rear + 1) & CQ_MASK;
1441 return 0;
1445 * Dequeue an element from the circular_queue, return a lock_list if
1446 * the queue is not empty, or NULL if otherwise.
1448 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
1450 struct lock_list * lock;
1452 if (__cq_empty(cq))
1453 return NULL;
1455 lock = cq->element[cq->front];
1456 cq->front = (cq->front + 1) & CQ_MASK;
1458 return lock;
1461 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
1463 return (cq->rear - cq->front) & CQ_MASK;
1466 static inline void mark_lock_accessed(struct lock_list *lock)
1468 lock->class->dep_gen_id = lockdep_dependency_gen_id;
1471 static inline void visit_lock_entry(struct lock_list *lock,
1472 struct lock_list *parent)
1474 lock->parent = parent;
1477 static inline unsigned long lock_accessed(struct lock_list *lock)
1479 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
1482 static inline struct lock_list *get_lock_parent(struct lock_list *child)
1484 return child->parent;
1487 static inline int get_lock_depth(struct lock_list *child)
1489 int depth = 0;
1490 struct lock_list *parent;
1492 while ((parent = get_lock_parent(child))) {
1493 child = parent;
1494 depth++;
1496 return depth;
1500 * Return the forward or backward dependency list.
1502 * @lock: the lock_list to get its class's dependency list
1503 * @offset: the offset to struct lock_class to determine whether it is
1504 * locks_after or locks_before
1506 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
1508 void *lock_class = lock->class;
1510 return lock_class + offset;
1513 * Return values of a bfs search:
1515 * BFS_E* indicates an error
1516 * BFS_R* indicates a result (match or not)
1518 * BFS_EINVALIDNODE: Find a invalid node in the graph.
1520 * BFS_EQUEUEFULL: The queue is full while doing the bfs.
1522 * BFS_RMATCH: Find the matched node in the graph, and put that node into
1523 * *@target_entry.
1525 * BFS_RNOMATCH: Haven't found the matched node and keep *@target_entry
1526 * _unchanged_.
1528 enum bfs_result {
1529 BFS_EINVALIDNODE = -2,
1530 BFS_EQUEUEFULL = -1,
1531 BFS_RMATCH = 0,
1532 BFS_RNOMATCH = 1,
1536 * bfs_result < 0 means error
1538 static inline bool bfs_error(enum bfs_result res)
1540 return res < 0;
1544 * DEP_*_BIT in lock_list::dep
1546 * For dependency @prev -> @next:
1548 * SR: @prev is shared reader (->read != 0) and @next is recursive reader
1549 * (->read == 2)
1550 * ER: @prev is exclusive locker (->read == 0) and @next is recursive reader
1551 * SN: @prev is shared reader and @next is non-recursive locker (->read != 2)
1552 * EN: @prev is exclusive locker and @next is non-recursive locker
1554 * Note that we define the value of DEP_*_BITs so that:
1555 * bit0 is prev->read == 0
1556 * bit1 is next->read != 2
1558 #define DEP_SR_BIT (0 + (0 << 1)) /* 0 */
1559 #define DEP_ER_BIT (1 + (0 << 1)) /* 1 */
1560 #define DEP_SN_BIT (0 + (1 << 1)) /* 2 */
1561 #define DEP_EN_BIT (1 + (1 << 1)) /* 3 */
1563 #define DEP_SR_MASK (1U << (DEP_SR_BIT))
1564 #define DEP_ER_MASK (1U << (DEP_ER_BIT))
1565 #define DEP_SN_MASK (1U << (DEP_SN_BIT))
1566 #define DEP_EN_MASK (1U << (DEP_EN_BIT))
1568 static inline unsigned int
1569 __calc_dep_bit(struct held_lock *prev, struct held_lock *next)
1571 return (prev->read == 0) + ((next->read != 2) << 1);
1574 static inline u8 calc_dep(struct held_lock *prev, struct held_lock *next)
1576 return 1U << __calc_dep_bit(prev, next);
1580 * calculate the dep_bit for backwards edges. We care about whether @prev is
1581 * shared and whether @next is recursive.
1583 static inline unsigned int
1584 __calc_dep_bitb(struct held_lock *prev, struct held_lock *next)
1586 return (next->read != 2) + ((prev->read == 0) << 1);
1589 static inline u8 calc_depb(struct held_lock *prev, struct held_lock *next)
1591 return 1U << __calc_dep_bitb(prev, next);
1595 * Initialize a lock_list entry @lock belonging to @class as the root for a BFS
1596 * search.
1598 static inline void __bfs_init_root(struct lock_list *lock,
1599 struct lock_class *class)
1601 lock->class = class;
1602 lock->parent = NULL;
1603 lock->only_xr = 0;
1607 * Initialize a lock_list entry @lock based on a lock acquisition @hlock as the
1608 * root for a BFS search.
1610 * ->only_xr of the initial lock node is set to @hlock->read == 2, to make sure
1611 * that <prev> -> @hlock and @hlock -> <whatever __bfs() found> is not -(*R)->
1612 * and -(S*)->.
1614 static inline void bfs_init_root(struct lock_list *lock,
1615 struct held_lock *hlock)
1617 __bfs_init_root(lock, hlock_class(hlock));
1618 lock->only_xr = (hlock->read == 2);
1622 * Similar to bfs_init_root() but initialize the root for backwards BFS.
1624 * ->only_xr of the initial lock node is set to @hlock->read != 0, to make sure
1625 * that <next> -> @hlock and @hlock -> <whatever backwards BFS found> is not
1626 * -(*S)-> and -(R*)-> (reverse order of -(*R)-> and -(S*)->).
1628 static inline void bfs_init_rootb(struct lock_list *lock,
1629 struct held_lock *hlock)
1631 __bfs_init_root(lock, hlock_class(hlock));
1632 lock->only_xr = (hlock->read != 0);
1635 static inline struct lock_list *__bfs_next(struct lock_list *lock, int offset)
1637 if (!lock || !lock->parent)
1638 return NULL;
1640 return list_next_or_null_rcu(get_dep_list(lock->parent, offset),
1641 &lock->entry, struct lock_list, entry);
1645 * Breadth-First Search to find a strong path in the dependency graph.
1647 * @source_entry: the source of the path we are searching for.
1648 * @data: data used for the second parameter of @match function
1649 * @match: match function for the search
1650 * @target_entry: pointer to the target of a matched path
1651 * @offset: the offset to struct lock_class to determine whether it is
1652 * locks_after or locks_before
1654 * We may have multiple edges (considering different kinds of dependencies,
1655 * e.g. ER and SN) between two nodes in the dependency graph. But
1656 * only the strong dependency path in the graph is relevant to deadlocks. A
1657 * strong dependency path is a dependency path that doesn't have two adjacent
1658 * dependencies as -(*R)-> -(S*)->, please see:
1660 * Documentation/locking/lockdep-design.rst
1662 * for more explanation of the definition of strong dependency paths
1664 * In __bfs(), we only traverse in the strong dependency path:
1666 * In lock_list::only_xr, we record whether the previous dependency only
1667 * has -(*R)-> in the search, and if it does (prev only has -(*R)->), we
1668 * filter out any -(S*)-> in the current dependency and after that, the
1669 * ->only_xr is set according to whether we only have -(*R)-> left.
1671 static enum bfs_result __bfs(struct lock_list *source_entry,
1672 void *data,
1673 bool (*match)(struct lock_list *entry, void *data),
1674 struct lock_list **target_entry,
1675 int offset)
1677 struct circular_queue *cq = &lock_cq;
1678 struct lock_list *lock = NULL;
1679 struct lock_list *entry;
1680 struct list_head *head;
1681 unsigned int cq_depth;
1682 bool first;
1684 lockdep_assert_locked();
1686 __cq_init(cq);
1687 __cq_enqueue(cq, source_entry);
1689 while ((lock = __bfs_next(lock, offset)) || (lock = __cq_dequeue(cq))) {
1690 if (!lock->class)
1691 return BFS_EINVALIDNODE;
1694 * Step 1: check whether we already finish on this one.
1696 * If we have visited all the dependencies from this @lock to
1697 * others (iow, if we have visited all lock_list entries in
1698 * @lock->class->locks_{after,before}) we skip, otherwise go
1699 * and visit all the dependencies in the list and mark this
1700 * list accessed.
1702 if (lock_accessed(lock))
1703 continue;
1704 else
1705 mark_lock_accessed(lock);
1708 * Step 2: check whether prev dependency and this form a strong
1709 * dependency path.
1711 if (lock->parent) { /* Parent exists, check prev dependency */
1712 u8 dep = lock->dep;
1713 bool prev_only_xr = lock->parent->only_xr;
1716 * Mask out all -(S*)-> if we only have *R in previous
1717 * step, because -(*R)-> -(S*)-> don't make up a strong
1718 * dependency.
1720 if (prev_only_xr)
1721 dep &= ~(DEP_SR_MASK | DEP_SN_MASK);
1723 /* If nothing left, we skip */
1724 if (!dep)
1725 continue;
1727 /* If there are only -(*R)-> left, set that for the next step */
1728 lock->only_xr = !(dep & (DEP_SN_MASK | DEP_EN_MASK));
1732 * Step 3: we haven't visited this and there is a strong
1733 * dependency path to this, so check with @match.
1735 if (match(lock, data)) {
1736 *target_entry = lock;
1737 return BFS_RMATCH;
1741 * Step 4: if not match, expand the path by adding the
1742 * forward or backwards dependencis in the search
1745 first = true;
1746 head = get_dep_list(lock, offset);
1747 list_for_each_entry_rcu(entry, head, entry) {
1748 visit_lock_entry(entry, lock);
1751 * Note we only enqueue the first of the list into the
1752 * queue, because we can always find a sibling
1753 * dependency from one (see __bfs_next()), as a result
1754 * the space of queue is saved.
1756 if (!first)
1757 continue;
1759 first = false;
1761 if (__cq_enqueue(cq, entry))
1762 return BFS_EQUEUEFULL;
1764 cq_depth = __cq_get_elem_count(cq);
1765 if (max_bfs_queue_depth < cq_depth)
1766 max_bfs_queue_depth = cq_depth;
1770 return BFS_RNOMATCH;
1773 static inline enum bfs_result
1774 __bfs_forwards(struct lock_list *src_entry,
1775 void *data,
1776 bool (*match)(struct lock_list *entry, void *data),
1777 struct lock_list **target_entry)
1779 return __bfs(src_entry, data, match, target_entry,
1780 offsetof(struct lock_class, locks_after));
1784 static inline enum bfs_result
1785 __bfs_backwards(struct lock_list *src_entry,
1786 void *data,
1787 bool (*match)(struct lock_list *entry, void *data),
1788 struct lock_list **target_entry)
1790 return __bfs(src_entry, data, match, target_entry,
1791 offsetof(struct lock_class, locks_before));
1795 static void print_lock_trace(const struct lock_trace *trace,
1796 unsigned int spaces)
1798 stack_trace_print(trace->entries, trace->nr_entries, spaces);
1802 * Print a dependency chain entry (this is only done when a deadlock
1803 * has been detected):
1805 static noinline void
1806 print_circular_bug_entry(struct lock_list *target, int depth)
1808 if (debug_locks_silent)
1809 return;
1810 printk("\n-> #%u", depth);
1811 print_lock_name(target->class);
1812 printk(KERN_CONT ":\n");
1813 print_lock_trace(target->trace, 6);
1816 static void
1817 print_circular_lock_scenario(struct held_lock *src,
1818 struct held_lock *tgt,
1819 struct lock_list *prt)
1821 struct lock_class *source = hlock_class(src);
1822 struct lock_class *target = hlock_class(tgt);
1823 struct lock_class *parent = prt->class;
1826 * A direct locking problem where unsafe_class lock is taken
1827 * directly by safe_class lock, then all we need to show
1828 * is the deadlock scenario, as it is obvious that the
1829 * unsafe lock is taken under the safe lock.
1831 * But if there is a chain instead, where the safe lock takes
1832 * an intermediate lock (middle_class) where this lock is
1833 * not the same as the safe lock, then the lock chain is
1834 * used to describe the problem. Otherwise we would need
1835 * to show a different CPU case for each link in the chain
1836 * from the safe_class lock to the unsafe_class lock.
1838 if (parent != source) {
1839 printk("Chain exists of:\n ");
1840 __print_lock_name(source);
1841 printk(KERN_CONT " --> ");
1842 __print_lock_name(parent);
1843 printk(KERN_CONT " --> ");
1844 __print_lock_name(target);
1845 printk(KERN_CONT "\n\n");
1848 printk(" Possible unsafe locking scenario:\n\n");
1849 printk(" CPU0 CPU1\n");
1850 printk(" ---- ----\n");
1851 printk(" lock(");
1852 __print_lock_name(target);
1853 printk(KERN_CONT ");\n");
1854 printk(" lock(");
1855 __print_lock_name(parent);
1856 printk(KERN_CONT ");\n");
1857 printk(" lock(");
1858 __print_lock_name(target);
1859 printk(KERN_CONT ");\n");
1860 printk(" lock(");
1861 __print_lock_name(source);
1862 printk(KERN_CONT ");\n");
1863 printk("\n *** DEADLOCK ***\n\n");
1867 * When a circular dependency is detected, print the
1868 * header first:
1870 static noinline void
1871 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1872 struct held_lock *check_src,
1873 struct held_lock *check_tgt)
1875 struct task_struct *curr = current;
1877 if (debug_locks_silent)
1878 return;
1880 pr_warn("\n");
1881 pr_warn("======================================================\n");
1882 pr_warn("WARNING: possible circular locking dependency detected\n");
1883 print_kernel_ident();
1884 pr_warn("------------------------------------------------------\n");
1885 pr_warn("%s/%d is trying to acquire lock:\n",
1886 curr->comm, task_pid_nr(curr));
1887 print_lock(check_src);
1889 pr_warn("\nbut task is already holding lock:\n");
1891 print_lock(check_tgt);
1892 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1893 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1895 print_circular_bug_entry(entry, depth);
1899 * We are about to add A -> B into the dependency graph, and in __bfs() a
1900 * strong dependency path A -> .. -> B is found: hlock_class equals
1901 * entry->class.
1903 * If A -> .. -> B can replace A -> B in any __bfs() search (means the former
1904 * is _stronger_ than or equal to the latter), we consider A -> B as redundant.
1905 * For example if A -> .. -> B is -(EN)-> (i.e. A -(E*)-> .. -(*N)-> B), and A
1906 * -> B is -(ER)-> or -(EN)->, then we don't need to add A -> B into the
1907 * dependency graph, as any strong path ..-> A -> B ->.. we can get with
1908 * having dependency A -> B, we could already get a equivalent path ..-> A ->
1909 * .. -> B -> .. with A -> .. -> B. Therefore A -> B is reduntant.
1911 * We need to make sure both the start and the end of A -> .. -> B is not
1912 * weaker than A -> B. For the start part, please see the comment in
1913 * check_redundant(). For the end part, we need:
1915 * Either
1917 * a) A -> B is -(*R)-> (everything is not weaker than that)
1919 * or
1921 * b) A -> .. -> B is -(*N)-> (nothing is stronger than this)
1924 static inline bool hlock_equal(struct lock_list *entry, void *data)
1926 struct held_lock *hlock = (struct held_lock *)data;
1928 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
1929 (hlock->read == 2 || /* A -> B is -(*R)-> */
1930 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
1934 * We are about to add B -> A into the dependency graph, and in __bfs() a
1935 * strong dependency path A -> .. -> B is found: hlock_class equals
1936 * entry->class.
1938 * We will have a deadlock case (conflict) if A -> .. -> B -> A is a strong
1939 * dependency cycle, that means:
1941 * Either
1943 * a) B -> A is -(E*)->
1945 * or
1947 * b) A -> .. -> B is -(*N)-> (i.e. A -> .. -(*N)-> B)
1949 * as then we don't have -(*R)-> -(S*)-> in the cycle.
1951 static inline bool hlock_conflict(struct lock_list *entry, void *data)
1953 struct held_lock *hlock = (struct held_lock *)data;
1955 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
1956 (hlock->read == 0 || /* B -> A is -(E*)-> */
1957 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
1960 static noinline void print_circular_bug(struct lock_list *this,
1961 struct lock_list *target,
1962 struct held_lock *check_src,
1963 struct held_lock *check_tgt)
1965 struct task_struct *curr = current;
1966 struct lock_list *parent;
1967 struct lock_list *first_parent;
1968 int depth;
1970 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1971 return;
1973 this->trace = save_trace();
1974 if (!this->trace)
1975 return;
1977 depth = get_lock_depth(target);
1979 print_circular_bug_header(target, depth, check_src, check_tgt);
1981 parent = get_lock_parent(target);
1982 first_parent = parent;
1984 while (parent) {
1985 print_circular_bug_entry(parent, --depth);
1986 parent = get_lock_parent(parent);
1989 printk("\nother info that might help us debug this:\n\n");
1990 print_circular_lock_scenario(check_src, check_tgt,
1991 first_parent);
1993 lockdep_print_held_locks(curr);
1995 printk("\nstack backtrace:\n");
1996 dump_stack();
1999 static noinline void print_bfs_bug(int ret)
2001 if (!debug_locks_off_graph_unlock())
2002 return;
2005 * Breadth-first-search failed, graph got corrupted?
2007 WARN(1, "lockdep bfs error:%d\n", ret);
2010 static bool noop_count(struct lock_list *entry, void *data)
2012 (*(unsigned long *)data)++;
2013 return false;
2016 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
2018 unsigned long count = 0;
2019 struct lock_list *target_entry;
2021 __bfs_forwards(this, (void *)&count, noop_count, &target_entry);
2023 return count;
2025 unsigned long lockdep_count_forward_deps(struct lock_class *class)
2027 unsigned long ret, flags;
2028 struct lock_list this;
2030 __bfs_init_root(&this, class);
2032 raw_local_irq_save(flags);
2033 lockdep_lock();
2034 ret = __lockdep_count_forward_deps(&this);
2035 lockdep_unlock();
2036 raw_local_irq_restore(flags);
2038 return ret;
2041 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
2043 unsigned long count = 0;
2044 struct lock_list *target_entry;
2046 __bfs_backwards(this, (void *)&count, noop_count, &target_entry);
2048 return count;
2051 unsigned long lockdep_count_backward_deps(struct lock_class *class)
2053 unsigned long ret, flags;
2054 struct lock_list this;
2056 __bfs_init_root(&this, class);
2058 raw_local_irq_save(flags);
2059 lockdep_lock();
2060 ret = __lockdep_count_backward_deps(&this);
2061 lockdep_unlock();
2062 raw_local_irq_restore(flags);
2064 return ret;
2068 * Check that the dependency graph starting at <src> can lead to
2069 * <target> or not.
2071 static noinline enum bfs_result
2072 check_path(struct held_lock *target, struct lock_list *src_entry,
2073 bool (*match)(struct lock_list *entry, void *data),
2074 struct lock_list **target_entry)
2076 enum bfs_result ret;
2078 ret = __bfs_forwards(src_entry, target, match, target_entry);
2080 if (unlikely(bfs_error(ret)))
2081 print_bfs_bug(ret);
2083 return ret;
2087 * Prove that the dependency graph starting at <src> can not
2088 * lead to <target>. If it can, there is a circle when adding
2089 * <target> -> <src> dependency.
2091 * Print an error and return BFS_RMATCH if it does.
2093 static noinline enum bfs_result
2094 check_noncircular(struct held_lock *src, struct held_lock *target,
2095 struct lock_trace **const trace)
2097 enum bfs_result ret;
2098 struct lock_list *target_entry;
2099 struct lock_list src_entry;
2101 bfs_init_root(&src_entry, src);
2103 debug_atomic_inc(nr_cyclic_checks);
2105 ret = check_path(target, &src_entry, hlock_conflict, &target_entry);
2107 if (unlikely(ret == BFS_RMATCH)) {
2108 if (!*trace) {
2110 * If save_trace fails here, the printing might
2111 * trigger a WARN but because of the !nr_entries it
2112 * should not do bad things.
2114 *trace = save_trace();
2117 print_circular_bug(&src_entry, target_entry, src, target);
2120 return ret;
2123 #ifdef CONFIG_LOCKDEP_SMALL
2125 * Check that the dependency graph starting at <src> can lead to
2126 * <target> or not. If it can, <src> -> <target> dependency is already
2127 * in the graph.
2129 * Return BFS_RMATCH if it does, or BFS_RMATCH if it does not, return BFS_E* if
2130 * any error appears in the bfs search.
2132 static noinline enum bfs_result
2133 check_redundant(struct held_lock *src, struct held_lock *target)
2135 enum bfs_result ret;
2136 struct lock_list *target_entry;
2137 struct lock_list src_entry;
2139 bfs_init_root(&src_entry, src);
2141 * Special setup for check_redundant().
2143 * To report redundant, we need to find a strong dependency path that
2144 * is equal to or stronger than <src> -> <target>. So if <src> is E,
2145 * we need to let __bfs() only search for a path starting at a -(E*)->,
2146 * we achieve this by setting the initial node's ->only_xr to true in
2147 * that case. And if <prev> is S, we set initial ->only_xr to false
2148 * because both -(S*)-> (equal) and -(E*)-> (stronger) are redundant.
2150 src_entry.only_xr = src->read == 0;
2152 debug_atomic_inc(nr_redundant_checks);
2154 ret = check_path(target, &src_entry, hlock_equal, &target_entry);
2156 if (ret == BFS_RMATCH)
2157 debug_atomic_inc(nr_redundant);
2159 return ret;
2161 #endif
2163 #ifdef CONFIG_TRACE_IRQFLAGS
2166 * Forwards and backwards subgraph searching, for the purposes of
2167 * proving that two subgraphs can be connected by a new dependency
2168 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
2170 * A irq safe->unsafe deadlock happens with the following conditions:
2172 * 1) We have a strong dependency path A -> ... -> B
2174 * 2) and we have ENABLED_IRQ usage of B and USED_IN_IRQ usage of A, therefore
2175 * irq can create a new dependency B -> A (consider the case that a holder
2176 * of B gets interrupted by an irq whose handler will try to acquire A).
2178 * 3) the dependency circle A -> ... -> B -> A we get from 1) and 2) is a
2179 * strong circle:
2181 * For the usage bits of B:
2182 * a) if A -> B is -(*N)->, then B -> A could be any type, so any
2183 * ENABLED_IRQ usage suffices.
2184 * b) if A -> B is -(*R)->, then B -> A must be -(E*)->, so only
2185 * ENABLED_IRQ_*_READ usage suffices.
2187 * For the usage bits of A:
2188 * c) if A -> B is -(E*)->, then B -> A could be any type, so any
2189 * USED_IN_IRQ usage suffices.
2190 * d) if A -> B is -(S*)->, then B -> A must be -(*N)->, so only
2191 * USED_IN_IRQ_*_READ usage suffices.
2195 * There is a strong dependency path in the dependency graph: A -> B, and now
2196 * we need to decide which usage bit of A should be accumulated to detect
2197 * safe->unsafe bugs.
2199 * Note that usage_accumulate() is used in backwards search, so ->only_xr
2200 * stands for whether A -> B only has -(S*)-> (in this case ->only_xr is true).
2202 * As above, if only_xr is false, which means A -> B has -(E*)-> dependency
2203 * path, any usage of A should be considered. Otherwise, we should only
2204 * consider _READ usage.
2206 static inline bool usage_accumulate(struct lock_list *entry, void *mask)
2208 if (!entry->only_xr)
2209 *(unsigned long *)mask |= entry->class->usage_mask;
2210 else /* Mask out _READ usage bits */
2211 *(unsigned long *)mask |= (entry->class->usage_mask & LOCKF_IRQ);
2213 return false;
2217 * There is a strong dependency path in the dependency graph: A -> B, and now
2218 * we need to decide which usage bit of B conflicts with the usage bits of A,
2219 * i.e. which usage bit of B may introduce safe->unsafe deadlocks.
2221 * As above, if only_xr is false, which means A -> B has -(*N)-> dependency
2222 * path, any usage of B should be considered. Otherwise, we should only
2223 * consider _READ usage.
2225 static inline bool usage_match(struct lock_list *entry, void *mask)
2227 if (!entry->only_xr)
2228 return !!(entry->class->usage_mask & *(unsigned long *)mask);
2229 else /* Mask out _READ usage bits */
2230 return !!((entry->class->usage_mask & LOCKF_IRQ) & *(unsigned long *)mask);
2234 * Find a node in the forwards-direction dependency sub-graph starting
2235 * at @root->class that matches @bit.
2237 * Return BFS_MATCH if such a node exists in the subgraph, and put that node
2238 * into *@target_entry.
2240 static enum bfs_result
2241 find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
2242 struct lock_list **target_entry)
2244 enum bfs_result result;
2246 debug_atomic_inc(nr_find_usage_forwards_checks);
2248 result = __bfs_forwards(root, &usage_mask, usage_match, target_entry);
2250 return result;
2254 * Find a node in the backwards-direction dependency sub-graph starting
2255 * at @root->class that matches @bit.
2257 static enum bfs_result
2258 find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
2259 struct lock_list **target_entry)
2261 enum bfs_result result;
2263 debug_atomic_inc(nr_find_usage_backwards_checks);
2265 result = __bfs_backwards(root, &usage_mask, usage_match, target_entry);
2267 return result;
2270 static void print_lock_class_header(struct lock_class *class, int depth)
2272 int bit;
2274 printk("%*s->", depth, "");
2275 print_lock_name(class);
2276 #ifdef CONFIG_DEBUG_LOCKDEP
2277 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
2278 #endif
2279 printk(KERN_CONT " {\n");
2281 for (bit = 0; bit < LOCK_TRACE_STATES; bit++) {
2282 if (class->usage_mask & (1 << bit)) {
2283 int len = depth;
2285 len += printk("%*s %s", depth, "", usage_str[bit]);
2286 len += printk(KERN_CONT " at:\n");
2287 print_lock_trace(class->usage_traces[bit], len);
2290 printk("%*s }\n", depth, "");
2292 printk("%*s ... key at: [<%px>] %pS\n",
2293 depth, "", class->key, class->key);
2297 * printk the shortest lock dependencies from @start to @end in reverse order:
2299 static void __used
2300 print_shortest_lock_dependencies(struct lock_list *leaf,
2301 struct lock_list *root)
2303 struct lock_list *entry = leaf;
2304 int depth;
2306 /*compute depth from generated tree by BFS*/
2307 depth = get_lock_depth(leaf);
2309 do {
2310 print_lock_class_header(entry->class, depth);
2311 printk("%*s ... acquired at:\n", depth, "");
2312 print_lock_trace(entry->trace, 2);
2313 printk("\n");
2315 if (depth == 0 && (entry != root)) {
2316 printk("lockdep:%s bad path found in chain graph\n", __func__);
2317 break;
2320 entry = get_lock_parent(entry);
2321 depth--;
2322 } while (entry && (depth >= 0));
2325 static void
2326 print_irq_lock_scenario(struct lock_list *safe_entry,
2327 struct lock_list *unsafe_entry,
2328 struct lock_class *prev_class,
2329 struct lock_class *next_class)
2331 struct lock_class *safe_class = safe_entry->class;
2332 struct lock_class *unsafe_class = unsafe_entry->class;
2333 struct lock_class *middle_class = prev_class;
2335 if (middle_class == safe_class)
2336 middle_class = next_class;
2339 * A direct locking problem where unsafe_class lock is taken
2340 * directly by safe_class lock, then all we need to show
2341 * is the deadlock scenario, as it is obvious that the
2342 * unsafe lock is taken under the safe lock.
2344 * But if there is a chain instead, where the safe lock takes
2345 * an intermediate lock (middle_class) where this lock is
2346 * not the same as the safe lock, then the lock chain is
2347 * used to describe the problem. Otherwise we would need
2348 * to show a different CPU case for each link in the chain
2349 * from the safe_class lock to the unsafe_class lock.
2351 if (middle_class != unsafe_class) {
2352 printk("Chain exists of:\n ");
2353 __print_lock_name(safe_class);
2354 printk(KERN_CONT " --> ");
2355 __print_lock_name(middle_class);
2356 printk(KERN_CONT " --> ");
2357 __print_lock_name(unsafe_class);
2358 printk(KERN_CONT "\n\n");
2361 printk(" Possible interrupt unsafe locking scenario:\n\n");
2362 printk(" CPU0 CPU1\n");
2363 printk(" ---- ----\n");
2364 printk(" lock(");
2365 __print_lock_name(unsafe_class);
2366 printk(KERN_CONT ");\n");
2367 printk(" local_irq_disable();\n");
2368 printk(" lock(");
2369 __print_lock_name(safe_class);
2370 printk(KERN_CONT ");\n");
2371 printk(" lock(");
2372 __print_lock_name(middle_class);
2373 printk(KERN_CONT ");\n");
2374 printk(" <Interrupt>\n");
2375 printk(" lock(");
2376 __print_lock_name(safe_class);
2377 printk(KERN_CONT ");\n");
2378 printk("\n *** DEADLOCK ***\n\n");
2381 static void
2382 print_bad_irq_dependency(struct task_struct *curr,
2383 struct lock_list *prev_root,
2384 struct lock_list *next_root,
2385 struct lock_list *backwards_entry,
2386 struct lock_list *forwards_entry,
2387 struct held_lock *prev,
2388 struct held_lock *next,
2389 enum lock_usage_bit bit1,
2390 enum lock_usage_bit bit2,
2391 const char *irqclass)
2393 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2394 return;
2396 pr_warn("\n");
2397 pr_warn("=====================================================\n");
2398 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
2399 irqclass, irqclass);
2400 print_kernel_ident();
2401 pr_warn("-----------------------------------------------------\n");
2402 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
2403 curr->comm, task_pid_nr(curr),
2404 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
2405 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
2406 lockdep_hardirqs_enabled(),
2407 curr->softirqs_enabled);
2408 print_lock(next);
2410 pr_warn("\nand this task is already holding:\n");
2411 print_lock(prev);
2412 pr_warn("which would create a new lock dependency:\n");
2413 print_lock_name(hlock_class(prev));
2414 pr_cont(" ->");
2415 print_lock_name(hlock_class(next));
2416 pr_cont("\n");
2418 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
2419 irqclass);
2420 print_lock_name(backwards_entry->class);
2421 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
2423 print_lock_trace(backwards_entry->class->usage_traces[bit1], 1);
2425 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
2426 print_lock_name(forwards_entry->class);
2427 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
2428 pr_warn("...");
2430 print_lock_trace(forwards_entry->class->usage_traces[bit2], 1);
2432 pr_warn("\nother info that might help us debug this:\n\n");
2433 print_irq_lock_scenario(backwards_entry, forwards_entry,
2434 hlock_class(prev), hlock_class(next));
2436 lockdep_print_held_locks(curr);
2438 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
2439 prev_root->trace = save_trace();
2440 if (!prev_root->trace)
2441 return;
2442 print_shortest_lock_dependencies(backwards_entry, prev_root);
2444 pr_warn("\nthe dependencies between the lock to be acquired");
2445 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
2446 next_root->trace = save_trace();
2447 if (!next_root->trace)
2448 return;
2449 print_shortest_lock_dependencies(forwards_entry, next_root);
2451 pr_warn("\nstack backtrace:\n");
2452 dump_stack();
2455 static const char *state_names[] = {
2456 #define LOCKDEP_STATE(__STATE) \
2457 __stringify(__STATE),
2458 #include "lockdep_states.h"
2459 #undef LOCKDEP_STATE
2462 static const char *state_rnames[] = {
2463 #define LOCKDEP_STATE(__STATE) \
2464 __stringify(__STATE)"-READ",
2465 #include "lockdep_states.h"
2466 #undef LOCKDEP_STATE
2469 static inline const char *state_name(enum lock_usage_bit bit)
2471 if (bit & LOCK_USAGE_READ_MASK)
2472 return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
2473 else
2474 return state_names[bit >> LOCK_USAGE_DIR_MASK];
2478 * The bit number is encoded like:
2480 * bit0: 0 exclusive, 1 read lock
2481 * bit1: 0 used in irq, 1 irq enabled
2482 * bit2-n: state
2484 static int exclusive_bit(int new_bit)
2486 int state = new_bit & LOCK_USAGE_STATE_MASK;
2487 int dir = new_bit & LOCK_USAGE_DIR_MASK;
2490 * keep state, bit flip the direction and strip read.
2492 return state | (dir ^ LOCK_USAGE_DIR_MASK);
2496 * Observe that when given a bitmask where each bitnr is encoded as above, a
2497 * right shift of the mask transforms the individual bitnrs as -1 and
2498 * conversely, a left shift transforms into +1 for the individual bitnrs.
2500 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
2501 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
2502 * instead by subtracting the bit number by 2, or shifting the mask right by 2.
2504 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
2506 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
2507 * all bits set) and recompose with bitnr1 flipped.
2509 static unsigned long invert_dir_mask(unsigned long mask)
2511 unsigned long excl = 0;
2513 /* Invert dir */
2514 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
2515 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
2517 return excl;
2521 * Note that a LOCK_ENABLED_IRQ_*_READ usage and a LOCK_USED_IN_IRQ_*_READ
2522 * usage may cause deadlock too, for example:
2524 * P1 P2
2525 * <irq disabled>
2526 * write_lock(l1); <irq enabled>
2527 * read_lock(l2);
2528 * write_lock(l2);
2529 * <in irq>
2530 * read_lock(l1);
2532 * , in above case, l1 will be marked as LOCK_USED_IN_IRQ_HARDIRQ_READ and l2
2533 * will marked as LOCK_ENABLE_IRQ_HARDIRQ_READ, and this is a possible
2534 * deadlock.
2536 * In fact, all of the following cases may cause deadlocks:
2538 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*
2539 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*
2540 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*_READ
2541 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*_READ
2543 * As a result, to calculate the "exclusive mask", first we invert the
2544 * direction (USED_IN/ENABLED) of the original mask, and 1) for all bits with
2545 * bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*). 2) for all
2546 * bits with bitnr0 cleared (LOCK_*_READ), add those with bitnr0 set (LOCK_*).
2548 static unsigned long exclusive_mask(unsigned long mask)
2550 unsigned long excl = invert_dir_mask(mask);
2552 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2553 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2555 return excl;
2559 * Retrieve the _possible_ original mask to which @mask is
2560 * exclusive. Ie: this is the opposite of exclusive_mask().
2561 * Note that 2 possible original bits can match an exclusive
2562 * bit: one has LOCK_USAGE_READ_MASK set, the other has it
2563 * cleared. So both are returned for each exclusive bit.
2565 static unsigned long original_mask(unsigned long mask)
2567 unsigned long excl = invert_dir_mask(mask);
2569 /* Include read in existing usages */
2570 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2571 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2573 return excl;
2577 * Find the first pair of bit match between an original
2578 * usage mask and an exclusive usage mask.
2580 static int find_exclusive_match(unsigned long mask,
2581 unsigned long excl_mask,
2582 enum lock_usage_bit *bitp,
2583 enum lock_usage_bit *excl_bitp)
2585 int bit, excl, excl_read;
2587 for_each_set_bit(bit, &mask, LOCK_USED) {
2589 * exclusive_bit() strips the read bit, however,
2590 * LOCK_ENABLED_IRQ_*_READ may cause deadlocks too, so we need
2591 * to search excl | LOCK_USAGE_READ_MASK as well.
2593 excl = exclusive_bit(bit);
2594 excl_read = excl | LOCK_USAGE_READ_MASK;
2595 if (excl_mask & lock_flag(excl)) {
2596 *bitp = bit;
2597 *excl_bitp = excl;
2598 return 0;
2599 } else if (excl_mask & lock_flag(excl_read)) {
2600 *bitp = bit;
2601 *excl_bitp = excl_read;
2602 return 0;
2605 return -1;
2609 * Prove that the new dependency does not connect a hardirq-safe(-read)
2610 * lock with a hardirq-unsafe lock - to achieve this we search
2611 * the backwards-subgraph starting at <prev>, and the
2612 * forwards-subgraph starting at <next>:
2614 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
2615 struct held_lock *next)
2617 unsigned long usage_mask = 0, forward_mask, backward_mask;
2618 enum lock_usage_bit forward_bit = 0, backward_bit = 0;
2619 struct lock_list *target_entry1;
2620 struct lock_list *target_entry;
2621 struct lock_list this, that;
2622 enum bfs_result ret;
2625 * Step 1: gather all hard/soft IRQs usages backward in an
2626 * accumulated usage mask.
2628 bfs_init_rootb(&this, prev);
2630 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, NULL);
2631 if (bfs_error(ret)) {
2632 print_bfs_bug(ret);
2633 return 0;
2636 usage_mask &= LOCKF_USED_IN_IRQ_ALL;
2637 if (!usage_mask)
2638 return 1;
2641 * Step 2: find exclusive uses forward that match the previous
2642 * backward accumulated mask.
2644 forward_mask = exclusive_mask(usage_mask);
2646 bfs_init_root(&that, next);
2648 ret = find_usage_forwards(&that, forward_mask, &target_entry1);
2649 if (bfs_error(ret)) {
2650 print_bfs_bug(ret);
2651 return 0;
2653 if (ret == BFS_RNOMATCH)
2654 return 1;
2657 * Step 3: we found a bad match! Now retrieve a lock from the backward
2658 * list whose usage mask matches the exclusive usage mask from the
2659 * lock found on the forward list.
2661 backward_mask = original_mask(target_entry1->class->usage_mask);
2663 ret = find_usage_backwards(&this, backward_mask, &target_entry);
2664 if (bfs_error(ret)) {
2665 print_bfs_bug(ret);
2666 return 0;
2668 if (DEBUG_LOCKS_WARN_ON(ret == BFS_RNOMATCH))
2669 return 1;
2672 * Step 4: narrow down to a pair of incompatible usage bits
2673 * and report it.
2675 ret = find_exclusive_match(target_entry->class->usage_mask,
2676 target_entry1->class->usage_mask,
2677 &backward_bit, &forward_bit);
2678 if (DEBUG_LOCKS_WARN_ON(ret == -1))
2679 return 1;
2681 print_bad_irq_dependency(curr, &this, &that,
2682 target_entry, target_entry1,
2683 prev, next,
2684 backward_bit, forward_bit,
2685 state_name(backward_bit));
2687 return 0;
2690 #else
2692 static inline int check_irq_usage(struct task_struct *curr,
2693 struct held_lock *prev, struct held_lock *next)
2695 return 1;
2697 #endif /* CONFIG_TRACE_IRQFLAGS */
2699 static void inc_chains(int irq_context)
2701 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2702 nr_hardirq_chains++;
2703 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2704 nr_softirq_chains++;
2705 else
2706 nr_process_chains++;
2709 static void dec_chains(int irq_context)
2711 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2712 nr_hardirq_chains--;
2713 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2714 nr_softirq_chains--;
2715 else
2716 nr_process_chains--;
2719 static void
2720 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
2722 struct lock_class *next = hlock_class(nxt);
2723 struct lock_class *prev = hlock_class(prv);
2725 printk(" Possible unsafe locking scenario:\n\n");
2726 printk(" CPU0\n");
2727 printk(" ----\n");
2728 printk(" lock(");
2729 __print_lock_name(prev);
2730 printk(KERN_CONT ");\n");
2731 printk(" lock(");
2732 __print_lock_name(next);
2733 printk(KERN_CONT ");\n");
2734 printk("\n *** DEADLOCK ***\n\n");
2735 printk(" May be due to missing lock nesting notation\n\n");
2738 static void
2739 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
2740 struct held_lock *next)
2742 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2743 return;
2745 pr_warn("\n");
2746 pr_warn("============================================\n");
2747 pr_warn("WARNING: possible recursive locking detected\n");
2748 print_kernel_ident();
2749 pr_warn("--------------------------------------------\n");
2750 pr_warn("%s/%d is trying to acquire lock:\n",
2751 curr->comm, task_pid_nr(curr));
2752 print_lock(next);
2753 pr_warn("\nbut task is already holding lock:\n");
2754 print_lock(prev);
2756 pr_warn("\nother info that might help us debug this:\n");
2757 print_deadlock_scenario(next, prev);
2758 lockdep_print_held_locks(curr);
2760 pr_warn("\nstack backtrace:\n");
2761 dump_stack();
2765 * Check whether we are holding such a class already.
2767 * (Note that this has to be done separately, because the graph cannot
2768 * detect such classes of deadlocks.)
2770 * Returns: 0 on deadlock detected, 1 on OK, 2 if another lock with the same
2771 * lock class is held but nest_lock is also held, i.e. we rely on the
2772 * nest_lock to avoid the deadlock.
2774 static int
2775 check_deadlock(struct task_struct *curr, struct held_lock *next)
2777 struct held_lock *prev;
2778 struct held_lock *nest = NULL;
2779 int i;
2781 for (i = 0; i < curr->lockdep_depth; i++) {
2782 prev = curr->held_locks + i;
2784 if (prev->instance == next->nest_lock)
2785 nest = prev;
2787 if (hlock_class(prev) != hlock_class(next))
2788 continue;
2791 * Allow read-after-read recursion of the same
2792 * lock class (i.e. read_lock(lock)+read_lock(lock)):
2794 if ((next->read == 2) && prev->read)
2795 continue;
2798 * We're holding the nest_lock, which serializes this lock's
2799 * nesting behaviour.
2801 if (nest)
2802 return 2;
2804 print_deadlock_bug(curr, prev, next);
2805 return 0;
2807 return 1;
2811 * There was a chain-cache miss, and we are about to add a new dependency
2812 * to a previous lock. We validate the following rules:
2814 * - would the adding of the <prev> -> <next> dependency create a
2815 * circular dependency in the graph? [== circular deadlock]
2817 * - does the new prev->next dependency connect any hardirq-safe lock
2818 * (in the full backwards-subgraph starting at <prev>) with any
2819 * hardirq-unsafe lock (in the full forwards-subgraph starting at
2820 * <next>)? [== illegal lock inversion with hardirq contexts]
2822 * - does the new prev->next dependency connect any softirq-safe lock
2823 * (in the full backwards-subgraph starting at <prev>) with any
2824 * softirq-unsafe lock (in the full forwards-subgraph starting at
2825 * <next>)? [== illegal lock inversion with softirq contexts]
2827 * any of these scenarios could lead to a deadlock.
2829 * Then if all the validations pass, we add the forwards and backwards
2830 * dependency.
2832 static int
2833 check_prev_add(struct task_struct *curr, struct held_lock *prev,
2834 struct held_lock *next, u16 distance,
2835 struct lock_trace **const trace)
2837 struct lock_list *entry;
2838 enum bfs_result ret;
2840 if (!hlock_class(prev)->key || !hlock_class(next)->key) {
2842 * The warning statements below may trigger a use-after-free
2843 * of the class name. It is better to trigger a use-after free
2844 * and to have the class name most of the time instead of not
2845 * having the class name available.
2847 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
2848 "Detected use-after-free of lock class %px/%s\n",
2849 hlock_class(prev),
2850 hlock_class(prev)->name);
2851 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
2852 "Detected use-after-free of lock class %px/%s\n",
2853 hlock_class(next),
2854 hlock_class(next)->name);
2855 return 2;
2859 * Prove that the new <prev> -> <next> dependency would not
2860 * create a circular dependency in the graph. (We do this by
2861 * a breadth-first search into the graph starting at <next>,
2862 * and check whether we can reach <prev>.)
2864 * The search is limited by the size of the circular queue (i.e.,
2865 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
2866 * in the graph whose neighbours are to be checked.
2868 ret = check_noncircular(next, prev, trace);
2869 if (unlikely(bfs_error(ret) || ret == BFS_RMATCH))
2870 return 0;
2872 if (!check_irq_usage(curr, prev, next))
2873 return 0;
2876 * Is the <prev> -> <next> dependency already present?
2878 * (this may occur even though this is a new chain: consider
2879 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
2880 * chains - the second one will be new, but L1 already has
2881 * L2 added to its dependency list, due to the first chain.)
2883 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
2884 if (entry->class == hlock_class(next)) {
2885 if (distance == 1)
2886 entry->distance = 1;
2887 entry->dep |= calc_dep(prev, next);
2890 * Also, update the reverse dependency in @next's
2891 * ->locks_before list.
2893 * Here we reuse @entry as the cursor, which is fine
2894 * because we won't go to the next iteration of the
2895 * outer loop:
2897 * For normal cases, we return in the inner loop.
2899 * If we fail to return, we have inconsistency, i.e.
2900 * <prev>::locks_after contains <next> while
2901 * <next>::locks_before doesn't contain <prev>. In
2902 * that case, we return after the inner and indicate
2903 * something is wrong.
2905 list_for_each_entry(entry, &hlock_class(next)->locks_before, entry) {
2906 if (entry->class == hlock_class(prev)) {
2907 if (distance == 1)
2908 entry->distance = 1;
2909 entry->dep |= calc_depb(prev, next);
2910 return 1;
2914 /* <prev> is not found in <next>::locks_before */
2915 return 0;
2919 #ifdef CONFIG_LOCKDEP_SMALL
2921 * Is the <prev> -> <next> link redundant?
2923 ret = check_redundant(prev, next);
2924 if (bfs_error(ret))
2925 return 0;
2926 else if (ret == BFS_RMATCH)
2927 return 2;
2928 #endif
2930 if (!*trace) {
2931 *trace = save_trace();
2932 if (!*trace)
2933 return 0;
2937 * Ok, all validations passed, add the new lock
2938 * to the previous lock's dependency list:
2940 ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
2941 &hlock_class(prev)->locks_after,
2942 next->acquire_ip, distance,
2943 calc_dep(prev, next),
2944 *trace);
2946 if (!ret)
2947 return 0;
2949 ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
2950 &hlock_class(next)->locks_before,
2951 next->acquire_ip, distance,
2952 calc_depb(prev, next),
2953 *trace);
2954 if (!ret)
2955 return 0;
2957 return 2;
2961 * Add the dependency to all directly-previous locks that are 'relevant'.
2962 * The ones that are relevant are (in increasing distance from curr):
2963 * all consecutive trylock entries and the final non-trylock entry - or
2964 * the end of this context's lock-chain - whichever comes first.
2966 static int
2967 check_prevs_add(struct task_struct *curr, struct held_lock *next)
2969 struct lock_trace *trace = NULL;
2970 int depth = curr->lockdep_depth;
2971 struct held_lock *hlock;
2974 * Debugging checks.
2976 * Depth must not be zero for a non-head lock:
2978 if (!depth)
2979 goto out_bug;
2981 * At least two relevant locks must exist for this
2982 * to be a head:
2984 if (curr->held_locks[depth].irq_context !=
2985 curr->held_locks[depth-1].irq_context)
2986 goto out_bug;
2988 for (;;) {
2989 u16 distance = curr->lockdep_depth - depth + 1;
2990 hlock = curr->held_locks + depth - 1;
2992 if (hlock->check) {
2993 int ret = check_prev_add(curr, hlock, next, distance, &trace);
2994 if (!ret)
2995 return 0;
2998 * Stop after the first non-trylock entry,
2999 * as non-trylock entries have added their
3000 * own direct dependencies already, so this
3001 * lock is connected to them indirectly:
3003 if (!hlock->trylock)
3004 break;
3007 depth--;
3009 * End of lock-stack?
3011 if (!depth)
3012 break;
3014 * Stop the search if we cross into another context:
3016 if (curr->held_locks[depth].irq_context !=
3017 curr->held_locks[depth-1].irq_context)
3018 break;
3020 return 1;
3021 out_bug:
3022 if (!debug_locks_off_graph_unlock())
3023 return 0;
3026 * Clearly we all shouldn't be here, but since we made it we
3027 * can reliable say we messed up our state. See the above two
3028 * gotos for reasons why we could possibly end up here.
3030 WARN_ON(1);
3032 return 0;
3035 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
3036 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
3037 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
3038 unsigned long nr_zapped_lock_chains;
3039 unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */
3040 unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */
3041 unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */
3044 * The first 2 chain_hlocks entries in the chain block in the bucket
3045 * list contains the following meta data:
3047 * entry[0]:
3048 * Bit 15 - always set to 1 (it is not a class index)
3049 * Bits 0-14 - upper 15 bits of the next block index
3050 * entry[1] - lower 16 bits of next block index
3052 * A next block index of all 1 bits means it is the end of the list.
3054 * On the unsized bucket (bucket-0), the 3rd and 4th entries contain
3055 * the chain block size:
3057 * entry[2] - upper 16 bits of the chain block size
3058 * entry[3] - lower 16 bits of the chain block size
3060 #define MAX_CHAIN_BUCKETS 16
3061 #define CHAIN_BLK_FLAG (1U << 15)
3062 #define CHAIN_BLK_LIST_END 0xFFFFU
3064 static int chain_block_buckets[MAX_CHAIN_BUCKETS];
3066 static inline int size_to_bucket(int size)
3068 if (size > MAX_CHAIN_BUCKETS)
3069 return 0;
3071 return size - 1;
3075 * Iterate all the chain blocks in a bucket.
3077 #define for_each_chain_block(bucket, prev, curr) \
3078 for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \
3079 (curr) >= 0; \
3080 (prev) = (curr), (curr) = chain_block_next(curr))
3083 * next block or -1
3085 static inline int chain_block_next(int offset)
3087 int next = chain_hlocks[offset];
3089 WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG));
3091 if (next == CHAIN_BLK_LIST_END)
3092 return -1;
3094 next &= ~CHAIN_BLK_FLAG;
3095 next <<= 16;
3096 next |= chain_hlocks[offset + 1];
3098 return next;
3102 * bucket-0 only
3104 static inline int chain_block_size(int offset)
3106 return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3];
3109 static inline void init_chain_block(int offset, int next, int bucket, int size)
3111 chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG;
3112 chain_hlocks[offset + 1] = (u16)next;
3114 if (size && !bucket) {
3115 chain_hlocks[offset + 2] = size >> 16;
3116 chain_hlocks[offset + 3] = (u16)size;
3120 static inline void add_chain_block(int offset, int size)
3122 int bucket = size_to_bucket(size);
3123 int next = chain_block_buckets[bucket];
3124 int prev, curr;
3126 if (unlikely(size < 2)) {
3128 * We can't store single entries on the freelist. Leak them.
3130 * One possible way out would be to uniquely mark them, other
3131 * than with CHAIN_BLK_FLAG, such that we can recover them when
3132 * the block before it is re-added.
3134 if (size)
3135 nr_lost_chain_hlocks++;
3136 return;
3139 nr_free_chain_hlocks += size;
3140 if (!bucket) {
3141 nr_large_chain_blocks++;
3144 * Variable sized, sort large to small.
3146 for_each_chain_block(0, prev, curr) {
3147 if (size >= chain_block_size(curr))
3148 break;
3150 init_chain_block(offset, curr, 0, size);
3151 if (prev < 0)
3152 chain_block_buckets[0] = offset;
3153 else
3154 init_chain_block(prev, offset, 0, 0);
3155 return;
3158 * Fixed size, add to head.
3160 init_chain_block(offset, next, bucket, size);
3161 chain_block_buckets[bucket] = offset;
3165 * Only the first block in the list can be deleted.
3167 * For the variable size bucket[0], the first block (the largest one) is
3168 * returned, broken up and put back into the pool. So if a chain block of
3169 * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be
3170 * queued up after the primordial chain block and never be used until the
3171 * hlock entries in the primordial chain block is almost used up. That
3172 * causes fragmentation and reduce allocation efficiency. That can be
3173 * monitored by looking at the "large chain blocks" number in lockdep_stats.
3175 static inline void del_chain_block(int bucket, int size, int next)
3177 nr_free_chain_hlocks -= size;
3178 chain_block_buckets[bucket] = next;
3180 if (!bucket)
3181 nr_large_chain_blocks--;
3184 static void init_chain_block_buckets(void)
3186 int i;
3188 for (i = 0; i < MAX_CHAIN_BUCKETS; i++)
3189 chain_block_buckets[i] = -1;
3191 add_chain_block(0, ARRAY_SIZE(chain_hlocks));
3195 * Return offset of a chain block of the right size or -1 if not found.
3197 * Fairly simple worst-fit allocator with the addition of a number of size
3198 * specific free lists.
3200 static int alloc_chain_hlocks(int req)
3202 int bucket, curr, size;
3205 * We rely on the MSB to act as an escape bit to denote freelist
3206 * pointers. Make sure this bit isn't set in 'normal' class_idx usage.
3208 BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG);
3210 init_data_structures_once();
3212 if (nr_free_chain_hlocks < req)
3213 return -1;
3216 * We require a minimum of 2 (u16) entries to encode a freelist
3217 * 'pointer'.
3219 req = max(req, 2);
3220 bucket = size_to_bucket(req);
3221 curr = chain_block_buckets[bucket];
3223 if (bucket) {
3224 if (curr >= 0) {
3225 del_chain_block(bucket, req, chain_block_next(curr));
3226 return curr;
3228 /* Try bucket 0 */
3229 curr = chain_block_buckets[0];
3233 * The variable sized freelist is sorted by size; the first entry is
3234 * the largest. Use it if it fits.
3236 if (curr >= 0) {
3237 size = chain_block_size(curr);
3238 if (likely(size >= req)) {
3239 del_chain_block(0, size, chain_block_next(curr));
3240 add_chain_block(curr + req, size - req);
3241 return curr;
3246 * Last resort, split a block in a larger sized bucket.
3248 for (size = MAX_CHAIN_BUCKETS; size > req; size--) {
3249 bucket = size_to_bucket(size);
3250 curr = chain_block_buckets[bucket];
3251 if (curr < 0)
3252 continue;
3254 del_chain_block(bucket, size, chain_block_next(curr));
3255 add_chain_block(curr + req, size - req);
3256 return curr;
3259 return -1;
3262 static inline void free_chain_hlocks(int base, int size)
3264 add_chain_block(base, max(size, 2));
3267 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
3269 u16 chain_hlock = chain_hlocks[chain->base + i];
3270 unsigned int class_idx = chain_hlock_class_idx(chain_hlock);
3272 return lock_classes + class_idx - 1;
3276 * Returns the index of the first held_lock of the current chain
3278 static inline int get_first_held_lock(struct task_struct *curr,
3279 struct held_lock *hlock)
3281 int i;
3282 struct held_lock *hlock_curr;
3284 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
3285 hlock_curr = curr->held_locks + i;
3286 if (hlock_curr->irq_context != hlock->irq_context)
3287 break;
3291 return ++i;
3294 #ifdef CONFIG_DEBUG_LOCKDEP
3296 * Returns the next chain_key iteration
3298 static u64 print_chain_key_iteration(u16 hlock_id, u64 chain_key)
3300 u64 new_chain_key = iterate_chain_key(chain_key, hlock_id);
3302 printk(" hlock_id:%d -> chain_key:%016Lx",
3303 (unsigned int)hlock_id,
3304 (unsigned long long)new_chain_key);
3305 return new_chain_key;
3308 static void
3309 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
3311 struct held_lock *hlock;
3312 u64 chain_key = INITIAL_CHAIN_KEY;
3313 int depth = curr->lockdep_depth;
3314 int i = get_first_held_lock(curr, hlock_next);
3316 printk("depth: %u (irq_context %u)\n", depth - i + 1,
3317 hlock_next->irq_context);
3318 for (; i < depth; i++) {
3319 hlock = curr->held_locks + i;
3320 chain_key = print_chain_key_iteration(hlock_id(hlock), chain_key);
3322 print_lock(hlock);
3325 print_chain_key_iteration(hlock_id(hlock_next), chain_key);
3326 print_lock(hlock_next);
3329 static void print_chain_keys_chain(struct lock_chain *chain)
3331 int i;
3332 u64 chain_key = INITIAL_CHAIN_KEY;
3333 u16 hlock_id;
3335 printk("depth: %u\n", chain->depth);
3336 for (i = 0; i < chain->depth; i++) {
3337 hlock_id = chain_hlocks[chain->base + i];
3338 chain_key = print_chain_key_iteration(hlock_id, chain_key);
3340 print_lock_name(lock_classes + chain_hlock_class_idx(hlock_id) - 1);
3341 printk("\n");
3345 static void print_collision(struct task_struct *curr,
3346 struct held_lock *hlock_next,
3347 struct lock_chain *chain)
3349 pr_warn("\n");
3350 pr_warn("============================\n");
3351 pr_warn("WARNING: chain_key collision\n");
3352 print_kernel_ident();
3353 pr_warn("----------------------------\n");
3354 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
3355 pr_warn("Hash chain already cached but the contents don't match!\n");
3357 pr_warn("Held locks:");
3358 print_chain_keys_held_locks(curr, hlock_next);
3360 pr_warn("Locks in cached chain:");
3361 print_chain_keys_chain(chain);
3363 pr_warn("\nstack backtrace:\n");
3364 dump_stack();
3366 #endif
3369 * Checks whether the chain and the current held locks are consistent
3370 * in depth and also in content. If they are not it most likely means
3371 * that there was a collision during the calculation of the chain_key.
3372 * Returns: 0 not passed, 1 passed
3374 static int check_no_collision(struct task_struct *curr,
3375 struct held_lock *hlock,
3376 struct lock_chain *chain)
3378 #ifdef CONFIG_DEBUG_LOCKDEP
3379 int i, j, id;
3381 i = get_first_held_lock(curr, hlock);
3383 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
3384 print_collision(curr, hlock, chain);
3385 return 0;
3388 for (j = 0; j < chain->depth - 1; j++, i++) {
3389 id = hlock_id(&curr->held_locks[i]);
3391 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
3392 print_collision(curr, hlock, chain);
3393 return 0;
3396 #endif
3397 return 1;
3401 * Given an index that is >= -1, return the index of the next lock chain.
3402 * Return -2 if there is no next lock chain.
3404 long lockdep_next_lockchain(long i)
3406 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
3407 return i < ARRAY_SIZE(lock_chains) ? i : -2;
3410 unsigned long lock_chain_count(void)
3412 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
3415 /* Must be called with the graph lock held. */
3416 static struct lock_chain *alloc_lock_chain(void)
3418 int idx = find_first_zero_bit(lock_chains_in_use,
3419 ARRAY_SIZE(lock_chains));
3421 if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
3422 return NULL;
3423 __set_bit(idx, lock_chains_in_use);
3424 return lock_chains + idx;
3428 * Adds a dependency chain into chain hashtable. And must be called with
3429 * graph_lock held.
3431 * Return 0 if fail, and graph_lock is released.
3432 * Return 1 if succeed, with graph_lock held.
3434 static inline int add_chain_cache(struct task_struct *curr,
3435 struct held_lock *hlock,
3436 u64 chain_key)
3438 struct hlist_head *hash_head = chainhashentry(chain_key);
3439 struct lock_chain *chain;
3440 int i, j;
3443 * The caller must hold the graph lock, ensure we've got IRQs
3444 * disabled to make this an IRQ-safe lock.. for recursion reasons
3445 * lockdep won't complain about its own locking errors.
3447 if (lockdep_assert_locked())
3448 return 0;
3450 chain = alloc_lock_chain();
3451 if (!chain) {
3452 if (!debug_locks_off_graph_unlock())
3453 return 0;
3455 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
3456 dump_stack();
3457 return 0;
3459 chain->chain_key = chain_key;
3460 chain->irq_context = hlock->irq_context;
3461 i = get_first_held_lock(curr, hlock);
3462 chain->depth = curr->lockdep_depth + 1 - i;
3464 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
3465 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
3466 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
3468 j = alloc_chain_hlocks(chain->depth);
3469 if (j < 0) {
3470 if (!debug_locks_off_graph_unlock())
3471 return 0;
3473 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
3474 dump_stack();
3475 return 0;
3478 chain->base = j;
3479 for (j = 0; j < chain->depth - 1; j++, i++) {
3480 int lock_id = hlock_id(curr->held_locks + i);
3482 chain_hlocks[chain->base + j] = lock_id;
3484 chain_hlocks[chain->base + j] = hlock_id(hlock);
3485 hlist_add_head_rcu(&chain->entry, hash_head);
3486 debug_atomic_inc(chain_lookup_misses);
3487 inc_chains(chain->irq_context);
3489 return 1;
3493 * Look up a dependency chain. Must be called with either the graph lock or
3494 * the RCU read lock held.
3496 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
3498 struct hlist_head *hash_head = chainhashentry(chain_key);
3499 struct lock_chain *chain;
3501 hlist_for_each_entry_rcu(chain, hash_head, entry) {
3502 if (READ_ONCE(chain->chain_key) == chain_key) {
3503 debug_atomic_inc(chain_lookup_hits);
3504 return chain;
3507 return NULL;
3511 * If the key is not present yet in dependency chain cache then
3512 * add it and return 1 - in this case the new dependency chain is
3513 * validated. If the key is already hashed, return 0.
3514 * (On return with 1 graph_lock is held.)
3516 static inline int lookup_chain_cache_add(struct task_struct *curr,
3517 struct held_lock *hlock,
3518 u64 chain_key)
3520 struct lock_class *class = hlock_class(hlock);
3521 struct lock_chain *chain = lookup_chain_cache(chain_key);
3523 if (chain) {
3524 cache_hit:
3525 if (!check_no_collision(curr, hlock, chain))
3526 return 0;
3528 if (very_verbose(class)) {
3529 printk("\nhash chain already cached, key: "
3530 "%016Lx tail class: [%px] %s\n",
3531 (unsigned long long)chain_key,
3532 class->key, class->name);
3535 return 0;
3538 if (very_verbose(class)) {
3539 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
3540 (unsigned long long)chain_key, class->key, class->name);
3543 if (!graph_lock())
3544 return 0;
3547 * We have to walk the chain again locked - to avoid duplicates:
3549 chain = lookup_chain_cache(chain_key);
3550 if (chain) {
3551 graph_unlock();
3552 goto cache_hit;
3555 if (!add_chain_cache(curr, hlock, chain_key))
3556 return 0;
3558 return 1;
3561 static int validate_chain(struct task_struct *curr,
3562 struct held_lock *hlock,
3563 int chain_head, u64 chain_key)
3566 * Trylock needs to maintain the stack of held locks, but it
3567 * does not add new dependencies, because trylock can be done
3568 * in any order.
3570 * We look up the chain_key and do the O(N^2) check and update of
3571 * the dependencies only if this is a new dependency chain.
3572 * (If lookup_chain_cache_add() return with 1 it acquires
3573 * graph_lock for us)
3575 if (!hlock->trylock && hlock->check &&
3576 lookup_chain_cache_add(curr, hlock, chain_key)) {
3578 * Check whether last held lock:
3580 * - is irq-safe, if this lock is irq-unsafe
3581 * - is softirq-safe, if this lock is hardirq-unsafe
3583 * And check whether the new lock's dependency graph
3584 * could lead back to the previous lock:
3586 * - within the current held-lock stack
3587 * - across our accumulated lock dependency records
3589 * any of these scenarios could lead to a deadlock.
3592 * The simple case: does the current hold the same lock
3593 * already?
3595 int ret = check_deadlock(curr, hlock);
3597 if (!ret)
3598 return 0;
3600 * Add dependency only if this lock is not the head
3601 * of the chain, and if the new lock introduces no more
3602 * lock dependency (because we already hold a lock with the
3603 * same lock class) nor deadlock (because the nest_lock
3604 * serializes nesting locks), see the comments for
3605 * check_deadlock().
3607 if (!chain_head && ret != 2) {
3608 if (!check_prevs_add(curr, hlock))
3609 return 0;
3612 graph_unlock();
3613 } else {
3614 /* after lookup_chain_cache_add(): */
3615 if (unlikely(!debug_locks))
3616 return 0;
3619 return 1;
3621 #else
3622 static inline int validate_chain(struct task_struct *curr,
3623 struct held_lock *hlock,
3624 int chain_head, u64 chain_key)
3626 return 1;
3629 static void init_chain_block_buckets(void) { }
3630 #endif /* CONFIG_PROVE_LOCKING */
3633 * We are building curr_chain_key incrementally, so double-check
3634 * it from scratch, to make sure that it's done correctly:
3636 static void check_chain_key(struct task_struct *curr)
3638 #ifdef CONFIG_DEBUG_LOCKDEP
3639 struct held_lock *hlock, *prev_hlock = NULL;
3640 unsigned int i;
3641 u64 chain_key = INITIAL_CHAIN_KEY;
3643 for (i = 0; i < curr->lockdep_depth; i++) {
3644 hlock = curr->held_locks + i;
3645 if (chain_key != hlock->prev_chain_key) {
3646 debug_locks_off();
3648 * We got mighty confused, our chain keys don't match
3649 * with what we expect, someone trample on our task state?
3651 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
3652 curr->lockdep_depth, i,
3653 (unsigned long long)chain_key,
3654 (unsigned long long)hlock->prev_chain_key);
3655 return;
3659 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
3660 * it registered lock class index?
3662 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
3663 return;
3665 if (prev_hlock && (prev_hlock->irq_context !=
3666 hlock->irq_context))
3667 chain_key = INITIAL_CHAIN_KEY;
3668 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
3669 prev_hlock = hlock;
3671 if (chain_key != curr->curr_chain_key) {
3672 debug_locks_off();
3674 * More smoking hash instead of calculating it, damn see these
3675 * numbers float.. I bet that a pink elephant stepped on my memory.
3677 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
3678 curr->lockdep_depth, i,
3679 (unsigned long long)chain_key,
3680 (unsigned long long)curr->curr_chain_key);
3682 #endif
3685 #ifdef CONFIG_PROVE_LOCKING
3686 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3687 enum lock_usage_bit new_bit);
3689 static void print_usage_bug_scenario(struct held_lock *lock)
3691 struct lock_class *class = hlock_class(lock);
3693 printk(" Possible unsafe locking scenario:\n\n");
3694 printk(" CPU0\n");
3695 printk(" ----\n");
3696 printk(" lock(");
3697 __print_lock_name(class);
3698 printk(KERN_CONT ");\n");
3699 printk(" <Interrupt>\n");
3700 printk(" lock(");
3701 __print_lock_name(class);
3702 printk(KERN_CONT ");\n");
3703 printk("\n *** DEADLOCK ***\n\n");
3706 static void
3707 print_usage_bug(struct task_struct *curr, struct held_lock *this,
3708 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
3710 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3711 return;
3713 pr_warn("\n");
3714 pr_warn("================================\n");
3715 pr_warn("WARNING: inconsistent lock state\n");
3716 print_kernel_ident();
3717 pr_warn("--------------------------------\n");
3719 pr_warn("inconsistent {%s} -> {%s} usage.\n",
3720 usage_str[prev_bit], usage_str[new_bit]);
3722 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
3723 curr->comm, task_pid_nr(curr),
3724 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
3725 lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
3726 lockdep_hardirqs_enabled(),
3727 lockdep_softirqs_enabled(curr));
3728 print_lock(this);
3730 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
3731 print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1);
3733 print_irqtrace_events(curr);
3734 pr_warn("\nother info that might help us debug this:\n");
3735 print_usage_bug_scenario(this);
3737 lockdep_print_held_locks(curr);
3739 pr_warn("\nstack backtrace:\n");
3740 dump_stack();
3744 * Print out an error if an invalid bit is set:
3746 static inline int
3747 valid_state(struct task_struct *curr, struct held_lock *this,
3748 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
3750 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
3751 print_usage_bug(curr, this, bad_bit, new_bit);
3752 return 0;
3754 return 1;
3759 * print irq inversion bug:
3761 static void
3762 print_irq_inversion_bug(struct task_struct *curr,
3763 struct lock_list *root, struct lock_list *other,
3764 struct held_lock *this, int forwards,
3765 const char *irqclass)
3767 struct lock_list *entry = other;
3768 struct lock_list *middle = NULL;
3769 int depth;
3771 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3772 return;
3774 pr_warn("\n");
3775 pr_warn("========================================================\n");
3776 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
3777 print_kernel_ident();
3778 pr_warn("--------------------------------------------------------\n");
3779 pr_warn("%s/%d just changed the state of lock:\n",
3780 curr->comm, task_pid_nr(curr));
3781 print_lock(this);
3782 if (forwards)
3783 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
3784 else
3785 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
3786 print_lock_name(other->class);
3787 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
3789 pr_warn("\nother info that might help us debug this:\n");
3791 /* Find a middle lock (if one exists) */
3792 depth = get_lock_depth(other);
3793 do {
3794 if (depth == 0 && (entry != root)) {
3795 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
3796 break;
3798 middle = entry;
3799 entry = get_lock_parent(entry);
3800 depth--;
3801 } while (entry && entry != root && (depth >= 0));
3802 if (forwards)
3803 print_irq_lock_scenario(root, other,
3804 middle ? middle->class : root->class, other->class);
3805 else
3806 print_irq_lock_scenario(other, root,
3807 middle ? middle->class : other->class, root->class);
3809 lockdep_print_held_locks(curr);
3811 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
3812 root->trace = save_trace();
3813 if (!root->trace)
3814 return;
3815 print_shortest_lock_dependencies(other, root);
3817 pr_warn("\nstack backtrace:\n");
3818 dump_stack();
3822 * Prove that in the forwards-direction subgraph starting at <this>
3823 * there is no lock matching <mask>:
3825 static int
3826 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
3827 enum lock_usage_bit bit)
3829 enum bfs_result ret;
3830 struct lock_list root;
3831 struct lock_list *target_entry;
3832 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
3833 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
3835 bfs_init_root(&root, this);
3836 ret = find_usage_forwards(&root, usage_mask, &target_entry);
3837 if (bfs_error(ret)) {
3838 print_bfs_bug(ret);
3839 return 0;
3841 if (ret == BFS_RNOMATCH)
3842 return 1;
3844 /* Check whether write or read usage is the match */
3845 if (target_entry->class->usage_mask & lock_flag(bit)) {
3846 print_irq_inversion_bug(curr, &root, target_entry,
3847 this, 1, state_name(bit));
3848 } else {
3849 print_irq_inversion_bug(curr, &root, target_entry,
3850 this, 1, state_name(read_bit));
3853 return 0;
3857 * Prove that in the backwards-direction subgraph starting at <this>
3858 * there is no lock matching <mask>:
3860 static int
3861 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
3862 enum lock_usage_bit bit)
3864 enum bfs_result ret;
3865 struct lock_list root;
3866 struct lock_list *target_entry;
3867 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
3868 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
3870 bfs_init_rootb(&root, this);
3871 ret = find_usage_backwards(&root, usage_mask, &target_entry);
3872 if (bfs_error(ret)) {
3873 print_bfs_bug(ret);
3874 return 0;
3876 if (ret == BFS_RNOMATCH)
3877 return 1;
3879 /* Check whether write or read usage is the match */
3880 if (target_entry->class->usage_mask & lock_flag(bit)) {
3881 print_irq_inversion_bug(curr, &root, target_entry,
3882 this, 0, state_name(bit));
3883 } else {
3884 print_irq_inversion_bug(curr, &root, target_entry,
3885 this, 0, state_name(read_bit));
3888 return 0;
3891 void print_irqtrace_events(struct task_struct *curr)
3893 const struct irqtrace_events *trace = &curr->irqtrace;
3895 printk("irq event stamp: %u\n", trace->irq_events);
3896 printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
3897 trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip,
3898 (void *)trace->hardirq_enable_ip);
3899 printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
3900 trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip,
3901 (void *)trace->hardirq_disable_ip);
3902 printk("softirqs last enabled at (%u): [<%px>] %pS\n",
3903 trace->softirq_enable_event, (void *)trace->softirq_enable_ip,
3904 (void *)trace->softirq_enable_ip);
3905 printk("softirqs last disabled at (%u): [<%px>] %pS\n",
3906 trace->softirq_disable_event, (void *)trace->softirq_disable_ip,
3907 (void *)trace->softirq_disable_ip);
3910 static int HARDIRQ_verbose(struct lock_class *class)
3912 #if HARDIRQ_VERBOSE
3913 return class_filter(class);
3914 #endif
3915 return 0;
3918 static int SOFTIRQ_verbose(struct lock_class *class)
3920 #if SOFTIRQ_VERBOSE
3921 return class_filter(class);
3922 #endif
3923 return 0;
3926 static int (*state_verbose_f[])(struct lock_class *class) = {
3927 #define LOCKDEP_STATE(__STATE) \
3928 __STATE##_verbose,
3929 #include "lockdep_states.h"
3930 #undef LOCKDEP_STATE
3933 static inline int state_verbose(enum lock_usage_bit bit,
3934 struct lock_class *class)
3936 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
3939 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
3940 enum lock_usage_bit bit, const char *name);
3942 static int
3943 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
3944 enum lock_usage_bit new_bit)
3946 int excl_bit = exclusive_bit(new_bit);
3947 int read = new_bit & LOCK_USAGE_READ_MASK;
3948 int dir = new_bit & LOCK_USAGE_DIR_MASK;
3951 * Validate that this particular lock does not have conflicting
3952 * usage states.
3954 if (!valid_state(curr, this, new_bit, excl_bit))
3955 return 0;
3958 * Check for read in write conflicts
3960 if (!read && !valid_state(curr, this, new_bit,
3961 excl_bit + LOCK_USAGE_READ_MASK))
3962 return 0;
3966 * Validate that the lock dependencies don't have conflicting usage
3967 * states.
3969 if (dir) {
3971 * mark ENABLED has to look backwards -- to ensure no dependee
3972 * has USED_IN state, which, again, would allow recursion deadlocks.
3974 if (!check_usage_backwards(curr, this, excl_bit))
3975 return 0;
3976 } else {
3978 * mark USED_IN has to look forwards -- to ensure no dependency
3979 * has ENABLED state, which would allow recursion deadlocks.
3981 if (!check_usage_forwards(curr, this, excl_bit))
3982 return 0;
3985 if (state_verbose(new_bit, hlock_class(this)))
3986 return 2;
3988 return 1;
3992 * Mark all held locks with a usage bit:
3994 static int
3995 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
3997 struct held_lock *hlock;
3998 int i;
4000 for (i = 0; i < curr->lockdep_depth; i++) {
4001 enum lock_usage_bit hlock_bit = base_bit;
4002 hlock = curr->held_locks + i;
4004 if (hlock->read)
4005 hlock_bit += LOCK_USAGE_READ_MASK;
4007 BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
4009 if (!hlock->check)
4010 continue;
4012 if (!mark_lock(curr, hlock, hlock_bit))
4013 return 0;
4016 return 1;
4020 * Hardirqs will be enabled:
4022 static void __trace_hardirqs_on_caller(void)
4024 struct task_struct *curr = current;
4027 * We are going to turn hardirqs on, so set the
4028 * usage bit for all held locks:
4030 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
4031 return;
4033 * If we have softirqs enabled, then set the usage
4034 * bit for all held locks. (disabled hardirqs prevented
4035 * this bit from being set before)
4037 if (curr->softirqs_enabled)
4038 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
4042 * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts
4043 * @ip: Caller address
4045 * Invoked before a possible transition to RCU idle from exit to user or
4046 * guest mode. This ensures that all RCU operations are done before RCU
4047 * stops watching. After the RCU transition lockdep_hardirqs_on() has to be
4048 * invoked to set the final state.
4050 void lockdep_hardirqs_on_prepare(unsigned long ip)
4052 if (unlikely(!debug_locks))
4053 return;
4056 * NMIs do not (and cannot) track lock dependencies, nothing to do.
4058 if (unlikely(in_nmi()))
4059 return;
4061 if (unlikely(this_cpu_read(lockdep_recursion)))
4062 return;
4064 if (unlikely(lockdep_hardirqs_enabled())) {
4066 * Neither irq nor preemption are disabled here
4067 * so this is racy by nature but losing one hit
4068 * in a stat is not a big deal.
4070 __debug_atomic_inc(redundant_hardirqs_on);
4071 return;
4075 * We're enabling irqs and according to our state above irqs weren't
4076 * already enabled, yet we find the hardware thinks they are in fact
4077 * enabled.. someone messed up their IRQ state tracing.
4079 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4080 return;
4083 * See the fine text that goes along with this variable definition.
4085 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
4086 return;
4089 * Can't allow enabling interrupts while in an interrupt handler,
4090 * that's general bad form and such. Recursion, limited stack etc..
4092 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context()))
4093 return;
4095 current->hardirq_chain_key = current->curr_chain_key;
4097 lockdep_recursion_inc();
4098 __trace_hardirqs_on_caller();
4099 lockdep_recursion_finish();
4101 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare);
4103 void noinstr lockdep_hardirqs_on(unsigned long ip)
4105 struct irqtrace_events *trace = &current->irqtrace;
4107 if (unlikely(!debug_locks))
4108 return;
4111 * NMIs can happen in the middle of local_irq_{en,dis}able() where the
4112 * tracking state and hardware state are out of sync.
4114 * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from,
4115 * and not rely on hardware state like normal interrupts.
4117 if (unlikely(in_nmi())) {
4118 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4119 return;
4122 * Skip:
4123 * - recursion check, because NMI can hit lockdep;
4124 * - hardware state check, because above;
4125 * - chain_key check, see lockdep_hardirqs_on_prepare().
4127 goto skip_checks;
4130 if (unlikely(this_cpu_read(lockdep_recursion)))
4131 return;
4133 if (lockdep_hardirqs_enabled()) {
4135 * Neither irq nor preemption are disabled here
4136 * so this is racy by nature but losing one hit
4137 * in a stat is not a big deal.
4139 __debug_atomic_inc(redundant_hardirqs_on);
4140 return;
4144 * We're enabling irqs and according to our state above irqs weren't
4145 * already enabled, yet we find the hardware thinks they are in fact
4146 * enabled.. someone messed up their IRQ state tracing.
4148 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4149 return;
4152 * Ensure the lock stack remained unchanged between
4153 * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on().
4155 DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key !=
4156 current->curr_chain_key);
4158 skip_checks:
4159 /* we'll do an OFF -> ON transition: */
4160 __this_cpu_write(hardirqs_enabled, 1);
4161 trace->hardirq_enable_ip = ip;
4162 trace->hardirq_enable_event = ++trace->irq_events;
4163 debug_atomic_inc(hardirqs_on_events);
4165 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on);
4168 * Hardirqs were disabled:
4170 void noinstr lockdep_hardirqs_off(unsigned long ip)
4172 if (unlikely(!debug_locks))
4173 return;
4176 * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep;
4177 * they will restore the software state. This ensures the software
4178 * state is consistent inside NMIs as well.
4180 if (in_nmi()) {
4181 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4182 return;
4183 } else if (__this_cpu_read(lockdep_recursion))
4184 return;
4187 * So we're supposed to get called after you mask local IRQs, but for
4188 * some reason the hardware doesn't quite think you did a proper job.
4190 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4191 return;
4193 if (lockdep_hardirqs_enabled()) {
4194 struct irqtrace_events *trace = &current->irqtrace;
4197 * We have done an ON -> OFF transition:
4199 __this_cpu_write(hardirqs_enabled, 0);
4200 trace->hardirq_disable_ip = ip;
4201 trace->hardirq_disable_event = ++trace->irq_events;
4202 debug_atomic_inc(hardirqs_off_events);
4203 } else {
4204 debug_atomic_inc(redundant_hardirqs_off);
4207 EXPORT_SYMBOL_GPL(lockdep_hardirqs_off);
4210 * Softirqs will be enabled:
4212 void lockdep_softirqs_on(unsigned long ip)
4214 struct irqtrace_events *trace = &current->irqtrace;
4216 if (unlikely(!lockdep_enabled()))
4217 return;
4220 * We fancy IRQs being disabled here, see softirq.c, avoids
4221 * funny state and nesting things.
4223 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4224 return;
4226 if (current->softirqs_enabled) {
4227 debug_atomic_inc(redundant_softirqs_on);
4228 return;
4231 lockdep_recursion_inc();
4233 * We'll do an OFF -> ON transition:
4235 current->softirqs_enabled = 1;
4236 trace->softirq_enable_ip = ip;
4237 trace->softirq_enable_event = ++trace->irq_events;
4238 debug_atomic_inc(softirqs_on_events);
4240 * We are going to turn softirqs on, so set the
4241 * usage bit for all held locks, if hardirqs are
4242 * enabled too:
4244 if (lockdep_hardirqs_enabled())
4245 mark_held_locks(current, LOCK_ENABLED_SOFTIRQ);
4246 lockdep_recursion_finish();
4250 * Softirqs were disabled:
4252 void lockdep_softirqs_off(unsigned long ip)
4254 if (unlikely(!lockdep_enabled()))
4255 return;
4258 * We fancy IRQs being disabled here, see softirq.c
4260 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4261 return;
4263 if (current->softirqs_enabled) {
4264 struct irqtrace_events *trace = &current->irqtrace;
4267 * We have done an ON -> OFF transition:
4269 current->softirqs_enabled = 0;
4270 trace->softirq_disable_ip = ip;
4271 trace->softirq_disable_event = ++trace->irq_events;
4272 debug_atomic_inc(softirqs_off_events);
4274 * Whoops, we wanted softirqs off, so why aren't they?
4276 DEBUG_LOCKS_WARN_ON(!softirq_count());
4277 } else
4278 debug_atomic_inc(redundant_softirqs_off);
4281 static int
4282 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4284 if (!check)
4285 goto lock_used;
4288 * If non-trylock use in a hardirq or softirq context, then
4289 * mark the lock as used in these contexts:
4291 if (!hlock->trylock) {
4292 if (hlock->read) {
4293 if (lockdep_hardirq_context())
4294 if (!mark_lock(curr, hlock,
4295 LOCK_USED_IN_HARDIRQ_READ))
4296 return 0;
4297 if (curr->softirq_context)
4298 if (!mark_lock(curr, hlock,
4299 LOCK_USED_IN_SOFTIRQ_READ))
4300 return 0;
4301 } else {
4302 if (lockdep_hardirq_context())
4303 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
4304 return 0;
4305 if (curr->softirq_context)
4306 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
4307 return 0;
4310 if (!hlock->hardirqs_off) {
4311 if (hlock->read) {
4312 if (!mark_lock(curr, hlock,
4313 LOCK_ENABLED_HARDIRQ_READ))
4314 return 0;
4315 if (curr->softirqs_enabled)
4316 if (!mark_lock(curr, hlock,
4317 LOCK_ENABLED_SOFTIRQ_READ))
4318 return 0;
4319 } else {
4320 if (!mark_lock(curr, hlock,
4321 LOCK_ENABLED_HARDIRQ))
4322 return 0;
4323 if (curr->softirqs_enabled)
4324 if (!mark_lock(curr, hlock,
4325 LOCK_ENABLED_SOFTIRQ))
4326 return 0;
4330 lock_used:
4331 /* mark it as used: */
4332 if (!mark_lock(curr, hlock, LOCK_USED))
4333 return 0;
4335 return 1;
4338 static inline unsigned int task_irq_context(struct task_struct *task)
4340 return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() +
4341 LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context;
4344 static int separate_irq_context(struct task_struct *curr,
4345 struct held_lock *hlock)
4347 unsigned int depth = curr->lockdep_depth;
4350 * Keep track of points where we cross into an interrupt context:
4352 if (depth) {
4353 struct held_lock *prev_hlock;
4355 prev_hlock = curr->held_locks + depth-1;
4357 * If we cross into another context, reset the
4358 * hash key (this also prevents the checking and the
4359 * adding of the dependency to 'prev'):
4361 if (prev_hlock->irq_context != hlock->irq_context)
4362 return 1;
4364 return 0;
4368 * Mark a lock with a usage bit, and validate the state transition:
4370 static int mark_lock(struct task_struct *curr, struct held_lock *this,
4371 enum lock_usage_bit new_bit)
4373 unsigned int new_mask, ret = 1;
4375 if (new_bit >= LOCK_USAGE_STATES) {
4376 DEBUG_LOCKS_WARN_ON(1);
4377 return 0;
4380 if (new_bit == LOCK_USED && this->read)
4381 new_bit = LOCK_USED_READ;
4383 new_mask = 1 << new_bit;
4386 * If already set then do not dirty the cacheline,
4387 * nor do any checks:
4389 if (likely(hlock_class(this)->usage_mask & new_mask))
4390 return 1;
4392 if (!graph_lock())
4393 return 0;
4395 * Make sure we didn't race:
4397 if (unlikely(hlock_class(this)->usage_mask & new_mask))
4398 goto unlock;
4400 if (!hlock_class(this)->usage_mask)
4401 debug_atomic_dec(nr_unused_locks);
4403 hlock_class(this)->usage_mask |= new_mask;
4405 if (new_bit < LOCK_TRACE_STATES) {
4406 if (!(hlock_class(this)->usage_traces[new_bit] = save_trace()))
4407 return 0;
4410 if (new_bit < LOCK_USED) {
4411 ret = mark_lock_irq(curr, this, new_bit);
4412 if (!ret)
4413 return 0;
4416 unlock:
4417 graph_unlock();
4420 * We must printk outside of the graph_lock:
4422 if (ret == 2) {
4423 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
4424 print_lock(this);
4425 print_irqtrace_events(curr);
4426 dump_stack();
4429 return ret;
4432 static inline short task_wait_context(struct task_struct *curr)
4435 * Set appropriate wait type for the context; for IRQs we have to take
4436 * into account force_irqthread as that is implied by PREEMPT_RT.
4438 if (lockdep_hardirq_context()) {
4440 * Check if force_irqthreads will run us threaded.
4442 if (curr->hardirq_threaded || curr->irq_config)
4443 return LD_WAIT_CONFIG;
4445 return LD_WAIT_SPIN;
4446 } else if (curr->softirq_context) {
4448 * Softirqs are always threaded.
4450 return LD_WAIT_CONFIG;
4453 return LD_WAIT_MAX;
4456 static int
4457 print_lock_invalid_wait_context(struct task_struct *curr,
4458 struct held_lock *hlock)
4460 short curr_inner;
4462 if (!debug_locks_off())
4463 return 0;
4464 if (debug_locks_silent)
4465 return 0;
4467 pr_warn("\n");
4468 pr_warn("=============================\n");
4469 pr_warn("[ BUG: Invalid wait context ]\n");
4470 print_kernel_ident();
4471 pr_warn("-----------------------------\n");
4473 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4474 print_lock(hlock);
4476 pr_warn("other info that might help us debug this:\n");
4478 curr_inner = task_wait_context(curr);
4479 pr_warn("context-{%d:%d}\n", curr_inner, curr_inner);
4481 lockdep_print_held_locks(curr);
4483 pr_warn("stack backtrace:\n");
4484 dump_stack();
4486 return 0;
4490 * Verify the wait_type context.
4492 * This check validates we takes locks in the right wait-type order; that is it
4493 * ensures that we do not take mutexes inside spinlocks and do not attempt to
4494 * acquire spinlocks inside raw_spinlocks and the sort.
4496 * The entire thing is slightly more complex because of RCU, RCU is a lock that
4497 * can be taken from (pretty much) any context but also has constraints.
4498 * However when taken in a stricter environment the RCU lock does not loosen
4499 * the constraints.
4501 * Therefore we must look for the strictest environment in the lock stack and
4502 * compare that to the lock we're trying to acquire.
4504 static int check_wait_context(struct task_struct *curr, struct held_lock *next)
4506 short next_inner = hlock_class(next)->wait_type_inner;
4507 short next_outer = hlock_class(next)->wait_type_outer;
4508 short curr_inner;
4509 int depth;
4511 if (!curr->lockdep_depth || !next_inner || next->trylock)
4512 return 0;
4514 if (!next_outer)
4515 next_outer = next_inner;
4518 * Find start of current irq_context..
4520 for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) {
4521 struct held_lock *prev = curr->held_locks + depth;
4522 if (prev->irq_context != next->irq_context)
4523 break;
4525 depth++;
4527 curr_inner = task_wait_context(curr);
4529 for (; depth < curr->lockdep_depth; depth++) {
4530 struct held_lock *prev = curr->held_locks + depth;
4531 short prev_inner = hlock_class(prev)->wait_type_inner;
4533 if (prev_inner) {
4535 * We can have a bigger inner than a previous one
4536 * when outer is smaller than inner, as with RCU.
4538 * Also due to trylocks.
4540 curr_inner = min(curr_inner, prev_inner);
4544 if (next_outer > curr_inner)
4545 return print_lock_invalid_wait_context(curr, next);
4547 return 0;
4550 #else /* CONFIG_PROVE_LOCKING */
4552 static inline int
4553 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4555 return 1;
4558 static inline unsigned int task_irq_context(struct task_struct *task)
4560 return 0;
4563 static inline int separate_irq_context(struct task_struct *curr,
4564 struct held_lock *hlock)
4566 return 0;
4569 static inline int check_wait_context(struct task_struct *curr,
4570 struct held_lock *next)
4572 return 0;
4575 #endif /* CONFIG_PROVE_LOCKING */
4578 * Initialize a lock instance's lock-class mapping info:
4580 void lockdep_init_map_waits(struct lockdep_map *lock, const char *name,
4581 struct lock_class_key *key, int subclass,
4582 short inner, short outer)
4584 int i;
4586 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
4587 lock->class_cache[i] = NULL;
4589 #ifdef CONFIG_LOCK_STAT
4590 lock->cpu = raw_smp_processor_id();
4591 #endif
4594 * Can't be having no nameless bastards around this place!
4596 if (DEBUG_LOCKS_WARN_ON(!name)) {
4597 lock->name = "NULL";
4598 return;
4601 lock->name = name;
4603 lock->wait_type_outer = outer;
4604 lock->wait_type_inner = inner;
4607 * No key, no joy, we need to hash something.
4609 if (DEBUG_LOCKS_WARN_ON(!key))
4610 return;
4612 * Sanity check, the lock-class key must either have been allocated
4613 * statically or must have been registered as a dynamic key.
4615 if (!static_obj(key) && !is_dynamic_key(key)) {
4616 if (debug_locks)
4617 printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
4618 DEBUG_LOCKS_WARN_ON(1);
4619 return;
4621 lock->key = key;
4623 if (unlikely(!debug_locks))
4624 return;
4626 if (subclass) {
4627 unsigned long flags;
4629 if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled()))
4630 return;
4632 raw_local_irq_save(flags);
4633 lockdep_recursion_inc();
4634 register_lock_class(lock, subclass, 1);
4635 lockdep_recursion_finish();
4636 raw_local_irq_restore(flags);
4639 EXPORT_SYMBOL_GPL(lockdep_init_map_waits);
4641 struct lock_class_key __lockdep_no_validate__;
4642 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
4644 static void
4645 print_lock_nested_lock_not_held(struct task_struct *curr,
4646 struct held_lock *hlock,
4647 unsigned long ip)
4649 if (!debug_locks_off())
4650 return;
4651 if (debug_locks_silent)
4652 return;
4654 pr_warn("\n");
4655 pr_warn("==================================\n");
4656 pr_warn("WARNING: Nested lock was not taken\n");
4657 print_kernel_ident();
4658 pr_warn("----------------------------------\n");
4660 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4661 print_lock(hlock);
4663 pr_warn("\nbut this task is not holding:\n");
4664 pr_warn("%s\n", hlock->nest_lock->name);
4666 pr_warn("\nstack backtrace:\n");
4667 dump_stack();
4669 pr_warn("\nother info that might help us debug this:\n");
4670 lockdep_print_held_locks(curr);
4672 pr_warn("\nstack backtrace:\n");
4673 dump_stack();
4676 static int __lock_is_held(const struct lockdep_map *lock, int read);
4679 * This gets called for every mutex_lock*()/spin_lock*() operation.
4680 * We maintain the dependency maps and validate the locking attempt:
4682 * The callers must make sure that IRQs are disabled before calling it,
4683 * otherwise we could get an interrupt which would want to take locks,
4684 * which would end up in lockdep again.
4686 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
4687 int trylock, int read, int check, int hardirqs_off,
4688 struct lockdep_map *nest_lock, unsigned long ip,
4689 int references, int pin_count)
4691 struct task_struct *curr = current;
4692 struct lock_class *class = NULL;
4693 struct held_lock *hlock;
4694 unsigned int depth;
4695 int chain_head = 0;
4696 int class_idx;
4697 u64 chain_key;
4699 if (unlikely(!debug_locks))
4700 return 0;
4702 if (!prove_locking || lock->key == &__lockdep_no_validate__)
4703 check = 0;
4705 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
4706 class = lock->class_cache[subclass];
4708 * Not cached?
4710 if (unlikely(!class)) {
4711 class = register_lock_class(lock, subclass, 0);
4712 if (!class)
4713 return 0;
4716 debug_class_ops_inc(class);
4718 if (very_verbose(class)) {
4719 printk("\nacquire class [%px] %s", class->key, class->name);
4720 if (class->name_version > 1)
4721 printk(KERN_CONT "#%d", class->name_version);
4722 printk(KERN_CONT "\n");
4723 dump_stack();
4727 * Add the lock to the list of currently held locks.
4728 * (we dont increase the depth just yet, up until the
4729 * dependency checks are done)
4731 depth = curr->lockdep_depth;
4733 * Ran out of static storage for our per-task lock stack again have we?
4735 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
4736 return 0;
4738 class_idx = class - lock_classes;
4740 if (depth) { /* we're holding locks */
4741 hlock = curr->held_locks + depth - 1;
4742 if (hlock->class_idx == class_idx && nest_lock) {
4743 if (!references)
4744 references++;
4746 if (!hlock->references)
4747 hlock->references++;
4749 hlock->references += references;
4751 /* Overflow */
4752 if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
4753 return 0;
4755 return 2;
4759 hlock = curr->held_locks + depth;
4761 * Plain impossible, we just registered it and checked it weren't no
4762 * NULL like.. I bet this mushroom I ate was good!
4764 if (DEBUG_LOCKS_WARN_ON(!class))
4765 return 0;
4766 hlock->class_idx = class_idx;
4767 hlock->acquire_ip = ip;
4768 hlock->instance = lock;
4769 hlock->nest_lock = nest_lock;
4770 hlock->irq_context = task_irq_context(curr);
4771 hlock->trylock = trylock;
4772 hlock->read = read;
4773 hlock->check = check;
4774 hlock->hardirqs_off = !!hardirqs_off;
4775 hlock->references = references;
4776 #ifdef CONFIG_LOCK_STAT
4777 hlock->waittime_stamp = 0;
4778 hlock->holdtime_stamp = lockstat_clock();
4779 #endif
4780 hlock->pin_count = pin_count;
4782 if (check_wait_context(curr, hlock))
4783 return 0;
4785 /* Initialize the lock usage bit */
4786 if (!mark_usage(curr, hlock, check))
4787 return 0;
4790 * Calculate the chain hash: it's the combined hash of all the
4791 * lock keys along the dependency chain. We save the hash value
4792 * at every step so that we can get the current hash easily
4793 * after unlock. The chain hash is then used to cache dependency
4794 * results.
4796 * The 'key ID' is what is the most compact key value to drive
4797 * the hash, not class->key.
4800 * Whoops, we did it again.. class_idx is invalid.
4802 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
4803 return 0;
4805 chain_key = curr->curr_chain_key;
4806 if (!depth) {
4808 * How can we have a chain hash when we ain't got no keys?!
4810 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
4811 return 0;
4812 chain_head = 1;
4815 hlock->prev_chain_key = chain_key;
4816 if (separate_irq_context(curr, hlock)) {
4817 chain_key = INITIAL_CHAIN_KEY;
4818 chain_head = 1;
4820 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
4822 if (nest_lock && !__lock_is_held(nest_lock, -1)) {
4823 print_lock_nested_lock_not_held(curr, hlock, ip);
4824 return 0;
4827 if (!debug_locks_silent) {
4828 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
4829 WARN_ON_ONCE(!hlock_class(hlock)->key);
4832 if (!validate_chain(curr, hlock, chain_head, chain_key))
4833 return 0;
4835 curr->curr_chain_key = chain_key;
4836 curr->lockdep_depth++;
4837 check_chain_key(curr);
4838 #ifdef CONFIG_DEBUG_LOCKDEP
4839 if (unlikely(!debug_locks))
4840 return 0;
4841 #endif
4842 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
4843 debug_locks_off();
4844 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
4845 printk(KERN_DEBUG "depth: %i max: %lu!\n",
4846 curr->lockdep_depth, MAX_LOCK_DEPTH);
4848 lockdep_print_held_locks(current);
4849 debug_show_all_locks();
4850 dump_stack();
4852 return 0;
4855 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
4856 max_lockdep_depth = curr->lockdep_depth;
4858 return 1;
4861 static void print_unlock_imbalance_bug(struct task_struct *curr,
4862 struct lockdep_map *lock,
4863 unsigned long ip)
4865 if (!debug_locks_off())
4866 return;
4867 if (debug_locks_silent)
4868 return;
4870 pr_warn("\n");
4871 pr_warn("=====================================\n");
4872 pr_warn("WARNING: bad unlock balance detected!\n");
4873 print_kernel_ident();
4874 pr_warn("-------------------------------------\n");
4875 pr_warn("%s/%d is trying to release lock (",
4876 curr->comm, task_pid_nr(curr));
4877 print_lockdep_cache(lock);
4878 pr_cont(") at:\n");
4879 print_ip_sym(KERN_WARNING, ip);
4880 pr_warn("but there are no more locks to release!\n");
4881 pr_warn("\nother info that might help us debug this:\n");
4882 lockdep_print_held_locks(curr);
4884 pr_warn("\nstack backtrace:\n");
4885 dump_stack();
4888 static noinstr int match_held_lock(const struct held_lock *hlock,
4889 const struct lockdep_map *lock)
4891 if (hlock->instance == lock)
4892 return 1;
4894 if (hlock->references) {
4895 const struct lock_class *class = lock->class_cache[0];
4897 if (!class)
4898 class = look_up_lock_class(lock, 0);
4901 * If look_up_lock_class() failed to find a class, we're trying
4902 * to test if we hold a lock that has never yet been acquired.
4903 * Clearly if the lock hasn't been acquired _ever_, we're not
4904 * holding it either, so report failure.
4906 if (!class)
4907 return 0;
4910 * References, but not a lock we're actually ref-counting?
4911 * State got messed up, follow the sites that change ->references
4912 * and try to make sense of it.
4914 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
4915 return 0;
4917 if (hlock->class_idx == class - lock_classes)
4918 return 1;
4921 return 0;
4924 /* @depth must not be zero */
4925 static struct held_lock *find_held_lock(struct task_struct *curr,
4926 struct lockdep_map *lock,
4927 unsigned int depth, int *idx)
4929 struct held_lock *ret, *hlock, *prev_hlock;
4930 int i;
4932 i = depth - 1;
4933 hlock = curr->held_locks + i;
4934 ret = hlock;
4935 if (match_held_lock(hlock, lock))
4936 goto out;
4938 ret = NULL;
4939 for (i--, prev_hlock = hlock--;
4940 i >= 0;
4941 i--, prev_hlock = hlock--) {
4943 * We must not cross into another context:
4945 if (prev_hlock->irq_context != hlock->irq_context) {
4946 ret = NULL;
4947 break;
4949 if (match_held_lock(hlock, lock)) {
4950 ret = hlock;
4951 break;
4955 out:
4956 *idx = i;
4957 return ret;
4960 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
4961 int idx, unsigned int *merged)
4963 struct held_lock *hlock;
4964 int first_idx = idx;
4966 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4967 return 0;
4969 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
4970 switch (__lock_acquire(hlock->instance,
4971 hlock_class(hlock)->subclass,
4972 hlock->trylock,
4973 hlock->read, hlock->check,
4974 hlock->hardirqs_off,
4975 hlock->nest_lock, hlock->acquire_ip,
4976 hlock->references, hlock->pin_count)) {
4977 case 0:
4978 return 1;
4979 case 1:
4980 break;
4981 case 2:
4982 *merged += (idx == first_idx);
4983 break;
4984 default:
4985 WARN_ON(1);
4986 return 0;
4989 return 0;
4992 static int
4993 __lock_set_class(struct lockdep_map *lock, const char *name,
4994 struct lock_class_key *key, unsigned int subclass,
4995 unsigned long ip)
4997 struct task_struct *curr = current;
4998 unsigned int depth, merged = 0;
4999 struct held_lock *hlock;
5000 struct lock_class *class;
5001 int i;
5003 if (unlikely(!debug_locks))
5004 return 0;
5006 depth = curr->lockdep_depth;
5008 * This function is about (re)setting the class of a held lock,
5009 * yet we're not actually holding any locks. Naughty user!
5011 if (DEBUG_LOCKS_WARN_ON(!depth))
5012 return 0;
5014 hlock = find_held_lock(curr, lock, depth, &i);
5015 if (!hlock) {
5016 print_unlock_imbalance_bug(curr, lock, ip);
5017 return 0;
5020 lockdep_init_map_waits(lock, name, key, 0,
5021 lock->wait_type_inner,
5022 lock->wait_type_outer);
5023 class = register_lock_class(lock, subclass, 0);
5024 hlock->class_idx = class - lock_classes;
5026 curr->lockdep_depth = i;
5027 curr->curr_chain_key = hlock->prev_chain_key;
5029 if (reacquire_held_locks(curr, depth, i, &merged))
5030 return 0;
5033 * I took it apart and put it back together again, except now I have
5034 * these 'spare' parts.. where shall I put them.
5036 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
5037 return 0;
5038 return 1;
5041 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5043 struct task_struct *curr = current;
5044 unsigned int depth, merged = 0;
5045 struct held_lock *hlock;
5046 int i;
5048 if (unlikely(!debug_locks))
5049 return 0;
5051 depth = curr->lockdep_depth;
5053 * This function is about (re)setting the class of a held lock,
5054 * yet we're not actually holding any locks. Naughty user!
5056 if (DEBUG_LOCKS_WARN_ON(!depth))
5057 return 0;
5059 hlock = find_held_lock(curr, lock, depth, &i);
5060 if (!hlock) {
5061 print_unlock_imbalance_bug(curr, lock, ip);
5062 return 0;
5065 curr->lockdep_depth = i;
5066 curr->curr_chain_key = hlock->prev_chain_key;
5068 WARN(hlock->read, "downgrading a read lock");
5069 hlock->read = 1;
5070 hlock->acquire_ip = ip;
5072 if (reacquire_held_locks(curr, depth, i, &merged))
5073 return 0;
5075 /* Merging can't happen with unchanged classes.. */
5076 if (DEBUG_LOCKS_WARN_ON(merged))
5077 return 0;
5080 * I took it apart and put it back together again, except now I have
5081 * these 'spare' parts.. where shall I put them.
5083 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
5084 return 0;
5086 return 1;
5090 * Remove the lock from the list of currently held locks - this gets
5091 * called on mutex_unlock()/spin_unlock*() (or on a failed
5092 * mutex_lock_interruptible()).
5094 static int
5095 __lock_release(struct lockdep_map *lock, unsigned long ip)
5097 struct task_struct *curr = current;
5098 unsigned int depth, merged = 1;
5099 struct held_lock *hlock;
5100 int i;
5102 if (unlikely(!debug_locks))
5103 return 0;
5105 depth = curr->lockdep_depth;
5107 * So we're all set to release this lock.. wait what lock? We don't
5108 * own any locks, you've been drinking again?
5110 if (depth <= 0) {
5111 print_unlock_imbalance_bug(curr, lock, ip);
5112 return 0;
5116 * Check whether the lock exists in the current stack
5117 * of held locks:
5119 hlock = find_held_lock(curr, lock, depth, &i);
5120 if (!hlock) {
5121 print_unlock_imbalance_bug(curr, lock, ip);
5122 return 0;
5125 if (hlock->instance == lock)
5126 lock_release_holdtime(hlock);
5128 WARN(hlock->pin_count, "releasing a pinned lock\n");
5130 if (hlock->references) {
5131 hlock->references--;
5132 if (hlock->references) {
5134 * We had, and after removing one, still have
5135 * references, the current lock stack is still
5136 * valid. We're done!
5138 return 1;
5143 * We have the right lock to unlock, 'hlock' points to it.
5144 * Now we remove it from the stack, and add back the other
5145 * entries (if any), recalculating the hash along the way:
5148 curr->lockdep_depth = i;
5149 curr->curr_chain_key = hlock->prev_chain_key;
5152 * The most likely case is when the unlock is on the innermost
5153 * lock. In this case, we are done!
5155 if (i == depth-1)
5156 return 1;
5158 if (reacquire_held_locks(curr, depth, i + 1, &merged))
5159 return 0;
5162 * We had N bottles of beer on the wall, we drank one, but now
5163 * there's not N-1 bottles of beer left on the wall...
5164 * Pouring two of the bottles together is acceptable.
5166 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
5169 * Since reacquire_held_locks() would have called check_chain_key()
5170 * indirectly via __lock_acquire(), we don't need to do it again
5171 * on return.
5173 return 0;
5176 static __always_inline
5177 int __lock_is_held(const struct lockdep_map *lock, int read)
5179 struct task_struct *curr = current;
5180 int i;
5182 for (i = 0; i < curr->lockdep_depth; i++) {
5183 struct held_lock *hlock = curr->held_locks + i;
5185 if (match_held_lock(hlock, lock)) {
5186 if (read == -1 || hlock->read == read)
5187 return 1;
5189 return 0;
5193 return 0;
5196 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
5198 struct pin_cookie cookie = NIL_COOKIE;
5199 struct task_struct *curr = current;
5200 int i;
5202 if (unlikely(!debug_locks))
5203 return cookie;
5205 for (i = 0; i < curr->lockdep_depth; i++) {
5206 struct held_lock *hlock = curr->held_locks + i;
5208 if (match_held_lock(hlock, lock)) {
5210 * Grab 16bits of randomness; this is sufficient to not
5211 * be guessable and still allows some pin nesting in
5212 * our u32 pin_count.
5214 cookie.val = 1 + (prandom_u32() >> 16);
5215 hlock->pin_count += cookie.val;
5216 return cookie;
5220 WARN(1, "pinning an unheld lock\n");
5221 return cookie;
5224 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5226 struct task_struct *curr = current;
5227 int i;
5229 if (unlikely(!debug_locks))
5230 return;
5232 for (i = 0; i < curr->lockdep_depth; i++) {
5233 struct held_lock *hlock = curr->held_locks + i;
5235 if (match_held_lock(hlock, lock)) {
5236 hlock->pin_count += cookie.val;
5237 return;
5241 WARN(1, "pinning an unheld lock\n");
5244 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5246 struct task_struct *curr = current;
5247 int i;
5249 if (unlikely(!debug_locks))
5250 return;
5252 for (i = 0; i < curr->lockdep_depth; i++) {
5253 struct held_lock *hlock = curr->held_locks + i;
5255 if (match_held_lock(hlock, lock)) {
5256 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
5257 return;
5259 hlock->pin_count -= cookie.val;
5261 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
5262 hlock->pin_count = 0;
5264 return;
5268 WARN(1, "unpinning an unheld lock\n");
5272 * Check whether we follow the irq-flags state precisely:
5274 static void check_flags(unsigned long flags)
5276 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP)
5277 if (!debug_locks)
5278 return;
5280 if (irqs_disabled_flags(flags)) {
5281 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) {
5282 printk("possible reason: unannotated irqs-off.\n");
5284 } else {
5285 if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) {
5286 printk("possible reason: unannotated irqs-on.\n");
5291 * We dont accurately track softirq state in e.g.
5292 * hardirq contexts (such as on 4KSTACKS), so only
5293 * check if not in hardirq contexts:
5295 if (!hardirq_count()) {
5296 if (softirq_count()) {
5297 /* like the above, but with softirqs */
5298 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
5299 } else {
5300 /* lick the above, does it taste good? */
5301 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
5305 if (!debug_locks)
5306 print_irqtrace_events(current);
5307 #endif
5310 void lock_set_class(struct lockdep_map *lock, const char *name,
5311 struct lock_class_key *key, unsigned int subclass,
5312 unsigned long ip)
5314 unsigned long flags;
5316 if (unlikely(!lockdep_enabled()))
5317 return;
5319 raw_local_irq_save(flags);
5320 lockdep_recursion_inc();
5321 check_flags(flags);
5322 if (__lock_set_class(lock, name, key, subclass, ip))
5323 check_chain_key(current);
5324 lockdep_recursion_finish();
5325 raw_local_irq_restore(flags);
5327 EXPORT_SYMBOL_GPL(lock_set_class);
5329 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5331 unsigned long flags;
5333 if (unlikely(!lockdep_enabled()))
5334 return;
5336 raw_local_irq_save(flags);
5337 lockdep_recursion_inc();
5338 check_flags(flags);
5339 if (__lock_downgrade(lock, ip))
5340 check_chain_key(current);
5341 lockdep_recursion_finish();
5342 raw_local_irq_restore(flags);
5344 EXPORT_SYMBOL_GPL(lock_downgrade);
5346 /* NMI context !!! */
5347 static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass)
5349 #ifdef CONFIG_PROVE_LOCKING
5350 struct lock_class *class = look_up_lock_class(lock, subclass);
5351 unsigned long mask = LOCKF_USED;
5353 /* if it doesn't have a class (yet), it certainly hasn't been used yet */
5354 if (!class)
5355 return;
5358 * READ locks only conflict with USED, such that if we only ever use
5359 * READ locks, there is no deadlock possible -- RCU.
5361 if (!hlock->read)
5362 mask |= LOCKF_USED_READ;
5364 if (!(class->usage_mask & mask))
5365 return;
5367 hlock->class_idx = class - lock_classes;
5369 print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES);
5370 #endif
5373 static bool lockdep_nmi(void)
5375 if (raw_cpu_read(lockdep_recursion))
5376 return false;
5378 if (!in_nmi())
5379 return false;
5381 return true;
5385 * read_lock() is recursive if:
5386 * 1. We force lockdep think this way in selftests or
5387 * 2. The implementation is not queued read/write lock or
5388 * 3. The locker is at an in_interrupt() context.
5390 bool read_lock_is_recursive(void)
5392 return force_read_lock_recursive ||
5393 !IS_ENABLED(CONFIG_QUEUED_RWLOCKS) ||
5394 in_interrupt();
5396 EXPORT_SYMBOL_GPL(read_lock_is_recursive);
5399 * We are not always called with irqs disabled - do that here,
5400 * and also avoid lockdep recursion:
5402 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
5403 int trylock, int read, int check,
5404 struct lockdep_map *nest_lock, unsigned long ip)
5406 unsigned long flags;
5408 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
5410 if (!debug_locks)
5411 return;
5413 if (unlikely(!lockdep_enabled())) {
5414 /* XXX allow trylock from NMI ?!? */
5415 if (lockdep_nmi() && !trylock) {
5416 struct held_lock hlock;
5418 hlock.acquire_ip = ip;
5419 hlock.instance = lock;
5420 hlock.nest_lock = nest_lock;
5421 hlock.irq_context = 2; // XXX
5422 hlock.trylock = trylock;
5423 hlock.read = read;
5424 hlock.check = check;
5425 hlock.hardirqs_off = true;
5426 hlock.references = 0;
5428 verify_lock_unused(lock, &hlock, subclass);
5430 return;
5433 raw_local_irq_save(flags);
5434 check_flags(flags);
5436 lockdep_recursion_inc();
5437 __lock_acquire(lock, subclass, trylock, read, check,
5438 irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
5439 lockdep_recursion_finish();
5440 raw_local_irq_restore(flags);
5442 EXPORT_SYMBOL_GPL(lock_acquire);
5444 void lock_release(struct lockdep_map *lock, unsigned long ip)
5446 unsigned long flags;
5448 trace_lock_release(lock, ip);
5450 if (unlikely(!lockdep_enabled()))
5451 return;
5453 raw_local_irq_save(flags);
5454 check_flags(flags);
5456 lockdep_recursion_inc();
5457 if (__lock_release(lock, ip))
5458 check_chain_key(current);
5459 lockdep_recursion_finish();
5460 raw_local_irq_restore(flags);
5462 EXPORT_SYMBOL_GPL(lock_release);
5464 noinstr int lock_is_held_type(const struct lockdep_map *lock, int read)
5466 unsigned long flags;
5467 int ret = 0;
5469 if (unlikely(!lockdep_enabled()))
5470 return 1; /* avoid false negative lockdep_assert_held() */
5472 raw_local_irq_save(flags);
5473 check_flags(flags);
5475 lockdep_recursion_inc();
5476 ret = __lock_is_held(lock, read);
5477 lockdep_recursion_finish();
5478 raw_local_irq_restore(flags);
5480 return ret;
5482 EXPORT_SYMBOL_GPL(lock_is_held_type);
5483 NOKPROBE_SYMBOL(lock_is_held_type);
5485 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
5487 struct pin_cookie cookie = NIL_COOKIE;
5488 unsigned long flags;
5490 if (unlikely(!lockdep_enabled()))
5491 return cookie;
5493 raw_local_irq_save(flags);
5494 check_flags(flags);
5496 lockdep_recursion_inc();
5497 cookie = __lock_pin_lock(lock);
5498 lockdep_recursion_finish();
5499 raw_local_irq_restore(flags);
5501 return cookie;
5503 EXPORT_SYMBOL_GPL(lock_pin_lock);
5505 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5507 unsigned long flags;
5509 if (unlikely(!lockdep_enabled()))
5510 return;
5512 raw_local_irq_save(flags);
5513 check_flags(flags);
5515 lockdep_recursion_inc();
5516 __lock_repin_lock(lock, cookie);
5517 lockdep_recursion_finish();
5518 raw_local_irq_restore(flags);
5520 EXPORT_SYMBOL_GPL(lock_repin_lock);
5522 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5524 unsigned long flags;
5526 if (unlikely(!lockdep_enabled()))
5527 return;
5529 raw_local_irq_save(flags);
5530 check_flags(flags);
5532 lockdep_recursion_inc();
5533 __lock_unpin_lock(lock, cookie);
5534 lockdep_recursion_finish();
5535 raw_local_irq_restore(flags);
5537 EXPORT_SYMBOL_GPL(lock_unpin_lock);
5539 #ifdef CONFIG_LOCK_STAT
5540 static void print_lock_contention_bug(struct task_struct *curr,
5541 struct lockdep_map *lock,
5542 unsigned long ip)
5544 if (!debug_locks_off())
5545 return;
5546 if (debug_locks_silent)
5547 return;
5549 pr_warn("\n");
5550 pr_warn("=================================\n");
5551 pr_warn("WARNING: bad contention detected!\n");
5552 print_kernel_ident();
5553 pr_warn("---------------------------------\n");
5554 pr_warn("%s/%d is trying to contend lock (",
5555 curr->comm, task_pid_nr(curr));
5556 print_lockdep_cache(lock);
5557 pr_cont(") at:\n");
5558 print_ip_sym(KERN_WARNING, ip);
5559 pr_warn("but there are no locks held!\n");
5560 pr_warn("\nother info that might help us debug this:\n");
5561 lockdep_print_held_locks(curr);
5563 pr_warn("\nstack backtrace:\n");
5564 dump_stack();
5567 static void
5568 __lock_contended(struct lockdep_map *lock, unsigned long ip)
5570 struct task_struct *curr = current;
5571 struct held_lock *hlock;
5572 struct lock_class_stats *stats;
5573 unsigned int depth;
5574 int i, contention_point, contending_point;
5576 depth = curr->lockdep_depth;
5578 * Whee, we contended on this lock, except it seems we're not
5579 * actually trying to acquire anything much at all..
5581 if (DEBUG_LOCKS_WARN_ON(!depth))
5582 return;
5584 hlock = find_held_lock(curr, lock, depth, &i);
5585 if (!hlock) {
5586 print_lock_contention_bug(curr, lock, ip);
5587 return;
5590 if (hlock->instance != lock)
5591 return;
5593 hlock->waittime_stamp = lockstat_clock();
5595 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
5596 contending_point = lock_point(hlock_class(hlock)->contending_point,
5597 lock->ip);
5599 stats = get_lock_stats(hlock_class(hlock));
5600 if (contention_point < LOCKSTAT_POINTS)
5601 stats->contention_point[contention_point]++;
5602 if (contending_point < LOCKSTAT_POINTS)
5603 stats->contending_point[contending_point]++;
5604 if (lock->cpu != smp_processor_id())
5605 stats->bounces[bounce_contended + !!hlock->read]++;
5608 static void
5609 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
5611 struct task_struct *curr = current;
5612 struct held_lock *hlock;
5613 struct lock_class_stats *stats;
5614 unsigned int depth;
5615 u64 now, waittime = 0;
5616 int i, cpu;
5618 depth = curr->lockdep_depth;
5620 * Yay, we acquired ownership of this lock we didn't try to
5621 * acquire, how the heck did that happen?
5623 if (DEBUG_LOCKS_WARN_ON(!depth))
5624 return;
5626 hlock = find_held_lock(curr, lock, depth, &i);
5627 if (!hlock) {
5628 print_lock_contention_bug(curr, lock, _RET_IP_);
5629 return;
5632 if (hlock->instance != lock)
5633 return;
5635 cpu = smp_processor_id();
5636 if (hlock->waittime_stamp) {
5637 now = lockstat_clock();
5638 waittime = now - hlock->waittime_stamp;
5639 hlock->holdtime_stamp = now;
5642 stats = get_lock_stats(hlock_class(hlock));
5643 if (waittime) {
5644 if (hlock->read)
5645 lock_time_inc(&stats->read_waittime, waittime);
5646 else
5647 lock_time_inc(&stats->write_waittime, waittime);
5649 if (lock->cpu != cpu)
5650 stats->bounces[bounce_acquired + !!hlock->read]++;
5652 lock->cpu = cpu;
5653 lock->ip = ip;
5656 void lock_contended(struct lockdep_map *lock, unsigned long ip)
5658 unsigned long flags;
5660 trace_lock_acquired(lock, ip);
5662 if (unlikely(!lock_stat || !lockdep_enabled()))
5663 return;
5665 raw_local_irq_save(flags);
5666 check_flags(flags);
5667 lockdep_recursion_inc();
5668 __lock_contended(lock, ip);
5669 lockdep_recursion_finish();
5670 raw_local_irq_restore(flags);
5672 EXPORT_SYMBOL_GPL(lock_contended);
5674 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
5676 unsigned long flags;
5678 trace_lock_contended(lock, ip);
5680 if (unlikely(!lock_stat || !lockdep_enabled()))
5681 return;
5683 raw_local_irq_save(flags);
5684 check_flags(flags);
5685 lockdep_recursion_inc();
5686 __lock_acquired(lock, ip);
5687 lockdep_recursion_finish();
5688 raw_local_irq_restore(flags);
5690 EXPORT_SYMBOL_GPL(lock_acquired);
5691 #endif
5694 * Used by the testsuite, sanitize the validator state
5695 * after a simulated failure:
5698 void lockdep_reset(void)
5700 unsigned long flags;
5701 int i;
5703 raw_local_irq_save(flags);
5704 lockdep_init_task(current);
5705 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
5706 nr_hardirq_chains = 0;
5707 nr_softirq_chains = 0;
5708 nr_process_chains = 0;
5709 debug_locks = 1;
5710 for (i = 0; i < CHAINHASH_SIZE; i++)
5711 INIT_HLIST_HEAD(chainhash_table + i);
5712 raw_local_irq_restore(flags);
5715 /* Remove a class from a lock chain. Must be called with the graph lock held. */
5716 static void remove_class_from_lock_chain(struct pending_free *pf,
5717 struct lock_chain *chain,
5718 struct lock_class *class)
5720 #ifdef CONFIG_PROVE_LOCKING
5721 int i;
5723 for (i = chain->base; i < chain->base + chain->depth; i++) {
5724 if (chain_hlock_class_idx(chain_hlocks[i]) != class - lock_classes)
5725 continue;
5727 * Each lock class occurs at most once in a lock chain so once
5728 * we found a match we can break out of this loop.
5730 goto free_lock_chain;
5732 /* Since the chain has not been modified, return. */
5733 return;
5735 free_lock_chain:
5736 free_chain_hlocks(chain->base, chain->depth);
5737 /* Overwrite the chain key for concurrent RCU readers. */
5738 WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY);
5739 dec_chains(chain->irq_context);
5742 * Note: calling hlist_del_rcu() from inside a
5743 * hlist_for_each_entry_rcu() loop is safe.
5745 hlist_del_rcu(&chain->entry);
5746 __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
5747 nr_zapped_lock_chains++;
5748 #endif
5751 /* Must be called with the graph lock held. */
5752 static void remove_class_from_lock_chains(struct pending_free *pf,
5753 struct lock_class *class)
5755 struct lock_chain *chain;
5756 struct hlist_head *head;
5757 int i;
5759 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
5760 head = chainhash_table + i;
5761 hlist_for_each_entry_rcu(chain, head, entry) {
5762 remove_class_from_lock_chain(pf, chain, class);
5768 * Remove all references to a lock class. The caller must hold the graph lock.
5770 static void zap_class(struct pending_free *pf, struct lock_class *class)
5772 struct lock_list *entry;
5773 int i;
5775 WARN_ON_ONCE(!class->key);
5778 * Remove all dependencies this lock is
5779 * involved in:
5781 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
5782 entry = list_entries + i;
5783 if (entry->class != class && entry->links_to != class)
5784 continue;
5785 __clear_bit(i, list_entries_in_use);
5786 nr_list_entries--;
5787 list_del_rcu(&entry->entry);
5789 if (list_empty(&class->locks_after) &&
5790 list_empty(&class->locks_before)) {
5791 list_move_tail(&class->lock_entry, &pf->zapped);
5792 hlist_del_rcu(&class->hash_entry);
5793 WRITE_ONCE(class->key, NULL);
5794 WRITE_ONCE(class->name, NULL);
5795 nr_lock_classes--;
5796 __clear_bit(class - lock_classes, lock_classes_in_use);
5797 } else {
5798 WARN_ONCE(true, "%s() failed for class %s\n", __func__,
5799 class->name);
5802 remove_class_from_lock_chains(pf, class);
5803 nr_zapped_classes++;
5806 static void reinit_class(struct lock_class *class)
5808 void *const p = class;
5809 const unsigned int offset = offsetof(struct lock_class, key);
5811 WARN_ON_ONCE(!class->lock_entry.next);
5812 WARN_ON_ONCE(!list_empty(&class->locks_after));
5813 WARN_ON_ONCE(!list_empty(&class->locks_before));
5814 memset(p + offset, 0, sizeof(*class) - offset);
5815 WARN_ON_ONCE(!class->lock_entry.next);
5816 WARN_ON_ONCE(!list_empty(&class->locks_after));
5817 WARN_ON_ONCE(!list_empty(&class->locks_before));
5820 static inline int within(const void *addr, void *start, unsigned long size)
5822 return addr >= start && addr < start + size;
5825 static bool inside_selftest(void)
5827 return current == lockdep_selftest_task_struct;
5830 /* The caller must hold the graph lock. */
5831 static struct pending_free *get_pending_free(void)
5833 return delayed_free.pf + delayed_free.index;
5836 static void free_zapped_rcu(struct rcu_head *cb);
5839 * Schedule an RCU callback if no RCU callback is pending. Must be called with
5840 * the graph lock held.
5842 static void call_rcu_zapped(struct pending_free *pf)
5844 WARN_ON_ONCE(inside_selftest());
5846 if (list_empty(&pf->zapped))
5847 return;
5849 if (delayed_free.scheduled)
5850 return;
5852 delayed_free.scheduled = true;
5854 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
5855 delayed_free.index ^= 1;
5857 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
5860 /* The caller must hold the graph lock. May be called from RCU context. */
5861 static void __free_zapped_classes(struct pending_free *pf)
5863 struct lock_class *class;
5865 check_data_structures();
5867 list_for_each_entry(class, &pf->zapped, lock_entry)
5868 reinit_class(class);
5870 list_splice_init(&pf->zapped, &free_lock_classes);
5872 #ifdef CONFIG_PROVE_LOCKING
5873 bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
5874 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
5875 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
5876 #endif
5879 static void free_zapped_rcu(struct rcu_head *ch)
5881 struct pending_free *pf;
5882 unsigned long flags;
5884 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
5885 return;
5887 raw_local_irq_save(flags);
5888 lockdep_lock();
5890 /* closed head */
5891 pf = delayed_free.pf + (delayed_free.index ^ 1);
5892 __free_zapped_classes(pf);
5893 delayed_free.scheduled = false;
5896 * If there's anything on the open list, close and start a new callback.
5898 call_rcu_zapped(delayed_free.pf + delayed_free.index);
5900 lockdep_unlock();
5901 raw_local_irq_restore(flags);
5905 * Remove all lock classes from the class hash table and from the
5906 * all_lock_classes list whose key or name is in the address range [start,
5907 * start + size). Move these lock classes to the zapped_classes list. Must
5908 * be called with the graph lock held.
5910 static void __lockdep_free_key_range(struct pending_free *pf, void *start,
5911 unsigned long size)
5913 struct lock_class *class;
5914 struct hlist_head *head;
5915 int i;
5917 /* Unhash all classes that were created by a module. */
5918 for (i = 0; i < CLASSHASH_SIZE; i++) {
5919 head = classhash_table + i;
5920 hlist_for_each_entry_rcu(class, head, hash_entry) {
5921 if (!within(class->key, start, size) &&
5922 !within(class->name, start, size))
5923 continue;
5924 zap_class(pf, class);
5930 * Used in module.c to remove lock classes from memory that is going to be
5931 * freed; and possibly re-used by other modules.
5933 * We will have had one synchronize_rcu() before getting here, so we're
5934 * guaranteed nobody will look up these exact classes -- they're properly dead
5935 * but still allocated.
5937 static void lockdep_free_key_range_reg(void *start, unsigned long size)
5939 struct pending_free *pf;
5940 unsigned long flags;
5942 init_data_structures_once();
5944 raw_local_irq_save(flags);
5945 lockdep_lock();
5946 pf = get_pending_free();
5947 __lockdep_free_key_range(pf, start, size);
5948 call_rcu_zapped(pf);
5949 lockdep_unlock();
5950 raw_local_irq_restore(flags);
5953 * Wait for any possible iterators from look_up_lock_class() to pass
5954 * before continuing to free the memory they refer to.
5956 synchronize_rcu();
5960 * Free all lockdep keys in the range [start, start+size). Does not sleep.
5961 * Ignores debug_locks. Must only be used by the lockdep selftests.
5963 static void lockdep_free_key_range_imm(void *start, unsigned long size)
5965 struct pending_free *pf = delayed_free.pf;
5966 unsigned long flags;
5968 init_data_structures_once();
5970 raw_local_irq_save(flags);
5971 lockdep_lock();
5972 __lockdep_free_key_range(pf, start, size);
5973 __free_zapped_classes(pf);
5974 lockdep_unlock();
5975 raw_local_irq_restore(flags);
5978 void lockdep_free_key_range(void *start, unsigned long size)
5980 init_data_structures_once();
5982 if (inside_selftest())
5983 lockdep_free_key_range_imm(start, size);
5984 else
5985 lockdep_free_key_range_reg(start, size);
5989 * Check whether any element of the @lock->class_cache[] array refers to a
5990 * registered lock class. The caller must hold either the graph lock or the
5991 * RCU read lock.
5993 static bool lock_class_cache_is_registered(struct lockdep_map *lock)
5995 struct lock_class *class;
5996 struct hlist_head *head;
5997 int i, j;
5999 for (i = 0; i < CLASSHASH_SIZE; i++) {
6000 head = classhash_table + i;
6001 hlist_for_each_entry_rcu(class, head, hash_entry) {
6002 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
6003 if (lock->class_cache[j] == class)
6004 return true;
6007 return false;
6010 /* The caller must hold the graph lock. Does not sleep. */
6011 static void __lockdep_reset_lock(struct pending_free *pf,
6012 struct lockdep_map *lock)
6014 struct lock_class *class;
6015 int j;
6018 * Remove all classes this lock might have:
6020 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
6022 * If the class exists we look it up and zap it:
6024 class = look_up_lock_class(lock, j);
6025 if (class)
6026 zap_class(pf, class);
6029 * Debug check: in the end all mapped classes should
6030 * be gone.
6032 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
6033 debug_locks_off();
6037 * Remove all information lockdep has about a lock if debug_locks == 1. Free
6038 * released data structures from RCU context.
6040 static void lockdep_reset_lock_reg(struct lockdep_map *lock)
6042 struct pending_free *pf;
6043 unsigned long flags;
6044 int locked;
6046 raw_local_irq_save(flags);
6047 locked = graph_lock();
6048 if (!locked)
6049 goto out_irq;
6051 pf = get_pending_free();
6052 __lockdep_reset_lock(pf, lock);
6053 call_rcu_zapped(pf);
6055 graph_unlock();
6056 out_irq:
6057 raw_local_irq_restore(flags);
6061 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
6062 * lockdep selftests.
6064 static void lockdep_reset_lock_imm(struct lockdep_map *lock)
6066 struct pending_free *pf = delayed_free.pf;
6067 unsigned long flags;
6069 raw_local_irq_save(flags);
6070 lockdep_lock();
6071 __lockdep_reset_lock(pf, lock);
6072 __free_zapped_classes(pf);
6073 lockdep_unlock();
6074 raw_local_irq_restore(flags);
6077 void lockdep_reset_lock(struct lockdep_map *lock)
6079 init_data_structures_once();
6081 if (inside_selftest())
6082 lockdep_reset_lock_imm(lock);
6083 else
6084 lockdep_reset_lock_reg(lock);
6087 /* Unregister a dynamically allocated key. */
6088 void lockdep_unregister_key(struct lock_class_key *key)
6090 struct hlist_head *hash_head = keyhashentry(key);
6091 struct lock_class_key *k;
6092 struct pending_free *pf;
6093 unsigned long flags;
6094 bool found = false;
6096 might_sleep();
6098 if (WARN_ON_ONCE(static_obj(key)))
6099 return;
6101 raw_local_irq_save(flags);
6102 if (!graph_lock())
6103 goto out_irq;
6105 pf = get_pending_free();
6106 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
6107 if (k == key) {
6108 hlist_del_rcu(&k->hash_entry);
6109 found = true;
6110 break;
6113 WARN_ON_ONCE(!found);
6114 __lockdep_free_key_range(pf, key, 1);
6115 call_rcu_zapped(pf);
6116 graph_unlock();
6117 out_irq:
6118 raw_local_irq_restore(flags);
6120 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
6121 synchronize_rcu();
6123 EXPORT_SYMBOL_GPL(lockdep_unregister_key);
6125 void __init lockdep_init(void)
6127 printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
6129 printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
6130 printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
6131 printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
6132 printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
6133 printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
6134 printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
6135 printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
6137 printk(" memory used by lock dependency info: %zu kB\n",
6138 (sizeof(lock_classes) +
6139 sizeof(lock_classes_in_use) +
6140 sizeof(classhash_table) +
6141 sizeof(list_entries) +
6142 sizeof(list_entries_in_use) +
6143 sizeof(chainhash_table) +
6144 sizeof(delayed_free)
6145 #ifdef CONFIG_PROVE_LOCKING
6146 + sizeof(lock_cq)
6147 + sizeof(lock_chains)
6148 + sizeof(lock_chains_in_use)
6149 + sizeof(chain_hlocks)
6150 #endif
6151 ) / 1024
6154 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
6155 printk(" memory used for stack traces: %zu kB\n",
6156 (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
6158 #endif
6160 printk(" per task-struct memory footprint: %zu bytes\n",
6161 sizeof(((struct task_struct *)NULL)->held_locks));
6164 static void
6165 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
6166 const void *mem_to, struct held_lock *hlock)
6168 if (!debug_locks_off())
6169 return;
6170 if (debug_locks_silent)
6171 return;
6173 pr_warn("\n");
6174 pr_warn("=========================\n");
6175 pr_warn("WARNING: held lock freed!\n");
6176 print_kernel_ident();
6177 pr_warn("-------------------------\n");
6178 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
6179 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
6180 print_lock(hlock);
6181 lockdep_print_held_locks(curr);
6183 pr_warn("\nstack backtrace:\n");
6184 dump_stack();
6187 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
6188 const void* lock_from, unsigned long lock_len)
6190 return lock_from + lock_len <= mem_from ||
6191 mem_from + mem_len <= lock_from;
6195 * Called when kernel memory is freed (or unmapped), or if a lock
6196 * is destroyed or reinitialized - this code checks whether there is
6197 * any held lock in the memory range of <from> to <to>:
6199 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
6201 struct task_struct *curr = current;
6202 struct held_lock *hlock;
6203 unsigned long flags;
6204 int i;
6206 if (unlikely(!debug_locks))
6207 return;
6209 raw_local_irq_save(flags);
6210 for (i = 0; i < curr->lockdep_depth; i++) {
6211 hlock = curr->held_locks + i;
6213 if (not_in_range(mem_from, mem_len, hlock->instance,
6214 sizeof(*hlock->instance)))
6215 continue;
6217 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
6218 break;
6220 raw_local_irq_restore(flags);
6222 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
6224 static void print_held_locks_bug(void)
6226 if (!debug_locks_off())
6227 return;
6228 if (debug_locks_silent)
6229 return;
6231 pr_warn("\n");
6232 pr_warn("====================================\n");
6233 pr_warn("WARNING: %s/%d still has locks held!\n",
6234 current->comm, task_pid_nr(current));
6235 print_kernel_ident();
6236 pr_warn("------------------------------------\n");
6237 lockdep_print_held_locks(current);
6238 pr_warn("\nstack backtrace:\n");
6239 dump_stack();
6242 void debug_check_no_locks_held(void)
6244 if (unlikely(current->lockdep_depth > 0))
6245 print_held_locks_bug();
6247 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
6249 #ifdef __KERNEL__
6250 void debug_show_all_locks(void)
6252 struct task_struct *g, *p;
6254 if (unlikely(!debug_locks)) {
6255 pr_warn("INFO: lockdep is turned off.\n");
6256 return;
6258 pr_warn("\nShowing all locks held in the system:\n");
6260 rcu_read_lock();
6261 for_each_process_thread(g, p) {
6262 if (!p->lockdep_depth)
6263 continue;
6264 lockdep_print_held_locks(p);
6265 touch_nmi_watchdog();
6266 touch_all_softlockup_watchdogs();
6268 rcu_read_unlock();
6270 pr_warn("\n");
6271 pr_warn("=============================================\n\n");
6273 EXPORT_SYMBOL_GPL(debug_show_all_locks);
6274 #endif
6277 * Careful: only use this function if you are sure that
6278 * the task cannot run in parallel!
6280 void debug_show_held_locks(struct task_struct *task)
6282 if (unlikely(!debug_locks)) {
6283 printk("INFO: lockdep is turned off.\n");
6284 return;
6286 lockdep_print_held_locks(task);
6288 EXPORT_SYMBOL_GPL(debug_show_held_locks);
6290 asmlinkage __visible void lockdep_sys_exit(void)
6292 struct task_struct *curr = current;
6294 if (unlikely(curr->lockdep_depth)) {
6295 if (!debug_locks_off())
6296 return;
6297 pr_warn("\n");
6298 pr_warn("================================================\n");
6299 pr_warn("WARNING: lock held when returning to user space!\n");
6300 print_kernel_ident();
6301 pr_warn("------------------------------------------------\n");
6302 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
6303 curr->comm, curr->pid);
6304 lockdep_print_held_locks(curr);
6308 * The lock history for each syscall should be independent. So wipe the
6309 * slate clean on return to userspace.
6311 lockdep_invariant_state(false);
6314 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
6316 struct task_struct *curr = current;
6318 /* Note: the following can be executed concurrently, so be careful. */
6319 pr_warn("\n");
6320 pr_warn("=============================\n");
6321 pr_warn("WARNING: suspicious RCU usage\n");
6322 print_kernel_ident();
6323 pr_warn("-----------------------------\n");
6324 pr_warn("%s:%d %s!\n", file, line, s);
6325 pr_warn("\nother info that might help us debug this:\n\n");
6326 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
6327 !rcu_lockdep_current_cpu_online()
6328 ? "RCU used illegally from offline CPU!\n"
6329 : "",
6330 rcu_scheduler_active, debug_locks);
6333 * If a CPU is in the RCU-free window in idle (ie: in the section
6334 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
6335 * considers that CPU to be in an "extended quiescent state",
6336 * which means that RCU will be completely ignoring that CPU.
6337 * Therefore, rcu_read_lock() and friends have absolutely no
6338 * effect on a CPU running in that state. In other words, even if
6339 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
6340 * delete data structures out from under it. RCU really has no
6341 * choice here: we need to keep an RCU-free window in idle where
6342 * the CPU may possibly enter into low power mode. This way we can
6343 * notice an extended quiescent state to other CPUs that started a grace
6344 * period. Otherwise we would delay any grace period as long as we run
6345 * in the idle task.
6347 * So complain bitterly if someone does call rcu_read_lock(),
6348 * rcu_read_lock_bh() and so on from extended quiescent states.
6350 if (!rcu_is_watching())
6351 pr_warn("RCU used illegally from extended quiescent state!\n");
6353 lockdep_print_held_locks(curr);
6354 pr_warn("\nstack backtrace:\n");
6355 dump_stack();
6357 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);