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