builtin-sched.c 45.0 KB
Newer Older
I
Ingo Molnar 已提交
1
#include "builtin.h"
2
#include "perf.h"
I
Ingo Molnar 已提交
3 4

#include "util/util.h"
5
#include "util/evlist.h"
I
Ingo Molnar 已提交
6
#include "util/cache.h"
7
#include "util/evsel.h"
I
Ingo Molnar 已提交
8 9 10
#include "util/symbol.h"
#include "util/thread.h"
#include "util/header.h"
11
#include "util/session.h"
12
#include "util/tool.h"
13
#include "util/cloexec.h"
I
Ingo Molnar 已提交
14 15

#include "util/parse-options.h"
16
#include "util/trace-event.h"
I
Ingo Molnar 已提交
17 18 19

#include "util/debug.h"

20
#include <sys/prctl.h>
21
#include <sys/resource.h>
I
Ingo Molnar 已提交
22

23 24 25
#include <semaphore.h>
#include <pthread.h>
#include <math.h>
26
#include <api/fs/fs.h>
27

28 29 30 31
#define PR_SET_NAME		15               /* Set process name */
#define MAX_CPUS		4096
#define COMM_LEN		20
#define SYM_LEN			129
32
#define MAX_PID			1024000
I
Ingo Molnar 已提交
33

34
struct sched_atom;
I
Ingo Molnar 已提交
35

36 37 38 39
struct task_desc {
	unsigned long		nr;
	unsigned long		pid;
	char			comm[COMM_LEN];
I
Ingo Molnar 已提交
40

41 42
	unsigned long		nr_events;
	unsigned long		curr_event;
43
	struct sched_atom	**atoms;
44 45 46

	pthread_t		thread;
	sem_t			sleep_sem;
I
Ingo Molnar 已提交
47

48 49 50 51 52 53 54 55 56 57
	sem_t			ready_for_work;
	sem_t			work_done_sem;

	u64			cpu_usage;
};

enum sched_event_type {
	SCHED_EVENT_RUN,
	SCHED_EVENT_SLEEP,
	SCHED_EVENT_WAKEUP,
58
	SCHED_EVENT_MIGRATION,
59 60
};

61
struct sched_atom {
62
	enum sched_event_type	type;
63
	int			specific_wait;
64 65 66 67 68 69 70
	u64			timestamp;
	u64			duration;
	unsigned long		nr;
	sem_t			*wait_sem;
	struct task_desc	*wakee;
};

71
#define TASK_STATE_TO_CHAR_STR "RSDTtZXxKWP"
72 73 74 75 76 77 78 79 80 81 82

enum thread_state {
	THREAD_SLEEPING = 0,
	THREAD_WAIT_CPU,
	THREAD_SCHED_IN,
	THREAD_IGNORE
};

struct work_atom {
	struct list_head	list;
	enum thread_state	state;
83
	u64			sched_out_time;
84 85 86 87 88
	u64			wake_up_time;
	u64			sched_in_time;
	u64			runtime;
};

89 90
struct work_atoms {
	struct list_head	work_list;
91 92 93
	struct thread		*thread;
	struct rb_node		node;
	u64			max_lat;
94
	u64			max_lat_at;
95 96 97 98 99
	u64			total_lat;
	u64			nb_atoms;
	u64			total_runtime;
};

100
typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
101

102
struct perf_sched;
103

104 105 106
struct trace_sched_handler {
	int (*switch_event)(struct perf_sched *sched, struct perf_evsel *evsel,
			    struct perf_sample *sample, struct machine *machine);
107

108 109
	int (*runtime_event)(struct perf_sched *sched, struct perf_evsel *evsel,
			     struct perf_sample *sample, struct machine *machine);
110

111 112
	int (*wakeup_event)(struct perf_sched *sched, struct perf_evsel *evsel,
			    struct perf_sample *sample, struct machine *machine);
113

114 115 116
	/* PERF_RECORD_FORK event, not sched_process_fork tracepoint */
	int (*fork_event)(struct perf_sched *sched, union perf_event *event,
			  struct machine *machine);
117 118

	int (*migrate_task_event)(struct perf_sched *sched,
119 120 121
				  struct perf_evsel *evsel,
				  struct perf_sample *sample,
				  struct machine *machine);
122 123 124 125 126 127
};

struct perf_sched {
	struct perf_tool tool;
	const char	 *sort_order;
	unsigned long	 nr_tasks;
128
	struct task_desc **pid_to_task;
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 task_desc **tasks;
	const struct trace_sched_handler *tp_handler;
	pthread_mutex_t	 start_work_mutex;
	pthread_mutex_t	 work_done_wait_mutex;
	int		 profile_cpu;
/*
 * Track the current task - that way we can know whether there's any
 * weird events, such as a task being switched away that is not current.
 */
	int		 max_cpu;
	u32		 curr_pid[MAX_CPUS];
	struct thread	 *curr_thread[MAX_CPUS];
	char		 next_shortname1;
	char		 next_shortname2;
	unsigned int	 replay_repeat;
	unsigned long	 nr_run_events;
	unsigned long	 nr_sleep_events;
	unsigned long	 nr_wakeup_events;
	unsigned long	 nr_sleep_corrections;
	unsigned long	 nr_run_events_optimized;
	unsigned long	 targetless_wakeups;
	unsigned long	 multitarget_wakeups;
	unsigned long	 nr_runs;
	unsigned long	 nr_timestamps;
	unsigned long	 nr_unordered_timestamps;
	unsigned long	 nr_context_switch_bugs;
	unsigned long	 nr_events;
	unsigned long	 nr_lost_chunks;
	unsigned long	 nr_lost_events;
	u64		 run_measurement_overhead;
	u64		 sleep_measurement_overhead;
	u64		 start_time;
	u64		 cpu_usage;
	u64		 runavg_cpu_usage;
	u64		 parent_cpu_usage;
	u64		 runavg_parent_cpu_usage;
	u64		 sum_runtime;
	u64		 sum_fluct;
	u64		 run_avg;
	u64		 all_runtime;
	u64		 all_count;
	u64		 cpu_last_switched[MAX_CPUS];
	struct rb_root	 atom_root, sorted_atom_root;
	struct list_head sort_list, cmp_pid;
173
	bool force;
174
};
175 176

static u64 get_nsecs(void)
I
Ingo Molnar 已提交
177 178 179 180 181 182 183 184
{
	struct timespec ts;

	clock_gettime(CLOCK_MONOTONIC, &ts);

	return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
}

185
static void burn_nsecs(struct perf_sched *sched, u64 nsecs)
I
Ingo Molnar 已提交
186
{
187
	u64 T0 = get_nsecs(), T1;
I
Ingo Molnar 已提交
188 189 190

	do {
		T1 = get_nsecs();
191
	} while (T1 + sched->run_measurement_overhead < T0 + nsecs);
I
Ingo Molnar 已提交
192 193
}

194
static void sleep_nsecs(u64 nsecs)
I
Ingo Molnar 已提交
195 196 197 198 199 200 201 202 203
{
	struct timespec ts;

	ts.tv_nsec = nsecs % 999999999;
	ts.tv_sec = nsecs / 999999999;

	nanosleep(&ts, NULL);
}

204
static void calibrate_run_measurement_overhead(struct perf_sched *sched)
I
Ingo Molnar 已提交
205
{
206
	u64 T0, T1, delta, min_delta = 1000000000ULL;
I
Ingo Molnar 已提交
207 208 209 210
	int i;

	for (i = 0; i < 10; i++) {
		T0 = get_nsecs();
211
		burn_nsecs(sched, 0);
I
Ingo Molnar 已提交
212 213 214 215
		T1 = get_nsecs();
		delta = T1-T0;
		min_delta = min(min_delta, delta);
	}
216
	sched->run_measurement_overhead = min_delta;
I
Ingo Molnar 已提交
217

218
	printf("run measurement overhead: %" PRIu64 " nsecs\n", min_delta);
I
Ingo Molnar 已提交
219 220
}

221
static void calibrate_sleep_measurement_overhead(struct perf_sched *sched)
I
Ingo Molnar 已提交
222
{
223
	u64 T0, T1, delta, min_delta = 1000000000ULL;
I
Ingo Molnar 已提交
224 225 226 227 228 229 230 231 232 233
	int i;

	for (i = 0; i < 10; i++) {
		T0 = get_nsecs();
		sleep_nsecs(10000);
		T1 = get_nsecs();
		delta = T1-T0;
		min_delta = min(min_delta, delta);
	}
	min_delta -= 10000;
234
	sched->sleep_measurement_overhead = min_delta;
I
Ingo Molnar 已提交
235

236
	printf("sleep measurement overhead: %" PRIu64 " nsecs\n", min_delta);
I
Ingo Molnar 已提交
237 238
}

