builtin-sched.c 51.5 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"
J
Jiri Olsa 已提交
14
#include "util/thread_map.h"
15
#include "util/color.h"
I
Ingo Molnar 已提交
16

17
#include <subcmd/parse-options.h>
18
#include "util/trace-event.h"
I
Ingo Molnar 已提交
19 20 21

#include "util/debug.h"

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

25 26 27
#include <semaphore.h>
#include <pthread.h>
#include <math.h>
28
#include <api/fs/fs.h>
29

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

36
struct sched_atom;
I
Ingo Molnar 已提交
37

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

43 44
	unsigned long		nr_events;
	unsigned long		curr_event;
45
	struct sched_atom	**atoms;
46 47 48

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

50 51 52 53 54 55 56 57 58 59
	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,
60
	SCHED_EVENT_MIGRATION,
61 62
};

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

73
#define TASK_STATE_TO_CHAR_STR "RSDTtZXxKWP"
74 75 76 77 78 79 80 81 82 83 84

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;
85
	u64			sched_out_time;
86 87 88 89 90
	u64			wake_up_time;
	u64			sched_in_time;
	u64			runtime;
};

91 92
struct work_atoms {
	struct list_head	work_list;
93 94 95
	struct thread		*thread;
	struct rb_node		node;
	u64			max_lat;
96
	u64			max_lat_at;
97 98 99
	u64			total_lat;
	u64			nb_atoms;
	u64			total_runtime;
100
	int			num_merged;
101 102
};

103
typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
104

105
struct perf_sched;
106

107 108 109
struct trace_sched_handler {
	int (*switch_event)(struct perf_sched *sched, struct perf_evsel *evsel,
			    struct perf_sample *sample, struct machine *machine);
110

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

114 115
	int (*wakeup_event)(struct perf_sched *sched, struct perf_evsel *evsel,
			    struct perf_sample *sample, struct machine *machine);
116

117 118 119
	/* PERF_RECORD_FORK event, not sched_process_fork tracepoint */
	int (*fork_event)(struct perf_sched *sched, union perf_event *event,
			  struct machine *machine);
120 121

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

J
Jiri Olsa 已提交
127
#define COLOR_PIDS PERF_COLOR_BLUE
J
Jiri Olsa 已提交
128
#define COLOR_CPUS PERF_COLOR_BG_RED
J
Jiri Olsa 已提交
129

130 131 132 133
struct perf_sched_map {
	DECLARE_BITMAP(comp_cpus_mask, MAX_CPUS);
	int			*comp_cpus;
	bool			 comp;
J
Jiri Olsa 已提交
134 135
	struct thread_map	*color_pids;
	const char		*color_pids_str;
J
Jiri Olsa 已提交
136 137
	struct cpu_map		*color_cpus;
	const char		*color_cpus_str;
138 139
	struct cpu_map		*cpus;
	const char		*cpus_str;
140 141
};

142 143 144 145
struct perf_sched {
	struct perf_tool tool;
	const char	 *sort_order;
	unsigned long	 nr_tasks;
146
	struct task_desc **pid_to_task;
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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	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];
189
	struct rb_root	 atom_root, sorted_atom_root, merged_atom_root;
190
	struct list_head sort_list, cmp_pid;
191
	bool force;
192
	bool skip_merge;
193
	struct perf_sched_map map;
194
};
195 196

static u64 get_nsecs(void)
I
Ingo Molnar 已提交
197 198 199 200 201 202 203 204
{
	struct timespec ts;

	clock_gettime(CLOCK_MONOTONIC, &ts);

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

205
static void burn_nsecs(struct perf_sched *sched, u64 nsecs)
I
Ingo Molnar 已提交
206
{
207
	u64 T0 = get_nsecs(), T1;
I
Ingo Molnar 已提交
208 209 210

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

214
static void sleep_nsecs(u64 nsecs)
I
Ingo Molnar 已提交
215 216 217 218 219 220 221 222 223
{
	struct timespec ts;

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

	nanosleep(&ts, NULL);
}

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

	for (i = 0; i < 10; i++) {
		T0 = get_nsecs();
231
		burn_nsecs(sched, 0);
I
Ingo Molnar 已提交
232 233 234 235
		T1 = get_nsecs();
		delta = T1-T0;
		min_delta = min(min_delta, delta);
	}
236
	sched->run_measurement_overhead = min_delta;
I
Ingo Molnar 已提交
237

238
	printf("run measurement overhead: %" PRIu64 " nsecs\n", min_delta);
I
Ingo Molnar 已提交
239 240
}

241
static void calibrate_sleep_measurement_overhead(struct perf_sched *sched)
I
Ingo Molnar 已提交
242
{
243
	u64 T0, T1, delta, min_delta = 1000000000ULL;
I
Ingo Molnar 已提交
244 245 246 247 248 249 250 251 252 253
	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;
254
	sched->sleep_measurement_overhead = min_delta;
I
Ingo Molnar 已提交
255

256
	printf("sleep measurement overhead: %" PRIu64 " nsecs\n", min_delta);
I
Ingo Molnar 已提交
257 258
}

259
static struct sched_atom *
260
get_new_event(struct task_desc *task, u64 timestamp)
I
Ingo Molnar 已提交
261
{
262
	struct sched_atom *event = zalloc(sizeof(*event));
I
Ingo Molnar 已提交
263 264 265 266 267 268 269
	unsigned long idx = task->nr_events;
	size_t size;

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

	task->nr_events++;
270 271 272
	size = sizeof(struct sched_atom *) * task->nr_events;
	task->atoms = realloc(task->atoms, size);
	BUG_ON(!task->atoms);
I
Ingo Molnar 已提交
273

274
	task->atoms[idx] = event;
I
Ingo Molnar 已提交
275 276 277 278

	return event;
}

279
static struct sched_atom *last_event(struct task_desc *task)
I
Ingo Molnar 已提交
280 281 282 283
{
	if (!task->nr_events)
		return NULL;

284
	return task->atoms[task->nr_events - 1];
I
Ingo Molnar 已提交
285 286
}

287 288
static void add_sched_event_run(struct perf_sched *sched, struct task_desc *task,
				u64 timestamp, u64 duration)
I
Ingo Molnar 已提交
289
{
290
	struct sched_atom *event, *curr_event = last_event(task);
I
Ingo Molnar 已提交
291 292

	/*
293 294 295
	 * optimize an existing RUN event by merging this one
	 * to it:
	 */
I
Ingo Molnar 已提交
296
	if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
297
		sched->nr_run_events_optimized++;
I
Ingo Molnar 已提交
298 299 300 301 302 303 304 305 306
		curr_event->duration += duration;
		return;
	}

	event = get_new_event(task, timestamp);

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

307
	sched->nr_run_events++;
I
Ingo Molnar 已提交
308 309
}

310 311
static void add_sched_event_wakeup(struct perf_sched *sched, struct task_desc *task,
				   u64 timestamp, struct task_desc *wakee)
I
Ingo Molnar 已提交
312
{
313
	struct sched_atom *event, *wakee_event;
I
Ingo Molnar 已提交
314 315 316 317 318 319 320

	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) {
321
		sched->targetless_wakeups++;
I
Ingo Molnar 已提交
322 323 324
		return;
	}
	if (wakee_event->wait_sem) {
325
		sched->multitarget_wakeups++;
I
Ingo Molnar 已提交
326 327 328
		return;
	}

329
	wakee_event->wait_sem = zalloc(sizeof(*wakee_event->wait_sem));
I
Ingo Molnar 已提交
330 331 332 333
	sem_init(wakee_event->wait_sem, 0, 0);
	wakee_event->specific_wait = 1;
	event->wait_sem = wakee_event->wait_sem;

