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