1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * kernel/lockdep.c
4 *
5 * Runtime locking correctness validator
6 *
7 * Started by Ingo Molnar:
8 *
9 * Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
10 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
11 *
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:
14 *
15 * - lock inversion scenarios
16 * - circular lock dependencies
17 * - hardirq/softirq safe/unsafe locking bugs
18 *
19 * Bugs are reported even if the current locking scenario does not cause
20 * any deadlock at this point.
21 *
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.
25 *
26 * Thanks to Arjan van de Ven for coming up with the initial idea of
27 * mapping lock dependencies runtime.
28 */
29 #define DISABLE_BRANCH_PROFILING
30 #include <linux/mutex.h>
31 #include <linux/sched.h>
32 #include <linux/sched/clock.h>
33 #include <linux/sched/task.h>
34 #include <linux/sched/mm.h>
35 #include <linux/delay.h>
36 #include <linux/module.h>
37 #include <linux/proc_fs.h>
38 #include <linux/seq_file.h>
39 #include <linux/spinlock.h>
40 #include <linux/kallsyms.h>
41 #include <linux/interrupt.h>
42 #include <linux/stacktrace.h>
43 #include <linux/debug_locks.h>
44 #include <linux/irqflags.h>
45 #include <linux/utsname.h>
46 #include <linux/hash.h>
47 #include <linux/ftrace.h>
48 #include <linux/stringify.h>
49 #include <linux/bitmap.h>
50 #include <linux/bitops.h>
51 #include <linux/gfp.h>
52 #include <linux/random.h>
53 #include <linux/jhash.h>
54 #include <linux/nmi.h>
55 #include <linux/rcupdate.h>
56 #include <linux/kprobes.h>
57 #include <linux/lockdep.h>
58 #include <linux/context_tracking.h>
59 #include <linux/console.h>
60 #include <linux/kasan.h>
61
62 #include <asm/sections.h>
63
64 #include "lockdep_internals.h"
65 #include "lock_events.h"
66
67 #include <trace/events/lock.h>
68
69 #ifdef CONFIG_PROVE_LOCKING
70 static int prove_locking = 1;
71 module_param(prove_locking, int, 0644);
72 #else
73 #define prove_locking 0
74 #endif
75
76 #ifdef CONFIG_LOCK_STAT
77 static int lock_stat = 1;
78 module_param(lock_stat, int, 0644);
79 #else
80 #define lock_stat 0
81 #endif
82
83 #ifdef CONFIG_SYSCTL
84 static const struct ctl_table kern_lockdep_table[] = {
85 #ifdef CONFIG_PROVE_LOCKING
86 {
87 .procname = "prove_locking",
88 .data = &prove_locking,
89 .maxlen = sizeof(int),
90 .mode = 0644,
91 .proc_handler = proc_dointvec,
92 },
93 #endif /* CONFIG_PROVE_LOCKING */
94 #ifdef CONFIG_LOCK_STAT
95 {
96 .procname = "lock_stat",
97 .data = &lock_stat,
98 .maxlen = sizeof(int),
99 .mode = 0644,
100 .proc_handler = proc_dointvec,
101 },
102 #endif /* CONFIG_LOCK_STAT */
103 };
104
kernel_lockdep_sysctls_init(void)105 static __init int kernel_lockdep_sysctls_init(void)
106 {
107 register_sysctl_init("kernel", kern_lockdep_table);
108 return 0;
109 }
110 late_initcall(kernel_lockdep_sysctls_init);
111 #endif /* CONFIG_SYSCTL */
112
113 DEFINE_PER_CPU(unsigned int, lockdep_recursion);
114 EXPORT_PER_CPU_SYMBOL_GPL(lockdep_recursion);
115
lockdep_enabled(void)116 static __always_inline bool lockdep_enabled(void)
117 {
118 if (!debug_locks)
119 return false;
120
121 if (this_cpu_read(lockdep_recursion))
122 return false;
123
124 if (current->lockdep_recursion)
125 return false;
126
127 return true;
128 }
129
130 /*
131 * lockdep_lock: protects the lockdep graph, the hashes and the
132 * class/list/hash allocators.
133 *
134 * This is one of the rare exceptions where it's justified
135 * to use a raw spinlock - we really dont want the spinlock
136 * code to recurse back into the lockdep code...
137 */
138 static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
139 static struct task_struct *__owner;
140
lockdep_lock(void)141 static inline void lockdep_lock(void)
142 {
143 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
144
145 __this_cpu_inc(lockdep_recursion);
146 arch_spin_lock(&__lock);
147 __owner = current;
148 }
149
lockdep_unlock(void)150 static inline void lockdep_unlock(void)
151 {
152 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
153
154 if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current))
155 return;
156
157 __owner = NULL;
158 arch_spin_unlock(&__lock);
159 __this_cpu_dec(lockdep_recursion);
160 }
161
162 #ifdef CONFIG_PROVE_LOCKING
lockdep_assert_locked(void)163 static inline bool lockdep_assert_locked(void)
164 {
165 return DEBUG_LOCKS_WARN_ON(__owner != current);
166 }
167 #endif
168
169 static struct task_struct *lockdep_selftest_task_struct;
170
171
graph_lock(void)172 static int graph_lock(void)
173 {
174 lockdep_lock();
175 lockevent_inc(lockdep_lock);
176 /*
177 * Make sure that if another CPU detected a bug while
178 * walking the graph we dont change it (while the other
179 * CPU is busy printing out stuff with the graph lock
180 * dropped already)
181 */
182 if (!debug_locks) {
183 lockdep_unlock();
184 return 0;
185 }
186 return 1;
187 }
188
graph_unlock(void)189 static inline void graph_unlock(void)
190 {
191 lockdep_unlock();
192 }
193
194 /*
195 * Turn lock debugging off and return with 0 if it was off already,
196 * and also release the graph lock:
197 */
debug_locks_off_graph_unlock(void)198 static inline int debug_locks_off_graph_unlock(void)
199 {
200 int ret = debug_locks_off();
201
202 lockdep_unlock();
203
204 return ret;
205 }
206
207 unsigned long nr_list_entries;
208 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
209 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
210
211 /*
212 * All data structures here are protected by the global debug_lock.
213 *
214 * nr_lock_classes is the number of elements of lock_classes[] that is
215 * in use.
216 */
217 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
218 #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
219 static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
220 unsigned long nr_lock_classes;
221 unsigned long nr_zapped_classes;
222 unsigned long max_lock_class_idx;
223 struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
224 DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
225
hlock_class(struct held_lock * hlock)226 static inline struct lock_class *hlock_class(struct held_lock *hlock)
227 {
228 unsigned int class_idx = hlock->class_idx;
229
230 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
231 barrier();
232
233 if (!test_bit(class_idx, lock_classes_in_use)) {
234 /*
235 * Someone passed in garbage, we give up.
236 */
237 DEBUG_LOCKS_WARN_ON(1);
238 return NULL;
239 }
240
241 /*
242 * At this point, if the passed hlock->class_idx is still garbage,
243 * we just have to live with it
244 */
245 return lock_classes + class_idx;
246 }
247
248 #ifdef CONFIG_LOCK_STAT
249 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
250
lockstat_clock(void)251 static inline u64 lockstat_clock(void)
252 {
253 return local_clock();
254 }
255
lock_point(unsigned long points[],unsigned long ip)256 static int lock_point(unsigned long points[], unsigned long ip)
257 {
258 int i;
259
260 for (i = 0; i < LOCKSTAT_POINTS; i++) {
261 if (points[i] == 0) {
262 points[i] = ip;
263 break;
264 }
265 if (points[i] == ip)
266 break;
267 }
268
269 return i;
270 }
271
lock_time_inc(struct lock_time * lt,u64 time)272 static void lock_time_inc(struct lock_time *lt, u64 time)
273 {
274 if (time > lt->max)
275 lt->max = time;
276
277 if (time < lt->min || !lt->nr)
278 lt->min = time;
279
280 lt->total += time;
281 lt->nr++;
282 }
283
lock_time_add(struct lock_time * src,struct lock_time * dst)284 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
285 {
286 if (!src->nr)
287 return;
288
289 if (src->max > dst->max)
290 dst->max = src->max;
291
292 if (src->min < dst->min || !dst->nr)
293 dst->min = src->min;
294
295 dst->total += src->total;
296 dst->nr += src->nr;
297 }
298
lock_stats(struct lock_class * class)299 struct lock_class_stats lock_stats(struct lock_class *class)
300 {
301 struct lock_class_stats stats;
302 int cpu, i;
303
304 memset(&stats, 0, sizeof(struct lock_class_stats));
305 for_each_possible_cpu(cpu) {
306 struct lock_class_stats *pcs =
307 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
308
309 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
310 stats.contention_point[i] += pcs->contention_point[i];
311
312 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
313 stats.contending_point[i] += pcs->contending_point[i];
314
315 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
316 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
317
318 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
319 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
320
321 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
322 stats.bounces[i] += pcs->bounces[i];
323 }
324
325 return stats;
326 }
327
clear_lock_stats(struct lock_class * class)328 void clear_lock_stats(struct lock_class *class)
329 {
330 int cpu;
331
332 for_each_possible_cpu(cpu) {
333 struct lock_class_stats *cpu_stats =
334 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
335
336 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
337 }
338 memset(class->contention_point, 0, sizeof(class->contention_point));
339 memset(class->contending_point, 0, sizeof(class->contending_point));
340 }
341
get_lock_stats(struct lock_class * class)342 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
343 {
344 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
345 }
346
lock_release_holdtime(struct held_lock * hlock)347 static void lock_release_holdtime(struct held_lock *hlock)
348 {
349 struct lock_class_stats *stats;
350 u64 holdtime;
351
352 if (!lock_stat)
353 return;
354
355 holdtime = lockstat_clock() - hlock->holdtime_stamp;
356
357 stats = get_lock_stats(hlock_class(hlock));
358 if (hlock->read)
359 lock_time_inc(&stats->read_holdtime, holdtime);
360 else
361 lock_time_inc(&stats->write_holdtime, holdtime);
362 }
363 #else
lock_release_holdtime(struct held_lock * hlock)364 static inline void lock_release_holdtime(struct held_lock *hlock)
365 {
366 }
367 #endif
368
369 /*
370 * We keep a global list of all lock classes. The list is only accessed with
371 * the lockdep spinlock lock held. free_lock_classes is a list with free
372 * elements. These elements are linked together by the lock_entry member in
373 * struct lock_class.
374 */
375 static LIST_HEAD(all_lock_classes);
376 static LIST_HEAD(free_lock_classes);
377
378 /**
379 * struct pending_free - information about data structures about to be freed
380 * @zapped: Head of a list with struct lock_class elements.
381 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
382 * are about to be freed.
383 */
384 struct pending_free {
385 struct list_head zapped;
386 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
387 };
388
389 /**
390 * struct delayed_free - data structures used for delayed freeing
391 *
392 * A data structure for delayed freeing of data structures that may be
393 * accessed by RCU readers at the time these were freed.
394 *
395 * @rcu_head: Used to schedule an RCU callback for freeing data structures.
396 * @index: Index of @pf to which freed data structures are added.
397 * @scheduled: Whether or not an RCU callback has been scheduled.
398 * @pf: Array with information about data structures about to be freed.
399 */
400 static struct delayed_free {
401 struct rcu_head rcu_head;
402 int index;
403 int scheduled;
404 struct pending_free pf[2];
405 } delayed_free;
406
407 /*
408 * The lockdep classes are in a hash-table as well, for fast lookup:
409 */
410 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
411 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
412 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
413 #define classhashentry(key) (classhash_table + __classhashfn((key)))
414
415 static struct hlist_head classhash_table[CLASSHASH_SIZE];
416
417 /*
418 * We put the lock dependency chains into a hash-table as well, to cache
419 * their existence:
420 */
421 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
422 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
423 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
424 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
425
426 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
427
428 /*
429 * the id of held_lock
430 */
hlock_id(struct held_lock * hlock)431 static inline u16 hlock_id(struct held_lock *hlock)
432 {
433 BUILD_BUG_ON(MAX_LOCKDEP_KEYS_BITS + 2 > 16);
434
435 return (hlock->class_idx | (hlock->read << MAX_LOCKDEP_KEYS_BITS));
436 }
437
chain_hlock_class_idx(u16 hlock_id)438 static inline __maybe_unused unsigned int chain_hlock_class_idx(u16 hlock_id)
439 {
440 return hlock_id & (MAX_LOCKDEP_KEYS - 1);
441 }
442
443 /*
444 * The hash key of the lock dependency chains is a hash itself too:
445 * it's a hash of all locks taken up to that lock, including that lock.
446 * It's a 64-bit hash, because it's important for the keys to be
447 * unique.
448 */
iterate_chain_key(u64 key,u32 idx)449 static inline u64 iterate_chain_key(u64 key, u32 idx)
450 {
451 u32 k0 = key, k1 = key >> 32;
452
453 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
454
455 return k0 | (u64)k1 << 32;
456 }
457
lockdep_init_task(struct task_struct * task)458 void lockdep_init_task(struct task_struct *task)
459 {
460 task->lockdep_depth = 0; /* no locks held yet */
461 task->curr_chain_key = INITIAL_CHAIN_KEY;
462 task->lockdep_recursion = 0;
463 }
464
lockdep_recursion_inc(void)465 static __always_inline void lockdep_recursion_inc(void)
466 {
467 __this_cpu_inc(lockdep_recursion);
468 }
469
lockdep_recursion_finish(void)470 static __always_inline void lockdep_recursion_finish(void)
471 {
472 if (WARN_ON_ONCE(__this_cpu_dec_return(lockdep_recursion)))
473 __this_cpu_write(lockdep_recursion, 0);
474 }
475
lockdep_set_selftest_task(struct task_struct * task)476 void lockdep_set_selftest_task(struct task_struct *task)
477 {
478 lockdep_selftest_task_struct = task;
479 }
480
481 /*
482 * Debugging switches:
483 */
484
485 #define VERBOSE 0
486 #define VERY_VERBOSE 0
487
488 #if VERBOSE
489 # define HARDIRQ_VERBOSE 1
490 # define SOFTIRQ_VERBOSE 1
491 #else
492 # define HARDIRQ_VERBOSE 0
493 # define SOFTIRQ_VERBOSE 0
494 #endif
495
496 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
497 /*
498 * Quick filtering for interesting events:
499 */
class_filter(struct lock_class * class)500 static int class_filter(struct lock_class *class)
501 {
502 #if 0
503 /* Example */
504 if (class->name_version == 1 &&
505 !strcmp(class->name, "lockname"))
506 return 1;
507 if (class->name_version == 1 &&
508 !strcmp(class->name, "&struct->lockfield"))
509 return 1;
510 #endif
511 /* Filter everything else. 1 would be to allow everything else */
512 return 0;
513 }
514 #endif
515
verbose(struct lock_class * class)516 static int verbose(struct lock_class *class)
517 {
518 #if VERBOSE
519 return class_filter(class);
520 #endif
521 return 0;
522 }
523
print_lockdep_off(const char * bug_msg)524 static void print_lockdep_off(const char *bug_msg)
525 {
526 printk(KERN_DEBUG "%s\n", bug_msg);
527 printk(KERN_DEBUG "turning off the locking correctness validator.\n");
528 #ifdef CONFIG_LOCK_STAT
529 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
530 #endif
531 }
532
533 unsigned long nr_stack_trace_entries;
534
535 #ifdef CONFIG_PROVE_LOCKING
536 /**
537 * struct lock_trace - single stack backtrace
538 * @hash_entry: Entry in a stack_trace_hash[] list.
539 * @hash: jhash() of @entries.
540 * @nr_entries: Number of entries in @entries.
541 * @entries: Actual stack backtrace.
542 */
543 struct lock_trace {
544 struct hlist_node hash_entry;
545 u32 hash;
546 u32 nr_entries;
547 unsigned long entries[] __aligned(sizeof(unsigned long));
548 };
549 #define LOCK_TRACE_SIZE_IN_LONGS \
550 (sizeof(struct lock_trace) / sizeof(unsigned long))
551 /*
552 * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock.
553 */
554 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
555 static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE];
556
traces_identical(struct lock_trace * t1,struct lock_trace * t2)557 static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2)
558 {
559 return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries &&
560 memcmp(t1->entries, t2->entries,
561 t1->nr_entries * sizeof(t1->entries[0])) == 0;
562 }
563
save_trace(void)564 static struct lock_trace *save_trace(void)
565 {
566 struct lock_trace *trace, *t2;
567 struct hlist_head *hash_head;
568 u32 hash;
569 int max_entries;
570
571 BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE);
572 BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES);
573
574 trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries);
575 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries -
576 LOCK_TRACE_SIZE_IN_LONGS;
577
578 if (max_entries <= 0) {
579 if (!debug_locks_off_graph_unlock())
580 return NULL;
581
582 nbcon_cpu_emergency_enter();
583 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
584 dump_stack();
585 nbcon_cpu_emergency_exit();
586
587 return NULL;
588 }
589 trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3);
590
591 hash = jhash(trace->entries, trace->nr_entries *
592 sizeof(trace->entries[0]), 0);
593 trace->hash = hash;
594 hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1));
595 hlist_for_each_entry(t2, hash_head, hash_entry) {
596 if (traces_identical(trace, t2))
597 return t2;
598 }
599 nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries;
600 hlist_add_head(&trace->hash_entry, hash_head);
601
602 return trace;
603 }
604
605 /* Return the number of stack traces in the stack_trace[] array. */
lockdep_stack_trace_count(void)606 u64 lockdep_stack_trace_count(void)
607 {
608 struct lock_trace *trace;
609 u64 c = 0;
610 int i;
611
612 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) {
613 hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) {
614 c++;
615 }
616 }
617
618 return c;
619 }
620
621 /* Return the number of stack hash chains that have at least one stack trace. */
lockdep_stack_hash_count(void)622 u64 lockdep_stack_hash_count(void)
623 {
624 u64 c = 0;
625 int i;
626
627 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++)
628 if (!hlist_empty(&stack_trace_hash[i]))
629 c++;
630
631 return c;
632 }
633 #endif
634
635 unsigned int nr_hardirq_chains;
636 unsigned int nr_softirq_chains;
637 unsigned int nr_process_chains;
638 unsigned int max_lockdep_depth;
639
640 #ifdef CONFIG_DEBUG_LOCKDEP
641 /*
642 * Various lockdep statistics:
643 */
644 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
645 #endif
646
647 #ifdef CONFIG_PROVE_LOCKING
648 /*
649 * Locking printouts:
650 */
651
652 #define __USAGE(__STATE) \
653 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
654 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
655 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
656 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
657
658 static const char *usage_str[] =
659 {
660 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
661 #include "lockdep_states.h"
662 #undef LOCKDEP_STATE
663 [LOCK_USED] = "INITIAL USE",
664 [LOCK_USED_READ] = "INITIAL READ USE",
665 /* abused as string storage for verify_lock_unused() */
666 [LOCK_USAGE_STATES] = "IN-NMI",
667 };
668 #endif
669
__get_key_name(const struct lockdep_subclass_key * key,char * str)670 const char *__get_key_name(const struct lockdep_subclass_key *key, char *str)
671 {
672 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
673 }
674
lock_flag(enum lock_usage_bit bit)675 static inline unsigned long lock_flag(enum lock_usage_bit bit)
676 {
677 return 1UL << bit;
678 }
679
get_usage_char(struct lock_class * class,enum lock_usage_bit bit)680 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
681 {
682 /*
683 * The usage character defaults to '.' (i.e., irqs disabled and not in
684 * irq context), which is the safest usage category.
685 */
686 char c = '.';
687
688 /*
689 * The order of the following usage checks matters, which will
690 * result in the outcome character as follows:
691 *
692 * - '+': irq is enabled and not in irq context
693 * - '-': in irq context and irq is disabled
694 * - '?': in irq context and irq is enabled
695 */
696 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
697 c = '+';
698 if (class->usage_mask & lock_flag(bit))
699 c = '?';
700 } else if (class->usage_mask & lock_flag(bit))
701 c = '-';
702
703 return c;
704 }
705
get_usage_chars(struct lock_class * class,char usage[LOCK_USAGE_CHARS])706 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
707 {
708 int i = 0;
709
710 #define LOCKDEP_STATE(__STATE) \
711 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
712 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
713 #include "lockdep_states.h"
714 #undef LOCKDEP_STATE
715
716 usage[i] = '\0';
717 }
718
__print_lock_name(struct held_lock * hlock,struct lock_class * class)719 static void __print_lock_name(struct held_lock *hlock, struct lock_class *class)
720 {
721 char str[KSYM_NAME_LEN];
722 const char *name;
723
724 name = class->name;
725 if (!name) {
726 name = __get_key_name(class->key, str);
727 printk(KERN_CONT "%s", name);
728 } else {
729 printk(KERN_CONT "%s", name);
730 if (class->name_version > 1)
731 printk(KERN_CONT "#%d", class->name_version);
732 if (class->subclass)
733 printk(KERN_CONT "/%d", class->subclass);
734 if (hlock && class->print_fn)
735 class->print_fn(hlock->instance);
736 }
737 }
738
print_lock_name(struct held_lock * hlock,struct lock_class * class)739 static void print_lock_name(struct held_lock *hlock, struct lock_class *class)
740 {
741 char usage[LOCK_USAGE_CHARS];
742
743 get_usage_chars(class, usage);
744
745 printk(KERN_CONT " (");
746 __print_lock_name(hlock, class);
747 printk(KERN_CONT "){%s}-{%d:%d}", usage,
748 class->wait_type_outer ?: class->wait_type_inner,
749 class->wait_type_inner);
750 }
751
print_lockdep_cache(struct lockdep_map * lock)752 static void print_lockdep_cache(struct lockdep_map *lock)
753 {
754 const char *name;
755 char str[KSYM_NAME_LEN];
756
757 name = lock->name;
758 if (!name)
759 name = __get_key_name(lock->key->subkeys, str);
760
761 printk(KERN_CONT "%s", name);
762 }
763
print_lock(struct held_lock * hlock)764 static void print_lock(struct held_lock *hlock)
765 {
766 /*
767 * We can be called locklessly through debug_show_all_locks() so be
768 * extra careful, the hlock might have been released and cleared.
769 *
770 * If this indeed happens, lets pretend it does not hurt to continue
771 * to print the lock unless the hlock class_idx does not point to a
772 * registered class. The rationale here is: since we don't attempt
773 * to distinguish whether we are in this situation, if it just
774 * happened we can't count on class_idx to tell either.
775 */
776 struct lock_class *lock = hlock_class(hlock);
777
778 if (!lock) {
779 printk(KERN_CONT "<RELEASED>\n");
780 return;
781 }
782
783 printk(KERN_CONT "%px", hlock->instance);
784 print_lock_name(hlock, lock);
785 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
786 }
787
lockdep_print_held_locks(struct task_struct * p)788 static void lockdep_print_held_locks(struct task_struct *p)
789 {
790 int i, depth = READ_ONCE(p->lockdep_depth);
791
792 if (!depth)
793 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
794 else
795 printk("%d lock%s held by %s/%d:\n", depth,
796 str_plural(depth), p->comm, task_pid_nr(p));
797 /*
798 * It's not reliable to print a task's held locks if it's not sleeping
799 * and it's not the current task.
800 */
801 if (p != current && task_is_running(p))
802 return;
803 for (i = 0; i < depth; i++) {
804 printk(" #%d: ", i);
805 print_lock(p->held_locks + i);
806 }
807 }
808
print_kernel_ident(void)809 static void print_kernel_ident(void)
810 {
811 printk("%s %.*s %s\n", init_utsname()->release,
812 (int)strcspn(init_utsname()->version, " "),
813 init_utsname()->version,
814 print_tainted());
815 }
816
very_verbose(struct lock_class * class)817 static int very_verbose(struct lock_class *class)
818 {
819 #if VERY_VERBOSE
820 return class_filter(class);
821 #endif
822 return 0;
823 }
824
825 /*
826 * Is this the address of a static object:
827 */
828 #ifdef __KERNEL__
static_obj(const void * obj)829 static int static_obj(const void *obj)
830 {
831 unsigned long addr = (unsigned long) obj;
832
833 if (is_kernel_core_data(addr))
834 return 1;
835
836 /*
837 * keys are allowed in the __ro_after_init section.
838 */
839 if (is_kernel_rodata(addr))
840 return 1;
841
842 /*
843 * in initdata section and used during bootup only?
844 * NOTE: On some platforms the initdata section is
845 * outside of the _stext ... _end range.
846 */
847 if (system_state < SYSTEM_FREEING_INITMEM &&
848 init_section_contains((void *)addr, 1))
849 return 1;
850
851 /*
852 * in-kernel percpu var?
853 */
854 if (is_kernel_percpu_address(addr))
855 return 1;
856
857 /*
858 * module static or percpu var?
859 */
860 return is_module_address(addr) || is_module_percpu_address(addr);
861 }
862 #endif
863
864 /*
865 * To make lock name printouts unique, we calculate a unique
866 * class->name_version generation counter. The caller must hold the graph
867 * lock.
868 */
count_matching_names(struct lock_class * new_class)869 static int count_matching_names(struct lock_class *new_class)
870 {
871 struct lock_class *class;
872 int count = 0;
873
874 if (!new_class->name)
875 return 0;
876
877 list_for_each_entry(class, &all_lock_classes, lock_entry) {
878 if (new_class->key - new_class->subclass == class->key)
879 return class->name_version;
880 if (class->name && !strcmp(class->name, new_class->name))
881 count = max(count, class->name_version);
882 }
883
884 return count + 1;
885 }
886
887 /* used from NMI context -- must be lockless */
888 static noinstr struct lock_class *
look_up_lock_class(const struct lockdep_map * lock,unsigned int subclass)889 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
890 {
891 struct lockdep_subclass_key *key;
892 struct hlist_head *hash_head;
893 struct lock_class *class;
894
895 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
896 instrumentation_begin();
897 debug_locks_off();
898 nbcon_cpu_emergency_enter();
899 printk(KERN_ERR
900 "BUG: looking up invalid subclass: %u\n", subclass);
901 printk(KERN_ERR
902 "turning off the locking correctness validator.\n");
903 dump_stack();
904 nbcon_cpu_emergency_exit();
905 instrumentation_end();
906 return NULL;
907 }
908
909 /*
910 * If it is not initialised then it has never been locked,
911 * so it won't be present in the hash table.
912 */
913 if (unlikely(!lock->key))
914 return NULL;
915
916 /*
917 * NOTE: the class-key must be unique. For dynamic locks, a static
918 * lock_class_key variable is passed in through the mutex_init()
919 * (or spin_lock_init()) call - which acts as the key. For static
920 * locks we use the lock object itself as the key.
921 */
922 BUILD_BUG_ON(sizeof(struct lock_class_key) >
923 sizeof(struct lockdep_map));
924
925 key = lock->key->subkeys + subclass;
926
927 hash_head = classhashentry(key);
928
929 /*
930 * We do an RCU walk of the hash, see lockdep_free_key_range().
931 */
932 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
933 return NULL;
934
935 hlist_for_each_entry_rcu_notrace(class, hash_head, hash_entry) {
936 if (class->key == key) {
937 /*
938 * Huh! same key, different name? Did someone trample
939 * on some memory? We're most confused.
940 */
941 WARN_ONCE(class->name != lock->name &&
942 lock->key != &__lockdep_no_validate__,
943 "Looking for class \"%s\" with key %ps, but found a different class \"%s\" with the same key\n",
944 lock->name, lock->key, class->name);
945 return class;
946 }
947 }
948
949 return NULL;
950 }
951
952 /*
953 * Static locks do not have their class-keys yet - for them the key is
954 * the lock object itself. If the lock is in the per cpu area, the
955 * canonical address of the lock (per cpu offset removed) is used.
956 */
assign_lock_key(struct lockdep_map * lock)957 static bool assign_lock_key(struct lockdep_map *lock)
958 {
959 unsigned long can_addr, addr = (unsigned long)lock;
960
961 #ifdef __KERNEL__
962 /*
963 * lockdep_free_key_range() assumes that struct lock_class_key
964 * objects do not overlap. Since we use the address of lock
965 * objects as class key for static objects, check whether the
966 * size of lock_class_key objects does not exceed the size of
967 * the smallest lock object.
968 */
969 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
970 #endif
971
972 if (__is_kernel_percpu_address(addr, &can_addr))
973 lock->key = (void *)can_addr;
974 else if (__is_module_percpu_address(addr, &can_addr))
975 lock->key = (void *)can_addr;
976 else if (static_obj(lock))
977 lock->key = (void *)lock;
978 else {
979 /* Debug-check: all keys must be persistent! */
980 debug_locks_off();
981 nbcon_cpu_emergency_enter();
982 pr_err("INFO: trying to register non-static key.\n");
983 pr_err("The code is fine but needs lockdep annotation, or maybe\n");
984 pr_err("you didn't initialize this object before use?\n");
985 pr_err("turning off the locking correctness validator.\n");
986 dump_stack();
987 nbcon_cpu_emergency_exit();
988 return false;
989 }
990
991 return true;
992 }
993
994 #ifdef CONFIG_DEBUG_LOCKDEP
995
996 /* Check whether element @e occurs in list @h */
in_list(struct list_head * e,struct list_head * h)997 static bool in_list(struct list_head *e, struct list_head *h)
998 {
999 struct list_head *f;
1000
1001 list_for_each(f, h) {
1002 if (e == f)
1003 return true;
1004 }
1005
1006 return false;
1007 }
1008
1009 /*
1010 * Check whether entry @e occurs in any of the locks_after or locks_before
1011 * lists.
1012 */
in_any_class_list(struct list_head * e)1013 static bool in_any_class_list(struct list_head *e)
1014 {
1015 struct lock_class *class;
1016 int i;
1017
1018 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1019 class = &lock_classes[i];
1020 if (in_list(e, &class->locks_after) ||
1021 in_list(e, &class->locks_before))
1022 return true;
1023 }
1024 return false;
1025 }
1026
class_lock_list_valid(struct lock_class * c,struct list_head * h)1027 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
1028 {
1029 struct lock_list *e;
1030
1031 list_for_each_entry(e, h, entry) {
1032 if (e->links_to != c) {
1033 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
1034 c->name ? : "(?)",
1035 (unsigned long)(e - list_entries),
1036 e->links_to && e->links_to->name ?
1037 e->links_to->name : "(?)",
1038 e->class && e->class->name ? e->class->name :
1039 "(?)");
1040 return false;
1041 }
1042 }
1043 return true;
1044 }
1045
1046 #ifdef CONFIG_PROVE_LOCKING
1047 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
1048 #endif
1049
check_lock_chain_key(struct lock_chain * chain)1050 static bool check_lock_chain_key(struct lock_chain *chain)
1051 {
1052 #ifdef CONFIG_PROVE_LOCKING
1053 u64 chain_key = INITIAL_CHAIN_KEY;
1054 int i;
1055
1056 for (i = chain->base; i < chain->base + chain->depth; i++)
1057 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
1058 /*
1059 * The 'unsigned long long' casts avoid that a compiler warning
1060 * is reported when building tools/lib/lockdep.
1061 */
1062 if (chain->chain_key != chain_key) {
1063 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
1064 (unsigned long long)(chain - lock_chains),
1065 (unsigned long long)chain->chain_key,
1066 (unsigned long long)chain_key);
1067 return false;
1068 }
1069 #endif
1070 return true;
1071 }
1072
in_any_zapped_class_list(struct lock_class * class)1073 static bool in_any_zapped_class_list(struct lock_class *class)
1074 {
1075 struct pending_free *pf;
1076 int i;
1077
1078 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
1079 if (in_list(&class->lock_entry, &pf->zapped))
1080 return true;
1081 }
1082
1083 return false;
1084 }
1085
__check_data_structures(void)1086 static bool __check_data_structures(void)
1087 {
1088 struct lock_class *class;
1089 struct lock_chain *chain;
1090 struct hlist_head *head;
1091 struct lock_list *e;
1092 int i;
1093
1094 /* Check whether all classes occur in a lock list. */
1095 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1096 class = &lock_classes[i];
1097 if (!in_list(&class->lock_entry, &all_lock_classes) &&
1098 !in_list(&class->lock_entry, &free_lock_classes) &&
1099 !in_any_zapped_class_list(class)) {
1100 printk(KERN_INFO "class %px/%s is not in any class list\n",
1101 class, class->name ? : "(?)");
1102 return false;
1103 }
1104 }
1105
1106 /* Check whether all classes have valid lock lists. */
1107 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1108 class = &lock_classes[i];
1109 if (!class_lock_list_valid(class, &class->locks_before))
1110 return false;
1111 if (!class_lock_list_valid(class, &class->locks_after))
1112 return false;
1113 }
1114
1115 /* Check the chain_key of all lock chains. */
1116 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
1117 head = chainhash_table + i;
1118 hlist_for_each_entry_rcu(chain, head, entry) {
1119 if (!check_lock_chain_key(chain))
1120 return false;
1121 }
1122 }
1123
1124 /*
1125 * Check whether all list entries that are in use occur in a class
1126 * lock list.
1127 */
1128 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1129 e = list_entries + i;
1130 if (!in_any_class_list(&e->entry)) {
1131 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
1132 (unsigned int)(e - list_entries),
1133 e->class->name ? : "(?)",
1134 e->links_to->name ? : "(?)");
1135 return false;
1136 }
1137 }
1138
1139 /*
1140 * Check whether all list entries that are not in use do not occur in
1141 * a class lock list.
1142 */
1143 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
1144 e = list_entries + i;
1145 if (in_any_class_list(&e->entry)) {
1146 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
1147 (unsigned int)(e - list_entries),
1148 e->class && e->class->name ? e->class->name :
1149 "(?)",
1150 e->links_to && e->links_to->name ?
1151 e->links_to->name : "(?)");
1152 return false;
1153 }
1154 }
1155
1156 return true;
1157 }
1158
1159 int check_consistency = 0;
1160 module_param(check_consistency, int, 0644);
1161
check_data_structures(void)1162 static void check_data_structures(void)
1163 {
1164 static bool once = false;
1165
1166 if (check_consistency && !once) {
1167 if (!__check_data_structures()) {
1168 once = true;
1169 WARN_ON(once);
1170 }
1171 }
1172 }
1173
1174 #else /* CONFIG_DEBUG_LOCKDEP */
1175
check_data_structures(void)1176 static inline void check_data_structures(void) { }
1177
1178 #endif /* CONFIG_DEBUG_LOCKDEP */
1179
1180 static void init_chain_block_buckets(void);
1181
1182 /*
1183 * Initialize the lock_classes[] array elements, the free_lock_classes list
1184 * and also the delayed_free structure.
1185 */
init_data_structures_once(void)1186 static void init_data_structures_once(void)
1187 {
1188 static bool __read_mostly ds_initialized, rcu_head_initialized;
1189 int i;
1190
1191 if (likely(rcu_head_initialized))
1192 return;
1193
1194 if (system_state >= SYSTEM_SCHEDULING) {
1195 init_rcu_head(&delayed_free.rcu_head);
1196 rcu_head_initialized = true;
1197 }
1198
1199 if (ds_initialized)
1200 return;
1201
1202 ds_initialized = true;
1203
1204 INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
1205 INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
1206
1207 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
1208 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
1209 INIT_LIST_HEAD(&lock_classes[i].locks_after);
1210 INIT_LIST_HEAD(&lock_classes[i].locks_before);
1211 }
1212 init_chain_block_buckets();
1213 }
1214
keyhashentry(const struct lock_class_key * key)1215 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
1216 {
1217 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
1218
1219 return lock_keys_hash + hash;
1220 }
1221
1222 /* Register a dynamically allocated key. */
lockdep_register_key(struct lock_class_key * key)1223 void lockdep_register_key(struct lock_class_key *key)
1224 {
1225 struct hlist_head *hash_head;
1226 struct lock_class_key *k;
1227 unsigned long flags;
1228
1229 if (WARN_ON_ONCE(static_obj(key)))
1230 return;
1231 hash_head = keyhashentry(key);
1232
1233 raw_local_irq_save(flags);
1234 if (!graph_lock())
1235 goto restore_irqs;
1236 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1237 if (WARN_ON_ONCE(k == key))
1238 goto out_unlock;
1239 }
1240 hlist_add_head_rcu(&key->hash_entry, hash_head);
1241 out_unlock:
1242 graph_unlock();
1243 restore_irqs:
1244 raw_local_irq_restore(flags);
1245 }
1246 EXPORT_SYMBOL_GPL(lockdep_register_key);
1247
1248 /* Check whether a key has been registered as a dynamic key. */
is_dynamic_key(const struct lock_class_key * key)1249 static bool is_dynamic_key(const struct lock_class_key *key)
1250 {
1251 struct hlist_head *hash_head;
1252 struct lock_class_key *k;
1253 bool found = false;
1254
1255 if (WARN_ON_ONCE(static_obj(key)))
1256 return false;
1257
1258 /*
1259 * If lock debugging is disabled lock_keys_hash[] may contain
1260 * pointers to memory that has already been freed. Avoid triggering
1261 * a use-after-free in that case by returning early.
1262 */
1263 if (!debug_locks)
1264 return true;
1265
1266 hash_head = keyhashentry(key);
1267
1268 rcu_read_lock();
1269 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
1270 if (k == key) {
1271 found = true;
1272 break;
1273 }
1274 }
1275 rcu_read_unlock();
1276
1277 return found;
1278 }
1279
1280 /*
1281 * Register a lock's class in the hash-table, if the class is not present
1282 * yet. Otherwise we look it up. We cache the result in the lock object
1283 * itself, so actual lookup of the hash should be once per lock object.
1284 */
1285 static struct lock_class *
register_lock_class(struct lockdep_map * lock,unsigned int subclass,int force)1286 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1287 {
1288 struct lockdep_subclass_key *key;
1289 struct hlist_head *hash_head;
1290 struct lock_class *class;
1291 int idx;
1292
1293 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1294
1295 class = look_up_lock_class(lock, subclass);
1296 if (likely(class))
1297 goto out_set_class_cache;
1298
1299 if (!lock->key) {
1300 if (!assign_lock_key(lock))
1301 return NULL;
1302 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
1303 return NULL;
1304 }
1305
1306 key = lock->key->subkeys + subclass;
1307 hash_head = classhashentry(key);
1308
1309 if (!graph_lock()) {
1310 return NULL;
1311 }
1312 /*
1313 * We have to do the hash-walk again, to avoid races
1314 * with another CPU:
1315 */
1316 hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
1317 if (class->key == key)
1318 goto out_unlock_set;
1319 }
1320
1321 init_data_structures_once();
1322
1323 /* Allocate a new lock class and add it to the hash. */
1324 class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
1325 lock_entry);
1326 if (!class) {
1327 if (!debug_locks_off_graph_unlock()) {
1328 return NULL;
1329 }
1330
1331 nbcon_cpu_emergency_enter();
1332 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
1333 dump_stack();
1334 nbcon_cpu_emergency_exit();
1335 return NULL;
1336 }
1337 nr_lock_classes++;
1338 __set_bit(class - lock_classes, lock_classes_in_use);
1339 debug_atomic_inc(nr_unused_locks);
1340 class->key = key;
1341 class->name = lock->name;
1342 class->subclass = subclass;
1343 WARN_ON_ONCE(!list_empty(&class->locks_before));
1344 WARN_ON_ONCE(!list_empty(&class->locks_after));
1345 class->name_version = count_matching_names(class);
1346 class->wait_type_inner = lock->wait_type_inner;
1347 class->wait_type_outer = lock->wait_type_outer;
1348 class->lock_type = lock->lock_type;
1349 /*
1350 * We use RCU's safe list-add method to make
1351 * parallel walking of the hash-list safe:
1352 */
1353 hlist_add_head_rcu(&class->hash_entry, hash_head);
1354 /*
1355 * Remove the class from the free list and add it to the global list
1356 * of classes.
1357 */
1358 list_move_tail(&class->lock_entry, &all_lock_classes);
1359 idx = class - lock_classes;
1360 if (idx > max_lock_class_idx)
1361 max_lock_class_idx = idx;
1362
1363 if (verbose(class)) {
1364 graph_unlock();
1365
1366 nbcon_cpu_emergency_enter();
1367 printk("\nnew class %px: %s", class->key, class->name);
1368 if (class->name_version > 1)
1369 printk(KERN_CONT "#%d", class->name_version);
1370 printk(KERN_CONT "\n");
1371 dump_stack();
1372 nbcon_cpu_emergency_exit();
1373
1374 if (!graph_lock()) {
1375 return NULL;
1376 }
1377 }
1378 out_unlock_set:
1379 graph_unlock();
1380
1381 out_set_class_cache:
1382 if (!subclass || force)
1383 lock->class_cache[0] = class;
1384 else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
1385 lock->class_cache[subclass] = class;
1386
1387 /*
1388 * Hash collision, did we smoke some? We found a class with a matching
1389 * hash but the subclass -- which is hashed in -- didn't match.
1390 */
1391 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
1392 return NULL;
1393
1394 return class;
1395 }
1396
1397 #ifdef CONFIG_PROVE_LOCKING
1398 /*
1399 * Allocate a lockdep entry. (assumes the graph_lock held, returns
1400 * with NULL on failure)
1401 */
alloc_list_entry(void)1402 static struct lock_list *alloc_list_entry(void)
1403 {
1404 int idx = find_first_zero_bit(list_entries_in_use,
1405 ARRAY_SIZE(list_entries));
1406
1407 if (idx >= ARRAY_SIZE(list_entries)) {
1408 if (!debug_locks_off_graph_unlock())
1409 return NULL;
1410
1411 nbcon_cpu_emergency_enter();
1412 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
1413 dump_stack();
1414 nbcon_cpu_emergency_exit();
1415 return NULL;
1416 }
1417 nr_list_entries++;
1418 __set_bit(idx, list_entries_in_use);
1419 return list_entries + idx;
1420 }
1421
1422 /*
1423 * Add a new dependency to the head of the list:
1424 */
add_lock_to_list(struct lock_class * this,struct lock_class * links_to,struct list_head * head,u16 distance,u8 dep,const struct lock_trace * trace)1425 static int add_lock_to_list(struct lock_class *this,
1426 struct lock_class *links_to, struct list_head *head,
1427 u16 distance, u8 dep,
1428 const struct lock_trace *trace)
1429 {
1430 struct lock_list *entry;
1431 /*
1432 * Lock not present yet - get a new dependency struct and
1433 * add it to the list:
1434 */
1435 entry = alloc_list_entry();
1436 if (!entry)
1437 return 0;
1438
1439 entry->class = this;
1440 entry->links_to = links_to;
1441 entry->dep = dep;
1442 entry->distance = distance;
1443 entry->trace = trace;
1444 /*
1445 * Both allocation and removal are done under the graph lock; but
1446 * iteration is under RCU-sched; see look_up_lock_class() and
1447 * lockdep_free_key_range().
1448 */
1449 list_add_tail_rcu(&entry->entry, head);
1450
1451 return 1;
1452 }
1453
1454 /*
1455 * For good efficiency of modular, we use power of 2
1456 */
1457 #define MAX_CIRCULAR_QUEUE_SIZE (1UL << CONFIG_LOCKDEP_CIRCULAR_QUEUE_BITS)
1458 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
1459
1460 /*
1461 * The circular_queue and helpers are used to implement graph
1462 * breadth-first search (BFS) algorithm, by which we can determine
1463 * whether there is a path from a lock to another. In deadlock checks,
1464 * a path from the next lock to be acquired to a previous held lock
1465 * indicates that adding the <prev> -> <next> lock dependency will
1466 * produce a circle in the graph. Breadth-first search instead of
1467 * depth-first search is used in order to find the shortest (circular)
1468 * path.
1469 */
1470 struct circular_queue {
1471 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
1472 unsigned int front, rear;
1473 };
1474
1475 static struct circular_queue lock_cq;
1476
1477 unsigned int max_bfs_queue_depth;
1478
1479 static unsigned int lockdep_dependency_gen_id;
1480
__cq_init(struct circular_queue * cq)1481 static inline void __cq_init(struct circular_queue *cq)
1482 {
1483 cq->front = cq->rear = 0;
1484 lockdep_dependency_gen_id++;
1485 }
1486
__cq_empty(struct circular_queue * cq)1487 static inline int __cq_empty(struct circular_queue *cq)
1488 {
1489 return (cq->front == cq->rear);
1490 }
1491
__cq_full(struct circular_queue * cq)1492 static inline int __cq_full(struct circular_queue *cq)
1493 {
1494 return ((cq->rear + 1) & CQ_MASK) == cq->front;
1495 }
1496
__cq_enqueue(struct circular_queue * cq,struct lock_list * elem)1497 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
1498 {
1499 if (__cq_full(cq))
1500 return -1;
1501
1502 cq->element[cq->rear] = elem;
1503 cq->rear = (cq->rear + 1) & CQ_MASK;
1504 return 0;
1505 }
1506
1507 /*
1508 * Dequeue an element from the circular_queue, return a lock_list if
1509 * the queue is not empty, or NULL if otherwise.
1510 */
__cq_dequeue(struct circular_queue * cq)1511 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
1512 {
1513 struct lock_list * lock;
1514
1515 if (__cq_empty(cq))
1516 return NULL;
1517
1518 lock = cq->element[cq->front];
1519 cq->front = (cq->front + 1) & CQ_MASK;
1520
1521 return lock;
1522 }
1523
__cq_get_elem_count(struct circular_queue * cq)1524 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
1525 {
1526 return (cq->rear - cq->front) & CQ_MASK;
1527 }
1528
mark_lock_accessed(struct lock_list * lock)1529 static inline void mark_lock_accessed(struct lock_list *lock)
1530 {
1531 lock->class->dep_gen_id = lockdep_dependency_gen_id;
1532 }
1533
visit_lock_entry(struct lock_list * lock,struct lock_list * parent)1534 static inline void visit_lock_entry(struct lock_list *lock,
1535 struct lock_list *parent)
1536 {
1537 lock->parent = parent;
1538 }
1539
lock_accessed(struct lock_list * lock)1540 static inline unsigned long lock_accessed(struct lock_list *lock)
1541 {
1542 return lock->class->dep_gen_id == lockdep_dependency_gen_id;
1543 }
1544
get_lock_parent(struct lock_list * child)1545 static inline struct lock_list *get_lock_parent(struct lock_list *child)
1546 {
1547 return child->parent;
1548 }
1549
get_lock_depth(struct lock_list * child)1550 static inline int get_lock_depth(struct lock_list *child)
1551 {
1552 int depth = 0;
1553 struct lock_list *parent;
1554
1555 while ((parent = get_lock_parent(child))) {
1556 child = parent;
1557 depth++;
1558 }
1559 return depth;
1560 }
1561
1562 /*
1563 * Return the forward or backward dependency list.
1564 *
1565 * @lock: the lock_list to get its class's dependency list
1566 * @offset: the offset to struct lock_class to determine whether it is
1567 * locks_after or locks_before
1568 */
get_dep_list(struct lock_list * lock,int offset)1569 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
1570 {
1571 void *lock_class = lock->class;
1572
1573 return lock_class + offset;
1574 }
1575 /*
1576 * Return values of a bfs search:
1577 *
1578 * BFS_E* indicates an error
1579 * BFS_R* indicates a result (match or not)
1580 *
1581 * BFS_EINVALIDNODE: Find a invalid node in the graph.
1582 *
1583 * BFS_EQUEUEFULL: The queue is full while doing the bfs.
1584 *
1585 * BFS_RMATCH: Find the matched node in the graph, and put that node into
1586 * *@target_entry.
1587 *
1588 * BFS_RNOMATCH: Haven't found the matched node and keep *@target_entry
1589 * _unchanged_.
1590 */
1591 enum bfs_result {
1592 BFS_EINVALIDNODE = -2,
1593 BFS_EQUEUEFULL = -1,
1594 BFS_RMATCH = 0,
1595 BFS_RNOMATCH = 1,
1596 };
1597
1598 /*
1599 * bfs_result < 0 means error
1600 */
bfs_error(enum bfs_result res)1601 static inline bool bfs_error(enum bfs_result res)
1602 {
1603 return res < 0;
1604 }
1605
1606 /*
1607 * DEP_*_BIT in lock_list::dep
1608 *
1609 * For dependency @prev -> @next:
1610 *
1611 * SR: @prev is shared reader (->read != 0) and @next is recursive reader
1612 * (->read == 2)
1613 * ER: @prev is exclusive locker (->read == 0) and @next is recursive reader
1614 * SN: @prev is shared reader and @next is non-recursive locker (->read != 2)
1615 * EN: @prev is exclusive locker and @next is non-recursive locker
1616 *
1617 * Note that we define the value of DEP_*_BITs so that:
1618 * bit0 is prev->read == 0
1619 * bit1 is next->read != 2
1620 */
1621 #define DEP_SR_BIT (0 + (0 << 1)) /* 0 */
1622 #define DEP_ER_BIT (1 + (0 << 1)) /* 1 */
1623 #define DEP_SN_BIT (0 + (1 << 1)) /* 2 */
1624 #define DEP_EN_BIT (1 + (1 << 1)) /* 3 */
1625
1626 #define DEP_SR_MASK (1U << (DEP_SR_BIT))
1627 #define DEP_ER_MASK (1U << (DEP_ER_BIT))
1628 #define DEP_SN_MASK (1U << (DEP_SN_BIT))
1629 #define DEP_EN_MASK (1U << (DEP_EN_BIT))
1630
1631 static inline unsigned int
__calc_dep_bit(struct held_lock * prev,struct held_lock * next)1632 __calc_dep_bit(struct held_lock *prev, struct held_lock *next)
1633 {
1634 return (prev->read == 0) + ((next->read != 2) << 1);
1635 }
1636
calc_dep(struct held_lock * prev,struct held_lock * next)1637 static inline u8 calc_dep(struct held_lock *prev, struct held_lock *next)
1638 {
1639 return 1U << __calc_dep_bit(prev, next);
1640 }
1641
1642 /*
1643 * calculate the dep_bit for backwards edges. We care about whether @prev is
1644 * shared and whether @next is recursive.
1645 */
1646 static inline unsigned int
__calc_dep_bitb(struct held_lock * prev,struct held_lock * next)1647 __calc_dep_bitb(struct held_lock *prev, struct held_lock *next)
1648 {
1649 return (next->read != 2) + ((prev->read == 0) << 1);
1650 }
1651
calc_depb(struct held_lock * prev,struct held_lock * next)1652 static inline u8 calc_depb(struct held_lock *prev, struct held_lock *next)
1653 {
1654 return 1U << __calc_dep_bitb(prev, next);
1655 }
1656
1657 /*
1658 * Initialize a lock_list entry @lock belonging to @class as the root for a BFS
1659 * search.
1660 */
__bfs_init_root(struct lock_list * lock,struct lock_class * class)1661 static inline void __bfs_init_root(struct lock_list *lock,
1662 struct lock_class *class)
1663 {
1664 lock->class = class;
1665 lock->parent = NULL;
1666 lock->only_xr = 0;
1667 }
1668
1669 /*
1670 * Initialize a lock_list entry @lock based on a lock acquisition @hlock as the
1671 * root for a BFS search.
1672 *
1673 * ->only_xr of the initial lock node is set to @hlock->read == 2, to make sure
1674 * that <prev> -> @hlock and @hlock -> <whatever __bfs() found> is not -(*R)->
1675 * and -(S*)->.
1676 */
bfs_init_root(struct lock_list * lock,struct held_lock * hlock)1677 static inline void bfs_init_root(struct lock_list *lock,
1678 struct held_lock *hlock)
1679 {
1680 __bfs_init_root(lock, hlock_class(hlock));
1681 lock->only_xr = (hlock->read == 2);
1682 }
1683
1684 /*
1685 * Similar to bfs_init_root() but initialize the root for backwards BFS.
1686 *
1687 * ->only_xr of the initial lock node is set to @hlock->read != 0, to make sure
1688 * that <next> -> @hlock and @hlock -> <whatever backwards BFS found> is not
1689 * -(*S)-> and -(R*)-> (reverse order of -(*R)-> and -(S*)->).
1690 */
bfs_init_rootb(struct lock_list * lock,struct held_lock * hlock)1691 static inline void bfs_init_rootb(struct lock_list *lock,
1692 struct held_lock *hlock)
1693 {
1694 __bfs_init_root(lock, hlock_class(hlock));
1695 lock->only_xr = (hlock->read != 0);
1696 }
1697
__bfs_next(struct lock_list * lock,int offset)1698 static inline struct lock_list *__bfs_next(struct lock_list *lock, int offset)
1699 {
1700 if (!lock || !lock->parent)
1701 return NULL;
1702
1703 return list_next_or_null_rcu(get_dep_list(lock->parent, offset),
1704 &lock->entry, struct lock_list, entry);
1705 }
1706
1707 /*
1708 * Breadth-First Search to find a strong path in the dependency graph.
1709 *
1710 * @source_entry: the source of the path we are searching for.
1711 * @data: data used for the second parameter of @match function
1712 * @match: match function for the search
1713 * @target_entry: pointer to the target of a matched path
1714 * @offset: the offset to struct lock_class to determine whether it is
1715 * locks_after or locks_before
1716 *
1717 * We may have multiple edges (considering different kinds of dependencies,
1718 * e.g. ER and SN) between two nodes in the dependency graph. But
1719 * only the strong dependency path in the graph is relevant to deadlocks. A
1720 * strong dependency path is a dependency path that doesn't have two adjacent
1721 * dependencies as -(*R)-> -(S*)->, please see:
1722 *
1723 * Documentation/locking/lockdep-design.rst
1724 *
1725 * for more explanation of the definition of strong dependency paths
1726 *
1727 * In __bfs(), we only traverse in the strong dependency path:
1728 *
1729 * In lock_list::only_xr, we record whether the previous dependency only
1730 * has -(*R)-> in the search, and if it does (prev only has -(*R)->), we
1731 * filter out any -(S*)-> in the current dependency and after that, the
1732 * ->only_xr is set according to whether we only have -(*R)-> left.
1733 */
__bfs(struct lock_list * source_entry,void * data,bool (* match)(struct lock_list * entry,void * data),bool (* skip)(struct lock_list * entry,void * data),struct lock_list ** target_entry,int offset)1734 static enum bfs_result __bfs(struct lock_list *source_entry,
1735 void *data,
1736 bool (*match)(struct lock_list *entry, void *data),
1737 bool (*skip)(struct lock_list *entry, void *data),
1738 struct lock_list **target_entry,
1739 int offset)
1740 {
1741 struct circular_queue *cq = &lock_cq;
1742 struct lock_list *lock = NULL;
1743 struct lock_list *entry;
1744 struct list_head *head;
1745 unsigned int cq_depth;
1746 bool first;
1747
1748 lockdep_assert_locked();
1749
1750 __cq_init(cq);
1751 __cq_enqueue(cq, source_entry);
1752
1753 while ((lock = __bfs_next(lock, offset)) || (lock = __cq_dequeue(cq))) {
1754 if (!lock->class)
1755 return BFS_EINVALIDNODE;
1756
1757 /*
1758 * Step 1: check whether we already finish on this one.
1759 *
1760 * If we have visited all the dependencies from this @lock to
1761 * others (iow, if we have visited all lock_list entries in
1762 * @lock->class->locks_{after,before}) we skip, otherwise go
1763 * and visit all the dependencies in the list and mark this
1764 * list accessed.
1765 */
1766 if (lock_accessed(lock))
1767 continue;
1768 else
1769 mark_lock_accessed(lock);
1770
1771 /*
1772 * Step 2: check whether prev dependency and this form a strong
1773 * dependency path.
1774 */
1775 if (lock->parent) { /* Parent exists, check prev dependency */
1776 u8 dep = lock->dep;
1777 bool prev_only_xr = lock->parent->only_xr;
1778
1779 /*
1780 * Mask out all -(S*)-> if we only have *R in previous
1781 * step, because -(*R)-> -(S*)-> don't make up a strong
1782 * dependency.
1783 */
1784 if (prev_only_xr)
1785 dep &= ~(DEP_SR_MASK | DEP_SN_MASK);
1786
1787 /* If nothing left, we skip */
1788 if (!dep)
1789 continue;
1790
1791 /* If there are only -(*R)-> left, set that for the next step */
1792 lock->only_xr = !(dep & (DEP_SN_MASK | DEP_EN_MASK));
1793 }
1794
1795 /*
1796 * Step 3: we haven't visited this and there is a strong
1797 * dependency path to this, so check with @match.
1798 * If @skip is provide and returns true, we skip this
1799 * lock (and any path this lock is in).
1800 */
1801 if (skip && skip(lock, data))
1802 continue;
1803
1804 if (match(lock, data)) {
1805 *target_entry = lock;
1806 return BFS_RMATCH;
1807 }
1808
1809 /*
1810 * Step 4: if not match, expand the path by adding the
1811 * forward or backwards dependencies in the search
1812 *
1813 */
1814 first = true;
1815 head = get_dep_list(lock, offset);
1816 list_for_each_entry_rcu(entry, head, entry) {
1817 visit_lock_entry(entry, lock);
1818
1819 /*
1820 * Note we only enqueue the first of the list into the
1821 * queue, because we can always find a sibling
1822 * dependency from one (see __bfs_next()), as a result
1823 * the space of queue is saved.
1824 */
1825 if (!first)
1826 continue;
1827
1828 first = false;
1829
1830 if (__cq_enqueue(cq, entry))
1831 return BFS_EQUEUEFULL;
1832
1833 cq_depth = __cq_get_elem_count(cq);
1834 if (max_bfs_queue_depth < cq_depth)
1835 max_bfs_queue_depth = cq_depth;
1836 }
1837 }
1838
1839 return BFS_RNOMATCH;
1840 }
1841
1842 static inline enum bfs_result
__bfs_forwards(struct lock_list * src_entry,void * data,bool (* match)(struct lock_list * entry,void * data),bool (* skip)(struct lock_list * entry,void * data),struct lock_list ** target_entry)1843 __bfs_forwards(struct lock_list *src_entry,
1844 void *data,
1845 bool (*match)(struct lock_list *entry, void *data),
1846 bool (*skip)(struct lock_list *entry, void *data),
1847 struct lock_list **target_entry)
1848 {
1849 return __bfs(src_entry, data, match, skip, target_entry,
1850 offsetof(struct lock_class, locks_after));
1851
1852 }
1853
1854 static inline enum bfs_result
__bfs_backwards(struct lock_list * src_entry,void * data,bool (* match)(struct lock_list * entry,void * data),bool (* skip)(struct lock_list * entry,void * data),struct lock_list ** target_entry)1855 __bfs_backwards(struct lock_list *src_entry,
1856 void *data,
1857 bool (*match)(struct lock_list *entry, void *data),
1858 bool (*skip)(struct lock_list *entry, void *data),
1859 struct lock_list **target_entry)
1860 {
1861 return __bfs(src_entry, data, match, skip, target_entry,
1862 offsetof(struct lock_class, locks_before));
1863
1864 }
1865
print_lock_trace(const struct lock_trace * trace,unsigned int spaces)1866 static void print_lock_trace(const struct lock_trace *trace,
1867 unsigned int spaces)
1868 {
1869 stack_trace_print(trace->entries, trace->nr_entries, spaces);
1870 }
1871
1872 /*
1873 * Print a dependency chain entry (this is only done when a deadlock
1874 * has been detected):
1875 */
1876 static noinline void
print_circular_bug_entry(struct lock_list * target,int depth)1877 print_circular_bug_entry(struct lock_list *target, int depth)
1878 {
1879 if (debug_locks_silent)
1880 return;
1881 printk("\n-> #%u", depth);
1882 print_lock_name(NULL, target->class);
1883 printk(KERN_CONT ":\n");
1884 print_lock_trace(target->trace, 6);
1885 }
1886
1887 static void
print_circular_lock_scenario(struct held_lock * src,struct held_lock * tgt,struct lock_list * prt)1888 print_circular_lock_scenario(struct held_lock *src,
1889 struct held_lock *tgt,
1890 struct lock_list *prt)
1891 {
1892 struct lock_class *source = hlock_class(src);
1893 struct lock_class *target = hlock_class(tgt);
1894 struct lock_class *parent = prt->class;
1895 int src_read = src->read;
1896 int tgt_read = tgt->read;
1897
1898 /*
1899 * A direct locking problem where unsafe_class lock is taken
1900 * directly by safe_class lock, then all we need to show
1901 * is the deadlock scenario, as it is obvious that the
1902 * unsafe lock is taken under the safe lock.
1903 *
1904 * But if there is a chain instead, where the safe lock takes
1905 * an intermediate lock (middle_class) where this lock is
1906 * not the same as the safe lock, then the lock chain is
1907 * used to describe the problem. Otherwise we would need
1908 * to show a different CPU case for each link in the chain
1909 * from the safe_class lock to the unsafe_class lock.
1910 */
1911 if (parent != source) {
1912 printk("Chain exists of:\n ");
1913 __print_lock_name(src, source);
1914 printk(KERN_CONT " --> ");
1915 __print_lock_name(NULL, parent);
1916 printk(KERN_CONT " --> ");
1917 __print_lock_name(tgt, target);
1918 printk(KERN_CONT "\n\n");
1919 }
1920
1921 printk(" Possible unsafe locking scenario:\n\n");
1922 printk(" CPU0 CPU1\n");
1923 printk(" ---- ----\n");
1924 if (tgt_read != 0)
1925 printk(" rlock(");
1926 else
1927 printk(" lock(");
1928 __print_lock_name(tgt, target);
1929 printk(KERN_CONT ");\n");
1930 printk(" lock(");
1931 __print_lock_name(NULL, parent);
1932 printk(KERN_CONT ");\n");
1933 printk(" lock(");
1934 __print_lock_name(tgt, target);
1935 printk(KERN_CONT ");\n");
1936 if (src_read != 0)
1937 printk(" rlock(");
1938 else if (src->sync)
1939 printk(" sync(");
1940 else
1941 printk(" lock(");
1942 __print_lock_name(src, source);
1943 printk(KERN_CONT ");\n");
1944 printk("\n *** DEADLOCK ***\n\n");
1945 }
1946
1947 /*
1948 * When a circular dependency is detected, print the
1949 * header first:
1950 */
1951 static noinline void
print_circular_bug_header(struct lock_list * entry,unsigned int depth,struct held_lock * check_src,struct held_lock * check_tgt)1952 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1953 struct held_lock *check_src,
1954 struct held_lock *check_tgt)
1955 {
1956 struct task_struct *curr = current;
1957
1958 if (debug_locks_silent)
1959 return;
1960
1961 pr_warn("\n");
1962 pr_warn("======================================================\n");
1963 pr_warn("WARNING: possible circular locking dependency detected\n");
1964 print_kernel_ident();
1965 pr_warn("------------------------------------------------------\n");
1966 pr_warn("%s/%d is trying to acquire lock:\n",
1967 curr->comm, task_pid_nr(curr));
1968 print_lock(check_src);
1969
1970 pr_warn("\nbut task is already holding lock:\n");
1971
1972 print_lock(check_tgt);
1973 pr_warn("\nwhich lock already depends on the new lock.\n\n");
1974 pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
1975
1976 print_circular_bug_entry(entry, depth);
1977 }
1978
1979 /*
1980 * We are about to add A -> B into the dependency graph, and in __bfs() a
1981 * strong dependency path A -> .. -> B is found: hlock_class equals
1982 * entry->class.
1983 *
1984 * If A -> .. -> B can replace A -> B in any __bfs() search (means the former
1985 * is _stronger_ than or equal to the latter), we consider A -> B as redundant.
1986 * For example if A -> .. -> B is -(EN)-> (i.e. A -(E*)-> .. -(*N)-> B), and A
1987 * -> B is -(ER)-> or -(EN)->, then we don't need to add A -> B into the
1988 * dependency graph, as any strong path ..-> A -> B ->.. we can get with
1989 * having dependency A -> B, we could already get a equivalent path ..-> A ->
1990 * .. -> B -> .. with A -> .. -> B. Therefore A -> B is redundant.
1991 *
1992 * We need to make sure both the start and the end of A -> .. -> B is not
1993 * weaker than A -> B. For the start part, please see the comment in
1994 * check_redundant(). For the end part, we need:
1995 *
1996 * Either
1997 *
1998 * a) A -> B is -(*R)-> (everything is not weaker than that)
1999 *
2000 * or
2001 *
2002 * b) A -> .. -> B is -(*N)-> (nothing is stronger than this)
2003 *
2004 */
hlock_equal(struct lock_list * entry,void * data)2005 static inline bool hlock_equal(struct lock_list *entry, void *data)
2006 {
2007 struct held_lock *hlock = (struct held_lock *)data;
2008
2009 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
2010 (hlock->read == 2 || /* A -> B is -(*R)-> */
2011 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
2012 }
2013
2014 /*
2015 * We are about to add B -> A into the dependency graph, and in __bfs() a
2016 * strong dependency path A -> .. -> B is found: hlock_class equals
2017 * entry->class.
2018 *
2019 * We will have a deadlock case (conflict) if A -> .. -> B -> A is a strong
2020 * dependency cycle, that means:
2021 *
2022 * Either
2023 *
2024 * a) B -> A is -(E*)->
2025 *
2026 * or
2027 *
2028 * b) A -> .. -> B is -(*N)-> (i.e. A -> .. -(*N)-> B)
2029 *
2030 * as then we don't have -(*R)-> -(S*)-> in the cycle.
2031 */
hlock_conflict(struct lock_list * entry,void * data)2032 static inline bool hlock_conflict(struct lock_list *entry, void *data)
2033 {
2034 struct held_lock *hlock = (struct held_lock *)data;
2035
2036 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
2037 (hlock->read == 0 || /* B -> A is -(E*)-> */
2038 !entry->only_xr); /* A -> .. -> B is -(*N)-> */
2039 }
2040
print_circular_bug(struct lock_list * this,struct lock_list * target,struct held_lock * check_src,struct held_lock * check_tgt)2041 static noinline void print_circular_bug(struct lock_list *this,
2042 struct lock_list *target,
2043 struct held_lock *check_src,
2044 struct held_lock *check_tgt)
2045 {
2046 struct task_struct *curr = current;
2047 struct lock_list *parent;
2048 struct lock_list *first_parent;
2049 int depth;
2050
2051 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2052 return;
2053
2054 this->trace = save_trace();
2055 if (!this->trace)
2056 return;
2057
2058 depth = get_lock_depth(target);
2059
2060 nbcon_cpu_emergency_enter();
2061
2062 print_circular_bug_header(target, depth, check_src, check_tgt);
2063
2064 parent = get_lock_parent(target);
2065 first_parent = parent;
2066
2067 while (parent) {
2068 print_circular_bug_entry(parent, --depth);
2069 parent = get_lock_parent(parent);
2070 }
2071
2072 printk("\nother info that might help us debug this:\n\n");
2073 print_circular_lock_scenario(check_src, check_tgt,
2074 first_parent);
2075
2076 lockdep_print_held_locks(curr);
2077
2078 printk("\nstack backtrace:\n");
2079 dump_stack();
2080
2081 nbcon_cpu_emergency_exit();
2082 }
2083
print_bfs_bug(int ret)2084 static noinline void print_bfs_bug(int ret)
2085 {
2086 if (!debug_locks_off_graph_unlock())
2087 return;
2088
2089 /*
2090 * Breadth-first-search failed, graph got corrupted?
2091 */
2092 if (ret == BFS_EQUEUEFULL)
2093 pr_warn("Increase LOCKDEP_CIRCULAR_QUEUE_BITS to avoid this warning:\n");
2094
2095 WARN(1, "lockdep bfs error:%d\n", ret);
2096 }
2097
noop_count(struct lock_list * entry,void * data)2098 static bool noop_count(struct lock_list *entry, void *data)
2099 {
2100 (*(unsigned long *)data)++;
2101 return false;
2102 }
2103
__lockdep_count_forward_deps(struct lock_list * this)2104 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
2105 {
2106 unsigned long count = 0;
2107 struct lock_list *target_entry;
2108
2109 __bfs_forwards(this, (void *)&count, noop_count, NULL, &target_entry);
2110
2111 return count;
2112 }
lockdep_count_forward_deps(struct lock_class * class)2113 unsigned long lockdep_count_forward_deps(struct lock_class *class)
2114 {
2115 unsigned long ret, flags;
2116 struct lock_list this;
2117
2118 __bfs_init_root(&this, class);
2119
2120 raw_local_irq_save(flags);
2121 lockdep_lock();
2122 ret = __lockdep_count_forward_deps(&this);
2123 lockdep_unlock();
2124 raw_local_irq_restore(flags);
2125
2126 return ret;
2127 }
2128
__lockdep_count_backward_deps(struct lock_list * this)2129 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
2130 {
2131 unsigned long count = 0;
2132 struct lock_list *target_entry;
2133
2134 __bfs_backwards(this, (void *)&count, noop_count, NULL, &target_entry);
2135
2136 return count;
2137 }
2138
lockdep_count_backward_deps(struct lock_class * class)2139 unsigned long lockdep_count_backward_deps(struct lock_class *class)
2140 {
2141 unsigned long ret, flags;
2142 struct lock_list this;
2143
2144 __bfs_init_root(&this, class);
2145
2146 raw_local_irq_save(flags);
2147 lockdep_lock();
2148 ret = __lockdep_count_backward_deps(&this);
2149 lockdep_unlock();
2150 raw_local_irq_restore(flags);
2151
2152 return ret;
2153 }
2154
2155 /*
2156 * Check that the dependency graph starting at <src> can lead to
2157 * <target> or not.
2158 */
2159 static noinline enum bfs_result
check_path(struct held_lock * target,struct lock_list * src_entry,bool (* match)(struct lock_list * entry,void * data),bool (* skip)(struct lock_list * entry,void * data),struct lock_list ** target_entry)2160 check_path(struct held_lock *target, struct lock_list *src_entry,
2161 bool (*match)(struct lock_list *entry, void *data),
2162 bool (*skip)(struct lock_list *entry, void *data),
2163 struct lock_list **target_entry)
2164 {
2165 enum bfs_result ret;
2166
2167 ret = __bfs_forwards(src_entry, target, match, skip, target_entry);
2168
2169 if (unlikely(bfs_error(ret)))
2170 print_bfs_bug(ret);
2171
2172 return ret;
2173 }
2174
2175 static void print_deadlock_bug(struct task_struct *, struct held_lock *, struct held_lock *);
2176
2177 /*
2178 * Prove that the dependency graph starting at <src> can not
2179 * lead to <target>. If it can, there is a circle when adding
2180 * <target> -> <src> dependency.
2181 *
2182 * Print an error and return BFS_RMATCH if it does.
2183 */
2184 static noinline enum bfs_result
check_noncircular(struct held_lock * src,struct held_lock * target,struct lock_trace ** const trace)2185 check_noncircular(struct held_lock *src, struct held_lock *target,
2186 struct lock_trace **const trace)
2187 {
2188 enum bfs_result ret;
2189 struct lock_list *target_entry;
2190 struct lock_list src_entry;
2191
2192 bfs_init_root(&src_entry, src);
2193
2194 debug_atomic_inc(nr_cyclic_checks);
2195
2196 ret = check_path(target, &src_entry, hlock_conflict, NULL, &target_entry);
2197
2198 if (unlikely(ret == BFS_RMATCH)) {
2199 if (!*trace) {
2200 /*
2201 * If save_trace fails here, the printing might
2202 * trigger a WARN but because of the !nr_entries it
2203 * should not do bad things.
2204 */
2205 *trace = save_trace();
2206 }
2207
2208 if (src->class_idx == target->class_idx)
2209 print_deadlock_bug(current, src, target);
2210 else
2211 print_circular_bug(&src_entry, target_entry, src, target);
2212 }
2213
2214 return ret;
2215 }
2216
2217 #ifdef CONFIG_TRACE_IRQFLAGS
2218
2219 /*
2220 * Forwards and backwards subgraph searching, for the purposes of
2221 * proving that two subgraphs can be connected by a new dependency
2222 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
2223 *
2224 * A irq safe->unsafe deadlock happens with the following conditions:
2225 *
2226 * 1) We have a strong dependency path A -> ... -> B
2227 *
2228 * 2) and we have ENABLED_IRQ usage of B and USED_IN_IRQ usage of A, therefore
2229 * irq can create a new dependency B -> A (consider the case that a holder
2230 * of B gets interrupted by an irq whose handler will try to acquire A).
2231 *
2232 * 3) the dependency circle A -> ... -> B -> A we get from 1) and 2) is a
2233 * strong circle:
2234 *
2235 * For the usage bits of B:
2236 * a) if A -> B is -(*N)->, then B -> A could be any type, so any
2237 * ENABLED_IRQ usage suffices.
2238 * b) if A -> B is -(*R)->, then B -> A must be -(E*)->, so only
2239 * ENABLED_IRQ_*_READ usage suffices.
2240 *
2241 * For the usage bits of A:
2242 * c) if A -> B is -(E*)->, then B -> A could be any type, so any
2243 * USED_IN_IRQ usage suffices.
2244 * d) if A -> B is -(S*)->, then B -> A must be -(*N)->, so only
2245 * USED_IN_IRQ_*_READ usage suffices.
2246 */
2247
2248 /*
2249 * There is a strong dependency path in the dependency graph: A -> B, and now
2250 * we need to decide which usage bit of A should be accumulated to detect
2251 * safe->unsafe bugs.
2252 *
2253 * Note that usage_accumulate() is used in backwards search, so ->only_xr
2254 * stands for whether A -> B only has -(S*)-> (in this case ->only_xr is true).
2255 *
2256 * As above, if only_xr is false, which means A -> B has -(E*)-> dependency
2257 * path, any usage of A should be considered. Otherwise, we should only
2258 * consider _READ usage.
2259 */
usage_accumulate(struct lock_list * entry,void * mask)2260 static inline bool usage_accumulate(struct lock_list *entry, void *mask)
2261 {
2262 if (!entry->only_xr)
2263 *(unsigned long *)mask |= entry->class->usage_mask;
2264 else /* Mask out _READ usage bits */
2265 *(unsigned long *)mask |= (entry->class->usage_mask & LOCKF_IRQ);
2266
2267 return false;
2268 }
2269
2270 /*
2271 * There is a strong dependency path in the dependency graph: A -> B, and now
2272 * we need to decide which usage bit of B conflicts with the usage bits of A,
2273 * i.e. which usage bit of B may introduce safe->unsafe deadlocks.
2274 *
2275 * As above, if only_xr is false, which means A -> B has -(*N)-> dependency
2276 * path, any usage of B should be considered. Otherwise, we should only
2277 * consider _READ usage.
2278 */
usage_match(struct lock_list * entry,void * mask)2279 static inline bool usage_match(struct lock_list *entry, void *mask)
2280 {
2281 if (!entry->only_xr)
2282 return !!(entry->class->usage_mask & *(unsigned long *)mask);
2283 else /* Mask out _READ usage bits */
2284 return !!((entry->class->usage_mask & LOCKF_IRQ) & *(unsigned long *)mask);
2285 }
2286
usage_skip(struct lock_list * entry,void * mask)2287 static inline bool usage_skip(struct lock_list *entry, void *mask)
2288 {
2289 if (entry->class->lock_type == LD_LOCK_NORMAL)
2290 return false;
2291
2292 /*
2293 * Skip local_lock() for irq inversion detection.
2294 *
2295 * For !RT, local_lock() is not a real lock, so it won't carry any
2296 * dependency.
2297 *
2298 * For RT, an irq inversion happens when we have lock A and B, and on
2299 * some CPU we can have:
2300 *
2301 * lock(A);
2302 * <interrupted>
2303 * lock(B);
2304 *
2305 * where lock(B) cannot sleep, and we have a dependency B -> ... -> A.
2306 *
2307 * Now we prove local_lock() cannot exist in that dependency. First we
2308 * have the observation for any lock chain L1 -> ... -> Ln, for any
2309 * 1 <= i <= n, Li.inner_wait_type <= L1.inner_wait_type, otherwise
2310 * wait context check will complain. And since B is not a sleep lock,
2311 * therefore B.inner_wait_type >= 2, and since the inner_wait_type of
2312 * local_lock() is 3, which is greater than 2, therefore there is no
2313 * way the local_lock() exists in the dependency B -> ... -> A.
2314 *
2315 * As a result, we will skip local_lock(), when we search for irq
2316 * inversion bugs.
2317 */
2318 if (entry->class->lock_type == LD_LOCK_PERCPU &&
2319 DEBUG_LOCKS_WARN_ON(entry->class->wait_type_inner < LD_WAIT_CONFIG))
2320 return false;
2321
2322 /*
2323 * Skip WAIT_OVERRIDE for irq inversion detection -- it's not actually
2324 * a lock and only used to override the wait_type.
2325 */
2326
2327 return true;
2328 }
2329
2330 /*
2331 * Find a node in the forwards-direction dependency sub-graph starting
2332 * at @root->class that matches @bit.
2333 *
2334 * Return BFS_MATCH if such a node exists in the subgraph, and put that node
2335 * into *@target_entry.
2336 */
2337 static enum bfs_result
find_usage_forwards(struct lock_list * root,unsigned long usage_mask,struct lock_list ** target_entry)2338 find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
2339 struct lock_list **target_entry)
2340 {
2341 enum bfs_result result;
2342
2343 debug_atomic_inc(nr_find_usage_forwards_checks);
2344
2345 result = __bfs_forwards(root, &usage_mask, usage_match, usage_skip, target_entry);
2346
2347 return result;
2348 }
2349
2350 /*
2351 * Find a node in the backwards-direction dependency sub-graph starting
2352 * at @root->class that matches @bit.
2353 */
2354 static enum bfs_result
find_usage_backwards(struct lock_list * root,unsigned long usage_mask,struct lock_list ** target_entry)2355 find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
2356 struct lock_list **target_entry)
2357 {
2358 enum bfs_result result;
2359
2360 debug_atomic_inc(nr_find_usage_backwards_checks);
2361
2362 result = __bfs_backwards(root, &usage_mask, usage_match, usage_skip, target_entry);
2363
2364 return result;
2365 }
2366
print_lock_class_header(struct lock_class * class,int depth)2367 static void print_lock_class_header(struct lock_class *class, int depth)
2368 {
2369 int bit;
2370
2371 printk("%*s->", depth, "");
2372 print_lock_name(NULL, class);
2373 #ifdef CONFIG_DEBUG_LOCKDEP
2374 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
2375 #endif
2376 printk(KERN_CONT " {\n");
2377
2378 for (bit = 0; bit < LOCK_TRACE_STATES; bit++) {
2379 if (class->usage_mask & (1 << bit)) {
2380 int len = depth;
2381
2382 len += printk("%*s %s", depth, "", usage_str[bit]);
2383 len += printk(KERN_CONT " at:\n");
2384 print_lock_trace(class->usage_traces[bit], len);
2385 }
2386 }
2387 printk("%*s }\n", depth, "");
2388
2389 printk("%*s ... key at: [<%px>] %pS\n",
2390 depth, "", class->key, class->key);
2391 }
2392
2393 /*
2394 * Dependency path printing:
2395 *
2396 * After BFS we get a lock dependency path (linked via ->parent of lock_list),
2397 * printing out each lock in the dependency path will help on understanding how
2398 * the deadlock could happen. Here are some details about dependency path
2399 * printing:
2400 *
2401 * 1) A lock_list can be either forwards or backwards for a lock dependency,
2402 * for a lock dependency A -> B, there are two lock_lists:
2403 *
2404 * a) lock_list in the ->locks_after list of A, whose ->class is B and
2405 * ->links_to is A. In this case, we can say the lock_list is
2406 * "A -> B" (forwards case).
2407 *
2408 * b) lock_list in the ->locks_before list of B, whose ->class is A
2409 * and ->links_to is B. In this case, we can say the lock_list is
2410 * "B <- A" (bacwards case).
2411 *
2412 * The ->trace of both a) and b) point to the call trace where B was
2413 * acquired with A held.
2414 *
2415 * 2) A "helper" lock_list is introduced during BFS, this lock_list doesn't
2416 * represent a certain lock dependency, it only provides an initial entry
2417 * for BFS. For example, BFS may introduce a "helper" lock_list whose
2418 * ->class is A, as a result BFS will search all dependencies starting with
2419 * A, e.g. A -> B or A -> C.
2420 *
2421 * The notation of a forwards helper lock_list is like "-> A", which means
2422 * we should search the forwards dependencies starting with "A", e.g A -> B
2423 * or A -> C.
2424 *
2425 * The notation of a bacwards helper lock_list is like "<- B", which means
2426 * we should search the backwards dependencies ending with "B", e.g.
2427 * B <- A or B <- C.
2428 */
2429
2430 /*
2431 * printk the shortest lock dependencies from @root to @leaf in reverse order.
2432 *
2433 * We have a lock dependency path as follow:
2434 *
2435 * @root @leaf
2436 * | |
2437 * V V
2438 * ->parent ->parent
2439 * | lock_list | <--------- | lock_list | ... | lock_list | <--------- | lock_list |
2440 * | -> L1 | | L1 -> L2 | ... |Ln-2 -> Ln-1| | Ln-1 -> Ln|
2441 *
2442 * , so it's natural that we start from @leaf and print every ->class and
2443 * ->trace until we reach the @root.
2444 */
2445 static void __used
print_shortest_lock_dependencies(struct lock_list * leaf,struct lock_list * root)2446 print_shortest_lock_dependencies(struct lock_list *leaf,
2447 struct lock_list *root)
2448 {
2449 struct lock_list *entry = leaf;
2450 int depth;
2451
2452 /*compute depth from generated tree by BFS*/
2453 depth = get_lock_depth(leaf);
2454
2455 do {
2456 print_lock_class_header(entry->class, depth);
2457 printk("%*s ... acquired at:\n", depth, "");
2458 print_lock_trace(entry->trace, 2);
2459 printk("\n");
2460
2461 if (depth == 0 && (entry != root)) {
2462 printk("lockdep:%s bad path found in chain graph\n", __func__);
2463 break;
2464 }
2465
2466 entry = get_lock_parent(entry);
2467 depth--;
2468 } while (entry && (depth >= 0));
2469 }
2470
2471 /*
2472 * printk the shortest lock dependencies from @leaf to @root.
2473 *
2474 * We have a lock dependency path (from a backwards search) as follow:
2475 *
2476 * @leaf @root
2477 * | |
2478 * V V
2479 * ->parent ->parent
2480 * | lock_list | ---------> | lock_list | ... | lock_list | ---------> | lock_list |
2481 * | L2 <- L1 | | L3 <- L2 | ... | Ln <- Ln-1 | | <- Ln |
2482 *
2483 * , so when we iterate from @leaf to @root, we actually print the lock
2484 * dependency path L1 -> L2 -> .. -> Ln in the non-reverse order.
2485 *
2486 * Another thing to notice here is that ->class of L2 <- L1 is L1, while the
2487 * ->trace of L2 <- L1 is the call trace of L2, in fact we don't have the call
2488 * trace of L1 in the dependency path, which is alright, because most of the
2489 * time we can figure out where L1 is held from the call trace of L2.
2490 */
2491 static void __used
print_shortest_lock_dependencies_backwards(struct lock_list * leaf,struct lock_list * root)2492 print_shortest_lock_dependencies_backwards(struct lock_list *leaf,
2493 struct lock_list *root)
2494 {
2495 struct lock_list *entry = leaf;
2496 const struct lock_trace *trace = NULL;
2497 int depth;
2498
2499 /*compute depth from generated tree by BFS*/
2500 depth = get_lock_depth(leaf);
2501
2502 do {
2503 print_lock_class_header(entry->class, depth);
2504 if (trace) {
2505 printk("%*s ... acquired at:\n", depth, "");
2506 print_lock_trace(trace, 2);
2507 printk("\n");
2508 }
2509
2510 /*
2511 * Record the pointer to the trace for the next lock_list
2512 * entry, see the comments for the function.
2513 */
2514 trace = entry->trace;
2515
2516 if (depth == 0 && (entry != root)) {
2517 printk("lockdep:%s bad path found in chain graph\n", __func__);
2518 break;
2519 }
2520
2521 entry = get_lock_parent(entry);
2522 depth--;
2523 } while (entry && (depth >= 0));
2524 }
2525
2526 static void
print_irq_lock_scenario(struct lock_list * safe_entry,struct lock_list * unsafe_entry,struct lock_class * prev_class,struct lock_class * next_class)2527 print_irq_lock_scenario(struct lock_list *safe_entry,
2528 struct lock_list *unsafe_entry,
2529 struct lock_class *prev_class,
2530 struct lock_class *next_class)
2531 {
2532 struct lock_class *safe_class = safe_entry->class;
2533 struct lock_class *unsafe_class = unsafe_entry->class;
2534 struct lock_class *middle_class = prev_class;
2535
2536 if (middle_class == safe_class)
2537 middle_class = next_class;
2538
2539 /*
2540 * A direct locking problem where unsafe_class lock is taken
2541 * directly by safe_class lock, then all we need to show
2542 * is the deadlock scenario, as it is obvious that the
2543 * unsafe lock is taken under the safe lock.
2544 *
2545 * But if there is a chain instead, where the safe lock takes
2546 * an intermediate lock (middle_class) where this lock is
2547 * not the same as the safe lock, then the lock chain is
2548 * used to describe the problem. Otherwise we would need
2549 * to show a different CPU case for each link in the chain
2550 * from the safe_class lock to the unsafe_class lock.
2551 */
2552 if (middle_class != unsafe_class) {
2553 printk("Chain exists of:\n ");
2554 __print_lock_name(NULL, safe_class);
2555 printk(KERN_CONT " --> ");
2556 __print_lock_name(NULL, middle_class);
2557 printk(KERN_CONT " --> ");
2558 __print_lock_name(NULL, unsafe_class);
2559 printk(KERN_CONT "\n\n");
2560 }
2561
2562 printk(" Possible interrupt unsafe locking scenario:\n\n");
2563 printk(" CPU0 CPU1\n");
2564 printk(" ---- ----\n");
2565 printk(" lock(");
2566 __print_lock_name(NULL, unsafe_class);
2567 printk(KERN_CONT ");\n");
2568 printk(" local_irq_disable();\n");
2569 printk(" lock(");
2570 __print_lock_name(NULL, safe_class);
2571 printk(KERN_CONT ");\n");
2572 printk(" lock(");
2573 __print_lock_name(NULL, middle_class);
2574 printk(KERN_CONT ");\n");
2575 printk(" <Interrupt>\n");
2576 printk(" lock(");
2577 __print_lock_name(NULL, safe_class);
2578 printk(KERN_CONT ");\n");
2579 printk("\n *** DEADLOCK ***\n\n");
2580 }
2581
2582 static void
print_bad_irq_dependency(struct task_struct * curr,struct lock_list * prev_root,struct lock_list * next_root,struct lock_list * backwards_entry,struct lock_list * forwards_entry,struct held_lock * prev,struct held_lock * next,enum lock_usage_bit bit1,enum lock_usage_bit bit2,const char * irqclass)2583 print_bad_irq_dependency(struct task_struct *curr,
2584 struct lock_list *prev_root,
2585 struct lock_list *next_root,
2586 struct lock_list *backwards_entry,
2587 struct lock_list *forwards_entry,
2588 struct held_lock *prev,
2589 struct held_lock *next,
2590 enum lock_usage_bit bit1,
2591 enum lock_usage_bit bit2,
2592 const char *irqclass)
2593 {
2594 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2595 return;
2596
2597 nbcon_cpu_emergency_enter();
2598
2599 pr_warn("\n");
2600 pr_warn("=====================================================\n");
2601 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
2602 irqclass, irqclass);
2603 print_kernel_ident();
2604 pr_warn("-----------------------------------------------------\n");
2605 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
2606 curr->comm, task_pid_nr(curr),
2607 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
2608 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
2609 lockdep_hardirqs_enabled(),
2610 curr->softirqs_enabled);
2611 print_lock(next);
2612
2613 pr_warn("\nand this task is already holding:\n");
2614 print_lock(prev);
2615 pr_warn("which would create a new lock dependency:\n");
2616 print_lock_name(prev, hlock_class(prev));
2617 pr_cont(" ->");
2618 print_lock_name(next, hlock_class(next));
2619 pr_cont("\n");
2620
2621 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
2622 irqclass);
2623 print_lock_name(NULL, backwards_entry->class);
2624 pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
2625
2626 print_lock_trace(backwards_entry->class->usage_traces[bit1], 1);
2627
2628 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
2629 print_lock_name(NULL, forwards_entry->class);
2630 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
2631 pr_warn("...");
2632
2633 print_lock_trace(forwards_entry->class->usage_traces[bit2], 1);
2634
2635 pr_warn("\nother info that might help us debug this:\n\n");
2636 print_irq_lock_scenario(backwards_entry, forwards_entry,
2637 hlock_class(prev), hlock_class(next));
2638
2639 lockdep_print_held_locks(curr);
2640
2641 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
2642 print_shortest_lock_dependencies_backwards(backwards_entry, prev_root);
2643
2644 pr_warn("\nthe dependencies between the lock to be acquired");
2645 pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
2646 next_root->trace = save_trace();
2647 if (!next_root->trace)
2648 goto out;
2649 print_shortest_lock_dependencies(forwards_entry, next_root);
2650
2651 pr_warn("\nstack backtrace:\n");
2652 dump_stack();
2653 out:
2654 nbcon_cpu_emergency_exit();
2655 }
2656
2657 static const char *state_names[] = {
2658 #define LOCKDEP_STATE(__STATE) \
2659 __stringify(__STATE),
2660 #include "lockdep_states.h"
2661 #undef LOCKDEP_STATE
2662 };
2663
2664 static const char *state_rnames[] = {
2665 #define LOCKDEP_STATE(__STATE) \
2666 __stringify(__STATE)"-READ",
2667 #include "lockdep_states.h"
2668 #undef LOCKDEP_STATE
2669 };
2670
state_name(enum lock_usage_bit bit)2671 static inline const char *state_name(enum lock_usage_bit bit)
2672 {
2673 if (bit & LOCK_USAGE_READ_MASK)
2674 return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
2675 else
2676 return state_names[bit >> LOCK_USAGE_DIR_MASK];
2677 }
2678
2679 /*
2680 * The bit number is encoded like:
2681 *
2682 * bit0: 0 exclusive, 1 read lock
2683 * bit1: 0 used in irq, 1 irq enabled
2684 * bit2-n: state
2685 */
exclusive_bit(int new_bit)2686 static int exclusive_bit(int new_bit)
2687 {
2688 int state = new_bit & LOCK_USAGE_STATE_MASK;
2689 int dir = new_bit & LOCK_USAGE_DIR_MASK;
2690
2691 /*
2692 * keep state, bit flip the direction and strip read.
2693 */
2694 return state | (dir ^ LOCK_USAGE_DIR_MASK);
2695 }
2696
2697 /*
2698 * Observe that when given a bitmask where each bitnr is encoded as above, a
2699 * right shift of the mask transforms the individual bitnrs as -1 and
2700 * conversely, a left shift transforms into +1 for the individual bitnrs.
2701 *
2702 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
2703 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
2704 * instead by subtracting the bit number by 2, or shifting the mask right by 2.
2705 *
2706 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
2707 *
2708 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
2709 * all bits set) and recompose with bitnr1 flipped.
2710 */
invert_dir_mask(unsigned long mask)2711 static unsigned long invert_dir_mask(unsigned long mask)
2712 {
2713 unsigned long excl = 0;
2714
2715 /* Invert dir */
2716 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
2717 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
2718
2719 return excl;
2720 }
2721
2722 /*
2723 * Note that a LOCK_ENABLED_IRQ_*_READ usage and a LOCK_USED_IN_IRQ_*_READ
2724 * usage may cause deadlock too, for example:
2725 *
2726 * P1 P2
2727 * <irq disabled>
2728 * write_lock(l1); <irq enabled>
2729 * read_lock(l2);
2730 * write_lock(l2);
2731 * <in irq>
2732 * read_lock(l1);
2733 *
2734 * , in above case, l1 will be marked as LOCK_USED_IN_IRQ_HARDIRQ_READ and l2
2735 * will marked as LOCK_ENABLE_IRQ_HARDIRQ_READ, and this is a possible
2736 * deadlock.
2737 *
2738 * In fact, all of the following cases may cause deadlocks:
2739 *
2740 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*
2741 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*
2742 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*_READ
2743 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*_READ
2744 *
2745 * As a result, to calculate the "exclusive mask", first we invert the
2746 * direction (USED_IN/ENABLED) of the original mask, and 1) for all bits with
2747 * bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*). 2) for all
2748 * bits with bitnr0 cleared (LOCK_*_READ), add those with bitnr0 set (LOCK_*).
2749 */
exclusive_mask(unsigned long mask)2750 static unsigned long exclusive_mask(unsigned long mask)
2751 {
2752 unsigned long excl = invert_dir_mask(mask);
2753
2754 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2755 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2756
2757 return excl;
2758 }
2759
2760 /*
2761 * Retrieve the _possible_ original mask to which @mask is
2762 * exclusive. Ie: this is the opposite of exclusive_mask().
2763 * Note that 2 possible original bits can match an exclusive
2764 * bit: one has LOCK_USAGE_READ_MASK set, the other has it
2765 * cleared. So both are returned for each exclusive bit.
2766 */
original_mask(unsigned long mask)2767 static unsigned long original_mask(unsigned long mask)
2768 {
2769 unsigned long excl = invert_dir_mask(mask);
2770
2771 /* Include read in existing usages */
2772 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
2773 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
2774
2775 return excl;
2776 }
2777
2778 /*
2779 * Find the first pair of bit match between an original
2780 * usage mask and an exclusive usage mask.
2781 */
find_exclusive_match(unsigned long mask,unsigned long excl_mask,enum lock_usage_bit * bitp,enum lock_usage_bit * excl_bitp)2782 static int find_exclusive_match(unsigned long mask,
2783 unsigned long excl_mask,
2784 enum lock_usage_bit *bitp,
2785 enum lock_usage_bit *excl_bitp)
2786 {
2787 int bit, excl, excl_read;
2788
2789 for_each_set_bit(bit, &mask, LOCK_USED) {
2790 /*
2791 * exclusive_bit() strips the read bit, however,
2792 * LOCK_ENABLED_IRQ_*_READ may cause deadlocks too, so we need
2793 * to search excl | LOCK_USAGE_READ_MASK as well.
2794 */
2795 excl = exclusive_bit(bit);
2796 excl_read = excl | LOCK_USAGE_READ_MASK;
2797 if (excl_mask & lock_flag(excl)) {
2798 *bitp = bit;
2799 *excl_bitp = excl;
2800 return 0;
2801 } else if (excl_mask & lock_flag(excl_read)) {
2802 *bitp = bit;
2803 *excl_bitp = excl_read;
2804 return 0;
2805 }
2806 }
2807 return -1;
2808 }
2809
2810 /*
2811 * Prove that the new dependency does not connect a hardirq-safe(-read)
2812 * lock with a hardirq-unsafe lock - to achieve this we search
2813 * the backwards-subgraph starting at <prev>, and the
2814 * forwards-subgraph starting at <next>:
2815 */
check_irq_usage(struct task_struct * curr,struct held_lock * prev,struct held_lock * next)2816 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
2817 struct held_lock *next)
2818 {
2819 unsigned long usage_mask = 0, forward_mask, backward_mask;
2820 enum lock_usage_bit forward_bit = 0, backward_bit = 0;
2821 struct lock_list *target_entry1;
2822 struct lock_list *target_entry;
2823 struct lock_list this, that;
2824 enum bfs_result ret;
2825
2826 /*
2827 * Step 1: gather all hard/soft IRQs usages backward in an
2828 * accumulated usage mask.
2829 */
2830 bfs_init_rootb(&this, prev);
2831
2832 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, usage_skip, NULL);
2833 if (bfs_error(ret)) {
2834 print_bfs_bug(ret);
2835 return 0;
2836 }
2837
2838 usage_mask &= LOCKF_USED_IN_IRQ_ALL;
2839 if (!usage_mask)
2840 return 1;
2841
2842 /*
2843 * Step 2: find exclusive uses forward that match the previous
2844 * backward accumulated mask.
2845 */
2846 forward_mask = exclusive_mask(usage_mask);
2847
2848 bfs_init_root(&that, next);
2849
2850 ret = find_usage_forwards(&that, forward_mask, &target_entry1);
2851 if (bfs_error(ret)) {
2852 print_bfs_bug(ret);
2853 return 0;
2854 }
2855 if (ret == BFS_RNOMATCH)
2856 return 1;
2857
2858 /*
2859 * Step 3: we found a bad match! Now retrieve a lock from the backward
2860 * list whose usage mask matches the exclusive usage mask from the
2861 * lock found on the forward list.
2862 *
2863 * Note, we should only keep the LOCKF_ENABLED_IRQ_ALL bits, considering
2864 * the follow case:
2865 *
2866 * When trying to add A -> B to the graph, we find that there is a
2867 * hardirq-safe L, that L -> ... -> A, and another hardirq-unsafe M,
2868 * that B -> ... -> M. However M is **softirq-safe**, if we use exact
2869 * invert bits of M's usage_mask, we will find another lock N that is
2870 * **softirq-unsafe** and N -> ... -> A, however N -> .. -> M will not
2871 * cause a inversion deadlock.
2872 */
2873 backward_mask = original_mask(target_entry1->class->usage_mask & LOCKF_ENABLED_IRQ_ALL);
2874
2875 ret = find_usage_backwards(&this, backward_mask, &target_entry);
2876 if (bfs_error(ret)) {
2877 print_bfs_bug(ret);
2878 return 0;
2879 }
2880 if (DEBUG_LOCKS_WARN_ON(ret == BFS_RNOMATCH))
2881 return 1;
2882
2883 /*
2884 * Step 4: narrow down to a pair of incompatible usage bits
2885 * and report it.
2886 */
2887 ret = find_exclusive_match(target_entry->class->usage_mask,
2888 target_entry1->class->usage_mask,
2889 &backward_bit, &forward_bit);
2890 if (DEBUG_LOCKS_WARN_ON(ret == -1))
2891 return 1;
2892
2893 print_bad_irq_dependency(curr, &this, &that,
2894 target_entry, target_entry1,
2895 prev, next,
2896 backward_bit, forward_bit,
2897 state_name(backward_bit));
2898
2899 return 0;
2900 }
2901
2902 #else
2903
check_irq_usage(struct task_struct * curr,struct held_lock * prev,struct held_lock * next)2904 static inline int check_irq_usage(struct task_struct *curr,
2905 struct held_lock *prev, struct held_lock *next)
2906 {
2907 return 1;
2908 }
2909
usage_skip(struct lock_list * entry,void * mask)2910 static inline bool usage_skip(struct lock_list *entry, void *mask)
2911 {
2912 return false;
2913 }
2914
2915 #endif /* CONFIG_TRACE_IRQFLAGS */
2916
2917 #ifdef CONFIG_LOCKDEP_SMALL
2918 /*
2919 * Check that the dependency graph starting at <src> can lead to
2920 * <target> or not. If it can, <src> -> <target> dependency is already
2921 * in the graph.
2922 *
2923 * Return BFS_RMATCH if it does, or BFS_RNOMATCH if it does not, return BFS_E* if
2924 * any error appears in the bfs search.
2925 */
2926 static noinline enum bfs_result
check_redundant(struct held_lock * src,struct held_lock * target)2927 check_redundant(struct held_lock *src, struct held_lock *target)
2928 {
2929 enum bfs_result ret;
2930 struct lock_list *target_entry;
2931 struct lock_list src_entry;
2932
2933 bfs_init_root(&src_entry, src);
2934 /*
2935 * Special setup for check_redundant().
2936 *
2937 * To report redundant, we need to find a strong dependency path that
2938 * is equal to or stronger than <src> -> <target>. So if <src> is E,
2939 * we need to let __bfs() only search for a path starting at a -(E*)->,
2940 * we achieve this by setting the initial node's ->only_xr to true in
2941 * that case. And if <prev> is S, we set initial ->only_xr to false
2942 * because both -(S*)-> (equal) and -(E*)-> (stronger) are redundant.
2943 */
2944 src_entry.only_xr = src->read == 0;
2945
2946 debug_atomic_inc(nr_redundant_checks);
2947
2948 /*
2949 * Note: we skip local_lock() for redundant check, because as the
2950 * comment in usage_skip(), A -> local_lock() -> B and A -> B are not
2951 * the same.
2952 */
2953 ret = check_path(target, &src_entry, hlock_equal, usage_skip, &target_entry);
2954
2955 if (ret == BFS_RMATCH)
2956 debug_atomic_inc(nr_redundant);
2957
2958 return ret;
2959 }
2960
2961 #else
2962
2963 static inline enum bfs_result
check_redundant(struct held_lock * src,struct held_lock * target)2964 check_redundant(struct held_lock *src, struct held_lock *target)
2965 {
2966 return BFS_RNOMATCH;
2967 }
2968
2969 #endif
2970
inc_chains(int irq_context)2971 static void inc_chains(int irq_context)
2972 {
2973 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2974 nr_hardirq_chains++;
2975 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2976 nr_softirq_chains++;
2977 else
2978 nr_process_chains++;
2979 }
2980
dec_chains(int irq_context)2981 static void dec_chains(int irq_context)
2982 {
2983 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
2984 nr_hardirq_chains--;
2985 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
2986 nr_softirq_chains--;
2987 else
2988 nr_process_chains--;
2989 }
2990
2991 static void
print_deadlock_scenario(struct held_lock * nxt,struct held_lock * prv)2992 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
2993 {
2994 struct lock_class *next = hlock_class(nxt);
2995 struct lock_class *prev = hlock_class(prv);
2996
2997 printk(" Possible unsafe locking scenario:\n\n");
2998 printk(" CPU0\n");
2999 printk(" ----\n");
3000 printk(" lock(");
3001 __print_lock_name(prv, prev);
3002 printk(KERN_CONT ");\n");
3003 printk(" lock(");
3004 __print_lock_name(nxt, next);
3005 printk(KERN_CONT ");\n");
3006 printk("\n *** DEADLOCK ***\n\n");
3007 printk(" May be due to missing lock nesting notation\n\n");
3008 }
3009
3010 static void
print_deadlock_bug(struct task_struct * curr,struct held_lock * prev,struct held_lock * next)3011 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
3012 struct held_lock *next)
3013 {
3014 struct lock_class *class = hlock_class(prev);
3015
3016 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
3017 return;
3018
3019 nbcon_cpu_emergency_enter();
3020
3021 pr_warn("\n");
3022 pr_warn("============================================\n");
3023 pr_warn("WARNING: possible recursive locking detected\n");
3024 print_kernel_ident();
3025 pr_warn("--------------------------------------------\n");
3026 pr_warn("%s/%d is trying to acquire lock:\n",
3027 curr->comm, task_pid_nr(curr));
3028 print_lock(next);
3029 pr_warn("\nbut task is already holding lock:\n");
3030 print_lock(prev);
3031
3032 if (class->cmp_fn) {
3033 pr_warn("and the lock comparison function returns %i:\n",
3034 class->cmp_fn(prev->instance, next->instance));
3035 }
3036
3037 pr_warn("\nother info that might help us debug this:\n");
3038 print_deadlock_scenario(next, prev);
3039 lockdep_print_held_locks(curr);
3040
3041 pr_warn("\nstack backtrace:\n");
3042 dump_stack();
3043
3044 nbcon_cpu_emergency_exit();
3045 }
3046
3047 /*
3048 * Check whether we are holding such a class already.
3049 *
3050 * (Note that this has to be done separately, because the graph cannot
3051 * detect such classes of deadlocks.)
3052 *
3053 * Returns: 0 on deadlock detected, 1 on OK, 2 if another lock with the same
3054 * lock class is held but nest_lock is also held, i.e. we rely on the
3055 * nest_lock to avoid the deadlock.
3056 */
3057 static int
check_deadlock(struct task_struct * curr,struct held_lock * next)3058 check_deadlock(struct task_struct *curr, struct held_lock *next)
3059 {
3060 struct lock_class *class;
3061 struct held_lock *prev;
3062 struct held_lock *nest = NULL;
3063 int i;
3064
3065 for (i = 0; i < curr->lockdep_depth; i++) {
3066 prev = curr->held_locks + i;
3067
3068 if (prev->instance == next->nest_lock)
3069 nest = prev;
3070
3071 if (hlock_class(prev) != hlock_class(next))
3072 continue;
3073
3074 /*
3075 * Allow read-after-read recursion of the same
3076 * lock class (i.e. read_lock(lock)+read_lock(lock)):
3077 */
3078 if ((next->read == 2) && prev->read)
3079 continue;
3080
3081 class = hlock_class(prev);
3082
3083 if (class->cmp_fn &&
3084 class->cmp_fn(prev->instance, next->instance) < 0)
3085 continue;
3086
3087 /*
3088 * We're holding the nest_lock, which serializes this lock's
3089 * nesting behaviour.
3090 */
3091 if (nest)
3092 return 2;
3093
3094 print_deadlock_bug(curr, prev, next);
3095 return 0;
3096 }
3097 return 1;
3098 }
3099
3100 /*
3101 * There was a chain-cache miss, and we are about to add a new dependency
3102 * to a previous lock. We validate the following rules:
3103 *
3104 * - would the adding of the <prev> -> <next> dependency create a
3105 * circular dependency in the graph? [== circular deadlock]
3106 *
3107 * - does the new prev->next dependency connect any hardirq-safe lock
3108 * (in the full backwards-subgraph starting at <prev>) with any
3109 * hardirq-unsafe lock (in the full forwards-subgraph starting at
3110 * <next>)? [== illegal lock inversion with hardirq contexts]
3111 *
3112 * - does the new prev->next dependency connect any softirq-safe lock
3113 * (in the full backwards-subgraph starting at <prev>) with any
3114 * softirq-unsafe lock (in the full forwards-subgraph starting at
3115 * <next>)? [== illegal lock inversion with softirq contexts]
3116 *
3117 * any of these scenarios could lead to a deadlock.
3118 *
3119 * Then if all the validations pass, we add the forwards and backwards
3120 * dependency.
3121 */
3122 static int
check_prev_add(struct task_struct * curr,struct held_lock * prev,struct held_lock * next,u16 distance,struct lock_trace ** const trace)3123 check_prev_add(struct task_struct *curr, struct held_lock *prev,
3124 struct held_lock *next, u16 distance,
3125 struct lock_trace **const trace)
3126 {
3127 struct lock_list *entry;
3128 enum bfs_result ret;
3129
3130 if (!hlock_class(prev)->key || !hlock_class(next)->key) {
3131 /*
3132 * The warning statements below may trigger a use-after-free
3133 * of the class name. It is better to trigger a use-after free
3134 * and to have the class name most of the time instead of not
3135 * having the class name available.
3136 */
3137 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
3138 "Detected use-after-free of lock class %px/%s\n",
3139 hlock_class(prev),
3140 hlock_class(prev)->name);
3141 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
3142 "Detected use-after-free of lock class %px/%s\n",
3143 hlock_class(next),
3144 hlock_class(next)->name);
3145 return 2;
3146 }
3147
3148 if (prev->class_idx == next->class_idx) {
3149 struct lock_class *class = hlock_class(prev);
3150
3151 if (class->cmp_fn &&
3152 class->cmp_fn(prev->instance, next->instance) < 0)
3153 return 2;
3154 }
3155
3156 /*
3157 * Prove that the new <prev> -> <next> dependency would not
3158 * create a circular dependency in the graph. (We do this by
3159 * a breadth-first search into the graph starting at <next>,
3160 * and check whether we can reach <prev>.)
3161 *
3162 * The search is limited by the size of the circular queue (i.e.,
3163 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
3164 * in the graph whose neighbours are to be checked.
3165 */
3166 ret = check_noncircular(next, prev, trace);
3167 if (unlikely(bfs_error(ret) || ret == BFS_RMATCH))
3168 return 0;
3169
3170 if (!check_irq_usage(curr, prev, next))
3171 return 0;
3172
3173 /*
3174 * Is the <prev> -> <next> dependency already present?
3175 *
3176 * (this may occur even though this is a new chain: consider
3177 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
3178 * chains - the second one will be new, but L1 already has
3179 * L2 added to its dependency list, due to the first chain.)
3180 */
3181 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
3182 if (entry->class == hlock_class(next)) {
3183 if (distance == 1)
3184 entry->distance = 1;
3185 entry->dep |= calc_dep(prev, next);
3186
3187 /*
3188 * Also, update the reverse dependency in @next's
3189 * ->locks_before list.
3190 *
3191 * Here we reuse @entry as the cursor, which is fine
3192 * because we won't go to the next iteration of the
3193 * outer loop:
3194 *
3195 * For normal cases, we return in the inner loop.
3196 *
3197 * If we fail to return, we have inconsistency, i.e.
3198 * <prev>::locks_after contains <next> while
3199 * <next>::locks_before doesn't contain <prev>. In
3200 * that case, we return after the inner and indicate
3201 * something is wrong.
3202 */
3203 list_for_each_entry(entry, &hlock_class(next)->locks_before, entry) {
3204 if (entry->class == hlock_class(prev)) {
3205 if (distance == 1)
3206 entry->distance = 1;
3207 entry->dep |= calc_depb(prev, next);
3208 return 1;
3209 }
3210 }
3211
3212 /* <prev> is not found in <next>::locks_before */
3213 return 0;
3214 }
3215 }
3216
3217 /*
3218 * Is the <prev> -> <next> link redundant?
3219 */
3220 ret = check_redundant(prev, next);
3221 if (bfs_error(ret))
3222 return 0;
3223 else if (ret == BFS_RMATCH)
3224 return 2;
3225
3226 if (!*trace) {
3227 *trace = save_trace();
3228 if (!*trace)
3229 return 0;
3230 }
3231
3232 /*
3233 * Ok, all validations passed, add the new lock
3234 * to the previous lock's dependency list:
3235 */
3236 ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
3237 &hlock_class(prev)->locks_after, distance,
3238 calc_dep(prev, next), *trace);
3239
3240 if (!ret)
3241 return 0;
3242
3243 ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
3244 &hlock_class(next)->locks_before, distance,
3245 calc_depb(prev, next), *trace);
3246 if (!ret)
3247 return 0;
3248
3249 return 2;
3250 }
3251
3252 /*
3253 * Add the dependency to all directly-previous locks that are 'relevant'.
3254 * The ones that are relevant are (in increasing distance from curr):
3255 * all consecutive trylock entries and the final non-trylock entry - or
3256 * the end of this context's lock-chain - whichever comes first.
3257 */
3258 static int
check_prevs_add(struct task_struct * curr,struct held_lock * next)3259 check_prevs_add(struct task_struct *curr, struct held_lock *next)
3260 {
3261 struct lock_trace *trace = NULL;
3262 int depth = curr->lockdep_depth;
3263 struct held_lock *hlock;
3264
3265 /*
3266 * Debugging checks.
3267 *
3268 * Depth must not be zero for a non-head lock:
3269 */
3270 if (!depth)
3271 goto out_bug;
3272 /*
3273 * At least two relevant locks must exist for this
3274 * to be a head:
3275 */
3276 if (curr->held_locks[depth].irq_context !=
3277 curr->held_locks[depth-1].irq_context)
3278 goto out_bug;
3279
3280 for (;;) {
3281 u16 distance = curr->lockdep_depth - depth + 1;
3282 hlock = curr->held_locks + depth - 1;
3283
3284 if (hlock->check) {
3285 int ret = check_prev_add(curr, hlock, next, distance, &trace);
3286 if (!ret)
3287 return 0;
3288
3289 /*
3290 * Stop after the first non-trylock entry,
3291 * as non-trylock entries have added their
3292 * own direct dependencies already, so this
3293 * lock is connected to them indirectly:
3294 */
3295 if (!hlock->trylock)
3296 break;
3297 }
3298
3299 depth--;
3300 /*
3301 * End of lock-stack?
3302 */
3303 if (!depth)
3304 break;
3305 /*
3306 * Stop the search if we cross into another context:
3307 */
3308 if (curr->held_locks[depth].irq_context !=
3309 curr->held_locks[depth-1].irq_context)
3310 break;
3311 }
3312 return 1;
3313 out_bug:
3314 if (!debug_locks_off_graph_unlock())
3315 return 0;
3316
3317 /*
3318 * Clearly we all shouldn't be here, but since we made it we
3319 * can reliable say we messed up our state. See the above two
3320 * gotos for reasons why we could possibly end up here.
3321 */
3322 WARN_ON(1);
3323
3324 return 0;
3325 }
3326
3327 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
3328 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
3329 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
3330 unsigned long nr_zapped_lock_chains;
3331 unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */
3332 unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */
3333 unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */
3334
3335 /*
3336 * The first 2 chain_hlocks entries in the chain block in the bucket
3337 * list contains the following meta data:
3338 *
3339 * entry[0]:
3340 * Bit 15 - always set to 1 (it is not a class index)
3341 * Bits 0-14 - upper 15 bits of the next block index
3342 * entry[1] - lower 16 bits of next block index
3343 *
3344 * A next block index of all 1 bits means it is the end of the list.
3345 *
3346 * On the unsized bucket (bucket-0), the 3rd and 4th entries contain
3347 * the chain block size:
3348 *
3349 * entry[2] - upper 16 bits of the chain block size
3350 * entry[3] - lower 16 bits of the chain block size
3351 */
3352 #define MAX_CHAIN_BUCKETS 16
3353 #define CHAIN_BLK_FLAG (1U << 15)
3354 #define CHAIN_BLK_LIST_END 0xFFFFU
3355
3356 static int chain_block_buckets[MAX_CHAIN_BUCKETS];
3357
size_to_bucket(int size)3358 static inline int size_to_bucket(int size)
3359 {
3360 if (size > MAX_CHAIN_BUCKETS)
3361 return 0;
3362
3363 return size - 1;
3364 }
3365
3366 /*
3367 * Iterate all the chain blocks in a bucket.
3368 */
3369 #define for_each_chain_block(bucket, prev, curr) \
3370 for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \
3371 (curr) >= 0; \
3372 (prev) = (curr), (curr) = chain_block_next(curr))
3373
3374 /*
3375 * next block or -1
3376 */
chain_block_next(int offset)3377 static inline int chain_block_next(int offset)
3378 {
3379 int next = chain_hlocks[offset];
3380
3381 WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG));
3382
3383 if (next == CHAIN_BLK_LIST_END)
3384 return -1;
3385
3386 next &= ~CHAIN_BLK_FLAG;
3387 next <<= 16;
3388 next |= chain_hlocks[offset + 1];
3389
3390 return next;
3391 }
3392
3393 /*
3394 * bucket-0 only
3395 */
chain_block_size(int offset)3396 static inline int chain_block_size(int offset)
3397 {
3398 return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3];
3399 }
3400
init_chain_block(int offset,int next,int bucket,int size)3401 static inline void init_chain_block(int offset, int next, int bucket, int size)
3402 {
3403 chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG;
3404 chain_hlocks[offset + 1] = (u16)next;
3405
3406 if (size && !bucket) {
3407 chain_hlocks[offset + 2] = size >> 16;
3408 chain_hlocks[offset + 3] = (u16)size;
3409 }
3410 }
3411
add_chain_block(int offset,int size)3412 static inline void add_chain_block(int offset, int size)
3413 {
3414 int bucket = size_to_bucket(size);
3415 int next = chain_block_buckets[bucket];
3416 int prev, curr;
3417
3418 if (unlikely(size < 2)) {
3419 /*
3420 * We can't store single entries on the freelist. Leak them.
3421 *
3422 * One possible way out would be to uniquely mark them, other
3423 * than with CHAIN_BLK_FLAG, such that we can recover them when
3424 * the block before it is re-added.
3425 */
3426 if (size)
3427 nr_lost_chain_hlocks++;
3428 return;
3429 }
3430
3431 nr_free_chain_hlocks += size;
3432 if (!bucket) {
3433 nr_large_chain_blocks++;
3434
3435 /*
3436 * Variable sized, sort large to small.
3437 */
3438 for_each_chain_block(0, prev, curr) {
3439 if (size >= chain_block_size(curr))
3440 break;
3441 }
3442 init_chain_block(offset, curr, 0, size);
3443 if (prev < 0)
3444 chain_block_buckets[0] = offset;
3445 else
3446 init_chain_block(prev, offset, 0, 0);
3447 return;
3448 }
3449 /*
3450 * Fixed size, add to head.
3451 */
3452 init_chain_block(offset, next, bucket, size);
3453 chain_block_buckets[bucket] = offset;
3454 }
3455
3456 /*
3457 * Only the first block in the list can be deleted.
3458 *
3459 * For the variable size bucket[0], the first block (the largest one) is
3460 * returned, broken up and put back into the pool. So if a chain block of
3461 * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be
3462 * queued up after the primordial chain block and never be used until the
3463 * hlock entries in the primordial chain block is almost used up. That
3464 * causes fragmentation and reduce allocation efficiency. That can be
3465 * monitored by looking at the "large chain blocks" number in lockdep_stats.
3466 */
del_chain_block(int bucket,int size,int next)3467 static inline void del_chain_block(int bucket, int size, int next)
3468 {
3469 nr_free_chain_hlocks -= size;
3470 chain_block_buckets[bucket] = next;
3471
3472 if (!bucket)
3473 nr_large_chain_blocks--;
3474 }
3475
init_chain_block_buckets(void)3476 static void init_chain_block_buckets(void)
3477 {
3478 int i;
3479
3480 for (i = 0; i < MAX_CHAIN_BUCKETS; i++)
3481 chain_block_buckets[i] = -1;
3482
3483 add_chain_block(0, ARRAY_SIZE(chain_hlocks));
3484 }
3485
3486 /*
3487 * Return offset of a chain block of the right size or -1 if not found.
3488 *
3489 * Fairly simple worst-fit allocator with the addition of a number of size
3490 * specific free lists.
3491 */
alloc_chain_hlocks(int req)3492 static int alloc_chain_hlocks(int req)
3493 {
3494 int bucket, curr, size;
3495
3496 /*
3497 * We rely on the MSB to act as an escape bit to denote freelist
3498 * pointers. Make sure this bit isn't set in 'normal' class_idx usage.
3499 */
3500 BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG);
3501
3502 init_data_structures_once();
3503
3504 if (nr_free_chain_hlocks < req)
3505 return -1;
3506
3507 /*
3508 * We require a minimum of 2 (u16) entries to encode a freelist
3509 * 'pointer'.
3510 */
3511 req = max(req, 2);
3512 bucket = size_to_bucket(req);
3513 curr = chain_block_buckets[bucket];
3514
3515 if (bucket) {
3516 if (curr >= 0) {
3517 del_chain_block(bucket, req, chain_block_next(curr));
3518 return curr;
3519 }
3520 /* Try bucket 0 */
3521 curr = chain_block_buckets[0];
3522 }
3523
3524 /*
3525 * The variable sized freelist is sorted by size; the first entry is
3526 * the largest. Use it if it fits.
3527 */
3528 if (curr >= 0) {
3529 size = chain_block_size(curr);
3530 if (likely(size >= req)) {
3531 del_chain_block(0, size, chain_block_next(curr));
3532 if (size > req)
3533 add_chain_block(curr + req, size - req);
3534 return curr;
3535 }
3536 }
3537
3538 /*
3539 * Last resort, split a block in a larger sized bucket.
3540 */
3541 for (size = MAX_CHAIN_BUCKETS; size > req; size--) {
3542 bucket = size_to_bucket(size);
3543 curr = chain_block_buckets[bucket];
3544 if (curr < 0)
3545 continue;
3546
3547 del_chain_block(bucket, size, chain_block_next(curr));
3548 add_chain_block(curr + req, size - req);
3549 return curr;
3550 }
3551
3552 return -1;
3553 }
3554
free_chain_hlocks(int base,int size)3555 static inline void free_chain_hlocks(int base, int size)
3556 {
3557 add_chain_block(base, max(size, 2));
3558 }
3559
lock_chain_get_class(struct lock_chain * chain,int i)3560 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
3561 {
3562 u16 chain_hlock = chain_hlocks[chain->base + i];
3563 unsigned int class_idx = chain_hlock_class_idx(chain_hlock);
3564
3565 return lock_classes + class_idx;
3566 }
3567
3568 /*
3569 * Returns the index of the first held_lock of the current chain
3570 */
get_first_held_lock(struct task_struct * curr,struct held_lock * hlock)3571 static inline int get_first_held_lock(struct task_struct *curr,
3572 struct held_lock *hlock)
3573 {
3574 int i;
3575 struct held_lock *hlock_curr;
3576
3577 for (i = curr->lockdep_depth - 1; i >= 0; i--) {
3578 hlock_curr = curr->held_locks + i;
3579 if (hlock_curr->irq_context != hlock->irq_context)
3580 break;
3581
3582 }
3583
3584 return ++i;
3585 }
3586
3587 #ifdef CONFIG_DEBUG_LOCKDEP
3588 /*
3589 * Returns the next chain_key iteration
3590 */
print_chain_key_iteration(u16 hlock_id,u64 chain_key)3591 static u64 print_chain_key_iteration(u16 hlock_id, u64 chain_key)
3592 {
3593 u64 new_chain_key = iterate_chain_key(chain_key, hlock_id);
3594
3595 printk(" hlock_id:%d -> chain_key:%016Lx",
3596 (unsigned int)hlock_id,
3597 (unsigned long long)new_chain_key);
3598 return new_chain_key;
3599 }
3600
3601 static void
print_chain_keys_held_locks(struct task_struct * curr,struct held_lock * hlock_next)3602 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
3603 {
3604 struct held_lock *hlock;
3605 u64 chain_key = INITIAL_CHAIN_KEY;
3606 int depth = curr->lockdep_depth;
3607 int i = get_first_held_lock(curr, hlock_next);
3608
3609 printk("depth: %u (irq_context %u)\n", depth - i + 1,
3610 hlock_next->irq_context);
3611 for (; i < depth; i++) {
3612 hlock = curr->held_locks + i;
3613 chain_key = print_chain_key_iteration(hlock_id(hlock), chain_key);
3614
3615 print_lock(hlock);
3616 }
3617
3618 print_chain_key_iteration(hlock_id(hlock_next), chain_key);
3619 print_lock(hlock_next);
3620 }
3621
print_chain_keys_chain(struct lock_chain * chain)3622 static void print_chain_keys_chain(struct lock_chain *chain)
3623 {
3624 int i;
3625 u64 chain_key = INITIAL_CHAIN_KEY;
3626 u16 hlock_id;
3627
3628 printk("depth: %u\n", chain->depth);
3629 for (i = 0; i < chain->depth; i++) {
3630 hlock_id = chain_hlocks[chain->base + i];
3631 chain_key = print_chain_key_iteration(hlock_id, chain_key);
3632
3633 print_lock_name(NULL, lock_classes + chain_hlock_class_idx(hlock_id));
3634 printk("\n");
3635 }
3636 }
3637
print_collision(struct task_struct * curr,struct held_lock * hlock_next,struct lock_chain * chain)3638 static void print_collision(struct task_struct *curr,
3639 struct held_lock *hlock_next,
3640 struct lock_chain *chain)
3641 {
3642 nbcon_cpu_emergency_enter();
3643
3644 pr_warn("\n");
3645 pr_warn("============================\n");
3646 pr_warn("WARNING: chain_key collision\n");
3647 print_kernel_ident();
3648 pr_warn("----------------------------\n");
3649 pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
3650 pr_warn("Hash chain already cached but the contents don't match!\n");
3651
3652 pr_warn("Held locks:");
3653 print_chain_keys_held_locks(curr, hlock_next);
3654
3655 pr_warn("Locks in cached chain:");
3656 print_chain_keys_chain(chain);
3657
3658 pr_warn("\nstack backtrace:\n");
3659 dump_stack();
3660
3661 nbcon_cpu_emergency_exit();
3662 }
3663 #endif
3664
3665 /*
3666 * Checks whether the chain and the current held locks are consistent
3667 * in depth and also in content. If they are not it most likely means
3668 * that there was a collision during the calculation of the chain_key.
3669 * Returns: 0 not passed, 1 passed
3670 */
check_no_collision(struct task_struct * curr,struct held_lock * hlock,struct lock_chain * chain)3671 static int check_no_collision(struct task_struct *curr,
3672 struct held_lock *hlock,
3673 struct lock_chain *chain)
3674 {
3675 #ifdef CONFIG_DEBUG_LOCKDEP
3676 int i, j, id;
3677
3678 i = get_first_held_lock(curr, hlock);
3679
3680 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
3681 print_collision(curr, hlock, chain);
3682 return 0;
3683 }
3684
3685 for (j = 0; j < chain->depth - 1; j++, i++) {
3686 id = hlock_id(&curr->held_locks[i]);
3687
3688 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
3689 print_collision(curr, hlock, chain);
3690 return 0;
3691 }
3692 }
3693 #endif
3694 return 1;
3695 }
3696
3697 /*
3698 * Given an index that is >= -1, return the index of the next lock chain.
3699 * Return -2 if there is no next lock chain.
3700 */
lockdep_next_lockchain(long i)3701 long lockdep_next_lockchain(long i)
3702 {
3703 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
3704 return i < ARRAY_SIZE(lock_chains) ? i : -2;
3705 }
3706
lock_chain_count(void)3707 unsigned long lock_chain_count(void)
3708 {
3709 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
3710 }
3711
3712 /* Must be called with the graph lock held. */
alloc_lock_chain(void)3713 static struct lock_chain *alloc_lock_chain(void)
3714 {
3715 int idx = find_first_zero_bit(lock_chains_in_use,
3716 ARRAY_SIZE(lock_chains));
3717
3718 if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
3719 return NULL;
3720 __set_bit(idx, lock_chains_in_use);
3721 return lock_chains + idx;
3722 }
3723
3724 /*
3725 * Adds a dependency chain into chain hashtable. And must be called with
3726 * graph_lock held.
3727 *
3728 * Return 0 if fail, and graph_lock is released.
3729 * Return 1 if succeed, with graph_lock held.
3730 */
add_chain_cache(struct task_struct * curr,struct held_lock * hlock,u64 chain_key)3731 static inline int add_chain_cache(struct task_struct *curr,
3732 struct held_lock *hlock,
3733 u64 chain_key)
3734 {
3735 struct hlist_head *hash_head = chainhashentry(chain_key);
3736 struct lock_chain *chain;
3737 int i, j;
3738
3739 /*
3740 * The caller must hold the graph lock, ensure we've got IRQs
3741 * disabled to make this an IRQ-safe lock.. for recursion reasons
3742 * lockdep won't complain about its own locking errors.
3743 */
3744 if (lockdep_assert_locked())
3745 return 0;
3746
3747 chain = alloc_lock_chain();
3748 if (!chain) {
3749 if (!debug_locks_off_graph_unlock())
3750 return 0;
3751
3752 nbcon_cpu_emergency_enter();
3753 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
3754 dump_stack();
3755 nbcon_cpu_emergency_exit();
3756 return 0;
3757 }
3758 chain->chain_key = chain_key;
3759 chain->irq_context = hlock->irq_context;
3760 i = get_first_held_lock(curr, hlock);
3761 chain->depth = curr->lockdep_depth + 1 - i;
3762
3763 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
3764 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
3765 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
3766
3767 j = alloc_chain_hlocks(chain->depth);
3768 if (j < 0) {
3769 if (!debug_locks_off_graph_unlock())
3770 return 0;
3771
3772 nbcon_cpu_emergency_enter();
3773 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
3774 dump_stack();
3775 nbcon_cpu_emergency_exit();
3776 return 0;
3777 }
3778
3779 chain->base = j;
3780 for (j = 0; j < chain->depth - 1; j++, i++) {
3781 int lock_id = hlock_id(curr->held_locks + i);
3782
3783 chain_hlocks[chain->base + j] = lock_id;
3784 }
3785 chain_hlocks[chain->base + j] = hlock_id(hlock);
3786 hlist_add_head_rcu(&chain->entry, hash_head);
3787 debug_atomic_inc(chain_lookup_misses);
3788 inc_chains(chain->irq_context);
3789
3790 return 1;
3791 }
3792
3793 /*
3794 * Look up a dependency chain. Must be called with either the graph lock or
3795 * the RCU read lock held.
3796 */
lookup_chain_cache(u64 chain_key)3797 static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
3798 {
3799 struct hlist_head *hash_head = chainhashentry(chain_key);
3800 struct lock_chain *chain;
3801
3802 hlist_for_each_entry_rcu(chain, hash_head, entry) {
3803 if (READ_ONCE(chain->chain_key) == chain_key) {
3804 debug_atomic_inc(chain_lookup_hits);
3805 return chain;
3806 }
3807 }
3808 return NULL;
3809 }
3810
3811 /*
3812 * If the key is not present yet in dependency chain cache then
3813 * add it and return 1 - in this case the new dependency chain is
3814 * validated. If the key is already hashed, return 0.
3815 * (On return with 1 graph_lock is held.)
3816 */
lookup_chain_cache_add(struct task_struct * curr,struct held_lock * hlock,u64 chain_key)3817 static inline int lookup_chain_cache_add(struct task_struct *curr,
3818 struct held_lock *hlock,
3819 u64 chain_key)
3820 {
3821 struct lock_class *class = hlock_class(hlock);
3822 struct lock_chain *chain = lookup_chain_cache(chain_key);
3823
3824 if (chain) {
3825 cache_hit:
3826 if (!check_no_collision(curr, hlock, chain))
3827 return 0;
3828
3829 if (very_verbose(class)) {
3830 printk("\nhash chain already cached, key: "
3831 "%016Lx tail class: [%px] %s\n",
3832 (unsigned long long)chain_key,
3833 class->key, class->name);
3834 }
3835
3836 return 0;
3837 }
3838
3839 if (very_verbose(class)) {
3840 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
3841 (unsigned long long)chain_key, class->key, class->name);
3842 }
3843
3844 if (!graph_lock())
3845 return 0;
3846
3847 /*
3848 * We have to walk the chain again locked - to avoid duplicates:
3849 */
3850 chain = lookup_chain_cache(chain_key);
3851 if (chain) {
3852 graph_unlock();
3853 goto cache_hit;
3854 }
3855
3856 if (!add_chain_cache(curr, hlock, chain_key))
3857 return 0;
3858
3859 return 1;
3860 }
3861
validate_chain(struct task_struct * curr,struct held_lock * hlock,int chain_head,u64 chain_key)3862 static int validate_chain(struct task_struct *curr,
3863 struct held_lock *hlock,
3864 int chain_head, u64 chain_key)
3865 {
3866 /*
3867 * Trylock needs to maintain the stack of held locks, but it
3868 * does not add new dependencies, because trylock can be done
3869 * in any order.
3870 *
3871 * We look up the chain_key and do the O(N^2) check and update of
3872 * the dependencies only if this is a new dependency chain.
3873 * (If lookup_chain_cache_add() return with 1 it acquires
3874 * graph_lock for us)
3875 */
3876 if (!hlock->trylock && hlock->check &&
3877 lookup_chain_cache_add(curr, hlock, chain_key)) {
3878 /*
3879 * Check whether last held lock:
3880 *
3881 * - is irq-safe, if this lock is irq-unsafe
3882 * - is softirq-safe, if this lock is hardirq-unsafe
3883 *
3884 * And check whether the new lock's dependency graph
3885 * could lead back to the previous lock:
3886 *
3887 * - within the current held-lock stack
3888 * - across our accumulated lock dependency records
3889 *
3890 * any of these scenarios could lead to a deadlock.
3891 */
3892 /*
3893 * The simple case: does the current hold the same lock
3894 * already?
3895 */
3896 int ret = check_deadlock(curr, hlock);
3897
3898 if (!ret)
3899 return 0;
3900 /*
3901 * Add dependency only if this lock is not the head
3902 * of the chain, and if the new lock introduces no more
3903 * lock dependency (because we already hold a lock with the
3904 * same lock class) nor deadlock (because the nest_lock
3905 * serializes nesting locks), see the comments for
3906 * check_deadlock().
3907 */
3908 if (!chain_head && ret != 2) {
3909 if (!check_prevs_add(curr, hlock))
3910 return 0;
3911 }
3912
3913 graph_unlock();
3914 } else {
3915 /* after lookup_chain_cache_add(): */
3916 if (unlikely(!debug_locks))
3917 return 0;
3918 }
3919
3920 return 1;
3921 }
3922 #else
validate_chain(struct task_struct * curr,struct held_lock * hlock,int chain_head,u64 chain_key)3923 static inline int validate_chain(struct task_struct *curr,
3924 struct held_lock *hlock,
3925 int chain_head, u64 chain_key)
3926 {
3927 return 1;
3928 }
3929
init_chain_block_buckets(void)3930 static void init_chain_block_buckets(void) { }
3931 #endif /* CONFIG_PROVE_LOCKING */
3932
3933 /*
3934 * We are building curr_chain_key incrementally, so double-check
3935 * it from scratch, to make sure that it's done correctly:
3936 */
check_chain_key(struct task_struct * curr)3937 static void check_chain_key(struct task_struct *curr)
3938 {
3939 #ifdef CONFIG_DEBUG_LOCKDEP
3940 struct held_lock *hlock, *prev_hlock = NULL;
3941 unsigned int i;
3942 u64 chain_key = INITIAL_CHAIN_KEY;
3943
3944 for (i = 0; i < curr->lockdep_depth; i++) {
3945 hlock = curr->held_locks + i;
3946 if (chain_key != hlock->prev_chain_key) {
3947 debug_locks_off();
3948 /*
3949 * We got mighty confused, our chain keys don't match
3950 * with what we expect, someone trample on our task state?
3951 */
3952 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
3953 curr->lockdep_depth, i,
3954 (unsigned long long)chain_key,
3955 (unsigned long long)hlock->prev_chain_key);
3956 return;
3957 }
3958
3959 /*
3960 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
3961 * it registered lock class index?
3962 */
3963 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
3964 return;
3965
3966 if (prev_hlock && (prev_hlock->irq_context !=
3967 hlock->irq_context))
3968 chain_key = INITIAL_CHAIN_KEY;
3969 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
3970 prev_hlock = hlock;
3971 }
3972 if (chain_key != curr->curr_chain_key) {
3973 debug_locks_off();
3974 /*
3975 * More smoking hash instead of calculating it, damn see these
3976 * numbers float.. I bet that a pink elephant stepped on my memory.
3977 */
3978 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
3979 curr->lockdep_depth, i,
3980 (unsigned long long)chain_key,
3981 (unsigned long long)curr->curr_chain_key);
3982 }
3983 #endif
3984 }
3985
3986 #ifdef CONFIG_PROVE_LOCKING
3987 static int mark_lock(struct task_struct *curr, struct held_lock *this,
3988 enum lock_usage_bit new_bit);
3989
print_usage_bug_scenario(struct held_lock * lock)3990 static void print_usage_bug_scenario(struct held_lock *lock)
3991 {
3992 struct lock_class *class = hlock_class(lock);
3993
3994 printk(" Possible unsafe locking scenario:\n\n");
3995 printk(" CPU0\n");
3996 printk(" ----\n");
3997 printk(" lock(");
3998 __print_lock_name(lock, class);
3999 printk(KERN_CONT ");\n");
4000 printk(" <Interrupt>\n");
4001 printk(" lock(");
4002 __print_lock_name(lock, class);
4003 printk(KERN_CONT ");\n");
4004 printk("\n *** DEADLOCK ***\n\n");
4005 }
4006
4007 static void
print_usage_bug(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit prev_bit,enum lock_usage_bit new_bit)4008 print_usage_bug(struct task_struct *curr, struct held_lock *this,
4009 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
4010 {
4011 if (!debug_locks_off() || debug_locks_silent)
4012 return;
4013
4014 nbcon_cpu_emergency_enter();
4015
4016 pr_warn("\n");
4017 pr_warn("================================\n");
4018 pr_warn("WARNING: inconsistent lock state\n");
4019 print_kernel_ident();
4020 pr_warn("--------------------------------\n");
4021
4022 pr_warn("inconsistent {%s} -> {%s} usage.\n",
4023 usage_str[prev_bit], usage_str[new_bit]);
4024
4025 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
4026 curr->comm, task_pid_nr(curr),
4027 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
4028 lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
4029 lockdep_hardirqs_enabled(),
4030 lockdep_softirqs_enabled(curr));
4031 print_lock(this);
4032
4033 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
4034 print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1);
4035
4036 print_irqtrace_events(curr);
4037 pr_warn("\nother info that might help us debug this:\n");
4038 print_usage_bug_scenario(this);
4039
4040 lockdep_print_held_locks(curr);
4041
4042 pr_warn("\nstack backtrace:\n");
4043 dump_stack();
4044
4045 nbcon_cpu_emergency_exit();
4046 }
4047
4048 /*
4049 * Print out an error if an invalid bit is set:
4050 */
4051 static inline int
valid_state(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit new_bit,enum lock_usage_bit bad_bit)4052 valid_state(struct task_struct *curr, struct held_lock *this,
4053 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
4054 {
4055 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
4056 graph_unlock();
4057 print_usage_bug(curr, this, bad_bit, new_bit);
4058 return 0;
4059 }
4060 return 1;
4061 }
4062
4063
4064 /*
4065 * print irq inversion bug:
4066 */
4067 static void
print_irq_inversion_bug(struct task_struct * curr,struct lock_list * root,struct lock_list * other,struct held_lock * this,int forwards,const char * irqclass)4068 print_irq_inversion_bug(struct task_struct *curr,
4069 struct lock_list *root, struct lock_list *other,
4070 struct held_lock *this, int forwards,
4071 const char *irqclass)
4072 {
4073 struct lock_list *entry = other;
4074 struct lock_list *middle = NULL;
4075 int depth;
4076
4077 if (!debug_locks_off_graph_unlock() || debug_locks_silent)
4078 return;
4079
4080 nbcon_cpu_emergency_enter();
4081
4082 pr_warn("\n");
4083 pr_warn("========================================================\n");
4084 pr_warn("WARNING: possible irq lock inversion dependency detected\n");
4085 print_kernel_ident();
4086 pr_warn("--------------------------------------------------------\n");
4087 pr_warn("%s/%d just changed the state of lock:\n",
4088 curr->comm, task_pid_nr(curr));
4089 print_lock(this);
4090 if (forwards)
4091 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
4092 else
4093 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
4094 print_lock_name(NULL, other->class);
4095 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
4096
4097 pr_warn("\nother info that might help us debug this:\n");
4098
4099 /* Find a middle lock (if one exists) */
4100 depth = get_lock_depth(other);
4101 do {
4102 if (depth == 0 && (entry != root)) {
4103 pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
4104 break;
4105 }
4106 middle = entry;
4107 entry = get_lock_parent(entry);
4108 depth--;
4109 } while (entry && entry != root && (depth >= 0));
4110 if (forwards)
4111 print_irq_lock_scenario(root, other,
4112 middle ? middle->class : root->class, other->class);
4113 else
4114 print_irq_lock_scenario(other, root,
4115 middle ? middle->class : other->class, root->class);
4116
4117 lockdep_print_held_locks(curr);
4118
4119 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
4120 root->trace = save_trace();
4121 if (!root->trace)
4122 goto out;
4123 print_shortest_lock_dependencies(other, root);
4124
4125 pr_warn("\nstack backtrace:\n");
4126 dump_stack();
4127 out:
4128 nbcon_cpu_emergency_exit();
4129 }
4130
4131 /*
4132 * Prove that in the forwards-direction subgraph starting at <this>
4133 * there is no lock matching <mask>:
4134 */
4135 static int
check_usage_forwards(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit bit)4136 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
4137 enum lock_usage_bit bit)
4138 {
4139 enum bfs_result ret;
4140 struct lock_list root;
4141 struct lock_list *target_entry;
4142 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
4143 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
4144
4145 bfs_init_root(&root, this);
4146 ret = find_usage_forwards(&root, usage_mask, &target_entry);
4147 if (bfs_error(ret)) {
4148 print_bfs_bug(ret);
4149 return 0;
4150 }
4151 if (ret == BFS_RNOMATCH)
4152 return 1;
4153
4154 /* Check whether write or read usage is the match */
4155 if (target_entry->class->usage_mask & lock_flag(bit)) {
4156 print_irq_inversion_bug(curr, &root, target_entry,
4157 this, 1, state_name(bit));
4158 } else {
4159 print_irq_inversion_bug(curr, &root, target_entry,
4160 this, 1, state_name(read_bit));
4161 }
4162
4163 return 0;
4164 }
4165
4166 /*
4167 * Prove that in the backwards-direction subgraph starting at <this>
4168 * there is no lock matching <mask>:
4169 */
4170 static int
check_usage_backwards(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit bit)4171 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
4172 enum lock_usage_bit bit)
4173 {
4174 enum bfs_result ret;
4175 struct lock_list root;
4176 struct lock_list *target_entry;
4177 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
4178 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
4179
4180 bfs_init_rootb(&root, this);
4181 ret = find_usage_backwards(&root, usage_mask, &target_entry);
4182 if (bfs_error(ret)) {
4183 print_bfs_bug(ret);
4184 return 0;
4185 }
4186 if (ret == BFS_RNOMATCH)
4187 return 1;
4188
4189 /* Check whether write or read usage is the match */
4190 if (target_entry->class->usage_mask & lock_flag(bit)) {
4191 print_irq_inversion_bug(curr, &root, target_entry,
4192 this, 0, state_name(bit));
4193 } else {
4194 print_irq_inversion_bug(curr, &root, target_entry,
4195 this, 0, state_name(read_bit));
4196 }
4197
4198 return 0;
4199 }
4200
print_irqtrace_events(struct task_struct * curr)4201 void print_irqtrace_events(struct task_struct *curr)
4202 {
4203 const struct irqtrace_events *trace = &curr->irqtrace;
4204
4205 nbcon_cpu_emergency_enter();
4206
4207 printk("irq event stamp: %u\n", trace->irq_events);
4208 printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
4209 trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip,
4210 (void *)trace->hardirq_enable_ip);
4211 printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
4212 trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip,
4213 (void *)trace->hardirq_disable_ip);
4214 printk("softirqs last enabled at (%u): [<%px>] %pS\n",
4215 trace->softirq_enable_event, (void *)trace->softirq_enable_ip,
4216 (void *)trace->softirq_enable_ip);
4217 printk("softirqs last disabled at (%u): [<%px>] %pS\n",
4218 trace->softirq_disable_event, (void *)trace->softirq_disable_ip,
4219 (void *)trace->softirq_disable_ip);
4220
4221 nbcon_cpu_emergency_exit();
4222 }
4223
HARDIRQ_verbose(struct lock_class * class)4224 static int HARDIRQ_verbose(struct lock_class *class)
4225 {
4226 #if HARDIRQ_VERBOSE
4227 return class_filter(class);
4228 #endif
4229 return 0;
4230 }
4231
SOFTIRQ_verbose(struct lock_class * class)4232 static int SOFTIRQ_verbose(struct lock_class *class)
4233 {
4234 #if SOFTIRQ_VERBOSE
4235 return class_filter(class);
4236 #endif
4237 return 0;
4238 }
4239
4240 static int (*state_verbose_f[])(struct lock_class *class) = {
4241 #define LOCKDEP_STATE(__STATE) \
4242 __STATE##_verbose,
4243 #include "lockdep_states.h"
4244 #undef LOCKDEP_STATE
4245 };
4246
state_verbose(enum lock_usage_bit bit,struct lock_class * class)4247 static inline int state_verbose(enum lock_usage_bit bit,
4248 struct lock_class *class)
4249 {
4250 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
4251 }
4252
4253 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
4254 enum lock_usage_bit bit, const char *name);
4255
4256 static int
mark_lock_irq(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit new_bit)4257 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
4258 enum lock_usage_bit new_bit)
4259 {
4260 int excl_bit = exclusive_bit(new_bit);
4261 int read = new_bit & LOCK_USAGE_READ_MASK;
4262 int dir = new_bit & LOCK_USAGE_DIR_MASK;
4263
4264 /*
4265 * Validate that this particular lock does not have conflicting
4266 * usage states.
4267 */
4268 if (!valid_state(curr, this, new_bit, excl_bit))
4269 return 0;
4270
4271 /*
4272 * Check for read in write conflicts
4273 */
4274 if (!read && !valid_state(curr, this, new_bit,
4275 excl_bit + LOCK_USAGE_READ_MASK))
4276 return 0;
4277
4278
4279 /*
4280 * Validate that the lock dependencies don't have conflicting usage
4281 * states.
4282 */
4283 if (dir) {
4284 /*
4285 * mark ENABLED has to look backwards -- to ensure no dependee
4286 * has USED_IN state, which, again, would allow recursion deadlocks.
4287 */
4288 if (!check_usage_backwards(curr, this, excl_bit))
4289 return 0;
4290 } else {
4291 /*
4292 * mark USED_IN has to look forwards -- to ensure no dependency
4293 * has ENABLED state, which would allow recursion deadlocks.
4294 */
4295 if (!check_usage_forwards(curr, this, excl_bit))
4296 return 0;
4297 }
4298
4299 if (state_verbose(new_bit, hlock_class(this)))
4300 return 2;
4301
4302 return 1;
4303 }
4304
4305 /*
4306 * Mark all held locks with a usage bit:
4307 */
4308 static int
mark_held_locks(struct task_struct * curr,enum lock_usage_bit base_bit)4309 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
4310 {
4311 struct held_lock *hlock;
4312 int i;
4313
4314 for (i = 0; i < curr->lockdep_depth; i++) {
4315 enum lock_usage_bit hlock_bit = base_bit;
4316 hlock = curr->held_locks + i;
4317
4318 if (hlock->read)
4319 hlock_bit += LOCK_USAGE_READ_MASK;
4320
4321 BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
4322
4323 if (!hlock->check)
4324 continue;
4325
4326 if (!mark_lock(curr, hlock, hlock_bit))
4327 return 0;
4328 }
4329
4330 return 1;
4331 }
4332
4333 /*
4334 * Hardirqs will be enabled:
4335 */
__trace_hardirqs_on_caller(void)4336 static void __trace_hardirqs_on_caller(void)
4337 {
4338 struct task_struct *curr = current;
4339
4340 /*
4341 * We are going to turn hardirqs on, so set the
4342 * usage bit for all held locks:
4343 */
4344 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
4345 return;
4346 /*
4347 * If we have softirqs enabled, then set the usage
4348 * bit for all held locks. (disabled hardirqs prevented
4349 * this bit from being set before)
4350 */
4351 if (curr->softirqs_enabled)
4352 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
4353 }
4354
4355 /**
4356 * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts
4357 *
4358 * Invoked before a possible transition to RCU idle from exit to user or
4359 * guest mode. This ensures that all RCU operations are done before RCU
4360 * stops watching. After the RCU transition lockdep_hardirqs_on() has to be
4361 * invoked to set the final state.
4362 */
lockdep_hardirqs_on_prepare(void)4363 void lockdep_hardirqs_on_prepare(void)
4364 {
4365 if (unlikely(!debug_locks))
4366 return;
4367
4368 /*
4369 * NMIs do not (and cannot) track lock dependencies, nothing to do.
4370 */
4371 if (unlikely(in_nmi()))
4372 return;
4373
4374 if (unlikely(this_cpu_read(lockdep_recursion)))
4375 return;
4376
4377 if (unlikely(lockdep_hardirqs_enabled())) {
4378 /*
4379 * Neither irq nor preemption are disabled here
4380 * so this is racy by nature but losing one hit
4381 * in a stat is not a big deal.
4382 */
4383 __debug_atomic_inc(redundant_hardirqs_on);
4384 return;
4385 }
4386
4387 /*
4388 * We're enabling irqs and according to our state above irqs weren't
4389 * already enabled, yet we find the hardware thinks they are in fact
4390 * enabled.. someone messed up their IRQ state tracing.
4391 */
4392 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4393 return;
4394
4395 /*
4396 * See the fine text that goes along with this variable definition.
4397 */
4398 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
4399 return;
4400
4401 /*
4402 * Can't allow enabling interrupts while in an interrupt handler,
4403 * that's general bad form and such. Recursion, limited stack etc..
4404 */
4405 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context()))
4406 return;
4407
4408 current->hardirq_chain_key = current->curr_chain_key;
4409
4410 lockdep_recursion_inc();
4411 __trace_hardirqs_on_caller();
4412 lockdep_recursion_finish();
4413 }
4414 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare);
4415
lockdep_hardirqs_on(unsigned long ip)4416 void noinstr lockdep_hardirqs_on(unsigned long ip)
4417 {
4418 struct irqtrace_events *trace = ¤t->irqtrace;
4419
4420 if (unlikely(!debug_locks))
4421 return;
4422
4423 /*
4424 * NMIs can happen in the middle of local_irq_{en,dis}able() where the
4425 * tracking state and hardware state are out of sync.
4426 *
4427 * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from,
4428 * and not rely on hardware state like normal interrupts.
4429 */
4430 if (unlikely(in_nmi())) {
4431 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4432 return;
4433
4434 /*
4435 * Skip:
4436 * - recursion check, because NMI can hit lockdep;
4437 * - hardware state check, because above;
4438 * - chain_key check, see lockdep_hardirqs_on_prepare().
4439 */
4440 goto skip_checks;
4441 }
4442
4443 if (unlikely(this_cpu_read(lockdep_recursion)))
4444 return;
4445
4446 if (lockdep_hardirqs_enabled()) {
4447 /*
4448 * Neither irq nor preemption are disabled here
4449 * so this is racy by nature but losing one hit
4450 * in a stat is not a big deal.
4451 */
4452 __debug_atomic_inc(redundant_hardirqs_on);
4453 return;
4454 }
4455
4456 /*
4457 * We're enabling irqs and according to our state above irqs weren't
4458 * already enabled, yet we find the hardware thinks they are in fact
4459 * enabled.. someone messed up their IRQ state tracing.
4460 */
4461 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4462 return;
4463
4464 /*
4465 * Ensure the lock stack remained unchanged between
4466 * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on().
4467 */
4468 DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key !=
4469 current->curr_chain_key);
4470
4471 skip_checks:
4472 /* we'll do an OFF -> ON transition: */
4473 __this_cpu_write(hardirqs_enabled, 1);
4474 trace->hardirq_enable_ip = ip;
4475 trace->hardirq_enable_event = ++trace->irq_events;
4476 debug_atomic_inc(hardirqs_on_events);
4477 }
4478 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on);
4479
4480 /*
4481 * Hardirqs were disabled:
4482 */
lockdep_hardirqs_off(unsigned long ip)4483 void noinstr lockdep_hardirqs_off(unsigned long ip)
4484 {
4485 if (unlikely(!debug_locks))
4486 return;
4487
4488 /*
4489 * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep;
4490 * they will restore the software state. This ensures the software
4491 * state is consistent inside NMIs as well.
4492 */
4493 if (in_nmi()) {
4494 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
4495 return;
4496 } else if (__this_cpu_read(lockdep_recursion))
4497 return;
4498
4499 /*
4500 * So we're supposed to get called after you mask local IRQs, but for
4501 * some reason the hardware doesn't quite think you did a proper job.
4502 */
4503 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4504 return;
4505
4506 if (lockdep_hardirqs_enabled()) {
4507 struct irqtrace_events *trace = ¤t->irqtrace;
4508
4509 /*
4510 * We have done an ON -> OFF transition:
4511 */
4512 __this_cpu_write(hardirqs_enabled, 0);
4513 trace->hardirq_disable_ip = ip;
4514 trace->hardirq_disable_event = ++trace->irq_events;
4515 debug_atomic_inc(hardirqs_off_events);
4516 } else {
4517 debug_atomic_inc(redundant_hardirqs_off);
4518 }
4519 }
4520 EXPORT_SYMBOL_GPL(lockdep_hardirqs_off);
4521
4522 /*
4523 * Softirqs will be enabled:
4524 */
lockdep_softirqs_on(unsigned long ip)4525 void lockdep_softirqs_on(unsigned long ip)
4526 {
4527 struct irqtrace_events *trace = ¤t->irqtrace;
4528
4529 if (unlikely(!lockdep_enabled()))
4530 return;
4531
4532 /*
4533 * We fancy IRQs being disabled here, see softirq.c, avoids
4534 * funny state and nesting things.
4535 */
4536 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4537 return;
4538
4539 if (current->softirqs_enabled) {
4540 debug_atomic_inc(redundant_softirqs_on);
4541 return;
4542 }
4543
4544 lockdep_recursion_inc();
4545 /*
4546 * We'll do an OFF -> ON transition:
4547 */
4548 current->softirqs_enabled = 1;
4549 trace->softirq_enable_ip = ip;
4550 trace->softirq_enable_event = ++trace->irq_events;
4551 debug_atomic_inc(softirqs_on_events);
4552 /*
4553 * We are going to turn softirqs on, so set the
4554 * usage bit for all held locks, if hardirqs are
4555 * enabled too:
4556 */
4557 if (lockdep_hardirqs_enabled())
4558 mark_held_locks(current, LOCK_ENABLED_SOFTIRQ);
4559 lockdep_recursion_finish();
4560 }
4561
4562 /*
4563 * Softirqs were disabled:
4564 */
lockdep_softirqs_off(unsigned long ip)4565 void lockdep_softirqs_off(unsigned long ip)
4566 {
4567 if (unlikely(!lockdep_enabled()))
4568 return;
4569
4570 /*
4571 * We fancy IRQs being disabled here, see softirq.c
4572 */
4573 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
4574 return;
4575
4576 if (current->softirqs_enabled) {
4577 struct irqtrace_events *trace = ¤t->irqtrace;
4578
4579 /*
4580 * We have done an ON -> OFF transition:
4581 */
4582 current->softirqs_enabled = 0;
4583 trace->softirq_disable_ip = ip;
4584 trace->softirq_disable_event = ++trace->irq_events;
4585 debug_atomic_inc(softirqs_off_events);
4586 /*
4587 * Whoops, we wanted softirqs off, so why aren't they?
4588 */
4589 DEBUG_LOCKS_WARN_ON(!softirq_count());
4590 } else
4591 debug_atomic_inc(redundant_softirqs_off);
4592 }
4593
4594 /**
4595 * lockdep_cleanup_dead_cpu - Ensure CPU lockdep state is cleanly stopped
4596 *
4597 * @cpu: index of offlined CPU
4598 * @idle: task pointer for offlined CPU's idle thread
4599 *
4600 * Invoked after the CPU is dead. Ensures that the tracing infrastructure
4601 * is left in a suitable state for the CPU to be subsequently brought
4602 * online again.
4603 */
lockdep_cleanup_dead_cpu(unsigned int cpu,struct task_struct * idle)4604 void lockdep_cleanup_dead_cpu(unsigned int cpu, struct task_struct *idle)
4605 {
4606 if (unlikely(!debug_locks))
4607 return;
4608
4609 if (unlikely(per_cpu(hardirqs_enabled, cpu))) {
4610 pr_warn("CPU %u left hardirqs enabled!", cpu);
4611 if (idle)
4612 print_irqtrace_events(idle);
4613 /* Clean it up for when the CPU comes online again. */
4614 per_cpu(hardirqs_enabled, cpu) = 0;
4615 }
4616 }
4617
4618 static int
mark_usage(struct task_struct * curr,struct held_lock * hlock,int check)4619 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4620 {
4621 if (!check)
4622 goto lock_used;
4623
4624 /*
4625 * If non-trylock use in a hardirq or softirq context, then
4626 * mark the lock as used in these contexts:
4627 */
4628 if (!hlock->trylock) {
4629 if (hlock->read) {
4630 if (lockdep_hardirq_context())
4631 if (!mark_lock(curr, hlock,
4632 LOCK_USED_IN_HARDIRQ_READ))
4633 return 0;
4634 if (curr->softirq_context)
4635 if (!mark_lock(curr, hlock,
4636 LOCK_USED_IN_SOFTIRQ_READ))
4637 return 0;
4638 } else {
4639 if (lockdep_hardirq_context())
4640 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
4641 return 0;
4642 if (curr->softirq_context)
4643 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
4644 return 0;
4645 }
4646 }
4647
4648 /*
4649 * For lock_sync(), don't mark the ENABLED usage, since lock_sync()
4650 * creates no critical section and no extra dependency can be introduced
4651 * by interrupts
4652 */
4653 if (!hlock->hardirqs_off && !hlock->sync) {
4654 if (hlock->read) {
4655 if (!mark_lock(curr, hlock,
4656 LOCK_ENABLED_HARDIRQ_READ))
4657 return 0;
4658 if (curr->softirqs_enabled)
4659 if (!mark_lock(curr, hlock,
4660 LOCK_ENABLED_SOFTIRQ_READ))
4661 return 0;
4662 } else {
4663 if (!mark_lock(curr, hlock,
4664 LOCK_ENABLED_HARDIRQ))
4665 return 0;
4666 if (curr->softirqs_enabled)
4667 if (!mark_lock(curr, hlock,
4668 LOCK_ENABLED_SOFTIRQ))
4669 return 0;
4670 }
4671 }
4672
4673 lock_used:
4674 /* mark it as used: */
4675 if (!mark_lock(curr, hlock, LOCK_USED))
4676 return 0;
4677
4678 return 1;
4679 }
4680
task_irq_context(struct task_struct * task)4681 static inline unsigned int task_irq_context(struct task_struct *task)
4682 {
4683 return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() +
4684 LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context;
4685 }
4686
separate_irq_context(struct task_struct * curr,struct held_lock * hlock)4687 static int separate_irq_context(struct task_struct *curr,
4688 struct held_lock *hlock)
4689 {
4690 unsigned int depth = curr->lockdep_depth;
4691
4692 /*
4693 * Keep track of points where we cross into an interrupt context:
4694 */
4695 if (depth) {
4696 struct held_lock *prev_hlock;
4697
4698 prev_hlock = curr->held_locks + depth-1;
4699 /*
4700 * If we cross into another context, reset the
4701 * hash key (this also prevents the checking and the
4702 * adding of the dependency to 'prev'):
4703 */
4704 if (prev_hlock->irq_context != hlock->irq_context)
4705 return 1;
4706 }
4707 return 0;
4708 }
4709
4710 /*
4711 * Mark a lock with a usage bit, and validate the state transition:
4712 */
mark_lock(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit new_bit)4713 static int mark_lock(struct task_struct *curr, struct held_lock *this,
4714 enum lock_usage_bit new_bit)
4715 {
4716 unsigned int new_mask, ret = 1;
4717
4718 if (new_bit >= LOCK_USAGE_STATES) {
4719 DEBUG_LOCKS_WARN_ON(1);
4720 return 0;
4721 }
4722
4723 if (new_bit == LOCK_USED && this->read)
4724 new_bit = LOCK_USED_READ;
4725
4726 new_mask = 1 << new_bit;
4727
4728 /*
4729 * If already set then do not dirty the cacheline,
4730 * nor do any checks:
4731 */
4732 if (likely(hlock_class(this)->usage_mask & new_mask))
4733 return 1;
4734
4735 if (!graph_lock())
4736 return 0;
4737 /*
4738 * Make sure we didn't race:
4739 */
4740 if (unlikely(hlock_class(this)->usage_mask & new_mask))
4741 goto unlock;
4742
4743 if (!hlock_class(this)->usage_mask)
4744 debug_atomic_dec(nr_unused_locks);
4745
4746 hlock_class(this)->usage_mask |= new_mask;
4747
4748 if (new_bit < LOCK_TRACE_STATES) {
4749 if (!(hlock_class(this)->usage_traces[new_bit] = save_trace()))
4750 return 0;
4751 }
4752
4753 if (new_bit < LOCK_USED) {
4754 ret = mark_lock_irq(curr, this, new_bit);
4755 if (!ret)
4756 return 0;
4757 }
4758
4759 unlock:
4760 graph_unlock();
4761
4762 /*
4763 * We must printk outside of the graph_lock:
4764 */
4765 if (ret == 2) {
4766 nbcon_cpu_emergency_enter();
4767 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
4768 print_lock(this);
4769 print_irqtrace_events(curr);
4770 dump_stack();
4771 nbcon_cpu_emergency_exit();
4772 }
4773
4774 return ret;
4775 }
4776
task_wait_context(struct task_struct * curr)4777 static inline short task_wait_context(struct task_struct *curr)
4778 {
4779 /*
4780 * Set appropriate wait type for the context; for IRQs we have to take
4781 * into account force_irqthread as that is implied by PREEMPT_RT.
4782 */
4783 if (lockdep_hardirq_context()) {
4784 /*
4785 * Check if force_irqthreads will run us threaded.
4786 */
4787 if (curr->hardirq_threaded || curr->irq_config)
4788 return LD_WAIT_CONFIG;
4789
4790 return LD_WAIT_SPIN;
4791 } else if (curr->softirq_context) {
4792 /*
4793 * Softirqs are always threaded.
4794 */
4795 return LD_WAIT_CONFIG;
4796 }
4797
4798 return LD_WAIT_MAX;
4799 }
4800
4801 static int
print_lock_invalid_wait_context(struct task_struct * curr,struct held_lock * hlock)4802 print_lock_invalid_wait_context(struct task_struct *curr,
4803 struct held_lock *hlock)
4804 {
4805 short curr_inner;
4806
4807 if (!debug_locks_off())
4808 return 0;
4809 if (debug_locks_silent)
4810 return 0;
4811
4812 nbcon_cpu_emergency_enter();
4813
4814 pr_warn("\n");
4815 pr_warn("=============================\n");
4816 pr_warn("[ BUG: Invalid wait context ]\n");
4817 print_kernel_ident();
4818 pr_warn("-----------------------------\n");
4819
4820 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
4821 print_lock(hlock);
4822
4823 pr_warn("other info that might help us debug this:\n");
4824
4825 curr_inner = task_wait_context(curr);
4826 pr_warn("context-{%d:%d}\n", curr_inner, curr_inner);
4827
4828 lockdep_print_held_locks(curr);
4829
4830 pr_warn("stack backtrace:\n");
4831 dump_stack();
4832
4833 nbcon_cpu_emergency_exit();
4834
4835 return 0;
4836 }
4837
4838 /*
4839 * Verify the wait_type context.
4840 *
4841 * This check validates we take locks in the right wait-type order; that is it
4842 * ensures that we do not take mutexes inside spinlocks and do not attempt to
4843 * acquire spinlocks inside raw_spinlocks and the sort.
4844 *
4845 * The entire thing is slightly more complex because of RCU, RCU is a lock that
4846 * can be taken from (pretty much) any context but also has constraints.
4847 * However when taken in a stricter environment the RCU lock does not loosen
4848 * the constraints.
4849 *
4850 * Therefore we must look for the strictest environment in the lock stack and
4851 * compare that to the lock we're trying to acquire.
4852 */
check_wait_context(struct task_struct * curr,struct held_lock * next)4853 static int check_wait_context(struct task_struct *curr, struct held_lock *next)
4854 {
4855 u8 next_inner = hlock_class(next)->wait_type_inner;
4856 u8 next_outer = hlock_class(next)->wait_type_outer;
4857 u8 curr_inner;
4858 int depth;
4859
4860 if (!next_inner || next->trylock)
4861 return 0;
4862
4863 if (!next_outer)
4864 next_outer = next_inner;
4865
4866 /*
4867 * Find start of current irq_context..
4868 */
4869 for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) {
4870 struct held_lock *prev = curr->held_locks + depth;
4871 if (prev->irq_context != next->irq_context)
4872 break;
4873 }
4874 depth++;
4875
4876 curr_inner = task_wait_context(curr);
4877
4878 for (; depth < curr->lockdep_depth; depth++) {
4879 struct held_lock *prev = curr->held_locks + depth;
4880 struct lock_class *class = hlock_class(prev);
4881 u8 prev_inner = class->wait_type_inner;
4882
4883 if (prev_inner) {
4884 /*
4885 * We can have a bigger inner than a previous one
4886 * when outer is smaller than inner, as with RCU.
4887 *
4888 * Also due to trylocks.
4889 */
4890 curr_inner = min(curr_inner, prev_inner);
4891
4892 /*
4893 * Allow override for annotations -- this is typically
4894 * only valid/needed for code that only exists when
4895 * CONFIG_PREEMPT_RT=n.
4896 */
4897 if (unlikely(class->lock_type == LD_LOCK_WAIT_OVERRIDE))
4898 curr_inner = prev_inner;
4899 }
4900 }
4901
4902 if (next_outer > curr_inner)
4903 return print_lock_invalid_wait_context(curr, next);
4904
4905 return 0;
4906 }
4907
4908 #else /* CONFIG_PROVE_LOCKING */
4909
4910 static inline int
mark_usage(struct task_struct * curr,struct held_lock * hlock,int check)4911 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
4912 {
4913 return 1;
4914 }
4915
task_irq_context(struct task_struct * task)4916 static inline unsigned int task_irq_context(struct task_struct *task)
4917 {
4918 return 0;
4919 }
4920
separate_irq_context(struct task_struct * curr,struct held_lock * hlock)4921 static inline int separate_irq_context(struct task_struct *curr,
4922 struct held_lock *hlock)
4923 {
4924 return 0;
4925 }
4926
check_wait_context(struct task_struct * curr,struct held_lock * next)4927 static inline int check_wait_context(struct task_struct *curr,
4928 struct held_lock *next)
4929 {
4930 return 0;
4931 }
4932
4933 #endif /* CONFIG_PROVE_LOCKING */
4934
4935 /*
4936 * Initialize a lock instance's lock-class mapping info:
4937 */
lockdep_init_map_type(struct lockdep_map * lock,const char * name,struct lock_class_key * key,int subclass,u8 inner,u8 outer,u8 lock_type)4938 void lockdep_init_map_type(struct lockdep_map *lock, const char *name,
4939 struct lock_class_key *key, int subclass,
4940 u8 inner, u8 outer, u8 lock_type)
4941 {
4942 int i;
4943
4944 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
4945 lock->class_cache[i] = NULL;
4946
4947 #ifdef CONFIG_LOCK_STAT
4948 lock->cpu = raw_smp_processor_id();
4949 #endif
4950
4951 /*
4952 * Can't be having no nameless bastards around this place!
4953 */
4954 if (DEBUG_LOCKS_WARN_ON(!name)) {
4955 lock->name = "NULL";
4956 return;
4957 }
4958
4959 lock->name = name;
4960
4961 lock->wait_type_outer = outer;
4962 lock->wait_type_inner = inner;
4963 lock->lock_type = lock_type;
4964
4965 /*
4966 * No key, no joy, we need to hash something.
4967 */
4968 if (DEBUG_LOCKS_WARN_ON(!key))
4969 return;
4970 /*
4971 * Sanity check, the lock-class key must either have been allocated
4972 * statically or must have been registered as a dynamic key.
4973 */
4974 if (!static_obj(key) && !is_dynamic_key(key)) {
4975 if (debug_locks)
4976 printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
4977 DEBUG_LOCKS_WARN_ON(1);
4978 return;
4979 }
4980 lock->key = key;
4981
4982 if (unlikely(!debug_locks))
4983 return;
4984
4985 if (subclass) {
4986 unsigned long flags;
4987
4988 if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled()))
4989 return;
4990
4991 raw_local_irq_save(flags);
4992 lockdep_recursion_inc();
4993 register_lock_class(lock, subclass, 1);
4994 lockdep_recursion_finish();
4995 raw_local_irq_restore(flags);
4996 }
4997 }
4998 EXPORT_SYMBOL_GPL(lockdep_init_map_type);
4999
5000 struct lock_class_key __lockdep_no_validate__;
5001 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
5002
5003 struct lock_class_key __lockdep_no_track__;
5004 EXPORT_SYMBOL_GPL(__lockdep_no_track__);
5005
5006 #ifdef CONFIG_PROVE_LOCKING
lockdep_set_lock_cmp_fn(struct lockdep_map * lock,lock_cmp_fn cmp_fn,lock_print_fn print_fn)5007 void lockdep_set_lock_cmp_fn(struct lockdep_map *lock, lock_cmp_fn cmp_fn,
5008 lock_print_fn print_fn)
5009 {
5010 struct lock_class *class = lock->class_cache[0];
5011 unsigned long flags;
5012
5013 raw_local_irq_save(flags);
5014 lockdep_recursion_inc();
5015
5016 if (!class)
5017 class = register_lock_class(lock, 0, 0);
5018
5019 if (class) {
5020 WARN_ON(class->cmp_fn && class->cmp_fn != cmp_fn);
5021 WARN_ON(class->print_fn && class->print_fn != print_fn);
5022
5023 class->cmp_fn = cmp_fn;
5024 class->print_fn = print_fn;
5025 }
5026
5027 lockdep_recursion_finish();
5028 raw_local_irq_restore(flags);
5029 }
5030 EXPORT_SYMBOL_GPL(lockdep_set_lock_cmp_fn);
5031 #endif
5032
5033 static void
print_lock_nested_lock_not_held(struct task_struct * curr,struct held_lock * hlock)5034 print_lock_nested_lock_not_held(struct task_struct *curr,
5035 struct held_lock *hlock)
5036 {
5037 if (!debug_locks_off())
5038 return;
5039 if (debug_locks_silent)
5040 return;
5041
5042 nbcon_cpu_emergency_enter();
5043
5044 pr_warn("\n");
5045 pr_warn("==================================\n");
5046 pr_warn("WARNING: Nested lock was not taken\n");
5047 print_kernel_ident();
5048 pr_warn("----------------------------------\n");
5049
5050 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
5051 print_lock(hlock);
5052
5053 pr_warn("\nbut this task is not holding:\n");
5054 pr_warn("%s\n", hlock->nest_lock->name);
5055
5056 pr_warn("\nstack backtrace:\n");
5057 dump_stack();
5058
5059 pr_warn("\nother info that might help us debug this:\n");
5060 lockdep_print_held_locks(curr);
5061
5062 pr_warn("\nstack backtrace:\n");
5063 dump_stack();
5064
5065 nbcon_cpu_emergency_exit();
5066 }
5067
5068 static int __lock_is_held(const struct lockdep_map *lock, int read);
5069
5070 /*
5071 * This gets called for every mutex_lock*()/spin_lock*() operation.
5072 * We maintain the dependency maps and validate the locking attempt:
5073 *
5074 * The callers must make sure that IRQs are disabled before calling it,
5075 * otherwise we could get an interrupt which would want to take locks,
5076 * which would end up in lockdep again.
5077 */
__lock_acquire(struct lockdep_map * lock,unsigned int subclass,int trylock,int read,int check,int hardirqs_off,struct lockdep_map * nest_lock,unsigned long ip,int references,int pin_count,int sync)5078 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
5079 int trylock, int read, int check, int hardirqs_off,
5080 struct lockdep_map *nest_lock, unsigned long ip,
5081 int references, int pin_count, int sync)
5082 {
5083 struct task_struct *curr = current;
5084 struct lock_class *class = NULL;
5085 struct held_lock *hlock;
5086 unsigned int depth;
5087 int chain_head = 0;
5088 int class_idx;
5089 u64 chain_key;
5090
5091 if (unlikely(!debug_locks))
5092 return 0;
5093
5094 if (unlikely(lock->key == &__lockdep_no_track__))
5095 return 0;
5096
5097 lockevent_inc(lockdep_acquire);
5098
5099 if (!prove_locking || lock->key == &__lockdep_no_validate__) {
5100 check = 0;
5101 lockevent_inc(lockdep_nocheck);
5102 }
5103
5104 if (subclass < NR_LOCKDEP_CACHING_CLASSES)
5105 class = lock->class_cache[subclass];
5106 /*
5107 * Not cached?
5108 */
5109 if (unlikely(!class)) {
5110 class = register_lock_class(lock, subclass, 0);
5111 if (!class)
5112 return 0;
5113 }
5114
5115 debug_class_ops_inc(class);
5116
5117 if (very_verbose(class)) {
5118 nbcon_cpu_emergency_enter();
5119 printk("\nacquire class [%px] %s", class->key, class->name);
5120 if (class->name_version > 1)
5121 printk(KERN_CONT "#%d", class->name_version);
5122 printk(KERN_CONT "\n");
5123 dump_stack();
5124 nbcon_cpu_emergency_exit();
5125 }
5126
5127 /*
5128 * Add the lock to the list of currently held locks.
5129 * (we dont increase the depth just yet, up until the
5130 * dependency checks are done)
5131 */
5132 depth = curr->lockdep_depth;
5133 /*
5134 * Ran out of static storage for our per-task lock stack again have we?
5135 */
5136 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
5137 return 0;
5138
5139 class_idx = class - lock_classes;
5140
5141 if (depth && !sync) {
5142 /* we're holding locks and the new held lock is not a sync */
5143 hlock = curr->held_locks + depth - 1;
5144 if (hlock->class_idx == class_idx && nest_lock) {
5145 if (!references)
5146 references++;
5147
5148 if (!hlock->references)
5149 hlock->references++;
5150
5151 hlock->references += references;
5152
5153 /* Overflow */
5154 if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
5155 return 0;
5156
5157 return 2;
5158 }
5159 }
5160
5161 hlock = curr->held_locks + depth;
5162 /*
5163 * Plain impossible, we just registered it and checked it weren't no
5164 * NULL like.. I bet this mushroom I ate was good!
5165 */
5166 if (DEBUG_LOCKS_WARN_ON(!class))
5167 return 0;
5168 hlock->class_idx = class_idx;
5169 hlock->acquire_ip = ip;
5170 hlock->instance = lock;
5171 hlock->nest_lock = nest_lock;
5172 hlock->irq_context = task_irq_context(curr);
5173 hlock->trylock = trylock;
5174 hlock->read = read;
5175 hlock->check = check;
5176 hlock->sync = !!sync;
5177 hlock->hardirqs_off = !!hardirqs_off;
5178 hlock->references = references;
5179 #ifdef CONFIG_LOCK_STAT
5180 hlock->waittime_stamp = 0;
5181 hlock->holdtime_stamp = lockstat_clock();
5182 #endif
5183 hlock->pin_count = pin_count;
5184
5185 if (check_wait_context(curr, hlock))
5186 return 0;
5187
5188 /* Initialize the lock usage bit */
5189 if (!mark_usage(curr, hlock, check))
5190 return 0;
5191
5192 /*
5193 * Calculate the chain hash: it's the combined hash of all the
5194 * lock keys along the dependency chain. We save the hash value
5195 * at every step so that we can get the current hash easily
5196 * after unlock. The chain hash is then used to cache dependency
5197 * results.
5198 *
5199 * The 'key ID' is what is the most compact key value to drive
5200 * the hash, not class->key.
5201 */
5202 /*
5203 * Whoops, we did it again.. class_idx is invalid.
5204 */
5205 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
5206 return 0;
5207
5208 chain_key = curr->curr_chain_key;
5209 if (!depth) {
5210 /*
5211 * How can we have a chain hash when we ain't got no keys?!
5212 */
5213 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
5214 return 0;
5215 chain_head = 1;
5216 }
5217
5218 hlock->prev_chain_key = chain_key;
5219 if (separate_irq_context(curr, hlock)) {
5220 chain_key = INITIAL_CHAIN_KEY;
5221 chain_head = 1;
5222 }
5223 chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
5224
5225 if (nest_lock && !__lock_is_held(nest_lock, -1)) {
5226 print_lock_nested_lock_not_held(curr, hlock);
5227 return 0;
5228 }
5229
5230 if (!debug_locks_silent) {
5231 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
5232 WARN_ON_ONCE(!hlock_class(hlock)->key);
5233 }
5234
5235 if (!validate_chain(curr, hlock, chain_head, chain_key))
5236 return 0;
5237
5238 /* For lock_sync(), we are done here since no actual critical section */
5239 if (hlock->sync)
5240 return 1;
5241
5242 curr->curr_chain_key = chain_key;
5243 curr->lockdep_depth++;
5244 check_chain_key(curr);
5245 #ifdef CONFIG_DEBUG_LOCKDEP
5246 if (unlikely(!debug_locks))
5247 return 0;
5248 #endif
5249 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
5250 debug_locks_off();
5251 nbcon_cpu_emergency_enter();
5252 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
5253 printk(KERN_DEBUG "depth: %i max: %lu!\n",
5254 curr->lockdep_depth, MAX_LOCK_DEPTH);
5255
5256 lockdep_print_held_locks(current);
5257 debug_show_all_locks();
5258 dump_stack();
5259 nbcon_cpu_emergency_exit();
5260
5261 return 0;
5262 }
5263
5264 if (unlikely(curr->lockdep_depth > max_lockdep_depth))
5265 max_lockdep_depth = curr->lockdep_depth;
5266
5267 return 1;
5268 }
5269
print_unlock_imbalance_bug(struct task_struct * curr,struct lockdep_map * lock,unsigned long ip)5270 static void print_unlock_imbalance_bug(struct task_struct *curr,
5271 struct lockdep_map *lock,
5272 unsigned long ip)
5273 {
5274 if (!debug_locks_off())
5275 return;
5276 if (debug_locks_silent)
5277 return;
5278
5279 nbcon_cpu_emergency_enter();
5280
5281 pr_warn("\n");
5282 pr_warn("=====================================\n");
5283 pr_warn("WARNING: bad unlock balance detected!\n");
5284 print_kernel_ident();
5285 pr_warn("-------------------------------------\n");
5286 pr_warn("%s/%d is trying to release lock (",
5287 curr->comm, task_pid_nr(curr));
5288 print_lockdep_cache(lock);
5289 pr_cont(") at:\n");
5290 print_ip_sym(KERN_WARNING, ip);
5291 pr_warn("but there are no more locks to release!\n");
5292 pr_warn("\nother info that might help us debug this:\n");
5293 lockdep_print_held_locks(curr);
5294
5295 pr_warn("\nstack backtrace:\n");
5296 dump_stack();
5297
5298 nbcon_cpu_emergency_exit();
5299 }
5300
match_held_lock(const struct held_lock * hlock,const struct lockdep_map * lock)5301 static noinstr int match_held_lock(const struct held_lock *hlock,
5302 const struct lockdep_map *lock)
5303 {
5304 if (hlock->instance == lock)
5305 return 1;
5306
5307 if (hlock->references) {
5308 const struct lock_class *class = lock->class_cache[0];
5309
5310 if (!class)
5311 class = look_up_lock_class(lock, 0);
5312
5313 /*
5314 * If look_up_lock_class() failed to find a class, we're trying
5315 * to test if we hold a lock that has never yet been acquired.
5316 * Clearly if the lock hasn't been acquired _ever_, we're not
5317 * holding it either, so report failure.
5318 */
5319 if (!class)
5320 return 0;
5321
5322 /*
5323 * References, but not a lock we're actually ref-counting?
5324 * State got messed up, follow the sites that change ->references
5325 * and try to make sense of it.
5326 */
5327 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
5328 return 0;
5329
5330 if (hlock->class_idx == class - lock_classes)
5331 return 1;
5332 }
5333
5334 return 0;
5335 }
5336
5337 /* @depth must not be zero */
find_held_lock(struct task_struct * curr,struct lockdep_map * lock,unsigned int depth,int * idx)5338 static struct held_lock *find_held_lock(struct task_struct *curr,
5339 struct lockdep_map *lock,
5340 unsigned int depth, int *idx)
5341 {
5342 struct held_lock *ret, *hlock, *prev_hlock;
5343 int i;
5344
5345 i = depth - 1;
5346 hlock = curr->held_locks + i;
5347 ret = hlock;
5348 if (match_held_lock(hlock, lock))
5349 goto out;
5350
5351 ret = NULL;
5352 for (i--, prev_hlock = hlock--;
5353 i >= 0;
5354 i--, prev_hlock = hlock--) {
5355 /*
5356 * We must not cross into another context:
5357 */
5358 if (prev_hlock->irq_context != hlock->irq_context) {
5359 ret = NULL;
5360 break;
5361 }
5362 if (match_held_lock(hlock, lock)) {
5363 ret = hlock;
5364 break;
5365 }
5366 }
5367
5368 out:
5369 *idx = i;
5370 return ret;
5371 }
5372
reacquire_held_locks(struct task_struct * curr,unsigned int depth,int idx,unsigned int * merged)5373 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
5374 int idx, unsigned int *merged)
5375 {
5376 struct held_lock *hlock;
5377 int first_idx = idx;
5378
5379 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
5380 return 0;
5381
5382 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
5383 switch (__lock_acquire(hlock->instance,
5384 hlock_class(hlock)->subclass,
5385 hlock->trylock,
5386 hlock->read, hlock->check,
5387 hlock->hardirqs_off,
5388 hlock->nest_lock, hlock->acquire_ip,
5389 hlock->references, hlock->pin_count, 0)) {
5390 case 0:
5391 return 1;
5392 case 1:
5393 break;
5394 case 2:
5395 *merged += (idx == first_idx);
5396 break;
5397 default:
5398 WARN_ON(1);
5399 return 0;
5400 }
5401 }
5402 return 0;
5403 }
5404
5405 static int
__lock_set_class(struct lockdep_map * lock,const char * name,struct lock_class_key * key,unsigned int subclass,unsigned long ip)5406 __lock_set_class(struct lockdep_map *lock, const char *name,
5407 struct lock_class_key *key, unsigned int subclass,
5408 unsigned long ip)
5409 {
5410 struct task_struct *curr = current;
5411 unsigned int depth, merged = 0;
5412 struct held_lock *hlock;
5413 struct lock_class *class;
5414 int i;
5415
5416 if (unlikely(!debug_locks))
5417 return 0;
5418
5419 depth = curr->lockdep_depth;
5420 /*
5421 * This function is about (re)setting the class of a held lock,
5422 * yet we're not actually holding any locks. Naughty user!
5423 */
5424 if (DEBUG_LOCKS_WARN_ON(!depth))
5425 return 0;
5426
5427 hlock = find_held_lock(curr, lock, depth, &i);
5428 if (!hlock) {
5429 print_unlock_imbalance_bug(curr, lock, ip);
5430 return 0;
5431 }
5432
5433 lockdep_init_map_type(lock, name, key, 0,
5434 lock->wait_type_inner,
5435 lock->wait_type_outer,
5436 lock->lock_type);
5437 class = register_lock_class(lock, subclass, 0);
5438 hlock->class_idx = class - lock_classes;
5439
5440 curr->lockdep_depth = i;
5441 curr->curr_chain_key = hlock->prev_chain_key;
5442
5443 if (reacquire_held_locks(curr, depth, i, &merged))
5444 return 0;
5445
5446 /*
5447 * I took it apart and put it back together again, except now I have
5448 * these 'spare' parts.. where shall I put them.
5449 */
5450 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
5451 return 0;
5452 return 1;
5453 }
5454
__lock_downgrade(struct lockdep_map * lock,unsigned long ip)5455 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5456 {
5457 struct task_struct *curr = current;
5458 unsigned int depth, merged = 0;
5459 struct held_lock *hlock;
5460 int i;
5461
5462 if (unlikely(!debug_locks))
5463 return 0;
5464
5465 depth = curr->lockdep_depth;
5466 /*
5467 * This function is about (re)setting the class of a held lock,
5468 * yet we're not actually holding any locks. Naughty user!
5469 */
5470 if (DEBUG_LOCKS_WARN_ON(!depth))
5471 return 0;
5472
5473 hlock = find_held_lock(curr, lock, depth, &i);
5474 if (!hlock) {
5475 print_unlock_imbalance_bug(curr, lock, ip);
5476 return 0;
5477 }
5478
5479 curr->lockdep_depth = i;
5480 curr->curr_chain_key = hlock->prev_chain_key;
5481
5482 WARN(hlock->read, "downgrading a read lock");
5483 hlock->read = 1;
5484 hlock->acquire_ip = ip;
5485
5486 if (reacquire_held_locks(curr, depth, i, &merged))
5487 return 0;
5488
5489 /* Merging can't happen with unchanged classes.. */
5490 if (DEBUG_LOCKS_WARN_ON(merged))
5491 return 0;
5492
5493 /*
5494 * I took it apart and put it back together again, except now I have
5495 * these 'spare' parts.. where shall I put them.
5496 */
5497 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
5498 return 0;
5499
5500 return 1;
5501 }
5502
5503 /*
5504 * Remove the lock from the list of currently held locks - this gets
5505 * called on mutex_unlock()/spin_unlock*() (or on a failed
5506 * mutex_lock_interruptible()).
5507 */
5508 static int
__lock_release(struct lockdep_map * lock,unsigned long ip)5509 __lock_release(struct lockdep_map *lock, unsigned long ip)
5510 {
5511 struct task_struct *curr = current;
5512 unsigned int depth, merged = 1;
5513 struct held_lock *hlock;
5514 int i;
5515
5516 if (unlikely(!debug_locks))
5517 return 0;
5518
5519 depth = curr->lockdep_depth;
5520 /*
5521 * So we're all set to release this lock.. wait what lock? We don't
5522 * own any locks, you've been drinking again?
5523 */
5524 if (depth <= 0) {
5525 print_unlock_imbalance_bug(curr, lock, ip);
5526 return 0;
5527 }
5528
5529 /*
5530 * Check whether the lock exists in the current stack
5531 * of held locks:
5532 */
5533 hlock = find_held_lock(curr, lock, depth, &i);
5534 if (!hlock) {
5535 print_unlock_imbalance_bug(curr, lock, ip);
5536 return 0;
5537 }
5538
5539 if (hlock->instance == lock)
5540 lock_release_holdtime(hlock);
5541
5542 WARN(hlock->pin_count, "releasing a pinned lock\n");
5543
5544 if (hlock->references) {
5545 hlock->references--;
5546 if (hlock->references) {
5547 /*
5548 * We had, and after removing one, still have
5549 * references, the current lock stack is still
5550 * valid. We're done!
5551 */
5552 return 1;
5553 }
5554 }
5555
5556 /*
5557 * We have the right lock to unlock, 'hlock' points to it.
5558 * Now we remove it from the stack, and add back the other
5559 * entries (if any), recalculating the hash along the way:
5560 */
5561
5562 curr->lockdep_depth = i;
5563 curr->curr_chain_key = hlock->prev_chain_key;
5564
5565 /*
5566 * The most likely case is when the unlock is on the innermost
5567 * lock. In this case, we are done!
5568 */
5569 if (i == depth-1)
5570 return 1;
5571
5572 if (reacquire_held_locks(curr, depth, i + 1, &merged))
5573 return 0;
5574
5575 /*
5576 * We had N bottles of beer on the wall, we drank one, but now
5577 * there's not N-1 bottles of beer left on the wall...
5578 * Pouring two of the bottles together is acceptable.
5579 */
5580 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
5581
5582 /*
5583 * Since reacquire_held_locks() would have called check_chain_key()
5584 * indirectly via __lock_acquire(), we don't need to do it again
5585 * on return.
5586 */
5587 return 0;
5588 }
5589
5590 static __always_inline
__lock_is_held(const struct lockdep_map * lock,int read)5591 int __lock_is_held(const struct lockdep_map *lock, int read)
5592 {
5593 struct task_struct *curr = current;
5594 int i;
5595
5596 for (i = 0; i < curr->lockdep_depth; i++) {
5597 struct held_lock *hlock = curr->held_locks + i;
5598
5599 if (match_held_lock(hlock, lock)) {
5600 if (read == -1 || !!hlock->read == read)
5601 return LOCK_STATE_HELD;
5602
5603 return LOCK_STATE_NOT_HELD;
5604 }
5605 }
5606
5607 return LOCK_STATE_NOT_HELD;
5608 }
5609
__lock_pin_lock(struct lockdep_map * lock)5610 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
5611 {
5612 struct pin_cookie cookie = NIL_COOKIE;
5613 struct task_struct *curr = current;
5614 int i;
5615
5616 if (unlikely(!debug_locks))
5617 return cookie;
5618
5619 for (i = 0; i < curr->lockdep_depth; i++) {
5620 struct held_lock *hlock = curr->held_locks + i;
5621
5622 if (match_held_lock(hlock, lock)) {
5623 /*
5624 * Grab 16bits of randomness; this is sufficient to not
5625 * be guessable and still allows some pin nesting in
5626 * our u32 pin_count.
5627 */
5628 cookie.val = 1 + (sched_clock() & 0xffff);
5629 hlock->pin_count += cookie.val;
5630 return cookie;
5631 }
5632 }
5633
5634 WARN(1, "pinning an unheld lock\n");
5635 return cookie;
5636 }
5637
__lock_repin_lock(struct lockdep_map * lock,struct pin_cookie cookie)5638 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5639 {
5640 struct task_struct *curr = current;
5641 int i;
5642
5643 if (unlikely(!debug_locks))
5644 return;
5645
5646 for (i = 0; i < curr->lockdep_depth; i++) {
5647 struct held_lock *hlock = curr->held_locks + i;
5648
5649 if (match_held_lock(hlock, lock)) {
5650 hlock->pin_count += cookie.val;
5651 return;
5652 }
5653 }
5654
5655 WARN(1, "pinning an unheld lock\n");
5656 }
5657
__lock_unpin_lock(struct lockdep_map * lock,struct pin_cookie cookie)5658 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5659 {
5660 struct task_struct *curr = current;
5661 int i;
5662
5663 if (unlikely(!debug_locks))
5664 return;
5665
5666 for (i = 0; i < curr->lockdep_depth; i++) {
5667 struct held_lock *hlock = curr->held_locks + i;
5668
5669 if (match_held_lock(hlock, lock)) {
5670 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
5671 return;
5672
5673 hlock->pin_count -= cookie.val;
5674
5675 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
5676 hlock->pin_count = 0;
5677
5678 return;
5679 }
5680 }
5681
5682 WARN(1, "unpinning an unheld lock\n");
5683 }
5684
5685 /*
5686 * Check whether we follow the irq-flags state precisely:
5687 */
check_flags(unsigned long flags)5688 static noinstr void check_flags(unsigned long flags)
5689 {
5690 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP)
5691 if (!debug_locks)
5692 return;
5693
5694 /* Get the warning out.. */
5695 instrumentation_begin();
5696
5697 if (irqs_disabled_flags(flags)) {
5698 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) {
5699 printk("possible reason: unannotated irqs-off.\n");
5700 }
5701 } else {
5702 if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) {
5703 printk("possible reason: unannotated irqs-on.\n");
5704 }
5705 }
5706
5707 #ifndef CONFIG_PREEMPT_RT
5708 /*
5709 * We dont accurately track softirq state in e.g.
5710 * hardirq contexts (such as on 4KSTACKS), so only
5711 * check if not in hardirq contexts:
5712 */
5713 if (!hardirq_count()) {
5714 if (softirq_count()) {
5715 /* like the above, but with softirqs */
5716 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
5717 } else {
5718 /* lick the above, does it taste good? */
5719 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
5720 }
5721 }
5722 #endif
5723
5724 if (!debug_locks)
5725 print_irqtrace_events(current);
5726
5727 instrumentation_end();
5728 #endif
5729 }
5730
lock_set_class(struct lockdep_map * lock,const char * name,struct lock_class_key * key,unsigned int subclass,unsigned long ip)5731 void lock_set_class(struct lockdep_map *lock, const char *name,
5732 struct lock_class_key *key, unsigned int subclass,
5733 unsigned long ip)
5734 {
5735 unsigned long flags;
5736
5737 if (unlikely(!lockdep_enabled()))
5738 return;
5739
5740 raw_local_irq_save(flags);
5741 lockdep_recursion_inc();
5742 check_flags(flags);
5743 if (__lock_set_class(lock, name, key, subclass, ip))
5744 check_chain_key(current);
5745 lockdep_recursion_finish();
5746 raw_local_irq_restore(flags);
5747 }
5748 EXPORT_SYMBOL_GPL(lock_set_class);
5749
lock_downgrade(struct lockdep_map * lock,unsigned long ip)5750 void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
5751 {
5752 unsigned long flags;
5753
5754 if (unlikely(!lockdep_enabled()))
5755 return;
5756
5757 raw_local_irq_save(flags);
5758 lockdep_recursion_inc();
5759 check_flags(flags);
5760 if (__lock_downgrade(lock, ip))
5761 check_chain_key(current);
5762 lockdep_recursion_finish();
5763 raw_local_irq_restore(flags);
5764 }
5765 EXPORT_SYMBOL_GPL(lock_downgrade);
5766
5767 /* NMI context !!! */
verify_lock_unused(struct lockdep_map * lock,struct held_lock * hlock,int subclass)5768 static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass)
5769 {
5770 #ifdef CONFIG_PROVE_LOCKING
5771 struct lock_class *class = look_up_lock_class(lock, subclass);
5772 unsigned long mask = LOCKF_USED;
5773
5774 /* if it doesn't have a class (yet), it certainly hasn't been used yet */
5775 if (!class)
5776 return;
5777
5778 /*
5779 * READ locks only conflict with USED, such that if we only ever use
5780 * READ locks, there is no deadlock possible -- RCU.
5781 */
5782 if (!hlock->read)
5783 mask |= LOCKF_USED_READ;
5784
5785 if (!(class->usage_mask & mask))
5786 return;
5787
5788 hlock->class_idx = class - lock_classes;
5789
5790 print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES);
5791 #endif
5792 }
5793
lockdep_nmi(void)5794 static bool lockdep_nmi(void)
5795 {
5796 if (raw_cpu_read(lockdep_recursion))
5797 return false;
5798
5799 if (!in_nmi())
5800 return false;
5801
5802 return true;
5803 }
5804
5805 /*
5806 * read_lock() is recursive if:
5807 * 1. We force lockdep think this way in selftests or
5808 * 2. The implementation is not queued read/write lock or
5809 * 3. The locker is at an in_interrupt() context.
5810 */
read_lock_is_recursive(void)5811 bool read_lock_is_recursive(void)
5812 {
5813 return force_read_lock_recursive ||
5814 !IS_ENABLED(CONFIG_QUEUED_RWLOCKS) ||
5815 in_interrupt();
5816 }
5817 EXPORT_SYMBOL_GPL(read_lock_is_recursive);
5818
5819 /*
5820 * We are not always called with irqs disabled - do that here,
5821 * and also avoid lockdep recursion:
5822 */
lock_acquire(struct lockdep_map * lock,unsigned int subclass,int trylock,int read,int check,struct lockdep_map * nest_lock,unsigned long ip)5823 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
5824 int trylock, int read, int check,
5825 struct lockdep_map *nest_lock, unsigned long ip)
5826 {
5827 unsigned long flags;
5828
5829 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
5830
5831 if (!debug_locks)
5832 return;
5833
5834 /*
5835 * As KASAN instrumentation is disabled and lock_acquire() is usually
5836 * the first lockdep call when a task tries to acquire a lock, add
5837 * kasan_check_byte() here to check for use-after-free and other
5838 * memory errors.
5839 */
5840 kasan_check_byte(lock);
5841
5842 if (unlikely(!lockdep_enabled())) {
5843 /* XXX allow trylock from NMI ?!? */
5844 if (lockdep_nmi() && !trylock) {
5845 struct held_lock hlock;
5846
5847 hlock.acquire_ip = ip;
5848 hlock.instance = lock;
5849 hlock.nest_lock = nest_lock;
5850 hlock.irq_context = 2; // XXX
5851 hlock.trylock = trylock;
5852 hlock.read = read;
5853 hlock.check = check;
5854 hlock.hardirqs_off = true;
5855 hlock.references = 0;
5856
5857 verify_lock_unused(lock, &hlock, subclass);
5858 }
5859 return;
5860 }
5861
5862 raw_local_irq_save(flags);
5863 check_flags(flags);
5864
5865 lockdep_recursion_inc();
5866 __lock_acquire(lock, subclass, trylock, read, check,
5867 irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 0);
5868 lockdep_recursion_finish();
5869 raw_local_irq_restore(flags);
5870 }
5871 EXPORT_SYMBOL_GPL(lock_acquire);
5872
lock_release(struct lockdep_map * lock,unsigned long ip)5873 void lock_release(struct lockdep_map *lock, unsigned long ip)
5874 {
5875 unsigned long flags;
5876
5877 trace_lock_release(lock, ip);
5878
5879 if (unlikely(!lockdep_enabled() ||
5880 lock->key == &__lockdep_no_track__))
5881 return;
5882
5883 raw_local_irq_save(flags);
5884 check_flags(flags);
5885
5886 lockdep_recursion_inc();
5887 if (__lock_release(lock, ip))
5888 check_chain_key(current);
5889 lockdep_recursion_finish();
5890 raw_local_irq_restore(flags);
5891 }
5892 EXPORT_SYMBOL_GPL(lock_release);
5893
5894 /*
5895 * lock_sync() - A special annotation for synchronize_{s,}rcu()-like API.
5896 *
5897 * No actual critical section is created by the APIs annotated with this: these
5898 * APIs are used to wait for one or multiple critical sections (on other CPUs
5899 * or threads), and it means that calling these APIs inside these critical
5900 * sections is potential deadlock.
5901 */
lock_sync(struct lockdep_map * lock,unsigned subclass,int read,int check,struct lockdep_map * nest_lock,unsigned long ip)5902 void lock_sync(struct lockdep_map *lock, unsigned subclass, int read,
5903 int check, struct lockdep_map *nest_lock, unsigned long ip)
5904 {
5905 unsigned long flags;
5906
5907 if (unlikely(!lockdep_enabled()))
5908 return;
5909
5910 raw_local_irq_save(flags);
5911 check_flags(flags);
5912
5913 lockdep_recursion_inc();
5914 __lock_acquire(lock, subclass, 0, read, check,
5915 irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 1);
5916 check_chain_key(current);
5917 lockdep_recursion_finish();
5918 raw_local_irq_restore(flags);
5919 }
5920 EXPORT_SYMBOL_GPL(lock_sync);
5921
lock_is_held_type(const struct lockdep_map * lock,int read)5922 noinstr int lock_is_held_type(const struct lockdep_map *lock, int read)
5923 {
5924 unsigned long flags;
5925 int ret = LOCK_STATE_NOT_HELD;
5926
5927 /*
5928 * Avoid false negative lockdep_assert_held() and
5929 * lockdep_assert_not_held().
5930 */
5931 if (unlikely(!lockdep_enabled()))
5932 return LOCK_STATE_UNKNOWN;
5933
5934 raw_local_irq_save(flags);
5935 check_flags(flags);
5936
5937 lockdep_recursion_inc();
5938 ret = __lock_is_held(lock, read);
5939 lockdep_recursion_finish();
5940 raw_local_irq_restore(flags);
5941
5942 return ret;
5943 }
5944 EXPORT_SYMBOL_GPL(lock_is_held_type);
5945 NOKPROBE_SYMBOL(lock_is_held_type);
5946
lock_pin_lock(struct lockdep_map * lock)5947 struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
5948 {
5949 struct pin_cookie cookie = NIL_COOKIE;
5950 unsigned long flags;
5951
5952 if (unlikely(!lockdep_enabled()))
5953 return cookie;
5954
5955 raw_local_irq_save(flags);
5956 check_flags(flags);
5957
5958 lockdep_recursion_inc();
5959 cookie = __lock_pin_lock(lock);
5960 lockdep_recursion_finish();
5961 raw_local_irq_restore(flags);
5962
5963 return cookie;
5964 }
5965 EXPORT_SYMBOL_GPL(lock_pin_lock);
5966
lock_repin_lock(struct lockdep_map * lock,struct pin_cookie cookie)5967 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5968 {
5969 unsigned long flags;
5970
5971 if (unlikely(!lockdep_enabled()))
5972 return;
5973
5974 raw_local_irq_save(flags);
5975 check_flags(flags);
5976
5977 lockdep_recursion_inc();
5978 __lock_repin_lock(lock, cookie);
5979 lockdep_recursion_finish();
5980 raw_local_irq_restore(flags);
5981 }
5982 EXPORT_SYMBOL_GPL(lock_repin_lock);
5983
lock_unpin_lock(struct lockdep_map * lock,struct pin_cookie cookie)5984 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
5985 {
5986 unsigned long flags;
5987
5988 if (unlikely(!lockdep_enabled()))
5989 return;
5990
5991 raw_local_irq_save(flags);
5992 check_flags(flags);
5993
5994 lockdep_recursion_inc();
5995 __lock_unpin_lock(lock, cookie);
5996 lockdep_recursion_finish();
5997 raw_local_irq_restore(flags);
5998 }
5999 EXPORT_SYMBOL_GPL(lock_unpin_lock);
6000
6001 #ifdef CONFIG_LOCK_STAT
print_lock_contention_bug(struct task_struct * curr,struct lockdep_map * lock,unsigned long ip)6002 static void print_lock_contention_bug(struct task_struct *curr,
6003 struct lockdep_map *lock,
6004 unsigned long ip)
6005 {
6006 if (!debug_locks_off())
6007 return;
6008 if (debug_locks_silent)
6009 return;
6010
6011 nbcon_cpu_emergency_enter();
6012
6013 pr_warn("\n");
6014 pr_warn("=================================\n");
6015 pr_warn("WARNING: bad contention detected!\n");
6016 print_kernel_ident();
6017 pr_warn("---------------------------------\n");
6018 pr_warn("%s/%d is trying to contend lock (",
6019 curr->comm, task_pid_nr(curr));
6020 print_lockdep_cache(lock);
6021 pr_cont(") at:\n");
6022 print_ip_sym(KERN_WARNING, ip);
6023 pr_warn("but there are no locks held!\n");
6024 pr_warn("\nother info that might help us debug this:\n");
6025 lockdep_print_held_locks(curr);
6026
6027 pr_warn("\nstack backtrace:\n");
6028 dump_stack();
6029
6030 nbcon_cpu_emergency_exit();
6031 }
6032
6033 static void
__lock_contended(struct lockdep_map * lock,unsigned long ip)6034 __lock_contended(struct lockdep_map *lock, unsigned long ip)
6035 {
6036 struct task_struct *curr = current;
6037 struct held_lock *hlock;
6038 struct lock_class_stats *stats;
6039 unsigned int depth;
6040 int i, contention_point, contending_point;
6041
6042 depth = curr->lockdep_depth;
6043 /*
6044 * Whee, we contended on this lock, except it seems we're not
6045 * actually trying to acquire anything much at all..
6046 */
6047 if (DEBUG_LOCKS_WARN_ON(!depth))
6048 return;
6049
6050 if (unlikely(lock->key == &__lockdep_no_track__))
6051 return;
6052
6053 hlock = find_held_lock(curr, lock, depth, &i);
6054 if (!hlock) {
6055 print_lock_contention_bug(curr, lock, ip);
6056 return;
6057 }
6058
6059 if (hlock->instance != lock)
6060 return;
6061
6062 hlock->waittime_stamp = lockstat_clock();
6063
6064 contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
6065 contending_point = lock_point(hlock_class(hlock)->contending_point,
6066 lock->ip);
6067
6068 stats = get_lock_stats(hlock_class(hlock));
6069 if (contention_point < LOCKSTAT_POINTS)
6070 stats->contention_point[contention_point]++;
6071 if (contending_point < LOCKSTAT_POINTS)
6072 stats->contending_point[contending_point]++;
6073 if (lock->cpu != smp_processor_id())
6074 stats->bounces[bounce_contended + !!hlock->read]++;
6075 }
6076
6077 static void
__lock_acquired(struct lockdep_map * lock,unsigned long ip)6078 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
6079 {
6080 struct task_struct *curr = current;
6081 struct held_lock *hlock;
6082 struct lock_class_stats *stats;
6083 unsigned int depth;
6084 u64 now, waittime = 0;
6085 int i, cpu;
6086
6087 depth = curr->lockdep_depth;
6088 /*
6089 * Yay, we acquired ownership of this lock we didn't try to
6090 * acquire, how the heck did that happen?
6091 */
6092 if (DEBUG_LOCKS_WARN_ON(!depth))
6093 return;
6094
6095 if (unlikely(lock->key == &__lockdep_no_track__))
6096 return;
6097
6098 hlock = find_held_lock(curr, lock, depth, &i);
6099 if (!hlock) {
6100 print_lock_contention_bug(curr, lock, _RET_IP_);
6101 return;
6102 }
6103
6104 if (hlock->instance != lock)
6105 return;
6106
6107 cpu = smp_processor_id();
6108 if (hlock->waittime_stamp) {
6109 now = lockstat_clock();
6110 waittime = now - hlock->waittime_stamp;
6111 hlock->holdtime_stamp = now;
6112 }
6113
6114 stats = get_lock_stats(hlock_class(hlock));
6115 if (waittime) {
6116 if (hlock->read)
6117 lock_time_inc(&stats->read_waittime, waittime);
6118 else
6119 lock_time_inc(&stats->write_waittime, waittime);
6120 }
6121 if (lock->cpu != cpu)
6122 stats->bounces[bounce_acquired + !!hlock->read]++;
6123
6124 lock->cpu = cpu;
6125 lock->ip = ip;
6126 }
6127
lock_contended(struct lockdep_map * lock,unsigned long ip)6128 void lock_contended(struct lockdep_map *lock, unsigned long ip)
6129 {
6130 unsigned long flags;
6131
6132 trace_lock_contended(lock, ip);
6133
6134 if (unlikely(!lock_stat || !lockdep_enabled()))
6135 return;
6136
6137 raw_local_irq_save(flags);
6138 check_flags(flags);
6139 lockdep_recursion_inc();
6140 __lock_contended(lock, ip);
6141 lockdep_recursion_finish();
6142 raw_local_irq_restore(flags);
6143 }
6144 EXPORT_SYMBOL_GPL(lock_contended);
6145
lock_acquired(struct lockdep_map * lock,unsigned long ip)6146 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
6147 {
6148 unsigned long flags;
6149
6150 trace_lock_acquired(lock, ip);
6151
6152 if (unlikely(!lock_stat || !lockdep_enabled()))
6153 return;
6154
6155 raw_local_irq_save(flags);
6156 check_flags(flags);
6157 lockdep_recursion_inc();
6158 __lock_acquired(lock, ip);
6159 lockdep_recursion_finish();
6160 raw_local_irq_restore(flags);
6161 }
6162 EXPORT_SYMBOL_GPL(lock_acquired);
6163 #endif
6164
6165 /*
6166 * Used by the testsuite, sanitize the validator state
6167 * after a simulated failure:
6168 */
6169
lockdep_reset(void)6170 void lockdep_reset(void)
6171 {
6172 unsigned long flags;
6173 int i;
6174
6175 raw_local_irq_save(flags);
6176 lockdep_init_task(current);
6177 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
6178 nr_hardirq_chains = 0;
6179 nr_softirq_chains = 0;
6180 nr_process_chains = 0;
6181 debug_locks = 1;
6182 for (i = 0; i < CHAINHASH_SIZE; i++)
6183 INIT_HLIST_HEAD(chainhash_table + i);
6184 raw_local_irq_restore(flags);
6185 }
6186
6187 /* Remove a class from a lock chain. Must be called with the graph lock held. */
remove_class_from_lock_chain(struct pending_free * pf,struct lock_chain * chain,struct lock_class * class)6188 static void remove_class_from_lock_chain(struct pending_free *pf,
6189 struct lock_chain *chain,
6190 struct lock_class *class)
6191 {
6192 #ifdef CONFIG_PROVE_LOCKING
6193 int i;
6194
6195 for (i = chain->base; i < chain->base + chain->depth; i++) {
6196 if (chain_hlock_class_idx(chain_hlocks[i]) != class - lock_classes)
6197 continue;
6198 /*
6199 * Each lock class occurs at most once in a lock chain so once
6200 * we found a match we can break out of this loop.
6201 */
6202 goto free_lock_chain;
6203 }
6204 /* Since the chain has not been modified, return. */
6205 return;
6206
6207 free_lock_chain:
6208 free_chain_hlocks(chain->base, chain->depth);
6209 /* Overwrite the chain key for concurrent RCU readers. */
6210 WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY);
6211 dec_chains(chain->irq_context);
6212
6213 /*
6214 * Note: calling hlist_del_rcu() from inside a
6215 * hlist_for_each_entry_rcu() loop is safe.
6216 */
6217 hlist_del_rcu(&chain->entry);
6218 __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
6219 nr_zapped_lock_chains++;
6220 #endif
6221 }
6222
6223 /* Must be called with the graph lock held. */
remove_class_from_lock_chains(struct pending_free * pf,struct lock_class * class)6224 static void remove_class_from_lock_chains(struct pending_free *pf,
6225 struct lock_class *class)
6226 {
6227 struct lock_chain *chain;
6228 struct hlist_head *head;
6229 int i;
6230
6231 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
6232 head = chainhash_table + i;
6233 hlist_for_each_entry_rcu(chain, head, entry) {
6234 remove_class_from_lock_chain(pf, chain, class);
6235 }
6236 }
6237 }
6238
6239 /*
6240 * Remove all references to a lock class. The caller must hold the graph lock.
6241 */
zap_class(struct pending_free * pf,struct lock_class * class)6242 static void zap_class(struct pending_free *pf, struct lock_class *class)
6243 {
6244 struct lock_list *entry;
6245 int i;
6246
6247 WARN_ON_ONCE(!class->key);
6248
6249 /*
6250 * Remove all dependencies this lock is
6251 * involved in:
6252 */
6253 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
6254 entry = list_entries + i;
6255 if (entry->class != class && entry->links_to != class)
6256 continue;
6257 __clear_bit(i, list_entries_in_use);
6258 nr_list_entries--;
6259 list_del_rcu(&entry->entry);
6260 }
6261 if (list_empty(&class->locks_after) &&
6262 list_empty(&class->locks_before)) {
6263 list_move_tail(&class->lock_entry, &pf->zapped);
6264 hlist_del_rcu(&class->hash_entry);
6265 WRITE_ONCE(class->key, NULL);
6266 WRITE_ONCE(class->name, NULL);
6267 /* Class allocated but not used, -1 in nr_unused_locks */
6268 if (class->usage_mask == 0)
6269 debug_atomic_dec(nr_unused_locks);
6270 nr_lock_classes--;
6271 __clear_bit(class - lock_classes, lock_classes_in_use);
6272 if (class - lock_classes == max_lock_class_idx)
6273 max_lock_class_idx--;
6274 } else {
6275 WARN_ONCE(true, "%s() failed for class %s\n", __func__,
6276 class->name);
6277 }
6278
6279 remove_class_from_lock_chains(pf, class);
6280 nr_zapped_classes++;
6281 }
6282
reinit_class(struct lock_class * class)6283 static void reinit_class(struct lock_class *class)
6284 {
6285 WARN_ON_ONCE(!class->lock_entry.next);
6286 WARN_ON_ONCE(!list_empty(&class->locks_after));
6287 WARN_ON_ONCE(!list_empty(&class->locks_before));
6288 memset_startat(class, 0, key);
6289 WARN_ON_ONCE(!class->lock_entry.next);
6290 WARN_ON_ONCE(!list_empty(&class->locks_after));
6291 WARN_ON_ONCE(!list_empty(&class->locks_before));
6292 }
6293
within(const void * addr,void * start,unsigned long size)6294 static inline int within(const void *addr, void *start, unsigned long size)
6295 {
6296 return addr >= start && addr < start + size;
6297 }
6298
inside_selftest(void)6299 static bool inside_selftest(void)
6300 {
6301 return current == lockdep_selftest_task_struct;
6302 }
6303
6304 /* The caller must hold the graph lock. */
get_pending_free(void)6305 static struct pending_free *get_pending_free(void)
6306 {
6307 return delayed_free.pf + delayed_free.index;
6308 }
6309
6310 static void free_zapped_rcu(struct rcu_head *cb);
6311
6312 /*
6313 * See if we need to queue an RCU callback, must called with
6314 * the lockdep lock held, returns false if either we don't have
6315 * any pending free or the callback is already scheduled.
6316 * Otherwise, a call_rcu() must follow this function call.
6317 */
prepare_call_rcu_zapped(struct pending_free * pf)6318 static bool prepare_call_rcu_zapped(struct pending_free *pf)
6319 {
6320 WARN_ON_ONCE(inside_selftest());
6321
6322 if (list_empty(&pf->zapped))
6323 return false;
6324
6325 if (delayed_free.scheduled)
6326 return false;
6327
6328 delayed_free.scheduled = true;
6329
6330 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
6331 delayed_free.index ^= 1;
6332
6333 return true;
6334 }
6335
6336 /* The caller must hold the graph lock. May be called from RCU context. */
__free_zapped_classes(struct pending_free * pf)6337 static void __free_zapped_classes(struct pending_free *pf)
6338 {
6339 struct lock_class *class;
6340
6341 check_data_structures();
6342
6343 list_for_each_entry(class, &pf->zapped, lock_entry)
6344 reinit_class(class);
6345
6346 list_splice_init(&pf->zapped, &free_lock_classes);
6347
6348 #ifdef CONFIG_PROVE_LOCKING
6349 bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
6350 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
6351 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
6352 #endif
6353 }
6354
free_zapped_rcu(struct rcu_head * ch)6355 static void free_zapped_rcu(struct rcu_head *ch)
6356 {
6357 struct pending_free *pf;
6358 unsigned long flags;
6359 bool need_callback;
6360
6361 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
6362 return;
6363
6364 raw_local_irq_save(flags);
6365 lockdep_lock();
6366
6367 /* closed head */
6368 pf = delayed_free.pf + (delayed_free.index ^ 1);
6369 __free_zapped_classes(pf);
6370 delayed_free.scheduled = false;
6371 need_callback =
6372 prepare_call_rcu_zapped(delayed_free.pf + delayed_free.index);
6373 lockdep_unlock();
6374 raw_local_irq_restore(flags);
6375
6376 /*
6377 * If there's pending free and its callback has not been scheduled,
6378 * queue an RCU callback.
6379 */
6380 if (need_callback)
6381 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
6382
6383 }
6384
6385 /*
6386 * Remove all lock classes from the class hash table and from the
6387 * all_lock_classes list whose key or name is in the address range [start,
6388 * start + size). Move these lock classes to the zapped_classes list. Must
6389 * be called with the graph lock held.
6390 */
__lockdep_free_key_range(struct pending_free * pf,void * start,unsigned long size)6391 static void __lockdep_free_key_range(struct pending_free *pf, void *start,
6392 unsigned long size)
6393 {
6394 struct lock_class *class;
6395 struct hlist_head *head;
6396 int i;
6397
6398 /* Unhash all classes that were created by a module. */
6399 for (i = 0; i < CLASSHASH_SIZE; i++) {
6400 head = classhash_table + i;
6401 hlist_for_each_entry_rcu(class, head, hash_entry) {
6402 if (!within(class->key, start, size) &&
6403 !within(class->name, start, size))
6404 continue;
6405 zap_class(pf, class);
6406 }
6407 }
6408 }
6409
6410 /*
6411 * Used in module.c to remove lock classes from memory that is going to be
6412 * freed; and possibly re-used by other modules.
6413 *
6414 * We will have had one synchronize_rcu() before getting here, so we're
6415 * guaranteed nobody will look up these exact classes -- they're properly dead
6416 * but still allocated.
6417 */
lockdep_free_key_range_reg(void * start,unsigned long size)6418 static void lockdep_free_key_range_reg(void *start, unsigned long size)
6419 {
6420 struct pending_free *pf;
6421 unsigned long flags;
6422 bool need_callback;
6423
6424 init_data_structures_once();
6425
6426 raw_local_irq_save(flags);
6427 lockdep_lock();
6428 pf = get_pending_free();
6429 __lockdep_free_key_range(pf, start, size);
6430 need_callback = prepare_call_rcu_zapped(pf);
6431 lockdep_unlock();
6432 raw_local_irq_restore(flags);
6433 if (need_callback)
6434 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
6435 /*
6436 * Wait for any possible iterators from look_up_lock_class() to pass
6437 * before continuing to free the memory they refer to.
6438 */
6439 synchronize_rcu();
6440 }
6441
6442 /*
6443 * Free all lockdep keys in the range [start, start+size). Does not sleep.
6444 * Ignores debug_locks. Must only be used by the lockdep selftests.
6445 */
lockdep_free_key_range_imm(void * start,unsigned long size)6446 static void lockdep_free_key_range_imm(void *start, unsigned long size)
6447 {
6448 struct pending_free *pf = delayed_free.pf;
6449 unsigned long flags;
6450
6451 init_data_structures_once();
6452
6453 raw_local_irq_save(flags);
6454 lockdep_lock();
6455 __lockdep_free_key_range(pf, start, size);
6456 __free_zapped_classes(pf);
6457 lockdep_unlock();
6458 raw_local_irq_restore(flags);
6459 }
6460
lockdep_free_key_range(void * start,unsigned long size)6461 void lockdep_free_key_range(void *start, unsigned long size)
6462 {
6463 init_data_structures_once();
6464
6465 if (inside_selftest())
6466 lockdep_free_key_range_imm(start, size);
6467 else
6468 lockdep_free_key_range_reg(start, size);
6469 }
6470
6471 /*
6472 * Check whether any element of the @lock->class_cache[] array refers to a
6473 * registered lock class. The caller must hold either the graph lock or the
6474 * RCU read lock.
6475 */
lock_class_cache_is_registered(struct lockdep_map * lock)6476 static bool lock_class_cache_is_registered(struct lockdep_map *lock)
6477 {
6478 struct lock_class *class;
6479 struct hlist_head *head;
6480 int i, j;
6481
6482 for (i = 0; i < CLASSHASH_SIZE; i++) {
6483 head = classhash_table + i;
6484 hlist_for_each_entry_rcu(class, head, hash_entry) {
6485 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
6486 if (lock->class_cache[j] == class)
6487 return true;
6488 }
6489 }
6490 return false;
6491 }
6492
6493 /* The caller must hold the graph lock. Does not sleep. */
__lockdep_reset_lock(struct pending_free * pf,struct lockdep_map * lock)6494 static void __lockdep_reset_lock(struct pending_free *pf,
6495 struct lockdep_map *lock)
6496 {
6497 struct lock_class *class;
6498 int j;
6499
6500 /*
6501 * Remove all classes this lock might have:
6502 */
6503 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
6504 /*
6505 * If the class exists we look it up and zap it:
6506 */
6507 class = look_up_lock_class(lock, j);
6508 if (class)
6509 zap_class(pf, class);
6510 }
6511 /*
6512 * Debug check: in the end all mapped classes should
6513 * be gone.
6514 */
6515 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
6516 debug_locks_off();
6517 }
6518
6519 /*
6520 * Remove all information lockdep has about a lock if debug_locks == 1. Free
6521 * released data structures from RCU context.
6522 */
lockdep_reset_lock_reg(struct lockdep_map * lock)6523 static void lockdep_reset_lock_reg(struct lockdep_map *lock)
6524 {
6525 struct pending_free *pf;
6526 unsigned long flags;
6527 int locked;
6528 bool need_callback = false;
6529
6530 raw_local_irq_save(flags);
6531 locked = graph_lock();
6532 if (!locked)
6533 goto out_irq;
6534
6535 pf = get_pending_free();
6536 __lockdep_reset_lock(pf, lock);
6537 need_callback = prepare_call_rcu_zapped(pf);
6538
6539 graph_unlock();
6540 out_irq:
6541 raw_local_irq_restore(flags);
6542 if (need_callback)
6543 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
6544 }
6545
6546 /*
6547 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
6548 * lockdep selftests.
6549 */
lockdep_reset_lock_imm(struct lockdep_map * lock)6550 static void lockdep_reset_lock_imm(struct lockdep_map *lock)
6551 {
6552 struct pending_free *pf = delayed_free.pf;
6553 unsigned long flags;
6554
6555 raw_local_irq_save(flags);
6556 lockdep_lock();
6557 __lockdep_reset_lock(pf, lock);
6558 __free_zapped_classes(pf);
6559 lockdep_unlock();
6560 raw_local_irq_restore(flags);
6561 }
6562
lockdep_reset_lock(struct lockdep_map * lock)6563 void lockdep_reset_lock(struct lockdep_map *lock)
6564 {
6565 init_data_structures_once();
6566
6567 if (inside_selftest())
6568 lockdep_reset_lock_imm(lock);
6569 else
6570 lockdep_reset_lock_reg(lock);
6571 }
6572
6573 /*
6574 * Unregister a dynamically allocated key.
6575 *
6576 * Unlike lockdep_register_key(), a search is always done to find a matching
6577 * key irrespective of debug_locks to avoid potential invalid access to freed
6578 * memory in lock_class entry.
6579 */
lockdep_unregister_key(struct lock_class_key * key)6580 void lockdep_unregister_key(struct lock_class_key *key)
6581 {
6582 struct hlist_head *hash_head = keyhashentry(key);
6583 struct lock_class_key *k;
6584 struct pending_free *pf;
6585 unsigned long flags;
6586 bool found = false;
6587 bool need_callback = false;
6588
6589 might_sleep();
6590
6591 if (WARN_ON_ONCE(static_obj(key)))
6592 return;
6593
6594 raw_local_irq_save(flags);
6595 lockdep_lock();
6596
6597 hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
6598 if (k == key) {
6599 hlist_del_rcu(&k->hash_entry);
6600 found = true;
6601 break;
6602 }
6603 }
6604 WARN_ON_ONCE(!found && debug_locks);
6605 if (found) {
6606 pf = get_pending_free();
6607 __lockdep_free_key_range(pf, key, 1);
6608 need_callback = prepare_call_rcu_zapped(pf);
6609 }
6610 lockdep_unlock();
6611 raw_local_irq_restore(flags);
6612
6613 if (need_callback)
6614 call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
6615
6616 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
6617 synchronize_rcu();
6618 }
6619 EXPORT_SYMBOL_GPL(lockdep_unregister_key);
6620
lockdep_init(void)6621 void __init lockdep_init(void)
6622 {
6623 pr_info("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
6624
6625 pr_info("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
6626 pr_info("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
6627 pr_info("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
6628 pr_info("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
6629 pr_info("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
6630 pr_info("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
6631 pr_info("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
6632
6633 pr_info(" memory used by lock dependency info: %zu kB\n",
6634 (sizeof(lock_classes) +
6635 sizeof(lock_classes_in_use) +
6636 sizeof(classhash_table) +
6637 sizeof(list_entries) +
6638 sizeof(list_entries_in_use) +
6639 sizeof(chainhash_table) +
6640 sizeof(delayed_free)
6641 #ifdef CONFIG_PROVE_LOCKING
6642 + sizeof(lock_cq)
6643 + sizeof(lock_chains)
6644 + sizeof(lock_chains_in_use)
6645 + sizeof(chain_hlocks)
6646 #endif
6647 ) / 1024
6648 );
6649
6650 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
6651 pr_info(" memory used for stack traces: %zu kB\n",
6652 (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
6653 );
6654 #endif
6655
6656 pr_info(" per task-struct memory footprint: %zu bytes\n",
6657 sizeof(((struct task_struct *)NULL)->held_locks));
6658 }
6659
6660 static void
print_freed_lock_bug(struct task_struct * curr,const void * mem_from,const void * mem_to,struct held_lock * hlock)6661 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
6662 const void *mem_to, struct held_lock *hlock)
6663 {
6664 if (!debug_locks_off())
6665 return;
6666 if (debug_locks_silent)
6667 return;
6668
6669 nbcon_cpu_emergency_enter();
6670
6671 pr_warn("\n");
6672 pr_warn("=========================\n");
6673 pr_warn("WARNING: held lock freed!\n");
6674 print_kernel_ident();
6675 pr_warn("-------------------------\n");
6676 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
6677 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
6678 print_lock(hlock);
6679 lockdep_print_held_locks(curr);
6680
6681 pr_warn("\nstack backtrace:\n");
6682 dump_stack();
6683
6684 nbcon_cpu_emergency_exit();
6685 }
6686
not_in_range(const void * mem_from,unsigned long mem_len,const void * lock_from,unsigned long lock_len)6687 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
6688 const void* lock_from, unsigned long lock_len)
6689 {
6690 return lock_from + lock_len <= mem_from ||
6691 mem_from + mem_len <= lock_from;
6692 }
6693
6694 /*
6695 * Called when kernel memory is freed (or unmapped), or if a lock
6696 * is destroyed or reinitialized - this code checks whether there is
6697 * any held lock in the memory range of <from> to <to>:
6698 */
debug_check_no_locks_freed(const void * mem_from,unsigned long mem_len)6699 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
6700 {
6701 struct task_struct *curr = current;
6702 struct held_lock *hlock;
6703 unsigned long flags;
6704 int i;
6705
6706 if (unlikely(!debug_locks))
6707 return;
6708
6709 raw_local_irq_save(flags);
6710 for (i = 0; i < curr->lockdep_depth; i++) {
6711 hlock = curr->held_locks + i;
6712
6713 if (not_in_range(mem_from, mem_len, hlock->instance,
6714 sizeof(*hlock->instance)))
6715 continue;
6716
6717 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
6718 break;
6719 }
6720 raw_local_irq_restore(flags);
6721 }
6722 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
6723
print_held_locks_bug(void)6724 static void print_held_locks_bug(void)
6725 {
6726 if (!debug_locks_off())
6727 return;
6728 if (debug_locks_silent)
6729 return;
6730
6731 nbcon_cpu_emergency_enter();
6732
6733 pr_warn("\n");
6734 pr_warn("====================================\n");
6735 pr_warn("WARNING: %s/%d still has locks held!\n",
6736 current->comm, task_pid_nr(current));
6737 print_kernel_ident();
6738 pr_warn("------------------------------------\n");
6739 lockdep_print_held_locks(current);
6740 pr_warn("\nstack backtrace:\n");
6741 dump_stack();
6742
6743 nbcon_cpu_emergency_exit();
6744 }
6745
debug_check_no_locks_held(void)6746 void debug_check_no_locks_held(void)
6747 {
6748 if (unlikely(current->lockdep_depth > 0))
6749 print_held_locks_bug();
6750 }
6751 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
6752
6753 #ifdef __KERNEL__
debug_show_all_locks(void)6754 void debug_show_all_locks(void)
6755 {
6756 struct task_struct *g, *p;
6757
6758 if (unlikely(!debug_locks)) {
6759 pr_warn("INFO: lockdep is turned off.\n");
6760 return;
6761 }
6762 pr_warn("\nShowing all locks held in the system:\n");
6763
6764 rcu_read_lock();
6765 for_each_process_thread(g, p) {
6766 if (!p->lockdep_depth)
6767 continue;
6768 lockdep_print_held_locks(p);
6769 touch_nmi_watchdog();
6770 touch_all_softlockup_watchdogs();
6771 }
6772 rcu_read_unlock();
6773
6774 pr_warn("\n");
6775 pr_warn("=============================================\n\n");
6776 }
6777 EXPORT_SYMBOL_GPL(debug_show_all_locks);
6778 #endif
6779
6780 /*
6781 * Careful: only use this function if you are sure that
6782 * the task cannot run in parallel!
6783 */
debug_show_held_locks(struct task_struct * task)6784 void debug_show_held_locks(struct task_struct *task)
6785 {
6786 if (unlikely(!debug_locks)) {
6787 printk("INFO: lockdep is turned off.\n");
6788 return;
6789 }
6790 lockdep_print_held_locks(task);
6791 }
6792 EXPORT_SYMBOL_GPL(debug_show_held_locks);
6793
lockdep_sys_exit(void)6794 asmlinkage __visible void lockdep_sys_exit(void)
6795 {
6796 struct task_struct *curr = current;
6797
6798 if (unlikely(curr->lockdep_depth)) {
6799 if (!debug_locks_off())
6800 return;
6801 nbcon_cpu_emergency_enter();
6802 pr_warn("\n");
6803 pr_warn("================================================\n");
6804 pr_warn("WARNING: lock held when returning to user space!\n");
6805 print_kernel_ident();
6806 pr_warn("------------------------------------------------\n");
6807 pr_warn("%s/%d is leaving the kernel with locks still held!\n",
6808 curr->comm, curr->pid);
6809 lockdep_print_held_locks(curr);
6810 nbcon_cpu_emergency_exit();
6811 }
6812
6813 /*
6814 * The lock history for each syscall should be independent. So wipe the
6815 * slate clean on return to userspace.
6816 */
6817 lockdep_invariant_state(false);
6818 }
6819
lockdep_rcu_suspicious(const char * file,const int line,const char * s)6820 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
6821 {
6822 struct task_struct *curr = current;
6823 int dl = READ_ONCE(debug_locks);
6824 bool rcu = warn_rcu_enter();
6825
6826 /* Note: the following can be executed concurrently, so be careful. */
6827 nbcon_cpu_emergency_enter();
6828 pr_warn("\n");
6829 pr_warn("=============================\n");
6830 pr_warn("WARNING: suspicious RCU usage\n");
6831 print_kernel_ident();
6832 pr_warn("-----------------------------\n");
6833 pr_warn("%s:%d %s!\n", file, line, s);
6834 pr_warn("\nother info that might help us debug this:\n\n");
6835 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n%s",
6836 !rcu_lockdep_current_cpu_online()
6837 ? "RCU used illegally from offline CPU!\n"
6838 : "",
6839 rcu_scheduler_active, dl,
6840 dl ? "" : "Possible false positive due to lockdep disabling via debug_locks = 0\n");
6841
6842 /*
6843 * If a CPU is in the RCU-free window in idle (ie: in the section
6844 * between ct_idle_enter() and ct_idle_exit(), then RCU
6845 * considers that CPU to be in an "extended quiescent state",
6846 * which means that RCU will be completely ignoring that CPU.
6847 * Therefore, rcu_read_lock() and friends have absolutely no
6848 * effect on a CPU running in that state. In other words, even if
6849 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
6850 * delete data structures out from under it. RCU really has no
6851 * choice here: we need to keep an RCU-free window in idle where
6852 * the CPU may possibly enter into low power mode. This way we can
6853 * notice an extended quiescent state to other CPUs that started a grace
6854 * period. Otherwise we would delay any grace period as long as we run
6855 * in the idle task.
6856 *
6857 * So complain bitterly if someone does call rcu_read_lock(),
6858 * rcu_read_lock_bh() and so on from extended quiescent states.
6859 */
6860 if (!rcu_is_watching())
6861 pr_warn("RCU used illegally from extended quiescent state!\n");
6862
6863 lockdep_print_held_locks(curr);
6864 pr_warn("\nstack backtrace:\n");
6865 dump_stack();
6866 nbcon_cpu_emergency_exit();
6867 warn_rcu_exit(rcu);
6868 }
6869 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);
6870