builtin-lock.c 23.1 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2
#include <errno.h>
3
#include <inttypes.h>
4 5 6
#include "builtin.h"
#include "perf.h"

7
#include "util/evlist.h" // for struct evsel_str_handler
8
#include "util/evsel.h"
9 10 11 12
#include "util/symbol.h"
#include "util/thread.h"
#include "util/header.h"

13
#include <subcmd/pager.h>
14
#include <subcmd/parse-options.h>
15 16 17 18
#include "util/trace-event.h"

#include "util/debug.h"
#include "util/session.h"
19
#include "util/tool.h"
20
#include "util/data.h"
21 22 23 24 25 26 27 28 29 30

#include <sys/types.h>
#include <sys/prctl.h>
#include <semaphore.h>
#include <pthread.h>
#include <math.h>
#include <limits.h>

#include <linux/list.h>
#include <linux/hash.h>
31
#include <linux/kernel.h>
32
#include <linux/zalloc.h>
33
#include <linux/err.h>
34

35 36
static struct perf_session *session;

37 38 39 40 41 42 43 44 45 46
/* based on kernel/lockdep.c */
#define LOCKHASH_BITS		12
#define LOCKHASH_SIZE		(1UL << LOCKHASH_BITS)

static struct list_head lockhash_table[LOCKHASH_SIZE];

#define __lockhashfn(key)	hash_long((unsigned long)key, LOCKHASH_BITS)
#define lockhashentry(key)	(lockhash_table + __lockhashfn((key)))

struct lock_stat {
47 48
	struct list_head	hash_entry;
	struct rb_node		rb;		/* used for sorting */
49

50
	/*
51
	 * FIXME: evsel__intval() returns u64,
52
	 * so address of lockdep_map should be dealed as 64bit.
53 54 55 56
	 * Is there more better solution?
	 */
	void			*addr;		/* address of lockdep_map, used as ID */
	char			*name;		/* for strcpy(), we cannot use const */
57

58
	unsigned int		nr_acquire;
59
	unsigned int		nr_acquired;
60 61
	unsigned int		nr_contended;
	unsigned int		nr_release;
62

63 64
	unsigned int		nr_readlock;
	unsigned int		nr_trylock;
65

66
	/* these times are in nano sec. */
67
	u64                     avg_wait_time;
68 69 70
	u64			wait_time_total;
	u64			wait_time_min;
	u64			wait_time_max;
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

	int			discard; /* flag of blacklist */
};

/*
 * States of lock_seq_stat
 *
 * UNINITIALIZED is required for detecting first event of acquire.
 * As the nature of lock events, there is no guarantee
 * that the first event for the locks are acquire,
 * it can be acquired, contended or release.
 */
#define SEQ_STATE_UNINITIALIZED      0	       /* initial state */
#define SEQ_STATE_RELEASED	1
#define SEQ_STATE_ACQUIRING	2
#define SEQ_STATE_ACQUIRED	3
#define SEQ_STATE_READ_ACQUIRED	4
#define SEQ_STATE_CONTENDED	5

/*
 * MAX_LOCK_DEPTH
 * Imported from include/linux/sched.h.
 * Should this be synchronized?
 */
#define MAX_LOCK_DEPTH 48

/*
 * struct lock_seq_stat:
 * Place to put on state of one lock sequence
 * 1) acquire -> acquired -> release
 * 2) acquire -> contended -> acquired -> release
 * 3) acquire (with read or try) -> release
 * 4) Are there other patterns?
 */
struct lock_seq_stat {
	struct list_head        list;
	int			state;
	u64			prev_event_time;
	void                    *addr;

	int                     read_count;
112 113
};

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 167 168 169 170 171 172
struct thread_stat {
	struct rb_node		rb;

	u32                     tid;
	struct list_head        seq_list;
};

static struct rb_root		thread_stats;

static struct thread_stat *thread_stat_find(u32 tid)
{
	struct rb_node *node;
	struct thread_stat *st;

	node = thread_stats.rb_node;
	while (node) {
		st = container_of(node, struct thread_stat, rb);
		if (st->tid == tid)
			return st;
		else if (tid < st->tid)
			node = node->rb_left;
		else
			node = node->rb_right;
	}

	return NULL;
}