239
static struct sched_atom *
240
get_new_event(struct task_desc *task, u64 timestamp)
I
Ingo Molnar 已提交
241
{
242
	struct sched_atom *event = zalloc(sizeof(*event));
I
Ingo Molnar 已提交
243 244 245 246 247 248 249
	unsigned long idx = task->nr_events;
	size_t size;

	event->timestamp = timestamp;
	event->nr = idx;

	task->nr_events++;
250 251 252
	size = sizeof(struct sched_atom *) * task->nr_events;
	task->atoms = realloc(task->atoms, size);
	BUG_ON(!task->atoms);
I
Ingo Molnar 已提交
253

254
	task->atoms[idx] = event;
I
Ingo Molnar 已提交
255 256 257 258

	return event;
}

259
static struct sched_atom *last_event(struct task_desc *task)
I
Ingo Molnar 已提交
260 261 262 263
{
	if (!task->nr_events)
		return NULL;

264
	return task->atoms[task->nr_events - 1];
I
Ingo Molnar 已提交
265 266
}

267 268
static void add_sched_event_run(struct perf_sched *sched, struct task_desc *task,
				u64 timestamp, u64 duration)
I
Ingo Molnar 已提交
269
{
270
	struct sched_atom *event, *curr_event = last_event(task);
I
Ingo Molnar 已提交
271 272

	/*
273 274 275
	 * optimize an existing RUN event by merging this one
	 * to it:
	 */
I
Ingo Molnar 已提交
276
	if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
277
		sched->nr_run_events_optimized++;
I
Ingo Molnar 已提交
278 279 280 281 282 283 284 285 286
		curr_event->duration += duration;
		return;
	}

	event = get_new_event(task, timestamp);

	event->type = SCHED_EVENT_RUN;
	event->duration = duration;

287
	sched->nr_run_events++;
I
Ingo Molnar 已提交
288 289
}

290 291
static void add_sched_event_wakeup(struct perf_sched *sched, struct task_desc *task,
				   u64 timestamp, struct task_desc *wakee)
I
Ingo Molnar 已提交
292
{
293
	struct sched_atom *event, *wakee_event;
I
Ingo Molnar 已提交
294 295 296 297 298 299 300

	event = get_new_event(task, timestamp);
	event->type = SCHED_EVENT_WAKEUP;
	event->wakee = wakee;

	wakee_event = last_event(wakee);
	if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
301
		sched->targetless_wakeups++;
I
Ingo Molnar 已提交
302 303 304
		return;
	}
	if (wakee_event->wait_sem) {
305
		sched->multitarget_wakeups++;
I
Ingo Molnar 已提交
306 307 308
		return;
	}

309
	wakee_event->wait_sem = zalloc(sizeof(*wakee_event->wait_sem));
I
Ingo Molnar 已提交
310 311 312 313
	sem_init(wakee_event->wait_sem, 0, 0);
	wakee_event->specific_wait = 1;
	event->wait_sem = wakee_event->wait_sem;

314
	sched->nr_wakeup_events++;
I
Ingo Molnar 已提交
315 316
}

317 318
static void add_sched_event_sleep(struct perf_sched *sched, struct task_desc *task,
				  u64 timestamp, u64 task_state __maybe_unused)
I
Ingo Molnar 已提交
319
{
320
	struct sched_atom *event = get_new_event(task, timestamp);
I
Ingo Molnar 已提交
321 322 323

	event->type = SCHED_EVENT_SLEEP;

324
	sched->nr_sleep_events++;
I
Ingo Molnar 已提交
325 326
}

327 328
static struct task_desc *register_pid(struct perf_sched *sched,
				      unsigned long pid, const char *comm)
I
Ingo Molnar 已提交
329 330
{
	struct task_desc *task;
331
	static int pid_max;
I
Ingo Molnar 已提交
332

333 334 335 336 337
	if (sched->pid_to_task == NULL) {
		if (sysctl__read_int("kernel/pid_max", &pid_max) < 0)
			pid_max = MAX_PID;
		BUG_ON((sched->pid_to_task = calloc(pid_max, sizeof(struct task_desc *))) == NULL);
	}
338 339 340 341 342 343
	if (pid >= (unsigned long)pid_max) {
		BUG_ON((sched->pid_to_task = realloc(sched->pid_to_task, (pid + 1) *
			sizeof(struct task_desc *))) == NULL);
		while (pid >= (unsigned long)pid_max)
			sched->pid_to_task[pid_max++] = NULL;
	}
I
Ingo Molnar 已提交
344

345
	task = sched->pid_to_task[pid];
I
Ingo Molnar 已提交
346 347 348 349

	if (task)
		return task;

350
	task = zalloc(sizeof(*task));
I
Ingo Molnar 已提交
351
	task->pid = pid;
352
	task->nr = sched->nr_tasks;
I
Ingo Molnar 已提交
353 354 355 356 357
	strcpy(task->comm, comm);
	/*
	 * every task starts in sleeping state - this gets ignored
	 * if there's no wakeup pointing to this sleep state:
	 */
358
	add_sched_event_sleep(sched, task, 0, 0);
I
Ingo Molnar 已提交
359

360 361
	sched->pid_to_task[pid] = task;
	sched->nr_tasks++;
362
	sched->tasks = realloc(sched->tasks, sched->nr_tasks * sizeof(struct task_desc *));
363 364
	BUG_ON(!sched->tasks);
	sched->tasks[task->nr] = task;
I
Ingo Molnar 已提交
365

I
Ingo Molnar 已提交
366
	if (verbose)
367
		printf("registered task #%ld, PID %ld (%s)\n", sched->nr_tasks, pid, comm);
I
Ingo Molnar 已提交
368 369 370 371 372

	return task;
}


373
static void print_task_traces(struct perf_sched *sched)
I
Ingo Molnar 已提交
374 375 376 377
{
	struct task_desc *task;
	unsigned long i;

378 379
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
380
		printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
I
Ingo Molnar 已提交
381 382 383 384
			task->nr, task->comm, task->pid, task->nr_events);
	}
}

385
static void add_cross_task_wakeups(struct perf_sched *sched)
I
Ingo Molnar 已提交
386 387 388 389
{
	struct task_desc *task1, *task2;
	unsigned long i, j;

390 391
	for (i = 0; i < sched->nr_tasks; i++) {
		task1 = sched->tasks[i];
I
Ingo Molnar 已提交
392
		j = i + 1;
393
		if (j == sched->nr_tasks)
I
Ingo Molnar 已提交
394
			j = 0;
395 396
		task2 = sched->tasks[j];
		add_sched_event_wakeup(sched, task1, 0, task2);
I
Ingo Molnar 已提交
397 398 399
	}
}

400 401
static void perf_sched__process_event(struct perf_sched *sched,
				      struct sched_atom *atom)
I
Ingo Molnar 已提交
402 403 404
{
	int ret = 0;

405
	switch (atom->type) {
I
Ingo Molnar 已提交
406
		case SCHED_EVENT_RUN:
407
			burn_nsecs(sched, atom->duration);
I
Ingo Molnar 已提交
408 409
			break;
		case SCHED_EVENT_SLEEP:
410 411
			if (atom->wait_sem)
				ret = sem_wait(atom->wait_sem);
I
Ingo Molnar 已提交
412 413 414
			BUG_ON(ret);
			break;
		case SCHED_EVENT_WAKEUP:
415 416
			if (atom->wait_sem)
				ret = sem_post(atom->wait_sem);
I
Ingo Molnar 已提交
417 418
			BUG_ON(ret);
			break;
419 420
		case SCHED_EVENT_MIGRATION:
			break;
I
Ingo Molnar 已提交
421 422 423 424 425
		default:
			BUG_ON(1);
	}
}

426
static u64 get_cpu_usage_nsec_parent(void)
I
Ingo Molnar 已提交
427 428
{
	struct rusage ru;
429
	u64 sum;
I
Ingo Molnar 已提交
430 431 432 433 434 435 436 437 438 439 440
	int err;

	err = getrusage(RUSAGE_SELF, &ru);
	BUG_ON(err);

	sum =  ru.ru_utime.tv_sec*1e9 + ru.ru_utime.tv_usec*1e3;
	sum += ru.ru_stime.tv_sec*1e9 + ru.ru_stime.tv_usec*1e3;

	return sum;
}

