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