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