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