334
	sched->nr_wakeup_events++;
I
Ingo Molnar 已提交
335 336
}

337 338
static void add_sched_event_sleep(struct perf_sched *sched, struct task_desc *task,
				  u64 timestamp, u64 task_state __maybe_unused)
I
Ingo Molnar 已提交
339
{
340
	struct sched_atom *event = get_new_event(task, timestamp);
I
Ingo Molnar 已提交
341 342 343

	event->type = SCHED_EVENT_SLEEP;

344
	sched->nr_sleep_events++;
I
Ingo Molnar 已提交
345 346
}

347 348
static struct task_desc *register_pid(struct perf_sched *sched,
				      unsigned long pid, const char *comm)
I
Ingo Molnar 已提交
349 350
{
	struct task_desc *task;
351
	static int pid_max;
I
Ingo Molnar 已提交
352

353 354 355 356 357
	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);
	}
358 359 360 361 362 363
	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 已提交
364

365
	task = sched->pid_to_task[pid];
I
Ingo Molnar 已提交
366 367 368 369

	if (task)
		return task;

370
	task = zalloc(sizeof(*task));
I
Ingo Molnar 已提交
371
	task->pid = pid;
372
	task->nr = sched->nr_tasks;
I
Ingo Molnar 已提交
373 374 375 376 377
	strcpy(task->comm, comm);
	/*
	 * every task starts in sleeping state - this gets ignored
	 * if there's no wakeup pointing to this sleep state:
	 */
378
	add_sched_event_sleep(sched, task, 0, 0);
I
Ingo Molnar 已提交
379

380 381
	sched->pid_to_task[pid] = task;
	sched->nr_tasks++;
382
	sched->tasks = realloc(sched->tasks, sched->nr_tasks * sizeof(struct task_desc *));
383 384
	BUG_ON(!sched->tasks);
	sched->tasks[task->nr] = task;
I
Ingo Molnar 已提交
385

I
Ingo Molnar 已提交
386
	if (verbose)
387
		printf("registered task #%ld, PID %ld (%s)\n", sched->nr_tasks, pid, comm);
I
Ingo Molnar 已提交
388 389 390 391 392

	return task;
}


393
static void print_task_traces(struct perf_sched *sched)
I
Ingo Molnar 已提交
394 395 396 397
{
	struct task_desc *task;
	unsigned long i;

398 399
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
400
		printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
I
Ingo Molnar 已提交
401 402 403 404
			task->nr, task->comm, task->pid, task->nr_events);
	}
}

405
static void add_cross_task_wakeups(struct perf_sched *sched)
I
Ingo Molnar 已提交
406 407 408 409
{
	struct task_desc *task1, *task2;
	unsigned long i, j;

410 411
	for (i = 0; i < sched->nr_tasks; i++) {
		task1 = sched->tasks[i];
I
Ingo Molnar 已提交
412
		j = i + 1;
413
		if (j == sched->nr_tasks)
I
Ingo Molnar 已提交
414
			j = 0;
415 416
		task2 = sched->tasks[j];
		add_sched_event_wakeup(sched, task1, 0, task2);
I
Ingo Molnar 已提交
417 418 419
	}
}

420 421
static void perf_sched__process_event(struct perf_sched *sched,
				      struct sched_atom *atom)
I
Ingo Molnar 已提交
422 423 424
{
	int ret = 0;

425
	switch (atom->type) {
I
Ingo Molnar 已提交
426
		case SCHED_EVENT_RUN:
427
			burn_nsecs(sched, atom->duration);
I
Ingo Molnar 已提交
428 429
			break;
		case SCHED_EVENT_SLEEP:
430 431
			if (atom->wait_sem)
				ret = sem_wait(atom->wait_sem);
I
Ingo Molnar 已提交
432 433 434
			BUG_ON(ret);
			break;
		case SCHED_EVENT_WAKEUP:
435 436
			if (atom->wait_sem)
				ret = sem_post(atom->wait_sem);
I
Ingo Molnar 已提交
437 438
			BUG_ON(ret);
			break;
439 440
		case SCHED_EVENT_MIGRATION:
			break;
I
Ingo Molnar 已提交
441 442 443 444 445
		default:
			BUG_ON(1);
	}
}

446
static u64 get_cpu_usage_nsec_parent(void)
I
Ingo Molnar 已提交
447 448
{
	struct rusage ru;
449
	u64 sum;
I
Ingo Molnar 已提交
450 451 452 453 454 455 456 457 458 459 460
	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;
}

461
static int self_open_counters(struct perf_sched *sched, unsigned long cur_task)
I
Ingo Molnar 已提交
462
{
463
	struct perf_event_attr attr;
464
	char sbuf[STRERR_BUFSIZE], info[STRERR_BUFSIZE];
465
	int fd;
466 467
	struct rlimit limit;
	bool need_privilege = false;
I
Ingo Molnar 已提交
468

469
	memset(&attr, 0, sizeof(attr));
I
Ingo Molnar 已提交
470

471 472
	attr.type = PERF_TYPE_SOFTWARE;
	attr.config = PERF_COUNT_SW_TASK_CLOCK;
I
Ingo Molnar 已提交
473

474
force_again:
475 476
	fd = sys_perf_event_open(&attr, 0, -1, -1,
				 perf_event_open_cloexec_flag());
477

478
	if (fd < 0) {
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
		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");
		}
495
		pr_err("Error: sys_perf_event_open() syscall returned "
496
		       "with %d (%s)\n%s", fd,
497
		       str_error_r(errno, sbuf, sizeof(sbuf)), info);
498 499
		exit(EXIT_FAILURE);
	}
500 501 502 503 504 505 506 507 508 509 510 511
	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 已提交
512 513
}

514 515 516
struct sched_thread_parms {
	struct task_desc  *task;
	struct perf_sched *sched;
517
	int fd;
518 519
};

I
Ingo Molnar 已提交
520 521
static void *thread_func(void *ctx)
{
522 523 524
	struct sched_thread_parms *parms = ctx;
	struct task_desc *this_task = parms->task;
	struct perf_sched *sched = parms->sched;
525
	u64 cpu_usage_0, cpu_usage_1;
I
Ingo Molnar 已提交
526 527
	unsigned long i, ret;
	char comm2[22];
528
	int fd = parms->fd;
I
Ingo Molnar 已提交
529

530
	zfree(&parms);
531

I
Ingo Molnar 已提交
532 533
	sprintf(comm2, ":%s", this_task->comm);
	prctl(PR_SET_NAME, comm2);
534 535
	if (fd < 0)
		return NULL;
I
Ingo Molnar 已提交
536 537 538
again:
	ret = sem_post(&this_task->ready_for_work);
	BUG_ON(ret);
539
	ret = pthread_mutex_lock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
540
	BUG_ON(ret);
541
	ret = pthread_mutex_unlock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
542 543
	BUG_ON(ret);

544
	cpu_usage_0 = get_cpu_usage_nsec_self(fd);
I
Ingo Molnar 已提交
545 546 547

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

551
	cpu_usage_1 = get_cpu_usage_nsec_self(fd);
I
Ingo Molnar 已提交
552 553 554 555
	this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
	ret = sem_post(&this_task->work_done_sem);
	BUG_ON(ret);

556
	ret = pthread_mutex_lock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
557
	BUG_ON(ret);
558
	ret = pthread_mutex_unlock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
559 560 561 562 563
	BUG_ON(ret);

	goto again;
}

