[PATCH] make kernel/printk.c:ignore_loglevel_setup() static
[linux-2.6] / kernel / lockdep.c
1 /*
2  * kernel/lockdep.c
3  *
4  * Runtime locking correctness validator
5  *
6  * Started by Ingo Molnar:
7  *
8  *  Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
9  *
10  * this code maps all the lock dependencies as they occur in a live kernel
11  * and will warn about the following classes of locking bugs:
12  *
13  * - lock inversion scenarios
14  * - circular lock dependencies
15  * - hardirq/softirq safe/unsafe locking bugs
16  *
17  * Bugs are reported even if the current locking scenario does not cause
18  * any deadlock at this point.
19  *
20  * I.e. if anytime in the past two locks were taken in a different order,
21  * even if it happened for another task, even if those were different
22  * locks (but of the same class as this lock), this code will detect it.
23  *
24  * Thanks to Arjan van de Ven for coming up with the initial idea of
25  * mapping lock dependencies runtime.
26  */
27 #include <linux/mutex.h>
28 #include <linux/sched.h>
29 #include <linux/delay.h>
30 #include <linux/module.h>
31 #include <linux/proc_fs.h>
32 #include <linux/seq_file.h>
33 #include <linux/spinlock.h>
34 #include <linux/kallsyms.h>
35 #include <linux/interrupt.h>
36 #include <linux/stacktrace.h>
37 #include <linux/debug_locks.h>
38 #include <linux/irqflags.h>
39 #include <linux/utsname.h>
40
41 #include <asm/sections.h>
42
43 #include "lockdep_internals.h"
44
45 /*
46  * lockdep_lock: protects the lockdep graph, the hashes and the
47  *               class/list/hash allocators.
48  *
49  * This is one of the rare exceptions where it's justified
50  * to use a raw spinlock - we really dont want the spinlock
51  * code to recurse back into the lockdep code...
52  */
53 static raw_spinlock_t lockdep_lock = (raw_spinlock_t)__RAW_SPIN_LOCK_UNLOCKED;
54
55 static int graph_lock(void)
56 {
57         __raw_spin_lock(&lockdep_lock);
58         /*
59          * Make sure that if another CPU detected a bug while
60          * walking the graph we dont change it (while the other
61          * CPU is busy printing out stuff with the graph lock
62          * dropped already)
63          */
64         if (!debug_locks) {
65                 __raw_spin_unlock(&lockdep_lock);
66                 return 0;
67         }
68         return 1;
69 }
70
71 static inline int graph_unlock(void)
72 {
73         __raw_spin_unlock(&lockdep_lock);
74         return 0;
75 }
76
77 /*
78  * Turn lock debugging off and return with 0 if it was off already,
79  * and also release the graph lock:
80  */
81 static inline int debug_locks_off_graph_unlock(void)
82 {
83         int ret = debug_locks_off();
84
85         __raw_spin_unlock(&lockdep_lock);
86
87         return ret;
88 }
89
90 static int lockdep_initialized;
91
92 unsigned long nr_list_entries;
93 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
94
95 /*
96  * Allocate a lockdep entry. (assumes the graph_lock held, returns
97  * with NULL on failure)
98  */
99 static struct lock_list *alloc_list_entry(void)
100 {
101         if (nr_list_entries >= MAX_LOCKDEP_ENTRIES) {
102                 if (!debug_locks_off_graph_unlock())
103                         return NULL;
104
105                 printk("BUG: MAX_LOCKDEP_ENTRIES too low!\n");
106                 printk("turning off the locking correctness validator.\n");
107                 return NULL;
108         }
109         return list_entries + nr_list_entries++;
110 }
111
112 /*
113  * All data structures here are protected by the global debug_lock.
114  *
115  * Mutex key structs only get allocated, once during bootup, and never
116  * get freed - this significantly simplifies the debugging code.
117  */
118 unsigned long nr_lock_classes;
119 static struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
120
121 /*
122  * We keep a global list of all lock classes. The list only grows,
123  * never shrinks. The list is only accessed with the lockdep
124  * spinlock lock held.
125  */
126 LIST_HEAD(all_lock_classes);
127
128 /*
129  * The lockdep classes are in a hash-table as well, for fast lookup:
130  */
131 #define CLASSHASH_BITS          (MAX_LOCKDEP_KEYS_BITS - 1)
132 #define CLASSHASH_SIZE          (1UL << CLASSHASH_BITS)
133 #define CLASSHASH_MASK          (CLASSHASH_SIZE - 1)
134 #define __classhashfn(key)      ((((unsigned long)key >> CLASSHASH_BITS) + (unsigned long)key) & CLASSHASH_MASK)
135 #define classhashentry(key)     (classhash_table + __classhashfn((key)))
136
137 static struct list_head classhash_table[CLASSHASH_SIZE];
138
139 unsigned long nr_lock_chains;
140 static struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
141
142 /*
143  * We put the lock dependency chains into a hash-table as well, to cache
144  * their existence:
145  */
146 #define CHAINHASH_BITS          (MAX_LOCKDEP_CHAINS_BITS-1)
147 #define CHAINHASH_SIZE          (1UL << CHAINHASH_BITS)
148 #define CHAINHASH_MASK          (CHAINHASH_SIZE - 1)
149 #define __chainhashfn(chain) \
150                 (((chain >> CHAINHASH_BITS) + chain) & CHAINHASH_MASK)
151 #define chainhashentry(chain)   (chainhash_table + __chainhashfn((chain)))
152
153 static struct list_head chainhash_table[CHAINHASH_SIZE];
154
155 /*
156  * The hash key of the lock dependency chains is a hash itself too:
157  * it's a hash of all locks taken up to that lock, including that lock.
158  * It's a 64-bit hash, because it's important for the keys to be
159  * unique.
160  */
161 #define iterate_chain_key(key1, key2) \
162         (((key1) << MAX_LOCKDEP_KEYS_BITS) ^ \
163         ((key1) >> (64-MAX_LOCKDEP_KEYS_BITS)) ^ \
164         (key2))
165
166 void lockdep_off(void)
167 {
168         current->lockdep_recursion++;
169 }
170
171 EXPORT_SYMBOL(lockdep_off);
172
173 void lockdep_on(void)
174 {
175         current->lockdep_recursion--;
176 }
177
178 EXPORT_SYMBOL(lockdep_on);
179
180 /*
181  * Debugging switches:
182  */
183
184 #define VERBOSE                 0
185 #define VERY_VERBOSE            0
186
187 #if VERBOSE
188 # define HARDIRQ_VERBOSE        1
189 # define SOFTIRQ_VERBOSE        1
190 #else
191 # define HARDIRQ_VERBOSE        0
192 # define SOFTIRQ_VERBOSE        0
193 #endif
194
195 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
196 /*
197  * Quick filtering for interesting events:
198  */
199 static int class_filter(struct lock_class *class)
200 {
201 #if 0
202         /* Example */
203         if (class->name_version == 1 &&
204                         !strcmp(class->name, "lockname"))
205                 return 1;
206         if (class->name_version == 1 &&
207                         !strcmp(class->name, "&struct->lockfield"))
208                 return 1;
209 #endif
210         /* Filter everything else. 1 would be to allow everything else */
211         return 0;
212 }
213 #endif
214
215 static int verbose(struct lock_class *class)
216 {
217 #if VERBOSE
218         return class_filter(class);
219 #endif
220         return 0;
221 }
222
223 #ifdef CONFIG_TRACE_IRQFLAGS
224
225 static int hardirq_verbose(struct lock_class *class)
226 {
227 #if HARDIRQ_VERBOSE
228         return class_filter(class);
229 #endif
230         return 0;
231 }
232
233 static int softirq_verbose(struct lock_class *class)
234 {
235 #if SOFTIRQ_VERBOSE
236         return class_filter(class);
237 #endif
238         return 0;
239 }
240
241 #endif
242
243 /*
244  * Stack-trace: tightly packed array of stack backtrace
245  * addresses. Protected by the graph_lock.
246  */
247 unsigned long nr_stack_trace_entries;
248 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
249
250 static int save_trace(struct stack_trace *trace)
251 {
252         trace->nr_entries = 0;
253         trace->max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
254         trace->entries = stack_trace + nr_stack_trace_entries;
255
256         trace->skip = 3;
257         trace->all_contexts = 0;
258
259         save_stack_trace(trace, NULL);
260
261         trace->max_entries = trace->nr_entries;
262
263         nr_stack_trace_entries += trace->nr_entries;
264
265         if (nr_stack_trace_entries == MAX_STACK_TRACE_ENTRIES) {
266                 if (!debug_locks_off_graph_unlock())
267                         return 0;
268
269                 printk("BUG: MAX_STACK_TRACE_ENTRIES too low!\n");
270                 printk("turning off the locking correctness validator.\n");
271                 dump_stack();
272
273                 return 0;
274         }
275
276         return 1;
277 }
278
279 unsigned int nr_hardirq_chains;
280 unsigned int nr_softirq_chains;
281 unsigned int nr_process_chains;
282 unsigned int max_lockdep_depth;
283 unsigned int max_recursion_depth;
284
285 #ifdef CONFIG_DEBUG_LOCKDEP
286 /*
287  * We cannot printk in early bootup code. Not even early_printk()
288  * might work. So we mark any initialization errors and printk
289  * about it later on, in lockdep_info().
290  */
291 static int lockdep_init_error;
292
293 /*
294  * Various lockdep statistics:
295  */
296 atomic_t chain_lookup_hits;
297 atomic_t chain_lookup_misses;
298 atomic_t hardirqs_on_events;
299 atomic_t hardirqs_off_events;
300 atomic_t redundant_hardirqs_on;
301 atomic_t redundant_hardirqs_off;
302 atomic_t softirqs_on_events;
303 atomic_t softirqs_off_events;
304 atomic_t redundant_softirqs_on;
305 atomic_t redundant_softirqs_off;
306 atomic_t nr_unused_locks;
307 atomic_t nr_cyclic_checks;
308 atomic_t nr_cyclic_check_recursions;
309 atomic_t nr_find_usage_forwards_checks;
310 atomic_t nr_find_usage_forwards_recursions;
311 atomic_t nr_find_usage_backwards_checks;
312 atomic_t nr_find_usage_backwards_recursions;
313 # define debug_atomic_inc(ptr)          atomic_inc(ptr)
314 # define debug_atomic_dec(ptr)          atomic_dec(ptr)
315 # define debug_atomic_read(ptr)         atomic_read(ptr)
316 #else
317 # define debug_atomic_inc(ptr)          do { } while (0)
318 # define debug_atomic_dec(ptr)          do { } while (0)
319 # define debug_atomic_read(ptr)         0
320 #endif
321
322 /*
323  * Locking printouts:
324  */
325
326 static const char *usage_str[] =
327 {
328         [LOCK_USED] =                   "initial-use ",
329         [LOCK_USED_IN_HARDIRQ] =        "in-hardirq-W",
330         [LOCK_USED_IN_SOFTIRQ] =        "in-softirq-W",
331         [LOCK_ENABLED_SOFTIRQS] =       "softirq-on-W",
332         [LOCK_ENABLED_HARDIRQS] =       "hardirq-on-W",
333         [LOCK_USED_IN_HARDIRQ_READ] =   "in-hardirq-R",
334         [LOCK_USED_IN_SOFTIRQ_READ] =   "in-softirq-R",
335         [LOCK_ENABLED_SOFTIRQS_READ] =  "softirq-on-R",
336         [LOCK_ENABLED_HARDIRQS_READ] =  "hardirq-on-R",
337 };
338
339 const char * __get_key_name(struct lockdep_subclass_key *key, char *str)
340 {
341         unsigned long offs, size;
342         char *modname;
343
344         return kallsyms_lookup((unsigned long)key, &size, &offs, &modname, str);
345 }
346
347 void
348 get_usage_chars(struct lock_class *class, char *c1, char *c2, char *c3, char *c4)
349 {
350         *c1 = '.', *c2 = '.', *c3 = '.', *c4 = '.';
351
352         if (class->usage_mask & LOCKF_USED_IN_HARDIRQ)
353                 *c1 = '+';
354         else
355                 if (class->usage_mask & LOCKF_ENABLED_HARDIRQS)
356                         *c1 = '-';
357
358         if (class->usage_mask & LOCKF_USED_IN_SOFTIRQ)
359                 *c2 = '+';
360         else
361                 if (class->usage_mask & LOCKF_ENABLED_SOFTIRQS)
362                         *c2 = '-';
363
364         if (class->usage_mask & LOCKF_ENABLED_HARDIRQS_READ)
365                 *c3 = '-';
366         if (class->usage_mask & LOCKF_USED_IN_HARDIRQ_READ) {
367                 *c3 = '+';
368                 if (class->usage_mask & LOCKF_ENABLED_HARDIRQS_READ)
369                         *c3 = '?';
370         }
371
372         if (class->usage_mask & LOCKF_ENABLED_SOFTIRQS_READ)
373                 *c4 = '-';
374         if (class->usage_mask & LOCKF_USED_IN_SOFTIRQ_READ) {
375                 *c4 = '+';
376                 if (class->usage_mask & LOCKF_ENABLED_SOFTIRQS_READ)
377                         *c4 = '?';
378         }
379 }
380
381 static void print_lock_name(struct lock_class *class)
382 {
383         char str[KSYM_NAME_LEN + 1], c1, c2, c3, c4;
384         const char *name;
385
386         get_usage_chars(class, &c1, &c2, &c3, &c4);
387
388         name = class->name;
389         if (!name) {
390                 name = __get_key_name(class->key, str);
391                 printk(" (%s", name);
392         } else {
393                 printk(" (%s", name);
394                 if (class->name_version > 1)
395                         printk("#%d", class->name_version);
396                 if (class->subclass)
397                         printk("/%d", class->subclass);
398         }
399         printk("){%c%c%c%c}", c1, c2, c3, c4);
400 }
401
402 static void print_lockdep_cache(struct lockdep_map *lock)
403 {
404         const char *name;
405         char str[KSYM_NAME_LEN + 1];
406
407         name = lock->name;
408         if (!name)
409                 name = __get_key_name(lock->key->subkeys, str);
410
411         printk("%s", name);
412 }
413
414 static void print_lock(struct held_lock *hlock)
415 {
416         print_lock_name(hlock->class);
417         printk(", at: ");
418         print_ip_sym(hlock->acquire_ip);
419 }
420
421 static void lockdep_print_held_locks(struct task_struct *curr)
422 {
423         int i, depth = curr->lockdep_depth;
424
425         if (!depth) {
426                 printk("no locks held by %s/%d.\n", curr->comm, curr->pid);
427                 return;
428         }
429         printk("%d lock%s held by %s/%d:\n",
430                 depth, depth > 1 ? "s" : "", curr->comm, curr->pid);
431
432         for (i = 0; i < depth; i++) {
433                 printk(" #%d: ", i);
434                 print_lock(curr->held_locks + i);
435         }
436 }
437
438 static void print_lock_class_header(struct lock_class *class, int depth)
439 {
440         int bit;
441
442         printk("%*s->", depth, "");
443         print_lock_name(class);
444         printk(" ops: %lu", class->ops);
445         printk(" {\n");
446
447         for (bit = 0; bit < LOCK_USAGE_STATES; bit++) {
448                 if (class->usage_mask & (1 << bit)) {
449                         int len = depth;
450
451                         len += printk("%*s   %s", depth, "", usage_str[bit]);
452                         len += printk(" at:\n");
453                         print_stack_trace(class->usage_traces + bit, len);
454                 }
455         }
456         printk("%*s }\n", depth, "");
457
458         printk("%*s ... key      at: ",depth,"");
459         print_ip_sym((unsigned long)class->key);
460 }
461
462 /*
463  * printk all lock dependencies starting at <entry>:
464  */
465 static void print_lock_dependencies(struct lock_class *class, int depth)
466 {
467         struct lock_list *entry;
468
469         if (DEBUG_LOCKS_WARN_ON(depth >= 20))
470                 return;
471
472         print_lock_class_header(class, depth);
473
474         list_for_each_entry(entry, &class->locks_after, entry) {
475                 if (DEBUG_LOCKS_WARN_ON(!entry->class))
476                         return;
477
478                 print_lock_dependencies(entry->class, depth + 1);
479
480                 printk("%*s ... acquired at:\n",depth,"");
481                 print_stack_trace(&entry->trace, 2);
482                 printk("\n");
483         }
484 }
485
486 /*
487  * Add a new dependency to the head of the list:
488  */
489 static int add_lock_to_list(struct lock_class *class, struct lock_class *this,
490                             struct list_head *head, unsigned long ip)
491 {
492         struct lock_list *entry;
493         /*
494          * Lock not present yet - get a new dependency struct and
495          * add it to the list:
496          */
497         entry = alloc_list_entry();
498         if (!entry)
499                 return 0;
500
501         entry->class = this;
502         if (!save_trace(&entry->trace))
503                 return 0;
504
505         /*
506          * Since we never remove from the dependency list, the list can
507          * be walked lockless by other CPUs, it's only allocation
508          * that must be protected by the spinlock. But this also means
509          * we must make new entries visible only once writes to the
510          * entry become visible - hence the RCU op:
511          */
512         list_add_tail_rcu(&entry->entry, head);
513
514         return 1;
515 }
516
517 /*
518  * Recursive, forwards-direction lock-dependency checking, used for
519  * both noncyclic checking and for hardirq-unsafe/softirq-unsafe
520  * checking.
521  *
522  * (to keep the stackframe of the recursive functions small we
523  *  use these global variables, and we also mark various helper
524  *  functions as noinline.)
525  */
526 static struct held_lock *check_source, *check_target;
527
528 /*
529  * Print a dependency chain entry (this is only done when a deadlock
530  * has been detected):
531  */
532 static noinline int
533 print_circular_bug_entry(struct lock_list *target, unsigned int depth)
534 {
535         if (debug_locks_silent)
536                 return 0;
537         printk("\n-> #%u", depth);
538         print_lock_name(target->class);
539         printk(":\n");
540         print_stack_trace(&target->trace, 6);
541
542         return 0;
543 }
544
545 static void print_kernel_version(void)
546 {
547         printk("%s %.*s\n", init_utsname()->release,
548                 (int)strcspn(init_utsname()->version, " "),
549                 init_utsname()->version);
550 }
551
552 /*
553  * When a circular dependency is detected, print the
554  * header first:
555  */
556 static noinline int
557 print_circular_bug_header(struct lock_list *entry, unsigned int depth)
558 {
559         struct task_struct *curr = current;
560
561         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
562                 return 0;
563
564         printk("\n=======================================================\n");
565         printk(  "[ INFO: possible circular locking dependency detected ]\n");
566         print_kernel_version();
567         printk(  "-------------------------------------------------------\n");
568         printk("%s/%d is trying to acquire lock:\n",
569                 curr->comm, curr->pid);
570         print_lock(check_source);
571         printk("\nbut task is already holding lock:\n");
572         print_lock(check_target);
573         printk("\nwhich lock already depends on the new lock.\n\n");
574         printk("\nthe existing dependency chain (in reverse order) is:\n");
575
576         print_circular_bug_entry(entry, depth);
577
578         return 0;
579 }
580
581 static noinline int print_circular_bug_tail(void)
582 {
583         struct task_struct *curr = current;
584         struct lock_list this;
585
586         if (debug_locks_silent)
587                 return 0;
588
589         this.class = check_source->class;
590         if (!save_trace(&this.trace))
591                 return 0;
592
593         print_circular_bug_entry(&this, 0);
594
595         printk("\nother info that might help us debug this:\n\n");
596         lockdep_print_held_locks(curr);
597
598         printk("\nstack backtrace:\n");
599         dump_stack();
600
601         return 0;
602 }
603
604 #define RECURSION_LIMIT 40
605
606 static int noinline print_infinite_recursion_bug(void)
607 {
608         if (!debug_locks_off_graph_unlock())
609                 return 0;
610
611         WARN_ON(1);
612
613         return 0;
614 }
615
616 /*
617  * Prove that the dependency graph starting at <entry> can not
618  * lead to <target>. Print an error and return 0 if it does.
619  */
620 static noinline int
621 check_noncircular(struct lock_class *source, unsigned int depth)
622 {
623         struct lock_list *entry;
624
625         debug_atomic_inc(&nr_cyclic_check_recursions);
626         if (depth > max_recursion_depth)
627                 max_recursion_depth = depth;
628         if (depth >= RECURSION_LIMIT)
629                 return print_infinite_recursion_bug();
630         /*
631          * Check this lock's dependency list:
632          */
633         list_for_each_entry(entry, &source->locks_after, entry) {
634                 if (entry->class == check_target->class)
635                         return print_circular_bug_header(entry, depth+1);
636                 debug_atomic_inc(&nr_cyclic_checks);
637                 if (!check_noncircular(entry->class, depth+1))
638                         return print_circular_bug_entry(entry, depth+1);
639         }
640         return 1;
641 }
642
643 static int very_verbose(struct lock_class *class)
644 {
645 #if VERY_VERBOSE
646         return class_filter(class);
647 #endif
648         return 0;
649 }
650 #ifdef CONFIG_TRACE_IRQFLAGS
651
652 /*
653  * Forwards and backwards subgraph searching, for the purposes of
654  * proving that two subgraphs can be connected by a new dependency
655  * without creating any illegal irq-safe -> irq-unsafe lock dependency.
656  */
657 static enum lock_usage_bit find_usage_bit;
658 static struct lock_class *forwards_match, *backwards_match;
659
660 /*
661  * Find a node in the forwards-direction dependency sub-graph starting
662  * at <source> that matches <find_usage_bit>.
663  *
664  * Return 2 if such a node exists in the subgraph, and put that node
665  * into <forwards_match>.
666  *
667  * Return 1 otherwise and keep <forwards_match> unchanged.
668  * Return 0 on error.
669  */
670 static noinline int
671 find_usage_forwards(struct lock_class *source, unsigned int depth)
672 {
673         struct lock_list *entry;
674         int ret;
675
676         if (depth > max_recursion_depth)
677                 max_recursion_depth = depth;
678         if (depth >= RECURSION_LIMIT)
679                 return print_infinite_recursion_bug();
680
681         debug_atomic_inc(&nr_find_usage_forwards_checks);
682         if (source->usage_mask & (1 << find_usage_bit)) {
683                 forwards_match = source;
684                 return 2;
685         }
686
687         /*
688          * Check this lock's dependency list:
689          */
690         list_for_each_entry(entry, &source->locks_after, entry) {
691                 debug_atomic_inc(&nr_find_usage_forwards_recursions);
692                 ret = find_usage_forwards(entry->class, depth+1);
693                 if (ret == 2 || ret == 0)
694                         return ret;
695         }
696         return 1;
697 }
698
699 /*
700  * Find a node in the backwards-direction dependency sub-graph starting
701  * at <source> that matches <find_usage_bit>.
702  *
703  * Return 2 if such a node exists in the subgraph, and put that node
704  * into <backwards_match>.
705  *
706  * Return 1 otherwise and keep <backwards_match> unchanged.
707  * Return 0 on error.
708  */
709 static noinline int
710 find_usage_backwards(struct lock_class *source, unsigned int depth)
711 {
712         struct lock_list *entry;
713         int ret;
714
715         if (depth > max_recursion_depth)
716                 max_recursion_depth = depth;
717         if (depth >= RECURSION_LIMIT)
718                 return print_infinite_recursion_bug();
719
720         debug_atomic_inc(&nr_find_usage_backwards_checks);
721         if (source->usage_mask & (1 << find_usage_bit)) {
722                 backwards_match = source;
723                 return 2;
724         }
725
726         /*
727          * Check this lock's dependency list:
728          */
729         list_for_each_entry(entry, &source->locks_before, entry) {
730                 debug_atomic_inc(&nr_find_usage_backwards_recursions);
731                 ret = find_usage_backwards(entry->class, depth+1);
732                 if (ret == 2 || ret == 0)
733                         return ret;
734         }
735         return 1;
736 }
737
738 static int
739 print_bad_irq_dependency(struct task_struct *curr,
740                          struct held_lock *prev,
741                          struct held_lock *next,
742                          enum lock_usage_bit bit1,
743                          enum lock_usage_bit bit2,
744                          const char *irqclass)
745 {
746         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
747                 return 0;
748
749         printk("\n======================================================\n");
750         printk(  "[ INFO: %s-safe -> %s-unsafe lock order detected ]\n",
751                 irqclass, irqclass);
752         print_kernel_version();
753         printk(  "------------------------------------------------------\n");
754         printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
755                 curr->comm, curr->pid,
756                 curr->hardirq_context, hardirq_count() >> HARDIRQ_SHIFT,
757                 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
758                 curr->hardirqs_enabled,
759                 curr->softirqs_enabled);
760         print_lock(next);
761
762         printk("\nand this task is already holding:\n");
763         print_lock(prev);
764         printk("which would create a new lock dependency:\n");
765         print_lock_name(prev->class);
766         printk(" ->");
767         print_lock_name(next->class);
768         printk("\n");
769
770         printk("\nbut this new dependency connects a %s-irq-safe lock:\n",
771                 irqclass);
772         print_lock_name(backwards_match);
773         printk("\n... which became %s-irq-safe at:\n", irqclass);
774
775         print_stack_trace(backwards_match->usage_traces + bit1, 1);
776
777         printk("\nto a %s-irq-unsafe lock:\n", irqclass);
778         print_lock_name(forwards_match);
779         printk("\n... which became %s-irq-unsafe at:\n", irqclass);
780         printk("...");
781
782         print_stack_trace(forwards_match->usage_traces + bit2, 1);
783
784         printk("\nother info that might help us debug this:\n\n");
785         lockdep_print_held_locks(curr);
786
787         printk("\nthe %s-irq-safe lock's dependencies:\n", irqclass);
788         print_lock_dependencies(backwards_match, 0);
789
790         printk("\nthe %s-irq-unsafe lock's dependencies:\n", irqclass);
791         print_lock_dependencies(forwards_match, 0);
792
793         printk("\nstack backtrace:\n");
794         dump_stack();
795
796         return 0;
797 }
798
799 static int
800 check_usage(struct task_struct *curr, struct held_lock *prev,
801             struct held_lock *next, enum lock_usage_bit bit_backwards,
802             enum lock_usage_bit bit_forwards, const char *irqclass)
803 {
804         int ret;
805
806         find_usage_bit = bit_backwards;
807         /* fills in <backwards_match> */
808         ret = find_usage_backwards(prev->class, 0);
809         if (!ret || ret == 1)
810                 return ret;
811
812         find_usage_bit = bit_forwards;
813         ret = find_usage_forwards(next->class, 0);
814         if (!ret || ret == 1)
815                 return ret;
816         /* ret == 2 */
817         return print_bad_irq_dependency(curr, prev, next,
818                         bit_backwards, bit_forwards, irqclass);
819 }
820
821 #endif
822
823 static int
824 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
825                    struct held_lock *next)
826 {
827         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
828                 return 0;
829
830         printk("\n=============================================\n");
831         printk(  "[ INFO: possible recursive locking detected ]\n");
832         print_kernel_version();
833         printk(  "---------------------------------------------\n");
834         printk("%s/%d is trying to acquire lock:\n",
835                 curr->comm, curr->pid);
836         print_lock(next);
837         printk("\nbut task is already holding lock:\n");
838         print_lock(prev);
839
840         printk("\nother info that might help us debug this:\n");
841         lockdep_print_held_locks(curr);
842
843         printk("\nstack backtrace:\n");
844         dump_stack();
845
846         return 0;
847 }
848
849 /*
850  * Check whether we are holding such a class already.
851  *
852  * (Note that this has to be done separately, because the graph cannot
853  * detect such classes of deadlocks.)
854  *
855  * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
856  */
857 static int
858 check_deadlock(struct task_struct *curr, struct held_lock *next,
859                struct lockdep_map *next_instance, int read)
860 {
861         struct held_lock *prev;
862         int i;
863
864         for (i = 0; i < curr->lockdep_depth; i++) {
865                 prev = curr->held_locks + i;
866                 if (prev->class != next->class)
867                         continue;
868                 /*
869                  * Allow read-after-read recursion of the same
870                  * lock class (i.e. read_lock(lock)+read_lock(lock)):
871                  */
872                 if ((read == 2) && prev->read)
873                         return 2;
874                 return print_deadlock_bug(curr, prev, next);
875         }
876         return 1;
877 }
878
879 /*
880  * There was a chain-cache miss, and we are about to add a new dependency
881  * to a previous lock. We recursively validate the following rules:
882  *
883  *  - would the adding of the <prev> -> <next> dependency create a
884  *    circular dependency in the graph? [== circular deadlock]
885  *
886  *  - does the new prev->next dependency connect any hardirq-safe lock
887  *    (in the full backwards-subgraph starting at <prev>) with any
888  *    hardirq-unsafe lock (in the full forwards-subgraph starting at
889  *    <next>)? [== illegal lock inversion with hardirq contexts]
890  *
891  *  - does the new prev->next dependency connect any softirq-safe lock
892  *    (in the full backwards-subgraph starting at <prev>) with any
893  *    softirq-unsafe lock (in the full forwards-subgraph starting at
894  *    <next>)? [== illegal lock inversion with softirq contexts]
895  *
896  * any of these scenarios could lead to a deadlock.
897  *
898  * Then if all the validations pass, we add the forwards and backwards
899  * dependency.
900  */
901 static int
902 check_prev_add(struct task_struct *curr, struct held_lock *prev,
903                struct held_lock *next)
904 {
905         struct lock_list *entry;
906         int ret;
907
908         /*
909          * Prove that the new <prev> -> <next> dependency would not
910          * create a circular dependency in the graph. (We do this by
911          * forward-recursing into the graph starting at <next>, and
912          * checking whether we can reach <prev>.)
913          *
914          * We are using global variables to control the recursion, to
915          * keep the stackframe size of the recursive functions low:
916          */
917         check_source = next;
918         check_target = prev;
919         if (!(check_noncircular(next->class, 0)))
920                 return print_circular_bug_tail();
921
922 #ifdef CONFIG_TRACE_IRQFLAGS
923         /*
924          * Prove that the new dependency does not connect a hardirq-safe
925          * lock with a hardirq-unsafe lock - to achieve this we search
926          * the backwards-subgraph starting at <prev>, and the
927          * forwards-subgraph starting at <next>:
928          */
929         if (!check_usage(curr, prev, next, LOCK_USED_IN_HARDIRQ,
930                                         LOCK_ENABLED_HARDIRQS, "hard"))
931                 return 0;
932
933         /*
934          * Prove that the new dependency does not connect a hardirq-safe-read
935          * lock with a hardirq-unsafe lock - to achieve this we search
936          * the backwards-subgraph starting at <prev>, and the
937          * forwards-subgraph starting at <next>:
938          */
939         if (!check_usage(curr, prev, next, LOCK_USED_IN_HARDIRQ_READ,
940                                         LOCK_ENABLED_HARDIRQS, "hard-read"))
941                 return 0;
942
943         /*
944          * Prove that the new dependency does not connect a softirq-safe
945          * lock with a softirq-unsafe lock - to achieve this we search
946          * the backwards-subgraph starting at <prev>, and the
947          * forwards-subgraph starting at <next>:
948          */
949         if (!check_usage(curr, prev, next, LOCK_USED_IN_SOFTIRQ,
950                                         LOCK_ENABLED_SOFTIRQS, "soft"))
951                 return 0;
952         /*
953          * Prove that the new dependency does not connect a softirq-safe-read
954          * lock with a softirq-unsafe lock - to achieve this we search
955          * the backwards-subgraph starting at <prev>, and the
956          * forwards-subgraph starting at <next>:
957          */
958         if (!check_usage(curr, prev, next, LOCK_USED_IN_SOFTIRQ_READ,
959                                         LOCK_ENABLED_SOFTIRQS, "soft"))
960                 return 0;
961 #endif
962         /*
963          * For recursive read-locks we do all the dependency checks,
964          * but we dont store read-triggered dependencies (only
965          * write-triggered dependencies). This ensures that only the
966          * write-side dependencies matter, and that if for example a
967          * write-lock never takes any other locks, then the reads are
968          * equivalent to a NOP.
969          */
970         if (next->read == 2 || prev->read == 2)
971                 return 1;
972         /*
973          * Is the <prev> -> <next> dependency already present?
974          *
975          * (this may occur even though this is a new chain: consider
976          *  e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
977          *  chains - the second one will be new, but L1 already has
978          *  L2 added to its dependency list, due to the first chain.)
979          */
980         list_for_each_entry(entry, &prev->class->locks_after, entry) {
981                 if (entry->class == next->class)
982                         return 2;
983         }
984
985         /*
986          * Ok, all validations passed, add the new lock
987          * to the previous lock's dependency list:
988          */
989         ret = add_lock_to_list(prev->class, next->class,
990                                &prev->class->locks_after, next->acquire_ip);
991         if (!ret)
992                 return 0;
993
994         ret = add_lock_to_list(next->class, prev->class,
995                                &next->class->locks_before, next->acquire_ip);
996         if (!ret)
997                 return 0;
998
999         /*
1000          * Debugging printouts:
1001          */
1002         if (verbose(prev->class) || verbose(next->class)) {
1003                 graph_unlock();
1004                 printk("\n new dependency: ");
1005                 print_lock_name(prev->class);
1006                 printk(" => ");
1007                 print_lock_name(next->class);
1008                 printk("\n");
1009                 dump_stack();
1010                 return graph_lock();
1011         }
1012         return 1;
1013 }
1014
1015 /*
1016  * Add the dependency to all directly-previous locks that are 'relevant'.
1017  * The ones that are relevant are (in increasing distance from curr):
1018  * all consecutive trylock entries and the final non-trylock entry - or
1019  * the end of this context's lock-chain - whichever comes first.
1020  */
1021 static int
1022 check_prevs_add(struct task_struct *curr, struct held_lock *next)
1023 {
1024         int depth = curr->lockdep_depth;
1025         struct held_lock *hlock;
1026
1027         /*
1028          * Debugging checks.
1029          *
1030          * Depth must not be zero for a non-head lock:
1031          */
1032         if (!depth)
1033                 goto out_bug;
1034         /*
1035          * At least two relevant locks must exist for this
1036          * to be a head:
1037          */
1038         if (curr->held_locks[depth].irq_context !=
1039                         curr->held_locks[depth-1].irq_context)
1040                 goto out_bug;
1041
1042         for (;;) {
1043                 hlock = curr->held_locks + depth-1;
1044                 /*
1045                  * Only non-recursive-read entries get new dependencies
1046                  * added:
1047                  */
1048                 if (hlock->read != 2) {
1049                         if (!check_prev_add(curr, hlock, next))
1050                                 return 0;
1051                         /*
1052                          * Stop after the first non-trylock entry,
1053                          * as non-trylock entries have added their
1054                          * own direct dependencies already, so this
1055                          * lock is connected to them indirectly:
1056                          */
1057                         if (!hlock->trylock)
1058                                 break;
1059                 }
1060                 depth--;
1061                 /*
1062                  * End of lock-stack?
1063                  */
1064                 if (!depth)
1065                         break;
1066                 /*
1067                  * Stop the search if we cross into another context:
1068                  */
1069                 if (curr->held_locks[depth].irq_context !=
1070                                 curr->held_locks[depth-1].irq_context)
1071                         break;
1072         }
1073         return 1;
1074 out_bug:
1075         if (!debug_locks_off_graph_unlock())
1076                 return 0;
1077
1078         WARN_ON(1);
1079
1080         return 0;
1081 }
1082
1083
1084 /*
1085  * Is this the address of a static object:
1086  */
1087 static int static_obj(void *obj)
1088 {
1089         unsigned long start = (unsigned long) &_stext,
1090                       end   = (unsigned long) &_end,
1091                       addr  = (unsigned long) obj;
1092 #ifdef CONFIG_SMP
1093         int i;
1094 #endif
1095
1096         /*
1097          * static variable?
1098          */
1099         if ((addr >= start) && (addr < end))
1100                 return 1;
1101
1102 #ifdef CONFIG_SMP
1103         /*
1104          * percpu var?
1105          */
1106         for_each_possible_cpu(i) {
1107                 start = (unsigned long) &__per_cpu_start + per_cpu_offset(i);
1108                 end   = (unsigned long) &__per_cpu_start + PERCPU_ENOUGH_ROOM
1109                                         + per_cpu_offset(i);
1110
1111                 if ((addr >= start) && (addr < end))
1112                         return 1;
1113         }
1114 #endif
1115
1116         /*
1117          * module var?
1118          */
1119         return is_module_address(addr);
1120 }
1121
1122 /*
1123  * To make lock name printouts unique, we calculate a unique
1124  * class->name_version generation counter:
1125  */
1126 static int count_matching_names(struct lock_class *new_class)
1127 {
1128         struct lock_class *class;
1129         int count = 0;
1130
1131         if (!new_class->name)
1132                 return 0;
1133
1134         list_for_each_entry(class, &all_lock_classes, lock_entry) {
1135                 if (new_class->key - new_class->subclass == class->key)
1136                         return class->name_version;
1137                 if (class->name && !strcmp(class->name, new_class->name))
1138                         count = max(count, class->name_version);
1139         }
1140
1141         return count + 1;
1142 }
1143
1144 /*
1145  * Register a lock's class in the hash-table, if the class is not present
1146  * yet. Otherwise we look it up. We cache the result in the lock object
1147  * itself, so actual lookup of the hash should be once per lock object.
1148  */
1149 static inline struct lock_class *
1150 look_up_lock_class(struct lockdep_map *lock, unsigned int subclass)
1151 {
1152         struct lockdep_subclass_key *key;
1153         struct list_head *hash_head;
1154         struct lock_class *class;
1155
1156 #ifdef CONFIG_DEBUG_LOCKDEP
1157         /*
1158          * If the architecture calls into lockdep before initializing
1159          * the hashes then we'll warn about it later. (we cannot printk
1160          * right now)
1161          */
1162         if (unlikely(!lockdep_initialized)) {
1163                 lockdep_init();
1164                 lockdep_init_error = 1;
1165         }
1166 #endif
1167
1168         /*
1169          * Static locks do not have their class-keys yet - for them the key
1170          * is the lock object itself:
1171          */
1172         if (unlikely(!lock->key))
1173                 lock->key = (void *)lock;
1174
1175         /*
1176          * NOTE: the class-key must be unique. For dynamic locks, a static
1177          * lock_class_key variable is passed in through the mutex_init()
1178          * (or spin_lock_init()) call - which acts as the key. For static
1179          * locks we use the lock object itself as the key.
1180          */
1181         BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(struct lock_class));
1182
1183         key = lock->key->subkeys + subclass;
1184
1185         hash_head = classhashentry(key);
1186
1187         /*
1188          * We can walk the hash lockfree, because the hash only
1189          * grows, and we are careful when adding entries to the end:
1190          */
1191         list_for_each_entry(class, hash_head, hash_entry)
1192                 if (class->key == key)
1193                         return class;
1194
1195         return NULL;
1196 }
1197
1198 /*
1199  * Register a lock's class in the hash-table, if the class is not present
1200  * yet. Otherwise we look it up. We cache the result in the lock object
1201  * itself, so actual lookup of the hash should be once per lock object.
1202  */
1203 static inline struct lock_class *
1204 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
1205 {
1206         struct lockdep_subclass_key *key;
1207         struct list_head *hash_head;
1208         struct lock_class *class;
1209         unsigned long flags;
1210
1211         class = look_up_lock_class(lock, subclass);
1212         if (likely(class))
1213                 return class;
1214
1215         /*
1216          * Debug-check: all keys must be persistent!
1217          */
1218         if (!static_obj(lock->key)) {
1219                 debug_locks_off();
1220                 printk("INFO: trying to register non-static key.\n");
1221                 printk("the code is fine but needs lockdep annotation.\n");
1222                 printk("turning off the locking correctness validator.\n");
1223                 dump_stack();
1224
1225                 return NULL;
1226         }
1227
1228         key = lock->key->subkeys + subclass;
1229         hash_head = classhashentry(key);
1230
1231         raw_local_irq_save(flags);
1232         if (!graph_lock()) {
1233                 raw_local_irq_restore(flags);
1234                 return NULL;
1235         }
1236         /*
1237          * We have to do the hash-walk again, to avoid races
1238          * with another CPU:
1239          */
1240         list_for_each_entry(class, hash_head, hash_entry)
1241                 if (class->key == key)
1242                         goto out_unlock_set;
1243         /*
1244          * Allocate a new key from the static array, and add it to
1245          * the hash:
1246          */
1247         if (nr_lock_classes >= MAX_LOCKDEP_KEYS) {
1248                 if (!debug_locks_off_graph_unlock()) {
1249                         raw_local_irq_restore(flags);
1250                         return NULL;
1251                 }
1252                 raw_local_irq_restore(flags);
1253
1254                 printk("BUG: MAX_LOCKDEP_KEYS too low!\n");
1255                 printk("turning off the locking correctness validator.\n");
1256                 return NULL;
1257         }
1258         class = lock_classes + nr_lock_classes++;
1259         debug_atomic_inc(&nr_unused_locks);
1260         class->key = key;
1261         class->name = lock->name;
1262         class->subclass = subclass;
1263         INIT_LIST_HEAD(&class->lock_entry);
1264         INIT_LIST_HEAD(&class->locks_before);
1265         INIT_LIST_HEAD(&class->locks_after);
1266         class->name_version = count_matching_names(class);
1267         /*
1268          * We use RCU's safe list-add method to make
1269          * parallel walking of the hash-list safe:
1270          */
1271         list_add_tail_rcu(&class->hash_entry, hash_head);
1272
1273         if (verbose(class)) {
1274                 graph_unlock();
1275                 raw_local_irq_restore(flags);
1276
1277                 printk("\nnew class %p: %s", class->key, class->name);
1278                 if (class->name_version > 1)
1279                         printk("#%d", class->name_version);
1280                 printk("\n");
1281                 dump_stack();
1282
1283                 raw_local_irq_save(flags);
1284                 if (!graph_lock()) {
1285                         raw_local_irq_restore(flags);
1286                         return NULL;
1287                 }
1288         }
1289 out_unlock_set:
1290         graph_unlock();
1291         raw_local_irq_restore(flags);
1292
1293         if (!subclass || force)
1294                 lock->class_cache = class;
1295
1296         DEBUG_LOCKS_WARN_ON(class->subclass != subclass);
1297
1298         return class;
1299 }
1300
1301 /*
1302  * Look up a dependency chain. If the key is not present yet then
1303  * add it and return 0 - in this case the new dependency chain is
1304  * validated. If the key is already hashed, return 1.
1305  */
1306 static inline int lookup_chain_cache(u64 chain_key, struct lock_class *class)
1307 {
1308         struct list_head *hash_head = chainhashentry(chain_key);
1309         struct lock_chain *chain;
1310
1311         DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1312         /*
1313          * We can walk it lock-free, because entries only get added
1314          * to the hash:
1315          */
1316         list_for_each_entry(chain, hash_head, entry) {
1317                 if (chain->chain_key == chain_key) {
1318 cache_hit:
1319                         debug_atomic_inc(&chain_lookup_hits);
1320                         if (very_verbose(class))
1321                                 printk("\nhash chain already cached, key: %016Lx tail class: [%p] %s\n", chain_key, class->key, class->name);
1322                         return 0;
1323                 }
1324         }
1325         if (very_verbose(class))
1326                 printk("\nnew hash chain, key: %016Lx tail class: [%p] %s\n", chain_key, class->key, class->name);
1327         /*
1328          * Allocate a new chain entry from the static array, and add
1329          * it to the hash:
1330          */
1331         if (!graph_lock())
1332                 return 0;
1333         /*
1334          * We have to walk the chain again locked - to avoid duplicates:
1335          */
1336         list_for_each_entry(chain, hash_head, entry) {
1337                 if (chain->chain_key == chain_key) {
1338                         graph_unlock();
1339                         goto cache_hit;
1340                 }
1341         }
1342         if (unlikely(nr_lock_chains >= MAX_LOCKDEP_CHAINS)) {
1343                 if (!debug_locks_off_graph_unlock())
1344                         return 0;
1345
1346                 printk("BUG: MAX_LOCKDEP_CHAINS too low!\n");
1347                 printk("turning off the locking correctness validator.\n");
1348                 return 0;
1349         }
1350         chain = lock_chains + nr_lock_chains++;
1351         chain->chain_key = chain_key;
1352         list_add_tail_rcu(&chain->entry, hash_head);
1353         debug_atomic_inc(&chain_lookup_misses);
1354 #ifdef CONFIG_TRACE_IRQFLAGS
1355         if (current->hardirq_context)
1356                 nr_hardirq_chains++;
1357         else {
1358                 if (current->softirq_context)
1359                         nr_softirq_chains++;
1360                 else
1361                         nr_process_chains++;
1362         }
1363 #else
1364         nr_process_chains++;
1365 #endif
1366
1367         return 1;
1368 }
1369
1370 /*
1371  * We are building curr_chain_key incrementally, so double-check
1372  * it from scratch, to make sure that it's done correctly:
1373  */
1374 static void check_chain_key(struct task_struct *curr)
1375 {
1376 #ifdef CONFIG_DEBUG_LOCKDEP
1377         struct held_lock *hlock, *prev_hlock = NULL;
1378         unsigned int i, id;
1379         u64 chain_key = 0;
1380
1381         for (i = 0; i < curr->lockdep_depth; i++) {
1382                 hlock = curr->held_locks + i;
1383                 if (chain_key != hlock->prev_chain_key) {
1384                         debug_locks_off();
1385                         printk("hm#1, depth: %u [%u], %016Lx != %016Lx\n",
1386                                 curr->lockdep_depth, i,
1387                                 (unsigned long long)chain_key,
1388                                 (unsigned long long)hlock->prev_chain_key);
1389                         WARN_ON(1);
1390                         return;
1391                 }
1392                 id = hlock->class - lock_classes;
1393                 DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS);
1394                 if (prev_hlock && (prev_hlock->irq_context !=
1395                                                         hlock->irq_context))
1396                         chain_key = 0;
1397                 chain_key = iterate_chain_key(chain_key, id);
1398                 prev_hlock = hlock;
1399         }
1400         if (chain_key != curr->curr_chain_key) {
1401                 debug_locks_off();
1402                 printk("hm#2, depth: %u [%u], %016Lx != %016Lx\n",
1403                         curr->lockdep_depth, i,
1404                         (unsigned long long)chain_key,
1405                         (unsigned long long)curr->curr_chain_key);
1406                 WARN_ON(1);
1407         }
1408 #endif
1409 }
1410
1411 #ifdef CONFIG_TRACE_IRQFLAGS
1412
1413 /*
1414  * print irq inversion bug:
1415  */
1416 static int
1417 print_irq_inversion_bug(struct task_struct *curr, struct lock_class *other,
1418                         struct held_lock *this, int forwards,
1419                         const char *irqclass)
1420 {
1421         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1422                 return 0;
1423
1424         printk("\n=========================================================\n");
1425         printk(  "[ INFO: possible irq lock inversion dependency detected ]\n");
1426         print_kernel_version();
1427         printk(  "---------------------------------------------------------\n");
1428         printk("%s/%d just changed the state of lock:\n",
1429                 curr->comm, curr->pid);
1430         print_lock(this);
1431         if (forwards)
1432                 printk("but this lock took another, %s-irq-unsafe lock in the past:\n", irqclass);
1433         else
1434                 printk("but this lock was taken by another, %s-irq-safe lock in the past:\n", irqclass);
1435         print_lock_name(other);
1436         printk("\n\nand interrupts could create inverse lock ordering between them.\n\n");
1437
1438         printk("\nother info that might help us debug this:\n");
1439         lockdep_print_held_locks(curr);
1440
1441         printk("\nthe first lock's dependencies:\n");
1442         print_lock_dependencies(this->class, 0);
1443
1444         printk("\nthe second lock's dependencies:\n");
1445         print_lock_dependencies(other, 0);
1446
1447         printk("\nstack backtrace:\n");
1448         dump_stack();
1449
1450         return 0;
1451 }
1452
1453 /*
1454  * Prove that in the forwards-direction subgraph starting at <this>
1455  * there is no lock matching <mask>:
1456  */
1457 static int
1458 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
1459                      enum lock_usage_bit bit, const char *irqclass)
1460 {
1461         int ret;
1462
1463         find_usage_bit = bit;
1464         /* fills in <forwards_match> */
1465         ret = find_usage_forwards(this->class, 0);
1466         if (!ret || ret == 1)
1467                 return ret;
1468
1469         return print_irq_inversion_bug(curr, forwards_match, this, 1, irqclass);
1470 }
1471
1472 /*
1473  * Prove that in the backwards-direction subgraph starting at <this>
1474  * there is no lock matching <mask>:
1475  */
1476 static int
1477 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
1478                       enum lock_usage_bit bit, const char *irqclass)
1479 {
1480         int ret;
1481
1482         find_usage_bit = bit;
1483         /* fills in <backwards_match> */
1484         ret = find_usage_backwards(this->class, 0);
1485         if (!ret || ret == 1)
1486                 return ret;
1487
1488         return print_irq_inversion_bug(curr, backwards_match, this, 0, irqclass);
1489 }
1490
1491 void print_irqtrace_events(struct task_struct *curr)
1492 {
1493         printk("irq event stamp: %u\n", curr->irq_events);
1494         printk("hardirqs last  enabled at (%u): ", curr->hardirq_enable_event);
1495         print_ip_sym(curr->hardirq_enable_ip);
1496         printk("hardirqs last disabled at (%u): ", curr->hardirq_disable_event);
1497         print_ip_sym(curr->hardirq_disable_ip);
1498         printk("softirqs last  enabled at (%u): ", curr->softirq_enable_event);
1499         print_ip_sym(curr->softirq_enable_ip);
1500         printk("softirqs last disabled at (%u): ", curr->softirq_disable_event);
1501         print_ip_sym(curr->softirq_disable_ip);
1502 }
1503
1504 #endif
1505
1506 static int
1507 print_usage_bug(struct task_struct *curr, struct held_lock *this,
1508                 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
1509 {
1510         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1511                 return 0;
1512
1513         printk("\n=================================\n");
1514         printk(  "[ INFO: inconsistent lock state ]\n");
1515         print_kernel_version();
1516         printk(  "---------------------------------\n");
1517
1518         printk("inconsistent {%s} -> {%s} usage.\n",
1519                 usage_str[prev_bit], usage_str[new_bit]);
1520
1521         printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
1522                 curr->comm, curr->pid,
1523                 trace_hardirq_context(curr), hardirq_count() >> HARDIRQ_SHIFT,
1524                 trace_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
1525                 trace_hardirqs_enabled(curr),
1526                 trace_softirqs_enabled(curr));
1527         print_lock(this);
1528
1529         printk("{%s} state was registered at:\n", usage_str[prev_bit]);
1530         print_stack_trace(this->class->usage_traces + prev_bit, 1);
1531
1532         print_irqtrace_events(curr);
1533         printk("\nother info that might help us debug this:\n");
1534         lockdep_print_held_locks(curr);
1535
1536         printk("\nstack backtrace:\n");
1537         dump_stack();
1538
1539         return 0;
1540 }
1541
1542 /*
1543  * Print out an error if an invalid bit is set:
1544  */
1545 static inline int
1546 valid_state(struct task_struct *curr, struct held_lock *this,
1547             enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
1548 {
1549         if (unlikely(this->class->usage_mask & (1 << bad_bit)))
1550                 return print_usage_bug(curr, this, bad_bit, new_bit);
1551         return 1;
1552 }
1553
1554 #define STRICT_READ_CHECKS      1
1555
1556 /*
1557  * Mark a lock with a usage bit, and validate the state transition:
1558  */
1559 static int mark_lock(struct task_struct *curr, struct held_lock *this,
1560                      enum lock_usage_bit new_bit, unsigned long ip)
1561 {
1562         unsigned int new_mask = 1 << new_bit, ret = 1;
1563
1564         /*
1565          * If already set then do not dirty the cacheline,
1566          * nor do any checks:
1567          */
1568         if (likely(this->class->usage_mask & new_mask))
1569                 return 1;
1570
1571         if (!graph_lock())
1572                 return 0;
1573         /*
1574          * Make sure we didnt race:
1575          */
1576         if (unlikely(this->class->usage_mask & new_mask)) {
1577                 graph_unlock();
1578                 return 1;
1579         }
1580
1581         this->class->usage_mask |= new_mask;
1582
1583 #ifdef CONFIG_TRACE_IRQFLAGS
1584         if (new_bit == LOCK_ENABLED_HARDIRQS ||
1585                         new_bit == LOCK_ENABLED_HARDIRQS_READ)
1586                 ip = curr->hardirq_enable_ip;
1587         else if (new_bit == LOCK_ENABLED_SOFTIRQS ||
1588                         new_bit == LOCK_ENABLED_SOFTIRQS_READ)
1589                 ip = curr->softirq_enable_ip;
1590 #endif
1591         if (!save_trace(this->class->usage_traces + new_bit))
1592                 return 0;
1593
1594         switch (new_bit) {
1595 #ifdef CONFIG_TRACE_IRQFLAGS
1596         case LOCK_USED_IN_HARDIRQ:
1597                 if (!valid_state(curr, this, new_bit, LOCK_ENABLED_HARDIRQS))
1598                         return 0;
1599                 if (!valid_state(curr, this, new_bit,
1600                                  LOCK_ENABLED_HARDIRQS_READ))
1601                         return 0;
1602                 /*
1603                  * just marked it hardirq-safe, check that this lock
1604                  * took no hardirq-unsafe lock in the past:
1605                  */
1606                 if (!check_usage_forwards(curr, this,
1607                                           LOCK_ENABLED_HARDIRQS, "hard"))
1608                         return 0;
1609 #if STRICT_READ_CHECKS
1610                 /*
1611                  * just marked it hardirq-safe, check that this lock
1612                  * took no hardirq-unsafe-read lock in the past:
1613                  */
1614                 if (!check_usage_forwards(curr, this,
1615                                 LOCK_ENABLED_HARDIRQS_READ, "hard-read"))
1616                         return 0;
1617 #endif
1618                 if (hardirq_verbose(this->class))
1619                         ret = 2;
1620                 break;
1621         case LOCK_USED_IN_SOFTIRQ:
1622                 if (!valid_state(curr, this, new_bit, LOCK_ENABLED_SOFTIRQS))
1623                         return 0;
1624                 if (!valid_state(curr, this, new_bit,
1625                                  LOCK_ENABLED_SOFTIRQS_READ))
1626                         return 0;
1627                 /*
1628                  * just marked it softirq-safe, check that this lock
1629                  * took no softirq-unsafe lock in the past:
1630                  */
1631                 if (!check_usage_forwards(curr, this,
1632                                           LOCK_ENABLED_SOFTIRQS, "soft"))
1633                         return 0;
1634 #if STRICT_READ_CHECKS
1635                 /*
1636                  * just marked it softirq-safe, check that this lock
1637                  * took no softirq-unsafe-read lock in the past:
1638                  */
1639                 if (!check_usage_forwards(curr, this,
1640                                 LOCK_ENABLED_SOFTIRQS_READ, "soft-read"))
1641                         return 0;
1642 #endif
1643                 if (softirq_verbose(this->class))
1644                         ret = 2;
1645                 break;
1646         case LOCK_USED_IN_HARDIRQ_READ:
1647                 if (!valid_state(curr, this, new_bit, LOCK_ENABLED_HARDIRQS))
1648                         return 0;
1649                 /*
1650                  * just marked it hardirq-read-safe, check that this lock
1651                  * took no hardirq-unsafe lock in the past:
1652                  */
1653                 if (!check_usage_forwards(curr, this,
1654                                           LOCK_ENABLED_HARDIRQS, "hard"))
1655                         return 0;
1656                 if (hardirq_verbose(this->class))
1657                         ret = 2;
1658                 break;
1659         case LOCK_USED_IN_SOFTIRQ_READ:
1660                 if (!valid_state(curr, this, new_bit, LOCK_ENABLED_SOFTIRQS))
1661                         return 0;
1662                 /*
1663                  * just marked it softirq-read-safe, check that this lock
1664                  * took no softirq-unsafe lock in the past:
1665                  */
1666                 if (!check_usage_forwards(curr, this,
1667                                           LOCK_ENABLED_SOFTIRQS, "soft"))
1668                         return 0;
1669                 if (softirq_verbose(this->class))
1670                         ret = 2;
1671                 break;
1672         case LOCK_ENABLED_HARDIRQS:
1673                 if (!valid_state(curr, this, new_bit, LOCK_USED_IN_HARDIRQ))
1674                         return 0;
1675                 if (!valid_state(curr, this, new_bit,
1676                                  LOCK_USED_IN_HARDIRQ_READ))
1677                         return 0;
1678                 /*
1679                  * just marked it hardirq-unsafe, check that no hardirq-safe
1680                  * lock in the system ever took it in the past:
1681                  */
1682                 if (!check_usage_backwards(curr, this,
1683                                            LOCK_USED_IN_HARDIRQ, "hard"))
1684                         return 0;
1685 #if STRICT_READ_CHECKS
1686                 /*
1687                  * just marked it hardirq-unsafe, check that no
1688                  * hardirq-safe-read lock in the system ever took
1689                  * it in the past:
1690                  */
1691                 if (!check_usage_backwards(curr, this,
1692                                    LOCK_USED_IN_HARDIRQ_READ, "hard-read"))
1693                         return 0;
1694 #endif
1695                 if (hardirq_verbose(this->class))
1696                         ret = 2;
1697                 break;
1698         case LOCK_ENABLED_SOFTIRQS:
1699                 if (!valid_state(curr, this, new_bit, LOCK_USED_IN_SOFTIRQ))
1700                         return 0;
1701                 if (!valid_state(curr, this, new_bit,
1702                                  LOCK_USED_IN_SOFTIRQ_READ))
1703                         return 0;
1704                 /*
1705                  * just marked it softirq-unsafe, check that no softirq-safe
1706                  * lock in the system ever took it in the past:
1707                  */
1708                 if (!check_usage_backwards(curr, this,
1709                                            LOCK_USED_IN_SOFTIRQ, "soft"))
1710                         return 0;
1711 #if STRICT_READ_CHECKS
1712                 /*
1713                  * just marked it softirq-unsafe, check that no
1714                  * softirq-safe-read lock in the system ever took
1715                  * it in the past:
1716                  */
1717                 if (!check_usage_backwards(curr, this,
1718                                    LOCK_USED_IN_SOFTIRQ_READ, "soft-read"))
1719                         return 0;
1720 #endif
1721                 if (softirq_verbose(this->class))
1722                         ret = 2;
1723                 break;
1724         case LOCK_ENABLED_HARDIRQS_READ:
1725                 if (!valid_state(curr, this, new_bit, LOCK_USED_IN_HARDIRQ))
1726                         return 0;
1727 #if STRICT_READ_CHECKS
1728                 /*
1729                  * just marked it hardirq-read-unsafe, check that no
1730                  * hardirq-safe lock in the system ever took it in the past:
1731                  */
1732                 if (!check_usage_backwards(curr, this,
1733                                            LOCK_USED_IN_HARDIRQ, "hard"))
1734                         return 0;
1735 #endif
1736                 if (hardirq_verbose(this->class))
1737                         ret = 2;
1738                 break;
1739         case LOCK_ENABLED_SOFTIRQS_READ:
1740                 if (!valid_state(curr, this, new_bit, LOCK_USED_IN_SOFTIRQ))
1741                         return 0;
1742 #if STRICT_READ_CHECKS
1743                 /*
1744                  * just marked it softirq-read-unsafe, check that no
1745                  * softirq-safe lock in the system ever took it in the past:
1746                  */
1747                 if (!check_usage_backwards(curr, this,
1748                                            LOCK_USED_IN_SOFTIRQ, "soft"))
1749                         return 0;
1750 #endif
1751                 if (softirq_verbose(this->class))
1752                         ret = 2;
1753                 break;
1754 #endif
1755         case LOCK_USED:
1756                 /*
1757                  * Add it to the global list of classes:
1758                  */
1759                 list_add_tail_rcu(&this->class->lock_entry, &all_lock_classes);
1760                 debug_atomic_dec(&nr_unused_locks);
1761                 break;
1762         default:
1763                 if (!debug_locks_off_graph_unlock())
1764                         return 0;
1765                 WARN_ON(1);
1766                 return 0;
1767         }
1768
1769         graph_unlock();
1770
1771         /*
1772          * We must printk outside of the graph_lock:
1773          */
1774         if (ret == 2) {
1775                 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
1776                 print_lock(this);
1777                 print_irqtrace_events(curr);
1778                 dump_stack();
1779         }
1780
1781         return ret;
1782 }
1783
1784 #ifdef CONFIG_TRACE_IRQFLAGS
1785 /*
1786  * Mark all held locks with a usage bit:
1787  */
1788 static int
1789 mark_held_locks(struct task_struct *curr, int hardirq, unsigned long ip)
1790 {
1791         enum lock_usage_bit usage_bit;
1792         struct held_lock *hlock;
1793         int i;
1794
1795         for (i = 0; i < curr->lockdep_depth; i++) {
1796                 hlock = curr->held_locks + i;
1797
1798                 if (hardirq) {
1799                         if (hlock->read)
1800                                 usage_bit = LOCK_ENABLED_HARDIRQS_READ;
1801                         else
1802                                 usage_bit = LOCK_ENABLED_HARDIRQS;
1803                 } else {
1804                         if (hlock->read)
1805                                 usage_bit = LOCK_ENABLED_SOFTIRQS_READ;
1806                         else
1807                                 usage_bit = LOCK_ENABLED_SOFTIRQS;
1808                 }
1809                 if (!mark_lock(curr, hlock, usage_bit, ip))
1810                         return 0;
1811         }
1812
1813         return 1;
1814 }
1815
1816 /*
1817  * Debugging helper: via this flag we know that we are in
1818  * 'early bootup code', and will warn about any invalid irqs-on event:
1819  */
1820 static int early_boot_irqs_enabled;
1821
1822 void early_boot_irqs_off(void)
1823 {
1824         early_boot_irqs_enabled = 0;
1825 }
1826
1827 void early_boot_irqs_on(void)
1828 {
1829         early_boot_irqs_enabled = 1;
1830 }
1831
1832 /*
1833  * Hardirqs will be enabled:
1834  */
1835 void trace_hardirqs_on(void)
1836 {
1837         struct task_struct *curr = current;
1838         unsigned long ip;
1839
1840         if (unlikely(!debug_locks || current->lockdep_recursion))
1841                 return;
1842
1843         if (DEBUG_LOCKS_WARN_ON(unlikely(!early_boot_irqs_enabled)))
1844                 return;
1845
1846         if (unlikely(curr->hardirqs_enabled)) {
1847                 debug_atomic_inc(&redundant_hardirqs_on);
1848                 return;
1849         }
1850         /* we'll do an OFF -> ON transition: */
1851         curr->hardirqs_enabled = 1;
1852         ip = (unsigned long) __builtin_return_address(0);
1853
1854         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
1855                 return;
1856         if (DEBUG_LOCKS_WARN_ON(current->hardirq_context))
1857                 return;
1858         /*
1859          * We are going to turn hardirqs on, so set the
1860          * usage bit for all held locks:
1861          */
1862         if (!mark_held_locks(curr, 1, ip))
1863                 return;
1864         /*
1865          * If we have softirqs enabled, then set the usage
1866          * bit for all held locks. (disabled hardirqs prevented
1867          * this bit from being set before)
1868          */
1869         if (curr->softirqs_enabled)
1870                 if (!mark_held_locks(curr, 0, ip))
1871                         return;
1872
1873         curr->hardirq_enable_ip = ip;
1874         curr->hardirq_enable_event = ++curr->irq_events;
1875         debug_atomic_inc(&hardirqs_on_events);
1876 }
1877
1878 EXPORT_SYMBOL(trace_hardirqs_on);
1879
1880 /*
1881  * Hardirqs were disabled:
1882  */
1883 void trace_hardirqs_off(void)
1884 {
1885         struct task_struct *curr = current;
1886
1887         if (unlikely(!debug_locks || current->lockdep_recursion))
1888                 return;
1889
1890         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
1891                 return;
1892
1893         if (curr->hardirqs_enabled) {
1894                 /*
1895                  * We have done an ON -> OFF transition:
1896                  */
1897                 curr->hardirqs_enabled = 0;
1898                 curr->hardirq_disable_ip = _RET_IP_;
1899                 curr->hardirq_disable_event = ++curr->irq_events;
1900                 debug_atomic_inc(&hardirqs_off_events);
1901         } else
1902                 debug_atomic_inc(&redundant_hardirqs_off);
1903 }
1904
1905 EXPORT_SYMBOL(trace_hardirqs_off);
1906
1907 /*
1908  * Softirqs will be enabled:
1909  */
1910 void trace_softirqs_on(unsigned long ip)
1911 {
1912         struct task_struct *curr = current;
1913
1914         if (unlikely(!debug_locks))
1915                 return;
1916
1917         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
1918                 return;
1919
1920         if (curr->softirqs_enabled) {
1921                 debug_atomic_inc(&redundant_softirqs_on);
1922                 return;
1923         }
1924
1925         /*
1926          * We'll do an OFF -> ON transition:
1927          */
1928         curr->softirqs_enabled = 1;
1929         curr->softirq_enable_ip = ip;
1930         curr->softirq_enable_event = ++curr->irq_events;
1931         debug_atomic_inc(&softirqs_on_events);
1932         /*
1933          * We are going to turn softirqs on, so set the
1934          * usage bit for all held locks, if hardirqs are
1935          * enabled too:
1936          */
1937         if (curr->hardirqs_enabled)
1938                 mark_held_locks(curr, 0, ip);
1939 }
1940
1941 /*
1942  * Softirqs were disabled:
1943  */
1944 void trace_softirqs_off(unsigned long ip)
1945 {
1946         struct task_struct *curr = current;
1947
1948         if (unlikely(!debug_locks))
1949                 return;
1950
1951         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
1952                 return;
1953
1954         if (curr->softirqs_enabled) {
1955                 /*
1956                  * We have done an ON -> OFF transition:
1957                  */
1958                 curr->softirqs_enabled = 0;
1959                 curr->softirq_disable_ip = ip;
1960                 curr->softirq_disable_event = ++curr->irq_events;
1961                 debug_atomic_inc(&softirqs_off_events);
1962                 DEBUG_LOCKS_WARN_ON(!softirq_count());
1963         } else
1964                 debug_atomic_inc(&redundant_softirqs_off);
1965 }
1966
1967 #endif
1968
1969 /*
1970  * Initialize a lock instance's lock-class mapping info:
1971  */
1972 void lockdep_init_map(struct lockdep_map *lock, const char *name,
1973                       struct lock_class_key *key, int subclass)
1974 {
1975         if (unlikely(!debug_locks))
1976                 return;
1977
1978         if (DEBUG_LOCKS_WARN_ON(!key))
1979                 return;
1980         if (DEBUG_LOCKS_WARN_ON(!name))
1981                 return;
1982         /*
1983          * Sanity check, the lock-class key must be persistent:
1984          */
1985         if (!static_obj(key)) {
1986                 printk("BUG: key %p not in .data!\n", key);
1987                 DEBUG_LOCKS_WARN_ON(1);
1988                 return;
1989         }
1990         lock->name = name;
1991         lock->key = key;
1992         lock->class_cache = NULL;
1993         if (subclass)
1994                 register_lock_class(lock, subclass, 1);
1995 }
1996
1997 EXPORT_SYMBOL_GPL(lockdep_init_map);
1998
1999 /*
2000  * This gets called for every mutex_lock*()/spin_lock*() operation.
2001  * We maintain the dependency maps and validate the locking attempt:
2002  */
2003 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
2004                           int trylock, int read, int check, int hardirqs_off,
2005                           unsigned long ip)
2006 {
2007         struct task_struct *curr = current;
2008         struct lock_class *class = NULL;
2009         struct held_lock *hlock;
2010         unsigned int depth, id;
2011         int chain_head = 0;
2012         u64 chain_key;
2013
2014         if (unlikely(!debug_locks))
2015                 return 0;
2016
2017         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2018                 return 0;
2019
2020         if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
2021                 debug_locks_off();
2022                 printk("BUG: MAX_LOCKDEP_SUBCLASSES too low!\n");
2023                 printk("turning off the locking correctness validator.\n");
2024                 return 0;
2025         }
2026
2027         if (!subclass)
2028                 class = lock->class_cache;
2029         /*
2030          * Not cached yet or subclass?
2031          */
2032         if (unlikely(!class)) {
2033                 class = register_lock_class(lock, subclass, 0);
2034                 if (!class)
2035                         return 0;
2036         }
2037         debug_atomic_inc((atomic_t *)&class->ops);
2038         if (very_verbose(class)) {
2039                 printk("\nacquire class [%p] %s", class->key, class->name);
2040                 if (class->name_version > 1)
2041                         printk("#%d", class->name_version);
2042                 printk("\n");
2043                 dump_stack();
2044         }
2045
2046         /*
2047          * Add the lock to the list of currently held locks.
2048          * (we dont increase the depth just yet, up until the
2049          * dependency checks are done)
2050          */
2051         depth = curr->lockdep_depth;
2052         if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
2053                 return 0;
2054
2055         hlock = curr->held_locks + depth;
2056
2057         hlock->class = class;
2058         hlock->acquire_ip = ip;
2059         hlock->instance = lock;
2060         hlock->trylock = trylock;
2061         hlock->read = read;
2062         hlock->check = check;
2063         hlock->hardirqs_off = hardirqs_off;
2064
2065         if (check != 2)
2066                 goto out_calc_hash;
2067 #ifdef CONFIG_TRACE_IRQFLAGS
2068         /*
2069          * If non-trylock use in a hardirq or softirq context, then
2070          * mark the lock as used in these contexts:
2071          */
2072         if (!trylock) {
2073                 if (read) {
2074                         if (curr->hardirq_context)
2075                                 if (!mark_lock(curr, hlock,
2076                                                 LOCK_USED_IN_HARDIRQ_READ, ip))
2077                                         return 0;
2078                         if (curr->softirq_context)
2079                                 if (!mark_lock(curr, hlock,
2080                                                 LOCK_USED_IN_SOFTIRQ_READ, ip))
2081                                         return 0;
2082                 } else {
2083                         if (curr->hardirq_context)
2084                                 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ, ip))
2085                                         return 0;
2086                         if (curr->softirq_context)
2087                                 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ, ip))
2088                                         return 0;
2089                 }
2090         }
2091         if (!hardirqs_off) {
2092                 if (read) {
2093                         if (!mark_lock(curr, hlock,
2094                                         LOCK_ENABLED_HARDIRQS_READ, ip))
2095                                 return 0;
2096                         if (curr->softirqs_enabled)
2097                                 if (!mark_lock(curr, hlock,
2098                                                 LOCK_ENABLED_SOFTIRQS_READ, ip))
2099                                         return 0;
2100                 } else {
2101                         if (!mark_lock(curr, hlock,
2102                                         LOCK_ENABLED_HARDIRQS, ip))
2103                                 return 0;
2104                         if (curr->softirqs_enabled)
2105                                 if (!mark_lock(curr, hlock,
2106                                                 LOCK_ENABLED_SOFTIRQS, ip))
2107                                         return 0;
2108                 }
2109         }
2110 #endif
2111         /* mark it as used: */
2112         if (!mark_lock(curr, hlock, LOCK_USED, ip))
2113                 return 0;
2114 out_calc_hash:
2115         /*
2116          * Calculate the chain hash: it's the combined has of all the
2117          * lock keys along the dependency chain. We save the hash value
2118          * at every step so that we can get the current hash easily
2119          * after unlock. The chain hash is then used to cache dependency
2120          * results.
2121          *
2122          * The 'key ID' is what is the most compact key value to drive
2123          * the hash, not class->key.
2124          */
2125         id = class - lock_classes;
2126         if (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
2127                 return 0;
2128
2129         chain_key = curr->curr_chain_key;
2130         if (!depth) {
2131                 if (DEBUG_LOCKS_WARN_ON(chain_key != 0))
2132                         return 0;
2133                 chain_head = 1;
2134         }
2135
2136         hlock->prev_chain_key = chain_key;
2137
2138 #ifdef CONFIG_TRACE_IRQFLAGS
2139         /*
2140          * Keep track of points where we cross into an interrupt context:
2141          */
2142         hlock->irq_context = 2*(curr->hardirq_context ? 1 : 0) +
2143                                 curr->softirq_context;
2144         if (depth) {
2145                 struct held_lock *prev_hlock;
2146
2147                 prev_hlock = curr->held_locks + depth-1;
2148                 /*
2149                  * If we cross into another context, reset the
2150                  * hash key (this also prevents the checking and the
2151                  * adding of the dependency to 'prev'):
2152                  */
2153                 if (prev_hlock->irq_context != hlock->irq_context) {
2154                         chain_key = 0;
2155                         chain_head = 1;
2156                 }
2157         }
2158 #endif
2159         chain_key = iterate_chain_key(chain_key, id);
2160         curr->curr_chain_key = chain_key;
2161
2162         /*
2163          * Trylock needs to maintain the stack of held locks, but it
2164          * does not add new dependencies, because trylock can be done
2165          * in any order.
2166          *
2167          * We look up the chain_key and do the O(N^2) check and update of
2168          * the dependencies only if this is a new dependency chain.
2169          * (If lookup_chain_cache() returns with 1 it acquires
2170          * graph_lock for us)
2171          */
2172         if (!trylock && (check == 2) && lookup_chain_cache(chain_key, class)) {
2173                 /*
2174                  * Check whether last held lock:
2175                  *
2176                  * - is irq-safe, if this lock is irq-unsafe
2177                  * - is softirq-safe, if this lock is hardirq-unsafe
2178                  *
2179                  * And check whether the new lock's dependency graph
2180                  * could lead back to the previous lock.
2181                  *
2182                  * any of these scenarios could lead to a deadlock. If
2183                  * All validations
2184                  */
2185                 int ret = check_deadlock(curr, hlock, lock, read);
2186
2187                 if (!ret)
2188                         return 0;
2189                 /*
2190                  * Mark recursive read, as we jump over it when
2191                  * building dependencies (just like we jump over
2192                  * trylock entries):
2193                  */
2194                 if (ret == 2)
2195                         hlock->read = 2;
2196                 /*
2197                  * Add dependency only if this lock is not the head
2198                  * of the chain, and if it's not a secondary read-lock:
2199                  */
2200                 if (!chain_head && ret != 2)
2201                         if (!check_prevs_add(curr, hlock))
2202                                 return 0;
2203                 graph_unlock();
2204         }
2205         curr->lockdep_depth++;
2206         check_chain_key(curr);
2207         if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
2208                 debug_locks_off();
2209                 printk("BUG: MAX_LOCK_DEPTH too low!\n");
2210                 printk("turning off the locking correctness validator.\n");
2211                 return 0;
2212         }
2213         if (unlikely(curr->lockdep_depth > max_lockdep_depth))
2214                 max_lockdep_depth = curr->lockdep_depth;
2215
2216         return 1;
2217 }
2218
2219 static int
2220 print_unlock_inbalance_bug(struct task_struct *curr, struct lockdep_map *lock,
2221                            unsigned long ip)
2222 {
2223         if (!debug_locks_off())
2224                 return 0;
2225         if (debug_locks_silent)
2226                 return 0;
2227
2228         printk("\n=====================================\n");
2229         printk(  "[ BUG: bad unlock balance detected! ]\n");
2230         printk(  "-------------------------------------\n");
2231         printk("%s/%d is trying to release lock (",
2232                 curr->comm, curr->pid);
2233         print_lockdep_cache(lock);
2234         printk(") at:\n");
2235         print_ip_sym(ip);
2236         printk("but there are no more locks to release!\n");
2237         printk("\nother info that might help us debug this:\n");
2238         lockdep_print_held_locks(curr);
2239
2240         printk("\nstack backtrace:\n");
2241         dump_stack();
2242
2243         return 0;
2244 }
2245
2246 /*
2247  * Common debugging checks for both nested and non-nested unlock:
2248  */
2249 static int check_unlock(struct task_struct *curr, struct lockdep_map *lock,
2250                         unsigned long ip)
2251 {
2252         if (unlikely(!debug_locks))
2253                 return 0;
2254         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2255                 return 0;
2256
2257         if (curr->lockdep_depth <= 0)
2258                 return print_unlock_inbalance_bug(curr, lock, ip);
2259
2260         return 1;
2261 }
2262
2263 /*
2264  * Remove the lock to the list of currently held locks in a
2265  * potentially non-nested (out of order) manner. This is a
2266  * relatively rare operation, as all the unlock APIs default
2267  * to nested mode (which uses lock_release()):
2268  */
2269 static int
2270 lock_release_non_nested(struct task_struct *curr,
2271                         struct lockdep_map *lock, unsigned long ip)
2272 {
2273         struct held_lock *hlock, *prev_hlock;
2274         unsigned int depth;
2275         int i;
2276
2277         /*
2278          * Check whether the lock exists in the current stack
2279          * of held locks:
2280          */
2281         depth = curr->lockdep_depth;
2282         if (DEBUG_LOCKS_WARN_ON(!depth))
2283                 return 0;
2284
2285         prev_hlock = NULL;
2286         for (i = depth-1; i >= 0; i--) {
2287                 hlock = curr->held_locks + i;
2288                 /*
2289                  * We must not cross into another context:
2290                  */
2291                 if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
2292                         break;
2293                 if (hlock->instance == lock)
2294                         goto found_it;
2295                 prev_hlock = hlock;
2296         }
2297         return print_unlock_inbalance_bug(curr, lock, ip);
2298
2299 found_it:
2300         /*
2301          * We have the right lock to unlock, 'hlock' points to it.
2302          * Now we remove it from the stack, and add back the other
2303          * entries (if any), recalculating the hash along the way:
2304          */
2305         curr->lockdep_depth = i;
2306         curr->curr_chain_key = hlock->prev_chain_key;
2307
2308         for (i++; i < depth; i++) {
2309                 hlock = curr->held_locks + i;
2310                 if (!__lock_acquire(hlock->instance,
2311                         hlock->class->subclass, hlock->trylock,
2312                                 hlock->read, hlock->check, hlock->hardirqs_off,
2313                                 hlock->acquire_ip))
2314                         return 0;
2315         }
2316
2317         if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - 1))
2318                 return 0;
2319         return 1;
2320 }
2321
2322 /*
2323  * Remove the lock to the list of currently held locks - this gets
2324  * called on mutex_unlock()/spin_unlock*() (or on a failed
2325  * mutex_lock_interruptible()). This is done for unlocks that nest
2326  * perfectly. (i.e. the current top of the lock-stack is unlocked)
2327  */
2328 static int lock_release_nested(struct task_struct *curr,
2329                                struct lockdep_map *lock, unsigned long ip)
2330 {
2331         struct held_lock *hlock;
2332         unsigned int depth;
2333
2334         /*
2335          * Pop off the top of the lock stack:
2336          */
2337         depth = curr->lockdep_depth - 1;
2338         hlock = curr->held_locks + depth;
2339
2340         /*
2341          * Is the unlock non-nested:
2342          */
2343         if (hlock->instance != lock)
2344                 return lock_release_non_nested(curr, lock, ip);
2345         curr->lockdep_depth--;
2346
2347         if (DEBUG_LOCKS_WARN_ON(!depth && (hlock->prev_chain_key != 0)))
2348                 return 0;
2349
2350         curr->curr_chain_key = hlock->prev_chain_key;
2351
2352 #ifdef CONFIG_DEBUG_LOCKDEP
2353         hlock->prev_chain_key = 0;
2354         hlock->class = NULL;
2355         hlock->acquire_ip = 0;
2356         hlock->irq_context = 0;
2357 #endif
2358         return 1;
2359 }
2360
2361 /*
2362  * Remove the lock to the list of currently held locks - this gets
2363  * called on mutex_unlock()/spin_unlock*() (or on a failed
2364  * mutex_lock_interruptible()). This is done for unlocks that nest
2365  * perfectly. (i.e. the current top of the lock-stack is unlocked)
2366  */
2367 static void
2368 __lock_release(struct lockdep_map *lock, int nested, unsigned long ip)
2369 {
2370         struct task_struct *curr = current;
2371
2372         if (!check_unlock(curr, lock, ip))
2373                 return;
2374
2375         if (nested) {
2376                 if (!lock_release_nested(curr, lock, ip))
2377                         return;
2378         } else {
2379                 if (!lock_release_non_nested(curr, lock, ip))
2380                         return;
2381         }
2382
2383         check_chain_key(curr);
2384 }
2385
2386 /*
2387  * Check whether we follow the irq-flags state precisely:
2388  */
2389 static void check_flags(unsigned long flags)
2390 {
2391 #if defined(CONFIG_DEBUG_LOCKDEP) && defined(CONFIG_TRACE_IRQFLAGS)
2392         if (!debug_locks)
2393                 return;
2394
2395         if (irqs_disabled_flags(flags))
2396                 DEBUG_LOCKS_WARN_ON(current->hardirqs_enabled);
2397         else
2398                 DEBUG_LOCKS_WARN_ON(!current->hardirqs_enabled);
2399
2400         /*
2401          * We dont accurately track softirq state in e.g.
2402          * hardirq contexts (such as on 4KSTACKS), so only
2403          * check if not in hardirq contexts:
2404          */
2405         if (!hardirq_count()) {
2406                 if (softirq_count())
2407                         DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
2408                 else
2409                         DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
2410         }
2411
2412         if (!debug_locks)
2413                 print_irqtrace_events(current);
2414 #endif
2415 }
2416
2417 /*
2418  * We are not always called with irqs disabled - do that here,
2419  * and also avoid lockdep recursion:
2420  */
2421 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
2422                   int trylock, int read, int check, unsigned long ip)
2423 {
2424         unsigned long flags;
2425
2426         if (unlikely(current->lockdep_recursion))
2427                 return;
2428
2429         raw_local_irq_save(flags);
2430         check_flags(flags);
2431
2432         current->lockdep_recursion = 1;
2433         __lock_acquire(lock, subclass, trylock, read, check,
2434                        irqs_disabled_flags(flags), ip);
2435         current->lockdep_recursion = 0;
2436         raw_local_irq_restore(flags);
2437 }
2438
2439 EXPORT_SYMBOL_GPL(lock_acquire);
2440
2441 void lock_release(struct lockdep_map *lock, int nested, unsigned long ip)
2442 {
2443         unsigned long flags;
2444
2445         if (unlikely(current->lockdep_recursion))
2446                 return;
2447
2448         raw_local_irq_save(flags);
2449         check_flags(flags);
2450         current->lockdep_recursion = 1;
2451         __lock_release(lock, nested, ip);
2452         current->lockdep_recursion = 0;
2453         raw_local_irq_restore(flags);
2454 }
2455
2456 EXPORT_SYMBOL_GPL(lock_release);
2457
2458 /*
2459  * Used by the testsuite, sanitize the validator state
2460  * after a simulated failure:
2461  */
2462
2463 void lockdep_reset(void)
2464 {
2465         unsigned long flags;
2466         int i;
2467
2468         raw_local_irq_save(flags);
2469         current->curr_chain_key = 0;
2470         current->lockdep_depth = 0;
2471         current->lockdep_recursion = 0;
2472         memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
2473         nr_hardirq_chains = 0;
2474         nr_softirq_chains = 0;
2475         nr_process_chains = 0;
2476         debug_locks = 1;
2477         for (i = 0; i < CHAINHASH_SIZE; i++)
2478                 INIT_LIST_HEAD(chainhash_table + i);
2479         raw_local_irq_restore(flags);
2480 }
2481
2482 static void zap_class(struct lock_class *class)
2483 {
2484         int i;
2485
2486         /*
2487          * Remove all dependencies this lock is
2488          * involved in:
2489          */
2490         for (i = 0; i < nr_list_entries; i++) {
2491                 if (list_entries[i].class == class)
2492                         list_del_rcu(&list_entries[i].entry);
2493         }
2494         /*
2495          * Unhash the class and remove it from the all_lock_classes list:
2496          */
2497         list_del_rcu(&class->hash_entry);
2498         list_del_rcu(&class->lock_entry);
2499
2500 }
2501
2502 static inline int within(void *addr, void *start, unsigned long size)
2503 {
2504         return addr >= start && addr < start + size;
2505 }
2506
2507 void lockdep_free_key_range(void *start, unsigned long size)
2508 {
2509         struct lock_class *class, *next;
2510         struct list_head *head;
2511         unsigned long flags;
2512         int i;
2513
2514         raw_local_irq_save(flags);
2515         graph_lock();
2516
2517         /*
2518          * Unhash all classes that were created by this module:
2519          */
2520         for (i = 0; i < CLASSHASH_SIZE; i++) {
2521                 head = classhash_table + i;
2522                 if (list_empty(head))
2523                         continue;
2524                 list_for_each_entry_safe(class, next, head, hash_entry)
2525                         if (within(class->key, start, size))
2526                                 zap_class(class);
2527         }
2528
2529         graph_unlock();
2530         raw_local_irq_restore(flags);
2531 }
2532
2533 void lockdep_reset_lock(struct lockdep_map *lock)
2534 {
2535         struct lock_class *class, *next;
2536         struct list_head *head;
2537         unsigned long flags;
2538         int i, j;
2539
2540         raw_local_irq_save(flags);
2541
2542         /*
2543          * Remove all classes this lock might have:
2544          */
2545         for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
2546                 /*
2547                  * If the class exists we look it up and zap it:
2548                  */
2549                 class = look_up_lock_class(lock, j);
2550                 if (class)
2551                         zap_class(class);
2552         }
2553         /*
2554          * Debug check: in the end all mapped classes should
2555          * be gone.
2556          */
2557         graph_lock();
2558         for (i = 0; i < CLASSHASH_SIZE; i++) {
2559                 head = classhash_table + i;
2560                 if (list_empty(head))
2561                         continue;
2562                 list_for_each_entry_safe(class, next, head, hash_entry) {
2563                         if (unlikely(class == lock->class_cache)) {
2564                                 if (debug_locks_off_graph_unlock())
2565                                         WARN_ON(1);
2566                                 goto out_restore;
2567                         }
2568                 }
2569         }
2570         graph_unlock();
2571
2572 out_restore:
2573         raw_local_irq_restore(flags);
2574 }
2575
2576 void __init lockdep_init(void)
2577 {
2578         int i;
2579
2580         /*
2581          * Some architectures have their own start_kernel()
2582          * code which calls lockdep_init(), while we also
2583          * call lockdep_init() from the start_kernel() itself,
2584          * and we want to initialize the hashes only once:
2585          */
2586         if (lockdep_initialized)
2587                 return;
2588
2589         for (i = 0; i < CLASSHASH_SIZE; i++)
2590                 INIT_LIST_HEAD(classhash_table + i);
2591
2592         for (i = 0; i < CHAINHASH_SIZE; i++)
2593                 INIT_LIST_HEAD(chainhash_table + i);
2594
2595         lockdep_initialized = 1;
2596 }
2597
2598 void __init lockdep_info(void)
2599 {
2600         printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
2601
2602         printk("... MAX_LOCKDEP_SUBCLASSES:    %lu\n", MAX_LOCKDEP_SUBCLASSES);
2603         printk("... MAX_LOCK_DEPTH:          %lu\n", MAX_LOCK_DEPTH);
2604         printk("... MAX_LOCKDEP_KEYS:        %lu\n", MAX_LOCKDEP_KEYS);
2605         printk("... CLASSHASH_SIZE:           %lu\n", CLASSHASH_SIZE);
2606         printk("... MAX_LOCKDEP_ENTRIES:     %lu\n", MAX_LOCKDEP_ENTRIES);
2607         printk("... MAX_LOCKDEP_CHAINS:      %lu\n", MAX_LOCKDEP_CHAINS);
2608         printk("... CHAINHASH_SIZE:          %lu\n", CHAINHASH_SIZE);
2609
2610         printk(" memory used by lock dependency info: %lu kB\n",
2611                 (sizeof(struct lock_class) * MAX_LOCKDEP_KEYS +
2612                 sizeof(struct list_head) * CLASSHASH_SIZE +
2613                 sizeof(struct lock_list) * MAX_LOCKDEP_ENTRIES +
2614                 sizeof(struct lock_chain) * MAX_LOCKDEP_CHAINS +
2615                 sizeof(struct list_head) * CHAINHASH_SIZE) / 1024);
2616
2617         printk(" per task-struct memory footprint: %lu bytes\n",
2618                 sizeof(struct held_lock) * MAX_LOCK_DEPTH);
2619
2620 #ifdef CONFIG_DEBUG_LOCKDEP
2621         if (lockdep_init_error)
2622                 printk("WARNING: lockdep init error! Arch code didnt call lockdep_init() early enough?\n");
2623 #endif
2624 }
2625
2626 static inline int in_range(const void *start, const void *addr, const void *end)
2627 {
2628         return addr >= start && addr <= end;
2629 }
2630
2631 static void
2632 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
2633                      const void *mem_to, struct held_lock *hlock)
2634 {
2635         if (!debug_locks_off())
2636                 return;
2637         if (debug_locks_silent)
2638                 return;
2639
2640         printk("\n=========================\n");
2641         printk(  "[ BUG: held lock freed! ]\n");
2642         printk(  "-------------------------\n");
2643         printk("%s/%d is freeing memory %p-%p, with a lock still held there!\n",
2644                 curr->comm, curr->pid, mem_from, mem_to-1);
2645         print_lock(hlock);
2646         lockdep_print_held_locks(curr);
2647
2648         printk("\nstack backtrace:\n");
2649         dump_stack();
2650 }
2651
2652 /*
2653  * Called when kernel memory is freed (or unmapped), or if a lock
2654  * is destroyed or reinitialized - this code checks whether there is
2655  * any held lock in the memory range of <from> to <to>:
2656  */
2657 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
2658 {
2659         const void *mem_to = mem_from + mem_len, *lock_from, *lock_to;
2660         struct task_struct *curr = current;
2661         struct held_lock *hlock;
2662         unsigned long flags;
2663         int i;
2664
2665         if (unlikely(!debug_locks))
2666                 return;
2667
2668         local_irq_save(flags);
2669         for (i = 0; i < curr->lockdep_depth; i++) {
2670                 hlock = curr->held_locks + i;
2671
2672                 lock_from = (void *)hlock->instance;
2673                 lock_to = (void *)(hlock->instance + 1);
2674
2675                 if (!in_range(mem_from, lock_from, mem_to) &&
2676                                         !in_range(mem_from, lock_to, mem_to))
2677                         continue;
2678
2679                 print_freed_lock_bug(curr, mem_from, mem_to, hlock);
2680                 break;
2681         }
2682         local_irq_restore(flags);
2683 }
2684 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
2685
2686 static void print_held_locks_bug(struct task_struct *curr)
2687 {
2688         if (!debug_locks_off())
2689                 return;
2690         if (debug_locks_silent)
2691                 return;
2692
2693         printk("\n=====================================\n");
2694         printk(  "[ BUG: lock held at task exit time! ]\n");
2695         printk(  "-------------------------------------\n");
2696         printk("%s/%d is exiting with locks still held!\n",
2697                 curr->comm, curr->pid);
2698         lockdep_print_held_locks(curr);
2699
2700         printk("\nstack backtrace:\n");
2701         dump_stack();
2702 }
2703
2704 void debug_check_no_locks_held(struct task_struct *task)
2705 {
2706         if (unlikely(task->lockdep_depth > 0))
2707                 print_held_locks_bug(task);
2708 }
2709
2710 void debug_show_all_locks(void)
2711 {
2712         struct task_struct *g, *p;
2713         int count = 10;
2714         int unlock = 1;
2715
2716         printk("\nShowing all locks held in the system:\n");
2717
2718         /*
2719          * Here we try to get the tasklist_lock as hard as possible,
2720          * if not successful after 2 seconds we ignore it (but keep
2721          * trying). This is to enable a debug printout even if a
2722          * tasklist_lock-holding task deadlocks or crashes.
2723          */
2724 retry:
2725         if (!read_trylock(&tasklist_lock)) {
2726                 if (count == 10)
2727                         printk("hm, tasklist_lock locked, retrying... ");
2728                 if (count) {
2729                         count--;
2730                         printk(" #%d", 10-count);
2731                         mdelay(200);
2732                         goto retry;
2733                 }
2734                 printk(" ignoring it.\n");
2735                 unlock = 0;
2736         }
2737         if (count != 10)
2738                 printk(" locked it.\n");
2739
2740         do_each_thread(g, p) {
2741                 if (p->lockdep_depth)
2742                         lockdep_print_held_locks(p);
2743                 if (!unlock)
2744                         if (read_trylock(&tasklist_lock))
2745                                 unlock = 1;
2746         } while_each_thread(g, p);
2747
2748         printk("\n");
2749         printk("=============================================\n\n");
2750
2751         if (unlock)
2752                 read_unlock(&tasklist_lock);
2753 }
2754
2755 EXPORT_SYMBOL_GPL(debug_show_all_locks);
2756
2757 void debug_show_held_locks(struct task_struct *task)
2758 {
2759         lockdep_print_held_locks(task);
2760 }
2761
2762 EXPORT_SYMBOL_GPL(debug_show_held_locks);
2763