• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * kernel/lockdep.c
3  *
4  * Runtime locking correctness validator
5  *
6  * Started by Ingo Molnar:
7  *
8  *  Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
9  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
10  *
11  * this code maps all the lock dependencies as they occur in a live kernel
12  * and will warn about the following classes of locking bugs:
13  *
14  * - lock inversion scenarios
15  * - circular lock dependencies
16  * - hardirq/softirq safe/unsafe locking bugs
17  *
18  * Bugs are reported even if the current locking scenario does not cause
19  * any deadlock at this point.
20  *
21  * I.e. if anytime in the past two locks were taken in a different order,
22  * even if it happened for another task, even if those were different
23  * locks (but of the same class as this lock), this code will detect it.
24  *
25  * Thanks to Arjan van de Ven for coming up with the initial idea of
26  * mapping lock dependencies runtime.
27  */
28 #define DISABLE_BRANCH_PROFILING
29 #include <linux/mutex.h>
30 #include <linux/sched.h>
31 #include <linux/delay.h>
32 #include <linux/module.h>
33 #include <linux/proc_fs.h>
34 #include <linux/seq_file.h>
35 #include <linux/spinlock.h>
36 #include <linux/kallsyms.h>
37 #include <linux/interrupt.h>
38 #include <linux/stacktrace.h>
39 #include <linux/debug_locks.h>
40 #include <linux/irqflags.h>
41 #include <linux/utsname.h>
42 #include <linux/hash.h>
43 #include <linux/ftrace.h>
44 #include <linux/stringify.h>
45 #include <linux/bitops.h>
46 #include <linux/gfp.h>
47 #include <linux/kmemcheck.h>
48 
49 #include <asm/sections.h>
50 
51 #include "lockdep_internals.h"
52 
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/lock.h>
55 
56 #ifdef CONFIG_PROVE_LOCKING
57 int prove_locking = 1;
58 module_param(prove_locking, int, 0644);
59 #else
60 #define prove_locking 0
61 #endif
62 
63 #ifdef CONFIG_LOCK_STAT
64 int lock_stat = 1;
65 module_param(lock_stat, int, 0644);
66 #else
67 #define lock_stat 0
68 #endif
69 
70 /*
71  * lockdep_lock: protects the lockdep graph, the hashes and the
72  *               class/list/hash allocators.
73  *
74  * This is one of the rare exceptions where it's justified
75  * to use a raw spinlock - we really dont want the spinlock
76  * code to recurse back into the lockdep code...
77  */
78 static arch_spinlock_t lockdep_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
79 
graph_lock(void)80 static int graph_lock(void)
81 {
82 	arch_spin_lock(&lockdep_lock);
83 	/*
84 	 * Make sure that if another CPU detected a bug while
85 	 * walking the graph we dont change it (while the other
86 	 * CPU is busy printing out stuff with the graph lock
87 	 * dropped already)
88 	 */
89 	if (!debug_locks) {
90 		arch_spin_unlock(&lockdep_lock);
91 		return 0;
92 	}
93 	/* prevent any recursions within lockdep from causing deadlocks */
94 	current->lockdep_recursion++;
95 	return 1;
96 }
97 
graph_unlock(void)98 static inline int graph_unlock(void)
99 {
100 	if (debug_locks && !arch_spin_is_locked(&lockdep_lock)) {
101 		/*
102 		 * The lockdep graph lock isn't locked while we expect it to
103 		 * be, we're confused now, bye!
104 		 */
105 		return DEBUG_LOCKS_WARN_ON(1);
106 	}
107 
108 	current->lockdep_recursion--;
109 	arch_spin_unlock(&lockdep_lock);
110 	return 0;
111 }
112 
113 /*
114  * Turn lock debugging off and return with 0 if it was off already,
115  * and also release the graph lock:
116  */
debug_locks_off_graph_unlock(void)117 static inline int debug_locks_off_graph_unlock(void)
118 {
119 	int ret = debug_locks_off();
120 
121 	arch_spin_unlock(&lockdep_lock);
122 
123 	return ret;
124 }
125 
126 static int lockdep_initialized;
127 
128 unsigned long nr_list_entries;
129 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
130 
131 /*
132  * All data structures here are protected by the global debug_lock.
133  *
134  * Mutex key structs only get allocated, once during bootup, and never
135  * get freed - this significantly simplifies the debugging code.
136  */
137 unsigned long nr_lock_classes;
138 static struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
139 
hlock_class(struct held_lock * hlock)140 static inline struct lock_class *hlock_class(struct held_lock *hlock)
141 {
142 	if (!hlock->class_idx) {
143 		/*
144 		 * Someone passed in garbage, we give up.
145 		 */
146 		DEBUG_LOCKS_WARN_ON(1);
147 		return NULL;
148 	}
149 	return lock_classes + hlock->class_idx - 1;
150 }
151 
152 #ifdef CONFIG_LOCK_STAT
153 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS],
154 		      cpu_lock_stats);
155 
lockstat_clock(void)156 static inline u64 lockstat_clock(void)
157 {
158 	return local_clock();
159 }
160 
lock_point(unsigned long points[],unsigned long ip)161 static int lock_point(unsigned long points[], unsigned long ip)
162 {
163 	int i;
164 
165 	for (i = 0; i < LOCKSTAT_POINTS; i++) {
166 		if (points[i] == 0) {
167 			points[i] = ip;
168 			break;
169 		}
170 		if (points[i] == ip)
171 			break;
172 	}
173 
174 	return i;
175 }
176 
lock_time_inc(struct lock_time * lt,u64 time)177 static void lock_time_inc(struct lock_time *lt, u64 time)
178 {
179 	if (time > lt->max)
180 		lt->max = time;
181 
182 	if (time < lt->min || !lt->nr)
183 		lt->min = time;
184 
185 	lt->total += time;
186 	lt->nr++;
187 }
188 
lock_time_add(struct lock_time * src,struct lock_time * dst)189 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
190 {
191 	if (!src->nr)
192 		return;
193 
194 	if (src->max > dst->max)
195 		dst->max = src->max;
196 
197 	if (src->min < dst->min || !dst->nr)
198 		dst->min = src->min;
199 
200 	dst->total += src->total;
201 	dst->nr += src->nr;
202 }
203 
lock_stats(struct lock_class * class)204 struct lock_class_stats lock_stats(struct lock_class *class)
205 {
206 	struct lock_class_stats stats;
207 	int cpu, i;
208 
209 	memset(&stats, 0, sizeof(struct lock_class_stats));
210 	for_each_possible_cpu(cpu) {
211 		struct lock_class_stats *pcs =
212 			&per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
213 
214 		for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
215 			stats.contention_point[i] += pcs->contention_point[i];
216 
217 		for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
218 			stats.contending_point[i] += pcs->contending_point[i];
219 
220 		lock_time_add(&pcs->read_waittime, &stats.read_waittime);
221 		lock_time_add(&pcs->write_waittime, &stats.write_waittime);
222 
223 		lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
224 		lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
225 
226 		for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
227 			stats.bounces[i] += pcs->bounces[i];
228 	}
229 
230 	return stats;
231 }
232 
clear_lock_stats(struct lock_class * class)233 void clear_lock_stats(struct lock_class *class)
234 {
235 	int cpu;
236 
237 	for_each_possible_cpu(cpu) {
238 		struct lock_class_stats *cpu_stats =
239 			&per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
240 
241 		memset(cpu_stats, 0, sizeof(struct lock_class_stats));
242 	}
243 	memset(class->contention_point, 0, sizeof(class->contention_point));
244 	memset(class->contending_point, 0, sizeof(class->contending_point));
245 }
246 
get_lock_stats(struct lock_class * class)247 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
248 {
249 	return &get_cpu_var(cpu_lock_stats)[class - lock_classes];
250 }
251 
put_lock_stats(struct lock_class_stats * stats)252 static void put_lock_stats(struct lock_class_stats *stats)
253 {
254 	put_cpu_var(cpu_lock_stats);
255 }
256 
lock_release_holdtime(struct held_lock * hlock)257 static void lock_release_holdtime(struct held_lock *hlock)
258 {
259 	struct lock_class_stats *stats;
260 	u64 holdtime;
261 
262 	if (!lock_stat)
263 		return;
264 
265 	holdtime = lockstat_clock() - hlock->holdtime_stamp;
266 
267 	stats = get_lock_stats(hlock_class(hlock));
268 	if (hlock->read)
269 		lock_time_inc(&stats->read_holdtime, holdtime);
270 	else
271 		lock_time_inc(&stats->write_holdtime, holdtime);
272 	put_lock_stats(stats);
273 }
274 #else
lock_release_holdtime(struct held_lock * hlock)275 static inline void lock_release_holdtime(struct held_lock *hlock)
276 {
277 }
278 #endif
279 
280 /*
281  * We keep a global list of all lock classes. The list only grows,
282  * never shrinks. The list is only accessed with the lockdep
283  * spinlock lock held.
284  */
285 LIST_HEAD(all_lock_classes);
286 
287 /*
288  * The lockdep classes are in a hash-table as well, for fast lookup:
289  */
290 #define CLASSHASH_BITS		(MAX_LOCKDEP_KEYS_BITS - 1)
291 #define CLASSHASH_SIZE		(1UL << CLASSHASH_BITS)
292 #define __classhashfn(key)	hash_long((unsigned long)key, CLASSHASH_BITS)
293 #define classhashentry(key)	(classhash_table + __classhashfn((key)))
294 
295 static struct list_head classhash_table[CLASSHASH_SIZE];
296 
297 /*
298  * We put the lock dependency chains into a hash-table as well, to cache
299  * their existence:
300  */
301 #define CHAINHASH_BITS		(MAX_LOCKDEP_CHAINS_BITS-1)
302 #define CHAINHASH_SIZE		(1UL << CHAINHASH_BITS)
303 #define __chainhashfn(chain)	hash_long(chain, CHAINHASH_BITS)
304 #define chainhashentry(chain)	(chainhash_table + __chainhashfn((chain)))
305 
306 static struct list_head chainhash_table[CHAINHASH_SIZE];
307 
308 /*
309  * The hash key of the lock dependency chains is a hash itself too:
310  * it's a hash of all locks taken up to that lock, including that lock.
311  * It's a 64-bit hash, because it's important for the keys to be
312  * unique.
313  */
314 #define iterate_chain_key(key1, key2) \
315 	(((key1) << MAX_LOCKDEP_KEYS_BITS) ^ \
316 	((key1) >> (64-MAX_LOCKDEP_KEYS_BITS)) ^ \
317 	(key2))
318 
lockdep_off(void)319 void lockdep_off(void)
320 {
321 	current->lockdep_recursion++;
322 }
323 EXPORT_SYMBOL(lockdep_off);
324 
lockdep_on(void)325 void lockdep_on(void)
326 {
327 	current->lockdep_recursion--;
328 }
329 EXPORT_SYMBOL(lockdep_on);
330 
331 /*
332  * Debugging switches:
333  */
334 
335 #define VERBOSE			0
336 #define VERY_VERBOSE		0
337 
338 #if VERBOSE
339 # define HARDIRQ_VERBOSE	1
340 # define SOFTIRQ_VERBOSE	1
341 # define RECLAIM_VERBOSE	1
342 #else
343 # define HARDIRQ_VERBOSE	0
344 # define SOFTIRQ_VERBOSE	0
345 # define RECLAIM_VERBOSE	0
346 #endif
347 
348 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE || RECLAIM_VERBOSE
349 /*
350  * Quick filtering for interesting events:
351  */
class_filter(struct lock_class * class)352 static int class_filter(struct lock_class *class)
353 {
354 #if 0
355 	/* Example */
356 	if (class->name_version == 1 &&
357 			!strcmp(class->name, "lockname"))
358 		return 1;
359 	if (class->name_version == 1 &&
360 			!strcmp(class->name, "&struct->lockfield"))
361 		return 1;
362 #endif
363 	/* Filter everything else. 1 would be to allow everything else */
364 	return 0;
365 }
366 #endif
367 
verbose(struct lock_class * class)368 static int verbose(struct lock_class *class)
369 {
370 #if VERBOSE
371 	return class_filter(class);
372 #endif
373 	return 0;
374 }
375 
376 /*
377  * Stack-trace: tightly packed array of stack backtrace
378  * addresses. Protected by the graph_lock.
379  */
380 unsigned long nr_stack_trace_entries;
381 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
382 
print_lockdep_off(const char * bug_msg)383 static void print_lockdep_off(const char *bug_msg)
384 {
385 	printk(KERN_DEBUG "%s\n", bug_msg);
386 	printk(KERN_DEBUG "turning off the locking correctness validator.\n");
387 #ifdef CONFIG_LOCK_STAT
388 	printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
389 #endif
390 }
391 
save_trace(struct stack_trace * trace)392 static int save_trace(struct stack_trace *trace)
393 {
394 	trace->nr_entries = 0;
395 	trace->max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
396 	trace->entries = stack_trace + nr_stack_trace_entries;
397 
398 	trace->skip = 3;
399 
400 	save_stack_trace(trace);
401 
402 	/*
403 	 * Some daft arches put -1 at the end to indicate its a full trace.
404 	 *
405 	 * <rant> this is buggy anyway, since it takes a whole extra entry so a
406 	 * complete trace that maxes out the entries provided will be reported
407 	 * as incomplete, friggin useless </rant>
408 	 */
409 	if (trace->nr_entries != 0 &&
410 	    trace->entries[trace->nr_entries-1] == ULONG_MAX)
411 		trace->nr_entries--;
412 
413 	trace->max_entries = trace->nr_entries;
414 
415 	nr_stack_trace_entries += trace->nr_entries;
416 
417 	if (nr_stack_trace_entries >= MAX_STACK_TRACE_ENTRIES-1) {
418 		if (!debug_locks_off_graph_unlock())
419 			return 0;
420 
421 		print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
422 		dump_stack();
423 
424 		return 0;
425 	}
426 
427 	return 1;
428 }
429 
430 unsigned int nr_hardirq_chains;
431 unsigned int nr_softirq_chains;
432 unsigned int nr_process_chains;
433 unsigned int max_lockdep_depth;
434 
435 #ifdef CONFIG_DEBUG_LOCKDEP
436 /*
437  * We cannot printk in early bootup code. Not even early_printk()
438  * might work. So we mark any initialization errors and printk
439  * about it later on, in lockdep_info().
440  */
441 static int lockdep_init_error;
442 static const char *lock_init_error;
443 static unsigned long lockdep_init_trace_data[20];
444 static struct stack_trace lockdep_init_trace = {
445 	.max_entries = ARRAY_SIZE(lockdep_init_trace_data),
446 	.entries = lockdep_init_trace_data,
447 };
448 
449 /*
450  * Various lockdep statistics:
451  */
452 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
453 #endif
454 
455 /*
456  * Locking printouts:
457  */
458 
459 #define __USAGE(__STATE)						\
460 	[LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W",	\
461 	[LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W",		\
462 	[LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
463 	[LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
464 
465 static const char *usage_str[] =
466 {
467 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
468 #include "lockdep_states.h"
469 #undef LOCKDEP_STATE
470 	[LOCK_USED] = "INITIAL USE",
471 };
472 
__get_key_name(struct lockdep_subclass_key * key,char * str)473 const char * __get_key_name(struct lockdep_subclass_key *key, char *str)
474 {
475 	return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
476 }
477 
lock_flag(enum lock_usage_bit bit)478 static inline unsigned long lock_flag(enum lock_usage_bit bit)
479 {
480 	return 1UL << bit;
481 }
482 
get_usage_char(struct lock_class * class,enum lock_usage_bit bit)483 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
484 {
485 	char c = '.';
486 
487 	if (class->usage_mask & lock_flag(bit + 2))
488 		c = '+';
489 	if (class->usage_mask & lock_flag(bit)) {
490 		c = '-';
491 		if (class->usage_mask & lock_flag(bit + 2))
492 			c = '?';
493 	}
494 
495 	return c;
496 }
497 
get_usage_chars(struct lock_class * class,char usage[LOCK_USAGE_CHARS])498 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
499 {
500 	int i = 0;
501 
502 #define LOCKDEP_STATE(__STATE) 						\
503 	usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE);	\
504 	usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
505 #include "lockdep_states.h"
506 #undef LOCKDEP_STATE
507 
508 	usage[i] = '\0';
509 }
510 
__print_lock_name(struct lock_class * class)511 static void __print_lock_name(struct lock_class *class)
512 {
513 	char str[KSYM_NAME_LEN];
514 	const char *name;
515 
516 	name = class->name;
517 	if (!name) {
518 		name = __get_key_name(class->key, str);
519 		printk("%s", name);
520 	} else {
521 		printk("%s", name);
522 		if (class->name_version > 1)
523 			printk("#%d", class->name_version);
524 		if (class->subclass)
525 			printk("/%d", class->subclass);
526 	}
527 }
528 
print_lock_name(struct lock_class * class)529 static void print_lock_name(struct lock_class *class)
530 {
531 	char usage[LOCK_USAGE_CHARS];
532 
533 	get_usage_chars(class, usage);
534 
535 	printk(" (");
536 	__print_lock_name(class);
537 	printk("){%s}", usage);
538 }
539 
print_lockdep_cache(struct lockdep_map * lock)540 static void print_lockdep_cache(struct lockdep_map *lock)
541 {
542 	const char *name;
543 	char str[KSYM_NAME_LEN];
544 
545 	name = lock->name;
546 	if (!name)
547 		name = __get_key_name(lock->key->subkeys, str);
548 
549 	printk("%s", name);
550 }
551 
print_lock(struct held_lock * hlock)552 static void print_lock(struct held_lock *hlock)
553 {
554 	/*
555 	 * We can be called locklessly through debug_show_all_locks() so be
556 	 * extra careful, the hlock might have been released and cleared.
557 	 */
558 	unsigned int class_idx = hlock->class_idx;
559 
560 	/* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfields: */
561 	barrier();
562 
563 	if (!class_idx || (class_idx - 1) >= MAX_LOCKDEP_KEYS) {
564 		printk("<RELEASED>\n");
565 		return;
566 	}
567 
568 	print_lock_name(lock_classes + class_idx - 1);
569 	printk(", at: ");
570 	print_ip_sym(hlock->acquire_ip);
571 }
572 
lockdep_print_held_locks(struct task_struct * curr)573 static void lockdep_print_held_locks(struct task_struct *curr)
574 {
575 	int i, depth = curr->lockdep_depth;
576 
577 	if (!depth) {
578 		printk("no locks held by %s/%d.\n", curr->comm, task_pid_nr(curr));
579 		return;
580 	}
581 	printk("%d lock%s held by %s/%d:\n",
582 		depth, depth > 1 ? "s" : "", curr->comm, task_pid_nr(curr));
583 
584 	for (i = 0; i < depth; i++) {
585 		printk(" #%d: ", i);
586 		print_lock(curr->held_locks + i);
587 	}
588 }
589 
print_kernel_ident(void)590 static void print_kernel_ident(void)
591 {
592 	printk("%s %.*s %s\n", init_utsname()->release,
593 		(int)strcspn(init_utsname()->version, " "),
594 		init_utsname()->version,
595 		print_tainted());
596 }
597 
very_verbose(struct lock_class * class)598 static int very_verbose(struct lock_class *class)
599 {
600 #if VERY_VERBOSE
601 	return class_filter(class);
602 #endif
603 	return 0;
604 }
605 
606 /*
607  * Is this the address of a static object:
608  */
609 #ifdef __KERNEL__
static_obj(void * obj)610 static int static_obj(void *obj)
611 {
612 	unsigned long start = (unsigned long) &_stext,
613 		      end   = (unsigned long) &_end,
614 		      addr  = (unsigned long) obj;
615 
616 	/*
617 	 * static variable?
618 	 */
619 	if ((addr >= start) && (addr < end))
620 		return 1;
621 
622 	if (arch_is_kernel_data(addr))
623 		return 1;
624 
625 	/*
626 	 * in-kernel percpu var?
627 	 */
628 	if (is_kernel_percpu_address(addr))
629 		return 1;
630 
631 	/*
632 	 * module static or percpu var?
633 	 */
634 	return is_module_address(addr) || is_module_percpu_address(addr);
635 }
636 #endif
637 
638 /*
639  * To make lock name printouts unique, we calculate a unique
640  * class->name_version generation counter:
641  */
count_matching_names(struct lock_class * new_class)642 static int count_matching_names(struct lock_class *new_class)
643 {
644 	struct lock_class *class;
645 	int count = 0;
646 
647 	if (!new_class->name)
648 		return 0;
649 
650 	list_for_each_entry_rcu(class, &all_lock_classes, lock_entry) {
651 		if (new_class->key - new_class->subclass == class->key)
652 			return class->name_version;
653 		if (class->name && !strcmp(class->name, new_class->name))
654 			count = max(count, class->name_version);
655 	}
656 
657 	return count + 1;
658 }
659 
660 /*
661  * Register a lock's class in the hash-table, if the class is not present
662  * yet. Otherwise we look it up. We cache the result in the lock object
663  * itself, so actual lookup of the hash should be once per lock object.
664  */
665 static inline struct lock_class *
look_up_lock_class(struct lockdep_map * lock,unsigned int subclass)666 look_up_lock_class(struct lockdep_map *lock, unsigned int subclass)
667 {
668 	struct lockdep_subclass_key *key;
669 	struct list_head *hash_head;
670 	struct lock_class *class;
671 
672 #ifdef CONFIG_DEBUG_LOCKDEP
673 	/*
674 	 * If the architecture calls into lockdep before initializing
675 	 * the hashes then we'll warn about it later. (we cannot printk
676 	 * right now)
677 	 */
678 	if (unlikely(!lockdep_initialized)) {
679 		lockdep_init();
680 		lockdep_init_error = 1;
681 		lock_init_error = lock->name;
682 		save_stack_trace(&lockdep_init_trace);
683 	}
684 #endif
685 
686 	if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
687 		debug_locks_off();
688 		printk(KERN_ERR
689 			"BUG: looking up invalid subclass: %u\n", subclass);
690 		printk(KERN_ERR
691 			"turning off the locking correctness validator.\n");
692 		dump_stack();
693 		return NULL;
694 	}
695 
696 	/*
697 	 * Static locks do not have their class-keys yet - for them the key
698 	 * is the lock object itself:
699 	 */
700 	if (unlikely(!lock->key))
701 		lock->key = (void *)lock;
702 
703 	/*
704 	 * NOTE: the class-key must be unique. For dynamic locks, a static
705 	 * lock_class_key variable is passed in through the mutex_init()
706 	 * (or spin_lock_init()) call - which acts as the key. For static
707 	 * locks we use the lock object itself as the key.
708 	 */
709 	BUILD_BUG_ON(sizeof(struct lock_class_key) >
710 			sizeof(struct lockdep_map));
711 
712 	key = lock->key->subkeys + subclass;
713 
714 	hash_head = classhashentry(key);
715 
716 	/*
717 	 * We do an RCU walk of the hash, see lockdep_free_key_range().
718 	 */
719 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
720 		return NULL;
721 
722 	list_for_each_entry_rcu(class, hash_head, hash_entry) {
723 		if (class->key == key) {
724 			/*
725 			 * Huh! same key, different name? Did someone trample
726 			 * on some memory? We're most confused.
727 			 */
728 			WARN_ON_ONCE(class->name != lock->name);
729 			return class;
730 		}
731 	}
732 
733 	return NULL;
734 }
735 
736 /*
737  * Register a lock's class in the hash-table, if the class is not present
738  * yet. Otherwise we look it up. We cache the result in the lock object
739  * itself, so actual lookup of the hash should be once per lock object.
740  */
741 static inline struct lock_class *
register_lock_class(struct lockdep_map * lock,unsigned int subclass,int force)742 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
743 {
744 	struct lockdep_subclass_key *key;
745 	struct list_head *hash_head;
746 	struct lock_class *class;
747 
748 	DEBUG_LOCKS_WARN_ON(!irqs_disabled());
749 
750 	class = look_up_lock_class(lock, subclass);
751 	if (likely(class))
752 		goto out_set_class_cache;
753 
754 	/*
755 	 * Debug-check: all keys must be persistent!
756  	 */
757 	if (!static_obj(lock->key)) {
758 		debug_locks_off();
759 		printk("INFO: trying to register non-static key.\n");
760 		printk("the code is fine but needs lockdep annotation.\n");
761 		printk("turning off the locking correctness validator.\n");
762 		dump_stack();
763 
764 		return NULL;
765 	}
766 
767 	key = lock->key->subkeys + subclass;
768 	hash_head = classhashentry(key);
769 
770 	if (!graph_lock()) {
771 		return NULL;
772 	}
773 	/*
774 	 * We have to do the hash-walk again, to avoid races
775 	 * with another CPU:
776 	 */
777 	list_for_each_entry_rcu(class, hash_head, hash_entry) {
778 		if (class->key == key)
779 			goto out_unlock_set;
780 	}
781 
782 	/*
783 	 * Allocate a new key from the static array, and add it to
784 	 * the hash:
785 	 */
786 	if (nr_lock_classes >= MAX_LOCKDEP_KEYS) {
787 		if (!debug_locks_off_graph_unlock()) {
788 			return NULL;
789 		}
790 
791 		print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
792 		dump_stack();
793 		return NULL;
794 	}
795 	class = lock_classes + nr_lock_classes++;
796 	debug_atomic_inc(nr_unused_locks);
797 	class->key = key;
798 	class->name = lock->name;
799 	class->subclass = subclass;
800 	INIT_LIST_HEAD(&class->lock_entry);
801 	INIT_LIST_HEAD(&class->locks_before);
802 	INIT_LIST_HEAD(&class->locks_after);
803 	class->name_version = count_matching_names(class);
804 	/*
805 	 * We use RCU's safe list-add method to make
806 	 * parallel walking of the hash-list safe:
807 	 */
808 	list_add_tail_rcu(&class->hash_entry, hash_head);
809 	/*
810 	 * Add it to the global list of classes:
811 	 */
812 	list_add_tail_rcu(&class->lock_entry, &all_lock_classes);
813 
814 	if (verbose(class)) {
815 		graph_unlock();
816 
817 		printk("\nnew class %p: %s", class->key, class->name);
818 		if (class->name_version > 1)
819 			printk("#%d", class->name_version);
820 		printk("\n");
821 		dump_stack();
822 
823 		if (!graph_lock()) {
824 			return NULL;
825 		}
826 	}
827 out_unlock_set:
828 	graph_unlock();
829 
830 out_set_class_cache:
831 	if (!subclass || force)
832 		lock->class_cache[0] = class;
833 	else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
834 		lock->class_cache[subclass] = class;
835 
836 	/*
837 	 * Hash collision, did we smoke some? We found a class with a matching
838 	 * hash but the subclass -- which is hashed in -- didn't match.
839 	 */
840 	if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
841 		return NULL;
842 
843 	return class;
844 }
845 
846 #ifdef CONFIG_PROVE_LOCKING
847 /*
848  * Allocate a lockdep entry. (assumes the graph_lock held, returns
849  * with NULL on failure)
850  */
alloc_list_entry(void)851 static struct lock_list *alloc_list_entry(void)
852 {
853 	if (nr_list_entries >= MAX_LOCKDEP_ENTRIES) {
854 		if (!debug_locks_off_graph_unlock())
855 			return NULL;
856 
857 		print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
858 		dump_stack();
859 		return NULL;
860 	}
861 	return list_entries + nr_list_entries++;
862 }
863 
864 /*
865  * Add a new dependency to the head of the list:
866  */
add_lock_to_list(struct lock_class * class,struct lock_class * this,struct list_head * head,unsigned long ip,int distance,struct stack_trace * trace)867 static int add_lock_to_list(struct lock_class *class, struct lock_class *this,
868 			    struct list_head *head, unsigned long ip,
869 			    int distance, struct stack_trace *trace)
870 {
871 	struct lock_list *entry;
872 	/*
873 	 * Lock not present yet - get a new dependency struct and
874 	 * add it to the list:
875 	 */
876 	entry = alloc_list_entry();
877 	if (!entry)
878 		return 0;
879 
880 	entry->class = this;
881 	entry->distance = distance;
882 	entry->trace = *trace;
883 	/*
884 	 * Both allocation and removal are done under the graph lock; but
885 	 * iteration is under RCU-sched; see look_up_lock_class() and
886 	 * lockdep_free_key_range().
887 	 */
888 	list_add_tail_rcu(&entry->entry, head);
889 
890 	return 1;
891 }
892 
893 /*
894  * For good efficiency of modular, we use power of 2
895  */
896 #define MAX_CIRCULAR_QUEUE_SIZE		4096UL
897 #define CQ_MASK				(MAX_CIRCULAR_QUEUE_SIZE-1)
898 
899 /*
900  * The circular_queue and helpers is used to implement the
901  * breadth-first search(BFS)algorithem, by which we can build
902  * the shortest path from the next lock to be acquired to the
903  * previous held lock if there is a circular between them.
904  */
905 struct circular_queue {
906 	unsigned long element[MAX_CIRCULAR_QUEUE_SIZE];
907 	unsigned int  front, rear;
908 };
909 
910 static struct circular_queue lock_cq;
911 
912 unsigned int max_bfs_queue_depth;
913 
914 static unsigned int lockdep_dependency_gen_id;
915 
__cq_init(struct circular_queue * cq)916 static inline void __cq_init(struct circular_queue *cq)
917 {
918 	cq->front = cq->rear = 0;
919 	lockdep_dependency_gen_id++;
920 }
921 
__cq_empty(struct circular_queue * cq)922 static inline int __cq_empty(struct circular_queue *cq)
923 {
924 	return (cq->front == cq->rear);
925 }
926 
__cq_full(struct circular_queue * cq)927 static inline int __cq_full(struct circular_queue *cq)
928 {
929 	return ((cq->rear + 1) & CQ_MASK) == cq->front;
930 }
931 
__cq_enqueue(struct circular_queue * cq,unsigned long elem)932 static inline int __cq_enqueue(struct circular_queue *cq, unsigned long elem)
933 {
934 	if (__cq_full(cq))
935 		return -1;
936 
937 	cq->element[cq->rear] = elem;
938 	cq->rear = (cq->rear + 1) & CQ_MASK;
939 	return 0;
940 }
941 
__cq_dequeue(struct circular_queue * cq,unsigned long * elem)942 static inline int __cq_dequeue(struct circular_queue *cq, unsigned long *elem)
943 {
944 	if (__cq_empty(cq))
945 		return -1;
946 
947 	*elem = cq->element[cq->front];
948 	cq->front = (cq->front + 1) & CQ_MASK;
949 	return 0;
950 }
951 
__cq_get_elem_count(struct circular_queue * cq)952 static inline unsigned int  __cq_get_elem_count(struct circular_queue *cq)
953 {
954 	return (cq->rear - cq->front) & CQ_MASK;
955 }
956 
mark_lock_accessed(struct lock_list * lock,struct lock_list * parent)957 static inline void mark_lock_accessed(struct lock_list *lock,
958 					struct lock_list *parent)
959 {
960 	unsigned long nr;
961 
962 	nr = lock - list_entries;
963 	WARN_ON(nr >= nr_list_entries); /* Out-of-bounds, input fail */
964 	lock->parent = parent;
965 	lock->class->dep_gen_id = lockdep_dependency_gen_id;
966 }
967 
lock_accessed(struct lock_list * lock)968 static inline unsigned long lock_accessed(struct lock_list *lock)
969 {
970 	unsigned long nr;
971 
972 	nr = lock - list_entries;
973 	WARN_ON(nr >= nr_list_entries); /* Out-of-bounds, input fail */
974 	return lock->class->dep_gen_id == lockdep_dependency_gen_id;
975 }
976 
get_lock_parent(struct lock_list * child)977 static inline struct lock_list *get_lock_parent(struct lock_list *child)
978 {
979 	return child->parent;
980 }
981 
get_lock_depth(struct lock_list * child)982 static inline int get_lock_depth(struct lock_list *child)
983 {
984 	int depth = 0;
985 	struct lock_list *parent;
986 
987 	while ((parent = get_lock_parent(child))) {
988 		child = parent;
989 		depth++;
990 	}
991 	return depth;
992 }
993 
__bfs(struct lock_list * source_entry,void * data,int (* match)(struct lock_list * entry,void * data),struct lock_list ** target_entry,int forward)994 static int __bfs(struct lock_list *source_entry,
995 		 void *data,
996 		 int (*match)(struct lock_list *entry, void *data),
997 		 struct lock_list **target_entry,
998 		 int forward)
999 {
1000 	struct lock_list *entry;
1001 	struct list_head *head;
1002 	struct circular_queue *cq = &lock_cq;
1003 	int ret = 1;
1004 
1005 	if (match(source_entry, data)) {
1006 		*target_entry = source_entry;
1007 		ret = 0;
1008 		goto exit;
1009 	}
1010 
1011 	if (forward)
1012 		head = &source_entry->class->locks_after;
1013 	else
1014 		head = &source_entry->class->locks_before;
1015 
1016 	if (list_empty(head))
1017 		goto exit;
1018 
1019 	__cq_init(cq);
1020 	__cq_enqueue(cq, (unsigned long)source_entry);
1021 
1022 	while (!__cq_empty(cq)) {
1023 		struct lock_list *lock;
1024 
1025 		__cq_dequeue(cq, (unsigned long *)&lock);
1026 
1027 		if (!lock->class) {
1028 			ret = -2;
1029 			goto exit;
1030 		}
1031 
1032 		if (forward)
1033 			head = &lock->class->locks_after;
1034 		else
1035 			head = &lock->class->locks_before;
1036 
1037 		DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1038 
1039 		list_for_each_entry_rcu(entry, head, entry) {
1040 			if (!lock_accessed(entry)) {
1041 				unsigned int cq_depth;
1042 				mark_lock_accessed(entry, lock);
1043 				if (match(entry, data)) {
1044 					*target_entry = entry;
1045 					ret = 0;
1046 					goto exit;
1047 				}
1048 
1049 				if (__cq_enqueue(cq, (unsigned long)entry)) {
1050 					ret = -1;
1051 					goto exit;
1052 				}
1053 				cq_depth = __cq_get_elem_count(cq);
1054 				if (max_bfs_queue_depth < cq_depth)
1055 					max_bfs_queue_depth = cq_depth;
1056 			}
1057 		}
1058 	}
1059 exit:
1060 	return ret;
1061 }
1062 
__bfs_forwards(struct lock_list * src_entry,void * data,int (* match)(struct lock_list * entry,void * data),struct lock_list ** target_entry)1063 static inline int __bfs_forwards(struct lock_list *src_entry,
1064 			void *data,
1065 			int (*match)(struct lock_list *entry, void *data),
1066 			struct lock_list **target_entry)
1067 {
1068 	return __bfs(src_entry, data, match, target_entry, 1);
1069 
1070 }
1071 
__bfs_backwards(struct lock_list * src_entry,void * data,int (* match)(struct lock_list * entry,void * data),struct lock_list ** target_entry)1072 static inline int __bfs_backwards(struct lock_list *src_entry,
1073 			void *data,
1074 			int (*match)(struct lock_list *entry, void *data),
1075 			struct lock_list **target_entry)
1076 {
1077 	return __bfs(src_entry, data, match, target_entry, 0);
1078 
1079 }
1080 
1081 /*
1082  * Recursive, forwards-direction lock-dependency checking, used for
1083  * both noncyclic checking and for hardirq-unsafe/softirq-unsafe
1084  * checking.
1085  */
1086 
1087 /*
1088  * Print a dependency chain entry (this is only done when a deadlock
1089  * has been detected):
1090  */
1091 static noinline int
print_circular_bug_entry(struct lock_list * target,int depth)1092 print_circular_bug_entry(struct lock_list *target, int depth)
1093 {
1094 	if (debug_locks_silent)
1095 		return 0;
1096 	printk("\n-> #%u", depth);
1097 	print_lock_name(target->class);
1098 	printk(":\n");
1099 	print_stack_trace(&target->trace, 6);
1100 
1101 	return 0;
1102 }
1103 
1104 static void
print_circular_lock_scenario(struct held_lock * src,struct held_lock * tgt,struct lock_list * prt)1105 print_circular_lock_scenario(struct held_lock *src,
1106 			     struct held_lock *tgt,
1107 			     struct lock_list *prt)
1108 {
1109 	struct lock_class *source = hlock_class(src);
1110 	struct lock_class *target = hlock_class(tgt);
1111 	struct lock_class *parent = prt->class;
1112 
1113 	/*
1114 	 * A direct locking problem where unsafe_class lock is taken
1115 	 * directly by safe_class lock, then all we need to show
1116 	 * is the deadlock scenario, as it is obvious that the
1117 	 * unsafe lock is taken under the safe lock.
1118 	 *
1119 	 * But if there is a chain instead, where the safe lock takes
1120 	 * an intermediate lock (middle_class) where this lock is
1121 	 * not the same as the safe lock, then the lock chain is
1122 	 * used to describe the problem. Otherwise we would need
1123 	 * to show a different CPU case for each link in the chain
1124 	 * from the safe_class lock to the unsafe_class lock.
1125 	 */
1126 	if (parent != source) {
1127 		printk("Chain exists of:\n  ");
1128 		__print_lock_name(source);
1129 		printk(" --> ");
1130 		__print_lock_name(parent);
1131 		printk(" --> ");
1132 		__print_lock_name(target);
1133 		printk("\n\n");
1134 	}
1135 
1136 	printk(" Possible unsafe locking scenario:\n\n");
1137 	printk("       CPU0                    CPU1\n");
1138 	printk("       ----                    ----\n");
1139 	printk("  lock(");
1140 	__print_lock_name(target);
1141 	printk(");\n");
1142 	printk("                               lock(");
1143 	__print_lock_name(parent);
1144 	printk(");\n");
1145 	printk("                               lock(");
1146 	__print_lock_name(target);
1147 	printk(");\n");
1148 	printk("  lock(");
1149 	__print_lock_name(source);
1150 	printk(");\n");
1151 	printk("\n *** DEADLOCK ***\n\n");
1152 }
1153 
1154 /*
1155  * When a circular dependency is detected, print the
1156  * header first:
1157  */
1158 static noinline int
print_circular_bug_header(struct lock_list * entry,unsigned int depth,struct held_lock * check_src,struct held_lock * check_tgt)1159 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1160 			struct held_lock *check_src,
1161 			struct held_lock *check_tgt)
1162 {
1163 	struct task_struct *curr = current;
1164 
1165 	if (debug_locks_silent)
1166 		return 0;
1167 
1168 	printk("\n");
1169 	printk("======================================================\n");
1170 	printk("[ INFO: possible circular locking dependency detected ]\n");
1171 	print_kernel_ident();
1172 	printk("-------------------------------------------------------\n");
1173 	printk("%s/%d is trying to acquire lock:\n",
1174 		curr->comm, task_pid_nr(curr));
1175 	print_lock(check_src);
1176 	printk("\nbut task is already holding lock:\n");
1177 	print_lock(check_tgt);
1178 	printk("\nwhich lock already depends on the new lock.\n\n");
1179 	printk("\nthe existing dependency chain (in reverse order) is:\n");
1180 
1181 	print_circular_bug_entry(entry, depth);
1182 
1183 	return 0;
1184 }
1185 
class_equal(struct lock_list * entry,void * data)1186 static inline int class_equal(struct lock_list *entry, void *data)
1187 {
1188 	return entry->class == data;
1189 }
1190 
print_circular_bug(struct lock_list * this,struct lock_list * target,struct held_lock * check_src,struct held_lock * check_tgt)1191 static noinline int print_circular_bug(struct lock_list *this,
1192 				struct lock_list *target,
1193 				struct held_lock *check_src,
1194 				struct held_lock *check_tgt)
1195 {
1196 	struct task_struct *curr = current;
1197 	struct lock_list *parent;
1198 	struct lock_list *first_parent;
1199 	int depth;
1200 
1201 	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1202 		return 0;
1203 
1204 	if (!save_trace(&this->trace))
1205 		return 0;
1206 
1207 	depth = get_lock_depth(target);
1208 
1209 	print_circular_bug_header(target, depth, check_src, check_tgt);
1210 
1211 	parent = get_lock_parent(target);
1212 	first_parent = parent;
1213 
1214 	while (parent) {
1215 		print_circular_bug_entry(parent, --depth);
1216 		parent = get_lock_parent(parent);
1217 	}
1218 
1219 	printk("\nother info that might help us debug this:\n\n");
1220 	print_circular_lock_scenario(check_src, check_tgt,
1221 				     first_parent);
1222 
1223 	lockdep_print_held_locks(curr);
1224 
1225 	printk("\nstack backtrace:\n");
1226 	dump_stack();
1227 
1228 	return 0;
1229 }
1230 
print_bfs_bug(int ret)1231 static noinline int print_bfs_bug(int ret)
1232 {
1233 	if (!debug_locks_off_graph_unlock())
1234 		return 0;
1235 
1236 	/*
1237 	 * Breadth-first-search failed, graph got corrupted?
1238 	 */
1239 	WARN(1, "lockdep bfs error:%d\n", ret);
1240 
1241 	return 0;
1242 }
1243 
noop_count(struct lock_list * entry,void * data)1244 static int noop_count(struct lock_list *entry, void *data)
1245 {
1246 	(*(unsigned long *)data)++;
1247 	return 0;
1248 }
1249 
__lockdep_count_forward_deps(struct lock_list * this)1250 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
1251 {
1252 	unsigned long  count = 0;
1253 	struct lock_list *uninitialized_var(target_entry);
1254 
1255 	__bfs_forwards(this, (void *)&count, noop_count, &target_entry);
1256 
1257 	return count;
1258 }
lockdep_count_forward_deps(struct lock_class * class)1259 unsigned long lockdep_count_forward_deps(struct lock_class *class)
1260 {
1261 	unsigned long ret, flags;
1262 	struct lock_list this;
1263 
1264 	this.parent = NULL;
1265 	this.class = class;
1266 
1267 	raw_local_irq_save(flags);
1268 	current->lockdep_recursion = 1;
1269 	arch_spin_lock(&lockdep_lock);
1270 	ret = __lockdep_count_forward_deps(&this);
1271 	arch_spin_unlock(&lockdep_lock);
1272 	current->lockdep_recursion = 0;
1273 	raw_local_irq_restore(flags);
1274 
1275 	return ret;
1276 }
1277 
__lockdep_count_backward_deps(struct lock_list * this)1278 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
1279 {
1280 	unsigned long  count = 0;
1281 	struct lock_list *uninitialized_var(target_entry);
1282 
1283 	__bfs_backwards(this, (void *)&count, noop_count, &target_entry);
1284 
1285 	return count;
1286 }
1287 
lockdep_count_backward_deps(struct lock_class * class)1288 unsigned long lockdep_count_backward_deps(struct lock_class *class)
1289 {
1290 	unsigned long ret, flags;
1291 	struct lock_list this;
1292 
1293 	this.parent = NULL;
1294 	this.class = class;
1295 
1296 	raw_local_irq_save(flags);
1297 	current->lockdep_recursion = 1;
1298 	arch_spin_lock(&lockdep_lock);
1299 	ret = __lockdep_count_backward_deps(&this);
1300 	arch_spin_unlock(&lockdep_lock);
1301 	current->lockdep_recursion = 0;
1302 	raw_local_irq_restore(flags);
1303 
1304 	return ret;
1305 }
1306 
1307 /*
1308  * Prove that the dependency graph starting at <entry> can not
1309  * lead to <target>. Print an error and return 0 if it does.
1310  */
1311 static noinline int
check_noncircular(struct lock_list * root,struct lock_class * target,struct lock_list ** target_entry)1312 check_noncircular(struct lock_list *root, struct lock_class *target,
1313 		struct lock_list **target_entry)
1314 {
1315 	int result;
1316 
1317 	debug_atomic_inc(nr_cyclic_checks);
1318 
1319 	result = __bfs_forwards(root, target, class_equal, target_entry);
1320 
1321 	return result;
1322 }
1323 
1324 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
1325 /*
1326  * Forwards and backwards subgraph searching, for the purposes of
1327  * proving that two subgraphs can be connected by a new dependency
1328  * without creating any illegal irq-safe -> irq-unsafe lock dependency.
1329  */
1330 
usage_match(struct lock_list * entry,void * bit)1331 static inline int usage_match(struct lock_list *entry, void *bit)
1332 {
1333 	return entry->class->usage_mask & (1 << (enum lock_usage_bit)bit);
1334 }
1335 
1336 
1337 
1338 /*
1339  * Find a node in the forwards-direction dependency sub-graph starting
1340  * at @root->class that matches @bit.
1341  *
1342  * Return 0 if such a node exists in the subgraph, and put that node
1343  * into *@target_entry.
1344  *
1345  * Return 1 otherwise and keep *@target_entry unchanged.
1346  * Return <0 on error.
1347  */
1348 static int
find_usage_forwards(struct lock_list * root,enum lock_usage_bit bit,struct lock_list ** target_entry)1349 find_usage_forwards(struct lock_list *root, enum lock_usage_bit bit,
1350 			struct lock_list **target_entry)
1351 {
1352 	int result;
1353 
1354 	debug_atomic_inc(nr_find_usage_forwards_checks);
1355 
1356 	result = __bfs_forwards(root, (void *)bit, usage_match, target_entry);
1357 
1358 	return result;
1359 }
1360 
1361 /*
1362  * Find a node in the backwards-direction dependency sub-graph starting
1363  * at @root->class that matches @bit.
1364  *
1365  * Return 0 if such a node exists in the subgraph, and put that node
1366  * into *@target_entry.
1367  *
1368  * Return 1 otherwise and keep *@target_entry unchanged.
1369  * Return <0 on error.
1370  */
1371 static int
find_usage_backwards(struct lock_list * root,enum lock_usage_bit bit,struct lock_list ** target_entry)1372 find_usage_backwards(struct lock_list *root, enum lock_usage_bit bit,
1373 			struct lock_list **target_entry)
1374 {
1375 	int result;
1376 
1377 	debug_atomic_inc(nr_find_usage_backwards_checks);
1378 
1379 	result = __bfs_backwards(root, (void *)bit, usage_match, target_entry);
1380 
1381 	return result;
1382 }
1383 
print_lock_class_header(struct lock_class * class,int depth)1384 static void print_lock_class_header(struct lock_class *class, int depth)
1385 {
1386 	int bit;
1387 
1388 	printk("%*s->", depth, "");
1389 	print_lock_name(class);
1390 	printk(" ops: %lu", class->ops);
1391 	printk(" {\n");
1392 
1393 	for (bit = 0; bit < LOCK_USAGE_STATES; bit++) {
1394 		if (class->usage_mask & (1 << bit)) {
1395 			int len = depth;
1396 
1397 			len += printk("%*s   %s", depth, "", usage_str[bit]);
1398 			len += printk(" at:\n");
1399 			print_stack_trace(class->usage_traces + bit, len);
1400 		}
1401 	}
1402 	printk("%*s }\n", depth, "");
1403 
1404 	printk("%*s ... key      at: ",depth,"");
1405 	print_ip_sym((unsigned long)class->key);
1406 }
1407 
1408 /*
1409  * printk the shortest lock dependencies from @start to @end in reverse order:
1410  */
1411 static void __used
print_shortest_lock_dependencies(struct lock_list * leaf,struct lock_list * root)1412 print_shortest_lock_dependencies(struct lock_list *leaf,
1413 				struct lock_list *root)
1414 {
1415 	struct lock_list *entry = leaf;
1416 	int depth;
1417 
1418 	/*compute depth from generated tree by BFS*/
1419 	depth = get_lock_depth(leaf);
1420 
1421 	do {
1422 		print_lock_class_header(entry->class, depth);
1423 		printk("%*s ... acquired at:\n", depth, "");
1424 		print_stack_trace(&entry->trace, 2);
1425 		printk("\n");
1426 
1427 		if (depth == 0 && (entry != root)) {
1428 			printk("lockdep:%s bad path found in chain graph\n", __func__);
1429 			break;
1430 		}
1431 
1432 		entry = get_lock_parent(entry);
1433 		depth--;
1434 	} while (entry && (depth >= 0));
1435 
1436 	return;
1437 }
1438 
1439 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)1440 print_irq_lock_scenario(struct lock_list *safe_entry,
1441 			struct lock_list *unsafe_entry,
1442 			struct lock_class *prev_class,
1443 			struct lock_class *next_class)
1444 {
1445 	struct lock_class *safe_class = safe_entry->class;
1446 	struct lock_class *unsafe_class = unsafe_entry->class;
1447 	struct lock_class *middle_class = prev_class;
1448 
1449 	if (middle_class == safe_class)
1450 		middle_class = next_class;
1451 
1452 	/*
1453 	 * A direct locking problem where unsafe_class lock is taken
1454 	 * directly by safe_class lock, then all we need to show
1455 	 * is the deadlock scenario, as it is obvious that the
1456 	 * unsafe lock is taken under the safe lock.
1457 	 *
1458 	 * But if there is a chain instead, where the safe lock takes
1459 	 * an intermediate lock (middle_class) where this lock is
1460 	 * not the same as the safe lock, then the lock chain is
1461 	 * used to describe the problem. Otherwise we would need
1462 	 * to show a different CPU case for each link in the chain
1463 	 * from the safe_class lock to the unsafe_class lock.
1464 	 */
1465 	if (middle_class != unsafe_class) {
1466 		printk("Chain exists of:\n  ");
1467 		__print_lock_name(safe_class);
1468 		printk(" --> ");
1469 		__print_lock_name(middle_class);
1470 		printk(" --> ");
1471 		__print_lock_name(unsafe_class);
1472 		printk("\n\n");
1473 	}
1474 
1475 	printk(" Possible interrupt unsafe locking scenario:\n\n");
1476 	printk("       CPU0                    CPU1\n");
1477 	printk("       ----                    ----\n");
1478 	printk("  lock(");
1479 	__print_lock_name(unsafe_class);
1480 	printk(");\n");
1481 	printk("                               local_irq_disable();\n");
1482 	printk("                               lock(");
1483 	__print_lock_name(safe_class);
1484 	printk(");\n");
1485 	printk("                               lock(");
1486 	__print_lock_name(middle_class);
1487 	printk(");\n");
1488 	printk("  <Interrupt>\n");
1489 	printk("    lock(");
1490 	__print_lock_name(safe_class);
1491 	printk(");\n");
1492 	printk("\n *** DEADLOCK ***\n\n");
1493 }
1494 
1495 static int
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)1496 print_bad_irq_dependency(struct task_struct *curr,
1497 			 struct lock_list *prev_root,
1498 			 struct lock_list *next_root,
1499 			 struct lock_list *backwards_entry,
1500 			 struct lock_list *forwards_entry,
1501 			 struct held_lock *prev,
1502 			 struct held_lock *next,
1503 			 enum lock_usage_bit bit1,
1504 			 enum lock_usage_bit bit2,
1505 			 const char *irqclass)
1506 {
1507 	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1508 		return 0;
1509 
1510 	printk("\n");
1511 	printk("======================================================\n");
1512 	printk("[ INFO: %s-safe -> %s-unsafe lock order detected ]\n",
1513 		irqclass, irqclass);
1514 	print_kernel_ident();
1515 	printk("------------------------------------------------------\n");
1516 	printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
1517 		curr->comm, task_pid_nr(curr),
1518 		curr->hardirq_context, hardirq_count() >> HARDIRQ_SHIFT,
1519 		curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
1520 		curr->hardirqs_enabled,
1521 		curr->softirqs_enabled);
1522 	print_lock(next);
1523 
1524 	printk("\nand this task is already holding:\n");
1525 	print_lock(prev);
1526 	printk("which would create a new lock dependency:\n");
1527 	print_lock_name(hlock_class(prev));
1528 	printk(" ->");
1529 	print_lock_name(hlock_class(next));
1530 	printk("\n");
1531 
1532 	printk("\nbut this new dependency connects a %s-irq-safe lock:\n",
1533 		irqclass);
1534 	print_lock_name(backwards_entry->class);
1535 	printk("\n... which became %s-irq-safe at:\n", irqclass);
1536 
1537 	print_stack_trace(backwards_entry->class->usage_traces + bit1, 1);
1538 
1539 	printk("\nto a %s-irq-unsafe lock:\n", irqclass);
1540 	print_lock_name(forwards_entry->class);
1541 	printk("\n... which became %s-irq-unsafe at:\n", irqclass);
1542 	printk("...");
1543 
1544 	print_stack_trace(forwards_entry->class->usage_traces + bit2, 1);
1545 
1546 	printk("\nother info that might help us debug this:\n\n");
1547 	print_irq_lock_scenario(backwards_entry, forwards_entry,
1548 				hlock_class(prev), hlock_class(next));
1549 
1550 	lockdep_print_held_locks(curr);
1551 
1552 	printk("\nthe dependencies between %s-irq-safe lock", irqclass);
1553 	printk(" and the holding lock:\n");
1554 	if (!save_trace(&prev_root->trace))
1555 		return 0;
1556 	print_shortest_lock_dependencies(backwards_entry, prev_root);
1557 
1558 	printk("\nthe dependencies between the lock to be acquired");
1559 	printk(" and %s-irq-unsafe lock:\n", irqclass);
1560 	if (!save_trace(&next_root->trace))
1561 		return 0;
1562 	print_shortest_lock_dependencies(forwards_entry, next_root);
1563 
1564 	printk("\nstack backtrace:\n");
1565 	dump_stack();
1566 
1567 	return 0;
1568 }
1569 
1570 static int
check_usage(struct task_struct * curr,struct held_lock * prev,struct held_lock * next,enum lock_usage_bit bit_backwards,enum lock_usage_bit bit_forwards,const char * irqclass)1571 check_usage(struct task_struct *curr, struct held_lock *prev,
1572 	    struct held_lock *next, enum lock_usage_bit bit_backwards,
1573 	    enum lock_usage_bit bit_forwards, const char *irqclass)
1574 {
1575 	int ret;
1576 	struct lock_list this, that;
1577 	struct lock_list *uninitialized_var(target_entry);
1578 	struct lock_list *uninitialized_var(target_entry1);
1579 
1580 	this.parent = NULL;
1581 
1582 	this.class = hlock_class(prev);
1583 	ret = find_usage_backwards(&this, bit_backwards, &target_entry);
1584 	if (ret < 0)
1585 		return print_bfs_bug(ret);
1586 	if (ret == 1)
1587 		return ret;
1588 
1589 	that.parent = NULL;
1590 	that.class = hlock_class(next);
1591 	ret = find_usage_forwards(&that, bit_forwards, &target_entry1);
1592 	if (ret < 0)
1593 		return print_bfs_bug(ret);
1594 	if (ret == 1)
1595 		return ret;
1596 
1597 	return print_bad_irq_dependency(curr, &this, &that,
1598 			target_entry, target_entry1,
1599 			prev, next,
1600 			bit_backwards, bit_forwards, irqclass);
1601 }
1602 
1603 static const char *state_names[] = {
1604 #define LOCKDEP_STATE(__STATE) \
1605 	__stringify(__STATE),
1606 #include "lockdep_states.h"
1607 #undef LOCKDEP_STATE
1608 };
1609 
1610 static const char *state_rnames[] = {
1611 #define LOCKDEP_STATE(__STATE) \
1612 	__stringify(__STATE)"-READ",
1613 #include "lockdep_states.h"
1614 #undef LOCKDEP_STATE
1615 };
1616 
state_name(enum lock_usage_bit bit)1617 static inline const char *state_name(enum lock_usage_bit bit)
1618 {
1619 	return (bit & 1) ? state_rnames[bit >> 2] : state_names[bit >> 2];
1620 }
1621 
exclusive_bit(int new_bit)1622 static int exclusive_bit(int new_bit)
1623 {
1624 	/*
1625 	 * USED_IN
1626 	 * USED_IN_READ
1627 	 * ENABLED
1628 	 * ENABLED_READ
1629 	 *
1630 	 * bit 0 - write/read
1631 	 * bit 1 - used_in/enabled
1632 	 * bit 2+  state
1633 	 */
1634 
1635 	int state = new_bit & ~3;
1636 	int dir = new_bit & 2;
1637 
1638 	/*
1639 	 * keep state, bit flip the direction and strip read.
1640 	 */
1641 	return state | (dir ^ 2);
1642 }
1643 
check_irq_usage(struct task_struct * curr,struct held_lock * prev,struct held_lock * next,enum lock_usage_bit bit)1644 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
1645 			   struct held_lock *next, enum lock_usage_bit bit)
1646 {
1647 	/*
1648 	 * Prove that the new dependency does not connect a hardirq-safe
1649 	 * lock with a hardirq-unsafe lock - to achieve this we search
1650 	 * the backwards-subgraph starting at <prev>, and the
1651 	 * forwards-subgraph starting at <next>:
1652 	 */
1653 	if (!check_usage(curr, prev, next, bit,
1654 			   exclusive_bit(bit), state_name(bit)))
1655 		return 0;
1656 
1657 	bit++; /* _READ */
1658 
1659 	/*
1660 	 * Prove that the new dependency does not connect a hardirq-safe-read
1661 	 * lock with a hardirq-unsafe lock - to achieve this we search
1662 	 * the backwards-subgraph starting at <prev>, and the
1663 	 * forwards-subgraph starting at <next>:
1664 	 */
1665 	if (!check_usage(curr, prev, next, bit,
1666 			   exclusive_bit(bit), state_name(bit)))
1667 		return 0;
1668 
1669 	return 1;
1670 }
1671 
1672 static int
check_prev_add_irq(struct task_struct * curr,struct held_lock * prev,struct held_lock * next)1673 check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
1674 		struct held_lock *next)
1675 {
1676 #define LOCKDEP_STATE(__STATE)						\
1677 	if (!check_irq_usage(curr, prev, next, LOCK_USED_IN_##__STATE))	\
1678 		return 0;
1679 #include "lockdep_states.h"
1680 #undef LOCKDEP_STATE
1681 
1682 	return 1;
1683 }
1684 
inc_chains(void)1685 static void inc_chains(void)
1686 {
1687 	if (current->hardirq_context)
1688 		nr_hardirq_chains++;
1689 	else {
1690 		if (current->softirq_context)
1691 			nr_softirq_chains++;
1692 		else
1693 			nr_process_chains++;
1694 	}
1695 }
1696 
1697 #else
1698 
1699 static inline int
check_prev_add_irq(struct task_struct * curr,struct held_lock * prev,struct held_lock * next)1700 check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
1701 		struct held_lock *next)
1702 {
1703 	return 1;
1704 }
1705 
inc_chains(void)1706 static inline void inc_chains(void)
1707 {
1708 	nr_process_chains++;
1709 }
1710 
1711 #endif
1712 
1713 static void
print_deadlock_scenario(struct held_lock * nxt,struct held_lock * prv)1714 print_deadlock_scenario(struct held_lock *nxt,
1715 			     struct held_lock *prv)
1716 {
1717 	struct lock_class *next = hlock_class(nxt);
1718 	struct lock_class *prev = hlock_class(prv);
1719 
1720 	printk(" Possible unsafe locking scenario:\n\n");
1721 	printk("       CPU0\n");
1722 	printk("       ----\n");
1723 	printk("  lock(");
1724 	__print_lock_name(prev);
1725 	printk(");\n");
1726 	printk("  lock(");
1727 	__print_lock_name(next);
1728 	printk(");\n");
1729 	printk("\n *** DEADLOCK ***\n\n");
1730 	printk(" May be due to missing lock nesting notation\n\n");
1731 }
1732 
1733 static int
print_deadlock_bug(struct task_struct * curr,struct held_lock * prev,struct held_lock * next)1734 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
1735 		   struct held_lock *next)
1736 {
1737 	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1738 		return 0;
1739 
1740 	printk("\n");
1741 	printk("=============================================\n");
1742 	printk("[ INFO: possible recursive locking detected ]\n");
1743 	print_kernel_ident();
1744 	printk("---------------------------------------------\n");
1745 	printk("%s/%d is trying to acquire lock:\n",
1746 		curr->comm, task_pid_nr(curr));
1747 	print_lock(next);
1748 	printk("\nbut task is already holding lock:\n");
1749 	print_lock(prev);
1750 
1751 	printk("\nother info that might help us debug this:\n");
1752 	print_deadlock_scenario(next, prev);
1753 	lockdep_print_held_locks(curr);
1754 
1755 	printk("\nstack backtrace:\n");
1756 	dump_stack();
1757 
1758 	return 0;
1759 }
1760 
1761 /*
1762  * Check whether we are holding such a class already.
1763  *
1764  * (Note that this has to be done separately, because the graph cannot
1765  * detect such classes of deadlocks.)
1766  *
1767  * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
1768  */
1769 static int
check_deadlock(struct task_struct * curr,struct held_lock * next,struct lockdep_map * next_instance,int read)1770 check_deadlock(struct task_struct *curr, struct held_lock *next,
1771 	       struct lockdep_map *next_instance, int read)
1772 {
1773 	struct held_lock *prev;
1774 	struct held_lock *nest = NULL;
1775 	int i;
1776 
1777 	for (i = 0; i < curr->lockdep_depth; i++) {
1778 		prev = curr->held_locks + i;
1779 
1780 		if (prev->instance == next->nest_lock)
1781 			nest = prev;
1782 
1783 		if (hlock_class(prev) != hlock_class(next))
1784 			continue;
1785 
1786 		/*
1787 		 * Allow read-after-read recursion of the same
1788 		 * lock class (i.e. read_lock(lock)+read_lock(lock)):
1789 		 */
1790 		if ((read == 2) && prev->read)
1791 			return 2;
1792 
1793 		/*
1794 		 * We're holding the nest_lock, which serializes this lock's
1795 		 * nesting behaviour.
1796 		 */
1797 		if (nest)
1798 			return 2;
1799 
1800 		return print_deadlock_bug(curr, prev, next);
1801 	}
1802 	return 1;
1803 }
1804 
1805 /*
1806  * There was a chain-cache miss, and we are about to add a new dependency
1807  * to a previous lock. We recursively validate the following rules:
1808  *
1809  *  - would the adding of the <prev> -> <next> dependency create a
1810  *    circular dependency in the graph? [== circular deadlock]
1811  *
1812  *  - does the new prev->next dependency connect any hardirq-safe lock
1813  *    (in the full backwards-subgraph starting at <prev>) with any
1814  *    hardirq-unsafe lock (in the full forwards-subgraph starting at
1815  *    <next>)? [== illegal lock inversion with hardirq contexts]
1816  *
1817  *  - does the new prev->next dependency connect any softirq-safe lock
1818  *    (in the full backwards-subgraph starting at <prev>) with any
1819  *    softirq-unsafe lock (in the full forwards-subgraph starting at
1820  *    <next>)? [== illegal lock inversion with softirq contexts]
1821  *
1822  * any of these scenarios could lead to a deadlock.
1823  *
1824  * Then if all the validations pass, we add the forwards and backwards
1825  * dependency.
1826  */
1827 static int
check_prev_add(struct task_struct * curr,struct held_lock * prev,struct held_lock * next,int distance,int trylock_loop)1828 check_prev_add(struct task_struct *curr, struct held_lock *prev,
1829 	       struct held_lock *next, int distance, int trylock_loop)
1830 {
1831 	struct lock_list *entry;
1832 	int ret;
1833 	struct lock_list this;
1834 	struct lock_list *uninitialized_var(target_entry);
1835 	/*
1836 	 * Static variable, serialized by the graph_lock().
1837 	 *
1838 	 * We use this static variable to save the stack trace in case
1839 	 * we call into this function multiple times due to encountering
1840 	 * trylocks in the held lock stack.
1841 	 */
1842 	static struct stack_trace trace;
1843 
1844 	/*
1845 	 * Prove that the new <prev> -> <next> dependency would not
1846 	 * create a circular dependency in the graph. (We do this by
1847 	 * forward-recursing into the graph starting at <next>, and
1848 	 * checking whether we can reach <prev>.)
1849 	 *
1850 	 * We are using global variables to control the recursion, to
1851 	 * keep the stackframe size of the recursive functions low:
1852 	 */
1853 	this.class = hlock_class(next);
1854 	this.parent = NULL;
1855 	ret = check_noncircular(&this, hlock_class(prev), &target_entry);
1856 	if (unlikely(!ret))
1857 		return print_circular_bug(&this, target_entry, next, prev);
1858 	else if (unlikely(ret < 0))
1859 		return print_bfs_bug(ret);
1860 
1861 	if (!check_prev_add_irq(curr, prev, next))
1862 		return 0;
1863 
1864 	/*
1865 	 * For recursive read-locks we do all the dependency checks,
1866 	 * but we dont store read-triggered dependencies (only
1867 	 * write-triggered dependencies). This ensures that only the
1868 	 * write-side dependencies matter, and that if for example a
1869 	 * write-lock never takes any other locks, then the reads are
1870 	 * equivalent to a NOP.
1871 	 */
1872 	if (next->read == 2 || prev->read == 2)
1873 		return 1;
1874 	/*
1875 	 * Is the <prev> -> <next> dependency already present?
1876 	 *
1877 	 * (this may occur even though this is a new chain: consider
1878 	 *  e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
1879 	 *  chains - the second one will be new, but L1 already has
1880 	 *  L2 added to its dependency list, due to the first chain.)
1881 	 */
1882 	list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
1883 		if (entry->class == hlock_class(next)) {
1884 			if (distance == 1)
1885 				entry->distance = 1;
1886 			return 2;
1887 		}
1888 	}
1889 
1890 	if (!trylock_loop && !save_trace(&trace))
1891 		return 0;
1892 
1893 	/*
1894 	 * Ok, all validations passed, add the new lock
1895 	 * to the previous lock's dependency list:
1896 	 */
1897 	ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
1898 			       &hlock_class(prev)->locks_after,
1899 			       next->acquire_ip, distance, &trace);
1900 
1901 	if (!ret)
1902 		return 0;
1903 
1904 	ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
1905 			       &hlock_class(next)->locks_before,
1906 			       next->acquire_ip, distance, &trace);
1907 	if (!ret)
1908 		return 0;
1909 
1910 	/*
1911 	 * Debugging printouts:
1912 	 */
1913 	if (verbose(hlock_class(prev)) || verbose(hlock_class(next))) {
1914 		graph_unlock();
1915 		printk("\n new dependency: ");
1916 		print_lock_name(hlock_class(prev));
1917 		printk(" => ");
1918 		print_lock_name(hlock_class(next));
1919 		printk("\n");
1920 		dump_stack();
1921 		return graph_lock();
1922 	}
1923 	return 1;
1924 }
1925 
1926 /*
1927  * Add the dependency to all directly-previous locks that are 'relevant'.
1928  * The ones that are relevant are (in increasing distance from curr):
1929  * all consecutive trylock entries and the final non-trylock entry - or
1930  * the end of this context's lock-chain - whichever comes first.
1931  */
1932 static int
check_prevs_add(struct task_struct * curr,struct held_lock * next)1933 check_prevs_add(struct task_struct *curr, struct held_lock *next)
1934 {
1935 	int depth = curr->lockdep_depth;
1936 	int trylock_loop = 0;
1937 	struct held_lock *hlock;
1938 
1939 	/*
1940 	 * Debugging checks.
1941 	 *
1942 	 * Depth must not be zero for a non-head lock:
1943 	 */
1944 	if (!depth)
1945 		goto out_bug;
1946 	/*
1947 	 * At least two relevant locks must exist for this
1948 	 * to be a head:
1949 	 */
1950 	if (curr->held_locks[depth].irq_context !=
1951 			curr->held_locks[depth-1].irq_context)
1952 		goto out_bug;
1953 
1954 	for (;;) {
1955 		int distance = curr->lockdep_depth - depth + 1;
1956 		hlock = curr->held_locks + depth - 1;
1957 		/*
1958 		 * Only non-recursive-read entries get new dependencies
1959 		 * added:
1960 		 */
1961 		if (hlock->read != 2 && hlock->check) {
1962 			if (!check_prev_add(curr, hlock, next,
1963 						distance, trylock_loop))
1964 				return 0;
1965 			/*
1966 			 * Stop after the first non-trylock entry,
1967 			 * as non-trylock entries have added their
1968 			 * own direct dependencies already, so this
1969 			 * lock is connected to them indirectly:
1970 			 */
1971 			if (!hlock->trylock)
1972 				break;
1973 		}
1974 		depth--;
1975 		/*
1976 		 * End of lock-stack?
1977 		 */
1978 		if (!depth)
1979 			break;
1980 		/*
1981 		 * Stop the search if we cross into another context:
1982 		 */
1983 		if (curr->held_locks[depth].irq_context !=
1984 				curr->held_locks[depth-1].irq_context)
1985 			break;
1986 		trylock_loop = 1;
1987 	}
1988 	return 1;
1989 out_bug:
1990 	if (!debug_locks_off_graph_unlock())
1991 		return 0;
1992 
1993 	/*
1994 	 * Clearly we all shouldn't be here, but since we made it we
1995 	 * can reliable say we messed up our state. See the above two
1996 	 * gotos for reasons why we could possibly end up here.
1997 	 */
1998 	WARN_ON(1);
1999 
2000 	return 0;
2001 }
2002 
2003 unsigned long nr_lock_chains;
2004 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
2005 int nr_chain_hlocks;
2006 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
2007 
lock_chain_get_class(struct lock_chain * chain,int i)2008 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
2009 {
2010 	return lock_classes + chain_hlocks[chain->base + i];
2011 }
2012 
2013 /*
2014  * Look up a dependency chain. If the key is not present yet then
2015  * add it and return 1 - in this case the new dependency chain is
2016  * validated. If the key is already hashed, return 0.
2017  * (On return with 1 graph_lock is held.)
2018  */
lookup_chain_cache(struct task_struct * curr,struct held_lock * hlock,u64 chain_key)2019 static inline int lookup_chain_cache(struct task_struct *curr,
2020 				     struct held_lock *hlock,
2021 				     u64 chain_key)
2022 {
2023 	struct lock_class *class = hlock_class(hlock);
2024 	struct list_head *hash_head = chainhashentry(chain_key);
2025 	struct lock_chain *chain;
2026 	struct held_lock *hlock_curr;
2027 	int i, j;
2028 
2029 	/*
2030 	 * We might need to take the graph lock, ensure we've got IRQs
2031 	 * disabled to make this an IRQ-safe lock.. for recursion reasons
2032 	 * lockdep won't complain about its own locking errors.
2033 	 */
2034 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2035 		return 0;
2036 	/*
2037 	 * We can walk it lock-free, because entries only get added
2038 	 * to the hash:
2039 	 */
2040 	list_for_each_entry_rcu(chain, hash_head, entry) {
2041 		if (chain->chain_key == chain_key) {
2042 cache_hit:
2043 			debug_atomic_inc(chain_lookup_hits);
2044 			if (very_verbose(class))
2045 				printk("\nhash chain already cached, key: "
2046 					"%016Lx tail class: [%p] %s\n",
2047 					(unsigned long long)chain_key,
2048 					class->key, class->name);
2049 			return 0;
2050 		}
2051 	}
2052 	if (very_verbose(class))
2053 		printk("\nnew hash chain, key: %016Lx tail class: [%p] %s\n",
2054 			(unsigned long long)chain_key, class->key, class->name);
2055 	/*
2056 	 * Allocate a new chain entry from the static array, and add
2057 	 * it to the hash:
2058 	 */
2059 	if (!graph_lock())
2060 		return 0;
2061 	/*
2062 	 * We have to walk the chain again locked - to avoid duplicates:
2063 	 */
2064 	list_for_each_entry(chain, hash_head, entry) {
2065 		if (chain->chain_key == chain_key) {
2066 			graph_unlock();
2067 			goto cache_hit;
2068 		}
2069 	}
2070 	if (unlikely(nr_lock_chains >= MAX_LOCKDEP_CHAINS)) {
2071 		if (!debug_locks_off_graph_unlock())
2072 			return 0;
2073 
2074 		print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
2075 		dump_stack();
2076 		return 0;
2077 	}
2078 	chain = lock_chains + nr_lock_chains++;
2079 	chain->chain_key = chain_key;
2080 	chain->irq_context = hlock->irq_context;
2081 	/* Find the first held_lock of current chain */
2082 	for (i = curr->lockdep_depth - 1; i >= 0; i--) {
2083 		hlock_curr = curr->held_locks + i;
2084 		if (hlock_curr->irq_context != hlock->irq_context)
2085 			break;
2086 	}
2087 	i++;
2088 	chain->depth = curr->lockdep_depth + 1 - i;
2089 	if (likely(nr_chain_hlocks + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS)) {
2090 		chain->base = nr_chain_hlocks;
2091 		nr_chain_hlocks += chain->depth;
2092 		for (j = 0; j < chain->depth - 1; j++, i++) {
2093 			int lock_id = curr->held_locks[i].class_idx - 1;
2094 			chain_hlocks[chain->base + j] = lock_id;
2095 		}
2096 		chain_hlocks[chain->base + j] = class - lock_classes;
2097 	}
2098 	list_add_tail_rcu(&chain->entry, hash_head);
2099 	debug_atomic_inc(chain_lookup_misses);
2100 	inc_chains();
2101 
2102 	return 1;
2103 }
2104 
validate_chain(struct task_struct * curr,struct lockdep_map * lock,struct held_lock * hlock,int chain_head,u64 chain_key)2105 static int validate_chain(struct task_struct *curr, struct lockdep_map *lock,
2106 		struct held_lock *hlock, int chain_head, u64 chain_key)
2107 {
2108 	/*
2109 	 * Trylock needs to maintain the stack of held locks, but it
2110 	 * does not add new dependencies, because trylock can be done
2111 	 * in any order.
2112 	 *
2113 	 * We look up the chain_key and do the O(N^2) check and update of
2114 	 * the dependencies only if this is a new dependency chain.
2115 	 * (If lookup_chain_cache() returns with 1 it acquires
2116 	 * graph_lock for us)
2117 	 */
2118 	if (!hlock->trylock && hlock->check &&
2119 	    lookup_chain_cache(curr, hlock, chain_key)) {
2120 		/*
2121 		 * Check whether last held lock:
2122 		 *
2123 		 * - is irq-safe, if this lock is irq-unsafe
2124 		 * - is softirq-safe, if this lock is hardirq-unsafe
2125 		 *
2126 		 * And check whether the new lock's dependency graph
2127 		 * could lead back to the previous lock.
2128 		 *
2129 		 * any of these scenarios could lead to a deadlock. If
2130 		 * All validations
2131 		 */
2132 		int ret = check_deadlock(curr, hlock, lock, hlock->read);
2133 
2134 		if (!ret)
2135 			return 0;
2136 		/*
2137 		 * Mark recursive read, as we jump over it when
2138 		 * building dependencies (just like we jump over
2139 		 * trylock entries):
2140 		 */
2141 		if (ret == 2)
2142 			hlock->read = 2;
2143 		/*
2144 		 * Add dependency only if this lock is not the head
2145 		 * of the chain, and if it's not a secondary read-lock:
2146 		 */
2147 		if (!chain_head && ret != 2)
2148 			if (!check_prevs_add(curr, hlock))
2149 				return 0;
2150 		graph_unlock();
2151 	} else
2152 		/* after lookup_chain_cache(): */
2153 		if (unlikely(!debug_locks))
2154 			return 0;
2155 
2156 	return 1;
2157 }
2158 #else
validate_chain(struct task_struct * curr,struct lockdep_map * lock,struct held_lock * hlock,int chain_head,u64 chain_key)2159 static inline int validate_chain(struct task_struct *curr,
2160 	       	struct lockdep_map *lock, struct held_lock *hlock,
2161 		int chain_head, u64 chain_key)
2162 {
2163 	return 1;
2164 }
2165 #endif
2166 
2167 /*
2168  * We are building curr_chain_key incrementally, so double-check
2169  * it from scratch, to make sure that it's done correctly:
2170  */
check_chain_key(struct task_struct * curr)2171 static void check_chain_key(struct task_struct *curr)
2172 {
2173 #ifdef CONFIG_DEBUG_LOCKDEP
2174 	struct held_lock *hlock, *prev_hlock = NULL;
2175 	unsigned int i, id;
2176 	u64 chain_key = 0;
2177 
2178 	for (i = 0; i < curr->lockdep_depth; i++) {
2179 		hlock = curr->held_locks + i;
2180 		if (chain_key != hlock->prev_chain_key) {
2181 			debug_locks_off();
2182 			/*
2183 			 * We got mighty confused, our chain keys don't match
2184 			 * with what we expect, someone trample on our task state?
2185 			 */
2186 			WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
2187 				curr->lockdep_depth, i,
2188 				(unsigned long long)chain_key,
2189 				(unsigned long long)hlock->prev_chain_key);
2190 			return;
2191 		}
2192 		id = hlock->class_idx - 1;
2193 		/*
2194 		 * Whoops ran out of static storage again?
2195 		 */
2196 		if (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
2197 			return;
2198 
2199 		if (prev_hlock && (prev_hlock->irq_context !=
2200 							hlock->irq_context))
2201 			chain_key = 0;
2202 		chain_key = iterate_chain_key(chain_key, id);
2203 		prev_hlock = hlock;
2204 	}
2205 	if (chain_key != curr->curr_chain_key) {
2206 		debug_locks_off();
2207 		/*
2208 		 * More smoking hash instead of calculating it, damn see these
2209 		 * numbers float.. I bet that a pink elephant stepped on my memory.
2210 		 */
2211 		WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
2212 			curr->lockdep_depth, i,
2213 			(unsigned long long)chain_key,
2214 			(unsigned long long)curr->curr_chain_key);
2215 	}
2216 #endif
2217 }
2218 
2219 static void
print_usage_bug_scenario(struct held_lock * lock)2220 print_usage_bug_scenario(struct held_lock *lock)
2221 {
2222 	struct lock_class *class = hlock_class(lock);
2223 
2224 	printk(" Possible unsafe locking scenario:\n\n");
2225 	printk("       CPU0\n");
2226 	printk("       ----\n");
2227 	printk("  lock(");
2228 	__print_lock_name(class);
2229 	printk(");\n");
2230 	printk("  <Interrupt>\n");
2231 	printk("    lock(");
2232 	__print_lock_name(class);
2233 	printk(");\n");
2234 	printk("\n *** DEADLOCK ***\n\n");
2235 }
2236 
2237 static int
print_usage_bug(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit prev_bit,enum lock_usage_bit new_bit)2238 print_usage_bug(struct task_struct *curr, struct held_lock *this,
2239 		enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
2240 {
2241 	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2242 		return 0;
2243 
2244 	printk("\n");
2245 	printk("=================================\n");
2246 	printk("[ INFO: inconsistent lock state ]\n");
2247 	print_kernel_ident();
2248 	printk("---------------------------------\n");
2249 
2250 	printk("inconsistent {%s} -> {%s} usage.\n",
2251 		usage_str[prev_bit], usage_str[new_bit]);
2252 
2253 	printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
2254 		curr->comm, task_pid_nr(curr),
2255 		trace_hardirq_context(curr), hardirq_count() >> HARDIRQ_SHIFT,
2256 		trace_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
2257 		trace_hardirqs_enabled(curr),
2258 		trace_softirqs_enabled(curr));
2259 	print_lock(this);
2260 
2261 	printk("{%s} state was registered at:\n", usage_str[prev_bit]);
2262 	print_stack_trace(hlock_class(this)->usage_traces + prev_bit, 1);
2263 
2264 	print_irqtrace_events(curr);
2265 	printk("\nother info that might help us debug this:\n");
2266 	print_usage_bug_scenario(this);
2267 
2268 	lockdep_print_held_locks(curr);
2269 
2270 	printk("\nstack backtrace:\n");
2271 	dump_stack();
2272 
2273 	return 0;
2274 }
2275 
2276 /*
2277  * Print out an error if an invalid bit is set:
2278  */
2279 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)2280 valid_state(struct task_struct *curr, struct held_lock *this,
2281 	    enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
2282 {
2283 	if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit)))
2284 		return print_usage_bug(curr, this, bad_bit, new_bit);
2285 	return 1;
2286 }
2287 
2288 static int mark_lock(struct task_struct *curr, struct held_lock *this,
2289 		     enum lock_usage_bit new_bit);
2290 
2291 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
2292 
2293 /*
2294  * print irq inversion bug:
2295  */
2296 static int
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)2297 print_irq_inversion_bug(struct task_struct *curr,
2298 			struct lock_list *root, struct lock_list *other,
2299 			struct held_lock *this, int forwards,
2300 			const char *irqclass)
2301 {
2302 	struct lock_list *entry = other;
2303 	struct lock_list *middle = NULL;
2304 	int depth;
2305 
2306 	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2307 		return 0;
2308 
2309 	printk("\n");
2310 	printk("=========================================================\n");
2311 	printk("[ INFO: possible irq lock inversion dependency detected ]\n");
2312 	print_kernel_ident();
2313 	printk("---------------------------------------------------------\n");
2314 	printk("%s/%d just changed the state of lock:\n",
2315 		curr->comm, task_pid_nr(curr));
2316 	print_lock(this);
2317 	if (forwards)
2318 		printk("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
2319 	else
2320 		printk("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
2321 	print_lock_name(other->class);
2322 	printk("\n\nand interrupts could create inverse lock ordering between them.\n\n");
2323 
2324 	printk("\nother info that might help us debug this:\n");
2325 
2326 	/* Find a middle lock (if one exists) */
2327 	depth = get_lock_depth(other);
2328 	do {
2329 		if (depth == 0 && (entry != root)) {
2330 			printk("lockdep:%s bad path found in chain graph\n", __func__);
2331 			break;
2332 		}
2333 		middle = entry;
2334 		entry = get_lock_parent(entry);
2335 		depth--;
2336 	} while (entry && entry != root && (depth >= 0));
2337 	if (forwards)
2338 		print_irq_lock_scenario(root, other,
2339 			middle ? middle->class : root->class, other->class);
2340 	else
2341 		print_irq_lock_scenario(other, root,
2342 			middle ? middle->class : other->class, root->class);
2343 
2344 	lockdep_print_held_locks(curr);
2345 
2346 	printk("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
2347 	if (!save_trace(&root->trace))
2348 		return 0;
2349 	print_shortest_lock_dependencies(other, root);
2350 
2351 	printk("\nstack backtrace:\n");
2352 	dump_stack();
2353 
2354 	return 0;
2355 }
2356 
2357 /*
2358  * Prove that in the forwards-direction subgraph starting at <this>
2359  * there is no lock matching <mask>:
2360  */
2361 static int
check_usage_forwards(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit bit,const char * irqclass)2362 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
2363 		     enum lock_usage_bit bit, const char *irqclass)
2364 {
2365 	int ret;
2366 	struct lock_list root;
2367 	struct lock_list *uninitialized_var(target_entry);
2368 
2369 	root.parent = NULL;
2370 	root.class = hlock_class(this);
2371 	ret = find_usage_forwards(&root, bit, &target_entry);
2372 	if (ret < 0)
2373 		return print_bfs_bug(ret);
2374 	if (ret == 1)
2375 		return ret;
2376 
2377 	return print_irq_inversion_bug(curr, &root, target_entry,
2378 					this, 1, irqclass);
2379 }
2380 
2381 /*
2382  * Prove that in the backwards-direction subgraph starting at <this>
2383  * there is no lock matching <mask>:
2384  */
2385 static int
check_usage_backwards(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit bit,const char * irqclass)2386 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
2387 		      enum lock_usage_bit bit, const char *irqclass)
2388 {
2389 	int ret;
2390 	struct lock_list root;
2391 	struct lock_list *uninitialized_var(target_entry);
2392 
2393 	root.parent = NULL;
2394 	root.class = hlock_class(this);
2395 	ret = find_usage_backwards(&root, bit, &target_entry);
2396 	if (ret < 0)
2397 		return print_bfs_bug(ret);
2398 	if (ret == 1)
2399 		return ret;
2400 
2401 	return print_irq_inversion_bug(curr, &root, target_entry,
2402 					this, 0, irqclass);
2403 }
2404 
print_irqtrace_events(struct task_struct * curr)2405 void print_irqtrace_events(struct task_struct *curr)
2406 {
2407 	printk("irq event stamp: %u\n", curr->irq_events);
2408 	printk("hardirqs last  enabled at (%u): ", curr->hardirq_enable_event);
2409 	print_ip_sym(curr->hardirq_enable_ip);
2410 	printk("hardirqs last disabled at (%u): ", curr->hardirq_disable_event);
2411 	print_ip_sym(curr->hardirq_disable_ip);
2412 	printk("softirqs last  enabled at (%u): ", curr->softirq_enable_event);
2413 	print_ip_sym(curr->softirq_enable_ip);
2414 	printk("softirqs last disabled at (%u): ", curr->softirq_disable_event);
2415 	print_ip_sym(curr->softirq_disable_ip);
2416 }
2417 
HARDIRQ_verbose(struct lock_class * class)2418 static int HARDIRQ_verbose(struct lock_class *class)
2419 {
2420 #if HARDIRQ_VERBOSE
2421 	return class_filter(class);
2422 #endif
2423 	return 0;
2424 }
2425 
SOFTIRQ_verbose(struct lock_class * class)2426 static int SOFTIRQ_verbose(struct lock_class *class)
2427 {
2428 #if SOFTIRQ_VERBOSE
2429 	return class_filter(class);
2430 #endif
2431 	return 0;
2432 }
2433 
RECLAIM_FS_verbose(struct lock_class * class)2434 static int RECLAIM_FS_verbose(struct lock_class *class)
2435 {
2436 #if RECLAIM_VERBOSE
2437 	return class_filter(class);
2438 #endif
2439 	return 0;
2440 }
2441 
2442 #define STRICT_READ_CHECKS	1
2443 
2444 static int (*state_verbose_f[])(struct lock_class *class) = {
2445 #define LOCKDEP_STATE(__STATE) \
2446 	__STATE##_verbose,
2447 #include "lockdep_states.h"
2448 #undef LOCKDEP_STATE
2449 };
2450 
state_verbose(enum lock_usage_bit bit,struct lock_class * class)2451 static inline int state_verbose(enum lock_usage_bit bit,
2452 				struct lock_class *class)
2453 {
2454 	return state_verbose_f[bit >> 2](class);
2455 }
2456 
2457 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
2458 			     enum lock_usage_bit bit, const char *name);
2459 
2460 static int
mark_lock_irq(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit new_bit)2461 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
2462 		enum lock_usage_bit new_bit)
2463 {
2464 	int excl_bit = exclusive_bit(new_bit);
2465 	int read = new_bit & 1;
2466 	int dir = new_bit & 2;
2467 
2468 	/*
2469 	 * mark USED_IN has to look forwards -- to ensure no dependency
2470 	 * has ENABLED state, which would allow recursion deadlocks.
2471 	 *
2472 	 * mark ENABLED has to look backwards -- to ensure no dependee
2473 	 * has USED_IN state, which, again, would allow  recursion deadlocks.
2474 	 */
2475 	check_usage_f usage = dir ?
2476 		check_usage_backwards : check_usage_forwards;
2477 
2478 	/*
2479 	 * Validate that this particular lock does not have conflicting
2480 	 * usage states.
2481 	 */
2482 	if (!valid_state(curr, this, new_bit, excl_bit))
2483 		return 0;
2484 
2485 	/*
2486 	 * Validate that the lock dependencies don't have conflicting usage
2487 	 * states.
2488 	 */
2489 	if ((!read || !dir || STRICT_READ_CHECKS) &&
2490 			!usage(curr, this, excl_bit, state_name(new_bit & ~1)))
2491 		return 0;
2492 
2493 	/*
2494 	 * Check for read in write conflicts
2495 	 */
2496 	if (!read) {
2497 		if (!valid_state(curr, this, new_bit, excl_bit + 1))
2498 			return 0;
2499 
2500 		if (STRICT_READ_CHECKS &&
2501 			!usage(curr, this, excl_bit + 1,
2502 				state_name(new_bit + 1)))
2503 			return 0;
2504 	}
2505 
2506 	if (state_verbose(new_bit, hlock_class(this)))
2507 		return 2;
2508 
2509 	return 1;
2510 }
2511 
2512 enum mark_type {
2513 #define LOCKDEP_STATE(__STATE)	__STATE,
2514 #include "lockdep_states.h"
2515 #undef LOCKDEP_STATE
2516 };
2517 
2518 /*
2519  * Mark all held locks with a usage bit:
2520  */
2521 static int
mark_held_locks(struct task_struct * curr,enum mark_type mark)2522 mark_held_locks(struct task_struct *curr, enum mark_type mark)
2523 {
2524 	enum lock_usage_bit usage_bit;
2525 	struct held_lock *hlock;
2526 	int i;
2527 
2528 	for (i = 0; i < curr->lockdep_depth; i++) {
2529 		hlock = curr->held_locks + i;
2530 
2531 		usage_bit = 2 + (mark << 2); /* ENABLED */
2532 		if (hlock->read)
2533 			usage_bit += 1; /* READ */
2534 
2535 		BUG_ON(usage_bit >= LOCK_USAGE_STATES);
2536 
2537 		if (!hlock->check)
2538 			continue;
2539 
2540 		if (!mark_lock(curr, hlock, usage_bit))
2541 			return 0;
2542 	}
2543 
2544 	return 1;
2545 }
2546 
2547 /*
2548  * Hardirqs will be enabled:
2549  */
__trace_hardirqs_on_caller(unsigned long ip)2550 static void __trace_hardirqs_on_caller(unsigned long ip)
2551 {
2552 	struct task_struct *curr = current;
2553 
2554 	/* we'll do an OFF -> ON transition: */
2555 	curr->hardirqs_enabled = 1;
2556 
2557 	/*
2558 	 * We are going to turn hardirqs on, so set the
2559 	 * usage bit for all held locks:
2560 	 */
2561 	if (!mark_held_locks(curr, HARDIRQ))
2562 		return;
2563 	/*
2564 	 * If we have softirqs enabled, then set the usage
2565 	 * bit for all held locks. (disabled hardirqs prevented
2566 	 * this bit from being set before)
2567 	 */
2568 	if (curr->softirqs_enabled)
2569 		if (!mark_held_locks(curr, SOFTIRQ))
2570 			return;
2571 
2572 	curr->hardirq_enable_ip = ip;
2573 	curr->hardirq_enable_event = ++curr->irq_events;
2574 	debug_atomic_inc(hardirqs_on_events);
2575 }
2576 
trace_hardirqs_on_caller(unsigned long ip)2577 __visible void trace_hardirqs_on_caller(unsigned long ip)
2578 {
2579 	time_hardirqs_on(CALLER_ADDR0, ip);
2580 
2581 	if (unlikely(!debug_locks || current->lockdep_recursion))
2582 		return;
2583 
2584 	if (unlikely(current->hardirqs_enabled)) {
2585 		/*
2586 		 * Neither irq nor preemption are disabled here
2587 		 * so this is racy by nature but losing one hit
2588 		 * in a stat is not a big deal.
2589 		 */
2590 		__debug_atomic_inc(redundant_hardirqs_on);
2591 		return;
2592 	}
2593 
2594 	/*
2595 	 * We're enabling irqs and according to our state above irqs weren't
2596 	 * already enabled, yet we find the hardware thinks they are in fact
2597 	 * enabled.. someone messed up their IRQ state tracing.
2598 	 */
2599 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2600 		return;
2601 
2602 	/*
2603 	 * See the fine text that goes along with this variable definition.
2604 	 */
2605 	if (DEBUG_LOCKS_WARN_ON(unlikely(early_boot_irqs_disabled)))
2606 		return;
2607 
2608 	/*
2609 	 * Can't allow enabling interrupts while in an interrupt handler,
2610 	 * that's general bad form and such. Recursion, limited stack etc..
2611 	 */
2612 	if (DEBUG_LOCKS_WARN_ON(current->hardirq_context))
2613 		return;
2614 
2615 	current->lockdep_recursion = 1;
2616 	__trace_hardirqs_on_caller(ip);
2617 	current->lockdep_recursion = 0;
2618 }
2619 EXPORT_SYMBOL(trace_hardirqs_on_caller);
2620 
trace_hardirqs_on(void)2621 void trace_hardirqs_on(void)
2622 {
2623 	trace_hardirqs_on_caller(CALLER_ADDR0);
2624 }
2625 EXPORT_SYMBOL(trace_hardirqs_on);
2626 
2627 /*
2628  * Hardirqs were disabled:
2629  */
trace_hardirqs_off_caller(unsigned long ip)2630 __visible void trace_hardirqs_off_caller(unsigned long ip)
2631 {
2632 	struct task_struct *curr = current;
2633 
2634 	time_hardirqs_off(CALLER_ADDR0, ip);
2635 
2636 	if (unlikely(!debug_locks || current->lockdep_recursion))
2637 		return;
2638 
2639 	/*
2640 	 * So we're supposed to get called after you mask local IRQs, but for
2641 	 * some reason the hardware doesn't quite think you did a proper job.
2642 	 */
2643 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2644 		return;
2645 
2646 	if (curr->hardirqs_enabled) {
2647 		/*
2648 		 * We have done an ON -> OFF transition:
2649 		 */
2650 		curr->hardirqs_enabled = 0;
2651 		curr->hardirq_disable_ip = ip;
2652 		curr->hardirq_disable_event = ++curr->irq_events;
2653 		debug_atomic_inc(hardirqs_off_events);
2654 	} else
2655 		debug_atomic_inc(redundant_hardirqs_off);
2656 }
2657 EXPORT_SYMBOL(trace_hardirqs_off_caller);
2658 
trace_hardirqs_off(void)2659 void trace_hardirqs_off(void)
2660 {
2661 	trace_hardirqs_off_caller(CALLER_ADDR0);
2662 }
2663 EXPORT_SYMBOL(trace_hardirqs_off);
2664 
2665 /*
2666  * Softirqs will be enabled:
2667  */
trace_softirqs_on(unsigned long ip)2668 void trace_softirqs_on(unsigned long ip)
2669 {
2670 	struct task_struct *curr = current;
2671 
2672 	if (unlikely(!debug_locks || current->lockdep_recursion))
2673 		return;
2674 
2675 	/*
2676 	 * We fancy IRQs being disabled here, see softirq.c, avoids
2677 	 * funny state and nesting things.
2678 	 */
2679 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2680 		return;
2681 
2682 	if (curr->softirqs_enabled) {
2683 		debug_atomic_inc(redundant_softirqs_on);
2684 		return;
2685 	}
2686 
2687 	current->lockdep_recursion = 1;
2688 	/*
2689 	 * We'll do an OFF -> ON transition:
2690 	 */
2691 	curr->softirqs_enabled = 1;
2692 	curr->softirq_enable_ip = ip;
2693 	curr->softirq_enable_event = ++curr->irq_events;
2694 	debug_atomic_inc(softirqs_on_events);
2695 	/*
2696 	 * We are going to turn softirqs on, so set the
2697 	 * usage bit for all held locks, if hardirqs are
2698 	 * enabled too:
2699 	 */
2700 	if (curr->hardirqs_enabled)
2701 		mark_held_locks(curr, SOFTIRQ);
2702 	current->lockdep_recursion = 0;
2703 }
2704 
2705 /*
2706  * Softirqs were disabled:
2707  */
trace_softirqs_off(unsigned long ip)2708 void trace_softirqs_off(unsigned long ip)
2709 {
2710 	struct task_struct *curr = current;
2711 
2712 	if (unlikely(!debug_locks || current->lockdep_recursion))
2713 		return;
2714 
2715 	/*
2716 	 * We fancy IRQs being disabled here, see softirq.c
2717 	 */
2718 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2719 		return;
2720 
2721 	if (curr->softirqs_enabled) {
2722 		/*
2723 		 * We have done an ON -> OFF transition:
2724 		 */
2725 		curr->softirqs_enabled = 0;
2726 		curr->softirq_disable_ip = ip;
2727 		curr->softirq_disable_event = ++curr->irq_events;
2728 		debug_atomic_inc(softirqs_off_events);
2729 		/*
2730 		 * Whoops, we wanted softirqs off, so why aren't they?
2731 		 */
2732 		DEBUG_LOCKS_WARN_ON(!softirq_count());
2733 	} else
2734 		debug_atomic_inc(redundant_softirqs_off);
2735 }
2736 
__lockdep_trace_alloc(gfp_t gfp_mask,unsigned long flags)2737 static void __lockdep_trace_alloc(gfp_t gfp_mask, unsigned long flags)
2738 {
2739 	struct task_struct *curr = current;
2740 
2741 	if (unlikely(!debug_locks))
2742 		return;
2743 
2744 	/* no reclaim without waiting on it */
2745 	if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
2746 		return;
2747 
2748 	/* this guy won't enter reclaim */
2749 	if ((curr->flags & PF_MEMALLOC) && !(gfp_mask & __GFP_NOMEMALLOC))
2750 		return;
2751 
2752 	/* We're only interested __GFP_FS allocations for now */
2753 	if (!(gfp_mask & __GFP_FS))
2754 		return;
2755 
2756 	/*
2757 	 * Oi! Can't be having __GFP_FS allocations with IRQs disabled.
2758 	 */
2759 	if (DEBUG_LOCKS_WARN_ON(irqs_disabled_flags(flags)))
2760 		return;
2761 
2762 	mark_held_locks(curr, RECLAIM_FS);
2763 }
2764 
2765 static void check_flags(unsigned long flags);
2766 
lockdep_trace_alloc(gfp_t gfp_mask)2767 void lockdep_trace_alloc(gfp_t gfp_mask)
2768 {
2769 	unsigned long flags;
2770 
2771 	if (unlikely(current->lockdep_recursion))
2772 		return;
2773 
2774 	raw_local_irq_save(flags);
2775 	check_flags(flags);
2776 	current->lockdep_recursion = 1;
2777 	__lockdep_trace_alloc(gfp_mask, flags);
2778 	current->lockdep_recursion = 0;
2779 	raw_local_irq_restore(flags);
2780 }
2781 
mark_irqflags(struct task_struct * curr,struct held_lock * hlock)2782 static int mark_irqflags(struct task_struct *curr, struct held_lock *hlock)
2783 {
2784 	/*
2785 	 * If non-trylock use in a hardirq or softirq context, then
2786 	 * mark the lock as used in these contexts:
2787 	 */
2788 	if (!hlock->trylock) {
2789 		if (hlock->read) {
2790 			if (curr->hardirq_context)
2791 				if (!mark_lock(curr, hlock,
2792 						LOCK_USED_IN_HARDIRQ_READ))
2793 					return 0;
2794 			if (curr->softirq_context)
2795 				if (!mark_lock(curr, hlock,
2796 						LOCK_USED_IN_SOFTIRQ_READ))
2797 					return 0;
2798 		} else {
2799 			if (curr->hardirq_context)
2800 				if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
2801 					return 0;
2802 			if (curr->softirq_context)
2803 				if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
2804 					return 0;
2805 		}
2806 	}
2807 	if (!hlock->hardirqs_off) {
2808 		if (hlock->read) {
2809 			if (!mark_lock(curr, hlock,
2810 					LOCK_ENABLED_HARDIRQ_READ))
2811 				return 0;
2812 			if (curr->softirqs_enabled)
2813 				if (!mark_lock(curr, hlock,
2814 						LOCK_ENABLED_SOFTIRQ_READ))
2815 					return 0;
2816 		} else {
2817 			if (!mark_lock(curr, hlock,
2818 					LOCK_ENABLED_HARDIRQ))
2819 				return 0;
2820 			if (curr->softirqs_enabled)
2821 				if (!mark_lock(curr, hlock,
2822 						LOCK_ENABLED_SOFTIRQ))
2823 					return 0;
2824 		}
2825 	}
2826 
2827 	/*
2828 	 * We reuse the irq context infrastructure more broadly as a general
2829 	 * context checking code. This tests GFP_FS recursion (a lock taken
2830 	 * during reclaim for a GFP_FS allocation is held over a GFP_FS
2831 	 * allocation).
2832 	 */
2833 	if (!hlock->trylock && (curr->lockdep_reclaim_gfp & __GFP_FS)) {
2834 		if (hlock->read) {
2835 			if (!mark_lock(curr, hlock, LOCK_USED_IN_RECLAIM_FS_READ))
2836 					return 0;
2837 		} else {
2838 			if (!mark_lock(curr, hlock, LOCK_USED_IN_RECLAIM_FS))
2839 					return 0;
2840 		}
2841 	}
2842 
2843 	return 1;
2844 }
2845 
separate_irq_context(struct task_struct * curr,struct held_lock * hlock)2846 static int separate_irq_context(struct task_struct *curr,
2847 		struct held_lock *hlock)
2848 {
2849 	unsigned int depth = curr->lockdep_depth;
2850 
2851 	/*
2852 	 * Keep track of points where we cross into an interrupt context:
2853 	 */
2854 	hlock->irq_context = 2*(curr->hardirq_context ? 1 : 0) +
2855 				curr->softirq_context;
2856 	if (depth) {
2857 		struct held_lock *prev_hlock;
2858 
2859 		prev_hlock = curr->held_locks + depth-1;
2860 		/*
2861 		 * If we cross into another context, reset the
2862 		 * hash key (this also prevents the checking and the
2863 		 * adding of the dependency to 'prev'):
2864 		 */
2865 		if (prev_hlock->irq_context != hlock->irq_context)
2866 			return 1;
2867 	}
2868 	return 0;
2869 }
2870 
2871 #else /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
2872 
2873 static inline
mark_lock_irq(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit new_bit)2874 int mark_lock_irq(struct task_struct *curr, struct held_lock *this,
2875 		enum lock_usage_bit new_bit)
2876 {
2877 	WARN_ON(1); /* Impossible innit? when we don't have TRACE_IRQFLAG */
2878 	return 1;
2879 }
2880 
mark_irqflags(struct task_struct * curr,struct held_lock * hlock)2881 static inline int mark_irqflags(struct task_struct *curr,
2882 		struct held_lock *hlock)
2883 {
2884 	return 1;
2885 }
2886 
separate_irq_context(struct task_struct * curr,struct held_lock * hlock)2887 static inline int separate_irq_context(struct task_struct *curr,
2888 		struct held_lock *hlock)
2889 {
2890 	return 0;
2891 }
2892 
lockdep_trace_alloc(gfp_t gfp_mask)2893 void lockdep_trace_alloc(gfp_t gfp_mask)
2894 {
2895 }
2896 
2897 #endif /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
2898 
2899 /*
2900  * Mark a lock with a usage bit, and validate the state transition:
2901  */
mark_lock(struct task_struct * curr,struct held_lock * this,enum lock_usage_bit new_bit)2902 static int mark_lock(struct task_struct *curr, struct held_lock *this,
2903 			     enum lock_usage_bit new_bit)
2904 {
2905 	unsigned int new_mask = 1 << new_bit, ret = 1;
2906 
2907 	/*
2908 	 * If already set then do not dirty the cacheline,
2909 	 * nor do any checks:
2910 	 */
2911 	if (likely(hlock_class(this)->usage_mask & new_mask))
2912 		return 1;
2913 
2914 	if (!graph_lock())
2915 		return 0;
2916 	/*
2917 	 * Make sure we didn't race:
2918 	 */
2919 	if (unlikely(hlock_class(this)->usage_mask & new_mask)) {
2920 		graph_unlock();
2921 		return 1;
2922 	}
2923 
2924 	hlock_class(this)->usage_mask |= new_mask;
2925 
2926 	if (!save_trace(hlock_class(this)->usage_traces + new_bit))
2927 		return 0;
2928 
2929 	switch (new_bit) {
2930 #define LOCKDEP_STATE(__STATE)			\
2931 	case LOCK_USED_IN_##__STATE:		\
2932 	case LOCK_USED_IN_##__STATE##_READ:	\
2933 	case LOCK_ENABLED_##__STATE:		\
2934 	case LOCK_ENABLED_##__STATE##_READ:
2935 #include "lockdep_states.h"
2936 #undef LOCKDEP_STATE
2937 		ret = mark_lock_irq(curr, this, new_bit);
2938 		if (!ret)
2939 			return 0;
2940 		break;
2941 	case LOCK_USED:
2942 		debug_atomic_dec(nr_unused_locks);
2943 		break;
2944 	default:
2945 		if (!debug_locks_off_graph_unlock())
2946 			return 0;
2947 		WARN_ON(1);
2948 		return 0;
2949 	}
2950 
2951 	graph_unlock();
2952 
2953 	/*
2954 	 * We must printk outside of the graph_lock:
2955 	 */
2956 	if (ret == 2) {
2957 		printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
2958 		print_lock(this);
2959 		print_irqtrace_events(curr);
2960 		dump_stack();
2961 	}
2962 
2963 	return ret;
2964 }
2965 
2966 /*
2967  * Initialize a lock instance's lock-class mapping info:
2968  */
lockdep_init_map(struct lockdep_map * lock,const char * name,struct lock_class_key * key,int subclass)2969 void lockdep_init_map(struct lockdep_map *lock, const char *name,
2970 		      struct lock_class_key *key, int subclass)
2971 {
2972 	int i;
2973 
2974 	kmemcheck_mark_initialized(lock, sizeof(*lock));
2975 
2976 	for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
2977 		lock->class_cache[i] = NULL;
2978 
2979 #ifdef CONFIG_LOCK_STAT
2980 	lock->cpu = raw_smp_processor_id();
2981 #endif
2982 
2983 	/*
2984 	 * Can't be having no nameless bastards around this place!
2985 	 */
2986 	if (DEBUG_LOCKS_WARN_ON(!name)) {
2987 		lock->name = "NULL";
2988 		return;
2989 	}
2990 
2991 	lock->name = name;
2992 
2993 	/*
2994 	 * No key, no joy, we need to hash something.
2995 	 */
2996 	if (DEBUG_LOCKS_WARN_ON(!key))
2997 		return;
2998 	/*
2999 	 * Sanity check, the lock-class key must be persistent:
3000 	 */
3001 	if (!static_obj(key)) {
3002 		printk("BUG: key %p not in .data!\n", key);
3003 		/*
3004 		 * What it says above ^^^^^, I suggest you read it.
3005 		 */
3006 		DEBUG_LOCKS_WARN_ON(1);
3007 		return;
3008 	}
3009 	lock->key = key;
3010 
3011 	if (unlikely(!debug_locks))
3012 		return;
3013 
3014 	if (subclass) {
3015 		unsigned long flags;
3016 
3017 		if (DEBUG_LOCKS_WARN_ON(current->lockdep_recursion))
3018 			return;
3019 
3020 		raw_local_irq_save(flags);
3021 		current->lockdep_recursion = 1;
3022 		register_lock_class(lock, subclass, 1);
3023 		current->lockdep_recursion = 0;
3024 		raw_local_irq_restore(flags);
3025 	}
3026 }
3027 EXPORT_SYMBOL_GPL(lockdep_init_map);
3028 
3029 struct lock_class_key __lockdep_no_validate__;
3030 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
3031 
3032 static int
print_lock_nested_lock_not_held(struct task_struct * curr,struct held_lock * hlock,unsigned long ip)3033 print_lock_nested_lock_not_held(struct task_struct *curr,
3034 				struct held_lock *hlock,
3035 				unsigned long ip)
3036 {
3037 	if (!debug_locks_off())
3038 		return 0;
3039 	if (debug_locks_silent)
3040 		return 0;
3041 
3042 	printk("\n");
3043 	printk("==================================\n");
3044 	printk("[ BUG: Nested lock was not taken ]\n");
3045 	print_kernel_ident();
3046 	printk("----------------------------------\n");
3047 
3048 	printk("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
3049 	print_lock(hlock);
3050 
3051 	printk("\nbut this task is not holding:\n");
3052 	printk("%s\n", hlock->nest_lock->name);
3053 
3054 	printk("\nstack backtrace:\n");
3055 	dump_stack();
3056 
3057 	printk("\nother info that might help us debug this:\n");
3058 	lockdep_print_held_locks(curr);
3059 
3060 	printk("\nstack backtrace:\n");
3061 	dump_stack();
3062 
3063 	return 0;
3064 }
3065 
3066 static int __lock_is_held(struct lockdep_map *lock);
3067 
3068 /*
3069  * This gets called for every mutex_lock*()/spin_lock*() operation.
3070  * We maintain the dependency maps and validate the locking attempt:
3071  */
__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)3072 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3073 			  int trylock, int read, int check, int hardirqs_off,
3074 			  struct lockdep_map *nest_lock, unsigned long ip,
3075 			  int references, int pin_count)
3076 {
3077 	struct task_struct *curr = current;
3078 	struct lock_class *class = NULL;
3079 	struct held_lock *hlock;
3080 	unsigned int depth, id;
3081 	int chain_head = 0;
3082 	int class_idx;
3083 	u64 chain_key;
3084 
3085 	if (unlikely(!debug_locks))
3086 		return 0;
3087 
3088 	/*
3089 	 * Lockdep should run with IRQs disabled, otherwise we could
3090 	 * get an interrupt which would want to take locks, which would
3091 	 * end up in lockdep and have you got a head-ache already?
3092 	 */
3093 	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3094 		return 0;
3095 
3096 	if (!prove_locking || lock->key == &__lockdep_no_validate__)
3097 		check = 0;
3098 
3099 	if (subclass < NR_LOCKDEP_CACHING_CLASSES)
3100 		class = lock->class_cache[subclass];
3101 	/*
3102 	 * Not cached?
3103 	 */
3104 	if (unlikely(!class)) {
3105 		class = register_lock_class(lock, subclass, 0);
3106 		if (!class)
3107 			return 0;
3108 	}
3109 	atomic_inc((atomic_t *)&class->ops);
3110 	if (very_verbose(class)) {
3111 		printk("\nacquire class [%p] %s", class->key, class->name);
3112 		if (class->name_version > 1)
3113 			printk("#%d", class->name_version);
3114 		printk("\n");
3115 		dump_stack();
3116 	}
3117 
3118 	/*
3119 	 * Add the lock to the list of currently held locks.
3120 	 * (we dont increase the depth just yet, up until the
3121 	 * dependency checks are done)
3122 	 */
3123 	depth = curr->lockdep_depth;
3124 	/*
3125 	 * Ran out of static storage for our per-task lock stack again have we?
3126 	 */
3127 	if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
3128 		return 0;
3129 
3130 	class_idx = class - lock_classes + 1;
3131 
3132 	if (depth) {
3133 		hlock = curr->held_locks + depth - 1;
3134 		if (hlock->class_idx == class_idx && nest_lock) {
3135 			if (!references)
3136 				references++;
3137 
3138 			if (!hlock->references)
3139 				hlock->references++;
3140 
3141 			hlock->references += references;
3142 
3143 			/* Overflow */
3144 			if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
3145 				return 0;
3146 
3147 			return 1;
3148 		}
3149 	}
3150 
3151 	hlock = curr->held_locks + depth;
3152 	/*
3153 	 * Plain impossible, we just registered it and checked it weren't no
3154 	 * NULL like.. I bet this mushroom I ate was good!
3155 	 */
3156 	if (DEBUG_LOCKS_WARN_ON(!class))
3157 		return 0;
3158 	hlock->class_idx = class_idx;
3159 	hlock->acquire_ip = ip;
3160 	hlock->instance = lock;
3161 	hlock->nest_lock = nest_lock;
3162 	hlock->trylock = trylock;
3163 	hlock->read = read;
3164 	hlock->check = check;
3165 	hlock->hardirqs_off = !!hardirqs_off;
3166 	hlock->references = references;
3167 #ifdef CONFIG_LOCK_STAT
3168 	hlock->waittime_stamp = 0;
3169 	hlock->holdtime_stamp = lockstat_clock();
3170 #endif
3171 	hlock->pin_count = pin_count;
3172 
3173 	if (check && !mark_irqflags(curr, hlock))
3174 		return 0;
3175 
3176 	/* mark it as used: */
3177 	if (!mark_lock(curr, hlock, LOCK_USED))
3178 		return 0;
3179 
3180 	/*
3181 	 * Calculate the chain hash: it's the combined hash of all the
3182 	 * lock keys along the dependency chain. We save the hash value
3183 	 * at every step so that we can get the current hash easily
3184 	 * after unlock. The chain hash is then used to cache dependency
3185 	 * results.
3186 	 *
3187 	 * The 'key ID' is what is the most compact key value to drive
3188 	 * the hash, not class->key.
3189 	 */
3190 	id = class - lock_classes;
3191 	/*
3192 	 * Whoops, we did it again.. ran straight out of our static allocation.
3193 	 */
3194 	if (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
3195 		return 0;
3196 
3197 	chain_key = curr->curr_chain_key;
3198 	if (!depth) {
3199 		/*
3200 		 * How can we have a chain hash when we ain't got no keys?!
3201 		 */
3202 		if (DEBUG_LOCKS_WARN_ON(chain_key != 0))
3203 			return 0;
3204 		chain_head = 1;
3205 	}
3206 
3207 	hlock->prev_chain_key = chain_key;
3208 	if (separate_irq_context(curr, hlock)) {
3209 		chain_key = 0;
3210 		chain_head = 1;
3211 	}
3212 	chain_key = iterate_chain_key(chain_key, id);
3213 
3214 	if (nest_lock && !__lock_is_held(nest_lock))
3215 		return print_lock_nested_lock_not_held(curr, hlock, ip);
3216 
3217 	if (!validate_chain(curr, lock, hlock, chain_head, chain_key))
3218 		return 0;
3219 
3220 	curr->curr_chain_key = chain_key;
3221 	curr->lockdep_depth++;
3222 	check_chain_key(curr);
3223 #ifdef CONFIG_DEBUG_LOCKDEP
3224 	if (unlikely(!debug_locks))
3225 		return 0;
3226 #endif
3227 	if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
3228 		debug_locks_off();
3229 		print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
3230 		printk(KERN_DEBUG "depth: %i  max: %lu!\n",
3231 		       curr->lockdep_depth, MAX_LOCK_DEPTH);
3232 
3233 		lockdep_print_held_locks(current);
3234 		debug_show_all_locks();
3235 		dump_stack();
3236 
3237 		return 0;
3238 	}
3239 
3240 	if (unlikely(curr->lockdep_depth > max_lockdep_depth))
3241 		max_lockdep_depth = curr->lockdep_depth;
3242 
3243 	return 1;
3244 }
3245 
3246 static int
print_unlock_imbalance_bug(struct task_struct * curr,struct lockdep_map * lock,unsigned long ip)3247 print_unlock_imbalance_bug(struct task_struct *curr, struct lockdep_map *lock,
3248 			   unsigned long ip)
3249 {
3250 	if (!debug_locks_off())
3251 		return 0;
3252 	if (debug_locks_silent)
3253 		return 0;
3254 
3255 	printk("\n");
3256 	printk("=====================================\n");
3257 	printk("[ BUG: bad unlock balance detected! ]\n");
3258 	print_kernel_ident();
3259 	printk("-------------------------------------\n");
3260 	printk("%s/%d is trying to release lock (",
3261 		curr->comm, task_pid_nr(curr));
3262 	print_lockdep_cache(lock);
3263 	printk(") at:\n");
3264 	print_ip_sym(ip);
3265 	printk("but there are no more locks to release!\n");
3266 	printk("\nother info that might help us debug this:\n");
3267 	lockdep_print_held_locks(curr);
3268 
3269 	printk("\nstack backtrace:\n");
3270 	dump_stack();
3271 
3272 	return 0;
3273 }
3274 
match_held_lock(struct held_lock * hlock,struct lockdep_map * lock)3275 static int match_held_lock(struct held_lock *hlock, struct lockdep_map *lock)
3276 {
3277 	if (hlock->instance == lock)
3278 		return 1;
3279 
3280 	if (hlock->references) {
3281 		struct lock_class *class = lock->class_cache[0];
3282 
3283 		if (!class)
3284 			class = look_up_lock_class(lock, 0);
3285 
3286 		/*
3287 		 * If look_up_lock_class() failed to find a class, we're trying
3288 		 * to test if we hold a lock that has never yet been acquired.
3289 		 * Clearly if the lock hasn't been acquired _ever_, we're not
3290 		 * holding it either, so report failure.
3291 		 */
3292 		if (!class)
3293 			return 0;
3294 
3295 		/*
3296 		 * References, but not a lock we're actually ref-counting?
3297 		 * State got messed up, follow the sites that change ->references
3298 		 * and try to make sense of it.
3299 		 */
3300 		if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
3301 			return 0;
3302 
3303 		if (hlock->class_idx == class - lock_classes + 1)
3304 			return 1;
3305 	}
3306 
3307 	return 0;
3308 }
3309 
3310 static int
__lock_set_class(struct lockdep_map * lock,const char * name,struct lock_class_key * key,unsigned int subclass,unsigned long ip)3311 __lock_set_class(struct lockdep_map *lock, const char *name,
3312 		 struct lock_class_key *key, unsigned int subclass,
3313 		 unsigned long ip)
3314 {
3315 	struct task_struct *curr = current;
3316 	struct held_lock *hlock, *prev_hlock;
3317 	struct lock_class *class;
3318 	unsigned int depth;
3319 	int i;
3320 
3321 	if (unlikely(!debug_locks))
3322 		return 0;
3323 
3324 	depth = curr->lockdep_depth;
3325 	/*
3326 	 * This function is about (re)setting the class of a held lock,
3327 	 * yet we're not actually holding any locks. Naughty user!
3328 	 */
3329 	if (DEBUG_LOCKS_WARN_ON(!depth))
3330 		return 0;
3331 
3332 	prev_hlock = NULL;
3333 	for (i = depth-1; i >= 0; i--) {
3334 		hlock = curr->held_locks + i;
3335 		/*
3336 		 * We must not cross into another context:
3337 		 */
3338 		if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3339 			break;
3340 		if (match_held_lock(hlock, lock))
3341 			goto found_it;
3342 		prev_hlock = hlock;
3343 	}
3344 	return print_unlock_imbalance_bug(curr, lock, ip);
3345 
3346 found_it:
3347 	lockdep_init_map(lock, name, key, 0);
3348 	class = register_lock_class(lock, subclass, 0);
3349 	hlock->class_idx = class - lock_classes + 1;
3350 
3351 	curr->lockdep_depth = i;
3352 	curr->curr_chain_key = hlock->prev_chain_key;
3353 
3354 	for (; i < depth; i++) {
3355 		hlock = curr->held_locks + i;
3356 		if (!__lock_acquire(hlock->instance,
3357 			hlock_class(hlock)->subclass, hlock->trylock,
3358 				hlock->read, hlock->check, hlock->hardirqs_off,
3359 				hlock->nest_lock, hlock->acquire_ip,
3360 				hlock->references, hlock->pin_count))
3361 			return 0;
3362 	}
3363 
3364 	/*
3365 	 * I took it apart and put it back together again, except now I have
3366 	 * these 'spare' parts.. where shall I put them.
3367 	 */
3368 	if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
3369 		return 0;
3370 	return 1;
3371 }
3372 
3373 /*
3374  * Remove the lock to the list of currently held locks - this gets
3375  * called on mutex_unlock()/spin_unlock*() (or on a failed
3376  * mutex_lock_interruptible()).
3377  *
3378  * @nested is an hysterical artifact, needs a tree wide cleanup.
3379  */
3380 static int
__lock_release(struct lockdep_map * lock,int nested,unsigned long ip)3381 __lock_release(struct lockdep_map *lock, int nested, unsigned long ip)
3382 {
3383 	struct task_struct *curr = current;
3384 	struct held_lock *hlock, *prev_hlock;
3385 	unsigned int depth;
3386 	int i;
3387 
3388 	if (unlikely(!debug_locks))
3389 		return 0;
3390 
3391 	depth = curr->lockdep_depth;
3392 	/*
3393 	 * So we're all set to release this lock.. wait what lock? We don't
3394 	 * own any locks, you've been drinking again?
3395 	 */
3396 	if (DEBUG_LOCKS_WARN_ON(depth <= 0))
3397 		 return print_unlock_imbalance_bug(curr, lock, ip);
3398 
3399 	/*
3400 	 * Check whether the lock exists in the current stack
3401 	 * of held locks:
3402 	 */
3403 	prev_hlock = NULL;
3404 	for (i = depth-1; i >= 0; i--) {
3405 		hlock = curr->held_locks + i;
3406 		/*
3407 		 * We must not cross into another context:
3408 		 */
3409 		if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3410 			break;
3411 		if (match_held_lock(hlock, lock))
3412 			goto found_it;
3413 		prev_hlock = hlock;
3414 	}
3415 	return print_unlock_imbalance_bug(curr, lock, ip);
3416 
3417 found_it:
3418 	if (hlock->instance == lock)
3419 		lock_release_holdtime(hlock);
3420 
3421 	WARN(hlock->pin_count, "releasing a pinned lock\n");
3422 
3423 	if (hlock->references) {
3424 		hlock->references--;
3425 		if (hlock->references) {
3426 			/*
3427 			 * We had, and after removing one, still have
3428 			 * references, the current lock stack is still
3429 			 * valid. We're done!
3430 			 */
3431 			return 1;
3432 		}
3433 	}
3434 
3435 	/*
3436 	 * We have the right lock to unlock, 'hlock' points to it.
3437 	 * Now we remove it from the stack, and add back the other
3438 	 * entries (if any), recalculating the hash along the way:
3439 	 */
3440 
3441 	curr->lockdep_depth = i;
3442 	curr->curr_chain_key = hlock->prev_chain_key;
3443 
3444 	for (i++; i < depth; i++) {
3445 		hlock = curr->held_locks + i;
3446 		if (!__lock_acquire(hlock->instance,
3447 			hlock_class(hlock)->subclass, hlock->trylock,
3448 				hlock->read, hlock->check, hlock->hardirqs_off,
3449 				hlock->nest_lock, hlock->acquire_ip,
3450 				hlock->references, hlock->pin_count))
3451 			return 0;
3452 	}
3453 
3454 	/*
3455 	 * We had N bottles of beer on the wall, we drank one, but now
3456 	 * there's not N-1 bottles of beer left on the wall...
3457 	 */
3458 	if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - 1))
3459 		return 0;
3460 
3461 	return 1;
3462 }
3463 
__lock_is_held(struct lockdep_map * lock)3464 static int __lock_is_held(struct lockdep_map *lock)
3465 {
3466 	struct task_struct *curr = current;
3467 	int i;
3468 
3469 	for (i = 0; i < curr->lockdep_depth; i++) {
3470 		struct held_lock *hlock = curr->held_locks + i;
3471 
3472 		if (match_held_lock(hlock, lock))
3473 			return 1;
3474 	}
3475 
3476 	return 0;
3477 }
3478 
__lock_pin_lock(struct lockdep_map * lock)3479 static void __lock_pin_lock(struct lockdep_map *lock)
3480 {
3481 	struct task_struct *curr = current;
3482 	int i;
3483 
3484 	if (unlikely(!debug_locks))
3485 		return;
3486 
3487 	for (i = 0; i < curr->lockdep_depth; i++) {
3488 		struct held_lock *hlock = curr->held_locks + i;
3489 
3490 		if (match_held_lock(hlock, lock)) {
3491 			hlock->pin_count++;
3492 			return;
3493 		}
3494 	}
3495 
3496 	WARN(1, "pinning an unheld lock\n");
3497 }
3498 
__lock_unpin_lock(struct lockdep_map * lock)3499 static void __lock_unpin_lock(struct lockdep_map *lock)
3500 {
3501 	struct task_struct *curr = current;
3502 	int i;
3503 
3504 	if (unlikely(!debug_locks))
3505 		return;
3506 
3507 	for (i = 0; i < curr->lockdep_depth; i++) {
3508 		struct held_lock *hlock = curr->held_locks + i;
3509 
3510 		if (match_held_lock(hlock, lock)) {
3511 			if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
3512 				return;
3513 
3514 			hlock->pin_count--;
3515 			return;
3516 		}
3517 	}
3518 
3519 	WARN(1, "unpinning an unheld lock\n");
3520 }
3521 
3522 /*
3523  * Check whether we follow the irq-flags state precisely:
3524  */
check_flags(unsigned long flags)3525 static void check_flags(unsigned long flags)
3526 {
3527 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP) && \
3528     defined(CONFIG_TRACE_IRQFLAGS)
3529 	if (!debug_locks)
3530 		return;
3531 
3532 	if (irqs_disabled_flags(flags)) {
3533 		if (DEBUG_LOCKS_WARN_ON(current->hardirqs_enabled)) {
3534 			printk("possible reason: unannotated irqs-off.\n");
3535 		}
3536 	} else {
3537 		if (DEBUG_LOCKS_WARN_ON(!current->hardirqs_enabled)) {
3538 			printk("possible reason: unannotated irqs-on.\n");
3539 		}
3540 	}
3541 
3542 	/*
3543 	 * We dont accurately track softirq state in e.g.
3544 	 * hardirq contexts (such as on 4KSTACKS), so only
3545 	 * check if not in hardirq contexts:
3546 	 */
3547 	if (!hardirq_count()) {
3548 		if (softirq_count()) {
3549 			/* like the above, but with softirqs */
3550 			DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
3551 		} else {
3552 			/* lick the above, does it taste good? */
3553 			DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
3554 		}
3555 	}
3556 
3557 	if (!debug_locks)
3558 		print_irqtrace_events(current);
3559 #endif
3560 }
3561 
lock_set_class(struct lockdep_map * lock,const char * name,struct lock_class_key * key,unsigned int subclass,unsigned long ip)3562 void lock_set_class(struct lockdep_map *lock, const char *name,
3563 		    struct lock_class_key *key, unsigned int subclass,
3564 		    unsigned long ip)
3565 {
3566 	unsigned long flags;
3567 
3568 	if (unlikely(current->lockdep_recursion))
3569 		return;
3570 
3571 	raw_local_irq_save(flags);
3572 	current->lockdep_recursion = 1;
3573 	check_flags(flags);
3574 	if (__lock_set_class(lock, name, key, subclass, ip))
3575 		check_chain_key(current);
3576 	current->lockdep_recursion = 0;
3577 	raw_local_irq_restore(flags);
3578 }
3579 EXPORT_SYMBOL_GPL(lock_set_class);
3580 
3581 /*
3582  * We are not always called with irqs disabled - do that here,
3583  * and also avoid lockdep recursion:
3584  */
lock_acquire(struct lockdep_map * lock,unsigned int subclass,int trylock,int read,int check,struct lockdep_map * nest_lock,unsigned long ip)3585 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3586 			  int trylock, int read, int check,
3587 			  struct lockdep_map *nest_lock, unsigned long ip)
3588 {
3589 	unsigned long flags;
3590 
3591 	if (unlikely(current->lockdep_recursion))
3592 		return;
3593 
3594 	raw_local_irq_save(flags);
3595 	check_flags(flags);
3596 
3597 	current->lockdep_recursion = 1;
3598 	trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
3599 	__lock_acquire(lock, subclass, trylock, read, check,
3600 		       irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
3601 	current->lockdep_recursion = 0;
3602 	raw_local_irq_restore(flags);
3603 }
3604 EXPORT_SYMBOL_GPL(lock_acquire);
3605 
lock_release(struct lockdep_map * lock,int nested,unsigned long ip)3606 void lock_release(struct lockdep_map *lock, int nested,
3607 			  unsigned long ip)
3608 {
3609 	unsigned long flags;
3610 
3611 	if (unlikely(current->lockdep_recursion))
3612 		return;
3613 
3614 	raw_local_irq_save(flags);
3615 	check_flags(flags);
3616 	current->lockdep_recursion = 1;
3617 	trace_lock_release(lock, ip);
3618 	if (__lock_release(lock, nested, ip))
3619 		check_chain_key(current);
3620 	current->lockdep_recursion = 0;
3621 	raw_local_irq_restore(flags);
3622 }
3623 EXPORT_SYMBOL_GPL(lock_release);
3624 
lock_is_held(struct lockdep_map * lock)3625 int lock_is_held(struct lockdep_map *lock)
3626 {
3627 	unsigned long flags;
3628 	int ret = 0;
3629 
3630 	if (unlikely(current->lockdep_recursion))
3631 		return 1; /* avoid false negative lockdep_assert_held() */
3632 
3633 	raw_local_irq_save(flags);
3634 	check_flags(flags);
3635 
3636 	current->lockdep_recursion = 1;
3637 	ret = __lock_is_held(lock);
3638 	current->lockdep_recursion = 0;
3639 	raw_local_irq_restore(flags);
3640 
3641 	return ret;
3642 }
3643 EXPORT_SYMBOL_GPL(lock_is_held);
3644 
lock_pin_lock(struct lockdep_map * lock)3645 void lock_pin_lock(struct lockdep_map *lock)
3646 {
3647 	unsigned long flags;
3648 
3649 	if (unlikely(current->lockdep_recursion))
3650 		return;
3651 
3652 	raw_local_irq_save(flags);
3653 	check_flags(flags);
3654 
3655 	current->lockdep_recursion = 1;
3656 	__lock_pin_lock(lock);
3657 	current->lockdep_recursion = 0;
3658 	raw_local_irq_restore(flags);
3659 }
3660 EXPORT_SYMBOL_GPL(lock_pin_lock);
3661 
lock_unpin_lock(struct lockdep_map * lock)3662 void lock_unpin_lock(struct lockdep_map *lock)
3663 {
3664 	unsigned long flags;
3665 
3666 	if (unlikely(current->lockdep_recursion))
3667 		return;
3668 
3669 	raw_local_irq_save(flags);
3670 	check_flags(flags);
3671 
3672 	current->lockdep_recursion = 1;
3673 	__lock_unpin_lock(lock);
3674 	current->lockdep_recursion = 0;
3675 	raw_local_irq_restore(flags);
3676 }
3677 EXPORT_SYMBOL_GPL(lock_unpin_lock);
3678 
lockdep_set_current_reclaim_state(gfp_t gfp_mask)3679 void lockdep_set_current_reclaim_state(gfp_t gfp_mask)
3680 {
3681 	current->lockdep_reclaim_gfp = gfp_mask;
3682 }
3683 
lockdep_clear_current_reclaim_state(void)3684 void lockdep_clear_current_reclaim_state(void)
3685 {
3686 	current->lockdep_reclaim_gfp = 0;
3687 }
3688 
3689 #ifdef CONFIG_LOCK_STAT
3690 static int
print_lock_contention_bug(struct task_struct * curr,struct lockdep_map * lock,unsigned long ip)3691 print_lock_contention_bug(struct task_struct *curr, struct lockdep_map *lock,
3692 			   unsigned long ip)
3693 {
3694 	if (!debug_locks_off())
3695 		return 0;
3696 	if (debug_locks_silent)
3697 		return 0;
3698 
3699 	printk("\n");
3700 	printk("=================================\n");
3701 	printk("[ BUG: bad contention detected! ]\n");
3702 	print_kernel_ident();
3703 	printk("---------------------------------\n");
3704 	printk("%s/%d is trying to contend lock (",
3705 		curr->comm, task_pid_nr(curr));
3706 	print_lockdep_cache(lock);
3707 	printk(") at:\n");
3708 	print_ip_sym(ip);
3709 	printk("but there are no locks held!\n");
3710 	printk("\nother info that might help us debug this:\n");
3711 	lockdep_print_held_locks(curr);
3712 
3713 	printk("\nstack backtrace:\n");
3714 	dump_stack();
3715 
3716 	return 0;
3717 }
3718 
3719 static void
__lock_contended(struct lockdep_map * lock,unsigned long ip)3720 __lock_contended(struct lockdep_map *lock, unsigned long ip)
3721 {
3722 	struct task_struct *curr = current;
3723 	struct held_lock *hlock, *prev_hlock;
3724 	struct lock_class_stats *stats;
3725 	unsigned int depth;
3726 	int i, contention_point, contending_point;
3727 
3728 	depth = curr->lockdep_depth;
3729 	/*
3730 	 * Whee, we contended on this lock, except it seems we're not
3731 	 * actually trying to acquire anything much at all..
3732 	 */
3733 	if (DEBUG_LOCKS_WARN_ON(!depth))
3734 		return;
3735 
3736 	prev_hlock = NULL;
3737 	for (i = depth-1; i >= 0; i--) {
3738 		hlock = curr->held_locks + i;
3739 		/*
3740 		 * We must not cross into another context:
3741 		 */
3742 		if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3743 			break;
3744 		if (match_held_lock(hlock, lock))
3745 			goto found_it;
3746 		prev_hlock = hlock;
3747 	}
3748 	print_lock_contention_bug(curr, lock, ip);
3749 	return;
3750 
3751 found_it:
3752 	if (hlock->instance != lock)
3753 		return;
3754 
3755 	hlock->waittime_stamp = lockstat_clock();
3756 
3757 	contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
3758 	contending_point = lock_point(hlock_class(hlock)->contending_point,
3759 				      lock->ip);
3760 
3761 	stats = get_lock_stats(hlock_class(hlock));
3762 	if (contention_point < LOCKSTAT_POINTS)
3763 		stats->contention_point[contention_point]++;
3764 	if (contending_point < LOCKSTAT_POINTS)
3765 		stats->contending_point[contending_point]++;
3766 	if (lock->cpu != smp_processor_id())
3767 		stats->bounces[bounce_contended + !!hlock->read]++;
3768 	put_lock_stats(stats);
3769 }
3770 
3771 static void
__lock_acquired(struct lockdep_map * lock,unsigned long ip)3772 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
3773 {
3774 	struct task_struct *curr = current;
3775 	struct held_lock *hlock, *prev_hlock;
3776 	struct lock_class_stats *stats;
3777 	unsigned int depth;
3778 	u64 now, waittime = 0;
3779 	int i, cpu;
3780 
3781 	depth = curr->lockdep_depth;
3782 	/*
3783 	 * Yay, we acquired ownership of this lock we didn't try to
3784 	 * acquire, how the heck did that happen?
3785 	 */
3786 	if (DEBUG_LOCKS_WARN_ON(!depth))
3787 		return;
3788 
3789 	prev_hlock = NULL;
3790 	for (i = depth-1; i >= 0; i--) {
3791 		hlock = curr->held_locks + i;
3792 		/*
3793 		 * We must not cross into another context:
3794 		 */
3795 		if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3796 			break;
3797 		if (match_held_lock(hlock, lock))
3798 			goto found_it;
3799 		prev_hlock = hlock;
3800 	}
3801 	print_lock_contention_bug(curr, lock, _RET_IP_);
3802 	return;
3803 
3804 found_it:
3805 	if (hlock->instance != lock)
3806 		return;
3807 
3808 	cpu = smp_processor_id();
3809 	if (hlock->waittime_stamp) {
3810 		now = lockstat_clock();
3811 		waittime = now - hlock->waittime_stamp;
3812 		hlock->holdtime_stamp = now;
3813 	}
3814 
3815 	trace_lock_acquired(lock, ip);
3816 
3817 	stats = get_lock_stats(hlock_class(hlock));
3818 	if (waittime) {
3819 		if (hlock->read)
3820 			lock_time_inc(&stats->read_waittime, waittime);
3821 		else
3822 			lock_time_inc(&stats->write_waittime, waittime);
3823 	}
3824 	if (lock->cpu != cpu)
3825 		stats->bounces[bounce_acquired + !!hlock->read]++;
3826 	put_lock_stats(stats);
3827 
3828 	lock->cpu = cpu;
3829 	lock->ip = ip;
3830 }
3831 
lock_contended(struct lockdep_map * lock,unsigned long ip)3832 void lock_contended(struct lockdep_map *lock, unsigned long ip)
3833 {
3834 	unsigned long flags;
3835 
3836 	if (unlikely(!lock_stat || !debug_locks))
3837 		return;
3838 
3839 	if (unlikely(current->lockdep_recursion))
3840 		return;
3841 
3842 	raw_local_irq_save(flags);
3843 	check_flags(flags);
3844 	current->lockdep_recursion = 1;
3845 	trace_lock_contended(lock, ip);
3846 	__lock_contended(lock, ip);
3847 	current->lockdep_recursion = 0;
3848 	raw_local_irq_restore(flags);
3849 }
3850 EXPORT_SYMBOL_GPL(lock_contended);
3851 
lock_acquired(struct lockdep_map * lock,unsigned long ip)3852 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
3853 {
3854 	unsigned long flags;
3855 
3856 	if (unlikely(!lock_stat || !debug_locks))
3857 		return;
3858 
3859 	if (unlikely(current->lockdep_recursion))
3860 		return;
3861 
3862 	raw_local_irq_save(flags);
3863 	check_flags(flags);
3864 	current->lockdep_recursion = 1;
3865 	__lock_acquired(lock, ip);
3866 	current->lockdep_recursion = 0;
3867 	raw_local_irq_restore(flags);
3868 }
3869 EXPORT_SYMBOL_GPL(lock_acquired);
3870 #endif
3871 
3872 /*
3873  * Used by the testsuite, sanitize the validator state
3874  * after a simulated failure:
3875  */
3876 
lockdep_reset(void)3877 void lockdep_reset(void)
3878 {
3879 	unsigned long flags;
3880 	int i;
3881 
3882 	raw_local_irq_save(flags);
3883 	current->curr_chain_key = 0;
3884 	current->lockdep_depth = 0;
3885 	current->lockdep_recursion = 0;
3886 	memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
3887 	nr_hardirq_chains = 0;
3888 	nr_softirq_chains = 0;
3889 	nr_process_chains = 0;
3890 	debug_locks = 1;
3891 	for (i = 0; i < CHAINHASH_SIZE; i++)
3892 		INIT_LIST_HEAD(chainhash_table + i);
3893 	raw_local_irq_restore(flags);
3894 }
3895 
zap_class(struct lock_class * class)3896 static void zap_class(struct lock_class *class)
3897 {
3898 	int i;
3899 
3900 	/*
3901 	 * Remove all dependencies this lock is
3902 	 * involved in:
3903 	 */
3904 	for (i = 0; i < nr_list_entries; i++) {
3905 		if (list_entries[i].class == class)
3906 			list_del_rcu(&list_entries[i].entry);
3907 	}
3908 	/*
3909 	 * Unhash the class and remove it from the all_lock_classes list:
3910 	 */
3911 	list_del_rcu(&class->hash_entry);
3912 	list_del_rcu(&class->lock_entry);
3913 
3914 	RCU_INIT_POINTER(class->key, NULL);
3915 	RCU_INIT_POINTER(class->name, NULL);
3916 }
3917 
within(const void * addr,void * start,unsigned long size)3918 static inline int within(const void *addr, void *start, unsigned long size)
3919 {
3920 	return addr >= start && addr < start + size;
3921 }
3922 
3923 /*
3924  * Used in module.c to remove lock classes from memory that is going to be
3925  * freed; and possibly re-used by other modules.
3926  *
3927  * We will have had one sync_sched() before getting here, so we're guaranteed
3928  * nobody will look up these exact classes -- they're properly dead but still
3929  * allocated.
3930  */
lockdep_free_key_range(void * start,unsigned long size)3931 void lockdep_free_key_range(void *start, unsigned long size)
3932 {
3933 	struct lock_class *class;
3934 	struct list_head *head;
3935 	unsigned long flags;
3936 	int i;
3937 	int locked;
3938 
3939 	raw_local_irq_save(flags);
3940 	locked = graph_lock();
3941 
3942 	/*
3943 	 * Unhash all classes that were created by this module:
3944 	 */
3945 	for (i = 0; i < CLASSHASH_SIZE; i++) {
3946 		head = classhash_table + i;
3947 		if (list_empty(head))
3948 			continue;
3949 		list_for_each_entry_rcu(class, head, hash_entry) {
3950 			if (within(class->key, start, size))
3951 				zap_class(class);
3952 			else if (within(class->name, start, size))
3953 				zap_class(class);
3954 		}
3955 	}
3956 
3957 	if (locked)
3958 		graph_unlock();
3959 	raw_local_irq_restore(flags);
3960 
3961 	/*
3962 	 * Wait for any possible iterators from look_up_lock_class() to pass
3963 	 * before continuing to free the memory they refer to.
3964 	 *
3965 	 * sync_sched() is sufficient because the read-side is IRQ disable.
3966 	 */
3967 	synchronize_sched();
3968 
3969 	/*
3970 	 * XXX at this point we could return the resources to the pool;
3971 	 * instead we leak them. We would need to change to bitmap allocators
3972 	 * instead of the linear allocators we have now.
3973 	 */
3974 }
3975 
lockdep_reset_lock(struct lockdep_map * lock)3976 void lockdep_reset_lock(struct lockdep_map *lock)
3977 {
3978 	struct lock_class *class;
3979 	struct list_head *head;
3980 	unsigned long flags;
3981 	int i, j;
3982 	int locked;
3983 
3984 	raw_local_irq_save(flags);
3985 
3986 	/*
3987 	 * Remove all classes this lock might have:
3988 	 */
3989 	for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
3990 		/*
3991 		 * If the class exists we look it up and zap it:
3992 		 */
3993 		class = look_up_lock_class(lock, j);
3994 		if (class)
3995 			zap_class(class);
3996 	}
3997 	/*
3998 	 * Debug check: in the end all mapped classes should
3999 	 * be gone.
4000 	 */
4001 	locked = graph_lock();
4002 	for (i = 0; i < CLASSHASH_SIZE; i++) {
4003 		head = classhash_table + i;
4004 		if (list_empty(head))
4005 			continue;
4006 		list_for_each_entry_rcu(class, head, hash_entry) {
4007 			int match = 0;
4008 
4009 			for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
4010 				match |= class == lock->class_cache[j];
4011 
4012 			if (unlikely(match)) {
4013 				if (debug_locks_off_graph_unlock()) {
4014 					/*
4015 					 * We all just reset everything, how did it match?
4016 					 */
4017 					WARN_ON(1);
4018 				}
4019 				goto out_restore;
4020 			}
4021 		}
4022 	}
4023 	if (locked)
4024 		graph_unlock();
4025 
4026 out_restore:
4027 	raw_local_irq_restore(flags);
4028 }
4029 
lockdep_init(void)4030 void lockdep_init(void)
4031 {
4032 	int i;
4033 
4034 	/*
4035 	 * Some architectures have their own start_kernel()
4036 	 * code which calls lockdep_init(), while we also
4037 	 * call lockdep_init() from the start_kernel() itself,
4038 	 * and we want to initialize the hashes only once:
4039 	 */
4040 	if (lockdep_initialized)
4041 		return;
4042 
4043 	for (i = 0; i < CLASSHASH_SIZE; i++)
4044 		INIT_LIST_HEAD(classhash_table + i);
4045 
4046 	for (i = 0; i < CHAINHASH_SIZE; i++)
4047 		INIT_LIST_HEAD(chainhash_table + i);
4048 
4049 	lockdep_initialized = 1;
4050 }
4051 
lockdep_info(void)4052 void __init lockdep_info(void)
4053 {
4054 	printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
4055 
4056 	printk("... MAX_LOCKDEP_SUBCLASSES:  %lu\n", MAX_LOCKDEP_SUBCLASSES);
4057 	printk("... MAX_LOCK_DEPTH:          %lu\n", MAX_LOCK_DEPTH);
4058 	printk("... MAX_LOCKDEP_KEYS:        %lu\n", MAX_LOCKDEP_KEYS);
4059 	printk("... CLASSHASH_SIZE:          %lu\n", CLASSHASH_SIZE);
4060 	printk("... MAX_LOCKDEP_ENTRIES:     %lu\n", MAX_LOCKDEP_ENTRIES);
4061 	printk("... MAX_LOCKDEP_CHAINS:      %lu\n", MAX_LOCKDEP_CHAINS);
4062 	printk("... CHAINHASH_SIZE:          %lu\n", CHAINHASH_SIZE);
4063 
4064 	printk(" memory used by lock dependency info: %lu kB\n",
4065 		(sizeof(struct lock_class) * MAX_LOCKDEP_KEYS +
4066 		sizeof(struct list_head) * CLASSHASH_SIZE +
4067 		sizeof(struct lock_list) * MAX_LOCKDEP_ENTRIES +
4068 		sizeof(struct lock_chain) * MAX_LOCKDEP_CHAINS +
4069 		sizeof(struct list_head) * CHAINHASH_SIZE
4070 #ifdef CONFIG_PROVE_LOCKING
4071 		+ sizeof(struct circular_queue)
4072 #endif
4073 		) / 1024
4074 		);
4075 
4076 	printk(" per task-struct memory footprint: %lu bytes\n",
4077 		sizeof(struct held_lock) * MAX_LOCK_DEPTH);
4078 
4079 #ifdef CONFIG_DEBUG_LOCKDEP
4080 	if (lockdep_init_error) {
4081 		printk("WARNING: lockdep init error: lock '%s' was acquired before lockdep_init().\n", lock_init_error);
4082 		printk("Call stack leading to lockdep invocation was:\n");
4083 		print_stack_trace(&lockdep_init_trace, 0);
4084 	}
4085 #endif
4086 }
4087 
4088 static void
print_freed_lock_bug(struct task_struct * curr,const void * mem_from,const void * mem_to,struct held_lock * hlock)4089 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
4090 		     const void *mem_to, struct held_lock *hlock)
4091 {
4092 	if (!debug_locks_off())
4093 		return;
4094 	if (debug_locks_silent)
4095 		return;
4096 
4097 	printk("\n");
4098 	printk("=========================\n");
4099 	printk("[ BUG: held lock freed! ]\n");
4100 	print_kernel_ident();
4101 	printk("-------------------------\n");
4102 	printk("%s/%d is freeing memory %p-%p, with a lock still held there!\n",
4103 		curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
4104 	print_lock(hlock);
4105 	lockdep_print_held_locks(curr);
4106 
4107 	printk("\nstack backtrace:\n");
4108 	dump_stack();
4109 }
4110 
not_in_range(const void * mem_from,unsigned long mem_len,const void * lock_from,unsigned long lock_len)4111 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
4112 				const void* lock_from, unsigned long lock_len)
4113 {
4114 	return lock_from + lock_len <= mem_from ||
4115 		mem_from + mem_len <= lock_from;
4116 }
4117 
4118 /*
4119  * Called when kernel memory is freed (or unmapped), or if a lock
4120  * is destroyed or reinitialized - this code checks whether there is
4121  * any held lock in the memory range of <from> to <to>:
4122  */
debug_check_no_locks_freed(const void * mem_from,unsigned long mem_len)4123 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
4124 {
4125 	struct task_struct *curr = current;
4126 	struct held_lock *hlock;
4127 	unsigned long flags;
4128 	int i;
4129 
4130 	if (unlikely(!debug_locks))
4131 		return;
4132 
4133 	raw_local_irq_save(flags);
4134 	for (i = 0; i < curr->lockdep_depth; i++) {
4135 		hlock = curr->held_locks + i;
4136 
4137 		if (not_in_range(mem_from, mem_len, hlock->instance,
4138 					sizeof(*hlock->instance)))
4139 			continue;
4140 
4141 		print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
4142 		break;
4143 	}
4144 	raw_local_irq_restore(flags);
4145 }
4146 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
4147 
print_held_locks_bug(void)4148 static void print_held_locks_bug(void)
4149 {
4150 	if (!debug_locks_off())
4151 		return;
4152 	if (debug_locks_silent)
4153 		return;
4154 
4155 	printk("\n");
4156 	printk("=====================================\n");
4157 	printk("[ BUG: %s/%d still has locks held! ]\n",
4158 	       current->comm, task_pid_nr(current));
4159 	print_kernel_ident();
4160 	printk("-------------------------------------\n");
4161 	lockdep_print_held_locks(current);
4162 	printk("\nstack backtrace:\n");
4163 	dump_stack();
4164 }
4165 
debug_check_no_locks_held(void)4166 void debug_check_no_locks_held(void)
4167 {
4168 	if (unlikely(current->lockdep_depth > 0))
4169 		print_held_locks_bug();
4170 }
4171 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
4172 
4173 #ifdef __KERNEL__
debug_show_all_locks(void)4174 void debug_show_all_locks(void)
4175 {
4176 	struct task_struct *g, *p;
4177 	int count = 10;
4178 	int unlock = 1;
4179 
4180 	if (unlikely(!debug_locks)) {
4181 		printk("INFO: lockdep is turned off.\n");
4182 		return;
4183 	}
4184 	printk("\nShowing all locks held in the system:\n");
4185 
4186 	/*
4187 	 * Here we try to get the tasklist_lock as hard as possible,
4188 	 * if not successful after 2 seconds we ignore it (but keep
4189 	 * trying). This is to enable a debug printout even if a
4190 	 * tasklist_lock-holding task deadlocks or crashes.
4191 	 */
4192 retry:
4193 	if (!read_trylock(&tasklist_lock)) {
4194 		if (count == 10)
4195 			printk("hm, tasklist_lock locked, retrying... ");
4196 		if (count) {
4197 			count--;
4198 			printk(" #%d", 10-count);
4199 			mdelay(200);
4200 			goto retry;
4201 		}
4202 		printk(" ignoring it.\n");
4203 		unlock = 0;
4204 	} else {
4205 		if (count != 10)
4206 			printk(KERN_CONT " locked it.\n");
4207 	}
4208 
4209 	do_each_thread(g, p) {
4210 		/*
4211 		 * It's not reliable to print a task's held locks
4212 		 * if it's not sleeping (or if it's not the current
4213 		 * task):
4214 		 */
4215 		if (p->state == TASK_RUNNING && p != current)
4216 			continue;
4217 		if (p->lockdep_depth)
4218 			lockdep_print_held_locks(p);
4219 		if (!unlock)
4220 			if (read_trylock(&tasklist_lock))
4221 				unlock = 1;
4222 	} while_each_thread(g, p);
4223 
4224 	printk("\n");
4225 	printk("=============================================\n\n");
4226 
4227 	if (unlock)
4228 		read_unlock(&tasklist_lock);
4229 }
4230 EXPORT_SYMBOL_GPL(debug_show_all_locks);
4231 #endif
4232 
4233 /*
4234  * Careful: only use this function if you are sure that
4235  * the task cannot run in parallel!
4236  */
debug_show_held_locks(struct task_struct * task)4237 void debug_show_held_locks(struct task_struct *task)
4238 {
4239 	if (unlikely(!debug_locks)) {
4240 		printk("INFO: lockdep is turned off.\n");
4241 		return;
4242 	}
4243 	lockdep_print_held_locks(task);
4244 }
4245 EXPORT_SYMBOL_GPL(debug_show_held_locks);
4246 
lockdep_sys_exit(void)4247 asmlinkage __visible void lockdep_sys_exit(void)
4248 {
4249 	struct task_struct *curr = current;
4250 
4251 	if (unlikely(curr->lockdep_depth)) {
4252 		if (!debug_locks_off())
4253 			return;
4254 		printk("\n");
4255 		printk("================================================\n");
4256 		printk("[ BUG: lock held when returning to user space! ]\n");
4257 		print_kernel_ident();
4258 		printk("------------------------------------------------\n");
4259 		printk("%s/%d is leaving the kernel with locks still held!\n",
4260 				curr->comm, curr->pid);
4261 		lockdep_print_held_locks(curr);
4262 	}
4263 }
4264 
lockdep_rcu_suspicious(const char * file,const int line,const char * s)4265 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
4266 {
4267 	struct task_struct *curr = current;
4268 
4269 #ifndef CONFIG_PROVE_RCU_REPEATEDLY
4270 	if (!debug_locks_off())
4271 		return;
4272 #endif /* #ifdef CONFIG_PROVE_RCU_REPEATEDLY */
4273 	/* Note: the following can be executed concurrently, so be careful. */
4274 	printk("\n");
4275 	printk("===============================\n");
4276 	printk("[ INFO: suspicious RCU usage. ]\n");
4277 	print_kernel_ident();
4278 	printk("-------------------------------\n");
4279 	printk("%s:%d %s!\n", file, line, s);
4280 	printk("\nother info that might help us debug this:\n\n");
4281 	printk("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
4282 	       !rcu_lockdep_current_cpu_online()
4283 			? "RCU used illegally from offline CPU!\n"
4284 			: !rcu_is_watching()
4285 				? "RCU used illegally from idle CPU!\n"
4286 				: "",
4287 	       rcu_scheduler_active, debug_locks);
4288 
4289 	/*
4290 	 * If a CPU is in the RCU-free window in idle (ie: in the section
4291 	 * between rcu_idle_enter() and rcu_idle_exit(), then RCU
4292 	 * considers that CPU to be in an "extended quiescent state",
4293 	 * which means that RCU will be completely ignoring that CPU.
4294 	 * Therefore, rcu_read_lock() and friends have absolutely no
4295 	 * effect on a CPU running in that state. In other words, even if
4296 	 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
4297 	 * delete data structures out from under it.  RCU really has no
4298 	 * choice here: we need to keep an RCU-free window in idle where
4299 	 * the CPU may possibly enter into low power mode. This way we can
4300 	 * notice an extended quiescent state to other CPUs that started a grace
4301 	 * period. Otherwise we would delay any grace period as long as we run
4302 	 * in the idle task.
4303 	 *
4304 	 * So complain bitterly if someone does call rcu_read_lock(),
4305 	 * rcu_read_lock_bh() and so on from extended quiescent states.
4306 	 */
4307 	if (!rcu_is_watching())
4308 		printk("RCU used illegally from extended quiescent state!\n");
4309 
4310 	lockdep_print_held_locks(curr);
4311 	printk("\nstack backtrace:\n");
4312 	dump_stack();
4313 }
4314 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);
4315