564
static void create_tasks(struct perf_sched *sched)
I
Ingo Molnar 已提交
565 566 567 568 569 570 571 572
{
	struct task_desc *task;
	pthread_attr_t attr;
	unsigned long i;
	int err;

	err = pthread_attr_init(&attr);
	BUG_ON(err);
573 574
	err = pthread_attr_setstacksize(&attr,
			(size_t) max(16 * 1024, PTHREAD_STACK_MIN));
I
Ingo Molnar 已提交
575
	BUG_ON(err);
576
	err = pthread_mutex_lock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
577
	BUG_ON(err);
578
	err = pthread_mutex_lock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
579
	BUG_ON(err);
580 581 582 583 584
	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;
585
		parms->fd = self_open_counters(sched, i);
I
Ingo Molnar 已提交
586 587 588 589
		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;
590
		err = pthread_create(&task->thread, &attr, thread_func, parms);
I
Ingo Molnar 已提交
591 592 593 594
		BUG_ON(err);
	}
}

595
static void wait_for_tasks(struct perf_sched *sched)
I
Ingo Molnar 已提交
596
{
597
	u64 cpu_usage_0, cpu_usage_1;
I
Ingo Molnar 已提交
598 599 600
	struct task_desc *task;
	unsigned long i, ret;

601 602 603
	sched->start_time = get_nsecs();
	sched->cpu_usage = 0;
	pthread_mutex_unlock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
604

605 606
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
607 608 609 610
		ret = sem_wait(&task->ready_for_work);
		BUG_ON(ret);
		sem_init(&task->ready_for_work, 0, 0);
	}
611
	ret = pthread_mutex_lock(&sched->work_done_wait_mutex);
I
Ingo Molnar 已提交
612 613 614 615
	BUG_ON(ret);

	cpu_usage_0 = get_cpu_usage_nsec_parent();

616
	pthread_mutex_unlock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
617

618 619
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
620 621 622
		ret = sem_wait(&task->work_done_sem);
		BUG_ON(ret);
		sem_init(&task->work_done_sem, 0, 0);
623
		sched->cpu_usage += task->cpu_usage;
I
Ingo Molnar 已提交
624 625 626 627
		task->cpu_usage = 0;
	}

	cpu_usage_1 = get_cpu_usage_nsec_parent();
628 629
	if (!sched->runavg_cpu_usage)
		sched->runavg_cpu_usage = sched->cpu_usage;
630
	sched->runavg_cpu_usage = (sched->runavg_cpu_usage * (sched->replay_repeat - 1) + sched->cpu_usage) / sched->replay_repeat;
I
Ingo Molnar 已提交
631

632 633 634
	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;
635 636
	sched->runavg_parent_cpu_usage = (sched->runavg_parent_cpu_usage * (sched->replay_repeat - 1) +
					 sched->parent_cpu_usage)/sched->replay_repeat;
I
Ingo Molnar 已提交
637

638
	ret = pthread_mutex_lock(&sched->start_work_mutex);
I
Ingo Molnar 已提交
639 640
	BUG_ON(ret);

641 642
	for (i = 0; i < sched->nr_tasks; i++) {
		task = sched->tasks[i];
I
Ingo Molnar 已提交
643 644 645 646 647
		sem_init(&task->sleep_sem, 0, 0);
		task->curr_event = 0;
	}
}

648
static void run_one_test(struct perf_sched *sched)
I
Ingo Molnar 已提交
649
{
K
Kyle McMartin 已提交
650
	u64 T0, T1, delta, avg_delta, fluct;
I
Ingo Molnar 已提交
651 652

	T0 = get_nsecs();
653
	wait_for_tasks(sched);
I
Ingo Molnar 已提交
654 655 656
	T1 = get_nsecs();

	delta = T1 - T0;
657 658
	sched->sum_runtime += delta;
	sched->nr_runs++;
I
Ingo Molnar 已提交
659

660
	avg_delta = sched->sum_runtime / sched->nr_runs;
I
Ingo Molnar 已提交
661 662 663 664
	if (delta < avg_delta)
		fluct = avg_delta - delta;
	else
		fluct = delta - avg_delta;
665 666 667
	sched->sum_fluct += fluct;
	if (!sched->run_avg)
		sched->run_avg = delta;
668
	sched->run_avg = (sched->run_avg * (sched->replay_repeat - 1) + delta) / sched->replay_repeat;
I
Ingo Molnar 已提交
669

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

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

I
Ingo Molnar 已提交
674
	printf("cpu: %0.2f / %0.2f",
675
		(double)sched->cpu_usage / 1e6, (double)sched->runavg_cpu_usage / 1e6);
I
Ingo Molnar 已提交
676 677 678

#if 0
	/*
679
	 * rusage statistics done by the parent, these are less
680
	 * accurate than the sched->sum_exec_runtime based statistics:
681
	 */
I
Ingo Molnar 已提交
682
	printf(" [%0.2f / %0.2f]",
683 684
		(double)sched->parent_cpu_usage/1e6,
		(double)sched->runavg_parent_cpu_usage/1e6);
I
Ingo Molnar 已提交
685 686
#endif

I
Ingo Molnar 已提交
687
	printf("\n");
I
Ingo Molnar 已提交
688

689 690 691
	if (sched->nr_sleep_corrections)
		printf(" (%ld sleep corrections)\n", sched->nr_sleep_corrections);
	sched->nr_sleep_corrections = 0;
I
Ingo Molnar 已提交
692 693
}

