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