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