694
static void test_calibrations(struct perf_sched *sched)
I
Ingo Molnar 已提交
695
{
696
	u64 T0, T1;
I
Ingo Molnar 已提交
697 698

	T0 = get_nsecs();
699
	burn_nsecs(sched, 1e6);
I
Ingo Molnar 已提交
700 701
	T1 = get_nsecs();

702
	printf("the run test took %" PRIu64 " nsecs\n", T1 - T0);
I
Ingo Molnar 已提交
703 704 705 706 707

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

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

711
static int
712
replay_wakeup_event(struct perf_sched *sched,
713 714
		    struct perf_evsel *evsel, struct perf_sample *sample,
		    struct machine *machine __maybe_unused)
715
{
716 717
	const char *comm = perf_evsel__strval(evsel, sample, "comm");
	const u32 pid	 = perf_evsel__intval(evsel, sample, "pid");
718
	struct task_desc *waker, *wakee;
719

I
Ingo Molnar 已提交
720
	if (verbose) {
721
		printf("sched_wakeup event %p\n", evsel);
722

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

726
	waker = register_pid(sched, sample->tid, "<unknown>");
727
	wakee = register_pid(sched, pid, comm);
728

729
	add_sched_event_wakeup(sched, waker, sample->time, wakee);
730
	return 0;
I
Ingo Molnar 已提交
731 732
}

733 734 735 736
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 已提交
737
{
738 739 740 741 742
	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");
743
	struct task_desc *prev, __maybe_unused *next;
744 745
	u64 timestamp0, timestamp = sample->time;
	int cpu = sample->cpu;
746 747
	s64 delta;

I
Ingo Molnar 已提交
748
	if (verbose)
749
		printf("sched_switch event %p\n", evsel);
I
Ingo Molnar 已提交
750

751
	if (cpu >= MAX_CPUS || cpu < 0)
752
		return 0;
753

754
	timestamp0 = sched->cpu_last_switched[cpu];
755 756 757 758 759
	if (timestamp0)
		delta = timestamp - timestamp0;
	else
		delta = 0;

760
	if (delta < 0) {
761
		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
762 763
		return -1;
	}
764

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

768 769
	prev = register_pid(sched, prev_pid, prev_comm);
	next = register_pid(sched, next_pid, next_comm);
770

771
	sched->cpu_last_switched[cpu] = timestamp;
772

773
	add_sched_event_run(sched, prev, timestamp, delta);
774
	add_sched_event_sleep(sched, prev, timestamp, prev_state);
775 776

	return 0;
777 778
}

779 780 781
static int replay_fork_event(struct perf_sched *sched,
			     union perf_event *event,
			     struct machine *machine)
782
{
783 784
	struct thread *child, *parent;

785 786 787 788
	child = machine__findnew_thread(machine, event->fork.pid,
					event->fork.tid);
	parent = machine__findnew_thread(machine, event->fork.ppid,
					 event->fork.ptid);
789 790 791 792

	if (child == NULL || parent == NULL) {
		pr_debug("thread does not exist on fork event: child %p, parent %p\n",
				 child, parent);
793
		goto out_put;
794
	}
795

796
	if (verbose) {
797
		printf("fork event\n");
798 799
		printf("... parent: %s/%d\n", thread__comm_str(parent), parent->tid);
		printf("...  child: %s/%d\n", thread__comm_str(child), child->tid);
800
	}
801

802 803
	register_pid(sched, parent->tid, thread__comm_str(parent));
	register_pid(sched, child->tid, thread__comm_str(child));
804 805 806
out_put:
	thread__put(child);
	thread__put(parent);
807
	return 0;
808
}
809

810 811
struct sort_dimension {
	const char		*name;
812
	sort_fn_t		cmp;
813 814 815
	struct list_head	list;
};

816
static int
817
thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
818 819 820 821
{
	struct sort_dimension *sort;
	int ret = 0;

822 823
	BUG_ON(list_empty(list));

824 825 826 827 828 829 830 831 832
	list_for_each_entry(sort, list, list) {
		ret = sort->cmp(l, r);
		if (ret)
			return ret;
	}

	return ret;
}

833
static struct work_atoms *
834 835 836 837
thread_atoms_search(struct rb_root *root, struct thread *thread,
			 struct list_head *sort_list)
{
	struct rb_node *node = root->rb_node;
838
	struct work_atoms key = { .thread = thread };
839 840

	while (node) {
841
		struct work_atoms *atoms;
842 843
		int cmp;

844
		atoms = container_of(node, struct work_atoms, node);
845 846 847 848 849 850 851 852 853 854 855 856 857 858

		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;
}

859
static void
860
__thread_latency_insert(struct rb_root *root, struct work_atoms *data,
861
			 struct list_head *sort_list)
862 863 864 865
{
	struct rb_node **new = &(root->rb_node), *parent = NULL;

	while (*new) {
866
		struct work_atoms *this;
867
		int cmp;
868

869
		this = container_of(*new, struct work_atoms, node);
870
		parent = *new;
871 872 873 874

		cmp = thread_lat_cmp(sort_list, data, this);

		if (cmp > 0)
875 876
			new = &((*new)->rb_left);
		else
877
			new = &((*new)->rb_right);
878 879 880 881 882 883
	}

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

884
static int thread_atoms_insert(struct perf_sched *sched, struct thread *thread)
885
{
886
	struct work_atoms *atoms = zalloc(sizeof(*atoms));
887 888 889 890
	if (!atoms) {
		pr_err("No memory at %s\n", __func__);
		return -1;
	}
891

892
	atoms->thread = thread__get(thread);
893
	INIT_LIST_HEAD(&atoms->work_list);
894
	__thread_latency_insert(&sched->atom_root, atoms, &sched->cmp_pid);
895
	return 0;
896 897
}

898
static char sched_out_state(u64 prev_state)
899 900 901
{
	const char *str = TASK_STATE_TO_CHAR_STR;

902
	return str[prev_state];
903 904
}

905
static int
906 907 908
add_sched_out_event(struct work_atoms *atoms,
		    char run_state,
		    u64 timestamp)
909
{
910
	struct work_atom *atom = zalloc(sizeof(*atom));
911 912 913 914
	if (!atom) {
		pr_err("Non memory at %s", __func__);
		return -1;
	}
915

916 917
	atom->sched_out_time = timestamp;

918
	if (run_state == 'R') {
919
		atom->state = THREAD_WAIT_CPU;
920
		atom->wake_up_time = atom->sched_out_time;
921 922
	}

923
	list_add_tail(&atom->list, &atoms->work_list);
924
	return 0;
925 926 927
}

static void
928 929
add_runtime_event(struct work_atoms *atoms, u64 delta,
		  u64 timestamp __maybe_unused)
930 931 932 933 934 935 936 937 938 939 940 941 942
{
	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)
943
{
944
	struct work_atom *atom;
945
	u64 delta;
946

947
	if (list_empty(&atoms->work_list))
948 949
		return;

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

952
	if (atom->state != THREAD_WAIT_CPU)
953 954
		return;

955 956
	if (timestamp < atom->wake_up_time) {
		atom->state = THREAD_IGNORE;
957 958 959
		return;
	}

960 961
	atom->state = THREAD_SCHED_IN;
	atom->sched_in_time = timestamp;
962

963
	delta = atom->sched_in_time - atom->wake_up_time;
964
	atoms->total_lat += delta;
965
	if (delta > atoms->max_lat) {
966
		atoms->max_lat = delta;
967 968
		atoms->max_lat_at = timestamp;
	}
969
	atoms->nb_atoms++;
970 971
}

972 973 974 975
static int latency_switch_event(struct perf_sched *sched,
				struct perf_evsel *evsel,
				struct perf_sample *sample,
				struct machine *machine)
976
{
977 978 979
	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");
980
	struct work_atoms *out_events, *in_events;
981
	struct thread *sched_out, *sched_in;
982
	u64 timestamp0, timestamp = sample->time;
983
	int cpu = sample->cpu, err = -1;
I
Ingo Molnar 已提交
984 985
	s64 delta;

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

988 989
	timestamp0 = sched->cpu_last_switched[cpu];
	sched->cpu_last_switched[cpu] = timestamp;
I
Ingo Molnar 已提交
990 991 992 993 994
	if (timestamp0)
		delta = timestamp - timestamp0;
	else
		delta = 0;

995 996 997 998
	if (delta < 0) {
		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
		return -1;
	}
999

1000 1001
	sched_out = machine__findnew_thread(machine, -1, prev_pid);
	sched_in = machine__findnew_thread(machine, -1, next_pid);
1002 1003
	if (sched_out == NULL || sched_in == NULL)
		goto out_put;
1004

1005
	out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
1006
	if (!out_events) {
1007
		if (thread_atoms_insert(sched, sched_out))
1008
			goto out_put;
1009
		out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
1010 1011
		if (!out_events) {
			pr_err("out-event: Internal tree error");
1012
			goto out_put;
1013
		}
1014
	}
1015
	if (add_sched_out_event(out_events, sched_out_state(prev_state), timestamp))
1016
		return -1;
1017

1018
	in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
1019
	if (!in_events) {
1020
		if (thread_atoms_insert(sched, sched_in))
1021
			goto out_put;
1022
		in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
1023 1024
		if (!in_events) {
			pr_err("in-event: Internal tree error");
1025
			goto out_put;
1026
		}
1027 1028 1029 1030
		/*
		 * Take came in we have not heard about yet,
		 * add in an initial atom in runnable state:
		 */
1031
		if (add_sched_out_event(in_events, 'R', timestamp))
1032
			goto out_put;
1033
	}
1034
	add_sched_in_event(in_events, timestamp);
1035 1036 1037 1038 1039
	err = 0;
out_put:
	thread__put(sched_out);
	thread__put(sched_in);
	return err;
1040
}
1041

1042 1043 1044 1045
static int latency_runtime_event(struct perf_sched *sched,
				 struct perf_evsel *evsel,
				 struct perf_sample *sample,
				 struct machine *machine)
1046
{
1047 1048
	const u32 pid	   = perf_evsel__intval(evsel, sample, "pid");
	const u64 runtime  = perf_evsel__intval(evsel, sample, "runtime");
1049
	struct thread *thread = machine__findnew_thread(machine, -1, pid);
1050
	struct work_atoms *atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1051
	u64 timestamp = sample->time;
1052 1053 1054 1055
	int cpu = sample->cpu, err = -1;

	if (thread == NULL)
		return -1;
1056 1057 1058

	BUG_ON(cpu >= MAX_CPUS || cpu < 0);
	if (!atoms) {
1059
		if (thread_atoms_insert(sched, thread))
1060
			goto out_put;
1061
		atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1062
		if (!atoms) {
1063
			pr_err("in-event: Internal tree error");
1064
			goto out_put;
1065 1066
		}
		if (add_sched_out_event(atoms, 'R', timestamp))
1067
			goto out_put;
1068 1069
	}

1070
	add_runtime_event(atoms, runtime, timestamp);
1071 1072 1073 1074
	err = 0;
out_put:
	thread__put(thread);
	return err;
1075 1076
}

1077 1078 1079 1080
static int latency_wakeup_event(struct perf_sched *sched,
				struct perf_evsel *evsel,
				struct perf_sample *sample,
				struct machine *machine)
1081
{
1082
	const u32 pid	  = perf_evsel__intval(evsel, sample, "pid");
1083
	struct work_atoms *atoms;
1084
	struct work_atom *atom;
1085
	struct thread *wakee;
1086
	u64 timestamp = sample->time;
1087
	int err = -1;
1088

1089
	wakee = machine__findnew_thread(machine, -1, pid);
1090 1091
	if (wakee == NULL)
		return -1;
1092
	atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1093
	if (!atoms) {
1094
		if (thread_atoms_insert(sched, wakee))
1095
			goto out_put;
1096
		atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1097
		if (!atoms) {
1098
			pr_err("wakeup-event: Internal tree error");
1099
			goto out_put;
1100 1101
		}
		if (add_sched_out_event(atoms, 'S', timestamp))
1102
			goto out_put;
1103 1104
	}

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

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

1109
	/*
1110 1111 1112 1113 1114 1115
	 * 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.
	 *
1116 1117
	 * You WILL be missing events if you've recorded only
	 * one CPU, or are only looking at only one, so don't
1118
	 * skip in this case.
1119
	 */
1120
	if (sched->profile_cpu == -1 && atom->state != THREAD_SLEEPING)
1121
		goto out_ok;
1122

1123
	sched->nr_timestamps++;
1124
	if (atom->sched_out_time > timestamp) {
1125
		sched->nr_unordered_timestamps++;
1126
		goto out_ok;
1127
	}
1128

1129 1130
	atom->state = THREAD_WAIT_CPU;
	atom->wake_up_time = timestamp;
1131 1132 1133 1134 1135
out_ok:
	err = 0;
out_put:
	thread__put(wakee);
	return err;
1136 1137
}

1138 1139 1140 1141
static int latency_migrate_task_event(struct perf_sched *sched,
				      struct perf_evsel *evsel,
				      struct perf_sample *sample,
				      struct machine *machine)
1142
{
1143
	const u32 pid = perf_evsel__intval(evsel, sample, "pid");
1144
	u64 timestamp = sample->time;
1145 1146 1147
	struct work_atoms *atoms;
	struct work_atom *atom;
	struct thread *migrant;
1148
	int err = -1;
1149 1150 1151 1152

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

1156
	migrant = machine__findnew_thread(machine, -1, pid);
1157 1158
	if (migrant == NULL)
		return -1;
1159
	atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1160
	if (!atoms) {
1161
		if (thread_atoms_insert(sched, migrant))
1162
			goto out_put;
1163
		register_pid(sched, migrant->tid, thread__comm_str(migrant));
1164
		atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1165
		if (!atoms) {
1166
			pr_err("migration-event: Internal tree error");
1167
			goto out_put;
1168 1169
		}
		if (add_sched_out_event(atoms, 'R', timestamp))
1170
			goto out_put;
1171 1172 1173 1174 1175 1176 1177
	}

	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;

1178
	sched->nr_timestamps++;
1179 1180

	if (atom->sched_out_time > timestamp)
1181
		sched->nr_unordered_timestamps++;
1182 1183 1184 1185
	err = 0;
out_put:
	thread__put(migrant);
	return err;
1186 1187
}

1188
static void output_lat_thread(struct perf_sched *sched, struct work_atoms *work_list)
1189 1190 1191
{
	int i;
	int ret;
1192
	u64 avg;
1193

1194
	if (!work_list->nb_atoms)
1195
		return;
1196 1197 1198
	/*
	 * Ignore idle threads:
	 */
1199
	if (!strcmp(thread__comm_str(work_list->thread), "swapper"))
1200
		return;
1201

1202 1203
	sched->all_runtime += work_list->total_runtime;
	sched->all_count   += work_list->nb_atoms;
1204

1205 1206 1207 1208
	if (work_list->num_merged > 1)
		ret = printf("  %s:(%d) ", thread__comm_str(work_list->thread), work_list->num_merged);
	else
		ret = printf("  %s:%d ", thread__comm_str(work_list->thread), work_list->thread->tid);
1209

M
mingo 已提交
1210
	for (i = 0; i < 24 - ret; i++)
1211 1212
		printf(" ");

1213
	avg = work_list->total_lat / work_list->nb_atoms;
1214

1215
	printf("|%11.3f ms |%9" PRIu64 " | avg:%9.3f ms | max:%9.3f ms | max at: %13.6f s\n",
1216 1217
	      (double)work_list->total_runtime / 1e6,
		 work_list->nb_atoms, (double)avg / 1e6,
1218 1219
		 (double)work_list->max_lat / 1e6,
		 (double)work_list->max_lat_at / 1e9);
1220 1221
}

1222
static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
1223
{
1224 1225
	if (l->thread == r->thread)
		return 0;
1226
	if (l->thread->tid < r->thread->tid)
1227
		return -1;
1228
	if (l->thread->tid > r->thread->tid)
1229
		return 1;
1230
	return (int)(l->thread - r->thread);
1231 1232
}

1233
static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
{
	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;
}

1254
static int max_cmp(struct work_atoms *l, struct work_atoms *r)
1255 1256 1257 1258 1259 1260 1261 1262 1263
{
	if (l->max_lat < r->max_lat)
		return -1;
	if (l->max_lat > r->max_lat)
		return 1;

	return 0;
}

1264
static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
1265 1266 1267 1268 1269 1270 1271 1272 1273
{
	if (l->nb_atoms < r->nb_atoms)
		return -1;
	if (l->nb_atoms > r->nb_atoms)
		return 1;

	return 0;
}

1274
static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
1275 1276 1277 1278 1279 1280 1281 1282 1283
{
	if (l->total_runtime < r->total_runtime)
		return -1;
	if (l->total_runtime > r->total_runtime)
		return 1;

	return 0;
}

1284
static int sort_dimension__add(const char *tok, struct list_head *list)
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
	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,
	};
1314

1315
	for (i = 0; i < ARRAY_SIZE(available_sorts); i++) {
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
		if (!strcmp(available_sorts[i]->name, tok)) {
			list_add_tail(&available_sorts[i]->list, list);

			return 0;
		}
	}

	return -1;
}

1326
static void perf_sched__sort_lat(struct perf_sched *sched)
1327 1328
{
	struct rb_node *node;
1329 1330
	struct rb_root *root = &sched->atom_root;
again:
1331
	for (;;) {
1332
		struct work_atoms *data;
1333
		node = rb_first(root);
1334 1335 1336
		if (!node)
			break;

1337
		rb_erase(node, root);
1338
		data = rb_entry(node, struct work_atoms, node);
1339
		__thread_latency_insert(&sched->sorted_atom_root, data, &sched->sort_list);
1340
	}
1341 1342 1343 1344
	if (root == &sched->atom_root) {
		root = &sched->merged_atom_root;
		goto again;
	}
1345 1346
}

1347
static int process_sched_wakeup_event(struct perf_tool *tool,
1348
				      struct perf_evsel *evsel,
1349
				      struct perf_sample *sample,
1350
				      struct machine *machine)
1351
{
1352
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1353

1354 1355
	if (sched->tp_handler->wakeup_event)
		return sched->tp_handler->wakeup_event(sched, evsel, sample, machine);
1356

1357
	return 0;
1358 1359
}

J
Jiri Olsa 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
union map_priv {
	void	*ptr;
	bool	 color;
};

static bool thread__has_color(struct thread *thread)
{
	union map_priv priv = {
		.ptr = thread__priv(thread),
	};

	return priv.color;
}

static struct thread*
map__findnew_thread(struct perf_sched *sched, struct machine *machine, pid_t pid, pid_t tid)
{
	struct thread *thread = machine__findnew_thread(machine, pid, tid);
	union map_priv priv = {
		.color = false,
	};

	if (!sched->map.color_pids || !thread || thread__priv(thread))
		return thread;

	if (thread_map__has(sched->map.color_pids, tid))
		priv.color = true;

	thread__set_priv(thread, priv.ptr);
	return thread;
}

1392 1393
static int map_switch_event(struct perf_sched *sched, struct perf_evsel *evsel,
			    struct perf_sample *sample, struct machine *machine)
1394
{
1395 1396
	const u32 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
	struct thread *sched_in;
1397
	int new_shortname;
1398
	u64 timestamp0, timestamp = sample->time;
1399
	s64 delta;
1400 1401 1402
	int i, this_cpu = sample->cpu;
	int cpus_nr;
	bool new_cpu = false;
1403
	const char *color = PERF_COLOR_NORMAL;
1404 1405 1406

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

1407 1408
	if (this_cpu > sched->max_cpu)
		sched->max_cpu = this_cpu;
1409

1410 1411 1412 1413 1414 1415 1416 1417 1418
	if (sched->map.comp) {
		cpus_nr = bitmap_weight(sched->map.comp_cpus_mask, MAX_CPUS);
		if (!test_and_set_bit(this_cpu, sched->map.comp_cpus_mask)) {
			sched->map.comp_cpus[cpus_nr++] = this_cpu;
			new_cpu = true;
		}
	} else
		cpus_nr = sched->max_cpu;

1419 1420
	timestamp0 = sched->cpu_last_switched[this_cpu];
	sched->cpu_last_switched[this_cpu] = timestamp;
1421 1422 1423 1424 1425
	if (timestamp0)
		delta = timestamp - timestamp0;
	else
		delta = 0;

1426
	if (delta < 0) {
1427
		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1428 1429
		return -1;
	}
1430

J
Jiri Olsa 已提交
1431
	sched_in = map__findnew_thread(sched, machine, -1, next_pid);
1432 1433
	if (sched_in == NULL)
		return -1;
1434

1435
	sched->curr_thread[this_cpu] = thread__get(sched_in);
1436 1437 1438 1439 1440

	printf("  ");

	new_shortname = 0;
	if (!sched_in->shortname[0]) {
1441 1442 1443 1444 1445 1446 1447
		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] = ' ';
1448
		} else {
1449 1450 1451 1452 1453
			sched_in->shortname[0] = sched->next_shortname1;
			sched_in->shortname[1] = sched->next_shortname2;

			if (sched->next_shortname1 < 'Z') {
				sched->next_shortname1++;
1454
			} else {
1455 1456 1457 1458 1459
				sched->next_shortname1 = 'A';
				if (sched->next_shortname2 < '9')
					sched->next_shortname2++;
				else
					sched->next_shortname2 = '0';
1460 1461 1462 1463 1464
			}
		}
		new_shortname = 1;
	}

1465 1466
	for (i = 0; i < cpus_nr; i++) {
		int cpu = sched->map.comp ? sched->map.comp_cpus[i] : i;
J
Jiri Olsa 已提交
1467 1468
		struct thread *curr_thread = sched->curr_thread[cpu];
		const char *pid_color = color;
J
Jiri Olsa 已提交
1469
		const char *cpu_color = color;
J
Jiri Olsa 已提交
1470 1471 1472

		if (curr_thread && thread__has_color(curr_thread))
			pid_color = COLOR_PIDS;
1473

1474 1475 1476
		if (sched->map.cpus && !cpu_map__has(sched->map.cpus, cpu))
			continue;

J
Jiri Olsa 已提交
1477 1478 1479
		if (sched->map.color_cpus && cpu_map__has(sched->map.color_cpus, cpu))
			cpu_color = COLOR_CPUS;

1480
		if (cpu != this_cpu)
J
Jiri Olsa 已提交
1481
			color_fprintf(stdout, cpu_color, " ");
1482
		else
J
Jiri Olsa 已提交
1483
			color_fprintf(stdout, cpu_color, "*");
1484

1485
		if (sched->curr_thread[cpu])
J
Jiri Olsa 已提交
1486
			color_fprintf(stdout, pid_color, "%2s ", sched->curr_thread[cpu]->shortname);
1487
		else
1488
			color_fprintf(stdout, color, "   ");
1489 1490
	}

1491 1492 1493
	if (sched->map.cpus && !cpu_map__has(sched->map.cpus, this_cpu))
		goto out;

1494
	color_fprintf(stdout, color, "  %12.6f secs ", (double)timestamp/1e9);
1495
	if (new_shortname) {
J
Jiri Olsa 已提交
1496 1497 1498 1499 1500 1501
		const char *pid_color = color;

		if (thread__has_color(sched_in))
			pid_color = COLOR_PIDS;

		color_fprintf(stdout, pid_color, "%s => %s:%d",
1502
		       sched_in->shortname, thread__comm_str(sched_in), sched_in->tid);
1503
	}
1504

1505
	if (sched->map.comp && new_cpu)
1506
		color_fprintf(stdout, color, " (CPU %d)", this_cpu);
1507

1508
out:
1509
	color_fprintf(stdout, color, "\n");
1510

1511 1512
	thread__put(sched_in);

1513
	return 0;
1514 1515
}