441
static int self_open_counters(struct perf_sched *sched, unsigned long cur_task)
I
Ingo Molnar 已提交
442
{
443
	struct perf_event_attr attr;
444
	char sbuf[STRERR_BUFSIZE], info[STRERR_BUFSIZE];
445
	int fd;
446 447
	struct rlimit limit;
	bool need_privilege = false;
I
Ingo Molnar 已提交
448

449
	memset(&attr, 0, sizeof(attr));
I
Ingo Molnar 已提交
450

451 452
	attr.type = PERF_TYPE_SOFTWARE;
	attr.config = PERF_COUNT_SW_TASK_CLOCK;
I
Ingo Molnar 已提交
453

454
force_again:
455 456
	fd = sys_perf_event_open(&attr, 0, -1, -1,
				 perf_event_open_cloexec_flag());
457

458
	if (fd < 0) {
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
		if (errno == EMFILE) {
			if (sched->force) {
				BUG_ON(getrlimit(RLIMIT_NOFILE, &limit) == -1);
				limit.rlim_cur += sched->nr_tasks - cur_task;
				if (limit.rlim_cur > limit.rlim_max) {
					limit.rlim_max = limit.rlim_cur;
					need_privilege = true;
				}
				if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
					if (need_privilege && errno == EPERM)
						strcpy(info, "Need privilege\n");
				} else
					goto force_again;
			} else
				strcpy(info, "Have a try with -f option\n");
		}
475
		pr_err("Error: sys_perf_event_open() syscall returned "
476 477
		       "with %d (%s)\n%s", fd,
		       strerror_r(errno, sbuf, sizeof(sbuf)), info);
478 479
		exit(EXIT_FAILURE);
	}
480 481 482 483 484 485 486 487 488 489 490 491
	return fd;
}

static u64 get_cpu_usage_nsec_self(int fd)
{
	u64 runtime;
	int ret;

	ret = read(fd, &runtime, sizeof(runtime));
	BUG_ON(ret != sizeof(runtime));

	return runtime;
I
Ingo Molnar 已提交
492 493
}

494 495 496
struct sched_thread_parms {
	struct task_desc  *task;
	struct perf_sched *sched;
497
	int fd;
498 499
};

I
Ingo Molnar 已提交
500 501
static void *thread_func(void *ctx)
{
502 503 504
	struct sched_thread_parms *parms = ctx;
	struct task_desc *this_task = parms->task;
	struct perf_sched *sched = parms->sched;
505
	u64 cpu_usage_0, cpu_usage_1;
I
Ingo Molnar 已提交
506 507
	unsigned long i, ret;
	char comm2[22];
508
	int fd = parms->fd;
I
Ingo Molnar 已提交
509

510
	zfree(&parms);
511

I
Ingo Molnar 已提交
512 513
	sprintf(comm2, ":%s", this_task->comm);
	prctl(PR_SET_NAME, comm2);
514 515
	if (fd < 0)
		return NULL;
I
Ingo Molnar 已提交
516 517 518
again:
	ret = sem_post(&this_task->ready_for_work);
	BUG_ON(ret);
519
	ret = pthread_mutex_lock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
520
	BUG_ON(ret);
521
	ret = pthread_mutex_unlock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
522 523
	BUG_ON(ret);

524
	cpu_usage_0 = get_cpu_usage_nsec_self(fd);
I
Ingo Molnar 已提交
525 526 527

	for (i = 0; i < this_task->nr_events; i++) {
		this_task->curr_event = i;
528
		perf_sched__process_event(sched, this_task->atoms[i]);
I
Ingo Molnar 已提交
529 530
	}

531
	cpu_usage_1 = get_cpu_usage_nsec_self(fd);
I
Ingo Molnar 已提交
532 533 534 535
	this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
	ret = sem_post(&this_task->work_done_sem);
	BUG_ON(ret);

536
	ret = pthread_mutex_lock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
537
	BUG_ON(ret);
538
	ret = pthread_mutex_unlock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
539 540 541 542 543
	BUG_ON(ret);

	goto again;
}

544
static void create_tasks(struct perf_sched *sched)
I
Ingo Molnar 已提交
545 546 547 548 549 550 551 552
{
	struct task_desc *task;
	pthread_attr_t attr;
	unsigned long i;
	int err;

	err = pthread_attr_init(&attr);
	BUG_ON(err);
553 554
	err = pthread_attr_setstacksize(&attr,
			(size_t) max(16 * 1024, PTHREAD_STACK_MIN));
I
Ingo Molnar 已提交
555
	BUG_ON(err);
556
	err = pthread_mutex_lock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
557
	BUG_ON(err);
558
	err = pthread_mutex_lock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
559
	BUG_ON(err);
560 561 562 563 564
	for (i = 0; i < sched->nr_tasks; i++) {
		struct sched_thread_parms *parms = malloc(sizeof(*parms));
		BUG_ON(parms == NULL);
		parms->task = task = sched->tasks[i];
		parms->sched = sched;
565
		parms->fd = self_open_counters(sched, i);
I
Ingo Molnar 已提交
566 567 568 569
		sem_init(&task->sleep_sem, 0, 0);
		sem_init(&task->ready_for_work, 0, 0);
		sem_init(&task->work_done_sem, 0, 0);
		task->curr_event = 0;
570
		err = pthread_create(&task->thread, &attr, thread_func, parms);
I
Ingo Molnar 已提交
571 572 573 574
		BUG_ON(err);
	}
}

575
static void wait_for_tasks(struct perf_sched *sched)
I
Ingo Molnar 已提交
576
{
577
	u64 cpu_usage_0, cpu_usage_1;
I
Ingo Molnar 已提交
578 579 580
	struct task_desc *task;
	unsigned long i, ret;

581 582 583
	sched->start_time = get_nsecs();
	sched->cpu_usage = 0;
	pthread_mutex_unlock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
584

585 586
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
587 588 589 590
		ret = sem_wait(&task->ready_for_work);
		BUG_ON(ret);
		sem_init(&task->ready_for_work, 0, 0);
	}
591
	ret = pthread_mutex_lock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
592 593 594 595
	BUG_ON(ret);

	cpu_usage_0 = get_cpu_usage_nsec_parent();

596
	pthread_mutex_unlock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
597

598 599
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
600 601 602
		ret = sem_wait(&task->work_done_sem);
		BUG_ON(ret);
		sem_init(&task->work_done_sem, 0, 0);
603
		sched->cpu_usage += task->cpu_usage;
I
Ingo Molnar 已提交
604 605 606 607
		task->cpu_usage = 0;
	}

	cpu_usage_1 = get_cpu_usage_nsec_parent();
608 609 610
	if (!sched->runavg_cpu_usage)
		sched->runavg_cpu_usage = sched->cpu_usage;
	sched->runavg_cpu_usage = (sched->runavg_cpu_usage * 9 + sched->cpu_usage) / 10;
I
Ingo Molnar 已提交
611

612 613 614 615 616
	sched->parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
	if (!sched->runavg_parent_cpu_usage)
		sched->runavg_parent_cpu_usage = sched->parent_cpu_usage;
	sched->runavg_parent_cpu_usage = (sched->runavg_parent_cpu_usage * 9 +
					 sched->parent_cpu_usage)/10;
I
Ingo Molnar 已提交
617

618
	ret = pthread_mutex_lock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
619 620
	BUG_ON(ret);

621 622
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
623 624 625 626 627
		sem_init(&task->sleep_sem, 0, 0);
		task->curr_event = 0;
	}
}

