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