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