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