lockdep.c 85.2 KB
Newer Older
Ingo Molnar's avatar
Ingo Molnar committed
1 2 3 4 5 6 7
/*
 * kernel/lockdep.c
 *
 * Runtime locking correctness validator
 *
 * Started by Ingo Molnar:
 *
Peter Zijlstra's avatar
Peter Zijlstra committed
8 9
 *  Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
 *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
Ingo Molnar's avatar
Ingo Molnar committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 *
 * this code maps all the lock dependencies as they occur in a live kernel
 * and will warn about the following classes of locking bugs:
 *
 * - lock inversion scenarios
 * - circular lock dependencies
 * - hardirq/softirq safe/unsafe locking bugs
 *
 * Bugs are reported even if the current locking scenario does not cause
 * any deadlock at this point.
 *
 * I.e. if anytime in the past two locks were taken in a different order,
 * even if it happened for another task, even if those were different
 * locks (but of the same class as this lock), this code will detect it.
 *
 * Thanks to Arjan van de Ven for coming up with the initial idea of
 * mapping lock dependencies runtime.
 */
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/spinlock.h>
#include <linux/kallsyms.h>
#include <linux/interrupt.h>
#include <linux/stacktrace.h>
#include <linux/debug_locks.h>
#include <linux/irqflags.h>
40
#include <linux/utsname.h>
Peter Zijlstra's avatar
Peter Zijlstra committed
41
#include <linux/hash.h>
42
#include <linux/ftrace.h>
Ingo Molnar's avatar
Ingo Molnar committed
43 44 45 46 47

#include <asm/sections.h>

#include "lockdep_internals.h"

48 49 50 51 52 53 54 55 56 57 58 59 60 61
#ifdef CONFIG_PROVE_LOCKING
int prove_locking = 1;
module_param(prove_locking, int, 0644);
#else
#define prove_locking 0
#endif

#ifdef CONFIG_LOCK_STAT
int lock_stat = 1;
module_param(lock_stat, int, 0644);
#else
#define lock_stat 0
#endif

Ingo Molnar's avatar
Ingo Molnar committed
62
/*
63 64
 * lockdep_lock: protects the lockdep graph, the hashes and the
 *               class/list/hash allocators.
Ingo Molnar's avatar
Ingo Molnar committed
65 66 67
 *
 * This is one of the rare exceptions where it's justified
 * to use a raw spinlock - we really dont want the spinlock
68
 * code to recurse back into the lockdep code...
Ingo Molnar's avatar
Ingo Molnar committed
69
 */
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
static raw_spinlock_t lockdep_lock = (raw_spinlock_t)__RAW_SPIN_LOCK_UNLOCKED;

static int graph_lock(void)
{
	__raw_spin_lock(&lockdep_lock);
	/*
	 * Make sure that if another CPU detected a bug while
	 * walking the graph we dont change it (while the other
	 * CPU is busy printing out stuff with the graph lock
	 * dropped already)
	 */
	if (!debug_locks) {
		__raw_spin_unlock(&lockdep_lock);
		return 0;
	}
85 86
	/* prevent any recursions within lockdep from causing deadlocks */
	current->lockdep_recursion++;
87 88 89 90 91
	return 1;
}

static inline int graph_unlock(void)
{
92 93 94
	if (debug_locks && !__raw_spin_is_locked(&lockdep_lock))
		return DEBUG_LOCKS_WARN_ON(1);

95
	current->lockdep_recursion--;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	__raw_spin_unlock(&lockdep_lock);
	return 0;
}

/*
 * Turn lock debugging off and return with 0 if it was off already,
 * and also release the graph lock:
 */
static inline int debug_locks_off_graph_unlock(void)
{
	int ret = debug_locks_off();

	__raw_spin_unlock(&lockdep_lock);

	return ret;
}
Ingo Molnar's avatar
Ingo Molnar committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

static int lockdep_initialized;

unsigned long nr_list_entries;
static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];

/*
 * All data structures here are protected by the global debug_lock.
 *
 * Mutex key structs only get allocated, once during bootup, and never
 * get freed - this significantly simplifies the debugging code.
 */
unsigned long nr_lock_classes;
static struct lock_class lock_classes[MAX_LOCKDEP_KEYS];

127 128 129 130 131 132 133 134 135
static inline struct lock_class *hlock_class(struct held_lock *hlock)
{
	if (!hlock->class_idx) {
		DEBUG_LOCKS_WARN_ON(1);
		return NULL;
	}
	return lock_classes + hlock->class_idx - 1;
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
#ifdef CONFIG_LOCK_STAT
static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], lock_stats);

static int lock_contention_point(struct lock_class *class, unsigned long ip)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(class->contention_point); i++) {
		if (class->contention_point[i] == 0) {
			class->contention_point[i] = ip;
			break;
		}
		if (class->contention_point[i] == ip)
			break;
	}

	return i;
}