628
static void run_one_test(struct perf_sched *sched)
I
Ingo Molnar 已提交
629
{
K
Kyle McMartin 已提交
630
	u64 T0, T1, delta, avg_delta, fluct;
I
Ingo Molnar 已提交
631 632

	T0 = get_nsecs();
633
	wait_for_tasks(sched);
I
Ingo Molnar 已提交
634 635 636
	T1 = get_nsecs();

	delta = T1 - T0;
637 638
	sched->sum_runtime += delta;
	sched->nr_runs++;
I
Ingo Molnar 已提交
639

640
	avg_delta = sched->sum_runtime / sched->nr_runs;
I
Ingo Molnar 已提交
641 642 643 644
	if (delta < avg_delta)
		fluct = avg_delta - delta;
	else
		fluct = delta - avg_delta;
645 646 647 648
	sched->sum_fluct += fluct;
	if (!sched->run_avg)
		sched->run_avg = delta;
	sched->run_avg = (sched->run_avg * 9 + delta) / 10;
I
Ingo Molnar 已提交
649

650
	printf("#%-3ld: %0.3f, ", sched->nr_runs, (double)delta / 1000000.0);
I
Ingo Molnar 已提交
651

652
	printf("ravg: %0.2f, ", (double)sched->run_avg / 1e6);
I
Ingo Molnar 已提交
653

I
Ingo Molnar 已提交
654
	printf("cpu: %0.2f / %0.2f",
655
		(double)sched->cpu_usage / 1e6, (double)sched->runavg_cpu_usage / 1e6);
I
Ingo Molnar 已提交
656 657 658

#if 0
	/*
659
	 * rusage statistics done by the parent, these are less
660
	 * accurate than the sched->sum_exec_runtime based statistics:
661
	 */
I
Ingo Molnar 已提交
662
	printf(" [%0.2f / %0.2f]",
663 664
		(double)sched->parent_cpu_usage/1e6,
		(double)sched->runavg_parent_cpu_usage/1e6);
I
Ingo Molnar 已提交
665 666
#endif

I
Ingo Molnar 已提交
667
	printf("\n");
I
Ingo Molnar 已提交
668

669 670 671
	if (sched->nr_sleep_corrections)
		printf(" (%ld sleep corrections)\n", sched->nr_sleep_corrections);
	sched->nr_sleep_corrections = 0;
I
Ingo Molnar 已提交
672 673
}

674
static void test_calibrations(struct perf_sched *sched)
I
Ingo Molnar 已提交
675
{
676
	u64 T0, T1;
I
Ingo Molnar 已提交
677 678

	T0 = get_nsecs();
679
	burn_nsecs(sched, 1e6);
I
Ingo Molnar 已提交
680 681
	T1 = get_nsecs();

682
	printf("the run test took %" PRIu64 " nsecs\n", T1 - T0);
I
Ingo Molnar 已提交
683 684 685 686 687

	T0 = get_nsecs();
	sleep_nsecs(1e6);
	T1 = get_nsecs();

688
	printf("the sleep test took %" PRIu64 " nsecs\n", T1 - T0);
I
Ingo Molnar 已提交
689 690
}

691
static int
692
replay_wakeup_event(struct perf_sched *sched,
693 694
		    struct perf_evsel *evsel, struct perf_sample *sample,
		    struct machine *machine __maybe_unused)
695
{
696 697
	const char *comm = perf_evsel__strval(evsel, sample, "comm");
	const u32 pid	 = perf_evsel__intval(evsel, sample, "pid");
698
	struct task_desc *waker, *wakee;
699

I
Ingo Molnar 已提交
700
	if (verbose) {
701
		printf("sched_wakeup event %p\n", evsel);
702

703
		printf(" ... pid %d woke up %s/%d\n", sample->tid, comm, pid);
I
Ingo Molnar 已提交
704
	}
705

706
	waker = register_pid(sched, sample->tid, "<unknown>");
707
	wakee = register_pid(sched, pid, comm);
708

709
	add_sched_event_wakeup(sched, waker, sample->time, wakee);
710
	return 0;
I
Ingo Molnar 已提交
711 712
}

713 714 715 716
static int replay_switch_event(struct perf_sched *sched,
			       struct perf_evsel *evsel,
			       struct perf_sample *sample,
			       struct machine *machine __maybe_unused)
I
Ingo Molnar 已提交
717
{
718 719 720 721 722
	const char *prev_comm  = perf_evsel__strval(evsel, sample, "prev_comm"),
		   *next_comm  = perf_evsel__strval(evsel, sample, "next_comm");
	const u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
		  next_pid = perf_evsel__intval(evsel, sample, "next_pid");
	const u64 prev_state = perf_evsel__intval(evsel, sample, "prev_state");
723
	struct task_desc *prev, __maybe_unused *next;
724 725
	u64 timestamp0, timestamp = sample->time;
	int cpu = sample->cpu;
726 727
	s64 delta;

I
Ingo Molnar 已提交
728
	if (verbose)
729
		printf("sched_switch event %p\n", evsel);
I
Ingo Molnar 已提交
730

731
	if (cpu >= MAX_CPUS || cpu < 0)
732
		return 0;
733

734
	timestamp0 = sched->cpu_last_switched[cpu];
735 736 737 738 739
	if (timestamp0)
		delta = timestamp - timestamp0;
	else
		delta = 0;

740
	if (delta < 0) {
741
		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
742 743
		return -1;
	}
744

745 746
	pr_debug(" ... switch from %s/%d to %s/%d [ran %" PRIu64 " nsecs]\n",
		 prev_comm, prev_pid, next_comm, next_pid, delta);
747

748 749
	prev = register_pid(sched, prev_pid, prev_comm);
	next = register_pid(sched, next_pid, next_comm);
750

751
	sched->cpu_last_switched[cpu] = timestamp;
752

753
	add_sched_event_run(sched, prev, timestamp, delta);
754
	add_sched_event_sleep(sched, prev, timestamp, prev_state);
755 756

	return 0;
757 758
}

759 760 761
static int replay_fork_event(struct perf_sched *sched,
			     union perf_event *event,
			     struct machine *machine)
762
{
763 764
	struct thread *child, *parent;

765 766 767 768
	child = machine__findnew_thread(machine, event->fork.pid,
					event->fork.tid);
	parent = machine__findnew_thread(machine, event->fork.ppid,
					 event->fork.ptid);
769 770 771 772 773 774

	if (child == NULL || parent == NULL) {
		pr_debug("thread does not exist on fork event: child %p, parent %p\n",
				 child, parent);
		return 0;
	}
775

776
	if (verbose) {
777
		printf("fork event\n");
778 779
		printf("... parent: %s/%d\n", thread__comm_str(parent), parent->tid);
		printf("...  child: %s/%d\n", thread__comm_str(child), child->tid);
780
	}
781

782 783
	register_pid(sched, parent->tid, thread__comm_str(parent));
	register_pid(sched, child->tid, thread__comm_str(child));
784
	return 0;
785
}
786

787 788
struct sort_dimension {
	const char		*name;
789
	sort_fn_t		cmp;
790 791 792
	struct list_head	list;
};

793
static int
794
thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
795 796 797 798
{
	struct sort_dimension *sort;
	int ret = 0;

799 800
	BUG_ON(list_empty(list));

801 802 803 804 805 806 807 808 809
	list_for_each_entry(sort, list, list) {
		ret = sort->cmp(l, r);
		if (ret)
			return ret;
	}

	return ret;
}

810
static struct work_atoms *
811 812 813 814
thread_atoms_search(struct rb_root *root, struct thread *thread,
			 struct list_head *sort_list)
{
	struct rb_node *node = root->rb_node;
815
	struct work_atoms key = { .thread = thread };
816 817

	while (node) {
818
		struct work_atoms *atoms;
819 820
		int cmp;

821
		atoms = container_of(node, struct work_atoms, node);
822 823 824 825 826 827 828 829 830 831 832 833 834 835

		cmp = thread_lat_cmp(sort_list, &key, atoms);
		if (cmp > 0)
			node = node->rb_left;
		else if (cmp < 0)
			node = node->rb_right;
		else {
			BUG_ON(thread != atoms->thread);
			return atoms;
		}
	}
	return NULL;
}

836
static void
837
__thread_latency_insert(struct rb_root *root, struct work_atoms *data,
838
			 struct list_head *sort_list)
839 840 841 842
{
	struct rb_node **new = &(root->rb_node), *parent = NULL;

	while (*new) {
843
		struct work_atoms *this;
844
		int cmp;
845

846
		this = container_of(*new, struct work_atoms, node);
847
		parent = *new;
848 849 850 851

		cmp = thread_lat_cmp(sort_list, data, this);

		if (cmp > 0)
852 853
			new = &((*new)->rb_left);
		else
854
			new = &((*new)->rb_right);
855 856 857 858 859 860
	}

	rb_link_node(&data->node, parent, new);
	rb_insert_color(&data->node, root);
}