static void thread_stat_insert(struct thread_stat *new)
{
	struct rb_node **rb = &thread_stats.rb_node;
	struct rb_node *parent = NULL;
	struct thread_stat *p;

	while (*rb) {
		p = container_of(*rb, struct thread_stat, rb);
		parent = *rb;

		if (new->tid < p->tid)
			rb = &(*rb)->rb_left;
		else if (new->tid > p->tid)
			rb = &(*rb)->rb_right;
		else
			BUG_ON("inserting invalid thread_stat\n");
	}

	rb_link_node(&new->rb, parent, rb);
	rb_insert_color(&new->rb, &thread_stats);
}

static struct thread_stat *thread_stat_findnew_after_first(u32 tid)
{
	struct thread_stat *st;

	st = thread_stat_find(tid);
	if (st)
		return st;

	st = zalloc(sizeof(struct thread_stat));
173 174 175 176
	if (!st) {
		pr_err("memory allocation failed\n");
		return NULL;
	}
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

	st->tid = tid;
	INIT_LIST_HEAD(&st->seq_list);

	thread_stat_insert(st);

	return st;
}

static struct thread_stat *thread_stat_findnew_first(u32 tid);
static struct thread_stat *(*thread_stat_findnew)(u32 tid) =
	thread_stat_findnew_first;

static struct thread_stat *thread_stat_findnew_first(u32 tid)
{
	struct thread_stat *st;

	st = zalloc(sizeof(struct thread_stat));
195 196 197 198
	if (!st) {
		pr_err("memory allocation failed\n");
		return NULL;
	}
199 200 201 202 203 204 205 206 207 208
	st->tid = tid;
	INIT_LIST_HEAD(&st->seq_list);

	rb_link_node(&st->rb, NULL, &thread_stats.rb_node);
	rb_insert_color(&st->rb, &thread_stats);

	thread_stat_findnew = thread_stat_findnew_after_first;
	return st;
}

209
/* build simple key function one is bigger than two */
210
#define SINGLE_KEY(member)						\
211 212 213 214 215 216 217 218
	static int lock_stat_key_ ## member(struct lock_stat *one,	\
					 struct lock_stat *two)		\
	{								\
		return one->member > two->member;			\
	}

SINGLE_KEY(nr_acquired)
SINGLE_KEY(nr_contended)
219
SINGLE_KEY(avg_wait_time)
220 221 222
SINGLE_KEY(wait_time_total)
SINGLE_KEY(wait_time_max)

223 224 225 226 227 228 229 230 231 232 233 234
static int lock_stat_key_wait_time_min(struct lock_stat *one,
					struct lock_stat *two)
{
	u64 s1 = one->wait_time_min;
	u64 s2 = two->wait_time_min;
	if (s1 == ULLONG_MAX)
		s1 = 0;
	if (s2 == ULLONG_MAX)
		s2 = 0;
	return s1 > s2;
}

235 236 237 238 239 240
struct lock_key {
	/*
	 * name: the value for specify by user
	 * this should be simpler than raw name of member
	 * e.g. nr_acquired -> acquired, wait_time_total -> wait_total
	 */
241 242
	const char		*name;
	int			(*key)(struct lock_stat*, struct lock_stat*);
243 244
};

245 246 247 248 249
static const char		*sort_key = "acquired";

static int			(*compare)(struct lock_stat *, struct lock_stat *);

static struct rb_root		result;	/* place to store sorted data */
250 251 252 253 254 255