1516
static int process_sched_switch_event(struct perf_tool *tool,
1517
				      struct perf_evsel *evsel,
1518
				      struct perf_sample *sample,
1519
				      struct machine *machine)
1520
{
1521
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1522
	int this_cpu = sample->cpu, err = 0;
1523 1524
	u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
	    next_pid = perf_evsel__intval(evsel, sample, "next_pid");
1525

1526
	if (sched->curr_pid[this_cpu] != (u32)-1) {
1527 1528 1529 1530
		/*
		 * Are we trying to switch away a PID that is
		 * not current?
		 */
1531
		if (sched->curr_pid[this_cpu] != prev_pid)
1532
			sched->nr_context_switch_bugs++;
1533 1534
	}

1535 1536
	if (sched->tp_handler->switch_event)
		err = sched->tp_handler->switch_event(sched, evsel, sample, machine);
1537 1538

	sched->curr_pid[this_cpu] = next_pid;
1539
	return err;
1540 1541
}

1542
static int process_sched_runtime_event(struct perf_tool *tool,
1543
				       struct perf_evsel *evsel,
1544
				       struct perf_sample *sample,
1545
				       struct machine *machine)
1546
{
1547
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1548

1549 1550
	if (sched->tp_handler->runtime_event)
		return sched->tp_handler->runtime_event(sched, evsel, sample, machine);
1551

1552
	return 0;
1553 1554
}

