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