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