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