1555 1556 1557 1558
static int perf_sched__process_fork_event(struct perf_tool *tool,
					  union perf_event *event,
					  struct perf_sample *sample,
					  struct machine *machine)
1559
{
1560
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1561

1562 1563 1564 1565
	/* 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 */
1566
	if (sched->tp_handler->fork_event)
1567
		return sched->tp_handler->fork_event(sched, event, machine);
1568

1569
	return 0;
1570 1571
}

1572
static int process_sched_migrate_task_event(struct perf_tool *tool,
1573
					    struct perf_evsel *evsel,
1574
					    struct perf_sample *sample,
1575
					    struct machine *machine)
1576
{
1577
	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1578

1579 1580
	if (sched->tp_handler->migrate_task_event)
		return sched->tp_handler->migrate_task_event(sched, evsel, sample, machine);
1581

1582
	return 0;
1583 1584
}

1585
typedef int (*tracepoint_handler)(struct perf_tool *tool,
1586
				  struct perf_evsel *evsel,
1587
				  struct perf_sample *sample,
1588
				  struct machine *machine);
I
Ingo Molnar 已提交
1589

1590 1591
static int perf_sched__process_tracepoint_sample(struct perf_tool *tool __maybe_unused,
						 union perf_event *event __maybe_unused,
1592 1593 1594
						 struct perf_sample *sample,
						 struct perf_evsel *evsel,
						 struct machine *machine)