static void lock_time_inc(struct lock_time *lt, s64 time)
{
	if (time > lt->max)
		lt->max = time;

	if (time < lt->min || !lt->min)
		lt->min = time;

	lt->total += time;
	lt->nr++;
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
{
	dst->min += src->min;
	dst->max += src->max;
	dst->total += src->total;
	dst->nr += src->nr;
}

struct lock_class_stats lock_stats(struct lock_class *class)
{
	struct lock_class_stats stats;
	int cpu, i;

	memset(&stats, 0, sizeof(struct lock_class_stats));
	for_each_possible_cpu(cpu) {
		struct lock_class_stats *pcs =
			&per_cpu(lock_stats, cpu)[class - lock_classes];

		for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
			stats.contention_point[i] += pcs->contention_point[i];

		lock_time_add(&pcs->read_waittime, &stats.read_waittime);
		lock_time_add(&pcs->write_waittime, &stats.write_waittime);

		lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
		lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
193 194 195

		for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
			stats.bounces[i] += pcs->bounces[i];
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	}

	return stats;
}

void clear_lock_stats(struct lock_class *class)
{
	int cpu;

	for_each_possible_cpu(cpu) {
		struct lock_class_stats *cpu_stats =
			&per_cpu(lock_stats, cpu)[class - lock_classes];

		memset(cpu_stats, 0, sizeof(struct lock_class_stats));
	}
	memset(class->contention_point, 0, sizeof(class->contention_point));
}

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
static struct lock_class_stats *get_lock_stats(struct lock_class *class)
{
	return &get_cpu_var(lock_stats)[class - lock_classes];
}

static void put_lock_stats(struct lock_class_stats *stats)
{
	put_cpu_var(lock_stats);
}

static void lock_release_holdtime(struct held_lock *hlock)
{
	struct lock_class_stats *stats;
	s64 holdtime;

	if (!lock_stat)
		return;

	holdtime = sched_clock() - hlock->holdtime_stamp;

234
	stats = get_lock_stats(hlock_class(hlock));
235 236 237 238 239 240 241 242 243 244 245 246
	if (hlock->read)
		lock_time_inc(&stats->read_holdtime, holdtime);
	else
		lock_time_inc(&stats->write_holdtime, holdtime);
	put_lock_stats(stats);
}
#else
static inline void lock_release_holdtime(struct held_lock *hlock)
{
}
#endif

Ingo Molnar's avatar
Ingo Molnar committed
247 248 249 250 251 252 253 254 255 256 257 258
/*
 * We keep a global list of all lock classes. The list only grows,
 * never shrinks. The list is only accessed with the lockdep
 * spinlock lock held.
 */
LIST_HEAD(all_lock_classes);

/*
 * The lockdep classes are in a hash-table as well, for fast lookup:
 */
#define CLASSHASH_BITS		(MAX_LOCKDEP_KEYS_BITS - 1)
#define CLASSHASH_SIZE		(1UL << CLASSHASH_BITS)
Peter Zijlstra's avatar
Peter Zijlstra committed
259
#define __classhashfn(key)	hash_long((unsigned long)key, CLASSHASH_BITS)
Ingo Molnar's avatar
Ingo Molnar committed
260 261 262 263 264 265 266 267 268 269
#define classhashentry(key)	(classhash_table + __classhashfn((key)))

static struct list_head classhash_table[CLASSHASH_SIZE];

/*
 * We put the lock dependency chains into a hash-table as well, to cache
 * their existence:
 */
#define CHAINHASH_BITS		(MAX_LOCKDEP_CHAINS_BITS-1)
#define CHAINHASH_SIZE		(1UL << CHAINHASH_BITS)
Peter Zijlstra's avatar
Peter Zijlstra committed
270
#define __chainhashfn(chain)	hash_long(chain, CHAINHASH_BITS)
Ingo Molnar's avatar
Ingo Molnar committed
271 272 273 274 275 276 277 278 279 280 281
#define chainhashentry(chain)	(chainhash_table + __chainhashfn((chain)))

static struct list_head chainhash_table[CHAINHASH_SIZE];

/*
 * The hash key of the lock dependency chains is a hash itself too:
 * it's a hash of all locks taken up to that lock, including that lock.
 * It's a 64-bit hash, because it's important for the keys to be
 * unique.
 */
#define iterate_chain_key(key1, key2) \
282 283
	(((key1) << MAX_LOCKDEP_KEYS_BITS) ^ \
	((key1) >> (64-MAX_LOCKDEP_KEYS_BITS)) ^ \
Ingo Molnar's avatar
Ingo Molnar committed
284 285
	(key2))

286
void lockdep_off(void)
Ingo Molnar's avatar
Ingo Molnar committed
287 288 289 290 291 292
{
	current->lockdep_recursion++;
}

EXPORT_SYMBOL(lockdep_off);

293
void lockdep_on(void)
Ingo Molnar's avatar
Ingo Molnar committed
294 295 296 297 298 299 300 301 302 303 304
{
	current->lockdep_recursion--;
}

EXPORT_SYMBOL(lockdep_on);

/*
 * Debugging switches:
 */

#define VERBOSE			0
305
#define VERY_VERBOSE		0
Ingo Molnar's avatar
Ingo Molnar committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

#if VERBOSE
# define HARDIRQ_VERBOSE	1
# define SOFTIRQ_VERBOSE	1
#else
# define HARDIRQ_VERBOSE	0
# define SOFTIRQ_VERBOSE	0
#endif

#if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
/*
 * Quick filtering for interesting events:
 */
static int class_filter(struct lock_class *class)
{
321 322
#if 0
	/* Example */
Ingo Molnar's avatar
Ingo Molnar committed
323
	if (class->name_version == 1 &&
324
			!strcmp(class->name, "lockname"))
Ingo Molnar's avatar
Ingo Molnar committed
325 326
		return 1;
	if (class->name_version == 1 &&
327
			!strcmp(class->name, "&struct->lockfield"))
Ingo Molnar's avatar
Ingo Molnar committed
328
		return 1;
329
#endif
330 331
	/* Filter everything else. 1 would be to allow everything else */
	return 0;
Ingo Molnar's avatar
Ingo Molnar committed
332 333 334 335 336 337 338 339 340 341 342 343 344
}
#endif

static int verbose(struct lock_class *class)
{
#if VERBOSE
	return class_filter(class);
#endif
	return 0;
}

/*
 * Stack-trace: tightly packed array of stack backtrace
345
 * addresses. Protected by the graph_lock.
Ingo Molnar's avatar
Ingo Molnar committed
346 347 348 349 350 351 352 353 354 355
 */
unsigned long nr_stack_trace_entries;
static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];

static int save_trace(struct stack_trace *trace)
{
	trace->nr_entries = 0;
	trace->max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries;
	trace->entries = stack_trace + nr_stack_trace_entries;

356 357
	trace->skip = 3;

358
	save_stack_trace(trace);
Ingo Molnar's avatar
Ingo Molnar committed
359 360 361 362 363 364

	trace->max_entries = trace->nr_entries;

	nr_stack_trace_entries += trace->nr_entries;

	if (nr_stack_trace_entries == MAX_STACK_TRACE_ENTRIES) {
365 366 367 368 369 370 371
		if (!debug_locks_off_graph_unlock())
			return 0;

		printk("BUG: MAX_STACK_TRACE_ENTRIES too low!\n");
		printk("turning off the locking correctness validator.\n");
		dump_stack();

Ingo Molnar's avatar
Ingo Molnar committed
372 373 374 375 376 377 378 379 380 381 382 383
		return 0;
	}

	return 1;
}

unsigned int nr_hardirq_chains;
unsigned int nr_softirq_chains;
unsigned int nr_process_chains;
unsigned int max_lockdep_depth;
unsigned int max_recursion_depth;

384 385 386 387 388 389 390 391 392 393 394 395 396
static unsigned int lockdep_dependency_gen_id;

static bool lockdep_dependency_visit(struct lock_class *source,
				     unsigned int depth)
{
	if (!depth)
		lockdep_dependency_gen_id++;
	if (source->dep_gen_id == lockdep_dependency_gen_id)
		return true;
	source->dep_gen_id = lockdep_dependency_gen_id;
	return false;
}

Ingo Molnar's avatar
Ingo Molnar committed
397 398 399 400 401 402 403
#ifdef CONFIG_DEBUG_LOCKDEP
/*
 * We cannot printk in early bootup code. Not even early_printk()
 * might work. So we mark any initialization errors and printk
 * about it later on, in lockdep_info().
 */
static int lockdep_init_error;
404 405 406 407 408
static unsigned long lockdep_init_trace_data[20];
static struct stack_trace lockdep_init_trace = {
	.max_entries = ARRAY_SIZE(lockdep_init_trace_data),
	.entries = lockdep_init_trace_data,
};
Ingo Molnar's avatar
Ingo Molnar committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

/*
 * Various lockdep statistics:
 */
atomic_t chain_lookup_hits;
atomic_t chain_lookup_misses;
atomic_t hardirqs_on_events;
atomic_t hardirqs_off_events;
atomic_t redundant_hardirqs_on;
atomic_t redundant_hardirqs_off;
atomic_t softirqs_on_events;
atomic_t softirqs_off_events;
atomic_t redundant_softirqs_on;
atomic_t redundant_softirqs_off;
atomic_t nr_unused_locks;
atomic_t nr_cyclic_checks;
atomic_t nr_cyclic_check_recursions;
atomic_t nr_find_usage_forwards_checks;
atomic_t nr_find_usage_forwards_recursions;
atomic_t nr_find_usage_backwards_checks;
atomic_t nr_find_usage_backwards_recursions;
# define debug_atomic_inc(ptr)		atomic_inc(ptr)
# define debug_atomic_dec(ptr)		atomic_dec(ptr)
# define debug_atomic_read(ptr)		atomic_read(ptr)
#else
# define debug_atomic_inc(ptr)		do { } while (0)
# define debug_atomic_dec(ptr)		do { } while (0)
# define debug_atomic_read(ptr)		0
#endif

/*
 * Locking printouts:
 */

static const char *usage_str[] =
{
	[LOCK_USED] =			"initial-use ",
	[LOCK_USED_IN_HARDIRQ] =	"in-hardirq-W",
	[LOCK_USED_IN_SOFTIRQ] =	"in-softirq-W",
	[LOCK_ENABLED_SOFTIRQS] =	"softirq-on-W",
	[LOCK_ENABLED_HARDIRQS] =	"hardirq-on-W",
	[LOCK_USED_IN_HARDIRQ_READ] =	"in-hardirq-R",
	[LOCK_USED_IN_SOFTIRQ_READ] =	"in-softirq-R",
	[LOCK_ENABLED_SOFTIRQS_READ] =	"softirq-on-R",
	[LOCK_ENABLED_HARDIRQS_READ] =	"hardirq-on-R",
};

const char * __get_key_name(struct lockdep_subclass_key *key, char *str)
{
Alexey Dobriyan's avatar
Alexey Dobriyan committed
458
	return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
Ingo Molnar's avatar
Ingo Molnar committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
}

