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