]> git.karo-electronics.de Git - karo-tx-linux.git/blob - kernel/locking/lockdep.c
Merge remote-tracking branch 'edac-amd/for-next'
[karo-tx-linux.git] / kernel / locking / 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
10  *
11  * this code maps all the lock dependencies as they occur in a live kernel
12  * and will warn about the following classes of locking bugs:
13  *
14  * - lock inversion scenarios
15  * - circular lock dependencies
16  * - hardirq/softirq safe/unsafe locking bugs
17  *
18  * Bugs are reported even if the current locking scenario does not cause
19  * any deadlock at this point.
20  *
21  * I.e. if anytime in the past two locks were taken in a different order,
22  * even if it happened for another task, even if those were different
23  * locks (but of the same class as this lock), this code will detect it.
24  *
25  * Thanks to Arjan van de Ven for coming up with the initial idea of
26  * mapping lock dependencies runtime.
27  */
28 #define DISABLE_BRANCH_PROFILING
29 #include <linux/mutex.h>
30 #include <linux/sched.h>
31 #include <linux/delay.h>
32 #include <linux/module.h>
33 #include <linux/proc_fs.h>
34 #include <linux/seq_file.h>
35 #include <linux/spinlock.h>
36 #include <linux/kallsyms.h>
37 #include <linux/interrupt.h>
38 #include <linux/stacktrace.h>
39 #include <linux/debug_locks.h>
40 #include <linux/irqflags.h>
41 #include <linux/utsname.h>
42 #include <linux/hash.h>
43 #include <linux/ftrace.h>
44 #include <linux/stringify.h>
45 #include <linux/bitops.h>
46 #include <linux/gfp.h>
47 #include <linux/kmemcheck.h>
48
49 #include <asm/sections.h>
50
51 #include "lockdep_internals.h"
52
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/lock.h>
55
56 #ifdef CONFIG_PROVE_LOCKING
57 int prove_locking = 1;
58 module_param(prove_locking, int, 0644);
59 #else
60 #define prove_locking 0
61 #endif
62
63 #ifdef CONFIG_LOCK_STAT
64 int lock_stat = 1;
65 module_param(lock_stat, int, 0644);
66 #else
67 #define lock_stat 0
68 #endif
69
70 /*
71  * lockdep_lock: protects the lockdep graph, the hashes and the
72  *               class/list/hash allocators.
73  *
74  * This is one of the rare exceptions where it's justified
75  * to use a raw spinlock - we really dont want the spinlock
76  * code to recurse back into the lockdep code...
77  */
78 static arch_spinlock_t lockdep_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
79
80 static int graph_lock(void)
81 {
82         arch_spin_lock(&lockdep_lock);
83         /*
84          * Make sure that if another CPU detected a bug while
85          * walking the graph we dont change it (while the other
86          * CPU is busy printing out stuff with the graph lock
87          * dropped already)
88          */
89         if (!debug_locks) {
90                 arch_spin_unlock(&lockdep_lock);
91                 return 0;
92         }
93         /* prevent any recursions within lockdep from causing deadlocks */
94         current->lockdep_recursion++;
95         return 1;
96 }
97
98 static inline int graph_unlock(void)
99 {
100         if (debug_locks && !arch_spin_is_locked(&lockdep_lock)) {
101                 /*
102                  * The lockdep graph lock isn't locked while we expect it to
103                  * be, we're confused now, bye!
104                  */
105                 return DEBUG_LOCKS_WARN_ON(1);
106         }
107
108         current->lockdep_recursion--;
109         arch_spin_unlock(&lockdep_lock);
110         return 0;
111 }
112
113 /*
114  * Turn lock debugging off and return with 0 if it was off already,
115  * and also release the graph lock:
116  */
117 static inline int debug_locks_off_graph_unlock(void)
118 {
119         int ret = debug_locks_off();
120
121         arch_spin_unlock(&lockdep_lock);
122
123         return ret;
124 }
125
126 unsigned long nr_list_entries;
127 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
128
129 /*
130  * All data structures here are protected by the global debug_lock.
131  *
132  * Mutex key structs only get allocated, once during bootup, and never
133  * get freed - this significantly simplifies the debugging code.
134  */
135 unsigned long nr_lock_classes;
136 static struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
137
138 static inline struct lock_class *hlock_class(struct held_lock *hlock)
139 {
140         if (!hlock->class_idx) {
141                 /*
142                  * Someone passed in garbage, we give up.
143                  */
144                 DEBUG_LOCKS_WARN_ON(1);
145                 return NULL;
146         }
147         return lock_classes + hlock->class_idx - 1;
148 }
149
150 #ifdef CONFIG_LOCK_STAT
151 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS],
152                       cpu_lock_stats);
153
154 static inline u64 lockstat_clock(void)
155 {
156         return local_clock();
157 }
158
159 static int lock_point(unsigned long points[], unsigned long ip)
160 {
161         int i;
162
163         for (i = 0; i < LOCKSTAT_POINTS; i++) {
164                 if (points[i] == 0) {
165                         points[i] = ip;
166                         break;
167                 }
168                 if (points[i] == ip)
169                         break;
170         }
171
172         return i;
173 }
174
175 static void lock_time_inc(struct lock_time *lt, u64 time)
176 {
177         if (time > lt->max)
178                 lt->max = time;
179
180         if (time < lt->min || !lt->nr)
181                 lt->min = time;
182
183         lt->total += time;
184         lt->nr++;
185 }
186
187 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
188 {
189         if (!src->nr)
190                 return;
191
192         if (src->max > dst->max)
193                 dst->max = src->max;
194
195         if (src->min < dst->min || !dst->nr)
196                 dst->min = src->min;
197
198         dst->total += src->total;
199         dst->nr += src->nr;
200 }
201
202 struct lock_class_stats lock_stats(struct lock_class *class)
203 {
204         struct lock_class_stats stats;
205         int cpu, i;
206
207         memset(&stats, 0, sizeof(struct lock_class_stats));
208         for_each_possible_cpu(cpu) {
209                 struct lock_class_stats *pcs =
210                         &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
211
212                 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
213                         stats.contention_point[i] += pcs->contention_point[i];
214
215                 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
216                         stats.contending_point[i] += pcs->contending_point[i];
217
218                 lock_time_add(&pcs->read_waittime, &stats.read_waittime);
219                 lock_time_add(&pcs->write_waittime, &stats.write_waittime);
220
221                 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
222                 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
223
224                 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
225                         stats.bounces[i] += pcs->bounces[i];
226         }
227
228         return stats;
229 }
230
231 void clear_lock_stats(struct lock_class *class)
232 {
233         int cpu;
234
235         for_each_possible_cpu(cpu) {
236                 struct lock_class_stats *cpu_stats =
237                         &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
238
239                 memset(cpu_stats, 0, sizeof(struct lock_class_stats));
240         }
241         memset(class->contention_point, 0, sizeof(class->contention_point));
242         memset(class->contending_point, 0, sizeof(class->contending_point));
243 }
244
245 static struct lock_class_stats *get_lock_stats(struct lock_class *class)
246 {
247         return &get_cpu_var(cpu_lock_stats)[class - lock_classes];
248 }
249
250 static void put_lock_stats(struct lock_class_stats *stats)
251 {
252         put_cpu_var(cpu_lock_stats);
253 }
254
255 static void lock_release_holdtime(struct held_lock *hlock)
256 {
257         struct lock_class_stats *stats;
258         u64 holdtime;
259
260         if (!lock_stat)
261                 return;
262
263         holdtime = lockstat_clock() - hlock->holdtime_stamp;
264
265         stats = get_lock_stats(hlock_class(hlock));
266         if (hlock->read)
267                 lock_time_inc(&stats->read_holdtime, holdtime);
268         else
269                 lock_time_inc(&stats->write_holdtime, holdtime);
270         put_lock_stats(stats);
271 }
272 #else
273 static inline void lock_release_holdtime(struct held_lock *hlock)
274 {
275 }
276 #endif
277
278 /*
279  * We keep a global list of all lock classes. The list only grows,
280  * never shrinks. The list is only accessed with the lockdep
281  * spinlock lock held.
282  */
283 LIST_HEAD(all_lock_classes);
284
285 /*
286  * The lockdep classes are in a hash-table as well, for fast lookup:
287  */
288 #define CLASSHASH_BITS          (MAX_LOCKDEP_KEYS_BITS - 1)
289 #define CLASSHASH_SIZE          (1UL << CLASSHASH_BITS)
290 #define __classhashfn(key)      hash_long((unsigned long)key, CLASSHASH_BITS)
291 #define classhashentry(key)     (classhash_table + __classhashfn((key)))
292
293 static struct hlist_head classhash_table[CLASSHASH_SIZE];
294
295 /*
296  * We put the lock dependency chains into a hash-table as well, to cache
297  * their existence:
298  */
299 #define CHAINHASH_BITS          (MAX_LOCKDEP_CHAINS_BITS-1)
300 #define CHAINHASH_SIZE          (1UL << CHAINHASH_BITS)
301 #define __chainhashfn(chain)    hash_long(chain, CHAINHASH_BITS)
302 #define chainhashentry(chain)   (chainhash_table + __chainhashfn((chain)))
303
304 static struct hlist_head chainhash_table[CHAINHASH_SIZE];
305
306 /*
307  * The hash key of the lock dependency chains is a hash itself too:
308  * it's a hash of all locks taken up to that lock, including that lock.
309  * It's a 64-bit hash, because it's important for the keys to be
310  * unique.
311  */
312 #define iterate_chain_key(key1, key2) \
313         (((key1) << MAX_LOCKDEP_KEYS_BITS) ^ \
314         ((key1) >> (64-MAX_LOCKDEP_KEYS_BITS)) ^ \
315         (key2))
316
317 void lockdep_off(void)
318 {
319         current->lockdep_recursion++;
320 }
321 EXPORT_SYMBOL(lockdep_off);
322
323 void lockdep_on(void)
324 {
325         current->lockdep_recursion--;
326 }
327 EXPORT_SYMBOL(lockdep_on);
328
329 /*
330  * Debugging switches:
331  */
332
333 #define VERBOSE                 0
334 #define VERY_VERBOSE            0
335
336 #if VERBOSE
337 # define HARDIRQ_VERBOSE        1
338 # define SOFTIRQ_VERBOSE        1
339 # define RECLAIM_VERBOSE        1
340 #else
341 # define HARDIRQ_VERBOSE        0
342 # define SOFTIRQ_VERBOSE        0
343 # define RECLAIM_VERBOSE        0
344 #endif
345
346 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE || RECLAIM_VERBOSE
347 /*
348  * Quick filtering for interesting events:
349  */
350 static int class_filter(struct lock_class *class)
351 {
352 #if 0
353         /* Example */
354         if (class->name_version == 1 &&
355                         !strcmp(class->name, "lockname"))
356                 return 1;
357         if (class->name_version == 1 &&
358                         !strcmp(class->name, "&struct->lockfield"))
359                 return 1;
360 #endif
361         /* Filter everything else. 1 would be to allow everything else */
362         return 0;
363 }
364 #endif
365
366 static int verbose(struct lock_class *class)
367 {
368 #if VERBOSE
369         return class_filter(class);
370 #endif
371         return 0;
372 }
373
374 /*
375  * Stack-trace: tightly packed array of stack backtrace
376  * addresses. Protected by the graph_lock.
377  */
378 unsigned long nr_stack_trace_entries;
379 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
380
381 static void print_lockdep_off(const char *bug_msg)
382 {
383         printk(KERN_DEBUG "%s\n", bug_msg);
384         printk(KERN_DEBUG "turning off the locking correctness validator.\n");
385 #ifdef CONFIG_LOCK_STAT
386         printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
387 #endif
388 }
389
390 static int save_trace(struct stack_trace *trace)
391 {
392         trace->nr_entries = 0;
393         trace->max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
394         trace->entries = stack_trace + nr_stack_trace_entries;
395
396         trace->skip = 3;
397
398         save_stack_trace(trace);
399
400         /*
401          * Some daft arches put -1 at the end to indicate its a full trace.
402          *
403          * <rant> this is buggy anyway, since it takes a whole extra entry so a
404          * complete trace that maxes out the entries provided will be reported
405          * as incomplete, friggin useless </rant>
406          */
407         if (trace->nr_entries != 0 &&
408             trace->entries[trace->nr_entries-1] == ULONG_MAX)
409                 trace->nr_entries--;
410
411         trace->max_entries = trace->nr_entries;
412
413         nr_stack_trace_entries += trace->nr_entries;
414
415         if (nr_stack_trace_entries >= MAX_STACK_TRACE_ENTRIES-1) {
416                 if (!debug_locks_off_graph_unlock())
417                         return 0;
418
419                 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
420                 dump_stack();
421
422                 return 0;
423         }
424
425         return 1;
426 }
427
428 unsigned int nr_hardirq_chains;
429 unsigned int nr_softirq_chains;
430 unsigned int nr_process_chains;
431 unsigned int max_lockdep_depth;
432
433 #ifdef CONFIG_DEBUG_LOCKDEP
434 /*
435  * Various lockdep statistics:
436  */
437 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
438 #endif
439
440 /*
441  * Locking printouts:
442  */
443
444 #define __USAGE(__STATE)                                                \
445         [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W",       \
446         [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W",         \
447         [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
448         [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
449
450 static const char *usage_str[] =
451 {
452 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
453 #include "lockdep_states.h"
454 #undef LOCKDEP_STATE
455         [LOCK_USED] = "INITIAL USE",
456 };
457
458 const char * __get_key_name(struct lockdep_subclass_key *key, char *str)
459 {
460         return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
461 }
462
463 static inline unsigned long lock_flag(enum lock_usage_bit bit)
464 {
465         return 1UL << bit;
466 }
467
468 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
469 {
470         char c = '.';
471
472         if (class->usage_mask & lock_flag(bit + 2))
473                 c = '+';
474         if (class->usage_mask & lock_flag(bit)) {
475                 c = '-';
476                 if (class->usage_mask & lock_flag(bit + 2))
477                         c = '?';
478         }
479
480         return c;
481 }
482
483 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
484 {
485         int i = 0;
486
487 #define LOCKDEP_STATE(__STATE)                                          \
488         usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE);     \
489         usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
490 #include "lockdep_states.h"
491 #undef LOCKDEP_STATE
492
493         usage[i] = '\0';
494 }
495
496 static void __print_lock_name(struct lock_class *class)
497 {
498         char str[KSYM_NAME_LEN];
499         const char *name;
500
501         name = class->name;
502         if (!name) {
503                 name = __get_key_name(class->key, str);
504                 printk("%s", name);
505         } else {
506                 printk("%s", name);
507                 if (class->name_version > 1)
508                         printk("#%d", class->name_version);
509                 if (class->subclass)
510                         printk("/%d", class->subclass);
511         }
512 }
513
514 static void print_lock_name(struct lock_class *class)
515 {
516         char usage[LOCK_USAGE_CHARS];
517
518         get_usage_chars(class, usage);
519
520         printk(" (");
521         __print_lock_name(class);
522         printk("){%s}", usage);
523 }
524
525 static void print_lockdep_cache(struct lockdep_map *lock)
526 {
527         const char *name;
528         char str[KSYM_NAME_LEN];
529
530         name = lock->name;
531         if (!name)
532                 name = __get_key_name(lock->key->subkeys, str);
533
534         printk("%s", name);
535 }
536
537 static void print_lock(struct held_lock *hlock)
538 {
539         /*
540          * We can be called locklessly through debug_show_all_locks() so be
541          * extra careful, the hlock might have been released and cleared.
542          */
543         unsigned int class_idx = hlock->class_idx;
544
545         /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfields: */
546         barrier();
547
548         if (!class_idx || (class_idx - 1) >= MAX_LOCKDEP_KEYS) {
549                 printk("<RELEASED>\n");
550                 return;
551         }
552
553         print_lock_name(lock_classes + class_idx - 1);
554         printk(", at: ");
555         print_ip_sym(hlock->acquire_ip);
556 }
557
558 static void lockdep_print_held_locks(struct task_struct *curr)
559 {
560         int i, depth = curr->lockdep_depth;
561
562         if (!depth) {
563                 printk("no locks held by %s/%d.\n", curr->comm, task_pid_nr(curr));
564                 return;
565         }
566         printk("%d lock%s held by %s/%d:\n",
567                 depth, depth > 1 ? "s" : "", curr->comm, task_pid_nr(curr));
568
569         for (i = 0; i < depth; i++) {
570                 printk(" #%d: ", i);
571                 print_lock(curr->held_locks + i);
572         }
573 }
574
575 static void print_kernel_ident(void)
576 {
577         printk("%s %.*s %s\n", init_utsname()->release,
578                 (int)strcspn(init_utsname()->version, " "),
579                 init_utsname()->version,
580                 print_tainted());
581 }
582
583 static int very_verbose(struct lock_class *class)
584 {
585 #if VERY_VERBOSE
586         return class_filter(class);
587 #endif
588         return 0;
589 }
590
591 /*
592  * Is this the address of a static object:
593  */
594 #ifdef __KERNEL__
595 static int static_obj(void *obj)
596 {
597         unsigned long start = (unsigned long) &_stext,
598                       end   = (unsigned long) &_end,
599                       addr  = (unsigned long) obj;
600
601         /*
602          * static variable?
603          */
604         if ((addr >= start) && (addr < end))
605                 return 1;
606
607         if (arch_is_kernel_data(addr))
608                 return 1;
609
610         /*
611          * in-kernel percpu var?
612          */
613         if (is_kernel_percpu_address(addr))
614                 return 1;
615
616         /*
617          * module static or percpu var?
618          */
619         return is_module_address(addr) || is_module_percpu_address(addr);
620 }
621 #endif
622
623 /*
624  * To make lock name printouts unique, we calculate a unique
625  * class->name_version generation counter:
626  */
627 static int count_matching_names(struct lock_class *new_class)
628 {
629         struct lock_class *class;
630         int count = 0;
631
632         if (!new_class->name)
633                 return 0;
634
635         list_for_each_entry_rcu(class, &all_lock_classes, lock_entry) {
636                 if (new_class->key - new_class->subclass == class->key)
637                         return class->name_version;
638                 if (class->name && !strcmp(class->name, new_class->name))
639                         count = max(count, class->name_version);
640         }
641
642         return count + 1;
643 }
644
645 /*
646  * Register a lock's class in the hash-table, if the class is not present
647  * yet. Otherwise we look it up. We cache the result in the lock object
648  * itself, so actual lookup of the hash should be once per lock object.
649  */
650 static inline struct lock_class *
651 look_up_lock_class(struct lockdep_map *lock, unsigned int subclass)
652 {
653         struct lockdep_subclass_key *key;
654         struct hlist_head *hash_head;
655         struct lock_class *class;
656
657         if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
658                 debug_locks_off();
659                 printk(KERN_ERR
660                         "BUG: looking up invalid subclass: %u\n", subclass);
661                 printk(KERN_ERR
662                         "turning off the locking correctness validator.\n");
663                 dump_stack();
664                 return NULL;
665         }
666
667         /*
668          * Static locks do not have their class-keys yet - for them the key
669          * is the lock object itself:
670          */
671         if (unlikely(!lock->key))
672                 lock->key = (void *)lock;
673
674         /*
675          * NOTE: the class-key must be unique. For dynamic locks, a static
676          * lock_class_key variable is passed in through the mutex_init()
677          * (or spin_lock_init()) call - which acts as the key. For static
678          * locks we use the lock object itself as the key.
679          */
680         BUILD_BUG_ON(sizeof(struct lock_class_key) >
681                         sizeof(struct lockdep_map));
682
683         key = lock->key->subkeys + subclass;
684
685         hash_head = classhashentry(key);
686
687         /*
688          * We do an RCU walk of the hash, see lockdep_free_key_range().
689          */
690         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
691                 return NULL;
692
693         hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
694                 if (class->key == key) {
695                         /*
696                          * Huh! same key, different name? Did someone trample
697                          * on some memory? We're most confused.
698                          */
699                         WARN_ON_ONCE(class->name != lock->name);
700                         return class;
701                 }
702         }
703
704         return NULL;
705 }
706
707 /*
708  * Register a lock's class in the hash-table, if the class is not present
709  * yet. Otherwise we look it up. We cache the result in the lock object
710  * itself, so actual lookup of the hash should be once per lock object.
711  */
712 static inline struct lock_class *
713 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
714 {
715         struct lockdep_subclass_key *key;
716         struct hlist_head *hash_head;
717         struct lock_class *class;
718
719         DEBUG_LOCKS_WARN_ON(!irqs_disabled());
720
721         class = look_up_lock_class(lock, subclass);
722         if (likely(class))
723                 goto out_set_class_cache;
724
725         /*
726          * Debug-check: all keys must be persistent!
727          */
728         if (!static_obj(lock->key)) {
729                 debug_locks_off();
730                 printk("INFO: trying to register non-static key.\n");
731                 printk("the code is fine but needs lockdep annotation.\n");
732                 printk("turning off the locking correctness validator.\n");
733                 dump_stack();
734
735                 return NULL;
736         }
737
738         key = lock->key->subkeys + subclass;
739         hash_head = classhashentry(key);
740
741         if (!graph_lock()) {
742                 return NULL;
743         }
744         /*
745          * We have to do the hash-walk again, to avoid races
746          * with another CPU:
747          */
748         hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
749                 if (class->key == key)
750                         goto out_unlock_set;
751         }
752
753         /*
754          * Allocate a new key from the static array, and add it to
755          * the hash:
756          */
757         if (nr_lock_classes >= MAX_LOCKDEP_KEYS) {
758                 if (!debug_locks_off_graph_unlock()) {
759                         return NULL;
760                 }
761
762                 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
763                 dump_stack();
764                 return NULL;
765         }
766         class = lock_classes + nr_lock_classes++;
767         debug_atomic_inc(nr_unused_locks);
768         class->key = key;
769         class->name = lock->name;
770         class->subclass = subclass;
771         INIT_LIST_HEAD(&class->lock_entry);
772         INIT_LIST_HEAD(&class->locks_before);
773         INIT_LIST_HEAD(&class->locks_after);
774         class->name_version = count_matching_names(class);
775         /*
776          * We use RCU's safe list-add method to make
777          * parallel walking of the hash-list safe:
778          */
779         hlist_add_head_rcu(&class->hash_entry, hash_head);
780         /*
781          * Add it to the global list of classes:
782          */
783         list_add_tail_rcu(&class->lock_entry, &all_lock_classes);
784
785         if (verbose(class)) {
786                 graph_unlock();
787
788                 printk("\nnew class %p: %s", class->key, class->name);
789                 if (class->name_version > 1)
790                         printk("#%d", class->name_version);
791                 printk("\n");
792                 dump_stack();
793
794                 if (!graph_lock()) {
795                         return NULL;
796                 }
797         }
798 out_unlock_set:
799         graph_unlock();
800
801 out_set_class_cache:
802         if (!subclass || force)
803                 lock->class_cache[0] = class;
804         else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
805                 lock->class_cache[subclass] = class;
806
807         /*
808          * Hash collision, did we smoke some? We found a class with a matching
809          * hash but the subclass -- which is hashed in -- didn't match.
810          */
811         if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
812                 return NULL;
813
814         return class;
815 }
816
817 #ifdef CONFIG_PROVE_LOCKING
818 /*
819  * Allocate a lockdep entry. (assumes the graph_lock held, returns
820  * with NULL on failure)
821  */
822 static struct lock_list *alloc_list_entry(void)
823 {
824         if (nr_list_entries >= MAX_LOCKDEP_ENTRIES) {
825                 if (!debug_locks_off_graph_unlock())
826                         return NULL;
827
828                 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
829                 dump_stack();
830                 return NULL;
831         }
832         return list_entries + nr_list_entries++;
833 }
834
835 /*
836  * Add a new dependency to the head of the list:
837  */
838 static int add_lock_to_list(struct lock_class *class, struct lock_class *this,
839                             struct list_head *head, unsigned long ip,
840                             int distance, struct stack_trace *trace)
841 {
842         struct lock_list *entry;
843         /*
844          * Lock not present yet - get a new dependency struct and
845          * add it to the list:
846          */
847         entry = alloc_list_entry();
848         if (!entry)
849                 return 0;
850
851         entry->class = this;
852         entry->distance = distance;
853         entry->trace = *trace;
854         /*
855          * Both allocation and removal are done under the graph lock; but
856          * iteration is under RCU-sched; see look_up_lock_class() and
857          * lockdep_free_key_range().
858          */
859         list_add_tail_rcu(&entry->entry, head);
860
861         return 1;
862 }
863
864 /*
865  * For good efficiency of modular, we use power of 2
866  */
867 #define MAX_CIRCULAR_QUEUE_SIZE         4096UL
868 #define CQ_MASK                         (MAX_CIRCULAR_QUEUE_SIZE-1)
869
870 /*
871  * The circular_queue and helpers is used to implement the
872  * breadth-first search(BFS)algorithem, by which we can build
873  * the shortest path from the next lock to be acquired to the
874  * previous held lock if there is a circular between them.
875  */
876 struct circular_queue {
877         unsigned long element[MAX_CIRCULAR_QUEUE_SIZE];
878         unsigned int  front, rear;
879 };
880
881 static struct circular_queue lock_cq;
882
883 unsigned int max_bfs_queue_depth;
884
885 static unsigned int lockdep_dependency_gen_id;
886
887 static inline void __cq_init(struct circular_queue *cq)
888 {
889         cq->front = cq->rear = 0;
890         lockdep_dependency_gen_id++;
891 }
892
893 static inline int __cq_empty(struct circular_queue *cq)
894 {
895         return (cq->front == cq->rear);
896 }
897
898 static inline int __cq_full(struct circular_queue *cq)
899 {
900         return ((cq->rear + 1) & CQ_MASK) == cq->front;
901 }
902
903 static inline int __cq_enqueue(struct circular_queue *cq, unsigned long elem)
904 {
905         if (__cq_full(cq))
906                 return -1;
907
908         cq->element[cq->rear] = elem;
909         cq->rear = (cq->rear + 1) & CQ_MASK;
910         return 0;
911 }
912
913 static inline int __cq_dequeue(struct circular_queue *cq, unsigned long *elem)
914 {
915         if (__cq_empty(cq))
916                 return -1;
917
918         *elem = cq->element[cq->front];
919         cq->front = (cq->front + 1) & CQ_MASK;
920         return 0;
921 }
922
923 static inline unsigned int  __cq_get_elem_count(struct circular_queue *cq)
924 {
925         return (cq->rear - cq->front) & CQ_MASK;
926 }
927
928 static inline void mark_lock_accessed(struct lock_list *lock,
929                                         struct lock_list *parent)
930 {
931         unsigned long nr;
932
933         nr = lock - list_entries;
934         WARN_ON(nr >= nr_list_entries); /* Out-of-bounds, input fail */
935         lock->parent = parent;
936         lock->class->dep_gen_id = lockdep_dependency_gen_id;
937 }
938
939 static inline unsigned long lock_accessed(struct lock_list *lock)
940 {
941         unsigned long nr;
942
943         nr = lock - list_entries;
944         WARN_ON(nr >= nr_list_entries); /* Out-of-bounds, input fail */
945         return lock->class->dep_gen_id == lockdep_dependency_gen_id;
946 }
947
948 static inline struct lock_list *get_lock_parent(struct lock_list *child)
949 {
950         return child->parent;
951 }
952
953 static inline int get_lock_depth(struct lock_list *child)
954 {
955         int depth = 0;
956         struct lock_list *parent;
957
958         while ((parent = get_lock_parent(child))) {
959                 child = parent;
960                 depth++;
961         }
962         return depth;
963 }
964
965 static int __bfs(struct lock_list *source_entry,
966                  void *data,
967                  int (*match)(struct lock_list *entry, void *data),
968                  struct lock_list **target_entry,
969                  int forward)
970 {
971         struct lock_list *entry;
972         struct list_head *head;
973         struct circular_queue *cq = &lock_cq;
974         int ret = 1;
975
976         if (match(source_entry, data)) {
977                 *target_entry = source_entry;
978                 ret = 0;
979                 goto exit;
980         }
981
982         if (forward)
983                 head = &source_entry->class->locks_after;
984         else
985                 head = &source_entry->class->locks_before;
986
987         if (list_empty(head))
988                 goto exit;
989
990         __cq_init(cq);
991         __cq_enqueue(cq, (unsigned long)source_entry);
992
993         while (!__cq_empty(cq)) {
994                 struct lock_list *lock;
995
996                 __cq_dequeue(cq, (unsigned long *)&lock);
997
998                 if (!lock->class) {
999                         ret = -2;
1000                         goto exit;
1001                 }
1002
1003                 if (forward)
1004                         head = &lock->class->locks_after;
1005                 else
1006                         head = &lock->class->locks_before;
1007
1008                 DEBUG_LOCKS_WARN_ON(!irqs_disabled());
1009
1010                 list_for_each_entry_rcu(entry, head, entry) {
1011                         if (!lock_accessed(entry)) {
1012                                 unsigned int cq_depth;
1013                                 mark_lock_accessed(entry, lock);
1014                                 if (match(entry, data)) {
1015                                         *target_entry = entry;
1016                                         ret = 0;
1017                                         goto exit;
1018                                 }
1019
1020                                 if (__cq_enqueue(cq, (unsigned long)entry)) {
1021                                         ret = -1;
1022                                         goto exit;
1023                                 }
1024                                 cq_depth = __cq_get_elem_count(cq);
1025                                 if (max_bfs_queue_depth < cq_depth)
1026                                         max_bfs_queue_depth = cq_depth;
1027                         }
1028                 }
1029         }
1030 exit:
1031         return ret;
1032 }
1033
1034 static inline int __bfs_forwards(struct lock_list *src_entry,
1035                         void *data,
1036                         int (*match)(struct lock_list *entry, void *data),
1037                         struct lock_list **target_entry)
1038 {
1039         return __bfs(src_entry, data, match, target_entry, 1);
1040
1041 }
1042
1043 static inline int __bfs_backwards(struct lock_list *src_entry,
1044                         void *data,
1045                         int (*match)(struct lock_list *entry, void *data),
1046                         struct lock_list **target_entry)
1047 {
1048         return __bfs(src_entry, data, match, target_entry, 0);
1049
1050 }
1051
1052 /*
1053  * Recursive, forwards-direction lock-dependency checking, used for
1054  * both noncyclic checking and for hardirq-unsafe/softirq-unsafe
1055  * checking.
1056  */
1057
1058 /*
1059  * Print a dependency chain entry (this is only done when a deadlock
1060  * has been detected):
1061  */
1062 static noinline int
1063 print_circular_bug_entry(struct lock_list *target, int depth)
1064 {
1065         if (debug_locks_silent)
1066                 return 0;
1067         printk("\n-> #%u", depth);
1068         print_lock_name(target->class);
1069         printk(":\n");
1070         print_stack_trace(&target->trace, 6);
1071
1072         return 0;
1073 }
1074
1075 static void
1076 print_circular_lock_scenario(struct held_lock *src,
1077                              struct held_lock *tgt,
1078                              struct lock_list *prt)
1079 {
1080         struct lock_class *source = hlock_class(src);
1081         struct lock_class *target = hlock_class(tgt);
1082         struct lock_class *parent = prt->class;
1083
1084         /*
1085          * A direct locking problem where unsafe_class lock is taken
1086          * directly by safe_class lock, then all we need to show
1087          * is the deadlock scenario, as it is obvious that the
1088          * unsafe lock is taken under the safe lock.
1089          *
1090          * But if there is a chain instead, where the safe lock takes
1091          * an intermediate lock (middle_class) where this lock is
1092          * not the same as the safe lock, then the lock chain is
1093          * used to describe the problem. Otherwise we would need
1094          * to show a different CPU case for each link in the chain
1095          * from the safe_class lock to the unsafe_class lock.
1096          */
1097         if (parent != source) {
1098                 printk("Chain exists of:\n  ");
1099                 __print_lock_name(source);
1100                 printk(" --> ");
1101                 __print_lock_name(parent);
1102                 printk(" --> ");
1103                 __print_lock_name(target);
1104                 printk("\n\n");
1105         }
1106
1107         printk(" Possible unsafe locking scenario:\n\n");
1108         printk("       CPU0                    CPU1\n");
1109         printk("       ----                    ----\n");
1110         printk("  lock(");
1111         __print_lock_name(target);
1112         printk(");\n");
1113         printk("                               lock(");
1114         __print_lock_name(parent);
1115         printk(");\n");
1116         printk("                               lock(");
1117         __print_lock_name(target);
1118         printk(");\n");
1119         printk("  lock(");
1120         __print_lock_name(source);
1121         printk(");\n");
1122         printk("\n *** DEADLOCK ***\n\n");
1123 }
1124
1125 /*
1126  * When a circular dependency is detected, print the
1127  * header first:
1128  */
1129 static noinline int
1130 print_circular_bug_header(struct lock_list *entry, unsigned int depth,
1131                         struct held_lock *check_src,
1132                         struct held_lock *check_tgt)
1133 {
1134         struct task_struct *curr = current;
1135
1136         if (debug_locks_silent)
1137                 return 0;
1138
1139         printk("\n");
1140         printk("======================================================\n");
1141         printk("[ INFO: possible circular locking dependency detected ]\n");
1142         print_kernel_ident();
1143         printk("-------------------------------------------------------\n");
1144         printk("%s/%d is trying to acquire lock:\n",
1145                 curr->comm, task_pid_nr(curr));
1146         print_lock(check_src);
1147         printk("\nbut task is already holding lock:\n");
1148         print_lock(check_tgt);
1149         printk("\nwhich lock already depends on the new lock.\n\n");
1150         printk("\nthe existing dependency chain (in reverse order) is:\n");
1151
1152         print_circular_bug_entry(entry, depth);
1153
1154         return 0;
1155 }
1156
1157 static inline int class_equal(struct lock_list *entry, void *data)
1158 {
1159         return entry->class == data;
1160 }
1161
1162 static noinline int print_circular_bug(struct lock_list *this,
1163                                 struct lock_list *target,
1164                                 struct held_lock *check_src,
1165                                 struct held_lock *check_tgt)
1166 {
1167         struct task_struct *curr = current;
1168         struct lock_list *parent;
1169         struct lock_list *first_parent;
1170         int depth;
1171
1172         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1173                 return 0;
1174
1175         if (!save_trace(&this->trace))
1176                 return 0;
1177
1178         depth = get_lock_depth(target);
1179
1180         print_circular_bug_header(target, depth, check_src, check_tgt);
1181
1182         parent = get_lock_parent(target);
1183         first_parent = parent;
1184
1185         while (parent) {
1186                 print_circular_bug_entry(parent, --depth);
1187                 parent = get_lock_parent(parent);
1188         }
1189
1190         printk("\nother info that might help us debug this:\n\n");
1191         print_circular_lock_scenario(check_src, check_tgt,
1192                                      first_parent);
1193
1194         lockdep_print_held_locks(curr);
1195
1196         printk("\nstack backtrace:\n");
1197         dump_stack();
1198
1199         return 0;
1200 }
1201
1202 static noinline int print_bfs_bug(int ret)
1203 {
1204         if (!debug_locks_off_graph_unlock())
1205                 return 0;
1206
1207         /*
1208          * Breadth-first-search failed, graph got corrupted?
1209          */
1210         WARN(1, "lockdep bfs error:%d\n", ret);
1211
1212         return 0;
1213 }
1214
1215 static int noop_count(struct lock_list *entry, void *data)
1216 {
1217         (*(unsigned long *)data)++;
1218         return 0;
1219 }
1220
1221 static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
1222 {
1223         unsigned long  count = 0;
1224         struct lock_list *uninitialized_var(target_entry);
1225
1226         __bfs_forwards(this, (void *)&count, noop_count, &target_entry);
1227
1228         return count;
1229 }
1230 unsigned long lockdep_count_forward_deps(struct lock_class *class)
1231 {
1232         unsigned long ret, flags;
1233         struct lock_list this;
1234
1235         this.parent = NULL;
1236         this.class = class;
1237
1238         local_irq_save(flags);
1239         arch_spin_lock(&lockdep_lock);
1240         ret = __lockdep_count_forward_deps(&this);
1241         arch_spin_unlock(&lockdep_lock);
1242         local_irq_restore(flags);
1243
1244         return ret;
1245 }
1246
1247 static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
1248 {
1249         unsigned long  count = 0;
1250         struct lock_list *uninitialized_var(target_entry);
1251
1252         __bfs_backwards(this, (void *)&count, noop_count, &target_entry);
1253
1254         return count;
1255 }
1256
1257 unsigned long lockdep_count_backward_deps(struct lock_class *class)
1258 {
1259         unsigned long ret, flags;
1260         struct lock_list this;
1261
1262         this.parent = NULL;
1263         this.class = class;
1264
1265         local_irq_save(flags);
1266         arch_spin_lock(&lockdep_lock);
1267         ret = __lockdep_count_backward_deps(&this);
1268         arch_spin_unlock(&lockdep_lock);
1269         local_irq_restore(flags);
1270
1271         return ret;
1272 }
1273
1274 /*
1275  * Prove that the dependency graph starting at <entry> can not
1276  * lead to <target>. Print an error and return 0 if it does.
1277  */
1278 static noinline int
1279 check_noncircular(struct lock_list *root, struct lock_class *target,
1280                 struct lock_list **target_entry)
1281 {
1282         int result;
1283
1284         debug_atomic_inc(nr_cyclic_checks);
1285
1286         result = __bfs_forwards(root, target, class_equal, target_entry);
1287
1288         return result;
1289 }
1290
1291 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
1292 /*
1293  * Forwards and backwards subgraph searching, for the purposes of
1294  * proving that two subgraphs can be connected by a new dependency
1295  * without creating any illegal irq-safe -> irq-unsafe lock dependency.
1296  */
1297
1298 static inline int usage_match(struct lock_list *entry, void *bit)
1299 {
1300         return entry->class->usage_mask & (1 << (enum lock_usage_bit)bit);
1301 }
1302
1303
1304
1305 /*
1306  * Find a node in the forwards-direction dependency sub-graph starting
1307  * at @root->class that matches @bit.
1308  *
1309  * Return 0 if such a node exists in the subgraph, and put that node
1310  * into *@target_entry.
1311  *
1312  * Return 1 otherwise and keep *@target_entry unchanged.
1313  * Return <0 on error.
1314  */
1315 static int
1316 find_usage_forwards(struct lock_list *root, enum lock_usage_bit bit,
1317                         struct lock_list **target_entry)
1318 {
1319         int result;
1320
1321         debug_atomic_inc(nr_find_usage_forwards_checks);
1322
1323         result = __bfs_forwards(root, (void *)bit, usage_match, target_entry);
1324
1325         return result;
1326 }
1327
1328 /*
1329  * Find a node in the backwards-direction dependency sub-graph starting
1330  * at @root->class that matches @bit.
1331  *
1332  * Return 0 if such a node exists in the subgraph, and put that node
1333  * into *@target_entry.
1334  *
1335  * Return 1 otherwise and keep *@target_entry unchanged.
1336  * Return <0 on error.
1337  */
1338 static int
1339 find_usage_backwards(struct lock_list *root, enum lock_usage_bit bit,
1340                         struct lock_list **target_entry)
1341 {
1342         int result;
1343
1344         debug_atomic_inc(nr_find_usage_backwards_checks);
1345
1346         result = __bfs_backwards(root, (void *)bit, usage_match, target_entry);
1347
1348         return result;
1349 }
1350
1351 static void print_lock_class_header(struct lock_class *class, int depth)
1352 {
1353         int bit;
1354
1355         printk("%*s->", depth, "");
1356         print_lock_name(class);
1357         printk(" ops: %lu", class->ops);
1358         printk(" {\n");
1359
1360         for (bit = 0; bit < LOCK_USAGE_STATES; bit++) {
1361                 if (class->usage_mask & (1 << bit)) {
1362                         int len = depth;
1363
1364                         len += printk("%*s   %s", depth, "", usage_str[bit]);
1365                         len += printk(" at:\n");
1366                         print_stack_trace(class->usage_traces + bit, len);
1367                 }
1368         }
1369         printk("%*s }\n", depth, "");
1370
1371         printk("%*s ... key      at: ",depth,"");
1372         print_ip_sym((unsigned long)class->key);
1373 }
1374
1375 /*
1376  * printk the shortest lock dependencies from @start to @end in reverse order:
1377  */
1378 static void __used
1379 print_shortest_lock_dependencies(struct lock_list *leaf,
1380                                 struct lock_list *root)
1381 {
1382         struct lock_list *entry = leaf;
1383         int depth;
1384
1385         /*compute depth from generated tree by BFS*/
1386         depth = get_lock_depth(leaf);
1387
1388         do {
1389                 print_lock_class_header(entry->class, depth);
1390                 printk("%*s ... acquired at:\n", depth, "");
1391                 print_stack_trace(&entry->trace, 2);
1392                 printk("\n");
1393
1394                 if (depth == 0 && (entry != root)) {
1395                         printk("lockdep:%s bad path found in chain graph\n", __func__);
1396                         break;
1397                 }
1398
1399                 entry = get_lock_parent(entry);
1400                 depth--;
1401         } while (entry && (depth >= 0));
1402
1403         return;
1404 }
1405
1406 static void
1407 print_irq_lock_scenario(struct lock_list *safe_entry,
1408                         struct lock_list *unsafe_entry,
1409                         struct lock_class *prev_class,
1410                         struct lock_class *next_class)
1411 {
1412         struct lock_class *safe_class = safe_entry->class;
1413         struct lock_class *unsafe_class = unsafe_entry->class;
1414         struct lock_class *middle_class = prev_class;
1415
1416         if (middle_class == safe_class)
1417                 middle_class = next_class;
1418
1419         /*
1420          * A direct locking problem where unsafe_class lock is taken
1421          * directly by safe_class lock, then all we need to show
1422          * is the deadlock scenario, as it is obvious that the
1423          * unsafe lock is taken under the safe lock.
1424          *
1425          * But if there is a chain instead, where the safe lock takes
1426          * an intermediate lock (middle_class) where this lock is
1427          * not the same as the safe lock, then the lock chain is
1428          * used to describe the problem. Otherwise we would need
1429          * to show a different CPU case for each link in the chain
1430          * from the safe_class lock to the unsafe_class lock.
1431          */
1432         if (middle_class != unsafe_class) {
1433                 printk("Chain exists of:\n  ");
1434                 __print_lock_name(safe_class);
1435                 printk(" --> ");
1436                 __print_lock_name(middle_class);
1437                 printk(" --> ");
1438                 __print_lock_name(unsafe_class);
1439                 printk("\n\n");
1440         }
1441
1442         printk(" Possible interrupt unsafe locking scenario:\n\n");
1443         printk("       CPU0                    CPU1\n");
1444         printk("       ----                    ----\n");
1445         printk("  lock(");
1446         __print_lock_name(unsafe_class);
1447         printk(");\n");
1448         printk("                               local_irq_disable();\n");
1449         printk("                               lock(");
1450         __print_lock_name(safe_class);
1451         printk(");\n");
1452         printk("                               lock(");
1453         __print_lock_name(middle_class);
1454         printk(");\n");
1455         printk("  <Interrupt>\n");
1456         printk("    lock(");
1457         __print_lock_name(safe_class);
1458         printk(");\n");
1459         printk("\n *** DEADLOCK ***\n\n");
1460 }
1461
1462 static int
1463 print_bad_irq_dependency(struct task_struct *curr,
1464                          struct lock_list *prev_root,
1465                          struct lock_list *next_root,
1466                          struct lock_list *backwards_entry,
1467                          struct lock_list *forwards_entry,
1468                          struct held_lock *prev,
1469                          struct held_lock *next,
1470                          enum lock_usage_bit bit1,
1471                          enum lock_usage_bit bit2,
1472                          const char *irqclass)
1473 {
1474         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1475                 return 0;
1476
1477         printk("\n");
1478         printk("======================================================\n");
1479         printk("[ INFO: %s-safe -> %s-unsafe lock order detected ]\n",
1480                 irqclass, irqclass);
1481         print_kernel_ident();
1482         printk("------------------------------------------------------\n");
1483         printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
1484                 curr->comm, task_pid_nr(curr),
1485                 curr->hardirq_context, hardirq_count() >> HARDIRQ_SHIFT,
1486                 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
1487                 curr->hardirqs_enabled,
1488                 curr->softirqs_enabled);
1489         print_lock(next);
1490
1491         printk("\nand this task is already holding:\n");
1492         print_lock(prev);
1493         printk("which would create a new lock dependency:\n");
1494         print_lock_name(hlock_class(prev));
1495         printk(" ->");
1496         print_lock_name(hlock_class(next));
1497         printk("\n");
1498
1499         printk("\nbut this new dependency connects a %s-irq-safe lock:\n",
1500                 irqclass);
1501         print_lock_name(backwards_entry->class);
1502         printk("\n... which became %s-irq-safe at:\n", irqclass);
1503
1504         print_stack_trace(backwards_entry->class->usage_traces + bit1, 1);
1505
1506         printk("\nto a %s-irq-unsafe lock:\n", irqclass);
1507         print_lock_name(forwards_entry->class);
1508         printk("\n... which became %s-irq-unsafe at:\n", irqclass);
1509         printk("...");
1510
1511         print_stack_trace(forwards_entry->class->usage_traces + bit2, 1);
1512
1513         printk("\nother info that might help us debug this:\n\n");
1514         print_irq_lock_scenario(backwards_entry, forwards_entry,
1515                                 hlock_class(prev), hlock_class(next));
1516
1517         lockdep_print_held_locks(curr);
1518
1519         printk("\nthe dependencies between %s-irq-safe lock", irqclass);
1520         printk(" and the holding lock:\n");
1521         if (!save_trace(&prev_root->trace))
1522                 return 0;
1523         print_shortest_lock_dependencies(backwards_entry, prev_root);
1524
1525         printk("\nthe dependencies between the lock to be acquired");
1526         printk(" and %s-irq-unsafe lock:\n", irqclass);
1527         if (!save_trace(&next_root->trace))
1528                 return 0;
1529         print_shortest_lock_dependencies(forwards_entry, next_root);
1530
1531         printk("\nstack backtrace:\n");
1532         dump_stack();
1533
1534         return 0;
1535 }
1536
1537 static int
1538 check_usage(struct task_struct *curr, struct held_lock *prev,
1539             struct held_lock *next, enum lock_usage_bit bit_backwards,
1540             enum lock_usage_bit bit_forwards, const char *irqclass)
1541 {
1542         int ret;
1543         struct lock_list this, that;
1544         struct lock_list *uninitialized_var(target_entry);
1545         struct lock_list *uninitialized_var(target_entry1);
1546
1547         this.parent = NULL;
1548
1549         this.class = hlock_class(prev);
1550         ret = find_usage_backwards(&this, bit_backwards, &target_entry);
1551         if (ret < 0)
1552                 return print_bfs_bug(ret);
1553         if (ret == 1)
1554                 return ret;
1555
1556         that.parent = NULL;
1557         that.class = hlock_class(next);
1558         ret = find_usage_forwards(&that, bit_forwards, &target_entry1);
1559         if (ret < 0)
1560                 return print_bfs_bug(ret);
1561         if (ret == 1)
1562                 return ret;
1563
1564         return print_bad_irq_dependency(curr, &this, &that,
1565                         target_entry, target_entry1,
1566                         prev, next,
1567                         bit_backwards, bit_forwards, irqclass);
1568 }
1569
1570 static const char *state_names[] = {
1571 #define LOCKDEP_STATE(__STATE) \
1572         __stringify(__STATE),
1573 #include "lockdep_states.h"
1574 #undef LOCKDEP_STATE
1575 };
1576
1577 static const char *state_rnames[] = {
1578 #define LOCKDEP_STATE(__STATE) \
1579         __stringify(__STATE)"-READ",
1580 #include "lockdep_states.h"
1581 #undef LOCKDEP_STATE
1582 };
1583
1584 static inline const char *state_name(enum lock_usage_bit bit)
1585 {
1586         return (bit & 1) ? state_rnames[bit >> 2] : state_names[bit >> 2];
1587 }
1588
1589 static int exclusive_bit(int new_bit)
1590 {
1591         /*
1592          * USED_IN
1593          * USED_IN_READ
1594          * ENABLED
1595          * ENABLED_READ
1596          *
1597          * bit 0 - write/read
1598          * bit 1 - used_in/enabled
1599          * bit 2+  state
1600          */
1601
1602         int state = new_bit & ~3;
1603         int dir = new_bit & 2;
1604
1605         /*
1606          * keep state, bit flip the direction and strip read.
1607          */
1608         return state | (dir ^ 2);
1609 }
1610
1611 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
1612                            struct held_lock *next, enum lock_usage_bit bit)
1613 {
1614         /*
1615          * Prove that the new dependency does not connect a hardirq-safe
1616          * lock with a hardirq-unsafe lock - to achieve this we search
1617          * the backwards-subgraph starting at <prev>, and the
1618          * forwards-subgraph starting at <next>:
1619          */
1620         if (!check_usage(curr, prev, next, bit,
1621                            exclusive_bit(bit), state_name(bit)))
1622                 return 0;
1623
1624         bit++; /* _READ */
1625
1626         /*
1627          * Prove that the new dependency does not connect a hardirq-safe-read
1628          * lock with a hardirq-unsafe lock - to achieve this we search
1629          * the backwards-subgraph starting at <prev>, and the
1630          * forwards-subgraph starting at <next>:
1631          */
1632         if (!check_usage(curr, prev, next, bit,
1633                            exclusive_bit(bit), state_name(bit)))
1634                 return 0;
1635
1636         return 1;
1637 }
1638
1639 static int
1640 check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
1641                 struct held_lock *next)
1642 {
1643 #define LOCKDEP_STATE(__STATE)                                          \
1644         if (!check_irq_usage(curr, prev, next, LOCK_USED_IN_##__STATE)) \
1645                 return 0;
1646 #include "lockdep_states.h"
1647 #undef LOCKDEP_STATE
1648
1649         return 1;
1650 }
1651
1652 static void inc_chains(void)
1653 {
1654         if (current->hardirq_context)
1655                 nr_hardirq_chains++;
1656         else {
1657                 if (current->softirq_context)
1658                         nr_softirq_chains++;
1659                 else
1660                         nr_process_chains++;
1661         }
1662 }
1663
1664 #else
1665
1666 static inline int
1667 check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
1668                 struct held_lock *next)
1669 {
1670         return 1;
1671 }
1672
1673 static inline void inc_chains(void)
1674 {
1675         nr_process_chains++;
1676 }
1677
1678 #endif
1679
1680 static void
1681 print_deadlock_scenario(struct held_lock *nxt,
1682                              struct held_lock *prv)
1683 {
1684         struct lock_class *next = hlock_class(nxt);
1685         struct lock_class *prev = hlock_class(prv);
1686
1687         printk(" Possible unsafe locking scenario:\n\n");
1688         printk("       CPU0\n");
1689         printk("       ----\n");
1690         printk("  lock(");
1691         __print_lock_name(prev);
1692         printk(");\n");
1693         printk("  lock(");
1694         __print_lock_name(next);
1695         printk(");\n");
1696         printk("\n *** DEADLOCK ***\n\n");
1697         printk(" May be due to missing lock nesting notation\n\n");
1698 }
1699
1700 static int
1701 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
1702                    struct held_lock *next)
1703 {
1704         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
1705                 return 0;
1706
1707         printk("\n");
1708         printk("=============================================\n");
1709         printk("[ INFO: possible recursive locking detected ]\n");
1710         print_kernel_ident();
1711         printk("---------------------------------------------\n");
1712         printk("%s/%d is trying to acquire lock:\n",
1713                 curr->comm, task_pid_nr(curr));
1714         print_lock(next);
1715         printk("\nbut task is already holding lock:\n");
1716         print_lock(prev);
1717
1718         printk("\nother info that might help us debug this:\n");
1719         print_deadlock_scenario(next, prev);
1720         lockdep_print_held_locks(curr);
1721
1722         printk("\nstack backtrace:\n");
1723         dump_stack();
1724
1725         return 0;
1726 }
1727
1728 /*
1729  * Check whether we are holding such a class already.
1730  *
1731  * (Note that this has to be done separately, because the graph cannot
1732  * detect such classes of deadlocks.)
1733  *
1734  * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
1735  */
1736 static int
1737 check_deadlock(struct task_struct *curr, struct held_lock *next,
1738                struct lockdep_map *next_instance, int read)
1739 {
1740         struct held_lock *prev;
1741         struct held_lock *nest = NULL;
1742         int i;
1743
1744         for (i = 0; i < curr->lockdep_depth; i++) {
1745                 prev = curr->held_locks + i;
1746
1747                 if (prev->instance == next->nest_lock)
1748                         nest = prev;
1749
1750                 if (hlock_class(prev) != hlock_class(next))
1751                         continue;
1752
1753                 /*
1754                  * Allow read-after-read recursion of the same
1755                  * lock class (i.e. read_lock(lock)+read_lock(lock)):
1756                  */
1757                 if ((read == 2) && prev->read)
1758                         return 2;
1759
1760                 /*
1761                  * We're holding the nest_lock, which serializes this lock's
1762                  * nesting behaviour.
1763                  */
1764                 if (nest)
1765                         return 2;
1766
1767                 return print_deadlock_bug(curr, prev, next);
1768         }
1769         return 1;
1770 }
1771
1772 /*
1773  * There was a chain-cache miss, and we are about to add a new dependency
1774  * to a previous lock. We recursively validate the following rules:
1775  *
1776  *  - would the adding of the <prev> -> <next> dependency create a
1777  *    circular dependency in the graph? [== circular deadlock]
1778  *
1779  *  - does the new prev->next dependency connect any hardirq-safe lock
1780  *    (in the full backwards-subgraph starting at <prev>) with any
1781  *    hardirq-unsafe lock (in the full forwards-subgraph starting at
1782  *    <next>)? [== illegal lock inversion with hardirq contexts]
1783  *
1784  *  - does the new prev->next dependency connect any softirq-safe lock
1785  *    (in the full backwards-subgraph starting at <prev>) with any
1786  *    softirq-unsafe lock (in the full forwards-subgraph starting at
1787  *    <next>)? [== illegal lock inversion with softirq contexts]
1788  *
1789  * any of these scenarios could lead to a deadlock.
1790  *
1791  * Then if all the validations pass, we add the forwards and backwards
1792  * dependency.
1793  */
1794 static int
1795 check_prev_add(struct task_struct *curr, struct held_lock *prev,
1796                struct held_lock *next, int distance, int *stack_saved)
1797 {
1798         struct lock_list *entry;
1799         int ret;
1800         struct lock_list this;
1801         struct lock_list *uninitialized_var(target_entry);
1802         /*
1803          * Static variable, serialized by the graph_lock().
1804          *
1805          * We use this static variable to save the stack trace in case
1806          * we call into this function multiple times due to encountering
1807          * trylocks in the held lock stack.
1808          */
1809         static struct stack_trace trace;
1810
1811         /*
1812          * Prove that the new <prev> -> <next> dependency would not
1813          * create a circular dependency in the graph. (We do this by
1814          * forward-recursing into the graph starting at <next>, and
1815          * checking whether we can reach <prev>.)
1816          *
1817          * We are using global variables to control the recursion, to
1818          * keep the stackframe size of the recursive functions low:
1819          */
1820         this.class = hlock_class(next);
1821         this.parent = NULL;
1822         ret = check_noncircular(&this, hlock_class(prev), &target_entry);
1823         if (unlikely(!ret))
1824                 return print_circular_bug(&this, target_entry, next, prev);
1825         else if (unlikely(ret < 0))
1826                 return print_bfs_bug(ret);
1827
1828         if (!check_prev_add_irq(curr, prev, next))
1829                 return 0;
1830
1831         /*
1832          * For recursive read-locks we do all the dependency checks,
1833          * but we dont store read-triggered dependencies (only
1834          * write-triggered dependencies). This ensures that only the
1835          * write-side dependencies matter, and that if for example a
1836          * write-lock never takes any other locks, then the reads are
1837          * equivalent to a NOP.
1838          */
1839         if (next->read == 2 || prev->read == 2)
1840                 return 1;
1841         /*
1842          * Is the <prev> -> <next> dependency already present?
1843          *
1844          * (this may occur even though this is a new chain: consider
1845          *  e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
1846          *  chains - the second one will be new, but L1 already has
1847          *  L2 added to its dependency list, due to the first chain.)
1848          */
1849         list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
1850                 if (entry->class == hlock_class(next)) {
1851                         if (distance == 1)
1852                                 entry->distance = 1;
1853                         return 2;
1854                 }
1855         }
1856
1857         if (!*stack_saved) {
1858                 if (!save_trace(&trace))
1859                         return 0;
1860                 *stack_saved = 1;
1861         }
1862
1863         /*
1864          * Ok, all validations passed, add the new lock
1865          * to the previous lock's dependency list:
1866          */
1867         ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
1868                                &hlock_class(prev)->locks_after,
1869                                next->acquire_ip, distance, &trace);
1870
1871         if (!ret)
1872                 return 0;
1873
1874         ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
1875                                &hlock_class(next)->locks_before,
1876                                next->acquire_ip, distance, &trace);
1877         if (!ret)
1878                 return 0;
1879
1880         /*
1881          * Debugging printouts:
1882          */
1883         if (verbose(hlock_class(prev)) || verbose(hlock_class(next))) {
1884                 /* We drop graph lock, so another thread can overwrite trace. */
1885                 *stack_saved = 0;
1886                 graph_unlock();
1887                 printk("\n new dependency: ");
1888                 print_lock_name(hlock_class(prev));
1889                 printk(" => ");
1890                 print_lock_name(hlock_class(next));
1891                 printk("\n");
1892                 dump_stack();
1893                 return graph_lock();
1894         }
1895         return 1;
1896 }
1897
1898 /*
1899  * Add the dependency to all directly-previous locks that are 'relevant'.
1900  * The ones that are relevant are (in increasing distance from curr):
1901  * all consecutive trylock entries and the final non-trylock entry - or
1902  * the end of this context's lock-chain - whichever comes first.
1903  */
1904 static int
1905 check_prevs_add(struct task_struct *curr, struct held_lock *next)
1906 {
1907         int depth = curr->lockdep_depth;
1908         int stack_saved = 0;
1909         struct held_lock *hlock;
1910
1911         /*
1912          * Debugging checks.
1913          *
1914          * Depth must not be zero for a non-head lock:
1915          */
1916         if (!depth)
1917                 goto out_bug;
1918         /*
1919          * At least two relevant locks must exist for this
1920          * to be a head:
1921          */
1922         if (curr->held_locks[depth].irq_context !=
1923                         curr->held_locks[depth-1].irq_context)
1924                 goto out_bug;
1925
1926         for (;;) {
1927                 int distance = curr->lockdep_depth - depth + 1;
1928                 hlock = curr->held_locks + depth - 1;
1929                 /*
1930                  * Only non-recursive-read entries get new dependencies
1931                  * added:
1932                  */
1933                 if (hlock->read != 2 && hlock->check) {
1934                         if (!check_prev_add(curr, hlock, next,
1935                                                 distance, &stack_saved))
1936                                 return 0;
1937                         /*
1938                          * Stop after the first non-trylock entry,
1939                          * as non-trylock entries have added their
1940                          * own direct dependencies already, so this
1941                          * lock is connected to them indirectly:
1942                          */
1943                         if (!hlock->trylock)
1944                                 break;
1945                 }
1946                 depth--;
1947                 /*
1948                  * End of lock-stack?
1949                  */
1950                 if (!depth)
1951                         break;
1952                 /*
1953                  * Stop the search if we cross into another context:
1954                  */
1955                 if (curr->held_locks[depth].irq_context !=
1956                                 curr->held_locks[depth-1].irq_context)
1957                         break;
1958         }
1959         return 1;
1960 out_bug:
1961         if (!debug_locks_off_graph_unlock())
1962                 return 0;
1963
1964         /*
1965          * Clearly we all shouldn't be here, but since we made it we
1966          * can reliable say we messed up our state. See the above two
1967          * gotos for reasons why we could possibly end up here.
1968          */
1969         WARN_ON(1);
1970
1971         return 0;
1972 }
1973
1974 unsigned long nr_lock_chains;
1975 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
1976 int nr_chain_hlocks;
1977 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
1978
1979 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
1980 {
1981         return lock_classes + chain_hlocks[chain->base + i];
1982 }
1983
1984 /*
1985  * Look up a dependency chain. If the key is not present yet then
1986  * add it and return 1 - in this case the new dependency chain is
1987  * validated. If the key is already hashed, return 0.
1988  * (On return with 1 graph_lock is held.)
1989  */
1990 static inline int lookup_chain_cache(struct task_struct *curr,
1991                                      struct held_lock *hlock,
1992                                      u64 chain_key)
1993 {
1994         struct lock_class *class = hlock_class(hlock);
1995         struct hlist_head *hash_head = chainhashentry(chain_key);
1996         struct lock_chain *chain;
1997         struct held_lock *hlock_curr;
1998         int i, j;
1999
2000         /*
2001          * We might need to take the graph lock, ensure we've got IRQs
2002          * disabled to make this an IRQ-safe lock.. for recursion reasons
2003          * lockdep won't complain about its own locking errors.
2004          */
2005         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2006                 return 0;
2007         /*
2008          * We can walk it lock-free, because entries only get added
2009          * to the hash:
2010          */
2011         hlist_for_each_entry_rcu(chain, hash_head, entry) {
2012                 if (chain->chain_key == chain_key) {
2013 cache_hit:
2014                         debug_atomic_inc(chain_lookup_hits);
2015                         if (very_verbose(class))
2016                                 printk("\nhash chain already cached, key: "
2017                                         "%016Lx tail class: [%p] %s\n",
2018                                         (unsigned long long)chain_key,
2019                                         class->key, class->name);
2020                         return 0;
2021                 }
2022         }
2023         if (very_verbose(class))
2024                 printk("\nnew hash chain, key: %016Lx tail class: [%p] %s\n",
2025                         (unsigned long long)chain_key, class->key, class->name);
2026         /*
2027          * Allocate a new chain entry from the static array, and add
2028          * it to the hash:
2029          */
2030         if (!graph_lock())
2031                 return 0;
2032         /*
2033          * We have to walk the chain again locked - to avoid duplicates:
2034          */
2035         hlist_for_each_entry(chain, hash_head, entry) {
2036                 if (chain->chain_key == chain_key) {
2037                         graph_unlock();
2038                         goto cache_hit;
2039                 }
2040         }
2041         if (unlikely(nr_lock_chains >= MAX_LOCKDEP_CHAINS)) {
2042                 if (!debug_locks_off_graph_unlock())
2043                         return 0;
2044
2045                 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
2046                 dump_stack();
2047                 return 0;
2048         }
2049         chain = lock_chains + nr_lock_chains++;
2050         chain->chain_key = chain_key;
2051         chain->irq_context = hlock->irq_context;
2052         /* Find the first held_lock of current chain */
2053         for (i = curr->lockdep_depth - 1; i >= 0; i--) {
2054                 hlock_curr = curr->held_locks + i;
2055                 if (hlock_curr->irq_context != hlock->irq_context)
2056                         break;
2057         }
2058         i++;
2059         chain->depth = curr->lockdep_depth + 1 - i;
2060         if (likely(nr_chain_hlocks + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS)) {
2061                 chain->base = nr_chain_hlocks;
2062                 nr_chain_hlocks += chain->depth;
2063                 for (j = 0; j < chain->depth - 1; j++, i++) {
2064                         int lock_id = curr->held_locks[i].class_idx - 1;
2065                         chain_hlocks[chain->base + j] = lock_id;
2066                 }
2067                 chain_hlocks[chain->base + j] = class - lock_classes;
2068         }
2069         hlist_add_head_rcu(&chain->entry, hash_head);
2070         debug_atomic_inc(chain_lookup_misses);
2071         inc_chains();
2072
2073         return 1;
2074 }
2075
2076 static int validate_chain(struct task_struct *curr, struct lockdep_map *lock,
2077                 struct held_lock *hlock, int chain_head, u64 chain_key)
2078 {
2079         /*
2080          * Trylock needs to maintain the stack of held locks, but it
2081          * does not add new dependencies, because trylock can be done
2082          * in any order.
2083          *
2084          * We look up the chain_key and do the O(N^2) check and update of
2085          * the dependencies only if this is a new dependency chain.
2086          * (If lookup_chain_cache() returns with 1 it acquires
2087          * graph_lock for us)
2088          */
2089         if (!hlock->trylock && hlock->check &&
2090             lookup_chain_cache(curr, hlock, chain_key)) {
2091                 /*
2092                  * Check whether last held lock:
2093                  *
2094                  * - is irq-safe, if this lock is irq-unsafe
2095                  * - is softirq-safe, if this lock is hardirq-unsafe
2096                  *
2097                  * And check whether the new lock's dependency graph
2098                  * could lead back to the previous lock.
2099                  *
2100                  * any of these scenarios could lead to a deadlock. If
2101                  * All validations
2102                  */
2103                 int ret = check_deadlock(curr, hlock, lock, hlock->read);
2104
2105                 if (!ret)
2106                         return 0;
2107                 /*
2108                  * Mark recursive read, as we jump over it when
2109                  * building dependencies (just like we jump over
2110                  * trylock entries):
2111                  */
2112                 if (ret == 2)
2113                         hlock->read = 2;
2114                 /*
2115                  * Add dependency only if this lock is not the head
2116                  * of the chain, and if it's not a secondary read-lock:
2117                  */
2118                 if (!chain_head && ret != 2)
2119                         if (!check_prevs_add(curr, hlock))
2120                                 return 0;
2121                 graph_unlock();
2122         } else
2123                 /* after lookup_chain_cache(): */
2124                 if (unlikely(!debug_locks))
2125                         return 0;
2126
2127         return 1;
2128 }
2129 #else
2130 static inline int validate_chain(struct task_struct *curr,
2131                 struct lockdep_map *lock, struct held_lock *hlock,
2132                 int chain_head, u64 chain_key)
2133 {
2134         return 1;
2135 }
2136 #endif
2137
2138 /*
2139  * We are building curr_chain_key incrementally, so double-check
2140  * it from scratch, to make sure that it's done correctly:
2141  */
2142 static void check_chain_key(struct task_struct *curr)
2143 {
2144 #ifdef CONFIG_DEBUG_LOCKDEP
2145         struct held_lock *hlock, *prev_hlock = NULL;
2146         unsigned int i, id;
2147         u64 chain_key = 0;
2148
2149         for (i = 0; i < curr->lockdep_depth; i++) {
2150                 hlock = curr->held_locks + i;
2151                 if (chain_key != hlock->prev_chain_key) {
2152                         debug_locks_off();
2153                         /*
2154                          * We got mighty confused, our chain keys don't match
2155                          * with what we expect, someone trample on our task state?
2156                          */
2157                         WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
2158                                 curr->lockdep_depth, i,
2159                                 (unsigned long long)chain_key,
2160                                 (unsigned long long)hlock->prev_chain_key);
2161                         return;
2162                 }
2163                 id = hlock->class_idx - 1;
2164                 /*
2165                  * Whoops ran out of static storage again?
2166                  */
2167                 if (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
2168                         return;
2169
2170                 if (prev_hlock && (prev_hlock->irq_context !=
2171                                                         hlock->irq_context))
2172                         chain_key = 0;
2173                 chain_key = iterate_chain_key(chain_key, id);
2174                 prev_hlock = hlock;
2175         }
2176         if (chain_key != curr->curr_chain_key) {
2177                 debug_locks_off();
2178                 /*
2179                  * More smoking hash instead of calculating it, damn see these
2180                  * numbers float.. I bet that a pink elephant stepped on my memory.
2181                  */
2182                 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
2183                         curr->lockdep_depth, i,
2184                         (unsigned long long)chain_key,
2185                         (unsigned long long)curr->curr_chain_key);
2186         }
2187 #endif
2188 }
2189
2190 static void
2191 print_usage_bug_scenario(struct held_lock *lock)
2192 {
2193         struct lock_class *class = hlock_class(lock);
2194
2195         printk(" Possible unsafe locking scenario:\n\n");
2196         printk("       CPU0\n");
2197         printk("       ----\n");
2198         printk("  lock(");
2199         __print_lock_name(class);
2200         printk(");\n");
2201         printk("  <Interrupt>\n");
2202         printk("    lock(");
2203         __print_lock_name(class);
2204         printk(");\n");
2205         printk("\n *** DEADLOCK ***\n\n");
2206 }
2207
2208 static int
2209 print_usage_bug(struct task_struct *curr, struct held_lock *this,
2210                 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
2211 {
2212         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2213                 return 0;
2214
2215         printk("\n");
2216         printk("=================================\n");
2217         printk("[ INFO: inconsistent lock state ]\n");
2218         print_kernel_ident();
2219         printk("---------------------------------\n");
2220
2221         printk("inconsistent {%s} -> {%s} usage.\n",
2222                 usage_str[prev_bit], usage_str[new_bit]);
2223
2224         printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
2225                 curr->comm, task_pid_nr(curr),
2226                 trace_hardirq_context(curr), hardirq_count() >> HARDIRQ_SHIFT,
2227                 trace_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
2228                 trace_hardirqs_enabled(curr),
2229                 trace_softirqs_enabled(curr));
2230         print_lock(this);
2231
2232         printk("{%s} state was registered at:\n", usage_str[prev_bit]);
2233         print_stack_trace(hlock_class(this)->usage_traces + prev_bit, 1);
2234
2235         print_irqtrace_events(curr);
2236         printk("\nother info that might help us debug this:\n");
2237         print_usage_bug_scenario(this);
2238
2239         lockdep_print_held_locks(curr);
2240
2241         printk("\nstack backtrace:\n");
2242         dump_stack();
2243
2244         return 0;
2245 }
2246
2247 /*
2248  * Print out an error if an invalid bit is set:
2249  */
2250 static inline int
2251 valid_state(struct task_struct *curr, struct held_lock *this,
2252             enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
2253 {
2254         if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit)))
2255                 return print_usage_bug(curr, this, bad_bit, new_bit);
2256         return 1;
2257 }
2258
2259 static int mark_lock(struct task_struct *curr, struct held_lock *this,
2260                      enum lock_usage_bit new_bit);
2261
2262 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
2263
2264 /*
2265  * print irq inversion bug:
2266  */
2267 static int
2268 print_irq_inversion_bug(struct task_struct *curr,
2269                         struct lock_list *root, struct lock_list *other,
2270                         struct held_lock *this, int forwards,
2271                         const char *irqclass)
2272 {
2273         struct lock_list *entry = other;
2274         struct lock_list *middle = NULL;
2275         int depth;
2276
2277         if (!debug_locks_off_graph_unlock() || debug_locks_silent)
2278                 return 0;
2279
2280         printk("\n");
2281         printk("=========================================================\n");
2282         printk("[ INFO: possible irq lock inversion dependency detected ]\n");
2283         print_kernel_ident();
2284         printk("---------------------------------------------------------\n");
2285         printk("%s/%d just changed the state of lock:\n",
2286                 curr->comm, task_pid_nr(curr));
2287         print_lock(this);
2288         if (forwards)
2289                 printk("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
2290         else
2291                 printk("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
2292         print_lock_name(other->class);
2293         printk("\n\nand interrupts could create inverse lock ordering between them.\n\n");
2294
2295         printk("\nother info that might help us debug this:\n");
2296
2297         /* Find a middle lock (if one exists) */
2298         depth = get_lock_depth(other);
2299         do {
2300                 if (depth == 0 && (entry != root)) {
2301                         printk("lockdep:%s bad path found in chain graph\n", __func__);
2302                         break;
2303                 }
2304                 middle = entry;
2305                 entry = get_lock_parent(entry);
2306                 depth--;
2307         } while (entry && entry != root && (depth >= 0));
2308         if (forwards)
2309                 print_irq_lock_scenario(root, other,
2310                         middle ? middle->class : root->class, other->class);
2311         else
2312                 print_irq_lock_scenario(other, root,
2313                         middle ? middle->class : other->class, root->class);
2314
2315         lockdep_print_held_locks(curr);
2316
2317         printk("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
2318         if (!save_trace(&root->trace))
2319                 return 0;
2320         print_shortest_lock_dependencies(other, root);
2321
2322         printk("\nstack backtrace:\n");
2323         dump_stack();
2324
2325         return 0;
2326 }
2327
2328 /*
2329  * Prove that in the forwards-direction subgraph starting at <this>
2330  * there is no lock matching <mask>:
2331  */
2332 static int
2333 check_usage_forwards(struct task_struct *curr, struct held_lock *this,
2334                      enum lock_usage_bit bit, const char *irqclass)
2335 {
2336         int ret;
2337         struct lock_list root;
2338         struct lock_list *uninitialized_var(target_entry);
2339
2340         root.parent = NULL;
2341         root.class = hlock_class(this);
2342         ret = find_usage_forwards(&root, bit, &target_entry);
2343         if (ret < 0)
2344                 return print_bfs_bug(ret);
2345         if (ret == 1)
2346                 return ret;
2347
2348         return print_irq_inversion_bug(curr, &root, target_entry,
2349                                         this, 1, irqclass);
2350 }
2351
2352 /*
2353  * Prove that in the backwards-direction subgraph starting at <this>
2354  * there is no lock matching <mask>:
2355  */
2356 static int
2357 check_usage_backwards(struct task_struct *curr, struct held_lock *this,
2358                       enum lock_usage_bit bit, const char *irqclass)
2359 {
2360         int ret;
2361         struct lock_list root;
2362         struct lock_list *uninitialized_var(target_entry);
2363
2364         root.parent = NULL;
2365         root.class = hlock_class(this);
2366         ret = find_usage_backwards(&root, bit, &target_entry);
2367         if (ret < 0)
2368                 return print_bfs_bug(ret);
2369         if (ret == 1)
2370                 return ret;
2371
2372         return print_irq_inversion_bug(curr, &root, target_entry,
2373                                         this, 0, irqclass);
2374 }
2375
2376 void print_irqtrace_events(struct task_struct *curr)
2377 {
2378         printk("irq event stamp: %u\n", curr->irq_events);
2379         printk("hardirqs last  enabled at (%u): ", curr->hardirq_enable_event);
2380         print_ip_sym(curr->hardirq_enable_ip);
2381         printk("hardirqs last disabled at (%u): ", curr->hardirq_disable_event);
2382         print_ip_sym(curr->hardirq_disable_ip);
2383         printk("softirqs last  enabled at (%u): ", curr->softirq_enable_event);
2384         print_ip_sym(curr->softirq_enable_ip);
2385         printk("softirqs last disabled at (%u): ", curr->softirq_disable_event);
2386         print_ip_sym(curr->softirq_disable_ip);
2387 }
2388
2389 static int HARDIRQ_verbose(struct lock_class *class)
2390 {
2391 #if HARDIRQ_VERBOSE
2392         return class_filter(class);
2393 #endif
2394         return 0;
2395 }
2396
2397 static int SOFTIRQ_verbose(struct lock_class *class)
2398 {
2399 #if SOFTIRQ_VERBOSE
2400         return class_filter(class);
2401 #endif
2402         return 0;
2403 }
2404
2405 static int RECLAIM_FS_verbose(struct lock_class *class)
2406 {
2407 #if RECLAIM_VERBOSE
2408         return class_filter(class);
2409 #endif
2410         return 0;
2411 }
2412
2413 #define STRICT_READ_CHECKS      1
2414
2415 static int (*state_verbose_f[])(struct lock_class *class) = {
2416 #define LOCKDEP_STATE(__STATE) \
2417         __STATE##_verbose,
2418 #include "lockdep_states.h"
2419 #undef LOCKDEP_STATE
2420 };
2421
2422 static inline int state_verbose(enum lock_usage_bit bit,
2423                                 struct lock_class *class)
2424 {
2425         return state_verbose_f[bit >> 2](class);
2426 }
2427
2428 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
2429                              enum lock_usage_bit bit, const char *name);
2430
2431 static int
2432 mark_lock_irq(struct task_struct *curr, struct held_lock *this,
2433                 enum lock_usage_bit new_bit)
2434 {
2435         int excl_bit = exclusive_bit(new_bit);
2436         int read = new_bit & 1;
2437         int dir = new_bit & 2;
2438
2439         /*
2440          * mark USED_IN has to look forwards -- to ensure no dependency
2441          * has ENABLED state, which would allow recursion deadlocks.
2442          *
2443          * mark ENABLED has to look backwards -- to ensure no dependee
2444          * has USED_IN state, which, again, would allow  recursion deadlocks.
2445          */
2446         check_usage_f usage = dir ?
2447                 check_usage_backwards : check_usage_forwards;
2448
2449         /*
2450          * Validate that this particular lock does not have conflicting
2451          * usage states.
2452          */
2453         if (!valid_state(curr, this, new_bit, excl_bit))
2454                 return 0;
2455
2456         /*
2457          * Validate that the lock dependencies don't have conflicting usage
2458          * states.
2459          */
2460         if ((!read || !dir || STRICT_READ_CHECKS) &&
2461                         !usage(curr, this, excl_bit, state_name(new_bit & ~1)))
2462                 return 0;
2463
2464         /*
2465          * Check for read in write conflicts
2466          */
2467         if (!read) {
2468                 if (!valid_state(curr, this, new_bit, excl_bit + 1))
2469                         return 0;
2470
2471                 if (STRICT_READ_CHECKS &&
2472                         !usage(curr, this, excl_bit + 1,
2473                                 state_name(new_bit + 1)))
2474                         return 0;
2475         }
2476
2477         if (state_verbose(new_bit, hlock_class(this)))
2478                 return 2;
2479
2480         return 1;
2481 }
2482
2483 enum mark_type {
2484 #define LOCKDEP_STATE(__STATE)  __STATE,
2485 #include "lockdep_states.h"
2486 #undef LOCKDEP_STATE
2487 };
2488
2489 /*
2490  * Mark all held locks with a usage bit:
2491  */
2492 static int
2493 mark_held_locks(struct task_struct *curr, enum mark_type mark)
2494 {
2495         enum lock_usage_bit usage_bit;
2496         struct held_lock *hlock;
2497         int i;
2498
2499         for (i = 0; i < curr->lockdep_depth; i++) {
2500                 hlock = curr->held_locks + i;
2501
2502                 usage_bit = 2 + (mark << 2); /* ENABLED */
2503                 if (hlock->read)
2504                         usage_bit += 1; /* READ */
2505
2506                 BUG_ON(usage_bit >= LOCK_USAGE_STATES);
2507
2508                 if (!hlock->check)
2509                         continue;
2510
2511                 if (!mark_lock(curr, hlock, usage_bit))
2512                         return 0;
2513         }
2514
2515         return 1;
2516 }
2517
2518 /*
2519  * Hardirqs will be enabled:
2520  */
2521 static void __trace_hardirqs_on_caller(unsigned long ip)
2522 {
2523         struct task_struct *curr = current;
2524
2525         /* we'll do an OFF -> ON transition: */
2526         curr->hardirqs_enabled = 1;
2527
2528         /*
2529          * We are going to turn hardirqs on, so set the
2530          * usage bit for all held locks:
2531          */
2532         if (!mark_held_locks(curr, HARDIRQ))
2533                 return;
2534         /*
2535          * If we have softirqs enabled, then set the usage
2536          * bit for all held locks. (disabled hardirqs prevented
2537          * this bit from being set before)
2538          */
2539         if (curr->softirqs_enabled)
2540                 if (!mark_held_locks(curr, SOFTIRQ))
2541                         return;
2542
2543         curr->hardirq_enable_ip = ip;
2544         curr->hardirq_enable_event = ++curr->irq_events;
2545         debug_atomic_inc(hardirqs_on_events);
2546 }
2547
2548 __visible void trace_hardirqs_on_caller(unsigned long ip)
2549 {
2550         time_hardirqs_on(CALLER_ADDR0, ip);
2551
2552         if (unlikely(!debug_locks || current->lockdep_recursion))
2553                 return;
2554
2555         if (unlikely(current->hardirqs_enabled)) {
2556                 /*
2557                  * Neither irq nor preemption are disabled here
2558                  * so this is racy by nature but losing one hit
2559                  * in a stat is not a big deal.
2560                  */
2561                 __debug_atomic_inc(redundant_hardirqs_on);
2562                 return;
2563         }
2564
2565         /*
2566          * We're enabling irqs and according to our state above irqs weren't
2567          * already enabled, yet we find the hardware thinks they are in fact
2568          * enabled.. someone messed up their IRQ state tracing.
2569          */
2570         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2571                 return;
2572
2573         /*
2574          * See the fine text that goes along with this variable definition.
2575          */
2576         if (DEBUG_LOCKS_WARN_ON(unlikely(early_boot_irqs_disabled)))
2577                 return;
2578
2579         /*
2580          * Can't allow enabling interrupts while in an interrupt handler,
2581          * that's general bad form and such. Recursion, limited stack etc..
2582          */
2583         if (DEBUG_LOCKS_WARN_ON(current->hardirq_context))
2584                 return;
2585
2586         current->lockdep_recursion = 1;
2587         __trace_hardirqs_on_caller(ip);
2588         current->lockdep_recursion = 0;
2589 }
2590 EXPORT_SYMBOL(trace_hardirqs_on_caller);
2591
2592 void trace_hardirqs_on(void)
2593 {
2594         trace_hardirqs_on_caller(CALLER_ADDR0);
2595 }
2596 EXPORT_SYMBOL(trace_hardirqs_on);
2597
2598 /*
2599  * Hardirqs were disabled:
2600  */
2601 __visible void trace_hardirqs_off_caller(unsigned long ip)
2602 {
2603         struct task_struct *curr = current;
2604
2605         time_hardirqs_off(CALLER_ADDR0, ip);
2606
2607         if (unlikely(!debug_locks || current->lockdep_recursion))
2608                 return;
2609
2610         /*
2611          * So we're supposed to get called after you mask local IRQs, but for
2612          * some reason the hardware doesn't quite think you did a proper job.
2613          */
2614         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2615                 return;
2616
2617         if (curr->hardirqs_enabled) {
2618                 /*
2619                  * We have done an ON -> OFF transition:
2620                  */
2621                 curr->hardirqs_enabled = 0;
2622                 curr->hardirq_disable_ip = ip;
2623                 curr->hardirq_disable_event = ++curr->irq_events;
2624                 debug_atomic_inc(hardirqs_off_events);
2625         } else
2626                 debug_atomic_inc(redundant_hardirqs_off);
2627 }
2628 EXPORT_SYMBOL(trace_hardirqs_off_caller);
2629
2630 void trace_hardirqs_off(void)
2631 {
2632         trace_hardirqs_off_caller(CALLER_ADDR0);
2633 }
2634 EXPORT_SYMBOL(trace_hardirqs_off);
2635
2636 /*
2637  * Softirqs will be enabled:
2638  */
2639 void trace_softirqs_on(unsigned long ip)
2640 {
2641         struct task_struct *curr = current;
2642
2643         if (unlikely(!debug_locks || current->lockdep_recursion))
2644                 return;
2645
2646         /*
2647          * We fancy IRQs being disabled here, see softirq.c, avoids
2648          * funny state and nesting things.
2649          */
2650         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2651                 return;
2652
2653         if (curr->softirqs_enabled) {
2654                 debug_atomic_inc(redundant_softirqs_on);
2655                 return;
2656         }
2657
2658         current->lockdep_recursion = 1;
2659         /*
2660          * We'll do an OFF -> ON transition:
2661          */
2662         curr->softirqs_enabled = 1;
2663         curr->softirq_enable_ip = ip;
2664         curr->softirq_enable_event = ++curr->irq_events;
2665         debug_atomic_inc(softirqs_on_events);
2666         /*
2667          * We are going to turn softirqs on, so set the
2668          * usage bit for all held locks, if hardirqs are
2669          * enabled too:
2670          */
2671         if (curr->hardirqs_enabled)
2672                 mark_held_locks(curr, SOFTIRQ);
2673         current->lockdep_recursion = 0;
2674 }
2675
2676 /*
2677  * Softirqs were disabled:
2678  */
2679 void trace_softirqs_off(unsigned long ip)
2680 {
2681         struct task_struct *curr = current;
2682
2683         if (unlikely(!debug_locks || current->lockdep_recursion))
2684                 return;
2685
2686         /*
2687          * We fancy IRQs being disabled here, see softirq.c
2688          */
2689         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
2690                 return;
2691
2692         if (curr->softirqs_enabled) {
2693                 /*
2694                  * We have done an ON -> OFF transition:
2695                  */
2696                 curr->softirqs_enabled = 0;
2697                 curr->softirq_disable_ip = ip;
2698                 curr->softirq_disable_event = ++curr->irq_events;
2699                 debug_atomic_inc(softirqs_off_events);
2700                 /*
2701                  * Whoops, we wanted softirqs off, so why aren't they?
2702                  */
2703                 DEBUG_LOCKS_WARN_ON(!softirq_count());
2704         } else
2705                 debug_atomic_inc(redundant_softirqs_off);
2706 }
2707
2708 static void __lockdep_trace_alloc(gfp_t gfp_mask, unsigned long flags)
2709 {
2710         struct task_struct *curr = current;
2711
2712         if (unlikely(!debug_locks))
2713                 return;
2714
2715         /* no reclaim without waiting on it */
2716         if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
2717                 return;
2718
2719         /* this guy won't enter reclaim */
2720         if ((curr->flags & PF_MEMALLOC) && !(gfp_mask & __GFP_NOMEMALLOC))
2721                 return;
2722
2723         /* We're only interested __GFP_FS allocations for now */
2724         if (!(gfp_mask & __GFP_FS))
2725                 return;
2726
2727         /*
2728          * Oi! Can't be having __GFP_FS allocations with IRQs disabled.
2729          */
2730         if (DEBUG_LOCKS_WARN_ON(irqs_disabled_flags(flags)))
2731                 return;
2732
2733         mark_held_locks(curr, RECLAIM_FS);
2734 }
2735
2736 static void check_flags(unsigned long flags);
2737
2738 void lockdep_trace_alloc(gfp_t gfp_mask)
2739 {
2740         unsigned long flags;
2741
2742         if (unlikely(current->lockdep_recursion))
2743                 return;
2744
2745         raw_local_irq_save(flags);
2746         check_flags(flags);
2747         current->lockdep_recursion = 1;
2748         __lockdep_trace_alloc(gfp_mask, flags);
2749         current->lockdep_recursion = 0;
2750         raw_local_irq_restore(flags);
2751 }
2752
2753 static int mark_irqflags(struct task_struct *curr, struct held_lock *hlock)
2754 {
2755         /*
2756          * If non-trylock use in a hardirq or softirq context, then
2757          * mark the lock as used in these contexts:
2758          */
2759         if (!hlock->trylock) {
2760                 if (hlock->read) {
2761                         if (curr->hardirq_context)
2762                                 if (!mark_lock(curr, hlock,
2763                                                 LOCK_USED_IN_HARDIRQ_READ))
2764                                         return 0;
2765                         if (curr->softirq_context)
2766                                 if (!mark_lock(curr, hlock,
2767                                                 LOCK_USED_IN_SOFTIRQ_READ))
2768                                         return 0;
2769                 } else {
2770                         if (curr->hardirq_context)
2771                                 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
2772                                         return 0;
2773                         if (curr->softirq_context)
2774                                 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
2775                                         return 0;
2776                 }
2777         }
2778         if (!hlock->hardirqs_off) {
2779                 if (hlock->read) {
2780                         if (!mark_lock(curr, hlock,
2781                                         LOCK_ENABLED_HARDIRQ_READ))
2782                                 return 0;
2783                         if (curr->softirqs_enabled)
2784                                 if (!mark_lock(curr, hlock,
2785                                                 LOCK_ENABLED_SOFTIRQ_READ))
2786                                         return 0;
2787                 } else {
2788                         if (!mark_lock(curr, hlock,
2789                                         LOCK_ENABLED_HARDIRQ))
2790                                 return 0;
2791                         if (curr->softirqs_enabled)
2792                                 if (!mark_lock(curr, hlock,
2793                                                 LOCK_ENABLED_SOFTIRQ))
2794                                         return 0;
2795                 }
2796         }
2797
2798         /*
2799          * We reuse the irq context infrastructure more broadly as a general
2800          * context checking code. This tests GFP_FS recursion (a lock taken
2801          * during reclaim for a GFP_FS allocation is held over a GFP_FS
2802          * allocation).
2803          */
2804         if (!hlock->trylock && (curr->lockdep_reclaim_gfp & __GFP_FS)) {
2805                 if (hlock->read) {
2806                         if (!mark_lock(curr, hlock, LOCK_USED_IN_RECLAIM_FS_READ))
2807                                         return 0;
2808                 } else {
2809                         if (!mark_lock(curr, hlock, LOCK_USED_IN_RECLAIM_FS))
2810                                         return 0;
2811                 }
2812         }
2813
2814         return 1;
2815 }
2816
2817 static int separate_irq_context(struct task_struct *curr,
2818                 struct held_lock *hlock)
2819 {
2820         unsigned int depth = curr->lockdep_depth;
2821
2822         /*
2823          * Keep track of points where we cross into an interrupt context:
2824          */
2825         hlock->irq_context = 2*(curr->hardirq_context ? 1 : 0) +
2826                                 curr->softirq_context;
2827         if (depth) {
2828                 struct held_lock *prev_hlock;
2829
2830                 prev_hlock = curr->held_locks + depth-1;
2831                 /*
2832                  * If we cross into another context, reset the
2833                  * hash key (this also prevents the checking and the
2834                  * adding of the dependency to 'prev'):
2835                  */
2836                 if (prev_hlock->irq_context != hlock->irq_context)
2837                         return 1;
2838         }
2839         return 0;
2840 }
2841
2842 #else /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
2843
2844 static inline
2845 int mark_lock_irq(struct task_struct *curr, struct held_lock *this,
2846                 enum lock_usage_bit new_bit)
2847 {
2848         WARN_ON(1); /* Impossible innit? when we don't have TRACE_IRQFLAG */
2849         return 1;
2850 }
2851
2852 static inline int mark_irqflags(struct task_struct *curr,
2853                 struct held_lock *hlock)
2854 {
2855         return 1;
2856 }
2857
2858 static inline int separate_irq_context(struct task_struct *curr,
2859                 struct held_lock *hlock)
2860 {
2861         return 0;
2862 }
2863
2864 void lockdep_trace_alloc(gfp_t gfp_mask)
2865 {
2866 }
2867
2868 #endif /* defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) */
2869
2870 /*
2871  * Mark a lock with a usage bit, and validate the state transition:
2872  */
2873 static int mark_lock(struct task_struct *curr, struct held_lock *this,
2874                              enum lock_usage_bit new_bit)
2875 {
2876         unsigned int new_mask = 1 << new_bit, ret = 1;
2877
2878         /*
2879          * If already set then do not dirty the cacheline,
2880          * nor do any checks:
2881          */
2882         if (likely(hlock_class(this)->usage_mask & new_mask))
2883                 return 1;
2884
2885         if (!graph_lock())
2886                 return 0;
2887         /*
2888          * Make sure we didn't race:
2889          */
2890         if (unlikely(hlock_class(this)->usage_mask & new_mask)) {
2891                 graph_unlock();
2892                 return 1;
2893         }
2894
2895         hlock_class(this)->usage_mask |= new_mask;
2896
2897         if (!save_trace(hlock_class(this)->usage_traces + new_bit))
2898                 return 0;
2899
2900         switch (new_bit) {
2901 #define LOCKDEP_STATE(__STATE)                  \
2902         case LOCK_USED_IN_##__STATE:            \
2903         case LOCK_USED_IN_##__STATE##_READ:     \
2904         case LOCK_ENABLED_##__STATE:            \
2905         case LOCK_ENABLED_##__STATE##_READ:
2906 #include "lockdep_states.h"
2907 #undef LOCKDEP_STATE
2908                 ret = mark_lock_irq(curr, this, new_bit);
2909                 if (!ret)
2910                         return 0;
2911                 break;
2912         case LOCK_USED:
2913                 debug_atomic_dec(nr_unused_locks);
2914                 break;
2915         default:
2916                 if (!debug_locks_off_graph_unlock())
2917                         return 0;
2918                 WARN_ON(1);
2919                 return 0;
2920         }
2921
2922         graph_unlock();
2923
2924         /*
2925          * We must printk outside of the graph_lock:
2926          */
2927         if (ret == 2) {
2928                 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
2929                 print_lock(this);
2930                 print_irqtrace_events(curr);
2931                 dump_stack();
2932         }
2933
2934         return ret;
2935 }
2936
2937 /*
2938  * Initialize a lock instance's lock-class mapping info:
2939  */
2940 void lockdep_init_map(struct lockdep_map *lock, const char *name,
2941                       struct lock_class_key *key, int subclass)
2942 {
2943         int i;
2944
2945         kmemcheck_mark_initialized(lock, sizeof(*lock));
2946
2947         for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
2948                 lock->class_cache[i] = NULL;
2949
2950 #ifdef CONFIG_LOCK_STAT
2951         lock->cpu = raw_smp_processor_id();
2952 #endif
2953
2954         /*
2955          * Can't be having no nameless bastards around this place!
2956          */
2957         if (DEBUG_LOCKS_WARN_ON(!name)) {
2958                 lock->name = "NULL";
2959                 return;
2960         }
2961
2962         lock->name = name;
2963
2964         /*
2965          * No key, no joy, we need to hash something.
2966          */
2967         if (DEBUG_LOCKS_WARN_ON(!key))
2968                 return;
2969         /*
2970          * Sanity check, the lock-class key must be persistent:
2971          */
2972         if (!static_obj(key)) {
2973                 printk("BUG: key %p not in .data!\n", key);
2974                 /*
2975                  * What it says above ^^^^^, I suggest you read it.
2976                  */
2977                 DEBUG_LOCKS_WARN_ON(1);
2978                 return;
2979         }
2980         lock->key = key;
2981
2982         if (unlikely(!debug_locks))
2983                 return;
2984
2985         if (subclass) {
2986                 unsigned long flags;
2987
2988                 if (DEBUG_LOCKS_WARN_ON(current->lockdep_recursion))
2989                         return;
2990
2991                 raw_local_irq_save(flags);
2992                 current->lockdep_recursion = 1;
2993                 register_lock_class(lock, subclass, 1);
2994                 current->lockdep_recursion = 0;
2995                 raw_local_irq_restore(flags);
2996         }
2997 }
2998 EXPORT_SYMBOL_GPL(lockdep_init_map);
2999
3000 struct lock_class_key __lockdep_no_validate__;
3001 EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
3002
3003 static int
3004 print_lock_nested_lock_not_held(struct task_struct *curr,
3005                                 struct held_lock *hlock,
3006                                 unsigned long ip)
3007 {
3008         if (!debug_locks_off())
3009                 return 0;
3010         if (debug_locks_silent)
3011                 return 0;
3012
3013         printk("\n");
3014         printk("==================================\n");
3015         printk("[ BUG: Nested lock was not taken ]\n");
3016         print_kernel_ident();
3017         printk("----------------------------------\n");
3018
3019         printk("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
3020         print_lock(hlock);
3021
3022         printk("\nbut this task is not holding:\n");
3023         printk("%s\n", hlock->nest_lock->name);
3024
3025         printk("\nstack backtrace:\n");
3026         dump_stack();
3027
3028         printk("\nother info that might help us debug this:\n");
3029         lockdep_print_held_locks(curr);
3030
3031         printk("\nstack backtrace:\n");
3032         dump_stack();
3033
3034         return 0;
3035 }
3036
3037 static int __lock_is_held(struct lockdep_map *lock);
3038
3039 /*
3040  * This gets called for every mutex_lock*()/spin_lock*() operation.
3041  * We maintain the dependency maps and validate the locking attempt:
3042  */
3043 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3044                           int trylock, int read, int check, int hardirqs_off,
3045                           struct lockdep_map *nest_lock, unsigned long ip,
3046                           int references, int pin_count)
3047 {
3048         struct task_struct *curr = current;
3049         struct lock_class *class = NULL;
3050         struct held_lock *hlock;
3051         unsigned int depth, id;
3052         int chain_head = 0;
3053         int class_idx;
3054         u64 chain_key;
3055
3056         if (unlikely(!debug_locks))
3057                 return 0;
3058
3059         /*
3060          * Lockdep should run with IRQs disabled, otherwise we could
3061          * get an interrupt which would want to take locks, which would
3062          * end up in lockdep and have you got a head-ache already?
3063          */
3064         if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
3065                 return 0;
3066
3067         if (!prove_locking || lock->key == &__lockdep_no_validate__)
3068                 check = 0;
3069
3070         if (subclass < NR_LOCKDEP_CACHING_CLASSES)
3071                 class = lock->class_cache[subclass];
3072         /*
3073          * Not cached?
3074          */
3075         if (unlikely(!class)) {
3076                 class = register_lock_class(lock, subclass, 0);
3077                 if (!class)
3078                         return 0;
3079         }
3080         atomic_inc((atomic_t *)&class->ops);
3081         if (very_verbose(class)) {
3082                 printk("\nacquire class [%p] %s", class->key, class->name);
3083                 if (class->name_version > 1)
3084                         printk("#%d", class->name_version);
3085                 printk("\n");
3086                 dump_stack();
3087         }
3088
3089         /*
3090          * Add the lock to the list of currently held locks.
3091          * (we dont increase the depth just yet, up until the
3092          * dependency checks are done)
3093          */
3094         depth = curr->lockdep_depth;
3095         /*
3096          * Ran out of static storage for our per-task lock stack again have we?
3097          */
3098         if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
3099                 return 0;
3100
3101         class_idx = class - lock_classes + 1;
3102
3103         if (depth) {
3104                 hlock = curr->held_locks + depth - 1;
3105                 if (hlock->class_idx == class_idx && nest_lock) {
3106                         if (hlock->references)
3107                                 hlock->references++;
3108                         else
3109                                 hlock->references = 2;
3110
3111                         return 1;
3112                 }
3113         }
3114
3115         hlock = curr->held_locks + depth;
3116         /*
3117          * Plain impossible, we just registered it and checked it weren't no
3118          * NULL like.. I bet this mushroom I ate was good!
3119          */
3120         if (DEBUG_LOCKS_WARN_ON(!class))
3121                 return 0;
3122         hlock->class_idx = class_idx;
3123         hlock->acquire_ip = ip;
3124         hlock->instance = lock;
3125         hlock->nest_lock = nest_lock;
3126         hlock->trylock = trylock;
3127         hlock->read = read;
3128         hlock->check = check;
3129         hlock->hardirqs_off = !!hardirqs_off;
3130         hlock->references = references;
3131 #ifdef CONFIG_LOCK_STAT
3132         hlock->waittime_stamp = 0;
3133         hlock->holdtime_stamp = lockstat_clock();
3134 #endif
3135         hlock->pin_count = pin_count;
3136
3137         if (check && !mark_irqflags(curr, hlock))
3138                 return 0;
3139
3140         /* mark it as used: */
3141         if (!mark_lock(curr, hlock, LOCK_USED))
3142                 return 0;
3143
3144         /*
3145          * Calculate the chain hash: it's the combined hash of all the
3146          * lock keys along the dependency chain. We save the hash value
3147          * at every step so that we can get the current hash easily
3148          * after unlock. The chain hash is then used to cache dependency
3149          * results.
3150          *
3151          * The 'key ID' is what is the most compact key value to drive
3152          * the hash, not class->key.
3153          */
3154         id = class - lock_classes;
3155         /*
3156          * Whoops, we did it again.. ran straight out of our static allocation.
3157          */
3158         if (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
3159                 return 0;
3160
3161         chain_key = curr->curr_chain_key;
3162         if (!depth) {
3163                 /*
3164                  * How can we have a chain hash when we ain't got no keys?!
3165                  */
3166                 if (DEBUG_LOCKS_WARN_ON(chain_key != 0))
3167                         return 0;
3168                 chain_head = 1;
3169         }
3170
3171         hlock->prev_chain_key = chain_key;
3172         if (separate_irq_context(curr, hlock)) {
3173                 chain_key = 0;
3174                 chain_head = 1;
3175         }
3176         chain_key = iterate_chain_key(chain_key, id);
3177
3178         if (nest_lock && !__lock_is_held(nest_lock))
3179                 return print_lock_nested_lock_not_held(curr, hlock, ip);
3180
3181         if (!validate_chain(curr, lock, hlock, chain_head, chain_key))
3182                 return 0;
3183
3184         curr->curr_chain_key = chain_key;
3185         curr->lockdep_depth++;
3186         check_chain_key(curr);
3187 #ifdef CONFIG_DEBUG_LOCKDEP
3188         if (unlikely(!debug_locks))
3189                 return 0;
3190 #endif
3191         if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
3192                 debug_locks_off();
3193                 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
3194                 printk(KERN_DEBUG "depth: %i  max: %lu!\n",
3195                        curr->lockdep_depth, MAX_LOCK_DEPTH);
3196
3197                 lockdep_print_held_locks(current);
3198                 debug_show_all_locks();
3199                 dump_stack();
3200
3201                 return 0;
3202         }
3203
3204         if (unlikely(curr->lockdep_depth > max_lockdep_depth))
3205                 max_lockdep_depth = curr->lockdep_depth;
3206
3207         return 1;
3208 }
3209
3210 static int
3211 print_unlock_imbalance_bug(struct task_struct *curr, struct lockdep_map *lock,
3212                            unsigned long ip)
3213 {
3214         if (!debug_locks_off())
3215                 return 0;
3216         if (debug_locks_silent)
3217                 return 0;
3218
3219         printk("\n");
3220         printk("=====================================\n");
3221         printk("[ BUG: bad unlock balance detected! ]\n");
3222         print_kernel_ident();
3223         printk("-------------------------------------\n");
3224         printk("%s/%d is trying to release lock (",
3225                 curr->comm, task_pid_nr(curr));
3226         print_lockdep_cache(lock);
3227         printk(") at:\n");
3228         print_ip_sym(ip);
3229         printk("but there are no more locks to release!\n");
3230         printk("\nother info that might help us debug this:\n");
3231         lockdep_print_held_locks(curr);
3232
3233         printk("\nstack backtrace:\n");
3234         dump_stack();
3235
3236         return 0;
3237 }
3238
3239 static int match_held_lock(struct held_lock *hlock, struct lockdep_map *lock)
3240 {
3241         if (hlock->instance == lock)
3242                 return 1;
3243
3244         if (hlock->references) {
3245                 struct lock_class *class = lock->class_cache[0];
3246
3247                 if (!class)
3248                         class = look_up_lock_class(lock, 0);
3249
3250                 /*
3251                  * If look_up_lock_class() failed to find a class, we're trying
3252                  * to test if we hold a lock that has never yet been acquired.
3253                  * Clearly if the lock hasn't been acquired _ever_, we're not
3254                  * holding it either, so report failure.
3255                  */
3256                 if (!class)
3257                         return 0;
3258
3259                 /*
3260                  * References, but not a lock we're actually ref-counting?
3261                  * State got messed up, follow the sites that change ->references
3262                  * and try to make sense of it.
3263                  */
3264                 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
3265                         return 0;
3266
3267                 if (hlock->class_idx == class - lock_classes + 1)
3268                         return 1;
3269         }
3270
3271         return 0;
3272 }
3273
3274 static int
3275 __lock_set_class(struct lockdep_map *lock, const char *name,
3276                  struct lock_class_key *key, unsigned int subclass,
3277                  unsigned long ip)
3278 {
3279         struct task_struct *curr = current;
3280         struct held_lock *hlock, *prev_hlock;
3281         struct lock_class *class;
3282         unsigned int depth;
3283         int i;
3284
3285         depth = curr->lockdep_depth;
3286         /*
3287          * This function is about (re)setting the class of a held lock,
3288          * yet we're not actually holding any locks. Naughty user!
3289          */
3290         if (DEBUG_LOCKS_WARN_ON(!depth))
3291                 return 0;
3292
3293         prev_hlock = NULL;
3294         for (i = depth-1; i >= 0; i--) {
3295                 hlock = curr->held_locks + i;
3296                 /*
3297                  * We must not cross into another context:
3298                  */
3299                 if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3300                         break;
3301                 if (match_held_lock(hlock, lock))
3302                         goto found_it;
3303                 prev_hlock = hlock;
3304         }
3305         return print_unlock_imbalance_bug(curr, lock, ip);
3306
3307 found_it:
3308         lockdep_init_map(lock, name, key, 0);
3309         class = register_lock_class(lock, subclass, 0);
3310         hlock->class_idx = class - lock_classes + 1;
3311
3312         curr->lockdep_depth = i;
3313         curr->curr_chain_key = hlock->prev_chain_key;
3314
3315         for (; i < depth; i++) {
3316                 hlock = curr->held_locks + i;
3317                 if (!__lock_acquire(hlock->instance,
3318                         hlock_class(hlock)->subclass, hlock->trylock,
3319                                 hlock->read, hlock->check, hlock->hardirqs_off,
3320                                 hlock->nest_lock, hlock->acquire_ip,
3321                                 hlock->references, hlock->pin_count))
3322                         return 0;
3323         }
3324
3325         /*
3326          * I took it apart and put it back together again, except now I have
3327          * these 'spare' parts.. where shall I put them.
3328          */
3329         if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
3330                 return 0;
3331         return 1;
3332 }
3333
3334 /*
3335  * Remove the lock to the list of currently held locks - this gets
3336  * called on mutex_unlock()/spin_unlock*() (or on a failed
3337  * mutex_lock_interruptible()).
3338  *
3339  * @nested is an hysterical artifact, needs a tree wide cleanup.
3340  */
3341 static int
3342 __lock_release(struct lockdep_map *lock, int nested, unsigned long ip)
3343 {
3344         struct task_struct *curr = current;
3345         struct held_lock *hlock, *prev_hlock;
3346         unsigned int depth;
3347         int i;
3348
3349         if (unlikely(!debug_locks))
3350                 return 0;
3351
3352         depth = curr->lockdep_depth;
3353         /*
3354          * So we're all set to release this lock.. wait what lock? We don't
3355          * own any locks, you've been drinking again?
3356          */
3357         if (DEBUG_LOCKS_WARN_ON(depth <= 0))
3358                  return print_unlock_imbalance_bug(curr, lock, ip);
3359
3360         /*
3361          * Check whether the lock exists in the current stack
3362          * of held locks:
3363          */
3364         prev_hlock = NULL;
3365         for (i = depth-1; i >= 0; i--) {
3366                 hlock = curr->held_locks + i;
3367                 /*
3368                  * We must not cross into another context:
3369                  */
3370                 if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3371                         break;
3372                 if (match_held_lock(hlock, lock))
3373                         goto found_it;
3374                 prev_hlock = hlock;
3375         }
3376         return print_unlock_imbalance_bug(curr, lock, ip);
3377
3378 found_it:
3379         if (hlock->instance == lock)
3380                 lock_release_holdtime(hlock);
3381
3382         WARN(hlock->pin_count, "releasing a pinned lock\n");
3383
3384         if (hlock->references) {
3385                 hlock->references--;
3386                 if (hlock->references) {
3387                         /*
3388                          * We had, and after removing one, still have
3389                          * references, the current lock stack is still
3390                          * valid. We're done!
3391                          */
3392                         return 1;
3393                 }
3394         }
3395
3396         /*
3397          * We have the right lock to unlock, 'hlock' points to it.
3398          * Now we remove it from the stack, and add back the other
3399          * entries (if any), recalculating the hash along the way:
3400          */
3401
3402         curr->lockdep_depth = i;
3403         curr->curr_chain_key = hlock->prev_chain_key;
3404
3405         for (i++; i < depth; i++) {
3406                 hlock = curr->held_locks + i;
3407                 if (!__lock_acquire(hlock->instance,
3408                         hlock_class(hlock)->subclass, hlock->trylock,
3409                                 hlock->read, hlock->check, hlock->hardirqs_off,
3410                                 hlock->nest_lock, hlock->acquire_ip,
3411                                 hlock->references, hlock->pin_count))
3412                         return 0;
3413         }
3414
3415         /*
3416          * We had N bottles of beer on the wall, we drank one, but now
3417          * there's not N-1 bottles of beer left on the wall...
3418          */
3419         if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - 1))
3420                 return 0;
3421
3422         return 1;
3423 }
3424
3425 static int __lock_is_held(struct lockdep_map *lock)
3426 {
3427         struct task_struct *curr = current;
3428         int i;
3429
3430         for (i = 0; i < curr->lockdep_depth; i++) {
3431                 struct held_lock *hlock = curr->held_locks + i;
3432
3433                 if (match_held_lock(hlock, lock))
3434                         return 1;
3435         }
3436
3437         return 0;
3438 }
3439
3440 static void __lock_pin_lock(struct lockdep_map *lock)
3441 {
3442         struct task_struct *curr = current;
3443         int i;
3444
3445         if (unlikely(!debug_locks))
3446                 return;
3447
3448         for (i = 0; i < curr->lockdep_depth; i++) {
3449                 struct held_lock *hlock = curr->held_locks + i;
3450
3451                 if (match_held_lock(hlock, lock)) {
3452                         hlock->pin_count++;
3453                         return;
3454                 }
3455         }
3456
3457         WARN(1, "pinning an unheld lock\n");
3458 }
3459
3460 static void __lock_unpin_lock(struct lockdep_map *lock)
3461 {
3462         struct task_struct *curr = current;
3463         int i;
3464
3465         if (unlikely(!debug_locks))
3466                 return;
3467
3468         for (i = 0; i < curr->lockdep_depth; i++) {
3469                 struct held_lock *hlock = curr->held_locks + i;
3470
3471                 if (match_held_lock(hlock, lock)) {
3472                         if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
3473                                 return;
3474
3475                         hlock->pin_count--;
3476                         return;
3477                 }
3478         }
3479
3480         WARN(1, "unpinning an unheld lock\n");
3481 }
3482
3483 /*
3484  * Check whether we follow the irq-flags state precisely:
3485  */
3486 static void check_flags(unsigned long flags)
3487 {
3488 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP) && \
3489     defined(CONFIG_TRACE_IRQFLAGS)
3490         if (!debug_locks)
3491                 return;
3492
3493         if (irqs_disabled_flags(flags)) {
3494                 if (DEBUG_LOCKS_WARN_ON(current->hardirqs_enabled)) {
3495                         printk("possible reason: unannotated irqs-off.\n");
3496                 }
3497         } else {
3498                 if (DEBUG_LOCKS_WARN_ON(!current->hardirqs_enabled)) {
3499                         printk("possible reason: unannotated irqs-on.\n");
3500                 }
3501         }
3502
3503         /*
3504          * We dont accurately track softirq state in e.g.
3505          * hardirq contexts (such as on 4KSTACKS), so only
3506          * check if not in hardirq contexts:
3507          */
3508         if (!hardirq_count()) {
3509                 if (softirq_count()) {
3510                         /* like the above, but with softirqs */
3511                         DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
3512                 } else {
3513                         /* lick the above, does it taste good? */
3514                         DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
3515                 }
3516         }
3517
3518         if (!debug_locks)
3519                 print_irqtrace_events(current);
3520 #endif
3521 }
3522
3523 void lock_set_class(struct lockdep_map *lock, const char *name,
3524                     struct lock_class_key *key, unsigned int subclass,
3525                     unsigned long ip)
3526 {
3527         unsigned long flags;
3528
3529         if (unlikely(current->lockdep_recursion))
3530                 return;
3531
3532         raw_local_irq_save(flags);
3533         current->lockdep_recursion = 1;
3534         check_flags(flags);
3535         if (__lock_set_class(lock, name, key, subclass, ip))
3536                 check_chain_key(current);
3537         current->lockdep_recursion = 0;
3538         raw_local_irq_restore(flags);
3539 }
3540 EXPORT_SYMBOL_GPL(lock_set_class);
3541
3542 /*
3543  * We are not always called with irqs disabled - do that here,
3544  * and also avoid lockdep recursion:
3545  */
3546 void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
3547                           int trylock, int read, int check,
3548                           struct lockdep_map *nest_lock, unsigned long ip)
3549 {
3550         unsigned long flags;
3551
3552         if (unlikely(current->lockdep_recursion))
3553                 return;
3554
3555         raw_local_irq_save(flags);
3556         check_flags(flags);
3557
3558         current->lockdep_recursion = 1;
3559         trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
3560         __lock_acquire(lock, subclass, trylock, read, check,
3561                        irqs_disabled_flags(flags), nest_lock, ip, 0, 0);
3562         current->lockdep_recursion = 0;
3563         raw_local_irq_restore(flags);
3564 }
3565 EXPORT_SYMBOL_GPL(lock_acquire);
3566
3567 void lock_release(struct lockdep_map *lock, int nested,
3568                           unsigned long ip)
3569 {
3570         unsigned long flags;
3571
3572         if (unlikely(current->lockdep_recursion))
3573                 return;
3574
3575         raw_local_irq_save(flags);
3576         check_flags(flags);
3577         current->lockdep_recursion = 1;
3578         trace_lock_release(lock, ip);
3579         if (__lock_release(lock, nested, ip))
3580                 check_chain_key(current);
3581         current->lockdep_recursion = 0;
3582         raw_local_irq_restore(flags);
3583 }
3584 EXPORT_SYMBOL_GPL(lock_release);
3585
3586 int lock_is_held(struct lockdep_map *lock)
3587 {
3588         unsigned long flags;
3589         int ret = 0;
3590
3591         if (unlikely(current->lockdep_recursion))
3592                 return 1; /* avoid false negative lockdep_assert_held() */
3593
3594         raw_local_irq_save(flags);
3595         check_flags(flags);
3596
3597         current->lockdep_recursion = 1;
3598         ret = __lock_is_held(lock);
3599         current->lockdep_recursion = 0;
3600         raw_local_irq_restore(flags);
3601
3602         return ret;
3603 }
3604 EXPORT_SYMBOL_GPL(lock_is_held);
3605
3606 void lock_pin_lock(struct lockdep_map *lock)
3607 {
3608         unsigned long flags;
3609
3610         if (unlikely(current->lockdep_recursion))
3611                 return;
3612
3613         raw_local_irq_save(flags);
3614         check_flags(flags);
3615
3616         current->lockdep_recursion = 1;
3617         __lock_pin_lock(lock);
3618         current->lockdep_recursion = 0;
3619         raw_local_irq_restore(flags);
3620 }
3621 EXPORT_SYMBOL_GPL(lock_pin_lock);
3622
3623 void lock_unpin_lock(struct lockdep_map *lock)
3624 {
3625         unsigned long flags;
3626
3627         if (unlikely(current->lockdep_recursion))
3628                 return;
3629
3630         raw_local_irq_save(flags);
3631         check_flags(flags);
3632
3633         current->lockdep_recursion = 1;
3634         __lock_unpin_lock(lock);
3635         current->lockdep_recursion = 0;
3636         raw_local_irq_restore(flags);
3637 }
3638 EXPORT_SYMBOL_GPL(lock_unpin_lock);
3639
3640 void lockdep_set_current_reclaim_state(gfp_t gfp_mask)
3641 {
3642         current->lockdep_reclaim_gfp = gfp_mask;
3643 }
3644
3645 void lockdep_clear_current_reclaim_state(void)
3646 {
3647         current->lockdep_reclaim_gfp = 0;
3648 }
3649
3650 #ifdef CONFIG_LOCK_STAT
3651 static int
3652 print_lock_contention_bug(struct task_struct *curr, struct lockdep_map *lock,
3653                            unsigned long ip)
3654 {
3655         if (!debug_locks_off())
3656                 return 0;
3657         if (debug_locks_silent)
3658                 return 0;
3659
3660         printk("\n");
3661         printk("=================================\n");
3662         printk("[ BUG: bad contention detected! ]\n");
3663         print_kernel_ident();
3664         printk("---------------------------------\n");
3665         printk("%s/%d is trying to contend lock (",
3666                 curr->comm, task_pid_nr(curr));
3667         print_lockdep_cache(lock);
3668         printk(") at:\n");
3669         print_ip_sym(ip);
3670         printk("but there are no locks held!\n");
3671         printk("\nother info that might help us debug this:\n");
3672         lockdep_print_held_locks(curr);
3673
3674         printk("\nstack backtrace:\n");
3675         dump_stack();
3676
3677         return 0;
3678 }
3679
3680 static void
3681 __lock_contended(struct lockdep_map *lock, unsigned long ip)
3682 {
3683         struct task_struct *curr = current;
3684         struct held_lock *hlock, *prev_hlock;
3685         struct lock_class_stats *stats;
3686         unsigned int depth;
3687         int i, contention_point, contending_point;
3688
3689         depth = curr->lockdep_depth;
3690         /*
3691          * Whee, we contended on this lock, except it seems we're not
3692          * actually trying to acquire anything much at all..
3693          */
3694         if (DEBUG_LOCKS_WARN_ON(!depth))
3695                 return;
3696
3697         prev_hlock = NULL;
3698         for (i = depth-1; i >= 0; i--) {
3699                 hlock = curr->held_locks + i;
3700                 /*
3701                  * We must not cross into another context:
3702                  */
3703                 if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3704                         break;
3705                 if (match_held_lock(hlock, lock))
3706                         goto found_it;
3707                 prev_hlock = hlock;
3708         }
3709         print_lock_contention_bug(curr, lock, ip);
3710         return;
3711
3712 found_it:
3713         if (hlock->instance != lock)
3714                 return;
3715
3716         hlock->waittime_stamp = lockstat_clock();
3717
3718         contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
3719         contending_point = lock_point(hlock_class(hlock)->contending_point,
3720                                       lock->ip);
3721
3722         stats = get_lock_stats(hlock_class(hlock));
3723         if (contention_point < LOCKSTAT_POINTS)
3724                 stats->contention_point[contention_point]++;
3725         if (contending_point < LOCKSTAT_POINTS)
3726                 stats->contending_point[contending_point]++;
3727         if (lock->cpu != smp_processor_id())
3728                 stats->bounces[bounce_contended + !!hlock->read]++;
3729         put_lock_stats(stats);
3730 }
3731
3732 static void
3733 __lock_acquired(struct lockdep_map *lock, unsigned long ip)
3734 {
3735         struct task_struct *curr = current;
3736         struct held_lock *hlock, *prev_hlock;
3737         struct lock_class_stats *stats;
3738         unsigned int depth;
3739         u64 now, waittime = 0;
3740         int i, cpu;
3741
3742         depth = curr->lockdep_depth;
3743         /*
3744          * Yay, we acquired ownership of this lock we didn't try to
3745          * acquire, how the heck did that happen?
3746          */
3747         if (DEBUG_LOCKS_WARN_ON(!depth))
3748                 return;
3749
3750         prev_hlock = NULL;
3751         for (i = depth-1; i >= 0; i--) {
3752                 hlock = curr->held_locks + i;
3753                 /*
3754                  * We must not cross into another context:
3755                  */
3756                 if (prev_hlock && prev_hlock->irq_context != hlock->irq_context)
3757                         break;
3758                 if (match_held_lock(hlock, lock))
3759                         goto found_it;
3760                 prev_hlock = hlock;
3761         }
3762         print_lock_contention_bug(curr, lock, _RET_IP_);
3763         return;
3764
3765 found_it:
3766         if (hlock->instance != lock)
3767                 return;
3768
3769         cpu = smp_processor_id();
3770         if (hlock->waittime_stamp) {
3771                 now = lockstat_clock();
3772                 waittime = now - hlock->waittime_stamp;
3773                 hlock->holdtime_stamp = now;
3774         }
3775
3776         trace_lock_acquired(lock, ip);
3777
3778         stats = get_lock_stats(hlock_class(hlock));
3779         if (waittime) {
3780                 if (hlock->read)
3781                         lock_time_inc(&stats->read_waittime, waittime);
3782                 else
3783                         lock_time_inc(&stats->write_waittime, waittime);
3784         }
3785         if (lock->cpu != cpu)
3786                 stats->bounces[bounce_acquired + !!hlock->read]++;
3787         put_lock_stats(stats);
3788
3789         lock->cpu = cpu;
3790         lock->ip = ip;
3791 }
3792
3793 void lock_contended(struct lockdep_map *lock, unsigned long ip)
3794 {
3795         unsigned long flags;
3796
3797         if (unlikely(!lock_stat))
3798                 return;
3799
3800         if (unlikely(current->lockdep_recursion))
3801                 return;
3802
3803         raw_local_irq_save(flags);
3804         check_flags(flags);
3805         current->lockdep_recursion = 1;
3806         trace_lock_contended(lock, ip);
3807         __lock_contended(lock, ip);
3808         current->lockdep_recursion = 0;
3809         raw_local_irq_restore(flags);
3810 }
3811 EXPORT_SYMBOL_GPL(lock_contended);
3812
3813 void lock_acquired(struct lockdep_map *lock, unsigned long ip)
3814 {
3815         unsigned long flags;
3816
3817         if (unlikely(!lock_stat))
3818                 return;
3819
3820         if (unlikely(current->lockdep_recursion))
3821                 return;
3822
3823         raw_local_irq_save(flags);
3824         check_flags(flags);
3825         current->lockdep_recursion = 1;
3826         __lock_acquired(lock, ip);
3827         current->lockdep_recursion = 0;
3828         raw_local_irq_restore(flags);
3829 }
3830 EXPORT_SYMBOL_GPL(lock_acquired);
3831 #endif
3832
3833 /*
3834  * Used by the testsuite, sanitize the validator state
3835  * after a simulated failure:
3836  */
3837
3838 void lockdep_reset(void)
3839 {
3840         unsigned long flags;
3841         int i;
3842
3843         raw_local_irq_save(flags);
3844         current->curr_chain_key = 0;
3845         current->lockdep_depth = 0;
3846         current->lockdep_recursion = 0;
3847         memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
3848         nr_hardirq_chains = 0;
3849         nr_softirq_chains = 0;
3850         nr_process_chains = 0;
3851         debug_locks = 1;
3852         for (i = 0; i < CHAINHASH_SIZE; i++)
3853                 INIT_HLIST_HEAD(chainhash_table + i);
3854         raw_local_irq_restore(flags);
3855 }
3856
3857 static void zap_class(struct lock_class *class)
3858 {
3859         int i;
3860
3861         /*
3862          * Remove all dependencies this lock is
3863          * involved in:
3864          */
3865         for (i = 0; i < nr_list_entries; i++) {
3866                 if (list_entries[i].class == class)
3867                         list_del_rcu(&list_entries[i].entry);
3868         }
3869         /*
3870          * Unhash the class and remove it from the all_lock_classes list:
3871          */
3872         hlist_del_rcu(&class->hash_entry);
3873         list_del_rcu(&class->lock_entry);
3874
3875         RCU_INIT_POINTER(class->key, NULL);
3876         RCU_INIT_POINTER(class->name, NULL);
3877 }
3878
3879 static inline int within(const void *addr, void *start, unsigned long size)
3880 {
3881         return addr >= start && addr < start + size;
3882 }
3883
3884 /*
3885  * Used in module.c to remove lock classes from memory that is going to be
3886  * freed; and possibly re-used by other modules.
3887  *
3888  * We will have had one sync_sched() before getting here, so we're guaranteed
3889  * nobody will look up these exact classes -- they're properly dead but still
3890  * allocated.
3891  */
3892 void lockdep_free_key_range(void *start, unsigned long size)
3893 {
3894         struct lock_class *class;
3895         struct hlist_head *head;
3896         unsigned long flags;
3897         int i;
3898         int locked;
3899
3900         raw_local_irq_save(flags);
3901         locked = graph_lock();
3902
3903         /*
3904          * Unhash all classes that were created by this module:
3905          */
3906         for (i = 0; i < CLASSHASH_SIZE; i++) {
3907                 head = classhash_table + i;
3908                 hlist_for_each_entry_rcu(class, head, hash_entry) {
3909                         if (within(class->key, start, size))
3910                                 zap_class(class);
3911                         else if (within(class->name, start, size))
3912                                 zap_class(class);
3913                 }
3914         }
3915
3916         if (locked)
3917                 graph_unlock();
3918         raw_local_irq_restore(flags);
3919
3920         /*
3921          * Wait for any possible iterators from look_up_lock_class() to pass
3922          * before continuing to free the memory they refer to.
3923          *
3924          * sync_sched() is sufficient because the read-side is IRQ disable.
3925          */
3926         synchronize_sched();
3927
3928         /*
3929          * XXX at this point we could return the resources to the pool;
3930          * instead we leak them. We would need to change to bitmap allocators
3931          * instead of the linear allocators we have now.
3932          */
3933 }
3934
3935 void lockdep_reset_lock(struct lockdep_map *lock)
3936 {
3937         struct lock_class *class;
3938         struct hlist_head *head;
3939         unsigned long flags;
3940         int i, j;
3941         int locked;
3942
3943         raw_local_irq_save(flags);
3944
3945         /*
3946          * Remove all classes this lock might have:
3947          */
3948         for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
3949                 /*
3950                  * If the class exists we look it up and zap it:
3951                  */
3952                 class = look_up_lock_class(lock, j);
3953                 if (class)
3954                         zap_class(class);
3955         }
3956         /*
3957          * Debug check: in the end all mapped classes should
3958          * be gone.
3959          */
3960         locked = graph_lock();
3961         for (i = 0; i < CLASSHASH_SIZE; i++) {
3962                 head = classhash_table + i;
3963                 hlist_for_each_entry_rcu(class, head, hash_entry) {
3964                         int match = 0;
3965
3966                         for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
3967                                 match |= class == lock->class_cache[j];
3968
3969                         if (unlikely(match)) {
3970                                 if (debug_locks_off_graph_unlock()) {
3971                                         /*
3972                                          * We all just reset everything, how did it match?
3973                                          */
3974                                         WARN_ON(1);
3975                                 }
3976                                 goto out_restore;
3977                         }
3978                 }
3979         }
3980         if (locked)
3981                 graph_unlock();
3982
3983 out_restore:
3984         raw_local_irq_restore(flags);
3985 }
3986
3987 void __init lockdep_info(void)
3988 {
3989         printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
3990
3991         printk("... MAX_LOCKDEP_SUBCLASSES:  %lu\n", MAX_LOCKDEP_SUBCLASSES);
3992         printk("... MAX_LOCK_DEPTH:          %lu\n", MAX_LOCK_DEPTH);
3993         printk("... MAX_LOCKDEP_KEYS:        %lu\n", MAX_LOCKDEP_KEYS);
3994         printk("... CLASSHASH_SIZE:          %lu\n", CLASSHASH_SIZE);
3995         printk("... MAX_LOCKDEP_ENTRIES:     %lu\n", MAX_LOCKDEP_ENTRIES);
3996         printk("... MAX_LOCKDEP_CHAINS:      %lu\n", MAX_LOCKDEP_CHAINS);
3997         printk("... CHAINHASH_SIZE:          %lu\n", CHAINHASH_SIZE);
3998
3999         printk(" memory used by lock dependency info: %lu kB\n",
4000                 (sizeof(struct lock_class) * MAX_LOCKDEP_KEYS +
4001                 sizeof(struct list_head) * CLASSHASH_SIZE +
4002                 sizeof(struct lock_list) * MAX_LOCKDEP_ENTRIES +
4003                 sizeof(struct lock_chain) * MAX_LOCKDEP_CHAINS +
4004                 sizeof(struct list_head) * CHAINHASH_SIZE
4005 #ifdef CONFIG_PROVE_LOCKING
4006                 + sizeof(struct circular_queue)
4007 #endif
4008                 ) / 1024
4009                 );
4010
4011         printk(" per task-struct memory footprint: %lu bytes\n",
4012                 sizeof(struct held_lock) * MAX_LOCK_DEPTH);
4013 }
4014
4015 static void
4016 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
4017                      const void *mem_to, struct held_lock *hlock)
4018 {
4019         if (!debug_locks_off())
4020                 return;
4021         if (debug_locks_silent)
4022                 return;
4023
4024         printk("\n");
4025         printk("=========================\n");
4026         printk("[ BUG: held lock freed! ]\n");
4027         print_kernel_ident();
4028         printk("-------------------------\n");
4029         printk("%s/%d is freeing memory %p-%p, with a lock still held there!\n",
4030                 curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
4031         print_lock(hlock);
4032         lockdep_print_held_locks(curr);
4033
4034         printk("\nstack backtrace:\n");
4035         dump_stack();
4036 }
4037
4038 static inline int not_in_range(const void* mem_from, unsigned long mem_len,
4039                                 const void* lock_from, unsigned long lock_len)
4040 {
4041         return lock_from + lock_len <= mem_from ||
4042                 mem_from + mem_len <= lock_from;
4043 }
4044
4045 /*
4046  * Called when kernel memory is freed (or unmapped), or if a lock
4047  * is destroyed or reinitialized - this code checks whether there is
4048  * any held lock in the memory range of <from> to <to>:
4049  */
4050 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
4051 {
4052         struct task_struct *curr = current;
4053         struct held_lock *hlock;
4054         unsigned long flags;
4055         int i;
4056
4057         if (unlikely(!debug_locks))
4058                 return;
4059
4060         local_irq_save(flags);
4061         for (i = 0; i < curr->lockdep_depth; i++) {
4062                 hlock = curr->held_locks + i;
4063
4064                 if (not_in_range(mem_from, mem_len, hlock->instance,
4065                                         sizeof(*hlock->instance)))
4066                         continue;
4067
4068                 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
4069                 break;
4070         }
4071         local_irq_restore(flags);
4072 }
4073 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
4074
4075 static void print_held_locks_bug(void)
4076 {
4077         if (!debug_locks_off())
4078                 return;
4079         if (debug_locks_silent)
4080                 return;
4081
4082         printk("\n");
4083         printk("=====================================\n");
4084         printk("[ BUG: %s/%d still has locks held! ]\n",
4085                current->comm, task_pid_nr(current));
4086         print_kernel_ident();
4087         printk("-------------------------------------\n");
4088         lockdep_print_held_locks(current);
4089         printk("\nstack backtrace:\n");
4090         dump_stack();
4091 }
4092
4093 void debug_check_no_locks_held(void)
4094 {
4095         if (unlikely(current->lockdep_depth > 0))
4096                 print_held_locks_bug();
4097 }
4098 EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
4099
4100 #ifdef __KERNEL__
4101 void debug_show_all_locks(void)
4102 {
4103         struct task_struct *g, *p;
4104         int count = 10;
4105         int unlock = 1;
4106
4107         if (unlikely(!debug_locks)) {
4108                 printk("INFO: lockdep is turned off.\n");
4109                 return;
4110         }
4111         printk("\nShowing all locks held in the system:\n");
4112
4113         /*
4114          * Here we try to get the tasklist_lock as hard as possible,
4115          * if not successful after 2 seconds we ignore it (but keep
4116          * trying). This is to enable a debug printout even if a
4117          * tasklist_lock-holding task deadlocks or crashes.
4118          */
4119 retry:
4120         if (!read_trylock(&tasklist_lock)) {
4121                 if (count == 10)
4122                         printk("hm, tasklist_lock locked, retrying... ");
4123                 if (count) {
4124                         count--;
4125                         printk(" #%d", 10-count);
4126                         mdelay(200);
4127                         goto retry;
4128                 }
4129                 printk(" ignoring it.\n");
4130                 unlock = 0;
4131         } else {
4132                 if (count != 10)
4133                         printk(KERN_CONT " locked it.\n");
4134         }
4135
4136         do_each_thread(g, p) {
4137                 /*
4138                  * It's not reliable to print a task's held locks
4139                  * if it's not sleeping (or if it's not the current
4140                  * task):
4141                  */
4142                 if (p->state == TASK_RUNNING && p != current)
4143                         continue;
4144                 if (p->lockdep_depth)
4145                         lockdep_print_held_locks(p);
4146                 if (!unlock)
4147                         if (read_trylock(&tasklist_lock))
4148                                 unlock = 1;
4149         } while_each_thread(g, p);
4150
4151         printk("\n");
4152         printk("=============================================\n\n");
4153
4154         if (unlock)
4155                 read_unlock(&tasklist_lock);
4156 }
4157 EXPORT_SYMBOL_GPL(debug_show_all_locks);
4158 #endif
4159
4160 /*
4161  * Careful: only use this function if you are sure that
4162  * the task cannot run in parallel!
4163  */
4164 void debug_show_held_locks(struct task_struct *task)
4165 {
4166         if (unlikely(!debug_locks)) {
4167                 printk("INFO: lockdep is turned off.\n");
4168                 return;
4169         }
4170         lockdep_print_held_locks(task);
4171 }
4172 EXPORT_SYMBOL_GPL(debug_show_held_locks);
4173
4174 asmlinkage __visible void lockdep_sys_exit(void)
4175 {
4176         struct task_struct *curr = current;
4177
4178         if (unlikely(curr->lockdep_depth)) {
4179                 if (!debug_locks_off())
4180                         return;
4181                 printk("\n");
4182                 printk("================================================\n");
4183                 printk("[ BUG: lock held when returning to user space! ]\n");
4184                 print_kernel_ident();
4185                 printk("------------------------------------------------\n");
4186                 printk("%s/%d is leaving the kernel with locks still held!\n",
4187                                 curr->comm, curr->pid);
4188                 lockdep_print_held_locks(curr);
4189         }
4190 }
4191
4192 void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
4193 {
4194         struct task_struct *curr = current;
4195
4196 #ifndef CONFIG_PROVE_RCU_REPEATEDLY
4197         if (!debug_locks_off())
4198                 return;
4199 #endif /* #ifdef CONFIG_PROVE_RCU_REPEATEDLY */
4200         /* Note: the following can be executed concurrently, so be careful. */
4201         printk("\n");
4202         printk("===============================\n");
4203         printk("[ INFO: suspicious RCU usage. ]\n");
4204         print_kernel_ident();
4205         printk("-------------------------------\n");
4206         printk("%s:%d %s!\n", file, line, s);
4207         printk("\nother info that might help us debug this:\n\n");
4208         printk("\n%srcu_scheduler_active = %d, debug_locks = %d\n",
4209                !rcu_lockdep_current_cpu_online()
4210                         ? "RCU used illegally from offline CPU!\n"
4211                         : !rcu_is_watching()
4212                                 ? "RCU used illegally from idle CPU!\n"
4213                                 : "",
4214                rcu_scheduler_active, debug_locks);
4215
4216         /*
4217          * If a CPU is in the RCU-free window in idle (ie: in the section
4218          * between rcu_idle_enter() and rcu_idle_exit(), then RCU
4219          * considers that CPU to be in an "extended quiescent state",
4220          * which means that RCU will be completely ignoring that CPU.
4221          * Therefore, rcu_read_lock() and friends have absolutely no
4222          * effect on a CPU running in that state. In other words, even if
4223          * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
4224          * delete data structures out from under it.  RCU really has no
4225          * choice here: we need to keep an RCU-free window in idle where
4226          * the CPU may possibly enter into low power mode. This way we can
4227          * notice an extended quiescent state to other CPUs that started a grace
4228          * period. Otherwise we would delay any grace period as long as we run
4229          * in the idle task.
4230          *
4231          * So complain bitterly if someone does call rcu_read_lock(),
4232          * rcu_read_lock_bh() and so on from extended quiescent states.
4233          */
4234         if (!rcu_is_watching())
4235                 printk("RCU used illegally from extended quiescent state!\n");
4236
4237         lockdep_print_held_locks(curr);
4238         printk("\nstack backtrace:\n");
4239         dump_stack();
4240 }
4241 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);