void
get_usage_chars(struct lock_class *class, char *c1, char *c2, char *c3, char *c4)
{
	*c1 = '.', *c2 = '.', *c3 = '.', *c4 = '.';

	if (class->usage_mask & LOCKF_USED_IN_HARDIRQ)
		*c1 = '+';
	else
		if (class->usage_mask & LOCKF_ENABLED_HARDIRQS)
			*c1 = '-';

	if (class->usage_mask & LOCKF_USED_IN_SOFTIRQ)
		*c2 = '+';
	else
		if (class->usage_mask & LOCKF_ENABLED_SOFTIRQS)
			*c2 = '-';

	if (class->usage_mask & LOCKF_ENABLED_HARDIRQS_READ)
		*c3 = '-';
	if (class->usage_mask & LOCKF_USED_IN_HARDIRQ_READ) {
		*c3 = '+';
		if (class->usage_mask & LOCKF_ENABLED_HARDIRQS_READ)
			*c3 = '?';
	}

	if (class->usage_mask & LOCKF_ENABLED_SOFTIRQS_READ)
		*c4 = '-';
	if (class->usage_mask & LOCKF_USED_IN_SOFTIRQ_READ) {
		*c4 = '+';
		if (class->usage_mask & LOCKF_ENABLED_SOFTIRQS_READ)
			*c4 = '?';
	}
}

static void print_lock_name(struct lock_class *class)
{
497
	char str[KSYM_NAME_LEN], c1, c2, c3, c4;
Ingo Molnar's avatar
Ingo Molnar committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
	const char *name;

	get_usage_chars(class, &c1, &c2, &c3, &c4);

	name = class->name;
	if (!name) {
		name = __get_key_name(class->key, str);
		printk(" (%s", name);
	} else {
		printk(" (%s", name);
		if (class->name_version > 1)
			printk("#%d", class->name_version);
		if (class->subclass)
			printk("/%d", class->subclass);
	}
	printk("){%c%c%c%c}", c1, c2, c3, c4);
}

static void print_lockdep_cache(struct lockdep_map *lock)
{
	const char *name;
519
	char str[KSYM_NAME_LEN];
Ingo Molnar's avatar
Ingo Molnar committed
520 521 522 523 524 525 526 527 528 529

	name = lock->name;
	if (!name)
		name = __get_key_name(lock->key->subkeys, str);

	printk("%s", name);
}

static void print_lock(struct held_lock *hlock)
{
530
	print_lock_name(hlock_class(hlock));
Ingo Molnar's avatar
Ingo Molnar committed
531 532 533 534 535 536 537 538 539
	printk(", at: ");
	print_ip_sym(hlock->acquire_ip);
}

static void lockdep_print_held_locks(struct task_struct *curr)
{
	int i, depth = curr->lockdep_depth;

	if (!depth) {
540
		printk("no locks held by %s/%d.\n", curr->comm, task_pid_nr(curr));
Ingo Molnar's avatar
Ingo Molnar committed
541 542 543
		return;
	}
	printk("%d lock%s held by %s/%d:\n",
544
		depth, depth > 1 ? "s" : "", curr->comm, task_pid_nr(curr));
Ingo Molnar's avatar
Ingo Molnar committed
545 546 547 548 549 550 551 552 553 554 555

	for (i = 0; i < depth; i++) {
		printk(" #%d: ", i);
		print_lock(curr->held_locks + i);
	}
}

static void print_lock_class_header(struct lock_class *class, int depth)
{
	int bit;

556
	printk("%*s->", depth, "");
Ingo Molnar's avatar
Ingo Molnar committed
557 558 559 560 561 562 563 564
	print_lock_name(class);
	printk(" ops: %lu", class->ops);
	printk(" {\n");

	for (bit = 0; bit < LOCK_USAGE_STATES; bit++) {
		if (class->usage_mask & (1 << bit)) {
			int len = depth;

565
			len += printk("%*s   %s", depth, "", usage_str[bit]);
Ingo Molnar's avatar
Ingo Molnar committed
566 567 568 569
			len += printk(" at:\n");
			print_stack_trace(class->usage_traces + bit, len);
		}
	}
570
	printk("%*s }\n", depth, "");
Ingo Molnar's avatar
Ingo Molnar committed
571

572
	printk("%*s ... key      at: ",depth,"");
Ingo Molnar's avatar
Ingo Molnar committed
573 574 575 576 577 578 579 580 581 582
	print_ip_sym((unsigned long)class->key);
}

/*
 * printk all lock dependencies starting at <entry>:
 */
static void print_lock_dependencies(struct lock_class *class, int depth)
{
	struct lock_list *entry;

583 584 585
	if (lockdep_dependency_visit(class, depth))
		return;

Ingo Molnar's avatar
Ingo Molnar committed
586 587 588 589 590 591
	if (DEBUG_LOCKS_WARN_ON(depth >= 20))
		return;

	print_lock_class_header(class, depth);

	list_for_each_entry(entry, &class->locks_after, entry) {
592 593 594
		if (DEBUG_LOCKS_WARN_ON(!entry->class))
			return;

Ingo Molnar's avatar
Ingo Molnar committed
595 596
		print_lock_dependencies(entry->class, depth + 1);

597
		printk("%*s ... acquired at:\n",depth,"");
Ingo Molnar's avatar
Ingo Molnar committed
598 599 600 601 602
		print_stack_trace(&entry->trace, 2);
		printk("\n");
	}
}

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
static void print_kernel_version(void)
{
	printk("%s %.*s\n", init_utsname()->release,
		(int)strcspn(init_utsname()->version, " "),
		init_utsname()->version);
}

static int very_verbose(struct lock_class *class)
{
#if VERY_VERBOSE
	return class_filter(class);
#endif
	return 0;
}

Ingo Molnar's avatar
Ingo Molnar committed
618
/*
619
 * Is this the address of a static object:
Ingo Molnar's avatar
Ingo Molnar committed
620
 */
621
static int static_obj(void *obj)
Ingo Molnar's avatar
Ingo Molnar committed
622
{
623 624 625 626 627 628 629
	unsigned long start = (unsigned long) &_stext,
		      end   = (unsigned long) &_end,
		      addr  = (unsigned long) obj;
#ifdef CONFIG_SMP
	int i;
#endif

Ingo Molnar's avatar
Ingo Molnar committed
630
	/*
631
	 * static variable?
Ingo Molnar's avatar
Ingo Molnar committed
632
	 */
633 634
	if ((addr >= start) && (addr < end))
		return 1;
Ingo Molnar's avatar
Ingo Molnar committed
635

636
#ifdef CONFIG_SMP
Ingo Molnar's avatar
Ingo Molnar committed
637
	/*
638
	 * percpu var?
Ingo Molnar's avatar
Ingo Molnar committed
639
	 */
640 641 642 643
	for_each_possible_cpu(i) {
		start = (unsigned long) &__per_cpu_start + per_cpu_offset(i);
		end   = (unsigned long) &__per_cpu_start + PERCPU_ENOUGH_ROOM
					+ per_cpu_offset(i);
Ingo Molnar's avatar
Ingo Molnar committed
644

645 646 647
		if ((addr >= start) && (addr < end))
			return 1;
	}
648
#endif
Ingo Molnar's avatar
Ingo Molnar committed
649

650 651 652 653
	/*
	 * module var?
	 */
	return is_module_address(addr);
654 655
}

Ingo Molnar's avatar
Ingo Molnar committed
656
/*
657 658
 * To make lock name printouts unique, we calculate a unique
 * class->name_version generation counter:
Ingo Molnar's avatar
Ingo Molnar committed
659
 */
660
static int count_matching_names(struct lock_class *new_class)
Ingo Molnar's avatar
Ingo Molnar committed
661
{
662 663
	struct lock_class *class;
	int count = 0;
Ingo Molnar's avatar
Ingo Molnar committed
664

665
	if (!new_class->name)
Ingo Molnar's avatar
Ingo Molnar committed
666 667
		return 0;

668 669 670 671 672 673
	list_for_each_entry(class, &all_lock_classes, lock_entry) {
		if (new_class->key - new_class->subclass == class->key)
			return class->name_version;
		if (class->name && !strcmp(class->name, new_class->name))
			count = max(count, class->name_version);
	}
Ingo Molnar's avatar
Ingo Molnar committed
674

675
	return count + 1;
Ingo Molnar's avatar
Ingo Molnar committed
676 677
}