861
static int thread_atoms_insert(struct perf_sched *sched, struct thread *thread)
862
{
863
	struct work_atoms *atoms = zalloc(sizeof(*atoms));
864 865 866 867
	if (!atoms) {
		pr_err("No memory at %s\n", __func__);
		return -1;
	}
868

869
	atoms->thread = thread__get(thread);
870
	INIT_LIST_HEAD(&atoms->work_list);
871
	__thread_latency_insert(&sched->atom_root, atoms, &sched->cmp_pid);
872
	return 0;
873 874
}

875
static char sched_out_state(u64 prev_state)
876 877 878
{
	const char *str = TASK_STATE_TO_CHAR_STR;

879
	return str[prev_state];
880 881
}

882
static int
883 884 885
add_sched_out_event(struct work_atoms *atoms,
		    char run_state,
		    u64 timestamp)
886
{
887
	struct work_atom *atom = zalloc(sizeof(*atom));
888 889 890 891
	if (!atom) {
		pr_err("Non memory at %s", __func__);
		return -1;
	}
892

893 894
	atom->sched_out_time = timestamp;

895
	if (run_state == 'R') {
896
		atom->state = THREAD_WAIT_CPU;
897
		atom->wake_up_time = atom->sched_out_time;
898 899
	}

900
	list_add_tail(&atom->list, &atoms->work_list);
901
	return 0;
902 903 904
}

static void
905 906
add_runtime_event(struct work_atoms *atoms, u64 delta,
		  u64 timestamp __maybe_unused)
907 908 909 910 911 912 913 914 915 916 917 918 919
{
	struct work_atom *atom;

	BUG_ON(list_empty(&atoms->work_list));

	atom = list_entry(atoms->work_list.prev, struct work_atom, list);

	atom->runtime += delta;
	atoms->total_runtime += delta;
}

static void
add_sched_in_event(struct work_atoms *atoms, u64 timestamp)
920
{
921
	struct work_atom *atom;
922
	u64 delta;
923

924
	if (list_empty(&atoms->work_list))
925 926
		return;

927
	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
928

929
	if (atom->state != THREAD_WAIT_CPU)
930 931
		return;

932 933
	if (timestamp < atom->wake_up_time) {
		atom->state = THREAD_IGNORE;
934 935 936
		return;
	}

937 938
	atom->state = THREAD_SCHED_IN;
	atom->sched_in_time = timestamp;
939

940
	delta = atom->sched_in_time - atom->wake_up_time;
941
	atoms->total_lat += delta;
942
	if (delta > atoms->max_lat) {
943
		atoms->max_lat = delta;
944 945
		atoms->max_lat_at = timestamp;
	}
946
	atoms->nb_atoms++;
947 948
}

949 950 951 952
static int latency_switch_event(struct perf_sched *sched,
				struct perf_evsel *evsel,
				struct perf_sample *sample,
				struct machine *machine)
953
{
954 955 956
	const u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
		  next_pid = perf_evsel__intval(evsel, sample, "next_pid");
	const u64 prev_state = perf_evsel__intval(evsel, sample, "prev_state");
957
	struct work_atoms *out_events, *in_events;
958
	struct thread *sched_out, *sched_in;
959 960
	u64 timestamp0, timestamp = sample->time;
	int cpu = sample->cpu;
I
Ingo Molnar 已提交
961 962
	s64 delta;

963
	BUG_ON(cpu >= MAX_CPUS || cpu < 0);
I
Ingo Molnar 已提交
964

965 966
	timestamp0 = sched->cpu_last_switched[cpu];
	sched->cpu_last_switched[cpu] = timestamp;
I
Ingo Molnar 已提交
967 968 969 970 971
	if (timestamp0)
		delta = timestamp - timestamp0;
	else
		delta = 0;

972 973 974 975
	if (delta < 0) {
		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
		return -1;
	}
976

977 978
	sched_out = machine__findnew_thread(machine, -1, prev_pid);
	sched_in = machine__findnew_thread(machine, -1, next_pid);
979

980
	out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
981
	if (!out_events) {
982
		if (thread_atoms_insert(sched, sched_out))
983
			return -1;
984
		out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
985 986 987 988
		if (!out_events) {
			pr_err("out-event: Internal tree error");
			return -1;
		}
989
	}
990
	if (add_sched_out_event(out_events, sched_out_state(prev_state), timestamp))
991
		return -1;
992

993
	in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
994
	if (!in_events) {
995
		if (thread_atoms_insert(sched, sched_in))
996
			return -1;
997
		in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
998 999 1000 1001
		if (!in_events) {
			pr_err("in-event: Internal tree error");
			return -1;
		}
1002 1003 1004 1005
		/*
		 * Take came in we have not heard about yet,
		 * add in an initial atom in runnable state:
		 */
1006 1007
		if (add_sched_out_event(in_events, 'R', timestamp))
			return -1;
1008
	}
1009
	add_sched_in_event(in_events, timestamp);
1010 1011

	return 0;
1012
}
1013

1014 1015 1016 1017
static int latency_runtime_event(struct perf_sched *sched,
				 struct perf_evsel *evsel,
				 struct perf_sample *sample,
				 struct machine *machine)
1018
{
1019 1020
	const u32 pid	   = perf_evsel__intval(evsel, sample, "pid");
	const u64 runtime  = perf_evsel__intval(evsel, sample, "runtime");
1021
	struct thread *thread = machine__findnew_thread(machine, -1, pid);
1022
	struct work_atoms *atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1023 1024
	u64 timestamp = sample->time;
	int cpu = sample->cpu;
1025 1026 1027

	BUG_ON(cpu >= MAX_CPUS || cpu < 0);
	if (!atoms) {
1028
		if (thread_atoms_insert(sched, thread))
1029
			return -1;
1030
		atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1031
		if (!atoms) {
1032
			pr_err("in-event: Internal tree error");
1033 1034 1035 1036
			return -1;
		}
		if (add_sched_out_event(atoms, 'R', timestamp))
			return -1;
1037 1038
	}

1039
	add_runtime_event(atoms, runtime, timestamp);
1040
	return 0;
1041 1042
}

1043 1044 1045 1046
static int latency_wakeup_event(struct perf_sched *sched,
				struct perf_evsel *evsel,
				struct perf_sample *sample,
				struct machine *machine)
1047
{
1048
	const u32 pid	  = perf_evsel__intval(evsel, sample, "pid");
1049
	struct work_atoms *atoms;
1050
	struct work_atom *atom;
1051
	struct thread *wakee;
1052
	u64 timestamp = sample->time;
1053

1054
	wakee = machine__findnew_thread(machine, -1, pid);
1055
	atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1056
	if (!atoms) {
1057
		if (thread_atoms_insert(sched, wakee))
1058
			return -1;
1059
		atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1060
		if (!atoms) {
1061
			pr_err("wakeup-event: Internal tree error");
1062 1063 1064 1065
			return -1;
		}
		if (add_sched_out_event(atoms, 'S', timestamp))
			return -1;
1066 1067
	}

1068
	BUG_ON(list_empty(&atoms->work_list));
1069

1070
	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1071

1072
	/*
1073 1074 1075 1076 1077 1078
	 * As we do not guarantee the wakeup event happens when
	 * task is out of run queue, also may happen when task is
	 * on run queue and wakeup only change ->state to TASK_RUNNING,
	 * then we should not set the ->wake_up_time when wake up a
	 * task which is on run queue.
	 *
1079 1080
	 * You WILL be missing events if you've recorded only
	 * one CPU, or are only looking at only one, so don't
1081
	 * skip in this case.
1082
	 */
1083
	if (sched->profile_cpu == -1 && atom->state != THREAD_SLEEPING)
1084
		return 0;
1085

1086
	sched->nr_timestamps++;
1087
	if (atom->sched_out_time > timestamp) {
1088
		sched->nr_unordered_timestamps++;
1089
		return 0;
1090
	}
1091

1092 1093
	atom->state = THREAD_WAIT_CPU;
	atom->wake_up_time = timestamp;
1094
	return 0;
1095 1096
}

1097 1098 1099 1100
static int latency_migrate_task_event(struct perf_sched *sched,
				      struct perf_evsel *evsel,
				      struct perf_sample *sample,
				      struct machine *machine)
