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