678 679 680 681 682 683 684
/*
 * Register a lock's class in the hash-table, if the class is not present
 * yet. Otherwise we look it up. We cache the result in the lock object
 * itself, so actual lookup of the hash should be once per lock object.
 */
static inline struct lock_class *
look_up_lock_class(struct lockdep_map *lock, unsigned int subclass)
Ingo Molnar's avatar
Ingo Molnar committed
685
{
686 687 688
	struct lockdep_subclass_key *key;
	struct list_head *hash_head;
	struct lock_class *class;
Ingo Molnar's avatar
Ingo Molnar committed
689

690 691 692 693 694 695 696 697 698
#ifdef CONFIG_DEBUG_LOCKDEP
	/*
	 * If the architecture calls into lockdep before initializing
	 * the hashes then we'll warn about it later. (we cannot printk
	 * right now)
	 */
	if (unlikely(!lockdep_initialized)) {
		lockdep_init();
		lockdep_init_error = 1;
699
		save_stack_trace(&lockdep_init_trace);
700 701
	}
#endif
Ingo Molnar's avatar
Ingo Molnar committed
702

703 704 705 706 707 708
	/*
	 * Static locks do not have their class-keys yet - for them the key
	 * is the lock object itself:
	 */
	if (unlikely(!lock->key))
		lock->key = (void *)lock;
Ingo Molnar's avatar
Ingo Molnar committed
709

710 711 712 713 714 715
	/*
	 * NOTE: the class-key must be unique. For dynamic locks, a static
	 * lock_class_key variable is passed in through the mutex_init()
	 * (or spin_lock_init()) call - which acts as the key. For static
	 * locks we use the lock object itself as the key.
	 */
Peter Zijlstra's avatar
Peter Zijlstra committed
716 717
	BUILD_BUG_ON(sizeof(struct lock_class_key) >
			sizeof(struct lockdep_map));
Ingo Molnar's avatar
Ingo Molnar committed
718

719
	key = lock->key->subkeys + subclass;
720

721
	hash_head = classhashentry(key);
722

723 724 725 726
	/*
	 * We can walk the hash lockfree, because the hash only
	 * grows, and we are careful when adding entries to the end:
	 */
Peter Zijlstra's avatar
Peter Zijlstra committed
727 728 729
	list_for_each_entry(class, hash_head, hash_entry) {
		if (class->key == key) {
			WARN_ON_ONCE(class->name != lock->name);
730
			return class;
Peter Zijlstra's avatar
Peter Zijlstra committed
731 732
		}
	}
Ingo Molnar's avatar
Ingo Molnar committed
733

734
	return NULL;
Ingo Molnar's avatar
Ingo Molnar committed
735 736 737
}

/*
738 739 740
 * Register a lock's class in the hash-table, if the class is not present
 * yet. Otherwise we look it up. We cache the result in the lock object
 * itself, so actual lookup of the hash should be once per lock object.
Ingo Molnar's avatar
Ingo Molnar committed
741
 */
742 743
static inline struct lock_class *
register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
Ingo Molnar's avatar
Ingo Molnar committed
744
{
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
	struct lockdep_subclass_key *key;
	struct list_head *hash_head;
	struct lock_class *class;
	unsigned long flags;

	class = look_up_lock_class(lock, subclass);
	if (likely(class))
		return class;

	/*
	 * Debug-check: all keys must be persistent!
 	 */
	if (!static_obj(lock->key)) {
		debug_locks_off();
		printk("INFO: trying to register non-static key.\n");
		printk("the code is fine but needs lockdep annotation.\n");
		printk("turning off the locking correctness validator.\n");
		dump_stack();

		return NULL;
	}

	key = lock->key->subkeys + subclass;
	hash_head = classhashentry(key);

	raw_local_irq_save(flags);
	if (!graph_lock()) {
		raw_local_irq_restore(flags);
		return NULL;
	}
	/*
	 * We have to do the hash-walk again, to avoid races
	 * with another CPU:
	 */
	list_for_each_entry(class, hash_head, hash_entry)
		if (class->key == key)
			goto out_unlock_set;
	/*
	 * Allocate a new key from the static array, and add it to
	 * the hash:
	 */
	if (nr_lock_classes >= MAX_LOCKDEP_KEYS) {
		if (!debug_locks_off_graph_unlock()) {
			raw_local_irq_restore(flags);
			return NULL;
		}
		raw_local_irq_restore(flags);

		printk("BUG: MAX_LOCKDEP_KEYS too low!\n");
		printk("turning off the locking correctness validator.\n");
		return NULL;
	}
	class = lock_classes + nr_lock_classes++;
	debug_atomic_inc(&nr_unused_locks);
	class->key = key;
	class->name = lock->name;
	class->subclass = subclass;
	INIT_LIST_HEAD(&class->lock_entry);
	INIT_LIST_HEAD(&class->locks_before);
	INIT_LIST_HEAD(&class->locks_after);
	class->name_version = count_matching_names(class);
	/*
	 * We use RCU's safe list-add method to make
	 * parallel walking of the hash-list safe:
	 */
	list_add_tail_rcu(&class->hash_entry, hash_head);
811 812 813 814
	/*
	 * Add it to the global list of classes:
	 */
	list_add_tail_rcu(&class->lock_entry, &all_lock_classes);
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

	if (verbose(class)) {
		graph_unlock();
		raw_local_irq_restore(flags);

		printk("\nnew class %p: %s", class->key, class->name);
		if (class->name_version > 1)
			printk("#%d", class->name_version);
		printk("\n");
		dump_stack();

		raw_local_irq_save(flags);
		if (!graph_lock()) {
			raw_local_irq_restore(flags);
			return NULL;
		}
	}
out_unlock_set:
	graph_unlock();
	raw_local_irq_restore(flags);

	if (!subclass || force)
		lock->class_cache = class;

	if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
		return NULL;

	return class;
}

#ifdef CONFIG_PROVE_LOCKING
/*
 * Allocate a lockdep entry. (assumes the graph_lock held, returns
 * with NULL on failure)
 */
static struct lock_list *alloc_list_entry(void)
{
	if (nr_list_entries >= MAX_LOCKDEP_ENTRIES) {
		if (!debug_locks_off_graph_unlock())
			return NULL;

		printk("BUG: MAX_LOCKDEP_ENTRIES too low!\n");
		printk("turning off the locking correctness validator.\n");
		return NULL;
	}
	return list_entries + nr_list_entries++;
}

/*
 * Add a new dependency to the head of the list:
 */
static int add_lock_to_list(struct lock_class *class, struct lock_class *this,
			    struct list_head *head, unsigned long ip, int distance)
{
	struct lock_list *entry;
	/*
	 * Lock not present yet - get a new dependency struct and
	 * add it to the list:
	 */
	entry = alloc_list_entry();
	if (!entry)
		return 0;

	entry->class = this;
	entry->distance = distance;
	if (!save_trace(&entry->trace))
		return 0;

	/*
	 * Since we never remove from the dependency list, the list can
	 * be walked lockless by other CPUs, it's only allocation
	 * that must be protected by the spinlock. But this also means
	 * we must make new entries visible only once writes to the
	 * entry become visible - hence the RCU op:
	 */
	list_add_tail_rcu(&entry->entry, head);

	return 1;
}

/*
 * Recursive, forwards-direction lock-dependency checking, used for
 * both noncyclic checking and for hardirq-unsafe/softirq-unsafe
 * checking.
 *
 * (to keep the stackframe of the recursive functions small we
 *  use these global variables, and we also mark various helper
 *  functions as noinline.)
 */
static struct held_lock *check_source, *check_target;

/*
 * Print a dependency chain entry (this is only done when a deadlock
 * has been detected):
 */
static noinline int
print_circular_bug_entry(struct lock_list *target, unsigned int depth)
{
	if (debug_locks_silent)
		return 0;
	printk("\n-> #%u", depth);
	print_lock_name(target->class);
	printk(":\n");
	print_stack_trace(&target->trace, 6);

	return 0;
}

/*
 * When a circular dependency is detected, print the
 * header first:
 */