1101
{
1102
	const u32 pid = perf_evsel__intval(evsel, sample, "pid");
1103
	u64 timestamp = sample->time;
1104 1105 1106 1107 1108 1109 1110
	struct work_atoms *atoms;
	struct work_atom *atom;
	struct thread *migrant;

	/*
	 * Only need to worry about migration when profiling one CPU.
	 */
1111
	if (sched->profile_cpu == -1)
1112
		return 0;
1113

1114
	migrant = machine__findnew_thread(machine, -1, pid);
1115
	atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1116
	if (!atoms) {
1117
		if (thread_atoms_insert(sched, migrant))
1118
			return -1;
1119
		register_pid(sched, migrant->tid, thread__comm_str(migrant));
1120
		atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1121
		if (!atoms) {
1122
			pr_err("migration-event: Internal tree error");
1123 1124 1125 1126
			return -1;
		}
		if (add_sched_out_event(atoms, 'R', timestamp))
			return -1;
1127 1128 1129 1130 1131 1132 1133
	}

	BUG_ON(list_empty(&atoms->work_list));

	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
	atom->sched_in_time = atom->sched_out_time = atom->wake_up_time = timestamp;

1134
	sched->nr_timestamps++;
1135 1136

	if (atom->sched_out_time > timestamp)
1137
		sched->nr_unordered_timestamps++;
1138 1139

	return 0;
1140 1141
}

1142
static void output_lat_thread(struct perf_sched *sched, struct work_atoms *work_list)
1143 1144 1145
{
	int i;
	int ret;
1146
	u64 avg;
1147

1148
	if (!work_list->nb_atoms)
1149
		return;
1150 1151 1152
	/*
	 * Ignore idle threads:
	 */
1153
	if (!strcmp(thread__comm_str(work_list->thread), "swapper"))
1154
		return;
1155

1156 1157
	sched->all_runtime += work_list->total_runtime;
	sched->all_count   += work_list->nb_atoms;
1158

1159
	ret = printf("  %s:%d ", thread__comm_str(work_list->thread), work_list->thread->tid);
1160

M
mingo 已提交
1161
	for (i = 0; i < 24 - ret; i++)
1162 1163
		printf(" ");

1164
	avg = work_list->total_lat / work_list->nb_atoms;
1165

1166
	printf("|%11.3f ms |%9" PRIu64 " | avg:%9.3f ms | max:%9.3f ms | max at: %13.6f s\n",
1167 1168
	      (double)work_list->total_runtime / 1e6,
		 work_list->nb_atoms, (double)avg / 1e6,
1169 1170
		 (double)work_list->max_lat / 1e6,
		 (double)work_list->max_lat_at / 1e9);
1171 1172
}

1173
static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
1174
{
1175
	if (l->thread->tid < r->thread->tid)
1176
		return -1;
1177
	if (l->thread->tid > r->thread->tid)
1178 1179 1180 1181 1182
		return 1;

	return 0;
}

1183
static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
{
	u64 avgl, avgr;

	if (!l->nb_atoms)
		return -1;

	if (!r->nb_atoms)
		return 1;

	avgl = l->total_lat / l->nb_atoms;
	avgr = r->total_lat / r->nb_atoms;

	if (avgl < avgr)
		return -1;
	if (avgl > avgr)
		return 1;

	return 0;
}

1204
static int max_cmp(struct work_atoms *l, struct work_atoms *r)
1205 1206 1207 1208 1209 1210 1211 1212 1213
{
	if (l->max_lat < r->max_lat)
		return -1;
	if (l->max_lat > r->max_lat)
		return 1;

	return 0;
}

1214
static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
1215 1216 1217 1218 1219 1220 1221 1222 1223
{
	if (l->nb_atoms < r->nb_atoms)
		return -1;
	if (l->nb_atoms > r->nb_atoms)
		return 1;

	return 0;
}

1224
static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
1225 1226 1227 1228 1229 1230 1231 1232 1233
{
	if (l->total_runtime < r->total_runtime)
		return -1;
	if (l->total_runtime > r->total_runtime)
		return 1;

	return 0;
}

1234
static int sort_dimension__add(const char *tok, struct list_head *list)
1235
{
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	size_t i;
	static struct sort_dimension avg_sort_dimension = {
		.name = "avg",
		.cmp  = avg_cmp,
	};
	static struct sort_dimension max_sort_dimension = {
		.name = "max",
		.cmp  = max_cmp,
	};
	static struct sort_dimension pid_sort_dimension = {
		.name = "pid",
		.cmp  = pid_cmp,
	};
	static struct sort_dimension runtime_sort_dimension = {
		.name = "runtime",
		.cmp  = runtime_cmp,
	};
	static struct sort_dimension switch_sort_dimension = {
		.name = "switch",
		.cmp  = switch_cmp,
	};
	struct sort_dimension *available_sorts[] = {
		&pid_sort_dimension,
		&avg_sort_dimension,
		&max_sort_dimension,
		&switch_sort_dimension,
		&runtime_sort_dimension,
	};
1264

1265
	for (i = 0; i < ARRAY_SIZE(available_sorts); i++) {
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
		if (!strcmp(available_sorts[i]->name, tok)) {
			list_add_tail(&available_sorts[i]->list, list);

			return 0;
		}
	}

	return -1;
}

1276
static void perf_sched__sort_lat(struct perf_sched *sched)
1277 1278 1279 1280
{
	struct rb_node *node;

	for (;;) {
1281
		struct work_atoms *data;
1282
		node = rb_first(&sched->atom_root);
1283 1284 1285
		if (!node)
			break;

1286
		rb_erase(node, &sched->atom_root);
1287
		data = rb_entry(node, struct work_atoms, node);
1288
		__thread_latency_insert(&sched->sorted_atom_root, data, &sched->sort_list);
1289 1290 1291
	}
}

1292
static int process_sched_wakeup_event(struct perf_tool *tool,
1293
				      struct perf_evsel *evsel,
1294
				      struct perf_sample *sample,
1295
				      struct machine *machine)
1296
{
1297
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1298

1299 1300
	if (sched->tp_handler->wakeup_event)
		return sched->tp_handler->wakeup_event(sched, evsel, sample, machine);
1301

1302
	return 0;
1303 1304
}

1305 1306
static int map_switch_event(struct perf_sched *sched, struct perf_evsel *evsel,
			    struct perf_sample *sample, struct machine *machine)
1307
{
1308 1309
	const u32 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
	struct thread *sched_in;
1310
	int new_shortname;
1311
	u64 timestamp0, timestamp = sample->time;
1312
	s64 delta;
1313
	int cpu, this_cpu = sample->cpu;
1314 1315 1316

	BUG_ON(this_cpu >= MAX_CPUS || this_cpu < 0);

1317 1318
	if (this_cpu > sched->max_cpu)
		sched->max_cpu = this_cpu;
1319

1320 1321
	timestamp0 = sched->cpu_last_switched[this_cpu];
	sched->cpu_last_switched[this_cpu] = timestamp;
1322 1323 1324 1325 1326
	if (timestamp0)
		delta = timestamp - timestamp0;
	else
		delta = 0;

1327
	if (delta < 0) {
1328
		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1329 1330
		return -1;
	}
1331

1332
	sched_in = machine__findnew_thread(machine, -1, next_pid);
1333

1334
	sched->curr_thread[this_cpu] = sched_in;
1335 1336 1337 1338 1339

	printf("  ");

	new_shortname = 0;
	if (!sched_in->shortname[0]) {
1340 1341 1342 1343 1344 1345 1346
		if (!strcmp(thread__comm_str(sched_in), "swapper")) {
			/*
			 * Don't allocate a letter-number for swapper:0
			 * as a shortname. Instead, we use '.' for it.
			 */
			sched_in->shortname[0] = '.';
			sched_in->shortname[1] = ' ';
1347
		} else {
1348 1349 1350 1351 1352
			sched_in->shortname[0] = sched->next_shortname1;
			sched_in->shortname[1] = sched->next_shortname2;

			if (sched->next_shortname1 < 'Z') {
				sched->next_shortname1++;
1353
			} else {
1354 1355 1356 1357 1358
				sched->next_shortname1 = 'A';
				if (sched->next_shortname2 < '9')
					sched->next_shortname2++;
				else
					sched->next_shortname2 = '0';
1359 1360 1361 1362 1363
			}
		}
		new_shortname = 1;
	}

1364
	for (cpu = 0; cpu <= sched->max_cpu; cpu++) {
1365 1366 1367 1368 1369
		if (cpu != this_cpu)
			printf(" ");
		else
			printf("*");

1370 1371 1372
		if (sched->curr_thread[cpu])
			printf("%2s ", sched->curr_thread[cpu]->shortname);
		else
1373 1374 1375 1376 1377 1378
			printf("   ");
	}

	printf("  %12.6f secs ", (double)timestamp/1e9);
	if (new_shortname) {
		printf("%s => %s:%d\n",
1379
		       sched_in->shortname, thread__comm_str(sched_in), sched_in->tid);
1380 1381 1382
	} else {
		printf("\n");
	}
1383 1384

	return 0;
1385 1386
}