#define DEF_KEY_LOCK(name, fn_suffix)	\
	{ #name, lock_stat_key_ ## fn_suffix }
struct lock_key keys[] = {
	DEF_KEY_LOCK(acquired, nr_acquired),
	DEF_KEY_LOCK(contended, nr_contended),
256
	DEF_KEY_LOCK(avg_wait, avg_wait_time),
257 258 259 260 261 262 263 264 265
	DEF_KEY_LOCK(wait_total, wait_time_total),
	DEF_KEY_LOCK(wait_min, wait_time_min),
	DEF_KEY_LOCK(wait_max, wait_time_max),

	/* extra comparisons much complicated should be here */

	{ NULL, NULL }
};

266
static int select_key(void)
267 268 269 270 271 272
{
	int i;

	for (i = 0; keys[i].name; i++) {
		if (!strcmp(keys[i].name, sort_key)) {
			compare = keys[i].key;
273
			return 0;
274 275 276
		}
	}

277 278 279
	pr_err("Unknown compare key: %s\n", sort_key);

	return -1;
280 281 282
}

static void insert_to_result(struct lock_stat *st,
283
			     int (*bigger)(struct lock_stat *, struct lock_stat *))
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
{
	struct rb_node **rb = &result.rb_node;
	struct rb_node *parent = NULL;
	struct lock_stat *p;

	while (*rb) {
		p = container_of(*rb, struct lock_stat, rb);
		parent = *rb;

		if (bigger(st, p))
			rb = &(*rb)->rb_left;
		else
			rb = &(*rb)->rb_right;
	}

	rb_link_node(&st->rb, parent, rb);
	rb_insert_color(&st->rb, &result);
}

/* returns left most element of result, and erase it */
static struct lock_stat *pop_from_result(void)
{
	struct rb_node *node = result.rb_node;

	if (!node)
		return NULL;

	while (node->rb_left)
		node = node->rb_left;

	rb_erase(node, &result);
	return container_of(node, struct lock_stat, rb);
}

318
static struct lock_stat *lock_stat_findnew(void *addr, const char *name)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
{
	struct list_head *entry = lockhashentry(addr);
	struct lock_stat *ret, *new;

	list_for_each_entry(ret, entry, hash_entry) {
		if (ret->addr == addr)
			return ret;
	}

	new = zalloc(sizeof(struct lock_stat));
	if (!new)
		goto alloc_failed;

	new->addr = addr;
	new->name = zalloc(sizeof(char) * strlen(name) + 1);
D
Davidlohr Bueso 已提交
334 335
	if (!new->name) {
		free(new);
336
		goto alloc_failed;
D
Davidlohr Bueso 已提交
337
	}
338

D
Davidlohr Bueso 已提交
339
	strcpy(new->name, name);
340 341 342 343 344 345
	new->wait_time_min = ULLONG_MAX;

	list_add(&new->hash_entry, entry);
	return new;

alloc_failed:
346 347
	pr_err("memory allocation failed\n");
	return NULL;
348 349 350
}

struct trace_lock_handler {
351
	int (*acquire_event)(struct evsel *evsel,
352
			     struct perf_sample *sample);
353

354
	int (*acquired_event)(struct evsel *evsel,
355
			      struct perf_sample *sample);
356

357
	int (*contended_event)(struct evsel *evsel,
358
			       struct perf_sample *sample);
359

360
	int (*release_event)(struct evsel *evsel,
361
			     struct perf_sample *sample);
362 363
};

364 365 366 367 368 369 370 371 372 373
static struct lock_seq_stat *get_seq(struct thread_stat *ts, void *addr)
{
	struct lock_seq_stat *seq;

	list_for_each_entry(seq, &ts->seq_list, list) {
		if (seq->addr == addr)
			return seq;
	}

	seq = zalloc(sizeof(struct lock_seq_stat));
374 375 376 377
	if (!seq) {
		pr_err("memory allocation failed\n");
		return NULL;
	}
378 379 380 381 382 383 384
	seq->state = SEQ_STATE_UNINITIALIZED;
	seq->addr = addr;

	list_add(&seq->list, &ts->seq_list);
	return seq;
}

385 386 387 388 389 390 391 392 393
enum broken_state {
	BROKEN_ACQUIRE,
	BROKEN_ACQUIRED,
	BROKEN_CONTENDED,
	BROKEN_RELEASE,
	BROKEN_MAX,
};

static int bad_hist[BROKEN_MAX];
394

395 396 397 398 399
enum acquire_flags {
	TRY_LOCK = 1,
	READ_LOCK = 2,
};

400
static int report_lock_acquire_event(struct evsel *evsel,
401
				     struct perf_sample *sample)
402
{
403
	void *addr;
404 405 406
	struct lock_stat *ls;
	struct thread_stat *ts;
	struct lock_seq_stat *seq;
407 408 409
	const char *name = evsel__strval(evsel, sample, "name");
	u64 tmp	 = evsel__intval(evsel, sample, "lockdep_addr");
	int flag = evsel__intval(evsel, sample, "flag");
410

411 412 413
	memcpy(&addr, &tmp, sizeof(void *));

	ls = lock_stat_findnew(addr, name);
414
	if (!ls)
415
		return -ENOMEM;
416
	if (ls->discard)
417
		return 0;
418

419
	ts = thread_stat_findnew(sample->tid);
420
	if (!ts)
421
		return -ENOMEM;
422

423
	seq = get_seq(ts, addr);
424
	if (!seq)
425
		return -ENOMEM;
426

427 428 429
	switch (seq->state) {
	case SEQ_STATE_UNINITIALIZED:
	case SEQ_STATE_RELEASED:
430
		if (!flag) {
431 432
			seq->state = SEQ_STATE_ACQUIRING;
		} else {
433
			if (flag & TRY_LOCK)
434
				ls->nr_trylock++;
435
			if (flag & READ_LOCK)
436 437 438 439 440 441 442
				ls->nr_readlock++;
			seq->state = SEQ_STATE_READ_ACQUIRED;
			seq->read_count = 1;
			ls->nr_acquired++;
		}
		break;
	case SEQ_STATE_READ_ACQUIRED:
443
		if (flag & READ_LOCK) {
444 445 446 447 448 449
			seq->read_count++;
			ls->nr_acquired++;
			goto end;
		} else {
			goto broken;
		}
450
		break;
451 452 453 454 455 456
	case SEQ_STATE_ACQUIRED:
	case SEQ_STATE_ACQUIRING:
	case SEQ_STATE_CONTENDED:
broken:
		/* broken lock sequence, discard it */
		ls->discard = 1;
457
		bad_hist[BROKEN_ACQUIRE]++;
458
		list_del_init(&seq->list);
459 460
		free(seq);
		goto end;
461
	default:
462
		BUG_ON("Unknown state of lock sequence found!\n");
463 464 465
		break;
	}

466
	ls->nr_acquire++;
467
	seq->prev_event_time = sample->time;
468
end:
469
	return 0;
470 471
}

472
static int report_lock_acquired_event(struct evsel *evsel,
473
				      struct perf_sample *sample)
474
{
475
	void *addr;
476 477 478 479
	struct lock_stat *ls;
	struct thread_stat *ts;
	struct lock_seq_stat *seq;
	u64 contended_term;
480 481
	const char *name = evsel__strval(evsel, sample, "name");
	u64 tmp = evsel__intval(evsel, sample, "lockdep_addr");
482 483

	memcpy(&addr, &tmp, sizeof(void *));
484

485
	ls = lock_stat_findnew(addr, name);
486
	if (!ls)
487
		return -ENOMEM;
488
	if (ls->discard)
489
		return 0;
490

491
	ts = thread_stat_findnew(sample->tid);
492
	if (!ts)
493
		return -ENOMEM;
494

495
	seq = get_seq(ts, addr);
496
	if (!seq)
497
		return -ENOMEM;
498

499 500 501
	switch (seq->state) {
	case SEQ_STATE_UNINITIALIZED:
		/* orphan event, do nothing */
502
		return 0;
503
	case SEQ_STATE_ACQUIRING:
504
		break;
505
	case SEQ_STATE_CONTENDED:
506
		contended_term = sample->time - seq->prev_event_time;
507 508 509
		ls->wait_time_total += contended_term;
		if (contended_term < ls->wait_time_min)
			ls->wait_time_min = contended_term;
510
		if (ls->wait_time_max < contended_term)
511
			ls->wait_time_max = contended_term;
512
		break;
513 514 515 516 517
	case SEQ_STATE_RELEASED:
	case SEQ_STATE_ACQUIRED:
	case SEQ_STATE_READ_ACQUIRED:
		/* broken lock sequence, discard it */
		ls->discard = 1;
518
		bad_hist[BROKEN_ACQUIRED]++;
519
		list_del_init(&seq->list);
520 521
		free(seq);
		goto end;
522
	default:
523
		BUG_ON("Unknown state of lock sequence found!\n");
524 525 526
		break;
	}

527 528
	seq->state = SEQ_STATE_ACQUIRED;
	ls->nr_acquired++;
529
	ls->avg_wait_time = ls->nr_contended ? ls->wait_time_total/ls->nr_contended : 0;
530
	seq->prev_event_time = sample->time;
531
end:
532
	return 0;
533 534
}

535
static int report_lock_contended_event(struct evsel *evsel,
536
				       struct perf_sample *sample)
537
{
538
	void *addr;
539 540 541
	struct lock_stat *ls;
	struct thread_stat *ts;
	struct lock_seq_stat *seq;
542 543
	const char *name = evsel__strval(evsel, sample, "name");
	u64 tmp = evsel__intval(evsel, sample, "lockdep_addr");
544 545

	memcpy(&addr, &tmp, sizeof(void *));
546

547
	ls = lock_stat_findnew(addr, name);
548
	if (!ls)
549
		return -ENOMEM;
550
	if (ls->discard)
551
		return 0;
552

553
	ts = thread_stat_findnew(sample->tid);
554
	if (!ts)
555
		return -ENOMEM;
556

557
	seq = get_seq(ts, addr);
558
	if (!seq)
559
		return -ENOMEM;
560

561 562 563
	switch (seq->state) {
	case SEQ_STATE_UNINITIALIZED:
		/* orphan event, do nothing */
564
		return 0;
565
	case SEQ_STATE_ACQUIRING:
566
		break;
567 568 569 570 571 572
	case SEQ_STATE_RELEASED:
	case SEQ_STATE_ACQUIRED:
	case SEQ_STATE_READ_ACQUIRED:
	case SEQ_STATE_CONTENDED:
		/* broken lock sequence, discard it */
		ls->discard = 1;
573
		bad_hist[BROKEN_CONTENDED]++;
574
		list_del_init(&seq->list);
575 576
		free(seq);
		goto end;
577
	default:
578
		BUG_ON("Unknown state of lock sequence found!\n");
579 580 581
		break;
	}

582 583
	seq->state = SEQ_STATE_CONTENDED;
	ls->nr_contended++;
584
	ls->avg_wait_time = ls->wait_time_total/ls->nr_contended;
585
	seq->prev_event_time = sample->time;
586
end:
587
	return 0;
588 589
}

590
static int report_lock_release_event(struct evsel *evsel,
591
				     struct perf_sample *sample)
592
{
593
	void *addr;
594 595 596
	struct lock_stat *ls;
	struct thread_stat *ts;
	struct lock_seq_stat *seq;
597 598
	const char *name = evsel__strval(evsel, sample, "name");
	u64 tmp = evsel__intval(evsel, sample, "lockdep_addr");
599

600 601 602
	memcpy(&addr, &tmp, sizeof(void *));

	ls = lock_stat_findnew(addr, name);
603
	if (!ls)
604
		return -ENOMEM;
605
	if (ls->discard)
606
		return 0;
607

608
	ts = thread_stat_findnew(sample->tid);
609
	if (!ts)
610
		return -ENOMEM;
611

612
	seq = get_seq(ts, addr);
613
	if (!seq)
614
		return -ENOMEM;
615

616 617 618 619 620 621 622 623 624 625
	switch (seq->state) {
	case SEQ_STATE_UNINITIALIZED:
		goto end;
	case SEQ_STATE_ACQUIRED:
		break;
	case SEQ_STATE_READ_ACQUIRED:
		seq->read_count--;
		BUG_ON(seq->read_count < 0);
		if (!seq->read_count) {
			ls->nr_release++;
626 627
			goto end;
		}
628 629 630 631 632 633
		break;
	case SEQ_STATE_ACQUIRING:
	case SEQ_STATE_CONTENDED:
	case SEQ_STATE_RELEASED:
		/* broken lock sequence, discard it */
		ls->discard = 1;
634
		bad_hist[BROKEN_RELEASE]++;
635
		goto free_seq;
636
	default:
637
		BUG_ON("Unknown state of lock sequence found!\n");
638 639 640
		break;
	}

641 642
	ls->nr_release++;
free_seq:
643
	list_del_init(&seq->list);
644
	free(seq);
645
end:
646
	return 0;
647 648 649 650
}

/* lock oriented handlers */
/* TODO: handlers for CPU oriented, thread oriented */
651 652 653 654 655
static struct trace_lock_handler report_lock_ops  = {
	.acquire_event		= report_lock_acquire_event,
	.acquired_event		= report_lock_acquired_event,
	.contended_event	= report_lock_contended_event,
	.release_event		= report_lock_release_event,
656 657 658 659
};

static struct trace_lock_handler *trace_handler;

660
static int evsel__process_lock_acquire(struct evsel *evsel, struct perf_sample *sample)
661
{
662
	if (trace_handler->acquire_event)
663 664
		return trace_handler->acquire_event(evsel, sample);
	return 0;
665 666
}

667
static int evsel__process_lock_acquired(struct evsel *evsel, struct perf_sample *sample)
668
{
669
	if (trace_handler->acquired_event)
670 671
		return trace_handler->acquired_event(evsel, sample);
	return 0;
672 673
}

674
static int evsel__process_lock_contended(struct evsel *evsel, struct perf_sample *sample)
675
{
676
	if (trace_handler->contended_event)
677 678
		return trace_handler->contended_event(evsel, sample);
	return 0;
679 680
}

681
static int evsel__process_lock_release(struct evsel *evsel, struct perf_sample *sample)
682
{
683
	if (trace_handler->release_event)
684 685
		return trace_handler->release_event(evsel, sample);
	return 0;
686 687
}

688 689 690 691 692 693 694 695
static void print_bad_events(int bad, int total)
{
	/* Output for debug, this have to be removed */
	int i;
	const char *name[4] =
		{ "acquire", "acquired", "contended", "release" };

	pr_info("\n=== output for debug===\n\n");
696
	pr_info("bad: %d, total: %d\n", bad, total);
697
	pr_info("bad rate: %.2f %%\n", (double)bad / (double)total * 100);
698 699 700 701 702
	pr_info("histogram of events caused bad sequence\n");
	for (i = 0; i < BROKEN_MAX; i++)
		pr_info(" %10s: %d\n", name[i], bad_hist[i]);
}

703 704 705 706 707
/* TODO: various way to print, coloring, nano or milli sec */
static void print_result(void)
{
	struct lock_stat *st;
	char cut_name[20];
708
	int bad, total;
709

710 711 712
	pr_info("%20s ", "Name");
	pr_info("%10s ", "acquired");
	pr_info("%10s ", "contended");
713

714
	pr_info("%15s ", "avg wait (ns)");
715 716 717
	pr_info("%15s ", "total wait (ns)");
	pr_info("%15s ", "max wait (ns)");
	pr_info("%15s ", "min wait (ns)");
718

719
	pr_info("\n\n");
720

721
	bad = total = 0;
722
	while ((st = pop_from_result())) {
723 724 725 726 727
		total++;
		if (st->discard) {
			bad++;
			continue;
		}
728 729 730 731
		bzero(cut_name, 20);

		if (strlen(st->name) < 16) {
			/* output raw name */
732
			pr_info("%20s ", st->name);
733 734 735 736 737 738 739
		} else {
			strncpy(cut_name, st->name, 16);
			cut_name[16] = '.';
			cut_name[17] = '.';
			cut_name[18] = '.';
			cut_name[19] = '\0';
			/* cut off name for saving output style */
740
			pr_info("%20s ", cut_name);
741 742
		}

743 744
		pr_info("%10u ", st->nr_acquired);
		pr_info("%10u ", st->nr_contended);
745

746
		pr_info("%15" PRIu64 " ", st->avg_wait_time);
747 748 749
		pr_info("%15" PRIu64 " ", st->wait_time_total);
		pr_info("%15" PRIu64 " ", st->wait_time_max);
		pr_info("%15" PRIu64 " ", st->wait_time_min == ULLONG_MAX ?
750
		       0 : st->wait_time_min);
751
		pr_info("\n");
752
	}
753

754
	print_bad_events(bad, total);
755 756
}

757
static bool info_threads, info_map;
758 759 760 761 762 763 764 765 766 767 768 769 770

static void dump_threads(void)
{
	struct thread_stat *st;
	struct rb_node *node;
	struct thread *t;

	pr_info("%10s: comm\n", "Thread ID");

	node = rb_first(&thread_stats);
	while (node) {
		st = container_of(node, struct thread_stat, rb);
		t = perf_session__findnew(session, st->tid);
771
		pr_info("%10d: %s\n", st->tid, thread__comm_str(t));
772
		node = rb_next(node);
773
		thread__put(t);
Z
Zou Wei 已提交
774
	}
775 776
}

777 778 779 780 781
static void dump_map(void)
{
	unsigned int i;
	struct lock_stat *st;

782
	pr_info("Address of instance: name of class\n");
783 784
	for (i = 0; i < LOCKHASH_SIZE; i++) {
		list_for_each_entry(st, &lockhash_table[i], hash_entry) {
785
			pr_info(" %p: %s\n", st->addr, st->name);
786 787 788 789
		}
	}
}

790
static int dump_info(void)
791
{
792 793
	int rc = 0;

794 795 796 797
	if (info_threads)
		dump_threads();
	else if (info_map)
		dump_map();
798 799 800 801 802 803
	else {
		rc = -1;
		pr_err("Unknown type of information\n");
	}

	return rc;
804 805
}

806
typedef int (*tracepoint_handler)(struct evsel *evsel,
807 808
				  struct perf_sample *sample);

809
static int process_sample_event(struct perf_tool *tool __maybe_unused,
810
				union perf_event *event,
811
				struct perf_sample *sample,
812
				struct evsel *evsel,
813
				struct machine *machine)
814
{
815
	int err = 0;
816 817
	struct thread *thread = machine__findnew_thread(machine, sample->pid,
							sample->tid);
818 819 820

	if (thread == NULL) {
		pr_debug("problem processing %d event, skipping it.\n",
821
			event->header.type);
822 823 824
		return -1;
	}

825 826
	if (evsel->handler != NULL) {
		tracepoint_handler f = evsel->handler;
827
		err = f(evsel, sample);
828 829
	}

830 831 832
	thread__put(thread);

	return err;
833 834
}

D
Davidlohr Bueso 已提交
835 836 837 838 839 840 841 842 843 844 845 846
static void sort_result(void)
{
	unsigned int i;
	struct lock_stat *st;

	for (i = 0; i < LOCKHASH_SIZE; i++) {
		list_for_each_entry(st, &lockhash_table[i], hash_entry) {
			insert_to_result(st, compare);
		}
	}
}

847
static const struct evsel_str_handler lock_tracepoints[] = {
848 849 850 851
	{ "lock:lock_acquire",	 evsel__process_lock_acquire,   }, /* CONFIG_LOCKDEP */
	{ "lock:lock_acquired",	 evsel__process_lock_acquired,  }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
	{ "lock:lock_contended", evsel__process_lock_contended, }, /* CONFIG_LOCKDEP, CONFIG_LOCK_STAT */
	{ "lock:lock_release",	 evsel__process_lock_release,   }, /* CONFIG_LOCKDEP */
852 853
};

854 855
static bool force;

D
Davidlohr Bueso 已提交
856
static int __cmd_report(bool display_info)
857
{
D
Davidlohr Bueso 已提交
858
	int err = -EINVAL;
859 860 861
	struct perf_tool eops = {
		.sample		 = process_sample_event,
		.comm		 = perf_event__process_comm,
862
		.namespaces	 = perf_event__process_namespaces,
863
		.ordered_events	 = true,
864
	};
865
	struct perf_data data = {
J
Jiri Olsa 已提交
866 867 868
		.path  = input_name,
		.mode  = PERF_DATA_MODE_READ,
		.force = force,
869
	};
D
Davidlohr Bueso 已提交
870

871
	session = perf_session__new(&data, false, &eops);
872
	if (IS_ERR(session)) {
873
		pr_err("Initializing perf session failed\n");
874
		return PTR_ERR(session);
875
	}
876

877
	symbol__init(&session->header.env);
878

D
Davidlohr Bueso 已提交
879 880 881
	if (!perf_session__has_traces(session, "lock record"))
		goto out_delete;

882 883
	if (perf_session__set_tracepoints_handlers(session, lock_tracepoints)) {
		pr_err("Initializing perf session tracepoint handlers failed\n");
D
Davidlohr Bueso 已提交
884
		goto out_delete;
885 886
	}

D
Davidlohr Bueso 已提交
887 888
	if (select_key())
		goto out_delete;
889

890
	err = perf_session__process_events(session);
D
Davidlohr Bueso 已提交
891 892
	if (err)
		goto out_delete;
893 894

	setup_pager();
D
Davidlohr Bueso 已提交
895 896 897 898 899 900
	if (display_info) /* used for info subcommand */
		err = dump_info();
	else {
		sort_result();
		print_result();
	}
901

D
Davidlohr Bueso 已提交
902 903 904
out_delete:
	perf_session__delete(session);
	return err;
905 906 907 908
}

static int __cmd_record(int argc, const char **argv)
{
909
	const char *record_args[] = {
910
		"record", "-R", "-m", "1024", "-c", "1",
911
	};
D
Davidlohr Bueso 已提交
912
	unsigned int rec_argc, i, j, ret;
913 914
	const char **rec_argv;

915
	for (i = 0; i < ARRAY_SIZE(lock_tracepoints); i++) {
916
		if (!is_valid_tracepoint(lock_tracepoints[i].name)) {
917 918
				pr_err("tracepoint %s is not enabled. "
				       "Are CONFIG_LOCKDEP and CONFIG_LOCK_STAT enabled?\n",
919
				       lock_tracepoints[i].name);
920 921 922 923
				return 1;
		}
	}

924
	rec_argc = ARRAY_SIZE(record_args) + argc - 1;
925 926
	/* factor of 2 is for -e in front of each tracepoint */
	rec_argc += 2 * ARRAY_SIZE(lock_tracepoints);
927

928
	rec_argv = calloc(rec_argc + 1, sizeof(char *));
D
Davidlohr Bueso 已提交
929
	if (!rec_argv)
930 931
		return -ENOMEM;

932 933 934
	for (i = 0; i < ARRAY_SIZE(record_args); i++)
		rec_argv[i] = strdup(record_args[i]);

935 936
	for (j = 0; j < ARRAY_SIZE(lock_tracepoints); j++) {
		rec_argv[i++] = "-e";
937
		rec_argv[i++] = strdup(lock_tracepoints[j].name);
938 939
	}

940 941 942 943 944
	for (j = 1; j < (unsigned int)argc; j++, i++)
		rec_argv[i] = argv[j];

	BUG_ON(i != rec_argc);

945
	ret = cmd_record(i, rec_argv);
D
Davidlohr Bueso 已提交
946 947
	free(rec_argv);
	return ret;
948 949
}

950
int cmd_lock(int argc, const char **argv)
951
{
952 953 954 955
	const struct option lock_options[] = {
	OPT_STRING('i', "input", &input_name, "file", "input file name"),
	OPT_INCR('v', "verbose", &verbose, "be more verbose (show symbol address, etc)"),
	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace, "dump raw trace in ASCII"),
956
	OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
957 958 959
	OPT_END()
	};

960 961 962 963 964
	const struct option info_options[] = {
	OPT_BOOLEAN('t', "threads", &info_threads,
		    "dump thread list in perf.data"),
	OPT_BOOLEAN('m', "map", &info_map,
		    "map of lock instances (address:name table)"),
965
	OPT_PARENT(lock_options)
966
	};
967

968 969
	const struct option report_options[] = {
	OPT_STRING('k', "key", &sort_key, "acquired",
970
		    "key for sorting (acquired / contended / avg_wait / wait_total / wait_max / wait_min)"),
971
	/* TODO: type */
972
	OPT_PARENT(lock_options)
973
	};
974

975 976 977 978
	const char * const info_usage[] = {
		"perf lock info [<options>]",
		NULL
	};
979 980 981 982
	const char *const lock_subcommands[] = { "record", "report", "script",
						 "info", NULL };
	const char *lock_usage[] = {
		NULL,
983 984 985 986 987 988
		NULL
	};
	const char * const report_usage[] = {
		"perf lock report [<options>]",
		NULL
	};
989
	unsigned int i;
990
	int rc = 0;
991 992 993 994

	for (i = 0; i < LOCKHASH_SIZE; i++)
		INIT_LIST_HEAD(lockhash_table + i);

995 996
	argc = parse_options_subcommand(argc, argv, lock_options, lock_subcommands,
					lock_usage, PARSE_OPT_STOP_AT_NON_OPTION);
997 998 999 1000 1001
	if (!argc)
		usage_with_options(lock_usage, lock_options);

	if (!strncmp(argv[0], "rec", 3)) {
		return __cmd_record(argc, argv);
1002 1003
	} else if (!strncmp(argv[0], "report", 6)) {
		trace_handler = &report_lock_ops;
1004 1005
		if (argc) {
			argc = parse_options(argc, argv,
1006
					     report_options, report_usage, 0);
1007
			if (argc)
1008
				usage_with_options(report_usage, report_options);
1009
		}
D
Davidlohr Bueso 已提交
1010
		rc = __cmd_report(false);
1011 1012
	} else if (!strcmp(argv[0], "script")) {
		/* Aliased to 'perf script' */
1013
		return cmd_script(argc, argv);
1014 1015 1016 1017 1018 1019 1020
	} else if (!strcmp(argv[0], "info")) {
		if (argc) {
			argc = parse_options(argc, argv,
					     info_options, info_usage, 0);
			if (argc)
				usage_with_options(info_usage, info_options);
		}
1021 1022
		/* recycling report_lock_ops */
		trace_handler = &report_lock_ops;
D
Davidlohr Bueso 已提交
1023
		rc = __cmd_report(true);
1024 1025 1026 1027
	} else {
		usage_with_options(lock_usage, lock_options);
	}

1028
	return rc;
1029
}