static noinline int
print_circular_bug_header(struct lock_list *entry, unsigned int depth)
{
	struct task_struct *curr = current;

	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
		return 0;

	printk("\n=======================================================\n");
	printk(  "[ INFO: possible circular locking dependency detected ]\n");
	print_kernel_version();
	printk(  "-------------------------------------------------------\n");
	printk("%s/%d is trying to acquire lock:\n",
940
		curr->comm, task_pid_nr(curr));
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
	print_lock(check_source);
	printk("\nbut task is already holding lock:\n");
	print_lock(check_target);
	printk("\nwhich lock already depends on the new lock.\n\n");
	printk("\nthe existing dependency chain (in reverse order) is:\n");

	print_circular_bug_entry(entry, depth);

	return 0;
}

static noinline int print_circular_bug_tail(void)
{
	struct task_struct *curr = current;
	struct lock_list this;

	if (debug_locks_silent)
		return 0;

960
	this.class = hlock_class(check_source);
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
	if (!save_trace(&this.trace))
		return 0;

	print_circular_bug_entry(&this, 0);

	printk("\nother info that might help us debug this:\n\n");
	lockdep_print_held_locks(curr);

	printk("\nstack backtrace:\n");
	dump_stack();

	return 0;
}

#define RECURSION_LIMIT 40

static int noinline print_infinite_recursion_bug(void)
{
	if (!debug_locks_off_graph_unlock())
		return 0;

	WARN_ON(1);

	return 0;
}

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
unsigned long __lockdep_count_forward_deps(struct lock_class *class,
					   unsigned int depth)
{
	struct lock_list *entry;
	unsigned long ret = 1;

	if (lockdep_dependency_visit(class, depth))
		return 0;

	/*
	 * Recurse this class's dependency list:
	 */
	list_for_each_entry(entry, &class->locks_after, entry)
		ret += __lockdep_count_forward_deps(entry->class, depth + 1);

	return ret;
}

unsigned long lockdep_count_forward_deps(struct lock_class *class)
{
	unsigned long ret, flags;

	local_irq_save(flags);
	__raw_spin_lock(&lockdep_lock);
	ret = __lockdep_count_forward_deps(class, 0);
	__raw_spin_unlock(&lockdep_lock);
	local_irq_restore(flags);

	return ret;
}

unsigned long __lockdep_count_backward_deps(struct lock_class *class,
					    unsigned int depth)
{
	struct lock_list *entry;
	unsigned long ret = 1;

	if (lockdep_dependency_visit(class, depth))
		return 0;
	/*
	 * Recurse this class's dependency list:
	 */
	list_for_each_entry(entry, &class->locks_before, entry)
		ret += __lockdep_count_backward_deps(entry->class, depth + 1);

	return ret;
}

unsigned long lockdep_count_backward_deps(struct lock_class *class)
{
	unsigned long ret, flags;

	local_irq_save(flags);
	__raw_spin_lock(&lockdep_lock);
	ret = __lockdep_count_backward_deps(class, 0);
	__raw_spin_unlock(&lockdep_lock);
	local_irq_restore(flags);

	return ret;
}

1048 1049 1050 1051 1052 1053 1054 1055 1056
/*
 * Prove that the dependency graph starting at <entry> can not
 * lead to <target>. Print an error and return 0 if it does.
 */
static noinline int
check_noncircular(struct lock_class *source, unsigned int depth)
{
	struct lock_list *entry;

1057 1058 1059
	if (lockdep_dependency_visit(source, depth))
		return 1;

1060 1061
	debug_atomic_inc(&nr_cyclic_check_recursions);
	if (depth > max_recursion_depth)
Ingo Molnar's avatar
Ingo Molnar committed
1062
		max_recursion_depth = depth;
1063
	if (depth >= RECURSION_LIMIT)
Ingo Molnar's avatar
Ingo Molnar committed
1064 1065 1066 1067 1068
		return print_infinite_recursion_bug();
	/*
	 * Check this lock's dependency list:
	 */
	list_for_each_entry(entry, &source->locks_after, entry) {
1069
		if (entry->class == hlock_class(check_target))
Ingo Molnar's avatar
Ingo Molnar committed
1070 1071 1072 1073 1074 1075 1076 1077
			return print_circular_bug_header(entry, depth+1);
		debug_atomic_inc(&nr_cyclic_checks);
		if (!check_noncircular(entry->class, depth+1))
			return print_circular_bug_entry(entry, depth+1);
	}
	return 1;
}

1078
#if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
Ingo Molnar's avatar
Ingo Molnar committed
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
/*
 * Forwards and backwards subgraph searching, for the purposes of
 * proving that two subgraphs can be connected by a new dependency
 * without creating any illegal irq-safe -> irq-unsafe lock dependency.
 */
static enum lock_usage_bit find_usage_bit;
static struct lock_class *forwards_match, *backwards_match;

/*
 * Find a node in the forwards-direction dependency sub-graph starting
 * at <source> that matches <find_usage_bit>.
 *
 * Return 2 if such a node exists in the subgraph, and put that node
 * into <forwards_match>.
 *
 * Return 1 otherwise and keep <forwards_match> unchanged.
 * Return 0 on error.
 */
static noinline int
find_usage_forwards(struct lock_class *source, unsigned int depth)
{
	struct lock_list *entry;
	int ret;

1103 1104 1105
	if (lockdep_dependency_visit(source, depth))
		return 1;

Ingo Molnar's avatar
Ingo Molnar committed
1106 1107
	if (depth > max_recursion_depth)
		max_recursion_depth = depth;
1108
	if (depth >= RECURSION_LIMIT)
Ingo Molnar's avatar
Ingo Molnar committed
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
		return print_infinite_recursion_bug();

	debug_atomic_inc(&nr_find_usage_forwards_checks);
	if (source->usage_mask & (1 << find_usage_bit)) {
		forwards_match = source;
		return 2;
	}

	/*
	 * Check this lock's dependency list:
	 */
	list_for_each_entry(entry, &source->locks_after, entry) {
		debug_atomic_inc(&nr_find_usage_forwards_recursions);
		ret = find_usage_forwards(entry->class, depth+1);
		if (ret == 2 || ret == 0)
			return ret;
	}
	return 1;
}

/*
 * Find a node in the backwards-direction dependency sub-graph starting
 * at <source> that matches <find_usage_bit>.
 *
 * Return 2 if such a node exists in the subgraph, and put that node
 * into <backwards_match>.
 *
 * Return 1 otherwise and keep <backwards_match> unchanged.
 * Return 0 on error.
 */
1139
static noinline int
Ingo Molnar's avatar
Ingo Molnar committed
1140 1141 1142 1143 1144
find_usage_backwards(struct lock_class *source, unsigned int depth)
{
	struct lock_list *entry;
	int ret;

1145 1146 1147
	if (lockdep_dependency_visit(source, depth))
		return 1;

1148 1149 1150
	if (!__raw_spin_is_locked(&lockdep_lock))
		return DEBUG_LOCKS_WARN_ON(1);

Ingo Molnar's avatar
Ingo Molnar committed
1151 1152
	if (depth > max_recursion_depth)
		max_recursion_depth = depth;
1153
	if (depth >= RECURSION_LIMIT)
Ingo Molnar's avatar
Ingo Molnar committed
1154 1155 1156 1157 1158 1159 1160 1161
		return print_infinite_recursion_bug();

	debug_atomic_inc(&nr_find_usage_backwards_checks);
	if (source->usage_mask & (1 << find_usage_bit)) {
		backwards_match = source;
		return 2;
	}

1162 1163 1164 1165 1166
	if (!source && debug_locks_off_graph_unlock()) {
		WARN_ON(1);
		return 0;
	}

Ingo Molnar's avatar
Ingo Molnar committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
	/*
	 * Check this lock's dependency list:
	 */
	list_for_each_entry(entry, &source->locks_before, entry) {
		debug_atomic_inc(&nr_find_usage_backwards_recursions);
		ret = find_usage_backwards(entry->class, depth+1);
		if (ret == 2 || ret == 0)
			return ret;
	}
	return 1;
}