1387
static int process_sched_switch_event(struct perf_tool *tool,
1388
				      struct perf_evsel *evsel,
1389
				      struct perf_sample *sample,
1390
				      struct machine *machine)
1391
{
1392
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1393
	int this_cpu = sample->cpu, err = 0;
1394 1395
	u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
	    next_pid = perf_evsel__intval(evsel, sample, "next_pid");
1396

1397
	if (sched->curr_pid[this_cpu] != (u32)-1) {
1398 1399 1400 1401
		/*
		 * Are we trying to switch away a PID that is
		 * not current?
		 */
1402
		if (sched->curr_pid[this_cpu] != prev_pid)
1403
			sched->nr_context_switch_bugs++;
1404 1405
	}

1406 1407
	if (sched->tp_handler->switch_event)
		err = sched->tp_handler->switch_event(sched, evsel, sample, machine);
1408 1409

	sched->curr_pid[this_cpu] = next_pid;
1410
	return err;
1411 1412
}

1413
static int process_sched_runtime_event(struct perf_tool *tool,
1414
				       struct perf_evsel *evsel,
1415
				       struct perf_sample *sample,
1416
				       struct machine *machine)
1417
{
1418
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1419

1420 1421
	if (sched->tp_handler->runtime_event)
		return sched->tp_handler->runtime_event(sched, evsel, sample, machine);
1422

1423
	return 0;
1424 1425
}

1426 1427 1428 1429
static int perf_sched__process_fork_event(struct perf_tool *tool,
					  union perf_event *event,
					  struct perf_sample *sample,
					  struct machine *machine)
1430
{
1431
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1432

1433 1434 1435 1436
	/* run the fork event through the perf machineruy */
	perf_event__process_fork(tool, event, sample, machine);

	/* and then run additional processing needed for this command */
1437
	if (sched->tp_handler->fork_event)
1438
		return sched->tp_handler->fork_event(sched, event, machine);
1439

1440
	return 0;
1441 1442
}

1443
static int process_sched_migrate_task_event(struct perf_tool *tool,
1444
					    struct perf_evsel *evsel,
1445
					    struct perf_sample *sample,
1446
					    struct machine *machine)
1447
{
1448
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1449

1450 1451
	if (sched->tp_handler->migrate_task_event)
		return sched->tp_handler->migrate_task_event(sched, evsel, sample, machine);
1452

1453
	return 0;
1454 1455
}

1456
typedef int (*tracepoint_handler)(struct perf_tool *tool,
1457
				  struct perf_evsel *evsel,
1458
				  struct perf_sample *sample,
1459
				  struct machine *machine);
I
Ingo Molnar 已提交
1460

1461 1462
static int perf_sched__process_tracepoint_sample(struct perf_tool *tool __maybe_unused,
						 union perf_event *event __maybe_unused,
1463 1464 1465
						 struct perf_sample *sample,
						 struct perf_evsel *evsel,
						 struct machine *machine)
I
Ingo Molnar 已提交
1466
{
1467
	int err = 0;
I
Ingo Molnar 已提交
1468

1469 1470
	if (evsel->handler != NULL) {
		tracepoint_handler f = evsel->handler;
1471
		err = f(tool, evsel, sample, machine);
1472
	}
I
Ingo Molnar 已提交
1473

1474
	return err;
I
Ingo Molnar 已提交
1475 1476
}

1477
static int perf_sched__read_events(struct perf_sched *sched)
I
Ingo Molnar 已提交
1478
{
1479 1480 1481 1482 1483 1484 1485
	const struct perf_evsel_str_handler handlers[] = {
		{ "sched:sched_switch",	      process_sched_switch_event, },
		{ "sched:sched_stat_runtime", process_sched_runtime_event, },
		{ "sched:sched_wakeup",	      process_sched_wakeup_event, },
		{ "sched:sched_wakeup_new",   process_sched_wakeup_event, },
		{ "sched:sched_migrate_task", process_sched_migrate_task_event, },
	};
1486
	struct perf_session *session;
1487 1488 1489
	struct perf_data_file file = {
		.path = input_name,
		.mode = PERF_DATA_MODE_READ,
1490
		.force = sched->force,
1491
	};
1492
	int rc = -1;
1493

1494
	session = perf_session__new(&file, false, &sched->tool);
1495 1496 1497 1498
	if (session == NULL) {
		pr_debug("No Memory for session\n");
		return -1;
	}
1499

1500
	symbol__init(&session->header.env);
1501

1502 1503
	if (perf_session__set_tracepoints_handlers(session, handlers))
		goto out_delete;
1504

1505
	if (perf_session__has_traces(session, "record -R")) {
1506
		int err = perf_session__process_events(session);
1507 1508 1509 1510
		if (err) {
			pr_err("Failed to process events, error %d", err);
			goto out_delete;
		}
1511

1512 1513 1514
		sched->nr_events      = session->evlist->stats.nr_events[0];
		sched->nr_lost_events = session->evlist->stats.total_lost;
		sched->nr_lost_chunks = session->evlist->stats.nr_events[PERF_RECORD_LOST];
1515
	}
1516

1517
	rc = 0;
1518 1519
out_delete:
	perf_session__delete(session);
1520
	return rc;
I
Ingo Molnar 已提交
1521 1522
}

1523
static void print_bad_events(struct perf_sched *sched)
1524
{
1525
	if (sched->nr_unordered_timestamps && sched->nr_timestamps) {
1526
		printf("  INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
1527 1528
			(double)sched->nr_unordered_timestamps/(double)sched->nr_timestamps*100.0,
			sched->nr_unordered_timestamps, sched->nr_timestamps);
1529
	}
1530
	if (sched->nr_lost_events && sched->nr_events) {
1531
		printf("  INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
1532 1533
			(double)sched->nr_lost_events/(double)sched->nr_events * 100.0,
			sched->nr_lost_events, sched->nr_events, sched->nr_lost_chunks);
1534
	}
1535
	if (sched->nr_context_switch_bugs && sched->nr_timestamps) {
1536
		printf("  INFO: %.3f%% context switch bugs (%ld out of %ld)",
1537 1538 1539
			(double)sched->nr_context_switch_bugs/(double)sched->nr_timestamps*100.0,
			sched->nr_context_switch_bugs, sched->nr_timestamps);
		if (sched->nr_lost_events)
1540 1541 1542 1543 1544
			printf(" (due to lost events?)");
		printf("\n");
	}
}

1545
static int perf_sched__lat(struct perf_sched *sched)
1546 1547 1548 1549
{
	struct rb_node *next;

	setup_pager();
1550

1551
	if (perf_sched__read_events(sched))
1552
		return -1;
1553

1554
	perf_sched__sort_lat(sched);
1555

1556 1557 1558
	printf("\n -----------------------------------------------------------------------------------------------------------------\n");
	printf("  Task                  |   Runtime ms  | Switches | Average delay ms | Maximum delay ms | Maximum delay at       |\n");
	printf(" -----------------------------------------------------------------------------------------------------------------\n");
1559

1560
	next = rb_first(&sched->sorted_atom_root);
1561 1562 1563 1564 1565

	while (next) {
		struct work_atoms *work_list;

		work_list = rb_entry(next, struct work_atoms, node);
1566
		output_lat_thread(sched, work_list);
1567
		next = rb_next(next);
1568
		thread__zput(work_list->thread);
1569 1570
	}

1571
	printf(" -----------------------------------------------------------------------------------------------------------------\n");
1572
	printf("  TOTAL:                |%11.3f ms |%9" PRIu64 " |\n",
1573
		(double)sched->all_runtime / 1e6, sched->all_count);
1574 1575 1576

	printf(" ---------------------------------------------------\n");

1577
	print_bad_events(sched);
1578 1579
	printf("\n");

1580
	return 0;
1581 1582
}

1583
static int perf_sched__map(struct perf_sched *sched)
1584
{
1585
	sched->max_cpu = sysconf(_SC_NPROCESSORS_CONF);
1586

1587
	setup_pager();
1588
	if (perf_sched__read_events(sched))
1589
		return -1;
1590
	print_bad_events(sched);
1591
	return 0;
1592 1593
}