I
Ingo Molnar 已提交
1595
{
1596
	int err = 0;
I
Ingo Molnar 已提交
1597

1598 1599
	if (evsel->handler != NULL) {
		tracepoint_handler f = evsel->handler;
1600
		err = f(tool, evsel, sample, machine);
1601
	}
I
Ingo Molnar 已提交
1602

1603
	return err;
I
Ingo Molnar 已提交
1604 1605
}

1606
static int perf_sched__read_events(struct perf_sched *sched)
I
Ingo Molnar 已提交
1607
{
1608 1609 1610 1611 1612 1613 1614
	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, },
	};
1615
	struct perf_session *session;
1616 1617 1618
	struct perf_data_file file = {
		.path = input_name,
		.mode = PERF_DATA_MODE_READ,
1619
		.force = sched->force,
1620
	};
1621
	int rc = -1;
1622

1623
	session = perf_session__new(&file, false, &sched->tool);
1624 1625 1626 1627
	if (session == NULL) {
		pr_debug("No Memory for session\n");
		return -1;
	}
1628

1629
	symbol__init(&session->header.env);
1630

1631 1632
	if (perf_session__set_tracepoints_handlers(session, handlers))
		goto out_delete;
1633

1634
	if (perf_session__has_traces(session, "record -R")) {
1635
		int err = perf_session__process_events(session);
1636 1637 1638 1639
		if (err) {
			pr_err("Failed to process events, error %d", err);
			goto out_delete;
		}
1640

1641 1642 1643
		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];
1644
	}
1645

1646
	rc = 0;
1647 1648
out_delete:
	perf_session__delete(session);
1649
	return rc;
I
Ingo Molnar 已提交
1650 1651
}

1652
static void print_bad_events(struct perf_sched *sched)
1653
{
1654
	if (sched->nr_unordered_timestamps && sched->nr_timestamps) {
1655
		printf("  INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
1656 1657
			(double)sched->nr_unordered_timestamps/(double)sched->nr_timestamps*100.0,
			sched->nr_unordered_timestamps, sched->nr_timestamps);
1658
	}
1659
	if (sched->nr_lost_events && sched->nr_events) {
1660
		printf("  INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
1661 1662
			(double)sched->nr_lost_events/(double)sched->nr_events * 100.0,
			sched->nr_lost_events, sched->nr_events, sched->nr_lost_chunks);
1663
	}
1664
	if (sched->nr_context_switch_bugs && sched->nr_timestamps) {
1665
		printf("  INFO: %.3f%% context switch bugs (%ld out of %ld)",
1666 1667 1668
			(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)
1669 1670 1671 1672 1673
			printf(" (due to lost events?)");
		printf("\n");
	}
}

1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 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
static void __merge_work_atoms(struct rb_root *root, struct work_atoms *data)
{
	struct rb_node **new = &(root->rb_node), *parent = NULL;
	struct work_atoms *this;
	const char *comm = thread__comm_str(data->thread), *this_comm;

	while (*new) {
		int cmp;

		this = container_of(*new, struct work_atoms, node);
		parent = *new;

		this_comm = thread__comm_str(this->thread);
		cmp = strcmp(comm, this_comm);
		if (cmp > 0) {
			new = &((*new)->rb_left);
		} else if (cmp < 0) {
			new = &((*new)->rb_right);
		} else {
			this->num_merged++;
			this->total_runtime += data->total_runtime;
			this->nb_atoms += data->nb_atoms;
			this->total_lat += data->total_lat;
			list_splice(&data->work_list, &this->work_list);
			if (this->max_lat < data->max_lat) {
				this->max_lat = data->max_lat;
				this->max_lat_at = data->max_lat_at;
			}
			zfree(&data);
			return;
		}
	}

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

static void perf_sched__merge_lat(struct perf_sched *sched)
{
	struct work_atoms *data;
	struct rb_node *node;

	if (sched->skip_merge)
		return;

	while ((node = rb_first(&sched->atom_root))) {
		rb_erase(node, &sched->atom_root);
		data = rb_entry(node, struct work_atoms, node);
		__merge_work_atoms(&sched->merged_atom_root, data);
	}
}

1727
static int perf_sched__lat(struct perf_sched *sched)
1728 1729 1730 1731
{
	struct rb_node *next;

	setup_pager();
1732

1733
	if (perf_sched__read_events(sched))
1734
		return -1;
1735

1736
	perf_sched__merge_lat(sched);
1737
	perf_sched__sort_lat(sched);
1738

1739 1740 1741
	printf("\n -----------------------------------------------------------------------------------------------------------------\n");
	printf("  Task                  |   Runtime ms  | Switches | Average delay ms | Maximum delay ms | Maximum delay at       |\n");
	printf(" -----------------------------------------------------------------------------------------------------------------\n");
1742

1743
	next = rb_first(&sched->sorted_atom_root);
1744 1745 1746 1747 1748

	while (next) {
		struct work_atoms *work_list;

		work_list = rb_entry(next, struct work_atoms, node);
1749
		output_lat_thread(sched, work_list);
1750
		next = rb_next(next);
1751
		thread__zput(work_list->thread);
1752 1753
	}

1754
	printf(" -----------------------------------------------------------------------------------------------------------------\n");
1755
	printf("  TOTAL:                |%11.3f ms |%9" PRIu64 " |\n",
1756
		(double)sched->all_runtime / 1e6, sched->all_count);
1757 1758 1759

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

1760
	print_bad_events(sched);
1761 1762
	printf("\n");

1763
	return 0;
1764 1765
}

1766 1767
static int setup_map_cpus(struct perf_sched *sched)
{
1768 1769
	struct cpu_map *map;

1770 1771 1772 1773
	sched->max_cpu  = sysconf(_SC_NPROCESSORS_CONF);

	if (sched->map.comp) {
		sched->map.comp_cpus = zalloc(sched->max_cpu * sizeof(int));
J
Jiri Olsa 已提交
1774 1775
		if (!sched->map.comp_cpus)
			return -1;
1776 1777
	}

1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
	if (!sched->map.cpus_str)
		return 0;

	map = cpu_map__new(sched->map.cpus_str);
	if (!map) {
		pr_err("failed to get cpus map from %s\n", sched->map.cpus_str);
		return -1;
	}

	sched->map.cpus = map;
1788 1789 1790
	return 0;
}

J
Jiri Olsa 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
static int setup_color_pids(struct perf_sched *sched)
{
	struct thread_map *map;

	if (!sched->map.color_pids_str)
		return 0;

	map = thread_map__new_by_tid_str(sched->map.color_pids_str);
	if (!map) {
		pr_err("failed to get thread map from %s\n", sched->map.color_pids_str);
		return -1;
	}

	sched->map.color_pids = map;
	return 0;
}

J
Jiri Olsa 已提交
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
static int setup_color_cpus(struct perf_sched *sched)
{
	struct cpu_map *map;

	if (!sched->map.color_cpus_str)
		return 0;

	map = cpu_map__new(sched->map.color_cpus_str);
	if (!map) {
		pr_err("failed to get thread map from %s\n", sched->map.color_cpus_str);
		return -1;
	}

	sched->map.color_cpus = map;
	return 0;
}

1825
static int perf_sched__map(struct perf_sched *sched)
1826
{
1827 1828
	if (setup_map_cpus(sched))
		return -1;
1829

J
Jiri Olsa 已提交
1830 1831 1832
	if (setup_color_pids(sched))
		return -1;

J
Jiri Olsa 已提交
1833 1834 1835
	if (setup_color_cpus(sched))
		return -1;

1836
	setup_pager();
1837
	if (perf_sched__read_events(sched))
1838
		return -1;
1839
	print_bad_events(sched);
1840
	return 0;
1841 1842
}

1843
static int perf_sched__replay(struct perf_sched *sched)
1844 1845 1846
{
	unsigned long i;

1847 1848
	calibrate_run_measurement_overhead(sched);
	calibrate_sleep_measurement_overhead(sched);
1849

1850
	test_calibrations(sched);
1851

1852
	if (perf_sched__read_events(sched))
1853
		return -1;
1854

1855 1856 1857
	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);
1858

1859 1860 1861 1862 1863
	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)
1864
		printf("run atoms optimized: %ld\n",
1865
			sched->nr_run_events_optimized);
1866

1867 1868
	print_task_traces(sched);
	add_cross_task_wakeups(sched);
1869

1870
	create_tasks(sched);
1871
	printf("------------------------------------------------------------\n");
1872 1873
	for (i = 0; i < sched->replay_repeat; i++)
		run_one_test(sched);
1874 1875

	return 0;
1876 1877
}