static int
print_bad_irq_dependency(struct task_struct *curr,
			 struct held_lock *prev,
			 struct held_lock *next,
			 enum lock_usage_bit bit1,
			 enum lock_usage_bit bit2,
			 const char *irqclass)
{
1187
	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
Ingo Molnar's avatar
Ingo Molnar committed
1188 1189 1190 1191 1192
		return 0;

	printk("\n======================================================\n");
	printk(  "[ INFO: %s-safe -> %s-unsafe lock order detected ]\n",
		irqclass, irqclass);
1193
	print_kernel_version();
Ingo Molnar's avatar
Ingo Molnar committed
1194 1195
	printk(  "------------------------------------------------------\n");
	printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
1196
		curr->comm, task_pid_nr(curr),
Ingo Molnar's avatar
Ingo Molnar committed
1197 1198 1199 1200 1201 1202 1203 1204 1205
		curr->hardirq_context, hardirq_count() >> HARDIRQ_SHIFT,
		curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
		curr->hardirqs_enabled,
		curr->softirqs_enabled);
	print_lock(next);

	printk("\nand this task is already holding:\n");
	print_lock(prev);
	printk("which would create a new lock dependency:\n");
1206
	print_lock_name(hlock_class(prev));
Ingo Molnar's avatar
Ingo Molnar committed
1207
	printk(" ->");
1208
	print_lock_name(hlock_class(next));
Ingo Molnar's avatar
Ingo Molnar committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
	printk("\n");

	printk("\nbut this new dependency connects a %s-irq-safe lock:\n",
		irqclass);
	print_lock_name(backwards_match);
	printk("\n... which became %s-irq-safe at:\n", irqclass);

	print_stack_trace(backwards_match->usage_traces + bit1, 1);

	printk("\nto a %s-irq-unsafe lock:\n", irqclass);
	print_lock_name(forwards_match);
	printk("\n... which became %s-irq-unsafe at:\n", irqclass);
	printk("...");

	print_stack_trace(forwards_match->usage_traces + bit2, 1);

	printk("\nother info that might help us debug this:\n\n");
	lockdep_print_held_locks(curr);

	printk("\nthe %s-irq-safe lock's dependencies:\n", irqclass);
	print_lock_dependencies(backwards_match, 0);

	printk("\nthe %s-irq-unsafe lock's dependencies:\n", irqclass);
	print_lock_dependencies(forwards_match, 0);

	printk("\nstack backtrace:\n");
	dump_stack();

	return 0;
}

static int
check_usage(struct task_struct *curr, struct held_lock *prev,
	    struct held_lock *next, enum lock_usage_bit bit_backwards,
	    enum lock_usage_bit bit_forwards, const char *irqclass)
{
	int ret;

	find_usage_bit = bit_backwards;
	/* fills in <backwards_match> */
1249
	ret = find_usage_backwards(hlock_class(prev), 0);
Ingo Molnar's avatar
Ingo Molnar committed
1250 1251 1252 1253
	if (!ret || ret == 1)
		return ret;

	find_usage_bit = bit_forwards;
1254
	ret = find_usage_forwards(hlock_class(next), 0);
Ingo Molnar's avatar
Ingo Molnar committed
1255 1256 1257 1258 1259 1260 1261
	if (!ret || ret == 1)
		return ret;
	/* ret == 2 */
	return print_bad_irq_dependency(curr, prev, next,
			bit_backwards, bit_forwards, irqclass);
}

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
static int
check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
		struct held_lock *next)
{
	/*
	 * Prove that the new dependency does not connect a hardirq-safe
	 * lock with a hardirq-unsafe lock - to achieve this we search
	 * the backwards-subgraph starting at <prev>, and the
	 * forwards-subgraph starting at <next>:
	 */
	if (!check_usage(curr, prev, next, LOCK_USED_IN_HARDIRQ,
					LOCK_ENABLED_HARDIRQS, "hard"))
		return 0;

	/*
	 * Prove that the new dependency does not connect a hardirq-safe-read
	 * lock with a hardirq-unsafe lock - to achieve this we search
	 * the backwards-subgraph starting at <prev>, and the
	 * forwards-subgraph starting at <next>:
	 */
	if (!check_usage(curr, prev, next, LOCK_USED_IN_HARDIRQ_READ,
					LOCK_ENABLED_HARDIRQS, "hard-read"))
		return 0;

	/*
	 * Prove that the new dependency does not connect a softirq-safe
	 * lock with a softirq-unsafe lock - to achieve this we search
	 * the backwards-subgraph starting at <prev>, and the
	 * forwards-subgraph starting at <next>:
	 */
	if (!check_usage(curr, prev, next, LOCK_USED_IN_SOFTIRQ,
					LOCK_ENABLED_SOFTIRQS, "soft"))
		return 0;
	/*
	 * Prove that the new dependency does not connect a softirq-safe-read
	 * lock with a softirq-unsafe lock - to achieve this we search
	 * the backwards-subgraph starting at <prev>, and the
	 * forwards-subgraph starting at <next>:
	 */
	if (!check_usage(curr, prev, next, LOCK_USED_IN_SOFTIRQ_READ,
					LOCK_ENABLED_SOFTIRQS, "soft"))
		return 0;

	return 1;
}

static void inc_chains(void)
{
	if (current->hardirq_context)
		nr_hardirq_chains++;
	else {
		if (current->softirq_context)
			nr_softirq_chains++;
		else
			nr_process_chains++;
	}
}

#else

static inline int
check_prev_add_irq(struct task_struct *curr, struct held_lock *prev,
		struct held_lock *next)
{
	return 1;
}

static inline void inc_chains(void)
{
	nr_process_chains++;
}

Ingo Molnar's avatar
Ingo Molnar committed
1334 1335 1336 1337 1338 1339
#endif

static int
print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
		   struct held_lock *next)
{
1340
	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
Ingo Molnar's avatar
Ingo Molnar committed
1341 1342 1343 1344
		return 0;

	printk("\n=============================================\n");
	printk(  "[ INFO: possible recursive locking detected ]\n");
1345
	print_kernel_version();
Ingo Molnar's avatar
Ingo Molnar committed
1346 1347
	printk(  "---------------------------------------------\n");
	printk("%s/%d is trying to acquire lock:\n",
1348
		curr->comm, task_pid_nr(curr));
Ingo Molnar's avatar
Ingo Molnar committed
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
	print_lock(next);
	printk("\nbut task is already holding lock:\n");
	print_lock(prev);

	printk("\nother info that might help us debug this:\n");
	lockdep_print_held_locks(curr);

	printk("\nstack backtrace:\n");
	dump_stack();

	return 0;
}

/*
 * Check whether we are holding such a class already.
 *
 * (Note that this has to be done separately, because the graph cannot
 * detect such classes of deadlocks.)
 *
 * Returns: 0 on deadlock detected, 1 on OK, 2 on recursive read
 */
static int
check_deadlock(struct task_struct *curr, struct held_lock *next,
	       struct lockdep_map *next_instance, int read)
{
	struct held_lock *prev;
1375
	struct held_lock *nest = NULL;
Ingo Molnar's avatar
Ingo Molnar committed
1376 1377 1378 1379
	int i;

	for (i = 0; i < curr->lockdep_depth; i++) {
		prev = curr->held_locks + i;
1380 1381 1382 1383

		if (prev->instance == next->nest_lock)
			nest = prev;

1384
		if (hlock_class(prev) != hlock_class(next))
Ingo Molnar's avatar
Ingo Molnar committed
1385
			continue;
1386

Ingo Molnar's avatar
Ingo Molnar committed
1387 1388
		/*
		 * Allow read-after-read recursion of the same
1389
		 * lock class (i.e. read_lock(lock)+read_lock(lock)):
Ingo Molnar's avatar
Ingo Molnar committed
1390
		 */
1391
		if ((read == 2) && prev->read)
Ingo Molnar's avatar
Ingo Molnar committed
1392
			return 2;
1393 1394 1395 1396 1397 1398 1399 1400

		/*
		 * We're holding the nest_lock, which serializes this lock's
		 * nesting behaviour.
		 */
		if (nest)
			return 2;

Ingo Molnar's avatar
Ingo Molnar committed
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
		return print_deadlock_bug(curr, prev, next);
	}
	return 1;
}

