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