1594
static int perf_sched__replay(struct perf_sched *sched)
1595 1596 1597
{
	unsigned long i;

1598 1599
	calibrate_run_measurement_overhead(sched);
	calibrate_sleep_measurement_overhead(sched);
1600

1601
	test_calibrations(sched);
1602

1603
	if (perf_sched__read_events(sched))
1604
		return -1;
1605

1606 1607 1608
	printf("nr_run_events:        %ld\n", sched->nr_run_events);
	printf("nr_sleep_events:      %ld\n", sched->nr_sleep_events);
	printf("nr_wakeup_events:     %ld\n", sched->nr_wakeup_events);
1609

1610 1611 1612 1613 1614
	if (sched->targetless_wakeups)
		printf("target-less wakeups:  %ld\n", sched->targetless_wakeups);
	if (sched->multitarget_wakeups)
		printf("multi-target wakeups: %ld\n", sched->multitarget_wakeups);
	if (sched->nr_run_events_optimized)
1615
		printf("run atoms optimized: %ld\n",
1616
			sched->nr_run_events_optimized);
1617

1618 1619
	print_task_traces(sched);
	add_cross_task_wakeups(sched);
1620

1621
	create_tasks(sched);
1622
	printf("------------------------------------------------------------\n");
1623 1624
	for (i = 0; i < sched->replay_repeat; i++)
		run_one_test(sched);
1625 1626

	return 0;
1627 1628
}

1629 1630
static void setup_sorting(struct perf_sched *sched, const struct option *options,
			  const char * const usage_msg[])
1631
{
1632
	char *tmp, *tok, *str = strdup(sched->sort_order);
1633 1634 1635

	for (tok = strtok_r(str, ", ", &tmp);
			tok; tok = strtok_r(NULL, ", ", &tmp)) {
1636
		if (sort_dimension__add(tok, &sched->sort_list) < 0) {
1637
			error("Unknown --sort key: `%s'", tok);
1638
			usage_with_options(usage_msg, options);
1639 1640 1641 1642 1643
		}
	}

	free(str);

1644
	sort_dimension__add("pid", &sched->cmp_pid);
1645 1646
}

1647 1648 1649 1650
static int __cmd_record(int argc, const char **argv)
{
	unsigned int rec_argc, i, j;
	const char **rec_argv;
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
	const char * const record_args[] = {
		"record",
		"-a",
		"-R",
		"-m", "1024",
		"-c", "1",
		"-e", "sched:sched_switch",
		"-e", "sched:sched_stat_wait",
		"-e", "sched:sched_stat_sleep",
		"-e", "sched:sched_stat_iowait",
		"-e", "sched:sched_stat_runtime",
		"-e", "sched:sched_process_fork",
		"-e", "sched:sched_wakeup",
1664
		"-e", "sched:sched_wakeup_new",
1665 1666
		"-e", "sched:sched_migrate_task",
	};
1667 1668 1669 1670

	rec_argc = ARRAY_SIZE(record_args) + argc - 1;
	rec_argv = calloc(rec_argc + 1, sizeof(char *));

1671
	if (rec_argv == NULL)
1672 1673
		return -ENOMEM;

1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
	for (i = 0; i < ARRAY_SIZE(record_args); i++)
		rec_argv[i] = strdup(record_args[i]);

	for (j = 1; j < (unsigned int)argc; j++, i++)
		rec_argv[i] = argv[j];

	BUG_ON(i != rec_argc);

	return cmd_record(i, rec_argv, NULL);
}

1685
int cmd_sched(int argc, const char **argv, const char *prefix __maybe_unused)
I
Ingo Molnar 已提交
1686
{
1687 1688 1689 1690 1691 1692 1693
	const char default_sort_order[] = "avg, max, switch, runtime";
	struct perf_sched sched = {
		.tool = {
			.sample		 = perf_sched__process_tracepoint_sample,
			.comm		 = perf_event__process_comm,
			.lost		 = perf_event__process_lost,
			.fork		 = perf_sched__process_fork_event,
1694
			.ordered_events = true,
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
		},
		.cmp_pid	      = LIST_HEAD_INIT(sched.cmp_pid),
		.sort_list	      = LIST_HEAD_INIT(sched.sort_list),
		.start_work_mutex     = PTHREAD_MUTEX_INITIALIZER,
		.work_done_wait_mutex = PTHREAD_MUTEX_INITIALIZER,
		.sort_order	      = default_sort_order,
		.replay_repeat	      = 10,
		.profile_cpu	      = -1,
		.next_shortname1      = 'A',
		.next_shortname2      = '0',
	};
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
	const struct option latency_options[] = {
	OPT_STRING('s', "sort", &sched.sort_order, "key[,key2...]",
		   "sort by key(s): runtime, switch, avg, max"),
	OPT_INCR('v', "verbose", &verbose,
		    "be more verbose (show symbol address, etc)"),
	OPT_INTEGER('C', "CPU", &sched.profile_cpu,
		    "CPU to profile on"),
	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
		    "dump raw trace in ASCII"),
	OPT_END()
	};
	const struct option replay_options[] = {
	OPT_UINTEGER('r', "repeat", &sched.replay_repeat,
		     "repeat the workload replay N times (-1: infinite)"),
	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"),
1724
	OPT_BOOLEAN('f', "force", &sched.force, "don't complain, do it"),
1725 1726 1727
	OPT_END()
	};
	const struct option sched_options[] = {
1728
	OPT_STRING('i', "input", &input_name, "file",
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
		    "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"),
	OPT_END()
	};
	const char * const latency_usage[] = {
		"perf sched latency [<options>]",
		NULL
	};
	const char * const replay_usage[] = {
		"perf sched replay [<options>]",
		NULL
	};
1744 1745 1746 1747
	const char *const sched_subcommands[] = { "record", "latency", "map",
						  "replay", "script", NULL };
	const char *sched_usage[] = {
		NULL,
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
		NULL
	};
	struct trace_sched_handler lat_ops  = {
		.wakeup_event	    = latency_wakeup_event,
		.switch_event	    = latency_switch_event,
		.runtime_event	    = latency_runtime_event,
		.migrate_task_event = latency_migrate_task_event,
	};
	struct trace_sched_handler map_ops  = {
		.switch_event	    = map_switch_event,
	};
	struct trace_sched_handler replay_ops  = {
		.wakeup_event	    = replay_wakeup_event,
		.switch_event	    = replay_switch_event,
		.fork_event	    = replay_fork_event,
	};
A
Adrian Hunter 已提交
1764 1765 1766 1767
	unsigned int i;

	for (i = 0; i < ARRAY_SIZE(sched.curr_pid); i++)
		sched.curr_pid[i] = -1;
1768

1769 1770
	argc = parse_options_subcommand(argc, argv, sched_options, sched_subcommands,
					sched_usage, PARSE_OPT_STOP_AT_NON_OPTION);
1771 1772
	if (!argc)
		usage_with_options(sched_usage, sched_options);
I
Ingo Molnar 已提交
1773

1774
	/*
1775
	 * Aliased to 'perf script' for now:
1776
	 */
1777 1778
	if (!strcmp(argv[0], "script"))
		return cmd_script(argc, argv, prefix);
1779

1780 1781 1782
	if (!strncmp(argv[0], "rec", 3)) {
		return __cmd_record(argc, argv);
	} else if (!strncmp(argv[0], "lat", 3)) {
1783
		sched.tp_handler = &lat_ops;
1784 1785 1786 1787 1788
		if (argc > 1) {
			argc = parse_options(argc, argv, latency_options, latency_usage, 0);
			if (argc)
				usage_with_options(latency_usage, latency_options);
		}
1789 1790
		setup_sorting(&sched, latency_options, latency_usage);
		return perf_sched__lat(&sched);
1791
	} else if (!strcmp(argv[0], "map")) {
1792 1793 1794
		sched.tp_handler = &map_ops;
		setup_sorting(&sched, latency_options, latency_usage);
		return perf_sched__map(&sched);
1795
	} else if (!strncmp(argv[0], "rep", 3)) {
1796
		sched.tp_handler = &replay_ops;
1797 1798 1799 1800 1801
		if (argc) {
			argc = parse_options(argc, argv, replay_options, replay_usage, 0);
			if (argc)
				usage_with_options(replay_usage, replay_options);
		}
1802
		return perf_sched__replay(&sched);
1803 1804 1805 1806
	} else {
		usage_with_options(sched_usage, sched_options);
	}

I
Ingo Molnar 已提交
1807
	return 0;
I
Ingo Molnar 已提交
1808
}