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