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