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