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