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