1878 1879
static void setup_sorting(struct perf_sched *sched, const struct option *options,
			  const char * const usage_msg[])
1880
{
1881
	char *tmp, *tok, *str = strdup(sched->sort_order);
1882 1883 1884

	for (tok = strtok_r(str, ", ", &tmp);
			tok; tok = strtok_r(NULL, ", ", &tmp)) {
1885
		if (sort_dimension__add(tok, &sched->sort_list) < 0) {
1886 1887
			usage_with_options_msg(usage_msg, options,
					"Unknown --sort key: `%s'", tok);
1888 1889 1890 1891 1892
		}
	}

	free(str);

1893
	sort_dimension__add("pid", &sched->cmp_pid);
1894 1895
}

1896 1897 1898 1899
static int __cmd_record(int argc, const char **argv)
{
	unsigned int rec_argc, i, j;
	const char **rec_argv;
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
	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",
1913
		"-e", "sched:sched_wakeup_new",
1914 1915
		"-e", "sched:sched_migrate_task",
	};
1916 1917 1918 1919

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

1920
	if (rec_argv == NULL)
1921 1922
		return -ENOMEM;

1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
	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);
}

1934
int cmd_sched(int argc, const char **argv, const char *prefix __maybe_unused)
I
Ingo Molnar 已提交
1935
{
1936 1937 1938 1939 1940 1941 1942
	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,
1943
			.ordered_events = true,
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
		},
		.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',
1954
		.skip_merge           = 0,
1955
	};
1956 1957 1958 1959 1960 1961 1962 1963 1964
	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"),
1965 1966
	OPT_BOOLEAN('p', "pids", &sched.skip_merge,
		    "latency stats per pid instead of per comm"),
1967 1968 1969 1970 1971 1972 1973 1974 1975
	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"),
1976
	OPT_BOOLEAN('f', "force", &sched.force, "don't complain, do it"),
1977 1978 1979
	OPT_END()
	};
	const struct option sched_options[] = {
1980
	OPT_STRING('i', "input", &input_name, "file",
1981 1982 1983 1984 1985 1986 1987
		    "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()
	};
1988 1989 1990
	const struct option map_options[] = {
	OPT_BOOLEAN(0, "compact", &sched.map.comp,
		    "map output in compact mode"),
J
Jiri Olsa 已提交
1991 1992
	OPT_STRING(0, "color-pids", &sched.map.color_pids_str, "pids",
		   "highlight given pids in map"),
J
Jiri Olsa 已提交
1993 1994
	OPT_STRING(0, "color-cpus", &sched.map.color_cpus_str, "cpus",
                    "highlight given CPUs in map"),
1995 1996
	OPT_STRING(0, "cpus", &sched.map.cpus_str, "cpus",
                    "display given CPUs in map"),
1997 1998
	OPT_END()
	};
1999 2000 2001 2002 2003 2004 2005 2006
	const char * const latency_usage[] = {
		"perf sched latency [<options>]",
		NULL
	};
	const char * const replay_usage[] = {
		"perf sched replay [<options>]",
		NULL
	};
2007 2008 2009 2010
	const char * const map_usage[] = {
		"perf sched map [<options>]",
		NULL
	};
2011 2012 2013 2014
	const char *const sched_subcommands[] = { "record", "latency", "map",
						  "replay", "script", NULL };
	const char *sched_usage[] = {
		NULL,
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
		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 已提交
2031 2032 2033 2034
	unsigned int i;

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

2036 2037
	argc = parse_options_subcommand(argc, argv, sched_options, sched_subcommands,
					sched_usage, PARSE_OPT_STOP_AT_NON_OPTION);
2038 2039
	if (!argc)
		usage_with_options(sched_usage, sched_options);
I
Ingo Molnar 已提交
2040

2041
	/*
2042
	 * Aliased to 'perf script' for now:
2043
	 */
2044 2045
	if (!strcmp(argv[0], "script"))
		return cmd_script(argc, argv, prefix);
2046

2047 2048 2049
	if (!strncmp(argv[0], "rec", 3)) {
		return __cmd_record(argc, argv);
	} else if (!strncmp(argv[0], "lat", 3)) {
2050
		sched.tp_handler = &lat_ops;
2051 2052 2053 2054 2055
		if (argc > 1) {
			argc = parse_options(argc, argv, latency_options, latency_usage, 0);
			if (argc)
				usage_with_options(latency_usage, latency_options);
		}
2056 2057
		setup_sorting(&sched, latency_options, latency_usage);
		return perf_sched__lat(&sched);
2058
	} else if (!strcmp(argv[0], "map")) {
2059
		if (argc) {
J
Jiri Olsa 已提交
2060
			argc = parse_options(argc, argv, map_options, map_usage, 0);
2061 2062 2063
			if (argc)
				usage_with_options(map_usage, map_options);
		}
2064 2065 2066
		sched.tp_handler = &map_ops;
		setup_sorting(&sched, latency_options, latency_usage);
		return perf_sched__map(&sched);
2067
	} else if (!strncmp(argv[0], "rep", 3)) {
2068
		sched.tp_handler = &replay_ops;
2069 2070 2071 2072 2073
		if (argc) {
			argc = parse_options(argc, argv, replay_options, replay_usage, 0);
			if (argc)
				usage_with_options(replay_usage, replay_options);
		}
2074
		return perf_sched__replay(&sched);
2075 2076 2077 2078
	} else {
		usage_with_options(sched_usage, sched_options);
	}

I
Ingo Molnar 已提交
2079
	return 0;
I
Ingo Molnar 已提交
2080
}