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