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