OSDN Git Service

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