/*
 * There was a chain-cache miss, and we are about to add a new dependency
 * to a previous lock. We recursively validate the following rules:
 *
 *  - would the adding of the <prev> -> <next> dependency create a
 *    circular dependency in the graph? [== circular deadlock]
 *
 *  - does the new prev->next dependency connect any hardirq-safe lock
 *    (in the full backwards-subgraph starting at <prev>) with any
 *    hardirq-unsafe lock (in the full forwards-subgraph starting at
 *    <next>)? [== illegal lock inversion with hardirq contexts]
 *
 *  - does the new prev->next dependency connect any softirq-safe lock
 *    (in the full backwards-subgraph starting at <prev>) with any
 *    softirq-unsafe lock (in the full forwards-subgraph starting at
 *    <next>)? [== illegal lock inversion with softirq contexts]
 *
 * any of these scenarios could lead to a deadlock.
 *
 * Then if all the validations pass, we add the forwards and backwards
 * dependency.
 */
static int
check_prev_add(struct task_struct *curr, struct held_lock *prev,
1430
	       struct held_lock *next, int distance)
Ingo Molnar's avatar
Ingo Molnar committed
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
{
	struct lock_list *entry;
	int ret;

	/*
	 * Prove that the new <prev> -> <next> dependency would not
	 * create a circular dependency in the graph. (We do this by
	 * forward-recursing into the graph starting at <next>, and
	 * checking whether we can reach <prev>.)
	 *
	 * We are using global variables to control the recursion, to
	 * keep the stackframe size of the recursive functions low:
	 */
	check_source = next;
	check_target = prev;
1446
	if (!(check_noncircular(hlock_class(next), 0)))
Ingo Molnar's avatar
Ingo Molnar committed
1447 1448
		return print_circular_bug_tail();

1449
	if (!check_prev_add_irq(curr, prev, next))
Ingo Molnar's avatar
Ingo Molnar committed
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
		return 0;

	/*
	 * For recursive read-locks we do all the dependency checks,
	 * but we dont store read-triggered dependencies (only
	 * write-triggered dependencies). This ensures that only the
	 * write-side dependencies matter, and that if for example a
	 * write-lock never takes any other locks, then the reads are
	 * equivalent to a NOP.
	 */
	if (next->read == 2 || prev->read == 2)
		return 1;
	/*
	 * Is the <prev> -> <next> dependency already present?
	 *
	 * (this may occur even though this is a new chain: consider
	 *  e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
	 *  chains - the second one will be new, but L1 already has
	 *  L2 added to its dependency list, due to the first chain.)
	 */
1470 1471
	list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
		if (entry->class == hlock_class(next)) {
1472 1473
			if (distance == 1)
				entry->distance = 1;
Ingo Molnar's avatar
Ingo Molnar committed
1474
			return 2;
1475
		}
Ingo Molnar's avatar
Ingo Molnar committed
1476 1477 1478 1479 1480 1481
	}

	/*
	 * Ok, all validations passed, add the new lock
	 * to the previous lock's dependency list:
	 */
1482 1483 1484
	ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
			       &hlock_class(prev)->locks_after,
			       next->acquire_ip, distance);
1485

Ingo Molnar's avatar
Ingo Molnar committed
1486 1487
	if (!ret)
		return 0;
1488

1489 1490 1491
	ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
			       &hlock_class(next)->locks_before,
			       next->acquire_ip, distance);
1492 1493
	if (!ret)
		return 0;
Ingo Molnar's avatar
Ingo Molnar committed
1494 1495

	/*
1496 1497
	 * Debugging printouts:
	 */
1498
	if (verbose(hlock_class(prev)) || verbose(hlock_class(next))) {
1499 1500
		graph_unlock();
		printk("\n new dependency: ");
1501
		print_lock_name(hlock_class(prev));
1502
		printk(" => ");
1503
		print_lock_name(hlock_class(next));
1504
		printk("\n");
Ingo Molnar's avatar
Ingo Molnar committed
1505
		dump_stack();
1506
		return graph_lock();
Ingo Molnar's avatar
Ingo Molnar committed
1507
	}
1508 1509
	return 1;
}
Ingo Molnar's avatar
Ingo Molnar committed
1510

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
/*
 * Add the dependency to all directly-previous locks that are 'relevant'.
 * The ones that are relevant are (in increasing distance from curr):
 * all consecutive trylock entries and the final non-trylock entry - or
 * the end of this context's lock-chain - whichever comes first.
 */
static int
check_prevs_add(struct task_struct *curr, struct held_lock *next)
{
	int depth = curr->lockdep_depth;
	struct held_lock *hlock;
1522

Ingo Molnar's avatar
Ingo Molnar committed
1523
	/*
1524 1525 1526
	 * Debugging checks.
	 *
	 * Depth must not be zero for a non-head lock:
Ingo Molnar's avatar
Ingo Molnar committed
1527
	 */
1528 1529
	if (!depth)
		goto out_bug;
Ingo Molnar's avatar
Ingo Molnar committed
1530
	/*
1531 1532
	 * At least two relevant locks must exist for this
	 * to be a head:
Ingo Molnar's avatar
Ingo Molnar committed
1533
	 */
1534 1535 1536
	if (curr->held_locks[depth].irq_context !=
			curr->held_locks[depth-1].irq_context)
		goto out_bug;
1537

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
	for (;;) {
		int distance = curr->lockdep_depth - depth + 1;
		hlock = curr->held_locks + depth-1;
		/*
		 * Only non-recursive-read entries get new dependencies
		 * added:
		 */
		if (hlock->read != 2) {
			if (!check_prev_add(curr, hlock, next, distance))
				return 0;
			/*
			 * Stop after the first non-trylock entry,
			 * as non-trylock entries have added their
			 * own direct dependencies already, so this
			 * lock is connected to them indirectly:
			 */
			if (!hlock->trylock)
				break;
1556
		}
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
		depth--;
		/*
		 * End of lock-stack?
		 */
		if (!depth)
			break;
		/*
		 * Stop the search if we cross into another context:
		 */
		if (curr->held_locks[depth].irq_context !=
				curr->held_locks[depth-1].irq_context)
			break;
Ingo Molnar's avatar
Ingo Molnar committed
1569
	}
1570 1571 1572 1573
	return 1;
out_bug:
	if (!debug_locks_off_graph_unlock())
		return 0;
Ingo Molnar's avatar
Ingo Molnar committed
1574

1575
	WARN_ON(1);
Ingo Molnar's avatar
Ingo Molnar committed
1576

1577
	return 0;
Ingo Molnar's avatar
Ingo Molnar committed
1578 1579
}

1580
unsigned long nr_lock_chains;
1581
struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
1582
int nr_chain_hlocks;
1583 1584 1585 1586 1587 1588
static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];

struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
{
	return lock_classes + chain_hlocks[chain->base + i];
}
1589

Ingo Molnar's avatar
Ingo Molnar committed
1590 1591
/*
 * Look up a dependency chain. If the key is not present yet then
1592 1593 1594
 * add it and return 1 - in this case the new dependency chain is
 * validated. If the key is already hashed, return 0.
 * (On return with 1 graph_lock is held.)
Ingo Molnar's avatar
Ingo Molnar committed
1595
 */
1596 1597 1598
static inline int lookup_chain_cache(struct task_struct *curr,
				     struct held_lock *hlock,
				     u64 chain_key)
