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