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