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