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