Ingo Molnar's avatar
Ingo Molnar committed
1599
{
1600
	struct lock_class *class = hlock_class(hlock);
Ingo Molnar's avatar
Ingo Molnar committed
1601 1602
	struct list_head *hash_head = chainhashentry(chain_key);
	struct lock_chain *chain;
1603
	struct held_lock *hlock_curr, *hlock_next;
1604
	int i, j, n, cn;
Ingo Molnar's avatar
Ingo Molnar committed
1605

1606 1607
	if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
		return 0;
Ingo Molnar's avatar
Ingo Molnar committed
1608 1609 1610 1611 1612 1613 1614 1615
	/*
	 * We can walk it lock-free, because entries only get added
	 * to the hash:
	 */
	list_for_each_entry(chain, hash_head, entry) {
		if (chain->chain_key == chain_key) {
cache_hit:
			debug_atomic_inc(&chain_lookup_hits);
1616
			if (very_verbose(class))
1617 1618 1619 1620
				printk("\nhash chain already cached, key: "
					"%016Lx tail class: [%p] %s\n",
					(unsigned long long)chain_key,
					class->key, class->name);
Ingo Molnar's avatar
Ingo Molnar committed
1621 1622 1623
			return 0;
		}
	}
1624
	if (very_verbose(class))
1625 1626
		printk("\nnew hash chain, key: %016Lx tail class: [%p] %s\n",
			(unsigned long long)chain_key, class->key, class->name);
Ingo Molnar's avatar
Ingo Molnar committed
1627 1628 1629 1630
	/*
	 * Allocate a new chain entry from the static array, and add
	 * it to the hash:
	 */
1631 1632
	if (!graph_lock())
		return 0;
Ingo Molnar's avatar
Ingo Molnar committed
1633 1634 1635 1636 1637
	/*
	 * We have to walk the chain again locked - to avoid duplicates:
	 */
	list_for_each_entry(chain, hash_head, entry) {
		if (chain->chain_key == chain_key) {
1638
			graph_unlock();
Ingo Molnar's avatar
Ingo Molnar committed
1639 1640 1641 1642
			goto cache_hit;
		}
	}
	if (unlikely(nr_lock_chains >= MAX_LOCKDEP_CHAINS)) {
1643 1644 1645
		if (!debug_locks_off_graph_unlock())
			return 0;

Ingo Molnar's avatar
Ingo Molnar committed
1646 1647 1648 1649 1650 1651
		printk("BUG: MAX_LOCKDEP_CHAINS too low!\n");
		printk("turning off the locking correctness validator.\n");
		return 0;
	}
	chain = lock_chains + nr_lock_chains++;
	chain->chain_key = chain_key;
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
	chain->irq_context = hlock->irq_context;
	/* Find the first held_lock of current chain */
	hlock_next = hlock;
	for (i = curr->lockdep_depth - 1; i >= 0; i--) {
		hlock_curr = curr->held_locks + i;
		if (hlock_curr->irq_context != hlock_next->irq_context)
			break;
		hlock_next = hlock;
	}
	i++;
	chain->depth = curr->lockdep_depth + 1 - i;
1663 1664 1665 1666 1667 1668 1669 1670 1671
	cn = nr_chain_hlocks;
	while (cn + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS) {
		n = cmpxchg(&nr_chain_hlocks, cn, cn + chain->depth);
		if (n == cn)
			break;
		cn = n;
	}
	if (likely(cn + chain->depth <= MAX_LOCKDEP_CHAIN_HLOCKS)) {
		chain->base = cn;
1672
		for (j = 0; j < chain->depth - 1; j++, i++) {
1673
			int lock_id = curr->held_locks[i].class_idx - 1;
1674 1675 1676 1677
			chain_hlocks[chain->base + j] = lock_id;
		}
		chain_hlocks[chain->base + j] = class - lock_classes;
	}
Ingo Molnar's avatar
Ingo Molnar committed
1678 1679
	list_add_tail_rcu(&chain->entry, hash_head);
	debug_atomic_inc(&chain_lookup_misses);
1680 1681 1682 1683 1684 1685
	inc_chains();

	return 1;
}

static int validate_chain(struct task_struct *curr, struct lockdep_map *lock,
1686
		struct held_lock *hlock, int chain_head, u64 chain_key)
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
{
	/*
	 * Trylock needs to maintain the stack of held locks, but it
	 * does not add new dependencies, because trylock can be done
	 * in any order.
	 *
	 * We look up the chain_key and do the O(N^2) check and update of
	 * the dependencies only if this is a new dependency chain.
	 * (If lookup_chain_cache() returns with 1 it acquires
	 * graph_lock for us)
	 */
	if (!hlock->trylock && (hlock->check == 2) &&
1699
	    lookup_chain_cache(curr, hlock, chain_key)) {
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
		/*
		 * Check whether last held lock:
		 *
		 * - is irq-safe, if this lock is irq-unsafe
		 * - is softirq-safe, if this lock is hardirq-unsafe
		 *
		 * And check whether the new lock's dependency graph
		 * could lead back to the previous lock.
		 *
		 * any of these scenarios could lead to a deadlock. If
		 * All validations
		 */
		int ret = check_deadlock(curr, hlock, lock, hlock->read);

		if (!ret)
			return 0;
		/*
		 * Mark recursive read, as we jump over it when
		 * building dependencies (just like we jump over
		 * trylock entries):
		 */
		if (ret == 2)
			hlock->read = 2;
		/*
		 * Add dependency only if this lock is not the head
		 * of the chain, and if it's not a secondary read-lock:
		 */
		if (!chain_head && ret != 2)
			if (!check_prevs_add(curr, hlock))
				return 0;
		graph_unlock();
	} else
		/* after lookup_chain_cache(): */
		if (unlikely(!debug_locks))
			return 0;
Ingo Molnar's avatar
Ingo Molnar committed
1735 1736 1737

	return 1;
}
1738 1739 1740
#else
static inline int validate_chain(struct task_struct *curr,
	       	struct lockdep_map *lock, struct held_lock *hlock,
1741
		int chain_head, u64 chain_key)
1742 1743 1744
{
	return 1;
}
1745
#endif
Ingo Molnar's avatar
Ingo Molnar committed
1746 1747 1748 1749 1750

/*
 * We are building curr_chain_key incrementally, so double-check
 * it from scratch, to make sure that it's done correctly:
 */
1751
static void check_chain_key(struct task_struct *curr)
Ingo Molnar's avatar
Ingo Molnar committed
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
{
#ifdef CONFIG_DEBUG_LOCKDEP
	struct held_lock *hlock, *prev_hlock = NULL;
	unsigned int i, id;
	u64 chain_key = 0;

	for (i = 0; i < curr->lockdep_depth; i++) {
		hlock = curr->held_locks + i;
		if (chain_key != hlock->prev_chain_key) {
			debug_locks_off();
			printk("hm#1, depth: %u [%u], %016Lx != %016Lx\n",
				curr->lockdep_depth, i,
				(unsigned long long)chain_key,
				(unsigned long long)hlock->prev_chain_key);
			WARN_ON(1);
			return;
		}
1769
		id = hlock->class_idx - 1;
1770 1771 1772
		if (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
			return;

Ingo Molnar's avatar
Ingo Molnar committed
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
		if (prev_hlock && (prev_hlock->irq_context !=
							hlock->irq_context))
			chain_key = 0;
		chain_key = iterate_chain_key(chain_key, id);
		prev_hlock = hlock;
	}
	if (chain_key != curr->curr_chain_key) {
		debug_locks_off();
		printk("hm#2, depth: %u [%u], %016Lx != %016Lx\n",
			curr->lockdep_depth, i,
			(unsigned long long)chain_key,
			(unsigned long long)curr->curr_chain_key);
		WARN_ON(1);
	}
#endif
}

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
static int
print_usage_bug(struct task_struct *curr, struct held_lock *this,
		enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
{
	if (!debug_locks_off_graph_unlock() || debug_locks_silent)
		return 0;

	printk("\n=================================\n");
	printk(  "[ INFO: inconsistent lock state ]\n");
	print_kernel_version();
	printk(  "---------------------------------\n");

	printk("inconsistent {%s} -> {%s} usage.\n",
		usage_str[prev_bit], usage_str[new_bit]);

	printk("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
1806
		curr->comm, task_pid_nr(curr),
1807 1808 1809 1810 1811 1812 1813
		trace_hardirq_context(curr), hardirq_count() >> HARDIRQ_SHIFT,
		trace_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
		trace_hardirqs_enabled(curr),
		trace_softirqs_enabled(curr));
	print_lock(this);

	printk("{%s} state was registered at:\n", usage_str[prev_bit]);
1814
	print_stack_trace(hlock_class(this)->usage_traces + prev_bit, 1);
1815 1816 1817