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