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