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