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