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